@code-yeongyu/senpi 2026.11.10 → 2026.11.11

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 (320) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/dist/bundle/{SKILL-B4R7BVOT.md → SKILL-R7FEIQKG.md} +1 -1
  3. package/dist/bundle/chunks/{SKILL-AZ6ONO52.js → SKILL-5O2UKORG.js} +1 -1
  4. package/dist/bundle/chunks/{SKILL-B4R7BVOT.md → SKILL-R7FEIQKG.md} +1 -1
  5. package/dist/bundle/chunks/{args-77GYOPEO.js → args-HFYB6URH.js} +1 -1
  6. package/dist/bundle/chunks/{azure-openai-responses-YFZ734T3.js → azure-openai-responses-MNN2TINI.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-ZUQCYIRY.js → chunk-2ODGHBUD.js} +1 -1
  8. package/dist/bundle/chunks/chunk-3IYEGHBI.js +2 -0
  9. package/dist/bundle/chunks/{chunk-I5ASHSLZ.js → chunk-4JMGWVRH.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-YKYWL2NO.js → chunk-5F2XC6UC.js} +3 -3
  11. package/dist/bundle/chunks/{chunk-MSDBBOB2.js → chunk-5H43O4MA.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-R3OP7IA4.js → chunk-5PIZWSNG.js} +4 -4
  13. package/dist/bundle/chunks/{chunk-33MZJTQ3.js → chunk-B4WD5XHP.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-Q63YLZMN.js → chunk-BPEA5SWW.js} +2 -2
  15. package/dist/bundle/chunks/{chunk-MOVJQVMC.js → chunk-BUDJLVMF.js} +3 -3
  16. package/dist/bundle/chunks/{chunk-V5FSENW6.js → chunk-COKX65TE.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-2EJ4BGBM.js → chunk-DHORIIVQ.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-NH7SYIGN.js → chunk-DLPV4B3R.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-RCHIMH7N.js → chunk-DQY26AX3.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-Y7Z7XPUF.js → chunk-DZQA5LVN.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-2CNSCMYC.js → chunk-E5O4SP5I.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-3Q5ZENSD.js → chunk-E6ZBTSC6.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-GVPZPVVO.js → chunk-IBDAV2AL.js} +3 -3
  24. package/dist/bundle/chunks/chunk-IREUIMFE.js +11 -0
  25. package/dist/bundle/chunks/{chunk-KU7OCWJF.js → chunk-J4ADZ2OK.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-T2SMQPRE.js → chunk-K3GAGIPX.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-BELNOPAI.js → chunk-L3KVP7VJ.js} +3 -3
  28. package/dist/bundle/chunks/{chunk-IYSJFQUU.js → chunk-L6DF5G6K.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-7MN7YNO5.js → chunk-L7DGTA3L.js} +1 -1
  30. package/dist/bundle/chunks/chunk-LJFQYCFH.js +2 -0
  31. package/dist/bundle/chunks/{chunk-J2NGJKXL.js → chunk-LXINMDMX.js} +1 -1
  32. package/dist/bundle/chunks/{chunk-H33A33M4.js → chunk-M2VJVJMK.js} +1 -1
  33. package/dist/bundle/chunks/{chunk-2U6HXWXS.js → chunk-NNQ34ZDW.js} +1 -1
  34. package/dist/bundle/chunks/chunk-NQKCJQHB.js +2 -0
  35. package/dist/bundle/chunks/{chunk-EJB5E2JK.js → chunk-NRZAJUUO.js} +2 -2
  36. package/dist/bundle/chunks/{chunk-R2Z7CX77.js → chunk-OSNR3IRD.js} +1 -1
  37. package/dist/bundle/chunks/{chunk-O3FG6HML.js → chunk-PJI5GT7U.js} +1 -1
  38. package/dist/bundle/chunks/{chunk-FDNM2DAE.js → chunk-PUZDKFRT.js} +164 -164
  39. package/dist/bundle/chunks/{chunk-BPNSOZ2C.js → chunk-QUVSIW2R.js} +1 -1
  40. package/dist/bundle/chunks/{chunk-WXYMAUFX.js → chunk-QX7WD3IM.js} +1 -1
  41. package/dist/bundle/chunks/{chunk-Y4ONXQMR.js → chunk-RGHVPUUX.js} +1 -1
  42. package/dist/bundle/chunks/{chunk-RYPM5BZQ.js → chunk-S7NAJQB3.js} +1 -1
  43. package/dist/bundle/chunks/{chunk-2BH54YQR.js → chunk-SANWO37B.js} +1 -1
  44. package/dist/bundle/chunks/{chunk-YQZNARTX.js → chunk-SS5VTBAV.js} +1 -1
  45. package/dist/bundle/chunks/{chunk-LT353NSF.js → chunk-T4CUD7RF.js} +1 -1
  46. package/dist/bundle/chunks/{chunk-J7FW7MED.js → chunk-TCZORL3V.js} +1 -1
  47. package/dist/bundle/chunks/{chunk-KU72IKV5.js → chunk-VGSWOLIY.js} +1 -1
  48. package/dist/bundle/chunks/{chunk-DBQBJTMF.js → chunk-VUY4BZDI.js} +1 -1
  49. package/dist/bundle/chunks/chunk-XI6THO4F.js +2 -0
  50. package/dist/bundle/chunks/{chunk-FAFIGBUD.js → chunk-XUDKT4UH.js} +3 -3
  51. package/dist/bundle/chunks/{cli-main-BX5AFWJQ.js → cli-main-7II7GCIR.js} +1 -1
  52. package/dist/bundle/chunks/{credential-accounts-LVVPKFEY.js → credential-accounts-N3B5YJS7.js} +1 -1
  53. package/dist/bundle/chunks/{dispatch-EP35KKJ3.js → dispatch-YUYZQXRP.js} +1 -1
  54. package/dist/bundle/chunks/github-copilot.js +1 -1
  55. package/dist/bundle/chunks/{hand-entry-F6PWKNPJ.js → hand-entry-ONOLRMVB.js} +3 -3
  56. package/dist/bundle/chunks/{headless-host-HKGNJGYT.js → headless-host-53UMJMM6.js} +1 -1
  57. package/dist/bundle/chunks/{health-write-FBF74QJ7.js → health-write-JLSF5EVV.js} +1 -1
  58. package/dist/bundle/chunks/{help-fast-path-5SCPY3OH.js → help-fast-path-552QLMWT.js} +1 -1
  59. package/dist/bundle/chunks/{host-command-47QQKJEY.js → host-command-KWMJLPBS.js} +1 -1
  60. package/dist/bundle/chunks/{host-lifecycle-VSAH4M3R.js → host-lifecycle-4WQDCN3Y.js} +1 -1
  61. package/dist/bundle/chunks/host-lifecycle.js +5 -5
  62. package/dist/bundle/chunks/{host-session-command-SL4AN5WD.js → host-session-command-ZDYEKCUB.js} +1 -1
  63. package/dist/bundle/chunks/{host-socket-request-DMYXC56U.js → host-socket-request-QN4Q2P5E.js} +1 -1
  64. package/dist/bundle/chunks/{interactive-mode-JDMIHJMQ.js → interactive-mode-EPE4M32G.js} +1 -1
  65. package/dist/bundle/chunks/{login-health-EVXVLHB2.js → login-health-TOSQT5RG.js} +1 -1
  66. package/dist/bundle/chunks/{main-4RITUAQF.js → main-OM7BKVZG.js} +1 -1
  67. package/dist/bundle/chunks/{multi-session-host-SKDD4OWM.js → multi-session-host-DB6XMY53.js} +11 -8
  68. package/dist/bundle/chunks/openai-codex-responses-VRGOAFEG.js +10 -0
  69. package/dist/bundle/chunks/{openai-responses-NIVBWE2H.js → openai-responses-I7PXRWCM.js} +2 -2
  70. package/dist/bundle/chunks/{package-manager-cli-B5VA4KFO.js → package-manager-cli-GLU5Q2KV.js} +1 -1
  71. package/dist/bundle/chunks/{role-HQUN4XXK.js → role-AEOLJRTP.js} +1 -1
  72. package/dist/bundle/chunks/{rotation-stream-F3BEMXBE.js → rotation-stream-E3FJFHXJ.js} +1 -1
  73. package/dist/bundle/chunks/rpc-mode-SDJVBT36.js +2 -0
  74. package/dist/bundle/chunks/{rpc-monitor-source-C6VQ3BC4.js → rpc-monitor-source-PGTDSGWP.js} +1 -1
  75. package/dist/bundle/chunks/{run-attached-tui-R3RB5P7G.js → run-attached-tui-4AENRP7P.js} +1 -1
  76. package/dist/bundle/chunks/{schedule-command-FPEQCX33.js → schedule-command-5SQD7M5N.js} +1 -1
  77. package/dist/bundle/chunks/session-control-endpoint-R25A2QGS.js +3 -0
  78. package/dist/bundle/chunks/{session-picker-2FZSNFS7.js → session-picker-GZM5CVQL.js} +1 -1
  79. package/dist/bundle/chunks/{session-slot-CZGQQCOC.js → session-slot-RH7JLO3F.js} +1 -1
  80. package/dist/bundle/chunks/session-worker.js +335 -332
  81. package/dist/bundle/chunks/{state-store-S7QAESIF.js → state-store-IECVTYXC.js} +1 -1
  82. package/dist/bundle/cli.js +2 -2
  83. package/dist/bundle/host-supervisor.js +5 -5
  84. package/dist/bundle/index.js +1 -1
  85. package/dist/bundle/rpc-entry.js +1 -1
  86. package/dist/bundle/runtime-manifest.json +1 -1
  87. package/dist/cli.js +9 -3
  88. package/dist/core/agent-session-runtime.d.ts +2 -0
  89. package/dist/core/agent-session-runtime.js +5 -0
  90. package/dist/core/agent-session.d.ts +15 -3
  91. package/dist/core/agent-session.js +91 -18
  92. package/dist/core/assistant-error-redaction.d.ts +9 -0
  93. package/dist/core/assistant-error-redaction.js +27 -0
  94. package/dist/core/config-reference-redaction.js +90 -10
  95. package/dist/core/context-files.d.ts +10 -0
  96. package/dist/core/context-files.js +58 -12
  97. package/dist/core/credential-accounts.d.ts +2 -0
  98. package/dist/core/credential-accounts.js +10 -1
  99. package/dist/core/dynamic-prompt/intent-gate.js +2 -2
  100. package/dist/core/dynamic-prompt/style.js +2 -2
  101. package/dist/core/dynamic-prompt/verification.js +2 -2
  102. package/dist/core/egress/wire.d.ts +13 -0
  103. package/dist/core/extensions/builtin/anthropic-subscription/accounts.d.ts +3 -0
  104. package/dist/core/extensions/builtin/anthropic-subscription/auth-lane.js +3 -2
  105. package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-account-test.js +3 -1
  106. package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-connection-test.d.ts +3 -1
  107. package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-connection-test.js +47 -16
  108. package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-login-slots.d.ts +1 -1
  109. package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-login-slots.js +4 -2
  110. package/dist/core/extensions/builtin/anthropic-subscription/claude-settings-env.d.ts +20 -0
  111. package/dist/core/extensions/builtin/anthropic-subscription/claude-settings-env.js +39 -0
  112. package/dist/core/extensions/builtin/anthropic-subscription/context-window.d.ts +17 -0
  113. package/dist/core/extensions/builtin/anthropic-subscription/context-window.js +23 -0
  114. package/dist/core/extensions/builtin/anthropic-subscription/errors.d.ts +1 -0
  115. package/dist/core/extensions/builtin/anthropic-subscription/errors.js +14 -5
  116. package/dist/core/extensions/builtin/anthropic-subscription/oauth-login.js +3 -3
  117. package/dist/core/extensions/builtin/anthropic-subscription/prompt-cache-ttl.d.ts +10 -4
  118. package/dist/core/extensions/builtin/anthropic-subscription/prompt-cache-ttl.js +14 -5
  119. package/dist/core/extensions/builtin/anthropic-subscription/query-environment.d.ts +3 -2
  120. package/dist/core/extensions/builtin/anthropic-subscription/query-environment.js +5 -4
  121. package/dist/core/extensions/builtin/anthropic-subscription/sdk-boundary.lazy.d.ts +2 -1
  122. package/dist/core/extensions/builtin/anthropic-subscription/sdk-boundary.lazy.js +1 -0
  123. package/dist/core/extensions/builtin/anthropic-subscription/stream.js +11 -1
  124. package/dist/core/extensions/builtin/config-reload/change-groups.js +6 -2
  125. package/dist/core/extensions/builtin/goal/continuation.d.ts +6 -0
  126. package/dist/core/extensions/builtin/goal/continuation.js +3 -2
  127. package/dist/core/extensions/builtin/goal/index.js +14 -26
  128. package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts +8 -6
  129. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +77 -39
  130. package/dist/core/extensions/builtin/goal/monitor-continuation.js +66 -7
  131. package/dist/core/extensions/builtin/goal/persistence.js +20 -0
  132. package/dist/core/extensions/builtin/goal/provider-retry.d.ts +9 -0
  133. package/dist/core/extensions/builtin/goal/provider-retry.js +16 -0
  134. package/dist/core/extensions/builtin/goal/reload-reengagement.d.ts +3 -2
  135. package/dist/core/extensions/builtin/goal/reload-reengagement.js +4 -4
  136. package/dist/core/extensions/builtin/goal/session-start-continuation.d.ts +28 -0
  137. package/dist/core/extensions/builtin/goal/session-start-continuation.js +75 -0
  138. package/dist/core/extensions/builtin/goal/store.d.ts +3 -2
  139. package/dist/core/extensions/builtin/goal/store.js +9 -2
  140. package/dist/core/extensions/builtin/goal/types.d.ts +9 -0
  141. package/dist/core/extensions/builtin/handoff-hint/index.js +15 -11
  142. package/dist/core/extensions/builtin/handoff-hint/replacement-relay.d.ts +16 -0
  143. package/dist/core/extensions/builtin/handoff-hint/replacement-relay.js +17 -0
  144. package/dist/core/extensions/builtin/html-render/tool.js +13 -3
  145. package/dist/core/extensions/builtin/imagegen/skill/SKILL.md +1 -1
  146. package/dist/core/extensions/builtin/imagegen/tool.js +4 -14
  147. package/dist/core/extensions/builtin/mcp/auth/catalog-identity.js +32 -8
  148. package/dist/core/extensions/builtin/mcp/auth/commands-auth.js +2 -1
  149. package/dist/core/extensions/builtin/mcp/auth/context.js +3 -0
  150. package/dist/core/extensions/builtin/mcp/auth/oauth-grant.d.ts +43 -0
  151. package/dist/core/extensions/builtin/mcp/auth/oauth-grant.js +196 -0
  152. package/dist/core/extensions/builtin/mcp/auth/oauth-issuer.d.ts +7 -1
  153. package/dist/core/extensions/builtin/mcp/auth/oauth-issuer.js +13 -0
  154. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.d.ts +6 -17
  155. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +67 -88
  156. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.d.ts +1 -1
  157. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.js +25 -4
  158. package/dist/core/extensions/builtin/mcp/auth/oauth.js +10 -7
  159. package/dist/core/extensions/builtin/mcp/auth/registered-redirect.d.ts +19 -0
  160. package/dist/core/extensions/builtin/mcp/auth/registered-redirect.js +55 -0
  161. package/dist/core/extensions/builtin/mcp/auth/token-store.d.ts +23 -1
  162. package/dist/core/extensions/builtin/mcp/auth/token-store.js +3 -0
  163. package/dist/core/extensions/builtin/mcp/catalog-cache.js +7 -6
  164. package/dist/core/extensions/builtin/mcp/catalog.js +3 -2
  165. package/dist/core/extensions/builtin/mcp/invocation.js +6 -0
  166. package/dist/core/extensions/builtin/mcp/service-register.js +16 -2
  167. package/dist/core/extensions/builtin/mcp/service-tools-changed.js +61 -54
  168. package/dist/core/extensions/builtin/mcp/startup-race.d.ts +2 -0
  169. package/dist/core/extensions/builtin/mcp/startup-race.js +25 -7
  170. package/dist/core/extensions/builtin/permission-system/parsers.js +1 -0
  171. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js +3 -3
  172. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-2.js +9 -8
  173. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js +3 -3
  174. package/dist/core/extensions/builtin/prompt-preset/claude-haiku-5-5.js +3 -3
  175. package/dist/core/extensions/builtin/prompt-preset/claude-opus-5-5.js +3 -3
  176. package/dist/core/extensions/builtin/prompt-preset/claude-opus-5.js +4 -4
  177. package/dist/core/extensions/builtin/prompt-preset/claude-sonnet-5-5.js +3 -3
  178. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-1-flash.js +3 -3
  179. package/dist/core/extensions/builtin/prompt-preset/gpt-5.5.js +3 -3
  180. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +2 -2
  181. package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +3 -3
  182. package/dist/core/extensions/builtin/prompt-preset/grok-4.5.js +1 -1
  183. package/dist/core/extensions/builtin/prompt-preset/grok-4.6.js +4 -4
  184. package/dist/core/extensions/builtin/prompt-preset/grok-4.7.js +5 -5
  185. package/dist/core/extensions/builtin/prompt-preset/kimi-k3-1.js +4 -4
  186. package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js +7 -6
  187. package/dist/core/extensions/loader.js +24 -4
  188. package/dist/core/extensions/runner.d.ts +9 -1
  189. package/dist/core/extensions/runner.js +9 -4
  190. package/dist/core/extensions/types.d.ts +19 -3
  191. package/dist/core/hand/hook-advertise.d.ts +41 -0
  192. package/dist/core/hand/hook-advertise.js +98 -0
  193. package/dist/core/hand/hook-contract.d.ts +66 -0
  194. package/dist/core/hand/hook-contract.js +138 -0
  195. package/dist/core/open-timing.d.ts +2 -0
  196. package/dist/core/open-timing.js +7 -1
  197. package/dist/core/resource-loader.js +21 -3
  198. package/dist/core/retry-fallback/controller-types.d.ts +2 -0
  199. package/dist/core/retry-fallback/controller.js +9 -2
  200. package/dist/core/retry-fallback/cooldown.d.ts +7 -0
  201. package/dist/core/retry-fallback/cooldown.js +13 -1
  202. package/dist/core/retry-fallback/credential-recovery.d.ts +7 -0
  203. package/dist/core/retry-fallback/credential-recovery.js +24 -0
  204. package/dist/core/retry-fallback/log.d.ts +7 -1
  205. package/dist/core/retry-fallback/log.js +82 -5
  206. package/dist/core/retry-fallback/model-config-error.js +2 -1
  207. package/dist/core/retry-fallback/settings.d.ts +8 -5
  208. package/dist/core/retry-fallback/settings.js +9 -6
  209. package/dist/core/session-manager.d.ts +2 -0
  210. package/dist/core/session-manager.js +15 -1
  211. package/dist/core/settings-manager.d.ts +6 -0
  212. package/dist/core/settings-manager.js +8 -0
  213. package/dist/core/turn-origin.d.ts +18 -10
  214. package/dist/core/turn-origin.js +34 -30
  215. package/dist/core/ultrafast-lanes.d.ts +1 -0
  216. package/dist/core/ultrafast-lanes.js +4 -2
  217. package/dist/modes/interactive/components/footer.d.ts +23 -5
  218. package/dist/modes/interactive/components/footer.js +45 -16
  219. package/dist/modes/interactive/interactive-mode.js +9 -1
  220. package/dist/modes/interactive/session-control-rpc-commands.d.ts +1 -1
  221. package/dist/modes/interactive/session-control-rpc-commands.js +5 -0
  222. package/dist/modes/rpc/admit-external-message-command.d.ts +2 -0
  223. package/dist/modes/rpc/admit-external-message-command.js +5 -1
  224. package/dist/modes/rpc/compact-admission-validation.js +4 -1
  225. package/dist/modes/rpc/connection-authority.d.ts +2 -1
  226. package/dist/modes/rpc/connection-authority.js +11 -9
  227. package/dist/modes/rpc/connection-handler.d.ts +2 -0
  228. package/dist/modes/rpc/connection-handler.js +33 -7
  229. package/dist/modes/rpc/connection-roles.d.ts +7 -0
  230. package/dist/modes/rpc/connection-roles.js +15 -0
  231. package/dist/modes/rpc/custom-capability.d.ts +6 -0
  232. package/dist/modes/rpc/custom-capability.js +6 -0
  233. package/dist/modes/rpc/delegated-drive-origin.d.ts +6 -6
  234. package/dist/modes/rpc/delegated-drive-origin.js +7 -8
  235. package/dist/modes/rpc/delegation-declaration.d.ts +2 -0
  236. package/dist/modes/rpc/delegation-declaration.js +7 -3
  237. package/dist/modes/rpc/effect-commands.d.ts +33 -0
  238. package/dist/modes/rpc/host-capabilities.d.ts +1 -0
  239. package/dist/modes/rpc/host-capabilities.js +7 -1
  240. package/dist/modes/rpc/host-gc-evidence.d.ts +1 -1
  241. package/dist/modes/rpc/host-gc-evidence.js +9 -3
  242. package/dist/modes/rpc/host-gc.js +4 -1
  243. package/dist/modes/rpc/host-observe-request.d.ts +2 -0
  244. package/dist/modes/rpc/host-observe-request.js +6 -1
  245. package/dist/modes/rpc/host-park-ledger.d.ts +19 -0
  246. package/dist/modes/rpc/host-park-ledger.js +110 -0
  247. package/dist/modes/rpc/lifecycle-delivery.js +4 -1
  248. package/dist/modes/rpc/loopless-tool-handlers.d.ts +6 -0
  249. package/dist/modes/rpc/loopless-tool-handlers.js +14 -1
  250. package/dist/modes/rpc/media-placeholders.js +1 -0
  251. package/dist/modes/rpc/method-classes-schema-host.d.ts +42 -1
  252. package/dist/modes/rpc/method-classes-schema-host.js +24 -21
  253. package/dist/modes/rpc/method-classes-schema-session.d.ts +20 -0
  254. package/dist/modes/rpc/method-classes-schema-session.js +6 -0
  255. package/dist/modes/rpc/method-classes-schema.d.ts +62 -1
  256. package/dist/modes/rpc/method-classes-schema.js +5 -2
  257. package/dist/modes/rpc/method-classes.d.ts +4 -0
  258. package/dist/modes/rpc/method-classes.js +6 -0
  259. package/dist/modes/rpc/multi-session-host.js +1 -1
  260. package/dist/modes/rpc/project-file-commands.d.ts +32 -0
  261. package/dist/modes/rpc/project-file-commands.js +195 -0
  262. package/dist/modes/rpc/project-file-path.d.ts +34 -0
  263. package/dist/modes/rpc/project-file-path.js +93 -0
  264. package/dist/modes/rpc/rpc-error-types.d.ts +9 -1
  265. package/dist/modes/rpc/rpc-error-types.js +8 -0
  266. package/dist/modes/rpc/rpc-host-command-types.d.ts +14 -1
  267. package/dist/modes/rpc/rpc-host-response-types.d.ts +21 -0
  268. package/dist/modes/rpc/rpc-mutation-response-types.d.ts +7 -0
  269. package/dist/modes/rpc/rpc-read-response-types.d.ts +7 -0
  270. package/dist/modes/rpc/rpc-session-command-types.d.ts +10 -0
  271. package/dist/modes/rpc/rpc-session-state-types.d.ts +2 -0
  272. package/dist/modes/rpc/session-attachment-gate.js +6 -0
  273. package/dist/modes/rpc/session-binding.d.ts +1 -0
  274. package/dist/modes/rpc/session-binding.js +6 -1
  275. package/dist/modes/rpc/session-command-activity.js +1 -0
  276. package/dist/modes/rpc/session-connection-context.d.ts +2 -0
  277. package/dist/modes/rpc/session-connection-context.js +4 -0
  278. package/dist/modes/rpc/session-registry-attach.d.ts +2 -0
  279. package/dist/modes/rpc/session-registry-attach.js +15 -11
  280. package/dist/modes/rpc/session-registry-claims.js +2 -0
  281. package/dist/modes/rpc/session-registry-open.js +13 -7
  282. package/dist/modes/rpc/session-registry-opening.js +2 -1
  283. package/dist/modes/rpc/session-registry-types.d.ts +4 -0
  284. package/dist/modes/rpc/session-registry.d.ts +3 -0
  285. package/dist/modes/rpc/session-registry.js +27 -3
  286. package/dist/modes/rpc/session-router-close.js +1 -0
  287. package/dist/modes/rpc/session-router-context.d.ts +4 -2
  288. package/dist/modes/rpc/session-router-context.js +3 -0
  289. package/dist/modes/rpc/session-router-host-reads.js +1 -0
  290. package/dist/modes/rpc/session-router-occupancy.js +10 -1
  291. package/dist/modes/rpc/session-router-open-result.d.ts +12 -0
  292. package/dist/modes/rpc/session-router-open-result.js +63 -0
  293. package/dist/modes/rpc/session-router-open.d.ts +3 -0
  294. package/dist/modes/rpc/session-router-open.js +15 -63
  295. package/dist/modes/rpc/session-router-park.d.ts +15 -0
  296. package/dist/modes/rpc/session-router-park.js +176 -0
  297. package/dist/modes/rpc/session-router-routing.d.ts +1 -1
  298. package/dist/modes/rpc/session-router-routing.js +7 -0
  299. package/dist/modes/rpc/session-status-source.js +2 -2
  300. package/dist/private-fd-startup-fillers.d.ts +2 -2
  301. package/dist/private-fd-startup-fillers.js +34 -4
  302. package/dist/senpi +9 -3
  303. package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
  304. package/docs/engine-socket/fixtures/rpc-inbound-samples.json +44 -2
  305. package/docs/extensions.md +11 -1
  306. package/docs/rpc.md +106 -2
  307. package/docs/settings.md +5 -3
  308. package/docs/skills.md +1 -1
  309. package/docs/usage.md +1 -1
  310. package/native/socket-secret/prebuilds/win32-arm64/senpi_socket_secret.win32-arm64.node +0 -0
  311. package/native/socket-secret/prebuilds/win32-x64/senpi_socket_secret.win32-x64.node +0 -0
  312. package/package.json +6 -6
  313. package/dist/bundle/chunks/chunk-436DNN4Z.js +0 -2
  314. package/dist/bundle/chunks/chunk-DLAY7CIU.js +0 -2
  315. package/dist/bundle/chunks/chunk-SJI6UB23.js +0 -2
  316. package/dist/bundle/chunks/chunk-XH2MWTXA.js +0 -11
  317. package/dist/bundle/chunks/chunk-YK3ZZCHI.js +0 -2
  318. package/dist/bundle/chunks/openai-codex-responses-ABB2J43U.js +0 -10
  319. package/dist/bundle/chunks/rpc-mode-ZDUGW2IM.js +0 -2
  320. package/dist/bundle/chunks/session-control-endpoint-MEDV66PS.js +0 -3
@@ -13,7 +13,7 @@ renameSync(temporary, launcher);
13
13
  `);return}let source=parsed,name=readString(source,"name");if(!name){process.stderr.write(`warning: ignoring ${BRAND_ENV_VAR} without a "name"
14
14
  `);return}let configDir=readString(source,"configDir")||`.${name}`;if(!isSafeConfigDirName(configDir)){process.stderr.write(`warning: ignoring ${BRAND_ENV_VAR} with an unsafe "configDir"
