@qqbrowser/qbot-dsh 0.0.11 → 0.0.12

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 (304) hide show
  1. package/lib/bin.js +1 -1
  2. package/lib/{dump-config-BD79jvHi.js → dump-config-xQTUTTDD.js} +1 -1
  3. package/lib/{plugin-B3Ecl7VN.js → plugin-DNAeLZbb.js} +1 -1
  4. package/lib/profile-boot-BkordgJK.js +1 -0
  5. package/node_modules/@deepseek-ai/cordis-plugin-group/package.json +1 -1
  6. package/node_modules/@deepseek-ai/cordis-plugin-hmr/lib/index.js +2 -2
  7. package/node_modules/@deepseek-ai/dsh-agent/lib/index.js +1 -1
  8. package/node_modules/@deepseek-ai/dsh-agent/package.json +1 -1
  9. package/node_modules/@deepseek-ai/dsh-agent-default-model/package.json +1 -1
  10. package/node_modules/@deepseek-ai/dsh-agent-instructions/lib/index.js +3 -3
  11. package/node_modules/@deepseek-ai/dsh-agent-instructions/package.json +1 -1
  12. package/node_modules/@deepseek-ai/dsh-agent-loop/package.json +1 -1
  13. package/node_modules/@deepseek-ai/dsh-agent-presets/package.json +1 -1
  14. package/node_modules/@deepseek-ai/dsh-agent-tool-presentation/package.json +1 -1
  15. package/node_modules/@deepseek-ai/dsh-anonymous-user-id/package.json +1 -1
  16. package/node_modules/@deepseek-ai/dsh-api-gateway/package.json +1 -1
  17. package/node_modules/@deepseek-ai/dsh-api-remotes/lib/client.js +2 -2
  18. package/node_modules/@deepseek-ai/dsh-api-remotes/package.json +1 -1
  19. package/node_modules/@deepseek-ai/dsh-app-boot/lib/index.js +12 -12
  20. package/node_modules/@deepseek-ai/dsh-app-boot/package.json +1 -1
  21. package/node_modules/@deepseek-ai/dsh-atomic-write/package.json +1 -1
  22. package/node_modules/@deepseek-ai/dsh-attachment/package.json +1 -1
  23. package/node_modules/@deepseek-ai/dsh-attachment-local/lib/index.js +1 -1
  24. package/node_modules/@deepseek-ai/dsh-attachment-local/package.json +1 -1
  25. package/node_modules/@deepseek-ai/dsh-base/cordis.patch.yml +2 -2
  26. package/node_modules/@deepseek-ai/dsh-base/package.json +1 -1
  27. package/node_modules/@deepseek-ai/dsh-bash-local/lib/index.js +1 -1
  28. package/node_modules/@deepseek-ai/dsh-bash-local/package.json +1 -1
  29. package/node_modules/@deepseek-ai/dsh-bash-sandbox/package.json +1 -1
  30. package/node_modules/@deepseek-ai/dsh-brand/package.json +1 -1
  31. package/node_modules/@deepseek-ai/dsh-client-connection/lib/client.js +6 -6
  32. package/node_modules/@deepseek-ai/dsh-client-connection/lib/index.js +2 -2
  33. package/node_modules/@deepseek-ai/dsh-client-connection/package.json +1 -1
  34. package/node_modules/@deepseek-ai/dsh-client-hmr/lib/client.js +1 -1
  35. package/node_modules/@deepseek-ai/dsh-client-hmr/package.json +1 -1
  36. package/node_modules/@deepseek-ai/dsh-client-locale/lib/client.js +1 -1
  37. package/node_modules/@deepseek-ai/dsh-client-locale/package.json +1 -1
  38. package/node_modules/@deepseek-ai/dsh-client-modules/package.json +1 -1
  39. package/node_modules/@deepseek-ai/dsh-client-runtime/lib/client.js +2 -2
  40. package/node_modules/@deepseek-ai/dsh-client-runtime/package.json +1 -1
  41. package/node_modules/@deepseek-ai/dsh-client-schema-form/package.json +1 -1
  42. package/node_modules/@deepseek-ai/dsh-client-ui-agent-preset/lib/client.js +1 -1
  43. package/node_modules/@deepseek-ai/dsh-client-ui-agent-preset/package.json +1 -1
  44. package/node_modules/@deepseek-ai/dsh-client-ui-attachment/package.json +1 -1
  45. package/node_modules/@deepseek-ai/dsh-client-ui-commands/lib/client.js +1 -1
  46. package/node_modules/@deepseek-ai/dsh-client-ui-commands/package.json +1 -1
  47. package/node_modules/@deepseek-ai/dsh-client-ui-conversation/lib/client.js +6 -6
  48. package/node_modules/@deepseek-ai/dsh-client-ui-conversation/package.json +1 -1
  49. package/node_modules/@deepseek-ai/dsh-client-ui-cordis/lib/client.js +1 -1
  50. package/node_modules/@deepseek-ai/dsh-client-ui-cordis/package.json +1 -1
  51. package/node_modules/@deepseek-ai/dsh-client-ui-deliverables/lib/client.js +1 -1
  52. package/node_modules/@deepseek-ai/dsh-client-ui-deliverables/package.json +1 -1
  53. package/node_modules/@deepseek-ai/dsh-client-ui-directory-picker-browse/lib/client.js +1 -1
  54. package/node_modules/@deepseek-ai/dsh-client-ui-directory-picker-browse/package.json +1 -1
  55. package/node_modules/@deepseek-ai/dsh-client-ui-directory-picker-native/package.json +1 -1
  56. package/node_modules/@deepseek-ai/dsh-client-ui-goal/lib/client.js +1 -1
  57. package/node_modules/@deepseek-ai/dsh-client-ui-goal/package.json +1 -1
  58. package/node_modules/@deepseek-ai/dsh-client-ui-input-trigger/lib/client.js +1 -1
  59. package/node_modules/@deepseek-ai/dsh-client-ui-input-trigger/package.json +1 -1
  60. package/node_modules/@deepseek-ai/dsh-client-ui-jobs/lib/client.js +1 -1
  61. package/node_modules/@deepseek-ai/dsh-client-ui-jobs/package.json +1 -1
  62. package/node_modules/@deepseek-ai/dsh-client-ui-layout/lib/client.js +1 -1
  63. package/node_modules/@deepseek-ai/dsh-client-ui-layout/package.json +1 -1
  64. package/node_modules/@deepseek-ai/dsh-client-ui-message-feedback/lib/client.js +1 -1
  65. package/node_modules/@deepseek-ai/dsh-client-ui-message-feedback/package.json +1 -1
  66. package/node_modules/@deepseek-ai/dsh-client-ui-model-selection/lib/client.js +1 -1
  67. package/node_modules/@deepseek-ai/dsh-client-ui-model-selection/package.json +1 -1
  68. package/node_modules/@deepseek-ai/dsh-client-ui-permission-presets/lib/client.js +1 -1
  69. package/node_modules/@deepseek-ai/dsh-client-ui-permission-presets/package.json +1 -1
  70. package/node_modules/@deepseek-ai/dsh-client-ui-plan/lib/client.js +1 -1
  71. package/node_modules/@deepseek-ai/dsh-client-ui-plan/package.json +1 -1
  72. package/node_modules/@deepseek-ai/dsh-client-ui-primitives/lib/index.js +11 -11
  73. package/node_modules/@deepseek-ai/dsh-client-ui-primitives/package.json +1 -1
  74. package/node_modules/@deepseek-ai/dsh-client-ui-settings/package.json +1 -1
  75. package/node_modules/@deepseek-ai/dsh-client-ui-settings-general/lib/client.js +1 -1
  76. package/node_modules/@deepseek-ai/dsh-client-ui-settings-general/package.json +1 -1
  77. package/node_modules/@deepseek-ai/dsh-client-ui-settings-models/lib/client.js +1 -1
  78. package/node_modules/@deepseek-ai/dsh-client-ui-settings-models/package.json +1 -1
  79. package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugin-inventory/lib/client.js +1 -1
  80. package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugin-inventory/package.json +1 -1
  81. package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugins/lib/client.js +1 -1
  82. package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugins/package.json +1 -1
  83. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/lib/client.js +1 -1
  84. package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/package.json +1 -1
  85. package/node_modules/@deepseek-ai/dsh-client-ui-skill/lib/client.js +1 -1
  86. package/node_modules/@deepseek-ai/dsh-client-ui-skill/package.json +1 -1
  87. package/node_modules/@deepseek-ai/dsh-client-ui-slots/lib/index.js +1 -1
  88. package/node_modules/@deepseek-ai/dsh-client-ui-slots/package.json +1 -1
  89. package/node_modules/@deepseek-ai/dsh-client-ui-subagent/lib/client.js +1 -1
  90. package/node_modules/@deepseek-ai/dsh-client-ui-subagent/package.json +1 -1
  91. package/node_modules/@deepseek-ai/dsh-client-ui-theme/lib/client.js +1 -1
  92. package/node_modules/@deepseek-ai/dsh-client-ui-theme/package.json +1 -1
  93. package/node_modules/@deepseek-ai/dsh-client-ui-tool/lib/client.js +1 -1
  94. package/node_modules/@deepseek-ai/dsh-client-ui-tool/package.json +1 -1
  95. package/node_modules/@deepseek-ai/dsh-client-ui-trajectory/lib/client.js +13 -13
  96. package/node_modules/@deepseek-ai/dsh-client-ui-trajectory/package.json +1 -1
  97. package/node_modules/@deepseek-ai/dsh-client-ui-user-questions/lib/client.js +1 -1
  98. package/node_modules/@deepseek-ai/dsh-client-ui-user-questions/package.json +1 -1
  99. package/node_modules/@deepseek-ai/dsh-client-ui-workflow-run/lib/client.js +1 -1
  100. package/node_modules/@deepseek-ai/dsh-client-ui-workflow-run/package.json +1 -1
  101. package/node_modules/@deepseek-ai/dsh-client-ui-workspace/lib/client.js +1 -1
  102. package/node_modules/@deepseek-ai/dsh-client-ui-workspace/package.json +1 -1
  103. package/node_modules/@deepseek-ai/dsh-client-web/package.json +1 -1
  104. package/node_modules/@deepseek-ai/dsh-client-web-react/lib/index.js +1 -1
  105. package/node_modules/@deepseek-ai/dsh-client-web-react/package.json +1 -1
  106. package/node_modules/@deepseek-ai/dsh-cmdline/package.json +1 -1
  107. package/node_modules/@deepseek-ai/dsh-code-runtime/package.json +1 -1
  108. package/node_modules/@deepseek-ai/dsh-code-runtime-worker-thread/lib/index.js +2 -2
  109. package/node_modules/@deepseek-ai/dsh-code-runtime-worker-thread/lib/worker.cjs +4 -2
  110. package/node_modules/@deepseek-ai/dsh-code-runtime-worker-thread/package.json +1 -1
  111. package/node_modules/@deepseek-ai/dsh-command-compact/package.json +1 -1
  112. package/node_modules/@deepseek-ai/dsh-command-feedback/package.json +1 -1
  113. package/node_modules/@deepseek-ai/dsh-command-goal/package.json +1 -1
  114. package/node_modules/@deepseek-ai/dsh-commands/package.json +1 -1
  115. package/node_modules/@deepseek-ai/dsh-compaction/package.json +1 -1
  116. package/node_modules/@deepseek-ai/dsh-compaction-basic/lib/index.js +1 -1
  117. package/node_modules/@deepseek-ai/dsh-compaction-basic/package.json +1 -1
  118. package/node_modules/@deepseek-ai/dsh-compaction-tool-result-pruner/package.json +1 -1
  119. package/node_modules/@deepseek-ai/dsh-content-review/package.json +1 -1
  120. package/node_modules/@deepseek-ai/dsh-cordis-client-runner/lib/client.js +7 -7
  121. package/node_modules/@deepseek-ai/dsh-cordis-client-runner/package.json +1 -1
  122. package/node_modules/@deepseek-ai/dsh-cordis-host-runner/package.json +1 -1
  123. package/node_modules/@deepseek-ai/dsh-credentials/package.json +1 -1
  124. package/node_modules/@deepseek-ai/dsh-credentials-local/package.json +1 -1
  125. package/node_modules/@deepseek-ai/dsh-fs/package.json +1 -1
  126. package/node_modules/@deepseek-ai/dsh-fs-local/lib/index.js +4 -4
  127. package/node_modules/@deepseek-ai/dsh-fs-local/package.json +1 -1
  128. package/node_modules/@deepseek-ai/dsh-fs-observation-policy/package.json +1 -1
  129. package/node_modules/@deepseek-ai/dsh-fs-sandbox/package.json +1 -1
  130. package/node_modules/@deepseek-ai/dsh-goal/package.json +1 -1
  131. package/node_modules/@deepseek-ai/dsh-goal-round-driver/package.json +1 -1
  132. package/node_modules/@deepseek-ai/dsh-headless/package.json +1 -1
  133. package/node_modules/@deepseek-ai/dsh-home-paths/lib/index.js +1 -1
  134. package/node_modules/@deepseek-ai/dsh-home-paths/package.json +1 -1
  135. package/node_modules/@deepseek-ai/dsh-home-quarantine-macos/package.json +1 -1
  136. package/node_modules/@deepseek-ai/dsh-host-apiproxy/lib/index.js +4 -4
  137. package/node_modules/@deepseek-ai/dsh-host-apiproxy/package.json +1 -1
  138. package/node_modules/@deepseek-ai/dsh-host-directory-picker/package.json +1 -1
  139. package/node_modules/@deepseek-ai/dsh-host-directory-picker-auto/package.json +1 -1
  140. package/node_modules/@deepseek-ai/dsh-host-directory-picker-browse/package.json +1 -1
  141. package/node_modules/@deepseek-ai/dsh-host-directory-picker-native/lib/worker.cjs +9 -7
  142. package/node_modules/@deepseek-ai/dsh-host-directory-picker-native/package.json +1 -1
  143. package/node_modules/@deepseek-ai/dsh-host-frontend-static/package.json +1 -1
  144. package/node_modules/@deepseek-ai/dsh-host-plugin-inventory/package.json +1 -1
  145. package/node_modules/@deepseek-ai/dsh-host-webserver/package.json +1 -1
  146. package/node_modules/@deepseek-ai/dsh-invariants/package.json +1 -1
  147. package/node_modules/@deepseek-ai/dsh-jobs/package.json +1 -1
  148. package/node_modules/@deepseek-ai/dsh-jobs-local/package.json +1 -1
  149. package/node_modules/@deepseek-ai/dsh-launch-environment/package.json +1 -1
  150. package/node_modules/@deepseek-ai/dsh-llm/lib/invariant.js +1 -1
  151. package/node_modules/@deepseek-ai/dsh-llm/package.json +1 -1
  152. package/node_modules/@deepseek-ai/dsh-llm-deepseek/lib/index.js +1 -1
  153. package/node_modules/@deepseek-ai/dsh-llm-deepseek/package.json +1 -1
  154. package/node_modules/@deepseek-ai/dsh-llm-gateway-openai/lib/index.js +1 -1
  155. package/node_modules/@deepseek-ai/dsh-llm-gateway-openai/package.json +1 -1
  156. package/node_modules/@deepseek-ai/dsh-llm-pi-ai/lib/index.js +1 -1
  157. package/node_modules/@deepseek-ai/dsh-llm-pi-ai/package.json +1 -1
  158. package/node_modules/@deepseek-ai/dsh-llm-retry/package.json +1 -1
  159. package/node_modules/@deepseek-ai/dsh-mcp-client/lib/index.js +2 -2
  160. package/node_modules/@deepseek-ai/dsh-mcp-client/package.json +1 -1
  161. package/node_modules/@deepseek-ai/dsh-message-feedback/package.json +1 -1
  162. package/node_modules/@deepseek-ai/dsh-native-command/package.json +1 -1
  163. package/node_modules/@deepseek-ai/dsh-output-retention/lib/index.js +1 -1
  164. package/node_modules/@deepseek-ai/dsh-output-retention/package.json +1 -1
  165. package/node_modules/@deepseek-ai/dsh-permission-presets/lib/index.js +1 -1
  166. package/node_modules/@deepseek-ai/dsh-permission-presets/package.json +1 -1
  167. package/node_modules/@deepseek-ai/dsh-persona/package.json +1 -1
  168. package/node_modules/@deepseek-ai/dsh-plan-mode/package.json +1 -1
  169. package/node_modules/@deepseek-ai/dsh-pwsh-local/lib/index.js +1 -1
  170. package/node_modules/@deepseek-ai/dsh-pwsh-local/package.json +1 -1
  171. package/node_modules/@deepseek-ai/dsh-pwsh-sandbox/package.json +1 -1
  172. package/node_modules/@deepseek-ai/dsh-qb-auth/lib/index.js +3 -3
  173. package/node_modules/@deepseek-ai/dsh-qb-auth/package.json +1 -1
  174. package/node_modules/@deepseek-ai/dsh-repeat-tool-reminder/package.json +1 -1
  175. package/node_modules/@deepseek-ai/dsh-sandbox/package.json +1 -1
  176. package/node_modules/@deepseek-ai/dsh-sandbox-local/package.json +1 -1
  177. package/node_modules/@deepseek-ai/dsh-sandbox-policy/package.json +1 -1
  178. package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/index.js +1 -1
  179. package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/runner.js +1 -1
  180. package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/types-D2_FQYSK.js +1 -0
  181. package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/package.json +1 -1
  182. package/node_modules/@deepseek-ai/dsh-schedule/lib/index.js +1 -1
  183. package/node_modules/@deepseek-ai/dsh-schedule/package.json +1 -1
  184. package/node_modules/@deepseek-ai/dsh-scope/package.json +1 -1
  185. package/node_modules/@deepseek-ai/dsh-session/lib/index.js +1 -1
  186. package/node_modules/@deepseek-ai/dsh-session/lib/invariant.js +1 -1
  187. package/node_modules/@deepseek-ai/dsh-session/package.json +1 -1
  188. package/node_modules/@deepseek-ai/dsh-session-checkpoint-policy/package.json +1 -1
  189. package/node_modules/@deepseek-ai/dsh-session-log-export/lib/client.js +1 -1
  190. package/node_modules/@deepseek-ai/dsh-session-log-export/package.json +1 -1
  191. package/node_modules/@deepseek-ai/dsh-session-persistence/lib/index.js +1 -1
  192. package/node_modules/@deepseek-ai/dsh-session-persistence/package.json +1 -1
  193. package/node_modules/@deepseek-ai/dsh-session-persistence-jsonl/lib/index.js +1 -1
  194. package/node_modules/@deepseek-ai/dsh-session-persistence-jsonl/package.json +1 -1
  195. package/node_modules/@deepseek-ai/dsh-session-projection/package.json +1 -1
  196. package/node_modules/@deepseek-ai/dsh-session-projection-cache/package.json +1 -1
  197. package/node_modules/@deepseek-ai/dsh-session-query/package.json +1 -1
  198. package/node_modules/@deepseek-ai/dsh-session-query-sqlite/package.json +1 -1
  199. package/node_modules/@deepseek-ai/dsh-session-reference/lib/index.js +4 -4
  200. package/node_modules/@deepseek-ai/dsh-session-reference/package.json +1 -1
  201. package/node_modules/@deepseek-ai/dsh-session-stats/package.json +1 -1
  202. package/node_modules/@deepseek-ai/dsh-session-telemetry/package.json +1 -1
  203. package/node_modules/@deepseek-ai/dsh-session-telemetry-otel/package.json +1 -1
  204. package/node_modules/@deepseek-ai/dsh-session-title/lib/index.js +2 -2
  205. package/node_modules/@deepseek-ai/dsh-session-title/package.json +1 -1
  206. package/node_modules/@deepseek-ai/dsh-session-title-first-prompt-llm/package.json +1 -1
  207. package/node_modules/@deepseek-ai/dsh-session-title-llm/lib/index.js +3 -3
  208. package/node_modules/@deepseek-ai/dsh-session-title-llm/package.json +1 -1
  209. package/node_modules/@deepseek-ai/dsh-settings/lib/invariant.js +1 -1
  210. package/node_modules/@deepseek-ai/dsh-settings/package.json +1 -1
  211. package/node_modules/@deepseek-ai/dsh-settings-file/package.json +1 -1
  212. package/node_modules/@deepseek-ai/dsh-shell/package.json +1 -1
  213. package/node_modules/@deepseek-ai/dsh-shell-env/package.json +1 -1
  214. package/node_modules/@deepseek-ai/dsh-skill/package.json +1 -1
  215. package/node_modules/@deepseek-ai/dsh-skill-badge/package.json +1 -1
  216. package/node_modules/@deepseek-ai/dsh-skill-filesystem/lib/index.js +1 -1
  217. package/node_modules/@deepseek-ai/dsh-skill-filesystem/package.json +1 -1
  218. package/node_modules/@deepseek-ai/dsh-spill/package.json +1 -1
  219. package/node_modules/@deepseek-ai/dsh-spill-local/lib/index.js +1 -1
  220. package/node_modules/@deepseek-ai/dsh-spill-local/package.json +1 -1
  221. package/node_modules/@deepseek-ai/dsh-spill-policy/lib/index.js +2 -2
  222. package/node_modules/@deepseek-ai/dsh-spill-policy/package.json +1 -1
  223. package/node_modules/@deepseek-ai/dsh-storage/package.json +1 -1
  224. package/node_modules/@deepseek-ai/dsh-storage-domain/lib/invariant.js +1 -1
  225. package/node_modules/@deepseek-ai/dsh-storage-domain/package.json +1 -1
  226. package/node_modules/@deepseek-ai/dsh-storage-json/package.json +1 -1
  227. package/node_modules/@deepseek-ai/dsh-subagent/lib/index.js +1 -1
  228. package/node_modules/@deepseek-ai/dsh-subagent/package.json +1 -1
  229. package/node_modules/@deepseek-ai/dsh-subagent-fork-in-process/package.json +1 -1
  230. package/node_modules/@deepseek-ai/dsh-subagent-in-process-driver/package.json +1 -1
  231. package/node_modules/@deepseek-ai/dsh-subagent-spawn-in-process/package.json +1 -1
  232. package/node_modules/@deepseek-ai/dsh-subprocess/package.json +1 -1
  233. package/node_modules/@deepseek-ai/dsh-subprocess-local/package.json +1 -1
  234. package/node_modules/@deepseek-ai/dsh-system-prompt/package.json +1 -1
  235. package/node_modules/@deepseek-ai/dsh-terminal/package.json +1 -1
  236. package/node_modules/@deepseek-ai/dsh-terminal-bash/lib/index.js +2 -2
  237. package/node_modules/@deepseek-ai/dsh-terminal-bash/package.json +1 -1
  238. package/node_modules/@deepseek-ai/dsh-time-context/lib/index.js +1 -1
  239. package/node_modules/@deepseek-ai/dsh-time-context/lib/invariant.js +1 -1
  240. package/node_modules/@deepseek-ai/dsh-time-context/package.json +1 -1
  241. package/node_modules/@deepseek-ai/dsh-timeout/package.json +1 -1
  242. package/node_modules/@deepseek-ai/dsh-tmux-context/package.json +1 -1
  243. package/node_modules/@deepseek-ai/dsh-token-meter/lib/index.js +1 -1
  244. package/node_modules/@deepseek-ai/dsh-token-meter/package.json +1 -1
  245. package/node_modules/@deepseek-ai/dsh-tool-ask-user/package.json +1 -1
  246. package/node_modules/@deepseek-ai/dsh-tool-bash/package.json +1 -1
  247. package/node_modules/@deepseek-ai/dsh-tool-bash-persistent/package.json +1 -1
  248. package/node_modules/@deepseek-ai/dsh-tool-call-timeout-policy/package.json +1 -1
  249. package/node_modules/@deepseek-ai/dsh-tool-cordis/package.json +1 -1
  250. package/node_modules/@deepseek-ai/dsh-tool-fs/lib/index.js +2 -2
  251. package/node_modules/@deepseek-ai/dsh-tool-fs/package.json +1 -1
  252. package/node_modules/@deepseek-ai/dsh-tool-fs-search/lib/index.js +1 -1
  253. package/node_modules/@deepseek-ai/dsh-tool-fs-search/package.json +1 -1
  254. package/node_modules/@deepseek-ai/dsh-tool-goal/package.json +1 -1
  255. package/node_modules/@deepseek-ai/dsh-tool-jobs/package.json +1 -1
  256. package/node_modules/@deepseek-ai/dsh-tool-pwsh/package.json +1 -1
  257. package/node_modules/@deepseek-ai/dsh-tool-ralph/lib/index.js +1 -1
  258. package/node_modules/@deepseek-ai/dsh-tool-ralph/package.json +1 -1
  259. package/node_modules/@deepseek-ai/dsh-tool-skill/package.json +1 -1
  260. package/node_modules/@deepseek-ai/dsh-tool-str-replace-editor/lib/index.js +6 -6
  261. package/node_modules/@deepseek-ai/dsh-tool-str-replace-editor/package.json +1 -1
  262. package/node_modules/@deepseek-ai/dsh-tool-subagent/package.json +1 -1
  263. package/node_modules/@deepseek-ai/dsh-tool-subagent-control/package.json +1 -1
  264. package/node_modules/@deepseek-ai/dsh-tool-subagent-report/package.json +1 -1
  265. package/node_modules/@deepseek-ai/dsh-tool-todo/package.json +1 -1
  266. package/node_modules/@deepseek-ai/dsh-tool-web/package.json +1 -1
  267. package/node_modules/@deepseek-ai/dsh-tool-workflow/lib/index.js +2 -2
  268. package/node_modules/@deepseek-ai/dsh-tool-workflow/package.json +1 -1
  269. package/node_modules/@deepseek-ai/dsh-tools/lib/index.js +26 -26
  270. package/node_modules/@deepseek-ai/dsh-tools/package.json +1 -1
  271. package/node_modules/@deepseek-ai/dsh-typert-loader/package.json +1 -1
  272. package/node_modules/@deepseek-ai/dsh-typert-protocol/package.json +1 -1
  273. package/node_modules/@deepseek-ai/dsh-typert-registry/package.json +1 -1
  274. package/node_modules/@deepseek-ai/dsh-user-approval/package.json +1 -1
  275. package/node_modules/@deepseek-ai/dsh-user-questions/package.json +1 -1
  276. package/node_modules/@deepseek-ai/dsh-web/lib/index.js +1 -1
  277. package/node_modules/@deepseek-ai/dsh-web/package.json +1 -1
  278. package/node_modules/@deepseek-ai/dsh-web-app/package.json +1 -1
  279. package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/{index-Dqw48FrP.js → index-BQQQ5Qt-.js} +2 -2
  280. package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/cpp-DddhVWhK.js +1 -0
  281. package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/{php-D-uCvoST.js → php-9bx0az3O.js} +1 -1
  282. package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/{ruby-DEItuUFs.js → ruby-HDLHRjSL.js} +1 -1
  283. package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/swift-C2oV4EkX.js +1 -0
  284. package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/{vendor-Cjbwl5VI.js → vendor-CeMKrCZm.js} +24 -24
  285. package/node_modules/@deepseek-ai/dsh-web-frontend/dist/index.html +2 -2
  286. package/node_modules/@deepseek-ai/dsh-web-frontend/package.json +1 -1
  287. package/node_modules/@deepseek-ai/dsh-web-search-deepseek/LICENSE +21 -0
  288. package/node_modules/@deepseek-ai/dsh-web-search-deepseek/lib/index.js +1 -0
  289. package/node_modules/@deepseek-ai/dsh-web-search-deepseek/lib/invariant.js +1 -0
  290. package/node_modules/@deepseek-ai/dsh-web-search-deepseek/package.json +1 -0
  291. package/node_modules/@deepseek-ai/dsh-web-search-dsh/lib/index.js +1 -1
  292. package/node_modules/@deepseek-ai/dsh-web-search-dsh/package.json +1 -1
  293. package/node_modules/@deepseek-ai/dsh-workflow/package.json +1 -1
  294. package/node_modules/@deepseek-ai/dsh-workflow-worker-thread/lib/index.js +2 -2
  295. package/node_modules/@deepseek-ai/dsh-workflow-worker-thread/lib/worker.cjs +3 -4
  296. package/node_modules/@deepseek-ai/dsh-workflow-worker-thread/package.json +1 -1
  297. package/node_modules/@deepseek-ai/dsh-workspace/lib/invariant.js +1 -1
  298. package/node_modules/@deepseek-ai/dsh-workspace/package.json +1 -1
  299. package/package.json +1 -1
  300. package/lib/profile-boot-_PCyp_wB.js +0 -1
  301. package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/types-BjBvdldw.js +0 -1
  302. package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/cpp-DIPi6g--.js +0 -1
  303. package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/swift-D82vCrfD.js +0 -1
  304. /package/lib/{profile-boot-B71dQloK.js → profile-boot-DDo03lXi.js} +0 -0
@@ -1,4 +1,4 @@
1
- var iu=Object.defineProperty;var a=(ye,we)=>iu(ye,"name",{value:we,configurable:!0});window.__ModuleLoader__.load({id:"@deepseek-ai/dsh-client-runtime",factory:a(ye=>{var we={exports:{}},k=we.exports;Object.defineProperty(k,Symbol.toStringTag,{value:"Module"});let Be=ye("@deepseek-ai/cordis"),ws=ye("@deepseek-ai/dsh-client-ui-slots");const bs="root";var Le=class extends Be.Service{static{a(this,"SlotRegistry")}_core=new ws.SlotCore;_stores=new Map;_renderer;_locale;_host;constructor(e){super(e,"slots"),this._core.onMutate(t=>{e.emit("slots/changed",t)})}inject(e,t){const n=this.ctx,s=n.effect(()=>{let r,i,o=!1,c=a(()=>{},"unsubscribe");const d=a(()=>{if(o)return;o=!0,c();const m=r;r=void 0,i=void 0,m?.()},"stop"),u=a(()=>{if(o)return;const m=this._core.specDynamic(e),v=this._core.declarationEpoch(e);if(r!==void 0&&i===v)return;const b=r;if(r=void 0,i=void 0,b?.(),m===void 0)return;const z=n.effect(t,`slots.inject(${JSON.stringify(e)}): declaration`);r=a(()=>{z()},"active"),i=v},"reconcile"),h=a(()=>{try{u()}catch(m){if(m?.code==="INACTIVE_EFFECT"){d();return}d();const v=m instanceof Error?m:new Error(String(m));queueMicrotask(()=>{throw v})}},"changed");c=this._core.subscribeDeclaration(e,h);try{u()}catch(m){throw d(),m}return d},`slots.inject(${JSON.stringify(e)})`);return()=>{s()}}install(e){if(this._renderer!==void 0)throw new Error("slot renderer already installed (install() is boot-once)");this.ctx.effect(()=>(this._renderer=e,()=>{this._renderer===e&&(this._renderer=void 0)}),"slots.install()")}installLocale(e){if(this._locale!==void 0)throw new Error("locale face already installed (installLocale() is boot-once)");this.ctx.effect(()=>(this._locale=e,()=>{this._locale===e&&(this._locale=void 0)}),"slots.installLocale()")}renderSlot(e,t){if(e!=="root")throw new Error(`ctx-level renderSlot only renders 'root' (got "${e}"); child slots render through the component props face`);if(this._renderer===void 0)throw new Error("slot renderer not installed — boot must call ctx.slots.install(createSlotRenderer()) before rendering 'root'");if(this._core.entries("root").length===0)throw new Error("'root' has no registration — a layout entry must register into 'root' before the shell renders it");return this._renderer.renderRoot(this.hostFace(),t)}pruneStoreScope(e){for(const[t,n]of this._stores)n.scope==="session"&&((n.instances.get(e)??t.create(e)).clearPersisted(),n.instances.delete(e))}entries(e){return this._core.entries(e)}entriesOfSlot(e){return this._core.entriesOfSlot(e)}snapshot(e){return this._core.snapshot(e)}onEntryError(e){return this._core.onEntryError(e)}spec(e){return this._core.spec(e)}subscribe(e,t){return this._core.subscribe(e,t)}getVersion(e){return this._core.getVersion(e)}_register(e,t){const n=typeof e.store=="function"?e.store():e.store,s=e.registrant??this.ctx.fiber?.name,r={...e,...n!==void 0?{store:n}:{},...s!==void 0?{registrant:s}:{}},i=this._core.register(r,t);if(n!==void 0){const c=this._core.specDynamic(e.name).scope;this._acquire(n,c)}let o=!1;return()=>{o||(o=!0,i(),n!==void 0&&this._release(n))}}hostFace(){if(this._host!==void 0)return this._host;const e=this.ctx.get("sessions");if(e===void 0)throw new Error("renderSlot('root') before the sessions service mounted — boot order puts runtime apply first");const t=this.ctx.get("workspaces");if(t===void 0)throw new Error("renderSlot('root') before the workspaces service mounted — boot order puts runtime apply first");const n=this;return this._host={subscribe:a((s,r)=>this._core.subscribe(s,r),"subscribe"),getVersion:a(s=>this._core.getVersion(s),"getVersion"),entriesOf:a(s=>this._core.entries(s),"entriesOf"),entriesOfSlot:a(s=>this._core.entriesOfSlot(s),"entriesOfSlot"),reportEntryError:a((s,r,i,o)=>{this._core.reportEntryError(s,r,i,o)},"reportEntryError"),specOf:a(s=>this._core.specDynamic(s),"specOf"),isLive:a(s=>this._core.isLive(s),"isLive"),storeOf:a((s,r)=>s.store===void 0?void 0:this.resolveStore(s.store,r),"storeOf"),sessions:{list:e.list,provideInfo:e.currentProvideInfo},workspaces:{list:t.list},get locale(){return n._locale}},this._host}resolveStore(e,t){const n=this._stores.get(e);if(n===void 0)throw new Error("store handle is not registered (entry unloaded, or the handle never went through register)");const s=n.scope==="root"?bs:t;if(s===void 0)throw new Error(`${n.scope} store resolution requires a session id`);let r=n.instances.get(s);return r===void 0&&(r=n.scope==="root"?e.create():e.create(s),n.instances.set(s,r)),r}_acquire(e,t){const n=this._stores.get(e);if(n===void 0){this._stores.set(e,{scope:t,refs:1,instances:new Map});return}n.refs+=1}_release(e){const t=this._stores.get(e);t!==void 0&&(t.refs-=1,t.refs===0&&this._stores.delete(e))}};Le.prototype.register=a(function(t,n){const s=t;return this.ctx.effect(()=>this._register(s,n),"slots.register()")},"register");function M(e){return{ok:!1,error:{code:"internal",message:e instanceof Error?e.message:String(e),details:{}}}}a(M,"transportError");var kt;function l(e,t,n){function s(c,d){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:d,constr:o,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,d);const u=o.prototype,h=Object.keys(u);for(let m=0;m<h.length;m++){const v=h[m];v in c||(c[v]=u[v].bind(c))}}a(s,"init");const r=n?.Parent??Object;class i extends r{static{a(this,"Definition")}}Object.defineProperty(i,"name",{value:e});function o(c){var d;const u=n?.Parent?new i:this;s(u,c),(d=u._zod).deferred??(d.deferred=[]);for(const h of u._zod.deferred)h();return u}return a(o,"_"),Object.defineProperty(o,"init",{value:s}),Object.defineProperty(o,Symbol.hasInstance,{value:a(c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e),"value")}),Object.defineProperty(o,"name",{value:e}),o}a(l,"$constructor");var Y=class extends Error{static{a(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},St=class extends Error{static{a(this,"$ZodEncodeError")}constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(kt=globalThis).__zod_globalConfig??(kt.__zod_globalConfig={});const be=globalThis.__zod_globalConfig;function B(e){return e&&Object.assign(be,e),be}a(B,"config");function It(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,s])=>t.indexOf(+n)===-1).map(([n,s])=>s)}a(It,"getEnumValues");function Ue(e,t){return typeof t=="bigint"?t.toString():t}a(Ue,"jsonStringifyReplacer");function _e(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}a(_e,"cached");function Ve(e){return e==null}a(Ve,"nullish");function We(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}a(We,"cleanRegex");function _s(e,t){const n=e/t,s=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-s)<r?0:n-s}a(_s,"floatSafeRemainder");const zt=Symbol("evaluating");function $(e,t,n){let s;Object.defineProperty(e,t,{get(){if(s!==zt)return s===void 0&&(s=zt,s=n()),s},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}a($,"defineLazy");function L(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}a(L,"assignProp");function j(...e){const t={};for(const n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}a(j,"mergeDefs");function $t(e){return JSON.stringify(e)}a($t,"esc");function ks(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}a(ks,"slugify");const Et="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(se,"isObject");const Ss=_e(()=>{if(be.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch{return!1}});function re(e){if(se(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(se(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}a(re,"isPlainObject$1");function Ot(e){return re(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}a(Ot,"shallowClone");const Is=new Set(["string","number","symbol"]);function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(H,"escapeRegex");function F(e,t,n){const s=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(s._zod.parent=e),s}a(F,"clone");function y(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:a(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:a(()=>t.error,"error")}:t}a(y,"normalizeParams");function zs(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}a(zs,"optionalKeys");const $s={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Es(e,t){const n=e._zod.def,s=n.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return F(e,j(e._zod.def,{get shape(){const r={};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return L(this,"shape",r),r},checks:[]}))}a(Es,"pick");function Os(e,t){const n=e._zod.def,s=n.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return F(e,j(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return L(this,"shape",r),r},checks:[]}))}a(Os,"omit");function Ps(e,t){if(!re(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const s=e._zod.def.shape;for(const r in t)if(Object.getOwnPropertyDescriptor(s,r)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return F(e,j(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return L(this,"shape",s),s}}))}a(Ps,"extend");function Ds(e,t){if(!re(t))throw new Error("Invalid input to safeExtend: expected a plain object");return F(e,j(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return L(this,"shape",n),n}}))}a(Ds,"safeExtend");function Cs(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");return F(e,j(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return L(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}a(Cs,"merge");function As(e,t,n){const s=t._zod.def.checks;if(s&&s.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return F(t,j(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const o in n){if(!(o in r))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(i[o]=e?new e({type:"optional",innerType:r[o]}):r[o])}else for(const o in r)i[o]=e?new e({type:"optional",innerType:r[o]}):r[o];return L(this,"shape",i),i},checks:[]}))}a(As,"partial");function Ts(e,t,n){return F(t,j(t._zod.def,{get shape(){const s=t._zod.def.shape,r={...s};if(n)for(const i in n){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(r[i]=new e({type:"nonoptional",innerType:s[i]}))}else for(const i in s)r[i]=new e({type:"nonoptional",innerType:s[i]});return L(this,"shape",r),r}}))}a(Ts,"required");function X(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}a(X,"aborted");function Zs(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}a(Zs,"explicitlyAborted");function Pt(e,t){return t.map(n=>{var s;return(s=n).path??(s.path=[]),n.path.unshift(e),n})}a(Pt,"prefixIssues");function ke(e){return typeof e=="string"?e:e?.message}a(ke,"unwrapMessage");function U(e,t,n){const s=e.message?e.message:ke(e.inst?._zod.def?.error?.(e))??ke(t?.error?.(e))??ke(n.customError?.(e))??ke(n.localeError?.(e))??"Invalid input",{inst:r,continue:i,input:o,...c}=e;return c.path??(c.path=[]),c.message=s,t?.reportInput&&(c.input=o),c}a(U,"finalizeIssue");function Je(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}a(Je,"getLengthableOrigin");function ie(...e){const[t,n,s]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:s}:{...t}}a(ie,"issue");const Dt=a((e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Ue,2),Object.defineProperty(e,"toString",{value:a(()=>e.message,"value"),enumerable:!1})},"initializer$1"),Ct=l("$ZodError",Dt),At=l("$ZodError",Dt,{Parent:Error});function Ns(e,t=n=>n.message){const n={},s=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):s.push(t(r));return{formErrors:s,fieldErrors:n}}a(Ns,"flattenError");function Ms(e,t=n=>n.message){const n={_errors:[]},s=a((r,i=[])=>{for(const o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(c=>s({issues:c},[...i,...o.path]));else if(o.code==="invalid_key")s({issues:o.issues},[...i,...o.path]);else if(o.code==="invalid_element")s({issues:o.issues},[...i,...o.path]);else{const c=[...i,...o.path];if(c.length===0)n._errors.push(t(o));else{let d=n,u=0;for(;u<c.length;){const h=c[u];u!==c.length-1?d[h]=d[h]||{_errors:[]}:(d[h]=d[h]||{_errors:[]},d[h]._errors.push(t(o))),d=d[h],u++}}}},"processError");return s(e),n}a(Ms,"formatError");const Ge=a(e=>(t,n,s,r)=>{const i=s?{...s,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Y;if(o.issues.length){const c=new(r?.Err??e)(o.issues.map(d=>U(d,i,B())));throw Et(c,r?.callee),c}return o.value},"_parse"),Ke=a(e=>async(t,n,s,r)=>{const i=s?{...s,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(r?.Err??e)(o.issues.map(d=>U(d,i,B())));throw Et(c,r?.callee),c}return o.value},"_parseAsync"),Se=a(e=>(t,n,s)=>{const r=s?{...s,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new Y;return i.issues.length?{success:!1,error:new(e??Ct)(i.issues.map(o=>U(o,r,B())))}:{success:!0,data:i.value}},"_safeParse"),xs=Se(At),Ie=a(e=>async(t,n,s)=>{const r=s?{...s,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(o=>U(o,r,B())))}:{success:!0,data:i.value}},"_safeParseAsync"),qs=Ie(At),Rs=a(e=>(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return Ge(e)(t,n,r)},"_encode"),js=a(e=>(t,n,s)=>Ge(e)(t,n,s),"_decode"),Fs=a(e=>async(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return Ke(e)(t,n,r)},"_encodeAsync"),Bs=a(e=>async(t,n,s)=>Ke(e)(t,n,s),"_decodeAsync"),Ls=a(e=>(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return Se(e)(t,n,r)},"_safeEncode"),Us=a(e=>(t,n,s)=>Se(e)(t,n,s),"_safeDecode"),Vs=a(e=>async(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return Ie(e)(t,n,r)},"_safeEncodeAsync"),Ws=a(e=>async(t,n,s)=>Ie(e)(t,n,s),"_safeDecodeAsync"),Js=/^[cC][0-9a-z]{6,}$/,Gs=/^[0-9a-z]+$/,Ks=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ys=/^[0-9a-vA-V]{20}$/,Hs=/^[A-Za-z0-9]{27}$/,Xs=/^[a-zA-Z0-9_-]{21}$/,Qs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,er=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Tt=a(e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,"uuid"),tr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function sr(){return new RegExp(nr,"u")}a(sr,"emoji");const rr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ir=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,or=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ar=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zt=/^[A-Za-z0-9_-]*$/,ur=/^https?$/,dr=/^\+[1-9]\d{6,14}$/,Nt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",lr=new RegExp(`^${Nt}$`);function Mt(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}a(Mt,"timeSource");function hr(e){return new RegExp(`^${Mt(e)}$`)}a(hr,"time$1");function fr(e){const t=Mt({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${n.join("|")})`;return new RegExp(`^${Nt}T(?:${s})$`)}a(fr,"datetime$1");const pr=a(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),mr=/^-?\d+$/,gr=/^-?\d+(?:\.\d+)?$/,vr=/^[^A-Z]*$/,yr=/^[^a-z]*$/,N=l("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xt={number:"number",bigint:"bigint",object:"date"},qt=l("$ZodCheckLessThan",(e,t)=>{N.init(e,t);const n=xt[typeof t.value];e._zod.onattach.push(s=>{const r=s._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Rt=l("$ZodCheckGreaterThan",(e,t)=>{N.init(e,t);const n=xt[typeof t.value];e._zod.onattach.push(s=>{const r=s._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),wr=l("$ZodCheckMultipleOf",(e,t)=>{N.init(e,t),e._zod.onattach.push(n=>{var s;(s=n._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):_s(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),br=l("$ZodCheckNumberFormat",(e,t)=>{N.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),s=n?"int":"number",[r,i]=$s[t.format];e._zod.onattach.push(o=>{const c=o._zod.bag;c.format=t.format,c.minimum=r,c.maximum=i,n&&(c.pattern=mr)}),e._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}c<r&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>i&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),_r=l("$ZodCheckMaxLength",(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=s=>{const r=s.value;return!Ve(r)&&r.length!==void 0}),e._zod.onattach.push(s=>{const r=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const r=s.value;if(r.length<=t.maximum)return;const i=Je(r);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),kr=l("$ZodCheckMinLength",(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=s=>{const r=s.value;return!Ve(r)&&r.length!==void 0}),e._zod.onattach.push(s=>{const r=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const r=s.value;if(r.length>=t.minimum)return;const i=Je(r);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Sr=l("$ZodCheckLengthEquals",(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=s=>{const r=s.value;return!Ve(r)&&r.length!==void 0}),e._zod.onattach.push(s=>{const r=s._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=s=>{const r=s.value,i=r.length;if(i===t.length)return;const o=Je(r),c=i>t.length;s.issues.push({origin:o,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),ze=l("$ZodCheckStringFormat",(e,t)=>{var n,s;N.init(e,t),e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),Ir=l("$ZodCheckRegex",(e,t)=>{ze.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),zr=l("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vr),ze.init(e,t)}),$r=l("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yr),ze.init(e,t)}),Er=l("$ZodCheckIncludes",(e,t)=>{N.init(e,t);const n=H(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=s,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(s)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Or=l("$ZodCheckStartsWith",(e,t)=>{N.init(e,t);const n=new RegExp(`^${H(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(s=>{const r=s._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),Pr=l("$ZodCheckEndsWith",(e,t)=>{N.init(e,t);const n=new RegExp(`.*${H(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(s=>{const r=s._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),Dr=l("$ZodCheckOverwrite",(e,t)=>{N.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});var Cr=class{static{a(this,"Doc")}constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const t=e.split(`
1
+ var iu=Object.defineProperty;var a=(ye,we)=>iu(ye,"name",{value:we,configurable:!0});window.__ModuleLoader__.load({id:"@deepseek-ai/dsh-client-runtime",factory:a(ye=>{var we={exports:{}},k=we.exports;Object.defineProperty(k,Symbol.toStringTag,{value:"Module"});let Be=ye("@deepseek-ai/cordis"),ws=ye("@deepseek-ai/dsh-client-ui-slots");const bs="root";var Le=class extends Be.Service{static{a(this,"SlotRegistry")}_core=new ws.SlotCore;_stores=new Map;_renderer;_locale;_host;constructor(e){super(e,"slots"),this._core.onMutate(t=>{e.emit("slots/changed",t)})}inject(e,t){const n=this.ctx,s=n.effect(()=>{let r,i,o=!1,c=a(()=>{},"unsubscribe");const d=a(()=>{if(o)return;o=!0,c();const m=r;r=void 0,i=void 0,m?.()},"stop"),u=a(()=>{if(o)return;const m=this._core.specDynamic(e),v=this._core.declarationEpoch(e);if(r!==void 0&&i===v)return;const b=r;if(r=void 0,i=void 0,b?.(),m===void 0)return;const z=n.effect(t,`slots.inject(${JSON.stringify(e)}): declaration`);r=a(()=>{z()},"active"),i=v},"reconcile"),h=a(()=>{try{u()}catch(m){if(m?.code==="INACTIVE_EFFECT"){d();return}d();const v=m instanceof Error?m:new Error(String(m));queueMicrotask(()=>{throw v})}},"changed");c=this._core.subscribeDeclaration(e,h);try{u()}catch(m){throw d(),m}return d},`slots.inject(${JSON.stringify(e)})`);return()=>{s()}}install(e){if(this._renderer!==void 0)throw new Error("slot renderer already installed (install() is boot-once)");this.ctx.effect(()=>(this._renderer=e,()=>{this._renderer===e&&(this._renderer=void 0)}),"slots.install()")}installLocale(e){if(this._locale!==void 0)throw new Error("locale face already installed (installLocale() is boot-once)");this.ctx.effect(()=>(this._locale=e,()=>{this._locale===e&&(this._locale=void 0)}),"slots.installLocale()")}renderSlot(e,t){if(e!=="root")throw new Error(`ctx-level renderSlot only renders 'root' (got "${e}"); child slots render through the component props face`);if(this._renderer===void 0)throw new Error("slot renderer not installed — boot must call ctx.slots.install(createSlotRenderer()) before rendering 'root'");if(this._core.entries("root").length===0)throw new Error("'root' has no registration — a layout entry must register into 'root' before the shell renders it");return this._renderer.renderRoot(this.hostFace(),t)}pruneStoreScope(e){for(const[t,n]of this._stores)n.scope==="session"&&((n.instances.get(e)??t.create(e)).clearPersisted(),n.instances.delete(e))}entries(e){return this._core.entries(e)}entriesOfSlot(e){return this._core.entriesOfSlot(e)}snapshot(e){return this._core.snapshot(e)}onEntryError(e){return this._core.onEntryError(e)}spec(e){return this._core.spec(e)}subscribe(e,t){return this._core.subscribe(e,t)}getVersion(e){return this._core.getVersion(e)}_register(e,t){const n=typeof e.store=="function"?e.store():e.store,s=e.registrant??this.ctx.fiber?.name,r={...e,...n!==void 0?{store:n}:{},...s!==void 0?{registrant:s}:{}},i=this._core.register(r,t);if(n!==void 0){const c=this._core.specDynamic(e.name).scope;this._acquire(n,c)}let o=!1;return()=>{o||(o=!0,i(),n!==void 0&&this._release(n))}}hostFace(){if(this._host!==void 0)return this._host;const e=this.ctx.get("sessions");if(e===void 0)throw new Error("renderSlot('root') before the sessions service mounted — boot order puts runtime apply first");const t=this.ctx.get("workspaces");if(t===void 0)throw new Error("renderSlot('root') before the workspaces service mounted — boot order puts runtime apply first");const n=this;return this._host={subscribe:a((s,r)=>this._core.subscribe(s,r),"subscribe"),getVersion:a(s=>this._core.getVersion(s),"getVersion"),entriesOf:a(s=>this._core.entries(s),"entriesOf"),entriesOfSlot:a(s=>this._core.entriesOfSlot(s),"entriesOfSlot"),reportEntryError:a((s,r,i,o)=>{this._core.reportEntryError(s,r,i,o)},"reportEntryError"),specOf:a(s=>this._core.specDynamic(s),"specOf"),isLive:a(s=>this._core.isLive(s),"isLive"),storeOf:a((s,r)=>s.store===void 0?void 0:this.resolveStore(s.store,r),"storeOf"),sessions:{list:e.list,provideInfo:e.currentProvideInfo},workspaces:{list:t.list},get locale(){return n._locale}},this._host}resolveStore(e,t){const n=this._stores.get(e);if(n===void 0)throw new Error("store handle is not registered (entry unloaded, or the handle never went through register)");const s=n.scope==="root"?bs:t;if(s===void 0)throw new Error(`${n.scope} store resolution requires a session id`);let r=n.instances.get(s);return r===void 0&&(r=n.scope==="root"?e.create():e.create(s),n.instances.set(s,r)),r}_acquire(e,t){const n=this._stores.get(e);if(n===void 0){this._stores.set(e,{scope:t,refs:1,instances:new Map});return}n.refs+=1}_release(e){const t=this._stores.get(e);t!==void 0&&(t.refs-=1,t.refs===0&&this._stores.delete(e))}};Le.prototype.register=a(function(t,n){const s=t;return this.ctx.effect(()=>this._register(s,n),"slots.register()")},"register");function M(e){return{ok:!1,error:{code:"internal",message:e instanceof Error?e.message:String(e),details:{}}}}a(M,"transportError");var kt;function l(e,t,n){function s(c,d){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:d,constr:o,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,d);const u=o.prototype,h=Object.keys(u);for(let m=0;m<h.length;m++){const v=h[m];v in c||(c[v]=u[v].bind(c))}}a(s,"init");const r=n?.Parent??Object;class i extends r{static{a(this,"Definition")}}Object.defineProperty(i,"name",{value:e});function o(c){var d;const u=n?.Parent?new i:this;s(u,c),(d=u._zod).deferred??(d.deferred=[]);for(const h of u._zod.deferred)h();return u}return a(o,"_"),Object.defineProperty(o,"init",{value:s}),Object.defineProperty(o,Symbol.hasInstance,{value:a(c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e),"value")}),Object.defineProperty(o,"name",{value:e}),o}a(l,"$constructor");var Y=class extends Error{static{a(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},St=class extends Error{static{a(this,"$ZodEncodeError")}constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(kt=globalThis).__zod_globalConfig??(kt.__zod_globalConfig={});const be=globalThis.__zod_globalConfig;function B(e){return e&&Object.assign(be,e),be}a(B,"config");function It(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,s])=>t.indexOf(+n)===-1).map(([n,s])=>s)}a(It,"getEnumValues");function Ue(e,t){return typeof t=="bigint"?t.toString():t}a(Ue,"jsonStringifyReplacer");function _e(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}a(_e,"cached");function Ve(e){return e==null}a(Ve,"nullish");function We(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}a(We,"cleanRegex");function _s(e,t){const n=e/t,s=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-s)<r?0:n-s}a(_s,"floatSafeRemainder");const zt=Symbol("evaluating");function $(e,t,n){let s;Object.defineProperty(e,t,{get(){if(s!==zt)return s===void 0&&(s=zt,s=n()),s},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}a($,"defineLazy");function L(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}a(L,"assignProp");function j(...e){const t={};for(const n of e){const s=Object.getOwnPropertyDescriptors(n);Object.assign(t,s)}return Object.defineProperties({},t)}a(j,"mergeDefs");function $t(e){return JSON.stringify(e)}a($t,"esc");function ks(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}a(ks,"slugify");const Et="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(se,"isObject");const Ss=_e(()=>{if(be.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch{return!1}});function re(e){if(se(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(se(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}a(re,"isPlainObject$1");function Ot(e){return re(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}a(Ot,"shallowClone");const Is=new Set(["string","number","symbol"]);function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(H,"escapeRegex");function F(e,t,n){const s=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(s._zod.parent=e),s}a(F,"clone");function y(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:a(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:a(()=>t.error,"error")}:t}a(y,"normalizeParams");function zs(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}a(zs,"optionalKeys");const $s={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Es(e,t){const n=e._zod.def,s=n.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return F(e,j(e._zod.def,{get shape(){const r={};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return L(this,"shape",r),r},checks:[]}))}a(Es,"pick");function Os(e,t){const n=e._zod.def,s=n.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return F(e,j(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return L(this,"shape",r),r},checks:[]}))}a(Os,"omit");function Ps(e,t){if(!re(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const s=e._zod.def.shape;for(const r in t)if(Object.getOwnPropertyDescriptor(s,r)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return F(e,j(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return L(this,"shape",s),s}}))}a(Ps,"extend");function Ds(e,t){if(!re(t))throw new Error("Invalid input to safeExtend: expected a plain object");return F(e,j(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return L(this,"shape",n),n}}))}a(Ds,"safeExtend");function Cs(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");return F(e,j(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return L(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}a(Cs,"merge");function As(e,t,n){const s=t._zod.def.checks;if(s&&s.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return F(t,j(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const o in n){if(!(o in r))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(i[o]=e?new e({type:"optional",innerType:r[o]}):r[o])}else for(const o in r)i[o]=e?new e({type:"optional",innerType:r[o]}):r[o];return L(this,"shape",i),i},checks:[]}))}a(As,"partial");function Ts(e,t,n){return F(t,j(t._zod.def,{get shape(){const s=t._zod.def.shape,r={...s};if(n)for(const i in n){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(r[i]=new e({type:"nonoptional",innerType:s[i]}))}else for(const i in s)r[i]=new e({type:"nonoptional",innerType:s[i]});return L(this,"shape",r),r}}))}a(Ts,"required");function X(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}a(X,"aborted");function Zs(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}a(Zs,"explicitlyAborted");function Pt(e,t){return t.map(n=>{var s;return(s=n).path??(s.path=[]),n.path.unshift(e),n})}a(Pt,"prefixIssues");function ke(e){return typeof e=="string"?e:e?.message}a(ke,"unwrapMessage");function U(e,t,n){const s=e.message?e.message:ke(e.inst?._zod.def?.error?.(e))??ke(t?.error?.(e))??ke(n.customError?.(e))??ke(n.localeError?.(e))??"Invalid input",{inst:r,continue:i,input:o,...c}=e;return c.path??(c.path=[]),c.message=s,t?.reportInput&&(c.input=o),c}a(U,"finalizeIssue");function Je(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}a(Je,"getLengthableOrigin");function ie(...e){const[t,n,s]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:s}:{...t}}a(ie,"issue");const Dt=a((e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Ue,2),Object.defineProperty(e,"toString",{value:a(()=>e.message,"value"),enumerable:!1})},"initializer$1"),Ct=l("$ZodError",Dt),At=l("$ZodError",Dt,{Parent:Error});function Ns(e,t=n=>n.message){const n={},s=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):s.push(t(r));return{formErrors:s,fieldErrors:n}}a(Ns,"flattenError");function Ms(e,t=n=>n.message){const n={_errors:[]},s=a((r,i=[])=>{for(const o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(c=>s({issues:c},[...i,...o.path]));else if(o.code==="invalid_key")s({issues:o.issues},[...i,...o.path]);else if(o.code==="invalid_element")s({issues:o.issues},[...i,...o.path]);else{const c=[...i,...o.path];if(c.length===0)n._errors.push(t(o));else{let d=n,u=0;for(;u<c.length;){const h=c[u];u!==c.length-1?d[h]=d[h]||{_errors:[]}:(d[h]=d[h]||{_errors:[]},d[h]._errors.push(t(o))),d=d[h],u++}}}},"processError");return s(e),n}a(Ms,"formatError");const Ge=a(e=>(t,n,s,r)=>{const i=s?{...s,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Y;if(o.issues.length){const c=new(r?.Err??e)(o.issues.map(d=>U(d,i,B())));throw Et(c,r?.callee),c}return o.value},"_parse"),Ke=a(e=>async(t,n,s,r)=>{const i=s?{...s,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(r?.Err??e)(o.issues.map(d=>U(d,i,B())));throw Et(c,r?.callee),c}return o.value},"_parseAsync"),Se=a(e=>(t,n,s)=>{const r=s?{...s,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new Y;return i.issues.length?{success:!1,error:new(e??Ct)(i.issues.map(o=>U(o,r,B())))}:{success:!0,data:i.value}},"_safeParse"),xs=Se(At),Ie=a(e=>async(t,n,s)=>{const r=s?{...s,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(o=>U(o,r,B())))}:{success:!0,data:i.value}},"_safeParseAsync"),qs=Ie(At),Rs=a(e=>(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return Ge(e)(t,n,r)},"_encode"),js=a(e=>(t,n,s)=>Ge(e)(t,n,s),"_decode"),Fs=a(e=>async(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return Ke(e)(t,n,r)},"_encodeAsync"),Bs=a(e=>async(t,n,s)=>Ke(e)(t,n,s),"_decodeAsync"),Ls=a(e=>(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return Se(e)(t,n,r)},"_safeEncode"),Us=a(e=>(t,n,s)=>Se(e)(t,n,s),"_safeDecode"),Vs=a(e=>async(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return Ie(e)(t,n,r)},"_safeEncodeAsync"),Ws=a(e=>async(t,n,s)=>Ie(e)(t,n,s),"_safeDecodeAsync"),Js=/^[cC][0-9a-z]{6,}$/,Gs=/^[0-9a-z]+$/,Ks=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ys=/^[0-9a-vA-V]{20}$/,Hs=/^[A-Za-z0-9]{27}$/,Xs=/^[a-zA-Z0-9_-]{21}$/,Qs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,er=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Tt=a(e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,"uuid"),tr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function sr(){return new RegExp(nr,"u")}a(sr,"emoji");const rr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ir=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,or=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ar=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zt=/^[A-Za-z0-9_-]*$/,ur=/^https?$/,dr=/^\+[1-9]\d{6,14}$/,Nt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",lr=new RegExp(`^${Nt}$`);function Mt(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}a(Mt,"timeSource");function hr(e){return new RegExp(`^${Mt(e)}$`)}a(hr,"time$1");function fr(e){const t=Mt({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${n.join("|")})`;return new RegExp(`^${Nt}T(?:${s})$`)}a(fr,"datetime$1");const pr=a(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),mr=/^-?\d+$/,gr=/^-?\d+(?:\.\d+)?$/,vr=/^[^A-Z]*$/,yr=/^[^a-z]*$/,N=l("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xt={number:"number",bigint:"bigint",object:"date"},qt=l("$ZodCheckLessThan",(e,t)=>{N.init(e,t);const n=xt[typeof t.value];e._zod.onattach.push(s=>{const r=s._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Rt=l("$ZodCheckGreaterThan",(e,t)=>{N.init(e,t);const n=xt[typeof t.value];e._zod.onattach.push(s=>{const r=s._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),wr=l("$ZodCheckMultipleOf",(e,t)=>{N.init(e,t),e._zod.onattach.push(n=>{var s;(s=n._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):_s(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),br=l("$ZodCheckNumberFormat",(e,t)=>{N.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),s=n?"int":"number",[r,i]=$s[t.format];e._zod.onattach.push(o=>{const c=o._zod.bag;c.format=t.format,c.minimum=r,c.maximum=i,n&&(c.pattern=mr)}),e._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}c<r&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>i&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),_r=l("$ZodCheckMaxLength",(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=s=>{const r=s.value;return!Ve(r)&&r.length!==void 0}),e._zod.onattach.push(s=>{const r=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const r=s.value;if(r.length<=t.maximum)return;const i=Je(r);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),kr=l("$ZodCheckMinLength",(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=s=>{const r=s.value;return!Ve(r)&&r.length!==void 0}),e._zod.onattach.push(s=>{const r=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const r=s.value;if(r.length>=t.minimum)return;const i=Je(r);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Sr=l("$ZodCheckLengthEquals",(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=s=>{const r=s.value;return!Ve(r)&&r.length!==void 0}),e._zod.onattach.push(s=>{const r=s._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=s=>{const r=s.value,i=r.length;if(i===t.length)return;const o=Je(r),c=i>t.length;s.issues.push({origin:o,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),ze=l("$ZodCheckStringFormat",(e,t)=>{var n,s;N.init(e,t),e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),Ir=l("$ZodCheckRegex",(e,t)=>{ze.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),zr=l("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vr),ze.init(e,t)}),$r=l("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yr),ze.init(e,t)}),Er=l("$ZodCheckIncludes",(e,t)=>{N.init(e,t);const n=H(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=s,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(s)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Or=l("$ZodCheckStartsWith",(e,t)=>{N.init(e,t);const n=new RegExp(`^${H(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(s=>{const r=s._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),Pr=l("$ZodCheckEndsWith",(e,t)=>{N.init(e,t);const n=new RegExp(`.*${H(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(s=>{const r=s._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),Dr=l("$ZodCheckOverwrite",(e,t)=>{N.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});var Cr=class{static{a(this,"Doc")}constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const t=e.split(`
2
2
  `).filter(r=>r),n=Math.min(...t.map(r=>r.length-r.trimStart().length)),s=t.map(r=>r.slice(n)).map(r=>" ".repeat(this.indent*2)+r);for(const r of s)this.content.push(r)}compile(){const e=Function,t=this?.args,n=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...t,n.join(`
3
3
  `))}};const Ar={major:4,minor:4,patch:3},D=l("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ar;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const r of s)for(const i of r._zod.onattach)i(e);if(s.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=a((o,c,d)=>{let u=X(o),h;for(const m of c){if(m._zod.def.when){if(Zs(o)||!m._zod.def.when(o))continue}else if(u)continue;const v=o.issues.length,b=m._zod.check(o);if(b instanceof Promise&&d?.async===!1)throw new Y;if(h||b instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await b,o.issues.length!==v&&(u||(u=X(o,v)))});else{if(o.issues.length===v)continue;u||(u=X(o,v))}}return h?h.then(()=>o):o},"runChecks"),i=a((o,c,d)=>{if(X(o))return o.aborted=!0,o;const u=r(c,s,d);if(u instanceof Promise){if(d.async===!1)throw new Y;return u.then(h=>e._zod.parse(h,d))}return e._zod.parse(u,d)},"handleCanaryResult");e._zod.run=(o,c)=>{if(c.skipChecks)return e._zod.parse(o,c);if(c.direction==="backward"){const u=e._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>i(h,o,c)):i(u,o,c)}const d=e._zod.parse(o,c);if(d instanceof Promise){if(c.async===!1)throw new Y;return d.then(u=>r(u,s,c))}return r(d,s,c)}}$(e,"~standard",()=>({validate:a(r=>{try{const i=xs(e,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return qs(e,r).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},"validate"),vendor:"zod",version:1}))}),Ye=l("$ZodString",(e,t)=>{D.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pr(e._zod.bag),e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),O=l("$ZodStringFormat",(e,t)=>{ze.init(e,t),Ye.init(e,t)}),Tr=l("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=er),O.init(e,t)}),Zr=l("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Tt(n))}else t.pattern??(t.pattern=Tt());O.init(e,t)}),Nr=l("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=tr),O.init(e,t)}),Mr=l("$ZodURL",(e,t)=>{O.init(e,t),e._zod.check=n=>{try{const s=n.value.trim();if(!t.normalize&&t.protocol?.source===ur.source&&!/^https?:\/\//i.test(s)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const r=new URL(s);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=r.href:n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),xr=l("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=sr()),O.init(e,t)}),qr=l("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Xs),O.init(e,t)}),Rr=l("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Js),O.init(e,t)}),jr=l("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Gs),O.init(e,t)}),Fr=l("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ks),O.init(e,t)}),Br=l("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ys),O.init(e,t)}),Lr=l("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Hs),O.init(e,t)}),Ur=l("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=fr(t)),O.init(e,t)}),Vr=l("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=lr),O.init(e,t)}),Wr=l("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hr(t)),O.init(e,t)}),Jr=l("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qs),O.init(e,t)}),Gr=l("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=rr),O.init(e,t),e._zod.bag.format="ipv4"}),Kr=l("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ir),O.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Yr=l("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=or),O.init(e,t)}),Hr=l("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ar),O.init(e,t),e._zod.check=n=>{const s=n.value.split("/");try{if(s.length!==2)throw new Error;const[r,i]=s;if(!i)throw new Error;const o=Number(i);if(`${o}`!==i)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function jt(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}a(jt,"isValidBase64");const Xr=l("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cr),O.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{jt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Qr(e){if(!Zt.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/");return jt(t.padEnd(Math.ceil(t.length/4)*4,"="))}a(Qr,"isValidBase64URL");const ei=l("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Zt),O.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{Qr(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),ti=l("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dr),O.init(e,t)});function ni(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[s]=n;if(!s)return!1;const r=JSON.parse(atob(s));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}a(ni,"isValidJWT");const si=l("$ZodJWT",(e,t)=>{O.init(e,t),e._zod.check=n=>{ni(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Ft=l("$ZodNumber",(e,t)=>{D.init(e,t),e._zod.pattern=e._zod.bag.pattern??gr,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...i?{received:i}:{}}),n}}),ri=l("$ZodNumberFormat",(e,t)=>{br.init(e,t),Ft.init(e,t)}),ii=l("$ZodUnknown",(e,t)=>{D.init(e,t),e._zod.parse=n=>n}),oi=l("$ZodNever",(e,t)=>{D.init(e,t),e._zod.parse=(n,s)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Bt(e,t,n){e.issues.length&&t.issues.push(...Pt(n,e.issues)),t.value[n]=e.value}a(Bt,"handleArrayResult");const ai=l("$ZodArray",(e,t)=>{D.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const i=[];for(let o=0;o<r.length;o++){const c=r[o],d=t.element._zod.run({value:c,issues:[]},s);d instanceof Promise?i.push(d.then(u=>Bt(u,n,o))):Bt(d,n,o)}return i.length?Promise.all(i).then(()=>n):n}});function $e(e,t,n,s,r,i){const o=n in s;if(e.issues.length){if(r&&i&&!o)return;t.issues.push(...Pt(n,e.issues))}if(!o&&!r){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}a($e,"handlePropertyResult");function Lt(e){const t=Object.keys(e.shape);for(const s of t)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${s}": expected a Zod schema`);const n=zs(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}a(Lt,"normalizeDef");function Ut(e,t,n,s,r,i){const o=[],c=r.keySet,d=r.catchall._zod,u=d.def.type,h=d.optin==="optional",m=d.optout==="optional";for(const v in t){if(v==="__proto__"||c.has(v))continue;if(u==="never"){o.push(v);continue}const b=d.run({value:t[v],issues:[]},s);b instanceof Promise?e.push(b.then(z=>$e(z,n,v,t,h,m))):$e(b,n,v,t,h,m)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}a(Ut,"handleCatchall");const ci=l("$ZodObject",(e,t)=>{if(D.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const o=t.shape;Object.defineProperty(t,"shape",{get:a(()=>{const c={...o};return Object.defineProperty(t,"shape",{value:c}),c},"get")})}const n=_e(()=>Lt(t));$(e._zod,"propValues",()=>{const o=t.shape,c={};for(const d in o){const u=o[d]._zod;if(u.values){c[d]??(c[d]=new Set);for(const h of u.values)c[d].add(h)}}return c});const s=se,r=t.catchall;let i;e._zod.parse=(o,c)=>{i??(i=n.value);const d=o.value;if(!s(d))return o.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),o;o.value={};const u=[],h=i.shape;for(const m of i.keys){const v=h[m],b=v._zod.optin==="optional",z=v._zod.optout==="optional",p=v._zod.run({value:d[m],issues:[]},c);p instanceof Promise?u.push(p.then(_=>$e(_,o,m,d,b,z))):$e(p,o,m,d,b,z)}return r?Ut(u,d,o,c,n.value,e):u.length?Promise.all(u).then(()=>o):o}}),ui=l("$ZodObjectJIT",(e,t)=>{ci.init(e,t);const n=e._zod.parse,s=_e(()=>Lt(t)),r=a(m=>{const v=new Cr(["shape","payload","ctx"]),b=s.value,z=a(A=>{const S=$t(A);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`},"parseStr");v.write("const input = payload.value;");const p=Object.create(null);let _=0;for(const A of b.keys)p[A]=`key_${_++}`;v.write("const newResult = {};");for(const A of b.keys){const S=p[A],I=$t(A),K=m[A],ve=K?._zod?.optin==="optional",ru=K?._zod?.optout==="optional";v.write(`const ${S} = ${z(A)};`),ve&&ru?v.write(`
4
4
  if (${S}.issues.length) {
@@ -61,4 +61,4 @@ var iu=Object.defineProperty;var a=(ye,we)=>iu(ye,"name",{value:we,configurable:
61
61
 
62
62
  `)}v.write("payload.value = newResult;"),v.write("return payload;");const E=v.compile();return(A,S)=>E(m,A,S)},"generateFastpass");let i;const o=se,c=!be.jitless,d=c&&Ss.value,u=t.catchall;let h;e._zod.parse=(m,v)=>{h??(h=s.value);const b=m.value;return o(b)?c&&d&&v?.async===!1&&v.jitless!==!0?(i||(i=r(t.shape)),m=i(m,v),u?Ut([],b,m,v,h,e):m):n(m,v):(m.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),m)}});function Vt(e,t,n,s){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!X(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(o=>U(o,s,B())))}),t)}a(Vt,"handleUnionResults");const Wt=l("$ZodUnion",(e,t)=>{D.init(e,t),$(e._zod,"optin",()=>t.options.some(s=>s._zod.optin==="optional")?"optional":void 0),$(e._zod,"optout",()=>t.options.some(s=>s._zod.optout==="optional")?"optional":void 0),$(e._zod,"values",()=>{if(t.options.every(s=>s._zod.values))return new Set(t.options.flatMap(s=>Array.from(s._zod.values)))}),$(e._zod,"pattern",()=>{if(t.options.every(s=>s._zod.pattern)){const s=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${s.map(r=>We(r.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(s,r)=>{if(n)return n(s,r);let i=!1;const o=[];for(const c of t.options){const d=c._zod.run({value:s.value,issues:[]},r);if(d instanceof Promise)o.push(d),i=!0;else{if(d.issues.length===0)return d;o.push(d)}}return i?Promise.all(o).then(c=>Vt(c,s,e,r)):Vt(o,s,e,r)}}),di=l("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Wt.init(e,t);const n=e._zod.parse;$(e._zod,"propValues",()=>{const r={};for(const i of t.options){const o=i._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[c,d]of Object.entries(o)){r[c]||(r[c]=new Set);for(const u of d)r[c].add(u)}}return r});const s=_e(()=>{const r=t.options,i=new Map;for(const o of r){const c=o._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const d of c){if(i.has(d))throw new Error(`Duplicate discriminator value "${String(d)}"`);i.set(d,o)}}return i});e._zod.parse=(r,i)=>{const o=r.value;if(!se(o))return r.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),r;const c=s.value.get(o?.[t.discriminator]);return c?c._zod.run(r,i):t.unionFallback||i.direction==="backward"?n(r,i):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(s.value.keys()),input:o,path:[t.discriminator],inst:e}),r)}}),li=l("$ZodIntersection",(e,t)=>{D.init(e,t),e._zod.parse=(n,s)=>{const r=n.value,i=t.left._zod.run({value:r,issues:[]},s),o=t.right._zod.run({value:r,issues:[]},s);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([c,d])=>Jt(n,c,d)):Jt(n,i,o)}});function He(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(re(e)&&re(t)){const n=Object.keys(t),s=Object.keys(e).filter(i=>n.indexOf(i)!==-1),r={...e,...t};for(const i of s){const o=He(e[i],t[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};r[i]=o.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let s=0;s<e.length;s++){const r=e[s],i=t[s],o=He(r,i);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}a(He,"mergeValues");function Jt(e,t,n){const s=new Map;let r;for(const c of t.issues)if(c.code==="unrecognized_keys"){r??(r=c);for(const d of c.keys)s.has(d)||s.set(d,{}),s.get(d).l=!0}else e.issues.push(c);for(const c of n.issues)if(c.code==="unrecognized_keys")for(const d of c.keys)s.has(d)||s.set(d,{}),s.get(d).r=!0;else e.issues.push(c);const i=[...s].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(i.length&&r&&e.issues.push({...r,keys:i}),X(e))return e;const o=He(t.value,n.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}a(Jt,"handleIntersectionResults");const hi=l("$ZodEnum",(e,t)=>{D.init(e,t);const n=It(t.entries),s=new Set(n);e._zod.values=s,e._zod.pattern=new RegExp(`^(${n.filter(r=>Is.has(typeof r)).map(r=>typeof r=="string"?H(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return s.has(o)||r.issues.push({code:"invalid_value",values:n,input:o,inst:e}),r}}),fi=l("$ZodLiteral",(e,t)=>{if(D.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(s=>typeof s=="string"?H(s):s?H(s.toString()):String(s)).join("|")})$`),e._zod.parse=(s,r)=>{const i=s.value;return n.has(i)||s.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),s}}),pi=l("$ZodTransform",(e,t)=>{D.init(e,t),e._zod.optin="optional",e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new St(e.constructor.name);const r=t.transform(n.value,n);if(s.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(n.value=i,n.fallback=!0,n));if(r instanceof Promise)throw new Y;return n.value=r,n.fallback=!0,n}});function Gt(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}a(Gt,"handleOptionalResult");const Kt=l("$ZodOptional",(e,t)=>{D.init(e,t),e._zod.optin="optional",e._zod.optout="optional",$(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),$(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${We(n.source)})?$`):void 0}),e._zod.parse=(n,s)=>{if(t.innerType._zod.optin==="optional"){const r=n.value,i=t.innerType._zod.run(n,s);return i instanceof Promise?i.then(o=>Gt(o,r)):Gt(i,r)}return n.value===void 0?n:t.innerType._zod.run(n,s)}}),mi=l("$ZodExactOptional",(e,t)=>{Kt.init(e,t),$(e._zod,"values",()=>t.innerType._zod.values),$(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,s)=>t.innerType._zod.run(n,s)}),gi=l("$ZodNullable",(e,t)=>{D.init(e,t),$(e._zod,"optin",()=>t.innerType._zod.optin),$(e._zod,"optout",()=>t.innerType._zod.optout),$(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${We(n.source)}|null)$`):void 0}),$(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,s)=>n.value===null?n:t.innerType._zod.run(n,s)}),vi=l("$ZodDefault",(e,t)=>{D.init(e,t),e._zod.optin="optional",$(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,s)=>{if(s.direction==="backward")return t.innerType._zod.run(n,s);if(n.value===void 0)return n.value=t.defaultValue,n;const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(i=>Yt(i,t)):Yt(r,t)}});function Yt(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}a(Yt,"handleDefaultResult");const yi=l("$ZodPrefault",(e,t)=>{D.init(e,t),e._zod.optin="optional",$(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,s)=>(s.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,s))}),wi=l("$ZodNonOptional",(e,t)=>{D.init(e,t),$(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(s=>s!==void 0)):void 0}),e._zod.parse=(n,s)=>{const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(i=>Ht(i,e)):Ht(r,e)}});function Ht(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}a(Ht,"handleNonOptionalResult");const bi=l("$ZodCatch",(e,t)=>{D.init(e,t),e._zod.optin="optional",$(e._zod,"optout",()=>t.innerType._zod.optout),$(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,s)=>{if(s.direction==="backward")return t.innerType._zod.run(n,s);const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(o=>U(o,s,B()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(i=>U(i,s,B()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),_i=l("$ZodPipe",(e,t)=>{D.init(e,t),$(e._zod,"values",()=>t.in._zod.values),$(e._zod,"optin",()=>t.in._zod.optin),$(e._zod,"optout",()=>t.out._zod.optout),$(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,s)=>{if(s.direction==="backward"){const i=t.out._zod.run(n,s);return i instanceof Promise?i.then(o=>Ee(o,t.in,s)):Ee(i,t.in,s)}const r=t.in._zod.run(n,s);return r instanceof Promise?r.then(i=>Ee(i,t.out,s)):Ee(r,t.out,s)}});function Ee(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}a(Ee,"handlePipeResult");const ki=l("$ZodReadonly",(e,t)=>{D.init(e,t),$(e._zod,"propValues",()=>t.innerType._zod.propValues),$(e._zod,"values",()=>t.innerType._zod.values),$(e._zod,"optin",()=>t.innerType?._zod?.optin),$(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,s)=>{if(s.direction==="backward")return t.innerType._zod.run(n,s);const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(Xt):Xt(r)}});function Xt(e){return e.value=Object.freeze(e.value),e}a(Xt,"handleReadonlyResult");const Si=l("$ZodCustom",(e,t)=>{N.init(e,t),D.init(e,t),e._zod.parse=(n,s)=>n,e._zod.check=n=>{const s=n.value,r=t.fn(s);if(r instanceof Promise)return r.then(i=>Qt(i,n,s,e));Qt(r,n,s,e)}});function Qt(e,t,n,s){if(!e){const r={code:"custom",input:n,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(r.params=s._zod.def.params),t.issues.push(ie(r))}}a(Qt,"handleRefineResult");var en,Ii=class{static{a(this,"$ZodRegistry")}constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const s={...n,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function zi(){return new Ii}a(zi,"registry"),(en=globalThis).__zod_globalRegistry??(en.__zod_globalRegistry=zi());const oe=globalThis.__zod_globalRegistry;function $i(e,t){return new e({type:"string",...y(t)})}a($i,"_string");function Ei(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...y(t)})}a(Ei,"_email");function tn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...y(t)})}a(tn,"_guid");function Oi(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...y(t)})}a(Oi,"_uuid");function Pi(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...y(t)})}a(Pi,"_uuidv4");function Di(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...y(t)})}a(Di,"_uuidv6");function Ci(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...y(t)})}a(Ci,"_uuidv7");function Ai(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...y(t)})}a(Ai,"_url");function Ti(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...y(t)})}a(Ti,"_emoji");function Zi(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...y(t)})}a(Zi,"_nanoid");function Ni(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...y(t)})}a(Ni,"_cuid");function Mi(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...y(t)})}a(Mi,"_cuid2");function xi(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...y(t)})}a(xi,"_ulid");function qi(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...y(t)})}a(qi,"_xid");function Ri(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...y(t)})}a(Ri,"_ksuid");function ji(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...y(t)})}a(ji,"_ipv4");function Fi(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...y(t)})}a(Fi,"_ipv6");function Bi(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...y(t)})}a(Bi,"_cidrv4");function Li(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...y(t)})}a(Li,"_cidrv6");function Ui(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...y(t)})}a(Ui,"_base64");function Vi(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...y(t)})}a(Vi,"_base64url");function Wi(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...y(t)})}a(Wi,"_e164");function Ji(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...y(t)})}a(Ji,"_jwt");function Gi(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...y(t)})}a(Gi,"_isoDateTime");function Ki(e,t){return new e({type:"string",format:"date",check:"string_format",...y(t)})}a(Ki,"_isoDate");function Yi(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...y(t)})}a(Yi,"_isoTime");function Hi(e,t){return new e({type:"string",format:"duration",check:"string_format",...y(t)})}a(Hi,"_isoDuration");function Xi(e,t){return new e({type:"number",checks:[],...y(t)})}a(Xi,"_number");function Qi(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...y(t)})}a(Qi,"_int");function eo(e){return new e({type:"unknown"})}a(eo,"_unknown");function to(e,t){return new e({type:"never",...y(t)})}a(to,"_never");function nn(e,t){return new qt({check:"less_than",...y(t),value:e,inclusive:!1})}a(nn,"_lt");function Xe(e,t){return new qt({check:"less_than",...y(t),value:e,inclusive:!0})}a(Xe,"_lte");function sn(e,t){return new Rt({check:"greater_than",...y(t),value:e,inclusive:!1})}a(sn,"_gt");function Qe(e,t){return new Rt({check:"greater_than",...y(t),value:e,inclusive:!0})}a(Qe,"_gte");function rn(e,t){return new wr({check:"multiple_of",...y(t),value:e})}a(rn,"_multipleOf");function on(e,t){return new _r({check:"max_length",...y(t),maximum:e})}a(on,"_maxLength");function Oe(e,t){return new kr({check:"min_length",...y(t),minimum:e})}a(Oe,"_minLength");function an(e,t){return new Sr({check:"length_equals",...y(t),length:e})}a(an,"_length");function no(e,t){return new Ir({check:"string_format",format:"regex",...y(t),pattern:e})}a(no,"_regex");function so(e){return new zr({check:"string_format",format:"lowercase",...y(e)})}a(so,"_lowercase");function ro(e){return new $r({check:"string_format",format:"uppercase",...y(e)})}a(ro,"_uppercase");function io(e,t){return new Er({check:"string_format",format:"includes",...y(t),includes:e})}a(io,"_includes");function oo(e,t){return new Or({check:"string_format",format:"starts_with",...y(t),prefix:e})}a(oo,"_startsWith");function ao(e,t){return new Pr({check:"string_format",format:"ends_with",...y(t),suffix:e})}a(ao,"_endsWith");function Q(e){return new Dr({check:"overwrite",tx:e})}a(Q,"_overwrite");function co(e){return Q(t=>t.normalize(e))}a(co,"_normalize");function uo(){return Q(e=>e.trim())}a(uo,"_trim");function lo(){return Q(e=>e.toLowerCase())}a(lo,"_toLowerCase");function ho(){return Q(e=>e.toUpperCase())}a(ho,"_toUpperCase");function fo(){return Q(e=>ks(e))}a(fo,"_slugify");function po(e,t,n){return new e({type:"array",element:t,...y(n)})}a(po,"_array");function mo(e,t,n){const s=y(n);return s.abort??(s.abort=!0),new e({type:"custom",check:"custom",fn:t,...s})}a(mo,"_custom");function go(e,t,n){return new e({type:"custom",check:"custom",fn:t,...y(n)})}a(go,"_refine");function vo(e,t){const n=yo(s=>(s.addIssue=r=>{if(typeof r=="string")s.issues.push(ie(r,s.value,n._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=s.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),s.issues.push(ie(i))}},e(s.value,s)),t);return n}a(vo,"_superRefine");function yo(e,t){const n=new N({check:"custom",...y(t)});return n._zod.check=e,n}a(yo,"_check");function cn(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??oe,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}a(cn,"initializeContext");function T(e,t,n={path:[],schemaPath:[]}){var s;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);const c=e._zod.toJSONSchema?.();if(c)o.schema=c;else{const u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,u);else{const m=o.schema,v=t.processors[r.type];if(!v)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);v(e,t,m,u)}const h=e._zod.parent;h&&(o.ref||(o.ref=h),T(h,t,u),t.seen.get(h).isParent=!0)}const d=t.metadataRegistry.get(e);return d&&Object.assign(o.schema,d),t.io==="input"&&Z(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&"_prefault"in o.schema&&((s=o.schema).default??(s.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}a(T,"process");function un(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const o of e.seen.entries()){const c=e.metadataRegistry.get(o[0])?.id;if(c){const d=s.get(c);if(d&&d!==o[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(c,o[0])}}const r=a(o=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const h=e.external.registry.get(o[0])?.id,m=e.external.uri??(b=>b);if(h)return{ref:m(h)};const v=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=v,{defId:v,ref:`${m("__shared")}#/${c}/${v}`}}if(o[1]===n)return{ref:"#"};const d=`#/${c}/`,u=o[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:d+u}},"makeURI"),i=a(o=>{if(o[1].schema.$ref)return;const c=o[1],{ref:d,defId:u}=r(o);c.def={...c.schema},u&&(c.defId=u);const h=c.schema;for(const m in h)delete h[m];h.$ref=d},"extractToDef");if(e.cycles==="throw")for(const o of e.seen.entries()){const c=o[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
63
63
 
64
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const c=o[1];if(t===o[0]){i(o);continue}if(e.external){const d=e.external.registry.get(o[0])?.id;if(t!==o[0]&&d){i(o);continue}}if(e.metadataRegistry.get(o[0])?.id){i(o);continue}if(c.cycle){i(o);continue}if(c.count>1&&e.reused==="ref"){i(o);continue}}}a(un,"extractDefs");function dn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=a(c=>{const d=e.seen.get(c);if(d.ref===null)return;const u=d.def??d.schema,h={...u},m=d.ref;if(d.ref=null,m){s(m);const b=e.seen.get(m),z=b.schema;if(z.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(z)):Object.assign(u,z),Object.assign(u,h),c._zod.parent===m)for(const p in u)p==="$ref"||p==="allOf"||p in h||delete u[p];if(z.$ref&&b.def)for(const p in u)p==="$ref"||p==="allOf"||p in b.def&&JSON.stringify(u[p])===JSON.stringify(b.def[p])&&delete u[p]}const v=c._zod.parent;if(v&&v!==m){s(v);const b=e.seen.get(v);if(b?.schema.$ref&&(u.$ref=b.schema.$ref,b.def))for(const z in u)z==="$ref"||z==="allOf"||z in b.def&&JSON.stringify(u[z])===JSON.stringify(b.def[z])&&delete u[z]}e.override({zodSchema:c,jsonSchema:u,path:d.path??[]})},"flattenRef");for(const c of[...e.seen.entries()].reverse())s(c[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const c=e.external.registry.get(t)?.id;if(!c)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(c)}Object.assign(r,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&r.id===i&&delete r.id;const o=e.external?.defs??{};for(const c of e.seen.entries()){const d=c[1];d.def&&d.defId&&(d.def.id===d.defId&&delete d.def.id,o[d.defId]=d.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?r.$defs=o:r.definitions=o);try{const c=JSON.parse(JSON.stringify(r));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:Pe(t,"input",e.processors),output:Pe(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}a(dn,"finalize$1");function Z(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return Z(s.element,n);if(s.type==="set")return Z(s.valueType,n);if(s.type==="lazy")return Z(s.getter(),n);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return Z(s.innerType,n);if(s.type==="intersection")return Z(s.left,n)||Z(s.right,n);if(s.type==="record"||s.type==="map")return Z(s.keyType,n)||Z(s.valueType,n);if(s.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Z(s.in,n)||Z(s.out,n);if(s.type==="object"){for(const r in s.shape)if(Z(s.shape[r],n))return!0;return!1}if(s.type==="union"){for(const r of s.options)if(Z(r,n))return!0;return!1}if(s.type==="tuple"){for(const r of s.items)if(Z(r,n))return!0;return!!(s.rest&&Z(s.rest,n))}return!1}a(Z,"isTransforming");const wo=a((e,t={})=>n=>{const s=cn({...n,processors:t});return T(e,s),un(s,e),dn(s,e)},"createToJSONSchemaMethod"),Pe=a((e,t,n={})=>s=>{const{libraryOptions:r,target:i}=s??{},o=cn({...r??{},target:i,io:t,processors:n});return T(e,o),un(o,e),dn(o,e)},"createStandardJSONSchemaMethod"),bo={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_o=a((e,t,n,s)=>{const r=n;r.type="string";const{minimum:i,maximum:o,format:c,patterns:d,contentEncoding:u}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof o=="number"&&(r.maxLength=o),c&&(r.format=bo[c]??c,r.format===""&&delete r.format,c==="time"&&delete r.format),u&&(r.contentEncoding=u),d&&d.size>0){const h=[...d];h.length===1?r.pattern=h[0].source:h.length>1&&(r.allOf=[...h.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},"stringProcessor"),ko=a((e,t,n,s)=>{const r=n,{minimum:i,maximum:o,format:c,multipleOf:d,exclusiveMaximum:u,exclusiveMinimum:h}=e._zod.bag;typeof c=="string"&&c.includes("int")?r.type="integer":r.type="number";const m=typeof h=="number"&&h>=(i??Number.NEGATIVE_INFINITY),v=typeof u=="number"&&u<=(o??Number.POSITIVE_INFINITY),b=t.target==="draft-04"||t.target==="openapi-3.0";m?b?(r.minimum=h,r.exclusiveMinimum=!0):r.exclusiveMinimum=h:typeof i=="number"&&(r.minimum=i),v?b?(r.maximum=u,r.exclusiveMaximum=!0):r.exclusiveMaximum=u:typeof o=="number"&&(r.maximum=o),typeof d=="number"&&(r.multipleOf=d)},"numberProcessor"),So=a((e,t,n,s)=>{n.not={}},"neverProcessor"),Io=a((e,t,n,s)=>{const r=e._zod.def,i=It(r.entries);i.every(o=>typeof o=="number")&&(n.type="number"),i.every(o=>typeof o=="string")&&(n.type="string"),n.enum=i},"enumProcessor"),zo=a((e,t,n,s)=>{const r=e._zod.def,i=[];for(const o of r.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(i.length!==0)if(i.length===1){const o=i[0];n.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[o]:n.const=o}else i.every(o=>typeof o=="number")&&(n.type="number"),i.every(o=>typeof o=="string")&&(n.type="string"),i.every(o=>typeof o=="boolean")&&(n.type="boolean"),i.every(o=>o===null)&&(n.type="null"),n.enum=i},"literalProcessor"),$o=a((e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},"customProcessor"),Eo=a((e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},"transformProcessor"),Oo=a((e,t,n,s)=>{const r=n,i=e._zod.def,{minimum:o,maximum:c}=e._zod.bag;typeof o=="number"&&(r.minItems=o),typeof c=="number"&&(r.maxItems=c),r.type="array",r.items=T(i.element,t,{...s,path:[...s.path,"items"]})},"arrayProcessor"),Po=a((e,t,n,s)=>{const r=n,i=e._zod.def;r.type="object",r.properties={};const o=i.shape;for(const u in o)r.properties[u]=T(o[u],t,{...s,path:[...s.path,"properties",u]});const c=new Set(Object.keys(o)),d=new Set([...c].filter(u=>{const h=i.shape[u]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));d.size>0&&(r.required=Array.from(d)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=T(i.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},"objectProcessor"),Do=a((e,t,n,s)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((c,d)=>T(c,t,{...s,path:[...s.path,i?"oneOf":"anyOf",d]}));i?n.oneOf=o:n.anyOf=o},"unionProcessor"),Co=a((e,t,n,s)=>{const r=e._zod.def,i=T(r.left,t,{...s,path:[...s.path,"allOf",0]}),o=T(r.right,t,{...s,path:[...s.path,"allOf",1]}),c=a(d=>"allOf"in d&&Object.keys(d).length===1,"isSimpleIntersection");n.allOf=[...c(i)?i.allOf:[i],...c(o)?o.allOf:[o]]},"intersectionProcessor"),Ao=a((e,t,n,s)=>{const r=e._zod.def,i=T(r.innerType,t,s),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=r.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},"nullableProcessor"),To=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType},"nonoptionalProcessor"),Zo=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},"defaultProcessor"),No=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},"prefaultProcessor"),Mo=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},"catchProcessor"),xo=a((e,t,n,s)=>{const r=e._zod.def,i=r.in._zod.traits.has("$ZodTransform"),o=t.io==="input"?i?r.out:r.in:r.out;T(o,t,s);const c=t.seen.get(e);c.ref=o},"pipeProcessor"),qo=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType,n.readOnly=!0},"readonlyProcessor"),ln=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType},"optionalProcessor"),Ro=l("ZodISODateTime",(e,t)=>{Ur.init(e,t),P.init(e,t)});function jo(e){return Gi(Ro,e)}a(jo,"datetime");const Fo=l("ZodISODate",(e,t)=>{Vr.init(e,t),P.init(e,t)});function Bo(e){return Ki(Fo,e)}a(Bo,"date");const Lo=l("ZodISOTime",(e,t)=>{Wr.init(e,t),P.init(e,t)});function Uo(e){return Yi(Lo,e)}a(Uo,"time");const Vo=l("ZodISODuration",(e,t)=>{Jr.init(e,t),P.init(e,t)});function Wo(e){return Hi(Vo,e)}a(Wo,"duration");const q=l("ZodError",a((e,t)=>{Ct.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a(n=>Ms(e,n),"value")},flatten:{value:a(n=>Ns(e,n),"value")},addIssue:{value:a(n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Ue,2)},"value")},addIssues:{value:a(n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Ue,2)},"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),{Parent:Error}),Jo=Ge(q),Go=Ke(q),Ko=Se(q),Yo=Ie(q),Ho=Rs(q),Xo=js(q),Qo=Fs(q),ea=Bs(q),ta=Ls(q),na=Us(q),sa=Vs(q),ra=Ws(q),hn=new WeakMap;function ae(e,t,n){const s=Object.getPrototypeOf(e);let r=hn.get(s);if(r||(r=new Set,hn.set(s,r)),!r.has(t)){r.add(t);for(const i in n){const o=n[i];Object.defineProperty(s,i,{configurable:!0,enumerable:!1,get(){const c=o.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}a(ae,"_installLazyMethods");const C=l("ZodType",(e,t)=>(D.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Pe(e,"input"),output:Pe(e,"output")}}),e.toJSONSchema=wo(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,s)=>Jo(e,n,s,{callee:e.parse}),e.safeParse=(n,s)=>Ko(e,n,s),e.parseAsync=async(n,s)=>Go(e,n,s,{callee:e.parseAsync}),e.safeParseAsync=async(n,s)=>Yo(e,n,s),e.spa=e.safeParseAsync,e.encode=(n,s)=>Ho(e,n,s),e.decode=(n,s)=>Xo(e,n,s),e.encodeAsync=async(n,s)=>Qo(e,n,s),e.decodeAsync=async(n,s)=>ea(e,n,s),e.safeEncode=(n,s)=>ta(e,n,s),e.safeDecode=(n,s)=>na(e,n,s),e.safeEncodeAsync=async(n,s)=>sa(e,n,s),e.safeDecodeAsync=async(n,s)=>ra(e,n,s),ae(e,"ZodType",{check(...n){const s=this.def;return this.clone(j(s,{checks:[...s.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,s){return F(this,n,s)},brand(){return this},register(n,s){return n.add(this,s),this},refine(n,s){return this.check(Ya(n,s))},superRefine(n,s){return this.check(Ha(n,s))},overwrite(n){return this.check(Q(n))},optional(){return _n(this)},exactOptional(){return xa(this)},nullable(){return kn(this)},nullish(){return _n(kn(this))},nonoptional(n){return La(this,n)},array(){return et(this)},or(n){return ce([this,n])},and(n){return Ca(this,n)},transform(n){return In(this,Na(n))},default(n){return ja(this,n)},prefault(n){return Ba(this,n)},catch(n){return Va(this,n)},pipe(n){return In(this,n)},readonly(){return Ga(this)},describe(n){const s=this.clone();return oe.add(s,{description:n}),s},meta(...n){if(n.length===0)return oe.get(this);const s=this.clone();return oe.add(s,n[0]),s},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return oe.get(e)?.description},configurable:!0}),e)),fn=l("_ZodString",(e,t)=>{Ye.init(e,t),C.init(e,t),e._zod.processJSONSchema=(s,r,i)=>_o(e,s,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,ae(e,"_ZodString",{regex(...s){return this.check(no(...s))},includes(...s){return this.check(io(...s))},startsWith(...s){return this.check(oo(...s))},endsWith(...s){return this.check(ao(...s))},min(...s){return this.check(Oe(...s))},max(...s){return this.check(on(...s))},length(...s){return this.check(an(...s))},nonempty(...s){return this.check(Oe(1,...s))},lowercase(s){return this.check(so(s))},uppercase(s){return this.check(ro(s))},trim(){return this.check(uo())},normalize(...s){return this.check(co(...s))},toLowerCase(){return this.check(lo())},toUpperCase(){return this.check(ho())},slugify(){return this.check(fo())}})}),ia=l("ZodString",(e,t)=>{Ye.init(e,t),fn.init(e,t),e.email=n=>e.check(Ei(oa,n)),e.url=n=>e.check(Ai(aa,n)),e.jwt=n=>e.check(Ji(ka,n)),e.emoji=n=>e.check(Ti(ca,n)),e.guid=n=>e.check(tn(pn,n)),e.uuid=n=>e.check(Oi(De,n)),e.uuidv4=n=>e.check(Pi(De,n)),e.uuidv6=n=>e.check(Di(De,n)),e.uuidv7=n=>e.check(Ci(De,n)),e.nanoid=n=>e.check(Zi(ua,n)),e.guid=n=>e.check(tn(pn,n)),e.cuid=n=>e.check(Ni(da,n)),e.cuid2=n=>e.check(Mi(la,n)),e.ulid=n=>e.check(xi(ha,n)),e.base64=n=>e.check(Ui(wa,n)),e.base64url=n=>e.check(Vi(ba,n)),e.xid=n=>e.check(qi(fa,n)),e.ksuid=n=>e.check(Ri(pa,n)),e.ipv4=n=>e.check(ji(ma,n)),e.ipv6=n=>e.check(Fi(ga,n)),e.cidrv4=n=>e.check(Bi(va,n)),e.cidrv6=n=>e.check(Li(ya,n)),e.e164=n=>e.check(Wi(_a,n)),e.datetime=n=>e.check(jo(n)),e.date=n=>e.check(Bo(n)),e.time=n=>e.check(Uo(n)),e.duration=n=>e.check(Wo(n))});function f(e){return $i(ia,e)}a(f,"string");const P=l("ZodStringFormat",(e,t)=>{O.init(e,t),fn.init(e,t)}),oa=l("ZodEmail",(e,t)=>{Nr.init(e,t),P.init(e,t)}),pn=l("ZodGUID",(e,t)=>{Tr.init(e,t),P.init(e,t)}),De=l("ZodUUID",(e,t)=>{Zr.init(e,t),P.init(e,t)}),aa=l("ZodURL",(e,t)=>{Mr.init(e,t),P.init(e,t)}),ca=l("ZodEmoji",(e,t)=>{xr.init(e,t),P.init(e,t)}),ua=l("ZodNanoID",(e,t)=>{qr.init(e,t),P.init(e,t)}),da=l("ZodCUID",(e,t)=>{Rr.init(e,t),P.init(e,t)}),la=l("ZodCUID2",(e,t)=>{jr.init(e,t),P.init(e,t)}),ha=l("ZodULID",(e,t)=>{Fr.init(e,t),P.init(e,t)}),fa=l("ZodXID",(e,t)=>{Br.init(e,t),P.init(e,t)}),pa=l("ZodKSUID",(e,t)=>{Lr.init(e,t),P.init(e,t)}),ma=l("ZodIPv4",(e,t)=>{Gr.init(e,t),P.init(e,t)}),ga=l("ZodIPv6",(e,t)=>{Kr.init(e,t),P.init(e,t)}),va=l("ZodCIDRv4",(e,t)=>{Yr.init(e,t),P.init(e,t)}),ya=l("ZodCIDRv6",(e,t)=>{Hr.init(e,t),P.init(e,t)}),wa=l("ZodBase64",(e,t)=>{Xr.init(e,t),P.init(e,t)}),ba=l("ZodBase64URL",(e,t)=>{ei.init(e,t),P.init(e,t)}),_a=l("ZodE164",(e,t)=>{ti.init(e,t),P.init(e,t)}),ka=l("ZodJWT",(e,t)=>{si.init(e,t),P.init(e,t)}),mn=l("ZodNumber",(e,t)=>{Ft.init(e,t),C.init(e,t),e._zod.processJSONSchema=(s,r,i)=>ko(e,s,r,i),ae(e,"ZodNumber",{gt(s,r){return this.check(sn(s,r))},gte(s,r){return this.check(Qe(s,r))},min(s,r){return this.check(Qe(s,r))},lt(s,r){return this.check(nn(s,r))},lte(s,r){return this.check(Xe(s,r))},max(s,r){return this.check(Xe(s,r))},int(s){return this.check(vn(s))},safe(s){return this.check(vn(s))},positive(s){return this.check(sn(0,s))},nonnegative(s){return this.check(Qe(0,s))},negative(s){return this.check(nn(0,s))},nonpositive(s){return this.check(Xe(0,s))},multipleOf(s,r){return this.check(rn(s,r))},step(s,r){return this.check(rn(s,r))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function gn(e){return Xi(mn,e)}a(gn,"number");const Sa=l("ZodNumberFormat",(e,t)=>{ri.init(e,t),mn.init(e,t)});function vn(e){return Qi(Sa,e)}a(vn,"int");const Ia=l("ZodUnknown",(e,t)=>{ii.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>{}});function ee(){return eo(Ia)}a(ee,"unknown");const za=l("ZodNever",(e,t)=>{oi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>So(e,n,s,r)});function $a(e){return to(za,e)}a($a,"never");const Ea=l("ZodArray",(e,t)=>{ai.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Oo(e,n,s,r),e.element=t.element,ae(e,"ZodArray",{min(n,s){return this.check(Oe(n,s))},nonempty(n){return this.check(Oe(1,n))},max(n,s){return this.check(on(n,s))},length(n,s){return this.check(an(n,s))},unwrap(){return this.element}})});function et(e,t){return po(Ea,e,t)}a(et,"array");const Oa=l("ZodObject",(e,t)=>{ui.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Po(e,n,s,r),$(e,"shape",()=>t.shape),ae(e,"ZodObject",{keyof(){return Aa(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:ee()})},loose(){return this.clone({...this._zod.def,catchall:ee()})},strict(){return this.clone({...this._zod.def,catchall:$a()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Ps(this,n)},safeExtend(n){return Ds(this,n)},merge(n){return Cs(this,n)},pick(n){return Es(this,n)},omit(n){return Os(this,n)},partial(...n){return As(bn,this,n[0])},required(...n){return Ts(Sn,this,n[0])}})});function g(e,t){return new Oa({type:"object",shape:e??{},...y(t)})}a(g,"object");const yn=l("ZodUnion",(e,t)=>{Wt.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Do(e,n,s,r),e.options=t.options});function ce(e,t){return new yn({type:"union",options:e,...y(t)})}a(ce,"union");const Pa=l("ZodDiscriminatedUnion",(e,t)=>{yn.init(e,t),di.init(e,t)});function wn(e,t,n){return new Pa({type:"union",options:t,discriminator:e,...y(n)})}a(wn,"discriminatedUnion");const Da=l("ZodIntersection",(e,t)=>{li.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Co(e,n,s,r)});function Ca(e,t){return new Da({type:"intersection",left:e,right:t})}a(Ca,"intersection");const tt=l("ZodEnum",(e,t)=>{hi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(s,r,i)=>Io(e,s,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(s,r)=>{const i={};for(const o of s)if(n.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new tt({...t,checks:[],...y(r),entries:i})},e.exclude=(s,r)=>{const i={...t.entries};for(const o of s)if(n.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new tt({...t,checks:[],...y(r),entries:i})}});function Aa(e,t){return new tt({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e,...y(t)})}a(Aa,"_enum");const Ta=l("ZodLiteral",(e,t)=>{fi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>zo(e,n,s,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function w(e,t){return new Ta({type:"literal",values:Array.isArray(e)?e:[e],...y(t)})}a(w,"literal");const Za=l("ZodTransform",(e,t)=>{pi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Eo(e,n,s,r),e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new St(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(ie(i,n.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),n.issues.push(ie(o))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=r,n.fallback=!0,n)}});function Na(e){return new Za({type:"transform",transform:e})}a(Na,"transform");const bn=l("ZodOptional",(e,t)=>{Kt.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>ln(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function _n(e){return new bn({type:"optional",innerType:e})}a(_n,"optional");const Ma=l("ZodExactOptional",(e,t)=>{mi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>ln(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function xa(e){return new Ma({type:"optional",innerType:e})}a(xa,"exactOptional");const qa=l("ZodNullable",(e,t)=>{gi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Ao(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function kn(e){return new qa({type:"nullable",innerType:e})}a(kn,"nullable");const Ra=l("ZodDefault",(e,t)=>{vi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Zo(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ja(e,t){return new Ra({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Ot(t)}})}a(ja,"_default");const Fa=l("ZodPrefault",(e,t)=>{yi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>No(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function Ba(e,t){return new Fa({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Ot(t)}})}a(Ba,"prefault");const Sn=l("ZodNonOptional",(e,t)=>{wi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>To(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function La(e,t){return new Sn({type:"nonoptional",innerType:e,...y(t)})}a(La,"nonoptional");const Ua=l("ZodCatch",(e,t)=>{bi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Mo(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Va(e,t){return new Ua({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}a(Va,"_catch");const Wa=l("ZodPipe",(e,t)=>{_i.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>xo(e,n,s,r),e.in=t.in,e.out=t.out});function In(e,t){return new Wa({type:"pipe",in:e,out:t})}a(In,"pipe");const Ja=l("ZodReadonly",(e,t)=>{ki.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>qo(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function Ga(e){return new Ja({type:"readonly",innerType:e})}a(Ga,"readonly");const zn=l("ZodCustom",(e,t)=>{Si.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>$o(e,n,s,r)});function Ka(e,t){return mo(zn,e??(()=>!0),t)}a(Ka,"custom");function Ya(e,t={}){return go(zn,e,t)}a(Ya,"refine");function Ha(e,t){return vo(e,t)}a(Ha,"superRefine");const Ce=f(),Xa=wn("code",[g({code:w("bad-request"),message:f(),details:g({issues:et(Ka())})}),g({code:w("cancelled"),message:f(),details:g({})}),g({code:w("session-not-found"),message:f(),details:g({sessionId:f()})}),g({code:w("model-unavailable"),message:f(),details:g({provider:f(),model:f()})}),g({code:w("session-conflict"),message:f(),details:g({sessionId:f(),requestedCwd:f(),existingCwd:f().optional()})}),g({code:w("invalid-time-zone"),message:f(),details:g({value:f()})}),g({code:w("workspace-attach-failed"),message:f(),details:g({sessionId:f(),workspaceId:f()})}),g({code:w("workspace-not-found"),message:f(),details:g({workspaceId:f()})}),g({code:w("workspace-invalid-path"),message:f(),details:g({path:f()})}),g({code:w("workspace-name-conflict"),message:f(),details:g({name:f()})}),g({code:w("workspace-move-invalid"),message:f(),details:g({workspaceId:f(),sessionId:f(),beforeSessionId:f().optional()})}),g({code:w("directory-unreadable"),message:f(),details:g({path:f()})}),g({code:w("directory-exists"),message:f(),details:g({path:f()})}),g({code:w("directory-create-failed"),message:f(),details:g({path:f()})}),g({code:w("directory-picker-unavailable"),message:f(),details:g({capability:f()})}),g({code:w("agent-preset-read-only"),message:f(),details:g({agentPreset:f(),reason:f()})}),g({code:w("agent-preset-locked"),message:f(),details:g({sessionId:f(),agentPreset:f()})}),g({code:w("agent-preset-conflict"),message:f(),details:g({sessionId:f(),requestedPreset:f(),existingPreset:f().optional()})}),g({code:w("agent-preset-not-found"),message:f(),details:g({agentPreset:f(),available:et(f())})}),g({code:w("agent-preset-invalid"),message:f(),details:g({agentPreset:f(),reason:f()})}),g({code:w("agent-busy"),message:f(),details:g({reason:f()})}),g({code:w("attachment-error"),message:f(),details:g({reason:f()})}),g({code:w("queue-item-not-found"),message:f(),details:g({itemId:f()})}),g({code:w("steer-unavailable"),message:f(),details:g({itemId:f()})}),g({code:w("command-error"),message:f(),details:g({})}),g({code:w("unknown-command"),message:f(),details:g({})}),g({code:w("settings-rejected"),message:f(),details:g({ns:f()})}),g({code:w("settings-not-exposed"),message:f(),details:g({ns:f()})}),g({code:w("settings-conflict"),message:f(),details:g({ns:f(),expected:gn(),actual:gn()})}),g({code:w("credential-rejected"),message:f(),details:g({ref:f()})}),g({code:w("model-discovery-failed"),message:f(),details:g({settingsNs:f(),baseURL:f().optional()})}),g({code:w("title-invalid"),message:f(),details:g({sessionId:f()})}),g({code:w("fork-unavailable"),message:f(),details:g({sessionId:f()})}),g({code:w("subagent-parent-unavailable"),message:f(),details:g({parentSessionId:f()})}),g({code:w("subagent-not-found"),message:f(),details:g({parentSessionId:f(),childSessionId:f()})}),g({code:w("subagent-catalog-diagnostic"),message:f(),details:g({parentSessionId:f(),childSessionId:f(),reason:ce([w("corrupt"),w("unsupported"),w("unavailable")])})}),g({code:w("subagent-not-resumable"),message:f(),details:g({childSessionId:f()})}),g({code:w("subagent-unauthorized"),message:f(),details:g({childSessionId:f()})}),g({code:w("subagent-delivery-unavailable"),message:f(),details:g({childSessionId:f()})}),g({code:w("internal"),message:f(),details:g({})})]);function $n(e){return ce([g({ok:w(!0),value:e}),g({ok:w(!1),error:Xa})])}a($n,"rpcResultSchema"),wn("type",[g({type:w("client-request"),rpcId:Ce,method:f(),payload:ee()}),g({type:w("server-response"),rpcId:Ce,result:$n(ee().optional())}),g({type:w("server-request"),rpcId:Ce,method:f(),payload:ee()}),g({type:w("client-response"),rpcId:Ce,result:$n(ee().optional())})]),ce([g({accepted:w(!0)}),g({accepted:w(!1),reason:ce([w("not-pending"),w("bad-response")])})]);const En=a(e=>{let t;const n=new Set,s=a((d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const m=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(v=>v(t,m))}},"setState"),r=a(()=>t,"getState"),c={setState:s,getState:r,subscribe:a(d=>(n.add(d),()=>n.delete(d)),"subscribe"),destroy:a(()=>{n.clear()},"destroy")};return t=e(s,r,c),c},"createStoreImpl"),Qa=a(e=>e?En(e):En,"createStore"),ec=a(e=>(t,n,s)=>{const r=s.subscribe;return s.subscribe=(i,o,c)=>{let d=i;if(o){const u=c?.equalityFn||Object.is;let h=i(s.getState());d=a(m=>{const v=i(m);if(!u(h,v)){const b=h;o(h=v,b)}},"listener"),c?.fireImmediately&&o(h,h)}return r(d)},e(t,n,s)},"subscribeWithSelectorImpl");function tc(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[s,r]of e)if(!Object.is(r,t.get(s)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const s of e)if(!t.has(s))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(t,n[s])||!Object.is(e[n[s]],t[n[s]]))return!1;return!0}a(tc,"shallow$1");var On=Symbol.for("immer-nothing"),Pn=Symbol.for("immer-draftable"),x=Symbol.for("immer-state");function R(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}a(R,"die");var ue=Object.getPrototypeOf;function te(e){return!!e&&!!e[x]}a(te,"isDraft");function V(e){return e?Cn(e)||Array.isArray(e)||!!e[Pn]||!!e.constructor?.[Pn]||de(e)||Ze(e):!1}a(V,"isDraftable");var nc=Object.prototype.constructor.toString(),Dn=new WeakMap;function Cn(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let s=Dn.get(n);return s===void 0&&(s=Function.toString.call(n),Dn.set(n,s)),s===nc}a(Cn,"isPlainObject");function Ae(e,t,n=!0){Te(e)===0?(n?Reflect.ownKeys(e):Object.keys(e)).forEach(s=>{t(s,e[s],e)}):e.forEach((s,r)=>t(r,s,e))}a(Ae,"each");function Te(e){const t=e[x];return t?t.type_:Array.isArray(e)?1:de(e)?2:Ze(e)?3:0}a(Te,"getArchtype");function nt(e,t){return Te(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}a(nt,"has");function An(e,t,n){const s=Te(e);s===2?e.set(t,n):s===3?e.add(n):e[t]=n}a(An,"set");function sc(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}a(sc,"is");function de(e){return e instanceof Map}a(de,"isMap");function Ze(e){return e instanceof Set}a(Ze,"isSet");function W(e){return e.copy_||e.base_}a(W,"latest");function st(e,t){if(de(e))return new Map(e);if(Ze(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=Cn(e);if(t===!0||t==="class_only"&&!n){const s=Object.getOwnPropertyDescriptors(e);delete s[x];let r=Reflect.ownKeys(s);for(let i=0;i<r.length;i++){const o=r[i],c=s[o];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(s[o]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[o]})}return Object.create(ue(e),s)}else{const s=ue(e);return s!==null&&n?{...e}:Object.assign(Object.create(s),e)}}a(st,"shallowCopy");function rt(e,t=!1){return Me(e)||te(e)||!V(e)||(Te(e)>1&&Object.defineProperties(e,{set:Ne,add:Ne,clear:Ne,delete:Ne}),Object.freeze(e),t&&Object.values(e).forEach(n=>rt(n,!0))),e}a(rt,"freeze");function rc(){R(2)}a(rc,"dontMutateFrozenCollections");var Ne={value:rc};function Me(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}a(Me,"isFrozen");var ic={};function J(e){const t=ic[e];return t||R(0,e),t}a(J,"getPlugin");var le;function Tn(){return le}a(Tn,"getCurrentScope");function oc(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}a(oc,"createScope$1");function Zn(e,t){t&&(J("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}a(Zn,"usePatchesInScope");function it(e){ot(e),e.drafts_.forEach(ac),e.drafts_=null}a(it,"revokeScope");function ot(e){e===le&&(le=e.parent_)}a(ot,"leaveScope");function Nn(e){return le=oc(le,e)}a(Nn,"enterScope");function ac(e){const t=e[x];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}a(ac,"revokeDraft");function Mn(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[x].modified_&&(it(t),R(4)),V(e)&&(e=xe(t,e),t.parent_||qe(t,e)),t.patches_&&J("Patches").generateReplacementPatches_(n[x].base_,e,t.patches_,t.inversePatches_)):e=xe(t,n,[]),it(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==On?e:void 0}a(Mn,"processResult");function xe(e,t,n){if(Me(t))return t;const s=e.immer_.shouldUseStrictIteration(),r=t[x];if(!r)return Ae(t,(i,o)=>xn(e,r,t,i,o,n),s),t;if(r.scope_!==e)return t;if(!r.modified_)return qe(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const i=r.copy_;let o=i,c=!1;r.type_===3&&(o=new Set(i),i.clear(),c=!0),Ae(o,(d,u)=>xn(e,r,i,d,u,n,c),s),qe(e,i,!1),n&&e.patches_&&J("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}a(xe,"finalize");function xn(e,t,n,s,r,i,o){if(r==null||typeof r!="object"&&!o)return;const c=Me(r);if(!(c&&!o)){if(te(r)){const d=xe(e,r,i&&t&&t.type_!==3&&!nt(t.assigned_,s)?i.concat(s):void 0);if(An(n,s,d),te(d))e.canAutoFreeze_=!1;else return}else o&&n.add(r);if(V(r)&&!c){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[s]===r&&c)return;xe(e,r),(!t||!t.scope_.parent_)&&typeof s!="symbol"&&(de(n)?n.has(s):Object.prototype.propertyIsEnumerable.call(n,s))&&qe(e,r)}}}a(xn,"finalizeProperty");function qe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&rt(t,n)}a(qe,"maybeFreeze");function cc(e,t){const n=Array.isArray(e),s={type_:n?1:0,scope_:t?t.scope_:Tn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let r=s,i=at;n&&(r=[s],i=he);const{revoke:o,proxy:c}=Proxy.revocable(r,i);return s.draft_=c,s.revoke_=o,c}a(cc,"createProxyProxy");var at={get(e,t){if(t===x)return e;const n=W(e);if(!nt(n,t))return uc(e,n,t);const s=n[t];return e.finalized_||!V(s)?s:s===ct(e.base_,t)?(dt(e),e.copy_[t]=lt(s,e)):s},has(e,t){return t in W(e)},ownKeys(e){return Reflect.ownKeys(W(e))},set(e,t,n){const s=qn(W(e),t);if(s?.set)return s.set.call(e.draft_,n),!0;if(!e.modified_){const r=ct(W(e),t),i=r?.[x];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(sc(n,r)&&(n!==void 0||nt(e.base_,t)))return!0;dt(e),ut(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return ct(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,dt(e),ut(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=W(e),s=Reflect.getOwnPropertyDescriptor(n,t);return s&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:s.enumerable,value:n[t]}},defineProperty(){R(11)},getPrototypeOf(e){return ue(e.base_)},setPrototypeOf(){R(12)}},he={};Ae(at,(e,t)=>{he[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),he.deleteProperty=function(e,t){return he.set.call(this,e,t,void 0)},he.set=function(e,t,n){return at.set.call(this,e[0],t,n,e[0])};function ct(e,t){const n=e[x];return(n?W(n):e)[t]}a(ct,"peek");function uc(e,t,n){const s=qn(t,n);return s?"value"in s?s.value:s.get?.call(e.draft_):void 0}a(uc,"readPropFromProto");function qn(e,t){if(!(t in e))return;let n=ue(e);for(;n;){const s=Object.getOwnPropertyDescriptor(n,t);if(s)return s;n=ue(n)}}a(qn,"getDescriptorFromProto");function ut(e){e.modified_||(e.modified_=!0,e.parent_&&ut(e.parent_))}a(ut,"markChanged");function dt(e){e.copy_||(e.copy_=st(e.base_,e.scope_.immer_.useStrictShallowCopy_))}a(dt,"prepareCopy");var dc=class{static{a(this,"Immer2")}constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,n,s)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const o=this;return a(function(d=i,...u){return o.produce(d,h=>n.call(this,h,...u))},"curriedProduce")}typeof n!="function"&&R(6),s!==void 0&&typeof s!="function"&&R(7);let r;if(V(t)){const i=Nn(this),o=lt(t,void 0);let c=!0;try{r=n(o),c=!1}finally{c?it(i):ot(i)}return Zn(i,s),Mn(r,i)}else if(!t||typeof t!="object"){if(r=n(t),r===void 0&&(r=t),r===On&&(r=void 0),this.autoFreeze_&&rt(r,!0),s){const i=[],o=[];J("Patches").generateReplacementPatches_(t,r,i,o),s(i,o)}return r}else R(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(i,...o)=>this.produceWithPatches(i,c=>t(c,...o));let s,r;return[this.produce(t,n,(i,o)=>{s=i,r=o}),s,r]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof e?.useStrictIteration=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){V(e)||R(8),te(e)&&(e=lc(e));const t=Nn(this),n=lt(e,void 0);return n[x].isManual_=!0,ot(t),n}finishDraft(e,t){const n=e&&e[x];(!n||!n.isManual_)&&R(9);const{scope_:s}=n;return Zn(s,t),Mn(void 0,s)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(r.path.length===0&&r.op==="replace"){e=r.value;break}}n>-1&&(t=t.slice(n+1));const s=J("Patches").applyPatches_;return te(e)?s(e,t):this.produce(e,r=>s(r,t))}};function lt(e,t){const n=de(e)?J("MapSet").proxyMap_(e,t):Ze(e)?J("MapSet").proxySet_(e,t):cc(e,t);return(t?t.scope_:Tn()).drafts_.push(n),n}a(lt,"createProxy");function lc(e){return te(e)||R(10,e),Rn(e)}a(lc,"current");function Rn(e){if(!V(e)||Me(e))return e;const t=e[x];let n,s=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=st(e,t.scope_.immer_.useStrictShallowCopy_),s=t.scope_.immer_.shouldUseStrictIteration()}else n=st(e,!0);return Ae(n,(r,i)=>{An(n,r,Rn(i))},s),t&&(t.finalized_=!1),n}a(Rn,"currentImpl");var hc=new dc().produce;function fc(e,t){return tc(e,t)}a(fc,"shallowEqual");function pc(e){const t=typeof requestAnimationFrame=="function"?s=>{requestAnimationFrame(()=>{s()})}:s=>{queueMicrotask(s)};let n=!1;return()=>{n||(n=!0,t(()=>{n=!1,e()}))}}a(pc,"rafBatch");function fe(e,t){const n=ec(()=>e),s=Qa()(n);t?.persist&&mc(s,t.persist.name);let r=a(i=>s.subscribe(i),"subscribe");if(t?.flush==="raf"){const i=new Set,o=pc(()=>{for(const c of[...i])c()});s.subscribe(o),r=a(c=>(i.add(c),()=>{i.delete(c)}),"subscribe")}return{getSnapshot:a(()=>s.getState(),"getSnapshot"),subscribe:a(i=>r(i),"subscribe"),update:a(i=>{s.setState(hc(s.getState(),o=>{i(o)}),!0)},"update"),set:a(i=>{s.setState(i,!0)},"set")}}a(fe,"createSnapshotStore");function mc(e,t){if(!(typeof localStorage>"u")){try{const n=localStorage.getItem(t);n!==null&&e.setState(JSON.parse(n),!0)}catch(n){console.error(`snapshot store '${t}' rehydration failed:`,n)}e.subscribe(n=>{try{localStorage.setItem(t,JSON.stringify(n))}catch(s){console.error(`snapshot store '${t}' persistence failed:`,s)}})}}a(mc,"attachPersistence");function cu(e){return e}a(cu,"devFreeze");function gc(e){return{spec:e,create(t){const n=e.persist===void 0?void 0:t===void 0?e.persist:`${e.persist}.${t}`,s=fe(e.init(),n!==void 0?{persist:{name:n}}:void 0),r={};for(const i of Object.keys(e.actions)){const o=e.actions[i];r[i]=(...c)=>{s.update(d=>{o(d,...c)})}}return{actions:r,getSnapshot:a(()=>s.getSnapshot(),"getSnapshot"),subscribe:a(i=>s.subscribe(i),"subscribe"),store:s,clearPersisted:a(()=>{if(!(n===void 0||typeof localStorage>"u"))try{localStorage.removeItem(n)}catch{}},"clearPersisted")}}}}a(gc,"defineStore");const jn=Symbol("dsh.client.scope");function vc(){}a(vc,"agentScope");function Fn(e,t){const n=e.plugin(vc);return{fiber:n,ctx:n.ctx.extend({[jn]:t,[Be.Context.filter](s){const r=Re(s);return r===void 0||r===t}})}}a(Fn,"createScope");function Re(e){return e[jn]}a(Re,"scopeOf");function yc(e,t,n){const s=new Map;for(const o of t)s.set(n(o),o);const r=e.map(o=>s.get(n(o))).filter(o=>o!==void 0),i=new Set(r.map(n));for(let o=0;o<t.length;o++){const c=t[o];if(c===void 0||i.has(n(c)))continue;let d=r.length;for(let u=o+1;u<t.length;u++){const h=t[u];if(h===void 0)continue;const m=r.findIndex(v=>n(v)===n(h));if(m!==-1){d=m;break}}r.splice(d,0,c),i.add(n(c))}return r}a(yc,"mergeOrderedBaseline");function wc(e,t,n){const s=new Map;for(const u of e)s.set(u.sessionId,u);const r=new Map,i=[];for(const u of e)if(u.parentSessionId!==void 0&&s.has(u.parentSessionId)){const h=r.get(u.parentSessionId)??[];h.push(u),r.set(u.parentSessionId,h)}else i.push(u);const o=[],c=new Set,d=a((u,h)=>{if(c.has(u.sessionId)){console.warn(`[web-runtime] lineage cycle at ${u.sessionId}; emitting as root`);return}c.add(u.sessionId);const m=t?.get(u.sessionId);o.push({...u,...m===void 0?{}:{pendingInteraction:m},completed:n?.has(u.sessionId)??!1,depth:h});const v=r.get(u.sessionId);if(v!==void 0)for(const b of v)d(b,h+1)},"walk");for(const u of i)d(u,0);for(const u of e)c.has(u.sessionId)||d(u,0);return o}a(wc,"flattenLineage");var ne=class{static{a(this,"Notifier")}rebuild;listeners=new Set;dirty=!1;notifyPending=!1;scheduled="none";scheduleGeneration=0;constructor(e){this.rebuild=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}markDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled!=="microtask"&&this.schedule("microtask")}markFrameDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled==="none"&&this.schedule(typeof globalThis.requestAnimationFrame=="function"?"frame":"microtask")}notifyNow(){this.dirty=!0,this.notifyPending=!0,this.invalidateSchedule(),this.flush()}ensureFresh(){this.dirty&&(this.dirty=!1,this.rebuild())}schedule(e){const t=++this.scheduleGeneration;this.scheduled=e;const n=a(()=>{t===this.scheduleGeneration&&(this.scheduled="none",this.flush())},"publish");e==="frame"?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled="none"}flush(){if(this.notifyPending&&this.listeners.size!==0){this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild());for(const e of this.listeners)e()}}},Bn=class{static{a(this,"ProjectionValueStore")}rows=new Map;channels=new Map;valuesCache;anyNotifier=new ne(()=>{});faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){const s=this.rows.get(e);s!==void 0&&n<=s.seq||(this.rows.set(e,{value:t,seq:n}),this.changed(e))}seed(e){const t=e.values;for(const n of Object.keys(t))this.apply(n,t[n],e.asOfSeq);for(const[n,s]of this.rows)Object.hasOwn(t,n)||s.seq>e.asOfSeq||(this.rows.delete(n),this.changed(n))}truncate(e){for(const[t,n]of this.rows)n.seq<=e||(this.rows.delete(t),this.changed(t))}changed(e){this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){const n=new ne(()=>{});t={notifier:n,face:{getSnapshot:a(()=>this.rows.get(e)?.value,"getSnapshot"),subscribe:a(s=>n.subscribe(s),"subscribe")}},this.channels.set(e,t)}return t}};function ht(e,t){return`${e.length}:${e}${t}`}a(ht,"conversationContextKey");var Ln=class{static{a(this,"MutableLocationDataStore")}entries=new Map;get(e){return this.entries.get(e)?.value}remove(e,t){return this.entries.get(t)?.owner!==e?!1:(this.entries.delete(t),!0)}set(e,t,n){const s=this.entries.get(t);if(s!==void 0&&s.owner!==e)throw new Error(`conversation Location data "${t}" is already owned by ${s.owner}`);return s?.value===n?!1:(this.entries.set(t,{owner:e,value:n}),!0)}replace(e){let t=this.entries.size!==e.size;if(!t)for(const[n,s]of e){const r=this.entries.get(n);if(r?.owner!==s.owner||r.value!==s.value){t=!0;break}}return t&&(this.entries=new Map(e)),t}};const ft={kind:"session"},bc={kind:"unresolved"};function pt(e){const t=e.data;if(t.turn===null)return{session:!0};const n=Number.isSafeInteger(t.turn)&&t.turn>=0?t.turn:void 0,s=Number.isSafeInteger(t.step)&&t.step>=0?t.step:void 0;return{...n===void 0?{}:{turn:n},...s===void 0?{}:{step:s}}}a(pt,"payloadCoordinates");function _c(e,t){return e.length===t.length&&e.every((n,s)=>n===t[s])}a(_c,"sameReferences");function Un(e,t){return e!==void 0&&e.start===t.start&&e.end===t.end&&e.status===t.status&&e.data===t.data}a(Un,"sameStep");function Vn(e,t){return e!==void 0&&e.start===t.start&&e.end===t.end&&e.status===t.status&&e.data===t.data&&_c(e.steps,t.steps)}a(Vn,"sameTurn");function Wn(e,t){return e===void 0||t===void 0||e.kind!==t.kind?e===t:e.kind==="session"||e.kind==="unresolved"?!0:t.kind==="session"||t.kind==="unresolved"?!1:e.kind==="turn"||t.kind==="turn"?e.kind==="turn"&&t.kind==="turn"&&e.turn===t.turn:e.turn===t.turn&&e.step===t.step}a(Wn,"sameLocation");var Jn=class{static{a(this,"ConversationLocationIndex")}coordinates=new Map;locations=new Map;seqsByTurn=new Map;timeline={turnOrder:[],turns:new Map};turnDataStores=new Map;stepDataStores=new Map;currentTurn;currentStep;snapshot(){return this.timeline}replaceData(e){const t=new Map,n=new Map;for(const{owner:r,data:i}of e){const o=i.kind==="turn"?t.get(i.turn)??new Map:n.get(je(i.turn,mt(i)))??new Map,c=o.get(i.key);if(c!==void 0&&c.owner!==r)throw new Error(`conversation Location data "${i.key}" is already owned by ${c.owner}`);o.set(i.key,{owner:r,value:i.value}),i.kind==="turn"?t.set(i.turn,o):n.set(je(i.turn,mt(i)),o)}let s=!1;for(const r of new Set([...this.turnDataStores.keys(),...t.keys()]))s=this.mutableTurnData(r).replace(t.get(r)??new Map)||s;for(const r of new Set([...this.stepDataStores.keys(),...n.keys()]))s=this.mutableStepData(r).replace(n.get(r)??new Map)||s;return s}applyData(e){let t=!1;for(const n of e){const s=n.previous;s!==null&&(t=this.storeFor(s).remove(n.owner,s.key)||t)}for(const n of e){const s=n.next;s!==null&&(t=this.storeFor(s).set(n.owner,s.key,s.value)||t)}return t}locationOf(e){return this.locations.get(e.seq)??ft}rebuild(e){const t=this.locations,n=new Map,s=new Map;let r,i;const o=a((p,_)=>{let E=n.get(p);return E===void 0?(E={turn:p,firstSeq:_,steps:new Map},n.set(p,E)):E.firstSeq=Math.min(E.firstSeq,_),E},"turnDraft"),c=a((p,_,E)=>{const A=o(p,E);let S=A.steps.get(_);return S===void 0?(S={turn:p,step:_,firstSeq:E},A.steps.set(_,S)):S.firstSeq=Math.min(S.firstSeq,E),S},"stepDraft");for(const{event:p}of e){const _=pt(p);p.type==="turn/start"&&(r=p.data.turn,i=void 0),p.type==="step/start"&&(r=p.data.turn,i=p.data.step),_.session!==!0&&_.turn!==void 0&&(r!==_.turn&&(i=void 0),r=_.turn,_.step!==void 0&&(i=_.step));const E=_.session===!0?void 0:_.turn??r,A=_.session===!0||p.type==="turn/start"||p.type==="turn/end"?void 0:_.step??(E===r?i:void 0);s.set(p.seq,{...E===void 0?{}:{turn:E},...E===void 0||A===void 0?{}:{step:A}}),E!==void 0&&o(E,p.seq),E!==void 0&&A!==void 0&&c(E,A,p.seq),p.type==="turn/start"?o(p.data.turn,p.seq).start=p:p.type==="turn/end"?o(p.data.turn,p.seq).end=p:p.type==="step/start"?c(p.data.turn,p.data.step,p.seq).start=p:p.type==="step/end"&&(c(p.data.turn,p.data.step,p.seq).end=p),p.type==="step/end"&&r===p.data.turn&&i===p.data.step&&(i=void 0),p.type==="turn/end"&&r===p.data.turn&&(r=void 0,i=void 0)}const d=this.timeline.turns,u=new Map,h=[...n.values()].sort((p,_)=>p.firstSeq-_.firstSeq);for(const p of h){const _=d.get(p.turn),E=new Map(_?.steps.map(I=>[I.step,I])??[]),A=[...p.steps.values()].sort((I,K)=>I.firstSeq-K.firstSeq).map(I=>{const K={turn:I.turn,step:I.step,start:I.start,end:I.end,status:I.end!==void 0?"closed":I.start===void 0?"unknown":"open",data:this.stepData(I.turn,I.step)},ve=E.get(I.step);return Un(ve,K)?ve:K}),S={turn:p.turn,start:p.start,end:p.end,status:p.end!==void 0?"closed":p.start===void 0?"unknown":"open",steps:A,data:this.turnData(p.turn)};u.set(p.turn,Vn(_,S)?_:S)}const m=h.map(p=>p.turn),v=this.timeline.turnOrder.length===m.length&&this.timeline.turnOrder.every((p,_)=>p===m[_])?this.timeline.turnOrder:m;let b=d.size===u.size;if(b){for(const[p,_]of u)if(d.get(p)!==_){b=!1;break}}this.timeline=b&&v===this.timeline.turnOrder?this.timeline:{turnOrder:v,turns:u},this.coordinates=s,this.locations=new Map,this.seqsByTurn=new Map;for(const{event:p}of e){const _=this.coordinates.get(p.seq);_?.turn!==void 0&&this.indexTurnSeq(_.turn,p.seq),this.locations.set(p.seq,this.resolve(p.seq))}this.currentTurn=r,this.currentStep=i;const z=new Set;for(const{event:p}of e)Wn(t.get(p.seq),this.locations.get(p.seq))||z.add(p.seq);return z}appendBoundary(e){if(e.type!=="turn/start"&&e.type!=="turn/end"&&e.type!=="step/start"&&e.type!=="step/end")throw new Error(`conversation Location boundary expected, received ${e.type}`);const t=pt(e);e.type==="turn/start"?(this.currentTurn=e.data.turn,this.currentStep=void 0):e.type==="step/start"&&(this.currentTurn=e.data.turn,this.currentStep=e.data.step),t.turn!==void 0&&(this.currentTurn!==t.turn&&(this.currentStep=void 0),this.currentTurn=t.turn,t.step!==void 0&&(this.currentStep=t.step));const n=t.turn??this.currentTurn;if(n===void 0)throw new Error(`conversation boundary ${e.type} has no turn`);const s=e.type==="turn/start"||e.type==="turn/end"?void 0:t.step??(n===this.currentTurn?this.currentStep:void 0);this.coordinates.set(e.seq,{turn:n,...s===void 0?{}:{step:s}}),this.indexTurnSeq(n,e.seq);const r=this.timeline.turns.get(n);let i=r?.steps??[];if(e.type==="step/start"||e.type==="step/end"){const m=e.data.step,v=i.find(_=>_.step===m),b={turn:n,step:m,start:e.type==="step/start"?e:v?.start,end:e.type==="step/end"?e:v?.end,status:e.type==="step/end"||v?.end!==void 0?"closed":"open",data:this.stepData(n,m)},z=Un(v,b)?v:b,p=i.findIndex(_=>_.step===m);i=p<0?[...i,z]:i.map((_,E)=>E===p?z:_)}const o={turn:n,start:e.type==="turn/start"?e:r?.start,end:e.type==="turn/end"?e:r?.end,status:e.type==="turn/end"||r?.end!==void 0?"closed":e.type==="turn/start"||r?.start!==void 0?"open":"unknown",steps:i,data:this.turnData(n)},c=Vn(r,o)?r:o,d=new Map(this.timeline.turns);d.set(n,c);const u=r===void 0?[...this.timeline.turnOrder,n]:this.timeline.turnOrder;this.timeline={turnOrder:u,turns:d};const h=new Set;for(const m of this.seqsByTurn.get(n)??[]){const v=this.locations.get(m),b=this.resolve(m);this.locations.set(m,b),Wn(v,b)||h.add(m)}return e.type==="step/end"&&this.currentTurn===e.data.turn&&this.currentStep===e.data.step&&(this.currentStep=void 0),e.type==="turn/end"&&this.currentTurn===e.data.turn&&(this.currentTurn=void 0,this.currentStep=void 0),h}appendNonBoundary(e){const t=pt(e);if(t.session===!0){this.coordinates.set(e.seq,{}),this.locations.set(e.seq,ft);return}t.turn!==void 0&&(this.currentTurn!==t.turn&&(this.currentStep=void 0),this.currentTurn=t.turn,t.step!==void 0&&(this.currentStep=t.step));const n=t.turn??this.currentTurn,s=t.step??(n===this.currentTurn?this.currentStep:void 0);this.coordinates.set(e.seq,{...n===void 0?{}:{turn:n},...n===void 0||s===void 0?{}:{step:s}}),n!==void 0&&this.indexTurnSeq(n,e.seq),this.locations.set(e.seq,this.resolve(e.seq))}indexTurnSeq(e,t){const n=this.seqsByTurn.get(e)??new Set;n.add(t),this.seqsByTurn.set(e,n)}turnData(e){return this.mutableTurnData(e)}stepData(e,t){return this.mutableStepData(je(e,t))}mutableTurnData(e){const t=this.turnDataStores.get(e)??new Ln;return this.turnDataStores.set(e,t),t}mutableStepData(e){const t=this.stepDataStores.get(e)??new Ln;return this.stepDataStores.set(e,t),t}storeFor(e){return e.kind==="turn"?this.mutableTurnData(e.turn):this.mutableStepData(je(e.turn,mt(e)))}resolve(e){const t=this.coordinates.get(e);if(t?.turn===void 0)return ft;const n=this.timeline.turns.get(t.turn);if(n===void 0)return bc;if(t.step===void 0)return{kind:"turn",turn:n};const s=n.steps.find(r=>r.step===t.step);return s===void 0?{kind:"turn",turn:n}:{kind:"step",turn:n,step:s}}};function je(e,t){return`${e}:${t}`}a(je,"stepDataKey");function mt(e){if(e.kind==="step"&&e.step!==void 0)return e.step;throw new Error(`conversation Step data "${e.key}" requires a step`)}a(mt,"requireStep");const Gn={none:0,"animation-frame":1,immediate:2},Kn=["step","turn"];function Yn(){return{step:null,turn:null}}a(Yn,"emptyLocationData");function Fe(e,t){return Gn[e]>=Gn[t]?e:t}a(Fe,"maximumPublication");function pe(e){return e.startSeq}a(pe,"startSeq");function Hn(e,t){let n=0,s=e.length;for(;n<s;){const r=n+Math.floor((s-n)/2),i=e[r];i!==void 0&&i.startSeq<t?n=r+1:s=r}return n}a(Hn,"insertionIndex");function me(e){return{key:e.key,kind:e.kind,id:e.id,matches:e.matches,start:e.start,state:e.state,current:e.current}}a(me,"contextSnapshot");function kc(e,t,n){const s=[];let r=0,i=0;for(;r<t.length||i<n.length;){const o=t[r],c=n[i];if(o!==void 0&&c!==void 0&&o.event.seq===c.event.seq)throw new Error(`conversation Context ${e} received duplicate Match ${o.event.seq}`);c===void 0||o!==void 0&&o.event.seq<c.event.seq?(s.push(o),r++):(s.push(c),i++)}return s}a(kc,"mergeMatches");var gt=class{static{a(this,"ConversationNodeAssembler")}eventDefinitions;viewDefinitions;contexts=new Map;contextsByKind=new Map;contextsBySeq=new Map;inputs=new Map;locationIndex=new Jn;dirty=new Set;revised=new Set;dependents=new Map;views=new Map;hasMore=!1;replacePending=!0;timelineDirty=!0;constructor(e,t){this.eventDefinitions=e,this.viewDefinitions=t,this.resetViewBuilders()}replaceWindow(e,t){this.contexts.clear(),this.contextsByKind.clear(),this.contextsBySeq.clear(),this.inputs.clear(),this.dirty.clear(),this.revised.clear(),this.dependents.clear(),this.hasMore=t;const n=[...e].sort((s,r)=>s.event.seq-r.event.seq);for(const s of n)this.inputs.set(s.event.seq,s);this.locationIndex.rebuild(n),this.timelineDirty=!0;for(const s of n)this.matchInput(s);this.replayDependencies(),this.revised.clear();for(const s of this.contexts.values())this.dirty.add(s);return this.replacePending=!0,"immediate"}append(e){if(this.inputs.has(e.event.seq))return"none";this.revised.clear(),this.inputs.set(e.event.seq,e);let t="none";if(Sc(e.event.type)){const n=this.locationIndex.snapshot(),s=this.locationIndex.appendBoundary(e.event);this.locationIndex.snapshot()!==n&&(this.timelineDirty=!0,t="immediate"),this.replayContexts(this.refreshMatchLocations(s)),s.size>0&&(t="immediate")}else this.locationIndex.appendNonBoundary(e.event);return t=Fe(t,this.matchInput(e)),this.replayRevisedDependents()&&(t="immediate"),this.revised.clear(),t}prepend(e,t){this.revised.clear();let n="none";const s=this.hasMore,r=e.filter(u=>!this.inputs.has(u.event.seq)).sort((u,h)=>u.event.seq-h.event.seq);for(const u of r)this.inputs.set(u.event.seq,u);this.hasMore=t;const i=this.locationIndex.snapshot(),o=this.locationIndex.rebuild(this.sortedInputs());this.locationIndex.snapshot()!==i&&(this.timelineDirty=!0);const c=this.refreshMatchLocations(o),d=new Map;for(const u of r)n=Fe(n,this.collectInput(u,d));return this.applyPendingMatches(d,c),this.replayContexts(c),(this.revised.size>0||s!==t)&&this.replayDependencies()&&(n="immediate"),o.size>0&&(n="immediate"),this.revised.clear(),n}rebuildRegistry(){return this.resetViewBuilders(),this.replaceWindow(this.sortedInputs(),this.hasMore)}flush(){if(!this.replacePending&&this.dirty.size===0&&!this.timelineDirty)return!1;if(this.replacePending){this.replaceLocationData();const n=new Map;for(const s of this.views.keys())n.set(s,[]);for(const s of this.contexts.values()){const r=s.definition.target;if(r===void 0||!this.views.has(r))continue;const i=this.buildNode(s,r);s.current.set(r,i),i!==null&&n.get(r)?.push(i)}for(const s of this.views.values())s.snapshot=s.builder.replace({nodes:n.get(s.target)??[],timeline:this.locationIndex.snapshot()});return this.replacePending=!1,this.dirty.clear(),this.timelineDirty=!1,!0}const e=new Map;for(const n of this.views.keys())e.set(n,[]);this.applyDirtyLocationData()&&(this.timelineDirty=!0);for(const n of this.dirty){const s=n.definition.target;if(s===void 0||!this.views.has(s))continue;const r=n.current.get(s)??null,i=this.buildNode(n,s);if(i===null&&r!==null)throw new Error(`conversation Definition "${n.kind}" withdrew materialized target "${s}"; return the same key with hidden visibility instead`);n.current.set(s,i),i!==null&&e.get(s)?.push(i)}this.dirty.clear();const t=this.timelineDirty;this.timelineDirty=!1;for(const n of this.views.values()){const s=e.get(n.target)??[];s.length===0&&!t||(n.snapshot=n.builder.apply({upserts:s,timeline:this.locationIndex.snapshot()}))}return!0}snapshot(e){return this.views.get(e)?.snapshot}get(e){return this.snapshot(e)}sortedInputs(){return[...this.inputs.values()].sort((e,t)=>e.event.seq-t.event.seq)}matchInput(e){return this.dispatchInput(e,(t,n,s)=>this.acceptMatch(t,n,s,e))}collectInput(e,t){return this.dispatchInput(e,(n,s,r)=>{const i=ht(n.kind,s),o={...e,role:r,location:this.locationIndex.locationOf(e.event)},c=t.get(i)??[];return c.push({definition:n,id:s,match:o}),t.set(i,c),n.publication?.(o)??"immediate"})}dispatchInput(e,t){const n=new Set;let s="none";for(const o of this.eventDefinitions.entries()){const c=o.match(e.event);c!==null&&(o.target!==void 0&&n.add(o.target),s=Fe(s,t(o,c.id,c.role)))}const r=this.eventDefinitions.fallbackEntry(),i=r?.target;if(r!==void 0&&i!==void 0&&!n.has(i)){const o=r.match(e.event);o!==null&&(s=Fe(s,t(r,o.id,o.role)))}return s}acceptMatch(e,t,n,s){const r=ht(e.kind,t);let i=this.contexts.get(r);if(n==="start"&&i?.start!==void 0)throw new Error(`conversation Context ${r} received more than one start Match`);i===void 0&&(i={key:r,kind:e.kind,id:t,definition:e,startSeq:void 0,start:void 0,matches:[],state:void 0,revision:0,current:new Map,locationData:Yn(),dependencies:new Map},this.contexts.set(r,i));const o={...s,role:n,location:this.locationIndex.locationOf(s.event)},c=i.matches.at(-1);if(c!==void 0&&c.event.seq>=s.event.seq)throw new Error(`conversation Context ${r} received non-appended Match ${s.event.seq}`);if(n==="start"&&i.matches.length>0)throw new Error(`conversation Context ${r} received an update before its start Match`);i.matches.push(o),n==="start"&&(i.startSeq=s.event.seq,i.start=o,this.indexStartedContext(i));const d=this.contextsBySeq.get(s.event.seq)??new Set;if(d.add(i),this.contextsBySeq.set(s.event.seq,d),n==="start")this.replayContext(i);else if(i.state!==void 0){const u=me(i);i.state=vt(e,"update",e.update(u,o)),i.revision++,this.revised.add(i)}return this.dirty.add(i),e.publication?.(o)??"immediate"}applyPendingMatches(e,t){const n=new Map;for(const[s,r]of e){const i=r[0];if(i===void 0)continue;let o=this.contexts.get(s);o===void 0&&(o={key:s,kind:i.definition.kind,id:i.id,definition:i.definition,startSeq:void 0,start:void 0,matches:[],state:void 0,revision:0,current:new Map,locationData:Yn(),dependencies:new Map},this.contexts.set(s,o));let c;const d=r.map(u=>{if(u.definition!==o.definition||u.id!==o.id)throw new Error(`conversation Context ${s} received inconsistent Definition identity`);if(u.match.role==="start"){if(c!==void 0||o.start!==void 0)throw new Error(`conversation Context ${s} received more than one start Match`);c=u.match}const h=this.contextsBySeq.get(u.match.event.seq)??new Set;return h.add(o),this.contextsBySeq.set(u.match.event.seq,h),u.match}).sort((u,h)=>u.event.seq-h.event.seq);if(o.matches=kc(o.key,d,o.matches),c!==void 0){o.start=c,o.startSeq=c.event.seq;const u=n.get(o.kind)??[];u.push(o),n.set(o.kind,u)}if(o.start!==void 0&&o.matches[0]!==o.start)throw new Error(`conversation Context ${o.key} received an update before its start Match`);t.add(o),this.dirty.add(o)}for(const[s,r]of n)this.indexStartedContexts(s,r)}replayContexts(e){const t=[...e].sort((n,s)=>(n.startSeq??Number.POSITIVE_INFINITY)-(s.startSeq??Number.POSITIVE_INFINITY));for(const n of t){if(n.start===void 0){n.state=void 0,this.dirty.add(n);continue}this.replayContext(n)}}replayContext(e){const t=e.start;if(t===void 0){e.state=void 0;return}if(e.matches[0]!==t)throw new Error(`conversation Context ${e.key} received an update before its start Match`);const n=new Map,s=this.readerFor(t.event.seq,n);e.state=void 0,e.state=vt(e.definition,"start",e.definition.start(me(e),t,s)),this.replaceDependencies(e,n);for(let r=1;r<e.matches.length;r++){const i=e.matches[r];if(i===void 0||i.role!=="update")continue;const o=me(e);e.state=vt(e.definition,"update",e.definition.update(o,i))}e.revision++,this.revised.add(e),this.dirty.add(e)}replaceDependencies(e,t){for(const n of e.dependencies.values()){if(n.key===void 0)continue;const s=this.dependents.get(n.key);s?.delete(e),s?.size===0&&this.dependents.delete(n.key)}e.dependencies=t;for(const n of t.values()){if(n.key===void 0)continue;const s=this.dependents.get(n.key)??new Set;s.add(e),this.dependents.set(n.key,s)}}replayRevisedDependents(){const e=[...this.revised],t=new Set;for(let n=0;n<e.length;n++){const s=e[n];if(s!==void 0)for(const r of this.dependents.get(s.key)??[])t.has(r)||(t.add(r),e.push(r))}return this.replayContexts(t),t.size>0}readerFor(e,t){return{previous:a(n=>{const s=this.previousContext(n,e);if(t.set(n,{kind:n,key:s?.key,revision:s?.revision,windowGap:s===void 0&&this.hasMore}),s?.state===void 0)return;const r=pe(s);if(r!==void 0)return{key:s.key,kind:s.kind,id:s.id,startSeq:r,state:s.state,matches:s.matches}},"previous")}}previousContext(e,t){const n=this.contextsByKind.get(e)??[],s=Hn(n,t);for(let r=s-1;r>=0;r--){const i=n[r];if(i?.state!==void 0)return i}}indexStartedContext(e){const t=e.startSeq;if(t===void 0)return;const n=this.contextsByKind.get(e.kind)??[],s=n.at(-1);s===void 0||s.startSeq<t?n.push(e):n.splice(Hn(n,t),0,e),this.contextsByKind.set(e.kind,n)}indexStartedContexts(e,t){if(t.length===0)return;const n=[...t].sort((c,d)=>c.startSeq-d.startSeq),s=this.contextsByKind.get(e)??[],r=[];let i=0,o=0;for(;i<s.length||o<n.length;){const c=s[i],d=n[o];d===void 0||c!==void 0&&c.startSeq<d.startSeq?(r.push(c),i++):(r.push(d),o++)}this.contextsByKind.set(e,r)}replayDependencies(){let e=!1;const t=[...this.contexts.values()].filter(n=>pe(n)!==void 0).sort((n,s)=>pe(n)-pe(s));for(const n of t){if(n.state===void 0||n.dependencies.size===0)continue;const s=pe(n);if(s===void 0)continue;let r=!1;for(const i of n.dependencies.values()){const o=this.previousContext(i.kind,s),c=o===void 0&&this.hasMore;if(o?.key!==i.key||o?.revision!==i.revision||c!==i.windowGap){r=!0;break}}r&&(this.replayContext(n),e=!0)}return e}refreshMatchLocations(e){const t=new Set;if(e.size===0)return t;for(const n of e)for(const s of this.contextsBySeq.get(n)??[])t.add(s);for(const n of t){let s=n.start;n.matches=n.matches.map(r=>{if(!e.has(r.event.seq))return r;const i={...r,location:this.locationIndex.locationOf(r.event)};return r===s&&(s=i),i}),n.start=s}return t}buildNode(e,t){if(e.definition.target!==t||e.definition.buildViewNode===void 0)return null;const n=e.definition.buildViewNode(me(e));if(n===null)return null;if(n.key!==e.key)throw new Error(`conversation Definition "${e.kind}" returned unstable key "${n.key}"; expected "${e.key}"`);if(n.target!==t)throw new Error(`conversation Definition "${e.kind}" returned target "${n.target}" while building "${t}"`);return n}buildLocationData(e,t){if(e.definition.buildLocationData===void 0)return null;const n=e.definition.buildLocationData(me(e),t);if(n===null)return null;if(n.kind!==t)throw new Error(`conversation Definition "${e.kind}" published ${n.kind} data through its ${t} scope`);if(n.key!==e.kind)throw new Error(`conversation Definition "${e.kind}" published Location data key "${n.key}"; expected its owned kind`);if(!Number.isSafeInteger(n.turn)||n.turn<0)throw new Error(`conversation Definition "${e.kind}" published invalid turn ${n.turn}`);if(n.kind==="step"&&(!Number.isSafeInteger(n.step)||n.step<0))throw new Error(`conversation Definition "${e.kind}" published invalid step ${String(n.step)}`);return n}replaceLocationData(){const e=[];for(const t of Kn){for(const n of this.contexts.values()){const s=this.buildLocationData(n,t);n.locationData[t]=s,s!==null&&e.push({owner:n.key,data:s})}this.locationIndex.replaceData(e)}}applyDirtyLocationData(){let e=!1;for(const t of Kn){const n=[];for(const s of this.dirty){const r=s.locationData[t],i=this.buildLocationData(s,t);s.locationData[t]=i,r!==i&&n.push({owner:s.key,previous:r,next:i})}e=this.locationIndex.applyData(n)||e}return e}resetViewBuilders(){this.views.clear();for(const e of this.viewDefinitions.entries()){const t=e.create();this.views.set(e.target,{target:e.target,builder:t,snapshot:t.empty})}this.replacePending=!0}};function Sc(e){return e==="turn/start"||e==="turn/end"||e==="step/start"||e==="step/end"}a(Sc,"isLocationBoundary");function vt(e,t,n){if(n===void 0)throw new Error(`conversation Definition "${e.kind}" returned undefined from ${t}()`);return n}a(vt,"requireState");function Ic(e){return e.map(Xn)}a(Ic,"toAssistantBlocks");function Xn(e){switch(e.type){case"text":return{kind:"text",text:e.text};case"reasoning":return{kind:"reasoning",text:e.text};case"image":return{kind:"image",attachment:e.attachment};case"tool-call":return{kind:"tool-call",callId:String(e.id),name:e.name,argsRaw:e.arguments};default:return{kind:"other",block:e}}}a(Xn,"toAssistantBlock");const G=[],zc={turnOrder:G,turns:new Map},$c={get:a(()=>{},"get")},Qn={order:G,nodes:{get:a(()=>{},"get"),values:a(()=>G,"values")},locations:{getTurn:a(()=>G,"getTurn"),getStep:a(()=>G,"getStep")},timeline:zc,legacy:{nodes:G,turnTimings:new Map,turnEnds:new Map,partial:null,runningCalls:G}},Ec={approval:"a",question:"q"};var yt=class{static{a(this,"PendingWait")}kind;key;sessionId;payload;#e=!1;#t;#n;constructor(e,t,n,s,r){this.kind=e,this.key=`${Ec[e]}:${t}`,this.sessionId=n,this.payload=s,this.#t=t,this.#n=r}respond(e){if(this.#e)throw new Error(`pending wait ${this.key} is already settled`);return this.#n({type:"client-response",rpcId:this.#t,result:e})}markSettled(){this.#e=!0}};function es(){const e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!="string"||e.length===0)throw new Error("browser time zone is unavailable");return e}a(es,"resolvedClientTimeZone");const ts=200;function Oc(e){const t=e.map(s=>s.type==="text"?s.text:`[${s.type}]`).join(" ").replace(/\s+/g," ").trim(),n=Array.from(t);return n.length>ts?`${n.slice(0,ts).join("")}…`:t}a(Oc,"previewOf");function Pc(e){return e.every(t=>t.type==="text")?e.map(t=>t.text).join(""):null}a(Pc,"textOf");var Dc=class{static{a(this,"SessionQueueMirror")}current=[];snapshot(){return this.current}reset(){return this.current.length===0?!1:(this.current=[],!0)}replace(e){this.current=e.map(t=>({id:t.id,messageId:t.message.id,placement:t.placement,content:t.message.content,preview:Oc(t.message.content),text:Pc(t.message.content)}))}acceptDurable(e){if(e.type!=="user/message")return!1;const t=e.data.id,n=this.current.findIndex(s=>s.placement==="steering"&&s.messageId===t);return n<0?!1:(this.current=this.current.filter((s,r)=>r!==n),!0)}},Cc=class{static{a(this,"Session")}sessionId;api;remote;options;events=[];views=[];baseSeq=0;hasMore=!1;openState="cold";openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;pending=new Map;pendingRev=0;pendingCache=null;queueMirror=new Dc;conversation;running=!1;address;parentAvailable=!1;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;lastAgentError=null;liveBuffer=[];stitching=!1;subscribedLastSeq=null;projections;snapshotCache;notifier;actx;constructor(e,t,n,s={}){this.sessionId=e,this.api=t,this.remote=n,this.options=s,this.projections=s.projections??new Bn,this.address=s.address,this.parentAvailable=s.parentAvailable??!1,this.conversation=s.conversation===void 0?new gt({entries:a(()=>[],"entries"),fallbackEntry:a(()=>{},"fallbackEntry")},{entries:a(()=>[],"entries")}):new gt(s.conversation.events,s.conversation.views),this.notifier=new ne(()=>{this.conversation.flush(),this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot()}bindScope(e){if(this.actx!==void 0)throw new Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}async prompt(e,t){this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let n;try{if(this.address===void 0)n=(await this.api.sessions.prompt({sessionId:this.sessionId,mode:t,content:e,clientTimeZone:es()})).result;else if(this.address.mode==="one-shot")n={ok:!1,error:{code:"subagent-not-resumable",message:"one-shot subagent conversations are read-only",details:{childSessionId:this.address.childSessionId}}};else if(e.some(s=>s.type==="image"))n={ok:!1,error:{code:"attachment-error",message:"Image input is unavailable for subagent continuations.",details:{reason:"SUBAGENT_IMAGE_UNSUPPORTED"}}};else{const s=(await this.api.subagents.prompt({...this.address,content:e.flatMap(r=>r.type==="text"?[{type:"text",text:r.text}]:[]),clientTimeZone:es()})).result;n=s.ok?{ok:!0,value:{accepted:!0}}:s}}catch(s){n=M(s)}return n.ok?(this.blankBit&&(this.blankBit=!1,this.options.onEngaged?.(this),this.notifier.markDirty()),n):(this.promptError={op:"send",error:n.error},this.notifier.markDirty(),n)}async readAttachment(e){try{const t=(await this.api.sessions.attachment({sessionId:this.sessionId,attachmentId:e})).result;if(!t.ok)return t;const n=atob(t.value.data),s=Uint8Array.from(n,r=>r.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:s}}}catch(t){return M(t)}}async updateQueue(e,t){try{return(await this.api.sessions.updateQueue({sessionId:this.sessionId,itemId:e,action:t})).result}catch(n){return M(n)}}async cancel(){const e=this.address;if(e!==void 0&&e.mode==="one-shot"){const n={ok:!1,error:{code:"subagent-delivery-unavailable",message:"subagent activation cancellation is unavailable",details:{childSessionId:e.childSessionId}}};return this.promptError={op:"stop",error:n.error},this.notifier.markDirty(),n}let t;try{t=e!==void 0?(await this.api.subagents.interrupt(e)).result:(await this.api.sessions.cancel({sessionId:this.sessionId})).result}catch(n){t=M(n)}return t.ok||(this.promptError={op:"stop",error:t.error},this.notifier.markDirty()),t}async rename(e){try{const{result:t}=await this.api.sessions.rename({sessionId:this.sessionId,title:e});return t.ok&&this.projections.apply("title",t.value.title,t.value.seq),t}catch(t){return M(t)}}async command(e){const t=await this.remote.commands.execute(this.sessionId,e);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState==="open")return Promise.resolve();if(this.openPromise!==null)return this.openPromise;const e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(!(this.openState!=="open"||!this.hasMore||this.loadingOlder)){this.loadingOlder=!0,this.notifier.markDirty();try{const{result:e}=await this.history({beforeSeq:this.baseSeq,maxMessages:50});if(!e.ok)return;const t=e.value.events;if(t.length===0){this.hasMore=e.value.hasMore,this.conversation.prepend([],this.hasMore);return}const n=t[t.length-1];if(n===void 0||n.event.seq+1!==this.baseSeq){console.error(`[web-runtime] history page discontinuous: tail seq ${n?.event.seq} vs baseSeq ${this.baseSeq}`),this.hasMore=!1,this.conversation.prepend([],!1);return}this.events=[...t.map(s=>s.event),...this.events],this.views=[...t.map(s=>s.view),...this.views],this.baseSeq=t[0]?.event.seq??this.baseSeq,this.hasMore=e.value.hasMore,this.conversation.prepend(t.map(ns),this.hasMore)}catch(e){console.error("[web-runtime] loadOlder failed:",e)}finally{this.loadingOlder=!1,this.notifier.markDirty()}}}async resync(){this.openState!=="cold"&&(this.openGeneration++,this.openPromise=null,this.openState="cold",this.openError=null,this.events=[],this.views=[],this.baseSeq=0,this.pending.clear(),this.pendingRev++,this.subscribedLastSeq=null,this.liveBuffer=[],this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}handleMuxEnvelope(e,t){switch(t.type){case"session/event":this.acceptLiveEvent(t.event,t.view);return;case"session/queue":this.queueMirror.replace(t.items),this.notifier.markDirty();return;case"session/subscribed":this.subscribedLastSeq=t.lastSeq,this.queueMirror.reset()&&this.notifier.markDirty();return;case"approval/requested":{const{type:n,sessionId:s,...r}=t;this.mint(new yt("approval",e,this.sessionId,r,i=>this.api.respond(i))),this.notifier.markDirty();return}case"approval/resolved":for(const n of this.pending.values())n.kind==="approval"&&n.payload.approvalId===t.approvalId&&this.settle(n);this.notifier.markDirty();return;case"question/requested":{const{type:n,sessionId:s,...r}=t;this.mint(new yt("question",e,this.sessionId,r,i=>this.api.respond(i))),this.notifier.markDirty();return}case"question/resolved":{const n=this.pending.get(`q:${t.questionRpcId}`);n!==void 0&&this.settle(n),this.notifier.markDirty();return}default:return}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t=!1){const n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!=="cold"?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}dispose(){}rebuildConversationRegistry(){this.scheduleConversation(this.conversation.rebuildRegistry())}mint(e){this.pending.set(e.key,e),this.pendingRev++}settle(e){e.markSettled(),this.pending.delete(e.key),this.pendingRev++}async doOpen(e){this.openState="loading",this.openError=null,this.notifier.markDirty();try{let{result:t}=await this.history({maxMessages:50});if(e!==this.openGeneration)return;if(!t.ok){this.openState="error",this.openError=t.error;return}this.installWindow(t.value.events,t.value.hasMore,t.value.projections);const n=this.windowTailSeq();if(this.subscribedLastSeq!==null&&n!==null&&this.subscribedLastSeq>n){if(t=(await this.history({maxMessages:50})).result,e!==this.openGeneration)return;t.ok&&this.installWindow(t.value.events,t.value.hasMore,t.value.projections)}this.openState="open"}catch(t){if(e!==this.openGeneration)return;this.openState="error";const n=M(t);this.openError=n.ok?null:n.error}finally{e===this.openGeneration&&this.notifier.markDirty()}}installWindow(e,t,n){this.events=e.map(r=>r.event),this.views=e.map(r=>r.view),this.baseSeq=this.events[0]?.seq??0,this.hasMore=t,this.events.some(r=>r.type==="turn/start")&&(this.firstPromptPendingTurn=!1),this.conversation.replaceWindow(e.map(ns),t),n!==void 0&&this.projections.seed(n);const s=this.liveBuffer;this.liveBuffer=[];for(const r of s)this.appendLive(r.event,r.view);this.notifier.markDirty()}appendLive(e,t){const n=this.windowTailSeq();if(n!==null&&e.seq<=n)return"none";this.events.push(e),this.views.push(t),e.type==="turn/start"&&(this.firstPromptPendingTurn=!1);const s=this.queueMirror.acceptDurable(e),r=this.conversation.append({event:e,view:t});return s?"immediate":r}acceptLiveEvent(e,t){if(this.openState==="loading"||this.stitching){this.liveBuffer.push({event:e,view:t});return}if(this.openState!=="open")return;const n=this.windowTailSeq();if(n!==null&&e.seq>n+1){this.liveBuffer.push({event:e,view:t}),this.repairGap();return}this.scheduleConversation(this.appendLive(e,t))}scheduleConversation(e){e==="immediate"?this.notifier.markDirty():e==="animation-frame"&&this.notifier.markFrameDirty()}async repairGap(){if(this.stitching)return;this.stitching=!0;const e=this.openGeneration;try{const{result:t}=await this.history({maxMessages:50});t.ok&&e===this.openGeneration&&this.openState==="open"&&this.installWindow(t.value.events,t.value.hasMore,t.value.projections)}catch(t){console.error("[web-runtime] gap repair failed:",t)}finally{this.stitching=!1}}windowTailSeq(){const e=this.events[this.events.length-1];return e===void 0?null:e.seq}buildSnapshot(){(this.pendingCache===null||this.pendingCache.rev!==this.pendingRev)&&(this.pendingCache={rev:this.pendingRev,value:[...this.pending.values()]});const e=this.conversation.snapshot("chat")??Qn,t=e.legacy;return{sessionId:this.sessionId,views:this.conversation,chat:e,nodes:t.nodes,turnTimings:t.turnTimings,turnEnds:t.turnEnds,partial:t.partial,runningCalls:t.runningCalls,pending:this.pendingCache.value,queue:this.queueMirror.snapshot(),running:this.running,subagent:this.address===void 0?null:{address:this.address,parentAvailable:this.parentAvailable},composerPhase:Tc(Ac(e)||!this.blankBit&&!this.firstPromptPendingTurn||this.running||this.pendingCache.value.length>0,this.promptAttempted),removed:this.removed,openState:this.openState,openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError}}history(e){return this.address===void 0?this.api.sessions.history({sessionId:this.sessionId,...e}):this.api.subagents.history({...this.address,...e})}};function ns(e){return{event:e.event,view:e.view}}a(ns,"conversationInput");function Ac(e){return e.order.some(t=>e.nodes.get(t)?.kind!=="command")}a(Ac,"hasVisibleConversationContent");function Tc(e,t){return e?"active":t?"engaging":"blank"}a(Tc,"derivePhase");function ss(e){const t=e.payload;switch(t.type){case"approval/requested":return`a:${t.approvalId}`;case"question/requested":return`q:${e.rpcId}`;case"session/queue":return"queue";default:return}}a(ss,"bufferedRequestKey");function Zc(e){if(e.length!==1)return"question";const t=e[0],n=t.intent;if(n?.kind!=="plan-review"||t.detail===void 0||t.multiSelect===!0)return"question";const s=t.options??[];return s.length>2?"question":s.some(r=>r.label===n.approve)?"plan-review":"question"}a(Zc,"questionInteractionStatus");var Nc=class{static{a(this,"SessionManager")}api;remote;conversation;sessions=new Map;pendingBuffers=new Map;pendingInteractions=new Map;completedNotifications=new Set;prevRunning=new Map;projectionStores=new Map;summaries=[];listState="idle";listPhase="pending";listError=null;listInflight=null;listMutations=null;addresses=new Map;catalogs=new Map;catalogInflight=new Map;catalogStale=new Set;openCatalogs=new Set;catalogDebounce=new Map;jobsBySession=new Map;selected;listSnapshotCache;entryCache=new Map;itemsCache=[];notifier=new ne(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e,t,n,s,r){this.api=e,this.remote=t,this.conversation=r,this.selected=n,s!==void 0&&this.addresses.set(s.childSessionId,s),this.listSnapshotCache=this.buildListSnapshot()}select(e){const t=this.navigationAddress(e);if(!this.summaries.some(n=>n.sessionId===e)&&t===void 0)throw new Error(`sessions.select: unknown session ${e}`);t!==void 0&&this.addresses.set(e,t),this.sessions.get(e)?.configureSubagent(t,t===void 0?!1:this.catalogs.get(t.parentSessionId)?.parentAvailable??!1),this.selected=e,this.completedNotifications.delete(e),this.refreshSubagents(e),this.notifier.notifyNow()}selectSubagent(e){const t=this.catalogs.get(e.parentSessionId),n=t?.entries.find(s=>s.id===e.childSessionId);if(n===void 0||n.kind!=="child"||n.mode!==e.mode)throw new Error(`sessions.selectSubagent: ${e.childSessionId} is not a healthy catalog child`);this.addresses.set(e.childSessionId,e),this.sessions.get(e.childSessionId)?.configureSubagent(e,t?.parentAvailable??!1),this.selected=e.childSessionId,this.completedNotifications.delete(e.childSessionId),this.refreshSubagents(e.childSessionId),this.notifier.notifyNow()}clearSelection(){this.selected=void 0,this.notifier.notifyNow()}subagentAddress(e){return this.addresses.get(e)}navigationAddress(e){const t=this.addresses.get(e);if(t!==void 0)return t;for(const[n,s]of this.catalogs){const r=s.entries.find(i=>i.kind==="child"&&i.id===e);if(r?.kind==="child")return{parentSessionId:n,childSessionId:e,mode:r.mode}}}drop(e){this.sessions.delete(e)}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);const n=this.pendingBuffers.get(e);if(n!==void 0){this.pendingBuffers.delete(e);for(const r of n)t.handleMuxEnvelope(r.rpcId,r.payload)}const s=this.summaries.find(r=>r.sessionId===e);if(s!==void 0)t.handleBlank(s.blank),t.handleRunning(s.running);else{const r=this.addresses.get(e),i=r===void 0?void 0:this.catalogs.get(r.parentSessionId)?.entries.find(o=>o.kind==="child"&&o.id===e);i?.kind==="child"&&(t.handleBlank(!1),t.handleRunning(i.activity==="running"))}}return t}createSession(e){const t=this.addresses.get(e);return new Cc(e,this.api,this.remote,{...t===void 0?{}:{address:t,parentAvailable:this.catalogs.get(t.parentSessionId)?.parentAvailable??!1},onEngaged:a(n=>{this.recordMutation({kind:"engaged",sessionId:n.sessionId})},"onEngaged"),projections:this.projectionStore(e),...this.conversation===void 0?{}:{conversation:this.conversation}})}rebuildConversationRegistry(){for(const e of this.sessions.values())e.rebuildConversationRegistry()}projectionStore(e){let t=this.projectionStores.get(e);return t===void 0&&(t=new Bn,t.subscribeAny(()=>{this.notifier.markDirty()}),this.projectionStores.set(e,t)),t}refreshSubagents(e){const t=this.catalogInflight.get(e);if(t!==void 0)return t.promise;const n=this.catalogs.get(e),s=new Set,r=new Map;this.catalogs.set(e,{entries:n?.entries??[],parentAvailable:n?.parentAvailable??!1,state:"loading",error:null}),this.notifier.markDirty();const i=(async()=>{try{const{result:o}=await this.api.subagents.list({parentSessionId:e});if(o.ok){const c=this.catalogInflight.get(e)?.parentAvailableOverride??o.value.parentAvailable;this.catalogs.set(e,{...o.value,entries:this.withCatalogMutations(o.value.entries,s,r),parentAvailable:c,state:"ready",error:null});for(const[d,u]of this.addresses)u.parentSessionId===e&&this.sessions.get(d)?.handleSubagentParentAvailable(c)}else this.catalogs.set(e,{entries:this.withCatalogMutations(n?.entries??[],s,r),parentAvailable:this.catalogInflight.get(e)?.parentAvailableOverride??n?.parentAvailable??!1,state:"error",error:o.error})}catch(o){const c=M(o);this.catalogs.set(e,{entries:this.withCatalogMutations(n?.entries??[],s,r),parentAvailable:this.catalogInflight.get(e)?.parentAvailableOverride??n?.parentAvailable??!1,state:"error",error:c.ok?null:c.error})}finally{this.catalogInflight.delete(e),this.catalogStale.delete(e)&&this.refreshSubagents(e),this.notifier.markDirty()}})();return this.catalogInflight.set(e,{promise:i,expandableRows:s,activityRows:r,parentAvailableOverride:void 0}),i}setSubagentCatalogOpen(e,t){if(t)this.openCatalogs.add(e),this.refreshSubagents(e);else{this.openCatalogs.delete(e);const n=this.catalogDebounce.get(e);n!==void 0&&(clearTimeout(n),this.catalogDebounce.delete(e))}}refreshList(){if(this.listInflight!==null)return this.listInflight;this.listState="loading",this.listError=null;const e=this.summaries,t=[];return this.listMutations=t,this.notifier.markDirty(),this.listInflight=(async()=>{try{const{result:n}=await this.api.sessions.list({});if(n.ok){const s=this.listPhase==="pending"?n.value.items:yc(e,n.value.items,i=>i.sessionId);for(const i of s)this.prevRunning.has(i.sessionId)||this.prevRunning.set(i.sessionId,i.running);let r=s;for(const i of t)r=rs(r,i),this.summaries=r,this.syncCompletedNotifications();this.summaries=r,this.listState="idle",this.listPhase="ready",this.syncCompletedNotifications();for(const i of this.summaries){const o=this.sessions.get(i.sessionId);o!==void 0&&(o.handleBlank(i.blank),o.handleRunning(i.running))}for(const i of n.value.items){const o=i.projections;if(o===void 0)continue;const c=this.projectionStore(i.sessionId),d=o.values;for(const u of Object.keys(d))c.apply(u,d[u],o.asOfSeq)}}else this.listState="error",this.listError=n.error}catch(n){this.listState="error";const s=M(n);this.listError=s.ok?null:s.error}finally{this.listMutations=null,this.listInflight=null,this.notifier.markDirty()}})(),this.listInflight}async search(e,t){try{return(await this.api.sessions.search({query:e},t)).result}catch(n){return M(n)}}async create(e={}){try{const t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId!==void 0?{workspaceId:e.workspaceId,...t}:{...e.cwd===void 0?{}:{cwd:e.cwd},...t},{result:s}=await this.api.sessions.create(n);if(s.ok)this.recordMutation({kind:"upsert",summary:{sessionId:s.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd!==void 0?{cwd:e.cwd}:{},...s.value.agentPreset!==void 0?{agentPreset:s.value.agentPreset}:{}}});else{const r=is(s.error);r!==void 0&&this.recordMutation({kind:"upsert",summary:{sessionId:r,updatedAt:Date.now(),running:!1,blank:!0}})}return s}catch(t){return M(t)}}async fork(e){try{const t=this.summaries.find(r=>r.sessionId===e.sessionId),{result:n}=await this.api.sessions.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:e.atSeq}}),s=n.ok?n.value.sessionId:is(n.error);return s!==void 0&&this.recordMutation({kind:"upsert",summary:{sessionId:s,updatedAt:Date.now(),running:!1,blank:!1,parentSessionId:e.sessionId,...t?.cwd!==void 0?{cwd:t.cwd}:{}}}),n}catch(t){return M(t)}}mergeSummary(e){this.recordMutation({kind:"upsert",summary:e})}noteAgentPreset(e,t){this.recordMutation({kind:"upsert",summary:{sessionId:e,updatedAt:Date.now(),running:!1,blank:!0,agentPreset:t}})}recordMutation(e){this.listMutations?.push(e),this.summaries=rs(this.summaries,e),this.syncCompletedNotifications(),this.notifier.markDirty()}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}trackPending(e,t,n){let s=this.pendingInteractions.get(e);s===void 0&&(s=new Map,this.pendingInteractions.set(e,s)),s.get(t)!==n&&(s.set(t,n),this.notifier.markDirty())}resolvePending(e,t){const n=this.pendingInteractions.get(e);n===void 0||!n.delete(t)||(n.size===0&&this.pendingInteractions.delete(e),this.notifier.markDirty())}handleMuxEnvelope(e){const t=e.payload;if(t.type==="stream/error")return;if(t.type==="session/event"&&t.event.type==="user/message"&&t.event.data.source.kind==="user"&&this.recordMutation({kind:"activity",sessionId:t.sessionId,updatedAt:t.event.time}),t.type==="session/projection"){this.projectionStore(t.sessionId).apply(t.key,t.value,t.seq),this.notifier.markDirty();return}if(t.type==="session/jobs"){t.jobs.length===0?this.jobsBySession.delete(t.sessionId):this.jobsBySession.set(t.sessionId,t.jobs),this.notifier.markDirty();return}if(t.type==="session/subscribed"){this.projectionStores.get(t.sessionId)?.truncate(t.lastSeq),this.jobsBySession.delete(t.sessionId),this.notifier.markDirty();const s=this.pendingBuffers.get(t.sessionId);if(s!==void 0){const r=s.filter(i=>i.payload.type!=="session/queue");r.length!==s.length&&(r.length===0?this.pendingBuffers.delete(t.sessionId):this.pendingBuffers.set(t.sessionId,r))}}t.type==="approval/requested"?this.trackPending(t.sessionId,`a:${t.approvalId}`,"approval"):t.type==="approval/resolved"?this.resolvePending(t.sessionId,`a:${t.approvalId}`):t.type==="question/requested"?this.trackPending(t.sessionId,`q:${e.rpcId}`,Zc(t.questions)):t.type==="question/resolved"&&this.resolvePending(t.sessionId,`q:${t.questionRpcId}`);const n=this.sessions.get(t.sessionId);if(n===void 0)switch(t.type){case"approval/requested":case"question/requested":case"session/queue":{const s=this.pendingBuffers.get(t.sessionId)??[],r=t.type==="approval/requested"?`a:${t.approvalId}`:t.type==="question/requested"?`q:${e.rpcId}`:"queue",i=s.findIndex(o=>ss(o)===r);i===-1?s.push(e):s[i]=e,this.pendingBuffers.set(t.sessionId,s);return}case"approval/resolved":case"question/resolved":{const s=this.pendingBuffers.get(t.sessionId);if(s===void 0)return;const r=t.type==="approval/resolved"?`a:${t.approvalId}`:`q:${t.questionRpcId}`,i=s.findIndex(o=>ss(o)===r);i!==-1&&s.splice(i,1),s.length===0&&this.pendingBuffers.delete(t.sessionId);return}default:return}n.handleMuxEnvelope(e.rpcId,t)}handleHostEnvelope(e){const t=e.payload;switch(t.type){case"host/session-added":this.mergeSummary({sessionId:t.sessionId,updatedAt:Date.now(),running:!1,blank:t.blank,...t.parentSessionId!==void 0?{parentSessionId:t.parentSessionId}:{},...t.origin!==void 0?{origin:t.origin}:{},...t.cwd!==void 0?{cwd:t.cwd}:{},...t.agentPreset!==void 0?{agentPreset:t.agentPreset}:{}}),this.sessions.get(t.sessionId)?.handleBlank(t.blank),t.origin==="subagent"&&t.parentSessionId!==void 0&&this.markCatalogParentExpandable(t.parentSessionId),t.parentSessionId!==void 0&&(this.selected===t.parentSessionId||this.openCatalogs.has(t.parentSessionId))&&this.scheduleCatalogRefresh(t.parentSessionId);return;case"host/session-removed":{const n=this.summaries.find(i=>i.sessionId===t.sessionId)?.origin==="subagent"||this.addresses.has(t.sessionId);this.recordMutation(n?{kind:"status",sessionId:t.sessionId,running:!1}:{kind:"remove",sessionId:t.sessionId}),this.updateCatalogActivity(t.sessionId,!1),n?this.sessions.get(t.sessionId)?.handleRunning(!1):this.sessions.get(t.sessionId)?.handleRemoved(),this.pendingBuffers.delete(t.sessionId),this.pendingInteractions.delete(t.sessionId),this.jobsBySession.delete(t.sessionId),n||this.projectionStores.delete(t.sessionId);const s=this.catalogInflight.get(t.sessionId);s!==void 0&&(s.parentAvailableOverride=!1,this.catalogStale.add(t.sessionId));const r=this.catalogs.get(t.sessionId);r!==void 0&&r.parentAvailable&&this.catalogs.set(t.sessionId,{...r,parentAvailable:!1});for(const[i,o]of this.addresses)o.parentSessionId===t.sessionId&&this.sessions.get(i)?.handleSubagentParentAvailable(!1);return}case"host/session-status":this.recordMutation({kind:"status",sessionId:t.sessionId,running:t.running}),this.sessions.get(t.sessionId)?.handleRunning(t.running),this.updateCatalogActivity(t.sessionId,t.running);return;case"host/agent-error":this.sessions.get(t.sessionId)?.handleAgentError(t.message);return;default:return}}handleDisconnected(){this.pendingInteractions.size>0&&(this.pendingInteractions.clear(),this.notifier.markDirty());for(const[e,t]of[...this.pendingBuffers]){const n=t.filter(s=>s.payload.type!=="approval/requested"&&s.payload.type!=="question/requested");n.length!==t.length&&(n.length===0?this.pendingBuffers.delete(e):this.pendingBuffers.set(e,n))}}handleConnected(){this.refreshList();const e=this.selected===void 0?void 0:this.addresses.get(this.selected);e!==void 0&&this.refreshSubagents(e.parentSessionId),this.selected!==void 0&&this.refreshSubagents(this.selected);for(const t of this.openCatalogs)this.refreshSubagents(t);for(const t of this.sessions.values())t.resync()}scheduleCatalogRefresh(e){if(this.catalogDebounce.has(e))return;const t=setTimeout(()=>{if(this.catalogDebounce.delete(e),this.catalogInflight.has(e)){this.catalogStale.add(e);return}this.refreshSubagents(e)},50);this.catalogDebounce.set(e,t)}updateCatalogActivity(e,t){const n=t?"running":"inactive";for(const r of this.catalogInflight.values())r.activityRows.set(e,n);let s=!1;for(const[r,i]of this.catalogs){if(!i.entries.some(c=>c.kind==="child"&&c.id===e&&c.activity!==n))continue;const o=i.entries.map(c=>c.kind!=="child"||c.id!==e?c:{...c,activity:n});s=!0,this.catalogs.set(r,{...i,entries:o})}s&&this.notifier.markDirty()}markCatalogParentExpandable(e){this.applyCatalogParentExpandable(e);for(const t of this.catalogInflight.values())t.expandableRows.add(e)}applyCatalogParentExpandable(e){let t=!1;for(const[n,s]of this.catalogs){if(!s.entries.some(i=>i.kind==="child"&&i.id===e&&!i.hasChildren))continue;const r=s.entries.map(i=>i.kind!=="child"||i.id!==e||i.hasChildren?i:{...i,hasChildren:!0});t=!0,this.catalogs.set(n,{...s,entries:r})}t&&this.notifier.markDirty()}withCatalogMutations(e,t,n){return e.map(s=>{if(s.kind!=="child")return s;const r=n.get(s.id);return!t.has(s.id)&&r===void 0?s:{...s,...t.has(s.id)?{hasChildren:!0}:{},...r===void 0?{}:{activity:r}}})}syncCompletedNotifications(){const e=new Set;for(const t of this.summaries){e.add(t.sessionId);const n=this.prevRunning.get(t.sessionId);if(n===void 0){this.prevRunning.set(t.sessionId,t.running);continue}n&&!t.running?t.sessionId!==this.selected&&this.completedNotifications.add(t.sessionId):t.running&&this.completedNotifications.delete(t.sessionId),this.prevRunning.set(t.sessionId,t.running)}for(const t of this.prevRunning.keys())e.has(t)||this.prevRunning.delete(t);for(const t of this.completedNotifications)e.has(t)||this.completedNotifications.delete(t)}buildListSnapshot(){const e=this.summaries.map(i=>{const o=this.projectionStores.get(i.sessionId),c=o?.get("title"),d=o?.values();return{...i,...typeof c=="string"&&c!==""?{title:c}:{},...d===void 0?{}:{projectionValues:d}}}),t=new Map;for(const[i,o]of this.pendingInteractions){const c=[...o.values()],d=c.find(u=>u!=="approval")??c[0];d!==void 0&&t.set(i,d)}const n=wc(e,t,this.completedNotifications).map(i=>{const o=this.entryCache.get(i.sessionId);return o!==void 0&&o.updatedAt===i.updatedAt&&o.running===i.running&&o.blank===i.blank&&o.agentPreset===i.agentPreset&&o.parentSessionId===i.parentSessionId&&o.cwd===i.cwd&&o.origin===i.origin&&o.title===i.title&&o.depth===i.depth&&o.pendingInteraction===i.pendingInteraction&&o.projectionValues===i.projectionValues&&o.completed===i.completed?o:(this.entryCache.set(i.sessionId,i),i)});for(const i of this.entryCache.keys())n.some(o=>o.sessionId===i)||this.entryCache.delete(i);n.length===this.itemsCache.length&&n.every((i,o)=>i===this.itemsCache[o])||(this.itemsCache=n);const s=this.selected,r=s!==void 0&&(n.some(i=>i.sessionId===s)||this.addresses.has(s))?s:void 0;return{items:this.itemsCache,current:r,state:this.listState,phase:this.listPhase,error:this.listError,subagentsByParent:Object.fromEntries(this.catalogs),jobsBySession:Object.fromEntries(this.jobsBySession),currentAddress:r===void 0?void 0:this.addresses.get(r)}}};function rs(e,t){switch(t.kind){case"upsert":{const n=e.find(r=>r.sessionId===t.summary.sessionId);if(n===void 0)return[t.summary,...e];const s={...n,blank:n.blank&&t.summary.blank,...n.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...n.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...n.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{},...t.summary.agentPreset!==void 0?{agentPreset:t.summary.agentPreset}:{}};return s.cwd===n.cwd&&s.parentSessionId===n.parentSessionId&&s.origin===n.origin&&s.blank===n.blank&&s.agentPreset===n.agentPreset?[...e]:e.map(r=>r.sessionId===t.summary.sessionId?s:r)}case"remove":return e.filter(n=>n.sessionId!==t.sessionId);case"status":return e.map(n=>n.sessionId===t.sessionId&&(n.running!==t.running||t.running&&n.blank)?{...n,running:t.running,blank:n.blank&&!t.running}:n);case"activity":return e.map(n=>n.sessionId===t.sessionId&&t.updatedAt>n.updatedAt?{...n,updatedAt:t.updatedAt}:n);case"engaged":return e.map(n=>n.sessionId===t.sessionId&&n.blank?{...n,blank:!1}:n)}}a(rs,"applyMutation");function is(e){const t=e;return t.code==="workspace-attach-failed"?t.details.sessionId:void 0}a(is,"workspaceAttachSessionId");var os=class{static{a(this,"SessionProvideChannel")}host;providers=[];maybeInfoCache;currentSnapshot;listeners=new Set;currentProvideInfo;constructor(e){this.host=e,this.providers.push({hooks:["session"],resolve:a(t=>({hooks:{session:t.session}}),"resolve")}),this.maybeInfoCache=this.materializeMaybeInfo(),this.currentSnapshot=this.maybeInfoCache,this.currentProvideInfo={getSnapshot:a(()=>this.currentSnapshot,"getSnapshot"),subscribe:a(t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}),"subscribe")}}get maybeInfo(){return this.maybeInfoCache}provide(e){this.providers.push(e);try{this.applyRosterChange()}catch(t){throw this.providers.splice(this.providers.indexOf(e),1),this.applyRosterChange(),t}return()=>{const t=this.providers.indexOf(e);t>=0&&this.providers.splice(t,1),this.applyRosterChange()}}publishCurrent(){const e=this.host.resolveCurrent();if(e!==this.currentSnapshot){this.currentSnapshot=e;for(const t of[...this.listeners])try{t()}catch(n){console.error("sessions.currentProvideInfo subscriber failed:",n)}}}materializeInfo(e){const t={},n={};for(const s of this.providers){const r=s.resolve(e),i=r.hooks??{},o=r.props??{};for(const c of Object.keys(i))if(!(s.hooks??[]).includes(c))throw new Error(`sessions.provide: undeclared hook "${c}"`);for(const c of Object.keys(o))if(!(s.props??[]).includes(c))throw new Error(`sessions.provide: undeclared prop "${c}"`);for(const c of s.hooks??[]){const d=i[c];if(d===void 0)throw new Error(`sessions.provide: missing hook "${c}"`);if(Object.hasOwn(t,c))throw new Error(`sessions.provide: duplicate hook "${c}"`);t[c]=d}for(const c of s.props??[]){if(!Object.hasOwn(o,c))throw new Error(`sessions.provide: missing prop "${c}"`);if(Object.hasOwn(n,c))throw new Error(`sessions.provide: duplicate prop "${c}"`);n[c]=o[c]}}return{sessionId:e.sessionId,hooks:t,props:n,projections:{faceOf:a(s=>e.session.projections.faceOf(s),"faceOf")}}}applyRosterChange(){this.maybeInfoCache=this.materializeMaybeInfo(),this.host.rebuildBundles(),this.publishCurrent()}materializeMaybeInfo(){const e={},t={};for(const n of this.providers){for(const s of n.hooks??[]){if(Object.hasOwn(e,s))throw new Error(`sessions.provide: duplicate hook "${s}"`);e[s]=void 0}for(const s of n.props??[]){if(Object.hasOwn(t,s))throw new Error(`sessions.provide: duplicate prop "${s}"`);t[s]=void 0}}return{sessionId:void 0,hooks:e,props:t}}},as=class extends Error{static{a(this,"SessionCreateError")}rpcError;requestedSessionId;name="SessionCreateError";constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},Mc=class extends Error{static{a(this,"SessionForkError")}rpcError;sourceSessionId;name="SessionForkError";constructor(e,t){super(`session fork failed: ${e.code}: ${e.message}`),this.rpcError=e,this.sourceSessionId=t}};function cs(e){return e.replace(/[/\\]+$/,"").split(/[/\\]/).pop()??""}a(cs,"workspaceTitleOf");function xc(e,t,n){if(e!==void 0)return e;if(t!==void 0&&t!==""){const s=cs(t);if(s!=="")return s}return n}a(xc,"displayTitleOf");function qc(e){const t=/^(.*?)\((\d+)\)$/u.exec(e);if(t?.[1]!==void 0&&t[2]!==void 0)return`${t[1]}(${BigInt(t[2])+1n})`;const n=/^(.*?)((\d+))$/u.exec(e);return n?.[1]!==void 0&&n[2]!==void 0?`${n[1]}(${BigInt(n[2])+1n})`:`${e} (1)`}a(qc,"increasedForkTitle");var us=class{static{a(this,"SessionRuntime")}rootCtx;searchResultLimit=20;list;manager;currentProvideInfo;selection;scopes=new Map;provideChannel;watched;deferredRemovals=new Set;constructor(e,t,n,s){this.rootCtx=e,this.selection=fe({},{persist:{name:"dsh.sessions.current"}});const r=this.selection.getSnapshot(),i=e.get("conversationEvents"),o=e.get("conversationViews"),c=s??(i===void 0||o===void 0?void 0:{events:i,views:o});this.manager=new Nc(t,n,r.sessionId,r.subagentAddress,c),this.list=fe({ids:[],byId:{},current:void 0,phase:"pending",subagentsByParent:{},jobsBySession:{},currentAddress:void 0}),this.manager.subscribe(()=>{this.projectList()}),this.list.subscribe(()=>{this.followCurrent(),this.provideChannel.publishCurrent()}),this.provideChannel=new os({rebuildBundles:a(()=>{for(const h of this.scopes.values())h.provideInfo=this.provideChannel.materializeInfo(h.binding)},"rebuildBundles"),resolveCurrent:a(()=>this.maybeProvideInfo(this.list.getSnapshot().current),"resolveCurrent")}),this.currentProvideInfo=this.provideChannel.currentProvideInfo;let d=!1;const u=a(()=>{d||(d=!0,queueMicrotask(()=>{d=!1,this.manager.rebuildConversationRegistry()}))},"scheduleRegistryRebuild");c!==void 0&&e.effect(()=>{const h=c.events.subscribe(u),m=c.views.subscribe(u);return()=>{h(),m()}},"sessions: conversation registry rebuild"),e.reflect.provide("sessions",this,void 0)}provide(e){return this.provideChannel.provide(e)}open(e){this.manager.select(e)}openSubagent(e){this.manager.selectSubagent(e)}subagentAddress(e){return this.manager.subagentAddress(e)}setSubagentCatalogOpen(e,t){this.manager.setSubagentCatalogOpen(e,t)}refreshSubagents(e){return this.manager.refreshSubagents(e)}noteAgentPreset(e,t){this.manager.noteAgentPreset(e,t)}clear(){this.manager.clearSelection()}refresh(){return this.manager.refreshList()}search(e,t){return this.manager.search(e,t)}handleMuxEnvelope(e){this.manager.handleMuxEnvelope(e)}handleHostEnvelope(e){this.manager.handleHostEnvelope(e)}handleConnected(){this.manager.handleConnected()}handleDisconnected(){this.manager.handleDisconnected()}async create(e={}){const t=await this.manager.create(e);if(!t.ok)throw new as(t.error,e.sessionId);return this.projectList(),t.value.sessionId}async fork(e){const t=e.increaseTitle?this.list.getSnapshot().byId[e.sessionId]?.title:void 0,n=await this.manager.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:Math.floor(e.atSeq)}});if(!n.ok)throw new Mc(n.error,e.sessionId);this.projectList();const s=n.value.sessionId;if(t!==void 0){const r=this.binding(s)?.session;if(r===void 0)throw new Error(`fork child "${s}" is not locally addressable`);const i=await r.rename(qc(t));if(!i.ok)throw new Error(`fork child rename failed: ${i.error.code}: ${i.error.message}`)}return s}scope(e){return this.resolve(e)?.ctx}scopeOf(e){return Re(e)}sessionOf(e){const t=Re(e);if(t!==void 0)return this.scopes.get(t)?.binding.session}binding(e){return this.resolve(e)?.binding}provideInfo(e){return this.resolve(e)?.provideInfo}maybeProvideInfo(e){return(e===void 0?void 0:this.provideInfo(e))??this.provideChannel.maybeInfo}followCurrent(){const e=this.list.getSnapshot(),t=e.current;if(t===void 0||e.byId[t]===void 0||t===this.watched)return;this.watched=t,this.sweepDeferred();const n=this.resolve(t);n!==void 0&&(n.session.open(),this.manager.refreshSubagents(t))}resolve(e){const t=this.scopes.get(e);if(t!==void 0)return t;if(!this.eligible(e))return;const{fiber:n,ctx:s}=Fn(this.rootCtx,e),r=this.manager.get(e);r.bindScope(s);const i={sessionId:e,session:r,ctx:s},o={fiber:n,ctx:s,binding:i,session:r,provideInfo:this.provideChannel.materializeInfo(i)};return this.scopes.set(e,o),o}eligible(e){const{ids:t,current:n}=this.list.getSnapshot();return n===e||t.includes(e)}projectList(){const{items:e,current:t,phase:n,subagentsByParent:s,jobsBySession:r,currentAddress:i}=this.manager.getListSnapshot(),o=[],c={};for(const u of e)o.push(u.sessionId),c[u.sessionId]={id:u.sessionId,displayTitle:xc(u.title,u.cwd,u.sessionId),running:u.running,...u.completed?{completed:!0}:{},blank:u.blank,updatedAt:u.updatedAt,...u.pendingInteraction===void 0?{}:{pendingInteraction:u.pendingInteraction},...u.projectionValues===void 0?{}:{projectionValues:u.projectionValues},...u.title!==void 0?{title:u.title}:{},...u.cwd!==void 0?{cwd:u.cwd}:{},...u.parentSessionId!==void 0?{parentId:u.parentSessionId}:{},...u.origin!==void 0?{origin:u.origin}:{},...u.agentPreset!==void 0?{agentPreset:u.agentPreset}:{}};if(t!==void 0&&i!==void 0){const u=new Set;let h=i;for(;h!==void 0&&!u.has(h.childSessionId);){const m=h.childSessionId;u.add(m);const v=s[h.parentSessionId]?.entries.find(_=>_.kind==="child"&&_.id===m);if(v?.kind!=="child")break;const b=v.label??m,z=c[m];z===void 0?c[m]={id:m,displayTitle:b,parentId:h.parentSessionId,origin:"subagent",running:v.activity==="running",blank:!1,updatedAt:0}:z.displayTitle!==b&&(c[m]={...z,displayTitle:b});const p=c[h.parentSessionId];if(p!==void 0&&p.origin!=="subagent")break;h=this.manager.navigationAddress(h.parentSessionId)}}const d=this.selection.getSnapshot().sessionId;t===void 0?d!==void 0&&this.selection.set({}):c[t]!==void 0&&(d!==t||this.selection.getSnapshot().subagentAddress?.childSessionId!==i?.childSessionId||this.selection.getSnapshot().subagentAddress?.parentSessionId!==i?.parentSessionId||this.selection.getSnapshot().subagentAddress?.mode!==i?.mode)&&this.selection.set({sessionId:t,...i===void 0?{}:{subagentAddress:i}}),this.list.set({ids:o,byId:c,current:t,phase:n,subagentsByParent:s,jobsBySession:r,currentAddress:i}),this.pruneScopes()}pruneScopes(){for(const[e,t]of this.scopes)if(!this.eligible(e)){if(e===this.watched){this.deferredRemovals.add(e);continue}this.scopes.delete(e),this.deferredRemovals.delete(e),this.dropScope(e,t)}}dropScope(e,t){t.fiber.dispose(),t.session.unbindScope(),this.rootCtx.get("slots")?.pruneStoreScope(e),this.manager.drop(e)}sweepDeferred(){for(const e of[...this.deferredRemovals]){if(e===this.watched)continue;if(this.eligible(e)){this.deferredRemovals.delete(e);continue}const t=this.scopes.get(e);this.deferredRemovals.delete(e),t!==void 0&&(this.scopes.delete(e),this.dropScope(e,t))}}},wt=class{static{a(this,"Workspace")}api;view;intent;materialization=null;snapshotCache;notifier=new ne(()=>{this.snapshotCache=this.buildSnapshot()});constructor(e,t){this.api=e,"workspaceId"in t?this.view=t:this.intent={input:t,snapshot:{name:Rc(t),phase:"ready"}},this.snapshotCache=this.buildSnapshot()}materialize(){if(this.materialization!==null)return this.materialization;const e=this.intent;if(e===void 0)return;e.snapshot={name:e.snapshot.name,phase:"creating"},this.notifier.notifyNow();const t=this.completeMaterialization(e).finally(()=>{this.materialization===t&&(this.materialization=null)});return this.materialization=t,t}adopt(e){if(this.view!==void 0&&this.view.workspaceId!==e.workspaceId)throw new Error("cannot adopt a different Workspace id");this.view=e,this.intent=void 0,this.notifier.markDirty()}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}async completeMaterialization(e){let t;try{t=(await this.api.workspace.create(e.input)).result}catch(n){t=M(n)}return this.intent!==e||(t.ok?this.adopt(t.value.workspace):(e.snapshot={name:e.snapshot.name,phase:"ready",error:`${t.error.code}: ${t.error.message}`},this.notifier.markDirty())),t}buildSnapshot(){return{view:this.view,intent:this.intent?.snapshot}}};function Rc(e){return e.path.replace(/[\\/]+$/,"").split(/[\\/]/).pop()??e.path}a(Rc,"intentName");var jc=class{static{a(this,"WorkspaceManager")}api;items=[];itemViewsSource=null;itemViewsCache=[];archivedSessionIds=[];state="idle";phase="pending";error=null;inflight=null;refreshFrames=null;archivedSupersedesRefresh=!1;orderRequestGeneration=0;orderFrameGeneration=0;committedOrder=[];removedIds=new Set;snapshotCache;notifier=new ne(()=>{this.snapshotCache=this.buildSnapshot()});constructor(e){this.api=e,this.snapshotCache=this.buildSnapshot()}refresh(){if(this.inflight!==null)return this.inflight;this.state="loading",this.error=null;const e=[];return this.refreshFrames=e,this.notifier.markDirty(),this.inflight=(async()=>{try{const{result:t}=await this.api.workspace.list({});if(t.ok){let n=t.value.items;n=n.filter(s=>!this.removedIds.has(s.workspaceId));for(const s of e)n=Bc(n,s);this.installViews(n),this.archivedSupersedesRefresh||this.installArchived(t.value.archivedSessionIds),this.state="idle",this.phase="ready"}else this.state="error",this.error=t.error}catch(t){this.state="error";const n=M(t);this.error=n.ok?null:n.error}finally{this.refreshFrames=null,this.archivedSupersedesRefresh=!1,this.inflight=null,this.notifier.markDirty()}})(),this.inflight}async create(e){const t=new wt(this.api,e),n=t.materialize();if(n===void 0)throw new Error("a local Workspace must be materializable");const s=await n;return s.ok&&this.upsert(s.value.workspace,t),s}async rename(e,t){const{result:n}=await this.api.workspace.rename({workspaceId:e,title:t});return n.ok&&this.upsert(n.value.workspace),n}async delete(e){const{result:t}=await this.api.workspace.delete({workspaceId:e});return t.ok&&this.remove(e,!0),t}async insertBefore(e,t){const n=++this.orderRequestGeneration,s=this.orderFrameGeneration,r=this.itemViews().map(o=>o.workspaceId);this.installOrder(Lc(r,e,t));let i;try{({result:i}=await this.api.workspace.insertBefore({workspaceId:e,...t===void 0?{}:{beforeWorkspaceId:t}}))}catch(o){throw n===this.orderRequestGeneration&&s===this.orderFrameGeneration&&this.installOrder(this.committedOrder),o}return i.ok&&n===this.orderRequestGeneration&&s===this.orderFrameGeneration?this.installOrder(i.value.workspaceIds,!0):!i.ok&&n===this.orderRequestGeneration&&s===this.orderFrameGeneration&&this.installOrder(this.committedOrder),i}async insertSessionBefore(e,t,n){const{result:s}=await this.api.workspace.insertSessionBefore({workspaceId:e,sessionId:t,...n===void 0?{}:{beforeSessionId:n}});return s.ok&&this.upsert(s.value.workspace),s}async archiveSession(e){const{result:t}=await this.api.workspace.archiveSession({sessionId:e});return t.ok&&this.installArchived(t.value.archivedSessionIds),t}handleHostEnvelope(e){e.payload.type==="host/workspace-changed"?this.upsert(e.payload.workspace):e.payload.type==="host/workspace-removed"?this.remove(e.payload.workspaceId):e.payload.type==="host/workspace-order-changed"?(this.orderFrameGeneration++,this.installOrder(e.payload.workspaceIds,!0)):e.payload.type==="host/archived-sessions-changed"&&this.installArchived(e.payload.archivedSessionIds)}handleConnected(){this.refresh()}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}buildSnapshot(){return{items:this.itemViews(),archivedSessionIds:this.archivedSessionIds,state:this.state,phase:this.phase,error:this.error}}installArchived(e){this.refreshFrames!==null&&(this.archivedSupersedesRefresh=!0),!(e.length===this.archivedSessionIds.length&&e.every((t,n)=>t===this.archivedSessionIds[n]))&&(this.archivedSessionIds=[...e],this.notifier.markDirty())}installOrder(e,t=!1){t&&(this.refreshFrames?.push({type:"order",workspaceIds:e}),this.committedOrder=[...e]);const n=new Map(e.map((r,i)=>[r,i])),s=[...this.items].sort((r,i)=>{const o=r.getSnapshot().view?.workspaceId,c=i.getSnapshot().view?.workspaceId;return(o===void 0?Number.MAX_SAFE_INTEGER:n.get(o)??Number.MAX_SAFE_INTEGER)-(c===void 0?Number.MAX_SAFE_INTEGER:n.get(c)??Number.MAX_SAFE_INTEGER)});s.every((r,i)=>r===this.items[i])||(this.items=s,this.notifier.markDirty())}upsert(e,t){if(this.removedIds.has(e.workspaceId))return;this.refreshFrames?.push({type:"upsert",workspace:e});const n=this.items.findIndex(r=>r.getSnapshot().view?.workspaceId===e.workspaceId),s=n===-1?void 0:this.items[n]?.getSnapshot().view;s!==void 0&&Date.parse(e.updatedAt)<Date.parse(s.updatedAt)||(this.committedOrder.includes(e.workspaceId)||(this.committedOrder=[e.workspaceId,...this.committedOrder]),t!==void 0?this.items=n===-1?[t,...this.items]:this.items.map((r,i)=>i===n?t:r):n===-1?this.items=[new wt(this.api,e),...this.items]:(this.items[n]?.adopt(e),this.items=[...this.items]),this.notifier.markDirty())}remove(e,t=!1){this.refreshFrames?.push({type:"remove",workspaceId:e}),this.removedIds.add(e),this.committedOrder=this.committedOrder.filter(s=>s!==e);const n=this.items.filter(s=>s.getSnapshot().view?.workspaceId!==e);if(n.length===this.items.length){t&&this.notifier.notifyNow();return}this.items=n,t?this.notifier.notifyNow():this.notifier.markDirty()}installViews(e){const t=new Map(this.items.flatMap(s=>{const r=s.getSnapshot().view;return r===void 0?[]:[[r.workspaceId,s]]})),n=new Map;for(const s of e){const r=n.get(s.workspaceId);if(r!==void 0){r.adopt(s);continue}const i=t.get(s.workspaceId)??new wt(this.api,s);i.adopt(s),n.set(s.workspaceId,i)}this.items=[...n.values()],this.committedOrder=e.map(s=>s.workspaceId)}itemViews(){return this.itemViewsSource===this.items?this.itemViewsCache:(this.itemViewsSource=this.items,this.itemViewsCache=this.items.flatMap(e=>{const t=e.getSnapshot().view;return t===void 0?[]:[t]}),this.itemViewsCache)}};function Fc(e,t){const n=e.findIndex(s=>s.workspaceId===t.workspaceId);return n===-1?[t,...e]:e.map((s,r)=>r===n?t:s)}a(Fc,"upsertWorkspace");function Bc(e,t){if(t.type==="upsert")return Fc(e,t.workspace);if(t.type==="remove")return e.filter(s=>s.workspaceId!==t.workspaceId);const n=new Map(t.workspaceIds.map((s,r)=>[s,r]));return[...e].sort((s,r)=>(n.get(s.workspaceId)??Number.MAX_SAFE_INTEGER)-(n.get(r.workspaceId)??Number.MAX_SAFE_INTEGER))}a(Bc,"applyWorkspaceDelta");function Lc(e,t,n){if(!e.includes(t)||n!==void 0&&!e.includes(n)||n===t)return[...e];const s=e.filter(i=>i!==t),r=n===void 0?s.length:s.indexOf(n);return[...s.slice(0,r),t,...s.slice(r)]}a(Lc,"insertIdBefore");var ds=class extends Error{static{a(this,"WorkspaceCreateError")}rpcError;constructor(e){super(`workspace create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.name="WorkspaceCreateError"}},bt=class extends Error{static{a(this,"DirectoryBrowseError")}rpcError;constructor(e){super(`directory browse failed: ${e.code}: ${e.message}`),this.rpcError=e,this.name="DirectoryBrowseError"}},ls=class{static{a(this,"WorkspaceRuntime")}api;sessions;list;manager;connecting=new Map;initialSelectionStarted=!1;constructor(e,t,n){this.api=t,this.sessions=n,this.manager=new jc(t),this.list=fe({items:[],archivedSessionIds:[],state:"idle",phase:"pending",error:null,baselinesReady:!1,recentWorkspaceId:void 0}),this.manager.subscribe(()=>{this.project()}),this.sessions.list.subscribe(()=>{this.project()}),e.reflect.provide("workspaces",this,void 0)}async connectWorkspace(e){const t=this.list.getSnapshot().items.find(o=>o.workspaceId===e);if(t===void 0)throw new Error(`workspaces.connectWorkspace: unknown workspace ${e}`);const n=this.connecting.get(e);if(n!==void 0)return n;const s=this.list.getSnapshot().archivedSessionIds,r=this.sessions.list.getSnapshot();for(const o of r.ids){const c=r.byId[o];if(c!==void 0&&c.blank&&c.cwd===t.path&&t.sessionIds.includes(c.id)&&!s.includes(c.id))return c.id}const i=this.sessions.create({workspaceId:e}).finally(()=>{this.connecting.delete(e)});return this.connecting.set(e,i),i}startInitialSelection(){if(this.initialSelectionStarted)throw new Error("workspaces.startInitialSelection: already started");this.initialSelectionStarted=!0;let e="waiting",t=!1;const n=a(()=>{if(t||e!=="waiting")return;const r=this.list.getSnapshot();if(!r.baselinesReady)return;const i=this.sessions.list.getSnapshot().current,o=r.recentWorkspaceId;if(i!==void 0||o===void 0){e="done";return}e="connecting",this.connectWorkspace(o).then(c=>{t||(this.sessions.list.getSnapshot().current===void 0&&this.sessions.open(c),e="done")},c=>{t||(e="waiting",console.warn("initial workspace selection failed:",c))})},"reconcile"),s=this.list.subscribe(n);return n(),()=>{t=!0,s()}}startSession(e){const t=this.list.getSnapshot(),n=this.sessions.list.getSnapshot().current,s=n===void 0?void 0:t.items.find(i=>i.sessionIds.includes(n))?.workspaceId,r=e??s??t.recentWorkspaceId;if(r===void 0){this.sessions.clear();return}this.connectWorkspace(r).then(i=>{this.sessions.open(i)},i=>{console.warn("new session failed:",i)})}async create(e){const t=await this.manager.create(e);if(!t.ok)throw new ds(t.error);return t.value.workspace}async pickDirectory(){const e=await this.api.host.pickDirectory({});if(!e.result.ok)throw new Error(`directory picker failed: ${e.result.error.message}`);return e.result.value.path}async listDirectory(e,t){const n=await this.api.host.listDirectory(e===void 0?{}:{path:e},t);if(!n.result.ok)throw new bt(n.result.error);return n.result.value}async createDirectory(e,t){const n=await this.api.host.createDirectory({path:e,name:t});if(!n.result.ok)throw new bt(n.result.error);return n.result.value.path}async openPath(e){const t=await this.api.host.openPath({path:e});if(!t.result.ok)throw new Error(`path open failed: ${t.result.error.message}`)}async rename(e,t){const n=await this.manager.rename(e,t);if(!n.ok)throw new Error(`workspace rename failed: ${n.error.code}: ${n.error.message}`);return n.value.workspace}async delete(e){const t=await this.manager.delete(e);if(!t.ok)throw new Error(`workspace delete failed: ${t.error.code}: ${t.error.message}`)}async insertBefore(e,t){const n=await this.manager.insertBefore(e,t);if(!n.ok)throw new Error(`workspace reorder failed: ${n.error.code}: ${n.error.message}`)}async archiveSession(e){const t=await this.manager.archiveSession(e);if(!t.ok)throw new Error(`session archive failed: ${t.error.code}: ${t.error.message}`)}async insertSessionBefore(e,t,n){const s=await this.manager.insertSessionBefore(e,t,n);if(!s.ok)throw new Error(`workspace move failed: ${s.error.code}: ${s.error.message}`);return s.value.workspace}refresh(){return this.manager.refresh()}handleHostEnvelope(e){this.manager.handleHostEnvelope(e)}handleConnected(){this.manager.handleConnected()}project(){const e=this.manager.getSnapshot(),t=this.sessions.list.getSnapshot(),n=e.phase==="ready"&&t.phase==="ready";t.current!==void 0&&e.archivedSessionIds.includes(t.current)&&this.sessions.clear(),this.list.set({items:e.items,archivedSessionIds:e.archivedSessionIds,state:e.state,phase:e.phase,error:e.error,baselinesReady:n,recentWorkspaceId:n?Uc(e.items,t.byId):void 0})}};function Uc(e,t){let n,s=Number.NEGATIVE_INFINITY;for(const r of e){let i=Number.NEGATIVE_INFINITY;for(const o of r.sessionIds){const c=t[o];c!==void 0&&(i=Math.max(i,c.updatedAt))}i===Number.NEGATIVE_INFINITY&&(i=Date.parse(r.createdAt)),(n===void 0||i>s)&&(n=r.workspaceId,s=i)}return n}a(Uc,"recentWorkspace");var hs=class extends Be.Service{static{a(this,"ConversationDefinitionRegistry")}definitions=new Map;listeners=new Set;cached=[];entries(){return this.cached}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}registerDefinition(e,t,n,s){if(this.definitions.has(e))throw new Error(n);const r=this.ctx.effect(()=>(this.definitions.set(e,t),this.refresh(),()=>{this.definitions.get(e)===t&&(this.definitions.delete(e),this.refresh())}),s);return()=>{r()}}refresh(){this.cached=[...this.definitions.values()];for(const e of this.listeners)e()}},fs=class extends hs{static{a(this,"ConversationEventRegistry")}fallback;constructor(e){super(e,"conversationEvents")}register(e){return ps(e),this.registerDefinition(e.kind,e,`conversation Definition "${e.kind}" is already registered`,`conversationEvents.register(${JSON.stringify(e.kind)})`)}registerFallback(e){if(ps(e),e.target===void 0)throw new Error("conversation fallback Definition must declare a target");if(this.fallback!==void 0)throw new Error("conversation fallback Definition is already registered");const t=this.ctx.effect(()=>(this.fallback=e,this.refresh(),()=>{this.fallback===e&&(this.fallback=void 0,this.refresh())}),`conversationEvents.registerFallback(${JSON.stringify(e.kind)})`);return()=>{t()}}fallbackEntry(){return this.fallback}};function ps(e){if(e.target===void 0!=(e.buildViewNode===void 0))throw new Error(`conversation Definition "${e.kind}" must declare target and buildViewNode together`)}a(ps,"assertDefinitionTarget");var ms=class extends hs{static{a(this,"ConversationViewRegistry")}constructor(e){super(e,"conversationViews")}register(e){return this.registerDefinition(e.target,e,`conversation view target "${e.target}" is already registered`,`conversationViews.register(${JSON.stringify(e.target)})`)}};const Vc=new Set(["user/message","assistant/message","tool/result"]);function gs(e){return Vc.has(e.type)?e.surfaceOp!==void 0:!1}a(gs,"isSurfaceEvent");function Wc(e){return gs(e)&&e.surfaceOp==="append"}a(Wc,"isAppendSurfaceEvent");function Jc(e){return gs(e)&&e.surfaceOp!=="append"}a(Jc,"isReplacementSurfaceEvent");function Gc(e){const t=new Map;for(const n of Object.values(e)){if(n.origin!=="subagent")continue;const s=new Set;let r=n;for(;r?.origin==="subagent"&&r.parentId!==void 0&&!s.has(r.id);){s.add(r.id);const i=t.get(r.parentId);i===void 0?t.set(r.parentId,{count:1,runningCount:n.running?1:0}):(i.count+=1,n.running&&(i.runningCount+=1)),r=e[r.parentId]}}return t}a(Gc,"indexSubagentDescendants");function Kc(e,t){return t.startsWith("/")||/^[A-Za-z]:[/\\]/.test(t)||t.startsWith("\\\\")||e===void 0||e===""?t:`${e.replace(/[/\\]+$/,"")}/${t.replace(/^[/\\]+/,"")}`}a(Kc,"resolveWorkspacePath");function Yc(e){switch(e){case"text":return{kind:"text",text:""};case"reasoning":return{kind:"reasoning",text:""};case"tool-call":return{kind:"tool-call",callId:"",name:"",argsRaw:""};default:return{kind:"other",block:null}}}a(Yc,"emptyAssistantBlock");function Hc(e){switch(e.type){case"text-delta":case"reasoning-delta":return e.text!=="";case"tool-call-delta":return e.argumentsDelta!==""||e.name!==void 0;default:return!1}}a(Hc,"isTokenDelta");function _t(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}a(_t,"asRecord");function ge(e,t){const n=e[t];return typeof n=="string"&&n.length>0?n:null}a(ge,"readString");function vs(e,t,n){const s=e[t];if(!Array.isArray(s))return[];const r=[];for(const i of s){const o=_t(i),c=o===null?null:ge(o,n);c!==null&&!r.includes(c)&&r.push(c)}return r}a(vs,"collect");function ys(e){return e.length>0?e.join(", "):null}a(ys,"joined");function Xc(e){const t=_t(e),n=t===null?null:ge(t,"kind");if(t===null||n===null)return{role:"inject",label:null};switch(n){case"session-reference":return{role:"recall",label:ys(vs(t,"references","label"))??n};case"agent-instructions":return{role:"inject",label:ys(vs(t,"changes","path"))??n};case"plugin":return{role:"inject",label:ge(t,"plugin")??n};case"skill-invocation":return{role:"inject",label:ge(t,"name")??n};default:return{role:"inject",label:n}}}a(Xc,"contextProvenance");const Qc=["instructions","catalog","snapshot","notice","relay","recall"];function eu(e){const t=_t(e),n=t===null?null:ge(t,"form");return n!==null&&Qc.includes(n)?n:null}a(eu,"contextForm");function tu(e){if(e===null||typeof e!="object")return String(e);const t=e;return t.code==="AUTH"?"API key is invalid":typeof t.message=="string"?t.message:JSON.stringify(e)}a(tu,"displayFailureMessage");const nu=["connection","typert","remote","remote.commands"];function su(e){e.plugin(Le);const t={events:new fs(e),views:new ms(e)},n=e.get("connection"),s=new us(e,n.api,e.remote,t);e.typert.contexts.registerClient("agent",{identity:a(o=>s.scopeOf(o),"identity")});const r=new ls(e,n.api,s);e.effect(()=>r.startInitialSelection(),"runtime: initial Workspace selection");const i=n.start({onMuxEnvelope:a(o=>{s.handleMuxEnvelope(o)},"onMuxEnvelope"),onHostEnvelope:a(o=>{s.handleHostEnvelope(o),r.handleHostEnvelope(o);const c=o.payload;c.type==="host/remote-event"&&e.remote.$dispatch(c.event,c.args)},"onHostEnvelope"),onConnected:a(()=>{s.handleConnected(),r.handleConnected(),e.emit("connection/reset")},"onConnected"),onStateChange:a(o=>{o==="reconnecting"&&s.handleDisconnected()},"onStateChange")});e.effect(()=>()=>{i.stop()},"runtime: connection stream loop")}return a(su,"apply"),k.ConversationEventRegistry=fs,k.ConversationLocationIndex=Jn,k.ConversationNodeAssembler=gt,k.ConversationViewRegistry=ms,k.DirectoryBrowseError=bt,k.EMPTY_CHAT_SNAPSHOT=Qn,k.EMPTY_CONVERSATION_VIEWS=$c,k.PendingWait=yt,k.SessionCreateError=as,k.SessionProvideChannel=os,k.SessionRuntime=us,k.SlotRegistry=Le,k.WorkspaceCreateError=ds,k.WorkspaceRuntime=ls,k.apply=su,k.contextForm=eu,k.contextProvenance=Xc,k.conversationContextKey=ht,k.createScope=Fn,k.createSnapshotStore=fe,k.defineStore=gc,k.displayFailureMessage=tu,k.emptyAssistantBlock=Yc,k.indexSubagentDescendants=Gc,k.inject=nu,k.isAppendSurfaceEvent=Wc,k.isReplacementSurfaceEvent=Jc,k.isTokenDelta=Hc,k.resolveWorkspacePath=Kc,k.scopeOf=Re,k.shallowEqual=fc,k.toAssistantBlock=Xn,k.toAssistantBlocks=Ic,k.workspaceTitleOf=cs,we.exports},"factory")});
64
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const c=o[1];if(t===o[0]){i(o);continue}if(e.external){const d=e.external.registry.get(o[0])?.id;if(t!==o[0]&&d){i(o);continue}}if(e.metadataRegistry.get(o[0])?.id){i(o);continue}if(c.cycle){i(o);continue}if(c.count>1&&e.reused==="ref"){i(o);continue}}}a(un,"extractDefs");function dn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=a(c=>{const d=e.seen.get(c);if(d.ref===null)return;const u=d.def??d.schema,h={...u},m=d.ref;if(d.ref=null,m){s(m);const b=e.seen.get(m),z=b.schema;if(z.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(z)):Object.assign(u,z),Object.assign(u,h),c._zod.parent===m)for(const p in u)p==="$ref"||p==="allOf"||p in h||delete u[p];if(z.$ref&&b.def)for(const p in u)p==="$ref"||p==="allOf"||p in b.def&&JSON.stringify(u[p])===JSON.stringify(b.def[p])&&delete u[p]}const v=c._zod.parent;if(v&&v!==m){s(v);const b=e.seen.get(v);if(b?.schema.$ref&&(u.$ref=b.schema.$ref,b.def))for(const z in u)z==="$ref"||z==="allOf"||z in b.def&&JSON.stringify(u[z])===JSON.stringify(b.def[z])&&delete u[z]}e.override({zodSchema:c,jsonSchema:u,path:d.path??[]})},"flattenRef");for(const c of[...e.seen.entries()].reverse())s(c[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const c=e.external.registry.get(t)?.id;if(!c)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(c)}Object.assign(r,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&r.id===i&&delete r.id;const o=e.external?.defs??{};for(const c of e.seen.entries()){const d=c[1];d.def&&d.defId&&(d.def.id===d.defId&&delete d.def.id,o[d.defId]=d.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?r.$defs=o:r.definitions=o);try{const c=JSON.parse(JSON.stringify(r));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:Pe(t,"input",e.processors),output:Pe(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}a(dn,"finalize$1");function Z(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return Z(s.element,n);if(s.type==="set")return Z(s.valueType,n);if(s.type==="lazy")return Z(s.getter(),n);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return Z(s.innerType,n);if(s.type==="intersection")return Z(s.left,n)||Z(s.right,n);if(s.type==="record"||s.type==="map")return Z(s.keyType,n)||Z(s.valueType,n);if(s.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Z(s.in,n)||Z(s.out,n);if(s.type==="object"){for(const r in s.shape)if(Z(s.shape[r],n))return!0;return!1}if(s.type==="union"){for(const r of s.options)if(Z(r,n))return!0;return!1}if(s.type==="tuple"){for(const r of s.items)if(Z(r,n))return!0;return!!(s.rest&&Z(s.rest,n))}return!1}a(Z,"isTransforming");const wo=a((e,t={})=>n=>{const s=cn({...n,processors:t});return T(e,s),un(s,e),dn(s,e)},"createToJSONSchemaMethod"),Pe=a((e,t,n={})=>s=>{const{libraryOptions:r,target:i}=s??{},o=cn({...r??{},target:i,io:t,processors:n});return T(e,o),un(o,e),dn(o,e)},"createStandardJSONSchemaMethod"),bo={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_o=a((e,t,n,s)=>{const r=n;r.type="string";const{minimum:i,maximum:o,format:c,patterns:d,contentEncoding:u}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof o=="number"&&(r.maxLength=o),c&&(r.format=bo[c]??c,r.format===""&&delete r.format,c==="time"&&delete r.format),u&&(r.contentEncoding=u),d&&d.size>0){const h=[...d];h.length===1?r.pattern=h[0].source:h.length>1&&(r.allOf=[...h.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},"stringProcessor"),ko=a((e,t,n,s)=>{const r=n,{minimum:i,maximum:o,format:c,multipleOf:d,exclusiveMaximum:u,exclusiveMinimum:h}=e._zod.bag;typeof c=="string"&&c.includes("int")?r.type="integer":r.type="number";const m=typeof h=="number"&&h>=(i??Number.NEGATIVE_INFINITY),v=typeof u=="number"&&u<=(o??Number.POSITIVE_INFINITY),b=t.target==="draft-04"||t.target==="openapi-3.0";m?b?(r.minimum=h,r.exclusiveMinimum=!0):r.exclusiveMinimum=h:typeof i=="number"&&(r.minimum=i),v?b?(r.maximum=u,r.exclusiveMaximum=!0):r.exclusiveMaximum=u:typeof o=="number"&&(r.maximum=o),typeof d=="number"&&(r.multipleOf=d)},"numberProcessor"),So=a((e,t,n,s)=>{n.not={}},"neverProcessor"),Io=a((e,t,n,s)=>{const r=e._zod.def,i=It(r.entries);i.every(o=>typeof o=="number")&&(n.type="number"),i.every(o=>typeof o=="string")&&(n.type="string"),n.enum=i},"enumProcessor"),zo=a((e,t,n,s)=>{const r=e._zod.def,i=[];for(const o of r.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(i.length!==0)if(i.length===1){const o=i[0];n.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[o]:n.const=o}else i.every(o=>typeof o=="number")&&(n.type="number"),i.every(o=>typeof o=="string")&&(n.type="string"),i.every(o=>typeof o=="boolean")&&(n.type="boolean"),i.every(o=>o===null)&&(n.type="null"),n.enum=i},"literalProcessor"),$o=a((e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},"customProcessor"),Eo=a((e,t,n,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},"transformProcessor"),Oo=a((e,t,n,s)=>{const r=n,i=e._zod.def,{minimum:o,maximum:c}=e._zod.bag;typeof o=="number"&&(r.minItems=o),typeof c=="number"&&(r.maxItems=c),r.type="array",r.items=T(i.element,t,{...s,path:[...s.path,"items"]})},"arrayProcessor"),Po=a((e,t,n,s)=>{const r=n,i=e._zod.def;r.type="object",r.properties={};const o=i.shape;for(const u in o)r.properties[u]=T(o[u],t,{...s,path:[...s.path,"properties",u]});const c=new Set(Object.keys(o)),d=new Set([...c].filter(u=>{const h=i.shape[u]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));d.size>0&&(r.required=Array.from(d)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=T(i.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},"objectProcessor"),Do=a((e,t,n,s)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((c,d)=>T(c,t,{...s,path:[...s.path,i?"oneOf":"anyOf",d]}));i?n.oneOf=o:n.anyOf=o},"unionProcessor"),Co=a((e,t,n,s)=>{const r=e._zod.def,i=T(r.left,t,{...s,path:[...s.path,"allOf",0]}),o=T(r.right,t,{...s,path:[...s.path,"allOf",1]}),c=a(d=>"allOf"in d&&Object.keys(d).length===1,"isSimpleIntersection");n.allOf=[...c(i)?i.allOf:[i],...c(o)?o.allOf:[o]]},"intersectionProcessor"),Ao=a((e,t,n,s)=>{const r=e._zod.def,i=T(r.innerType,t,s),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=r.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},"nullableProcessor"),To=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType},"nonoptionalProcessor"),Zo=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},"defaultProcessor"),No=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},"prefaultProcessor"),Mo=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},"catchProcessor"),xo=a((e,t,n,s)=>{const r=e._zod.def,i=r.in._zod.traits.has("$ZodTransform"),o=t.io==="input"?i?r.out:r.in:r.out;T(o,t,s);const c=t.seen.get(e);c.ref=o},"pipeProcessor"),qo=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType,n.readOnly=!0},"readonlyProcessor"),ln=a((e,t,n,s)=>{const r=e._zod.def;T(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType},"optionalProcessor"),Ro=l("ZodISODateTime",(e,t)=>{Ur.init(e,t),P.init(e,t)});function jo(e){return Gi(Ro,e)}a(jo,"datetime");const Fo=l("ZodISODate",(e,t)=>{Vr.init(e,t),P.init(e,t)});function Bo(e){return Ki(Fo,e)}a(Bo,"date");const Lo=l("ZodISOTime",(e,t)=>{Wr.init(e,t),P.init(e,t)});function Uo(e){return Yi(Lo,e)}a(Uo,"time");const Vo=l("ZodISODuration",(e,t)=>{Jr.init(e,t),P.init(e,t)});function Wo(e){return Hi(Vo,e)}a(Wo,"duration");const q=l("ZodError",a((e,t)=>{Ct.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a(n=>Ms(e,n),"value")},flatten:{value:a(n=>Ns(e,n),"value")},addIssue:{value:a(n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Ue,2)},"value")},addIssues:{value:a(n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Ue,2)},"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),{Parent:Error}),Jo=Ge(q),Go=Ke(q),Ko=Se(q),Yo=Ie(q),Ho=Rs(q),Xo=js(q),Qo=Fs(q),ea=Bs(q),ta=Ls(q),na=Us(q),sa=Vs(q),ra=Ws(q),hn=new WeakMap;function ae(e,t,n){const s=Object.getPrototypeOf(e);let r=hn.get(s);if(r||(r=new Set,hn.set(s,r)),!r.has(t)){r.add(t);for(const i in n){const o=n[i];Object.defineProperty(s,i,{configurable:!0,enumerable:!1,get(){const c=o.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}a(ae,"_installLazyMethods");const C=l("ZodType",(e,t)=>(D.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Pe(e,"input"),output:Pe(e,"output")}}),e.toJSONSchema=wo(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,s)=>Jo(e,n,s,{callee:e.parse}),e.safeParse=(n,s)=>Ko(e,n,s),e.parseAsync=async(n,s)=>Go(e,n,s,{callee:e.parseAsync}),e.safeParseAsync=async(n,s)=>Yo(e,n,s),e.spa=e.safeParseAsync,e.encode=(n,s)=>Ho(e,n,s),e.decode=(n,s)=>Xo(e,n,s),e.encodeAsync=async(n,s)=>Qo(e,n,s),e.decodeAsync=async(n,s)=>ea(e,n,s),e.safeEncode=(n,s)=>ta(e,n,s),e.safeDecode=(n,s)=>na(e,n,s),e.safeEncodeAsync=async(n,s)=>sa(e,n,s),e.safeDecodeAsync=async(n,s)=>ra(e,n,s),ae(e,"ZodType",{check(...n){const s=this.def;return this.clone(j(s,{checks:[...s.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,s){return F(this,n,s)},brand(){return this},register(n,s){return n.add(this,s),this},refine(n,s){return this.check(Ya(n,s))},superRefine(n,s){return this.check(Ha(n,s))},overwrite(n){return this.check(Q(n))},optional(){return _n(this)},exactOptional(){return xa(this)},nullable(){return kn(this)},nullish(){return _n(kn(this))},nonoptional(n){return La(this,n)},array(){return et(this)},or(n){return ce([this,n])},and(n){return Ca(this,n)},transform(n){return In(this,Na(n))},default(n){return ja(this,n)},prefault(n){return Ba(this,n)},catch(n){return Va(this,n)},pipe(n){return In(this,n)},readonly(){return Ga(this)},describe(n){const s=this.clone();return oe.add(s,{description:n}),s},meta(...n){if(n.length===0)return oe.get(this);const s=this.clone();return oe.add(s,n[0]),s},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return oe.get(e)?.description},configurable:!0}),e)),fn=l("_ZodString",(e,t)=>{Ye.init(e,t),C.init(e,t),e._zod.processJSONSchema=(s,r,i)=>_o(e,s,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,ae(e,"_ZodString",{regex(...s){return this.check(no(...s))},includes(...s){return this.check(io(...s))},startsWith(...s){return this.check(oo(...s))},endsWith(...s){return this.check(ao(...s))},min(...s){return this.check(Oe(...s))},max(...s){return this.check(on(...s))},length(...s){return this.check(an(...s))},nonempty(...s){return this.check(Oe(1,...s))},lowercase(s){return this.check(so(s))},uppercase(s){return this.check(ro(s))},trim(){return this.check(uo())},normalize(...s){return this.check(co(...s))},toLowerCase(){return this.check(lo())},toUpperCase(){return this.check(ho())},slugify(){return this.check(fo())}})}),ia=l("ZodString",(e,t)=>{Ye.init(e,t),fn.init(e,t),e.email=n=>e.check(Ei(oa,n)),e.url=n=>e.check(Ai(aa,n)),e.jwt=n=>e.check(Ji(ka,n)),e.emoji=n=>e.check(Ti(ca,n)),e.guid=n=>e.check(tn(pn,n)),e.uuid=n=>e.check(Oi(De,n)),e.uuidv4=n=>e.check(Pi(De,n)),e.uuidv6=n=>e.check(Di(De,n)),e.uuidv7=n=>e.check(Ci(De,n)),e.nanoid=n=>e.check(Zi(ua,n)),e.guid=n=>e.check(tn(pn,n)),e.cuid=n=>e.check(Ni(da,n)),e.cuid2=n=>e.check(Mi(la,n)),e.ulid=n=>e.check(xi(ha,n)),e.base64=n=>e.check(Ui(wa,n)),e.base64url=n=>e.check(Vi(ba,n)),e.xid=n=>e.check(qi(fa,n)),e.ksuid=n=>e.check(Ri(pa,n)),e.ipv4=n=>e.check(ji(ma,n)),e.ipv6=n=>e.check(Fi(ga,n)),e.cidrv4=n=>e.check(Bi(va,n)),e.cidrv6=n=>e.check(Li(ya,n)),e.e164=n=>e.check(Wi(_a,n)),e.datetime=n=>e.check(jo(n)),e.date=n=>e.check(Bo(n)),e.time=n=>e.check(Uo(n)),e.duration=n=>e.check(Wo(n))});function f(e){return $i(ia,e)}a(f,"string");const P=l("ZodStringFormat",(e,t)=>{O.init(e,t),fn.init(e,t)}),oa=l("ZodEmail",(e,t)=>{Nr.init(e,t),P.init(e,t)}),pn=l("ZodGUID",(e,t)=>{Tr.init(e,t),P.init(e,t)}),De=l("ZodUUID",(e,t)=>{Zr.init(e,t),P.init(e,t)}),aa=l("ZodURL",(e,t)=>{Mr.init(e,t),P.init(e,t)}),ca=l("ZodEmoji",(e,t)=>{xr.init(e,t),P.init(e,t)}),ua=l("ZodNanoID",(e,t)=>{qr.init(e,t),P.init(e,t)}),da=l("ZodCUID",(e,t)=>{Rr.init(e,t),P.init(e,t)}),la=l("ZodCUID2",(e,t)=>{jr.init(e,t),P.init(e,t)}),ha=l("ZodULID",(e,t)=>{Fr.init(e,t),P.init(e,t)}),fa=l("ZodXID",(e,t)=>{Br.init(e,t),P.init(e,t)}),pa=l("ZodKSUID",(e,t)=>{Lr.init(e,t),P.init(e,t)}),ma=l("ZodIPv4",(e,t)=>{Gr.init(e,t),P.init(e,t)}),ga=l("ZodIPv6",(e,t)=>{Kr.init(e,t),P.init(e,t)}),va=l("ZodCIDRv4",(e,t)=>{Yr.init(e,t),P.init(e,t)}),ya=l("ZodCIDRv6",(e,t)=>{Hr.init(e,t),P.init(e,t)}),wa=l("ZodBase64",(e,t)=>{Xr.init(e,t),P.init(e,t)}),ba=l("ZodBase64URL",(e,t)=>{ei.init(e,t),P.init(e,t)}),_a=l("ZodE164",(e,t)=>{ti.init(e,t),P.init(e,t)}),ka=l("ZodJWT",(e,t)=>{si.init(e,t),P.init(e,t)}),mn=l("ZodNumber",(e,t)=>{Ft.init(e,t),C.init(e,t),e._zod.processJSONSchema=(s,r,i)=>ko(e,s,r,i),ae(e,"ZodNumber",{gt(s,r){return this.check(sn(s,r))},gte(s,r){return this.check(Qe(s,r))},min(s,r){return this.check(Qe(s,r))},lt(s,r){return this.check(nn(s,r))},lte(s,r){return this.check(Xe(s,r))},max(s,r){return this.check(Xe(s,r))},int(s){return this.check(vn(s))},safe(s){return this.check(vn(s))},positive(s){return this.check(sn(0,s))},nonnegative(s){return this.check(Qe(0,s))},negative(s){return this.check(nn(0,s))},nonpositive(s){return this.check(Xe(0,s))},multipleOf(s,r){return this.check(rn(s,r))},step(s,r){return this.check(rn(s,r))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function gn(e){return Xi(mn,e)}a(gn,"number");const Sa=l("ZodNumberFormat",(e,t)=>{ri.init(e,t),mn.init(e,t)});function vn(e){return Qi(Sa,e)}a(vn,"int");const Ia=l("ZodUnknown",(e,t)=>{ii.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>{}});function ee(){return eo(Ia)}a(ee,"unknown");const za=l("ZodNever",(e,t)=>{oi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>So(e,n,s,r)});function $a(e){return to(za,e)}a($a,"never");const Ea=l("ZodArray",(e,t)=>{ai.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Oo(e,n,s,r),e.element=t.element,ae(e,"ZodArray",{min(n,s){return this.check(Oe(n,s))},nonempty(n){return this.check(Oe(1,n))},max(n,s){return this.check(on(n,s))},length(n,s){return this.check(an(n,s))},unwrap(){return this.element}})});function et(e,t){return po(Ea,e,t)}a(et,"array");const Oa=l("ZodObject",(e,t)=>{ui.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Po(e,n,s,r),$(e,"shape",()=>t.shape),ae(e,"ZodObject",{keyof(){return Aa(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:ee()})},loose(){return this.clone({...this._zod.def,catchall:ee()})},strict(){return this.clone({...this._zod.def,catchall:$a()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Ps(this,n)},safeExtend(n){return Ds(this,n)},merge(n){return Cs(this,n)},pick(n){return Es(this,n)},omit(n){return Os(this,n)},partial(...n){return As(bn,this,n[0])},required(...n){return Ts(Sn,this,n[0])}})});function g(e,t){const n={type:"object",shape:e??{},...y(t)};return new Oa(n)}a(g,"object");const yn=l("ZodUnion",(e,t)=>{Wt.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Do(e,n,s,r),e.options=t.options});function ce(e,t){return new yn({type:"union",options:e,...y(t)})}a(ce,"union");const Pa=l("ZodDiscriminatedUnion",(e,t)=>{yn.init(e,t),di.init(e,t)});function wn(e,t,n){return new Pa({type:"union",options:t,discriminator:e,...y(n)})}a(wn,"discriminatedUnion");const Da=l("ZodIntersection",(e,t)=>{li.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Co(e,n,s,r)});function Ca(e,t){return new Da({type:"intersection",left:e,right:t})}a(Ca,"intersection");const tt=l("ZodEnum",(e,t)=>{hi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(s,r,i)=>Io(e,s,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(s,r)=>{const i={};for(const o of s)if(n.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new tt({...t,checks:[],...y(r),entries:i})},e.exclude=(s,r)=>{const i={...t.entries};for(const o of s)if(n.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new tt({...t,checks:[],...y(r),entries:i})}});function Aa(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new tt({type:"enum",entries:n,...y(t)})}a(Aa,"_enum");const Ta=l("ZodLiteral",(e,t)=>{fi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>zo(e,n,s,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function w(e,t){return new Ta({type:"literal",values:Array.isArray(e)?e:[e],...y(t)})}a(w,"literal");const Za=l("ZodTransform",(e,t)=>{pi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Eo(e,n,s,r),e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new St(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(ie(i,n.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),n.issues.push(ie(o))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=r,n.fallback=!0,n)}});function Na(e){return new Za({type:"transform",transform:e})}a(Na,"transform");const bn=l("ZodOptional",(e,t)=>{Kt.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>ln(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function _n(e){return new bn({type:"optional",innerType:e})}a(_n,"optional");const Ma=l("ZodExactOptional",(e,t)=>{mi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>ln(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function xa(e){return new Ma({type:"optional",innerType:e})}a(xa,"exactOptional");const qa=l("ZodNullable",(e,t)=>{gi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Ao(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function kn(e){return new qa({type:"nullable",innerType:e})}a(kn,"nullable");const Ra=l("ZodDefault",(e,t)=>{vi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Zo(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ja(e,t){return new Ra({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Ot(t)}})}a(ja,"_default");const Fa=l("ZodPrefault",(e,t)=>{yi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>No(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function Ba(e,t){return new Fa({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Ot(t)}})}a(Ba,"prefault");const Sn=l("ZodNonOptional",(e,t)=>{wi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>To(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function La(e,t){return new Sn({type:"nonoptional",innerType:e,...y(t)})}a(La,"nonoptional");const Ua=l("ZodCatch",(e,t)=>{bi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Mo(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Va(e,t){return new Ua({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}a(Va,"_catch");const Wa=l("ZodPipe",(e,t)=>{_i.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>xo(e,n,s,r),e.in=t.in,e.out=t.out});function In(e,t){return new Wa({type:"pipe",in:e,out:t})}a(In,"pipe");const Ja=l("ZodReadonly",(e,t)=>{ki.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>qo(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function Ga(e){return new Ja({type:"readonly",innerType:e})}a(Ga,"readonly");const zn=l("ZodCustom",(e,t)=>{Si.init(e,t),C.init(e,t),e._zod.processJSONSchema=(n,s,r)=>$o(e,n,s,r)});function Ka(e,t){return mo(zn,e??(()=>!0),t)}a(Ka,"custom");function Ya(e,t={}){return go(zn,e,t)}a(Ya,"refine");function Ha(e,t){return vo(e,t)}a(Ha,"superRefine");const Ce=f(),Xa=wn("code",[g({code:w("bad-request"),message:f(),details:g({issues:et(Ka())})}),g({code:w("cancelled"),message:f(),details:g({})}),g({code:w("session-not-found"),message:f(),details:g({sessionId:f()})}),g({code:w("model-unavailable"),message:f(),details:g({provider:f(),model:f()})}),g({code:w("session-conflict"),message:f(),details:g({sessionId:f(),requestedCwd:f(),existingCwd:f().optional()})}),g({code:w("invalid-time-zone"),message:f(),details:g({value:f()})}),g({code:w("workspace-attach-failed"),message:f(),details:g({sessionId:f(),workspaceId:f()})}),g({code:w("workspace-not-found"),message:f(),details:g({workspaceId:f()})}),g({code:w("workspace-invalid-path"),message:f(),details:g({path:f()})}),g({code:w("workspace-name-conflict"),message:f(),details:g({name:f()})}),g({code:w("workspace-move-invalid"),message:f(),details:g({workspaceId:f(),sessionId:f(),beforeSessionId:f().optional()})}),g({code:w("directory-unreadable"),message:f(),details:g({path:f()})}),g({code:w("directory-exists"),message:f(),details:g({path:f()})}),g({code:w("directory-create-failed"),message:f(),details:g({path:f()})}),g({code:w("directory-picker-unavailable"),message:f(),details:g({capability:f()})}),g({code:w("agent-preset-read-only"),message:f(),details:g({agentPreset:f(),reason:f()})}),g({code:w("agent-preset-locked"),message:f(),details:g({sessionId:f(),agentPreset:f()})}),g({code:w("agent-preset-conflict"),message:f(),details:g({sessionId:f(),requestedPreset:f(),existingPreset:f().optional()})}),g({code:w("agent-preset-not-found"),message:f(),details:g({agentPreset:f(),available:et(f())})}),g({code:w("agent-preset-invalid"),message:f(),details:g({agentPreset:f(),reason:f()})}),g({code:w("agent-busy"),message:f(),details:g({reason:f()})}),g({code:w("attachment-error"),message:f(),details:g({reason:f()})}),g({code:w("queue-item-not-found"),message:f(),details:g({itemId:f()})}),g({code:w("steer-unavailable"),message:f(),details:g({itemId:f()})}),g({code:w("command-error"),message:f(),details:g({})}),g({code:w("unknown-command"),message:f(),details:g({})}),g({code:w("settings-rejected"),message:f(),details:g({ns:f()})}),g({code:w("settings-not-exposed"),message:f(),details:g({ns:f()})}),g({code:w("settings-conflict"),message:f(),details:g({ns:f(),expected:gn(),actual:gn()})}),g({code:w("credential-rejected"),message:f(),details:g({ref:f()})}),g({code:w("model-discovery-failed"),message:f(),details:g({settingsNs:f(),baseURL:f().optional()})}),g({code:w("title-invalid"),message:f(),details:g({sessionId:f()})}),g({code:w("fork-unavailable"),message:f(),details:g({sessionId:f()})}),g({code:w("subagent-parent-unavailable"),message:f(),details:g({parentSessionId:f()})}),g({code:w("subagent-not-found"),message:f(),details:g({parentSessionId:f(),childSessionId:f()})}),g({code:w("subagent-catalog-diagnostic"),message:f(),details:g({parentSessionId:f(),childSessionId:f(),reason:ce([w("corrupt"),w("unsupported"),w("unavailable")])})}),g({code:w("subagent-not-resumable"),message:f(),details:g({childSessionId:f()})}),g({code:w("subagent-unauthorized"),message:f(),details:g({childSessionId:f()})}),g({code:w("subagent-delivery-unavailable"),message:f(),details:g({childSessionId:f()})}),g({code:w("internal"),message:f(),details:g({})})]);function $n(e){return ce([g({ok:w(!0),value:e}),g({ok:w(!1),error:Xa})])}a($n,"rpcResultSchema"),wn("type",[g({type:w("client-request"),rpcId:Ce,method:f(),payload:ee()}),g({type:w("server-response"),rpcId:Ce,result:$n(ee().optional())}),g({type:w("server-request"),rpcId:Ce,method:f(),payload:ee()}),g({type:w("client-response"),rpcId:Ce,result:$n(ee().optional())})]),ce([g({accepted:w(!0)}),g({accepted:w(!1),reason:ce([w("not-pending"),w("bad-response")])})]);const En=a(e=>{let t;const n=new Set,s=a((d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const m=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(v=>v(t,m))}},"setState"),r=a(()=>t,"getState"),c={setState:s,getState:r,subscribe:a(d=>(n.add(d),()=>n.delete(d)),"subscribe"),destroy:a(()=>{n.clear()},"destroy")};return t=e(s,r,c),c},"createStoreImpl"),Qa=a(e=>e?En(e):En,"createStore"),ec=a(e=>(t,n,s)=>{const r=s.subscribe;return s.subscribe=(i,o,c)=>{let d=i;if(o){const u=c?.equalityFn||Object.is;let h=i(s.getState());d=a(m=>{const v=i(m);if(!u(h,v)){const b=h;o(h=v,b)}},"listener"),c?.fireImmediately&&o(h,h)}return r(d)},e(t,n,s)},"subscribeWithSelectorImpl");function tc(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[s,r]of e)if(!Object.is(r,t.get(s)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const s of e)if(!t.has(s))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(t,n[s])||!Object.is(e[n[s]],t[n[s]]))return!1;return!0}a(tc,"shallow$1");var On=Symbol.for("immer-nothing"),Pn=Symbol.for("immer-draftable"),x=Symbol.for("immer-state");function R(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}a(R,"die");var ue=Object.getPrototypeOf;function te(e){return!!e&&!!e[x]}a(te,"isDraft");function V(e){return e?Cn(e)||Array.isArray(e)||!!e[Pn]||!!e.constructor?.[Pn]||de(e)||Ze(e):!1}a(V,"isDraftable");var nc=Object.prototype.constructor.toString(),Dn=new WeakMap;function Cn(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let s=Dn.get(n);return s===void 0&&(s=Function.toString.call(n),Dn.set(n,s)),s===nc}a(Cn,"isPlainObject");function Ae(e,t,n=!0){Te(e)===0?(n?Reflect.ownKeys(e):Object.keys(e)).forEach(s=>{t(s,e[s],e)}):e.forEach((s,r)=>t(r,s,e))}a(Ae,"each");function Te(e){const t=e[x];return t?t.type_:Array.isArray(e)?1:de(e)?2:Ze(e)?3:0}a(Te,"getArchtype");function nt(e,t){return Te(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}a(nt,"has");function An(e,t,n){const s=Te(e);s===2?e.set(t,n):s===3?e.add(n):e[t]=n}a(An,"set");function sc(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}a(sc,"is");function de(e){return e instanceof Map}a(de,"isMap");function Ze(e){return e instanceof Set}a(Ze,"isSet");function W(e){return e.copy_||e.base_}a(W,"latest");function st(e,t){if(de(e))return new Map(e);if(Ze(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=Cn(e);if(t===!0||t==="class_only"&&!n){const s=Object.getOwnPropertyDescriptors(e);delete s[x];let r=Reflect.ownKeys(s);for(let i=0;i<r.length;i++){const o=r[i],c=s[o];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(s[o]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[o]})}return Object.create(ue(e),s)}else{const s=ue(e);if(s!==null&&n)return{...e};const r=Object.create(s);return Object.assign(r,e)}}a(st,"shallowCopy");function rt(e,t=!1){return Me(e)||te(e)||!V(e)||(Te(e)>1&&Object.defineProperties(e,{set:Ne,add:Ne,clear:Ne,delete:Ne}),Object.freeze(e),t&&Object.values(e).forEach(n=>rt(n,!0))),e}a(rt,"freeze");function rc(){R(2)}a(rc,"dontMutateFrozenCollections");var Ne={value:rc};function Me(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}a(Me,"isFrozen");var ic={};function J(e){const t=ic[e];return t||R(0,e),t}a(J,"getPlugin");var le;function Tn(){return le}a(Tn,"getCurrentScope");function oc(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}a(oc,"createScope$1");function Zn(e,t){t&&(J("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}a(Zn,"usePatchesInScope");function it(e){ot(e),e.drafts_.forEach(ac),e.drafts_=null}a(it,"revokeScope");function ot(e){e===le&&(le=e.parent_)}a(ot,"leaveScope");function Nn(e){return le=oc(le,e)}a(Nn,"enterScope");function ac(e){const t=e[x];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}a(ac,"revokeDraft");function Mn(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[x].modified_&&(it(t),R(4)),V(e)&&(e=xe(t,e),t.parent_||qe(t,e)),t.patches_&&J("Patches").generateReplacementPatches_(n[x].base_,e,t.patches_,t.inversePatches_)):e=xe(t,n,[]),it(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==On?e:void 0}a(Mn,"processResult");function xe(e,t,n){if(Me(t))return t;const s=e.immer_.shouldUseStrictIteration(),r=t[x];if(!r)return Ae(t,(i,o)=>xn(e,r,t,i,o,n),s),t;if(r.scope_!==e)return t;if(!r.modified_)return qe(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const i=r.copy_;let o=i,c=!1;r.type_===3&&(o=new Set(i),i.clear(),c=!0),Ae(o,(d,u)=>xn(e,r,i,d,u,n,c),s),qe(e,i,!1),n&&e.patches_&&J("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}a(xe,"finalize");function xn(e,t,n,s,r,i,o){if(r==null||typeof r!="object"&&!o)return;const c=Me(r);if(!(c&&!o)){if(te(r)){const d=xe(e,r,i&&t&&t.type_!==3&&!nt(t.assigned_,s)?i.concat(s):void 0);if(An(n,s,d),te(d))e.canAutoFreeze_=!1;else return}else o&&n.add(r);if(V(r)&&!c){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[s]===r&&c)return;xe(e,r),(!t||!t.scope_.parent_)&&typeof s!="symbol"&&(de(n)?n.has(s):Object.prototype.propertyIsEnumerable.call(n,s))&&qe(e,r)}}}a(xn,"finalizeProperty");function qe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&rt(t,n)}a(qe,"maybeFreeze");function cc(e,t){const n=Array.isArray(e),s={type_:n?1:0,scope_:t?t.scope_:Tn(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let r=s,i=at;n&&(r=[s],i=he);const{revoke:o,proxy:c}=Proxy.revocable(r,i);return s.draft_=c,s.revoke_=o,c}a(cc,"createProxyProxy");var at={get(e,t){if(t===x)return e;const n=W(e);if(!nt(n,t))return uc(e,n,t);const s=n[t];return e.finalized_||!V(s)?s:s===ct(e.base_,t)?(dt(e),e.copy_[t]=lt(s,e)):s},has(e,t){return t in W(e)},ownKeys(e){return Reflect.ownKeys(W(e))},set(e,t,n){const s=qn(W(e),t);if(s?.set)return s.set.call(e.draft_,n),!0;if(!e.modified_){const r=ct(W(e),t),i=r?.[x];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(sc(n,r)&&(n!==void 0||nt(e.base_,t)))return!0;dt(e),ut(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return ct(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,dt(e),ut(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=W(e),s=Reflect.getOwnPropertyDescriptor(n,t);return s&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:s.enumerable,value:n[t]}},defineProperty(){R(11)},getPrototypeOf(e){return ue(e.base_)},setPrototypeOf(){R(12)}},he={};Ae(at,(e,t)=>{he[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),he.deleteProperty=function(e,t){return he.set.call(this,e,t,void 0)},he.set=function(e,t,n){return at.set.call(this,e[0],t,n,e[0])};function ct(e,t){const n=e[x];return(n?W(n):e)[t]}a(ct,"peek");function uc(e,t,n){const s=qn(t,n);return s?"value"in s?s.value:s.get?.call(e.draft_):void 0}a(uc,"readPropFromProto");function qn(e,t){if(!(t in e))return;let n=ue(e);for(;n;){const s=Object.getOwnPropertyDescriptor(n,t);if(s)return s;n=ue(n)}}a(qn,"getDescriptorFromProto");function ut(e){e.modified_||(e.modified_=!0,e.parent_&&ut(e.parent_))}a(ut,"markChanged");function dt(e){e.copy_||(e.copy_=st(e.base_,e.scope_.immer_.useStrictShallowCopy_))}a(dt,"prepareCopy");var dc=class{static{a(this,"Immer2")}constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,n,s)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const o=this;return a(function(d=i,...u){return o.produce(d,h=>n.call(this,h,...u))},"curriedProduce")}typeof n!="function"&&R(6),s!==void 0&&typeof s!="function"&&R(7);let r;if(V(t)){const i=Nn(this),o=lt(t,void 0);let c=!0;try{r=n(o),c=!1}finally{c?it(i):ot(i)}return Zn(i,s),Mn(r,i)}else if(!t||typeof t!="object"){if(r=n(t),r===void 0&&(r=t),r===On&&(r=void 0),this.autoFreeze_&&rt(r,!0),s){const i=[],o=[];J("Patches").generateReplacementPatches_(t,r,i,o),s(i,o)}return r}else R(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(i,...o)=>this.produceWithPatches(i,c=>t(c,...o));let s,r;return[this.produce(t,n,(i,o)=>{s=i,r=o}),s,r]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof e?.useStrictIteration=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){V(e)||R(8),te(e)&&(e=lc(e));const t=Nn(this),n=lt(e,void 0);return n[x].isManual_=!0,ot(t),n}finishDraft(e,t){const n=e&&e[x];(!n||!n.isManual_)&&R(9);const{scope_:s}=n;return Zn(s,t),Mn(void 0,s)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(r.path.length===0&&r.op==="replace"){e=r.value;break}}n>-1&&(t=t.slice(n+1));const s=J("Patches").applyPatches_;return te(e)?s(e,t):this.produce(e,r=>s(r,t))}};function lt(e,t){const n=de(e)?J("MapSet").proxyMap_(e,t):Ze(e)?J("MapSet").proxySet_(e,t):cc(e,t);return(t?t.scope_:Tn()).drafts_.push(n),n}a(lt,"createProxy");function lc(e){return te(e)||R(10,e),Rn(e)}a(lc,"current");function Rn(e){if(!V(e)||Me(e))return e;const t=e[x];let n,s=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=st(e,t.scope_.immer_.useStrictShallowCopy_),s=t.scope_.immer_.shouldUseStrictIteration()}else n=st(e,!0);return Ae(n,(r,i)=>{An(n,r,Rn(i))},s),t&&(t.finalized_=!1),n}a(Rn,"currentImpl");var hc=new dc().produce;function fc(e,t){return tc(e,t)}a(fc,"shallowEqual");function pc(e){const t=typeof requestAnimationFrame=="function"?s=>{requestAnimationFrame(()=>{s()})}:s=>{queueMicrotask(s)};let n=!1;return()=>{n||(n=!0,t(()=>{n=!1,e()}))}}a(pc,"rafBatch");function fe(e,t){const n=ec(()=>e),s=Qa()(n);t?.persist&&mc(s,t.persist.name);let r=a(i=>s.subscribe(i),"subscribe");if(t?.flush==="raf"){const i=new Set,o=pc(()=>{for(const c of[...i])c()});s.subscribe(o),r=a(c=>(i.add(c),()=>{i.delete(c)}),"subscribe")}return{getSnapshot:a(()=>s.getState(),"getSnapshot"),subscribe:a(i=>r(i),"subscribe"),update:a(i=>{s.setState(hc(s.getState(),o=>{i(o)}),!0)},"update"),set:a(i=>{s.setState(i,!0)},"set")}}a(fe,"createSnapshotStore");function mc(e,t){if(!(typeof localStorage>"u")){try{const n=localStorage.getItem(t);n!==null&&e.setState(JSON.parse(n),!0)}catch(n){console.error(`snapshot store '${t}' rehydration failed:`,n)}e.subscribe(n=>{try{localStorage.setItem(t,JSON.stringify(n))}catch(s){console.error(`snapshot store '${t}' persistence failed:`,s)}})}}a(mc,"attachPersistence");function cu(e){return e}a(cu,"devFreeze");function gc(e){return{spec:e,create(t){const n=e.persist===void 0?void 0:t===void 0?e.persist:`${e.persist}.${t}`,s=fe(e.init(),n!==void 0?{persist:{name:n}}:void 0),r={};for(const i of Object.keys(e.actions)){const o=e.actions[i];r[i]=(...c)=>{s.update(d=>{o(d,...c)})}}return{actions:r,getSnapshot:a(()=>s.getSnapshot(),"getSnapshot"),subscribe:a(i=>s.subscribe(i),"subscribe"),store:s,clearPersisted:a(()=>{if(!(n===void 0||typeof localStorage>"u"))try{localStorage.removeItem(n)}catch{}},"clearPersisted")}}}}a(gc,"defineStore");const jn=Symbol("dsh.client.scope");function vc(){}a(vc,"agentScope");function Fn(e,t){const n=e.plugin(vc);return{fiber:n,ctx:n.ctx.extend({[jn]:t,[Be.Context.filter](s){const r=Re(s);return r===void 0||r===t}})}}a(Fn,"createScope");function Re(e){return e[jn]}a(Re,"scopeOf");function yc(e,t,n){const s=new Map;for(const o of t)s.set(n(o),o);const r=e.map(o=>s.get(n(o))).filter(o=>o!==void 0),i=new Set(r.map(n));for(let o=0;o<t.length;o++){const c=t[o];if(c===void 0||i.has(n(c)))continue;let d=r.length;for(let u=o+1;u<t.length;u++){const h=t[u];if(h===void 0)continue;const m=r.findIndex(v=>n(v)===n(h));if(m!==-1){d=m;break}}r.splice(d,0,c),i.add(n(c))}return r}a(yc,"mergeOrderedBaseline");function wc(e,t,n){const s=new Map;for(const u of e)s.set(u.sessionId,u);const r=new Map,i=[];for(const u of e)if(u.parentSessionId!==void 0&&s.has(u.parentSessionId)){const h=r.get(u.parentSessionId)??[];h.push(u),r.set(u.parentSessionId,h)}else i.push(u);const o=[],c=new Set,d=a((u,h)=>{if(c.has(u.sessionId)){console.warn(`[web-runtime] lineage cycle at ${u.sessionId}; emitting as root`);return}c.add(u.sessionId);const m=t?.get(u.sessionId);o.push({...u,...m===void 0?{}:{pendingInteraction:m},completed:n?.has(u.sessionId)??!1,depth:h});const v=r.get(u.sessionId);if(v!==void 0)for(const b of v)d(b,h+1)},"walk");for(const u of i)d(u,0);for(const u of e)c.has(u.sessionId)||d(u,0);return o}a(wc,"flattenLineage");var ne=class{static{a(this,"Notifier")}rebuild;listeners=new Set;dirty=!1;notifyPending=!1;scheduled="none";scheduleGeneration=0;constructor(e){this.rebuild=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}markDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled!=="microtask"&&this.schedule("microtask")}markFrameDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled==="none"&&this.schedule(typeof globalThis.requestAnimationFrame=="function"?"frame":"microtask")}notifyNow(){this.dirty=!0,this.notifyPending=!0,this.invalidateSchedule(),this.flush()}ensureFresh(){this.dirty&&(this.dirty=!1,this.rebuild())}schedule(e){const t=++this.scheduleGeneration;this.scheduled=e;const n=a(()=>{t===this.scheduleGeneration&&(this.scheduled="none",this.flush())},"publish");e==="frame"?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled="none"}flush(){if(this.notifyPending&&this.listeners.size!==0){this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild());for(const e of this.listeners)e()}}},Bn=class{static{a(this,"ProjectionValueStore")}rows=new Map;channels=new Map;valuesCache;anyNotifier=new ne(()=>{});faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){const s=this.rows.get(e);s!==void 0&&n<=s.seq||(this.rows.set(e,{value:t,seq:n}),this.changed(e))}seed(e){const t=e.values;for(const n of Object.keys(t))this.apply(n,t[n],e.asOfSeq);for(const[n,s]of this.rows)Object.hasOwn(t,n)||s.seq>e.asOfSeq||(this.rows.delete(n),this.changed(n))}truncate(e){for(const[t,n]of this.rows)n.seq<=e||(this.rows.delete(t),this.changed(t))}changed(e){this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){const n=new ne(()=>{});t={notifier:n,face:{getSnapshot:a(()=>this.rows.get(e)?.value,"getSnapshot"),subscribe:a(s=>n.subscribe(s),"subscribe")}},this.channels.set(e,t)}return t}};function ht(e,t){return`${e.length}:${e}${t}`}a(ht,"conversationContextKey");var Ln=class{static{a(this,"MutableLocationDataStore")}entries=new Map;get(e){return this.entries.get(e)?.value}remove(e,t){return this.entries.get(t)?.owner!==e?!1:(this.entries.delete(t),!0)}set(e,t,n){const s=this.entries.get(t);if(s!==void 0&&s.owner!==e)throw new Error(`conversation Location data "${t}" is already owned by ${s.owner}`);return s?.value===n?!1:(this.entries.set(t,{owner:e,value:n}),!0)}replace(e){let t=this.entries.size!==e.size;if(!t)for(const[n,s]of e){const r=this.entries.get(n);if(r?.owner!==s.owner||r.value!==s.value){t=!0;break}}return t&&(this.entries=new Map(e)),t}};const ft={kind:"session"},bc={kind:"unresolved"};function pt(e){const t=e.data;if(t.turn===null)return{session:!0};const n=Number.isSafeInteger(t.turn)&&t.turn>=0?t.turn:void 0,s=Number.isSafeInteger(t.step)&&t.step>=0?t.step:void 0;return{...n===void 0?{}:{turn:n},...s===void 0?{}:{step:s}}}a(pt,"payloadCoordinates");function _c(e,t){return e.length===t.length&&e.every((n,s)=>n===t[s])}a(_c,"sameReferences");function Un(e,t){return e!==void 0&&e.start===t.start&&e.end===t.end&&e.status===t.status&&e.data===t.data}a(Un,"sameStep");function Vn(e,t){return e!==void 0&&e.start===t.start&&e.end===t.end&&e.status===t.status&&e.data===t.data&&_c(e.steps,t.steps)}a(Vn,"sameTurn");function Wn(e,t){return e===void 0||t===void 0||e.kind!==t.kind?e===t:e.kind==="session"||e.kind==="unresolved"?!0:t.kind==="session"||t.kind==="unresolved"?!1:e.kind==="turn"||t.kind==="turn"?e.kind==="turn"&&t.kind==="turn"&&e.turn===t.turn:e.turn===t.turn&&e.step===t.step}a(Wn,"sameLocation");var Jn=class{static{a(this,"ConversationLocationIndex")}coordinates=new Map;locations=new Map;seqsByTurn=new Map;timeline={turnOrder:[],turns:new Map};turnDataStores=new Map;stepDataStores=new Map;currentTurn;currentStep;snapshot(){return this.timeline}replaceData(e){const t=new Map,n=new Map;for(const{owner:r,data:i}of e){const o=i.kind==="turn"?t.get(i.turn)??new Map:n.get(je(i.turn,mt(i)))??new Map,c=o.get(i.key);if(c!==void 0&&c.owner!==r)throw new Error(`conversation Location data "${i.key}" is already owned by ${c.owner}`);o.set(i.key,{owner:r,value:i.value}),i.kind==="turn"?t.set(i.turn,o):n.set(je(i.turn,mt(i)),o)}let s=!1;for(const r of new Set([...this.turnDataStores.keys(),...t.keys()]))s=this.mutableTurnData(r).replace(t.get(r)??new Map)||s;for(const r of new Set([...this.stepDataStores.keys(),...n.keys()]))s=this.mutableStepData(r).replace(n.get(r)??new Map)||s;return s}applyData(e){let t=!1;for(const n of e){const s=n.previous;s!==null&&(t=this.storeFor(s).remove(n.owner,s.key)||t)}for(const n of e){const s=n.next;s!==null&&(t=this.storeFor(s).set(n.owner,s.key,s.value)||t)}return t}locationOf(e){return this.locations.get(e.seq)??ft}rebuild(e){const t=this.locations,n=new Map,s=new Map;let r,i;const o=a((p,_)=>{let E=n.get(p);return E===void 0?(E={turn:p,firstSeq:_,steps:new Map},n.set(p,E)):E.firstSeq=Math.min(E.firstSeq,_),E},"turnDraft"),c=a((p,_,E)=>{const A=o(p,E);let S=A.steps.get(_);return S===void 0?(S={turn:p,step:_,firstSeq:E},A.steps.set(_,S)):S.firstSeq=Math.min(S.firstSeq,E),S},"stepDraft");for(const{event:p}of e){const _=pt(p);p.type==="turn/start"&&(r=p.data.turn,i=void 0),p.type==="step/start"&&(r=p.data.turn,i=p.data.step),_.session!==!0&&_.turn!==void 0&&(r!==_.turn&&(i=void 0),r=_.turn,_.step!==void 0&&(i=_.step));const E=_.session===!0?void 0:_.turn??r,A=_.session===!0||p.type==="turn/start"||p.type==="turn/end"?void 0:_.step??(E===r?i:void 0);s.set(p.seq,{...E===void 0?{}:{turn:E},...E===void 0||A===void 0?{}:{step:A}}),E!==void 0&&o(E,p.seq),E!==void 0&&A!==void 0&&c(E,A,p.seq),p.type==="turn/start"?o(p.data.turn,p.seq).start=p:p.type==="turn/end"?o(p.data.turn,p.seq).end=p:p.type==="step/start"?c(p.data.turn,p.data.step,p.seq).start=p:p.type==="step/end"&&(c(p.data.turn,p.data.step,p.seq).end=p),p.type==="step/end"&&r===p.data.turn&&i===p.data.step&&(i=void 0),p.type==="turn/end"&&r===p.data.turn&&(r=void 0,i=void 0)}const d=this.timeline.turns,u=new Map,h=[...n.values()].sort((p,_)=>p.firstSeq-_.firstSeq);for(const p of h){const _=d.get(p.turn),E=new Map(_?.steps.map(I=>[I.step,I])??[]),A=[...p.steps.values()].sort((I,K)=>I.firstSeq-K.firstSeq).map(I=>{const K={turn:I.turn,step:I.step,start:I.start,end:I.end,status:I.end!==void 0?"closed":I.start===void 0?"unknown":"open",data:this.stepData(I.turn,I.step)},ve=E.get(I.step);return Un(ve,K)?ve:K}),S={turn:p.turn,start:p.start,end:p.end,status:p.end!==void 0?"closed":p.start===void 0?"unknown":"open",steps:A,data:this.turnData(p.turn)};u.set(p.turn,Vn(_,S)?_:S)}const m=h.map(p=>p.turn),v=this.timeline.turnOrder.length===m.length&&this.timeline.turnOrder.every((p,_)=>p===m[_])?this.timeline.turnOrder:m;let b=d.size===u.size;if(b){for(const[p,_]of u)if(d.get(p)!==_){b=!1;break}}this.timeline=b&&v===this.timeline.turnOrder?this.timeline:{turnOrder:v,turns:u},this.coordinates=s,this.locations=new Map,this.seqsByTurn=new Map;for(const{event:p}of e){const _=this.coordinates.get(p.seq);_?.turn!==void 0&&this.indexTurnSeq(_.turn,p.seq),this.locations.set(p.seq,this.resolve(p.seq))}this.currentTurn=r,this.currentStep=i;const z=new Set;for(const{event:p}of e)Wn(t.get(p.seq),this.locations.get(p.seq))||z.add(p.seq);return z}appendBoundary(e){if(e.type!=="turn/start"&&e.type!=="turn/end"&&e.type!=="step/start"&&e.type!=="step/end")throw new Error(`conversation Location boundary expected, received ${e.type}`);const t=pt(e);e.type==="turn/start"?(this.currentTurn=e.data.turn,this.currentStep=void 0):e.type==="step/start"&&(this.currentTurn=e.data.turn,this.currentStep=e.data.step),t.turn!==void 0&&(this.currentTurn!==t.turn&&(this.currentStep=void 0),this.currentTurn=t.turn,t.step!==void 0&&(this.currentStep=t.step));const n=t.turn??this.currentTurn;if(n===void 0)throw new Error(`conversation boundary ${e.type} has no turn`);const s=e.type==="turn/start"||e.type==="turn/end"?void 0:t.step??(n===this.currentTurn?this.currentStep:void 0);this.coordinates.set(e.seq,{turn:n,...s===void 0?{}:{step:s}}),this.indexTurnSeq(n,e.seq);const r=this.timeline.turns.get(n);let i=r?.steps??[];if(e.type==="step/start"||e.type==="step/end"){const m=e.data.step,v=i.find(_=>_.step===m),b={turn:n,step:m,start:e.type==="step/start"?e:v?.start,end:e.type==="step/end"?e:v?.end,status:e.type==="step/end"||v?.end!==void 0?"closed":"open",data:this.stepData(n,m)},z=Un(v,b)?v:b,p=i.findIndex(_=>_.step===m);i=p<0?[...i,z]:i.map((_,E)=>E===p?z:_)}const o={turn:n,start:e.type==="turn/start"?e:r?.start,end:e.type==="turn/end"?e:r?.end,status:e.type==="turn/end"||r?.end!==void 0?"closed":e.type==="turn/start"||r?.start!==void 0?"open":"unknown",steps:i,data:this.turnData(n)},c=Vn(r,o)?r:o,d=new Map(this.timeline.turns);d.set(n,c);const u=r===void 0?[...this.timeline.turnOrder,n]:this.timeline.turnOrder;this.timeline={turnOrder:u,turns:d};const h=new Set;for(const m of this.seqsByTurn.get(n)??[]){const v=this.locations.get(m),b=this.resolve(m);this.locations.set(m,b),Wn(v,b)||h.add(m)}return e.type==="step/end"&&this.currentTurn===e.data.turn&&this.currentStep===e.data.step&&(this.currentStep=void 0),e.type==="turn/end"&&this.currentTurn===e.data.turn&&(this.currentTurn=void 0,this.currentStep=void 0),h}appendNonBoundary(e){const t=pt(e);if(t.session===!0){this.coordinates.set(e.seq,{}),this.locations.set(e.seq,ft);return}t.turn!==void 0&&(this.currentTurn!==t.turn&&(this.currentStep=void 0),this.currentTurn=t.turn,t.step!==void 0&&(this.currentStep=t.step));const n=t.turn??this.currentTurn,s=t.step??(n===this.currentTurn?this.currentStep:void 0);this.coordinates.set(e.seq,{...n===void 0?{}:{turn:n},...n===void 0||s===void 0?{}:{step:s}}),n!==void 0&&this.indexTurnSeq(n,e.seq),this.locations.set(e.seq,this.resolve(e.seq))}indexTurnSeq(e,t){const n=this.seqsByTurn.get(e)??new Set;n.add(t),this.seqsByTurn.set(e,n)}turnData(e){return this.mutableTurnData(e)}stepData(e,t){return this.mutableStepData(je(e,t))}mutableTurnData(e){const t=this.turnDataStores.get(e)??new Ln;return this.turnDataStores.set(e,t),t}mutableStepData(e){const t=this.stepDataStores.get(e)??new Ln;return this.stepDataStores.set(e,t),t}storeFor(e){return e.kind==="turn"?this.mutableTurnData(e.turn):this.mutableStepData(je(e.turn,mt(e)))}resolve(e){const t=this.coordinates.get(e);if(t?.turn===void 0)return ft;const n=this.timeline.turns.get(t.turn);if(n===void 0)return bc;if(t.step===void 0)return{kind:"turn",turn:n};const s=n.steps.find(r=>r.step===t.step);return s===void 0?{kind:"turn",turn:n}:{kind:"step",turn:n,step:s}}};function je(e,t){return`${e}:${t}`}a(je,"stepDataKey");function mt(e){if(e.kind==="step"&&e.step!==void 0)return e.step;throw new Error(`conversation Step data "${e.key}" requires a step`)}a(mt,"requireStep");const Gn={none:0,"animation-frame":1,immediate:2},Kn=["step","turn"];function Yn(){return{step:null,turn:null}}a(Yn,"emptyLocationData");function Fe(e,t){return Gn[e]>=Gn[t]?e:t}a(Fe,"maximumPublication");function pe(e){return e.startSeq}a(pe,"startSeq");function Hn(e,t){let n=0,s=e.length;for(;n<s;){const r=n+Math.floor((s-n)/2),i=e[r];i!==void 0&&i.startSeq<t?n=r+1:s=r}return n}a(Hn,"insertionIndex");function me(e){return{key:e.key,kind:e.kind,id:e.id,matches:e.matches,start:e.start,state:e.state,current:e.current}}a(me,"contextSnapshot");function kc(e,t,n){const s=[];let r=0,i=0;for(;r<t.length||i<n.length;){const o=t[r],c=n[i];if(o!==void 0&&c!==void 0&&o.event.seq===c.event.seq)throw new Error(`conversation Context ${e} received duplicate Match ${o.event.seq}`);c===void 0||o!==void 0&&o.event.seq<c.event.seq?(s.push(o),r++):(s.push(c),i++)}return s}a(kc,"mergeMatches");var gt=class{static{a(this,"ConversationNodeAssembler")}eventDefinitions;viewDefinitions;contexts=new Map;contextsByKind=new Map;contextsBySeq=new Map;inputs=new Map;locationIndex=new Jn;dirty=new Set;revised=new Set;dependents=new Map;views=new Map;hasMore=!1;replacePending=!0;timelineDirty=!0;constructor(e,t){this.eventDefinitions=e,this.viewDefinitions=t,this.resetViewBuilders()}replaceWindow(e,t){this.contexts.clear(),this.contextsByKind.clear(),this.contextsBySeq.clear(),this.inputs.clear(),this.dirty.clear(),this.revised.clear(),this.dependents.clear(),this.hasMore=t;const n=[...e].sort((s,r)=>s.event.seq-r.event.seq);for(const s of n)this.inputs.set(s.event.seq,s);this.locationIndex.rebuild(n),this.timelineDirty=!0;for(const s of n)this.matchInput(s);this.replayDependencies(),this.revised.clear();for(const s of this.contexts.values())this.dirty.add(s);return this.replacePending=!0,"immediate"}append(e){if(this.inputs.has(e.event.seq))return"none";this.revised.clear(),this.inputs.set(e.event.seq,e);let t="none";if(Sc(e.event.type)){const n=this.locationIndex.snapshot(),s=this.locationIndex.appendBoundary(e.event);this.locationIndex.snapshot()!==n&&(this.timelineDirty=!0,t="immediate"),this.replayContexts(this.refreshMatchLocations(s)),s.size>0&&(t="immediate")}else this.locationIndex.appendNonBoundary(e.event);return t=Fe(t,this.matchInput(e)),this.replayRevisedDependents()&&(t="immediate"),this.revised.clear(),t}prepend(e,t){this.revised.clear();let n="none";const s=this.hasMore,r=e.filter(u=>!this.inputs.has(u.event.seq)).sort((u,h)=>u.event.seq-h.event.seq);for(const u of r)this.inputs.set(u.event.seq,u);this.hasMore=t;const i=this.locationIndex.snapshot(),o=this.locationIndex.rebuild(this.sortedInputs());this.locationIndex.snapshot()!==i&&(this.timelineDirty=!0);const c=this.refreshMatchLocations(o),d=new Map;for(const u of r)n=Fe(n,this.collectInput(u,d));return this.applyPendingMatches(d,c),this.replayContexts(c),(this.revised.size>0||s!==t)&&this.replayDependencies()&&(n="immediate"),o.size>0&&(n="immediate"),this.revised.clear(),n}rebuildRegistry(){return this.resetViewBuilders(),this.replaceWindow(this.sortedInputs(),this.hasMore)}flush(){if(!this.replacePending&&this.dirty.size===0&&!this.timelineDirty)return!1;if(this.replacePending){this.replaceLocationData();const n=new Map;for(const s of this.views.keys())n.set(s,[]);for(const s of this.contexts.values()){const r=s.definition.target;if(r===void 0||!this.views.has(r))continue;const i=this.buildNode(s,r);s.current.set(r,i),i!==null&&n.get(r)?.push(i)}for(const s of this.views.values())s.snapshot=s.builder.replace({nodes:n.get(s.target)??[],timeline:this.locationIndex.snapshot()});return this.replacePending=!1,this.dirty.clear(),this.timelineDirty=!1,!0}const e=new Map;for(const n of this.views.keys())e.set(n,[]);this.applyDirtyLocationData()&&(this.timelineDirty=!0);for(const n of this.dirty){const s=n.definition.target;if(s===void 0||!this.views.has(s))continue;const r=n.current.get(s)??null,i=this.buildNode(n,s);if(i===null&&r!==null)throw new Error(`conversation Definition "${n.kind}" withdrew materialized target "${s}"; return the same key with hidden visibility instead`);n.current.set(s,i),i!==null&&e.get(s)?.push(i)}this.dirty.clear();const t=this.timelineDirty;this.timelineDirty=!1;for(const n of this.views.values()){const s=e.get(n.target)??[];s.length===0&&!t||(n.snapshot=n.builder.apply({upserts:s,timeline:this.locationIndex.snapshot()}))}return!0}snapshot(e){return this.views.get(e)?.snapshot}get(e){return this.snapshot(e)}sortedInputs(){return[...this.inputs.values()].sort((e,t)=>e.event.seq-t.event.seq)}matchInput(e){return this.dispatchInput(e,(t,n,s)=>this.acceptMatch(t,n,s,e))}collectInput(e,t){return this.dispatchInput(e,(n,s,r)=>{const i=ht(n.kind,s),o={...e,role:r,location:this.locationIndex.locationOf(e.event)},c=t.get(i)??[];return c.push({definition:n,id:s,match:o}),t.set(i,c),n.publication?.(o)??"immediate"})}dispatchInput(e,t){const n=new Set;let s="none";for(const o of this.eventDefinitions.entries()){const c=o.match(e.event);c!==null&&(o.target!==void 0&&n.add(o.target),s=Fe(s,t(o,c.id,c.role)))}const r=this.eventDefinitions.fallbackEntry(),i=r?.target;if(r!==void 0&&i!==void 0&&!n.has(i)){const o=r.match(e.event);o!==null&&(s=Fe(s,t(r,o.id,o.role)))}return s}acceptMatch(e,t,n,s){const r=ht(e.kind,t);let i=this.contexts.get(r);if(n==="start"&&i?.start!==void 0)throw new Error(`conversation Context ${r} received more than one start Match`);i===void 0&&(i={key:r,kind:e.kind,id:t,definition:e,startSeq:void 0,start:void 0,matches:[],state:void 0,revision:0,current:new Map,locationData:Yn(),dependencies:new Map},this.contexts.set(r,i));const o={...s,role:n,location:this.locationIndex.locationOf(s.event)},c=i.matches.at(-1);if(c!==void 0&&c.event.seq>=s.event.seq)throw new Error(`conversation Context ${r} received non-appended Match ${s.event.seq}`);if(n==="start"&&i.matches.length>0)throw new Error(`conversation Context ${r} received an update before its start Match`);i.matches.push(o),n==="start"&&(i.startSeq=s.event.seq,i.start=o,this.indexStartedContext(i));const d=this.contextsBySeq.get(s.event.seq)??new Set;if(d.add(i),this.contextsBySeq.set(s.event.seq,d),n==="start")this.replayContext(i);else if(i.state!==void 0){const u=me(i);i.state=vt(e,"update",e.update(u,o)),i.revision++,this.revised.add(i)}return this.dirty.add(i),e.publication?.(o)??"immediate"}applyPendingMatches(e,t){const n=new Map;for(const[s,r]of e){const i=r[0];if(i===void 0)continue;let o=this.contexts.get(s);o===void 0&&(o={key:s,kind:i.definition.kind,id:i.id,definition:i.definition,startSeq:void 0,start:void 0,matches:[],state:void 0,revision:0,current:new Map,locationData:Yn(),dependencies:new Map},this.contexts.set(s,o));let c;const d=r.map(u=>{if(u.definition!==o.definition||u.id!==o.id)throw new Error(`conversation Context ${s} received inconsistent Definition identity`);if(u.match.role==="start"){if(c!==void 0||o.start!==void 0)throw new Error(`conversation Context ${s} received more than one start Match`);c=u.match}const h=this.contextsBySeq.get(u.match.event.seq)??new Set;return h.add(o),this.contextsBySeq.set(u.match.event.seq,h),u.match}).sort((u,h)=>u.event.seq-h.event.seq);if(o.matches=kc(o.key,d,o.matches),c!==void 0){o.start=c,o.startSeq=c.event.seq;const u=n.get(o.kind)??[];u.push(o),n.set(o.kind,u)}if(o.start!==void 0&&o.matches[0]!==o.start)throw new Error(`conversation Context ${o.key} received an update before its start Match`);t.add(o),this.dirty.add(o)}for(const[s,r]of n)this.indexStartedContexts(s,r)}replayContexts(e){const t=[...e].sort((n,s)=>(n.startSeq??Number.POSITIVE_INFINITY)-(s.startSeq??Number.POSITIVE_INFINITY));for(const n of t){if(n.start===void 0){n.state=void 0,this.dirty.add(n);continue}this.replayContext(n)}}replayContext(e){const t=e.start;if(t===void 0){e.state=void 0;return}if(e.matches[0]!==t)throw new Error(`conversation Context ${e.key} received an update before its start Match`);const n=new Map,s=this.readerFor(t.event.seq,n);e.state=void 0,e.state=vt(e.definition,"start",e.definition.start(me(e),t,s)),this.replaceDependencies(e,n);for(let r=1;r<e.matches.length;r++){const i=e.matches[r];if(i===void 0||i.role!=="update")continue;const o=me(e);e.state=vt(e.definition,"update",e.definition.update(o,i))}e.revision++,this.revised.add(e),this.dirty.add(e)}replaceDependencies(e,t){for(const n of e.dependencies.values()){if(n.key===void 0)continue;const s=this.dependents.get(n.key);s?.delete(e),s?.size===0&&this.dependents.delete(n.key)}e.dependencies=t;for(const n of t.values()){if(n.key===void 0)continue;const s=this.dependents.get(n.key)??new Set;s.add(e),this.dependents.set(n.key,s)}}replayRevisedDependents(){const e=[...this.revised],t=new Set;for(let n=0;n<e.length;n++){const s=e[n];if(s!==void 0)for(const r of this.dependents.get(s.key)??[])t.has(r)||(t.add(r),e.push(r))}return this.replayContexts(t),t.size>0}readerFor(e,t){return{previous:a(n=>{const s=this.previousContext(n,e);if(t.set(n,{kind:n,key:s?.key,revision:s?.revision,windowGap:s===void 0&&this.hasMore}),s?.state===void 0)return;const r=pe(s);if(r!==void 0)return{key:s.key,kind:s.kind,id:s.id,startSeq:r,state:s.state,matches:s.matches}},"previous")}}previousContext(e,t){const n=this.contextsByKind.get(e)??[],s=Hn(n,t);for(let r=s-1;r>=0;r--){const i=n[r];if(i?.state!==void 0)return i}}indexStartedContext(e){const t=e.startSeq;if(t===void 0)return;const n=this.contextsByKind.get(e.kind)??[],s=n.at(-1);s===void 0||s.startSeq<t?n.push(e):n.splice(Hn(n,t),0,e),this.contextsByKind.set(e.kind,n)}indexStartedContexts(e,t){if(t.length===0)return;const n=[...t].sort((c,d)=>c.startSeq-d.startSeq),s=this.contextsByKind.get(e)??[],r=[];let i=0,o=0;for(;i<s.length||o<n.length;){const c=s[i],d=n[o];d===void 0||c!==void 0&&c.startSeq<d.startSeq?(r.push(c),i++):(r.push(d),o++)}this.contextsByKind.set(e,r)}replayDependencies(){let e=!1;const t=[...this.contexts.values()].filter(n=>pe(n)!==void 0).sort((n,s)=>pe(n)-pe(s));for(const n of t){if(n.state===void 0||n.dependencies.size===0)continue;const s=pe(n);if(s===void 0)continue;let r=!1;for(const i of n.dependencies.values()){const o=this.previousContext(i.kind,s),c=o===void 0&&this.hasMore;if(o?.key!==i.key||o?.revision!==i.revision||c!==i.windowGap){r=!0;break}}r&&(this.replayContext(n),e=!0)}return e}refreshMatchLocations(e){const t=new Set;if(e.size===0)return t;for(const n of e)for(const s of this.contextsBySeq.get(n)??[])t.add(s);for(const n of t){let s=n.start;n.matches=n.matches.map(r=>{if(!e.has(r.event.seq))return r;const i={...r,location:this.locationIndex.locationOf(r.event)};return r===s&&(s=i),i}),n.start=s}return t}buildNode(e,t){if(e.definition.target!==t||e.definition.buildViewNode===void 0)return null;const n=e.definition.buildViewNode(me(e));if(n===null)return null;if(n.key!==e.key)throw new Error(`conversation Definition "${e.kind}" returned unstable key "${n.key}"; expected "${e.key}"`);if(n.target!==t)throw new Error(`conversation Definition "${e.kind}" returned target "${n.target}" while building "${t}"`);return n}buildLocationData(e,t){if(e.definition.buildLocationData===void 0)return null;const n=e.definition.buildLocationData(me(e),t);if(n===null)return null;if(n.kind!==t)throw new Error(`conversation Definition "${e.kind}" published ${n.kind} data through its ${t} scope`);if(n.key!==e.kind)throw new Error(`conversation Definition "${e.kind}" published Location data key "${n.key}"; expected its owned kind`);if(!Number.isSafeInteger(n.turn)||n.turn<0)throw new Error(`conversation Definition "${e.kind}" published invalid turn ${n.turn}`);if(n.kind==="step"&&(!Number.isSafeInteger(n.step)||n.step<0))throw new Error(`conversation Definition "${e.kind}" published invalid step ${String(n.step)}`);return n}replaceLocationData(){const e=[];for(const t of Kn){for(const n of this.contexts.values()){const s=this.buildLocationData(n,t);n.locationData[t]=s,s!==null&&e.push({owner:n.key,data:s})}this.locationIndex.replaceData(e)}}applyDirtyLocationData(){let e=!1;for(const t of Kn){const n=[];for(const s of this.dirty){const r=s.locationData[t],i=this.buildLocationData(s,t);s.locationData[t]=i,r!==i&&n.push({owner:s.key,previous:r,next:i})}e=this.locationIndex.applyData(n)||e}return e}resetViewBuilders(){this.views.clear();for(const e of this.viewDefinitions.entries()){const t=e.create();this.views.set(e.target,{target:e.target,builder:t,snapshot:t.empty})}this.replacePending=!0}};function Sc(e){return e==="turn/start"||e==="turn/end"||e==="step/start"||e==="step/end"}a(Sc,"isLocationBoundary");function vt(e,t,n){if(n===void 0)throw new Error(`conversation Definition "${e.kind}" returned undefined from ${t}()`);return n}a(vt,"requireState");function Ic(e){return e.map(Xn)}a(Ic,"toAssistantBlocks");function Xn(e){switch(e.type){case"text":return{kind:"text",text:e.text};case"reasoning":return{kind:"reasoning",text:e.text};case"image":return{kind:"image",attachment:e.attachment};case"tool-call":return{kind:"tool-call",callId:String(e.id),name:e.name,argsRaw:e.arguments};default:return{kind:"other",block:e}}}a(Xn,"toAssistantBlock");const G=[],zc={turnOrder:G,turns:new Map},$c={get:a(()=>{},"get")},Qn={order:G,nodes:{get:a(()=>{},"get"),values:a(()=>G,"values")},locations:{getTurn:a(()=>G,"getTurn"),getStep:a(()=>G,"getStep")},timeline:zc,legacy:{nodes:G,turnTimings:new Map,turnEnds:new Map,partial:null,runningCalls:G}},Ec={approval:"a",question:"q"};var yt=class{static{a(this,"PendingWait")}kind;key;sessionId;payload;#e=!1;#t;#n;constructor(e,t,n,s,r){this.kind=e,this.key=`${Ec[e]}:${t}`,this.sessionId=n,this.payload=s,this.#t=t,this.#n=r}respond(e){if(this.#e)throw new Error(`pending wait ${this.key} is already settled`);return this.#n({type:"client-response",rpcId:this.#t,result:e})}markSettled(){this.#e=!0}};function es(){const e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!="string"||e.length===0)throw new Error("browser time zone is unavailable");return e}a(es,"resolvedClientTimeZone");const ts=200;function Oc(e){const t=e.map(s=>s.type==="text"?s.text:`[${s.type}]`).join(" ").replace(/\s+/g," ").trim(),n=Array.from(t);return n.length>ts?`${n.slice(0,ts).join("")}…`:t}a(Oc,"previewOf");function Pc(e){return e.every(t=>t.type==="text")?e.map(t=>t.text).join(""):null}a(Pc,"textOf");var Dc=class{static{a(this,"SessionQueueMirror")}current=[];snapshot(){return this.current}reset(){return this.current.length===0?!1:(this.current=[],!0)}replace(e){this.current=e.map(t=>({id:t.id,messageId:t.message.id,placement:t.placement,content:t.message.content,preview:Oc(t.message.content),text:Pc(t.message.content)}))}acceptDurable(e){if(e.type!=="user/message")return!1;const t=e.data.id,n=this.current.findIndex(s=>s.placement==="steering"&&s.messageId===t);return n<0?!1:(this.current=this.current.filter((s,r)=>r!==n),!0)}},Cc=class{static{a(this,"Session")}sessionId;api;remote;options;events=[];views=[];baseSeq=0;hasMore=!1;openState="cold";openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;pending=new Map;pendingRev=0;pendingCache=null;queueMirror=new Dc;conversation;running=!1;address;parentAvailable=!1;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;lastAgentError=null;liveBuffer=[];stitching=!1;subscribedLastSeq=null;projections;snapshotCache;notifier;actx;constructor(e,t,n,s={}){this.sessionId=e,this.api=t,this.remote=n,this.options=s,this.projections=s.projections??new Bn,this.address=s.address,this.parentAvailable=s.parentAvailable??!1,this.conversation=s.conversation===void 0?new gt({entries:a(()=>[],"entries"),fallbackEntry:a(()=>{},"fallbackEntry")},{entries:a(()=>[],"entries")}):new gt(s.conversation.events,s.conversation.views),this.notifier=new ne(()=>{this.conversation.flush(),this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot()}bindScope(e){if(this.actx!==void 0)throw new Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}async prompt(e,t){this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let n;try{if(this.address===void 0)n=(await this.api.sessions.prompt({sessionId:this.sessionId,mode:t,content:e,clientTimeZone:es()})).result;else if(this.address.mode==="one-shot")n={ok:!1,error:{code:"subagent-not-resumable",message:"one-shot subagent conversations are read-only",details:{childSessionId:this.address.childSessionId}}};else if(e.some(s=>s.type==="image"))n={ok:!1,error:{code:"attachment-error",message:"Image input is unavailable for subagent continuations.",details:{reason:"SUBAGENT_IMAGE_UNSUPPORTED"}}};else{const s=(await this.api.subagents.prompt({...this.address,content:e.flatMap(r=>r.type==="text"?[{type:"text",text:r.text}]:[]),clientTimeZone:es()})).result;n=s.ok?{ok:!0,value:{accepted:!0}}:s}}catch(s){n=M(s)}return n.ok?(this.blankBit&&(this.blankBit=!1,this.options.onEngaged?.(this),this.notifier.markDirty()),n):(this.promptError={op:"send",error:n.error},this.notifier.markDirty(),n)}async readAttachment(e){try{const t=(await this.api.sessions.attachment({sessionId:this.sessionId,attachmentId:e})).result;if(!t.ok)return t;const n=atob(t.value.data),s=Uint8Array.from(n,r=>r.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:s}}}catch(t){return M(t)}}async updateQueue(e,t){try{return(await this.api.sessions.updateQueue({sessionId:this.sessionId,itemId:e,action:t})).result}catch(n){return M(n)}}async cancel(){const e=this.address;if(e!==void 0&&e.mode==="one-shot"){const n={ok:!1,error:{code:"subagent-delivery-unavailable",message:"subagent activation cancellation is unavailable",details:{childSessionId:e.childSessionId}}};return this.promptError={op:"stop",error:n.error},this.notifier.markDirty(),n}let t;try{t=e!==void 0?(await this.api.subagents.interrupt(e)).result:(await this.api.sessions.cancel({sessionId:this.sessionId})).result}catch(n){t=M(n)}return t.ok||(this.promptError={op:"stop",error:t.error},this.notifier.markDirty()),t}async rename(e){try{const{result:t}=await this.api.sessions.rename({sessionId:this.sessionId,title:e});return t.ok&&this.projections.apply("title",t.value.title,t.value.seq),t}catch(t){return M(t)}}async command(e){const t=await this.remote.commands.execute(this.sessionId,e);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState==="open")return Promise.resolve();if(this.openPromise!==null)return this.openPromise;const e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(!(this.openState!=="open"||!this.hasMore||this.loadingOlder)){this.loadingOlder=!0,this.notifier.markDirty();try{const{result:e}=await this.history({beforeSeq:this.baseSeq,maxMessages:50});if(!e.ok)return;const t=e.value.events;if(t.length===0){this.hasMore=e.value.hasMore,this.conversation.prepend([],this.hasMore);return}const n=t[t.length-1];if(n===void 0||n.event.seq+1!==this.baseSeq){console.error(`[web-runtime] history page discontinuous: tail seq ${n?.event.seq} vs baseSeq ${this.baseSeq}`),this.hasMore=!1,this.conversation.prepend([],!1);return}this.events=[...t.map(s=>s.event),...this.events],this.views=[...t.map(s=>s.view),...this.views],this.baseSeq=t[0]?.event.seq??this.baseSeq,this.hasMore=e.value.hasMore,this.conversation.prepend(t.map(ns),this.hasMore)}catch(e){console.error("[web-runtime] loadOlder failed:",e)}finally{this.loadingOlder=!1,this.notifier.markDirty()}}}async resync(){this.openState!=="cold"&&(this.openGeneration++,this.openPromise=null,this.openState="cold",this.openError=null,this.events=[],this.views=[],this.baseSeq=0,this.pending.clear(),this.pendingRev++,this.subscribedLastSeq=null,this.liveBuffer=[],this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}handleMuxEnvelope(e,t){switch(t.type){case"session/event":this.acceptLiveEvent(t.event,t.view);return;case"session/queue":this.queueMirror.replace(t.items),this.notifier.markDirty();return;case"session/subscribed":this.subscribedLastSeq=t.lastSeq,this.queueMirror.reset()&&this.notifier.markDirty();return;case"approval/requested":{const{type:n,sessionId:s,...r}=t;this.mint(new yt("approval",e,this.sessionId,r,i=>this.api.respond(i))),this.notifier.markDirty();return}case"approval/resolved":for(const n of this.pending.values())n.kind==="approval"&&n.payload.approvalId===t.approvalId&&this.settle(n);this.notifier.markDirty();return;case"question/requested":{const{type:n,sessionId:s,...r}=t;this.mint(new yt("question",e,this.sessionId,r,i=>this.api.respond(i))),this.notifier.markDirty();return}case"question/resolved":{const n=this.pending.get(`q:${t.questionRpcId}`);n!==void 0&&this.settle(n),this.notifier.markDirty();return}default:return}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t=!1){const n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!=="cold"?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}dispose(){}rebuildConversationRegistry(){this.scheduleConversation(this.conversation.rebuildRegistry())}mint(e){this.pending.set(e.key,e),this.pendingRev++}settle(e){e.markSettled(),this.pending.delete(e.key),this.pendingRev++}async doOpen(e){this.openState="loading",this.openError=null,this.notifier.markDirty();try{let{result:t}=await this.history({maxMessages:50});if(e!==this.openGeneration)return;if(!t.ok){this.openState="error",this.openError=t.error;return}this.installWindow(t.value.events,t.value.hasMore,t.value.projections);const n=this.windowTailSeq();if(this.subscribedLastSeq!==null&&n!==null&&this.subscribedLastSeq>n){if(t=(await this.history({maxMessages:50})).result,e!==this.openGeneration)return;t.ok&&this.installWindow(t.value.events,t.value.hasMore,t.value.projections)}this.openState="open"}catch(t){if(e!==this.openGeneration)return;this.openState="error";const n=M(t);this.openError=n.ok?null:n.error}finally{e===this.openGeneration&&this.notifier.markDirty()}}installWindow(e,t,n){this.events=e.map(r=>r.event),this.views=e.map(r=>r.view),this.baseSeq=this.events[0]?.seq??0,this.hasMore=t,this.events.some(r=>r.type==="turn/start")&&(this.firstPromptPendingTurn=!1),this.conversation.replaceWindow(e.map(ns),t),n!==void 0&&this.projections.seed(n);const s=this.liveBuffer;this.liveBuffer=[];for(const r of s)this.appendLive(r.event,r.view);this.notifier.markDirty()}appendLive(e,t){const n=this.windowTailSeq();if(n!==null&&e.seq<=n)return"none";this.events.push(e),this.views.push(t),e.type==="turn/start"&&(this.firstPromptPendingTurn=!1);const s=this.queueMirror.acceptDurable(e),r=this.conversation.append({event:e,view:t});return s?"immediate":r}acceptLiveEvent(e,t){if(this.openState==="loading"||this.stitching){this.liveBuffer.push({event:e,view:t});return}if(this.openState!=="open")return;const n=this.windowTailSeq();if(n!==null&&e.seq>n+1){this.liveBuffer.push({event:e,view:t}),this.repairGap();return}this.scheduleConversation(this.appendLive(e,t))}scheduleConversation(e){e==="immediate"?this.notifier.markDirty():e==="animation-frame"&&this.notifier.markFrameDirty()}async repairGap(){if(this.stitching)return;this.stitching=!0;const e=this.openGeneration;try{const{result:t}=await this.history({maxMessages:50});t.ok&&e===this.openGeneration&&this.openState==="open"&&this.installWindow(t.value.events,t.value.hasMore,t.value.projections)}catch(t){console.error("[web-runtime] gap repair failed:",t)}finally{this.stitching=!1}}windowTailSeq(){const e=this.events[this.events.length-1];return e===void 0?null:e.seq}buildSnapshot(){(this.pendingCache===null||this.pendingCache.rev!==this.pendingRev)&&(this.pendingCache={rev:this.pendingRev,value:[...this.pending.values()]});const e=this.conversation.snapshot("chat")??Qn,t=e.legacy;return{sessionId:this.sessionId,views:this.conversation,chat:e,nodes:t.nodes,turnTimings:t.turnTimings,turnEnds:t.turnEnds,partial:t.partial,runningCalls:t.runningCalls,pending:this.pendingCache.value,queue:this.queueMirror.snapshot(),running:this.running,subagent:this.address===void 0?null:{address:this.address,parentAvailable:this.parentAvailable},composerPhase:Tc(Ac(e)||!this.blankBit&&!this.firstPromptPendingTurn||this.running||this.pendingCache.value.length>0,this.promptAttempted),removed:this.removed,openState:this.openState,openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError}}history(e){return this.address===void 0?this.api.sessions.history({sessionId:this.sessionId,...e}):this.api.subagents.history({...this.address,...e})}};function ns(e){return{event:e.event,view:e.view}}a(ns,"conversationInput");function Ac(e){return e.order.some(t=>e.nodes.get(t)?.kind!=="command")}a(Ac,"hasVisibleConversationContent");function Tc(e,t){return e?"active":t?"engaging":"blank"}a(Tc,"derivePhase");function ss(e){const t=e.payload;switch(t.type){case"approval/requested":return`a:${t.approvalId}`;case"question/requested":return`q:${e.rpcId}`;case"session/queue":return"queue";default:return}}a(ss,"bufferedRequestKey");function Zc(e){if(e.length!==1)return"question";const t=e[0],n=t.intent;if(n?.kind!=="plan-review"||t.detail===void 0||t.multiSelect===!0)return"question";const s=t.options??[];return s.length>2?"question":s.some(r=>r.label===n.approve)?"plan-review":"question"}a(Zc,"questionInteractionStatus");var Nc=class{static{a(this,"SessionManager")}api;remote;conversation;sessions=new Map;pendingBuffers=new Map;pendingInteractions=new Map;completedNotifications=new Set;prevRunning=new Map;projectionStores=new Map;summaries=[];listState="idle";listPhase="pending";listError=null;listInflight=null;listMutations=null;addresses=new Map;catalogs=new Map;catalogInflight=new Map;catalogStale=new Set;openCatalogs=new Set;catalogDebounce=new Map;jobsBySession=new Map;selected;listSnapshotCache;entryCache=new Map;itemsCache=[];notifier=new ne(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e,t,n,s,r){this.api=e,this.remote=t,this.conversation=r,this.selected=n,s!==void 0&&this.addresses.set(s.childSessionId,s),this.listSnapshotCache=this.buildListSnapshot()}select(e){const t=this.navigationAddress(e);if(!this.summaries.some(n=>n.sessionId===e)&&t===void 0)throw new Error(`sessions.select: unknown session ${e}`);t!==void 0&&this.addresses.set(e,t),this.sessions.get(e)?.configureSubagent(t,t===void 0?!1:this.catalogs.get(t.parentSessionId)?.parentAvailable??!1),this.selected=e,this.completedNotifications.delete(e),this.refreshSubagents(e),this.notifier.notifyNow()}selectSubagent(e){const t=this.catalogs.get(e.parentSessionId),n=t?.entries.find(s=>s.id===e.childSessionId);if(n===void 0||n.kind!=="child"||n.mode!==e.mode)throw new Error(`sessions.selectSubagent: ${e.childSessionId} is not a healthy catalog child`);this.addresses.set(e.childSessionId,e),this.sessions.get(e.childSessionId)?.configureSubagent(e,t?.parentAvailable??!1),this.selected=e.childSessionId,this.completedNotifications.delete(e.childSessionId),this.refreshSubagents(e.childSessionId),this.notifier.notifyNow()}clearSelection(){this.selected=void 0,this.notifier.notifyNow()}subagentAddress(e){return this.addresses.get(e)}navigationAddress(e){const t=this.addresses.get(e);if(t!==void 0)return t;for(const[n,s]of this.catalogs){const r=s.entries.find(i=>i.kind==="child"&&i.id===e);if(r?.kind==="child")return{parentSessionId:n,childSessionId:e,mode:r.mode}}}drop(e){this.sessions.delete(e)}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);const n=this.pendingBuffers.get(e);if(n!==void 0){this.pendingBuffers.delete(e);for(const r of n)t.handleMuxEnvelope(r.rpcId,r.payload)}const s=this.summaries.find(r=>r.sessionId===e);if(s!==void 0)t.handleBlank(s.blank),t.handleRunning(s.running);else{const r=this.addresses.get(e),i=r===void 0?void 0:this.catalogs.get(r.parentSessionId)?.entries.find(o=>o.kind==="child"&&o.id===e);i?.kind==="child"&&(t.handleBlank(!1),t.handleRunning(i.activity==="running"))}}return t}createSession(e){const t=this.addresses.get(e);return new Cc(e,this.api,this.remote,{...t===void 0?{}:{address:t,parentAvailable:this.catalogs.get(t.parentSessionId)?.parentAvailable??!1},onEngaged:a(n=>{this.recordMutation({kind:"engaged",sessionId:n.sessionId})},"onEngaged"),projections:this.projectionStore(e),...this.conversation===void 0?{}:{conversation:this.conversation}})}rebuildConversationRegistry(){for(const e of this.sessions.values())e.rebuildConversationRegistry()}projectionStore(e){let t=this.projectionStores.get(e);return t===void 0&&(t=new Bn,t.subscribeAny(()=>{this.notifier.markDirty()}),this.projectionStores.set(e,t)),t}refreshSubagents(e){const t=this.catalogInflight.get(e);if(t!==void 0)return t.promise;const n=this.catalogs.get(e),s=new Set,r=new Map;this.catalogs.set(e,{entries:n?.entries??[],parentAvailable:n?.parentAvailable??!1,state:"loading",error:null}),this.notifier.markDirty();const i=(async()=>{try{const{result:o}=await this.api.subagents.list({parentSessionId:e});if(o.ok){const c=this.catalogInflight.get(e)?.parentAvailableOverride??o.value.parentAvailable;this.catalogs.set(e,{...o.value,entries:this.withCatalogMutations(o.value.entries,s,r),parentAvailable:c,state:"ready",error:null});for(const[d,u]of this.addresses)u.parentSessionId===e&&this.sessions.get(d)?.handleSubagentParentAvailable(c)}else this.catalogs.set(e,{entries:this.withCatalogMutations(n?.entries??[],s,r),parentAvailable:this.catalogInflight.get(e)?.parentAvailableOverride??n?.parentAvailable??!1,state:"error",error:o.error})}catch(o){const c=M(o);this.catalogs.set(e,{entries:this.withCatalogMutations(n?.entries??[],s,r),parentAvailable:this.catalogInflight.get(e)?.parentAvailableOverride??n?.parentAvailable??!1,state:"error",error:c.ok?null:c.error})}finally{this.catalogInflight.delete(e),this.catalogStale.delete(e)&&this.refreshSubagents(e),this.notifier.markDirty()}})();return this.catalogInflight.set(e,{promise:i,expandableRows:s,activityRows:r,parentAvailableOverride:void 0}),i}setSubagentCatalogOpen(e,t){if(t)this.openCatalogs.add(e),this.refreshSubagents(e);else{this.openCatalogs.delete(e);const n=this.catalogDebounce.get(e);n!==void 0&&(clearTimeout(n),this.catalogDebounce.delete(e))}}refreshList(){if(this.listInflight!==null)return this.listInflight;this.listState="loading",this.listError=null;const e=this.summaries,t=[];return this.listMutations=t,this.notifier.markDirty(),this.listInflight=(async()=>{try{const{result:n}=await this.api.sessions.list({});if(n.ok){const s=this.listPhase==="pending"?n.value.items:yc(e,n.value.items,i=>i.sessionId);for(const i of s)this.prevRunning.has(i.sessionId)||this.prevRunning.set(i.sessionId,i.running);let r=s;for(const i of t)r=rs(r,i),this.summaries=r,this.syncCompletedNotifications();this.summaries=r,this.listState="idle",this.listPhase="ready",this.syncCompletedNotifications();for(const i of this.summaries){const o=this.sessions.get(i.sessionId);o!==void 0&&(o.handleBlank(i.blank),o.handleRunning(i.running))}for(const i of n.value.items){const o=i.projections;if(o===void 0)continue;const c=this.projectionStore(i.sessionId),d=o.values;for(const u of Object.keys(d))c.apply(u,d[u],o.asOfSeq)}}else this.listState="error",this.listError=n.error}catch(n){this.listState="error";const s=M(n);this.listError=s.ok?null:s.error}finally{this.listMutations=null,this.listInflight=null,this.notifier.markDirty()}})(),this.listInflight}async search(e,t){try{return(await this.api.sessions.search({query:e},t)).result}catch(n){return M(n)}}async create(e={}){try{const t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId!==void 0?{workspaceId:e.workspaceId,...t}:{...e.cwd===void 0?{}:{cwd:e.cwd},...t},{result:s}=await this.api.sessions.create(n);if(s.ok)this.recordMutation({kind:"upsert",summary:{sessionId:s.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd!==void 0?{cwd:e.cwd}:{},...s.value.agentPreset!==void 0?{agentPreset:s.value.agentPreset}:{}}});else{const r=is(s.error);r!==void 0&&this.recordMutation({kind:"upsert",summary:{sessionId:r,updatedAt:Date.now(),running:!1,blank:!0}})}return s}catch(t){return M(t)}}async fork(e){try{const t=this.summaries.find(r=>r.sessionId===e.sessionId),{result:n}=await this.api.sessions.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:e.atSeq}}),s=n.ok?n.value.sessionId:is(n.error);return s!==void 0&&this.recordMutation({kind:"upsert",summary:{sessionId:s,updatedAt:Date.now(),running:!1,blank:!1,parentSessionId:e.sessionId,...t?.cwd!==void 0?{cwd:t.cwd}:{}}}),n}catch(t){return M(t)}}mergeSummary(e){this.recordMutation({kind:"upsert",summary:e})}noteAgentPreset(e,t){this.recordMutation({kind:"upsert",summary:{sessionId:e,updatedAt:Date.now(),running:!1,blank:!0,agentPreset:t}})}recordMutation(e){this.listMutations?.push(e),this.summaries=rs(this.summaries,e),this.syncCompletedNotifications(),this.notifier.markDirty()}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}trackPending(e,t,n){let s=this.pendingInteractions.get(e);s===void 0&&(s=new Map,this.pendingInteractions.set(e,s)),s.get(t)!==n&&(s.set(t,n),this.notifier.markDirty())}resolvePending(e,t){const n=this.pendingInteractions.get(e);n===void 0||!n.delete(t)||(n.size===0&&this.pendingInteractions.delete(e),this.notifier.markDirty())}handleMuxEnvelope(e){const t=e.payload;if(t.type==="stream/error")return;if(t.type==="session/event"&&t.event.type==="user/message"&&t.event.data.source.kind==="user"&&this.recordMutation({kind:"activity",sessionId:t.sessionId,updatedAt:t.event.time}),t.type==="session/projection"){this.projectionStore(t.sessionId).apply(t.key,t.value,t.seq),this.notifier.markDirty();return}if(t.type==="session/jobs"){t.jobs.length===0?this.jobsBySession.delete(t.sessionId):this.jobsBySession.set(t.sessionId,t.jobs),this.notifier.markDirty();return}if(t.type==="session/subscribed"){this.projectionStores.get(t.sessionId)?.truncate(t.lastSeq),this.jobsBySession.delete(t.sessionId),this.notifier.markDirty();const s=this.pendingBuffers.get(t.sessionId);if(s!==void 0){const r=s.filter(i=>i.payload.type!=="session/queue");r.length!==s.length&&(r.length===0?this.pendingBuffers.delete(t.sessionId):this.pendingBuffers.set(t.sessionId,r))}}t.type==="approval/requested"?this.trackPending(t.sessionId,`a:${t.approvalId}`,"approval"):t.type==="approval/resolved"?this.resolvePending(t.sessionId,`a:${t.approvalId}`):t.type==="question/requested"?this.trackPending(t.sessionId,`q:${e.rpcId}`,Zc(t.questions)):t.type==="question/resolved"&&this.resolvePending(t.sessionId,`q:${t.questionRpcId}`);const n=this.sessions.get(t.sessionId);if(n===void 0)switch(t.type){case"approval/requested":case"question/requested":case"session/queue":{const s=this.pendingBuffers.get(t.sessionId)??[],r=t.type==="approval/requested"?`a:${t.approvalId}`:t.type==="question/requested"?`q:${e.rpcId}`:"queue",i=s.findIndex(o=>ss(o)===r);i===-1?s.push(e):s[i]=e,this.pendingBuffers.set(t.sessionId,s);return}case"approval/resolved":case"question/resolved":{const s=this.pendingBuffers.get(t.sessionId);if(s===void 0)return;const r=t.type==="approval/resolved"?`a:${t.approvalId}`:`q:${t.questionRpcId}`,i=s.findIndex(o=>ss(o)===r);i!==-1&&s.splice(i,1),s.length===0&&this.pendingBuffers.delete(t.sessionId);return}default:return}n.handleMuxEnvelope(e.rpcId,t)}handleHostEnvelope(e){const t=e.payload;switch(t.type){case"host/session-added":this.mergeSummary({sessionId:t.sessionId,updatedAt:Date.now(),running:!1,blank:t.blank,...t.parentSessionId!==void 0?{parentSessionId:t.parentSessionId}:{},...t.origin!==void 0?{origin:t.origin}:{},...t.cwd!==void 0?{cwd:t.cwd}:{},...t.agentPreset!==void 0?{agentPreset:t.agentPreset}:{}}),this.sessions.get(t.sessionId)?.handleBlank(t.blank),t.origin==="subagent"&&t.parentSessionId!==void 0&&this.markCatalogParentExpandable(t.parentSessionId),t.parentSessionId!==void 0&&(this.selected===t.parentSessionId||this.openCatalogs.has(t.parentSessionId))&&this.scheduleCatalogRefresh(t.parentSessionId);return;case"host/session-removed":{const n=this.summaries.find(i=>i.sessionId===t.sessionId)?.origin==="subagent"||this.addresses.has(t.sessionId);this.recordMutation(n?{kind:"status",sessionId:t.sessionId,running:!1}:{kind:"remove",sessionId:t.sessionId}),this.updateCatalogActivity(t.sessionId,!1),n?this.sessions.get(t.sessionId)?.handleRunning(!1):this.sessions.get(t.sessionId)?.handleRemoved(),this.pendingBuffers.delete(t.sessionId),this.pendingInteractions.delete(t.sessionId),this.jobsBySession.delete(t.sessionId),n||this.projectionStores.delete(t.sessionId);const s=this.catalogInflight.get(t.sessionId);s!==void 0&&(s.parentAvailableOverride=!1,this.catalogStale.add(t.sessionId));const r=this.catalogs.get(t.sessionId);r!==void 0&&r.parentAvailable&&this.catalogs.set(t.sessionId,{...r,parentAvailable:!1});for(const[i,o]of this.addresses)o.parentSessionId===t.sessionId&&this.sessions.get(i)?.handleSubagentParentAvailable(!1);return}case"host/session-status":this.recordMutation({kind:"status",sessionId:t.sessionId,running:t.running}),this.sessions.get(t.sessionId)?.handleRunning(t.running),this.updateCatalogActivity(t.sessionId,t.running);return;case"host/agent-error":this.sessions.get(t.sessionId)?.handleAgentError(t.message);return;default:return}}handleDisconnected(){this.pendingInteractions.size>0&&(this.pendingInteractions.clear(),this.notifier.markDirty());for(const[e,t]of[...this.pendingBuffers]){const n=t.filter(s=>s.payload.type!=="approval/requested"&&s.payload.type!=="question/requested");n.length!==t.length&&(n.length===0?this.pendingBuffers.delete(e):this.pendingBuffers.set(e,n))}}handleConnected(){this.refreshList();const e=this.selected===void 0?void 0:this.addresses.get(this.selected);e!==void 0&&this.refreshSubagents(e.parentSessionId),this.selected!==void 0&&this.refreshSubagents(this.selected);for(const t of this.openCatalogs)this.refreshSubagents(t);for(const t of this.sessions.values())t.resync()}scheduleCatalogRefresh(e){if(this.catalogDebounce.has(e))return;const t=setTimeout(()=>{if(this.catalogDebounce.delete(e),this.catalogInflight.has(e)){this.catalogStale.add(e);return}this.refreshSubagents(e)},50);this.catalogDebounce.set(e,t)}updateCatalogActivity(e,t){const n=t?"running":"inactive";for(const r of this.catalogInflight.values())r.activityRows.set(e,n);let s=!1;for(const[r,i]of this.catalogs){if(!i.entries.some(c=>c.kind==="child"&&c.id===e&&c.activity!==n))continue;const o=i.entries.map(c=>c.kind!=="child"||c.id!==e?c:{...c,activity:n});s=!0,this.catalogs.set(r,{...i,entries:o})}s&&this.notifier.markDirty()}markCatalogParentExpandable(e){this.applyCatalogParentExpandable(e);for(const t of this.catalogInflight.values())t.expandableRows.add(e)}applyCatalogParentExpandable(e){let t=!1;for(const[n,s]of this.catalogs){if(!s.entries.some(i=>i.kind==="child"&&i.id===e&&!i.hasChildren))continue;const r=s.entries.map(i=>i.kind!=="child"||i.id!==e||i.hasChildren?i:{...i,hasChildren:!0});t=!0,this.catalogs.set(n,{...s,entries:r})}t&&this.notifier.markDirty()}withCatalogMutations(e,t,n){return e.map(s=>{if(s.kind!=="child")return s;const r=n.get(s.id);return!t.has(s.id)&&r===void 0?s:{...s,...t.has(s.id)?{hasChildren:!0}:{},...r===void 0?{}:{activity:r}}})}syncCompletedNotifications(){const e=new Set;for(const t of this.summaries){e.add(t.sessionId);const n=this.prevRunning.get(t.sessionId);if(n===void 0){this.prevRunning.set(t.sessionId,t.running);continue}n&&!t.running?t.sessionId!==this.selected&&this.completedNotifications.add(t.sessionId):t.running&&this.completedNotifications.delete(t.sessionId),this.prevRunning.set(t.sessionId,t.running)}for(const t of this.prevRunning.keys())e.has(t)||this.prevRunning.delete(t);for(const t of this.completedNotifications)e.has(t)||this.completedNotifications.delete(t)}buildListSnapshot(){const e=this.summaries.map(i=>{const o=this.projectionStores.get(i.sessionId),c=o?.get("title"),d=o?.values();return{...i,...typeof c=="string"&&c!==""?{title:c}:{},...d===void 0?{}:{projectionValues:d}}}),t=new Map;for(const[i,o]of this.pendingInteractions){const c=[...o.values()],d=c.find(u=>u!=="approval")??c[0];d!==void 0&&t.set(i,d)}const n=wc(e,t,this.completedNotifications).map(i=>{const o=this.entryCache.get(i.sessionId);return o!==void 0&&o.updatedAt===i.updatedAt&&o.running===i.running&&o.blank===i.blank&&o.agentPreset===i.agentPreset&&o.parentSessionId===i.parentSessionId&&o.cwd===i.cwd&&o.origin===i.origin&&o.title===i.title&&o.depth===i.depth&&o.pendingInteraction===i.pendingInteraction&&o.projectionValues===i.projectionValues&&o.completed===i.completed?o:(this.entryCache.set(i.sessionId,i),i)});for(const i of this.entryCache.keys())n.some(o=>o.sessionId===i)||this.entryCache.delete(i);n.length===this.itemsCache.length&&n.every((i,o)=>i===this.itemsCache[o])||(this.itemsCache=n);const s=this.selected,r=s!==void 0&&(n.some(i=>i.sessionId===s)||this.addresses.has(s))?s:void 0;return{items:this.itemsCache,current:r,state:this.listState,phase:this.listPhase,error:this.listError,subagentsByParent:Object.fromEntries(this.catalogs),jobsBySession:Object.fromEntries(this.jobsBySession),currentAddress:r===void 0?void 0:this.addresses.get(r)}}};function rs(e,t){switch(t.kind){case"upsert":{const n=e.find(r=>r.sessionId===t.summary.sessionId);if(n===void 0)return[t.summary,...e];const s={...n,blank:n.blank&&t.summary.blank,...n.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...n.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...n.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{},...t.summary.agentPreset!==void 0?{agentPreset:t.summary.agentPreset}:{}};return s.cwd===n.cwd&&s.parentSessionId===n.parentSessionId&&s.origin===n.origin&&s.blank===n.blank&&s.agentPreset===n.agentPreset?[...e]:e.map(r=>r.sessionId===t.summary.sessionId?s:r)}case"remove":return e.filter(n=>n.sessionId!==t.sessionId);case"status":return e.map(n=>n.sessionId===t.sessionId&&(n.running!==t.running||t.running&&n.blank)?{...n,running:t.running,blank:n.blank&&!t.running}:n);case"activity":return e.map(n=>n.sessionId===t.sessionId&&t.updatedAt>n.updatedAt?{...n,updatedAt:t.updatedAt}:n);case"engaged":return e.map(n=>n.sessionId===t.sessionId&&n.blank?{...n,blank:!1}:n)}}a(rs,"applyMutation");function is(e){const t=e;return t.code==="workspace-attach-failed"?t.details.sessionId:void 0}a(is,"workspaceAttachSessionId");var os=class{static{a(this,"SessionProvideChannel")}host;providers=[];maybeInfoCache;currentSnapshot;listeners=new Set;currentProvideInfo;constructor(e){this.host=e,this.providers.push({hooks:["session"],resolve:a(t=>({hooks:{session:t.session}}),"resolve")}),this.maybeInfoCache=this.materializeMaybeInfo(),this.currentSnapshot=this.maybeInfoCache,this.currentProvideInfo={getSnapshot:a(()=>this.currentSnapshot,"getSnapshot"),subscribe:a(t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}),"subscribe")}}get maybeInfo(){return this.maybeInfoCache}provide(e){this.providers.push(e);try{this.applyRosterChange()}catch(t){throw this.providers.splice(this.providers.indexOf(e),1),this.applyRosterChange(),t}return()=>{const t=this.providers.indexOf(e);t>=0&&this.providers.splice(t,1),this.applyRosterChange()}}publishCurrent(){const e=this.host.resolveCurrent();if(e!==this.currentSnapshot){this.currentSnapshot=e;for(const t of[...this.listeners])try{t()}catch(n){console.error("sessions.currentProvideInfo subscriber failed:",n)}}}materializeInfo(e){const t={},n={};for(const s of this.providers){const r=s.resolve(e),i=r.hooks??{},o=r.props??{};for(const c of Object.keys(i))if(!(s.hooks??[]).includes(c))throw new Error(`sessions.provide: undeclared hook "${c}"`);for(const c of Object.keys(o))if(!(s.props??[]).includes(c))throw new Error(`sessions.provide: undeclared prop "${c}"`);for(const c of s.hooks??[]){const d=i[c];if(d===void 0)throw new Error(`sessions.provide: missing hook "${c}"`);if(Object.hasOwn(t,c))throw new Error(`sessions.provide: duplicate hook "${c}"`);t[c]=d}for(const c of s.props??[]){if(!Object.hasOwn(o,c))throw new Error(`sessions.provide: missing prop "${c}"`);if(Object.hasOwn(n,c))throw new Error(`sessions.provide: duplicate prop "${c}"`);n[c]=o[c]}}return{sessionId:e.sessionId,hooks:t,props:n,projections:{faceOf:a(s=>e.session.projections.faceOf(s),"faceOf")}}}applyRosterChange(){this.maybeInfoCache=this.materializeMaybeInfo(),this.host.rebuildBundles(),this.publishCurrent()}materializeMaybeInfo(){const e={},t={};for(const n of this.providers){for(const s of n.hooks??[]){if(Object.hasOwn(e,s))throw new Error(`sessions.provide: duplicate hook "${s}"`);e[s]=void 0}for(const s of n.props??[]){if(Object.hasOwn(t,s))throw new Error(`sessions.provide: duplicate prop "${s}"`);t[s]=void 0}}return{sessionId:void 0,hooks:e,props:t}}},as=class extends Error{static{a(this,"SessionCreateError")}rpcError;requestedSessionId;name="SessionCreateError";constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},Mc=class extends Error{static{a(this,"SessionForkError")}rpcError;sourceSessionId;name="SessionForkError";constructor(e,t){super(`session fork failed: ${e.code}: ${e.message}`),this.rpcError=e,this.sourceSessionId=t}};function cs(e){return e.replace(/[/\\]+$/,"").split(/[/\\]/).pop()??""}a(cs,"workspaceTitleOf");function xc(e,t,n){if(e!==void 0)return e;if(t!==void 0&&t!==""){const s=cs(t);if(s!=="")return s}return n}a(xc,"displayTitleOf");function qc(e){const t=/^(.*?)\((\d+)\)$/u.exec(e);if(t?.[1]!==void 0&&t[2]!==void 0)return`${t[1]}(${BigInt(t[2])+1n})`;const n=/^(.*?)((\d+))$/u.exec(e);return n?.[1]!==void 0&&n[2]!==void 0?`${n[1]}(${BigInt(n[2])+1n})`:`${e} (1)`}a(qc,"increasedForkTitle");var us=class{static{a(this,"SessionRuntime")}rootCtx;searchResultLimit=20;list;manager;currentProvideInfo;selection;scopes=new Map;provideChannel;watched;deferredRemovals=new Set;constructor(e,t,n,s){this.rootCtx=e,this.selection=fe({},{persist:{name:"dsh.sessions.current"}});const r=this.selection.getSnapshot(),i=e.get("conversationEvents"),o=e.get("conversationViews"),c=s??(i===void 0||o===void 0?void 0:{events:i,views:o});this.manager=new Nc(t,n,r.sessionId,r.subagentAddress,c),this.list=fe({ids:[],byId:{},current:void 0,phase:"pending",subagentsByParent:{},jobsBySession:{},currentAddress:void 0}),this.manager.subscribe(()=>{this.projectList()}),this.list.subscribe(()=>{this.followCurrent(),this.provideChannel.publishCurrent()}),this.provideChannel=new os({rebuildBundles:a(()=>{for(const h of this.scopes.values())h.provideInfo=this.provideChannel.materializeInfo(h.binding)},"rebuildBundles"),resolveCurrent:a(()=>this.maybeProvideInfo(this.list.getSnapshot().current),"resolveCurrent")}),this.currentProvideInfo=this.provideChannel.currentProvideInfo;let d=!1;const u=a(()=>{d||(d=!0,queueMicrotask(()=>{d=!1,this.manager.rebuildConversationRegistry()}))},"scheduleRegistryRebuild");c!==void 0&&e.effect(()=>{const h=c.events.subscribe(u),m=c.views.subscribe(u);return()=>{h(),m()}},"sessions: conversation registry rebuild"),e.reflect.provide("sessions",this,void 0)}provide(e){return this.provideChannel.provide(e)}open(e){this.manager.select(e)}openSubagent(e){this.manager.selectSubagent(e)}subagentAddress(e){return this.manager.subagentAddress(e)}setSubagentCatalogOpen(e,t){this.manager.setSubagentCatalogOpen(e,t)}refreshSubagents(e){return this.manager.refreshSubagents(e)}noteAgentPreset(e,t){this.manager.noteAgentPreset(e,t)}clear(){this.manager.clearSelection()}refresh(){return this.manager.refreshList()}search(e,t){return this.manager.search(e,t)}handleMuxEnvelope(e){this.manager.handleMuxEnvelope(e)}handleHostEnvelope(e){this.manager.handleHostEnvelope(e)}handleConnected(){this.manager.handleConnected()}handleDisconnected(){this.manager.handleDisconnected()}async create(e={}){const t=await this.manager.create(e);if(!t.ok)throw new as(t.error,e.sessionId);return this.projectList(),t.value.sessionId}async fork(e){const t=e.increaseTitle?this.list.getSnapshot().byId[e.sessionId]?.title:void 0,n=await this.manager.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:Math.floor(e.atSeq)}});if(!n.ok)throw new Mc(n.error,e.sessionId);this.projectList();const s=n.value.sessionId;if(t!==void 0){const r=this.binding(s)?.session;if(r===void 0)throw new Error(`fork child "${s}" is not locally addressable`);const i=await r.rename(qc(t));if(!i.ok)throw new Error(`fork child rename failed: ${i.error.code}: ${i.error.message}`)}return s}scope(e){return this.resolve(e)?.ctx}scopeOf(e){return Re(e)}sessionOf(e){const t=Re(e);if(t!==void 0)return this.scopes.get(t)?.binding.session}binding(e){return this.resolve(e)?.binding}provideInfo(e){return this.resolve(e)?.provideInfo}maybeProvideInfo(e){return(e===void 0?void 0:this.provideInfo(e))??this.provideChannel.maybeInfo}followCurrent(){const e=this.list.getSnapshot(),t=e.current;if(t===void 0||e.byId[t]===void 0||t===this.watched)return;this.watched=t,this.sweepDeferred();const n=this.resolve(t);n!==void 0&&(n.session.open(),this.manager.refreshSubagents(t))}resolve(e){const t=this.scopes.get(e);if(t!==void 0)return t;if(!this.eligible(e))return;const{fiber:n,ctx:s}=Fn(this.rootCtx,e),r=this.manager.get(e);r.bindScope(s);const i={sessionId:e,session:r,ctx:s},o={fiber:n,ctx:s,binding:i,session:r,provideInfo:this.provideChannel.materializeInfo(i)};return this.scopes.set(e,o),o}eligible(e){const{ids:t,current:n}=this.list.getSnapshot();return n===e||t.includes(e)}projectList(){const{items:e,current:t,phase:n,subagentsByParent:s,jobsBySession:r,currentAddress:i}=this.manager.getListSnapshot(),o=[],c={};for(const u of e)o.push(u.sessionId),c[u.sessionId]={id:u.sessionId,displayTitle:xc(u.title,u.cwd,u.sessionId),running:u.running,...u.completed?{completed:!0}:{},blank:u.blank,updatedAt:u.updatedAt,...u.pendingInteraction===void 0?{}:{pendingInteraction:u.pendingInteraction},...u.projectionValues===void 0?{}:{projectionValues:u.projectionValues},...u.title!==void 0?{title:u.title}:{},...u.cwd!==void 0?{cwd:u.cwd}:{},...u.parentSessionId!==void 0?{parentId:u.parentSessionId}:{},...u.origin!==void 0?{origin:u.origin}:{},...u.agentPreset!==void 0?{agentPreset:u.agentPreset}:{}};if(t!==void 0&&i!==void 0){const u=new Set;let h=i;for(;h!==void 0&&!u.has(h.childSessionId);){const m=h.childSessionId;u.add(m);const v=s[h.parentSessionId]?.entries.find(_=>_.kind==="child"&&_.id===m);if(v?.kind!=="child")break;const b=v.label??m,z=c[m];z===void 0?c[m]={id:m,displayTitle:b,parentId:h.parentSessionId,origin:"subagent",running:v.activity==="running",blank:!1,updatedAt:0}:z.displayTitle!==b&&(c[m]={...z,displayTitle:b});const p=c[h.parentSessionId];if(p!==void 0&&p.origin!=="subagent")break;h=this.manager.navigationAddress(h.parentSessionId)}}const d=this.selection.getSnapshot().sessionId;t===void 0?d!==void 0&&this.selection.set({}):c[t]!==void 0&&(d!==t||this.selection.getSnapshot().subagentAddress?.childSessionId!==i?.childSessionId||this.selection.getSnapshot().subagentAddress?.parentSessionId!==i?.parentSessionId||this.selection.getSnapshot().subagentAddress?.mode!==i?.mode)&&this.selection.set({sessionId:t,...i===void 0?{}:{subagentAddress:i}}),this.list.set({ids:o,byId:c,current:t,phase:n,subagentsByParent:s,jobsBySession:r,currentAddress:i}),this.pruneScopes()}pruneScopes(){for(const[e,t]of this.scopes)if(!this.eligible(e)){if(e===this.watched){this.deferredRemovals.add(e);continue}this.scopes.delete(e),this.deferredRemovals.delete(e),this.dropScope(e,t)}}dropScope(e,t){t.fiber.dispose(),t.session.unbindScope(),this.rootCtx.get("slots")?.pruneStoreScope(e),this.manager.drop(e)}sweepDeferred(){for(const e of[...this.deferredRemovals]){if(e===this.watched)continue;if(this.eligible(e)){this.deferredRemovals.delete(e);continue}const t=this.scopes.get(e);this.deferredRemovals.delete(e),t!==void 0&&(this.scopes.delete(e),this.dropScope(e,t))}}},wt=class{static{a(this,"Workspace")}api;view;intent;materialization=null;snapshotCache;notifier=new ne(()=>{this.snapshotCache=this.buildSnapshot()});constructor(e,t){this.api=e,"workspaceId"in t?this.view=t:this.intent={input:t,snapshot:{name:Rc(t),phase:"ready"}},this.snapshotCache=this.buildSnapshot()}materialize(){if(this.materialization!==null)return this.materialization;const e=this.intent;if(e===void 0)return;e.snapshot={name:e.snapshot.name,phase:"creating"},this.notifier.notifyNow();const t=this.completeMaterialization(e).finally(()=>{this.materialization===t&&(this.materialization=null)});return this.materialization=t,t}adopt(e){if(this.view!==void 0&&this.view.workspaceId!==e.workspaceId)throw new Error("cannot adopt a different Workspace id");this.view=e,this.intent=void 0,this.notifier.markDirty()}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}async completeMaterialization(e){let t;try{t=(await this.api.workspace.create(e.input)).result}catch(n){t=M(n)}return this.intent!==e||(t.ok?this.adopt(t.value.workspace):(e.snapshot={name:e.snapshot.name,phase:"ready",error:`${t.error.code}: ${t.error.message}`},this.notifier.markDirty())),t}buildSnapshot(){return{view:this.view,intent:this.intent?.snapshot}}};function Rc(e){return e.path.replace(/[\\/]+$/,"").split(/[\\/]/).pop()??e.path}a(Rc,"intentName");var jc=class{static{a(this,"WorkspaceManager")}api;items=[];itemViewsSource=null;itemViewsCache=[];archivedSessionIds=[];state="idle";phase="pending";error=null;inflight=null;refreshFrames=null;archivedSupersedesRefresh=!1;orderRequestGeneration=0;orderFrameGeneration=0;committedOrder=[];removedIds=new Set;snapshotCache;notifier=new ne(()=>{this.snapshotCache=this.buildSnapshot()});constructor(e){this.api=e,this.snapshotCache=this.buildSnapshot()}refresh(){if(this.inflight!==null)return this.inflight;this.state="loading",this.error=null;const e=[];return this.refreshFrames=e,this.notifier.markDirty(),this.inflight=(async()=>{try{const{result:t}=await this.api.workspace.list({});if(t.ok){let n=t.value.items;n=n.filter(s=>!this.removedIds.has(s.workspaceId));for(const s of e)n=Bc(n,s);this.installViews(n),this.archivedSupersedesRefresh||this.installArchived(t.value.archivedSessionIds),this.state="idle",this.phase="ready"}else this.state="error",this.error=t.error}catch(t){this.state="error";const n=M(t);this.error=n.ok?null:n.error}finally{this.refreshFrames=null,this.archivedSupersedesRefresh=!1,this.inflight=null,this.notifier.markDirty()}})(),this.inflight}async create(e){const t=new wt(this.api,e),n=t.materialize();if(n===void 0)throw new Error("a local Workspace must be materializable");const s=await n;return s.ok&&this.upsert(s.value.workspace,t),s}async rename(e,t){const{result:n}=await this.api.workspace.rename({workspaceId:e,title:t});return n.ok&&this.upsert(n.value.workspace),n}async delete(e){const{result:t}=await this.api.workspace.delete({workspaceId:e});return t.ok&&this.remove(e,!0),t}async insertBefore(e,t){const n=++this.orderRequestGeneration,s=this.orderFrameGeneration,r=this.itemViews().map(o=>o.workspaceId);this.installOrder(Lc(r,e,t));let i;try{({result:i}=await this.api.workspace.insertBefore({workspaceId:e,...t===void 0?{}:{beforeWorkspaceId:t}}))}catch(o){throw n===this.orderRequestGeneration&&s===this.orderFrameGeneration&&this.installOrder(this.committedOrder),o}return i.ok&&n===this.orderRequestGeneration&&s===this.orderFrameGeneration?this.installOrder(i.value.workspaceIds,!0):!i.ok&&n===this.orderRequestGeneration&&s===this.orderFrameGeneration&&this.installOrder(this.committedOrder),i}async insertSessionBefore(e,t,n){const{result:s}=await this.api.workspace.insertSessionBefore({workspaceId:e,sessionId:t,...n===void 0?{}:{beforeSessionId:n}});return s.ok&&this.upsert(s.value.workspace),s}async archiveSession(e){const{result:t}=await this.api.workspace.archiveSession({sessionId:e});return t.ok&&this.installArchived(t.value.archivedSessionIds),t}handleHostEnvelope(e){e.payload.type==="host/workspace-changed"?this.upsert(e.payload.workspace):e.payload.type==="host/workspace-removed"?this.remove(e.payload.workspaceId):e.payload.type==="host/workspace-order-changed"?(this.orderFrameGeneration++,this.installOrder(e.payload.workspaceIds,!0)):e.payload.type==="host/archived-sessions-changed"&&this.installArchived(e.payload.archivedSessionIds)}handleConnected(){this.refresh()}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}buildSnapshot(){return{items:this.itemViews(),archivedSessionIds:this.archivedSessionIds,state:this.state,phase:this.phase,error:this.error}}installArchived(e){this.refreshFrames!==null&&(this.archivedSupersedesRefresh=!0),!(e.length===this.archivedSessionIds.length&&e.every((t,n)=>t===this.archivedSessionIds[n]))&&(this.archivedSessionIds=[...e],this.notifier.markDirty())}installOrder(e,t=!1){t&&(this.refreshFrames?.push({type:"order",workspaceIds:e}),this.committedOrder=[...e]);const n=new Map(e.map((r,i)=>[r,i])),s=[...this.items].sort((r,i)=>{const o=r.getSnapshot().view?.workspaceId,c=i.getSnapshot().view?.workspaceId;return(o===void 0?Number.MAX_SAFE_INTEGER:n.get(o)??Number.MAX_SAFE_INTEGER)-(c===void 0?Number.MAX_SAFE_INTEGER:n.get(c)??Number.MAX_SAFE_INTEGER)});s.every((r,i)=>r===this.items[i])||(this.items=s,this.notifier.markDirty())}upsert(e,t){if(this.removedIds.has(e.workspaceId))return;this.refreshFrames?.push({type:"upsert",workspace:e});const n=this.items.findIndex(r=>r.getSnapshot().view?.workspaceId===e.workspaceId),s=n===-1?void 0:this.items[n]?.getSnapshot().view;s!==void 0&&Date.parse(e.updatedAt)<Date.parse(s.updatedAt)||(this.committedOrder.includes(e.workspaceId)||(this.committedOrder=[e.workspaceId,...this.committedOrder]),t!==void 0?this.items=n===-1?[t,...this.items]:this.items.map((r,i)=>i===n?t:r):n===-1?this.items=[new wt(this.api,e),...this.items]:(this.items[n]?.adopt(e),this.items=[...this.items]),this.notifier.markDirty())}remove(e,t=!1){this.refreshFrames?.push({type:"remove",workspaceId:e}),this.removedIds.add(e),this.committedOrder=this.committedOrder.filter(s=>s!==e);const n=this.items.filter(s=>s.getSnapshot().view?.workspaceId!==e);if(n.length===this.items.length){t&&this.notifier.notifyNow();return}this.items=n,t?this.notifier.notifyNow():this.notifier.markDirty()}installViews(e){const t=new Map(this.items.flatMap(s=>{const r=s.getSnapshot().view;return r===void 0?[]:[[r.workspaceId,s]]})),n=new Map;for(const s of e){const r=n.get(s.workspaceId);if(r!==void 0){r.adopt(s);continue}const i=t.get(s.workspaceId)??new wt(this.api,s);i.adopt(s),n.set(s.workspaceId,i)}this.items=[...n.values()],this.committedOrder=e.map(s=>s.workspaceId)}itemViews(){return this.itemViewsSource===this.items?this.itemViewsCache:(this.itemViewsSource=this.items,this.itemViewsCache=this.items.flatMap(e=>{const t=e.getSnapshot().view;return t===void 0?[]:[t]}),this.itemViewsCache)}};function Fc(e,t){const n=e.findIndex(s=>s.workspaceId===t.workspaceId);return n===-1?[t,...e]:e.map((s,r)=>r===n?t:s)}a(Fc,"upsertWorkspace");function Bc(e,t){if(t.type==="upsert")return Fc(e,t.workspace);if(t.type==="remove")return e.filter(s=>s.workspaceId!==t.workspaceId);const n=new Map(t.workspaceIds.map((s,r)=>[s,r]));return[...e].sort((s,r)=>(n.get(s.workspaceId)??Number.MAX_SAFE_INTEGER)-(n.get(r.workspaceId)??Number.MAX_SAFE_INTEGER))}a(Bc,"applyWorkspaceDelta");function Lc(e,t,n){if(!e.includes(t)||n!==void 0&&!e.includes(n)||n===t)return[...e];const s=e.filter(i=>i!==t),r=n===void 0?s.length:s.indexOf(n);return[...s.slice(0,r),t,...s.slice(r)]}a(Lc,"insertIdBefore");var ds=class extends Error{static{a(this,"WorkspaceCreateError")}rpcError;constructor(e){super(`workspace create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.name="WorkspaceCreateError"}},bt=class extends Error{static{a(this,"DirectoryBrowseError")}rpcError;constructor(e){super(`directory browse failed: ${e.code}: ${e.message}`),this.rpcError=e,this.name="DirectoryBrowseError"}},ls=class{static{a(this,"WorkspaceRuntime")}api;sessions;list;manager;connecting=new Map;initialSelectionStarted=!1;constructor(e,t,n){this.api=t,this.sessions=n,this.manager=new jc(t),this.list=fe({items:[],archivedSessionIds:[],state:"idle",phase:"pending",error:null,baselinesReady:!1,recentWorkspaceId:void 0}),this.manager.subscribe(()=>{this.project()}),this.sessions.list.subscribe(()=>{this.project()}),e.reflect.provide("workspaces",this,void 0)}async connectWorkspace(e){const t=this.list.getSnapshot().items.find(o=>o.workspaceId===e);if(t===void 0)throw new Error(`workspaces.connectWorkspace: unknown workspace ${e}`);const n=this.connecting.get(e);if(n!==void 0)return n;const s=this.list.getSnapshot().archivedSessionIds,r=this.sessions.list.getSnapshot();for(const o of r.ids){const c=r.byId[o];if(c!==void 0&&c.blank&&c.cwd===t.path&&t.sessionIds.includes(c.id)&&!s.includes(c.id))return c.id}const i=this.sessions.create({workspaceId:e}).finally(()=>{this.connecting.delete(e)});return this.connecting.set(e,i),i}startInitialSelection(){if(this.initialSelectionStarted)throw new Error("workspaces.startInitialSelection: already started");this.initialSelectionStarted=!0;let e="waiting",t=!1;const n=a(()=>{if(t||e!=="waiting")return;const r=this.list.getSnapshot();if(!r.baselinesReady)return;const i=this.sessions.list.getSnapshot().current,o=r.recentWorkspaceId;if(i!==void 0||o===void 0){e="done";return}e="connecting",this.connectWorkspace(o).then(c=>{t||(this.sessions.list.getSnapshot().current===void 0&&this.sessions.open(c),e="done")},c=>{t||(e="waiting",console.warn("initial workspace selection failed:",c))})},"reconcile"),s=this.list.subscribe(n);return n(),()=>{t=!0,s()}}startSession(e){const t=this.list.getSnapshot(),n=this.sessions.list.getSnapshot().current,s=n===void 0?void 0:t.items.find(i=>i.sessionIds.includes(n))?.workspaceId,r=e??s??t.recentWorkspaceId;if(r===void 0){this.sessions.clear();return}this.connectWorkspace(r).then(i=>{this.sessions.open(i)},i=>{console.warn("new session failed:",i)})}async create(e){const t=await this.manager.create(e);if(!t.ok)throw new ds(t.error);return t.value.workspace}async pickDirectory(){const e=await this.api.host.pickDirectory({});if(!e.result.ok)throw new Error(`directory picker failed: ${e.result.error.message}`);return e.result.value.path}async listDirectory(e,t){const n=await this.api.host.listDirectory(e===void 0?{}:{path:e},t);if(!n.result.ok)throw new bt(n.result.error);return n.result.value}async createDirectory(e,t){const n=await this.api.host.createDirectory({path:e,name:t});if(!n.result.ok)throw new bt(n.result.error);return n.result.value.path}async openPath(e){const t=await this.api.host.openPath({path:e});if(!t.result.ok)throw new Error(`path open failed: ${t.result.error.message}`)}async rename(e,t){const n=await this.manager.rename(e,t);if(!n.ok)throw new Error(`workspace rename failed: ${n.error.code}: ${n.error.message}`);return n.value.workspace}async delete(e){const t=await this.manager.delete(e);if(!t.ok)throw new Error(`workspace delete failed: ${t.error.code}: ${t.error.message}`)}async insertBefore(e,t){const n=await this.manager.insertBefore(e,t);if(!n.ok)throw new Error(`workspace reorder failed: ${n.error.code}: ${n.error.message}`)}async archiveSession(e){const t=await this.manager.archiveSession(e);if(!t.ok)throw new Error(`session archive failed: ${t.error.code}: ${t.error.message}`)}async insertSessionBefore(e,t,n){const s=await this.manager.insertSessionBefore(e,t,n);if(!s.ok)throw new Error(`workspace move failed: ${s.error.code}: ${s.error.message}`);return s.value.workspace}refresh(){return this.manager.refresh()}handleHostEnvelope(e){this.manager.handleHostEnvelope(e)}handleConnected(){this.manager.handleConnected()}project(){const e=this.manager.getSnapshot(),t=this.sessions.list.getSnapshot(),n=e.phase==="ready"&&t.phase==="ready";t.current!==void 0&&e.archivedSessionIds.includes(t.current)&&this.sessions.clear(),this.list.set({items:e.items,archivedSessionIds:e.archivedSessionIds,state:e.state,phase:e.phase,error:e.error,baselinesReady:n,recentWorkspaceId:n?Uc(e.items,t.byId):void 0})}};function Uc(e,t){let n,s=Number.NEGATIVE_INFINITY;for(const r of e){let i=Number.NEGATIVE_INFINITY;for(const o of r.sessionIds){const c=t[o];c!==void 0&&(i=Math.max(i,c.updatedAt))}i===Number.NEGATIVE_INFINITY&&(i=Date.parse(r.createdAt)),(n===void 0||i>s)&&(n=r.workspaceId,s=i)}return n}a(Uc,"recentWorkspace");var hs=class extends Be.Service{static{a(this,"ConversationDefinitionRegistry")}definitions=new Map;listeners=new Set;cached=[];entries(){return this.cached}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}registerDefinition(e,t,n,s){if(this.definitions.has(e))throw new Error(n);const r=this.ctx.effect(()=>(this.definitions.set(e,t),this.refresh(),()=>{this.definitions.get(e)===t&&(this.definitions.delete(e),this.refresh())}),s);return()=>{r()}}refresh(){this.cached=[...this.definitions.values()];for(const e of this.listeners)e()}},fs=class extends hs{static{a(this,"ConversationEventRegistry")}fallback;constructor(e){super(e,"conversationEvents")}register(e){return ps(e),this.registerDefinition(e.kind,e,`conversation Definition "${e.kind}" is already registered`,`conversationEvents.register(${JSON.stringify(e.kind)})`)}registerFallback(e){if(ps(e),e.target===void 0)throw new Error("conversation fallback Definition must declare a target");if(this.fallback!==void 0)throw new Error("conversation fallback Definition is already registered");const t=this.ctx.effect(()=>(this.fallback=e,this.refresh(),()=>{this.fallback===e&&(this.fallback=void 0,this.refresh())}),`conversationEvents.registerFallback(${JSON.stringify(e.kind)})`);return()=>{t()}}fallbackEntry(){return this.fallback}};function ps(e){if(e.target===void 0!=(e.buildViewNode===void 0))throw new Error(`conversation Definition "${e.kind}" must declare target and buildViewNode together`)}a(ps,"assertDefinitionTarget");var ms=class extends hs{static{a(this,"ConversationViewRegistry")}constructor(e){super(e,"conversationViews")}register(e){return this.registerDefinition(e.target,e,`conversation view target "${e.target}" is already registered`,`conversationViews.register(${JSON.stringify(e.target)})`)}};const Vc=new Set(["user/message","assistant/message","tool/result"]);function gs(e){return Vc.has(e.type)?e.surfaceOp!==void 0:!1}a(gs,"isSurfaceEvent");function Wc(e){return gs(e)&&e.surfaceOp==="append"}a(Wc,"isAppendSurfaceEvent");function Jc(e){return gs(e)&&e.surfaceOp!=="append"}a(Jc,"isReplacementSurfaceEvent");function Gc(e){const t=new Map;for(const n of Object.values(e)){if(n.origin!=="subagent")continue;const s=new Set;let r=n;for(;r?.origin==="subagent"&&r.parentId!==void 0&&!s.has(r.id);){s.add(r.id);const i=t.get(r.parentId);i===void 0?t.set(r.parentId,{count:1,runningCount:n.running?1:0}):(i.count+=1,n.running&&(i.runningCount+=1)),r=e[r.parentId]}}return t}a(Gc,"indexSubagentDescendants");function Kc(e,t){return t.startsWith("/")||/^[A-Za-z]:[/\\]/.test(t)||t.startsWith("\\\\")||e===void 0||e===""?t:`${e.replace(/[/\\]+$/,"")}/${t.replace(/^[/\\]+/,"")}`}a(Kc,"resolveWorkspacePath");function Yc(e){switch(e){case"text":return{kind:"text",text:""};case"reasoning":return{kind:"reasoning",text:""};case"tool-call":return{kind:"tool-call",callId:"",name:"",argsRaw:""};default:return{kind:"other",block:null}}}a(Yc,"emptyAssistantBlock");function Hc(e){switch(e.type){case"text-delta":case"reasoning-delta":return e.text!=="";case"tool-call-delta":return e.argumentsDelta!==""||e.name!==void 0;default:return!1}}a(Hc,"isTokenDelta");function _t(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}a(_t,"asRecord");function ge(e,t){const n=e[t];return typeof n=="string"&&n.length>0?n:null}a(ge,"readString");function vs(e,t,n){const s=e[t];if(!Array.isArray(s))return[];const r=[];for(const i of s){const o=_t(i),c=o===null?null:ge(o,n);c!==null&&!r.includes(c)&&r.push(c)}return r}a(vs,"collect");function ys(e){return e.length>0?e.join(", "):null}a(ys,"joined");function Xc(e){const t=_t(e),n=t===null?null:ge(t,"kind");if(t===null||n===null)return{role:"inject",label:null};switch(n){case"session-reference":return{role:"recall",label:ys(vs(t,"references","label"))??n};case"agent-instructions":return{role:"inject",label:ys(vs(t,"changes","path"))??n};case"plugin":return{role:"inject",label:ge(t,"plugin")??n};case"skill-invocation":return{role:"inject",label:ge(t,"name")??n};default:return{role:"inject",label:n}}}a(Xc,"contextProvenance");const Qc=["instructions","catalog","snapshot","notice","relay","recall"];function eu(e){const t=_t(e),n=t===null?null:ge(t,"form");return n!==null&&Qc.includes(n)?n:null}a(eu,"contextForm");function tu(e){if(e===null||typeof e!="object")return String(e);const t=e;return t.code==="AUTH"?"API key is invalid":typeof t.message=="string"?t.message:JSON.stringify(e)}a(tu,"displayFailureMessage");const nu=["connection","typert","remote","remote.commands"];function su(e){e.plugin(Le);const t={events:new fs(e),views:new ms(e)},n=e.get("connection"),s=new us(e,n.api,e.remote,t);e.typert.contexts.registerClient("agent",{identity:a(o=>s.scopeOf(o),"identity")});const r=new ls(e,n.api,s);e.effect(()=>r.startInitialSelection(),"runtime: initial Workspace selection");const i=n.start({onMuxEnvelope:a(o=>{s.handleMuxEnvelope(o)},"onMuxEnvelope"),onHostEnvelope:a(o=>{s.handleHostEnvelope(o),r.handleHostEnvelope(o);const c=o.payload;c.type==="host/remote-event"&&e.remote.$dispatch(c.event,c.args)},"onHostEnvelope"),onConnected:a(()=>{s.handleConnected(),r.handleConnected(),e.emit("connection/reset")},"onConnected"),onStateChange:a(o=>{o==="reconnecting"&&s.handleDisconnected()},"onStateChange")});e.effect(()=>()=>{i.stop()},"runtime: connection stream loop")}return a(su,"apply"),k.ConversationEventRegistry=fs,k.ConversationLocationIndex=Jn,k.ConversationNodeAssembler=gt,k.ConversationViewRegistry=ms,k.DirectoryBrowseError=bt,k.EMPTY_CHAT_SNAPSHOT=Qn,k.EMPTY_CONVERSATION_VIEWS=$c,k.PendingWait=yt,k.SessionCreateError=as,k.SessionProvideChannel=os,k.SessionRuntime=us,k.SlotRegistry=Le,k.WorkspaceCreateError=ds,k.WorkspaceRuntime=ls,k.apply=su,k.contextForm=eu,k.contextProvenance=Xc,k.conversationContextKey=ht,k.createScope=Fn,k.createSnapshotStore=fe,k.defineStore=gc,k.displayFailureMessage=tu,k.emptyAssistantBlock=Yc,k.indexSubagentDescendants=Gc,k.inject=nu,k.isAppendSurfaceEvent=Wc,k.isReplacementSurfaceEvent=Jc,k.isTokenDelta=Hc,k.resolveWorkspacePath=Kc,k.scopeOf=Re,k.shallowEqual=fc,k.toAssistantBlock=Xn,k.toAssistantBlocks=Ic,k.workspaceTitleOf=cs,we.exports},"factory")});