15
15
  `);return}let changelog=readChangelog(source);return{name,command:readString(source,"command"),displayVersion:readString(source,"displayVersion"),configDir,flatLayout:source.flatLayout===!0,envPrefix:(readString(source,"envPrefix")||name).toUpperCase(),userAgent:readString(source,"userAgent")||name,originator:readString(source,"originator"),logo:readString(source,"logo"),update:readUpdateChannel(source),...changelog?{changelog}:{}}}function consumeBrandProfile(env=process.env){return parseBrandProfile(env[BRAND_ENV_VAR])}function scrubBrandFromEnvironment(env=process.env){delete env[BRAND_ENV_VAR]}function brandProfile(){return profileResolved||(cachedProfile=consumeBrandProfile(),profileResolved=!0),cachedProfile}function brandEnvNames(suffix,profile=brandProfile()){let prefixes=[profile?.envPrefix,...LEGACY_ENV_PREFIXES].filter(prefix=>typeof prefix=="string"&&prefix.length>0);return[...new Set(prefixes)].map(prefix=>`${prefix}_${suffix}`)}function envValue(suffix,env=process.env){for(let name of brandEnvNames(suffix)){let value=env[name];if(value!==void 0)return value}}var BRAND_ENV_VAR,LEGACY_ENV_PREFIXES,cachedProfile,profileResolved,init_brand=__esm({"packages/coding-agent/dist/core/brand.js"(){BRAND_ENV_VAR="SENPI_BRAND";LEGACY_ENV_PREFIXES=["SENPI","PI"],profileResolved=!1}});import{lstatSync}from"node:fs";import{dirname,join,normalize}from"node:path";function isDirectory(path2){try{return lstatSync(path2).isDirectory()}catch{return!1}}function isFile(path2){try{return lstatSync(path2).isFile()}catch{return!1}}function findNearestParentConfigDir(cwd,homeDir,configDirName,requiredChildDir,requiredChildFile){let normalizedHomeDir=normalize(homeDir),currentDir=normalize(cwd);for(let depth=0;depth<=MAX_PARENT_CONFIG_SEARCH_DEPTH;depth+=1){if(currentDir===normalizedHomeDir)return;let configDir=join(currentDir,configDirName),hasRequiredChild=requiredChildFile?isFile(join(configDir,requiredChildFile)):!requiredChildDir||isDirectory(join(configDir,requiredChildDir));if(isDirectory(configDir)&&hasRequiredChild)return configDir;let parentDir=dirname(currentDir);if(parentDir===currentDir)return;currentDir=parentDir}}var MAX_PARENT_CONFIG_SEARCH_DEPTH,init_nearest_parent_config=__esm({"packages/coding-agent/dist/nearest-parent-config.js"(){MAX_PARENT_CONFIG_SEARCH_DEPTH=100}});import{readFileSync}from"node:fs";import{isAbsolute,join as join2,relative}from"node:path";function readRuntimeSnapshotMarker(packageRoot){let text;try{text=readFileSync(join2(packageRoot,RUNTIME_SNAPSHOT_MARKER),"utf8")}catch(error62){if(error62 instanceof Error&&"code"in error62&&(error62.code==="ENOENT"||error62.code==="ENOTDIR"))return;throw error62}let parsed=JSON.parse(text);if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&"installPackageDir"in parsed&&typeof parsed.installPackageDir=="string")return{buildId:parsed.buildId,installPackageDir:parsed.installPackageDir}}var RUNTIME_SNAPSHOT_MARKER,init_marker=__esm({"packages/coding-agent/dist/runtime-snapshot/marker.js"(){RUNTIME_SNAPSHOT_MARKER="runtime-snapshot.json"}});var require_windows=__commonJS({"node_modules/isexe/windows.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs2=__require("fs");function checkPathExt(path2,options){var pathext=options.pathExt!==void 0?options.pathExt:process.env.PATHEXT;if(!pathext||(pathext=pathext.split(";"),pathext.indexOf("")!==-1))return!0;for(var i=0;i<pathext.length;i++){var p=pathext[i].toLowerCase();if(p&&path2.substr(-p.length).toLowerCase()===p)return!0}return!1}function checkStat(stat5,path2,options){return!stat5.isSymbolicLink()&&!stat5.isFile()?!1:checkPathExt(path2,options)}function isexe(path2,options,cb){fs2.stat(path2,function(er,stat5){cb(er,er?!1:checkStat(stat5,path2,options))})}function sync(path2,options){return checkStat(fs2.statSync(path2),path2,options)}}});var require_mode=__commonJS({"node_modules/isexe/mode.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs2=__require("fs");function isexe(path2,options,cb){fs2.stat(path2,function(er,stat5){cb(er,er?!1:checkStat(stat5,options))})}function sync(path2,options){return checkStat(fs2.statSync(path2),options)}function checkStat(stat5,options){return stat5.isFile()&&checkMode(stat5,options)}function checkMode(stat5,options){var mod=stat5.mode,uid=stat5.uid,gid=stat5.gid,myUid=options.uid!==void 0?options.uid:process.getuid&&process.getuid(),myGid=options.gid!==void 0?options.gid:process.getgid&&process.getgid(),u=parseInt("100",8),g=parseInt("010",8),o=parseInt("001",8),ug=u|g,ret=mod&o||mod&g&&gid===myGid||mod&u&&uid===myUid||mod&ug&&myUid===0;return ret}}});var require_isexe=__commonJS({"node_modules/isexe/index.js"(exports,module){var fs2=__require("fs"),core;process.platform==="win32"||global.TESTING_WINDOWS?core=require_windows():core=require_mode();module.exports=isexe;isexe.sync=sync;function isexe(path2,options,cb){if(typeof options=="function"&&(cb=options,options={}),!cb){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(resolve5,reject){isexe(path2,options||{},function(er,is){er?reject(er):resolve5(is)})})}core(path2,options||{},function(er,is){er&&(er.code==="EACCES"||options&&options.ignoreErrors)&&(er=null,is=!1),cb(er,is)})}function sync(path2,options){try{return core.sync(path2,options||{})}catch(er){if(options&&options.ignoreErrors||er.code==="EACCES")return!1;throw er}}}});var require_which=__commonJS({"node_modules/which/which.js"(exports,module){var isWindows=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",path2=__require("path"),COLON=isWindows?";":":",isexe=require_isexe(),getNotFoundError=cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),getPathInfo=(cmd,opt)=>{let colon=opt.colon||COLON,pathEnv=cmd.match(/\//)||isWindows&&cmd.match(/\\/)?[""]:[...isWindows?[process.cwd()]:[],...(opt.path||process.env.PATH||"").split(colon)],pathExtExe=isWindows?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",pathExt=isWindows?pathExtExe.split(colon):[""];return isWindows&&cmd.indexOf(".")!==-1&&pathExt[0]!==""&&pathExt.unshift(""),{pathEnv,pathExt,pathExtExe}},which=(cmd,opt,cb)=>{typeof opt=="function"&&(cb=opt,opt={}),opt||(opt={});let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[],step=i=>new Promise((resolve5,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve5(found):reject(getNotFoundError(cmd));let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path2.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve5(subStep(p,i,0))}),subStep=(p,i,ii)=>new Promise((resolve5,reject)=>{if(ii===pathExt.length)return resolve5(step(i+1));let ext=pathExt[ii];isexe(p+ext,{pathExt:pathExtExe},(er,is)=>{if(!er&&is)if(opt.all)found.push(p+ext);else return resolve5(p+ext);return resolve5(subStep(p,i,ii+1))})});return cb?step(0).then(res=>cb(null,res),cb):step(0)},whichSync=(cmd,opt)=>{opt=opt||{};let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[];for(let i=0;i<pathEnv.length;i++){let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path2.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j=0;j<pathExt.length;j++){let cur=p+pathExt[j];try{if(isexe.sync(cur,{pathExt:pathExtExe}))if(opt.all)found.push(cur);else return cur}catch{}}}if(opt.all&&found.length)return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)};module.exports=which;which.sync=whichSync}});var require_path_key=__commonJS({"node_modules/path-key/index.js"(exports,module){"use strict";var pathKey=(options={})=>{let environment=options.env||process.env;return(options.platform||process.platform)!=="win32"?"PATH":Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"};module.exports=pathKey;module.exports.default=pathKey}});var require_resolveCommand=__commonJS({"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports,module){"use strict";var path2=__require("path"),which=require_which(),getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){let env=parsed.options.env||process.env,cwd=process.cwd(),hasCustomCwd=parsed.options.cwd!=null,shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd)try{process.chdir(parsed.options.cwd)}catch{}let resolved;try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path2.delimiter:void 0})}catch{}finally{shouldSwitchCwd&&process.chdir(cwd)}return resolved&&(resolved=path2.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)),resolved}function resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,!0)}module.exports=resolveCommand}});var require_escape=__commonJS({"node_modules/cross-spawn/lib/util/escape.js"(exports,module){"use strict";var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){return arg=arg.replace(metaCharsRegExp,"^$1"),arg}function escapeArgument(arg,doubleEscapeMetaChars){return arg=`${arg}`,arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1"),arg=`"${arg}"`,arg=arg.replace(metaCharsRegExp,"^$1"),doubleEscapeMetaChars&&(arg=arg.replace(metaCharsRegExp,"^$1")),arg}module.exports.command=escapeCommand;module.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/shebang-regex/index.js"(exports,module){"use strict";module.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/shebang-command/index.js"(exports,module){"use strict";var shebangRegex=require_shebang_regex();module.exports=(string4="")=>{let match=string4.match(shebangRegex);if(!match)return null;let[path2,argument]=match[0].replace(/#! ?/,"").split(" "),binary=path2.split("/").pop();return binary==="env"?argument:argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/cross-spawn/lib/util/readShebang.js"(exports,module){"use strict";var fs2=__require("fs"),shebangCommand=require_shebang_command();function readShebang(command){let buffer=Buffer.alloc(150),fd;try{fd=fs2.openSync(command,"r"),fs2.readSync(fd,buffer,0,150,0),fs2.closeSync(fd)}catch{}return shebangCommand(buffer.toString())}module.exports=readShebang}});var require_parse=__commonJS({"node_modules/cross-spawn/lib/parse.js"(exports,module){"use strict";var path2=__require("path"),resolveCommand=require_resolveCommand(),escape=require_escape(),readShebang=require_readShebang(),isWin=process.platform==="win32",isExecutableRegExp=/\.(?:com|exe)$/i,isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);let shebang=parsed.file&&readShebang(parsed.file);return shebang?(parsed.args.unshift(parsed.file),parsed.command=shebang,resolveCommand(parsed)):parsed.file}function parseNonShell(parsed){if(!isWin)return parsed;let commandFile=detectShebang(parsed),needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){let needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path2.normalize(parsed.command),parsed.command=escape.command(parsed.command),parsed.args=parsed.args.map(arg=>escape.argument(arg,needsDoubleEscapeMetaChars));let shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`],parsed.command=process.env.comspec||"cmd.exe",parsed.options.windowsVerbatimArguments=!0}return parsed}function parse4(command,args,options){args&&!Array.isArray(args)&&(options=args,args=null),args=args?args.slice(0):[],options=Object.assign({},options);let parsed={command,args,options,file:void 0,original:{command,args}};return options.shell?parsed:parseNonShell(parsed)}module.exports=parse4}});var require_enoent=__commonJS({"node_modules/cross-spawn/lib/enoent.js"(exports,module){"use strict";var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}function hookChildProcess(cp,parsed){if(!isWin)return;let originalEmit=cp.emit;cp.emit=function(name,arg1){if(name==="exit"){let err=verifyENOENT(arg1,parsed);if(err)return originalEmit.call(cp,"error",err)}return originalEmit.apply(cp,arguments)}}function verifyENOENT(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawn"):null}function verifyENOENTSync(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawnSync"):null}module.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError}}});var require_cross_spawn=__commonJS({"node_modules/cross-spawn/index.js"(exports,module){"use strict";var cp=__require("child_process"),parse4=require_parse(),enoent=require_enoent();function spawn(command,args,options){let parsed=parse4(command,args,options),spawned=cp.spawn(parsed.command,parsed.args,parsed.options);return enoent.hookChildProcess(spawned,parsed),spawned}function spawnSync(command,args,options){let parsed=parse4(command,args,options),result=cp.spawnSync(parsed.command,parsed.args,parsed.options);return result.error=result.error||enoent.verifyENOENTSync(result.status,parsed),result}module.exports=spawn;module.exports.spawn=spawn;module.exports.sync=spawnSync;module.exports._parse=parse4;module.exports._enoent=enoent}});var import_cross_spawn,init_child_process=__esm({"packages/coding-agent/dist/utils/child-process.js"(){import_cross_spawn=__toESM(require_cross_spawn(),1)}});import{homedir as homedir2}from"node:os";import{isAbsolute as isAbsolute2,join as join3,resolve as nodeResolvePath,parse,relative as relative2,sep}from"node:path";import{fileURLToPath}from"node:url";function normalizeWindowsShellPath(filePath){if(!filePath.startsWith("/")||filePath.startsWith("//")||filePath.includes("\\"))return filePath;let match=filePath.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(!match)return filePath;let suffix=match[2]?.replaceAll("/","\\");return`${match[1].toUpperCase()}:\\${suffix??""}`}function normalizePath(input2,options={}){let normalized=options.trim?input2.trim():input2;if(options.normalizeUnicodeSpaces&&(normalized=normalized.replace(UNICODE_SPACES," ")),options.stripAtPrefix&&normalized.startsWith("@")&&(normalized=normalized.slice(1)),process.platform==="win32"&&(normalized=normalizeWindowsShellPath(normalized)),options.expandTilde??!0){let home=options.homeDir??homedir2();if(normalized==="~")return home;if(normalized.startsWith("~/")||process.platform==="win32"&&normalized.startsWith("~\\"))return join3(home,normalized.slice(2))}return/^file:\/\//.test(normalized)?fileURLToPath(normalized):normalized}var UNICODE_SPACES,init_paths=__esm({"packages/coding-agent/dist/utils/paths.js"(){init_child_process();UNICODE_SPACES=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g}});function splitBom(content){return content.startsWith("\uFEFF")?{bom:"\uFEFF",text:content.slice(1)}:{bom:"",text:content}}function stripBom(content){return splitBom(content).text}var init_text=__esm({"packages/coding-agent/dist/utils/text.js"(){}});import{accessSync,constants,existsSync,readFileSync as readFileSync2,realpathSync}from"fs";import{homedir as homedir3,userInfo}from"os";import{basename,dirname as dirname2,join as join4,resolve,sep as sep2,win32}from"path";import{fileURLToPath as fileURLToPath2}from"url";function findNodePackageDir(startDir){let dir=startDir;for(;dir!==dirname2(dir);){if(existsSync(join4(dir,"package.json"))){let parent=dirname2(dir);return basename(dir)==="dist"&&existsSync(join4(parent,"package.json"))?parent:dir}dir=dirname2(dir)}return startDir}function getPackageDir(){let envDir=envValue("PACKAGE_DIR");return envDir?normalizePath(envDir):isBunBinary?dirname2(process.execPath):(nodePackageDir??=findNodePackageDir(__dirname),nodePackageDir)}function getPackageJsonPath(){return join4(getPackageDir(),"package.json")}function resolveAgentDir(cwd,homeDir,envDir){if(envDir)return normalizePath(envDir,{homeDir});if(CONFIG_FLAT_LAYOUT)return findNearestParentConfigDir(cwd,homeDir,CONFIG_DIR_NAME,void 0,FLAT_LAYOUT_SENTINEL)??join4(homeDir,CONFIG_DIR_NAME);let projectConfigDir=findNearestParentConfigDir(cwd,homeDir,CONFIG_DIR_NAME,"agent");return projectConfigDir?join4(projectConfigDir,"agent"):join4(homeDir,CONFIG_DIR_NAME,"agent")}function isGuardedTestRun(env){return env.SENPI_TEST_AGENT_DIR_GUARD==="1"}function realHomeDir(){try{return userInfo().homedir}catch{return}}function assertAgentDirAllowedInTests(agentDir,activeConfigDirName,env=process.env){if(!isGuardedTestRun(env)||env.SENPI_TEST_USE_REAL_AGENT_DIR==="1")return;let home=realHomeDir();if(!home)return;let target=resolve(agentDir);for(let configDir of new Set([...KNOWN_BRAND_CONFIG_DIRS,activeConfigDirName])){let root=join4(home,configDir);if(target===root||target.startsWith(root+sep2))throw new RealAgentDirInTestError(target)}}function getAgentDir(){let agentDir=resolveAgentDir(process.cwd(),homedir3(),envValue("CODING_AGENT_DIR"));return assertAgentDirAllowedInTests(agentDir,CONFIG_DIR_NAME),agentDir}var __filename,__dirname,isBunBinary,isBunRuntime,isBundledNode,nodePackageDir,pkg,piConfigName,BRAND,PACKAGE_NAME,APP_NAME,APP_COMMAND,APP_TITLE,CONFIG_DIR_NAME,CONFIG_FLAT_LAYOUT,VERSION,DISPLAY_VERSION,ENV_PREFIX,ENV_AGENT_DIR,ENV_SESSION_DIR,FLAT_LAYOUT_SENTINEL,KNOWN_BRAND_CONFIG_DIRS,RealAgentDirInTestError,init_config=__esm({"packages/coding-agent/dist/config.js"(){init_bun_global_launcher();init_brand();init_nearest_parent_config();init_marker();init_child_process();init_paths();init_text();__filename=fileURLToPath2(import.meta.url),__dirname=dirname2(__filename),isBunBinary=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),isBunRuntime=!!process.versions.bun,isBundledNode=!0;pkg={};try{pkg=JSON.parse(stripBom(readFileSync2(getPackageJsonPath(),"utf-8")))}catch(e){if(e.code!=="ENOENT")throw e}piConfigName=pkg.piConfig?.name,BRAND=brandProfile(),PACKAGE_NAME=pkg.name||"@earendil-works/pi-coding-agent",APP_NAME=BRAND?.name||piConfigName||"pi",APP_COMMAND=BRAND?.command??APP_NAME,APP_TITLE=BRAND?.name||(piConfigName?APP_NAME:"\u03C0"),CONFIG_DIR_NAME=BRAND?.configDir||pkg.piConfig?.configDir||".pi",CONFIG_FLAT_LAYOUT=BRAND?.flatLayout===!0,VERSION=pkg.version||"0.0.0",DISPLAY_VERSION=BRAND?.displayVersion||VERSION,ENV_PREFIX=BRAND?.envPrefix||APP_NAME.toUpperCase(),ENV_AGENT_DIR=`${ENV_PREFIX}_CODING_AGENT_DIR`,ENV_SESSION_DIR=`${ENV_PREFIX}_CODING_AGENT_SESSION_DIR`,FLAT_LAYOUT_SENTINEL="settings.json";KNOWN_BRAND_CONFIG_DIRS=[".senpi",".omo",".pi"],RealAgentDirInTestError=class extends Error{constructor(agentDir){super(`Refusing to use the real agent directory ${agentDir} from a test run. Point <BRAND>_CODING_AGENT_DIR at a temp dir, or set SENPI_TEST_USE_REAL_AGENT_DIR=1 to opt in.`),this.name="RealAgentDirInTestError",this.agentDir=agentDir}}}});var require_signals=__commonJS({"node_modules/signal-exit/signals.js"(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}});var require_signal_exit=__commonJS({"node_modules/signal-exit/index.js"(exports,module){var process2=global.process,processOk=function(process3){return process3&&typeof process3=="object"&&typeof process3.removeListener=="function"&&typeof process3.emit=="function"&&typeof process3.reallyExit=="function"&&typeof process3.listeners=="function"&&typeof process3.kill=="function"&&typeof process3.pid=="number"&&typeof process3.on=="function"};processOk(process2)?(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process2.platform),EE=__require("events"),typeof EE!="function"&&(EE=EE.EventEmitter),process2.__signal_exit_emitter__?emitter=process2.__signal_exit_emitter__:(emitter=process2.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={}),emitter.infinite||(emitter.setMaxListeners(1/0),emitter.infinite=!0),module.exports=function(cb,opts){if(!processOk(global.process))return function(){};assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1&&load();var ev="exit";opts&&opts.alwaysLast&&(ev="afterexit");var remove=function(){emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0&&unload()};return emitter.on(ev,cb),remove},unload=function(){!loaded||!processOk(global.process)||(loaded=!1,signals.forEach(function(sig){try{process2.removeListener(sig,sigListeners[sig])}catch{}}),process2.emit=originalProcessEmit,process2.reallyExit=originalProcessReallyExit,emitter.count-=1)},module.exports.unload=unload,emit=function(event,code,signal){emitter.emitted[event]||(emitter.emitted[event]=!0,emitter.emit(event,code,signal))},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(processOk(global.process)){var listeners=process2.listeners(sig);listeners.length===emitter.count&&(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP"&&(sig="SIGINT"),process2.kill(process2.pid,sig))}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){loaded||!processOk(global.process)||(loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process2.on(sig,sigListeners[sig]),!0}catch{return!1}}),process2.emit=processEmit,process2.reallyExit=processReallyExit)},module.exports.load=load,originalProcessReallyExit=process2.reallyExit,processReallyExit=function(code){processOk(global.process)&&(process2.exitCode=code||0,emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),originalProcessReallyExit.call(process2,process2.exitCode))},originalProcessEmit=process2.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){arg!==void 0&&(process2.exitCode=arg);var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}):module.exports=function(){return function(){}};var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit}});import{stat}from"node:fs/promises";async function openLockDatabase(lockPath){if(typeof globalThis.Bun<"u"){let{Database}=await import("bun:sqlite"),database2=new Database(lockPath,{create:!0});return{exec:sql=>database2.exec(sql),close:()=>database2.close(!1)}}let{DatabaseSync}=await import("node:sqlite"),database=new DatabaseSync(lockPath);return{exec:sql=>database.exec(sql),close:()=>database.close()}}async function acquireOwnershipSafeLock(lockPath,options={}){let retries=options.retries??DEFAULT_RETRIES,deadline=Date.now()+retries.retries*retries.maxTimeout;for(;;){await rejectLegacyDirectory(lockPath);let busyMs=Math.max(1,Math.min(retries.maxTimeout,deadline-Date.now())),database;try{database=await openLockDatabase(lockPath),database.exec(`PRAGMA busy_timeout = ${busyMs}; BEGIN EXCLUSIVE;`);let released=!1,held=database;return async()=>{if(!released){released=!0;try{held.exec("COMMIT;")}finally{held.close()}}}}catch(error62){try{database?.close()}catch{}if(await rejectLegacyDirectory(lockPath),isBusy(error62)&&Date.now()<deadline){await new Promise(resolve5=>setTimeout(resolve5,Math.min(retries.minTimeout,Math.max(1,deadline-Date.now()))));continue}throw error62}}}async function rejectLegacyDirectory(lockPath){try{if((await stat(lockPath)).isDirectory())throw new LegacyLockArtifactError(lockPath)}catch(error62){if(error62 instanceof LegacyLockArtifactError||error62.code!=="ENOENT")throw error62}}function isBusy(error62){let message=error62 instanceof Error?error62.message:String(error62);return/busy|locked/i.test(message)||error62?.code==="SQLITE_BUSY"}var LegacyLockArtifactError,DEFAULT_RETRIES,init_ownership_safe_lock=__esm({"packages/coding-agent/dist/modes/rpc/ownership-safe-lock.js"(){LegacyLockArtifactError=class extends Error{constructor(lockPath){super(`Legacy lock directory is present at ${lockPath}`),this.code="ELEGACY_LOCK_ARTIFACT",this.name="LegacyLockArtifactError",this.lockPath=lockPath}},DEFAULT_RETRIES={retries:100,minTimeout:20,maxTimeout:100}}});import{execFile,execFileSync}from"node:child_process";function processStartTimeMs(identity){if(/^\d+$/.test(identity)){let parsed2=Number((BigInt(identity)-WINDOWS_FILETIME_EPOCH)/10000n);return Number.isFinite(parsed2)?parsed2:void 0}let localIdentity=identity.trim(),korean=/^(\d{4})\uB144\s+(\d{1,2})\uC6D4\s+(\d{1,2})\uC77C\s+[\uC6D4\uD654\uC218\uBAA9\uAE08\uD1A0\uC77C]\uC694\uC77C\s+(\d{1,2})\uC2DC\s+(\d{1,2})\uBD84\s+(\d{1,2})\uCD08$/.exec(localIdentity),japanese=/^[\u65E5\u6708\u706B\u6C34\u6728\u91D1\u571F](?:\u66DC\u65E5)?\s+(\d{1,2})\/\s*(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})$/.exec(localIdentity),parts=korean?korean.slice(1):japanese?[japanese[6],japanese[1],japanese[2],japanese[3],japanese[4],japanese[5]]:void 0;if(parts===void 0){let parsed2=Date.parse(identity);return Number.isFinite(parsed2)?parsed2:void 0}let[year=NaN,month=NaN,day=NaN,hour=NaN,minute=NaN,second=NaN]=parts.map(Number),parsed=new Date(year,month-1,day,hour,minute,second,0);return parsed.getFullYear()===year&&parsed.getMonth()===month-1&&parsed.getDate()===day&&parsed.getHours()===hour&&parsed.getMinutes()===minute&&parsed.getSeconds()===second?parsed.getTime():void 0}function sameProcessStartMs(recorded,observed){return recorded!==void 0&&observed!==void 0&&Number.isFinite(recorded)&&Number.isFinite(observed)&&Math.abs(recorded-observed)<=PROCESS_START_TOLERANCE_MS}function parseDaemonPidFile(text){let parsed;try{parsed=JSON.parse(text)}catch(error62){if(error62 instanceof SyntaxError)return;throw error62}let unguarded=parsed!==null&&isRecord(parsed)&&parsed.processStartTime===null;if(!(!isRecord(parsed)||typeof parsed.pid!="number"||!unguarded&&typeof parsed.processStartTime!="string")&&!(!Number.isInteger(parsed.pid)||parsed.pid<=0)){if(unguarded)return{pid:parsed.pid,processStartTime:null};if(!(typeof parsed.processStartTime!="string"||parsed.processStartTime.trim()===""))return{pid:parsed.pid,processStartTime:parsed.processStartTime}}}async function readProcessIdentity(pid,platform=process.platform,timeoutMs,isLive=processIsLive,timeZone){let command=platform==="win32"?{executable:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`$process = Get-CimInstance Win32_Process -Filter "ProcessId=${String(pid)}" -ErrorAction Stop; if ($null -eq $process) { Write-Output '__SENPI_ABSENT__'; exit 0 }; $process.CreationDate.ToFileTimeUtc().ToString("D", [Globalization.CultureInfo]::InvariantCulture)`]}:{executable:"ps",args:["-o","stat=,lstart=","-p",String(pid)]};return new Promise(resolve5=>{let effectiveTimeoutMs=timeoutMs??(platform==="win32"?1e3:void 0);execFile(command.executable,command.args,{windowsHide:!0,...effectiveTimeoutMs===void 0?{}:{timeout:effectiveTimeoutMs},...platform==="win32"&&timeZone===void 0?{}:{env:{...process.env,LC_ALL:"C",LANG:"C",...timeZone?{TZ:timeZone}:{}}}},(error62,stdout)=>{if(error62){let code="code"in error62?error62.code:void 0;if(platform!=="win32"&&code===1||!isLive(pid)){resolve5({kind:"absent"});return}resolve5({kind:"error",error:error62});return}let snapshot=stdout.trim();if(snapshot==="__SENPI_ABSENT__")return resolve5({kind:"absent"});let state3=platform==="win32"?"":snapshot.split(/\s+/,1)[0]??"";if(state3.startsWith("Z"))return resolve5({kind:"absent"});let output2=platform==="win32"?snapshot:snapshot.slice(state3.length).trim();if(!output2||platform==="win32"&&!/^\d+$/.test(output2))return resolve5({kind:"error",error:new Error("invalid process identity output")});resolve5({kind:"present",identity:timeZone&&platform!=="win32"?`${output2} UTC`:output2})}).once("error",error62=>resolve5({kind:"error",error:error62}))})}async function readProcessStartTime(pid,platform=process.platform,timeoutMs){return readProcessIdentity(pid,platform,timeoutMs).then(result=>{if(result.kind==="error")throw result.error;return result.kind==="present"?result.identity:void 0})}function processIsLive(pid){try{return process.kill(pid,0),!0}catch(error62){if(isNodeErrorCode(error62,"ESRCH"))return!1;if(isNodeErrorCode(error62,"EPERM"))return!0;throw error62}}async function waitForStartTime(pid,timeoutMs,readStartTime=readProcessStartTime,isLive=processIsLive){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){let startTime;try{startTime=await readStartTime(pid)}catch{}if(startTime)return startTime;await delay(20)}if(!isLive(pid))throw new Error(`spawned daemon pid ${pid} had no process start time`)}function delay(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode(error62,code){return error62 instanceof Error&&"code"in error62&&error62.code===code}var WINDOWS_FILETIME_EPOCH,PROCESS_START_TOLERANCE_MS,init_process_identity=__esm({"packages/coding-agent/dist/utils/process-identity.js"(){WINDOWS_FILETIME_EPOCH=116444736000000000n,PROCESS_START_TOLERANCE_MS=3e3}});import{createHmac,timingSafeEqual}from"node:crypto";function launchProofRecordRefusal(id){return{...id===void 0?{}:{id},type:"response",command:RPC_LAUNCH_PROOF_RECORD,success:!1,error:"reserved_record",errorCode:"reserved_record"}}function rpcAuthProof(key,label,...parts){return createHmac("sha256",key).update([`senpi-rpc-${label}`,...parts].join(`
16
- `),"utf8").digest("hex")}function rpcProofMatches(expected,received){return typeof received=="string"&&RPC_AUTH_HEX.test(received)&&timingSafeEqual(Buffer.from(expected,"hex"),Buffer.from(received,"hex"))}function authRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}var RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_ID,RPC_LAUNCH_PROOF_RECORD,RpcEndpointAuthError,init_rpc_auth_proof=__esm({"packages/coding-agent/dist/modes/rpc/rpc-auth-proof.js"(){RPC_AUTH_CAPABILITY="socket_auth",RPC_AUTH_HEX=/^[a-f0-9]{64}$/,RPC_LAUNCH_ID=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,RPC_LAUNCH_PROOF_RECORD="launch_proven";RpcEndpointAuthError=class extends Error{constructor(code,detail,options){super(`${code}: ${detail}`,options),this.code=code,this.name="RpcEndpointAuthError"}}}});function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record3=request;return record3.type==="warm"||record3.type==="authenticate"||record3.type===RPC_LAUNCH_PROOF_RECORD?!0:record3[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record3.type)}function observingHoldChange(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let record3=request;if(record3[OBSERVE_REQUEST_FIELD]!==!0||!OBSERVING_COMMANDS.has(record3.type))return;let hold=record3[HOLD_HOST_FIELD];return typeof hold=="boolean"?hold:void 0}function originHostInstance(env=process.env){let instance=env[HOST_INSTANCE_ID_ENV]?.trim();return instance||void 0}function requestOriginHostInstance(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let origin=Reflect.get(request,ORIGIN_HOST_INSTANCE_FIELD);return typeof origin=="string"&&origin.length>0?origin:void 0}var OBSERVE_REQUEST_FIELD,ORIGIN_HOST_INSTANCE_FIELD,HOLD_HOST_FIELD,OBSERVING_COMMANDS,init_host_observe_request=__esm({"packages/coding-agent/dist/modes/rpc/host-observe-request.js"(){init_host_identity_env();init_rpc_auth_proof();OBSERVE_REQUEST_FIELD="observe",ORIGIN_HOST_INSTANCE_FIELD="origin_host_instance",HOLD_HOST_FIELD="hold_host",OBSERVING_COMMANDS=new Set(["get_protocol_info","get_snapshot","list_sessions","subscribe_sessions","unsubscribe_sessions","get_effect_status","get_pending_inputs","get_subscription_limits","get_state","get_entries"])}});import{StringDecoder}from"node:string_decoder";import{isBigIntObject,isBooleanObject,isNumberObject,isStringObject}from"node:util/types";function isStackOverflow(cause){return cause instanceof RangeError&&cause.message.startsWith("Maximum call stack size exceeded")}function jsonStep(input2,key){let value=input2;if(typeof value=="object"&&value!==null||typeof value=="function"||typeof value=="bigint"){let toJSON=value.toJSON;typeof toJSON=="function"&&(value=toJSON.call(value,key))}if(typeof value=="object"&&value!==null){if(isNumberObject(value))value=+value;else if(isStringObject(value))value=String(value);else if(isBooleanObject(value))value=Boolean.prototype.valueOf.call(value);else if(isBigIntObject(value))throw new TypeError("Do not know how to serialize a BigInt")}if(typeof value=="bigint")throw new TypeError("Do not know how to serialize a BigInt");return typeof value=="number"?Number.isFinite(value)?Object.is(value,-0)?0:value:null:typeof value>"u"||typeof value=="function"||typeof value=="symbol"?OMITTED:value}function jsonNormalValue(input2){let ancestors=new Set,stack=[],enter=(input3,key)=>{let value=jsonStep(input3,key);if(typeof value!="object"||value===null)return value;if(ancestors.has(value))throw new TypeError("Converting circular structure to JSON");if(ancestors.add(value),Array.isArray(value)){let out2=[];return stack.push({source:value,out:out2,keys:void 0,length:value.length,index:0}),out2}let keys=Object.keys(value),out={};return stack.push({source:value,out,keys,length:keys.length,index:0}),out},root=enter(input2,"");for(;stack.length>0;){let frame=stack[stack.length-1];if(frame.index===frame.length){ancestors.delete(frame.source),stack.pop();continue}let index=frame.index++;if(frame.keys===void 0){let child2=enter(frame.source[index],String(index));frame.out.push(child2===OMITTED?null:child2);continue}let name=frame.keys[index],child=enter(frame.source[name],name);child!==OMITTED&&Object.defineProperty(frame.out,name,{value:child,enumerable:!0,configurable:!0,writable:!0})}return root===OMITTED?void 0:root}function normalJsonText(root){let parts=[],stack=[],open4=value=>{typeof value!="object"||value===null?parts.push(JSON.stringify(value)):Array.isArray(value)?(parts.push("["),stack.push({value,index:0})):(parts.push("{"),stack.push({value,keys:Object.keys(value),index:0}))};for(open4(root);stack.length>0;){let frame=stack[stack.length-1],{keys}=frame,length=keys===void 0?frame.value.length:keys.length;if(frame.index===length){parts.push(keys===void 0?"]":"}"),stack.pop();continue}let index=frame.index++;if(index>0&&parts.push(","),keys===void 0)open4(frame.value[index]);else{let name=keys[index];parts.push(JSON.stringify(name),":"),open4(frame.value[name])}}return parts.join("")}function legacyJsonText(value){try{return JSON.stringify(value)}catch(cause){if(!isStackOverflow(cause))throw cause;let normal=jsonNormalValue(value);return normal===void 0?void 0:normalJsonText(normal)}}function serializeJsonLine(value){return`${legacyJsonText(value)}
16
+ `),"utf8").digest("hex")}function rpcProofMatches(expected,received){return typeof received=="string"&&RPC_AUTH_HEX.test(received)&&timingSafeEqual(Buffer.from(expected,"hex"),Buffer.from(received,"hex"))}function authRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}var RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_ID,RPC_LAUNCH_PROOF_RECORD,RpcEndpointAuthError,init_rpc_auth_proof=__esm({"packages/coding-agent/dist/modes/rpc/rpc-auth-proof.js"(){RPC_AUTH_CAPABILITY="socket_auth",RPC_AUTH_HEX=/^[a-f0-9]{64}$/,RPC_LAUNCH_ID=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,RPC_LAUNCH_PROOF_RECORD="launch_proven";RpcEndpointAuthError=class extends Error{constructor(code,detail,options){super(`${code}: ${detail}`,options),this.code=code,this.name="RpcEndpointAuthError"}}}});function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record3=request;return record3.type==="warm"||record3.type==="park_session"||record3.type==="authenticate"||record3.type===RPC_LAUNCH_PROOF_RECORD?!0:record3[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record3.type)}function observingHoldChange(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let record3=request;if(record3[OBSERVE_REQUEST_FIELD]!==!0||!OBSERVING_COMMANDS.has(record3.type))return;let hold=record3[HOLD_HOST_FIELD];return typeof hold=="boolean"?hold:void 0}function originHostInstance(env=process.env){let instance=env[HOST_INSTANCE_ID_ENV]?.trim();return instance||void 0}function requestOriginHostInstance(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let origin=Reflect.get(request,ORIGIN_HOST_INSTANCE_FIELD);return typeof origin=="string"&&origin.length>0?origin:void 0}var OBSERVE_REQUEST_FIELD,ORIGIN_HOST_INSTANCE_FIELD,HOLD_HOST_FIELD,OBSERVING_COMMANDS,init_host_observe_request=__esm({"packages/coding-agent/dist/modes/rpc/host-observe-request.js"(){init_host_identity_env();init_rpc_auth_proof();OBSERVE_REQUEST_FIELD="observe",ORIGIN_HOST_INSTANCE_FIELD="origin_host_instance",HOLD_HOST_FIELD="hold_host",OBSERVING_COMMANDS=new Set(["get_protocol_info","get_snapshot","list_sessions","subscribe_sessions","unsubscribe_sessions","get_effect_status","get_pending_inputs","get_subscription_limits","get_state","get_entries"])}});import{StringDecoder}from"node:string_decoder";import{isBigIntObject,isBooleanObject,isNumberObject,isStringObject}from"node:util/types";function isStackOverflow(cause){return cause instanceof RangeError&&cause.message.startsWith("Maximum call stack size exceeded")}function jsonStep(input2,key){let value=input2;if(typeof value=="object"&&value!==null||typeof value=="function"||typeof value=="bigint"){let toJSON=value.toJSON;typeof toJSON=="function"&&(value=toJSON.call(value,key))}if(typeof value=="object"&&value!==null){if(isNumberObject(value))value=+value;else if(isStringObject(value))value=String(value);else if(isBooleanObject(value))value=Boolean.prototype.valueOf.call(value);else if(isBigIntObject(value))throw new TypeError("Do not know how to serialize a BigInt")}if(typeof value=="bigint")throw new TypeError("Do not know how to serialize a BigInt");return typeof value=="number"?Number.isFinite(value)?Object.is(value,-0)?0:value:null:typeof value>"u"||typeof value=="function"||typeof value=="symbol"?OMITTED:value}function jsonNormalValue(input2){let ancestors=new Set,stack=[],enter=(input3,key)=>{let value=jsonStep(input3,key);if(typeof value!="object"||value===null)return value;if(ancestors.has(value))throw new TypeError("Converting circular structure to JSON");if(ancestors.add(value),Array.isArray(value)){let out2=[];return stack.push({source:value,out:out2,keys:void 0,length:value.length,index:0}),out2}let keys=Object.keys(value),out={};return stack.push({source:value,out,keys,length:keys.length,index:0}),out},root=enter(input2,"");for(;stack.length>0;){let frame=stack[stack.length-1];if(frame.index===frame.length){ancestors.delete(frame.source),stack.pop();continue}let index=frame.index++;if(frame.keys===void 0){let child2=enter(frame.source[index],String(index));frame.out.push(child2===OMITTED?null:child2);continue}let name=frame.keys[index],child=enter(frame.source[name],name);child!==OMITTED&&Object.defineProperty(frame.out,name,{value:child,enumerable:!0,configurable:!0,writable:!0})}return root===OMITTED?void 0:root}function normalJsonText(root){let parts=[],stack=[],open4=value=>{typeof value!="object"||value===null?parts.push(JSON.stringify(value)):Array.isArray(value)?(parts.push("["),stack.push({value,index:0})):(parts.push("{"),stack.push({value,keys:Object.keys(value),index:0}))};for(open4(root);stack.length>0;){let frame=stack[stack.length-1],{keys}=frame,length=keys===void 0?frame.value.length:keys.length;if(frame.index===length){parts.push(keys===void 0?"]":"}"),stack.pop();continue}let index=frame.index++;if(index>0&&parts.push(","),keys===void 0)open4(frame.value[index]);else{let name=keys[index];parts.push(JSON.stringify(name),":"),open4(frame.value[name])}}return parts.join("")}function legacyJsonText(value){try{return JSON.stringify(value)}catch(cause){if(!isStackOverflow(cause))throw cause;let normal=jsonNormalValue(value);return normal===void 0?void 0:normalJsonText(normal)}}function serializeJsonLine(value){return`${legacyJsonText(value)}
17
17
  `}function attachJsonlLineReader(stream,onLine,options={}){let decoder=new StringDecoder("utf8"),maxLineLength=options.maxLineLength??Number.POSITIVE_INFINITY;if(!(maxLineLength>0))throw new Error("maxLineLength must be greater than zero.");let buffer="",discardingOversizedLine=!1,consume=text=>{let offset=0;for(;offset<text.length;){if(discardingOversizedLine){let newlineIndex2=text.indexOf(`
18
18
  `,offset);if(newlineIndex2===-1)return;discardingOversizedLine=!1,offset=newlineIndex2+1;continue}let newlineIndex=text.indexOf(`
19
19
  `,offset);if(newlineIndex===-1){let remainder=text.slice(offset);buffer.length+remainder.length>maxLineLength?(buffer="",discardingOversizedLine=!0,options.onOversizedLine?.()):buffer+=remainder;return}let segment=text.slice(offset,newlineIndex);if(buffer.length+segment.length>maxLineLength)options.onOversizedLine?.();else{let line=buffer+segment;onLine(line.endsWith("\r")?line.slice(0,-1):line)}buffer="",offset=newlineIndex+1}},onData=chunk=>{consume(typeof chunk=="string"?chunk:decoder.write(chunk))},onEnd=()=>{consume(decoder.end()),!discardingOversizedLine&&buffer.length>0&&onLine(buffer.endsWith("\r")?buffer.slice(0,-1):buffer),buffer="",discardingOversizedLine=!1};return stream.on("data",onData),stream.on("end",onEnd),()=>{stream.off("data",onData),stream.off("end",onEnd)}}var OMITTED,MAX_RPC_LINE_CHARACTERS,init_jsonl=__esm({"packages/coding-agent/dist/modes/rpc/jsonl.js"(){OMITTED=Symbol("omitted");MAX_RPC_LINE_CHARACTERS=16*1024*1024}});import{createHash as createHash2,randomBytes as randomBytes2,timingSafeEqual as timingSafeEqual2}from"node:crypto";import{constants as constants2}from"node:fs";import{chmod as chmod2,link,mkdir as mkdir2,open,readFile as readFile4,realpath,rename as rename2,unlink,writeFile as writeFile3}from"node:fs/promises";import{basename as basename6,dirname as dirname7,join as join12,win32 as win323}from"node:path";function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path2){let existing=await readSecretEntry(path2);if(existing?.length===SOCKET_SECRET_BYTES)return existing;await mkdir2(dirname7(path2),{recursive:!0,mode:448});let release=await acquireOwnershipSafeLock(await socketSecretLockPath(path2));try{let current=await readSecretEntry(path2);if(current?.length===SOCKET_SECRET_BYTES)return current;if(process.platform==="win32")return await writeSocketSecretInPlace(path2);let candidate=randomBytes2(SOCKET_SECRET_BYTES);if(current===void 0){if(await publishSocketSecretIfAbsent(path2,candidate)==="published")return candidate;let winner=await readSecretEntry(path2);if(winner?.length===SOCKET_SECRET_BYTES)return winner;throw new Error(`RPC socket secret is invalid and was not replaced: ${path2}`)}return await replaceSocketSecret(path2,candidate),candidate}finally{await release()}}async function readSecretEntry(path2){let handle;try{handle=await open(path2,constants2.O_RDONLY|(constants2.O_NOFOLLOW??0))}catch(error62){if(isNodeErrorCode3(error62,"ENOENT"))return;throw isNodeErrorCode3(error62,"ELOOP")?new Error(`RPC socket secret is not a regular file: ${path2}`):error62}try{if(!(await handle.stat()).isFile())throw new Error(`RPC socket secret is not a regular file: ${path2}`);let buffer=Buffer.alloc(SOCKET_SECRET_BYTES+1),length=0;for(;length<buffer.length;){let{bytesRead}=await handle.read(buffer,length,buffer.length-length,null);if(bytesRead===0)break;length+=bytesRead}return buffer.subarray(0,length)}finally{await handle.close()}}async function createSocketSecret(path2){if(process.platform==="win32")return writeSocketSecretInPlace(path2);await mkdir2(dirname7(path2),{recursive:!0,mode:448});let candidate=randomBytes2(SOCKET_SECRET_BYTES);if(await readSecretEntry(path2)===void 0&&await publishSocketSecretIfAbsent(path2,candidate)==="published")return candidate;let winner=await readSecretEntry(path2);if(winner?.length!==SOCKET_SECRET_BYTES)throw new Error(`RPC socket secret is invalid and was not replaced: ${path2}`);return winner}async function publishSocketSecretIfAbsent(path2,candidate){let staging=stagingPath(path2);await writeStaging(staging,candidate);try{return await link(staging,path2),await syncDirectory(dirname7(path2)),"published"}catch(error62){if(isNodeErrorCode3(error62,"EEXIST"))return"collision";throw error62}finally{await unlink(staging).catch(error62=>{if(!isNodeErrorCode3(error62,"ENOENT"))throw error62})}}async function writeStaging(staging,candidate){let handle=await open(staging,constants2.O_WRONLY|constants2.O_CREAT|constants2.O_EXCL|(constants2.O_NOFOLLOW??0),384),failure2;try{await handle.chmod(384);let offset=0;for(;offset<candidate.length;){let{bytesWritten}=await handle.write(candidate,offset,candidate.length-offset,null);if(bytesWritten===0)throw new Error(`short write to the RPC socket secret staging file: ${staging}`);offset+=bytesWritten}await handle.sync()}catch(error62){failure2=error62}if(await handle.close().catch(error62=>{failure2??=error62}),failure2!==void 0)throw await unlink(staging).catch(()=>{}),failure2}async function syncDirectory(dir){let handle=await open(dir,constants2.O_RDONLY);try{await handle.sync()}finally{await handle.close()}}async function socketSecretLockPath(path2){let lockPath=join12(await realpath(dirname7(path2)),`${basename6(path2)}.publish.lock`),handle=await open(lockPath,constants2.O_RDONLY|constants2.O_CREAT|(constants2.O_NOFOLLOW??0),384);try{if(!(await handle.stat()).isFile())throw new Error(`RPC socket secret lock is not a regular file: ${lockPath}`)}finally{await handle.close()}return lockPath}async function replaceSocketSecret(path2,candidate){let staging=stagingPath(path2);await writeStaging(staging,candidate);try{await rename2(staging,path2)}catch(error62){throw await unlink(staging).catch(()=>{}),error62}await syncDirectory(dirname7(path2))}function stagingPath(path2){return join12(dirname7(path2),`.${basename6(path2)}.stage-${process.pid}-${randomBytes2(8).toString("hex")}`)}async function writeSocketSecretInPlace(path2){await mkdir2(dirname7(path2),{recursive:!0});let secret=randomBytes2(SOCKET_SECRET_BYTES);return await writeFile3(path2,secret,{mode:384}),await chmod2(path2,384),secret}async function readSocketSecret(path2){let secret=await readFile4(path2);if(secret.length!==SOCKET_SECRET_BYTES)throw new Error(`invalid RPC socket secret: ${path2}`);return secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win323.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash2("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual2(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode3(error62,code){return error62 instanceof Error&&"code"in error62&&error62.code===code}var WINDOWS_PIPE_PREFIX,SOCKET_SECRET_BYTES,SOCKET_SECRET_SUFFIX,SOCKET_SECRET_FILE_ENV,SOCKET_HANDSHAKE_TIMEOUT_MS,init_socket_transport=__esm({"packages/coding-agent/dist/modes/rpc/socket-transport.js"(){init_ownership_safe_lock();WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3}});import{randomBytes as randomBytes3,randomUUID as randomUUID3}from"node:crypto";import{constants as constants3,unlinkSync as unlinkSync2}from"node:fs";import*as fs from"node:fs/promises";import{join as join13}from"node:path";async function checkRpcKeyDirectory(path2,privateKeys=!1){let checked=privateKeys?path2:await fs.realpath(path2),problem=keyDirectoryProblem(await fs.lstat(checked),checked,privateKeys);if(problem!==void 0)throw new RpcEndpointAuthError("unsafe_key_record",`${checked} ${problem}`)}function keyDirectoryProblem(info,path2,privateKeys){if(!info.isDirectory())return"is not a directory";if(info.uid!==process.getuid?.())return"is not owned by this user";let mode=info.mode&4095;return privateKeys?mode===448?void 0:`must be mode 0700 (is 0${mode.toString(8)}); run: chmod 700 ${path2}`:(mode&18)===0?void 0:`is writable by group or others; run: chmod go-w ${path2}`}async function checkRpcKeyParents(root){await checkRpcKeyDirectory(root),await checkRpcKeyDirectory(join13(root,"rpc"))}async function readRpcKeyRecord(root,launchId){if(!RPC_LAUNCH_ID.test(launchId))throw new RpcEndpointAuthError("unsafe_key_record",`invalid launch id under ${root}`);let path2=join13(root,"rpc","keys",launchId);try{await checkRpcKeyParents(root),await checkRpcKeyDirectory(join13(root,"rpc","keys"),!0);let handle=await fs.open(path2,constants3.O_RDONLY|constants3.O_NOFOLLOW|constants3.O_NONBLOCK);try{let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384||info.size>MAX_KEY_RECORD_BYTES)throw new RpcEndpointAuthError("unsafe_key_record",path2);let record3=authRecord(JSON.parse(await handle.readFile("utf8")));if(record3?.version!==1||record3.launch_id!==launchId||typeof record3.key!="string"||!RPC_AUTH_HEX.test(record3.key))throw new RpcEndpointAuthError("unsafe_key_record",path2);return record3}finally{await handle.close()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause instanceof RpcEndpointAuthError?cause:new RpcEndpointAuthError("unsafe_key_record",path2,{cause})}}var MAX_KEY_RECORD_BYTES,RpcPublicEndpoint,init_rpc_public_key=__esm({"packages/coding-agent/dist/modes/rpc/rpc-public-key.js"(){init_process_identity();init_rpc_auth_proof();MAX_KEY_RECORD_BYTES=4096;RpcPublicEndpoint=class{constructor(agentDir,endpoint){this.key=randomBytes3(32),this.launchId=randomUUID3(),this.publication=Promise.withResolvers(),this.created=!1,this.exitCleanup=()=>{if(this.created)try{unlinkSync2(this.recordPath)}catch(cause){cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"||process.stderr.write(`senpi rpc host: could not remove own endpoint key record
@@ -83,12 +83,12 @@ ${code}
83
83
 
84
84
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}seen.count>1&&ctx.reused==="ref"&&extractToDef(entry)}ctx.external&&(ctx.sharedDefsExtractedFor=ctx.external)}function compactTypeUnion(schema){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let member of Array.isArray(type)?type:[type]){if(typeof member!="string")return;types.includes(member)||types.push(member)}}delete schema.anyOf,schema.type=types.length===1?types[0]:types}function undeclaredConstraint(member){let extra=member.additionalProperties;return extra===void 0||extra===!1||typeof extra!="object"||extra===null?null:Object.keys(extra).length?extra:null}function foldObjects(members2){let objects=[];for(let member of members2){if(typeof member!="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required2=new Set;for(let object3 of objects){for(let key in object3.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part=other.properties?.[key]??undeclaredConstraint(other);part!=null&&(parts.some(seen=>JSON.stringify(seen)===JSON.stringify(part))||parts.push(part))}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object3.required??[])required2.add(key)}let folded={type:"object",properties};if(required2.size&&(folded.required=[...required2]),objects.every(object3=>object3.additionalProperties===!1))folded.additionalProperties=!1;else{let constraints=[];for(let object3 of objects){let constraint=undeclaredConstraint(object3);constraint&&!constraints.some(seen=>JSON.stringify(seen)===JSON.stringify(constraint))&&constraints.push(constraint)}constraints.length===1?folded.additionalProperties=constraints[0]:constraints.length>1&&(folded.additionalProperties={allOf:constraints})}return folded}function foldIntersection(json2){let allOf=json2.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json2)return;let unions=allOf.filter(m=>UNION_KEYS.some(k=>Array.isArray(m[k]))),folded=null;if(!unions.length)folded=foldObjects(allOf);else{let union2=unions[0],keyword=UNION_KEYS.find(k=>Array.isArray(union2[k]));if(Object.keys(union2).length!==1)return;let rest=allOf.filter(m=>m!==union2),branches=union2[keyword].map(branch=>foldObjects([...rest,branch]));if(branches.some(b=>!b))return;folded={[keyword]:branches}}folded&&(delete json2.allOf,assignProps(json2,folded))}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema)):assignProps(schema2,refSchema),assignProps(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2)key==="$ref"||key==="allOf"||key in _cached||delete schema2[key];if(refSchema.$ref&&refSeen.def)for(let key in schema2)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])&&delete schema2[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema2.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema2)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])&&delete schema2[key]}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json2 of[seen.schema,seen.def]){let allOf=json2?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);existing?existing.push(json2):carriers.set(allOf,[json2])}for(let allOf of ctx.intersections)for(let json2 of carriers.get(allOf)??[])foldIntersection(json2)}}let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,assignProp(defs,seen.defId,seen.def))}ctx.external&&(ctx.sharedEmitDoneFor=ctx.external),ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var FOLDABLE_KEYS,UNION_KEYS,createToJSONSchemaMethod,createStandardJSONSchemaMethod,init_to_json_schema=__esm({"packages/coding-agent/node_modules/zod/v4/core/to-json-schema.js"(){init_registries();init_util();FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)}}});function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);let bag=schema._zod.bag;bag.minimum!==void 0&&narrowMin(agg,"minimum",bag.minimum),bag.exclusiveMinimum!==void 0&&narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum),bag.maximum!==void 0&&narrowMax(agg,"maximum",bag.maximum),bag.exclusiveMaximum!==void 0&&narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum),bag.multipleOf!==void 0&&addDivisor(agg,bag.multipleOf),bag.format!==void 0&&(agg.format??(agg.format=bag.format),bag.format.includes("int")&&(agg.isInt=!0)),bag.mime&&intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}function inputOptin(schema){let def=schema._zod.def;return def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")?inputOptin(def.out):def.type==="catch"?inputOptin(def.innerType):schema._zod.optin}function stringifyKeyNames(bySchema,json2,visited){if(json2.$ref){if(visited.has(json2))return json2;visited.add(json2);let def=bySchema.get(json2)?.def;if(!def)return json2;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json2:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json2[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map(branch=>stringifyKeyNames(bySchema,branch,visited));mapped.some((branch,i)=>branch!==branches[i])&&(json2={...json2,[keyword]:mapped})}let types=Array.isArray(json2.type)?json2.type:[json2.type],numericType=!types.includes("string")&&types.some(t=>t==="number"||t==="integer"),values=json2.enum??(json2.const!==void 0?[json2.const]:void 0);if(!numericType&&!values?.some(v=>typeof v=="number"))return json2;let{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json2;return rest.enum?rest.enum=rest.enum.map(v=>typeof v=="number"?String(v):v):typeof rest.const=="number"&&(rest.const=String(rest.const)),numericType&&(rest.type="string",values||(rest.pattern=(types.includes("number")?number:integer).source)),rest}function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())entry.def&&!bySchema.has(entry.schema)&&bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record3 of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record3),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);rewritten!==names&&rewrites.set(names,rewritten)}if(rewrites.size)for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);rewritten&&(carrier.propertyNames=rewritten)}}function serializeDefaultValue(value,schema,ctx,json2,params){let unrepresentable=!1,serialized=JSON.stringify(value,(_,val)=>typeof val!="bigint"?val:(unrepresentable=!0,null));return unrepresentable?(handleUnrepresentable(schema,ctx,json2,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT):JSON.parse(serialized)}function toJSONSchema(input2,params){if("_idmap"in input2){let registry2=input2,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;processSchema(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),assignProp(schemas,key,finalize(ctx2,schema))}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return processSchema(input2,ctx),extractDefs(ctx,input2),finalize(ctx,input2)}var narrowMin,narrowMax,narrowBoth,addDivisor,addPattern,intersectMime,setFormat,minContributor,maxContributor,formatContributor,contributors,formatMap,exactPatterns,exactPattern,stringProcessor,numberProcessor,booleanProcessor,bigintProcessor,symbolProcessor,nullProcessor,undefinedProcessor,voidProcessor,neverProcessor,anyProcessor,unknownProcessor,dateProcessor,enumProcessor,literalProcessor,nanProcessor,templateLiteralProcessor,fileProcessor,successProcessor,customProcessor,functionProcessor,transformProcessor,mapProcessor,setProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,tupleProcessor,pendingRecords,recordProcessor,nullableProcessor,nonoptionalProcessor,UNREPRESENTABLE_DEFAULT,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,promiseProcessor,optionalProcessor,lazyProcessor,allProcessors,init_json_schema_processors=__esm({"packages/coding-agent/node_modules/zod/v4/core/json-schema-processors.js"(){init_regexes();init_schemas();init_to_json_schema();init_util();narrowMin=(agg,key,value)=>{(agg[key]===void 0||value>agg[key])&&(agg[key]=value)},narrowMax=(agg,key,value)=>{(agg[key]===void 0||value<agg[key])&&(agg[key]=value)},narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value),narrowMax(agg,"maximum",value)},addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]),agg.multipleOf.includes(value)||agg.multipleOf.push(value)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter(m=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{agg.format=format,format.includes("int")&&(agg.isInt=!0)},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=ranges=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format),def.pattern&&addPattern(agg,def.pattern),(def.format==="base64"||def.format==="base64url")&&(agg.contentEncoding=def.format),(def.local||def.precision===-1)&&(agg.laxFormat=!0)},mime_type:(agg,def)=>intersectMime(agg,def.mime)};formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=p=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json2=_json;json2.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum=="number"&&(json2.minLength=minimum),typeof maximum=="number"&&(json2.maxLength=maximum),format&&(json2.format=formatMap[format]??format,json2.format===""&&delete json2.format,(format==="time"||laxFormat)&&delete json2.format),contentEncoding&&(json2.contentEncoding=contentEncoding),patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);patternList.length===1?json2.pattern=patternList[0].source:patternList.length>1&&(json2.allOf=[...patternList.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema,ctx,_json,params)=>{let json2=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json2.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin?legacy?(json2.minimum=exclusiveMinimum,json2.exclusiveMinimum=!0):json2.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json2.minimum=minimum),exMax?legacy?(json2.maximum=exclusiveMaximum,json2.exclusiveMaximum=!0):json2.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json2.maximum=maximum),multipleOf){let divisors=new Set;for(let divisor of multipleOf)Number.isFinite(divisor)&&divisor!==0?divisors.add(Math.abs(divisor)):handleUnrepresentable(schema,ctx,json2,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;first!==void 0&&(json2.multipleOf=first),rest.length&&(json2.allOf=[...json2.allOf??[],...rest.map(m=>({multipleOf:m}))])}},booleanProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},bigintProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"BigInt cannot be represented in JSON Schema")},symbolProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json2,_params)=>{ctx.target==="openapi-3.0"?(json2.type="string",json2.nullable=!0,json2.enum=[null]):json2.type="null"},undefinedProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Undefined cannot be represented in JSON Schema")},voidProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json2,_params)=>{json2.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json2,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.length===0){json2.not={};return}values.every(v=>typeof v=="number")&&(json2.type="number"),values.every(v=>typeof v=="string")&&(json2.type="string"),json2.enum=values},literalProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;if(def.values.length===0){json2.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema,ctx,json2,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val=="bigint"){if(handleUnrepresentable(schema,ctx,json2,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json2.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json2.enum=[val]:json2.const=val}else vals.every(v=>typeof v=="number")&&(json2.type="number"),vals.every(v=>typeof v=="string")&&(json2.type="string"),vals.every(v=>typeof v=="boolean")&&(json2.type="boolean"),vals.every(v=>v===null)&&(json2.type="null"),json2.enum=vals},nanProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json2,_params)=>{let _json=json2,pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json2,_params)=>{let _json=json2;_json.type="string",_json.format="binary",_json.contentEncoding="binary";let{minimum,maximum,mime}=aggregateChecks(schema);minimum!==void 0&&(_json.minLength=minimum),maximum!==void 0&&(_json.maxLength=maximum),mime&&(mime.length===0?_json.not={}:mime.length===1?_json.contentMediaType=mime[0]:_json.anyOf=mime.map(m=>({contentMediaType:m})))},successProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},customProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Custom types cannot be represented in JSON Schema")},functionProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Function types cannot be represented in JSON Schema")},transformProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Transforms cannot be represented in JSON Schema")},mapProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Map cannot be represented in JSON Schema")},setProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum),json2.type="array",json2.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};objectProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,ctx,json2,params,"Symbol keys cannot be represented in JSON Schema"))return;json2.type="object",json2.properties={};for(let key in shape)assignProp(json2.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)&&requiredKeys.push(key)}requiredKeys.length>0&&(json2.required=requiredKeys),def.catchall?._zod.def.type==="never"?json2.additionalProperties=!1:def.catchall?def.catchall&&(json2.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json2.additionalProperties=!1)},unionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));isExclusive?json2.oneOf=options:json2.anyOf=options},intersectionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json2.allOf=allOf,ctx.intersections.push(allOf)},tupleProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null,minItems=def.items.length;for(;minItems>0;){let item=def.items[minItems-1];if(!(ctx.io==="input"?inputOptin(item)!==void 0:item._zod.optout==="optional"))break;minItems--}let maxItems=def.items.length,isClosed=!def.rest;ctx.target==="draft-2020-12"?(json2.prefixItems=prefixItems,isClosed?json2.items=!1:rest&&(json2.items=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):ctx.target==="openapi-3.0"?(json2.items={anyOf:prefixItems},rest&&json2.items.anyOf.push(rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):(json2.items=prefixItems,isClosed?json2.additionalItems=!1:rest&&(json2.additionalItems=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems));let{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum)};pendingRecords=new WeakMap;recordProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json2.patternProperties={};for(let pattern of patterns)assignProp(json2.patternProperties,exactPattern(pattern).source,valueSchema)}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json2.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);pending||(pending=[],pendingRecords.set(ctx,pending),ctx.deferred.push(()=>rewriteKeyNames(ctx))),pending.push(schema)}json2.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json2.required=validKeyValues.map(String))}},nullableProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json2.nullable=!0):json2.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();defaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value!==UNREPRESENTABLE_DEFAULT&&(json2.default=value)},prefaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value!==UNREPRESENTABLE_DEFAULT&&(json2._prefault=value)},catchProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json2,params,"Dynamic catch values are not supported in JSON Schema");return}json2.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json2.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}}});var JSONSchemaGenerator,init_json_schema_generator=__esm({"packages/coding-agent/node_modules/zod/v4/core/json-schema-generator.js"(){init_json_schema_processors();init_to_json_schema();JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";normalizedTarget==="draft-4"&&(normalizedTarget="draft-04"),normalizedTarget==="draft-7"&&(normalizedTarget="draft-07"),this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){_params&&(_params.cycles&&(this.ctx.cycles=_params.cycles),_params.reused&&(this.ctx.reused=_params.reused),_params.external&&(this.ctx.external=_params.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}}}});var json_schema_exports={};var init_json_schema=__esm({"packages/coding-agent/node_modules/zod/v4/core/json-schema.js"(){}});var core_exports2={};__export(core_exports2,{$ZodAny:()=>$ZodAny,$ZodArray:()=>$ZodArray,$ZodAsyncError:()=>$ZodAsyncError,$ZodBase64:()=>$ZodBase64,$ZodBase64URL:()=>$ZodBase64URL,$ZodBigInt:()=>$ZodBigInt,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBoolean:()=>$ZodBoolean,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCUID:()=>$ZodCUID,$ZodCUID2:()=>$ZodCUID2,$ZodCatch:()=>$ZodCatch,$ZodCheck:()=>$ZodCheck,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckProperties:()=>$ZodCheckProperties,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCodec:()=>$ZodCodec,$ZodCreditCard:()=>$ZodCreditCard,$ZodCustom:()=>$ZodCustom,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCyclicError:()=>$ZodCyclicError,$ZodDate:()=>$ZodDate,$ZodDefault:()=>$ZodDefault,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodE164:()=>$ZodE164,$ZodEmail:()=>$ZodEmail,$ZodEmoji:()=>$ZodEmoji,$ZodEncodeError:()=>$ZodEncodeError,$ZodEnum:()=>$ZodEnum,$ZodError:()=>$ZodError,$ZodExactOptional:()=>$ZodExactOptional,$ZodFile:()=>$ZodFile,$ZodFunction:()=>$ZodFunction,$ZodGUID:()=>$ZodGUID,$ZodIBAN:()=>$ZodIBAN,$ZodIPv4:()=>$ZodIPv4,$ZodIPv6:()=>$ZodIPv6,$ZodISODate:()=>$ZodISODate,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODuration:()=>$ZodISODuration,$ZodISOTime:()=>$ZodISOTime,$ZodIntersection:()=>$ZodIntersection,$ZodJWT:()=>$ZodJWT,$ZodKSUID:()=>$ZodKSUID,$ZodLazy:()=>$ZodLazy,$ZodLiteral:()=>$ZodLiteral,$ZodMAC:()=>$ZodMAC,$ZodMap:()=>$ZodMap,$ZodNaN:()=>$ZodNaN,$ZodNanoID:()=>$ZodNanoID,$ZodNever:()=>$ZodNever,$ZodNonOptional:()=>$ZodNonOptional,$ZodNull:()=>$ZodNull,$ZodNullable:()=>$ZodNullable,$ZodNumber:()=>$ZodNumber,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodObject:()=>$ZodObject,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodOptional:()=>$ZodOptional,$ZodPipe:()=>$ZodPipe,$ZodPrefault:()=>$ZodPrefault,$ZodPreprocess:()=>$ZodPreprocess,$ZodPromise:()=>$ZodPromise,$ZodReadonly:()=>$ZodReadonly,$ZodRealError:()=>$ZodRealError,$ZodRecord:()=>$ZodRecord,$ZodRegistry:()=>$ZodRegistry,$ZodSet:()=>$ZodSet,$ZodString:()=>$ZodString,$ZodStringFormat:()=>$ZodStringFormat,$ZodSuccess:()=>$ZodSuccess,$ZodSymbol:()=>$ZodSymbol,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodTransform:()=>$ZodTransform,$ZodTuple:()=>$ZodTuple,$ZodType:()=>$ZodType,$ZodULID:()=>$ZodULID,$ZodURL:()=>$ZodURL,$ZodUUID:()=>$ZodUUID,$ZodUndefined:()=>$ZodUndefined,$ZodUnion:()=>$ZodUnion,$ZodUnknown:()=>$ZodUnknown,$ZodVoid:()=>$ZodVoid,$ZodXID:()=>$ZodXID,$ZodXor:()=>$ZodXor,$brand:()=>$brand,$constructor:()=>$constructor,$input:()=>$input,$output:()=>$output,Doc:()=>Doc,INVALID:()=>INVALID,JSONSchema:()=>json_schema_exports,JSONSchemaGenerator:()=>JSONSchemaGenerator,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,URL_BAD_FORMAT:()=>URL_BAD_FORMAT,URL_UNPARSEABLE:()=>URL_UNPARSEABLE,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,_any:()=>_any,_array:()=>_array,_base64:()=>_base64,_base64url:()=>_base64url,_bigint:()=>_bigint,_boolean:()=>_boolean,_catch:()=>_catch,_check:()=>_check,_cidrv4:()=>_cidrv4,_cidrv6:()=>_cidrv6,_coercedBigint:()=>_coercedBigint,_coercedBoolean:()=>_coercedBoolean,_coercedDate:()=>_coercedDate,_coercedNumber:()=>_coercedNumber,_coercedString:()=>_coercedString,_creditCard:()=>_creditCard,_cuid:()=>_cuid,_cuid2:()=>_cuid2,_custom:()=>_custom,_date:()=>_date,_decode:()=>_decode,_decodeAsync:()=>_decodeAsync,_default:()=>_default,_discriminatedUnion:()=>_discriminatedUnion,_e164:()=>_e164,_email:()=>_email,_emoji:()=>_emoji2,_encode:()=>_encode,_encodeAsync:()=>_encodeAsync,_endsWith:()=>_endsWith,_enum:()=>_enum,_file:()=>_file,_float32:()=>_float32,_float64:()=>_float64,_gt:()=>_gt,_gte:()=>_gte,_guid:()=>_guid,_iban:()=>_iban,_includes:()=>_includes,_int:()=>_int,_int32:()=>_int32,_int64:()=>_int64,_intersection:()=>_intersection,_ipv4:()=>_ipv4,_ipv6:()=>_ipv6,_isoDate:()=>_isoDate,_isoDateTime:()=>_isoDateTime,_isoDuration:()=>_isoDuration,_isoTime:()=>_isoTime,_jwt:()=>_jwt,_ksuid:()=>_ksuid,_lazy:()=>_lazy,_length:()=>_length,_literal:()=>_literal,_lowercase:()=>_lowercase,_lt:()=>_lt,_lte:()=>_lte,_mac:()=>_mac,_map:()=>_map,_max:()=>_lte,_maxLength:()=>_maxLength,_maxSize:()=>_maxSize,_mime:()=>_mime,_min:()=>_gte,_minLength:()=>_minLength,_minSize:()=>_minSize,_multipleOf:()=>_multipleOf,_nan:()=>_nan,_nanoid:()=>_nanoid,_nativeEnum:()=>_nativeEnum,_negative:()=>_negative,_never:()=>_never,_nonnegative:()=>_nonnegative,_nonoptional:()=>_nonoptional,_nonpositive:()=>_nonpositive,_normalize:()=>_normalize,_null:()=>_null2,_nullable:()=>_nullable,_number:()=>_number,_optional:()=>_optional,_overwrite:()=>_overwrite,_parse:()=>_parse,_parseAsync:()=>_parseAsync,_pipe:()=>_pipe,_positive:()=>_positive,_promise:()=>_promise,_properties:()=>_properties,_property:()=>_property,_readonly:()=>_readonly,_record:()=>_record,_refine:()=>_refine,_regex:()=>_regex,_safeDecode:()=>_safeDecode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeEncode:()=>_safeEncode,_safeEncodeAsync:()=>_safeEncodeAsync,_safeParse:()=>_safeParse,_safeParseAsync:()=>_safeParseAsync,_set:()=>_set,_size:()=>_size,_slugify:()=>_slugify,_startsWith:()=>_startsWith,_string:()=>_string,_stringFormat:()=>_stringFormat,_stringbool:()=>_stringbool,_success:()=>_success,_superRefine:()=>_superRefine,_symbol:()=>_symbol,_templateLiteral:()=>_templateLiteral,_toLowerCase:()=>_toLowerCase,_toUpperCase:()=>_toUpperCase,_transform:()=>_transform,_trim:()=>_trim,_tuple:()=>_tuple,_uint32:()=>_uint32,_uint64:()=>_uint64,_ulid:()=>_ulid,_undefined:()=>_undefined2,_union:()=>_union,_unknown:()=>_unknown,_uppercase:()=>_uppercase,_url:()=>_url,_uuid:()=>_uuid,_uuidv4:()=>_uuidv4,_uuidv6:()=>_uuidv6,_uuidv7:()=>_uuidv7,_void:()=>_void,_xid:()=>_xid,_xor:()=>_xor,base64Charset:()=>base64Charset,base64urlCharset:()=>base64urlCharset,canParseURL:()=>canParseURL,clone:()=>clone,compile:()=>compile,compileFn:()=>compileFn,config:()=>config,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe,encode:()=>encode,encodeAsync:()=>encodeAsync,extractDefs:()=>extractDefs,finalize:()=>finalize,flattenError:()=>flattenError,formatError:()=>formatError,getDiscriminatedOption:()=>getDiscriminatedOption,globalConfig:()=>globalConfig,globalRegistry:()=>globalRegistry,handleUnrepresentable:()=>handleUnrepresentable,initializeContext:()=>initializeContext,isBackEdge:()=>isBackEdge,isRecursiveSchema:()=>isRecursiveSchema,isValidBase64:()=>isValidBase64,isValidBase64URL:()=>isValidBase64URL,isValidCIDRv6:()=>isValidCIDRv6,isValidCreditCard:()=>isValidCreditCard,isValidIBAN:()=>isValidIBAN,isValidIPv6:()=>isValidIPv6,isValidJWT:()=>isValidJWT,locales:()=>locales_exports,memoizer:()=>memoizer,mergeValues:()=>mergeValues,meta:()=>meta,parse:()=>parse2,parseAsync:()=>parseAsync,parseURLObject:()=>parseURLObject,prettifyError:()=>prettifyError,process:()=>processSchema,processSchema:()=>processSchema,regexes:()=>regexes_exports,registry:()=>registry,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,standardProps:()=>standardProps,stripTabAndNewline:()=>stripTabAndNewline,toDotPath:()=>toDotPath,toJSONSchema:()=>toJSONSchema,toZod:()=>toZod,treeifyError:()=>treeifyError,urlHostnameOk:()=>urlHostnameOk,urlProtocolOk:()=>urlProtocolOk,util:()=>util_exports,validate:()=>validate,validateAsync:()=>validateAsync,validateURL:()=>validateURL,version:()=>version,withParser:()=>withParser});var init_core2=__esm({"packages/coding-agent/node_modules/zod/v4/core/index.js"(){init_core();init_parse();init_errors();init_schemas();init_memoizer();init_checks();init_versions();init_util();init_util();init_regexes();init_locales();init_registries();init_doc();init_compile();init_api();init_to_json_schema();init_json_schema_processors();init_json_schema_generator();init_json_schema()}});var checks_exports2={};__export(checks_exports2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,properties:()=>_properties,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var init_checks2=__esm({"packages/coding-agent/node_modules/zod/v4/classic/checks.js"(){init_core2()}});function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value=make(this);return Object.defineProperty(this,key,{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,key,{value,configurable:!0,writable:!0})}})}var _installedErrorProtos,initializer2,ZodError,ZodRealError,init_errors2=__esm({"packages/coding-agent/node_modules/zod/v4/classic/errors.js"(){init_core2();init_core2();init_util();_installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);_installedErrorProtos.has(proto)||(_installedErrorProtos.add(proto),_lazyMethod(proto,"format",self=>mapper=>formatError(self,mapper)),_lazyMethod(proto,"flatten",self=>mapper=>flattenError(self,mapper)),_lazyMethod(proto,"addIssue",self=>issue2=>{self.issues.push(issue2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),_lazyMethod(proto,"addIssues",self=>issues2=>{self.issues.push(...issues2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),Object.defineProperty(proto,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error})}});var parse3,parseAsync2,safeParse2,safeParseAsync2,encode2,decode2,encodeAsync2,decodeAsync2,safeEncode2,safeDecode2,safeEncodeAsync2,safeDecodeAsync2,init_parse2=__esm({"packages/coding-agent/node_modules/zod/v4/classic/parse.js"(){init_core2();init_errors2();init_core2();parse3=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError)}});var schemas_exports2={};__export(schemas_exports2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object2,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record2,refine:()=>refine,set:()=>set,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function guid2(params){return _guid(ZodGUID,params)}function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...util_exports.normalizeParams(params)})}function emoji2(params){return _emoji2(ZodEmoji,params)}function nanoid2(params){return _nanoid(ZodNanoID,params)}function cuid3(params){return _cuid(ZodCUID,params)}function cuid22(params){return _cuid2(ZodCUID2,params)}function ulid2(params){return _ulid(ZodULID,params)}function xid2(params){return _xid(ZodXID,params)}function ksuid2(params){return _ksuid(ZodKSUID,params)}function ipv42(params){return _ipv4(ZodIPv4,params)}function mac2(params){return _mac(ZodMAC,params)}function ipv62(params){return _ipv6(ZodIPv6,params)}function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}function base642(params){return _base64(ZodBase64,params)}function base64url2(params){return _base64url(ZodBase64URL,params)}function e1642(params){return _e164(ZodE164,params)}function creditCard2(params){return _creditCard(ZodCreditCard,params)}function iban2(params){return _iban(ZodIBAN,params)}function jwt(params){return _jwt(ZodJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=regexes_exports[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function bigint2(params){return _bigint(ZodBigInt,params)}function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}function symbol(params){return _symbol(ZodSymbol,params)}function _undefined3(params){return _undefined2(ZodUndefined,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function _void2(params){return _void(ZodVoid,params)}function date2(params){return _date(ZodDate,params)}function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}function object2(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...util_exports.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...util_exports.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...util_exports.normalizeParams(params)})}function record2(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params),partial:!0})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...util_exports.normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...util_exports.normalizeParams(params)})}function set(valueType,params){return new ZodSet({type:"set",valueType,...util_exports.normalizeParams(params)})}function _enum2(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}function file(params){return _file(ZodFile,params)}function transform(fn){return new ZodTransform({type:"transform",transform:fn})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}function success(innerType){return new ZodSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:util_exports.constantCatch(catchValue)})}function nan(params){return _nan(ZodNaN,params)}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){let def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...util_exports.normalizeParams(params)})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function promise(innerType){return new ZodPromise({type:"promise",innerType})}function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}function check(fn){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn,ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function _instanceof(cls,params={}){let inst=new ZodInstanceOf({type:"custom",check:"custom",fn:data=>data instanceof cls,abort:!0,...util_exports.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=payload=>{payload.value instanceof cls||payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}function json(params){let jsonSchema=lazy(()=>union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record2(string2(),jsonSchema)]));return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodType,_ZodString,ZodString,ZodStringFormat,ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodMAC,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodCreditCard,ZodIBAN,ZodJWT,ZodCustomStringFormat,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodBigIntFormat,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodDate,ZodArray,ZodObject,ZodUnion,ZodXor,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodEnum,ZodLiteral,ZodFile,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodSuccess,ZodCatch,ZodNaN,ZodPipe,ZodCodec,ZodPreprocess,ZodReadonly,ZodTemplateLiteral,ZodLazy,ZodPromise,ZodFunction,ZodCustom,describe2,meta2,ZodInstanceOf,stringbool,init_schemas2=__esm({"packages/coding-agent/node_modules/zod/v4/classic/schemas.js"(){init_core2();init_core2();init_json_schema_processors();init_regexes();init_to_json_schema();init_en();init_checks2();init_parse2();ZodType=$constructor("ZodType",(inst,def)=>(_ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst),{check(...chks){let def=this.def;return this.clone(util_exports.mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta3){return reg.add(this,meta3),this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get"~standard"(){return util_exports.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set"~standard"(value){util_exports.own(this,"~standard",value)},parse:function _parse2(data,params){return parse3(this,data,params,{callee:_parse2})},parseAsync:async function _parseAsync2(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync2})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){util_exports.own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode2(data,params){return encode2(this,data,params,{callee:_encode2})},decode:function _decode2(data,params){return decode2(this,data,params,{callee:_decode2})},encodeAsync:async function _encodeAsync2(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync2})},decodeAsync:async function _decodeAsync2(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync2})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},util_exports.derived({format:inst=>aggregateChecks(inst).format??null,minLength:inst=>aggregateChecks(inst).minimum??null,maxLength:inst=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def),ZodStringFormat.init(inst,def)});ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def),ZodStringFormat.init(inst,def)});ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params),inst.isFinite=!0},util_exports.derived({minValue:inst=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:inst=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:inst=>{let{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:inst=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},util_exports.derived({minValue:inst=>aggregateChecks(inst).minimum??null,maxValue:inst=>aggregateChecks(inst).maximum??null,format:inst=>aggregateChecks(inst).format??null},{gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},gt(value,params){return this.check(_gt(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value,params){return this.check(_multipleOf(value,params))}}));ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params))},util_exports.derived({minDate:inst=>{let{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:inst=>{let{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params),inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params),util_exports.installLazyProp(inst,"shape",self=>self._zod.def.shape,!1)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},exactPartial(...args){return util_exports.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){let def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map(item=>new ZodOptional({type:"optional",innerType:item}))})}});ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer(),$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer(),$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params),inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output2=def.transform(payload.value,payload);return output2 instanceof Promise?output2.then(output3=>(payload.value=output3,payload)):(payload.value=output2,payload)}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params),inst.in=def.in,inst.out=def.out});ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});describe2=describe,meta2=meta,ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args)}});function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodIssueCode,ZodFirstPartyTypeKind,init_compat=__esm({"packages/coding-agent/node_modules/zod/v4/classic/compat.js"(){init_core2();ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={})}});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var init_iso=__esm({"packages/coding-agent/node_modules/zod/v4/classic/iso.js"(){init_core2();init_schemas2();init_schemas2()}});function detectVersion(schema,defaultTarget){let $schema=schema.$schema;return $schema==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":$schema==="http://json-schema.org/draft-07/schema#"?"draft-7":$schema==="http://json-schema.org/draft-04/schema#"?"draft-4":defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let path2=ref.slice(1).split("/").filter(Boolean);if(path2.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path2[0]===defsKey){let key=path2[1]===void 0?void 0:decodeJSONPointerSegment(path2[1]);if(!key||!ctx.defs[key])throw new Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){return z.transform(value=>value).check(payload=>{let value=payload.value;if(typeof value!="object"||value===null||Array.isArray(value))return;let keys=Object.getOwnPropertyNames(value);if(guards.minProperties!==void 0&&keys.length<guards.minProperties&&payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:!0,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value,inst:objectSchema,continue:!0}),guards.maxProperties!==void 0&&keys.length>guards.maxProperties&&payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value,inst:objectSchema,continue:!0}),guards.keySchema)for(let key of keys){let result=guards.keySchema.safeParse(key);result.success||payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:!0})}}).pipe(objectSchema)}function canonicalKey(value,seen){if(value===null)return"z";let type=typeof value;if(type!=="object"){if(type==="number"&&Number.isNaN(value))return null;let raw=String(value);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value))return null;seen.add(value);try{if(Array.isArray(value)){let parts2=[];for(let item of value){let key=canonicalKey(item,seen);if(key===null)return null;parts2.push(key)}return`a${parts2.length}:[${parts2.join(",")}]`}let keys=Object.keys(value).sort(),parts=[];for(let k of keys){let key=canonicalKey(value[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value)}}function containsRef(value){return typeof value!="object"||value===null?!1:Array.isArray(value)?value.some(containsRef):typeof value.$ref=="string"?!0:Object.entries(value).some(([key,sub])=>SCHEMA_KEYWORDS.has(key)?containsRef(sub):!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!="object"||sub===null?!1:Object.values(sub).some(containsRef))}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){return z.transform(value=>value).check(payload=>{let items=payload.value;if(Array.isArray(items)){if(guards.uniqueItems===!0){let firstSeen=new Map;for(let i=0;i<items.length;i++){let key=canonicalKey(items[i],new Set);if(key===null)continue;let first=firstSeen.get(key);if(first===void 0){firstSeen.set(key,i);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${first}`,input:items,path:[i],continue:!0})}}if(guards.containsSchema){let minContains=guards.minContains??1,ceiling=guards.maxContains!==void 0?guards.maxContains+1:Number.POSITIVE_INFINITY,matches2=0;for(let item of items)if(guards.containsSchema.safeParse(item).success&&++matches2>=ceiling)break;matches2<minContains&&payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches2}`,input:items,continue:!0}),guards.maxContains!==void 0&&matches2>guards.maxContains&&payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:!0})}}}).pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema!==!1)return restSchema===void 0||restSchema===!0?z.any():convertSchema(restSchema,ctx)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not=="object"&&Object.keys(schema.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw new Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every(v=>typeof v=="string"))return z.enum(enumValues);let literalSchemas=enumValues.map(v=>z.literal(v));return literalSchemas.length<2?literalSchemas[0]:z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map(t=>{let typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});return typeSchemas.length===0?z.never():typeSchemas.length===1?typeSchemas[0]:z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;format==="email"?stringSchema=stringSchema.check(z.email()):format==="uri"||format==="uri-reference"?stringSchema=stringSchema.check(z.url()):format==="uuid"||format==="guid"?stringSchema=stringSchema.check(z.uuid()):format==="date-time"?stringSchema=stringSchema.check(z.iso.datetime({offset:!0})):format==="date"?stringSchema=stringSchema.check(z.iso.date()):format==="time"?stringSchema=stringSchema.check(z.regex(fullTime)):format==="duration"?stringSchema=stringSchema.check(z.iso.duration()):format==="hostname"?stringSchema=stringSchema.check(z.hostname()):format==="ipv4"?stringSchema=stringSchema.check(z.ipv4()):format==="ipv6"?stringSchema=stringSchema.check(z.ipv6()):format==="mac"?stringSchema=stringSchema.check(z.mac()):format==="cidr"?stringSchema=stringSchema.check(z.cidrv4()):format==="cidr-v6"?stringSchema=stringSchema.check(z.cidrv6()):format==="base64"?stringSchema=stringSchema.check(z.base64()):format==="base64url"?stringSchema=stringSchema.check(z.base64url()):format==="e164"?stringSchema=stringSchema.check(z.e164()):format==="credit_card"?stringSchema=stringSchema.check(z.creditCard()):format==="iban"?stringSchema=stringSchema.check(z.iban()):format==="jwt"?stringSchema=stringSchema.check(z.jwt()):format==="emoji"?stringSchema=stringSchema.check(z.emoji()):format==="nanoid"?stringSchema=stringSchema.check(z.nanoid()):format==="cuid"?stringSchema=stringSchema.check(z.cuid()):format==="cuid2"?stringSchema=stringSchema.check(z.cuid2()):format==="ulid"?stringSchema=stringSchema.check(z.ulid()):format==="xid"?stringSchema=stringSchema.check(z.xid()):format==="ksuid"&&(stringSchema=stringSchema.check(z.ksuid()))}typeof schema.minLength=="number"&&(stringSchema=stringSchema.min(schema.minLength)),typeof schema.maxLength=="number"&&(stringSchema=stringSchema.max(schema.maxLength)),schema.pattern&&(stringSchema=stringSchema.regex(new RegExp(schema.pattern))),zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();typeof schema.minimum=="number"&&schema.exclusiveMinimum!==!0&&(numberSchema=numberSchema.min(schema.minimum)),typeof schema.maximum=="number"&&schema.exclusiveMaximum!==!0&&(numberSchema=numberSchema.max(schema.maximum)),typeof schema.exclusiveMinimum=="number"?numberSchema=numberSchema.gt(schema.exclusiveMinimum):schema.exclusiveMinimum===!0&&typeof schema.minimum=="number"&&(numberSchema=numberSchema.gt(schema.minimum)),typeof schema.exclusiveMaximum=="number"?numberSchema=numberSchema.lt(schema.exclusiveMaximum):schema.exclusiveMaximum===!0&&typeof schema.maximum=="number"&&(numberSchema=numberSchema.lt(schema.maximum)),typeof schema.multipleOf=="number"&&(numberSchema=numberSchema.multipleOf(schema.multipleOf)),zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]),additionalSchema=typeof schema.additionalProperties=="object"?convertSchema(schema.additionalProperties,ctx):void 0;for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0&&schemasToIntersect.push(z.object(shape).passthrough()),schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++)result=z.intersection(result,schemasToIntersect[i]);zodSchema=result}if(schema.additionalProperties===!1){let propertyKeys=Object.keys(shape),patterns=patternKeys.map(p=>new RegExp(p)),basePatternSchema=zodSchema;zodSchema=zodSchema.check(payload=>{if(!isPlainObject(payload.value))return;let unrecognized=[];for(let key of Object.keys(payload.value))propertyKeys.includes(key)||patterns.some(regex=>regex.test(key))||unrecognized.push(key);unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})})}}else{let objectSchema=z.object(shape);schema.additionalProperties===!1?zodSchema=objectSchema.strict():additionalSchema?zodSchema=objectSchema.catchall(additionalSchema):zodSchema=objectSchema.passthrough()}let hasKeyGuard=schema.propertyNames!==void 0&&schema.propertyNames!==!0,minProperties=typeof schema.minProperties=="number"?schema.minProperties:void 0,maxProperties=typeof schema.maxProperties=="number"?schema.maxProperties:void 0;if(hasKeyGuard||minProperties!==void 0||maxProperties!==void 0){let keySchema;if(hasKeyGuard){let keyJSONSchema=typeof schema.propertyNames=="object"&&schema.propertyNames.type===void 0?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{let prefixItems=schema.prefixItems,items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=prefixItems.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=Array.isArray(items)?void 0:getTupleRest(items,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(Array.isArray(items)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=items.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=getTupleRest(schema.additionalItems,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);typeof schema.minItems=="number"&&(arraySchema=arraySchema.min(schema.minItems)),typeof schema.maxItems=="number"&&(arraySchema=arraySchema.max(schema.maxItems)),zodSchema=arraySchema}else zodSchema=z.array(z.any());(schema.uniqueItems===!0||schema.contains!==void 0)&&(zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===!0,containsSchema:schema.contains!==void 0?convertSchema(schema.contains,ctx):void 0,minContains:typeof schema.minContains=="number"?schema.minContains:void 0,maxContains:typeof schema.maxContains=="number"?schema.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema=="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map(s=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map(s=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++)result=z.intersection(result,convertSchema(schema.allOf[i],ctx));baseSchema=result}schema.nullable===!0&&ctx.version==="openapi-3.0"&&(baseSchema=z.nullable(baseSchema)),schema.readOnly===!0&&(baseSchema=z.readonly(baseSchema)),schema.default!==void 0&&(baseSchema=baseSchema.default(schema.default));let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);if(schema.type==="object"&&schema.$ref===void 0){schema.propertyNames!==void 0&&!containsRef(schema.propertyNames)&&(extraMeta.propertyNames=schema.propertyNames);for(let key of["minProperties","maxProperties"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}if(schema.type==="array"&&schema.$ref===void 0){schema.contains!==void 0&&!containsRef(schema.contains)&&(extraMeta.contains=schema.contains);for(let key of["uniqueItems","minContains","maxContains"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}for(let key of Object.keys(schema))RECOGNIZED_KEYS.has(key)||assignProp(extraMeta,key,schema[key]);return Object.keys(extraMeta).length>0&&ctx.registry.add(baseSchema,extraMeta),schema.description&&(baseSchema=baseSchema.describe(schema.description)),baseSchema}function fromJSONSchema(schema,params){if(typeof schema=="boolean")return schema?z.any():z.never();let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let version2=detectVersion(normalized,params?.defaultTarget),defs=normalized.$defs||normalized.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var z,RECOGNIZED_KEYS,SCHEMA_KEYWORDS,SCHEMA_MAP_KEYWORDS,fullTime,init_from_json_schema=__esm({"packages/coding-agent/node_modules/zod/v4/classic/from-json-schema.js"(){init_registries();init_util();init_checks2();init_iso();init_schemas2();z={...schemas_exports2,...checks_exports2,iso:iso_exports},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/}});function visit(schema,fnOrHandlers){let fn=typeof fnOrHandlers=="function"?fnOrHandlers:(node2,rewritten)=>{let h=fnOrHandlers[node2._zod.def.type];return h?h(node2,rewritten):node2},cache=new Map;function run(s){let cached2=cache.get(s);if(cached2===RESOLVING)return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)});if(cached2!==void 0)return cached2;cache.set(s,RESOLVING);let inner=mapInner(s),mapped=fn(inner,inner!==s);return cache.set(s,mapped),mapped}function mapInner(s){let def=s._zod.def,kind=def.type;switch(kind){case"object":{let oldShape=def.shape,keys=Object.keys(oldShape),changed=!1,newShape={};for(let k of keys){let mapped=run(oldShape[k]);mapped!==oldShape[k]&&(changed=!0),newShape[k]=mapped}let newCatchall=def.catchall;return def.catchall&&(newCatchall=run(def.catchall),newCatchall!==def.catchall&&(changed=!0)),changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{let mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{let oldItems=def.items,changed=!1,newItems=[];for(let item of oldItems){let mapped=run(item);mapped!==item&&(changed=!0),newItems.push(mapped)}let newRest=def.rest;return def.rest&&(newRest=run(def.rest),newRest!==def.rest&&(changed=!0)),changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{let newKey=run(def.keyType),newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{let newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{let oldOptions=def.options,changed=!1,newOptions=[];for(let opt of oldOptions){let mapped=run(opt);mapped!==opt&&(changed=!0),newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{let newLeft=run(def.left),newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{let newIn=run(def.in),newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{let newInput=run(def.input),newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{let original=def.getter,{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return run(schema)}var RESOLVING,init_visit=__esm({"packages/coding-agent/node_modules/zod/v4/core/visit.js"(){init_schemas();init_util();RESOLVING=Symbol("z.visit/resolving")}});function deepPartial(schema){return visit(schema,{object:s=>s.partial(),union:s=>{let def=s._zod.def;return def.discriminator===void 0?s:union(def.options)}})}var init_deep_partial=__esm({"packages/coding-agent/node_modules/zod/v4/classic/deep-partial.js"(){init_visit();init_schemas2()}});function withChecks(side,checks){if(!checks?.length)return side;let def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:!0})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:s=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:s=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}var init_in_out=__esm({"packages/coding-agent/node_modules/zod/v4/classic/in-out.js"(){init_util();init_visit();init_schemas2()}});var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm({"packages/coding-agent/node_modules/zod/v4/classic/coerce.js"(){init_core2();init_schemas2()}});var external_exports={};__export(external_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,INVALID:()=>INVALID,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRealError:()=>ZodRealError,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>coerce_exports,compile:()=>compile,config:()=>config,core:()=>core_exports2,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,decode:()=>decode2,decodeAsync:()=>decodeAsync2,deepPartial:()=>deepPartial,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode2,encodeAsync:()=>encodeAsync2,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,fromJSONSchema:()=>fromJSONSchema,function:()=>_function,getDiscriminatedOption:()=>getDiscriminatedOption,getErrorMap:()=>getErrorMap,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,includes:()=>_includes,input:()=>input,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>iso_exports,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,length:()=>_length,literal:()=>literal,locales:()=>locales_exports,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,memoizer:()=>memoizer,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object2,optional:()=>optional,output:()=>output,overwrite:()=>_overwrite,parse:()=>parse3,parseAsync:()=>parseAsync2,partialRecord:()=>partialRecord,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,preprocess:()=>preprocess,prettifyError:()=>prettifyError,promise:()=>promise,properties:()=>_properties,property:()=>_property,readonly:()=>readonly,record:()=>record2,refine:()=>refine,regex:()=>_regex,regexes:()=>regexes_exports,registry:()=>registry,safeDecode:()=>safeDecode2,safeDecodeAsync:()=>safeDecodeAsync2,safeEncode:()=>safeEncode2,safeEncodeAsync:()=>safeEncodeAsync2,safeParse:()=>safeParse2,safeParseAsync:()=>safeParseAsync2,set:()=>set,setErrorMap:()=>setErrorMap,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,toZod:()=>toZod,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>util_exports,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,validate:()=>validate,validateAsync:()=>validateAsync,void:()=>_void2,withParser:()=>withParser,xid:()=>xid2,xor:()=>xor});var init_external=__esm({"packages/coding-agent/node_modules/zod/v4/classic/external.js"(){init_core2();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();init_core2();init_json_schema_processors();init_from_json_schema();init_deep_partial();init_in_out();init_locales();init_iso();init_iso();init_coerce()}});var init_zod=__esm({"packages/coding-agent/node_modules/zod/index.js"(){init_external();init_external()}});function serializeEngineTrustMarker(marker){let parsed=markerSchema.safeParse(marker);if(!parsed.success)throw new EngineTrustContractError("trust-marker-invalid","engine trust marker is not version 1");return JSON.stringify(parsed.data)}var ENGINE_TRUST_MARKER_ENV,ENGINE_TRUST_HOP_ENV,ENGINE_TRUST_FALLBACK_REASONS,EngineTrustContractError,path,digest,restoreValue,markerSchema,init_marker2=__esm({"packages/coding-agent/dist/engine-trust/marker.js"(){init_zod();ENGINE_TRUST_MARKER_ENV="SENPI_ENGINE_TRUST",ENGINE_TRUST_HOP_ENV="SENPI_ENGINE_TRUST_HOP",ENGINE_TRUST_FALLBACK_REASONS=["helper-timeout","helper-crash","helper-malformed-output","helper-missing","helper-wrong-arch","helper-signature","access-denied","negatives-incomplete","linux-bundle-unreadable","linux-bundle-malformed"],EngineTrustContractError=class extends Error{constructor(code,message){super(message),this.name="EngineTrustContractError",this.code=code}},path=external_exports.string().min(1).refine(value=>!value.includes("\0")),digest=external_exports.string().regex(/^[0-9a-f]{64}$/u),restoreValue=external_exports.string().nullable().optional(),markerSchema=external_exports.strictObject({v:external_exports.literal(1),file:path,sha256:digest,automatic:external_exports.enum(["os","fallback"]),fallbackReason:external_exports.enum(ENGINE_TRUST_FALLBACK_REASONS).nullable(),owner:external_exports.enum(["server","standalone"]),user:digest.nullable(),defaults:external_exports.strictObject({file:path,dir:path}).nullable(),restore:external_exports.strictObject({NODE_EXTRA_CA_CERTS:restoreValue,NODE_USE_SYSTEM_CA:restoreValue,SSL_CERT_FILE:restoreValue,SSL_CERT_DIR:restoreValue,BUN_OPTIONS:restoreValue})}).refine(marker=>marker.automatic==="fallback"==(marker.fallbackReason!==null)).refine(marker=>marker.owner==="standalone"||marker.defaults!==null).refine(marker=>marker.owner==="server"||marker.restore.BUN_OPTIONS===void 0)}});function buildTrustLaunchEnvironment(base,options){let{marker,hop,platform}=options,env={...base};if(marker.owner==="server")for(let name of SERVER_REMOVED_NAMES)deleteName(env,name,platform);return marker.defaults!==null&&(setName(env,"SSL_CERT_FILE",representablePath(marker.defaults.file,platform),platform),setName(env,"SSL_CERT_DIR",representablePath(marker.defaults.dir,platform),platform)),setName(env,EXTRA_CA_ENV,marker.file,platform),setName(env,ENGINE_TRUST_MARKER_ENV,serializeEngineTrustMarker(marker),platform),hop?setName(env,ENGINE_TRUST_HOP_ENV,"1",platform):deleteName(env,ENGINE_TRUST_HOP_ENV,platform),definedEntries(env)}function representablePath(path2,platform){if(path2.includes(platform==="win32"?";":":"))throw new EngineTrustContractError("trust-path-unrepresentable","engine trust closure path holds a list separator");return path2}function definedEntries(env){let out={};for(let[name,value]of Object.entries(env))value!==void 0&&(out[name]=value);return out}var EXTRA_CA_ENV,SERVER_REMOVED_NAMES,init_launch_environment=__esm({"packages/coding-agent/dist/engine-trust/launch-environment.js"(){init_environment_names();init_marker2();EXTRA_CA_ENV="NODE_EXTRA_CA_CERTS",SERVER_REMOVED_NAMES=["NODE_USE_SYSTEM_CA","BUN_OPTIONS"]}});var hand_off_exports={};__export(hand_off_exports,{adoptedEngineTrustHandOff:()=>adoptedEngineTrustHandOff,engineTrustHandOffEnvironment:()=>engineTrustHandOffEnvironment});function engineTrustHandOffEnvironment(marker,platform){return buildTrustLaunchEnvironment({},{marker:{...marker,restore:{}},hop:!1,platform})}function adoptedEngineTrustHandOff(platform=process.platform){let marker=adoptedEngineTrust();return marker===void 0?{}:engineTrustHandOffEnvironment(marker,platform)}var init_hand_off=__esm({"packages/coding-agent/dist/engine-trust/hand-off.js"(){init_adopted();init_launch_environment()}});var mcp_presenter_bootstrap_exports={};__export(mcp_presenter_bootstrap_exports,{MCP_PRESENTER_BOOTSTRAP_FD:()=>MCP_PRESENTER_BOOTSTRAP_FD,PRESENTER_EXCHANGE_MS:()=>PRESENTER_EXCHANGE_MS,PRESENTER_PARKING_MS:()=>PRESENTER_PARKING_MS,presenterBootstrapStream:()=>presenterBootstrapStream,relayPresenterBootstrap:()=>relayPresenterBootstrap});import{Socket as Socket3}from"node:net";function presenterBootstrapStream(fd){if(fd===MCP_PRESENTER_BOOTSTRAP_FD)return inheritedDuplex(fd)}function relayPresenterBootstrap(upstream,child,launch){let downstream=child.stdio[MCP_PRESENTER_BOOTSTRAP_FD];return downstream instanceof Socket3?new Promise(resolve5=>{let ended=!1,acknowledging,parked=!0,finish=()=>{ended||(ended=!0,clearTimeout(timer),unreadUp(),unreadDown(),upstream.destroy(),downstream.destroy(),resolve5(acknowledging??"closed"))},timer=setTimeout(finish,PRESENTER_PARKING_MS),unreadUp=attachJsonlLineReader(upstream,line=>{if(parked&&(parked=!1,clearTimeout(timer),timer=setTimeout(finish,PRESENTER_EXCHANGE_MS)),launch)try{let record3=JSON.parse(line);if(typeof record3=="object"&&record3!==null&&"type"in record3&&record3.type==="enroll"&&"version"in record3&&record3.version===2&&(!("launchKind"in record3)||record3.launchKind!==launch.kind||launch.predecessorHostInstance===void 0||!("predecessorHostInstance"in record3)||record3.predecessorHostInstance!==launch.predecessorHostInstance))return finish()}catch{return finish()}downstream.write(`${line}
85
85
  `)||finish()},{maxLineLength:16*1024,onOversizedLine:finish}),unreadDown=attachJsonlLineReader(downstream,line=>{try{let record3=JSON.parse(line);acknowledging=typeof record3=="object"&&record3!==null&&"type"in record3&&(record3.type==="enrolled"||record3.type==="unavailable")?record3.type:void 0,upstream.write(`${line}
86
- `,()=>{acknowledging&&finish()})}catch{finish()}},{maxLineLength:16*1024,onOversizedLine:finish});upstream.once("error",finish),downstream.once("error",finish),upstream.once("end",finish),downstream.once("end",()=>{acknowledging||finish()}),child.once("exit",finish)}):(upstream.destroy(),Promise.resolve("closed"))}var MCP_PRESENTER_BOOTSTRAP_FD,PRESENTER_EXCHANGE_MS,PRESENTER_PARKING_MS,init_mcp_presenter_bootstrap=__esm({"packages/coding-agent/dist/modes/rpc/mcp-presenter-bootstrap.js"(){init_inherited_duplex();init_jsonl();MCP_PRESENTER_BOOTSTRAP_FD=4,PRESENTER_EXCHANGE_MS=3e4,PRESENTER_PARKING_MS=18e4}});init_inherited_duplex();init_host_identity_env();import{fstatSync as fstatSync2,writeSync}from"node:fs";import{isMainThread}from"node:worker_threads";var STARTUP_ATTEMPT_FILE="startup-attempt.json",ADOPTION_GRANT_FILE="adoption-grant.json";function encodeStartupHandOff(handOff){return JSON.stringify(handOff)}function parseStartupHandOff(value){if(value)try{let parsed=JSON.parse(value);if(typeof parsed!="object"||parsed===null)return;let{binding,role,budgetMs,fillers}=parsed;if(role!=="supervisor"&&role!=="host"||typeof budgetMs!="number"||!Number.isFinite(budgetMs)||budgetMs<=0||typeof binding!="object"||binding===null)return;let fields=binding;if(typeof fields.attempt!="string"||typeof fields.instanceId!="string")return;let slots=Array.isArray(fillers)?fillers.filter(slot=>Number.isInteger(slot)&&slot>=3&&slot<16):[];return{binding,role,budgetMs,fillers:slots}}catch{return}}function startupEventLine(binding,role,seq,milestone){return`${JSON.stringify({v:1,binding,role,seq,milestone})}
86
+ `,()=>{acknowledging&&finish()})}catch{finish()}},{maxLineLength:16*1024,onOversizedLine:finish});upstream.once("error",finish),downstream.once("error",finish),upstream.once("end",finish),downstream.once("end",()=>{acknowledging||finish()}),child.once("exit",finish)}):(upstream.destroy(),Promise.resolve("closed"))}var MCP_PRESENTER_BOOTSTRAP_FD,PRESENTER_EXCHANGE_MS,PRESENTER_PARKING_MS,init_mcp_presenter_bootstrap=__esm({"packages/coding-agent/dist/modes/rpc/mcp-presenter-bootstrap.js"(){init_inherited_duplex();init_jsonl();MCP_PRESENTER_BOOTSTRAP_FD=4,PRESENTER_EXCHANGE_MS=3e4,PRESENTER_PARKING_MS=18e4}});init_inherited_duplex();init_host_identity_env();import{fstatSync as fstatSync3,writeSync}from"node:fs";import{isMainThread}from"node:worker_threads";var STARTUP_ATTEMPT_FILE="startup-attempt.json",ADOPTION_GRANT_FILE="adoption-grant.json";function encodeStartupHandOff(handOff){return JSON.stringify(handOff)}function parseStartupHandOff(value){if(value)try{let parsed=JSON.parse(value);if(typeof parsed!="object"||parsed===null)return;let{binding,role,budgetMs,fillers}=parsed;if(role!=="supervisor"&&role!=="host"||typeof budgetMs!="number"||!Number.isFinite(budgetMs)||budgetMs<=0||typeof binding!="object"||binding===null)return;let fields=binding;if(typeof fields.attempt!="string"||typeof fields.instanceId!="string")return;let slots=Array.isArray(fillers)?fillers.filter(slot=>Number.isInteger(slot)&&slot>=3&&slot<16):[];return{binding,role,budgetMs,fillers:slots}}catch{return}}function startupEventLine(binding,role,seq,milestone){return`${JSON.stringify({v:1,binding,role,seq,milestone})}
87
87
  `}function startupGrantLine(attempt){return`${JSON.stringify({grant:"public_published",attempt})}
88
88
  `}function relayStartupLine(line){return`${JSON.stringify({relay:"host",line})}
89
- `}init_host_identity_env();import{closeSync as closeSync2}from"node:fs";var PRIVATE_FDS_TABLE_ENV="SENPI_PRIVATE_FDS",UNPARSEABLE_TABLE="unparseable";var NAME=/^[a-z][a-z0-9-]{0,63}$/,QUOTED_NAME=/"([a-z][a-z0-9-]{0,63})"\s*:/g;function decodePrivateFdTable(encoded){let value;try{value=encoded.length>4096?void 0:JSON.parse(encoded)}catch{value=void 0}if(typeof value!="object"||value===null||Array.isArray(value)){let names=[];for(let match of encoded.slice(0,4096).matchAll(QUOTED_NAME))match[1]!==void 0&&names.push(match[1]);return{parsed:!1,names}}return{parsed:!0,entries:Object.entries(value).filter(([name])=>NAME.test(name)),values:Object.values(value)}}function withStartupPipe(base){let stdio=[...base],fillers=[];for(let slot=3;slot<16;slot+=1){let entry=stdio[slot];(entry==null||entry==="ignore")&&(stdio[slot]="pipe",fillers.push(slot))}return stdio[16]="pipe",{stdio,fillers}}function releaseStartupFillers(child,fillers){for(let slot of fillers){let stream=child.stdio[slot];typeof stream=="object"&&stream!==null&&"destroy"in stream&&typeof stream.destroy=="function"&&stream.destroy()}}function namedPrivateSlots(encoded){let slots=new Set;if(!encoded)return slots;let table=decodePrivateFdTable(encoded);if(table.parsed){for(let entry of table.values)for(let fd of[entry].flat())typeof fd=="number"&&slots.add(fd);return slots}}function releaseInheritedStartupFillers(env){let handOff=parseStartupHandOff(env[HOST_STARTUP_EVENTS_ENV]);if(!handOff?.fillers?.length)return;let privateSlots=namedPrivateSlots(env[PRIVATE_FDS_TABLE_ENV]);if(privateSlots){for(let slot of handOff.fillers)if(!privateSlots.has(slot))try{closeSync2(slot)}catch{}}env[HOST_STARTUP_EVENTS_ENV]=encodeStartupHandOff({...handOff,fillers:[]})}var STATE=Symbol.for("senpi.startup-beacon.v1");function isStartupPipe(fd){try{let stat5=fstatSync2(fd);return isFifoMode(stat5.mode)||stat5.isSocket()}catch{return!1}}function captured(){let previous=Reflect.get(globalThis,STATE);if(previous!==void 0)return previous;isMainThread&&releaseInheritedStartupFillers(process.env);let handOff=isMainThread?parseStartupHandOff(process.env[HOST_STARTUP_EVENTS_ENV]):void 0;isMainThread&&delete process.env[HOST_STARTUP_EVENTS_ENV];let state3=handOff&&isStartupPipe(16)?{handOff,seq:0,open:!0}:null;return Reflect.set(globalThis,STATE,state3),state3&&write2(state3,startupEventLine(state3.handOff.binding,state3.handOff.role,++state3.seq,bootstrapOf(state3))),state3}function bootstrapOf(state3){return state3.handOff.role==="supervisor"?"supervisor_bootstrap":"host_bootstrap"}function write2(state3,line){if(state3.open)try{writeSync(16,line)}catch{state3.open=!1}}var state=captured(),reporter=state?startupReporter(line=>write2(state,line)):void 0;function startupReporter(emit){let relaying=!1,relayEnded=!1,setupSent=!1,runtimeRelayed=!1,heldOwn=[],heldHost=[],waitingForHost=()=>relaying&&!relayEnded&&!runtimeRelayed,releaseOwn=()=>{if(!waitingForHost())for(let line of heldOwn.splice(0))emit(line)},forwardHost=record3=>{emit(relayStartupLine(record3)),recordMilestone(record3)==="host_runtime"&&(runtimeRelayed=!0),releaseOwn()};return{report(line,milestone){if(heldOwn.length>0||milestone==="internal_ready"&&waitingForHost()){heldOwn.push(line);return}if(emit(line),milestone==="supervisor_setup"){setupSent=!0;for(let record3 of heldHost.splice(0))forwardHost(record3)}},relay(stream){relaying=!0;let forward=record3=>{setupSent?forwardHost(record3):heldHost.push(record3)},ended=()=>{relayEnded=!0,releaseOwn()},pending="";stream.setEncoding("utf8"),stream.on("data",chunk=>{pending+=chunk;for(let newline=pending.indexOf(`
89
+ `}init_host_identity_env();import{closeSync as closeSync2,fstatSync as fstatSync2}from"node:fs";var PRIVATE_FDS_TABLE_ENV="SENPI_PRIVATE_FDS",UNPARSEABLE_TABLE="unparseable";var NAME=/^[a-z][a-z0-9-]{0,63}$/,QUOTED_NAME=/"([a-z][a-z0-9-]{0,63})"\s*:/g;function decodePrivateFdTable(encoded){let value;try{value=encoded.length>4096?void 0:JSON.parse(encoded)}catch{value=void 0}if(typeof value!="object"||value===null||Array.isArray(value)){let names=[];for(let match of encoded.slice(0,4096).matchAll(QUOTED_NAME))match[1]!==void 0&&names.push(match[1]);return{parsed:!1,names}}return{parsed:!0,entries:Object.entries(value).filter(([name])=>NAME.test(name)),values:Object.values(value)}}function withStartupPipe(base){let stdio=[...base],fillers=[];for(let slot=3;slot<16;slot+=1){let entry=stdio[slot];(entry==null||entry==="ignore")&&(stdio[slot]="pipe",fillers.push(slot))}return stdio[16]="pipe",{stdio,fillers}}function releaseStartupFillers(child,fillers){for(let slot of fillers){let stream=child.stdio[slot];typeof stream=="object"&&stream!==null&&"destroy"in stream&&typeof stream.destroy=="function"&&stream.destroy()}}function namedPrivateSlots(encoded){let slots=new Set;if(!encoded)return slots;let table=decodePrivateFdTable(encoded);if(table.parsed){for(let entry of table.values)for(let fd of[entry].flat())typeof fd=="number"&&slots.add(fd);return slots}}function statOf(fd){try{return fstatSync2(fd)}catch{return}}var sameFile=(a,b)=>a.dev===b.dev&&a.ino===b.ino;function inheritedFillerCheck(){if(process.platform==="win32")return()=>!0;let startup=statOf(16);if(!startup?.isSocket())return()=>!1;let kept=[startup,...[0,1,2].map(statOf).filter(stat5=>stat5!==void 0)];return slot=>{let stat5=statOf(slot);return stat5!==void 0&&stat5.isSocket()&&!kept.some(other=>sameFile(stat5,other))}}function releaseInheritedStartupFillers(env){let handOff=parseStartupHandOff(env[HOST_STARTUP_EVENTS_ENV]);if(!handOff?.fillers?.length)return;let privateSlots=namedPrivateSlots(env[PRIVATE_FDS_TABLE_ENV]);if(privateSlots){let inherited=inheritedFillerCheck();for(let slot of handOff.fillers)if(!(privateSlots.has(slot)||!inherited(slot)))try{closeSync2(slot)}catch{}}env[HOST_STARTUP_EVENTS_ENV]=encodeStartupHandOff({...handOff,fillers:[]})}var STATE=Symbol.for("senpi.startup-beacon.v1");function isStartupPipe(fd){try{let stat5=fstatSync3(fd);return isFifoMode(stat5.mode)||stat5.isSocket()}catch{return!1}}function captured(){let previous=Reflect.get(globalThis,STATE);if(previous!==void 0)return previous;isMainThread&&releaseInheritedStartupFillers(process.env);let handOff=isMainThread?parseStartupHandOff(process.env[HOST_STARTUP_EVENTS_ENV]):void 0;isMainThread&&delete process.env[HOST_STARTUP_EVENTS_ENV];let state3=handOff&&isStartupPipe(16)?{handOff,seq:0,open:!0}:null;return Reflect.set(globalThis,STATE,state3),state3&&write2(state3,startupEventLine(state3.handOff.binding,state3.handOff.role,++state3.seq,bootstrapOf(state3))),state3}function bootstrapOf(state3){return state3.handOff.role==="supervisor"?"supervisor_bootstrap":"host_bootstrap"}function write2(state3,line){if(state3.open)try{writeSync(16,line)}catch{state3.open=!1}}var state=captured(),reporter=state?startupReporter(line=>write2(state,line)):void 0;function startupReporter(emit){let relaying=!1,relayEnded=!1,setupSent=!1,runtimeRelayed=!1,heldOwn=[],heldHost=[],waitingForHost=()=>relaying&&!relayEnded&&!runtimeRelayed,releaseOwn=()=>{if(!waitingForHost())for(let line of heldOwn.splice(0))emit(line)},forwardHost=record3=>{emit(relayStartupLine(record3)),recordMilestone(record3)==="host_runtime"&&(runtimeRelayed=!0),releaseOwn()};return{report(line,milestone){if(heldOwn.length>0||milestone==="internal_ready"&&waitingForHost()){heldOwn.push(line);return}if(emit(line),milestone==="supervisor_setup"){setupSent=!0;for(let record3 of heldHost.splice(0))forwardHost(record3)}},relay(stream){relaying=!0;let forward=record3=>{setupSent?forwardHost(record3):heldHost.push(record3)},ended=()=>{relayEnded=!0,releaseOwn()},pending="";stream.setEncoding("utf8"),stream.on("data",chunk=>{pending+=chunk;for(let newline=pending.indexOf(`
90
90
  `);newline>=0;newline=pending.indexOf(`
91
- `))forward(pending.slice(0,newline)),pending=pending.slice(newline+1);pending.length>4096&&(forward(pending.slice(0,4097)),pending="")}),stream.on("end",ended),stream.on("close",ended),stream.on("error",ended)}}}function recordMilestone(record3){try{let value=JSON.parse(record3);return typeof value=="object"&&value!==null?Reflect.get(value,"milestone"):void 0}catch{return}}function startupHandOff(){return state?.handOff}function reportStartupMilestone(milestone){state&&reporter&&reporter.report(startupEventLine(state.handOff.binding,state.handOff.role,++state.seq,milestone),milestone)}function hostChildStartupHandOff(fillers){return state?encodeStartupHandOff({...state.handOff,role:"host",fillers}):void 0}function relayHostStartupEvents(stream){if(!reporter||!stream){stream?.resume();return}reporter.relay(stream)}import{homedir}from"node:os";try{process.cwd()}catch{let fallback=homedir();process.chdir(fallback),console.error(`the current working directory no longer exists; continuing from ${fallback}`)}import{closeSync as closeSync3,fstatSync as fstatSync4}from"node:fs";import{isMainThread as isMainThread2}from"node:worker_threads";init_inherited_duplex();import{fstatSync as fstatSync3}from"node:fs";var clearInherit;function clearPrivateFdInherit(fd){try{if(fstatSync3(fd),clearInherit===void 0){let ffi=process.getBuiltinModule("bun:ffi");if(ffi===void 0)return!1;let crt=ffi.dlopen("ucrtbase.dll",{_get_osfhandle:{args:[ffi.FFIType.i32],returns:ffi.FFIType.ptr}}),kernel=ffi.dlopen("kernel32.dll",{SetHandleInformation:{args:[ffi.FFIType.ptr,ffi.FFIType.u32,ffi.FFIType.u32],returns:ffi.FFIType.i32}}),invalidHandle=BigInt.asUintN(process.arch==="ia32"||process.arch==="arm"?32:64,-1n);clearInherit=descriptor=>{let handle=crt.symbols._get_osfhandle(descriptor);if(!handle)return!1;let pointer=BigInt(handle);return pointer===-1n||pointer===invalidHandle||handle===Number(invalidHandle)?!1:kernel.symbols.SetHandleInformation(handle,1,0)===1}}return clearInherit(fd)}catch{return!1}}var PRIVATE_FDS_FINAL_ENV="SENPI_PRIVATE_FDS_FINAL",STATE2=Symbol.for("senpi.private-fds.v3"),WINDOWS_PRIVATE_FD_PAIR_PROVEN={bun:"1.4.4"};function isState(value){return typeof value=="object"&&value!==null&&"declared"in value&&value.declared instanceof Set&&"channels"in value&&value.channels instanceof Map&&"forward"in value&&value.forward instanceof Map}var ADOPTABLE_MAX=15;function ipcDescriptor(){let channel=Reflect.get(process,"channel");if(typeof channel!="object"||channel===null)return null;let fd=Reflect.get(channel,"fd");return typeof fd=="number"?fd:void 0}function isSocket(fd){try{return fstatSync4(fd).isSocket()}catch{return!1}}function isPipe(fd){try{return isFifoMode(fstatSync4(fd).mode)}catch{return!1}}function inRange(fd){return typeof fd=="number"&&Number.isSafeInteger(fd)&&fd>=5&&fd<=64}function inspectEntry(fd,shared,runtime,cleared){let{ipc}=runtime;return Array.isArray(fd)?runtime.platform!=="win32"||runtime.proven===!1||runtime.bun!==runtime.proven.bun||fd.length!==2||!inRange(fd[0])||!inRange(fd[1])||fd[0]===fd[1]||shared||ipc===void 0||fd[0]===ipc||fd[1]===ipc||!runtime.isPipe(fd[0])||!runtime.isPipe(fd[1])?{channel:null,discard:null}:{channel:cleared.get(fd[0])&&cleared.get(fd[1])?[fd[0],fd[1]]:null,discard:null}:inRange(fd)?runtime.platform==="win32"||ipc===void 0||fd===ipc||!runtime.isSocket(fd)?{channel:null,discard:null}:shared||fd>ADOPTABLE_MAX?{channel:null,discard:fd}:{channel:fd,discard:null}:{channel:null,discard:null}}function parseTable(encoded,inspection={}){let table=decodePrivateFdTable(encoded),entries=new Map;if(!table.parsed){for(let name of table.names)entries.set(name,null);return{entries,parsed:!1,discard:new Set}}let raw=table.entries,runtime={platform:process.platform,bun:process.versions.bun,proven:WINDOWS_PRIVATE_FD_PAIR_PROVEN,ipc:ipcDescriptor(),isSocket,isPipe,clearInherit:clearPrivateFdInherit,...inspection},cleared=new Map;if(runtime.platform==="win32")for(let fd of table.values)for(let number4 of Array.isArray(fd)?fd:[fd])inRange(number4)&&!cleared.has(number4)&&cleared.set(number4,runtime.clearInherit(number4));let counts=new Map;for(let[,fd]of raw)for(let number4 of Array.isArray(fd)?fd:[fd])typeof number4=="number"&&counts.set(number4,(counts.get(number4)??0)+1);let discard=new Set;for(let[name,fd]of raw){let shared=(Array.isArray(fd)?fd:[fd]).some(number4=>typeof number4=="number"&&(counts.get(number4)??0)>1),entry=inspectEntry(fd,shared,runtime,cleared);entries.set(name,entry.channel),entry.discard!==null&&discard.add(entry.discard)}for(let[fd,ok]of cleared)!ok&&fd!==runtime.ipc&&discard.add(fd);return{entries,parsed:!0,discard}}function closeDiscarded(fd,close=closeSync3){try{close(fd)}catch(error62){if(!(error62 instanceof Error&&"code"in error62&&error62.code==="EBADF"))throw error62}}function capturedState(){let previous=Reflect.get(globalThis,STATE2);if(isState(previous))return previous;let encoded=isMainThread2?process.env[PRIVATE_FDS_TABLE_ENV]:void 0,final=isMainThread2&&process.env[PRIVATE_FDS_FINAL_ENV]==="1";isMainThread2&&(delete process.env[PRIVATE_FDS_TABLE_ENV],delete process.env[PRIVATE_FDS_FINAL_ENV]);let{entries,parsed,discard}=encoded?parseTable(encoded):{entries:new Map,parsed:!0,discard:new Set};for(let fd of discard)closeDiscarded(fd);let unparseable=!parsed&&entries.size===0,state3={present:!!encoded,declared:new Set(entries.keys()),unparseable,channels:new Map,forward:new Map,forwardUnparseable:unparseable&&!final};for(let[name,fd]of entries)fd!==null&&state3.channels.set(name,fd),final||state3.forward.set(name,fd);return Reflect.set(globalThis,STATE2,state3),state3}var state2=capturedState();function takePrivateDescriptors(){if(state2.forwardUnparseable)return{kind:"unparseable"};let entries=new Map(state2.forward);for(let[name,fd]of entries)state2.forward.set(name,null),fd!==null&&state2.channels.delete(name);return{kind:"entries",entries}}init_config();init_brand();init_marker();import{realpathSync as realpathSync5}from"node:fs";import{dirname as dirname12,resolve as resolve4}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";import{mkdirSync,readdirSync,readFileSync as readFileSync3,renameSync,rmSync,statSync,unlinkSync,utimesSync,writeFileSync}from"node:fs";import{join as join5}from"node:path";init_marker();init_marker();var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25;var UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode(error62){return error62 instanceof Error&&"code"in error62?error62.code:void 0}function ageMs(path2,now){try{return now-statSync(path2).mtimeMs}catch(error62){if(errorCode(error62)==="ENOENT")return Number.POSITIVE_INFINITY;throw error62}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync(root,{recursive:!0});let lock=join5(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync(lock);break}catch(error62){if(errorCode(error62)!=="EEXIST")throw error62}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync(lock,{recursive:!0,force:!0})}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync(join5(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync(join5(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join5(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}init_config();import{randomUUID as randomUUID6}from"node:crypto";import{mkdir as mkdir9,rm as rm7}from"node:fs/promises";import{join as join20}from"node:path";var HostAdmission=class{constructor(info){this.stopped=!1,this.listeners=new Set,this.replies=Promise.resolve(),this.info=info}get stopping(){return this.stopped}protocol(){return{...this.info,lifecycle:this.stopped?"stopping":"ready"}}observe(info){this.info=info}stop(){this.stopped||(this.stopped=!0,this.replies=Promise.all([...this.listeners].map(listener=>listener())).then(()=>{}))}async flush(){let timer;try{await Promise.race([this.replies,new Promise(resolve5=>{timer=setTimeout(resolve5,2e3)})])}finally{clearTimeout(timer)}}onStop(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}};function hostStoppingResponse(id,command,admission){return{...typeof id=="string"?{id}:{},type:"response",command,success:!1,error:"host_stopping",errorCode:"host_stopping",errorData:{instanceId:admission.protocol().instanceId}}}var import_signal_exit=__toESM(require_signal_exit(),1);init_config();function crashingRuntimeVersions(){return{...process.versions.bun===void 0?{}:{bunVersion:process.versions.bun},senpiVersion:VERSION,...DISPLAY_VERSION===VERSION?{}:{productVersion:DISPLAY_VERSION}}}init_ownership_safe_lock();import{appendFileSync,mkdirSync as mkdirSync2,readFileSync as readFileSync4,writeFileSync as writeFileSync2}from"node:fs";import{join as join6}from"node:path";var HOST_CRASH_RECORD_LIMIT=50,CRASH_RECORD_FILE_MODE=384,TERMINAL_RECORD_LOCK_WAIT_MS=500;function hostCrashRecordFile(daemonDir){return join6(daemonDir,"crashes.jsonl")}function recordHostCrash(daemonDir,record3){try{mkdirSync2(daemonDir,{recursive:!0,mode:448}),appendFileSync(hostCrashRecordFile(daemonDir),`${JSON.stringify(record3)}
91
+ `))forward(pending.slice(0,newline)),pending=pending.slice(newline+1);pending.length>4096&&(forward(pending.slice(0,4097)),pending="")}),stream.on("end",ended),stream.on("close",ended),stream.on("error",ended)}}}function recordMilestone(record3){try{let value=JSON.parse(record3);return typeof value=="object"&&value!==null?Reflect.get(value,"milestone"):void 0}catch{return}}function startupHandOff(){return state?.handOff}function reportStartupMilestone(milestone){state&&reporter&&reporter.report(startupEventLine(state.handOff.binding,state.handOff.role,++state.seq,milestone),milestone)}function hostChildStartupHandOff(fillers){return state?encodeStartupHandOff({...state.handOff,role:"host",fillers}):void 0}function relayHostStartupEvents(stream){if(!reporter||!stream){stream?.resume();return}reporter.relay(stream)}import{homedir}from"node:os";try{process.cwd()}catch{let fallback=homedir();process.chdir(fallback),console.error(`the current working directory no longer exists; continuing from ${fallback}`)}import{closeSync as closeSync3,fstatSync as fstatSync5}from"node:fs";import{isMainThread as isMainThread2}from"node:worker_threads";init_inherited_duplex();import{fstatSync as fstatSync4}from"node:fs";var clearInherit;function clearPrivateFdInherit(fd){try{if(fstatSync4(fd),clearInherit===void 0){let ffi=process.getBuiltinModule("bun:ffi");if(ffi===void 0)return!1;let crt=ffi.dlopen("ucrtbase.dll",{_get_osfhandle:{args:[ffi.FFIType.i32],returns:ffi.FFIType.ptr}}),kernel=ffi.dlopen("kernel32.dll",{SetHandleInformation:{args:[ffi.FFIType.ptr,ffi.FFIType.u32,ffi.FFIType.u32],returns:ffi.FFIType.i32}}),invalidHandle=BigInt.asUintN(process.arch==="ia32"||process.arch==="arm"?32:64,-1n);clearInherit=descriptor=>{let handle=crt.symbols._get_osfhandle(descriptor);if(!handle)return!1;let pointer=BigInt(handle);return pointer===-1n||pointer===invalidHandle||handle===Number(invalidHandle)?!1:kernel.symbols.SetHandleInformation(handle,1,0)===1}}return clearInherit(fd)}catch{return!1}}var PRIVATE_FDS_FINAL_ENV="SENPI_PRIVATE_FDS_FINAL",STATE2=Symbol.for("senpi.private-fds.v3"),WINDOWS_PRIVATE_FD_PAIR_PROVEN={bun:"1.4.4"};function isState(value){return typeof value=="object"&&value!==null&&"declared"in value&&value.declared instanceof Set&&"channels"in value&&value.channels instanceof Map&&"forward"in value&&value.forward instanceof Map}var ADOPTABLE_MAX=15;function ipcDescriptor(){let channel=Reflect.get(process,"channel");if(typeof channel!="object"||channel===null)return null;let fd=Reflect.get(channel,"fd");return typeof fd=="number"?fd:void 0}function isSocket(fd){try{return fstatSync5(fd).isSocket()}catch{return!1}}function isPipe(fd){try{return isFifoMode(fstatSync5(fd).mode)}catch{return!1}}function inRange(fd){return typeof fd=="number"&&Number.isSafeInteger(fd)&&fd>=5&&fd<=64}function inspectEntry(fd,shared,runtime,cleared){let{ipc}=runtime;return Array.isArray(fd)?runtime.platform!=="win32"||runtime.proven===!1||runtime.bun!==runtime.proven.bun||fd.length!==2||!inRange(fd[0])||!inRange(fd[1])||fd[0]===fd[1]||shared||ipc===void 0||fd[0]===ipc||fd[1]===ipc||!runtime.isPipe(fd[0])||!runtime.isPipe(fd[1])?{channel:null,discard:null}:{channel:cleared.get(fd[0])&&cleared.get(fd[1])?[fd[0],fd[1]]:null,discard:null}:inRange(fd)?runtime.platform==="win32"||ipc===void 0||fd===ipc||!runtime.isSocket(fd)?{channel:null,discard:null}:shared||fd>ADOPTABLE_MAX?{channel:null,discard:fd}:{channel:fd,discard:null}:{channel:null,discard:null}}function parseTable(encoded,inspection={}){let table=decodePrivateFdTable(encoded),entries=new Map;if(!table.parsed){for(let name of table.names)entries.set(name,null);return{entries,parsed:!1,discard:new Set}}let raw=table.entries,runtime={platform:process.platform,bun:process.versions.bun,proven:WINDOWS_PRIVATE_FD_PAIR_PROVEN,ipc:ipcDescriptor(),isSocket,isPipe,clearInherit:clearPrivateFdInherit,...inspection},cleared=new Map;if(runtime.platform==="win32")for(let fd of table.values)for(let number4 of Array.isArray(fd)?fd:[fd])inRange(number4)&&!cleared.has(number4)&&cleared.set(number4,runtime.clearInherit(number4));let counts=new Map;for(let[,fd]of raw)for(let number4 of Array.isArray(fd)?fd:[fd])typeof number4=="number"&&counts.set(number4,(counts.get(number4)??0)+1);let discard=new Set;for(let[name,fd]of raw){let shared=(Array.isArray(fd)?fd:[fd]).some(number4=>typeof number4=="number"&&(counts.get(number4)??0)>1),entry=inspectEntry(fd,shared,runtime,cleared);entries.set(name,entry.channel),entry.discard!==null&&discard.add(entry.discard)}for(let[fd,ok]of cleared)!ok&&fd!==runtime.ipc&&discard.add(fd);return{entries,parsed:!0,discard}}function closeDiscarded(fd,close=closeSync3){try{close(fd)}catch(error62){if(!(error62 instanceof Error&&"code"in error62&&error62.code==="EBADF"))throw error62}}function capturedState(){let previous=Reflect.get(globalThis,STATE2);if(isState(previous))return previous;let encoded=isMainThread2?process.env[PRIVATE_FDS_TABLE_ENV]:void 0,final=isMainThread2&&process.env[PRIVATE_FDS_FINAL_ENV]==="1";isMainThread2&&(delete process.env[PRIVATE_FDS_TABLE_ENV],delete process.env[PRIVATE_FDS_FINAL_ENV]);let{entries,parsed,discard}=encoded?parseTable(encoded):{entries:new Map,parsed:!0,discard:new Set};for(let fd of discard)closeDiscarded(fd);let unparseable=!parsed&&entries.size===0,state3={present:!!encoded,declared:new Set(entries.keys()),unparseable,channels:new Map,forward:new Map,forwardUnparseable:unparseable&&!final};for(let[name,fd]of entries)fd!==null&&state3.channels.set(name,fd),final||state3.forward.set(name,fd);return Reflect.set(globalThis,STATE2,state3),state3}var state2=capturedState();function takePrivateDescriptors(){if(state2.forwardUnparseable)return{kind:"unparseable"};let entries=new Map(state2.forward);for(let[name,fd]of entries)state2.forward.set(name,null),fd!==null&&state2.channels.delete(name);return{kind:"entries",entries}}init_config();init_brand();init_marker();import{realpathSync as realpathSync5}from"node:fs";import{dirname as dirname12,resolve as resolve4}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";import{mkdirSync,readdirSync,readFileSync as readFileSync3,renameSync,rmSync,statSync,unlinkSync,utimesSync,writeFileSync}from"node:fs";import{join as join5}from"node:path";init_marker();init_marker();var LOCK_NAME=".lock",CLAIMS_DIR="claims",STALE_LOCK_MS=3e4,LOCK_WAIT_MS=5e3,LOCK_RETRY_MS=25;var UNUSED_SNAPSHOT_GRACE_MS=10*6e4,LEFTOVER_MS=60*6e4;function errorCode(error62){return error62 instanceof Error&&"code"in error62?error62.code:void 0}function ageMs(path2,now){try{return now-statSync(path2).mtimeMs}catch(error62){if(errorCode(error62)==="ENOENT")return Number.POSITIVE_INFINITY;throw error62}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function withRuntimeLock(root,task){mkdirSync(root,{recursive:!0});let lock=join5(root,LOCK_NAME),deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{mkdirSync(lock);break}catch(error62){if(errorCode(error62)!=="EEXIST")throw error62}if(ageMs(lock,Date.now())>STALE_LOCK_MS)rmSync(lock,{recursive:!0,force:!0});else{if(Date.now()>deadline)return;sleepSync(LOCK_RETRY_MS)}}try{return task()}finally{rmSync(lock,{recursive:!0,force:!0})}}function claimRuntimeSnapshot(snapshotDir,pid){mkdirSync(join5(snapshotDir,CLAIMS_DIR),{recursive:!0}),writeFileSync(join5(snapshotDir,CLAIMS_DIR,String(pid)),"");let now=new Date;utimesSync(join5(snapshotDir,RUNTIME_SNAPSHOT_MARKER),now,now)}init_config();import{randomUUID as randomUUID6}from"node:crypto";import{mkdir as mkdir9,rm as rm7}from"node:fs/promises";import{join as join20}from"node:path";var HostAdmission=class{constructor(info){this.stopped=!1,this.listeners=new Set,this.replies=Promise.resolve(),this.info=info}get stopping(){return this.stopped}protocol(){return{...this.info,lifecycle:this.stopped?"stopping":"ready"}}observe(info){this.info=info}stop(){this.stopped||(this.stopped=!0,this.replies=Promise.all([...this.listeners].map(listener=>listener())).then(()=>{}))}async flush(){let timer;try{await Promise.race([this.replies,new Promise(resolve5=>{timer=setTimeout(resolve5,2e3)})])}finally{clearTimeout(timer)}}onStop(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}};function hostStoppingResponse(id,command,admission){return{...typeof id=="string"?{id}:{},type:"response",command,success:!1,error:"host_stopping",errorCode:"host_stopping",errorData:{instanceId:admission.protocol().instanceId}}}var import_signal_exit=__toESM(require_signal_exit(),1);init_config();function crashingRuntimeVersions(){return{...process.versions.bun===void 0?{}:{bunVersion:process.versions.bun},senpiVersion:VERSION,...DISPLAY_VERSION===VERSION?{}:{productVersion:DISPLAY_VERSION}}}init_ownership_safe_lock();import{appendFileSync,mkdirSync as mkdirSync2,readFileSync as readFileSync4,writeFileSync as writeFileSync2}from"node:fs";import{join as join6}from"node:path";var HOST_CRASH_RECORD_LIMIT=50,CRASH_RECORD_FILE_MODE=384,TERMINAL_RECORD_LOCK_WAIT_MS=500;function hostCrashRecordFile(daemonDir){return join6(daemonDir,"crashes.jsonl")}function recordHostCrash(daemonDir,record3){try{mkdirSync2(daemonDir,{recursive:!0,mode:448}),appendFileSync(hostCrashRecordFile(daemonDir),`${JSON.stringify(record3)}
92
92
  `,{mode:CRASH_RECORD_FILE_MODE}),pruneHostCrashRecords(daemonDir)}catch{}}async function recordTerminalHostRecord(daemonDir,record3){let release=await acquireRecordLock(daemonDir);try{(!(record3.generation!==void 0&&readHostCrashRecords(daemonDir).some(existing=>existing.kind==="rpc-host"&&existing.generation===record3.generation))||release===void 0)&&recordHostCrash(daemonDir,{...record3,kind:"rpc-host"})}finally{await release?.().catch(()=>{})}}async function acquireRecordLock(daemonDir){try{return mkdirSync2(daemonDir,{recursive:!0,mode:448}),await acquireOwnershipSafeLock(join6(daemonDir,"crashes.lock"),{retries:{retries:Math.ceil(TERMINAL_RECORD_LOCK_WAIT_MS/50),minTimeout:20,maxTimeout:50}})}catch{return}}function readHostCrashRecords(daemonDir){let raw;try{raw=readFileSync4(hostCrashRecordFile(daemonDir),"utf8")}catch{return[]}let records=[];for(let line of raw.split(`
93
93
  `))if(line.trim()!=="")try{let value=JSON.parse(line);typeof value=="object"&&value!==null&&typeof Reflect.get(value,"at")=="string"&&records.push(value)}catch{}return records}function pruneHostCrashRecords(daemonDir){let records=readHostCrashRecords(daemonDir);if(records.length<=HOST_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-HOST_CRASH_RECORD_LIMIT);writeFileSync2(hostCrashRecordFile(daemonDir),`${kept.map(r=>JSON.stringify(r)).join(`
94
94
  `)}
@@ -99,7 +99,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
99
99
  `)}),this.on("error",()=>{}),wire.on("data",chunk=>{wire.pause(),this.pending=chunk,this.offset=0,this.consume()}),wire.once("end",()=>{this.wireDone=!0,this.pending===void 0&&this.finish()}),wire.once("error",error62=>this.destroy(error62)),wire.once("close",()=>{this.wireDone=!0,this.wireClosed=!0,this.ended&&this.readableEnded?this.destroy():this.pending===void 0&&this.finish()}),this.once("end",()=>{this.wireClosed&&this.destroy()})}finish(){this.ended||(this.ended=!0,this.headerUsed!==0||this.body!==void 0?this.destroy(new Error("internal_record_truncated")):this.push(null))}consume(){try{let chunk=this.pending;if(!chunk)return;for(;this.offset<chunk.length;){if(!this.body){let n2=Math.min(4-this.headerUsed,chunk.length-this.offset);if(chunk.copy(this.header,this.headerUsed,this.offset,this.offset+n2),this.headerUsed+=n2,this.offset+=n2,this.headerUsed!==4)break;let length=this.header.readUInt32BE();if(length<17||length>INTERNAL_RECORD_MAX+16)throw new Error("internal_record_length");this.headerUsed=0,this.body=Buffer.alloc(length)}let n=Math.min(this.body.length-this.bodyUsed,chunk.length-this.offset);if(chunk.copy(this.body,this.bodyUsed,this.offset,this.offset+n),this.bodyUsed+=n,this.offset+=n,this.bodyUsed===this.body.length){let plaintext=this.receiver.open(this.body);if(this.body=void 0,this.bodyUsed=0,!this.push(plaintext)){this.offset===chunk.length&&(this.pending=void 0,this.wireDone&&this.finish());return}}}this.pending=void 0,this.wireDone?this.finish():this.wire.resume()}catch(cause){this.destroy(cause instanceof Error&&cause.message.startsWith("internal_record")?cause:new Error("internal_record_unverified",{cause}))}}_read(){this.pending?this.consume():this.wire.resume()}_write(chunk,_encoding,callback){let offset=0,next=error62=>{if(error62){callback(error62);return}if(this.destroyed){callback(new Error("internal_hop_lost"));return}if(offset===chunk.length){callback();return}try{let end=Math.min(chunk.length,offset+INTERNAL_RECORD_MAX),record3=this.sender.seal(chunk.subarray(offset,end));offset=end,this.wire.write(record3,next)}catch(cause){callback(cause instanceof Error?cause:new Error("internal_record_invalid"))}};next()}_final(callback){this.wire.end(callback)}_destroy(error62,callback){this.wire.destroy(),callback(error62)}};init_jsonl();init_rpc_auth_proof();var INTERNAL_LAUNCH_ID="internal";function proof(key,label,first,second){return rpcAuthProof(key,label,INTERNAL_LAUNCH_ID,first,second)}function matches(actual,expected){return rpcProofMatches(expected,actual)}function object(value){if(!isObject(value))throw new Error("auth_failed");return value}function isObject(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function nonce(value){if(typeof value!="string"||!RPC_AUTH_HEX.test(value))throw new Error("auth_failed");return value}async function handshake(socket,budget,run){let readBytes=0,ended=!1,rejectPending,fail=error62=>{ended=!0,rejectPending?.(error62),socket.destroy()},timer=budget.timeoutMs===void 0?void 0:setTimeout(()=>fail(new Error("internal_auth_timeout")),budget.timeoutMs);timer?.unref();let onError=error62=>fail(error62),onClose=()=>fail(new Error("internal_hop_lost"));socket.on("error",onError),socket.once("close",onClose);let read2=()=>new Promise((resolve5,reject)=>{if(ended)return reject(new Error("internal_hop_lost"));let buffer=Buffer.alloc(0);rejectPending=cause=>{socket.off("data",data),reject(cause)};let data=chunk=>{let newline=chunk.indexOf(10),used=newline===-1?chunk.length:newline+1;if(readBytes+=used,readBytes>budget.maxBytes)return fail(new Error("internal_auth_oversized"));if(buffer=Buffer.concat([buffer,chunk.subarray(0,used)]),newline!==-1){socket.pause(),socket.off("data",data),rejectPending=void 0,used<chunk.length&&socket.unshift(chunk.subarray(used));try{resolve5(object(JSON.parse(buffer.toString("utf8"))))}catch{reject(new Error("auth_failed"))}}};socket.on("data",data),socket.resume()});try{return await run(read2,frame=>new Promise((resolve5,reject)=>{socket.write(`${JSON.stringify(frame)}
100
100
  `,error62=>error62?reject(error62):resolve5())}))}catch(cause){throw socket.destroy(),cause}finally{timer&&clearTimeout(timer),socket.off("error",onError),socket.off("close",onClose)}}function connectInternalConnection(socket,key,options={}){return handshake(socket,{maxBytes:MAX_RPC_LINE_CHARACTERS,timeoutMs:options.timeoutMs},async(read2,send)=>{let clientNonce=randomBytes(32).toString("hex"),[response]=await Promise.all([read2(),send({id:"internal-protocol",type:"get_protocol_info",observe:!0,auth:{client_nonce:clientNonce}})]),data=response.data;if(!isObject(data)||!isObject(data.auth))throw new Error("host_identity_unproven");let auth=data.auth,serverNonce=nonce(auth.server_nonce);if(response.id!=="internal-protocol"||response.success!==!0||auth.launch_id!==INTERNAL_LAUNCH_ID||!matches(auth.server_proof,proof(key,"server",clientNonce,serverNonce)))throw new Error("host_identity_unproven");let[result]=await Promise.all([read2(),send({id:"internal-auth",type:"authenticate",client_proof:proof(key,"client",serverNonce,clientNonce)})]);if(result.id!=="internal-auth"||result.command!=="authenticate"||result.success!==!0)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"client")})}init_jsonl();function activeTurnsForIdleDecision(input2){return input2.healthy?input2.observedBusy:input2.unhealthySince===void 0||input2.now-input2.unhealthySince<input2.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open4().catch(armRetry)},options.retryDelayMs))};async function open4(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open:open4,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}init_socket_transport();var INTERNAL_OBSERVER_HANDSHAKE_MS=5e3,SupervisorActivity=class{constructor(options){this.options=options,this.decider=new IdleExitDecider(options.idleExitMs,Date.now,startupHandOff()?.budgetMs),this.runs=new SessionRunActivity({settleHoldMs:options.idleExitMs,onSettleHoldExpired:(sessionId,heldMs)=>supervisorLog(`session ${sessionId} settled ${heldMs} ms ago and its agent_settled extension handlers have not finished; idle exit no longer waits for them`)}),this.clients=new ClientOccupancy(()=>this.refresh(),options.instanceId),this.observerLink=createObserverLink({open:()=>this.connectObserver(),settled:options.settled,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}})}current(){return{connections:this.clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:this.observerLink.healthy(),unhealthySince:this.observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:this.decider.idleExitMs,observedBusy:this.runs.busySessions})}}refresh(){let current=this.current();return(current.connections>0||current.activeTurns>0||this.clients.unclassifiedCount>0)&&this.options.onActivity?.(),holdIdleExitForSettling(this.decider.update(current),this.runs)}quiescent(){return this.observerLink.healthy()&&this.runs.busySessions===0&&this.runs.settlingSessions===0&&this.clients.attachedCount===0&&this.clients.unclassifiedCount===0}openObserver(){return this.observerLink.open()}stopObserver(){this.observerLink.stop(),this.observerSocket?.destroy()}async connectObserver(){let secret=this.options.internalSecret,next=createConnection(resolveSocketTransportAddress(this.options.internalSocket,process.platform,secret));secret&&sendSocketHandshake(next,secret);let stream;try{this.options.internalKey?stream=await connectInternalConnection(next,this.options.internalKey,{timeoutMs:INTERNAL_OBSERVER_HANDSHAKE_MS}):(await waitForConnect(next,5e3),stream=next)}catch(cause){throw next.destroy(),cause}return this.observerSocket=stream,attachJsonlLineReader(stream,line=>this.observeHostEvent(line),{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{let lost=()=>{handler(),this.options.onActivity?.()};stream.once("close",lost),stream.once("error",lost)}}}observeHostEvent(line){this.runs.observe(line)&&this.refresh()}},OWNER_EXIT_GRACE_MS=2e3,OWNER_PROBE_MAX_INTERVAL_MS=5e3,SupervisorOwner=class{constructor(generationDir){this.watchFailed=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.gone=!1,this.revision=0,this.stopped=!1,this.idle=new IdleExitDecider(OWNER_EXIT_GRACE_MS,()=>performance.now()),this.generationDir=generationDir}async start(fd){if(await this.reload(),!(fd===void 0||this.owner==null))try{let pipe2=new Socket2({fd,readable:!0,writable:!1});this.pipe=pipe2;let bound=this.owner,failed=!1,eof=()=>{!failed&&!this.stopped&&sameHostOwner(this.owner,bound)&&(this.gone=!0)};pipe2.once("end",eof),process.platform==="win32"&&pipe2.once("close",eof),pipe2.once("error",()=>{failed=!0,this.pipe===pipe2&&(this.pipe=void 0),pipe2.destroy()}),pipe2.resume()}catch{this.pipe=void 0}}async reload(){let revision=++this.revision,next=await readHostOwner(this.generationDir);if(!(this.stopped||revision!==this.revision)){if(sameHostOwner(this.owner,next)||(this.pipe?.destroy(),this.pipe=void 0,this.gone=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.activity()),this.owner=next,next==null)this.watcher?.close(),this.watcher=void 0;else if(!this.watcher&&!this.watchFailed)try{this.watcher=watch2(this.generationDir,(_event,filename)=>{filename?.toString()==="owner.json"&&this.reload()}),this.watcher.once("error",()=>{this.watchFailed=!0,this.watcher?.close(),this.watcher=void 0})}catch{this.watchFailed=!0}}}activity(){this.idle.update({connections:1,activeTurns:0})}async shouldExit(activity){this.watcher||await this.reload();let owner=this.owner,revision=this.revision;if(owner!=null&&(!this.pipe||process.ppid!==owner.pid)&&!this.gone&&performance.now()>=this.nextProbeAt){let gone=await hostOwnerGone(owner);if(this.stopped||revision!==this.revision)return!1;this.gone=gone,this.nextProbeAt=performance.now()+this.probeIntervalMs,this.probeIntervalMs=Math.min(OWNER_PROBE_MAX_INTERVAL_MS,this.probeIntervalMs*2)}let quiet=this.gone&&owner!=null&&activity.quiescent();if(this.idle.update({connections:quiet?0:1,activeTurns:0})!=="exit")return!1;let current=await readHostOwner(this.generationDir);return this.stopped||revision!==this.revision?!1:sameHostOwner(owner,current)?activity.quiescent():(await this.reload(),!1)}stop(){this.stopped=!0,this.watcher?.close(),this.pipe?.destroy()}};function waitForConnect(socket,timeoutMs){return new Promise((resolve5,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve5()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}init_process_identity();init_host_observe_request();import{readFile as readFile6}from"node:fs/promises";import{execFile as execFile3}from"node:child_process";import{lstat,mkdir as mkdir3,readFile as readFile5,rename as rename3,unlink as unlink2,writeFile as writeFile4}from"node:fs/promises";import{createConnection as createConnection2}from"node:net";import{dirname as dirname8}from"node:path";import{execFile as execFile2}from"node:child_process";import{stat as stat3}from"node:fs/promises";var SCAN_TIMEOUT_MS=5e3;async function socketHoldersByIdentity(identity){let listing=await new Promise(resolve5=>{execFile2("lsof",["-U","-w","-F","pn"],{timeout:SCAN_TIMEOUT_MS,maxBuffer:67108864},(error62,out)=>{let code=error62===null?void 0:Reflect.get(error62,"code");resolve5(error62===null||code===1?String(out):void 0)})});if(listing===void 0)return;let pids=new Set,sameInode=new Map,pid;for(let line of listing.split(`
101
101
  `)){if(line.startsWith("p")&&(pid=Number(line.slice(1))),!line.startsWith("n/")||pid===void 0||!Number.isInteger(pid))continue;let name=line.slice(1).replace(/ type=\S+.*$/,""),same=sameInode.get(name);if(same===void 0){let entry=await stat3(name).catch(()=>{});same=entry!==void 0&&entry.dev===identity.dev&&entry.ino===identity.ino,sameInode.set(name,same)}same&&pids.add(pid)}return[...pids]}init_socket_transport();var PUBLIC_SOCKET_IDENTITY_FILE="public-socket.owner";var MAX_SOCKET_PATH_BYTES=103,BIND_SCRATCH_INFIX=".bind-",BIND_SCRATCH_SOCKET="s";function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function sameSocketIdentity(a,b){return a.dev===b.dev&&a.ino===b.ino}function classifyConnectError(code,platform){return code==="ENOENT"?"gone":code==="ECONNREFUSED"?platform==="linux"?"dead":"confirm-holder":"live"}var HOLDER_PROBE_TIMEOUT_MS=5e3,lsofSocketHolders=async socketPath=>{let byPath=await lsofHoldersByPath(socketPath);if(byPath===void 0||byPath.length>0)return byPath;let entry=await lstat(socketPath).catch(()=>{});return entry!==void 0&&entry.nlink>1?socketHoldersByIdentity(entry):byPath},lsofHoldersByPath=socketPath=>new Promise(resolve5=>{execFile3("lsof",["-t","--",socketPath],{timeout:HOLDER_PROBE_TIMEOUT_MS},(error62,stdout)=>{let pids=String(stdout).split(/\s+/).filter(part=>/^\d+$/.test(part)).map(Number);if(pids.length>0)return resolve5(pids);let exitCode=error62===null?void 0:Reflect.get(error62,"code");resolve5(error62===null||exitCode===1?[]:void 0)})}),CONNECT_PROBE_TIMEOUT_MS=2e3;function connectOnce(socketPath){return new Promise(resolve5=>{let socket=createConnection2(resolveSocketTransportAddress(socketPath,process.platform)),settle2=value=>{socket.destroy(),resolve5(value)};socket.setTimeout(CONNECT_PROBE_TIMEOUT_MS,()=>settle2({code:"timeout"})),socket.once("connect",()=>settle2({connected:!0})),socket.once("error",cause=>settle2({code:cause.code}))})}async function socketEntryListenerState(socketPath,platform=process.platform,holders=lsofSocketHolders){let attempt=await connectOnce(socketPath);if("connected"in attempt)return{verdict:"live",evidence:"accepting connections"};let verdict=classifyConnectError(attempt.code,platform);if(verdict!=="confirm-holder")return{verdict,evidence:`connect ${attempt.code??"failed"}`};let pids=await holders(socketPath);return pids===void 0?{verdict:"live",evidence:"connect ECONNREFUSED, holders unknown"}:pids.length>0?{verdict:"live",evidence:`connect ECONNREFUSED, held open by pid ${pids.join(",")}`}:{verdict:"dead",evidence:"connect ECONNREFUSED, held by nobody"}}async function statSocketIdentity(socketPath){try{let{dev,ino}=await lstat(socketPath);return{dev,ino}}catch(cause){if(isNodeErrorCode4(cause,"ENOENT"))return;throw cause}}async function classifyEndpointOwnership(socketPath,identity){if(identity===void 0||process.platform==="win32"||socketPath.startsWith("\0"))return"unknown";let current;try{current=await statSocketIdentity(socketPath)}catch{return"unknown"}return current===void 0?"absent":sameSocketIdentity(current,identity)?"held":"replaced"}async function writeSocketIdentityFile(path2,identity){await mkdir3(dirname8(path2),{recursive:!0,mode:448});let tmpPath=`${path2}.${process.pid}.tmp`;await writeFile4(tmpPath,`${JSON.stringify(identity)}
102
- `,{mode:384}),await rename3(tmpPath,path2)}async function unlinkOwnedSocket(socketPath,identity,log){if(process.platform==="win32"||socketPath.startsWith("\0"))return;let current;try{current=await statSocketIdentity(socketPath)}catch(cause){log(`socket ${socketPath} ownership could not be verified (${errorMessage2(cause)}); leaving it`);return}if(current!==void 0){if(identity===void 0){log(`socket path ${socketPath} ownership unknown; leaving it`);return}if(!sameSocketIdentity(current,identity)){log(`socket path ${socketPath} now owned by another host; leaving it`);return}try{await unlink2(socketPath)}catch(cause){isNodeErrorCode4(cause,"ENOENT")||log(`socket ${socketPath} removal failed (${errorMessage2(cause)})`)}}}async function shieldSocketDuringClose(socketPath,close){if(process.platform==="win32"||socketPath.startsWith("\0"))return close();let shieldPath=`${socketPath}.shield-${process.pid}`,shielded=!1;try{await statSocketIdentity(socketPath)!==void 0&&(await rename3(socketPath,shieldPath),shielded=!0)}catch{}try{await close()}finally{if(shielded)try{await rename3(shieldPath,socketPath)}catch{}}}function errorMessage2(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode4(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}async function adoptPublicSocket(bindSocket,publicSocket,expected){if(expected===void 0)throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);let current=await statSocketIdentity(publicSocket);if(current===void 0||current.dev!==expected.dev||current.ino!==expected.ino)throw new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);await rename3(bindSocket,publicSocket)}var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3,REPLACED_CONFIRMATIONS=3,IDENTITY_PROBE_TIMEOUT_MS=2e3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0)return endpoint.pointer===void 0?()=>{}:watchPointerSupersession(endpoint,endpoint.pointer,onLost);let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore2)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function watchPointerSupersession(endpoint,pointer,onLost){let probe=endpoint.probeInstanceId??probeAnsweringInstance,readPointer=endpoint.readPointerInstanceId??pointerInstanceId,agreeingPolls=0,observing=!1,lost=!1,observe=async()=>{let named=await readPointer(pointer.file);return named===void 0||named===pointer.instanceId?!1:await probe(endpoint.path)===named},timer=setInterval(()=>{lost||observing||endpoint.settled?.()===!0||(observing=!0,observe().then(replaced=>{lost||endpoint.settled?.()===!0||(agreeingPolls=replaced?agreeingPolls+1:0,!(agreeingPolls<REPLACED_CONFIRMATIONS)&&(lost=!0,clearInterval(timer),onLost("replaced")))},()=>{agreeingPolls=0}).finally(()=>{observing=!1}))},SUPERSESSION_POLL_MS);return timer.unref?.(),()=>clearInterval(timer)}async function pointerInstanceId(file2){try{let parsed=JSON.parse(await readFile6(file2,"utf8")),instanceId=typeof parsed=="object"&&parsed!==null?Reflect.get(parsed,"instance_id"):void 0;return typeof instanceId=="string"&&instanceId!==""?instanceId:void 0}catch{return}}async function probeAnsweringInstance(path2){let{isRecord:isRecord6,requestOnSocket:requestOnSocket2}=await Promise.resolve().then(()=>(init_host_socket_request(),host_socket_request_exports)),answer=await requestOnSocket2(path2,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},IDENTITY_PROBE_TIMEOUT_MS).catch(()=>{});return isRecord6(answer)&&typeof answer.instanceId=="string"?answer.instanceId:void 0}function ignore2(){}var SupervisorDrain=class{constructor(child,shuttingDown,beginStopping=()=>{},relay){this.draining=!1,this.child=child,this.shuttingDown=shuttingDown,this.beginStopping=beginStopping,this.relay=relay}get active(){return this.draining}drain(){if(this.draining||this.shuttingDown())return;this.draining=!0,this.beginStopping(),supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;this.graceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),this.requestChildDrain()},graceMs),this.graceTimer.unref(),this.requestChildDrain()}stop(){this.graceTimer&&clearTimeout(this.graceTimer)}async acceptRequests(generation){let stop=watchDrainRequest(generation.drainRequestFile,request=>{supervisorLog(`drain requested (${request.reason})`),this.drain()});return await writeDrainWatch(generation.drainWatchFile,{pid:process.pid}).catch(cause=>{supervisorLog(`cannot advertise the drain request: ${errorMessage(cause)}`)}),stop}requestChildDrain(){let{child,relay}=this;if(!(child.pid===void 0||child.exitCode!==null||child.signalCode!==null)&&(relay&&writeDrainRequest(relay.file,{sender:relay.sender,reason:"supervisor_drain"}).catch(cause=>{supervisorLog(`could not relay the drain to the host: ${errorMessage(cause)}`)}),process.platform!=="win32"))try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`)}}};function drainOnPublicSocketLoss(path2,identity,settled,drain,onReplaced,pointer){return watchForSupersession({path:path2,identity,settled,...pointer&&{pointer}},loss=>{loss==="replaced"&&onReplaced(),supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drain.drain()})}var CHILD_IDENTITY_TICK_MS=500,CHILD_IDENTITY_READ_GAP_TICKS=10,CHILD_IDENTITY_READ_GAP_MAX_TICKS=120;function childLiveness(pid){try{return process.kill(pid,0),"alive"}catch(cause){return cause instanceof Error&&"code"in cause&&cause.code==="ESRCH"?"dead":"unknown"}}async function watchWin32ChildIdentity(child,shuttingDown,onGone){let pid=child.pid;if(pid===void 0)return()=>{};let readStartTime=()=>readProcessStartTime(pid,process.platform,1e3),baseline=await readStartTime().catch(()=>{}),adoptable=!0,suspect=!1,deadTicks=0,reading=!1,ended=!1,ticksUntilRead=0,readGapTicks=CHILD_IDENTITY_READ_GAP_TICKS,backOff=()=>{ticksUntilRead=readGapTicks,readGapTicks=Math.min(readGapTicks*2,CHILD_IDENTITY_READ_GAP_MAX_TICKS)},end=()=>{ended=!0,onGone()},settle2=current=>{if(!ended){if(baseline===void 0){current!==void 0&&adoptable&&childLiveness(pid)==="alive"?baseline=current:backOff();return}if(current!==void 0&&current!==baseline)return end();current===baseline&&(suspect=!1),backOff()}},timer=setInterval(()=>{if(ended||shuttingDown()||child.exitCode!==null||child.signalCode!==null)return;ticksUntilRead>0&&ticksUntilRead--;let liveness=childLiveness(pid);if(liveness==="dead"){if(deadTicks++,deadTicks>=2)return end();suspect=!0,adoptable=!1;return}(deadTicks>0||liveness==="unknown")&&(suspect=!0,adoptable=!1),deadTicks=0,!(!(baseline===void 0?adoptable:suspect)||reading||ticksUntilRead>0)&&(reading=!0,readStartTime().then(settle2,()=>{ended||backOff()}).finally(()=>{reading=!1}))},CHILD_IDENTITY_TICK_MS);return timer.unref?.(),()=>{ended=!0,clearInterval(timer)}}import{randomBytes as randomBytes5}from"node:crypto";import{readFile as readFile8}from"node:fs/promises";import{join as join16}from"node:path";init_process_identity();import{readFileSync as readFileSync6}from"node:fs";function readProcessStartTicks(pid,platform=process.platform){if(platform==="linux")try{let stat5=readFileSync6(`/proc/${pid}/stat`,"utf8"),ticks=stat5.slice(stat5.lastIndexOf(")")+2).split(" ")[19];return ticks!==void 0&&/^\d+$/.test(ticks)?ticks:void 0}catch{return}}init_process_identity();import{randomUUID as randomUUID4}from"node:crypto";import{realpathSync as realpathSync4}from"node:fs";import{mkdir as mkdir5,readFile as readFile7,writeFile as writeFile5}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join14}from"node:path";var INTERNAL_HOST_DIR_PREFIX="senpi-rpc-host-internal-",SHORT_TEMP_ROOT="/tmp";function internalHostDirRoots(){let primary=tmpdir();return canonicalPath(primary)!==canonicalPath(SHORT_TEMP_ROOT)?[primary,SHORT_TEMP_ROOT]:[Buffer.byteLength(primary)<Buffer.byteLength(SHORT_TEMP_ROOT)?primary:SHORT_TEMP_ROOT]}function canonicalPath(path2){try{return realpathSync4(path2)}catch{return path2}}function internalHostDirRoot(name){for(let root of internalHostDirRoots())if(Buffer.byteLength(join14(root,name,"host.sock"))<=MAX_SOCKET_PATH_BYTES)return root;let tried=internalHostDirRoots().map(root=>join14(root,name,"host.sock"));throw new Error(`internal_socket_path_too_long: every candidate exceeds ${MAX_SOCKET_PATH_BYTES} bytes (${tried.join(", ")}); set TMPDIR to a shorter directory`)}async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join14(baseDir,`internal-${randomUUID4()}`);return await mkdir5(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID4()}`,dir:dir2,secretPath:join14(dir2,"secret")}}let name=`${INTERNAL_HOST_DIR_PREFIX}${randomUUID4().slice(0,8)}`,dir=join14(internalHostDirRoot(name),name);return await mkdir5(dir,{recursive:!1,mode:448}),await writeFile5(join14(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join14(dir,"host.sock"),dir,secretPath:join14(dir,".secret")}}var CHILD_START_TIME_WAIT_MS=1e4,CHILD_START_TIME_UNHURRIED_MS=15e3;async function readChildStartTime(pid,timeoutMs){let identity=await readProcessIdentity(pid,process.platform,timeoutMs,void 0,"UTC");if(identity.kind==="error")throw identity.error;return identity.kind==="present"?identity.identity:void 0}async function recordChildPid(file2,pid,running){try{await writeJsonAtomic(file2,{pid,processStartTime:null});let processStartTime=await waitForStartTime(pid,CHILD_START_TIME_WAIT_MS,p=>readChildStartTime(p,1e3)).catch(()=>{})??await readChildStartTime(pid,CHILD_START_TIME_UNHURRIED_MS).catch(()=>{});if(processStartTime===void 0){supervisorLog(`host child pid ${pid} start time unreadable at recording`);return}if(!running())return;await writeJsonAtomic(file2,{pid,processStartTime})}catch(cause){supervisorLog(`could not record the host child pid: ${errorMessage(cause)}`)}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile7(settingsFile,"utf8"))}catch{return}}import{execFileSync as execFileSync2}from"node:child_process";import{closeSync as closeSync4,constants as constants4,fstatSync as fstatSync5,openSync,rmSync as rmSync2}from"node:fs";import{join as join15}from"node:path";var HOST_WATCH_LIFETIME_FIFO_ENV="SENPI_RPC_HOST_LIFETIME_FIFO";function prepareLifetimeBinding(hopDir,platform=process.platform){if(platform!=="linux")return{};let path2=join15(hopDir,"lifetime.fifo");try{return rmSync2(path2,{force:!0}),execFileSync2("mkfifo",["-m","600",path2],{stdio:"ignore"}),openSync(path2,constants4.O_RDWR),{lifetimeFifo:path2}}catch{return{}}}init_socket_transport();async function recordedOwnerStartTime(dir){if(dir!==void 0)try{let owner=JSON.parse(await readFile8(join16(dir,".owner"),"utf8")),start=owner!==null&&typeof owner=="object"?Reflect.get(owner,"processStartTime"):void 0;return typeof start=="string"?start:void 0}catch{return}}async function prepareInternalHop(daemonDir){let created=await createInternalSocketPath(daemonDir),internal={...created,secretPath:created.secretPath??socketSecretPath(created.socket)},internalSecret=process.platform==="win32"?await createSocketSecret(internal.secretPath):void 0,internalKey=process.platform==="win32"?void 0:randomBytes5(32);return{internal,internalSocket:internal.socket,internalSecret,internalKey,...internalKey&&internal.dir!==void 0?prepareLifetimeBinding(internal.dir):{},supervisorStart:internalKey?{time:await recordedOwnerStartTime(internal.dir),ticks:readProcessStartTicks(process.pid)}:void 0,transport:{...internalSecret?{internalSecret}:{},...internalKey?{internalKey}:{}}}}import childProcess from"node:child_process";import{closeSync as closeSync5}from"node:fs";var TABLE_ENV="SENPI_PRIVATE_FDS";function preparePrivateFdSpawn(options,hop={},forward=takePrivateDescriptors()){let env={...options.env??process.env};delete env[TABLE_ENV],delete env[PRIVATE_FDS_FINAL_ENV];let base=options.stdio??"pipe",stdio=typeof base=="string"?[base,base,base]:[...base],owned=[];if(forward.kind==="unparseable")env[TABLE_ENV]=UNPARSEABLE_TABLE;else if(forward.entries.size>0){let carries=!options.shell,table={};for(let[name,fd]of forward.entries){let descriptors=fd===null?[]:typeof fd=="number"?[fd]:fd;if(owned.push(...descriptors),fd!==null&&carries){for(let descriptor of descriptors){for(;stdio.length<=descriptor;)stdio.push("ignore");stdio[descriptor]=descriptor}table[name]=fd}else table[name]=null}env[TABLE_ENV]=JSON.stringify(table)}return env[TABLE_ENV]!==void 0&&hop.final&&(env[PRIVATE_FDS_FINAL_ENV]="1"),{options:{...options,env,stdio},close(){for(let fd of owned)closeSync5(fd)}}}function spawnWithPrivateFds(spawn,command,args,options,hop={}){let transfer=preparePrivateFdSpawn(options,hop);try{return spawn(command,args,transfer.options)}finally{transfer.close()}}init_config();import{extname}from"node:path";function runtimeExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}init_host_identity_env();import{read}from"node:fs";import{readFile as readFile10}from"node:fs/promises";import{join as join19}from"node:path";import{Readable}from"node:stream";import{randomUUID as randomUUID5}from"node:crypto";import{mkdir as mkdir6,readFile as readFile9,rename as rename4,rm as rm4,writeFile as writeFile6}from"node:fs/promises";import{dirname as dirname10}from"node:path";import{createHash as createHash3}from"node:crypto";import{tmpdir as tmpdir2}from"node:os";import{dirname as dirname9,join as join17}from"node:path";init_ownership_safe_lock();init_socket_transport();var LOCK_BUSY_WAIT_MS=100;function hostEnsureLockTarget(socket){return join17(tmpdir2(),"senpi-rpc-host-locks",createSocketLockName(socket))}function hostEnsureLockOptions(waitMs){return{retries:{retries:Math.ceil(waitMs/LOCK_BUSY_WAIT_MS),minTimeout:20,maxTimeout:LOCK_BUSY_WAIT_MS}}}function createSocketLockName(socket){return createHash3("sha256").update(socketLockAddress(socket),"utf8").digest("hex").slice(0,32)}function socketLockAddress(socket){return process.platform==="win32"||socket.startsWith("\0")?resolveSocketTransportAddress(socket,process.platform):canonicalEndpointPath(socket)}init_ownership_safe_lock();var ENDPOINT_FENCE_WAIT_MS=15e3;function endpointOwnerToken(endpoint,instanceId,generation){return{v:1,endpoint,instanceId,generation,pid:process.pid,nonce:randomUUID5()}}var ownerFile=socket=>`${hostEnsureLockTarget(socket)}.owner.json`;async function withEndpointFence(socket,run,hooks){let fence=`${hostEnsureLockTarget(socket)}.fence.lock`;await mkdir6(dirname10(fence),{recursive:!0});let release;try{release=await acquireOwnershipSafeLock(fence,{retries:{retries:0,minTimeout:1,maxTimeout:1}})}catch(cause){if(!isBusy(cause))throw cause;hooks?.onFenceBusy?.(),release=await acquireOwnershipSafeLock(fence,hostEnsureLockOptions(ENDPOINT_FENCE_WAIT_MS))}try{return await run()}finally{await release()}}async function readEndpointOwner(socket){let parsed;try{parsed=JSON.parse(await readFile9(ownerFile(socket),"utf8"))}catch{return}if(typeof parsed!="object"||parsed===null)return;let token=parsed;return token.v===1&&typeof token.instanceId=="string"&&typeof token.nonce=="string"?parsed:void 0}async function writeEndpointOwner(socket,token){let path2=ownerFile(socket),staged=`${path2}.${process.pid}.tmp`;await writeFile6(staged,`${JSON.stringify(token)}
102
+ `,{mode:384}),await rename3(tmpPath,path2)}async function unlinkOwnedSocket(socketPath,identity,log){if(process.platform==="win32"||socketPath.startsWith("\0"))return;let current;try{current=await statSocketIdentity(socketPath)}catch(cause){log(`socket ${socketPath} ownership could not be verified (${errorMessage2(cause)}); leaving it`);return}if(current!==void 0){if(identity===void 0){log(`socket path ${socketPath} ownership unknown; leaving it`);return}if(!sameSocketIdentity(current,identity)){log(`socket path ${socketPath} now owned by another host; leaving it`);return}try{await unlink2(socketPath)}catch(cause){isNodeErrorCode4(cause,"ENOENT")||log(`socket ${socketPath} removal failed (${errorMessage2(cause)})`)}}}async function shieldSocketDuringClose(socketPath,close){if(process.platform==="win32"||socketPath.startsWith("\0"))return close();let shieldPath=`${socketPath}.shield-${process.pid}`,shielded=!1;try{await statSocketIdentity(socketPath)!==void 0&&(await rename3(socketPath,shieldPath),shielded=!0)}catch{}try{await close()}finally{if(shielded)try{await rename3(shieldPath,socketPath)}catch{}}}function errorMessage2(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode4(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}async function adoptPublicSocket(bindSocket,publicSocket,expected){if(expected===void 0)throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);let current=await statSocketIdentity(publicSocket);if(current===void 0||current.dev!==expected.dev||current.ino!==expected.ino)throw new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);await rename3(bindSocket,publicSocket)}var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3,REPLACED_CONFIRMATIONS=3,IDENTITY_PROBE_TIMEOUT_MS=2e3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0)return endpoint.pointer===void 0?()=>{}:watchPointerSupersession(endpoint,endpoint.pointer,onLost);let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore2)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function watchPointerSupersession(endpoint,pointer,onLost){let probe=endpoint.probeInstanceId??probeAnsweringInstance,readPointer=endpoint.readPointerInstanceId??pointerInstanceId,agreeingPolls=0,observing=!1,lost=!1,observe=async()=>{let named=await readPointer(pointer.file);return named===void 0||named===pointer.instanceId?!1:await probe(endpoint.path)===named},timer=setInterval(()=>{lost||observing||endpoint.settled?.()===!0||(observing=!0,observe().then(replaced=>{lost||endpoint.settled?.()===!0||(agreeingPolls=replaced?agreeingPolls+1:0,!(agreeingPolls<REPLACED_CONFIRMATIONS)&&(lost=!0,clearInterval(timer),onLost("replaced")))},()=>{agreeingPolls=0}).finally(()=>{observing=!1}))},SUPERSESSION_POLL_MS);return timer.unref?.(),()=>clearInterval(timer)}async function pointerInstanceId(file2){try{let parsed=JSON.parse(await readFile6(file2,"utf8")),instanceId=typeof parsed=="object"&&parsed!==null?Reflect.get(parsed,"instance_id"):void 0;return typeof instanceId=="string"&&instanceId!==""?instanceId:void 0}catch{return}}async function probeAnsweringInstance(path2){let{isRecord:isRecord6,requestOnSocket:requestOnSocket2}=await Promise.resolve().then(()=>(init_host_socket_request(),host_socket_request_exports)),answer=await requestOnSocket2(path2,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},IDENTITY_PROBE_TIMEOUT_MS).catch(()=>{});return isRecord6(answer)&&typeof answer.instanceId=="string"?answer.instanceId:void 0}function ignore2(){}var SupervisorDrain=class{constructor(child,shuttingDown,beginStopping=()=>{},relay){this.draining=!1,this.child=child,this.shuttingDown=shuttingDown,this.beginStopping=beginStopping,this.relay=relay}get active(){return this.draining}drain(){if(this.draining||this.shuttingDown())return;this.draining=!0,this.beginStopping(),supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;this.graceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),this.requestChildDrain()},graceMs),this.graceTimer.unref(),this.requestChildDrain()}stop(){this.graceTimer&&clearTimeout(this.graceTimer)}async acceptRequests(generation){let stop=watchDrainRequest(generation.drainRequestFile,request=>{supervisorLog(`drain requested (${request.reason})`),this.drain()});return await writeDrainWatch(generation.drainWatchFile,{pid:process.pid}).catch(cause=>{supervisorLog(`cannot advertise the drain request: ${errorMessage(cause)}`)}),stop}requestChildDrain(){let{child,relay}=this;if(!(child.pid===void 0||child.exitCode!==null||child.signalCode!==null)&&(relay&&writeDrainRequest(relay.file,{sender:relay.sender,reason:"supervisor_drain"}).catch(cause=>{supervisorLog(`could not relay the drain to the host: ${errorMessage(cause)}`)}),process.platform!=="win32"))try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`)}}};function drainOnPublicSocketLoss(path2,identity,settled,drain,onReplaced,pointer){return watchForSupersession({path:path2,identity,settled,...pointer&&{pointer}},loss=>{loss==="replaced"&&onReplaced(),supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drain.drain()})}var CHILD_IDENTITY_TICK_MS=500,CHILD_IDENTITY_READ_GAP_TICKS=10,CHILD_IDENTITY_READ_GAP_MAX_TICKS=120;function childLiveness(pid){try{return process.kill(pid,0),"alive"}catch(cause){return cause instanceof Error&&"code"in cause&&cause.code==="ESRCH"?"dead":"unknown"}}async function watchWin32ChildIdentity(child,shuttingDown,onGone){let pid=child.pid;if(pid===void 0)return()=>{};let readStartTime=()=>readProcessStartTime(pid,process.platform,1e3),baseline=await readStartTime().catch(()=>{}),adoptable=!0,suspect=!1,deadTicks=0,reading=!1,ended=!1,ticksUntilRead=0,readGapTicks=CHILD_IDENTITY_READ_GAP_TICKS,backOff=()=>{ticksUntilRead=readGapTicks,readGapTicks=Math.min(readGapTicks*2,CHILD_IDENTITY_READ_GAP_MAX_TICKS)},end=()=>{ended=!0,onGone()},settle2=current=>{if(!ended){if(baseline===void 0){current!==void 0&&adoptable&&childLiveness(pid)==="alive"?baseline=current:backOff();return}if(current!==void 0&&current!==baseline)return end();current===baseline&&(suspect=!1),backOff()}},timer=setInterval(()=>{if(ended||shuttingDown()||child.exitCode!==null||child.signalCode!==null)return;ticksUntilRead>0&&ticksUntilRead--;let liveness=childLiveness(pid);if(liveness==="dead"){if(deadTicks++,deadTicks>=2)return end();suspect=!0,adoptable=!1;return}(deadTicks>0||liveness==="unknown")&&(suspect=!0,adoptable=!1),deadTicks=0,!(!(baseline===void 0?adoptable:suspect)||reading||ticksUntilRead>0)&&(reading=!0,readStartTime().then(settle2,()=>{ended||backOff()}).finally(()=>{reading=!1}))},CHILD_IDENTITY_TICK_MS);return timer.unref?.(),()=>{ended=!0,clearInterval(timer)}}import{randomBytes as randomBytes5}from"node:crypto";import{readFile as readFile8}from"node:fs/promises";import{join as join16}from"node:path";init_process_identity();import{readFileSync as readFileSync6}from"node:fs";function readProcessStartTicks(pid,platform=process.platform){if(platform==="linux")try{let stat5=readFileSync6(`/proc/${pid}/stat`,"utf8"),ticks=stat5.slice(stat5.lastIndexOf(")")+2).split(" ")[19];return ticks!==void 0&&/^\d+$/.test(ticks)?ticks:void 0}catch{return}}init_process_identity();import{randomUUID as randomUUID4}from"node:crypto";import{realpathSync as realpathSync4}from"node:fs";import{mkdir as mkdir5,readFile as readFile7,writeFile as writeFile5}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join14}from"node:path";var INTERNAL_HOST_DIR_PREFIX="senpi-rpc-host-internal-",SHORT_TEMP_ROOT="/tmp";function internalHostDirRoots(){let primary=tmpdir();return canonicalPath(primary)!==canonicalPath(SHORT_TEMP_ROOT)?[primary,SHORT_TEMP_ROOT]:[Buffer.byteLength(primary)<Buffer.byteLength(SHORT_TEMP_ROOT)?primary:SHORT_TEMP_ROOT]}function canonicalPath(path2){try{return realpathSync4(path2)}catch{return path2}}function internalHostDirRoot(name){for(let root of internalHostDirRoots())if(Buffer.byteLength(join14(root,name,"host.sock"))<=MAX_SOCKET_PATH_BYTES)return root;let tried=internalHostDirRoots().map(root=>join14(root,name,"host.sock"));throw new Error(`internal_socket_path_too_long: every candidate exceeds ${MAX_SOCKET_PATH_BYTES} bytes (${tried.join(", ")}); set TMPDIR to a shorter directory`)}async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join14(baseDir,`internal-${randomUUID4()}`);return await mkdir5(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID4()}`,dir:dir2,secretPath:join14(dir2,"secret")}}let name=`${INTERNAL_HOST_DIR_PREFIX}${randomUUID4().slice(0,8)}`,dir=join14(internalHostDirRoot(name),name);return await mkdir5(dir,{recursive:!1,mode:448}),await writeFile5(join14(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join14(dir,"host.sock"),dir,secretPath:join14(dir,".secret")}}var CHILD_START_TIME_WAIT_MS=1e4,CHILD_START_TIME_UNHURRIED_MS=15e3;async function readChildStartTime(pid,timeoutMs){let identity=await readProcessIdentity(pid,process.platform,timeoutMs,void 0,"UTC");if(identity.kind==="error")throw identity.error;return identity.kind==="present"?identity.identity:void 0}async function recordChildPid(file2,pid,running){try{await writeJsonAtomic(file2,{pid,processStartTime:null});let processStartTime=await waitForStartTime(pid,CHILD_START_TIME_WAIT_MS,p=>readChildStartTime(p,1e3)).catch(()=>{})??await readChildStartTime(pid,CHILD_START_TIME_UNHURRIED_MS).catch(()=>{});if(processStartTime===void 0){supervisorLog(`host child pid ${pid} start time unreadable at recording`);return}if(!running())return;await writeJsonAtomic(file2,{pid,processStartTime})}catch(cause){supervisorLog(`could not record the host child pid: ${errorMessage(cause)}`)}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile7(settingsFile,"utf8"))}catch{return}}import{execFileSync as execFileSync2}from"node:child_process";import{closeSync as closeSync4,constants as constants4,fstatSync as fstatSync6,openSync,rmSync as rmSync2}from"node:fs";import{join as join15}from"node:path";var HOST_WATCH_LIFETIME_FIFO_ENV="SENPI_RPC_HOST_LIFETIME_FIFO";function prepareLifetimeBinding(hopDir,platform=process.platform){if(platform!=="linux")return{};let path2=join15(hopDir,"lifetime.fifo");try{return rmSync2(path2,{force:!0}),execFileSync2("mkfifo",["-m","600",path2],{stdio:"ignore"}),openSync(path2,constants4.O_RDWR),{lifetimeFifo:path2}}catch{return{}}}init_socket_transport();async function recordedOwnerStartTime(dir){if(dir!==void 0)try{let owner=JSON.parse(await readFile8(join16(dir,".owner"),"utf8")),start=owner!==null&&typeof owner=="object"?Reflect.get(owner,"processStartTime"):void 0;return typeof start=="string"?start:void 0}catch{return}}async function prepareInternalHop(daemonDir){let created=await createInternalSocketPath(daemonDir),internal={...created,secretPath:created.secretPath??socketSecretPath(created.socket)},internalSecret=process.platform==="win32"?await createSocketSecret(internal.secretPath):void 0,internalKey=process.platform==="win32"?void 0:randomBytes5(32);return{internal,internalSocket:internal.socket,internalSecret,internalKey,...internalKey&&internal.dir!==void 0?prepareLifetimeBinding(internal.dir):{},supervisorStart:internalKey?{time:await recordedOwnerStartTime(internal.dir),ticks:readProcessStartTicks(process.pid)}:void 0,transport:{...internalSecret?{internalSecret}:{},...internalKey?{internalKey}:{}}}}import childProcess from"node:child_process";import{closeSync as closeSync5}from"node:fs";var TABLE_ENV="SENPI_PRIVATE_FDS";function preparePrivateFdSpawn(options,hop={},forward=takePrivateDescriptors()){let env={...options.env??process.env};delete env[TABLE_ENV],delete env[PRIVATE_FDS_FINAL_ENV];let base=options.stdio??"pipe",stdio=typeof base=="string"?[base,base,base]:[...base],owned=[];if(forward.kind==="unparseable")env[TABLE_ENV]=UNPARSEABLE_TABLE;else if(forward.entries.size>0){let carries=!options.shell,table={};for(let[name,fd]of forward.entries){let descriptors=fd===null?[]:typeof fd=="number"?[fd]:fd;if(owned.push(...descriptors),fd!==null&&carries){for(let descriptor of descriptors){for(;stdio.length<=descriptor;)stdio.push("ignore");stdio[descriptor]=descriptor}table[name]=fd}else table[name]=null}env[TABLE_ENV]=JSON.stringify(table)}return env[TABLE_ENV]!==void 0&&hop.final&&(env[PRIVATE_FDS_FINAL_ENV]="1"),{options:{...options,env,stdio},close(){for(let fd of owned)closeSync5(fd)}}}function spawnWithPrivateFds(spawn,command,args,options,hop={}){let transfer=preparePrivateFdSpawn(options,hop);try{return spawn(command,args,transfer.options)}finally{transfer.close()}}init_config();import{extname}from"node:path";function runtimeExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}init_host_identity_env();import{read}from"node:fs";import{readFile as readFile10}from"node:fs/promises";import{join as join19}from"node:path";import{Readable}from"node:stream";import{randomUUID as randomUUID5}from"node:crypto";import{mkdir as mkdir6,readFile as readFile9,rename as rename4,rm as rm4,writeFile as writeFile6}from"node:fs/promises";import{dirname as dirname10}from"node:path";import{createHash as createHash3}from"node:crypto";import{tmpdir as tmpdir2}from"node:os";import{dirname as dirname9,join as join17}from"node:path";init_ownership_safe_lock();init_socket_transport();var LOCK_BUSY_WAIT_MS=100;function hostEnsureLockTarget(socket){return join17(tmpdir2(),"senpi-rpc-host-locks",createSocketLockName(socket))}function hostEnsureLockOptions(waitMs){return{retries:{retries:Math.ceil(waitMs/LOCK_BUSY_WAIT_MS),minTimeout:20,maxTimeout:LOCK_BUSY_WAIT_MS}}}function createSocketLockName(socket){return createHash3("sha256").update(socketLockAddress(socket),"utf8").digest("hex").slice(0,32)}function socketLockAddress(socket){return process.platform==="win32"||socket.startsWith("\0")?resolveSocketTransportAddress(socket,process.platform):canonicalEndpointPath(socket)}init_ownership_safe_lock();var ENDPOINT_FENCE_WAIT_MS=15e3;function endpointOwnerToken(endpoint,instanceId,generation){return{v:1,endpoint,instanceId,generation,pid:process.pid,nonce:randomUUID5()}}var ownerFile=socket=>`${hostEnsureLockTarget(socket)}.owner.json`;async function withEndpointFence(socket,run,hooks){let fence=`${hostEnsureLockTarget(socket)}.fence.lock`;await mkdir6(dirname10(fence),{recursive:!0});let release;try{release=await acquireOwnershipSafeLock(fence,{retries:{retries:0,minTimeout:1,maxTimeout:1}})}catch(cause){if(!isBusy(cause))throw cause;hooks?.onFenceBusy?.(),release=await acquireOwnershipSafeLock(fence,hostEnsureLockOptions(ENDPOINT_FENCE_WAIT_MS))}try{return await run()}finally{await release()}}async function readEndpointOwner(socket){let parsed;try{parsed=JSON.parse(await readFile9(ownerFile(socket),"utf8"))}catch{return}if(typeof parsed!="object"||parsed===null)return;let token=parsed;return token.v===1&&typeof token.instanceId=="string"&&typeof token.nonce=="string"?parsed:void 0}async function writeEndpointOwner(socket,token){let path2=ownerFile(socket),staged=`${path2}.${process.pid}.tmp`;await writeFile6(staged,`${JSON.stringify(token)}
103
103
  `,{mode:384}),await rename4(staged,path2)}async function claimEndpoint(socket,token,bind){let claim2=async()=>{await bind?.(),await writeEndpointOwner(socket,token)};if(await readEndpointOwner(socket)){await withEndpointFence(socket,claim2);return}await mkdir6(dirname10(ownerFile(socket)),{recursive:!0}),await claim2()}async function adoptEndpoint(options){let{publicSocket}=options;await withEndpointFence(publicSocket,async()=>{if(options.granted&&!await options.granted())throw new Error(`${publicSocket}: the launcher revoked this generation's adoption grant`);let current=await readEndpointOwner(publicSocket);if(options.expectedOwner!==void 0&&current&&current.instanceId!==options.expectedOwner)throw new Error(`${publicSocket}: owner token names ${current.instanceId}, not ${options.expectedOwner}; refusing to replace it`);await adoptPublicSocket(options.bindSocket,publicSocket,options.expected),await writeEndpointOwner(publicSocket,options.token)},options.hooks)}async function unlinkOwnedEndpoint(socket,identity,instanceId,log,hooks){await withEndpointFence(socket,async()=>{let current=await readEndpointOwner(socket);if(current&&current.instanceId!==instanceId){log(`socket path ${socket} is owned by generation ${current.instanceId} now; leaving it`);return}await hooks?.afterValidate?.(),await unlinkOwnedSocket(socket,identity,log),current&&await rm4(ownerFile(socket),{force:!0})})}async function closeShieldedEndpoint(socket,close){await withEndpointFence(socket,()=>shieldSocketDuringClose(socket,close))}import{lstat as lstat4,mkdir as mkdir8,unlink as unlink4}from"node:fs/promises";import{createConnection as createConnection5,createServer}from"node:net";import{dirname as dirname11}from"node:path";import{StringDecoder as StringDecoder2}from"node:string_decoder";init_jsonl();init_rpc_auth_proof();function proxyWithAdmission(client,internal,admission,auth,launchProven=!1){let reply=chunk=>write3(client,auth?auth.response(chunk.toString()):chunk),pending=[],refused=new Set,protocols=0,refusals=Promise.resolve(),unsubscribe=admission.onStop(()=>(refusals=refusePending(),refusals));async function refusePending(){let ids=pending.splice(0);for(let id of ids)refused.add(id);try{for(let id of ids)await reply(serializeJsonLine(hostStoppingResponse(id,"open_session",admission)))}catch{fail()}}client.once("close",()=>{unsubscribe(),internal?.destroy()});let fail=()=>{internal?.destroy(),client.destroy()};client.once("error",fail),internal?.once("error",()=>{admission.stopping||fail()}),requests().catch(()=>{admission.stopping||fail()}),internal&&responses(internal).catch(()=>{admission.stopping||fail()});async function requests(){internal&&launchProven&&internal.write(`${JSON.stringify({type:RPC_LAUNCH_PROOF_RECORD})}
104
104
  `);for await(let line of lines(auth?.input??client,MAX_RPC_LINE_CHARACTERS)){if(line===void 0){await reply(serializeJsonLine({type:"response",command:"parse",success:!1,error:`RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`}));continue}let request=record(line);if(!auth&&request?.type===RPC_LAUNCH_PROOF_RECORD){await reply(serializeJsonLine(launchProofRecordRefusal(request.id)));continue}admission.stopping&&request?.type==="get_protocol_info"?await reply(serializeJsonLine({id:request.id,type:"response",command:request.type,success:!0,data:admission.protocol()})):admission.stopping&&(request?.type==="open_session"||!internal)?await reply(serializeJsonLine(hostStoppingResponse(request?.id,String(request?.type??"parse"),admission))):internal&&(request?.type==="open_session"&&pending.push(request.id),request?.type==="get_protocol_info"&&protocols++,await write3(internal,`${line}
105
105
  `))}internal?.end()}async function responses(source){let fragments=[];for await(let chunk of source){let newline=chunk.lastIndexOf(10);if(newline===-1){fragments.push(chunk);continue}let complete=chunk.subarray(0,newline+1);if(!auth&&pending.length===0&&protocols===0&&refused.size===0){client.cork();let written;try{for(let fragment of fragments)client.write(fragment);written=write3(client,complete)}finally{client.uncork()}await written}else{let batch=fragments.length>0?Buffer.concat([...fragments,complete]):complete;await reply(filterReplies(batch))}fragments=newline+1<chunk.length?[chunk.subarray(newline+1)]:[]}fragments.length>0&&await reply(filterReplies(Buffer.concat(fragments))),await refusals,client.end(()=>client.destroy())}function filterReplies(batch){if(pending.length===0&&protocols===0&&refused.size===0)return batch;let output2=[],changed=!1;for(let start=0;start<batch.length;){let newline=batch.indexOf(10,start),end=newline===-1?batch.length:newline+1,line=batch.subarray(start,end);start=end;let response=line.includes('"open_session"')||line.includes('"get_protocol_info"')?record(line.toString("utf8")):void 0;if(response?.type==="response"&&response.command==="open_session"){if(refused.has(response.id)){changed=!0;continue}let index=pending.indexOf(response.id);index!==-1&&pending.splice(index,1)}if(response?.type==="response"&&response.command==="get_protocol_info"&&(protocols=Math.max(0,protocols-1),response.success===!0)){isRecord5(response.data)&&admission.observe(response.data),output2.push(Buffer.from(serializeJsonLine({...response,data:admission.protocol()}))),changed=!0;continue}output2.push(line)}return changed?Buffer.concat(output2):batch}}async function write3(socket,line){await new Promise((resolve5,reject)=>{socket.write(line,error62=>error62?reject(error62):resolve5())})}async function*lines(socket,limit){let decoder=new StringDecoder2("utf8"),buffer="",discarding=!1;for await(let chunk of socket){let text=typeof chunk=="string"?chunk:decoder.write(chunk),offset=0;for(;offset<text.length;){let newline=text.indexOf(`