@codexhost/cli-win32-x64 0.32.1 → 0.34.0

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 (159) hide show
  1. package/README.md +2 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +559 -15
  4. package/app/console-web.js +1361 -192
  5. package/app/desktop-controller.mjs +620 -16
  6. package/app/desktop-mcp-client.mjs +619 -0
  7. package/app/host-runtime.mjs +10370 -5625
  8. package/app/plugins/antigravity/plugin.mjs +888 -73
  9. package/app/plugins/claude-code/assets/icon.svg +1 -1
  10. package/app/plugins/claude-code/manifest.json +1 -1
  11. package/app/plugins/claude-code/plugin.mjs +1280 -198
  12. package/app/plugins/codebuddy/plugin.mjs +643 -35
  13. package/app/plugins/codex-usage/plugin.mjs +544 -12
  14. package/app/plugins/copilot/assets/icon.svg +1 -1
  15. package/app/plugins/copilot/manifest.json +1 -1
  16. package/app/plugins/copilot/plugin.mjs +546 -14
  17. package/app/plugins/cursor-cli/plugin.mjs +544 -12
  18. package/app/plugins/deepseek-harness/assets/icon.svg +1 -1
  19. package/app/plugins/deepseek-harness/manifest.json +1 -1
  20. package/app/plugins/deepseek-harness/plugin.mjs +983 -153
  21. package/app/plugins/devin/assets/icon.svg +1 -1
  22. package/app/plugins/devin/manifest.json +1 -1
  23. package/app/plugins/devin/plugin.mjs +546 -13
  24. package/app/plugins/enabled.json +1 -0
  25. package/app/plugins/grok/plugin.mjs +544 -12
  26. package/app/plugins/hermes/plugin.mjs +544 -12
  27. package/app/plugins/kimi-code/plugin.mjs +544 -12
  28. package/app/plugins/kiro-cli/plugin.mjs +544 -12
  29. package/app/plugins/omp/assets/icon.svg +1 -1
  30. package/app/plugins/omp/plugin.mjs +1381 -243
  31. package/app/plugins/opencode/plugin.mjs +548 -13
  32. package/app/plugins/pi/assets/icon.svg +1 -1
  33. package/app/plugins/pi/manifest.json +1 -1
  34. package/app/plugins/pi/plugin.mjs +572 -14
  35. package/app/plugins/qoder/assets/icon.svg +1 -1
  36. package/app/plugins/qoder/plugin.mjs +570 -12
  37. package/app/plugins/qoder-cn/assets/icon.svg +1 -1
  38. package/app/plugins/qoder-cn/plugin.mjs +570 -12
  39. package/app/plugins/qwen-code/assets/icon.svg +1 -1
  40. package/app/plugins/qwen-code/plugin.mjs +573 -12
  41. package/app/plugins/workbuddy/plugin.mjs +1263 -472
  42. package/app/plugins/workbuddy-cn/assets/icon.svg +27 -0
  43. package/app/plugins/workbuddy-cn/manifest.json +32 -0
  44. package/app/plugins/workbuddy-cn/plugin.mjs +36211 -0
  45. package/app/plugins/zcode/plugin.mjs +564 -19
  46. package/app/renderer-extension.js +2932 -262
  47. package/app/web/assets/{abnfDiagram-XWFEHMT6-7XITZmBH.js → abnfDiagram-XWFEHMT6-Cg-E7mc4.js} +1 -1
  48. package/app/web/assets/{architectureDiagram-CSQXQB3N-C8Usdzd8.js → architectureDiagram-CSQXQB3N-B__CwXjW.js} +1 -1
  49. package/app/web/assets/{blockDiagram-BEDRHYPZ-CyN9yE_Q.js → blockDiagram-BEDRHYPZ-Bk2gCIVM.js} +1 -1
  50. package/app/web/assets/{c4Diagram-M2UUVUY5-CjhY1l3g.js → c4Diagram-M2UUVUY5-DU_TpjJ3.js} +1 -1
  51. package/app/web/assets/{chunk-2Q5K7J3B-o24_rh4_.js → chunk-2Q5K7J3B-DnJEi6e4.js} +1 -1
  52. package/app/web/assets/{chunk-3GCGMST5-D7bw3E1a.js → chunk-3GCGMST5-Dia9jGkf.js} +1 -1
  53. package/app/web/assets/{chunk-5VM5RSS4-D0v4acf7.js → chunk-5VM5RSS4-2PGDiDvK.js} +1 -1
  54. package/app/web/assets/{chunk-7U7NFRK5-CYJxP4rV.js → chunk-7U7NFRK5-BLPm3d5H.js} +1 -1
  55. package/app/web/assets/{chunk-CNRTWJTD-DTgCtcCl.js → chunk-CNRTWJTD-GH_nAEXs.js} +1 -1
  56. package/app/web/assets/{chunk-D5HYT7QG-qRNelehW.js → chunk-D5HYT7QG-DnIm-Ely.js} +1 -1
  57. package/app/web/assets/{chunk-EBZ3SEQC-BgJPPYdu.js → chunk-EBZ3SEQC-C6N5qLCR.js} +2 -2
  58. package/app/web/assets/{chunk-JWPE2WC7-C50ZnSQQ.js → chunk-JWPE2WC7-D_kMgdmr.js} +1 -1
  59. package/app/web/assets/{chunk-KTR4FSNJ-Cifh4XHc.js → chunk-KTR4FSNJ-BRb9femQ.js} +1 -1
  60. package/app/web/assets/{chunk-XXDRQBXY-D23WAHPW.js → chunk-XXDRQBXY-BFaK95zq.js} +1 -1
  61. package/app/web/assets/{classDiagram-v2-KXABOMEV-B3cezFGj.js → classDiagram-v2-KXABOMEV--_hR_XrU.js} +1 -1
  62. package/app/web/assets/{cose-bilkent-JH36ORCC-VSMi4La2.js → cose-bilkent-JH36ORCC-C7ghEB3_.js} +1 -1
  63. package/app/web/assets/{cynefin-EF2NZ3EQ-qQnfHq16.js → cynefin-EF2NZ3EQ-Ce1lURwZ.js} +1 -1
  64. package/app/web/assets/{cynefinDiagram-NJNITYFG-BJELApXD.js → cynefinDiagram-NJNITYFG-Cgr5aSTS.js} +1 -1
  65. package/app/web/assets/{dagre-KIHZ2IZ3-C8B5ZMVs.js → dagre-KIHZ2IZ3-BBFKmRP1.js} +1 -1
  66. package/app/web/assets/{diagram-7YQZDPLS-HIWoNpzV.js → diagram-7YQZDPLS-CJQih32K.js} +1 -1
  67. package/app/web/assets/{diagram-QBROCOUO-3_vS1jbp.js → diagram-QBROCOUO-Cl3S7IUT.js} +1 -1
  68. package/app/web/assets/{diagram-RJJCUUZO-C_Kndn_e.js → diagram-RJJCUUZO-B6C8N2cV.js} +1 -1
  69. package/app/web/assets/{diagram-WERXNKYE-BLWdOwya.js → diagram-WERXNKYE-NkciBSQl.js} +1 -1
  70. package/app/web/assets/{diagram-YHHI257C-DJeOs6eS.js → diagram-YHHI257C-DlEvljeY.js} +1 -1
  71. package/app/web/assets/{diagram-YR4HJLHV-BKNULu-g.js → diagram-YR4HJLHV-e4_Gzbt6.js} +1 -1
  72. package/app/web/assets/{ebnfDiagram-N527522P-Bu8aReoF.js → ebnfDiagram-N527522P-WvQEFmPi.js} +1 -1
  73. package/app/web/assets/{elk-O5DQBFGD-CIp7Z0ER.js → elk-O5DQBFGD-CkyJsjzf.js} +1 -1
  74. package/app/web/assets/{erDiagram-K3K3BIDK-BTsor1Lp.js → erDiagram-K3K3BIDK-B93gK3X0.js} +1 -1
  75. package/app/web/assets/{flowDiagram-Z6JWZHQI-p_h5PKQr.js → flowDiagram-Z6JWZHQI-NFaGX6B4.js} +1 -1
  76. package/app/web/assets/{ganttDiagram-3PRQTZWP-DKjfPPJ1.js → ganttDiagram-3PRQTZWP-Czh68CQm.js} +1 -1
  77. package/app/web/assets/{gitGraphDiagram-VXDFKS5L-RnPOf2fj.js → gitGraphDiagram-VXDFKS5L-t95UHKja.js} +1 -1
  78. package/app/web/assets/{grid-E2QIVN74-C96GnBO1.js → grid-E2QIVN74-C87DucDN.js} +1 -1
  79. package/app/web/assets/index-CGI50Nfg.css +1 -0
  80. package/app/web/assets/index-Dr6wHi0A.js +208 -0
  81. package/app/web/assets/{infoDiagram-EZ3ZOAHP-B68eZHsb.js → infoDiagram-EZ3ZOAHP-CxFlfQbY.js} +1 -1
  82. package/app/web/assets/{ishikawaDiagram-S3EKX5GW-BLj7PFLt.js → ishikawaDiagram-S3EKX5GW-D4IwQJde.js} +1 -1
  83. package/app/web/assets/{journeyDiagram-POQNLL5X-Bo-_In0d.js → journeyDiagram-POQNLL5X-C0Bf5W4T.js} +1 -1
  84. package/app/web/assets/{kanban-definition-BH5XI6FM-BpHvxprW.js → kanban-definition-BH5XI6FM-Cda7r2yr.js} +1 -1
  85. package/app/web/assets/langs/{graphql-D6Z3qcRW.js → graphql-2R4AZ1iu.js} +1 -1
  86. package/app/web/assets/langs/{http-XiU9G9In.js → http-q2Qm0vBh.js} +1 -1
  87. package/app/web/assets/langs/{php-DL3xwS-7.js → php-Cz2gDBnd.js} +1 -1
  88. package/app/web/assets/langs/{rst-DudRVJ9g.js → rst-_9muvx-X.js} +1 -1
  89. package/app/web/assets/langs/{ruby-_FqsfqJi.js → ruby-cn7REk4H.js} +1 -1
  90. package/app/web/assets/langs/{svelte-ClsVJoBT.js → svelte-CPnL2mcy.js} +1 -1
  91. package/app/web/assets/langs/{vue-BiKMXCyK.js → vue-DO0YwyVz.js} +1 -1
  92. package/app/web/assets/{mermaid.core-COb9i2Gl.js → mermaid.core-f4LJm6AC.js} +5 -5
  93. package/app/web/assets/{mindmap-definition-WVAN44T4-DG15AlXd.js → mindmap-definition-WVAN44T4-DKapinG7.js} +1 -1
  94. package/app/web/assets/{pegDiagram-D4NLKWP3-GMBk8RM6.js → pegDiagram-D4NLKWP3-D7iEZGN2.js} +1 -1
  95. package/app/web/assets/{pieDiagram-36ENHN4W-BzeJgVnn.js → pieDiagram-36ENHN4W-CopXZ5qt.js} +1 -1
  96. package/app/web/assets/{quadrantDiagram-ZQUDMS73-C--Kif6a.js → quadrantDiagram-ZQUDMS73-mmkKPDGK.js} +1 -1
  97. package/app/web/assets/{railroadDiagram-JIZHGYPL-NPLVu_R7.js → railroadDiagram-JIZHGYPL-BAGwIIkV.js} +1 -1
  98. package/app/web/assets/{render-VIF2ZAQL-DdpQ8E0J.js → render-VIF2ZAQL-dXxGa09y.js} +2 -2
  99. package/app/web/assets/{requirementDiagram-AXW2TVFA-WWRwRbkA.js → requirementDiagram-AXW2TVFA-C35tmLFs.js} +1 -1
  100. package/app/web/assets/{sankeyDiagram-FBCJTAIF-hBr6pZ0V.js → sankeyDiagram-FBCJTAIF-BbSo5yeK.js} +1 -1
  101. package/app/web/assets/{sequenceDiagram-3LA2ROMG-DvzZWy5J.js → sequenceDiagram-3LA2ROMG-Cgm2unNy.js} +1 -1
  102. package/app/web/assets/{sizeCapture-2Q2CQKSF-C2B86W70.js → sizeCapture-2Q2CQKSF-DCXFjl2x.js} +1 -1
  103. package/app/web/assets/{stateDiagram-v2-ATKHQDJO-Jwj3XqMx.js → stateDiagram-v2-ATKHQDJO-B349iAao.js} +1 -1
  104. package/app/web/assets/{swimlanes-YQL5WMAO-DxI0hC09.js → swimlanes-YQL5WMAO-6OvL1sEz.js} +1 -1
  105. package/app/web/assets/swimlanesDiagram-UCCPES4V-CIKaQUvP.js +8 -0
  106. package/app/web/assets/{timeline-definition-7Z437IG3-m8Ew8iuN.js → timeline-definition-7Z437IG3-Bh1E3mhW.js} +1 -1
  107. package/app/web/assets/{usecaseDiagram-RDK6N6HP-BsiPSzIT.js → usecaseDiagram-RDK6N6HP-Dr5A05lL.js} +1 -1
  108. package/app/web/assets/{vendor-BKfNgqAm.js → vendor-BMCjWFMy.js} +20 -20
  109. package/app/web/assets/{vennDiagram-SHRQU5PJ-yYfXhiGp.js → vennDiagram-SHRQU5PJ-CQPPBa27.js} +1 -1
  110. package/app/web/assets/{wardleyDiagram-F3OXNVQS-DHLEfnsg.js → wardleyDiagram-F3OXNVQS-BHin00q8.js} +1 -1
  111. package/app/web/assets/{xychartDiagram-GDYJKCDI-Drn_UxYt.js → xychartDiagram-GDYJKCDI-D4BAWlQZ.js} +1 -1
  112. package/app/web/codex-agent.png +0 -0
  113. package/app/web/codex.png +0 -0
  114. package/app/web/codexhost-settings.js +337 -137
  115. package/app/web/index.html +3 -3
  116. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +65 -65
  117. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  118. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +75 -75
  119. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +162 -74
  120. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +104 -100
  121. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  122. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +114 -2
  123. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +5 -5
  124. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +6 -6
  125. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +80 -80
  126. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
  127. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +69 -69
  128. package/app/web/role-avatars/builtin/advisor-otter.webp +0 -0
  129. package/app/web/role-avatars/builtin/architect-otter.webp +0 -0
  130. package/app/web/role-avatars/builtin/audio-otter.webp +0 -0
  131. package/app/web/role-avatars/builtin/backend-otter.webp +0 -0
  132. package/app/web/role-avatars/builtin/builder-otter.webp +0 -0
  133. package/app/web/role-avatars/builtin/classic-otter.webp +0 -0
  134. package/app/web/role-avatars/builtin/data-otter.webp +0 -0
  135. package/app/web/role-avatars/builtin/debugger-otter.webp +0 -0
  136. package/app/web/role-avatars/builtin/frontend-otter.webp +0 -0
  137. package/app/web/role-avatars/builtin/idea-otter.webp +0 -0
  138. package/app/web/role-avatars/builtin/ops-otter.webp +0 -0
  139. package/app/web/role-avatars/builtin/pm-otter.webp +0 -0
  140. package/app/web/role-avatars/builtin/researcher-otter.webp +0 -0
  141. package/app/web/role-avatars/builtin/reviewer-otter.webp +0 -0
  142. package/app/web/role-avatars/builtin/sailor-otter.webp +0 -0
  143. package/app/web/role-avatars/builtin/scholar-otter.webp +0 -0
  144. package/app/web/role-avatars/builtin/security-otter.webp +0 -0
  145. package/app/web/role-avatars/builtin/tester-otter.webp +0 -0
  146. package/app/web/role-avatars/builtin/wizard-otter.webp +0 -0
  147. package/app/web/role-avatars/builtin/writer-otter.webp +0 -0
  148. package/app/web-modules/node_modules/@deepseek-ai/dsh-host-webserver/index.js +7 -1
  149. package/app/web-modules/server.mjs +6951 -2390
  150. package/bin/codexhost.exe +0 -0
  151. package/libexec/codexhost-node-repl.exe +0 -0
  152. package/libexec/codexhost-screenshot.exe +0 -0
  153. package/libexec/codexhost-shell.exe +0 -0
  154. package/libexec/codexhost-shim.exe +0 -0
  155. package/libexec/codexhost-updater.exe +0 -0
  156. package/package.json +1 -1
  157. package/app/web/assets/index-CDRWzs-u.js +0 -205
  158. package/app/web/assets/index-Dwdnvinl.css +0 -1
  159. package/app/web/assets/swimlanesDiagram-UCCPES4V-CR0nv8kJ.js +0 -8
@@ -1,6 +1,6 @@
1
- window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-api-session-controller`,factory:e=>{var t={exports:{}},n=t.exports;Object.defineProperty(n,Symbol.toStringTag,{value:`Module`});let r=e("@deepseek-ai/cordis"),i=e("@deepseek-ai/dsh-api-gateway/client"),a=e("@deepseek-ai/dsh-client-store");var o=class extends Error{code;details;isDSHRemoteError=!0;constructor(e,t,n,r){super(t,r),this.code=e,this.details=n,this.name=`RemoteError`}};let s=Symbol.for(`dsh.typert.owned-value`);function c(e,t){let n=!0;return{[s]:!0,value:e,[Symbol.dispose](){n&&(n=!1,t())}}}function l(e){return e}function u(e){return e.event.seq}function d(e){return e.event.seq}function f(e){return e}function p(e){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`SessionSeq must be a non-negative safe integer, got ${String(e)}`);return f(e)}function m(e){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(e)}`);return f(e)}let ee=/* @__PURE__ */ new Set(/* @__PURE__ */ `agent-preset/selected.agent/inbox/spliced.approval/asked.approval/decided.approval/policy.assistant/attempt.assistant/message.command/done.command/run.compaction/end.compaction/prune.compaction/start.compaction/summary.deliverables/presented.developer/message.feedback/message-delete.feedback/message-put.feedback/record.goal/change.hook/invoked.hook/result.image/offload.llm/retry.llm/retry-started.model/selection.permission/preset.plan/mode.request/context.request/header.sandbox/mode.schedule/change.session-log-deepseek/delivery-accepted.session/end-seed.session/title.session/title-llm-request.step/end.step/start.subagent/catalog.subagent/descriptor.subagent/model-selection-policy.system/message.team/member.team/message/delivered.team/message/queued.team/task.todo/write.tool-workflow/agent-end.tool-workflow/agent-start.tool-workflow/run-end.tool-workflow/run-start.tool/call.tool/ptc-dispatch.tool/ptc-dispatch-start.tool/result.turn/end.turn/start.user/message.web/deepseek-search-llm-request.workspace/changes`.split(`.`)),te=/* @__PURE__ */ new Set([`system/message`,`developer/message`,`user/message`,`assistant/message`,`tool/result`]);function ne(e){return te.has(e)}function re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ie(e,t){let n=e.data;if(te.has(e.type)&&re(n)){let r=e.type===`user/message`?n:n.message;if(re(r)){if(e.type===`developer/message`!=(r.role===`developer`))throw Error(`${t} developer/message and developer role must occur together`);if(r.role!==`developer`&&Array.isArray(r.content)&&r.content.some(e=>re(e)&&(e.type===`tool-addition`||e.type===`tool-removal`)))throw Error(`${t} tool-change blocks require developer role`);if(e.type===`developer/message`&&Array.isArray(r.content)){let e=!1;for(let n of r.content)if(!(!re(n)||n.type!==`tool-addition`&&n.type!==`tool-removal`)){if(typeof n.toolName!=`string`||n.toolName.length===0)throw Error(`${t} ${n.type} requires a nonempty toolName`);if(n.type===`tool-addition`&&(e=!0,Object.hasOwn(n,`tool`)))throw Error(`${t} tool-addition must omit inline tool definitions`)}if(e?!ae(n.headerSeq):Object.hasOwn(n,`headerSeq`))throw Error(`${t} requires headerSeq exactly when tool additions are present`)}}}if(e.type===`request/header`){if(!re(n))throw Error(`${t} data must be an object`);let e=n.header;if(!re(e))throw Error(`${t} header must be an object`);if(Object.hasOwn(e,`system`))throw Error(`${t} must omit header.system; use system/message`);if(Array.isArray(e.tools)&&e.tools.length===0)throw Error(`${t} must omit empty tools`);let r=e.adapterDefaults;if(re(r)&&Object.keys(r).length===0)throw Error(`${t} must omit empty adapterDefaults`)}else if(e.type===`tool/result`){if(!re(n))throw Error(`${t} data must be an object`);if(n.error===void 0)return;let e=n.message;if(!re(e)||e.isError!==!0)throw Error(`${t} error requires message.isError === true`)}}function ae(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}function oe(e){let t=e;return Object.keys(t).length===3&&Object.hasOwn(t,`op`)&&Object.hasOwn(t,`startSeq`)&&Object.hasOwn(t,`endSeq`)&&t.op===`replace`&&ae(t.startSeq)&&ae(t.endSeq)}function se(e){let t=e;if(!ne(e.type)){if(!ee.has(e.type)&&e.ignorable===!0)return;if(t.surfaceOp!==void 0)throw Error(`session event "${e.type}" is not surface-eligible and cannot carry surfaceOp`);if(t.sourceEventSeqs!==void 0)throw Error(`session event "${e.type}" is not surface-eligible and cannot carry sourceEventSeqs`);return}let n=t.surfaceOp;if(n===void 0)throw Error(`session event "${e.type}" is surface-eligible and requires a surfaceOp marker`);if(n===`append`)return n;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`session event "${e.type}" carries an invalid surfaceOp`);if(!oe(n))throw Error(`session event "${e.type}" carries an invalid replace surfaceOp`);return n}function ce(e,t){let n=e.sourceEventSeqs;if(e.type===`assistant/message`&&n!==void 0)throw Error(`assistant/message embeds its source stream and cannot carry sourceEventSeqs`);let r=/* @__PURE__ */ new Set;if(n!==void 0){if(!Array.isArray(n))throw Error(`sourceEventSeqs on event at seq ${e.seq} must be an array when present`);if(n.length===0)throw Error(`sourceEventSeqs must not be empty`);let t;for(let i of n){if(!ae(i))throw Error(`session event "${e.type}" sourceEventSeqs must densely contain non-negative safe integers`);r.add(i),t===void 0&&i>=e.seq&&(t=i)}if(r.size!==n.length)throw Error(`sourceEventSeqs must not contain duplicates`);if(t!==void 0)throw Error(`sourceEventSeqs must reference earlier events: ${t} >= current seq ${e.seq}`)}let i=t.filter(e=>!r.has(e));if(i.length>0)throw Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${i.join(`, `)}`)}function le(e){let t=se(e);if(t!==void 0&&t!==`append`&&(t.startSeq>=e.seq||t.endSeq>=e.seq))throw Error(`surface replace at seq ${e.seq}: startSeq and endSeq must reference earlier events`);return t!==void 0&&ce(e,[]),t}function ue(e){let t=`session wire event`;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);let n=e;for(let e of Object.keys(n))switch(e){case`type`:case`seq`:case`time`:case`data`:case`ignorable`:case`surfaceOp`:case`sourceEventSeqs`:break;default:throw Error(`${t} has unexpected field ${e}`)}let r=n.seq;if(typeof n.type!=`string`||typeof r!=`number`||!Number.isSafeInteger(r)||r<0||Object.is(r,-0)||typeof n.time!=`number`||!Number.isSafeInteger(n.time)||!Object.hasOwn(n,`data`)||n.data===void 0||Object.hasOwn(n,`ignorable`)&&n.ignorable!==!0)throw Error(`${t} has an invalid envelope`);let i=n;le(i),ie(i,t)}function de(e){switch(e.type){case`replace`:case`prepend`:return{...e,entries:l(e.entries)};case`append`:return{type:`append`,entry:e.entry};case`notification`:return e.notification}}function fe(e,t){let n=e.$stream({name:`session control stream`,open:t=>e.session.control(t),ended:e=>e?new i.RemoteStreamCarrierError(`session control stream ended without a terminal result`):/* @__PURE__ */ Error(`session control stream ended before its opening snapshot`),...t.carrierFailed===void 0?{}:{carrierFailed:t.carrierFailed}});return new i.RemoteSnapshotStream(n,{name:`session control stream`,isSnapshot:e=>e.type===`baseline`,replace:t.accept,update:t.accept,failed:t.failed})}var pe=class extends i.RemoteJournalStream{remote;address;journal;epoch;capture(){return this.journal&&{...this.journal,records:[...this.journal.records]}}get journalEpoch(){return this.epoch}constructor(e,t,n,r){super(e,{name:`session event stream`,emptyCursor:-1,entries:e=>e.records,hasMore:e=>e.hasMore,first:u,last:d,compare:(e,t)=>e-t,follows:(e,t)=>t===e+1,publish:e=>{this.epoch===void 0?this.journal=void 0:e.type===`replace`?this.journal={epoch:this.epoch,cursor:e.entries.at(-1)?.event.seq??-1,records:[...e.entries],hasMore:e.hasMore}:this.journal!==void 0&&e.type===`append`?(this.journal.cursor=e.entry.event.seq,this.journal.records.push(e.entry)):this.journal!==void 0&&e.type===`prepend`&&(this.journal.records.unshift(...e.entries),this.journal.hasMore=e.hasMore),n.publish(de(e))},...n.carrierFailed===void 0?{}:{carrierFailed:n.carrierFailed},failed:n.failed}),this.remote=e,this.address=t,this.journal=r&&{...r,records:[...r.records]},this.epoch=r?.epoch}async*follow(e,t){let n,r=this.journal;for await(let a of this.remote.session.follow({address:this.address,assistantStream:!0,...this.repairRequest(e),...r===void 0?{}:{resume:{epoch:r.epoch,cursor:r.cursor}}},t))if(a.type===`snapshot`){for(let e of a.records)ue(e.event);if(a.assistantStream===void 0)throw new o(`gateway/internal`,`session assistant stream omitted its opted-in opening baseline`,{});let e=a.records,t=a.hasMore;if(a.resumedAfter!==void 0){if(r===void 0||a.epoch!==r.epoch||a.resumedAfter!==r.cursor||a.cursor!==(e.at(-1)?.event.seq??r.cursor)||e.length>0&&e[0]?.event.seq!==r.cursor+1)throw new o(`gateway/internal`,`Invalid session resume baseline`,{});e=[...r.records,...e],t=r.hasMore}let i=a.epoch!==void 0&&a.epoch!==this.epoch;this.epoch=a.epoch,n=a.assistantStream.revision,yield{type:`opened`,...i?{reset:!0}:{},cursor:a.cursor,page:{records:e,hasMore:t,projections:a.projections,assistantStream:a.assistantStream}}}else if(a.type===`assistant-stream`){let e=(n??0)+1;if(a.frame.revision!==e)throw new i.RemoteStreamCarrierError(`session assistant stream skipped revision ${String(e)}`);n=a.frame.revision,yield{type:`notification`,notification:a}}else a.type===`projection`?yield{type:`notification`,notification:a}:(ue(a.event),yield{type:`entry`,entry:a})}async readPage(e,t,n){let r=await this.remote.session.page({address:this.address,throughSeq:t,...e},n);if(!r.ok)throw r.error;for(let e of r.value.records)ue(e.event);return r.value}repairRequest(e){return{...e.maxMessages===void 0?{}:{maxMessages:e.maxMessages},...e.turnWindow===void 0?{}:{turnWindow:e.turnWindow}}}};function me(e){let t=e.replace(/[/\\]+$/,``),n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));return t.slice(n+1)}let he=Symbol(`dsh.client.scope`);function ge(){}function _e(e,t){let n=e.plugin(ge),i={sessionId:t};return{fiber:n,ctx:n.ctx.extend({[he]:i,[r.Context.filter](e){let t=ye(e);return t===void 0||t===i}})}}function ve(e){return ye(e)?.sessionId}function ye(e){return e[he]}function be(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function xe(e,t=`|`){return e.map(e=>qe(e)).join(t)}function Se(e,t){return typeof t==`bigint`?t.toString():t}var Ce=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function we(e){return new Ce(e)}function Te(e){return e==null}function Ee(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function De(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}let Oe=/* @__PURE__*/ Symbol(`evaluating`);function ke(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Oe)return r===void 0&&(r=Oe,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ae(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function je(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function Me(e){return je(e._zod.def)??e._zod.def.shape}function Ne(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Ae(this,t,e),e},enumerable:!0,configurable:!0})}function Pe(e,t,n){t in e?Ae(e,t,n):e[t]=n}function Fe(e,t,n,r){let i=Me(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?Ne(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Pe(e,a,r?r(n.value,a):n.value))}}function Ie(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Ne(e,n,()=>t[n]):Pe(e,n,r.value))}}function h(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Le(e){return JSON.stringify(e)}function Re(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}let ze=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Be(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let Ve=/* @__PURE__*/ we(()=>{if(b.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function He(e){if(Be(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Be(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Ue(e){return He(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let We=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function Ge(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ke(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function g(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function qe(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Je(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}let Ye={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Xe={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function Ze(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return Fe(i,e,Qe(e,t)),Ke(e,h(n,{shape:i,checks:[]}))}function Qe(e,t){let n=Me(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function $e(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(Qe(e,t)),a={};return Fe(a,e,Reflect.ownKeys(Me(e)).filter(e=>!i.has(e))),Ke(e,h(n,{shape:a,checks:[]}))}function et(e,t){if(!He(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Me(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ke(e,h(e._zod.def,{shape:tt(e,t)}))}function tt(e,t){let n={};return Fe(n,e,Reflect.ownKeys(Me(e))),Ie(n,t),n}function nt(e,t){if(!He(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Ke(e,h(e._zod.def,{shape:tt(e,t)}))}function rt(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return Fe(n,e,Reflect.ownKeys(Me(e))),Fe(n,t,Reflect.ownKeys(Me(t))),Ke(e,h(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function it(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(Qe(t,n)):void 0,o={};return Fe(o,t,Reflect.ownKeys(Me(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),Ke(t,h(t._zod.def,{shape:o,checks:[]}))}function at(e,t,n){let r=n?new Set(Qe(t,n)):void 0,i={};return Fe(i,t,Reflect.ownKeys(Me(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),Ke(t,h(t._zod.def,{shape:i}))}function _(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}function ot(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}function st(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ct(e){return typeof e==`string`?e:e?.message}function lt(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function ut(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function dt(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:ct(e.inst?._zod.def?.error?.(e))??ct(a?.(e))??ct(t?.error?.(e))??ct(n.customError?.(e))??ct(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}let ft=/[\uD800-\uDBFF]/;function pt(e){let t=e.length;if(!ft.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function mt(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ht(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function gt(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function _t(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):xt(e,n,r.value)}}function vt(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function yt(e,t,n){return vt(e,t,n,!1)}function bt(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return vt(this,n,r(this))},set(e){vt(this,n,e)}})}return t}function xt(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:vt(this,t,n.bind(this))},set(e){vt(this,t,e)}})}function St(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Ct,wt=!1,Tt={configurable:!0,get(){wt=!0}};function v(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Ct!==e._zod?Ct=void 0:(Ct=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Tt);let e=wt;wt=!1;try{let r=n(this);return wt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),wt||=e,r}catch(n){throw delete this[t],wt||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Et(e,t,n,r){let i=St(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function Dt(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var Ot;let kt=/*@__PURE__*/ Object.freeze({status:`aborted`}),At={value:void 0,enumerable:!1},jt=`captureStackTrace`in Error?Error:null;function Mt(e){let t=jt;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return jt=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function y(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=/* @__PURE__ */ new Set}a.prototype=i;let o=n,s=o&&/* @__PURE__ */ new WeakSet;function c(n,r){if(!n._zod){At.value=new a(r);try{Object.defineProperty(n,"_zod",At)}finally{At.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),_t(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Mt(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Nt=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Pt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Ot=globalThis).__zod_globalConfig??(Ot.__zod_globalConfig={});let b=globalThis.__zod_globalConfig;function Ft(e){return e&&Object.assign(b,e),b}function It(){let e=this._zod;return e.message??=JSON.stringify(e.def,Se,2),e.message}function Lt(e){this._zod.message=e}let Rt={get:It,set:Lt,enumerable:!0,configurable:!0},zt={value:void 0,enumerable:!1},Bt=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Vt=(e,t)=>{e.name=`$ZodError`,zt.value=t,Object.defineProperty(e,"issues",zt),zt.value=void 0,Object.defineProperty(e,"message",Rt);let n=Object.getPrototypeOf(e);Bt.has(n)||(Bt.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Ht=y(`$ZodError`,Vt);y(`$ZodError`,Vt,void 0,{Parent:Error});function Ut(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Wt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Ut(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Gt(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function Kt(e,t){return{callee:t?.callee??e,Err:t?.Err}}let qt=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Nt;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>dt(e,o,Ft())));throw ze(n,a?.callee??t),n}return s.value};return t},Jt=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>dt(e,o,Ft())));throw ze(n,a?.callee??t),n}return s.value};return t},Yt=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Nt;return a.issues.length?Xt(e,a.issues,i):{success:!0,data:a.value}};function Xt(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>dt(e,n,Ft()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}let Zt=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?Xt(e,a.issues,i):{success:!0,data:a.value}},Qt=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),$t=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),en=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Qt)return!0;if(r.definite===!0&&n===void 0)return!1}return tn(e,t,n)});function tn(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[$t]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new Nt;return a.issues.length===0}let nn=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},rn=e=>{let t=qt(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Kt(n,a))};return n},an=e=>{let t=qt(e),n=(e,r,i,a)=>t(e,r,i,Kt(n,a));return n},on=e=>{let t=Jt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Kt(n,a))};return n},sn=e=>{let t=Jt(e),n=async(e,r,i,a)=>await t(e,r,i,Kt(n,a));return n},cn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Yt(e)(t,n,i)},ln=e=>(t,n,r)=>Yt(e)(t,n,r),un=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Zt(e)(t,n,i)},dn=e=>async(t,n,r)=>Zt(e)(t,n,r),fn=/^[cC][0-9a-z]{6,}$/,pn=/^[0-9a-z]+$/,mn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,hn=/^[0-9a-vA-V]{20}$/,gn=/^[A-Za-z0-9]{27}$/,_n=/^[a-zA-Z0-9_-]{21}$/;function vn(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}let yn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,bn=/^([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})$/,xn=e=>e?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)$/,Sn=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Cn(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}let wn=/^(?:(?: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])$/,Tn=/^(([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}|:))$/,En=/^((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])$/,Dn=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,On=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kn=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,An=/^https?$/,jn=/^\+[1-9]\d{6,14}$/,Mn=`(?:(?:\\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])))`;function Nn(e){return RegExp(`^${e}$`)}let Pn=/*@__PURE__*/ Nn(Mn);function Fn(e){let 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}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function In(e){return RegExp(`^${Fn(e)}$`)}function Ln(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Fn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Fn({precision:e.precision})}`:n;return RegExp(`^${Mn}T(?:${r})$`)}let Rn=/^[\s\S]{0,}$/,zn=/^-?\d+$/,Bn=/^-?\d+(?:\.\d+)?$/,Vn=/^(?:true|false)$/i,Hn=/^null$/i,Un=/^[^A-Z]*$/,Wn=/^[^a-z]*$/,x=/*@__PURE__*/ y(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Gn=e=>{let t=e.value;return!Te(t)&&t.length!==void 0},Kn={number:`number`,bigint:`bigint`,object:`date`},qn=/*@__PURE__*/ y(`$ZodCheckLessThan`,(e,t)=>{x.init(e,t);let n=Kn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Kn[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Jn=/*@__PURE__*/ y(`$ZodCheckGreaterThan`,(e,t)=>{x.init(e,t);let n=Kn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Kn[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yn=/*@__PURE__*/ y(`$ZodCheckMultipleOf`,(e,t)=>{x.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):De(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})}}),Xn=/*@__PURE__*/ y(`$ZodCheckNumberFormat`,(e,t)=>{x.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ye[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Zn=/*@__PURE__*/ y(`$ZodCheckMaxLength`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=Gn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?pt(r):i)<=t.maximum)return;let a=mt(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Qn=/*@__PURE__*/ y(`$ZodCheckMinLength`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=Gn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?pt(r):i)>=t.minimum)return;let a=mt(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$n=/*@__PURE__*/ y(`$ZodCheckLengthEquals`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=Gn),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?pt(r):i;if(a===t.length)return;let o=mt(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),er=/*@__PURE__*/ y(`$ZodCheckStringFormat`,(e,t)=>{var n,r;x.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),tr=/*@__PURE__*/ y(`$ZodCheckRegex`,(e,t)=>{er.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})}}),nr=/*@__PURE__*/ y(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Un,er.init(e,t)}),rr=/*@__PURE__*/ y(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Wn,er.init(e,t)}),ir=/*@__PURE__*/ y(`$ZodCheckIncludes`,(e,t)=>{x.init(e,t);let n=Ge(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),ar=/*@__PURE__*/ y(`$ZodCheckStartsWith`,(e,t)=>{x.init(e,t);let n=RegExp(`^${Ge(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),or=/*@__PURE__*/ y(`$ZodCheckEndsWith`,(e,t)=>{x.init(e,t);let n=RegExp(`.*${Ge(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),sr=/*@__PURE__*/ y(`$ZodCheckOverwrite`,(e,t)=>{x.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var cr=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
1
+ window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-api-session-controller`,factory:e=>{var t={exports:{}},n=t.exports;Object.defineProperty(n,Symbol.toStringTag,{value:`Module`});let r=e("@deepseek-ai/cordis"),i=e("@deepseek-ai/dsh-api-gateway/client"),a=e("@deepseek-ai/dsh-client-store");var o=class extends Error{code;details;isDSHRemoteError=!0;constructor(e,t,n,r){super(t,r),this.code=e,this.details=n,this.name=`RemoteError`}};let s=Symbol.for(`dsh.typert.owned-value`);function c(e,t){let n=!0;return{[s]:!0,value:e,[Symbol.dispose](){n&&(n=!1,t())}}}function l(e){return e}function u(e){return e.event.seq}function d(e){return e.event.seq}function f(e){return e}function p(e){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`SessionSeq must be a non-negative safe integer, got ${String(e)}`);return f(e)}function m(e){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(e)}`);return f(e)}let ee=/* @__PURE__ */ new Set(/* @__PURE__ */ `agent-preset/selected.agent/inbox/spliced.approval/asked.approval/decided.approval/policy.assistant/attempt.assistant/message.command/done.command/run.compaction/end.compaction/prune.compaction/start.compaction/summary.deliverables/presented.developer/message.feedback/message-delete.feedback/message-put.feedback/record.goal/change.hook/invoked.hook/result.image/offload.llm/retry.llm/retry-started.model/selection.permission/preset.plan/mode.request/context.request/header.sandbox/mode.schedule/change.session-log-deepseek/delivery-accepted.session/end-seed.session/title.session/title-llm-request.step/end.step/start.subagent/catalog.subagent/descriptor.subagent/model-selection-policy.system/message.team/member.team/message/delivered.team/message/queued.team/task.todo/write.tool-workflow/agent-end.tool-workflow/agent-start.tool-workflow/run-end.tool-workflow/run-start.tool/call.tool/ptc-dispatch.tool/ptc-dispatch-start.tool/result.turn/end.turn/start.user/message.web/deepseek-search-llm-request.workspace/changes`.split(`.`)),te=/* @__PURE__ */ new Set([`system/message`,`developer/message`,`user/message`,`assistant/message`,`tool/result`]);function ne(e){return te.has(e)}function re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ie(e,t){let n=e.data;if(te.has(e.type)&&re(n)){let r=e.type===`user/message`?n:n.message;if(re(r)){if(e.type===`developer/message`!=(r.role===`developer`))throw Error(`${t} developer/message and developer role must occur together`);if(r.role!==`developer`&&Array.isArray(r.content)&&r.content.some(e=>re(e)&&(e.type===`tool-addition`||e.type===`tool-removal`)))throw Error(`${t} tool-change blocks require developer role`);if(e.type===`developer/message`&&Array.isArray(r.content)){let e=!1;for(let n of r.content)if(!(!re(n)||n.type!==`tool-addition`&&n.type!==`tool-removal`)){if(typeof n.toolName!=`string`||n.toolName.length===0)throw Error(`${t} ${n.type} requires a nonempty toolName`);if(n.type===`tool-addition`&&(e=!0,Object.hasOwn(n,`tool`)))throw Error(`${t} tool-addition must omit inline tool definitions`)}if(e?!ae(n.headerSeq):Object.hasOwn(n,`headerSeq`))throw Error(`${t} requires headerSeq exactly when tool additions are present`)}}}if(e.type===`request/header`){if(!re(n))throw Error(`${t} data must be an object`);let e=n.header;if(!re(e))throw Error(`${t} header must be an object`);if(Object.hasOwn(e,`system`))throw Error(`${t} must omit header.system; use system/message`);if(Array.isArray(e.tools)&&e.tools.length===0)throw Error(`${t} must omit empty tools`);let r=e.adapterDefaults;if(re(r)&&Object.keys(r).length===0)throw Error(`${t} must omit empty adapterDefaults`)}else if(e.type===`tool/result`){if(!re(n))throw Error(`${t} data must be an object`);if(n.error===void 0)return;let e=n.message;if(!re(e)||e.isError!==!0)throw Error(`${t} error requires message.isError === true`)}}function ae(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}function oe(e){let t=e;return Object.keys(t).length===3&&Object.hasOwn(t,`op`)&&Object.hasOwn(t,`startSeq`)&&Object.hasOwn(t,`endSeq`)&&t.op===`replace`&&ae(t.startSeq)&&ae(t.endSeq)}function se(e){let t=e;if(!ne(e.type)){if(!ee.has(e.type)&&e.ignorable===!0)return;if(t.surfaceOp!==void 0)throw Error(`session event "${e.type}" is not surface-eligible and cannot carry surfaceOp`);if(t.sourceEventSeqs!==void 0)throw Error(`session event "${e.type}" is not surface-eligible and cannot carry sourceEventSeqs`);return}let n=t.surfaceOp;if(n===void 0)throw Error(`session event "${e.type}" is surface-eligible and requires a surfaceOp marker`);if(n===`append`)return n;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`session event "${e.type}" carries an invalid surfaceOp`);if(!oe(n))throw Error(`session event "${e.type}" carries an invalid replace surfaceOp`);return n}function ce(e,t){let n=e.sourceEventSeqs;if(e.type===`assistant/message`&&n!==void 0)throw Error(`assistant/message embeds its source stream and cannot carry sourceEventSeqs`);let r=/* @__PURE__ */ new Set;if(n!==void 0){if(!Array.isArray(n))throw Error(`sourceEventSeqs on event at seq ${e.seq} must be an array when present`);if(n.length===0)throw Error(`sourceEventSeqs must not be empty`);let t;for(let i of n){if(!ae(i))throw Error(`session event "${e.type}" sourceEventSeqs must densely contain non-negative safe integers`);r.add(i),t===void 0&&i>=e.seq&&(t=i)}if(r.size!==n.length)throw Error(`sourceEventSeqs must not contain duplicates`);if(t!==void 0)throw Error(`sourceEventSeqs must reference earlier events: ${t} >= current seq ${e.seq}`)}let i=t.filter(e=>!r.has(e));if(i.length>0)throw Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${i.join(`, `)}`)}function le(e){let t=se(e);if(t!==void 0&&t!==`append`&&(t.startSeq>=e.seq||t.endSeq>=e.seq))throw Error(`surface replace at seq ${e.seq}: startSeq and endSeq must reference earlier events`);return t!==void 0&&ce(e,[]),t}function ue(e){let t=`session wire event`;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);let n=e;for(let e of Object.keys(n))switch(e){case`type`:case`seq`:case`time`:case`data`:case`ignorable`:case`surfaceOp`:case`sourceEventSeqs`:break;default:throw Error(`${t} has unexpected field ${e}`)}let r=n.seq;if(typeof n.type!=`string`||typeof r!=`number`||!Number.isSafeInteger(r)||r<0||Object.is(r,-0)||typeof n.time!=`number`||!Number.isSafeInteger(n.time)||!Object.hasOwn(n,`data`)||n.data===void 0||Object.hasOwn(n,`ignorable`)&&n.ignorable!==!0)throw Error(`${t} has an invalid envelope`);let i=n;le(i),ie(i,t)}function de(e){switch(e.type){case`replace`:case`prepend`:return{...e,entries:l(e.entries)};case`append`:return{type:`append`,entry:e.entry};case`notification`:return e.notification}}function fe(e,t){let n=e.$stream({name:`session control stream`,open:t=>e.session.control(t),ended:e=>e?new i.RemoteStreamCarrierError(`session control stream ended without a terminal result`):/* @__PURE__ */ Error(`session control stream ended before its opening snapshot`),...t.carrierFailed===void 0?{}:{carrierFailed:t.carrierFailed}});return new i.RemoteSnapshotStream(n,{name:`session control stream`,isSnapshot:e=>e.type===`baseline`,replace:t.accept,update:t.accept,failed:t.failed})}var pe=class extends i.RemoteJournalStream{remote;address;journal;epoch;capture(){return this.journal&&{...this.journal,records:[...this.journal.records]}}get journalEpoch(){return this.epoch}constructor(e,t,n,r){super(e,{name:`session event stream`,emptyCursor:-1,entries:e=>e.records,hasMore:e=>e.hasMore,first:u,last:d,compare:(e,t)=>e-t,follows:(e,t)=>t===e+1,publish:e=>{this.epoch===void 0?this.journal=void 0:e.type===`replace`?this.journal={epoch:this.epoch,cursor:e.entries.at(-1)?.event.seq??-1,records:[...e.entries],hasMore:e.hasMore}:this.journal!==void 0&&e.type===`append`?(this.journal.cursor=e.entry.event.seq,this.journal.records.push(e.entry)):this.journal!==void 0&&e.type===`prepend`&&(this.journal.records.unshift(...e.entries),this.journal.hasMore=e.hasMore),n.publish(de(e))},...n.carrierFailed===void 0?{}:{carrierFailed:n.carrierFailed},failed:n.failed}),this.remote=e,this.address=t,this.journal=r&&{...r,records:[...r.records]},this.epoch=r?.epoch}async*follow(e,t){let n,r=this.journal;for await(let a of this.remote.session.follow({address:this.address,assistantStream:!0,...this.repairRequest(e),...r===void 0?{}:{resume:{epoch:r.epoch,cursor:r.cursor}}},t))if(a.type===`snapshot`){for(let e of a.records)ue(e.event);if(a.assistantStream===void 0)throw new o(`gateway/internal`,`session assistant stream omitted its opted-in opening baseline`,{});let e=a.records,t=a.hasMore;if(a.resumedAfter!==void 0){if(r===void 0||a.epoch!==r.epoch||a.resumedAfter!==r.cursor||a.cursor!==(e.at(-1)?.event.seq??r.cursor)||e.length>0&&e[0]?.event.seq!==r.cursor+1)throw new o(`gateway/internal`,`Invalid session resume baseline`,{});e=[...r.records,...e],t=r.hasMore}let i=a.epoch!==void 0&&a.epoch!==this.epoch;this.epoch=a.epoch,n=a.assistantStream.revision,yield{type:`opened`,...i?{reset:!0}:{},cursor:a.cursor,page:{records:e,hasMore:t,projections:a.projections,assistantStream:a.assistantStream}}}else if(a.type===`assistant-stream`){let e=(n??0)+1;if(a.frame.revision!==e)throw new i.RemoteStreamCarrierError(`session assistant stream skipped revision ${String(e)}`);n=a.frame.revision,yield{type:`notification`,notification:a}}else a.type===`projection`?yield{type:`notification`,notification:a}:(ue(a.event),yield{type:`entry`,entry:a})}async readPage(e,t,n){let r=await this.remote.session.page({address:this.address,throughSeq:t,...e},n);if(!r.ok)throw r.error;for(let e of r.value.records)ue(e.event);return r.value}repairRequest(e){return{...e.maxMessages===void 0?{}:{maxMessages:e.maxMessages},...e.turnWindow===void 0?{}:{turnWindow:e.turnWindow}}}};function me(e){let t=e.replace(/[/\\]+$/,``),n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));return t.slice(n+1)}let he=Symbol(`dsh.client.scope`);function ge(){}function _e(e,t){let n=e.plugin(ge),i={sessionId:t};return{fiber:n,ctx:n.ctx.extend({[he]:i,[r.Context.filter](e){let t=ye(e);return t===void 0||t===i}})}}function ve(e){return ye(e)?.sessionId}function ye(e){return e[he]}function be(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function xe(e,t=`|`){return e.map(e=>Je(e)).join(t)}function Se(e,t){return typeof t==`bigint`?t.toString():t}var Ce=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function we(e){return new Ce(e)}function Te(e){return e==null}function Ee(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function De(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}let Oe=/* @__PURE__*/ Symbol(`evaluating`);function ke(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Oe)return r===void 0&&(r=Oe,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ae(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function je(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function Me(e){return je(e._zod.def)??e._zod.def.shape}function Ne(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Ae(this,t,e),e},enumerable:!0,configurable:!0})}function Pe(e,t,n){t in e?Ae(e,t,n):e[t]=n}function Fe(e,t,n,r){let i=Me(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?Ne(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Pe(e,a,r?r(n.value,a):n.value))}}function Ie(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Ne(e,n,()=>t[n]):Pe(e,n,r.value))}}function h(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Le(e){return JSON.stringify(e)}function Re(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}let ze=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Be(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let Ve=/* @__PURE__*/ we(()=>{if(b.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function He(e){if(Be(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Be(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Ue(e){return He(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let We=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]),Ge=/* @__PURE__*/ new Set([`string`,`number`,`bigint`,`boolean`,`symbol`,`undefined`]);function Ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function qe(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function g(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Je(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Ye(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}let Xe={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ze={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function Qe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return Fe(i,e,$e(e,t)),qe(e,h(n,{shape:i,checks:[]}))}function $e(e,t){let n=Me(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function et(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set($e(e,t)),a={};return Fe(a,e,Reflect.ownKeys(Me(e)).filter(e=>!i.has(e))),qe(e,h(n,{shape:a,checks:[]}))}function tt(e,t){if(!He(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Me(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return qe(e,h(e._zod.def,{shape:nt(e,t)}))}function nt(e,t){let n={};return Fe(n,e,Reflect.ownKeys(Me(e))),Ie(n,t),n}function rt(e,t){if(!He(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return qe(e,h(e._zod.def,{shape:nt(e,t)}))}function it(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return Fe(n,e,Reflect.ownKeys(Me(e))),Fe(n,t,Reflect.ownKeys(Me(t))),qe(e,h(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function at(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set($e(t,n)):void 0,o={};return Fe(o,t,Reflect.ownKeys(Me(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),qe(t,h(t._zod.def,{shape:o,checks:[]}))}function ot(e,t,n){let r=n?new Set($e(t,n)):void 0,i={};return Fe(i,t,Reflect.ownKeys(Me(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),qe(t,h(t._zod.def,{shape:i}))}function _(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}function st(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}function ct(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function lt(e){return typeof e==`string`?e:e?.message}function ut(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function dt(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function ft(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:lt(e.inst?._zod.def?.error?.(e))??lt(a?.(e))??lt(t?.error?.(e))??lt(n.customError?.(e))??lt(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}let pt=/[\uD800-\uDBFF]/;function mt(e){let t=e.length;if(!pt.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function ht(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function gt(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function _t(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function vt(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):St(e,n,r.value)}}function yt(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function bt(e,t,n){return yt(e,t,n,!1)}function xt(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return yt(this,n,r(this))},set(e){yt(this,n,e)}})}return t}function St(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:yt(this,t,n.bind(this))},set(e){yt(this,t,e)}})}function Ct(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let wt,Tt=!1,Et={configurable:!0,get(){Tt=!0}};function v(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&wt!==e._zod?wt=void 0:(wt=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Et);let e=Tt;Tt=!1;try{let r=n(this);return Tt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Tt||=e,r}catch(n){throw delete this[t],Tt||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Dt(e,t,n,r){let i=Ct(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function Ot(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var kt;let At=/*@__PURE__*/ Object.freeze({status:`aborted`}),jt={value:void 0,enumerable:!1},Mt=`captureStackTrace`in Error?Error:null;function Nt(e){let t=Mt;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Mt=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function y(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=/* @__PURE__ */ new Set}a.prototype=i;let o=n,s=o&&/* @__PURE__ */ new WeakSet;function c(n,r){if(!n._zod){jt.value=new a(r);try{Object.defineProperty(n,"_zod",jt)}finally{jt.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),vt(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Nt(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Pt=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Ft=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(kt=globalThis).__zod_globalConfig??(kt.__zod_globalConfig={});let b=globalThis.__zod_globalConfig;function It(e){return e&&Object.assign(b,e),b}function Lt(){let e=this._zod;return e.message??=JSON.stringify(e.def,Se,2),e.message}function Rt(e){this._zod.message=e}let zt={get:Lt,set:Rt,enumerable:!0,configurable:!0},Bt={value:void 0,enumerable:!1},Vt=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Ht=(e,t)=>{e.name=`$ZodError`,Bt.value=t,Object.defineProperty(e,"issues",Bt),Bt.value=void 0,Object.defineProperty(e,"message",zt);let n=Object.getPrototypeOf(e);Vt.has(n)||(Vt.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Ut=y(`$ZodError`,Ht);y(`$ZodError`,Ht,void 0,{Parent:Error});function Wt(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Gt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Wt(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Kt(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function qt(e,t){return{callee:t?.callee??e,Err:t?.Err}}let Jt=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Pt;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>ft(e,o,It())));throw ze(n,a?.callee??t),n}return s.value};return t},Yt=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>ft(e,o,It())));throw ze(n,a?.callee??t),n}return s.value};return t},Xt=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Pt;return a.issues.length?Zt(e,a.issues,i):{success:!0,data:a.value}};function Zt(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>ft(e,n,It()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}let Qt=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?Zt(e,a.issues,i):{success:!0,data:a.value}},$t=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),en=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),tn=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==$t)return!0;if(r.definite===!0&&n===void 0)return!1}return nn(e,t,n)});function nn(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[en]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new Pt;return a.issues.length===0}let rn=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},an=e=>{let t=Jt(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,qt(n,a))};return n},on=e=>{let t=Jt(e),n=(e,r,i,a)=>t(e,r,i,qt(n,a));return n},sn=e=>{let t=Yt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,qt(n,a))};return n},cn=e=>{let t=Yt(e),n=async(e,r,i,a)=>await t(e,r,i,qt(n,a));return n},ln=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Xt(e)(t,n,i)},un=e=>(t,n,r)=>Xt(e)(t,n,r),dn=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Qt(e)(t,n,i)},fn=e=>async(t,n,r)=>Qt(e)(t,n,r),pn=/^[cC][0-9a-z]{6,}$/,mn=/^[0-9a-z]+$/,hn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,gn=/^[0-9a-vA-V]{20}$/,_n=/^[A-Za-z0-9]{27}$/,vn=/^[a-zA-Z0-9_-]{21}$/;function yn(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}let bn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xn=/^([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})$/,Sn=e=>e?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)$/,Cn=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function wn(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}let Tn=/^(?:(?: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])$/,En=/^(([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}|:))$/,Dn=/^((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])$/,On=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,kn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,An=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,jn=/^https?$/,Mn=/^\+[1-9]\d{6,14}$/,Nn=`(?:(?:\\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])))`;function Pn(e){return RegExp(`^${e}$`)}let Fn=/*@__PURE__*/ Pn(Nn);function In(e){let 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}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ln(e){return RegExp(`^${In(e)}$`)}function Rn(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${In({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${In({precision:e.precision})}`:n;return RegExp(`^${Nn}T(?:${r})$`)}let zn=/^[\s\S]{0,}$/,Bn=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Vn=/^-?\d+$/,Hn=/^-?\d+(?:\.\d+)?$/,Un=/^(?:true|false)$/i,Wn=/^null$/i,Gn=/^[^A-Z]*$/,Kn=/^[^a-z]*$/,x=/*@__PURE__*/ y(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),qn=e=>{let t=e.value;return!Te(t)&&t.length!==void 0},Jn={number:`number`,bigint:`bigint`,object:`date`},Yn=/*@__PURE__*/ y(`$ZodCheckLessThan`,(e,t)=>{x.init(e,t);let n=Jn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Jn[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xn=/*@__PURE__*/ y(`$ZodCheckGreaterThan`,(e,t)=>{x.init(e,t);let n=Jn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Jn[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Zn=/*@__PURE__*/ y(`$ZodCheckMultipleOf`,(e,t)=>{x.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):De(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})}}),Qn=/*@__PURE__*/ y(`$ZodCheckNumberFormat`,(e,t)=>{x.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Xe[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),$n=/*@__PURE__*/ y(`$ZodCheckMaxLength`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=qn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?mt(r):i)<=t.maximum)return;let a=ht(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),er=/*@__PURE__*/ y(`$ZodCheckMinLength`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=qn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?mt(r):i)>=t.minimum)return;let a=ht(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),tr=/*@__PURE__*/ y(`$ZodCheckLengthEquals`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=qn),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?mt(r):i;if(a===t.length)return;let o=ht(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),nr=/*@__PURE__*/ y(`$ZodCheckStringFormat`,(e,t)=>{var n,r;x.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),rr=/*@__PURE__*/ y(`$ZodCheckRegex`,(e,t)=>{nr.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})}}),ir=/*@__PURE__*/ y(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Gn,nr.init(e,t)}),ar=/*@__PURE__*/ y(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Kn,nr.init(e,t)}),or=/*@__PURE__*/ y(`$ZodCheckIncludes`,(e,t)=>{x.init(e,t);let n=Ke(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),sr=/*@__PURE__*/ y(`$ZodCheckStartsWith`,(e,t)=>{x.init(e,t);let n=RegExp(`^${Ke(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),cr=/*@__PURE__*/ y(`$ZodCheckEndsWith`,(e,t)=>{x.init(e,t);let n=RegExp(`.*${Ke(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),lr=/*@__PURE__*/ y(`$ZodCheckOverwrite`,(e,t)=>{x.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var ur=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
2
2
  `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
3
- `)}\n};`)(...Object.values(this.closed))}};let lr={major:4,minor:6,patch:7},S=/*@__PURE__*/ y(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=lr;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=_(t),a;for(let o of n){if(o._zod.def.when){if(ot(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Nt;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(ut(t.issues,n,e),i||=_(t,n))});else{if(t.issues.length===n)continue;ut(t.issues,n,e),i||=_(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(_(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Nt;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Nt;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return yt(this,`~standard`,fr(this))},set"~standard"(e){vt(this,`~standard`,e)}}),ur=(e,t)=>e.issues.length?{issues:e.issues.map(e=>dt(e,t,Ft()))}:{value:e.value};async function dr(e,t){let n={async:!0};return ur(await e._zod.run({value:t,issues:[]},n),n)}function fr(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return ur(r,n)}catch{}return dr(e,t)},vendor:`zod`,version:1}}let pr=/*@__PURE__*/ y(`$ZodString`,(e,t)=>{S.init(e,t),e._zod.pattern=t.pattern??Rn,e._zod.parse=(n,r)=>{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}}),C=/*@__PURE__*/ y(`$ZodStringFormat`,(e,t)=>{er.init(e,t),pr.init(e,t)}),mr=/*@__PURE__*/ y(`$ZodGUID`,(e,t)=>{t.pattern??=bn,C.init(e,t)}),hr=/*@__PURE__*/ y(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=xn(e)}else t.pattern??=xn();C.init(e,t)}),gr=/*@__PURE__*/ y(`$ZodEmail`,(e,t)=>{t.pattern??=Sn,C.init(e,t)});function _r(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function vr(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?_r(e)||2:yr(e,t)}function yr(e,t){if(!t.normalize&&t.protocol?.source===An.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}let br=/[\t\n\r]/g;function xr(e){return e.replace(br,``)}function Sr(e,t){return t.lastIndex=0,t.test(e.hostname)}function Cr(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}let wr=/*@__PURE__*/ y(`$ZodURL`,(e,t)=>{C.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=vr(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=xr(r);return}t.hostname&&!Sr(i,t.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&&!Cr(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:xr(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Tr=/*@__PURE__*/ y(`$ZodEmoji`,(e,t)=>{t.pattern??=Cn(),C.init(e,t)}),Er=/*@__PURE__*/ y(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?_n:vn(t.length),C.init(e,t)}),Dr=/*@__PURE__*/ y(`$ZodCUID`,(e,t)=>{t.pattern??=fn,C.init(e,t)}),Or=/*@__PURE__*/ y(`$ZodCUID2`,(e,t)=>{t.pattern??=pn,C.init(e,t)}),kr=/*@__PURE__*/ y(`$ZodULID`,(e,t)=>{t.pattern??=mn,C.init(e,t)}),Ar=/*@__PURE__*/ y(`$ZodXID`,(e,t)=>{t.pattern??=hn,C.init(e,t)}),jr=/*@__PURE__*/ y(`$ZodKSUID`,(e,t)=>{t.pattern??=gn,C.init(e,t)}),Mr=/*@__PURE__*/ y(`$ZodISODateTime`,(e,t)=>{t.pattern??=Ln(t),C.init(e,t)}),Nr=/*@__PURE__*/ y(`$ZodISODate`,(e,t)=>{t.pattern??=Pn,C.init(e,t)}),Pr=/*@__PURE__*/ y(`$ZodISOTime`,(e,t)=>{t.pattern??=In(t),C.init(e,t)}),Fr=/*@__PURE__*/ y(`$ZodISODuration`,(e,t)=>{t.pattern??=yn,C.init(e,t)}),Ir=/*@__PURE__*/ y(`$ZodIPv4`,(e,t)=>{t.pattern??=wn,C.init(e,t)}),Lr=/^[0-9a-fA-F:.]+$/;function Rr(e){return Lr.test(e)?_r(`http://[${e}]`):!1}let zr=/*@__PURE__*/ y(`$ZodIPv6`,(e,t)=>{t.pattern??=Tn,C.init(e,t),e._zod.check=n=>{Rr(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Br=/*@__PURE__*/ y(`$ZodCIDRv4`,(e,t)=>{t.pattern??=En,C.init(e,t)});function Vr(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:Rr(n)}let Hr=/*@__PURE__*/ y(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Dn,C.init(e,t),e._zod.check=n=>{Vr(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Ur(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let Wr=/^[0-9a-zA-Z+/]*={0,2}$/,Gr=/*@__PURE__*/ y(`$ZodBase64`,(e,t)=>{t.pattern??=Wr,C.init(e,t),e._zod.check=n=>{Ur(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Kr=/^[A-Za-z0-9_-]*$/;function qr(e){if(!Kr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Ur(t.padEnd(Math.ceil(t.length/4)*4,`=`))}let Jr=/*@__PURE__*/ y(`$ZodBase64URL`,(e,t)=>{t.pattern??=Kr,C.init(e,t),e._zod.check=n=>{qr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Yr=/*@__PURE__*/ y(`$ZodE164`,(e,t)=>{t.pattern??=jn,C.init(e,t)});function Xr(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}let Zr=/*@__PURE__*/ y(`$ZodJWT`,(e,t)=>{C.init(e,t),e._zod.check=n=>{Xr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Qr=/*@__PURE__*/ y(`$ZodNumber`,(e,t)=>{S.init(e,t),e._zod.pattern=Bn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),$r=/*@__PURE__*/ y(`$ZodNumberFormat`,(e,t)=>{Xn.init(e,t),Qr.init(e,t)}),ei=/*@__PURE__*/ y(`$ZodBoolean`,(e,t)=>{S.init(e,t),e._zod.pattern=Vn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),ti=/*@__PURE__*/ y(`$ZodNull`,(e,t)=>{S.init(e,t),e._zod.pattern=Hn,e._zod.values=/* @__PURE__ */ new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),ni=/*@__PURE__*/ y(`$ZodUnknown`,(e,t)=>{S.init(e,t),e._zod.parse=e=>e}),ri=/*@__PURE__*/ y(`$ZodNever`,(e,t)=>{S.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function ii(e,t){let n=lt(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of lt(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,ut(n.issues,t,e),n}}return i(n,a)}}let ai=e=>Array.isArray(e)?e.length:-1;function oi(e,t,n){e.issues.length&&t.issues.push(...st(n,e.issues)),t.value[n]=e.value}let si=/*@__PURE__*/ y(`$ZodArray`,(e,t)=>{S.init(e,t);let n=b.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>oi(t,r,e)));else if(oi(c,r,e),s&&c.issues.length!==0&&_(c))break}return o.length?Promise.all(o).then(()=>r):r},ii(e,ai)});function ci(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...st(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}let li=[];function ui(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:li,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=Je(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function di(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(_(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>ci(e,n,i,t,d,f))):ci(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}let fi=/*@__PURE__*/ y(`$ZodObject`,(e,t)=>{S.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=we(()=>ui(t));v(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||Ae(n,e,/* @__PURE__ */ new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=Be,o=t.catchall,s,c=b.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(_(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>ci(n,t,e,r,a,o))):ci(s,t,e,r,a,o)}return o?di(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),pi=/*@__PURE__*/ y(`$ZodObjectJIT`,(e,t)=>{fi.init(e,t);let n=e._zod.parse,r=we(()=>ui(t)),i=b.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new cr([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
3
+ `)}\n};`)(...Object.values(this.closed))}};let dr={major:4,minor:6,patch:7},S=/*@__PURE__*/ y(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=dr;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=_(t),a;for(let o of n){if(o._zod.def.when){if(st(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Pt;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(dt(t.issues,n,e),i||=_(t,n))});else{if(t.issues.length===n)continue;dt(t.issues,n,e),i||=_(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(_(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Pt;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Pt;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return bt(this,`~standard`,mr(this))},set"~standard"(e){yt(this,`~standard`,e)}}),fr=(e,t)=>e.issues.length?{issues:e.issues.map(e=>ft(e,t,It()))}:{value:e.value};async function pr(e,t){let n={async:!0};return fr(await e._zod.run({value:t,issues:[]},n),n)}function mr(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return fr(r,n)}catch{}return pr(e,t)},vendor:`zod`,version:1}}let hr=/*@__PURE__*/ y(`$ZodString`,(e,t)=>{S.init(e,t),e._zod.pattern=t.pattern??zn,e._zod.parse=(n,r)=>{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}}),C=/*@__PURE__*/ y(`$ZodStringFormat`,(e,t)=>{nr.init(e,t),hr.init(e,t)}),gr=/*@__PURE__*/ y(`$ZodGUID`,(e,t)=>{t.pattern??=xn,C.init(e,t)}),_r=/*@__PURE__*/ y(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Sn(e)}else t.pattern??=Sn();C.init(e,t)}),vr=/*@__PURE__*/ y(`$ZodEmail`,(e,t)=>{t.pattern??=Cn,C.init(e,t)});function yr(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function br(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?yr(e)||2:xr(e,t)}function xr(e,t){if(!t.normalize&&t.protocol?.source===jn.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}let Sr=/[\t\n\r]/g;function Cr(e){return e.replace(Sr,``)}function wr(e,t){return t.lastIndex=0,t.test(e.hostname)}function Tr(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}let Er=/*@__PURE__*/ y(`$ZodURL`,(e,t)=>{C.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=br(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=Cr(r);return}t.hostname&&!wr(i,t.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&&!Tr(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:Cr(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Dr=/*@__PURE__*/ y(`$ZodEmoji`,(e,t)=>{t.pattern??=wn(),C.init(e,t)}),Or=/*@__PURE__*/ y(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?vn:yn(t.length),C.init(e,t)}),kr=/*@__PURE__*/ y(`$ZodCUID`,(e,t)=>{t.pattern??=pn,C.init(e,t)}),Ar=/*@__PURE__*/ y(`$ZodCUID2`,(e,t)=>{t.pattern??=mn,C.init(e,t)}),jr=/*@__PURE__*/ y(`$ZodULID`,(e,t)=>{t.pattern??=hn,C.init(e,t)}),Mr=/*@__PURE__*/ y(`$ZodXID`,(e,t)=>{t.pattern??=gn,C.init(e,t)}),Nr=/*@__PURE__*/ y(`$ZodKSUID`,(e,t)=>{t.pattern??=_n,C.init(e,t)}),Pr=/*@__PURE__*/ y(`$ZodISODateTime`,(e,t)=>{t.pattern??=Rn(t),C.init(e,t)}),Fr=/*@__PURE__*/ y(`$ZodISODate`,(e,t)=>{t.pattern??=Fn,C.init(e,t)}),Ir=/*@__PURE__*/ y(`$ZodISOTime`,(e,t)=>{t.pattern??=Ln(t),C.init(e,t)}),Lr=/*@__PURE__*/ y(`$ZodISODuration`,(e,t)=>{t.pattern??=bn,C.init(e,t)}),Rr=/*@__PURE__*/ y(`$ZodIPv4`,(e,t)=>{t.pattern??=Tn,C.init(e,t)}),zr=/^[0-9a-fA-F:.]+$/;function Br(e){return zr.test(e)?yr(`http://[${e}]`):!1}let Vr=/*@__PURE__*/ y(`$ZodIPv6`,(e,t)=>{t.pattern??=En,C.init(e,t),e._zod.check=n=>{Br(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Hr=/*@__PURE__*/ y(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Dn,C.init(e,t)});function Ur(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:Br(n)}let Wr=/*@__PURE__*/ y(`$ZodCIDRv6`,(e,t)=>{t.pattern??=On,C.init(e,t),e._zod.check=n=>{Ur(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Gr(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let Kr=/^[0-9a-zA-Z+/]*={0,2}$/,qr=/*@__PURE__*/ y(`$ZodBase64`,(e,t)=>{t.pattern??=Kr,C.init(e,t),e._zod.check=n=>{Gr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Jr=/^[A-Za-z0-9_-]*$/;function Yr(e){if(!Jr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Gr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}let Xr=/*@__PURE__*/ y(`$ZodBase64URL`,(e,t)=>{t.pattern??=Jr,C.init(e,t),e._zod.check=n=>{Yr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Zr=/*@__PURE__*/ y(`$ZodE164`,(e,t)=>{t.pattern??=Mn,C.init(e,t)});function Qr(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}let $r=/*@__PURE__*/ y(`$ZodJWT`,(e,t)=>{C.init(e,t),e._zod.check=n=>{Qr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),ei=/*@__PURE__*/ y(`$ZodNumber`,(e,t)=>{S.init(e,t),e._zod.pattern=Hn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),ti=/*@__PURE__*/ y(`$ZodNumberFormat`,(e,t)=>{Qn.init(e,t),ei.init(e,t)}),ni=/*@__PURE__*/ y(`$ZodBoolean`,(e,t)=>{S.init(e,t),e._zod.pattern=Un,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),ri=/*@__PURE__*/ y(`$ZodNull`,(e,t)=>{S.init(e,t),e._zod.pattern=Wn,e._zod.values=/* @__PURE__ */ new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),ii=/*@__PURE__*/ y(`$ZodUnknown`,(e,t)=>{S.init(e,t),e._zod.parse=e=>e}),ai=/*@__PURE__*/ y(`$ZodNever`,(e,t)=>{S.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function oi(e,t){let n=ut(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of ut(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,dt(n.issues,t,e),n}}return i(n,a)}}let si=e=>Array.isArray(e)?e.length:-1;function ci(e,t,n){e.issues.length&&t.issues.push(...ct(n,e.issues)),t.value[n]=e.value}let li=/*@__PURE__*/ y(`$ZodArray`,(e,t)=>{S.init(e,t);let n=b.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>ci(t,r,e)));else if(ci(c,r,e),s&&c.issues.length!==0&&_(c))break}return o.length?Promise.all(o).then(()=>r):r},oi(e,si)});function ui(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...ct(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}let di=[];function fi(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:di,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=Ye(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function pi(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(_(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>ui(e,n,i,t,d,f))):ui(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}let mi=/*@__PURE__*/ y(`$ZodObject`,(e,t)=>{S.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=we(()=>fi(t));v(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||Ae(n,e,/* @__PURE__ */ new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=Be,o=t.catchall,s,c=b.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(_(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>ui(n,t,e,r,a,o))):ui(s,t,e,r,a,o)}return o?pi(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),hi=/*@__PURE__*/ y(`$ZodObjectJIT`,(e,t)=>{mi.init(e,t);let n=e._zod.parse,r=we(()=>fi(t)),i=b.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new ur([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
4
4
  let ${e}_ab = false;
5
5
  for (let i = 0; i < ${e}.issues.length; i++) {
6
6
  const iss = ${e}.issues[i];
@@ -50,80 +50,80 @@ window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-api-session-controller`,facto
50
50
  newResult[${r}] = ${n}.value;
51
51
  }
52
52
 
53
- `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Be,c=!b.jitless,l=c&&Ve.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?di([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function mi(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!_(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>dt(e,r,Ft())))}),t)}let hi=/*@__PURE__*/ y(`$ZodUnion`,(e,t)=>{S.init(e,t),v(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),v(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),v(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),v(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Ee(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>mi(t,r,e,i)):mi(o,r,e,i)}});function gi(e){let t=/* @__PURE__ */ new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}let _i=/*@__PURE__*/ y(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,hi.init(e,t);let n=e._zod.parse;v(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||Ae(t,e,/* @__PURE__ */ new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=je(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=we(()=>gi(t));e._zod.parse=(i,a)=>{let o=i.value;if(!Be(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),vi=/*@__PURE__*/ y(`$ZodIntersection`,(e,t)=>{S.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>bi(e,t,n)):bi(e,i,a)}});function yi(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(He(e)&&He(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=yi(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=yi(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function bi(e,t,n){let r=/* @__PURE__ */ new Map,i,a=/* @__PURE__ */ new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=yi(t.value,n.value);if(!c.valid){if(_(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}let xi=/*@__PURE__*/ y(`$ZodTuple`,(e,t)=>{S.init(e,t);let n=t.items,r=b.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=Si(n,`optin`),l=Si(n,`optout`);if(!t.rest){if(o.length<c)return i.issues.push({code:`too_small`,minimum:c,inclusive:!0,input:o,inst:e,origin:`array`}),i;o.length>n.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length),d=t.rest?a?.abortEarly:void 0,f=!1;for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:o[e],issues:[]},a);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):(u[e]=t,d&&!f&&t.issues.length&&(f=_(t)))}if(t.rest&&!f){let e=n.length-1,r=o.slice(n.length),c=i.issues.length;for(let n of r){if(d&&i.issues.length!==c){if(_(i,c))break;c=i.issues.length}e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>Ci(t,i,e))):Ci(r,i,e)}}return s.length?Promise.all(s).then(()=>wi(u,i,n,o,l)):wi(u,i,n,o,l)}});function Si(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function Ci(e,t,n){e.issues.length&&t.issues.push(...st(n,e.issues)),t.value[n]=e.value}function wi(e,t,n,r,i){for(let a=0;a<n.length;a++){let o=e[a],s=a<r.length;if(!s&&a>=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...st(a,o.issues))}t.value[a]=o.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}let Ti=/*@__PURE__*/ y(`$ZodRecord`,(e,t)=>{S.init(e,t);let n=b.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!He(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=/* @__PURE__ */ new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>dt(e,i,Ft())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...st(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...st(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&Bn.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>dt(e,i,Ft())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...st(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...st(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Ei=/*@__PURE__*/ y(`$ZodEnum`,(e,t)=>{S.init(e,t);let n=be(t.entries),r=new Set(n);e._zod.values=r,v(e,`pattern`,e=>{let t=be(e.def.entries).filter(e=>We.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Ge(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Di=/*@__PURE__*/ y(`$ZodLiteral`,(e,t)=>{S.init(e,t);let n=new Set(t.values);e._zod.values=n,v(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?Ge(e):e?Ge(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Oi=/*@__PURE__*/ y(`$ZodTransform`,(e,t)=>{S.init(e,t),e._zod.optin=`optional`,b.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Pt(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Nt;return n.value=i,n}});function ki(e,t){return e.value=t.issues.length?void 0:t.value,e}let Ai=/*@__PURE__*/ y(`$ZodOptional`,(e,t)=>{S.init(e,t),v(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,v(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0}),v(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ee(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ki(e,t)):ki(e,r)}return t.innerType._zod.run(e,n)}}),ji=/*@__PURE__*/ y(`$ZodExactOptional`,(e,t)=>{Ai.init(e,t),v(e,`values`,e=>e.def.innerType._zod.values),v(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Mi=/*@__PURE__*/ y(`$ZodNullable`,(e,t)=>{S.init(e,t),v(e,`optin`,e=>e.def.innerType._zod.optin),v(e,`optout`,e=>e.def.innerType._zod.optout),v(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ee(t.source)}|null)$`):void 0}),v(e,`values`,e=>e.def.innerType._zod.values?/* @__PURE__ */ new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Ni=/*@__PURE__*/ y(`$ZodDefault`,(e,t)=>{S.init(e,t),e._zod.optin=`defaulted`,v(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Pi(e,t)):Pi(r,t)}});function Pi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let Fi=/*@__PURE__*/ y(`$ZodPrefault`,(e,t)=>{S.init(e,t),e._zod.optin=`defaulted`,v(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Ii=/*@__PURE__*/ y(`$ZodNonOptional`,(e,t)=>{S.init(e,t),v(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Li(t,e)):Li(i,e)}});function Li(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function Ri(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>dt(e,r,Ft()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}let zi=/*@__PURE__*/ y(`$ZodCatch`,(e,t)=>{S.init(e,t),v(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),v(e,`optout`,e=>e.def.innerType._zod.optout),v(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>Ri(e,r,t,n)):Ri(e,r,t,n)}}),Bi=/*@__PURE__*/ y(`$ZodPipe`,(e,t)=>{S.init(e,t),v(e,`values`,e=>e.def.in._zod.values),v(e,`optin`,e=>e.def.in._zod.optin),v(e,`optout`,e=>e.def.out._zod.optout),v(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Vi(e,t.in,n)):Vi(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Vi(e,t.out,n)):Vi(r,t.out,n)}});function Vi(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}let Hi=/*@__PURE__*/ y(`$ZodReadonly`,(e,t)=>{S.init(e,t),v(e,`propValues`,e=>e.def.innerType._zod.propValues),v(e,`values`,e=>e.def.innerType._zod.values),v(e,`optin`,e=>e.def.innerType?._zod?.optin),v(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Ui):Ui(r)}});function Ui(e){return e.memo||(e.value=Object.freeze(e.value)),e}let Wi=/*@__PURE__*/ y(`$ZodLazy`,(e,t)=>{S.init(e,t),ke(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),v(e,`pattern`,e=>e.innerType?._zod?.pattern),v(e,`propValues`,e=>e.innerType?._zod?.propValues),v(e,`optin`,e=>e.innerType?._zod?.optin??void 0),v(e,`optout`,e=>e.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Gi=/*@__PURE__*/ y(`$ZodCustom`,(e,t)=>{x.init(e,t),S.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ki(t,n,r,e));Ki(i,n,r,e)}});function Ki(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(gt(e))}}var qi=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};let Ji=`~memo`,Yi=[];function Xi(e){return typeof e==`object`&&!!e}function Zi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}let Qi=/*@__PURE__*/ new WeakMap;function $i(e,t,n){let r=Qi.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,a=e=>{if(i!==2&&e?._zod){let r=$i(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?1:o.value?._zod?$i(o.value,t,n):0;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=je(c);s(e?o(e,!0):1),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?$i(r,t,!1):1);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),ea(e,i)}function ea(e,t){return t!==1&&Qi.set(e,t===2),t}function ta(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let na,ra=[],ia={alloc(e,t,n){let r=na;if(!r)return n;na=void 0;let i={value:n,issues:null};return r.set(t.value,i),ra.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&oa(n,e.value))throw new qi;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=$i(e,/* @__PURE__ */ new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===2||r?n=!0:r=!0}let l=s.value;if(!Xi(l))return t(s,c);let u=c[Ji];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[Ji]=u);let d;i===c?d=a:(d=ta(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Zi(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;na=d;let p=ra.length,m=t(s,c);na=void 0;let ee=ra.length>p?ra.pop():void 0;return m instanceof Promise?m.then(e=>(ee&&(ee.issues=e.issues.length?Zi(e.issues):Yi),e)):(ee&&(ee.issues=m.issues.length?Zi(m.issues):Yi),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function aa(){return ia}function oa(e,t){let n=e[Ji]?.backEdges;return n!==void 0&&Xi(t)&&n.has(t)}let sa=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(ht(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${qe(e.values[0])}`:`Invalid option: expected one of ${xe(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${xe(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function ca(){return{localeError:sa()}}var la,ua=class{constructor(){this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let 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=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let 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){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function da(){return new ua}(la=globalThis).__zod_globalRegistry??(la.__zod_globalRegistry=da());let fa=globalThis.__zod_globalRegistry;function pa(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
54
- function ma(e,t){return new e(pa({type:`string`,...g(t)}))}// @__NO_SIDE_EFFECTS__
55
- function ha(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
56
- function ga(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
57
- function _a(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
58
- function va(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...g(t)})}// @__NO_SIDE_EFFECTS__
59
- function ya(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...g(t)})}// @__NO_SIDE_EFFECTS__
60
- function ba(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...g(t)})}// @__NO_SIDE_EFFECTS__
61
- function xa(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
62
- function Sa(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
63
- function Ca(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
64
- function wa(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
65
- function Ta(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
66
- function Ea(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
67
- function Da(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
68
- function Oa(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
69
- function ka(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
70
- function Aa(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
71
- function ja(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
72
- function Ma(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
73
- function Na(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
74
- function Pa(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
75
- function Fa(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
76
- function Ia(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
77
- function La(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...g(t)})}// @__NO_SIDE_EFFECTS__
78
- function Ra(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...g(t)})}// @__NO_SIDE_EFFECTS__
79
- function za(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...g(t)})}// @__NO_SIDE_EFFECTS__
80
- function Ba(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...g(t)})}// @__NO_SIDE_EFFECTS__
81
- function Va(e,t){return new e(pa({type:`number`,checks:[],...g(t)}))}// @__NO_SIDE_EFFECTS__
82
- function Ha(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...g(t)})}// @__NO_SIDE_EFFECTS__
83
- function Ua(e,t){return new e({type:`boolean`,...g(t)})}// @__NO_SIDE_EFFECTS__
84
- function Wa(e,t){return new e({type:`null`,...g(t)})}// @__NO_SIDE_EFFECTS__
85
- function Ga(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
86
- function Ka(e,t){return new e({type:`never`,...g(t)})}// @__NO_SIDE_EFFECTS__
87
- function qa(e,t){return new qn({check:`less_than`,...g(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
88
- function Ja(e,t){return new qn({check:`less_than`,...g(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
89
- function Ya(e,t){return new Jn({check:`greater_than`,...g(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
90
- function Xa(e,t){return new Jn({check:`greater_than`,...g(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
91
- function Za(e,t){return new Yn({check:`multiple_of`,...g(t),value:e})}// @__NO_SIDE_EFFECTS__
92
- function Qa(e,t){return new Zn({check:`max_length`,...g(t),maximum:e})}// @__NO_SIDE_EFFECTS__
93
- function $a(e,t){return new Qn({check:`min_length`,...g(t),minimum:e})}// @__NO_SIDE_EFFECTS__
94
- function eo(e,t){return new $n({check:`length_equals`,...g(t),length:e})}// @__NO_SIDE_EFFECTS__
95
- function to(e,t){return new tr({check:`string_format`,format:`regex`,...g(t),pattern:e})}// @__NO_SIDE_EFFECTS__
96
- function no(e){return new nr({check:`string_format`,format:`lowercase`,...g(e)})}// @__NO_SIDE_EFFECTS__
97
- function ro(e){return new rr({check:`string_format`,format:`uppercase`,...g(e)})}// @__NO_SIDE_EFFECTS__
98
- function io(e,t){return new ir({check:`string_format`,format:`includes`,...g(t),includes:e})}// @__NO_SIDE_EFFECTS__
99
- function ao(e,t){return new ar({check:`string_format`,format:`starts_with`,...g(t),prefix:e})}// @__NO_SIDE_EFFECTS__
100
- function oo(e,t){return new or({check:`string_format`,format:`ends_with`,...g(t),suffix:e})}// @__NO_SIDE_EFFECTS__
101
- function so(e){return new sr({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
102
- function co(e){return/* @__PURE__ */ so(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
103
- function lo(){return/* @__PURE__ */ so(e=>e.trim())}// @__NO_SIDE_EFFECTS__
104
- function uo(){return/* @__PURE__ */ so(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
105
- function fo(){return/* @__PURE__ */ so(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
106
- function po(){return/* @__PURE__ */ so(e=>Re(e))}// @__NO_SIDE_EFFECTS__
107
- function mo(e,t,n){return new e({type:`array`,element:t,...g(n)})}// @__NO_SIDE_EFFECTS__
108
- function ho(e,t,n){let r=g(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
109
- function go(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...g(n)})}// @__NO_SIDE_EFFECTS__
110
- function _o(e,t){let n=/* @__PURE__ */ vo(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(gt(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(gt(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
111
- function vo(e,t){let n=new x({check:`custom`,...g(t)});return n._zod.check=e,n}function yo(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Ae(e,t,n[t]);return e}function bo(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??fa,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function xo(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function w(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,w(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&yo(o.schema,c),t.io===`input`&&T(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function So(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Co(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${So(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+So(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
53
+ `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Be,c=!b.jitless,l=c&&Ve.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?pi([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function gi(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!_(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>ft(e,r,It())))}),t)}let _i=/*@__PURE__*/ y(`$ZodUnion`,(e,t)=>{S.init(e,t),v(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),v(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),v(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),v(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Ee(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>gi(t,r,e,i)):gi(o,r,e,i)}});function vi(e){let t=/* @__PURE__ */ new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}let yi=/*@__PURE__*/ y(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,_i.init(e,t);let n=e._zod.parse;v(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||Ae(t,e,/* @__PURE__ */ new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=je(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=we(()=>vi(t));e._zod.parse=(i,a)=>{let o=i.value;if(!Be(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),bi=/*@__PURE__*/ y(`$ZodIntersection`,(e,t)=>{S.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Si(e,t,n)):Si(e,i,a)}});function xi(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(He(e)&&He(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=xi(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=xi(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Si(e,t,n){let r=/* @__PURE__ */ new Map,i,a=/* @__PURE__ */ new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=xi(t.value,n.value);if(!c.valid){if(_(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}let Ci=/*@__PURE__*/ y(`$ZodTuple`,(e,t)=>{S.init(e,t);let n=t.items,r=b.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=wi(n,`optin`),l=wi(n,`optout`);if(!t.rest){if(o.length<c)return i.issues.push({code:`too_small`,minimum:c,inclusive:!0,input:o,inst:e,origin:`array`}),i;o.length>n.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length),d=t.rest?a?.abortEarly:void 0,f=!1;for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:o[e],issues:[]},a);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):(u[e]=t,d&&!f&&t.issues.length&&(f=_(t)))}if(t.rest&&!f){let e=n.length-1,r=o.slice(n.length),c=i.issues.length;for(let n of r){if(d&&i.issues.length!==c){if(_(i,c))break;c=i.issues.length}e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>Ti(t,i,e))):Ti(r,i,e)}}return s.length?Promise.all(s).then(()=>Ei(u,i,n,o,l)):Ei(u,i,n,o,l)}});function wi(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function Ti(e,t,n){e.issues.length&&t.issues.push(...ct(n,e.issues)),t.value[n]=e.value}function Ei(e,t,n,r,i){for(let a=0;a<n.length;a++){let o=e[a],s=a<r.length;if(!s&&a>=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...ct(a,o.issues))}t.value[a]=o.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}let Di=/*@__PURE__*/ y(`$ZodRecord`,(e,t)=>{S.init(e,t);let n=b.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!He(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=/* @__PURE__ */ new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>ft(e,i,It())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...ct(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...ct(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&Hn.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>ft(e,i,It())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...ct(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...ct(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Oi=/*@__PURE__*/ y(`$ZodEnum`,(e,t)=>{S.init(e,t);let n=be(t.entries),r=new Set(n);e._zod.values=r,v(e,`pattern`,e=>{let t=be(e.def.entries).filter(e=>We.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Ke(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),ki=/*@__PURE__*/ y(`$ZodLiteral`,(e,t)=>{S.init(e,t);let n=new Set(t.values);e._zod.values=n,v(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?Ke(e):e?Ke(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Ai=/*@__PURE__*/ y(`$ZodTransform`,(e,t)=>{S.init(e,t),e._zod.optin=`optional`,b.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ft(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Pt;return n.value=i,n}});function ji(e,t){return e.value=t.issues.length?void 0:t.value,e}let Mi=/*@__PURE__*/ y(`$ZodOptional`,(e,t)=>{S.init(e,t),v(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,v(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0}),v(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ee(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ji(e,t)):ji(e,r)}return t.innerType._zod.run(e,n)}}),Ni=/*@__PURE__*/ y(`$ZodExactOptional`,(e,t)=>{Mi.init(e,t),v(e,`values`,e=>e.def.innerType._zod.values),v(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Pi=/*@__PURE__*/ y(`$ZodNullable`,(e,t)=>{S.init(e,t),v(e,`optin`,e=>e.def.innerType._zod.optin),v(e,`optout`,e=>e.def.innerType._zod.optout),v(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ee(t.source)}|null)$`):void 0}),v(e,`values`,e=>e.def.innerType._zod.values?/* @__PURE__ */ new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Fi=/*@__PURE__*/ y(`$ZodDefault`,(e,t)=>{S.init(e,t),e._zod.optin=`defaulted`,v(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Ii(e,t)):Ii(r,t)}});function Ii(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let Li=/*@__PURE__*/ y(`$ZodPrefault`,(e,t)=>{S.init(e,t),e._zod.optin=`defaulted`,v(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Ri=/*@__PURE__*/ y(`$ZodNonOptional`,(e,t)=>{S.init(e,t),v(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>zi(t,e)):zi(i,e)}});function zi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function Bi(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>ft(e,r,It()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}let Vi=/*@__PURE__*/ y(`$ZodCatch`,(e,t)=>{S.init(e,t),v(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),v(e,`optout`,e=>e.def.innerType._zod.optout),v(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>Bi(e,r,t,n)):Bi(e,r,t,n)}}),Hi=/*@__PURE__*/ y(`$ZodPipe`,(e,t)=>{S.init(e,t),v(e,`values`,e=>e.def.in._zod.values),v(e,`optin`,e=>e.def.in._zod.optin),v(e,`optout`,e=>e.def.out._zod.optout),v(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ui(e,t.in,n)):Ui(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ui(e,t.out,n)):Ui(r,t.out,n)}});function Ui(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}let Wi=/*@__PURE__*/ y(`$ZodReadonly`,(e,t)=>{S.init(e,t),v(e,`propValues`,e=>e.def.innerType._zod.propValues),v(e,`values`,e=>e.def.innerType._zod.values),v(e,`optin`,e=>e.def.innerType?._zod?.optin),v(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Gi):Gi(r)}});function Gi(e){return e.memo||(e.value=Object.freeze(e.value)),e}function Ki(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes(`int`),i,a;for(let e of t.checks??[]){let t=e._zod.def;t.pattern&&(n=t.pattern),r||=!!t.format?.includes(`int`);let o=t.minimum??t.length,s=t.maximum??t.length;o!==void 0&&(i===void 0||o>i)&&(i=o),s!==void 0&&(a===void 0||s<a)&&(a=s)}if(n)return n.source;if(i!==void 0&&a!==void 0&&i>a)return`(?!)`;if(i!==void 0||a!==void 0)return Bn({minimum:i,maximum:a}).source;let o=e._zod.pattern;return(r&&o===Hn?Vn:o)?.source}function qi(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let e=r._zod.pattern?.source,t=qi(r);return n&&e&&t&&t!==e?n.replace(Ee(e),()=>Ee(t)):n}if(t.options){let e=t.options.map(qi);if(e.every(Boolean))return`^(${e.map(e=>Ee(e)).join(`|`)})$`}return Ki(e)}let Ji=/*@__PURE__*/ y(`$ZodTemplateLiteral`,(e,t)=>{S.init(e,t);let n=[];for(let e of t.parts)if(typeof e==`object`&&e){let t=qi(e);if(!t)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);n.push(Ee(t))}else if(e===null||Ge.has(typeof e))n.push(Ke(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${n.join(``)}$`),e._zod.parse=(n,r)=>typeof n.value==`string`?(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:`invalid_format`,format:t.format??`template_literal`,pattern:e._zod.pattern.source}),n):(n.issues.push({input:n.value,inst:e,expected:`string`,code:`invalid_type`}),n)}),Yi=/*@__PURE__*/ y(`$ZodLazy`,(e,t)=>{S.init(e,t),ke(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),v(e,`pattern`,e=>e.innerType?._zod?.pattern),v(e,`propValues`,e=>e.innerType?._zod?.propValues),v(e,`optin`,e=>e.innerType?._zod?.optin??void 0),v(e,`optout`,e=>e.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Xi=/*@__PURE__*/ y(`$ZodCustom`,(e,t)=>{x.init(e,t),S.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Zi(t,n,r,e));Zi(i,n,r,e)}});function Zi(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(_t(e))}}var Qi=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};let $i=`~memo`,ea=[];function ta(e){return typeof e==`object`&&!!e}function na(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}let ra=/*@__PURE__*/ new WeakMap;function ia(e,t,n){let r=ra.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,a=e=>{if(i!==2&&e?._zod){let r=ia(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?1:o.value?._zod?ia(o.value,t,n):0;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=je(c);s(e?o(e,!0):1),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?ia(r,t,!1):1);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),aa(e,i)}function aa(e,t){return t!==1&&ra.set(e,t===2),t}function oa(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let sa,ca=[],la={alloc(e,t,n){let r=sa;if(!r)return n;sa=void 0;let i={value:n,issues:null};return r.set(t.value,i),ca.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&da(n,e.value))throw new Qi;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=ia(e,/* @__PURE__ */ new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===2||r?n=!0:r=!0}let l=s.value;if(!ta(l))return t(s,c);let u=c[$i];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[$i]=u);let d;i===c?d=a:(d=oa(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...na(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;sa=d;let p=ca.length,m=t(s,c);sa=void 0;let ee=ca.length>p?ca.pop():void 0;return m instanceof Promise?m.then(e=>(ee&&(ee.issues=e.issues.length?na(e.issues):ea),e)):(ee&&(ee.issues=m.issues.length?na(m.issues):ea),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function ua(){return la}function da(e,t){let n=e[$i]?.backEdges;return n!==void 0&&ta(t)&&n.has(t)}let fa=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(gt(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Je(e.values[0])}`:`Invalid option: expected one of ${xe(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${xe(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function pa(){return{localeError:fa()}}var ma,ha=class{constructor(){this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let 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=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let 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){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function ga(){return new ha}(ma=globalThis).__zod_globalRegistry??(ma.__zod_globalRegistry=ga());let _a=globalThis.__zod_globalRegistry;function va(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
54
+ function ya(e,t){return new e(va({type:`string`,...g(t)}))}// @__NO_SIDE_EFFECTS__
55
+ function ba(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
56
+ function xa(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
57
+ function Sa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
58
+ function Ca(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...g(t)})}// @__NO_SIDE_EFFECTS__
59
+ function wa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...g(t)})}// @__NO_SIDE_EFFECTS__
60
+ function Ta(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...g(t)})}// @__NO_SIDE_EFFECTS__
61
+ function Ea(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
62
+ function Da(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
63
+ function Oa(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
64
+ function ka(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
65
+ function Aa(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
66
+ function ja(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
67
+ function Ma(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
68
+ function Na(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
69
+ function Pa(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
70
+ function Fa(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
71
+ function Ia(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
72
+ function La(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
73
+ function Ra(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
74
+ function za(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
75
+ function Ba(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
76
+ function Va(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
77
+ function Ha(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...g(t)})}// @__NO_SIDE_EFFECTS__
78
+ function Ua(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...g(t)})}// @__NO_SIDE_EFFECTS__
79
+ function Wa(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...g(t)})}// @__NO_SIDE_EFFECTS__
80
+ function Ga(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...g(t)})}// @__NO_SIDE_EFFECTS__
81
+ function Ka(e,t){return new e(va({type:`number`,checks:[],...g(t)}))}// @__NO_SIDE_EFFECTS__
82
+ function qa(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...g(t)})}// @__NO_SIDE_EFFECTS__
83
+ function Ja(e,t){return new e({type:`boolean`,...g(t)})}// @__NO_SIDE_EFFECTS__
84
+ function Ya(e,t){return new e({type:`null`,...g(t)})}// @__NO_SIDE_EFFECTS__
85
+ function Xa(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
86
+ function Za(e,t){return new e({type:`never`,...g(t)})}// @__NO_SIDE_EFFECTS__
87
+ function Qa(e,t){return new Yn({check:`less_than`,...g(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
88
+ function $a(e,t){return new Yn({check:`less_than`,...g(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
89
+ function eo(e,t){return new Xn({check:`greater_than`,...g(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
90
+ function to(e,t){return new Xn({check:`greater_than`,...g(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
91
+ function no(e,t){return new Zn({check:`multiple_of`,...g(t),value:e})}// @__NO_SIDE_EFFECTS__
92
+ function ro(e,t){return new $n({check:`max_length`,...g(t),maximum:e})}// @__NO_SIDE_EFFECTS__
93
+ function io(e,t){return new er({check:`min_length`,...g(t),minimum:e})}// @__NO_SIDE_EFFECTS__
94
+ function ao(e,t){return new tr({check:`length_equals`,...g(t),length:e})}// @__NO_SIDE_EFFECTS__
95
+ function oo(e,t){return new rr({check:`string_format`,format:`regex`,...g(t),pattern:e})}// @__NO_SIDE_EFFECTS__
96
+ function so(e){return new ir({check:`string_format`,format:`lowercase`,...g(e)})}// @__NO_SIDE_EFFECTS__
97
+ function co(e){return new ar({check:`string_format`,format:`uppercase`,...g(e)})}// @__NO_SIDE_EFFECTS__
98
+ function lo(e,t){return new or({check:`string_format`,format:`includes`,...g(t),includes:e})}// @__NO_SIDE_EFFECTS__
99
+ function uo(e,t){return new sr({check:`string_format`,format:`starts_with`,...g(t),prefix:e})}// @__NO_SIDE_EFFECTS__
100
+ function fo(e,t){return new cr({check:`string_format`,format:`ends_with`,...g(t),suffix:e})}// @__NO_SIDE_EFFECTS__
101
+ function po(e){return new lr({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
102
+ function mo(e){return/* @__PURE__ */ po(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
103
+ function ho(){return/* @__PURE__ */ po(e=>e.trim())}// @__NO_SIDE_EFFECTS__
104
+ function go(){return/* @__PURE__ */ po(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
105
+ function _o(){return/* @__PURE__ */ po(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
106
+ function vo(){return/* @__PURE__ */ po(e=>Re(e))}// @__NO_SIDE_EFFECTS__
107
+ function yo(e,t,n){return new e({type:`array`,element:t,...g(n)})}// @__NO_SIDE_EFFECTS__
108
+ function bo(e,t,n){let r=g(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
109
+ function xo(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...g(n)})}// @__NO_SIDE_EFFECTS__
110
+ function So(e,t){let n=/* @__PURE__ */ Co(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(_t(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(_t(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
111
+ function Co(e,t){let n=new x({check:`custom`,...g(t)});return n._zod.check=e,n}function wo(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Ae(e,t,n[t]);return e}function To(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??_a,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function Eo(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function w(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,w(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&wo(o.schema,c),t.io===`input`&&T(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Do(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Oo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${Do(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+Do(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
112
112
 
113
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function wo(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;wo(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}let To=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),Eo=[`oneOf`,`anyOf`];function Do(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Oo(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!To.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??Do(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ae(n,r,e.length===1?e[0]:Oo(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=Do(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function ko(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of To)if(t in e)return;let n=t.filter(e=>Eo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Oo(t);else{let e=n[0],i=Eo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>Oo([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,yo(e,r))}function Ao(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):yo(i,s),yo(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())wo(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])ko(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}yo(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Ae(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Mo(t,`input`,e.processors),output:Mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function T(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return T(r.element,n);if(r.type===`set`)return T(r.valueType,n);if(r.type===`lazy`)return T(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return T(r.innerType,n);if(r.type===`intersection`)return T(r.left,n)||T(r.right,n);if(r.type===`record`||r.type===`map`)return T(r.keyType,n)||T(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:T(r.in,n)||T(r.out,n);if(r.type===`object`){for(let e in r.shape)if(T(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(T(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(T(e,n))return!0;return!!(r.rest&&T(r.rest,n))}return!1}let jo=(e,t={})=>n=>{let r=bo({...n,processors:t});return w(e,r),Co(r,e),Ao(r,e)},Mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=bo({...i??{},target:a,io:t,processors:n});return w(e,o),Co(o,e),Ao(o,e)},No=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Po=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Fo=(e,t)=>{No(e,`minimum`,t),Po(e,`maximum`,t)},Io=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Lo=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Ro=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},zo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Bo=(e,t)=>No(e,`minimum`,t.minimum),Vo=(e,t)=>Po(e,`maximum`,t.maximum),Ho=e=>(t,n)=>{zo(t,n.format);let[r,i]=e[n.format];No(t,`minimum`,r),Po(t,`maximum`,i)},Uo={greater_than:(e,t)=>No(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>Po(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Io(e,t.value),number_format:Ho(Ye),bigint_format:Ho(Xe),min_length:Bo,max_length:Vo,length_equals:(e,t)=>Fo(e,t.length),min_size:Bo,max_size:Vo,size_equals:(e,t)=>Fo(e,t.size),string_format:(e,t)=>{zo(e,t.format),t.pattern&&Lo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Ro(e,t.mime)};function E(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Uo[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&No(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&No(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&Po(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&Po(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Io(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Ro(t,i.mime);for(let e of i.patterns??[])Lo(t,e);return t}let Wo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Go=/* @__PURE__ */ new Map([[Wr,On],[Kr,kn]]),Ko=e=>Go.get(e)??e,qo=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=E(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Wo[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Ko);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=E(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):xo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Yo=(e,t,n,r)=>{n.type=`boolean`},Xo=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Zo=(e,t,n,r)=>{n.not={}},Qo=(e,t,n,r)=>{let i=e._zod.def,a=be(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},$o=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(xo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(xo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},es=(e,t,n,r)=>{xo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},ts=(e,t,n,r)=>{xo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ns=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=E(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=w(a.element,t,{...r,path:[...r.path,`items`]})};function rs(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?rs(t.out):t.type===`catch`?rs(t.innerType):e._zod.optin}let is=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&xo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ae(i.properties,e,w(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?rs(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=w(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},as=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>w(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},os=(e,t,n,r)=>{let i=e._zod.def,a=w(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=w(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},ss=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>w(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?w(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?rs(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=E(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function cs(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=cs(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>cs(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Bn:zn).source)),p}let ls=/* @__PURE__ */ new WeakMap;function us(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of ls.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=cs(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}let ds=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=E(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=w(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ae(i.patternProperties,Ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=w(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=ls.get(t);n||(n=[],ls.set(t,n),t.deferred.push(()=>us(t))),n.push(e)}i.additionalProperties=w(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&rs(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},fs=(e,t,n,r)=>{let i=e._zod.def,a=w(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},ps=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ms=Symbol();function hs(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(xo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),ms):JSON.parse(o)}let gs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=hs(i.defaultValue,e,t,n,r);o!==ms&&(n.default=o)},_s=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=hs(i.defaultValue,e,t,n,r);o!==ms&&(n._prefault=o)},vs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{xo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},ys=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;w(o,t,r);let s=t.seen.get(e);s.ref=o},bs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},xs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ss=(e,t,n,r)=>{let i=e._zod.innerType;w(i,t,r);let a=t.seen.get(e);a.ref=i},Cs=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function ws(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}let D=/*@__PURE__*/ y(`ZodError`,(e,t)=>{Ht.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Cs.has(n)||(Cs.add(n),ws(n,`format`,e=>t=>Gt(e,t)),ws(n,`flatten`,e=>t=>Wt(e,t)),ws(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Se,2)}),ws(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Se,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Ts=/* @__PURE__ */ qt(D),Es=/* @__PURE__ */ Jt(D),Ds=/* @__PURE__ */ Yt(D),Os=/* @__PURE__ */ Zt(D),ks=/* @__PURE__ */ rn(D),As=/* @__PURE__ */ an(D),js=/* @__PURE__ */ on(D),Ms=/* @__PURE__ */ sn(D),Ns=/* @__PURE__ */ cn(D),Ps=/* @__PURE__ */ ln(D),Fs=/* @__PURE__ */ un(D),Is=/* @__PURE__ */ dn(D);function Ls(){b.localeError||Ft(ca())}function Rs(){b.memoizer||Ft({memoizer:aa()})}let O=/*@__PURE__*/ y(`ZodType`,(e,t)=>(Ls(),S.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(h(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ke(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(nl(e,t))},superRefine(e,t){return this.check(rl(e,t))},overwrite(e){return this.check(/* @__PURE__ */ so(e))},optional(){return Fc(this)},exactOptional(){return Lc(this)},nullable(){return zc(this)},nullish(){return Fc(zc(this))},nonoptional(e){return Gc(this,e)},array(){return P(this)},or(e){return L([this,e])},and(e){return Ec(this,e)},transform(e){return Yc(this,Nc(e))},default(e){return Vc(this,e)},prefault(e){return Uc(this,e)},catch(e){return qc(this,e)},pipe(e){return Yc(this,e)},readonly(){return Zc(this)},describe(e){let t=this.clone();return fa.add(t,{description:e}),t},meta(...e){if(e.length===0)return fa.get(this);let t=this.clone();return fa.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return yt(this,`~standard`,{...fr(this),jsonSchema:{input:Mo(this,`input`),output:Mo(this,`output`)}})},set"~standard"(e){vt(this,`~standard`,e)},parse:function e(t,n){return Ts(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Es(this,t,n,{callee:e})},safeParse(e,t){return Ds(this,e,t)},async safeParseAsync(e,t){return Os(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){vt(this,`spa`,e)},validate(e,t){return en(this,e,t)},validateAsync(e,t){return nn(this,e,t)},encode:function e(t,n){return ks(this,t,n,{callee:e})},decode:function e(t,n){return As(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await js(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Ms(this,t,n,{callee:e})},safeEncode(e,t){return Ns(this,e,t)},safeDecode(e,t){return Ps(this,e,t)},async safeEncodeAsync(e,t){return Fs(this,e,t)},async safeDecodeAsync(e,t){return Is(this,e,t)},toJSONSchema(e){return jo(this,{})(e)},get description(){return fa.get(this)?.description},get _def(){return this._zod.def}}),zs=/*@__PURE__*/ y(`_ZodString`,(e,t)=>{pr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qo(e,t,n,r)},/*@__PURE__*/ bt({format:e=>E(e).format??null,minLength:e=>E(e).minimum??null,maxLength:e=>E(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ to(...e))},includes(...e){return this.check(/* @__PURE__ */ io(...e))},startsWith(...e){return this.check(/* @__PURE__ */ ao(...e))},endsWith(...e){return this.check(/* @__PURE__ */ oo(...e))},min(...e){return this.check(/* @__PURE__ */ $a(...e))},max(...e){return this.check(/* @__PURE__ */ Qa(...e))},length(...e){return this.check(/* @__PURE__ */ eo(...e))},nonempty(...e){return this.check(/* @__PURE__ */ $a(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ no(e))},uppercase(e){return this.check(/* @__PURE__ */ ro(e))},trim(){return this.check(/* @__PURE__ */ lo())},normalize(...e){return this.check(/* @__PURE__ */ co(...e))},toLowerCase(){return this.check(/* @__PURE__ */ uo())},toUpperCase(){return this.check(/* @__PURE__ */ fo())},slugify(){return this.check(/* @__PURE__ */ po())}})),Bs=/*@__PURE__*/ y(`ZodString`,(e,t)=>{pr.init(e,t),zs.init(e,t)},{email(e){return this.check(/* @__PURE__ */ ha(Gs,e))},url(e){return this.check(/* @__PURE__ */ xa(Ys,e))},jwt(e){return this.check(/* @__PURE__ */ Ia(dc,e))},emoji(e){return this.check(/* @__PURE__ */ Sa(Zs,e))},guid(e){return this.check(/* @__PURE__ */ ga(Ks,e))},uuid(e){return this.check(/* @__PURE__ */ _a(qs,e))},uuidv4(e){return this.check(/* @__PURE__ */ va(qs,e))},uuidv6(e){return this.check(/* @__PURE__ */ ya(qs,e))},uuidv7(e){return this.check(/* @__PURE__ */ ba(qs,e))},nanoid(e){return this.check(/* @__PURE__ */ Ca(Qs,e))},cuid(e){return this.check(/* @__PURE__ */ wa($s,e))},cuid2(e){return this.check(/* @__PURE__ */ Ta(ec,e))},ulid(e){return this.check(/* @__PURE__ */ Ea(tc,e))},base64(e){return this.check(/* @__PURE__ */ Na(cc,e))},base64url(e){return this.check(/* @__PURE__ */ Pa(lc,e))},xid(e){return this.check(/* @__PURE__ */ Da(nc,e))},ksuid(e){return this.check(/* @__PURE__ */ Oa(rc,e))},ipv4(e){return this.check(/* @__PURE__ */ ka(ic,e))},ipv6(e){return this.check(/* @__PURE__ */ Aa(ac,e))},cidrv4(e){return this.check(/* @__PURE__ */ ja(oc,e))},cidrv6(e){return this.check(/* @__PURE__ */ Ma(sc,e))},e164(e){return this.check(/* @__PURE__ */ Fa(uc,e))},datetime(e){return this.check(/* @__PURE__ */ La(Vs,e))},date(e){return this.check(/* @__PURE__ */ Ra(Hs,e))},time(e){return this.check(/* @__PURE__ */ za(Us,e))},duration(e){return this.check(/* @__PURE__ */ Ba(Ws,e))}});function k(e){return/* @__PURE__ */ ma(Bs,e)}let A=/*@__PURE__*/ y(`ZodStringFormat`,(e,t)=>{C.init(e,t),zs.init(e,t)}),Vs=/*@__PURE__*/ y(`ZodISODateTime`,(e,t)=>{Mr.init(e,t),A.init(e,t)}),Hs=/*@__PURE__*/ y(`ZodISODate`,(e,t)=>{Nr.init(e,t),A.init(e,t)}),Us=/*@__PURE__*/ y(`ZodISOTime`,(e,t)=>{Pr.init(e,t),A.init(e,t)}),Ws=/*@__PURE__*/ y(`ZodISODuration`,(e,t)=>{Fr.init(e,t),A.init(e,t)}),Gs=/*@__PURE__*/ y(`ZodEmail`,(e,t)=>{gr.init(e,t),A.init(e,t)}),Ks=/*@__PURE__*/ y(`ZodGUID`,(e,t)=>{mr.init(e,t),A.init(e,t)}),qs=/*@__PURE__*/ y(`ZodUUID`,(e,t)=>{hr.init(e,t),A.init(e,t)});function Js(e){return/* @__PURE__ */ _a(qs,e)}let Ys=/*@__PURE__*/ y(`ZodURL`,(e,t)=>{wr.init(e,t),A.init(e,t)});function Xs(e){return/* @__PURE__ */ xa(Ys,e)}let Zs=/*@__PURE__*/ y(`ZodEmoji`,(e,t)=>{Tr.init(e,t),A.init(e,t)}),Qs=/*@__PURE__*/ y(`ZodNanoID`,(e,t)=>{Er.init(e,t),A.init(e,t)}),$s=/*@__PURE__*/ y(`ZodCUID`,(e,t)=>{Dr.init(e,t),A.init(e,t)}),ec=/*@__PURE__*/ y(`ZodCUID2`,(e,t)=>{Or.init(e,t),A.init(e,t)}),tc=/*@__PURE__*/ y(`ZodULID`,(e,t)=>{kr.init(e,t),A.init(e,t)}),nc=/*@__PURE__*/ y(`ZodXID`,(e,t)=>{Ar.init(e,t),A.init(e,t)}),rc=/*@__PURE__*/ y(`ZodKSUID`,(e,t)=>{jr.init(e,t),A.init(e,t)}),ic=/*@__PURE__*/ y(`ZodIPv4`,(e,t)=>{Ir.init(e,t),A.init(e,t)}),ac=/*@__PURE__*/ y(`ZodIPv6`,(e,t)=>{zr.init(e,t),A.init(e,t)}),oc=/*@__PURE__*/ y(`ZodCIDRv4`,(e,t)=>{Br.init(e,t),A.init(e,t)}),sc=/*@__PURE__*/ y(`ZodCIDRv6`,(e,t)=>{Hr.init(e,t),A.init(e,t)}),cc=/*@__PURE__*/ y(`ZodBase64`,(e,t)=>{Gr.init(e,t),A.init(e,t)}),lc=/*@__PURE__*/ y(`ZodBase64URL`,(e,t)=>{Jr.init(e,t),A.init(e,t)}),uc=/*@__PURE__*/ y(`ZodE164`,(e,t)=>{Yr.init(e,t),A.init(e,t)}),dc=/*@__PURE__*/ y(`ZodJWT`,(e,t)=>{Zr.init(e,t),A.init(e,t)}),fc=/*@__PURE__*/ y(`ZodNumber`,(e,t)=>{Qr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jo(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ bt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=E(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=E(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=E(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>E(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ Ya(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},min(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},lt(e,t){return this.check(/* @__PURE__ */ qa(e,t))},lte(e,t){return this.check(/* @__PURE__ */ Ja(e,t))},max(e,t){return this.check(/* @__PURE__ */ Ja(e,t))},int(e){return this.check(M(e))},safe(e){return this.check(M(e))},positive(e){return this.check(/* @__PURE__ */ Ya(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Xa(0,e))},negative(e){return this.check(/* @__PURE__ */ qa(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ Ja(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Za(e,t))},step(e,t){return this.check(/* @__PURE__ */ Za(e,t))},finite(){return this}}));function j(e){return/* @__PURE__ */ Va(fc,e)}let pc=/*@__PURE__*/ y(`ZodNumberFormat`,(e,t)=>{$r.init(e,t),fc.init(e,t)});function M(e){return/* @__PURE__ */ Ha(pc,e)}let mc=/*@__PURE__*/ y(`ZodBoolean`,(e,t)=>{ei.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r)});function N(e){return/* @__PURE__ */ Ua(mc,e)}let hc=/*@__PURE__*/ y(`ZodNull`,(e,t)=>{ti.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r)});function gc(e){return/* @__PURE__ */ Wa(hc,e)}let _c=/*@__PURE__*/ y(`ZodUnknown`,(e,t)=>{ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function vc(){return/* @__PURE__ */ Ga(_c)}let yc=/*@__PURE__*/ y(`ZodNever`,(e,t)=>{ri.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r)});function bc(e){return/* @__PURE__ */ Ka(yc,e)}let xc=/*@__PURE__*/ y(`ZodArray`,(e,t)=>{Rs(),si.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ $a(e,t))},nonempty(e){return this.check(/* @__PURE__ */ $a(1,e))},max(e,t){return this.check(/* @__PURE__ */ Qa(e,t))},length(e,t){return this.check(/* @__PURE__ */ eo(e,t))},unwrap(){return this.element}});function P(e,t){return/* @__PURE__ */ mo(xc,e,t)}let Sc=/*@__PURE__*/ y(`ZodObject`,(e,t)=>{Rs(),pi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),Et(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(h(this._zod.def,{catchall:e}))},passthrough(){return this.clone(h(this._zod.def,{catchall:vc()}))},loose(){return this.clone(h(this._zod.def,{catchall:vc()}))},strict(){return this.clone(h(this._zod.def,{catchall:bc()}))},strip(){return this.clone(h(this._zod.def,{catchall:void 0}))},extend(e){return et(this,e)},safeExtend(e){return nt(this,e)},merge(e){return rt(this,e)},pick(e){return Ze(this,e)},omit(e){return $e(this,e)},partial(...e){return it(Pc,this,e[0])},exactPartial(...e){return it(Ic,this,e[0],`exactPartial`)},required(...e){return at(Wc,this,e[0])}});function F(e,t){let n={type:`object`,shape:e??{},...g(t)};return new Sc(n)}function I(e,t){return new Sc({type:`object`,shape:e,catchall:bc(),...g(t)})}let Cc=/*@__PURE__*/ y(`ZodUnion`,(e,t)=>{hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.options=t.options});function L(e,t){return new Cc({type:`union`,options:e,...g(t)})}let wc=/*@__PURE__*/ y(`ZodDiscriminatedUnion`,(e,t)=>{Cc.init(e,t),_i.init(e,t)});function R(e,t,n){return new wc({type:`union`,options:t,discriminator:e,...g(n)})}let Tc=/*@__PURE__*/ y(`ZodIntersection`,(e,t)=>{vi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r)});function Ec(e,t){return new Tc({type:`intersection`,left:e,right:t})}let Dc=/*@__PURE__*/ y(`ZodTuple`,(e,t)=>{Rs(),xi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ss(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Pc({type:`optional`,innerType:e}))})}});function Oc(e,t,n){let r=t instanceof S;return new Dc({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}let kc=/*@__PURE__*/ y(`ZodRecord`,(e,t)=>{Rs(),Ti.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return!t||!t._zod?new kc({type:`record`,keyType:k(),valueType:e,...g(t)}):new kc({type:`record`,keyType:e,valueType:t,...g(n)})}let Ac=/*@__PURE__*/ y(`ZodEnum`,(e,t)=>{Ei.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Ac({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Ac({...t,checks:[],...g(r),entries:i})}});function B(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Ac({type:`enum`,entries:n,...g(t)})}let jc=/*@__PURE__*/ y(`ZodLiteral`,(e,t)=>{Di.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function V(e,t){return new jc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}let Mc=/*@__PURE__*/ y(`ZodTransform`,(e,t)=>{Rs(),Oi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Pt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(gt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(gt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Nc(e){return new Mc({type:`transform`,transform:e})}let Pc=/*@__PURE__*/ y(`ZodOptional`,(e,t)=>{Ai.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Fc(e){return new Pc({type:`optional`,innerType:e})}let Ic=/*@__PURE__*/ y(`ZodExactOptional`,(e,t)=>{ji.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Lc(e){return new Ic({type:`optional`,innerType:e})}let Rc=/*@__PURE__*/ y(`ZodNullable`,(e,t)=>{Mi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function zc(e){return new Rc({type:`nullable`,innerType:e})}let Bc=/*@__PURE__*/ y(`ZodDefault`,(e,t)=>{Ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Vc(e,t){return new Bc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Hc=/*@__PURE__*/ y(`ZodPrefault`,(e,t)=>{Fi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Uc(e,t){return new Hc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Wc=/*@__PURE__*/ y(`ZodNonOptional`,(e,t)=>{Ii.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ps(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Gc(e,t){return new Wc({type:`nonoptional`,innerType:e,...g(t)})}let Kc=/*@__PURE__*/ y(`ZodCatch`,(e,t)=>{zi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function qc(e,t){return new Kc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Dt(t)})}let Jc=/*@__PURE__*/ y(`ZodPipe`,(e,t)=>{Bi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.in=t.in,e.out=t.out});function Yc(e,t){return new Jc({type:`pipe`,in:e,out:t})}let Xc=/*@__PURE__*/ y(`ZodReadonly`,(e,t)=>{Hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Zc(e){return new Xc({type:`readonly`,innerType:e})}let Qc=/*@__PURE__*/ y(`ZodLazy`,(e,t)=>{Wi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ss(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function $c(e){return new Qc({type:`lazy`,getter:e})}let el=/*@__PURE__*/ y(`ZodCustom`,(e,t)=>{Gi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r)});function tl(e,t){return/* @__PURE__ */ ho(el,e??(()=>!0),t)}function nl(e,t={}){return/* @__PURE__ */ go(el,e,t)}function rl(e,t){return/* @__PURE__ */ _o(e,t)}function il(e){return/* @__PURE__ */ La(Vs,e)}function al(e){return(t,n)=>{for(let r of e)Object.hasOwn(t,r)&&t[r]===void 0&&n.addIssue({code:`custom`,path:[r],message:`Explicit undefined is not valid JSON`})}}let ol=L([k(),j(),N(),gc()]);function sl(e){let t=/* @__PURE__ */ new WeakSet,n=[{value:e,leaving:!1}];try{for(;n.length>0;){let e=n.pop();if(!e)break;if(e.leaving)t.delete(e.value);else if(typeof e.value==`object`&&e.value!==null){if(t.has(e.value))return!1;t.add(e.value),n.push({value:e.value,leaving:!0});for(let t of Object.values(e.value))n.push({value:t,leaving:!1})}}}catch{return!1}return!0}let cl=tl(sl,{message:`JSON value must not contain circular references`}),ll=$c(()=>L([ol,P(ll),z(k(),ll)])),H=cl.pipe(ll);cl.pipe(P(ll));let ul=cl.pipe(z(k(),ll)),dl=I({code:k().min(1),message:k().min(1),retryable:N(),diagnostic:k().min(1).optional(),stage:k().min(1).optional(),durationMs:j().int().nonnegative().optional(),stderrTail:k().min(1).optional()}).superRefine(al([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),fl=k().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),pl=e=>k().min(1).max(e).refine(e=>e.trim().length>0),ml=z(fl,F({label:pl(256).optional(),description:pl(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),hl=z(fl,pl(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),gl=k().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),U=gl.brand(),W=gl.brand(),_l=gl.brand();gl.brand(),gl.brand();let vl=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),yl=vl.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),bl=F({modes:P(F({id:yl,label:vl.max(256),description:vl.max(1024).optional(),dangerous:N().optional(),localizations:ml.optional()}).strict()).min(1).max(32),defaultModeId:yl}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});F({threadId:W,permissionModeId:yl}).strict();let xl=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`});F({sourceThreadId:W,lastTurnId:_l.optional(),targetHarnessId:U,targetModel:xl.max(1024).optional(),targetThinkingOptionId:xl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).optional()}).strict();let Sl=F({sourceThreadId:W,sourceHarnessId:U,sourceHarnessLabel:xl.max(256).optional(),sourceModel:xl.max(1024).optional(),targetHarnessId:U,targetHarnessLabel:xl.max(256).optional(),targetModel:xl.max(1024).optional(),totalTurns:j().int().min(1),boundaryTurnNumber:j().int().min(1),includedTurnNumbers:P(j().int().min(1)),omittedTurns:j().int().min(0),preview:k().max(32e3),createdAtMs:j().int().nonnegative()}).strict();F({threadId:W,handoff:Sl}).strict();let G=j().int().safe().nonnegative(),Cl=j().finite().nonnegative(),wl=j().finite().min(0).max(100),Tl=F({version:L([V(3),V(4)]).optional(),requestId:k().min(1),turnId:k().min(1).max(1024),outputTokens:G,startedAtMs:G,completedAtMs:G}).strict().refine(e=>e.completedAtMs>e.startedAtMs),El=F({version:L([V(2),V(3),V(4)]).optional(),value:Cl,turnId:k().min(1).max(1024),at:G}).strict();F({outputTimings:P(Tl).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:El.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:El.extend({value:G}).optional()}).strict();let Dl=e=>hl.refine(t=>Object.values(t).every(t=>t.length<=e)),Ol=F({composerIndicators:P(F({kind:V(`countdown`),id:k().min(1).max(64),expiresAtUnix:G,label:Dl(256).optional(),tooltip:Dl(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:G.optional(),cachedInputTokens:G.optional(),cacheWriteInputTokens:G.optional(),outputTokens:G.optional(),outputTokensPerSecond:Cl.optional(),sessionOutputTokensPerSecond:Cl.optional(),apiOutputTokensPerSecond:Cl.optional(),reasoningOutputTokens:G.optional(),totalTokens:G.optional(),totalCostUsd:Cl.optional(),totalCredits:Cl.optional(),contextUsagePercent:Cl.optional(),cacheHitRatePercent:wl.optional(),contextWindowTokens:G.optional(),contextUsedTokens:G.optional(),planFiveHourUsedPercent:wl.optional(),planFiveHourResetsAtUnix:G.optional(),planSevenDayUsedPercent:wl.optional(),planSevenDayResetsAtUnix:G.optional(),sessionCacheHitRatePercent:wl.optional(),timeToFirstOutputMs:G.optional(),latestRequestTimeToFirstOutputMs:G.optional(),costSource:B([`publicPrice`,`native`]).optional(),unpricedModels:P(k().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{Object.keys(e).length===0&&t.addIssue({code:`custom`,message:`Thread Usage must contain a reliable field`});let n=e.contextUsedTokens!==void 0;n!==(e.contextWindowTokens!==void 0)&&t.addIssue({code:`custom`,message:`Thread Usage context fields must be provided together`,path:[n?`contextWindowTokens`:`contextUsedTokens`]}),e.contextWindowTokens===0&&t.addIssue({code:`custom`,message:`Thread Usage contextWindowTokens must be greater than zero`,path:[`contextWindowTokens`]}),e.costSource!==void 0&&e.totalCostUsd===void 0&&t.addIssue({code:`custom`,message:`Thread Usage costSource must be provided with totalCostUsd`,path:[`costSource`]}),e.unpricedModels!==void 0&&e.costSource!==`publicPrice`&&t.addIssue({code:`custom`,message:`Thread Usage unpricedModels must be provided with a publicPrice cost`,path:[`unpricedModels`]}),e.planFiveHourResetsAtUnix!==void 0&&e.planFiveHourUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planFiveHourResetsAtUnix must be provided with planFiveHourUsedPercent`,path:[`planFiveHourResetsAtUnix`]}),e.planSevenDayResetsAtUnix!==void 0&&e.planSevenDayUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planSevenDayResetsAtUnix must be provided with planSevenDayUsedPercent`,path:[`planSevenDayResetsAtUnix`]})}),kl=j().finite().min(0).max(100),Al=B([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),jl=F({id:k().min(1).max(256),label:k().min(1).max(256),localizations:ml.optional()}).strict(),Ml=F({product:k().min(1),periodType:Al.optional(),scope:jl.optional(),localizations:ml.optional(),used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),usagePercent:kl,resetsAt:k().min(1).optional()}).strict(),Nl=F({availableCount:j().int().safe().positive(),nextExpiresAt:k().min(1).optional(),expiresAt:P(k().min(1)).min(1).max(32).optional()}).strict(),Pl=F({used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),label:k().min(1).optional(),scope:jl.optional(),localizations:ml.optional(),usedPercent:kl,resetsAt:k().min(1).optional(),periodType:Al,productUsage:P(Ml).min(1).optional(),resetCredits:Nl.optional()}).strict(),Fl=F({amount:j().finite().nonnegative(),currency:k().trim().min(1).max(8),label:k().trim().min(1).max(128).optional()}).strict();F({threadId:W,refresh:V(`exact`).optional()}).strict(),F({threadId:W,usage:Ol.nullable(),accountCredits:Pl.optional(),accountBalance:Fl.optional(),accountCreditsSupported:N().optional()}).strict();let Il=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Ll=k().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Rl=B([`priority`,`ultrafast`]),K=F({id:Ll,serviceTier:Rl.optional()}).strict();function zl(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let q=Il.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Bl=Il.max(256),Vl=F({id:q,label:Il.max(256)}).strict(),Hl=F({ref:K,label:Il.max(256),resolvedModelLabel:Bl.optional(),fastModel:K.optional(),supportedThinkingOptionIds:P(q).optional()}).strict().refine(e=>e.fastModel?.serviceTier===void 0||e.fastModel.id===e.ref.id,{path:[`fastModel`,`id`],message:`A tiered Fast Model must share the base Model ID`});function Ul(e,t){if(t)return e?.models.find(e=>zl(e.ref,t)||zl(e.fastModel,t))}let Wl=P(Vl).superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Thinking option IDs must be unique`,path:[r,`id`]}),n.add(i.id)}),Gl=B([`catalog`,`activeModel`]),Kl=F({models:P(Hl),defaultModel:K.optional(),thinkingOptions:Wl,defaultThinkingOptionId:q.optional(),thinkingOptionsScope:Gl.optional()}).strict().superRefine((e,t)=>{let n=[],r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.some(e=>zl(e,a.ref))&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.push(a.ref),a.fastModel&&(n.some(e=>zl(e,a.fastModel))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.push(a.fastModel));let e=/* @__PURE__ */ new Set;for(let[n,o]of(a.supportedThinkingOptionIds??[]).entries())e.has(o)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,n]}),e.add(o),r.has(o)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,n]})}e.defaultModel&&!Ul(e,e.defaultModel)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),ql=F({fork:N(),forkAcrossCwd:N(),rollbackLastTurn:N()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Jl=B([`live`,`atCreate`]),Yl=F({configuration:F({selectModel:N(),selectThinkingOption:N(),selectPermissionMode:N(),permissionModeScope:Jl.default(`live`)}).strict(),history:ql,subagents:F({observe:N(),readTranscript:N()}).strict().optional(),autonomousTurns:F({observe:N()}).strict().optional(),steer:N().optional(),persistentPlan:N().optional()}).strict();F({effectiveModel:K.optional(),resolvedModelLabel:Bl.optional(),effectiveThinkingOptionId:q.optional(),availableThinkingOptions:Wl.optional(),effectivePermissionModeId:yl.optional()}).strict().superRefine((e,t)=>{e.effectiveThinkingOptionId&&e.availableThinkingOptions&&!e.availableThinkingOptions.some(({id:t})=>t===e.effectiveThinkingOptionId)&&t.addIssue({code:`custom`,message:`Effective Thinking option must be currently available`,path:[`effectiveThinkingOptionId`]})});let Xl=F({open:V(!0)}).strict();L([F({status:V(`ready`),catalog:Kl,permissionModes:bl.optional(),capabilities:Yl,webUi:Xl.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),F({status:B([`notInstalled`,`unavailable`,`error`]),error:dl}).strict()]),F({harnessId:U,cwd:Il.max(16384).optional(),refresh:N().optional(),purpose:V(`availability`).optional(),credentialAccess:B([`allow`,`retry`]).optional()}).strict(),F({harnessId:U}).strict(),F({}).strict(),F({threadId:W,model:K}).strict(),F({threadId:W,thinkingOptionId:q}).strict(),F({threadId:W,includeReferenceCapability:N().optional()}).strict(),R(`owner`,[F({owner:V(`codex`),locked:N(),effectiveModel:K.optional(),resolvedModelLabel:Bl.optional(),effectiveThinkingOptionId:q.optional(),effectivePermissionModeId:yl.optional(),history:ql.optional(),supportsThreadReferences:V(!0).optional(),handoff:Sl.optional()}).strict(),F({owner:V(`external`),harnessId:Il.max(256),transportModelId:Il.max(8192),effectiveModel:K.optional(),resolvedModelLabel:Bl.optional(),effectiveThinkingOptionId:q.optional(),availableThinkingOptions:Wl.optional(),effectivePermissionModeId:yl.optional(),catalog:Kl.optional(),history:ql,usage:Ol.optional(),handoff:Sl.optional(),locked:V(!0)}).strict()]),F({threadIds:P(W).min(1).max(100)}).strict().superRefine(({threadIds:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i)&&t.addIssue({code:`custom`,message:`Thread ownership-list IDs must be unique`,path:[`threadIds`,r]}),n.add(i)});let Zl=R(`owner`,[F({threadId:W,owner:V(`codex`)}).strict(),F({threadId:W,owner:V(`external`),harnessId:k().max(256).pipe(U)}).strict()]);F({threads:P(Zl).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),F({threadId:W,text:k().optional()}).strict(),F({kind:V(`application`),value:k().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),kt}}).pipe(F({expectedTurnId:_l,clientUserMessageId:k().min(1),delivery:B([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),B([`activeTurn`,`newTurn`]),F({delivery:B([`official`,`activeTurn`,`newTurn`])}).strict();let Ql=k().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),$l=Ql.pipe(U),eu=$l.refine(e=>e!==`codex`,`The official Codex identity is reserved`),tu=k().min(1).max(512).refine(e=>!/[\\\u0000:#?]/u.test(e)&&!e.startsWith(`/`)&&!e.split(`/`).some(e=>e===`..`||e===``),`Plugin resources must be relative paths inside the plugin`),nu=Xs().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),ru=F({en:k().max(4096),"zh-CN":k().max(4096).optional()}).strict(),iu=F({commands:P(F({terminal:k().max(256),command:k().max(4096)}).strict()).max(8),before:ru.optional(),after:ru.optional(),downloads:P(F({label:k().max(128),url:nu}).strict()).max(8).optional()}).strict(),au={id:$l,name:k().trim().min(1).max(128),version:k().min(1).max(128),kind:V(`usage`).optional(),iconStyle:F({vector:F({viewBox:k().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:P(F({d:k().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:B([`evenodd`,`nonzero`]).optional(),fill:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:k().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:j().min(0).max(50).optional(),paddingRatio:j().min(0).max(.25).optional()}).strict().optional(),installation:iu.optional(),notice:ru.optional(),launchCommand:V(!0).optional(),links:F({website:nu.optional(),documentation:nu.optional(),installation:nu.optional()}).strict().optional()};F({manifestVersion:V(1),...au,adapterApiVersion:j().int().positive(),entry:tu,icon:tu.optional()}).strict();let ou=k().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),su=F({...au,icon:ou.optional()}).strict();F({}).strict(),F({plugins:P(su.extend({id:eu})).max(128)}).strict(),F({version:V(1),enabled:P($l).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let cu=131072,lu=524288,uu=Ql,du=B([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),fu=B([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),pu=k().trim().min(1).max(128);function mu(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return}}let hu=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),gu=tu.refine(e=>mu(e)!==void 0&&hu(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),_u=k().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Xs({protocol:/^https?$/u})).refine(e=>{let{username:t,password:n}=new URL(e);return!t&&!n&&!/[\\\s]/u.test(e)},`URL must not contain credentials, backslashes, or whitespace`);function vu(e){return I({en:e,"zh-CN":e})}let yu=vu(k().trim().min(1)),bu=P(fu).max(fu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),xu=P(du).max(du.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),Su={key:k().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:yu,description:yu.optional()},Cu={...Su,step:j().positive().optional(),default:j().optional()},wu=I({value:k(),label:yu}),Tu=R(`type`,[I({...Su,type:V(`boolean`),default:N().optional()}),I({...Su,type:V(`string`),placeholder:yu.optional(),default:k().optional()}),I({...Cu,type:V(`number`),min:j().optional(),max:j().optional()}),I({...Cu,type:V(`range`),min:j(),max:j()}),I({...Su,type:V(`select`),options:P(wu).min(1),default:k().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),Eu=F({manifestVersion:M().positive(),id:uu,name:L([pu,vu(pu)]),version:k().min(1).max(128),desktopApi:M().positive()}).passthrough().extend({manifestVersion:V(1),desktopApi:V(1),description:I({en:k().max(4096),"zh-CN":k().max(4096).optional()}).optional(),author:k().trim().min(1).max(128).optional(),repository:_u.optional(),details:I({en:k().max(16384),"zh-CN":k().max(16384).optional()}).optional(),icon:gu.optional(),screenshots:P(gu).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:I({script:tu,style:tu.optional()}).optional(),backend:I({script:tu.refine(hu)}).optional(),slots:xu.default(()=>[]),settingsSchema:P(Tu).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:bu.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),Du=k().regex(/^[a-f0-9]{64}$/u),Ou=I({state:B([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:Du.optional(),error:k().optional(),conflictWith:uu.optional()});I({controllerPid:M().positive(),targetId:k().nullable(),updatedAt:il(),handledReloadToken:Js().optional(),extensions:z(k(),Ou),surfaces:z(k(),Ou).optional()});let ku=B([`official`,`community`]);function Au(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let ju=_u.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||Au(t)||t.origin===`https://github.com`&&/^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(t.pathname)||t.origin===`https://codeload.github.com`&&/^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(t.pathname)},`Expected a .zip download URL or a GitHub zipball URL`),Mu=I({id:uu,version:k().trim().min(1).max(128),name:yu.extend({en:pu,"zh-CN":pu}),description:vu(k().trim().min(1).max(4096)),details:vu(k().trim().min(1).max(16384)).optional(),author:k().trim().min(1).max(128),repository:_u,stars:j().int().min(0).optional(),downloads:j().int().min(0).optional(),categories:bu.optional(),trustTier:ku.default(`community`),icon:_u.optional(),screenshots:P(_u).max(4).optional(),downloadUrl:ju,sha256:Du,slots:xu.optional(),publishedAt:k().optional(),updatedAt:k().optional(),minCodexHostVersion:k().optional()});I({schemaVersion:V(1),generatedAt:k(),extensions:P(Mu).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let Nu=k().trim().min(1).max(128),Pu=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,Fu=uu.refine(e=>!Pu.test(e),`Reserved extension ID`),Iu=B([`desktop`,`web`]),Lu=Du,Ru=Js(),zu=tu.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Pu.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),Bu=Eu.shape,Vu=(e,t=0)=>I({en:k().trim().min(t).max(e),"zh-CN":k().trim().min(t).max(e)}),Hu=e=>zu.refine(t=>t.endsWith(e),`Expected a ${e} file`),Uu=Hu(`.mjs`),Wu=Hu(`.css`).optional(),Gu=e=>e.normalize(`NFC`).toLowerCase(),Ku=I({manifestVersion:V(2),id:Fu,name:Vu(128,1),version:k().trim().min(1).max(128),description:Vu(4096),details:Vu(16384).optional(),author:Bu.author,repository:Bu.repository,icon:Bu.icon.refine(e=>e===void 0||zu.safeParse(e).success),screenshots:Bu.screenshots.refine(e=>e===void 0||e.every(e=>zu.safeParse(e).success)),categories:Bu.categories,settingsSchema:Bu.settingsSchema,slots:Bu.slots.removeDefault().optional(),page:I({apiVersion:V(1),entry:Uu,style:Wu,title:Vu(128,1).optional()}).optional(),widget:I({apiVersion:V(1),entry:Uu,style:Wu}).optional(),desktop:I({apiVersion:V(1),script:Hu(`.js`),style:Wu}).optional(),web:I({apiVersion:V(1),entry:Uu.optional(),style:Wu}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:I({apiVersion:V(1),entry:Uu}).optional()}).refine(({page:e,widget:t,desktop:n,web:r,backend:i})=>!!(e||t||n||r||i),`Expected at least one page, widget, desktop, web, or backend entry`).refine(({page:e,widget:t,web:n,backend:r})=>!r||[e?.entry,t?.entry,n?.entry].every(e=>e===void 0||Gu(e)!==Gu(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function qu({hasPage:e,hasWidget:t,hasDesktop:n,hasWeb:r,hasBackend:i}){if(e||t||i&&!n&&!r)return[`desktop`,`web`];let a=[];return n&&a.push(`desktop`),r&&a.push(`web`),a}let Ju=Nu,Yu=B([`running`,`waiting`,`idle`,`unknown`]),Xu=I({sourceThreadId:W,createdAtMs:j().int().nonnegative()}),Zu=I({harnessId:U,title:k().optional(),status:Yu,archived:N(),updatedAtMs:j().int().nonnegative().optional()}),Qu=I({revision:M().nonnegative(),parents:z(W,W),handoffs:z(W,Xu).optional(),nodes:z(W,Zu),truncated:N()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,handoffs:t,nodes:n})=>Object.entries(e).every(([e,t])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t))&&Object.entries(t??{}).every(([e,{sourceThreadId:t}])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t)),`Missing Thread tree node`),$u=k().min(1).max(128);I({});let ed=I({subscriptionId:$u});I({}),ed.extend({snapshot:Qu});let td=M().nonnegative(),nd=I({revision:td,enabled:P(Fu).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});I({version:V(1),seeded:P(Fu).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});let rd=F({version:k().trim().min(1).max(128),publishedAt:k().trim().min(1).max(64).optional(),notes:k().trim().min(1).max(8192),url:_u.optional()}),{downloadUrl:id,...ad}=Mu.shape,od=F({...ad,id:Fu,format:V(`codexhost`),targets:P(Iu).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:I({page:M().positive().optional(),widget:M().positive().optional(),desktop:M().positive().optional(),web:M().positive().optional(),backend:M().positive().optional()}),downloadUrl:id.refine(e=>e.startsWith(`https://`),`Expected HTTPS`),featured:N().optional(),featuredOrder:M().nonnegative().optional(),changelog:P(rd).max(20).optional()}).refine(({targets:e,apis:t})=>{let n=qu({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);F({schemaVersion:V(2),generatedAt:k().min(1),extensions:P(od).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:_u,fetchedAt:il(),cached:N(),stale:N().optional()});let sd={id:Fu},cd={...sd,activationId:Ru,digest:Lu},ld={...sd,activationId:cd.activationId.optional()},ud=k().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),dd=k().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function fd(e){return k().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let pd=I({type:V(`github`),repository:k().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:dd.optional(),tag:dd.optional(),asset:k().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:zu.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),md=L([I({type:V(`catalog`),...sd}),pd,I({type:V(`zip`),base64:fd(67108864).min(4)}),I({type:V(`zip`),localZipPath:ud}),I({type:V(`localDir`),localDir:ud})]),hd=R(`type`,[I({type:V(`catalog`),...sd}),pd,I({type:V(`zip`)}),I({type:V(`localDir`)})]),gd=I({...cd,manifest:Ku,installedAt:il(),source:hd.optional()}),_d=e=>k().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),vd={desktopConflictWith:Fu.optional()},yd=B([`none`,`inactive`,`starting`,`running`,`failed`]),bd=R(`state`,[gd.extend({state:V(`valid`),enabled:N(),...vd,iconDataUrl:_d(cu).optional(),screenshotDataUrls:P(_d(lu)).max(4).optional(),backendState:yd.optional(),backendError:k().optional()}),I({state:B([`invalid`,`incompatible`]),id:k().min(1),enabled:N(),error:k()})]);I({revision:td,configuration:nd,diagnostics:P(k()),extensions:P(bd)}),I({revision:td,extensions:P(gd.extend({...vd,settingsRevision:td})).max(64)});let J={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,catalogIcon:`codexhost/extensions/catalogIcon`,catalogScreenshot:`codexhost/extensions/catalogScreenshot`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`,threadTree:`codexhost/extensions/threadTree`},xd=Object.freeze(Object.values(J));new Set(xd),I({});let Sd={expectedRevision:td};I({...sd,...Sd}),gd.extend({replaced:N()}),R(`state`,[I({state:V(`saved`),configuration:nd}),I({state:V(`revision-conflict`),revision:td})]),I({...ld,digest:cd.digest.optional(),path:zu}),I({mimeType:k().min(1),base64:fd(16777216),digest:cd.digest}),I({mimeType:B([`image/png`,`image/jpeg`,`image/webp`]),base64:fd(cu)});let Cd=M().min(0).max(3);I({mimeType:B([`image/png`,`image/jpeg`,`image/webp`]),base64:fd(lu)}),I({settingsRevision:td,values:ul}),J.list,J.snapshot,J.catalog,I({forceRefresh:N().optional(),staleWhileRevalidate:N().optional()}),J.catalogIcon,I({...sd}),J.catalogScreenshot,I({...sd,index:Cd}),J.install,I({source:md}),J.update,I({...sd,expectedDigest:cd.digest,expectedActivationId:cd.activationId.optional(),source:md.optional()}),J.enable,J.disable,J.uninstall,I({...sd,removeData:N().optional(),expectedDigest:cd.digest.optional()}),I({...sd,removed:N()}),J.recover,I({expectedRevision:Sd.expectedRevision.optional()}),J.asset,J.settingsGet,I(ld),J.settingsSet,I({...ld,expectedSettingsRevision:td,values:ul}),J.backendInvoke,I({...ld,method:Ju,params:H.optional()}),I({result:H}),J.threadTree,F({threadId:W}).strict(),F({confirmed:N()}).strict();let wd=[`codex-desktop`,`web`,`web-desktop-shell`,`web-mobile`,`ssh-remote`,`cli`],Td=[`darwin`,`win32`,`linux`],Ed=[`arm64`,`x64`,`ia32`,`arm`],Dd=[`zh`,`en`,`ja`,`ko`,`de`,`fr`,`es`,`pt`,`ru`,`other`],Od=[`codex`,`claude-code`,`antigravity`,`pi`,`opencode`,`cursor-cli`,`deepseek-harness`,`grok`,`omp`,`qwen-code`,`kiro-cli`,`codebuddy`,`workbuddy`,`devin`,`hermes`,`qoder`,`qoder-cn`,`kimi-code`,`zcode`,`copilot`,`custom`],kd=[`official-relay`,`self-hosted-relay`,`tailscale-serve`,`tailscale-funnel`,`tailscale-ip`,`lan`,`custom-proxy`,`remote-peer`],Ad=k().min(1).max(40).regex(/^[0-9A-Za-z._+-]+$/u),jd=B(wd),Md=B(Dd),Nd=B(Od),Pd=B(kd);new Set(Od),new Set(Dd),F({enabled:N(),forcedOffByEnv:N()}).strict(),F({enabled:N()}).strict(),F({surfaces:P(jd).max(12).optional(),harnesses:P(Nd).max(32).optional(),remoteAccess:P(Pd).max(12).optional()}).strict(),F({dailyActive:V(!0).optional(),weeklyActive:V(!0).optional(),monthlyActive:V(!0).optional(),newInstall:V(!0).optional(),retainedD1:V(!0).optional(),retainedD7:V(!0).optional(),remoteAny:V(!0).optional(),appVersion:Ad.optional(),codexDesktopVersion:Ad.optional(),os:B(Td).optional(),arch:B(Ed).optional(),uiLanguage:Md.optional(),surfaces:P(jd).min(1).max(12).optional(),harnesses:P(Nd).min(1).max(32).optional(),remoteAccess:P(Pd).min(1).max(12).optional()}).strict().refine(e=>Object.keys(e).length>0,{message:`Telemetry heartbeat must contain at least one countable field`});let Fd=4e3,Id={threadId:W};R(`action`,[I({...Id,action:B([`get`,`pause`,`resume`,`clear`])}),I({...Id,action:B([`create`,`edit`]),objective:k().trim().min(1).refine(e=>Array.from(e).length<=Fd,`A goal objective can have up to ${Fd} characters.`)})]),F({goal:F({threadId:W,objective:k(),status:B([`active`,`paused`,`blocked`,`usageLimited`,`budgetLimited`,`complete`]),tokenBudget:M().positive().nullable().default(null),tokensUsed:M().nonnegative(),timeUsedSeconds:M().nonnegative()}).nullable()});let Ld=k().trim().min(1),Rd=k().min(1),zd=F({icon:k().nullable(),color:k().nullable()}),Bd=zd.nullable(),Vd={create:{method:`codexhost/thread/sections/create`,params:F({name:Ld}).strict()},update:{method:`codexhost/thread/sections/update`,params:F({sectionId:Rd,name:Ld,appearance:zd.strict().nullable().optional()}).strict()},delete:{method:`codexhost/thread/sections/delete`,params:F({sectionId:Rd}).strict()}};R(`status`,[F({status:V(`unknown`)}),F({status:V(`confirmed`),sectionId:Rd,section:F({id:Rd,name:k().min(1),appearance:Bd}).nullable(),syncPending:N()})]),[Vd.create.method,Vd.update.method,Vd.delete.method,...xd],F({threadSectionsV1:V(!0).optional(),complete:V(!1).optional(),sections:P(F({id:k().min(1),name:k().min(1),appearance:Bd.optional(),threads:P(ul)}))}),F({threadId:k().min(1).max(1024),sectionId:k().min(1).max(1024).nullable(),beforeThreadId:k().min(1).max(1024).nullable().optional(),expectedSourceSectionId:k().min(1).max(1024).optional()}).refine(e=>e.expectedSourceSectionId===void 0||e.sectionId===null),F({threadIds:P(k().min(1))}).strict(),F({threadId:k().min(1).max(1024),pinned:N()}).strict(),F({}).strict(),F({parents:z(k().min(1),k().min(1))}).strict(),F({prompt:k().max(16384).optional()}).strict(),F({projects:P(F({id:k(),name:k(),rootPaths:P(k()),createdAt:j().int().optional()})),nativeProjects:V(!0).optional(),assignments:z(k(),k()),projectless:P(k()),pinned:P(k()),sectionProjects:z(k(),P(k())).optional(),pinnedProjects:P(k()).optional()});let Hd=z(k(),vc()),Ud=F({epoch:k().uuid(),sequence:j().int().nonnegative()});R(`type`,[F({type:V(`projects-changed`),cursor:Ud}),F({type:V(`skills-changed`),cursor:Ud,cwd:k().optional()}),F({type:V(`harness-inspection-changed`),cursor:Ud,harnessId:k().min(1)}),F({type:V(`display-settings-changed`),cursor:Ud}),F({type:V(`sections-changed`),cursor:Ud}),F({type:V(`preferences-changed`),cursor:Ud,revision:j().int().nonnegative()}),F({type:V(`extensions-changed`),cursor:Ud,revision:td}),F({type:V(`hello`),version:V(1),cursor:Ud,reset:N()}),F({type:V(`changed`),cursor:Ud,threadId:k().min(1),method:k().min(1)})]);let Wd=R(`type`,[F({type:V(`text`),id:k(),prompt:k(),secret:N().optional(),optional:N().optional()}),F({type:V(`choice`),id:k(),prompt:k(),multiple:N(),allowOther:N(),optional:N().optional(),options:P(F({value:k(),label:k(),description:k().optional()}))})]),Gd=R(`type`,[F({type:V(`approval`),title:k(),description:k().optional(),subject:vc().optional(),actions:P(F({id:k(),label:k(),effect:k()}))}),F({type:V(`question`),title:k().optional(),questions:P(Wd)})]),Kd=F({requestId:L([k(),j().int()]),threadId:k(),kind:B([`approval`,`question`]),interaction:Gd,request:Hd}),qd=F({id:k().min(1),clientUserMessageId:k().min(1),input:P(Hd),presentationInput:P(Hd).nullable().optional()}).passthrough();F({fields:P(F({path:P(L([k(),j().int().nonnegative()])),originalLength:j().int().nonnegative()}))});let Jd=F({id:k().min(1),status:k().min(1),codexhostTurnOutcome:F({status:V(`unknown`),reason:k()}).optional(),items:P(F({id:k().min(1),type:k().min(1)}).passthrough()),codexhostFileOperations:P(F({beforeItemId:k().nullable(),item:F({id:k().min(1),type:k().min(1)}).passthrough()})).optional(),error:F({message:k().optional()}).passthrough().nullable().optional(),fingerprint:k().min(1).optional(),unchanged:V(!0).optional()}).passthrough(),Yd=F({id:k().min(1).max(512),fingerprint:k().min(1).max(128)});F({threadId:k().min(1),knownTurns:P(Yd).max(64).optional(),truncateToolOutput:N().optional()});let Xd=F({harnessId:k().min(1),nativeSessionId:k().min(1)});F({cursor:Ud,activeTurnId:k().min(1).nullable().optional(),command:F({name:k().min(1),turn:Jd,subsequentTurnId:k().min(1).optional()}).optional(),thread:F({id:k().min(1),cwd:k(),modelProvider:k().min(1),createdAt:j(),updatedAt:j(),recencyAt:j().nullable().optional(),status:F({type:k()}).passthrough(),name:k().nullable().optional(),preview:k().optional(),codexhostImportSource:Xd.optional(),turns:P(Jd).length(0)}).passthrough(),turnsPage:F({data:P(Jd).max(5),nextCursor:k().nullable()}),configuration:F({codexCollaborationMode:B([`plan`,`default`]).optional(),native:F({model:k().min(1).max(1024).optional(),reasoningEffort:k().min(1).max(128).optional()}).optional(),effectiveModel:K.optional(),effectiveThinkingOptionId:q.optional(),effectivePermissionModeId:yl.optional()}),queue:F({items:P(qd),pausedReason:B([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:P(Kd),handoff:Sl.optional()}),F({version:V(1),owner:V(`service`).optional(),pid:j().int().positive(),port:j().int().min(1).max(65535),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j(),epoch:k().uuid(),capabilities:F({peerDelegation:V(1).optional(),threadReferenceContext:V(1).optional()}).optional()}),F({epoch:k().uuid(),threadId:k().min(1),requestId:L([k(),j().int()]),result:Hd}),F({includeArchived:N().optional(),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional(),scope:L([F({cwd:k().min(1).max(4096),excludeCwds:P(k().min(1).max(4096)).max(1024)}).strict(),F({projectId:k().min(1).max(1024),legacyThreadIds:P(k().min(1).max(1024)).max(1024),rootPaths:P(k().min(1).max(4096)).max(1024).optional()}).strict()]).optional()}).strict(),F({threads:P(ul),ownership:P(Zl),archivedThreadIds:P(W),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional()}).strict(),su.pick({id:!0,name:!0,icon:!0,iconStyle:!0});let Zd=I({threadId:k().max(1024),title:k().max(240),project:k().max(240),harness:I({id:k().min(1).max(128),name:k().min(1).max(128)}).optional(),state:B([`idle`,`running`,`waiting`,`completed`,`failed`]),updatedAt:j().nonnegative()});I({epoch:k().max(128),revision:M().nonnegative(),running:M().nonnegative(),waiting:M().nonnegative(),sessions:P(Zd).max(32).default([]),notifications:P(I({threadId:k().max(1024),key:k().max(4096),kind:B([`completed`,`failed`,`approval`,`question`]),revision:M().nonnegative()})).max(256)});let Qd=k().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);F({available:N()}).strict(),F({path:k().min(1),mimeType:Qd}).strict();let $d=B([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);R(`ok`,[F({ok:V(!0),text:k()}).strict(),F({ok:V(!1),error:F({code:$d}).strict()}).strict()]),F({threadId:W.optional(),cwd:k().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let ef=F({name:k().min(1).regex(/^[^\s[\]]+$/u),description:k().optional(),path:k().min(1),scope:B([`project`,`global`]),source:k().min(1)}).strict();F({revision:j().int().nonnegative(),complete:N(),skills:P(ef),warnings:P(k()).optional()}).strict(),F({cwd:k().min(1).optional()}).strict();let tf=F({kind:B([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:k().min(1)}).strict(),nf=R(`status`,[F({status:V(`not-installed`)}),F({status:V(`not-running`)}),F({status:V(`not-logged-in`)}),F({status:V(`https-disabled`)}),F({status:V(`not-serving`),command:k()}),F({status:V(`occupied`),target:k()}),F({status:V(`serving`),url:k(),funnel:N()}),F({status:V(`error`),message:k()})]);F({state:nf,error:k().optional()}).strict();let rf=R(`status`,[F({status:V(`on`)}),F({status:V(`off`)}),F({status:V(`invalid`),reason:k()})]),af=F({lan:N(),autostart:rf}).strict(),of=F({expiresAt:k().optional(),issuing:N(),failure:F({detail:k().optional(),retryAt:k(),paused:N()}).optional()}),sf=R(`status`,[F({status:V(`off`),reason:B([`invite`,`name-taken`,`banned`]).optional()}),F({status:V(`connecting`),reason:B([`full`,`unreachable`]).optional()}),F({status:V(`connected`),url:k(),certificate:of}),F({status:V(`missing-certificate`),url:k(),certificate:of}),F({status:V(`stopped`),reason:B([`replaced`,`rejected`,`unsupported-version`])})]);k().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i).transform(e=>e.toLowerCase()),k().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let cf=B([`official`,`self-hosted`]);F({secret:k().min(1),lastUsedAt:j().nullable(),networkUrls:P(tf),directCandidates:P(tf).optional(),tailscale:nf,background:af.optional(),relay:F({state:sf,enabled:N(),kind:cf,officialHost:k(),customHost:k().optional(),officialHostname:k().optional(),customHostname:k().optional(),quotaUntil:k().optional()}).strict().optional()}).strict();let lf=I({threadId:k().min(1).max(1024),view:B([`result`,`messages`]),from:j().int().min(1).max(2**53-1).optional(),to:j().int().min(1).max(2**53-1).optional()}),uf=/^[a-zA-Z0-9_-]{1,64}$/u,Y=k().regex(uf),df=k().regex(uf),ff=k().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),pf=B([`relay`,`tailscale`,`lan`,`custom`]),mf=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],hf=B(mf);new Set(mf);let gf=B([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]),_f=F({peerId:Y,hostId:ff,nodeId:df.optional(),name:k().min(1).max(120),color:hf.optional(),origin:k().min(1).max(2048),transportKind:pf,encrypted:N(),enabled:N(),state:gf,supportsPeerPairing:N().optional(),pairedBack:N().optional(),linkedPeerIds:P(Y).max(128).optional(),latencyMs:j().int().nonnegative().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),lastError:k().max(1e3).optional(),projectCount:j().int().nonnegative(),createdAt:k(),updatedAt:k()});F({localPlatform:k().max(64).optional(),peers:P(_f)}),F({connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),name:k().trim().min(1).max(120).optional(),color:hf.optional(),pairBack:N().optional(),meshPeerIds:P(Y).max(64).optional(),selfOrigin:k().min(1).max(2048).optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),I({origin:k().min(1).max(2048),token:k().min(1).max(2048),name:k().trim().min(1).max(120).optional(),color:hf.optional(),expectedNodeId:df.optional()}),F({status:B([`added`,`updated`,`existing`]),peerId:Y,hostId:ff,nodeId:df.optional()});let vf=B([`added`,`updated`,`existing`,`failed`,`skipped`]);F({results:P(F({targetPeerId:Y,targetName:k().min(1).max(120),introducedHost:L([V(`local`),Y]),introducedName:k().min(1).max(120),status:vf,error:k().max(1e3).optional()}))}),F({peerIds:P(Y).max(64).optional(),includeSelf:N().optional(),includeMesh:N().optional(),selfOrigin:k().min(1).max(2048).optional()}),F({peerId:Y,name:k().trim().min(1).max(120).optional(),color:hf.nullable().optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),enabled:N().optional()}),F({peerId:Y}),F({removed:N()}),F({peerId:Y.optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let yf=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});F({ok:N(),nodeId:df.optional(),supportsPeerPairing:N().optional(),pairedBack:N().optional(),latencyMs:j().int().nonnegative().optional(),origin:k().max(2048).optional(),transportKind:pf.optional(),encrypted:N().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),projectCount:j().int().nonnegative().optional(),projects:P(yf).optional(),error:k().max(1e3).optional()});let bf=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192),threadIds:P(k().min(1).max(1024))}),xf=F({attachments:V(1).optional(),workspaceFiles:V(1).optional(),officePreview:V(1).optional(),delegation:V(1).optional(),peerPairing:V(1).optional()}),Sf=F({version:k().max(128),platform:k().max(64),hostname:k().max(255),homeDir:k().max(4096).optional(),epoch:k().min(1).max(256),nodeId:df.optional(),peerNodes:z(ff,df).refine(e=>Object.keys(e).length<=128).optional(),projects:P(bf),capabilities:xf.optional()});I({threadId:k().min(1).max(1024),scope:k().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u).optional(),requestId:k().min(1).max(256).optional(),mode:B([`queue`,`steer`]).optional(),expectedTurnId:k().min(1).max(1024).nullable().optional(),content:P(R(`type`,[I({type:V(`text`),text:k()}),I({type:V(`file`),receiptId:k().min(1).max(128)})])).min(1).max(64)});let Cf=F({ok:V(!1),error:F({code:k(),message:k(),details:z(k(),vc()).optional()})});L([F({ok:V(!0),value:F({receiptId:k().min(1),file:F({attachmentId:k(),name:k(),bytes:j().int().nonnegative()})})}),Cf]),L([F({ok:V(!0),value:F({accepted:V(!0)})}),Cf]);let wf=F({name:k().min(1).max(512),path:k().min(1).max(8192),kind:V(`directory`)});F({peerId:Y,path:k().min(1).max(8192).optional()}),F({path:k().min(1).max(8192),parentPath:k().min(1).max(8192).nullable(),homeDir:k().min(1).max(8192).optional(),entries:P(wf)}),F({peerId:Y,parentPath:k().min(1).max(8192),name:k().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),F({path:k().min(1).max(8192),name:k().min(1).max(255)}),F({peerId:Y,path:k().min(1).max(8192),title:k().trim().min(1).max(255).optional()}),F({peerId:Y,workspaceId:k().min(1).max(1024),title:k().trim().min(1).max(255)}),F({peerId:Y,workspaceId:k().min(1).max(1024)}),F({workspaceId:k().min(1).max(1024).optional(),manifest:Sf}),F({sessionHostId:k().min(1).max(128).optional()}),F({hosts:P(F({hostId:L([V(`local`),ff]),name:k().min(1).max(120),isLocal:N().optional(),color:hf.optional(),hostname:k().max(255).optional()}))}),F({hostId:L([V(`local`),ff])}),F({harnesses:P(F({id:k().regex(/^[a-z0-9][a-z0-9-]*$/u),name:k().min(1).max(120)}))});let Tf=B([`listHarnesses`,`inspect`,`start`,`send`,`cancel`,`read`,`answer`,`list`]);I({operation:Tf,hopCount:j().int().min(0).max(16),sourceId:Y.optional(),input:ul});let Ef=I({code:k().min(1).max(128),message:k().max(4096),details:ul.optional()});L([I({ok:V(!0),value:H}),I({ok:V(!1),error:Ef})]);let Df=I({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});I({hosts:P(I({hostId:ff,nodeId:df.optional(),displayName:k().min(1).max(120),online:N(),state:gf,delegation:N(),projects:P(Df),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional()}))}),I({version:V(1),instanceId:k().min(1).max(128),pid:j().int().positive(),endpoint:k().min(1).max(256),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j().int().nonnegative()}),L([I({operation:V(`hosts`)}),I({operation:Tf,hostId:ff,hopCount:j().int().min(0).max(16),timeoutMs:j().int().min(1).max(12e4).optional(),input:ul})]);let Of=F({id:k().min(1).max(256),harnessId:k().min(1),label:k().min(1).max(512),provider:B([`openai-codex`,`xai`])}).strict(),kf=k().regex(/^[a-z][a-z0-9-]{0,47}$/),Af=F({name:kf,source:Of,importedAt:k()}).strict(),jf=R(`action`,[F({action:V(`list`)}).strict(),F({action:V(`import`),sourceId:k().min(1).max(256),name:kf,confirmed:V(!0)}).strict(),F({action:V(`reimport`),sourceId:k().min(1).max(256),name:kf,confirmed:V(!0)}).strict(),F({action:V(`remove`),name:kf,confirmed:V(!0)}).strict()]),Mf=F({provider:k().min(1).max(128),type:B([`oauth`,`api_key`,`unknown`]),label:k().min(1).max(512).optional(),vendor:B([`openai-codex`,`xai`]).optional()}).strict();F({sources:P(Of),targets:P(F({harnessId:k(),providers:P(B([`openai-codex`,`xai`])),imports:P(Af),others:P(Mf).default([])}).strict())}).strict(),F({targetHarnessId:k().min(1).max(128).optional(),request:jf}).strict(),F({events:N()});let Nf=P(I({agent:k().min(1).max(128),section:B([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);I({entries:Nf.nullable()}),I({}),I({entries:Nf,initializeOnly:N().optional()});let Pf=I({enabled:N(),timeoutMinutes:j().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let Ff=k().regex(/^external$/u),If=U.transform(e=>String(e)),Lf=I({model:K.optional(),thinkingOptionId:q.optional(),permissionModeId:yl.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`);R(`mode`,[I({mode:V(`global`)}),I({mode:V(`last`)}),I({mode:V(`manual`),harnessId:U})]);let Rf=I({lastHarness:U.optional(),byHarness:z(If,Lf)}),zf=I({model:K.optional(),thinkingOptionId:q.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),Bf=I({byHarness:z(If,zf)}),Vf=k().min(1).max(1024),Hf=I({idleRelease:Pf.optional(),favorites:z(If,P(Vf).max(2048)).default({}),newThread:Rf.optional(),delegation:Bf.optional()});I({scope:Ff,revision:j().int().nonnegative(),values:Hf}),I({scope:Ff.default(`external`)});let Uf=R(`kind`,[I({kind:V(`idleRelease`),value:Pf}),I({kind:V(`favorite`),harnessId:U,modelId:Vf,enabled:N()}),I({kind:V(`favorites`),harnessId:U,modelIds:P(Vf).max(2048)}),I({kind:V(`newThread`),lastHarness:U.optional(),harnessId:U.optional(),configuration:Lf.optional()}),I({kind:V(`delegation`),harnessId:U,configuration:zf.nullable()})]);I({scope:Ff.default(`external`),operations:P(Uf).min(1).max(256),initializeOnly:N().optional(),expectedRevision:j().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),I({version:V(1),revision:j().int().nonnegative(),scopes:z(Ff,Hf)});let Wf=j().finite().nonnegative(),Gf=I({input:Wf,output:Wf,cacheRead:Wf.optional(),cacheWrite:Wf.optional(),cacheWrite1h:Wf.optional()}),Kf=k().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);I({path:k(),entries:P(I({key:k(),price:Gf})),error:k().nullable()}),I({}),I({key:Kf,price:Gf.nullable(),previousKey:Kf.optional()}),I({model:Kf});let qf=I({official:N().optional(),canonicalModelId:k().min(1).optional(),provider:k().min(1).max(512),model:k().min(1).max(512),price:Gf});I({price:Gf.nullable(),suggestions:P(qf).max(6).optional()});let Jf=[`today`,`7d`,`30d`,`90d`,`all`],X=j().int().min(0).max(2**53-1),Yf=k().regex(/^\d{4}-\d{2}-\d{2}$/u),Xf=k().min(1).max(128),Zf=k().min(1).max(512),Qf=k().min(1).max(4096);I({range:B(Jf),timeZone:k().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:Xf.optional(),model:Zf.nullable().optional(),project:Qf.nullable().optional(),date:Yf.optional()});let $f=I({requests:X,inputTokens:X,cachedInputTokens:X,cacheWriteInputTokens:X,cacheKnownInputTokens:X,cacheHitCachedInputTokens:X,cacheHitInputTokens:X,outputTokens:X,reasoningOutputTokens:X,costUsd:j().finite().min(0),unpricedRequests:X,unmeteredRequests:X}),ep=$f.shape,tp=I({harness:Xf,sessionId:k().min(1).max(512),project:Qf.nullable(),title:k().min(1).max(200).optional(),models:P(Zf).max(16),firstAtMs:X,lastAtMs:X,...ep});I({range:B(Jf),from:Yf.nullable(),to:Yf,filters:I({harness:Xf.nullable(),model:Zf.nullable(),unknownModel:N(),project:Qf.nullable(),unknownProject:N(),date:Yf.nullable()}),reading:I({complete:N(),sources:X,read:X}),failures:P(I({harness:Xf,message:k().max(2048)})).max(256),options:I({harnesses:P(Xf).max(256),models:P(Zf.nullable()).max(4096),projects:P(Qf.nullable()).max(4096)}),modelLabels:P(I({harness:Xf,model:Zf,label:Zf})).max(4096).optional(),credits:P(I({harness:Xf,model:Zf.nullable(),credits:j().finite().min(0),reportedRequests:X,requests:X})).max(4096).optional(),totals:$f,daily:P(I({date:Yf,harness:Xf,...ep})).max(2e5),hourly:P(I({weekday:j().int().min(0).max(6),hour:j().int().min(0).max(23),...ep})).max(168),byHarness:P(I({harness:Xf,...ep})).max(256),byModel:P(I({model:Zf.nullable(),...ep,harnessPricedRequests:X})).max(4096),byProject:P(I({project:Qf.nullable(),...ep})).max(4096),sessions:P(tp).max(100),recentSessions:P(tp).max(100).optional()}),F({threadId:W}),F({discarded:N()});let np=R(`type`,[F({id:k().min(1),type:V(`choice`),prompt:k(),options:P(F({value:k().min(1),label:k(),description:k().optional()})).min(1),multiple:N(),allowOther:N(),optional:N()}),F({id:k().min(1),type:V(`text`),prompt:k(),multiline:N(),secret:V(!1),optional:N(),placeholder:k().optional(),prefill:k().optional()})]),rp=F({interactionId:k().min(1),turnId:k().min(1),title:k().optional(),questions:P(np).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});I({threadId:k().min(1)}),F({questions:P(rp)}),I({threadId:k().min(1),turnId:k().min(1),interactionId:k().min(1),answers:z(k(),P(k())),cancelled:N().default(!1)}),F({accepted:V(!0)});let ip=`codexhostActiveTurnId`,ap=/* @__PURE__ */ new Set([ip,`codexhostTurnChanges`,`codexhostToolOutput`,`codexGoal`]),op=F({path:k(),oldText:k().nullable(),newText:k()});F({sessionId:k().min(1),turn:j().int().nonnegative(),path:k().min(1).optional()}),F({diffs:P(op)}),I({}),I({}),F({reference:F({sessionId:k().min(1),epoch:k().min(1),turn:j().int().nonnegative(),seq:j().int().nonnegative(),callId:k().min(1),part:j().int().nonnegative(),version:k().min(1)}),length:j().int().nonnegative(),bytes:j().int().nonnegative()}),I({title:k().trim().min(1).max(200),type:B([`info`,`warning`,`danger`]),body:k().trim().min(1).max(16384)}),I({}),I({url:k().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status.codexhost/update/macos-signing/status.codexhost/update/macos-signing/setup.codexhost/update/macos-signing/remove`.split(`.`));let sp=B([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),cp=B([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);I({threadId:k(),title:k(),harnessId:k(),state:sp,reason:cp,inactiveMs:j().nonnegative()}),I({threadId:W,turnId:_l});let lp=F({email:k().trim().min(1).max(320).optional(),label:k().trim().min(1).max(256).optional(),plan:k().trim().min(1).max(128).optional(),credits:Pl.optional(),balance:Fl.optional()}).strict();function up(e){return e.refine(e=>{let t=e;return t.credits!==void 0||t.balance!==void 0},{message:`Account must report either credits or a balance`})}let dp=up(lp),fp={harnessId:U,harnessName:k().trim().min(1).max(128)},pp=F(fp).strict();F({}).strict(),F({sources:P(pp).max(128)}).strict(),F({harnessId:U,refresh:N().optional()}).strict(),F({...fp,account:dp.nullable(),accounts:P(dp).max(8).optional()}).strict(),F({refresh:N().optional()}).strict(),F({accounts:P(up(lp.extend(fp))).max(128)}).strict(),F({harnessId:eu,model:K.optional(),thinkingOptionId:q.optional(),permissionModeId:yl.optional(),prewarm:V(!0).optional()}).strict();let mp=k().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);F({harnessId:eu}).strict().extend({path:mp.nullable()}),F({path:mp.nullable(),restartRequired:N()}).strict(),F({harnessId:U,action:B([`check`,`update`,`install`]),confirmedVersion:k().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let hp=F({currentVersion:k().min(1).max(128),latestVersion:k().min(1).max(128),updateAvailable:N(),canUpdate:N(),latestVerifiedVersion:k().min(1).max(128).optional(),confirmationRequired:V(!0).optional(),versionKind:B([`cli`,`application`]).optional(),manualUpdateUrl:Xs().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:k().max(2048).optional(),messageCode:k().min(1).max(128).optional(),notice:hl.optional(),latestVersionKind:B([`unknown`,`tracking-branch`]).optional()}).strict();F({taskId:k().uuid()}).strict(),R(`status`,[F({taskId:k().uuid(),status:V(`running`)}).strict(),F({taskId:k().uuid(),status:V(`succeeded`),result:hp}).strict(),F({taskId:k().uuid(),status:V(`failed`),error:F({code:j().int(),message:k().min(1).max(2048)}).strict()}).strict()]);let gp=k().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),_p=k().trim().min(1),vp=B([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),yp=F({accountId:gp,label:_p.max(256),email:k().email().max(320).optional(),planType:vp.optional()}).strict(),bp=B([`ready`,`unavailable`]);F({version:V(2),currentAccountId:gp.nullable(),phase:bp,revision:j().int().nonnegative(),instanceId:_p.max(1024).optional(),accounts:P(yp).max(1)}).strict(),F({accountId:gp,refresh:N().optional()}).strict(),F({accountId:gp,usage:Ol.nullable(),accountCredits:Pl.optional(),freshness:B([`live`,`cached`]),observedAt:k().datetime().nullable()}).strict();let xp=1e3,Sp=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Cp=Sp.max(1024),wp=F({nativeSessionId:Cp,title:Sp.max(4096).nullable(),updatedAt:j().int().nonnegative().max(864e13),cwd:Sp.max(16384),running:N().nullable()}).strict();F({}).strict(),F({harnesses:P(F({harnessId:eu,name:Sp.max(128)}).strict()).max(128)}).strict(),F({harnessId:eu,query:k().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:j().int().nonnegative().safe().optional(),limit:j().int().min(1).max(xp).optional()}).strict(),F({candidates:P(wp).max(xp),total:j().int().nonnegative().safe()}).strict(),F({harnessId:eu,nativeSessionId:Cp}).strict(),F({threadId:Sp.max(1024).pipe(W)}).strict();let Tp=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Ep=Cp,Dp=wp;F({}).strict(),F({candidates:P(Dp).max(1e3)}).strict(),F({nativeSessionId:Ep}).strict(),F({threadId:Tp.max(1024).pipe(W)}).strict(),F({threadId:W,lastTurnId:_l}).strict(),F({threadId:W}).strict();let Op=k().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();F({commands:P(F({id:Op,invocation:k().min(1).max(128),label:k().trim().min(1).max(128),description:k().trim().min(1).max(512).optional(),localizations:ml.optional(),argumentMode:B([`none`,`text`]),kind:B([`command`,`skill`]).optional()}).strict()),warnings:P(k().min(1)).optional(),source:B([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),F({harnessId:U,cwd:k().min(1).optional()}).strict(),F({threadId:W}).strict(),F({threadId:W,commandId:Op,turnId:_l.optional(),arguments:ul.optional()}).strict(),F({accepted:V(!0),turnId:_l.optional()}).strict();let kp=V(`2.0`).optional(),Z=bc().optional(),Ap=k().min(1),jp=L([k(),j().int()]),Mp=F({code:j().int(),message:k(),data:H.optional()}).catchall(H).superRefine(al([`data`]));L([F({jsonrpc:kp,id:jp,method:Ap,params:H.optional(),result:Z,error:Z}).catchall(H).superRefine(al([`jsonrpc`,`params`,`result`,`error`])),F({jsonrpc:kp,id:Z,method:Ap,params:H.optional(),result:Z,error:Z}).catchall(H).superRefine(al([`jsonrpc`,`id`,`params`,`result`,`error`])),F({jsonrpc:kp,id:jp,method:Z,params:Z,result:H,error:Z}).catchall(H).superRefine(al([`jsonrpc`,`method`,`params`,`error`])),F({jsonrpc:kp,id:jp,method:Z,params:Z,result:Z,error:Mp}).catchall(H).superRefine(al([`jsonrpc`,`method`,`params`,`result`]))]);let Np=k().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});I({harnessId:U,nativeSessionId:Np,locator:H.optional(),formatVersion:V(1)}).superRefine(al([`locator`])),I({harnessId:U,nativeSessionId:Np,nativeTurnKey:Np,formatVersion:V(1)}),I({harnessId:U,nativeSessionId:Np,checkpointId:Np,locator:H.optional(),formatVersion:V(1)}).superRefine(al([`locator`]));let Pp=k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Fp=B([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Ip=B([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),Lp=I({completed:j().int().nonnegative(),total:j().int().positive()}).refine(e=>e.completed<=e.total,{path:[`completed`],message:`completed must not exceed total`}),Rp=I({version:Pp,installation:Fp,phase:Ip,updatedAt:j().int().nonnegative(),downloadedBytes:j().int().nonnegative().optional(),totalBytes:j().int().positive().optional(),npmDownload:Lp.optional(),error:k().min(1).max(500).nullable(),serviceStopOutput:k().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});I({});let zp=k().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`),Bp=B([`idle`,`downloading`,`ready`,`failed`]),Vp=I({downloadedBytes:j().int().nonnegative(),totalBytes:j().int().positive()}).refine(e=>e.downloadedBytes<=e.totalBytes,{path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`});F({currentVersion:Pp,installation:Fp.nullable(),latestVersion:Pp.nullable(),updateAvailable:N(),installationAvailable:N(),releaseNotes:k().min(1).max(2e4).nullable(),releaseNotesUrl:zp.nullable(),status:Rp.nullable(),error:k().min(1).max(500).nullable(),stagedVersion:Pp.nullable().optional(),backgroundPhase:Bp.optional(),backgroundDownload:Vp.nullable().optional(),backgroundError:k().min(1).max(500).nullable().optional(),runningTaskCount:j().int().nonnegative().optional()}),I({status:Rp}),I({status:Rp.nullable()}),I({supported:N(),enabled:N(),certificatePresent:N(),appSignedWithLocalCert:N(),appPath:k().min(1).nullable(),certificateName:k().min(1),certificateSha1:k().regex(/^[0-9A-Fa-f]{40}$/u).nullable()});let Hp=I({icon:k().min(1).max(16).optional(),title:k().min(1).max(120),body:k().min(1).max(1200),contributors:P(k().min(1).max(39)).max(30)}),Up=I({summary:k().min(1).max(600).optional(),themes:P(Hp).min(1).max(12)}),Wp=I({version:Pp,publishedAt:il(),url:k().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:Up.nullable(),en:Up.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});I({manual:N().optional()}),I({announcement:Wp.nullable(),unread:N()}),I({version:Pp}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Gp=B([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);F({runningVersion:k().nullable(),installedVersion:k().nullable(),restartRequired:N(),remote:N(),updateSupported:N(),update:F({phase:Gp,targetVersion:k().nullable(),error:k().nullable()})});let Kp=F({version:k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();F({hostname:k().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),action:B([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:N().optional(),version:k().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),F({state:B([`installed`,`not-installed`])}).strict();let Q=k().min(1).max(1024),qp={hostId:Q.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},$={...qp,threadId:Q},Jp=k().min(1).max(8e3),Yp={text:Jp,requestId:Q};R(`accepted`,[F({accepted:V(!0),startQueuedItemId:Q.optional()}),F({accepted:V(!1),code:B([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:k()})]),R(`available`,[F({available:V(!1)}),F({available:V(!0),items:P(F({id:Q,clientUserMessageId:Q,preview:k().max(801)})).max(100)})]);let Xp=R(`kind`,[I({kind:V(`hosts`)}),I({kind:V(`create`),...qp,cwd:k().min(1).max(8192),epoch:Q}),I({kind:V(`projectHarnesses`),...qp,epoch:Q}),I({kind:V(`inspectHarness`),...qp,epoch:Q,cwd:k().min(1).max(8192),harnessId:Q}),I({kind:V(`startSelected`),...qp,epoch:Q,cwd:k().min(1).max(8192),harnessId:Q,model:k().min(1).max(4096),serviceTier:B([`priority`,`ultrafast`]).optional(),reasoningEffort:Q.optional()}),I({kind:V(`status`),...$}),I({kind:V(`list`),...qp,cursor:k().nullable(),archived:N(),includeLoaded:V(!0).optional()}),I({kind:V(`read`),...$,page:I({cursor:k().min(1).max(8192).nullable(),epoch:Q.optional(),sortDirection:B([`asc`,`desc`]).optional(),limit:j().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),I({kind:V(`usage`),...$,epoch:Q}),I({kind:V(`configure`),...$,epoch:Q,modelId:Q.optional(),serviceTier:Rl.optional(),thinkingOptionId:Q.optional(),permissionModeId:Q.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),I({kind:V(`prompt`),...$,epoch:Q,text:Jp,requestId:Q.optional()}),I({kind:V(`queue`),...$,epoch:Q}),I({kind:V(`delivery`),...$,epoch:Q,action:R(`kind`,[I({kind:V(`enqueue`),...Yp}),I({kind:V(`steer`),...Yp,turnId:Q}),I({kind:V(`remove`),itemId:Q}),I({kind:V(`start`),itemId:Q,onlyIfHead:V(!0).optional()}),I({kind:V(`sendNow`),itemId:Q})])}),I({kind:V(`interrupt`),...$,epoch:Q,turnId:Q}),I({kind:V(`rename`),...$,epoch:Q,name:k().min(1).max(512)}),I({kind:V(`archive`),...$,epoch:Q,archived:N()}),I({kind:V(`respond`),...$,epoch:Q,requestId:L([Q,j().int()]),result:z(k(),vc())})]),Zp=k().min(1).max(1024),Qp=F({hostId:Zp,displayName:k().min(1).max(1024),source:B([`codex-managed`,`discovered`]),sshAlias:k().max(1024).nullable(),sshHost:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),autoConnect:N(),connectionAnalyticsId:k().max(1024).optional()}),$p=I({displayName:k().min(1).max(1024),hostname:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable()});R(`action`,[I({action:V(`session`),operation:Xp}),I({action:V(`list`)}),I({action:V(`catalog`)}),I({action:V(`read-thread`),hostId:Zp.refine(e=>e!==`local`),input:lf}),I({action:V(`save`),draft:$p,previous:Qp.nullable()}),I({action:V(`remove`),previous:Qp}),I({action:V(`connect`),hostId:Zp,enabled:N()}),I({action:V(`state`),hostId:Zp}),I({action:V(`runtime`),hostId:Zp}),I({action:V(`update`),hostId:Zp.refine(e=>e!==`local`),version:Kp.shape.version})]),L([I({result:H}),I({error:I({code:j().int(),message:k()})})]),I({prompt:k().trim().min(1).max(2e3),cwd:k().max(4096).nullable()}),k().trim().min(1).max(60).nullable();let em=k().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),tm=L([k(),F({en:k()}).catchall(k())]),nm=F({title:tm.optional(),description:tm.optional(),icon:k().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:k().optional()});F({extensions:P(F({id:em,name:k().min(1).max(214),version:k().min(1).max(128),format:V(`dsh`),supportedTargets:Oc([V(`web`)]),enabledTargets:P(V(`web`)).max(1),source:k().min(1).max(4096),projectUrl:k().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:k(),meta:nm.optional(),loadError:k().optional()})),loadedIds:P(em),safeMode:N(),storeError:k().optional()});let rm=k().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);F({spec:k().trim().min(1).max(4096),registry:rm.optional()}).strict(),F({id:em,enabled:N()}).strict(),F({id:em}).strict(),V(1);function im(e,t,n){let r=/* @__PURE__ */ new Map;for(let e of t)r.set(n(e),e);let i=e.map(e=>r.get(n(e))).filter(e=>e!==void 0),a=new Set(i.map(n));for(let e=0;e<t.length;e++){let r=t[e];
113
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function ko(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;ko(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}let Ao=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),jo=[`oneOf`,`anyOf`];function Mo(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function No(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Ao.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??Mo(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ae(n,r,e.length===1?e[0]:No(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=Mo(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function Po(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Ao)if(t in e)return;let n=t.filter(e=>jo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=No(t);else{let e=n[0],i=jo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>No([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,wo(e,r))}function Fo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):wo(i,s),wo(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())ko(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])Po(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}wo(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Ae(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Lo(t,`input`,e.processors),output:Lo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function T(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return T(r.element,n);if(r.type===`set`)return T(r.valueType,n);if(r.type===`lazy`)return T(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return T(r.innerType,n);if(r.type===`intersection`)return T(r.left,n)||T(r.right,n);if(r.type===`record`||r.type===`map`)return T(r.keyType,n)||T(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:T(r.in,n)||T(r.out,n);if(r.type===`object`){for(let e in r.shape)if(T(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(T(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(T(e,n))return!0;return!!(r.rest&&T(r.rest,n))}return!1}let Io=(e,t={})=>n=>{let r=To({...n,processors:t});return w(e,r),Oo(r,e),Fo(r,e)},Lo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=To({...i??{},target:a,io:t,processors:n});return w(e,o),Oo(o,e),Fo(o,e)},Ro=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},zo=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Bo=(e,t)=>{Ro(e,`minimum`,t),zo(e,`maximum`,t)},Vo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Ho=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Uo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Wo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Go=(e,t)=>Ro(e,`minimum`,t.minimum),Ko=(e,t)=>zo(e,`maximum`,t.maximum),qo=e=>(t,n)=>{Wo(t,n.format);let[r,i]=e[n.format];Ro(t,`minimum`,r),zo(t,`maximum`,i)},Jo={greater_than:(e,t)=>Ro(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>zo(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Vo(e,t.value),number_format:qo(Xe),bigint_format:qo(Ze),min_length:Go,max_length:Ko,length_equals:(e,t)=>Bo(e,t.length),min_size:Go,max_size:Ko,size_equals:(e,t)=>Bo(e,t.size),string_format:(e,t)=>{Wo(e,t.format),t.pattern&&Ho(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Uo(e,t.mime)};function E(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Jo[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Ro(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Ro(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&zo(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&zo(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Vo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Uo(t,i.mime);for(let e of i.patterns??[])Ho(t,e);return t}let Yo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Xo=/* @__PURE__ */ new Map([[Kr,kn],[Jr,An]]),Zo=e=>Xo.get(e)??e,Qo=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=E(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Yo[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Zo);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},$o=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=E(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):Eo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},es=(e,t,n,r)=>{n.type=`boolean`},ts=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ns=(e,t,n,r)=>{n.not={}},rs=(e,t,n,r)=>{let i=e._zod.def,a=be(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},is=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(Eo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(Eo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},as=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},os=(e,t,n,r)=>{Eo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},ss=(e,t,n,r)=>{Eo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},cs=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=E(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=w(a.element,t,{...r,path:[...r.path,`items`]})};function ls(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?ls(t.out):t.type===`catch`?ls(t.innerType):e._zod.optin}let us=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Eo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ae(i.properties,e,w(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?ls(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=w(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},ds=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>w(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},fs=(e,t,n,r)=>{let i=e._zod.def,a=w(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=w(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},ps=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>w(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?w(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?ls(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=E(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function ms(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=ms(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>ms(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Hn:Vn).source)),p}let hs=/* @__PURE__ */ new WeakMap;function gs(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of hs.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=ms(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}let _s=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=E(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=w(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ae(i.patternProperties,Zo(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=w(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=hs.get(t);n||(n=[],hs.set(t,n),t.deferred.push(()=>gs(t))),n.push(e)}i.additionalProperties=w(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&ls(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},vs=(e,t,n,r)=>{let i=e._zod.def,a=w(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},ys=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},bs=Symbol();function xs(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Eo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),bs):JSON.parse(o)}let Ss=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=xs(i.defaultValue,e,t,n,r);o!==bs&&(n.default=o)},Cs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=xs(i.defaultValue,e,t,n,r);o!==bs&&(n._prefault=o)},ws=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Eo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},Ts=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;w(o,t,r);let s=t.seen.get(e);s.ref=o},Es=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ds=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Os=(e,t,n,r)=>{let i=e._zod.innerType;w(i,t,r);let a=t.seen.get(e);a.ref=i},ks=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function As(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}let D=/*@__PURE__*/ y(`ZodError`,(e,t)=>{Ut.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);ks.has(n)||(ks.add(n),As(n,`format`,e=>t=>Kt(e,t)),As(n,`flatten`,e=>t=>Gt(e,t)),As(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Se,2)}),As(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Se,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),js=/* @__PURE__ */ Jt(D),Ms=/* @__PURE__ */ Yt(D),Ns=/* @__PURE__ */ Xt(D),Ps=/* @__PURE__ */ Qt(D),Fs=/* @__PURE__ */ an(D),Is=/* @__PURE__ */ on(D),Ls=/* @__PURE__ */ sn(D),Rs=/* @__PURE__ */ cn(D),zs=/* @__PURE__ */ ln(D),Bs=/* @__PURE__ */ un(D),Vs=/* @__PURE__ */ dn(D),Hs=/* @__PURE__ */ fn(D);function Us(){b.localeError||It(pa())}function Ws(){b.memoizer||It({memoizer:ua()})}let O=/*@__PURE__*/ y(`ZodType`,(e,t)=>(Us(),S.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(h(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return qe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(dl(e,t))},superRefine(e,t){return this.check(fl(e,t))},overwrite(e){return this.check(/* @__PURE__ */ po(e))},optional(){return Hc(this)},exactOptional(){return Wc(this)},nullable(){return Kc(this)},nullish(){return Hc(Kc(this))},nonoptional(e){return Qc(this,e)},array(){return P(this)},or(e){return L([this,e])},and(e){return Nc(this,e)},transform(e){return nl(this,Bc(e))},default(e){return Jc(this,e)},prefault(e){return Xc(this,e)},catch(e){return el(this,e)},pipe(e){return nl(this,e)},readonly(){return il(this)},describe(e){let t=this.clone();return _a.add(t,{description:e}),t},meta(...e){if(e.length===0)return _a.get(this);let t=this.clone();return _a.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return bt(this,`~standard`,{...mr(this),jsonSchema:{input:Lo(this,`input`),output:Lo(this,`output`)}})},set"~standard"(e){yt(this,`~standard`,e)},parse:function e(t,n){return js(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ms(this,t,n,{callee:e})},safeParse(e,t){return Ns(this,e,t)},async safeParseAsync(e,t){return Ps(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){yt(this,`spa`,e)},validate(e,t){return tn(this,e,t)},validateAsync(e,t){return rn(this,e,t)},encode:function e(t,n){return Fs(this,t,n,{callee:e})},decode:function e(t,n){return Is(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Ls(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Rs(this,t,n,{callee:e})},safeEncode(e,t){return zs(this,e,t)},safeDecode(e,t){return Bs(this,e,t)},async safeEncodeAsync(e,t){return Vs(this,e,t)},async safeDecodeAsync(e,t){return Hs(this,e,t)},toJSONSchema(e){return Io(this,{})(e)},get description(){return _a.get(this)?.description},get _def(){return this._zod.def}}),Gs=/*@__PURE__*/ y(`_ZodString`,(e,t)=>{hr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,n,r)},/*@__PURE__*/ xt({format:e=>E(e).format??null,minLength:e=>E(e).minimum??null,maxLength:e=>E(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ oo(...e))},includes(...e){return this.check(/* @__PURE__ */ lo(...e))},startsWith(...e){return this.check(/* @__PURE__ */ uo(...e))},endsWith(...e){return this.check(/* @__PURE__ */ fo(...e))},min(...e){return this.check(/* @__PURE__ */ io(...e))},max(...e){return this.check(/* @__PURE__ */ ro(...e))},length(...e){return this.check(/* @__PURE__ */ ao(...e))},nonempty(...e){return this.check(/* @__PURE__ */ io(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ so(e))},uppercase(e){return this.check(/* @__PURE__ */ co(e))},trim(){return this.check(/* @__PURE__ */ ho())},normalize(...e){return this.check(/* @__PURE__ */ mo(...e))},toLowerCase(){return this.check(/* @__PURE__ */ go())},toUpperCase(){return this.check(/* @__PURE__ */ _o())},slugify(){return this.check(/* @__PURE__ */ vo())}})),Ks=/*@__PURE__*/ y(`ZodString`,(e,t)=>{hr.init(e,t),Gs.init(e,t)},{email(e){return this.check(/* @__PURE__ */ ba(Zs,e))},url(e){return this.check(/* @__PURE__ */ Ea(nc,e))},jwt(e){return this.check(/* @__PURE__ */ Va(vc,e))},emoji(e){return this.check(/* @__PURE__ */ Da(ic,e))},guid(e){return this.check(/* @__PURE__ */ xa(Qs,e))},uuid(e){return this.check(/* @__PURE__ */ Sa($s,e))},uuidv4(e){return this.check(/* @__PURE__ */ Ca($s,e))},uuidv6(e){return this.check(/* @__PURE__ */ wa($s,e))},uuidv7(e){return this.check(/* @__PURE__ */ Ta($s,e))},nanoid(e){return this.check(/* @__PURE__ */ Oa(ac,e))},cuid(e){return this.check(/* @__PURE__ */ ka(oc,e))},cuid2(e){return this.check(/* @__PURE__ */ Aa(sc,e))},ulid(e){return this.check(/* @__PURE__ */ ja(cc,e))},base64(e){return this.check(/* @__PURE__ */ Ra(hc,e))},base64url(e){return this.check(/* @__PURE__ */ za(gc,e))},xid(e){return this.check(/* @__PURE__ */ Ma(lc,e))},ksuid(e){return this.check(/* @__PURE__ */ Na(uc,e))},ipv4(e){return this.check(/* @__PURE__ */ Pa(dc,e))},ipv6(e){return this.check(/* @__PURE__ */ Fa(fc,e))},cidrv4(e){return this.check(/* @__PURE__ */ Ia(pc,e))},cidrv6(e){return this.check(/* @__PURE__ */ La(mc,e))},e164(e){return this.check(/* @__PURE__ */ Ba(_c,e))},datetime(e){return this.check(/* @__PURE__ */ Ha(qs,e))},date(e){return this.check(/* @__PURE__ */ Ua(Js,e))},time(e){return this.check(/* @__PURE__ */ Wa(Ys,e))},duration(e){return this.check(/* @__PURE__ */ Ga(Xs,e))}});function k(e){return/* @__PURE__ */ ya(Ks,e)}let A=/*@__PURE__*/ y(`ZodStringFormat`,(e,t)=>{C.init(e,t),Gs.init(e,t)}),qs=/*@__PURE__*/ y(`ZodISODateTime`,(e,t)=>{Pr.init(e,t),A.init(e,t)}),Js=/*@__PURE__*/ y(`ZodISODate`,(e,t)=>{Fr.init(e,t),A.init(e,t)}),Ys=/*@__PURE__*/ y(`ZodISOTime`,(e,t)=>{Ir.init(e,t),A.init(e,t)}),Xs=/*@__PURE__*/ y(`ZodISODuration`,(e,t)=>{Lr.init(e,t),A.init(e,t)}),Zs=/*@__PURE__*/ y(`ZodEmail`,(e,t)=>{vr.init(e,t),A.init(e,t)}),Qs=/*@__PURE__*/ y(`ZodGUID`,(e,t)=>{gr.init(e,t),A.init(e,t)}),$s=/*@__PURE__*/ y(`ZodUUID`,(e,t)=>{_r.init(e,t),A.init(e,t)});function ec(e){return/* @__PURE__ */ Sa($s,e)}function tc(e){return/* @__PURE__ */ Ca($s,e)}let nc=/*@__PURE__*/ y(`ZodURL`,(e,t)=>{Er.init(e,t),A.init(e,t)});function rc(e){return/* @__PURE__ */ Ea(nc,e)}let ic=/*@__PURE__*/ y(`ZodEmoji`,(e,t)=>{Dr.init(e,t),A.init(e,t)}),ac=/*@__PURE__*/ y(`ZodNanoID`,(e,t)=>{Or.init(e,t),A.init(e,t)}),oc=/*@__PURE__*/ y(`ZodCUID`,(e,t)=>{kr.init(e,t),A.init(e,t)}),sc=/*@__PURE__*/ y(`ZodCUID2`,(e,t)=>{Ar.init(e,t),A.init(e,t)}),cc=/*@__PURE__*/ y(`ZodULID`,(e,t)=>{jr.init(e,t),A.init(e,t)}),lc=/*@__PURE__*/ y(`ZodXID`,(e,t)=>{Mr.init(e,t),A.init(e,t)}),uc=/*@__PURE__*/ y(`ZodKSUID`,(e,t)=>{Nr.init(e,t),A.init(e,t)}),dc=/*@__PURE__*/ y(`ZodIPv4`,(e,t)=>{Rr.init(e,t),A.init(e,t)}),fc=/*@__PURE__*/ y(`ZodIPv6`,(e,t)=>{Vr.init(e,t),A.init(e,t)}),pc=/*@__PURE__*/ y(`ZodCIDRv4`,(e,t)=>{Hr.init(e,t),A.init(e,t)}),mc=/*@__PURE__*/ y(`ZodCIDRv6`,(e,t)=>{Wr.init(e,t),A.init(e,t)}),hc=/*@__PURE__*/ y(`ZodBase64`,(e,t)=>{qr.init(e,t),A.init(e,t)}),gc=/*@__PURE__*/ y(`ZodBase64URL`,(e,t)=>{Xr.init(e,t),A.init(e,t)}),_c=/*@__PURE__*/ y(`ZodE164`,(e,t)=>{Zr.init(e,t),A.init(e,t)}),vc=/*@__PURE__*/ y(`ZodJWT`,(e,t)=>{$r.init(e,t),A.init(e,t)}),yc=/*@__PURE__*/ y(`ZodNumber`,(e,t)=>{ei.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ xt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=E(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=E(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=E(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>E(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ eo(e,t))},gte(e,t){return this.check(/* @__PURE__ */ to(e,t))},min(e,t){return this.check(/* @__PURE__ */ to(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Qa(e,t))},lte(e,t){return this.check(/* @__PURE__ */ $a(e,t))},max(e,t){return this.check(/* @__PURE__ */ $a(e,t))},int(e){return this.check(M(e))},safe(e){return this.check(M(e))},positive(e){return this.check(/* @__PURE__ */ eo(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ to(0,e))},negative(e){return this.check(/* @__PURE__ */ Qa(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ $a(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ no(e,t))},step(e,t){return this.check(/* @__PURE__ */ no(e,t))},finite(){return this}}));function j(e){return/* @__PURE__ */ Ka(yc,e)}let bc=/*@__PURE__*/ y(`ZodNumberFormat`,(e,t)=>{ti.init(e,t),yc.init(e,t)});function M(e){return/* @__PURE__ */ qa(bc,e)}let xc=/*@__PURE__*/ y(`ZodBoolean`,(e,t)=>{ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r)});function N(e){return/* @__PURE__ */ Ja(xc,e)}let Sc=/*@__PURE__*/ y(`ZodNull`,(e,t)=>{ri.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r)});function Cc(e){return/* @__PURE__ */ Ya(Sc,e)}let wc=/*@__PURE__*/ y(`ZodUnknown`,(e,t)=>{ii.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Tc(){return/* @__PURE__ */ Xa(wc)}let Ec=/*@__PURE__*/ y(`ZodNever`,(e,t)=>{ai.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r)});function Dc(e){return/* @__PURE__ */ Za(Ec,e)}let Oc=/*@__PURE__*/ y(`ZodArray`,(e,t)=>{Ws(),li.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cs(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ io(e,t))},nonempty(e){return this.check(/* @__PURE__ */ io(1,e))},max(e,t){return this.check(/* @__PURE__ */ ro(e,t))},length(e,t){return this.check(/* @__PURE__ */ ao(e,t))},unwrap(){return this.element}});function P(e,t){return/* @__PURE__ */ yo(Oc,e,t)}let kc=/*@__PURE__*/ y(`ZodObject`,(e,t)=>{Ws(),hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>us(e,t,n,r),Dt(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(h(this._zod.def,{catchall:e}))},passthrough(){return this.clone(h(this._zod.def,{catchall:Tc()}))},loose(){return this.clone(h(this._zod.def,{catchall:Tc()}))},strict(){return this.clone(h(this._zod.def,{catchall:Dc()}))},strip(){return this.clone(h(this._zod.def,{catchall:void 0}))},extend(e){return tt(this,e)},safeExtend(e){return rt(this,e)},merge(e){return it(this,e)},pick(e){return Qe(this,e)},omit(e){return et(this,e)},partial(...e){return at(Vc,this,e[0])},exactPartial(...e){return at(Uc,this,e[0],`exactPartial`)},required(...e){return ot(Zc,this,e[0])}});function F(e,t){let n={type:`object`,shape:e??{},...g(t)};return new kc(n)}function I(e,t){return new kc({type:`object`,shape:e,catchall:Dc(),...g(t)})}let Ac=/*@__PURE__*/ y(`ZodUnion`,(e,t)=>{_i.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r),e.options=t.options});function L(e,t){return new Ac({type:`union`,options:e,...g(t)})}let jc=/*@__PURE__*/ y(`ZodDiscriminatedUnion`,(e,t)=>{Ac.init(e,t),yi.init(e,t)});function R(e,t,n){return new jc({type:`union`,options:t,discriminator:e,...g(n)})}let Mc=/*@__PURE__*/ y(`ZodIntersection`,(e,t)=>{bi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r)});function Nc(e,t){return new Mc({type:`intersection`,left:e,right:t})}let Pc=/*@__PURE__*/ y(`ZodTuple`,(e,t)=>{Ws(),Ci.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ps(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Vc({type:`optional`,innerType:e}))})}});function Fc(e,t,n){let r=t instanceof S;return new Pc({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}let Ic=/*@__PURE__*/ y(`ZodRecord`,(e,t)=>{Ws(),Di.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return!t||!t._zod?new Ic({type:`record`,keyType:k(),valueType:e,...g(t)}):new Ic({type:`record`,keyType:e,valueType:t,...g(n)})}let Lc=/*@__PURE__*/ y(`ZodEnum`,(e,t)=>{Oi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Lc({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Lc({...t,checks:[],...g(r),entries:i})}});function B(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Lc({type:`enum`,entries:n,...g(t)})}let Rc=/*@__PURE__*/ y(`ZodLiteral`,(e,t)=>{ki.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function V(e,t){return new Rc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}let zc=/*@__PURE__*/ y(`ZodTransform`,(e,t)=>{Ws(),Ai.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ss(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ft(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(_t(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(_t(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Bc(e){return new zc({type:`transform`,transform:e})}let Vc=/*@__PURE__*/ y(`ZodOptional`,(e,t)=>{Mi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ds(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`optional`,innerType:e})}let Uc=/*@__PURE__*/ y(`ZodExactOptional`,(e,t)=>{Ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ds(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wc(e){return new Uc({type:`optional`,innerType:e})}let Gc=/*@__PURE__*/ y(`ZodNullable`,(e,t)=>{Pi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Kc(e){return new Gc({type:`nullable`,innerType:e})}let qc=/*@__PURE__*/ y(`ZodDefault`,(e,t)=>{Fi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ss(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Jc(e,t){return new qc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Yc=/*@__PURE__*/ y(`ZodPrefault`,(e,t)=>{Li.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xc(e,t){return new Yc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Zc=/*@__PURE__*/ y(`ZodNonOptional`,(e,t)=>{Ri.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qc(e,t){return new Zc({type:`nonoptional`,innerType:e,...g(t)})}let $c=/*@__PURE__*/ y(`ZodCatch`,(e,t)=>{Vi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ws(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function el(e,t){return new $c({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Ot(t)})}let tl=/*@__PURE__*/ y(`ZodPipe`,(e,t)=>{Hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ts(e,t,n,r),e.in=t.in,e.out=t.out});function nl(e,t){return new tl({type:`pipe`,in:e,out:t})}let rl=/*@__PURE__*/ y(`ZodReadonly`,(e,t)=>{Wi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function il(e){return new rl({type:`readonly`,innerType:e})}let al=/*@__PURE__*/ y(`ZodTemplateLiteral`,(e,t)=>{Ji.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r)});function ol(e,t){return new al({type:`template_literal`,parts:e,...g(t)})}let sl=/*@__PURE__*/ y(`ZodLazy`,(e,t)=>{Yi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Os(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function cl(e){return new sl({type:`lazy`,getter:e})}let ll=/*@__PURE__*/ y(`ZodCustom`,(e,t)=>{Xi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r)});function ul(e,t){return/* @__PURE__ */ bo(ll,e??(()=>!0),t)}function dl(e,t={}){return/* @__PURE__ */ xo(ll,e,t)}function fl(e,t){return/* @__PURE__ */ So(e,t)}function pl(e){return/* @__PURE__ */ Ha(qs,e)}function ml(e){return(t,n)=>{for(let r of e)Object.hasOwn(t,r)&&t[r]===void 0&&n.addIssue({code:`custom`,path:[r],message:`Explicit undefined is not valid JSON`})}}let hl=L([k(),j(),N(),Cc()]);function gl(e){let t=/* @__PURE__ */ new WeakSet,n=[{value:e,leaving:!1}];try{for(;n.length>0;){let e=n.pop();if(!e)break;if(e.leaving)t.delete(e.value);else if(typeof e.value==`object`&&e.value!==null){if(t.has(e.value))return!1;t.add(e.value),n.push({value:e.value,leaving:!0});for(let t of Object.values(e.value))n.push({value:t,leaving:!1})}}}catch{return!1}return!0}let _l=ul(gl,{message:`JSON value must not contain circular references`}),vl=cl(()=>L([hl,P(vl),z(k(),vl)])),H=_l.pipe(vl);_l.pipe(P(vl));let yl=_l.pipe(z(k(),vl)),bl=I({code:k().min(1),message:k().min(1),retryable:N(),diagnostic:k().min(1).optional(),stage:k().min(1).optional(),durationMs:j().int().nonnegative().optional(),stderrTail:k().min(1).optional()}).superRefine(ml([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),xl=k().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),Sl=e=>k().min(1).max(e).refine(e=>e.trim().length>0),Cl=z(xl,F({label:Sl(256).optional(),description:Sl(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),wl=z(xl,Sl(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),Tl=k().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),U=Tl.brand(),W=Tl.brand(),El=Tl.brand();Tl.brand();let G=Tl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand();Tl.brand();let Dl=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Ol=Dl.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),kl=F({modes:P(F({id:Ol,label:Dl.max(256),description:Dl.max(1024).optional(),dangerous:N().optional(),localizations:Cl.optional()}).strict()).min(1).max(32),defaultModeId:Ol}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});F({threadId:W,permissionModeId:Ol}).strict();let Al=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`});F({sourceThreadId:W,lastTurnId:El.optional(),targetHarnessId:U,targetModel:Al.max(1024).optional(),targetThinkingOptionId:Al.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).optional()}).strict();let jl=F({sourceThreadId:W,sourceHarnessId:U,sourceHarnessLabel:Al.max(256).optional(),sourceModel:Al.max(1024).optional(),targetHarnessId:U,targetHarnessLabel:Al.max(256).optional(),targetModel:Al.max(1024).optional(),totalTurns:j().int().min(1),boundaryTurnNumber:j().int().min(1),includedTurnNumbers:P(j().int().min(1)),omittedTurns:j().int().min(0),preview:k().max(32e3),createdAtMs:j().int().nonnegative()}).strict();F({threadId:W,handoff:jl}).strict();let Ml=k().regex(/^[a-z0-9][a-z0-9-]{0,63}$/u),Nl=k().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Role model must not contain control characters`),Pl=B([`stone`,`rose`,`mist`,`sage`,`amber`,`aqua`]),Fl=ol([`builtin:`,B([`pm-otter`,`frontend-otter`,`backend-otter`,`reviewer-otter`,`idea-otter`,`researcher-otter`,`writer-otter`,`architect-otter`,`debugger-otter`,`tester-otter`,`classic-otter`,`ops-otter`,`security-otter`,`audio-otter`,`scholar-otter`,`data-otter`,`advisor-otter`,`builder-otter`,`wizard-otter`,`sailor-otter`])]),Il=/^[a-zA-Z0-9_-]{1,64}\.(png|jpg|jpeg|webp)$/u,Ll=ol([`custom:`,k().regex(Il)]),Rl=ol([`catalog:`,k().regex(Il)]),zl=L([Fl,Ll]),Bl=L([Fl,Rl]),Vl=L([zl,Rl]),Hl=k().url().max(2048).refine(e=>/^https:\/\//i.test(e),`URL must use https://`),Ul=F({en:k().trim().min(1).max(2e3),"zh-CN":k().trim().min(1).max(2e3)}),Wl=F({slug:Ml,name:Ul,description:Ul,avatar:Bl,accentColor:Pl,recommendedHarnessId:U.optional(),author:k().trim().min(1).max(128),authorUrl:Hl.optional(),sourceUrl:Hl.optional(),license:k().trim().min(1).max(64).optional(),official:N().optional(),instructions:k().trim().min(1).max(1e5),updatedAt:pl()});F({formatVersion:V(1),generatedAt:pl(),roles:P(Wl)});let Gl=F({slug:Ml,name:k().refine(e=>e.trim().length>0),avatar:zl,accentColor:Pl}),Kl=Gl.readonly(),ql=Gl.extend({description:k(),harnessId:U,model:Nl.optional(),thinkingOptionId:G.optional(),instructions:k(),updatedAt:pl()});ql.omit({updatedAt:!0,avatar:!0}).extend({avatar:Vl}).partial({slug:!0}),F({locale:k().trim().min(1).max(64).optional()}),F({roles:P(ql)}),F({slug:Ml}),F({role:ql.nullable()}),F({role:ql}),F({deleted:N()}),F({refresh:N().optional()}),F({roles:P(Wl),fetchedAt:pl(),likes:z(Ml,j().int().nonnegative()).optional(),myLikes:z(Ml,j().int().min(0).max(5)).optional(),stale:N().optional(),error:k().optional()}),F({slug:Ml}),F({slug:Ml,likes:j().int().nonnegative(),myLikes:j().int().min(0).max(5),maxLikes:V(5),limitReached:N().optional()});let K=j().int().safe().nonnegative(),Jl=j().finite().nonnegative(),Yl=j().finite().min(0).max(100),Xl=F({version:L([V(3),V(4)]).optional(),requestId:k().min(1),turnId:k().min(1).max(1024),outputTokens:K,startedAtMs:K,completedAtMs:K}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Zl=F({version:L([V(2),V(3),V(4)]).optional(),value:Jl,turnId:k().min(1).max(1024),at:K}).strict();F({outputTimings:P(Xl).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Zl.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Zl.extend({value:K}).optional()}).strict();let Ql=e=>wl.refine(t=>Object.values(t).every(t=>t.length<=e)),$l=F({composerIndicators:P(F({kind:V(`countdown`),id:k().min(1).max(64),expiresAtUnix:K,label:Ql(256).optional(),tooltip:Ql(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:K.optional(),cachedInputTokens:K.optional(),cacheWriteInputTokens:K.optional(),outputTokens:K.optional(),outputTokensPerSecond:Jl.optional(),sessionOutputTokensPerSecond:Jl.optional(),apiOutputTokensPerSecond:Jl.optional(),reasoningOutputTokens:K.optional(),totalTokens:K.optional(),totalCostUsd:Jl.optional(),totalCredits:Jl.optional(),contextUsagePercent:Jl.optional(),cacheHitRatePercent:Yl.optional(),contextWindowTokens:K.optional(),contextUsedTokens:K.optional(),planFiveHourUsedPercent:Yl.optional(),planFiveHourResetsAtUnix:K.optional(),planSevenDayUsedPercent:Yl.optional(),planSevenDayResetsAtUnix:K.optional(),sessionCacheHitRatePercent:Yl.optional(),timeToFirstOutputMs:K.optional(),latestRequestTimeToFirstOutputMs:K.optional(),costSource:B([`publicPrice`,`native`]).optional(),unpricedModels:P(k().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{Object.keys(e).length===0&&t.addIssue({code:`custom`,message:`Thread Usage must contain a reliable field`});let n=e.contextUsedTokens!==void 0;n!==(e.contextWindowTokens!==void 0)&&t.addIssue({code:`custom`,message:`Thread Usage context fields must be provided together`,path:[n?`contextWindowTokens`:`contextUsedTokens`]}),e.contextWindowTokens===0&&t.addIssue({code:`custom`,message:`Thread Usage contextWindowTokens must be greater than zero`,path:[`contextWindowTokens`]}),e.costSource!==void 0&&e.totalCostUsd===void 0&&t.addIssue({code:`custom`,message:`Thread Usage costSource must be provided with totalCostUsd`,path:[`costSource`]}),e.unpricedModels!==void 0&&e.costSource!==`publicPrice`&&t.addIssue({code:`custom`,message:`Thread Usage unpricedModels must be provided with a publicPrice cost`,path:[`unpricedModels`]}),e.planFiveHourResetsAtUnix!==void 0&&e.planFiveHourUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planFiveHourResetsAtUnix must be provided with planFiveHourUsedPercent`,path:[`planFiveHourResetsAtUnix`]}),e.planSevenDayResetsAtUnix!==void 0&&e.planSevenDayUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planSevenDayResetsAtUnix must be provided with planSevenDayUsedPercent`,path:[`planSevenDayResetsAtUnix`]})}),eu=j().finite().min(0).max(100),tu=B([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),nu=F({id:k().min(1).max(256),label:k().min(1).max(256),localizations:Cl.optional()}).strict(),ru=F({product:k().min(1),periodType:tu.optional(),scope:nu.optional(),localizations:Cl.optional(),used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),usagePercent:eu,resetsAt:k().min(1).optional()}).strict(),iu=F({availableCount:j().int().safe().positive(),nextExpiresAt:k().min(1).optional(),expiresAt:P(k().min(1)).min(1).max(32).optional()}).strict(),au=F({used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),label:k().min(1).optional(),scope:nu.optional(),localizations:Cl.optional(),usedPercent:eu,resetsAt:k().min(1).optional(),periodType:tu,productUsage:P(ru).min(1).optional(),resetCredits:iu.optional()}).strict(),ou=F({amount:j().finite().nonnegative(),currency:k().trim().min(1).max(8),label:k().trim().min(1).max(128).optional()}).strict();F({threadId:W,refresh:V(`exact`).optional()}).strict(),F({threadId:W,usage:$l.nullable(),accountCredits:au.optional(),accountBalance:ou.optional(),accountCreditsSupported:N().optional()}).strict();let su=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),cu=k().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),lu=B([`priority`,`ultrafast`]),q=F({id:cu,serviceTier:lu.optional()}).strict();function uu(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let du=su.max(256),fu=F({id:G,label:su.max(256)}).strict(),pu=F({ref:q,label:su.max(256),resolvedModelLabel:du.optional(),fastModel:q.optional(),supportedThinkingOptionIds:P(G).optional()}).strict().refine(e=>e.fastModel?.serviceTier===void 0||e.fastModel.id===e.ref.id,{path:[`fastModel`,`id`],message:`A tiered Fast Model must share the base Model ID`});function mu(e,t){if(t)return e?.models.find(e=>uu(e.ref,t)||uu(e.fastModel,t))}let hu=P(fu).superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Thinking option IDs must be unique`,path:[r,`id`]}),n.add(i.id)}),gu=B([`catalog`,`activeModel`]),_u=F({models:P(pu),defaultModel:q.optional(),thinkingOptions:hu,defaultThinkingOptionId:G.optional(),thinkingOptionsScope:gu.optional()}).strict().superRefine((e,t)=>{let n=[],r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.some(e=>uu(e,a.ref))&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.push(a.ref),a.fastModel&&(n.some(e=>uu(e,a.fastModel))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.push(a.fastModel));let e=/* @__PURE__ */ new Set;for(let[n,o]of(a.supportedThinkingOptionIds??[]).entries())e.has(o)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,n]}),e.add(o),r.has(o)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,n]})}e.defaultModel&&!mu(e,e.defaultModel)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),vu=F({fork:N(),forkAcrossCwd:N(),rollbackLastTurn:N()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),yu=B([`live`,`atCreate`]),bu=F({configuration:F({selectModel:N(),selectThinkingOption:N(),selectPermissionMode:N(),permissionModeScope:yu.default(`live`)}).strict(),history:vu,subagents:F({observe:N(),readTranscript:N()}).strict().optional(),autonomousTurns:F({observe:N()}).strict().optional(),steer:N().optional(),persistentPlan:N().optional()}).strict();F({effectiveModel:q.optional(),resolvedModelLabel:du.optional(),effectiveThinkingOptionId:G.optional(),availableThinkingOptions:hu.optional(),effectivePermissionModeId:Ol.optional()}).strict().superRefine((e,t)=>{e.effectiveThinkingOptionId&&e.availableThinkingOptions&&!e.availableThinkingOptions.some(({id:t})=>t===e.effectiveThinkingOptionId)&&t.addIssue({code:`custom`,message:`Effective Thinking option must be currently available`,path:[`effectiveThinkingOptionId`]})});let xu=F({open:V(!0)}).strict();L([F({status:V(`ready`),catalog:_u,permissionModes:kl.optional(),capabilities:bu,webUi:xu.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),F({status:B([`notInstalled`,`unavailable`,`error`]),error:bl}).strict()]),F({harnessId:U,cwd:su.max(16384).optional(),refresh:N().optional(),purpose:V(`availability`).optional(),credentialAccess:B([`allow`,`retry`]).optional()}).strict(),F({harnessId:U}).strict(),F({}).strict(),F({threadId:W,model:q}).strict(),F({threadId:W,thinkingOptionId:G}).strict(),F({threadId:W,includeReferenceCapability:N().optional()}).strict(),R(`owner`,[F({owner:V(`codex`),locked:N(),effectiveModel:q.optional(),resolvedModelLabel:du.optional(),effectiveThinkingOptionId:G.optional(),effectivePermissionModeId:Ol.optional(),history:vu.optional(),supportsThreadReferences:V(!0).optional(),handoff:jl.optional(),roleSnapshot:Kl.optional(),nativeSessionRef:Dc().optional()}),F({owner:V(`external`),harnessId:su.max(256),transportModelId:su.max(8192),effectiveModel:q.optional(),resolvedModelLabel:du.optional(),effectiveThinkingOptionId:G.optional(),availableThinkingOptions:hu.optional(),effectivePermissionModeId:Ol.optional(),catalog:_u.optional(),history:vu,usage:$l.optional(),handoff:jl.optional(),roleSnapshot:Kl.optional(),nativeSessionRef:Dc().optional(),locked:V(!0)})]),F({threadIds:P(W).min(1).max(100)}).strict().superRefine(({threadIds:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i)&&t.addIssue({code:`custom`,message:`Thread ownership-list IDs must be unique`,path:[`threadIds`,r]}),n.add(i)});let Su=R(`owner`,[F({threadId:W,owner:V(`codex`)}).strict(),F({threadId:W,owner:V(`external`),harnessId:k().max(256).pipe(U)}).strict()]);F({threads:P(Su).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),F({threadId:W,text:k().optional()}).strict(),F({kind:V(`application`),value:k().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),At}}).pipe(F({expectedTurnId:El,clientUserMessageId:k().min(1),delivery:B([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),B([`activeTurn`,`newTurn`]),F({delivery:B([`official`,`activeTurn`,`newTurn`])}).strict();let Cu=k().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),wu=Cu.pipe(U),Tu=wu.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Eu=k().min(1).max(512).refine(e=>!/[\\\u0000:#?]/u.test(e)&&!e.startsWith(`/`)&&!e.split(`/`).some(e=>e===`..`||e===``),`Plugin resources must be relative paths inside the plugin`),Du=rc().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),Ou=F({en:k().max(4096),"zh-CN":k().max(4096).optional()}).strict(),ku=F({commands:P(F({terminal:k().max(256),command:k().max(4096)}).strict()).max(8),before:Ou.optional(),after:Ou.optional(),downloads:P(F({label:k().max(128),url:Du}).strict()).max(8).optional()}).strict(),Au={id:wu,name:k().trim().min(1).max(128),version:k().min(1).max(128),kind:V(`usage`).optional(),iconStyle:F({vector:F({viewBox:k().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:P(F({d:k().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:B([`evenodd`,`nonzero`]).optional(),fill:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:k().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:j().min(0).max(50).optional(),paddingRatio:j().min(0).max(.25).optional()}).strict().optional(),installation:ku.optional(),notice:Ou.optional(),launchCommand:V(!0).optional(),links:F({website:Du.optional(),documentation:Du.optional(),installation:Du.optional()}).strict().optional()};F({manifestVersion:V(1),...Au,adapterApiVersion:j().int().positive(),entry:Eu,icon:Eu.optional()}).strict();let ju=k().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),Mu=F({...Au,icon:ju.optional()}).strict();F({}).strict(),F({plugins:P(Mu.extend({id:Tu})).max(128)}).strict(),F({version:V(1),enabled:P(wu).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let Nu=131072,Pu=524288,Fu=Cu,Iu=B([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),Lu=B([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),Ru=k().trim().min(1).max(128);function zu(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return}}let Bu=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),Vu=Eu.refine(e=>zu(e)!==void 0&&Bu(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),Hu=k().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(rc({protocol:/^https?$/u})).refine(e=>{let{username:t,password:n}=new URL(e);return!t&&!n&&!/[\\\s]/u.test(e)},`URL must not contain credentials, backslashes, or whitespace`);function Uu(e){return I({en:e,"zh-CN":e})}let Wu=Uu(k().trim().min(1)),Gu=P(Lu).max(Lu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),Ku=P(Iu).max(Iu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),qu={key:k().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:Wu,description:Wu.optional()},Ju={...qu,step:j().positive().optional(),default:j().optional()},Yu=I({value:k(),label:Wu}),Xu=R(`type`,[I({...qu,type:V(`boolean`),default:N().optional()}),I({...qu,type:V(`string`),placeholder:Wu.optional(),default:k().optional()}),I({...Ju,type:V(`number`),min:j().optional(),max:j().optional()}),I({...Ju,type:V(`range`),min:j(),max:j()}),I({...qu,type:V(`select`),options:P(Yu).min(1),default:k().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),Zu=F({manifestVersion:M().positive(),id:Fu,name:L([Ru,Uu(Ru)]),version:k().min(1).max(128),desktopApi:M().positive()}).passthrough().extend({manifestVersion:V(1),desktopApi:V(1),description:I({en:k().max(4096),"zh-CN":k().max(4096).optional()}).optional(),author:k().trim().min(1).max(128).optional(),repository:Hu.optional(),details:I({en:k().max(16384),"zh-CN":k().max(16384).optional()}).optional(),icon:Vu.optional(),screenshots:P(Vu).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:I({script:Eu,style:Eu.optional()}).optional(),backend:I({script:Eu.refine(Bu)}).optional(),slots:Ku.default(()=>[]),settingsSchema:P(Xu).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:Gu.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),Qu=k().regex(/^[a-f0-9]{64}$/u),$u=I({state:B([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:Qu.optional(),error:k().optional(),conflictWith:Fu.optional()});I({controllerPid:M().positive(),targetId:k().nullable(),updatedAt:pl(),handledReloadToken:ec().optional(),extensions:z(k(),$u),surfaces:z(k(),$u).optional()});let ed=B([`official`,`community`]);function td(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let nd=Hu.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||td(t)||t.origin===`https://github.com`&&/^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(t.pathname)||t.origin===`https://codeload.github.com`&&/^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(t.pathname)},`Expected a .zip download URL or a GitHub zipball URL`),rd=I({id:Fu,version:k().trim().min(1).max(128),name:Wu.extend({en:Ru,"zh-CN":Ru}),description:Uu(k().trim().min(1).max(4096)),details:Uu(k().trim().min(1).max(16384)).optional(),author:k().trim().min(1).max(128),repository:Hu,stars:j().int().min(0).optional(),downloads:j().int().min(0).optional(),categories:Gu.optional(),trustTier:ed.default(`community`),icon:Hu.optional(),screenshots:P(Hu).max(4).optional(),downloadUrl:nd,sha256:Qu,slots:Ku.optional(),publishedAt:k().optional(),updatedAt:k().optional(),minCodexHostVersion:k().optional()});I({schemaVersion:V(1),generatedAt:k(),extensions:P(rd).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let id=k().trim().min(1).max(128),ad=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,od=Fu.refine(e=>!ad.test(e),`Reserved extension ID`),sd=B([`desktop`,`web`]),cd=Qu,ld=ec(),ud=Eu.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!ad.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),dd=Zu.shape,fd=(e,t=0)=>I({en:k().trim().min(t).max(e),"zh-CN":k().trim().min(t).max(e)}),pd=e=>ud.refine(t=>t.endsWith(e),`Expected a ${e} file`),md=pd(`.mjs`),hd=pd(`.css`).optional(),gd=e=>e.normalize(`NFC`).toLowerCase(),_d=I({manifestVersion:V(2),id:od,name:fd(128,1),version:k().trim().min(1).max(128),description:fd(4096),details:fd(16384).optional(),author:dd.author,repository:dd.repository,icon:dd.icon.refine(e=>e===void 0||ud.safeParse(e).success),screenshots:dd.screenshots.refine(e=>e===void 0||e.every(e=>ud.safeParse(e).success)),categories:dd.categories,settingsSchema:dd.settingsSchema,slots:dd.slots.removeDefault().optional(),page:I({apiVersion:V(1),entry:md,style:hd,title:fd(128,1).optional()}).optional(),widget:I({apiVersion:V(1),entry:md,style:hd}).optional(),desktop:I({apiVersion:V(1),script:pd(`.js`),style:hd}).optional(),web:I({apiVersion:V(1),entry:md.optional(),style:hd}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:I({apiVersion:V(1),entry:md}).optional()}).refine(({page:e,widget:t,desktop:n,web:r,backend:i})=>!!(e||t||n||r||i),`Expected at least one page, widget, desktop, web, or backend entry`).refine(({page:e,widget:t,web:n,backend:r})=>!r||[e?.entry,t?.entry,n?.entry].every(e=>e===void 0||gd(e)!==gd(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function vd({hasPage:e,hasWidget:t,hasDesktop:n,hasWeb:r,hasBackend:i}){if(e||t||i&&!n&&!r)return[`desktop`,`web`];let a=[];return n&&a.push(`desktop`),r&&a.push(`web`),a}let yd=id,bd=B([`running`,`waiting`,`idle`,`unknown`]),xd=F({createdAtMs:j().int().nonnegative()}),Sd=I({sourceThreadId:W,createdAtMs:j().int().nonnegative()}),Cd=I({harnessId:U,title:k().optional(),status:bd,archived:N(),updatedAtMs:j().int().nonnegative().optional()}),wd=F({revision:M().nonnegative(),parents:z(W,W),delegations:z(W,xd).optional(),handoffs:z(W,Sd).optional(),nodes:z(W,Cd),truncated:N()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,handoffs:t,nodes:n})=>Object.entries(e).every(([e,t])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t))&&Object.entries(t??{}).every(([e,{sourceThreadId:t}])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t)),`Missing Thread tree node`).refine(({parents:e,delegations:t})=>Object.keys(t??{}).every(t=>Object.hasOwn(e,t)),`Delegation metadata requires a matching parent edge`),Td=k().min(1).max(128);I({});let Ed=I({subscriptionId:Td});I({}),Ed.extend({snapshot:wd});let Dd=M().nonnegative(),Od=I({revision:Dd,enabled:P(od).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});I({version:V(1),seeded:P(od).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});let kd=F({version:k().trim().min(1).max(128),publishedAt:k().trim().min(1).max(64).optional(),notes:k().trim().min(1).max(8192),url:Hu.optional()}),{downloadUrl:Ad,...jd}=rd.shape,Md=F({...jd,id:od,format:V(`codexhost`),targets:P(sd).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:I({page:M().positive().optional(),widget:M().positive().optional(),desktop:M().positive().optional(),web:M().positive().optional(),backend:M().positive().optional()}),downloadUrl:Ad.refine(e=>e.startsWith(`https://`),`Expected HTTPS`),featured:N().optional(),featuredOrder:M().nonnegative().optional(),changelog:P(kd).max(20).optional()}).refine(({targets:e,apis:t})=>{let n=vd({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);F({schemaVersion:V(2),generatedAt:k().min(1),extensions:P(Md).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:Hu,fetchedAt:pl(),cached:N(),stale:N().optional()});let Nd={id:od},Pd={...Nd,activationId:ld,digest:cd},Fd={...Nd,activationId:Pd.activationId.optional()},Id=k().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),Ld=k().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function Rd(e){return k().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let zd=I({type:V(`github`),repository:k().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:Ld.optional(),tag:Ld.optional(),asset:k().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:ud.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),Bd=L([I({type:V(`catalog`),...Nd}),zd,I({type:V(`zip`),base64:Rd(67108864).min(4)}),I({type:V(`zip`),localZipPath:Id}),I({type:V(`localDir`),localDir:Id})]),Vd=R(`type`,[I({type:V(`catalog`),...Nd}),zd,I({type:V(`zip`)}),I({type:V(`localDir`)})]),Hd=I({...Pd,manifest:_d,installedAt:pl(),source:Vd.optional()}),Ud=e=>k().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),Wd={desktopConflictWith:od.optional()},Gd=B([`none`,`inactive`,`starting`,`running`,`failed`]),Kd=R(`state`,[Hd.extend({state:V(`valid`),enabled:N(),...Wd,iconDataUrl:Ud(Nu).optional(),screenshotDataUrls:P(Ud(Pu)).max(4).optional(),backendState:Gd.optional(),backendError:k().optional()}),I({state:B([`invalid`,`incompatible`]),id:k().min(1),enabled:N(),error:k()})]);I({revision:Dd,configuration:Od,diagnostics:P(k()),extensions:P(Kd)}),I({revision:Dd,extensions:P(Hd.extend({...Wd,settingsRevision:Dd})).max(64)});let J={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,catalogIcon:`codexhost/extensions/catalogIcon`,catalogScreenshot:`codexhost/extensions/catalogScreenshot`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`,threadTree:`codexhost/extensions/threadTree`},qd=Object.freeze(Object.values(J));new Set(qd),I({});let Jd={expectedRevision:Dd};I({...Nd,...Jd}),Hd.extend({replaced:N()}),R(`state`,[I({state:V(`saved`),configuration:Od}),I({state:V(`revision-conflict`),revision:Dd})]),I({...Fd,digest:Pd.digest.optional(),path:ud}),I({mimeType:k().min(1),base64:Rd(16777216),digest:Pd.digest}),I({mimeType:B([`image/png`,`image/jpeg`,`image/webp`]),base64:Rd(Nu)});let Yd=M().min(0).max(3);I({mimeType:B([`image/png`,`image/jpeg`,`image/webp`]),base64:Rd(Pu)}),I({settingsRevision:Dd,values:yl}),J.list,J.snapshot,J.catalog,I({forceRefresh:N().optional(),staleWhileRevalidate:N().optional()}),J.catalogIcon,I({...Nd}),J.catalogScreenshot,I({...Nd,index:Yd}),J.install,I({source:Bd}),J.update,I({...Nd,expectedDigest:Pd.digest,expectedActivationId:Pd.activationId.optional(),source:Bd.optional()}),J.enable,J.disable,J.uninstall,I({...Nd,removeData:N().optional(),expectedDigest:Pd.digest.optional()}),I({...Nd,removed:N()}),J.recover,I({expectedRevision:Jd.expectedRevision.optional()}),J.asset,J.settingsGet,I(Fd),J.settingsSet,I({...Fd,expectedSettingsRevision:Dd,values:yl}),J.backendInvoke,I({...Fd,method:yd,params:H.optional()}),I({result:H}),J.threadTree;let Xd=k().regex(/^remote:[A-Za-z0-9_-]{8,512}$/u),Zd=L([tc(),Xd]),Qd=tc(),$d=k().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u),ef=B([`none`,`last_speaker`,`all`]),tf=B([`active`,`muted`,`removed`]),nf=M().nonnegative(),Y=M().positive(),rf=Y.max(20),X=k().refine(e=>e.trim().length>0),af=pl(),of={handle:$d.optional(),displayName:X.optional(),note:k().optional()},sf=F({memberId:Qd,threadId:W,handle:$d,displayName:X,note:k().optional(),roleSlug:Ml.optional(),roleSnapshot:Kl.optional(),harnessId:U,status:tf,projectless:N().optional(),joinedAtSeq:nf,lastDeliveredSeq:nf,lastRosterVersion:nf,createdAt:af}),cf=F({workspaceRoot:X,outputDirectory:X}),lf=F({hostId:X,displayName:X,state:X.optional(),color:k().optional(),filePreview:N().optional()}),uf=F({roomId:Zd,title:X,defaultCwd:X,projectlessWorkspace:cf.optional(),unmentionedPolicy:ef.default(`none`),allowAgentMentions:N().default(!0),maxAgentHops:rf.default(5),lastSeq:nf,lastSpeakerMemberId:Qd.optional(),rosterVersion:nf,humanEpoch:nf,relayPaused:N(),pinned:N(),createdAt:af,updatedAt:af,members:P(sf),remote:lf.optional()}).superRefine(({members:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,{handle:i,status:a}]of e.entries())a!==`removed`&&(n.has(i)&&t.addIssue({code:`custom`,path:[`members`,r,`handle`],message:`Handle must be unique among non-removed members`}),n.add(i))}),df=F({kind:B([`image`,`file`]),attachmentId:X.max(256),name:X.max(256),path:X.max(4096),bytes:nf,mediaType:X.max(128).optional(),width:Y.optional(),height:Y.optional()}),ff=F({roomId:Zd,seq:Y,messageId:X,senderType:B([`user`,`agent`,`system`]),senderMemberId:Qd.optional(),senderHandle:$d.optional(),senderName:k().optional(),senderThreadId:W.optional(),sourceTurnId:X.optional(),replyToSeq:Y.optional(),content:k(),attachments:P(df).max(12).optional(),mentionedMemberIds:P(Qd),mentionAll:N().optional(),hopCount:nf,createdAt:af}),pf={...of,model:Nl.optional(),thinkingOptionId:G.optional(),worktree:N().optional()},mf=R(`kind`,[I({kind:V(`role`),roleSlug:Ml,...pf}),I({kind:V(`harness`),harnessId:U,...pf}),I({kind:V(`existing`),threadId:W,...of,includeRecentHistory:N().default(!0).optional()})]),hf={roomId:Zd},gf={...hf,memberId:Qd},_f={title:X.optional(),unmentionedPolicy:ef.optional(),allowAgentMentions:N().optional(),maxAgentHops:rf.optional()};I({}),F({rooms:P(uf)}),I({...hf,limit:Y.optional(),beforeSeq:Y.optional()}),F({room:uf.nullable(),messages:P(ff),hasMore:N()}),I({..._f,defaultCwd:X.optional(),members:P(mf)}),F({room:uf}),I({...hf,..._f,pinned:N().optional(),relayPaused:N().optional()}),I(hf),F({deleted:N()}),I({...hf,member:mf}),F({room:uf,member:sf}),I({...gf,...of,status:tf.optional()}),I(gf),I({...gf,threadId:W,redeliverFrom:Y.optional(),note:k().optional()}),I({...hf,memberId:Qd.optional(),memberHandle:$d.optional(),threadId:W,redeliverFrom:Y.optional(),note:k().optional()}).refine(e=>e.memberId!==void 0!=(e.memberHandle!==void 0),`Provide exactly one of memberId or memberHandle`),F({room:uf,member:sf,previousThreadId:W,awakened:N()});let vf=F({roomId:Zd,title:X,memberCount:nf,updatedAt:af,member:F({memberId:Qd,threadId:W,handle:$d,displayName:X,status:tf,harnessId:U,roleSlug:Ml.optional(),roleName:X.optional()}).optional()});I({threadId:W.optional()}),F({rooms:P(vf)}),I({...hf,content:k().max(64e3),attachments:P(df).max(12).optional(),replyToSeq:Y.optional(),targetMemberIds:P(Qd).optional(),mentionAll:N().optional(),notice:N().optional()}).superRefine((e,t)=>{e.notice===!0?(e.content.trim().length===0&&t.addIssue({code:`custom`,path:[`content`],message:`Notice content is required`}),e.content.length>2e3&&t.addIssue({code:`custom`,path:[`content`],message:`Notice content must be at most 2000 characters`}),((e.targetMemberIds?.length??0)>0||e.mentionAll===!0||(e.attachments?.length??0)>0)&&t.addIssue({code:`custom`,path:[`notice`],message:`System notices cannot target members or include attachments`})):e.content.trim().length===0&&(e.attachments?.length??0)===0&&t.addIssue({code:`custom`,path:[`content`],message:`Message content or at least one attachment is required`})}),F({room:uf,message:ff,awakenedMemberIds:P(Qd)}),I({...hf,fromSeq:Y.optional(),toSeq:Y.optional(),limit:Y.optional()}),F({...hf,messages:P(ff),totalSeq:nf}),I({cwd:X,roomId:Zd.optional()}),F({isGitRepo:N()}),F({threadId:W}).strict(),F({confirmed:N()}).strict();let yf=[`codex-desktop`,`web`,`web-desktop-shell`,`web-mobile`,`ssh-remote`,`cli`],bf=[`darwin`,`win32`,`linux`],xf=[`arm64`,`x64`,`ia32`,`arm`],Sf=[`zh`,`en`,`ja`,`ko`,`de`,`fr`,`es`,`pt`,`ru`,`other`],Cf=[`codex`,`claude-code`,`antigravity`,`pi`,`opencode`,`cursor-cli`,`deepseek-harness`,`grok`,`omp`,`qwen-code`,`kiro-cli`,`codebuddy`,`workbuddy`,`workbuddy-cn`,`devin`,`hermes`,`qoder`,`qoder-cn`,`kimi-code`,`zcode`,`copilot`,`custom`],wf=[`official-relay`,`self-hosted-relay`,`tailscale-serve`,`tailscale-funnel`,`tailscale-ip`,`lan`,`custom-proxy`,`remote-peer`],Tf=k().min(1).max(40).regex(/^[0-9A-Za-z._+-]+$/u),Ef=B(yf),Df=B(Sf),Of=B(Cf),kf=B(wf);new Set(Cf),new Set(Sf),F({enabled:N(),forcedOffByEnv:N()}).strict(),F({enabled:N()}).strict(),F({surfaces:P(Ef).max(12).optional(),harnesses:P(Of).max(32).optional(),remoteAccess:P(kf).max(12).optional()}).strict(),F({dailyActive:V(!0).optional(),weeklyActive:V(!0).optional(),monthlyActive:V(!0).optional(),newInstall:V(!0).optional(),retainedD1:V(!0).optional(),retainedD7:V(!0).optional(),remoteAny:V(!0).optional(),appVersion:Tf.optional(),codexDesktopVersion:Tf.optional(),os:B(bf).optional(),arch:B(xf).optional(),uiLanguage:Df.optional(),surfaces:P(Ef).min(1).max(12).optional(),harnesses:P(Of).min(1).max(32).optional(),remoteAccess:P(kf).min(1).max(12).optional()}).strict().refine(e=>Object.keys(e).length>0,{message:`Telemetry heartbeat must contain at least one countable field`});let Af=4e3,jf={threadId:W};R(`action`,[I({...jf,action:B([`get`,`pause`,`resume`,`clear`])}),I({...jf,action:B([`create`,`edit`]),objective:k().trim().min(1).refine(e=>Array.from(e).length<=Af,`A goal objective can have up to ${Af} characters.`)})]),F({goal:F({threadId:W,objective:k(),status:B([`active`,`paused`,`blocked`,`usageLimited`,`budgetLimited`,`complete`]),tokenBudget:M().positive().nullable().default(null),tokensUsed:M().nonnegative(),timeUsedSeconds:M().nonnegative()}).nullable()});let Mf=k().trim().min(1),Nf=k().min(1),Pf=F({icon:k().nullable(),color:k().nullable()}),Ff=Pf.nullable(),If={create:{method:`codexhost/thread/sections/create`,params:F({name:Mf}).strict()},update:{method:`codexhost/thread/sections/update`,params:F({sectionId:Nf,name:Mf,appearance:Pf.strict().nullable().optional()}).strict()},delete:{method:`codexhost/thread/sections/delete`,params:F({sectionId:Nf}).strict()}};R(`status`,[F({status:V(`unknown`)}),F({status:V(`confirmed`),sectionId:Nf,section:F({id:Nf,name:k().min(1),appearance:Ff}).nullable(),syncPending:N()})]),[If.create.method,If.update.method,If.delete.method,...qd],F({threadSectionsV1:V(!0).optional(),complete:V(!1).optional(),sections:P(F({id:k().min(1),name:k().min(1),appearance:Ff.optional(),threads:P(yl)}))}),F({threadId:k().min(1).max(1024),sectionId:k().min(1).max(1024).nullable(),beforeThreadId:k().min(1).max(1024).nullable().optional(),expectedSourceSectionId:k().min(1).max(1024).optional()}).refine(e=>e.expectedSourceSectionId===void 0||e.sectionId===null),F({threadIds:P(k().min(1))}).strict(),F({threadId:k().min(1).max(1024),pinned:N()}).strict(),F({}).strict(),F({parents:z(k().min(1),k().min(1))}).strict(),F({prompt:k().max(16384).optional()}).strict(),F({projects:P(F({id:k(),name:k(),rootPaths:P(k()),createdAt:j().int().optional()})),nativeProjects:V(!0).optional(),assignments:z(k(),k()),projectless:P(k()),pinned:P(k()),sectionProjects:z(k(),P(k())).optional(),pinnedProjects:P(k()).optional()});let Lf=z(k(),Tc()),Rf=F({epoch:k().uuid(),sequence:j().int().nonnegative()});R(`type`,[F({type:V(`projects-changed`),cursor:Rf}),F({type:V(`skills-changed`),cursor:Rf,cwd:k().optional()}),F({type:V(`harness-inspection-changed`),cursor:Rf,harnessId:k().min(1)}),F({type:V(`display-settings-changed`),cursor:Rf}),F({type:V(`sections-changed`),cursor:Rf}),F({type:V(`groups-changed`),cursor:Rf,roomId:k().optional()}),F({type:V(`preferences-changed`),cursor:Rf,revision:j().int().nonnegative()}),F({type:V(`extensions-changed`),cursor:Rf,revision:Dd}),F({type:V(`hello`),version:V(1),cursor:Rf,reset:N()}),F({type:V(`changed`),cursor:Rf,threadId:k().min(1),method:k().min(1)})]);let zf=R(`type`,[F({type:V(`text`),id:k(),prompt:k(),secret:N().optional(),optional:N().optional()}),F({type:V(`choice`),id:k(),prompt:k(),multiple:N(),allowOther:N(),optional:N().optional(),options:P(F({value:k(),label:k(),description:k().optional()}))})]),Bf=R(`type`,[F({type:V(`approval`),title:k(),description:k().optional(),subject:Tc().optional(),actions:P(F({id:k(),label:k(),effect:k()}))}),F({type:V(`question`),title:k().optional(),questions:P(zf)})]),Vf=F({requestId:L([k(),j().int()]),threadId:k(),kind:B([`approval`,`question`]),interaction:Bf,request:Lf}),Hf=F({id:k().min(1),clientUserMessageId:k().min(1),input:P(Lf),presentationInput:P(Lf).nullable().optional()}).passthrough();F({fields:P(F({path:P(L([k(),j().int().nonnegative()])),originalLength:j().int().nonnegative()}))});let Uf=F({id:k().min(1),status:k().min(1),codexhostTurnOutcome:F({status:V(`unknown`),reason:k()}).optional(),items:P(F({id:k().min(1),type:k().min(1)}).passthrough()),codexhostFileOperations:P(F({beforeItemId:k().nullable(),item:F({id:k().min(1),type:k().min(1)}).passthrough()})).optional(),error:F({message:k().optional()}).passthrough().nullable().optional(),fingerprint:k().min(1).optional(),unchanged:V(!0).optional()}).passthrough(),Wf=F({id:k().min(1).max(512),fingerprint:k().min(1).max(128)});F({threadId:k().min(1),knownTurns:P(Wf).max(64).optional(),truncateToolOutput:N().optional()});let Gf=F({harnessId:k().min(1),nativeSessionId:k().min(1)});F({cursor:Rf,activeTurnId:k().min(1).nullable().optional(),command:F({name:k().min(1),turn:Uf,subsequentTurnId:k().min(1).optional()}).optional(),thread:F({id:k().min(1),cwd:k(),modelProvider:k().min(1),createdAt:j(),updatedAt:j(),recencyAt:j().nullable().optional(),status:F({type:k()}).passthrough(),name:k().nullable().optional(),preview:k().optional(),roleSnapshot:Kl.optional(),codexhostImportSource:Gf.optional(),turns:P(Uf).length(0)}).passthrough(),turnsPage:F({data:P(Uf).max(5),nextCursor:k().nullable()}),configuration:F({codexCollaborationMode:B([`plan`,`default`]).optional(),native:F({model:k().min(1).max(1024).optional(),reasoningEffort:k().min(1).max(128).optional()}).optional(),effectiveModel:q.optional(),effectiveThinkingOptionId:G.optional(),effectivePermissionModeId:Ol.optional()}),queue:F({items:P(Hf),pausedReason:B([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:P(Vf),handoff:jl.optional()}),F({version:V(1),owner:V(`service`).optional(),pid:j().int().positive(),port:j().int().min(1).max(65535),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j(),epoch:k().uuid(),capabilities:F({peerDelegation:V(1).optional(),threadReferenceContext:V(1).optional()}).optional()}),F({epoch:k().uuid(),threadId:k().min(1),requestId:L([k(),j().int()]),result:Lf}),F({includeArchived:N().optional(),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional(),scope:L([F({cwd:k().min(1).max(4096),excludeCwds:P(k().min(1).max(4096)).max(1024)}).strict(),F({projectId:k().min(1).max(1024),legacyThreadIds:P(k().min(1).max(1024)).max(1024),rootPaths:P(k().min(1).max(4096)).max(1024).optional()}).strict()]).optional()}).strict(),F({threads:P(yl),ownership:P(Su),archivedThreadIds:P(W),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional()}).strict(),Mu.pick({id:!0,name:!0,icon:!0,iconStyle:!0});let Kf=I({threadId:k().max(1024),title:k().max(240),project:k().max(240),harness:I({id:k().min(1).max(128),name:k().min(1).max(128)}).optional(),state:B([`idle`,`running`,`waiting`,`completed`,`failed`]),updatedAt:j().nonnegative()});I({epoch:k().max(128),revision:M().nonnegative(),running:M().nonnegative(),waiting:M().nonnegative(),sessions:P(Kf).max(32).default([]),notifications:P(I({threadId:k().max(1024),key:k().max(4096),kind:B([`completed`,`failed`,`approval`,`question`]),revision:M().nonnegative()})).max(256)});let qf=k().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);F({available:N()}).strict(),F({path:k().min(1),mimeType:qf}).strict();let Jf=B([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);R(`ok`,[F({ok:V(!0),text:k()}).strict(),F({ok:V(!1),error:F({code:Jf}).strict()}).strict()]),F({threadId:W.optional(),cwd:k().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Yf=F({name:k().min(1).regex(/^[^\s[\]]+$/u),description:k().optional(),path:k().min(1),scope:B([`project`,`global`]),source:k().min(1)}).strict();F({revision:j().int().nonnegative(),complete:N(),skills:P(Yf),warnings:P(k()).optional()}).strict(),F({cwd:k().min(1).optional()}).strict();let Xf=F({kind:B([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:k().min(1)}).strict(),Zf=R(`status`,[F({status:V(`not-installed`)}),F({status:V(`not-running`)}),F({status:V(`not-logged-in`)}),F({status:V(`https-disabled`)}),F({status:V(`not-serving`),command:k()}),F({status:V(`occupied`),target:k()}),F({status:V(`serving`),url:k(),funnel:N()}),F({status:V(`error`),message:k()})]);F({state:Zf,error:k().optional()}).strict();let Qf=R(`status`,[F({status:V(`on`)}),F({status:V(`off`)}),F({status:V(`invalid`),reason:k()})]),$f=F({lan:N(),autostart:Qf}).strict(),ep=F({expiresAt:k().optional(),issuing:N(),failure:F({detail:k().optional(),retryAt:k(),paused:N()}).optional()}),tp=R(`status`,[F({status:V(`off`),reason:B([`invite`,`name-taken`,`banned`]).optional()}),F({status:V(`connecting`),reason:B([`full`,`unreachable`]).optional()}),F({status:V(`connected`),url:k(),certificate:ep}),F({status:V(`missing-certificate`),url:k(),certificate:ep}),F({status:V(`stopped`),reason:B([`replaced`,`rejected`,`unsupported-version`])})]);k().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i).transform(e=>e.toLowerCase()),k().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let np=B([`official`,`self-hosted`]);F({secret:k().min(1),lastUsedAt:j().nullable(),networkUrls:P(Xf),directCandidates:P(Xf).optional(),tailscale:Zf,background:$f.optional(),relay:F({state:tp,enabled:N(),kind:np,officialHost:k(),customHost:k().optional(),officialHostname:k().optional(),customHostname:k().optional(),quotaUntil:k().optional()}).strict().optional()}).strict();let rp=I({threadId:k().min(1).max(1024),view:B([`result`,`messages`]),from:j().int().min(1).max(2**53-1).optional(),to:j().int().min(1).max(2**53-1).optional()}),ip=/^[a-zA-Z0-9_-]{1,64}$/u,Z=k().regex(ip),ap=k().regex(ip),op=k().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),sp=B([`relay`,`tailscale`,`lan`,`ssh`,`custom`]),cp=B([`auto`,`key`,`password`]);F({host:k().trim().min(1).max(255),port:j().int().min(1).max(65535).optional(),user:k().trim().min(1).max(128).optional(),identityFile:k().trim().min(1).max(1024).optional(),authMode:cp.default(`auto`),remoteDataDir:k().trim().min(1).max(1024).optional()});let lp=F({host:k().min(1).max(255),port:j().int().min(1).max(65535).optional(),user:k().min(1).max(128).optional(),authMode:cp,keyInstalled:N().optional()}),up=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],dp=B(up);new Set(up);let fp=B([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]),pp=F({peerId:Z,hostId:op,nodeId:ap.optional(),name:k().min(1).max(120),color:dp.optional(),origin:k().min(1).max(2048),transportKind:sp,ssh:lp.optional(),encrypted:N(),enabled:N(),state:fp,supportsPeerPairing:N().optional(),pairedBack:N().optional(),linkedPeerIds:P(Z).max(128).optional(),latencyMs:j().int().nonnegative().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),lastError:k().max(1e3).optional(),projectCount:j().int().nonnegative(),createdAt:k(),updatedAt:k()});F({localPlatform:k().max(64).optional(),peers:P(pp)}),F({connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),name:k().trim().min(1).max(120).optional(),color:dp.optional(),pairBack:N().optional(),meshPeerIds:P(Z).max(64).optional(),selfOrigin:k().min(1).max(2048).optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),I({origin:k().min(1).max(2048),token:k().min(1).max(2048),name:k().trim().min(1).max(120).optional(),color:dp.optional(),expectedNodeId:ap.optional()}),F({status:B([`added`,`updated`,`existing`]),peerId:Z,hostId:op,nodeId:ap.optional()});let mp=B([`added`,`updated`,`existing`,`failed`,`skipped`]);F({results:P(F({targetPeerId:Z,targetName:k().min(1).max(120),introducedHost:L([V(`local`),Z]),introducedName:k().min(1).max(120),status:mp,error:k().max(1e3).optional()}))}),F({peerIds:P(Z).max(64).optional(),includeSelf:N().optional(),includeMesh:N().optional(),selfOrigin:k().min(1).max(2048).optional()}),F({peerId:Z,name:k().trim().min(1).max(120).optional(),color:dp.nullable().optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),enabled:N().optional()}),F({peerId:Z}),F({removed:N()}),F({peerId:Z.optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let hp=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});F({ok:N(),nodeId:ap.optional(),supportsPeerPairing:N().optional(),pairedBack:N().optional(),latencyMs:j().int().nonnegative().optional(),origin:k().max(2048).optional(),transportKind:sp.optional(),encrypted:N().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),projectCount:j().int().nonnegative().optional(),projects:P(hp).optional(),error:k().max(1e3).optional()});let gp=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192),threadIds:P(k().min(1).max(1024))}),_p=F({attachments:V(1).optional(),workspaceFiles:V(1).optional(),officePreview:V(1).optional(),delegation:V(1).optional(),peerPairing:V(1).optional()}),vp=F({version:k().max(128),platform:k().max(64),hostname:k().max(255),homeDir:k().max(4096).optional(),epoch:k().min(1).max(256),nodeId:ap.optional(),peerNodes:z(op,ap).refine(e=>Object.keys(e).length<=128).optional(),projects:P(gp),capabilities:_p.optional()});I({threadId:k().min(1).max(1024),scope:k().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u).optional(),requestId:k().min(1).max(256).optional(),mode:B([`queue`,`steer`]).optional(),expectedTurnId:k().min(1).max(1024).nullable().optional(),content:P(R(`type`,[I({type:V(`text`),text:k()}),I({type:V(`file`),receiptId:k().min(1).max(128)})])).min(1).max(64)});let yp=F({ok:V(!1),error:F({code:k(),message:k(),details:z(k(),Tc()).optional()})});L([F({ok:V(!0),value:F({receiptId:k().min(1),file:F({attachmentId:k(),name:k(),bytes:j().int().nonnegative()})})}),yp]),L([F({ok:V(!0),value:F({accepted:V(!0)})}),yp]);let bp=F({name:k().min(1).max(512),path:k().min(1).max(8192),kind:V(`directory`)});F({peerId:Z,path:k().min(1).max(8192).optional()}),F({path:k().min(1).max(8192),parentPath:k().min(1).max(8192).nullable(),homeDir:k().min(1).max(8192).optional(),entries:P(bp)}),F({peerId:Z,parentPath:k().min(1).max(8192),name:k().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),F({path:k().min(1).max(8192),name:k().min(1).max(255)}),F({peerId:Z,path:k().min(1).max(8192),title:k().trim().min(1).max(255).optional()}),F({peerId:Z,workspaceId:k().min(1).max(1024),title:k().trim().min(1).max(255)}),F({peerId:Z,workspaceId:k().min(1).max(1024)}),F({workspaceId:k().min(1).max(1024).optional(),manifest:vp}),F({sessionHostId:k().min(1).max(128).optional()}),F({hosts:P(F({hostId:L([V(`local`),op]),name:k().min(1).max(120),isLocal:N().optional(),color:dp.optional(),hostname:k().max(255).optional()}))}),F({hostId:L([V(`local`),op])}),F({harnesses:P(F({id:k().regex(/^[a-z0-9][a-z0-9-]*$/u),name:k().min(1).max(120)}))}),F({hosts:P(F({alias:k().min(1).max(255),hostName:k().max(255).optional(),user:k().max(128).optional(),port:j().int().min(1).max(65535).optional(),identityFile:k().max(1024).optional()}))}),F({host:k().trim().min(1).max(255),port:j().int().min(1).max(65535).optional(),user:k().trim().min(1).max(128).optional(),identityFile:k().trim().min(1).max(1024).optional(),authMode:cp.default(`auto`),password:k().max(1024).optional(),installAuthorizedKey:N().optional(),name:k().trim().min(1).max(120).optional(),color:dp.optional(),remoteDataDir:k().trim().min(1).max(1024).optional(),sessionId:k().min(1).max(128).optional()}),F({ok:N(),codexhostInstalled:N(),version:k().max(128).optional(),nodeId:ap.optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),latencyMs:j().int().nonnegative().optional(),errorCode:k().max(128).optional(),error:k().max(1e3).optional()}),F({ok:N(),version:k().max(128).optional(),message:k().max(1e3).optional()}),F({promptId:k().min(1).max(128),sessionId:k().min(1).max(128).optional(),peerId:Z.optional(),host:k().min(1).max(255),kind:B([`host-key`,`password`,`passphrase`,`otp`,`generic`]),prompt:k().min(1).max(1e3),echo:N()}),F({promptId:k().min(1).max(128),sessionId:k().min(1).max(128).optional(),response:k().max(1024).optional(),cancel:N().optional()}),I({hostId:op,threadId:k().min(1).max(1024).optional()});let xp=B([`listHarnesses`,`inspect`,`start`,`send`,`cancel`,`read`,`answer`,`list`]);I({operation:xp,hopCount:j().int().min(0).max(16),sourceId:Z.optional(),input:yl});let Sp=I({code:k().min(1).max(128),message:k().max(4096),details:yl.optional()});L([I({ok:V(!0),value:H}),I({ok:V(!1),error:Sp})]);let Cp=I({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});I({hosts:P(I({hostId:op,nodeId:ap.optional(),displayName:k().min(1).max(120),online:N(),state:fp,delegation:N(),projects:P(Cp),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional()}))}),I({version:V(1),instanceId:k().min(1).max(128),pid:j().int().positive(),endpoint:k().min(1).max(256),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j().int().nonnegative()}),L([I({operation:V(`hosts`)}),I({operation:xp,hostId:op,hopCount:j().int().min(0).max(16),timeoutMs:j().int().min(1).max(12e4).optional(),input:yl})]);let wp=F({id:k().min(1).max(256),harnessId:k().min(1),label:k().min(1).max(512),provider:B([`openai-codex`,`xai`])}).strict(),Tp=k().regex(/^[a-z][a-z0-9-]{0,47}$/),Ep=F({name:Tp,source:wp,importedAt:k()}).strict(),Dp=R(`action`,[F({action:V(`list`)}).strict(),F({action:V(`import`),sourceId:k().min(1).max(256),name:Tp,confirmed:V(!0)}).strict(),F({action:V(`reimport`),sourceId:k().min(1).max(256),name:Tp,confirmed:V(!0)}).strict(),F({action:V(`remove`),name:Tp,confirmed:V(!0)}).strict()]),Op=F({provider:k().min(1).max(128),type:B([`oauth`,`api_key`,`unknown`]),label:k().min(1).max(512).optional(),vendor:B([`openai-codex`,`xai`]).optional()}).strict();F({sources:P(wp),targets:P(F({harnessId:k(),providers:P(B([`openai-codex`,`xai`])),imports:P(Ep),others:P(Op).default([])}).strict())}).strict(),F({targetHarnessId:k().min(1).max(128).optional(),request:Dp}).strict(),F({events:N()});let kp=P(I({agent:k().min(1).max(128),section:B([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);I({entries:kp.nullable()}),I({}),I({entries:kp,initializeOnly:N().optional()});let Ap=I({enabled:N(),timeoutMinutes:j().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let jp=k().regex(/^external$/u),Mp=U.transform(e=>String(e)),Np=I({model:q.optional(),thinkingOptionId:G.optional(),permissionModeId:Ol.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`);R(`mode`,[I({mode:V(`global`)}),I({mode:V(`last`)}),I({mode:V(`manual`),harnessId:U})]);let Pp=I({lastHarness:U.optional(),byHarness:z(Mp,Np)}),Fp=I({model:q.optional(),thinkingOptionId:G.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),Ip=I({byHarness:z(Mp,Fp)}),Lp=k().min(1).max(1024),Rp=F({idleRelease:Ap.optional(),favorites:z(Mp,P(Lp).max(2048)).default({}),newThread:Pp.optional(),delegation:Ip.optional(),showGroupChatsInSidebar:N().optional()});I({scope:jp,revision:j().int().nonnegative(),values:Rp}),I({scope:jp.default(`external`)});let zp=R(`kind`,[I({kind:V(`idleRelease`),value:Ap}),I({kind:V(`favorite`),harnessId:U,modelId:Lp,enabled:N()}),I({kind:V(`favorites`),harnessId:U,modelIds:P(Lp).max(2048)}),I({kind:V(`newThread`),lastHarness:U.optional(),harnessId:U.optional(),configuration:Np.optional()}),I({kind:V(`delegation`),harnessId:U,configuration:Fp.nullable()}),I({kind:V(`groupChatsSidebar`),visible:N()})]);I({scope:jp.default(`external`),operations:P(zp).min(1).max(256),initializeOnly:N().optional(),expectedRevision:j().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),I({version:V(1),revision:j().int().nonnegative(),scopes:z(jp,Rp)});let Bp=j().finite().nonnegative(),Vp=I({input:Bp,output:Bp,cacheRead:Bp.optional(),cacheWrite:Bp.optional(),cacheWrite1h:Bp.optional()}),Hp=k().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);I({path:k(),entries:P(I({key:k(),price:Vp})),error:k().nullable()}),I({}),I({key:Hp,price:Vp.nullable(),previousKey:Hp.optional()}),I({model:Hp});let Up=I({official:N().optional(),canonicalModelId:k().min(1).optional(),provider:k().min(1).max(512),model:k().min(1).max(512),price:Vp});I({price:Vp.nullable(),suggestions:P(Up).max(6).optional()});let Wp=[`today`,`7d`,`30d`,`90d`,`all`],Q=j().int().min(0).max(2**53-1),Gp=k().regex(/^\d{4}-\d{2}-\d{2}$/u),Kp=k().min(1).max(128),qp=k().min(1).max(512),Jp=k().min(1).max(4096);I({range:B(Wp),timeZone:k().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:Kp.optional(),model:qp.nullable().optional(),project:Jp.nullable().optional(),date:Gp.optional()});let Yp=I({requests:Q,inputTokens:Q,cachedInputTokens:Q,cacheWriteInputTokens:Q,cacheKnownInputTokens:Q,cacheHitCachedInputTokens:Q,cacheHitInputTokens:Q,outputTokens:Q,reasoningOutputTokens:Q,costUsd:j().finite().min(0),unpricedRequests:Q,unmeteredRequests:Q}),Xp=Yp.shape,Zp=I({harness:Kp,sessionId:k().min(1).max(512),project:Jp.nullable(),title:k().min(1).max(200).optional(),models:P(qp).max(16),firstAtMs:Q,lastAtMs:Q,...Xp});I({range:B(Wp),from:Gp.nullable(),to:Gp,filters:I({harness:Kp.nullable(),model:qp.nullable(),unknownModel:N(),project:Jp.nullable(),unknownProject:N(),date:Gp.nullable()}),reading:I({complete:N(),sources:Q,read:Q}),failures:P(I({harness:Kp,message:k().max(2048)})).max(256),options:I({harnesses:P(Kp).max(256),models:P(qp.nullable()).max(4096),projects:P(Jp.nullable()).max(4096)}),modelLabels:P(I({harness:Kp,model:qp,label:qp})).max(4096).optional(),credits:P(I({harness:Kp,model:qp.nullable(),credits:j().finite().min(0),reportedRequests:Q,requests:Q})).max(4096).optional(),totals:Yp,daily:P(I({date:Gp,harness:Kp,...Xp})).max(2e5),hourly:P(I({weekday:j().int().min(0).max(6),hour:j().int().min(0).max(23),...Xp})).max(168),byHarness:P(I({harness:Kp,...Xp})).max(256),byModel:P(I({model:qp.nullable(),...Xp,harnessPricedRequests:Q})).max(4096),byProject:P(I({project:Jp.nullable(),...Xp})).max(4096),sessions:P(Zp).max(100),recentSessions:P(Zp).max(100).optional()}),F({threadId:W}),F({discarded:N()});let Qp=R(`type`,[F({id:k().min(1),type:V(`choice`),prompt:k(),options:P(F({value:k().min(1),label:k(),description:k().optional()})).min(1),multiple:N(),allowOther:N(),optional:N()}),F({id:k().min(1),type:V(`text`),prompt:k(),multiline:N(),secret:V(!1),optional:N(),placeholder:k().optional(),prefill:k().optional()})]),$p=F({interactionId:k().min(1),turnId:k().min(1),title:k().optional(),questions:P(Qp).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});I({threadId:k().min(1)}),F({questions:P($p)}),I({threadId:k().min(1),turnId:k().min(1),interactionId:k().min(1),answers:z(k(),P(k())),cancelled:N().default(!1)}),F({accepted:V(!0)});let em=`codexhostActiveTurnId`,tm=/* @__PURE__ */ new Set([em,`codexhostTurnChanges`,`codexhostToolOutput`,`codexGoal`]),nm=F({path:k(),oldText:k().nullable(),newText:k()});F({sessionId:k().min(1),turn:j().int().nonnegative(),path:k().min(1).optional()}),F({diffs:P(nm)}),I({}),I({}),F({reference:F({sessionId:k().min(1),epoch:k().min(1),turn:j().int().nonnegative(),seq:j().int().nonnegative(),callId:k().min(1),part:j().int().nonnegative(),version:k().min(1)}),length:j().int().nonnegative(),bytes:j().int().nonnegative()}),I({}),I({}),I({title:k().trim().min(1).max(200),type:B([`info`,`warning`,`danger`]),body:k().trim().min(1).max(16384)}),I({}),I({url:k().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status.codexhost/update/macos-signing/status.codexhost/update/macos-signing/setup.codexhost/update/macos-signing/remove`.split(`.`));let rm=B([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),im=B([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);I({threadId:k(),title:k(),harnessId:k(),state:rm,reason:im,inactiveMs:j().nonnegative()}),I({threadId:W,turnId:El});let am=F({email:k().trim().min(1).max(320).optional(),label:k().trim().min(1).max(256).optional(),plan:k().trim().min(1).max(128).optional(),credits:au.optional(),balance:ou.optional()}).strict();function om(e){return e.refine(e=>{let t=e;return t.credits!==void 0||t.balance!==void 0},{message:`Account must report either credits or a balance`})}let sm=om(am),cm={harnessId:U,harnessName:k().trim().min(1).max(128)},lm=F(cm).strict();F({}).strict(),F({sources:P(lm).max(128)}).strict(),F({harnessId:U,refresh:N().optional()}).strict(),F({...cm,account:sm.nullable(),accounts:P(sm).max(8).optional()}).strict(),F({refresh:N().optional()}).strict(),F({accounts:P(om(am.extend(cm))).max(128)}).strict(),F({harnessId:Tu,model:q.optional(),thinkingOptionId:G.optional(),permissionModeId:Ol.optional(),prewarm:V(!0).optional()}).strict();let um=k().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);F({harnessId:Tu}).strict().extend({path:um.nullable()}),F({path:um.nullable(),restartRequired:N()}).strict(),F({harnessId:U,action:B([`check`,`update`,`install`]),confirmedVersion:k().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let dm=F({currentVersion:k().min(1).max(128),latestVersion:k().min(1).max(128),updateAvailable:N(),canUpdate:N(),latestVerifiedVersion:k().min(1).max(128).optional(),confirmationRequired:V(!0).optional(),versionKind:B([`cli`,`application`]).optional(),manualUpdateUrl:rc().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:k().max(2048).optional(),messageCode:k().min(1).max(128).optional(),notice:wl.optional(),latestVersionKind:B([`unknown`,`tracking-branch`]).optional()}).strict();F({taskId:k().uuid()}).strict(),R(`status`,[F({taskId:k().uuid(),status:V(`running`)}).strict(),F({taskId:k().uuid(),status:V(`succeeded`),result:dm}).strict(),F({taskId:k().uuid(),status:V(`failed`),error:F({code:j().int(),message:k().min(1).max(2048)}).strict()}).strict()]);let fm=k().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),pm=k().trim().min(1),mm=B([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),hm=F({accountId:fm,label:pm.max(256),email:k().email().max(320).optional(),planType:mm.optional()}).strict(),gm=B([`ready`,`unavailable`]);F({version:V(2),currentAccountId:fm.nullable(),phase:gm,revision:j().int().nonnegative(),instanceId:pm.max(1024).optional(),accounts:P(hm).max(1)}).strict(),F({accountId:fm,refresh:N().optional()}).strict(),F({accountId:fm,usage:$l.nullable(),accountCredits:au.optional(),freshness:B([`live`,`cached`]),observedAt:k().datetime().nullable()}).strict();let _m=1e3,vm=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),ym=vm.max(1024),bm=F({nativeSessionId:ym,title:vm.max(4096).nullable(),updatedAt:j().int().nonnegative().max(864e13),cwd:vm.max(16384),running:N().nullable()}).strict();F({}).strict(),F({harnesses:P(F({harnessId:Tu,name:vm.max(128)}).strict()).max(128)}).strict(),F({harnessId:Tu,query:k().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:j().int().nonnegative().safe().optional(),limit:j().int().min(1).max(_m).optional()}).strict(),F({candidates:P(bm).max(_m),total:j().int().nonnegative().safe()}).strict(),F({harnessId:Tu,nativeSessionId:ym}).strict(),F({threadId:vm.max(1024).pipe(W)}).strict();let xm=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Sm=ym,Cm=bm;F({}).strict(),F({candidates:P(Cm).max(1e3)}).strict(),F({nativeSessionId:Sm}).strict(),F({threadId:xm.max(1024).pipe(W)}).strict(),F({threadId:W,lastTurnId:El}).strict(),F({threadId:W}).strict();let wm=k().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();F({commands:P(F({id:wm,invocation:k().min(1).max(128),label:k().trim().min(1).max(128),description:k().trim().min(1).max(512).optional(),localizations:Cl.optional(),argumentMode:B([`none`,`text`]),kind:B([`command`,`skill`]).optional()}).strict()),warnings:P(k().min(1)).optional(),source:B([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),F({harnessId:U,cwd:k().min(1).optional()}).strict(),F({threadId:W}).strict(),F({threadId:W,commandId:wm,turnId:El.optional(),arguments:yl.optional()}).strict(),F({accepted:V(!0),turnId:El.optional()}).strict();let Tm=V(`2.0`).optional(),Em=Dc().optional(),Dm=k().min(1),Om=L([k(),j().int()]),km=F({code:j().int(),message:k(),data:H.optional()}).catchall(H).superRefine(ml([`data`]));L([F({jsonrpc:Tm,id:Om,method:Dm,params:H.optional(),result:Em,error:Em}).catchall(H).superRefine(ml([`jsonrpc`,`params`,`result`,`error`])),F({jsonrpc:Tm,id:Em,method:Dm,params:H.optional(),result:Em,error:Em}).catchall(H).superRefine(ml([`jsonrpc`,`id`,`params`,`result`,`error`])),F({jsonrpc:Tm,id:Om,method:Em,params:Em,result:H,error:Em}).catchall(H).superRefine(ml([`jsonrpc`,`method`,`params`,`error`])),F({jsonrpc:Tm,id:Om,method:Em,params:Em,result:Em,error:km}).catchall(H).superRefine(ml([`jsonrpc`,`method`,`params`,`result`]))]);let Am=k().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});I({harnessId:U,nativeSessionId:Am,locator:H.optional(),formatVersion:V(1)}).superRefine(ml([`locator`])),I({harnessId:U,nativeSessionId:Am,nativeTurnKey:Am,formatVersion:V(1)}),I({harnessId:U,nativeSessionId:Am,checkpointId:Am,locator:H.optional(),formatVersion:V(1)}).superRefine(ml([`locator`]));let jm=k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Mm=B([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Nm=B([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),Pm=I({completed:j().int().nonnegative(),total:j().int().positive()}).refine(e=>e.completed<=e.total,{path:[`completed`],message:`completed must not exceed total`}),Fm=I({version:jm,installation:Mm,phase:Nm,updatedAt:j().int().nonnegative(),downloadedBytes:j().int().nonnegative().optional(),totalBytes:j().int().positive().optional(),npmDownload:Pm.optional(),error:k().min(1).max(500).nullable(),serviceStopOutput:k().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});I({});let Im=k().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`),Lm=B([`idle`,`downloading`,`ready`,`failed`]),Rm=I({downloadedBytes:j().int().nonnegative(),totalBytes:j().int().positive()}).refine(e=>e.downloadedBytes<=e.totalBytes,{path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`});F({currentVersion:jm,installation:Mm.nullable(),latestVersion:jm.nullable(),updateAvailable:N(),installationAvailable:N(),releaseNotes:k().min(1).max(2e4).nullable(),releaseNotesUrl:Im.nullable(),status:Fm.nullable(),error:k().min(1).max(500).nullable(),stagedVersion:jm.nullable().optional(),backgroundPhase:Lm.optional(),backgroundDownload:Rm.nullable().optional(),backgroundError:k().min(1).max(500).nullable().optional(),runningTaskCount:j().int().nonnegative().optional()}),I({status:Fm}),I({status:Fm.nullable()}),I({supported:N(),enabled:N(),certificatePresent:N(),appSignedWithLocalCert:N(),appPath:k().min(1).nullable(),certificateName:k().min(1),certificateSha1:k().regex(/^[0-9A-Fa-f]{40}$/u).nullable()});let zm=I({icon:k().min(1).max(16).optional(),title:k().min(1).max(120),body:k().min(1).max(1200),contributors:P(k().min(1).max(39)).max(30)}),Bm=I({summary:k().min(1).max(600).optional(),themes:P(zm).min(1).max(12)}),Vm=I({version:jm,publishedAt:pl(),url:k().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:Bm.nullable(),en:Bm.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});I({manual:N().optional()}),I({announcement:Vm.nullable(),unread:N()}),I({version:jm}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)(?:\?hostId=([^\s()<>"?#/&]+))?\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Hm=B([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);F({runningVersion:k().nullable(),installedVersion:k().nullable(),restartRequired:N(),remote:N(),updateSupported:N(),update:F({phase:Hm,targetVersion:k().nullable(),error:k().nullable()})});let Um=F({version:k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();F({hostname:k().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),action:B([`inspect`,`install`,`update`,`restart`,`repair`,`uninstall`]),uninstallPackage:N().optional(),version:k().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),F({state:B([`installed`,`not-installed`])}).strict();let $=k().min(1).max(1024),Wm={hostId:$.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},Gm={...Wm,threadId:$},Km=k().min(1).max(8e3),qm={text:Km,requestId:$},Jm=P($).min(2).max(100).refine(e=>new Set(e).size===e.length,`Queued submission IDs must be distinct`);R(`accepted`,[F({accepted:V(!0),startQueuedItemId:$.optional()}),F({accepted:V(!1),code:B([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:k()})]),R(`available`,[F({available:V(!1)}),F({available:V(!0),canReorder:V(!0).optional(),items:P(F({id:$,clientUserMessageId:$,preview:k().max(801)})).max(100)})]);let Ym=R(`kind`,[I({kind:V(`hosts`)}),I({kind:V(`create`),...Wm,cwd:k().min(1).max(8192),epoch:$}),I({kind:V(`projectHarnesses`),...Wm,epoch:$}),I({kind:V(`inspectHarness`),...Wm,epoch:$,cwd:k().min(1).max(8192),harnessId:$}),I({kind:V(`startSelected`),...Wm,epoch:$,cwd:k().min(1).max(8192),harnessId:$,model:k().min(1).max(4096),serviceTier:B([`priority`,`ultrafast`]).optional(),reasoningEffort:$.optional()}),I({kind:V(`status`),...Gm}),I({kind:V(`list`),...Wm,cursor:k().nullable(),archived:N(),includeLoaded:V(!0).optional()}),I({kind:V(`read`),...Gm,page:I({cursor:k().min(1).max(8192).nullable(),epoch:$.optional(),sortDirection:B([`asc`,`desc`]).optional(),limit:j().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),I({kind:V(`usage`),...Gm,epoch:$}),I({kind:V(`configure`),...Gm,epoch:$,modelId:$.optional(),serviceTier:lu.optional(),thinkingOptionId:$.optional(),permissionModeId:$.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),I({kind:V(`prompt`),...Gm,epoch:$,text:Km,requestId:$.optional()}),I({kind:V(`queue`),...Gm,epoch:$}),I({kind:V(`delivery`),...Gm,epoch:$,action:R(`kind`,[I({kind:V(`enqueue`),...qm}),I({kind:V(`steer`),...qm,turnId:$}),I({kind:V(`remove`),itemId:$}),I({kind:V(`reorder`),itemIds:Jm}),I({kind:V(`start`),itemId:$,onlyIfHead:V(!0).optional()}),I({kind:V(`sendNow`),itemId:$})])}),I({kind:V(`interrupt`),...Gm,epoch:$,turnId:$}),I({kind:V(`rename`),...Gm,epoch:$,name:k().min(1).max(512)}),I({kind:V(`archive`),...Gm,epoch:$,archived:N()}),I({kind:V(`respond`),...Gm,epoch:$,requestId:L([$,j().int()]),result:z(k(),Tc())})]),Xm=k().min(1).max(1024),Zm=F({hostId:Xm,displayName:k().min(1).max(1024),source:B([`codex-managed`,`discovered`]),sshAlias:k().max(1024).nullable(),sshHost:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),autoConnect:N(),connectionAnalyticsId:k().max(1024).optional()}),Qm=I({displayName:k().min(1).max(1024),hostname:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable()});R(`action`,[I({action:V(`session`),operation:Ym}),I({action:V(`list`)}),I({action:V(`catalog`)}),I({action:V(`read-thread`),hostId:Xm.refine(e=>e!==`local`),input:rp}),I({action:V(`save`),draft:Qm,previous:Zm.nullable()}),I({action:V(`remove`),previous:Zm}),I({action:V(`connect`),hostId:Xm,enabled:N()}),I({action:V(`state`),hostId:Xm}),I({action:V(`runtime`),hostId:Xm}),I({action:V(`update`),hostId:Xm.refine(e=>e!==`local`),version:Um.shape.version})]),L([I({result:H}),I({error:I({code:j().int(),message:k()})})]),I({prompt:k().trim().min(1).max(2e3),cwd:k().max(4096).nullable()}),k().trim().min(1).max(60).nullable();let $m=k().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),eh=L([k(),F({en:k()}).catchall(k())]),th=F({title:eh.optional(),description:eh.optional(),icon:k().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:k().optional()});F({extensions:P(F({id:$m,name:k().min(1).max(214),version:k().min(1).max(128),format:V(`dsh`),supportedTargets:Fc([V(`web`)]),enabledTargets:P(V(`web`)).max(1),source:k().min(1).max(4096),projectUrl:k().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:k(),meta:th.optional(),loadError:k().optional()})),loadedIds:P($m),safeMode:N(),storeError:k().optional()});let nh=k().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);F({spec:k().trim().min(1).max(4096),registry:nh.optional()}).strict(),F({id:$m,enabled:N()}).strict(),F({id:$m}).strict(),V(1);function rh(e,t,n){let r=/* @__PURE__ */ new Map;for(let e of t)r.set(n(e),e);let i=e.map(e=>r.get(n(e))).filter(e=>e!==void 0),a=new Set(i.map(n));for(let e=0;e<t.length;e++){let r=t[e];
114
114
  /* v8 ignore next -- dense-array guard: index is bounded by baseline.length. */
115
- if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];if(e===void 0||!a.has(n(e)))continue;let s=i.findIndex(t=>n(t)===n(e));if(s!==-1){o=s;break}}i.splice(o,0,r),a.add(n(r))}return i}let am={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
116
- `,r:`\r`,t:` `},om=/[\\\u0000-\u001f]/u;function sm(e){return e===` `||e===`
117
- `||e===`\r`||e===` `}function cm(e){return e>=`0`&&e<=`9`||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}(class e{static EMPTY=e.fromObject({});static fromText(t){let n=new e;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new e;return n.object=typeof t==`object`&&t&&!Array.isArray(t)?t:{},n.sealed=!0,n}chunks=[];object;sealed=!1;#e=[];#t=0;#n=0;#r=`root`;#i=!1;#a=0;#o=!1;#s=``;#c=null;#l=[];#u=!1;#d;#f=!1;#p=/* @__PURE__ */ new Map;#m=[];#h=/* @__PURE__ */ new Map;get isSealed(){return this.sealed}get invalid(){return this.scan(),this.#r===`invalid`||this.#f}append(e){if(this.sealed)throw Error(`PartialArguments: cannot append to a sealed view`);e.length!==0&&(this.chunks.push(e),this.#t+=e.length,this.#e.push(this.#t))}settle(t){if(this.object!==void 0||t.length!==this.#t)return e.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return e.fromText(t);n+=r.length}return this.chunks=t.length===0?[]:[t],this.#e=t.length===0?[]:[t.length],this.sealed=!0,this}refresh(){if(this.#h.size===0)return!1;this.scan();let e=!1,t=!1;for(let n of this.#h.values())n.completion?t=!0:e=this.refreshRead(n)||e;if(t)for(let t of this.#h.values())t.completion&&(e=this.refreshRead(t)||e);return this.sealed&&this.#h.clear(),e}refreshRead(e){let t=e.answer();return!Object.is(t,e.last)&&(e.last=t,!0)}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),e=>e.length)}has(e){return this.remember(`has`,e,()=>this.hasNow(e))}complete(e){return this.remember(`complete`,e,()=>this.completeNow(e))}stringLength(e,t){let n=Math.max(1,Math.floor(t?.step??1)),r=t?.offset??0;return this.remember(`length:${n}:${r}`,e,()=>this.lengthNow(e),e=>e===void 0?void 0:Math.ceil((e+r)/n))}stringExceeds(e,t){let n=Math.max(0,Math.floor(t));return this.remember(`exceeds:${n}`,e,()=>(this.lengthNow(e,n+1)??0)>n)}text(e){return this.remember(`text`,e,()=>this.textNow(e))}textPrefix(e,t){let n=Math.max(1,Math.floor(t));return this.remember(`prefix:${n}`,e,()=>this.textPrefixNow(e,n))}value(e){return this.remember(`value`,e,()=>this.valueNow(e))}remember(e,t,n,r){this.scan();let i=n();if(!this.sealed){let a=`${e}/${t}`;this.#h.has(a)||this.#h.set(a,{completion:e===`complete`,answer:r===void 0?n:()=>r(n()),last:r===void 0?i:r(i)})}return i}closedNow(){return this.sealed||this.#r===`closed`||this.#r===`invalid`}keysNow(){return this.object===void 0?this.#m:Object.keys(this.object)}hasNow(e){return this.object===void 0?this.#p.has(e):Object.hasOwn(this.object,e)}completeNow(e){if(this.object!==void 0)return Object.hasOwn(this.object,e);let t=this.#p.get(e);return t!==void 0&&t.end>=0&&(t.kind===`string`?t.invalidAt===void 0:!t.invalid)}lengthNow(e,t=1/0){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t.length:void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;if(n.text!==void 0&&n.text.at===n.end)return n.text.length;let r=n.length??={at:n.start,length:0,text:``};return this.readString(n,r,t,!1),r.length}textNow(e){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t:void 0}let t=this.#p.get(e);if(t?.kind!==`string`)return;if(t.text===void 0&&t.end>=0&&t.needsDecoding&&t.invalidAt===void 0){let e;try{e=JSON.parse(`"${this.slice(t.start,t.end)}"`)}catch{}e!==void 0&&(t.text={at:t.end,length:e.length,text:e})}let n=t.text??={at:t.start,length:0,text:``};return this.readString(t,n,1/0,!0),n.text}textPrefixNow(e,t){if(this.object!==void 0){let n=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof n==`string`?n.slice(0,t):void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;let r=n.prefixes??=/* @__PURE__ */ new Map,i=r.get(t);return i===void 0&&(i={at:n.start,length:0,text:``},r.set(t,i)),this.readString(n,i,t,!0),i.text}valueNow(e){if(this.object!==void 0){if(!Object.hasOwn(this.object,e))return;let t=this.object[e];return typeof t==`string`?void 0:t}let t=this.#p.get(e);if(!(t?.kind!==`value`||t.end<0||t.invalid)){if(t.parsed===void 0)try{t.parsed=JSON.parse(this.slice(t.start,t.end))}catch{t.invalid=!0,this.#f=!0}return t.parsed}}chunkAt(e){let t=0,n=this.#e.length;for(;t<n;){let r=t+n>>>1;this.#e[r]<=e?t=r+1:n=r}return t}slice(e,t){if(e>=t)return``;let n=this.chunkAt(e),r=this.chunkAt(t-1),i=n===0?0:this.#e[n-1];if(n===r)return this.chunks[n].slice(e-i,t-i);let a=[this.chunks[n].slice(e-i)];for(let e=n+1;e<r;e++)a.push(this.chunks[e]);return a.push(this.chunks[r].slice(0,t-this.#e[r-1])),a.join(``)}readString(e,t,n,r){let i=Math.min(e.end<0?this.#n:e.end,e.invalidAt??1/0,this.#d??1/0);if(!e.needsDecoding){let e=Math.min(i-t.at,n-t.length);if(e<=0)return;r&&(t.text+=this.slice(t.at,t.at+e)),t.at+=e,t.length+=e;return}let a=this.chunkAt(t.at);for(;t.at<i&&t.length<n;){let o=a===0?0:this.#e[a-1],s=this.chunks[a],c=s.slice(t.at-o,Math.min(s.length,i-o)),l=c.search(om),u=Math.min(l<0?c.length:l,n-t.length);if(u>0){r&&(t.text+=c.slice(0,u)),t.at+=u,t.length+=u,t.at===o+s.length&&a++;continue}let d=c.length>1?c[1]:t.at+1<i?this.chunks[a+1][0]:void 0,f,p=2;if(c[0]===`\\`&&d===void 0&&e.end<0)return;if(c[0]===`\\`&&d===`u`){let n=this.slice(t.at+2,Math.min(i,t.at+6)),r=!0;for(let e=0;e<n.length;e++)cm(n[e])||(r=!1);if(r){if(n.length<4&&e.end<0)return;n.length===4&&(f=String.fromCharCode(Number.parseInt(n,16)))}p=6}else c[0]===`\\`&&d!==void 0&&(f=am[d]);if(f===void 0){e.invalidAt=t.at,this.#f=!0;return}for(r&&(t.text+=f),t.length++,t.at+=p;a<this.chunks.length&&t.at>=this.#e[a];)a++}}scan(){if(this.object===void 0&&this.#n!==this.#t)for(let e=this.chunkAt(this.#n);e<this.chunks.length&&this.#d===void 0;e++){let t=this.chunks[e],n=e===0?0:this.#e[e-1];for(let e=this.#n-n;e<t.length&&this.#r!==`invalid`;e++){if(this.#r===`string`||this.#r===`nested`&&this.#u){let n=this.stringBoundary(t,e);if(this.#n+=n-e,e=n,e===t.length)break}this.step(t[e],this.#n),this.#n++}}}stringBoundary(e,t){let n=t;for(;;){let t=e.indexOf(`"`,n),r=t<0?e.length:t;if(this.#r===`string`){let t=this.#c;!t.needsDecoding&&om.test(e.slice(n,r))&&(t.needsDecoding=!0)}let i=r;for(;i>n&&e[i-1]===`\\`;)i--;let a=(r-i)%2==1!==(i===n&&this.#i);if(this.#i=t<0&&a,t<0||!a)return r;n=t+1}}step(e,t){switch(this.#r){case`root`:if(sm(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(sm(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(sm(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(sm(e))return;if(e===`:`){this.#r=`value`;return}this.fail();return;case`value`:this.beginValue(e,t);return;case`string`:{let e=this.#c;e.end=t,this.#c=null,this.#r=`comma-or-end`;return}case`scalar`:this.stepScalar(e,t);return;case`nested`:this.stepNested(e,t);return;case`comma-or-end`:if(sm(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(sm(e))return;this.fail();return;
115
+ if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];if(e===void 0||!a.has(n(e)))continue;let s=i.findIndex(t=>n(t)===n(e));if(s!==-1){o=s;break}}i.splice(o,0,r),a.add(n(r))}return i}let ih={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
116
+ `,r:`\r`,t:` `},ah=/[\\\u0000-\u001f]/u;function oh(e){return e===` `||e===`
117
+ `||e===`\r`||e===` `}function sh(e){return e>=`0`&&e<=`9`||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}(class e{static EMPTY=e.fromObject({});static fromText(t){let n=new e;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new e;return n.object=typeof t==`object`&&t&&!Array.isArray(t)?t:{},n.sealed=!0,n}chunks=[];object;sealed=!1;#e=[];#t=0;#n=0;#r=`root`;#i=!1;#a=0;#o=!1;#s=``;#c=null;#l=[];#u=!1;#d;#f=!1;#p=/* @__PURE__ */ new Map;#m=[];#h=/* @__PURE__ */ new Map;get isSealed(){return this.sealed}get invalid(){return this.scan(),this.#r===`invalid`||this.#f}append(e){if(this.sealed)throw Error(`PartialArguments: cannot append to a sealed view`);e.length!==0&&(this.chunks.push(e),this.#t+=e.length,this.#e.push(this.#t))}settle(t){if(this.object!==void 0||t.length!==this.#t)return e.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return e.fromText(t);n+=r.length}return this.chunks=t.length===0?[]:[t],this.#e=t.length===0?[]:[t.length],this.sealed=!0,this}refresh(){if(this.#h.size===0)return!1;this.scan();let e=!1,t=!1;for(let n of this.#h.values())n.completion?t=!0:e=this.refreshRead(n)||e;if(t)for(let t of this.#h.values())t.completion&&(e=this.refreshRead(t)||e);return this.sealed&&this.#h.clear(),e}refreshRead(e){let t=e.answer();return!Object.is(t,e.last)&&(e.last=t,!0)}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),e=>e.length)}has(e){return this.remember(`has`,e,()=>this.hasNow(e))}complete(e){return this.remember(`complete`,e,()=>this.completeNow(e))}stringLength(e,t){let n=Math.max(1,Math.floor(t?.step??1)),r=t?.offset??0;return this.remember(`length:${n}:${r}`,e,()=>this.lengthNow(e),e=>e===void 0?void 0:Math.ceil((e+r)/n))}stringExceeds(e,t){let n=Math.max(0,Math.floor(t));return this.remember(`exceeds:${n}`,e,()=>(this.lengthNow(e,n+1)??0)>n)}text(e){return this.remember(`text`,e,()=>this.textNow(e))}textPrefix(e,t){let n=Math.max(1,Math.floor(t));return this.remember(`prefix:${n}`,e,()=>this.textPrefixNow(e,n))}value(e){return this.remember(`value`,e,()=>this.valueNow(e))}remember(e,t,n,r){this.scan();let i=n();if(!this.sealed){let a=`${e}/${t}`;this.#h.has(a)||this.#h.set(a,{completion:e===`complete`,answer:r===void 0?n:()=>r(n()),last:r===void 0?i:r(i)})}return i}closedNow(){return this.sealed||this.#r===`closed`||this.#r===`invalid`}keysNow(){return this.object===void 0?this.#m:Object.keys(this.object)}hasNow(e){return this.object===void 0?this.#p.has(e):Object.hasOwn(this.object,e)}completeNow(e){if(this.object!==void 0)return Object.hasOwn(this.object,e);let t=this.#p.get(e);return t!==void 0&&t.end>=0&&(t.kind===`string`?t.invalidAt===void 0:!t.invalid)}lengthNow(e,t=1/0){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t.length:void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;if(n.text!==void 0&&n.text.at===n.end)return n.text.length;let r=n.length??={at:n.start,length:0,text:``};return this.readString(n,r,t,!1),r.length}textNow(e){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t:void 0}let t=this.#p.get(e);if(t?.kind!==`string`)return;if(t.text===void 0&&t.end>=0&&t.needsDecoding&&t.invalidAt===void 0){let e;try{e=JSON.parse(`"${this.slice(t.start,t.end)}"`)}catch{}e!==void 0&&(t.text={at:t.end,length:e.length,text:e})}let n=t.text??={at:t.start,length:0,text:``};return this.readString(t,n,1/0,!0),n.text}textPrefixNow(e,t){if(this.object!==void 0){let n=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof n==`string`?n.slice(0,t):void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;let r=n.prefixes??=/* @__PURE__ */ new Map,i=r.get(t);return i===void 0&&(i={at:n.start,length:0,text:``},r.set(t,i)),this.readString(n,i,t,!0),i.text}valueNow(e){if(this.object!==void 0){if(!Object.hasOwn(this.object,e))return;let t=this.object[e];return typeof t==`string`?void 0:t}let t=this.#p.get(e);if(!(t?.kind!==`value`||t.end<0||t.invalid)){if(t.parsed===void 0)try{t.parsed=JSON.parse(this.slice(t.start,t.end))}catch{t.invalid=!0,this.#f=!0}return t.parsed}}chunkAt(e){let t=0,n=this.#e.length;for(;t<n;){let r=t+n>>>1;this.#e[r]<=e?t=r+1:n=r}return t}slice(e,t){if(e>=t)return``;let n=this.chunkAt(e),r=this.chunkAt(t-1),i=n===0?0:this.#e[n-1];if(n===r)return this.chunks[n].slice(e-i,t-i);let a=[this.chunks[n].slice(e-i)];for(let e=n+1;e<r;e++)a.push(this.chunks[e]);return a.push(this.chunks[r].slice(0,t-this.#e[r-1])),a.join(``)}readString(e,t,n,r){let i=Math.min(e.end<0?this.#n:e.end,e.invalidAt??1/0,this.#d??1/0);if(!e.needsDecoding){let e=Math.min(i-t.at,n-t.length);if(e<=0)return;r&&(t.text+=this.slice(t.at,t.at+e)),t.at+=e,t.length+=e;return}let a=this.chunkAt(t.at);for(;t.at<i&&t.length<n;){let o=a===0?0:this.#e[a-1],s=this.chunks[a],c=s.slice(t.at-o,Math.min(s.length,i-o)),l=c.search(ah),u=Math.min(l<0?c.length:l,n-t.length);if(u>0){r&&(t.text+=c.slice(0,u)),t.at+=u,t.length+=u,t.at===o+s.length&&a++;continue}let d=c.length>1?c[1]:t.at+1<i?this.chunks[a+1][0]:void 0,f,p=2;if(c[0]===`\\`&&d===void 0&&e.end<0)return;if(c[0]===`\\`&&d===`u`){let n=this.slice(t.at+2,Math.min(i,t.at+6)),r=!0;for(let e=0;e<n.length;e++)sh(n[e])||(r=!1);if(r){if(n.length<4&&e.end<0)return;n.length===4&&(f=String.fromCharCode(Number.parseInt(n,16)))}p=6}else c[0]===`\\`&&d!==void 0&&(f=ih[d]);if(f===void 0){e.invalidAt=t.at,this.#f=!0;return}for(r&&(t.text+=f),t.length++,t.at+=p;a<this.chunks.length&&t.at>=this.#e[a];)a++}}scan(){if(this.object===void 0&&this.#n!==this.#t)for(let e=this.chunkAt(this.#n);e<this.chunks.length&&this.#d===void 0;e++){let t=this.chunks[e],n=e===0?0:this.#e[e-1];for(let e=this.#n-n;e<t.length&&this.#r!==`invalid`;e++){if(this.#r===`string`||this.#r===`nested`&&this.#u){let n=this.stringBoundary(t,e);if(this.#n+=n-e,e=n,e===t.length)break}this.step(t[e],this.#n),this.#n++}}}stringBoundary(e,t){let n=t;for(;;){let t=e.indexOf(`"`,n),r=t<0?e.length:t;if(this.#r===`string`){let t=this.#c;!t.needsDecoding&&ah.test(e.slice(n,r))&&(t.needsDecoding=!0)}let i=r;for(;i>n&&e[i-1]===`\\`;)i--;let a=(r-i)%2==1!==(i===n&&this.#i);if(this.#i=t<0&&a,t<0||!a)return r;n=t+1}}step(e,t){switch(this.#r){case`root`:if(oh(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(oh(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(oh(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(oh(e))return;if(e===`:`){this.#r=`value`;return}this.fail();return;case`value`:this.beginValue(e,t);return;case`string`:{let e=this.#c;e.end=t,this.#c=null,this.#r=`comma-or-end`;return}case`scalar`:this.stepScalar(e,t);return;case`nested`:this.stepNested(e,t);return;case`comma-or-end`:if(oh(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(oh(e))return;this.fail();return;
118
118
  /* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
119
119
  case`invalid`:return;
120
120
  /* v8 ignore next 2 -- Every scanner mode has a handler above. */
121
- default:lm(this.#r)}}fail(){this.#d=this.#n,this.#r=`invalid`,this.#c=null}beginKey(e){this.#r=`key`,this.#a=e+1,this.#o=!1,this.#i=!1}stepKey(e,t){if(e<` `){this.fail();return}if(this.#i){this.#i=!1;return}if(e===`\\`){this.#i=!0,this.#o=!0;return}if(e!==`"`)return;let n=this.slice(this.#a,t);if(this.#o)try{this.#s=JSON.parse(`"${n}"`)}catch{this.fail();return}else this.#s=n;this.#r=`colon`}open(e){this.#p.has(this.#s)||this.#m.push(this.#s),this.#p.set(this.#s,e),this.#c=e}beginValue(e,t){sm(e)||(e===`"`?(this.open({kind:`string`,start:t+1,end:-1,needsDecoding:!1,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0}),this.#i=!1,this.#r=`string`):e===`}`||e===`,`||e===`:`||e===`]`?this.fail():(this.open({kind:`value`,start:t,end:-1,parsed:void 0,invalid:!1}),e===`{`||e===`[`?(this.#r=`nested`,this.#l=[e===`{`?`}`:`]`],this.#u=!1,this.#i=!1):this.#r=`scalar`))}stepScalar(e,t){(e===`,`||e===`}`||sm(e))&&(this.closeValue(t),this.#r=e===`,`?`key-only`:e===`}`?`closed`:`comma-or-end`)}stepNested(e,t){if(this.#u)this.#u=!1;else if(e===`"`)this.#u=!0;else if(e===`{`||e===`[`)this.#l.push(e===`{`?`}`:`]`);else if(e===`}`||e===`]`){if(this.#l.pop()!==e){this.fail();return}this.#l.length===0&&(this.closeValue(t+1),this.#r=`comma-or-end`)}}closeValue(e){let t=this.#c;t.end=e,this.#c=null}});function lm(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function um(e,t){let n=Object.getOwnPropertyDescriptor(e,`constructor`)?.value;if(typeof n!=`function`)return!1;try{return n.name===t&&n.prototype===e&&Function.prototype.toString.call(n)===Function.prototype.toString.call(t===`Array`?Array:Object)}catch{return!1}}function dm(e){return Object.getPrototypeOf(e)===null&&um(e,`Object`)}function fm(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!um(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&dm(n)}function pm(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&dm(t)}function mm(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function hm(e,t){let n=/* @__PURE__ */ new Set,r,i=(e,t)=>{e!==void 0&&(e.kind===`root`?r=t:e.kind===`array`?e.target[e.index]=t:Object.defineProperty(e.target,e.key,{value:t,enumerable:!0,configurable:!0,writable:!0}))},a=[{kind:`visit`,value:e,...t?{destination:{kind:`root`}}:{}}];for(let e=a.pop();e!==void 0;e=a.pop()){if(e.kind===`leave`){n.delete(e.source);continue}if(e.kind===`array-item`){if(!Object.prototype.hasOwnProperty.call(e.source,e.index))return;a.push({kind:`visit`,value:e.source[e.index],...e.target===void 0?{}:{destination:{kind:`array`,target:e.target,index:e.index}}});continue}if(e.kind===`object-property`){a.push({kind:`visit`,value:e.source[e.key],...e.target===void 0?{}:{destination:{kind:`object`,target:e.target,key:e.key}}});continue}let r=e.value;if(r===null){i(e.destination,null);continue}if(typeof r==`boolean`||typeof r==`string`){i(e.destination,r);continue}if(typeof r==`number`){if(!Number.isFinite(r)||Object.is(r,-0))return;i(e.destination,r);continue}if(typeof r!=`object`||n.has(r))return;if(Array.isArray(r)){if(!fm(r))return;let o=r.length;if(Reflect.ownKeys(r).length!==o+1)return;let s=t?[]:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o-1;e>=0;e--)a.push({kind:`array-item`,source:r,index:e,...s===void 0?{}:{target:s}});continue}if(!pm(r))return;let o=mm(r);if(o===void 0)return;let s=t?{}:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o.length-1;e>=0;e--){let t=o[e];
121
+ default:ch(this.#r)}}fail(){this.#d=this.#n,this.#r=`invalid`,this.#c=null}beginKey(e){this.#r=`key`,this.#a=e+1,this.#o=!1,this.#i=!1}stepKey(e,t){if(e<` `){this.fail();return}if(this.#i){this.#i=!1;return}if(e===`\\`){this.#i=!0,this.#o=!0;return}if(e!==`"`)return;let n=this.slice(this.#a,t);if(this.#o)try{this.#s=JSON.parse(`"${n}"`)}catch{this.fail();return}else this.#s=n;this.#r=`colon`}open(e){this.#p.has(this.#s)||this.#m.push(this.#s),this.#p.set(this.#s,e),this.#c=e}beginValue(e,t){oh(e)||(e===`"`?(this.open({kind:`string`,start:t+1,end:-1,needsDecoding:!1,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0}),this.#i=!1,this.#r=`string`):e===`}`||e===`,`||e===`:`||e===`]`?this.fail():(this.open({kind:`value`,start:t,end:-1,parsed:void 0,invalid:!1}),e===`{`||e===`[`?(this.#r=`nested`,this.#l=[e===`{`?`}`:`]`],this.#u=!1,this.#i=!1):this.#r=`scalar`))}stepScalar(e,t){(e===`,`||e===`}`||oh(e))&&(this.closeValue(t),this.#r=e===`,`?`key-only`:e===`}`?`closed`:`comma-or-end`)}stepNested(e,t){if(this.#u)this.#u=!1;else if(e===`"`)this.#u=!0;else if(e===`{`||e===`[`)this.#l.push(e===`{`?`}`:`]`);else if(e===`}`||e===`]`){if(this.#l.pop()!==e){this.fail();return}this.#l.length===0&&(this.closeValue(t+1),this.#r=`comma-or-end`)}}closeValue(e){let t=this.#c;t.end=e,this.#c=null}});function ch(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function lh(e,t){let n=Object.getOwnPropertyDescriptor(e,`constructor`)?.value;if(typeof n!=`function`)return!1;try{return n.name===t&&n.prototype===e&&Function.prototype.toString.call(n)===Function.prototype.toString.call(t===`Array`?Array:Object)}catch{return!1}}function uh(e){return Object.getPrototypeOf(e)===null&&lh(e,`Object`)}function dh(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!lh(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&uh(n)}function fh(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&uh(t)}function ph(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function mh(e,t){let n=/* @__PURE__ */ new Set,r,i=(e,t)=>{e!==void 0&&(e.kind===`root`?r=t:e.kind===`array`?e.target[e.index]=t:Object.defineProperty(e.target,e.key,{value:t,enumerable:!0,configurable:!0,writable:!0}))},a=[{kind:`visit`,value:e,...t?{destination:{kind:`root`}}:{}}];for(let e=a.pop();e!==void 0;e=a.pop()){if(e.kind===`leave`){n.delete(e.source);continue}if(e.kind===`array-item`){if(!Object.prototype.hasOwnProperty.call(e.source,e.index))return;a.push({kind:`visit`,value:e.source[e.index],...e.target===void 0?{}:{destination:{kind:`array`,target:e.target,index:e.index}}});continue}if(e.kind===`object-property`){a.push({kind:`visit`,value:e.source[e.key],...e.target===void 0?{}:{destination:{kind:`object`,target:e.target,key:e.key}}});continue}let r=e.value;if(r===null){i(e.destination,null);continue}if(typeof r==`boolean`||typeof r==`string`){i(e.destination,r);continue}if(typeof r==`number`){if(!Number.isFinite(r)||Object.is(r,-0))return;i(e.destination,r);continue}if(typeof r!=`object`||n.has(r))return;if(Array.isArray(r)){if(!dh(r))return;let o=r.length;if(Reflect.ownKeys(r).length!==o+1)return;let s=t?[]:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o-1;e>=0;e--)a.push({kind:`array-item`,source:r,index:e,...s===void 0?{}:{target:s}});continue}if(!fh(r))return;let o=ph(r);if(o===void 0)return;let s=t?{}:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o.length-1;e>=0;e--){let t=o[e];
122
122
  /* v8 ignore next -- the loop is bounded by the captured key count. */
123
- if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function gm(e){return hm(e,!0)}function _m(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
123
+ if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function hh(e){return mh(e,!0)}function gh(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
124
124
  /* v8 ignore next -- the loop condition guarantees one pending task. */
125
125
  if(e===void 0)continue;if(e.kind===`property`){n.push({kind:`visit`,node:e.source[e.key]});continue}let r=e.node;if(typeof r!=`object`||!r||r instanceof AbortSignal||t.has(r))continue;t.add(r),Object.freeze(r);let i=Object.keys(r);for(let e=i.length-1;e>=0;e--){let t=i[e];
126
126
  /* v8 ignore next -- the loop is bounded by the captured key count. */
127
- t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function vm(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.sessionId,n);let n=/* @__PURE__ */ new Map,r=[];for(let i of e)if(i.parentSessionId!==void 0&&t.has(i.parentSessionId)){let e=n.get(i.parentSessionId)??[];e.push(i),n.set(i.parentSessionId,e)}else r.push(i);let i=[],a=/* @__PURE__ */ new Set,o=(e,t)=>{if(a.has(e.sessionId)){console.warn(`[session-controller] lineage cycle at ${e.sessionId}; emitting as root`);return}a.add(e.sessionId);let{agentAvailable:r,...s}=e;i.push({...s,depth:t});let c=n.get(e.sessionId);if(c!==void 0)for(let e of c)o(e,t+1)};for(let e of r)o(e,0);for(let t of e)a.has(t.sessionId)||o(t,0);return i}var ym=class{rebuild;listeners=/* @__PURE__ */ 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){let t=++this.scheduleGeneration;this.scheduled=e;let n=()=>{t===this.scheduleGeneration&&(this.scheduled=`none`,this.flush())};e===`frame`?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled=`none`}flush(){this.notifyPending&&this.listeners.size!==0&&(this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild()),(0,a.notifySubscribers)(this.listeners,`[session-controller]`))}};function bm(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!bm(e[n],t[n]))return!1;return!0}let n=Object.getPrototypeOf(e);if(n!==Object.getPrototypeOf(t)||n!==Object.prototype&&n!==null)return!1;let r=e,i=t,a=Object.keys(r),o=Object.keys(i);if(a.length!==o.length)return!1;for(let e of a)if(!Object.hasOwn(i,e)||!bm(r[e],i[e]))return!1;return!0}var xm=class{anyIgnoredKeys;rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;writeRevision=0;anyNotifier=new ym(()=>{});constructor(e){this.anyIgnoredKeys=e}get revision(){return this.writeRevision}faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}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){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<=r.seq?!1:r!==void 0&&bm(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyLive(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<r.seq?!1:r!==void 0&&bm(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyCached(e){for(let t of Object.keys(e)){let n=this.rows.get(t);n?.kind!==`sequenced`&&(n!==void 0&&bm(n.value,e[t])?this.writeRevision+=1:(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t)))}}seed(e,t,n){let r=e.values;for(let[e,t]of this.rows)t.kind!==`cached`||Object.hasOwn(r,e)||(this.rows.delete(e),this.changed(e));for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.writeRevision+=1,this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyIgnoredKeys?.has(e)||this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new ym(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}};let Sm=/* @__PURE__ */ new WeakMap;function Cm(e){return e.length*2}function wm(e,t){return Cm(e)+Cm(t)+64}function Tm(e){if(e===void 0||e.size===0)return 0;let t=64;for(let[n,r]of e)t+=wm(n,r);return t}function Em(e,t=0,n){if(e==null)return 0;switch(typeof e){case`string`:return Cm(e);case`number`:case`boolean`:case`bigint`:case`symbol`:return 8;case`function`:return 64;case`object`:{if(t>=12)return 64;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength+64;let r=Sm.get(e);if(r!==void 0)return r;if(n?.has(e))return 8;let i=n??/* @__PURE__ */ new Set;i.add(e);let a=64;try{if(Array.isArray(e)){a+=e.length*8;for(let n=0;n<e.length;n+=1)a+=Em(e[n],t+1,i)}else if(e instanceof Map)for(let[n,r]of e)a+=64+Em(n,t+1,i)+Em(r,t+1,i);else if(e instanceof Set)for(let n of e)a+=8+Em(n,t+1,i);else{let n=e;for(let e in n)Object.hasOwn(n,e)&&(a+=Cm(e)+8+Em(n[e],t+1,i))}}finally{i.delete(e)}return t===0&&n===void 0&&Object.isFrozen(e)&&Sm.set(e,a),a}default:return 0}}function Dm(e){let t=Sm.get(e);if(t!==void 0)return t;let n=Em(e);return Sm.set(e,n),n}function Om(e){let t=0;for(let n=0;n<e.length;n+=1)t+=8+Dm(e[n]);return t}function km(e){return e===void 0?0:64+Cm(e.epoch)+Om(e.records)}function Am(e){let t=64,n;if(e.journal!==void 0){t+=64+Cm(e.journal.epoch),n=/* @__PURE__ */ new Set;for(let r of e.journal.records)t+=8+Dm(r),n.add(r),typeof r.event==`object`&&r.event!==null&&n.add(r.event)}t+=64;for(let r of e.entries){if(t+=8,n!==void 0){if(n.has(r))continue;if(typeof r.event==`object`&&r.event!==null&&n.has(r.event)){t+=64;continue}}t+=Dm(r)}return t+=Tm(e.toolOutputs),t+=Em(e.projections),t}var jm=class{readRemote;values=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;maxBytes;totalBytes=0;constructor(e,t,n={}){if(this.readRemote=e,this.maxBytes=Math.max(0,n.maxBytes??8388608),t!==void 0)for(let[e,n]of t)this.remember(e,n)}get estimatedBytes(){return this.totalBytes}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return this.values.delete(t),this.values.set(t,n),Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.remember(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}remember(e,t){let n=this.values.get(e);n!==void 0&&(this.totalBytes-=wm(e,n),this.values.delete(e));let r=wm(e,t);if(!(r>this.maxBytes))for(this.values.set(e,t),this.totalBytes+=r;this.totalBytes>this.maxBytes&&this.values.size>0;){let t=this.values.entries().next().value;if(t[0]===e)break;this.values.delete(t[0]),this.totalBytes-=wm(t[0],t[1])}}};function Mm(){let e=globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=Array.from(e,(e,t)=>(t===6?e&15|64:t===8?e&63|128:e).toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Nm(e){return{kind:`leaf`,entries:e,length:e.length}}function Pm(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Fm(e){if(e.kind===`leaf`)return e.entries;let t=Array(e.length),n=[e],r=0;for(;n.length>0;){let e=n.pop();if(e.kind===`concat`)n.push(e.right,e.left);else for(let n of e.entries)t[r]=n,r+=1}return t}function Im(e,t,n,r){let i;return{get entries(){return i??=Fm(e),i},hasMore:t,revision:n,change:r}}var Lm=class{listeners=/* @__PURE__ */ new Set;window=Nm([]);estimatedEntryBytes=0;snapshot=Im(this.window,!1,0,{kind:`replace`,entries:[]});get estimatedBytes(){return this.estimatedEntryBytes}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=Nm(e),this.estimatedEntryBytes=Om(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Pm(Nm(e),this.window),this.estimatedEntryBytes+=Om(e),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Pm(this.window,Nm(t)),this.estimatedEntryBytes+=8+Dm(e),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Fm(this.window).filter(t=>t.type!==`transient`||t.event.data.attemptId!==e);if(t!==void 0){let e=n.findIndex(e=>e.event.seq>t.event.seq);e<0?n.push(t):n.splice(e,0,t)}this.window=Nm(n),this.estimatedEntryBytes=Om(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Im(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Rm(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function zm(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Bm(e,t){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`${t} index must be a non-negative safe integer`);return e}function Vm(e){let t=gm(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Hm(e){let t=[];for(let n of e){let e=Um(n);if(e.type===`chunk`){t.push({time:e.time,chunk:e.chunk});continue}let r=e.type===`tool-call-chunks`?e.args:e.texts,i=e.time0;for(let n=0;n<r.length;n+=1){n>0&&(i+=e.dt[n-1]);let a;a=e.type===`text-chunks`?{type:`text-delta`,index:e.index,text:r[n]}:e.type===`reasoning-chunks`?{type:`reasoning-delta`,index:e.index,text:r[n]}:{type:`tool-call-delta`,index:e.index,id:e.id,...Object.hasOwn(e,`name`)?{name:e.name}:{},argumentsDelta:r[n]},t.push({time:i,chunk:a})}}return t}function Um(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`Assistant stream record must be an object`);let t=e;switch(t.type){case`text-chunks`:case`reasoning-chunks`:{Km(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Gm(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Wm(t,e.length,t.type),t}case`tool-call-chunks`:{Km(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Gm(t.args,`tool-call-chunks args`);if(e.length===0)throw TypeError(`tool-call-chunks args must be non-empty`);if(typeof t.id!=`string`||t.id.length===0)throw TypeError(`tool-call-chunks id must be a non-empty string`);if(t.name!==void 0&&(typeof t.name!=`string`||t.name.length===0))throw TypeError(`tool-call-chunks name must be a non-empty string`);return Wm(t,e.length,t.type),t}case`chunk`:{Km(t,[`type`,`time`,`chunk`],`chunk`);let e=zm(t.time);if(typeof t.chunk!=`object`||t.chunk===null||Array.isArray(t.chunk))throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`);let n;try{n=Vm(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return _m({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Wm(e,t,n){if(zm(e.time0),Bm(e.index,n),!Array.isArray(e.dt)||e.dt.some(e=>!Number.isSafeInteger(e)))throw TypeError(`${n} dt must contain safe integers`);if(e.dt.length!==t-1)throw TypeError(`${n} dt length must be one less than its members`);let r=e.time0;for(let t of e.dt)if(r+=t,!Number.isSafeInteger(r))throw TypeError(`${n} member times must stay safe integers`)}function Gm(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Km(e,t,n){if(Object.keys(e).length!==t.length||!t.every(t=>Object.hasOwn(e,t)))throw TypeError(`${n} Assistant stream record must contain exactly ${t.join(`, `)}`)}var qm=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;estimatedPendingBytes(){if(this.pending.size===0)return 0;let e=0;for(let t of this.pending.values())e+=8+Dm(t);return e}replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Hm(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=Jm(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function Jm(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function Ym(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Xm={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},Zm={...Xm,turnWindow:{...Xm.turnWindow,minMessages:200}};var Qm=class{sessionId;remote;baseSeq=m(0);cachedJournal;toolOutputs;hasMore=!1;openState=`cold`;lastSyncedAt;openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;olderError=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;onEngaged;assistantStream=new qm;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionTarget;submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Lm;cachedProjectionBytesRevision=-1;cachedProjectionBytes=0;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new jm(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new xm,n.cachedView){let e=n.cachedView;this.cachedJournal=e.journal,this.baseSeq=e.baseSeq,this.hasMore=e.hasMore,this.lastSyncedAt=e.lastSyncedAt,this.projections.applyCached(e.projections),this.eventSource.replace(e.entries,e.hasMore)}this.address=n.address,this.parentAvailable=n.parentAvailable,this.notifier=new ym(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){if(this.submissionTarget!==void 0)return this.submissionTarget.beginSubmission(e);let t=Mm(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onObserved:e.onObserved,onRetire:e.onRetire,observed:!1,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}handoffSubmissions(e){if(e=e.submissionOwner(),e===this||this.submissionTarget!==void 0)return[];let t=this.pendingSubmissions.map(e=>e.requestId);if(t.length===0)return t;e.pendingSubmissions=[...e.pendingSubmissions,...this.pendingSubmissions];for(let n of t){let t=this.submissionSettlements.get(n);t!==void 0&&e.submissionSettlements.set(n,t);let r=this.inFlightPrompts.get(n);r!==void 0&&e.inFlightPrompts.set(n,r)}this.submissionSettlements.clear(),this.submissionTarget=e,e.promptAttempted||=this.promptAttempted;for(let{event:t}of e.eventSource.getSnapshot().entries)e.observeSubmissionEvent(t);return e.observeSubmissionInbox(),e.notifier.markDirty(),t}submissionOwner(){return this.submissionTarget?.submissionOwner()??this}get hasInFlightPrompts(){return this.inFlightPrompts.size>0}activeTurnForSteering(){let e=this.projections.get(ip);return typeof e==`string`?e:null}async prompt(e,t,n,r){if(this.submissionTarget!==void 0)return this.submissionTarget.prompt(e,t,n,r);let i=r??Mm();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=Rm(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Rm()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}let c=this.submissionOwner();return!s.ok&&s.error.code===`remote/outcome-unknown`&&c.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(c.acceptPrompt(),s):(r!==void 0&&c.retireFailedSubmission(r),c.promptError={op:`send`,error:s.error,requestId:i},c.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i);let e=this.submissionOwner();e.inFlightPrompts.get(i)===a&&e.inFlightPrompts.delete(i),this.notifier.markDirty()}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let 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;let 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)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...Xm})}catch(e){t===this.openGeneration&&(this.olderError=(0,i.isRemoteFailure)(e)?e:new o(`gateway/internal`,`Could not load earlier history.`,{}))}finally{t===this.openGeneration&&(this.loadingOlder=!1,this.notifier.markDirty())}}loadThrough(e){if(this.openState!==`open`||!this.hasMore||this.baseSeq<=e)return Promise.resolve();if(this.jumpPromise!==null)return this.jumpTargetSeq=p(Math.min(this.jumpTargetSeq??e,e)),this.jumpPromise;if(this.loadingOlder)return Promise.resolve();let t=this.events;if(t===void 0)return Promise.resolve();let n={beforeSeq:this.baseSeq,hasMore:this.hasMore,pages:[]};this.pendingHistory=n,this.jumpTargetSeq=e,this.olderError=null,this.loadingOlder=!0,this.notifier.markDirty();let r=this.openGeneration;return this.jumpPromise=(async()=>{try{for(;n.hasMore&&this.jumpTargetSeq!==null&&n.beforeSeq>this.jumpTargetSeq;){if(r!==this.openGeneration)return;let e=n.beforeSeq;if(await t.prepend({beforeSeq:e,...Zm}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=m(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}estimatedBytes(){let e=this.projections.revision;return this.cachedProjectionBytesRevision!==e&&(this.cachedProjectionBytes=Em(this.projections.values()),this.cachedProjectionBytesRevision=e),(this.eventSource.estimatedBytes>0?this.eventSource.estimatedBytes:km(this.cachedJournal))+this.assistantStream.estimatedPendingBytes()+this.toolOutputs.estimatedBytes+this.cachedProjectionBytes}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:new Map(this.toolOutputs.values),entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}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){let 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.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(ap),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Xm),e!==this.openGeneration||this.events!==n)return;this.cachedJournal=void 0,this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:Ym(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq)),e.key===`subagent`&&this.address?.mode===`unknown`&&this.notifier.markDirty()}let t=this.lastSyncedAt;this.lastSyncedAt=Date.now(),(e.type!==`assistant-stream`||t===void 0)&&this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=m(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,ap),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event);else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId);else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),t&&this.notifier.markDirty()}else e?.type===`transient`&&this.eventSource.append(e.entry)}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e);return}let n=this.hasMore;this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t),n!==t&&this.notifier.markDirty();for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:eh(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;this.confirmPrompt(r.rpcId);let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=eh(e.content),this.notifySubmissionObserved(i,i.admitted),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,eh(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}notifySubmissionObserved(e,t){e.observed||(e.observed=!0,e.onObserved?.(t))}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,this.notifySubmissionObserved(n,t),$m(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){if(this.submissionTarget!==void 0){this.submissionTarget.retireFailedSubmission(e);return}let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){if(this.submissionTarget!==void 0){this.submissionTarget.finishSubmission(e,t);return}let n=this.submissionSettlements.get(e);
127
+ t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function _h(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.sessionId,n);let n=/* @__PURE__ */ new Map,r=[];for(let i of e)if(i.parentSessionId!==void 0&&t.has(i.parentSessionId)){let e=n.get(i.parentSessionId)??[];e.push(i),n.set(i.parentSessionId,e)}else r.push(i);let i=[],a=/* @__PURE__ */ new Set,o=(e,t)=>{if(a.has(e.sessionId)){console.warn(`[session-controller] lineage cycle at ${e.sessionId}; emitting as root`);return}a.add(e.sessionId);let{agentAvailable:r,...s}=e;i.push({...s,depth:t});let c=n.get(e.sessionId);if(c!==void 0)for(let e of c)o(e,t+1)};for(let e of r)o(e,0);for(let t of e)a.has(t.sessionId)||o(t,0);return i}var vh=class{rebuild;listeners=/* @__PURE__ */ 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){let t=++this.scheduleGeneration;this.scheduled=e;let n=()=>{t===this.scheduleGeneration&&(this.scheduled=`none`,this.flush())};e===`frame`?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled=`none`}flush(){this.notifyPending&&this.listeners.size!==0&&(this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild()),(0,a.notifySubscribers)(this.listeners,`[session-controller]`))}};function yh(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!yh(e[n],t[n]))return!1;return!0}let n=Object.getPrototypeOf(e);if(n!==Object.getPrototypeOf(t)||n!==Object.prototype&&n!==null)return!1;let r=e,i=t,a=Object.keys(r),o=Object.keys(i);if(a.length!==o.length)return!1;for(let e of a)if(!Object.hasOwn(i,e)||!yh(r[e],i[e]))return!1;return!0}var bh=class{anyIgnoredKeys;rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;writeRevision=0;anyNotifier=new vh(()=>{});constructor(e){this.anyIgnoredKeys=e}get revision(){return this.writeRevision}faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}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){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<=r.seq?!1:r!==void 0&&yh(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyLive(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<r.seq?!1:r!==void 0&&yh(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyCached(e){for(let t of Object.keys(e)){let n=this.rows.get(t);n?.kind!==`sequenced`&&(n!==void 0&&yh(n.value,e[t])?this.writeRevision+=1:(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t)))}}seed(e,t,n){let r=e.values;for(let[e,t]of this.rows)t.kind!==`cached`||Object.hasOwn(r,e)||(this.rows.delete(e),this.changed(e));for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.writeRevision+=1,this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyIgnoredKeys?.has(e)||this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new vh(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}};let xh=/* @__PURE__ */ new WeakMap;function Sh(e){return e.length*2}function Ch(e,t){return Sh(e)+Sh(t)+64}function wh(e){if(e===void 0||e.size===0)return 0;let t=64;for(let[n,r]of e)t+=Ch(n,r);return t}function Th(e,t=0,n){if(e==null)return 0;switch(typeof e){case`string`:return Sh(e);case`number`:case`boolean`:case`bigint`:case`symbol`:return 8;case`function`:return 64;case`object`:{if(t>=12)return 64;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength+64;let r=xh.get(e);if(r!==void 0)return r;if(n?.has(e))return 8;let i=n??/* @__PURE__ */ new Set;i.add(e);let a=64;try{if(Array.isArray(e)){a+=e.length*8;for(let n=0;n<e.length;n+=1)a+=Th(e[n],t+1,i)}else if(e instanceof Map)for(let[n,r]of e)a+=64+Th(n,t+1,i)+Th(r,t+1,i);else if(e instanceof Set)for(let n of e)a+=8+Th(n,t+1,i);else{let n=e;for(let e in n)Object.hasOwn(n,e)&&(a+=Sh(e)+8+Th(n[e],t+1,i))}}finally{i.delete(e)}return t===0&&n===void 0&&Object.isFrozen(e)&&xh.set(e,a),a}default:return 0}}function Eh(e){let t=xh.get(e);if(t!==void 0)return t;let n=Th(e);return xh.set(e,n),n}function Dh(e){let t=0;for(let n=0;n<e.length;n+=1)t+=8+Eh(e[n]);return t}function Oh(e){return e===void 0?0:64+Sh(e.epoch)+Dh(e.records)}function kh(e){let t=64,n;if(e.journal!==void 0){t+=64+Sh(e.journal.epoch),n=/* @__PURE__ */ new Set;for(let r of e.journal.records)t+=8+Eh(r),n.add(r),typeof r.event==`object`&&r.event!==null&&n.add(r.event)}t+=64;for(let r of e.entries){if(t+=8,n!==void 0){if(n.has(r))continue;if(typeof r.event==`object`&&r.event!==null&&n.has(r.event)){t+=64;continue}}t+=Eh(r)}return t+=wh(e.toolOutputs),t+=Th(e.projections),t}var Ah=class{readRemote;values=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;maxBytes;totalBytes=0;constructor(e,t,n={}){if(this.readRemote=e,this.maxBytes=Math.max(0,n.maxBytes??8388608),t!==void 0)for(let[e,n]of t)this.remember(e,n)}get estimatedBytes(){return this.totalBytes}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return this.values.delete(t),this.values.set(t,n),Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.remember(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}remember(e,t){let n=this.values.get(e);n!==void 0&&(this.totalBytes-=Ch(e,n),this.values.delete(e));let r=Ch(e,t);if(!(r>this.maxBytes))for(this.values.set(e,t),this.totalBytes+=r;this.totalBytes>this.maxBytes&&this.values.size>0;){let t=this.values.entries().next().value;if(t[0]===e)break;this.values.delete(t[0]),this.totalBytes-=Ch(t[0],t[1])}}};function jh(){let e=globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=Array.from(e,(e,t)=>(t===6?e&15|64:t===8?e&63|128:e).toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Mh(e){return{kind:`leaf`,entries:e,length:e.length}}function Nh(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Ph(e){if(e.kind===`leaf`)return e.entries;let t=Array(e.length),n=[e],r=0;for(;n.length>0;){let e=n.pop();if(e.kind===`concat`)n.push(e.right,e.left);else for(let n of e.entries)t[r]=n,r+=1}return t}function Fh(e,t,n,r){let i;return{get entries(){return i??=Ph(e),i},hasMore:t,revision:n,change:r}}var Ih=class{listeners=/* @__PURE__ */ new Set;window=Mh([]);estimatedEntryBytes=0;snapshot=Fh(this.window,!1,0,{kind:`replace`,entries:[]});get estimatedBytes(){return this.estimatedEntryBytes}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=Mh(e),this.estimatedEntryBytes=Dh(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Nh(Mh(e),this.window),this.estimatedEntryBytes+=Dh(e),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Nh(this.window,Mh(t)),this.estimatedEntryBytes+=8+Eh(e),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Ph(this.window).filter(t=>t.type!==`transient`||t.event.data.attemptId!==e);if(t!==void 0){let e=n.findIndex(e=>e.event.seq>t.event.seq);e<0?n.push(t):n.splice(e,0,t)}this.window=Mh(n),this.estimatedEntryBytes=Dh(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Fh(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Lh(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Rh(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function zh(e,t){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`${t} index must be a non-negative safe integer`);return e}function Bh(e){let t=hh(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Vh(e){let t=[];for(let n of e){let e=Hh(n);if(e.type===`chunk`){t.push({time:e.time,chunk:e.chunk});continue}let r=e.type===`tool-call-chunks`?e.args:e.texts,i=e.time0;for(let n=0;n<r.length;n+=1){n>0&&(i+=e.dt[n-1]);let a;a=e.type===`text-chunks`?{type:`text-delta`,index:e.index,text:r[n]}:e.type===`reasoning-chunks`?{type:`reasoning-delta`,index:e.index,text:r[n]}:{type:`tool-call-delta`,index:e.index,id:e.id,...Object.hasOwn(e,`name`)?{name:e.name}:{},argumentsDelta:r[n]},t.push({time:i,chunk:a})}}return t}function Hh(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`Assistant stream record must be an object`);let t=e;switch(t.type){case`text-chunks`:case`reasoning-chunks`:{Gh(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Wh(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Uh(t,e.length,t.type),t}case`tool-call-chunks`:{Gh(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Wh(t.args,`tool-call-chunks args`);if(e.length===0)throw TypeError(`tool-call-chunks args must be non-empty`);if(typeof t.id!=`string`||t.id.length===0)throw TypeError(`tool-call-chunks id must be a non-empty string`);if(t.name!==void 0&&(typeof t.name!=`string`||t.name.length===0))throw TypeError(`tool-call-chunks name must be a non-empty string`);return Uh(t,e.length,t.type),t}case`chunk`:{Gh(t,[`type`,`time`,`chunk`],`chunk`);let e=Rh(t.time);if(typeof t.chunk!=`object`||t.chunk===null||Array.isArray(t.chunk))throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`);let n;try{n=Bh(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return gh({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Uh(e,t,n){if(Rh(e.time0),zh(e.index,n),!Array.isArray(e.dt)||e.dt.some(e=>!Number.isSafeInteger(e)))throw TypeError(`${n} dt must contain safe integers`);if(e.dt.length!==t-1)throw TypeError(`${n} dt length must be one less than its members`);let r=e.time0;for(let t of e.dt)if(r+=t,!Number.isSafeInteger(r))throw TypeError(`${n} member times must stay safe integers`)}function Wh(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Gh(e,t,n){if(Object.keys(e).length!==t.length||!t.every(t=>Object.hasOwn(e,t)))throw TypeError(`${n} Assistant stream record must contain exactly ${t.join(`, `)}`)}var Kh=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;estimatedPendingBytes(){if(this.pending.size===0)return 0;let e=0;for(let t of this.pending.values())e+=8+Eh(t);return e}replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Vh(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=qh(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function qh(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function Jh(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Yh={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},Xh={...Yh,turnWindow:{...Yh.turnWindow,minMessages:200}};var Zh=class{sessionId;remote;baseSeq=m(0);cachedJournal;toolOutputs;hasMore=!1;openState=`cold`;lastSyncedAt;openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;olderError=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;onEngaged;assistantStream=new Kh;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionTarget;submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Ih;cachedProjectionBytesRevision=-1;cachedProjectionBytes=0;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Ah(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new bh,n.cachedView){let e=n.cachedView;this.cachedJournal=e.journal,this.baseSeq=e.baseSeq,this.hasMore=e.hasMore,this.lastSyncedAt=e.lastSyncedAt,this.projections.applyCached(e.projections),this.eventSource.replace(e.entries,e.hasMore)}this.address=n.address,this.parentAvailable=n.parentAvailable,this.notifier=new vh(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){if(this.submissionTarget!==void 0)return this.submissionTarget.beginSubmission(e);let t=jh(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onObserved:e.onObserved,onRetire:e.onRetire,observed:!1,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}handoffSubmissions(e){if(e=e.submissionOwner(),e===this||this.submissionTarget!==void 0)return[];let t=this.pendingSubmissions.map(e=>e.requestId);if(t.length===0)return t;e.pendingSubmissions=[...e.pendingSubmissions,...this.pendingSubmissions];for(let n of t){let t=this.submissionSettlements.get(n);t!==void 0&&e.submissionSettlements.set(n,t);let r=this.inFlightPrompts.get(n);r!==void 0&&e.inFlightPrompts.set(n,r)}this.submissionSettlements.clear(),this.submissionTarget=e,e.promptAttempted||=this.promptAttempted;for(let{event:t}of e.eventSource.getSnapshot().entries)e.observeSubmissionEvent(t);return e.observeSubmissionInbox(),e.notifier.markDirty(),t}submissionOwner(){return this.submissionTarget?.submissionOwner()??this}get hasInFlightPrompts(){return this.inFlightPrompts.size>0}activeTurnForSteering(){let e=this.projections.get(em);return typeof e==`string`?e:null}async prompt(e,t,n,r){if(this.submissionTarget!==void 0)return this.submissionTarget.prompt(e,t,n,r);let i=r??jh();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=Lh(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Lh()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}let c=this.submissionOwner();return!s.ok&&s.error.code===`remote/outcome-unknown`&&c.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(c.acceptPrompt(),s):(r!==void 0&&c.retireFailedSubmission(r),c.promptError={op:`send`,error:s.error,requestId:i},c.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i);let e=this.submissionOwner();e.inFlightPrompts.get(i)===a&&e.inFlightPrompts.delete(i),this.notifier.markDirty()}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let 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;let 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)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...Yh})}catch(e){t===this.openGeneration&&(this.olderError=(0,i.isRemoteFailure)(e)?e:new o(`gateway/internal`,`Could not load earlier history.`,{}))}finally{t===this.openGeneration&&(this.loadingOlder=!1,this.notifier.markDirty())}}loadThrough(e){if(this.openState!==`open`||!this.hasMore||this.baseSeq<=e)return Promise.resolve();if(this.jumpPromise!==null)return this.jumpTargetSeq=p(Math.min(this.jumpTargetSeq??e,e)),this.jumpPromise;if(this.loadingOlder)return Promise.resolve();let t=this.events;if(t===void 0)return Promise.resolve();let n={beforeSeq:this.baseSeq,hasMore:this.hasMore,pages:[]};this.pendingHistory=n,this.jumpTargetSeq=e,this.olderError=null,this.loadingOlder=!0,this.notifier.markDirty();let r=this.openGeneration;return this.jumpPromise=(async()=>{try{for(;n.hasMore&&this.jumpTargetSeq!==null&&n.beforeSeq>this.jumpTargetSeq;){if(r!==this.openGeneration)return;let e=n.beforeSeq;if(await t.prepend({beforeSeq:e,...Xh}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=m(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}estimatedBytes(){let e=this.projections.revision;return this.cachedProjectionBytesRevision!==e&&(this.cachedProjectionBytes=Th(this.projections.values()),this.cachedProjectionBytesRevision=e),(this.eventSource.estimatedBytes>0?this.eventSource.estimatedBytes:Oh(this.cachedJournal))+this.assistantStream.estimatedPendingBytes()+this.toolOutputs.estimatedBytes+this.cachedProjectionBytes}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:new Map(this.toolOutputs.values),entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}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){let 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.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(tm),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Yh),e!==this.openGeneration||this.events!==n)return;this.cachedJournal=void 0,this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:Jh(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq)),e.key===`subagent`&&this.address?.mode===`unknown`&&this.notifier.markDirty()}let t=this.lastSyncedAt;this.lastSyncedAt=Date.now(),(e.type!==`assistant-stream`||t===void 0)&&this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=m(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,tm),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event);else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId);else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),t&&this.notifier.markDirty()}else e?.type===`transient`&&this.eventSource.append(e.entry)}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e);return}let n=this.hasMore;this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t),n!==t&&this.notifier.markDirty();for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:$h(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;this.confirmPrompt(r.rpcId);let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=$h(e.content),this.notifySubmissionObserved(i,i.admitted),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,$h(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}notifySubmissionObserved(e,t){e.observed||(e.observed=!0,e.onObserved?.(t))}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,this.notifySubmissionObserved(n,t),Qh(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){if(this.submissionTarget!==void 0){this.submissionTarget.retireFailedSubmission(e);return}let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){if(this.submissionTarget!==void 0){this.submissionTarget.finishSubmission(e,t);return}let n=this.submissionSettlements.get(e);
128
128
  /* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
129
- n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function $m(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function eh(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;(e.type===`image`||e.type===`file`)&&typeof e.attachment==`object`&&e.attachment!==null&&t.push(e.attachment)}return t}var th=class{views=/* @__PURE__ */ new Map;maxEntries;maxBytes;estimateBytes;cachedBytes=0;constructor(e={}){this.maxEntries=Math.max(0,e.maxEntries??8),this.maxBytes=Math.max(0,e.maxBytes??25165824),this.estimateBytes=e.estimateBytes??Am}get size(){return this.views.size}get totalBytes(){return this.cachedBytes}take(e){let t=this.views.get(e);if(t!==void 0)return this.views.delete(e),this.cachedBytes-=t.bytes,t.view}remember(e,t){let n=this.views.get(e);n!==void 0&&(this.views.delete(e),this.cachedBytes-=n.bytes);let r=Math.max(0,this.estimateBytes(t));if(this.maxEntries===0||r>this.maxBytes)return[e];this.views.set(e,{view:t,bytes:r}),this.cachedBytes+=r;let i=[];for(;this.views.size>this.maxEntries||this.cachedBytes>this.maxBytes;){let t=this.views.entries().next().value;if(t[0]===e)break;this.views.delete(t[0]),this.cachedBytes-=t[1].bytes,i.push(t[0])}return i}delete(e){let t=this.views.get(e);t!==void 0&&(this.views.delete(e),this.cachedBytes-=t.bytes)}clear(){this.views.clear(),this.cachedBytes=0}};function nh(e){return e===-1?-1:p(e)}let rh=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]),ih=/* @__PURE__ */ new Set([...ap,`codexhostTurnTimes`,`codexhostUsage`,`contextPressure`,`contextBreakdown`,`inbox`,`queueState`,`turnOutline`,`sessionStats`,`compacting`,`goal`,`agentPreset`,`plan`,`todos`,`permissions`,`nativePermissions`,`modelSelection`,`attachmentInput`,`imageLimits`,`sentMessageEdit`]);var ah=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new th;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;workspaceOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;workspaceStartCursor;workspaceHistory=/* @__PURE__ */ new Map;activeWorkspacePage;activeListCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];projectionSnapshotCache=/* @__PURE__ */ new Map;projectionsBySessionCache={};notifier=new ym(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r)for(let t of this.recentViews.remember(e,r))this.projectionStores.get(t)?.discard(ap);return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.resetListQueries(),this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new Qm(e,this.remote,{...t===void 0?{}:{address:t,...n===void 0?{}:{parentAvailable:n}},onEngaged:e=>{!this.disposed&&this.retainedIds(this.summaries).has(e.sessionId)&&(this.engagedSessions.has(e.sessionId)||(this.engagedSessions.add(e.sessionId),this.recordMutation({kind:`engaged`,sessionId:e.sessionId})),this.sessions.get(e.sessionId)?.handleBlank(!1))},projections:this.projectionStore(e),cachedView:this.recentViews.take(e)})}effectiveBlank(e){return e.blank&&!this.engagedSessions.has(e.sessionId)}retainedIds(e){let t=new Set(e.map(e=>e.sessionId));for(let e of this.sessions.keys())t.add(e);for(let e of this.addresses.keys())t.add(e);return t}pruneEngagement(e,t){t.has(e)||this.engagedSessions.delete(e)}projectionStore(e){let t=this.projectionStores.get(e);if(t===void 0){t=new xm(ih);let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markFrameDirty()}),this.projectionStores.set(e,t)}return t}refreshProjections(e){let t=this.projectionInflight.get(e);if(t!==void 0)return t.promise;if(this.projectionLoads.get(e)?.state===`ready`)return Promise.resolve();let n=new AbortController,r=this.projectionStore(e),a=r.revision;this.projectionLoads.set(e,{state:`loading`,error:null}),this.notifier.markDirty();let o=(async()=>{try{let t=await this.remote.session.projections({sessionId:e},n.signal);if(n.signal.aborted)return;t.ok?(t.value===null?r.revision===a&&r.clear():r.seed({...t.value,asOfSeq:nh(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.resetListQueries(),this.refreshList())}resetListQueries(){this.nextCursor=void 0,this.workspaceStartCursor=void 0,this.workspaceHistory=/* @__PURE__ */ new Map,this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null}hasSummary(e){return this.summaries.some(t=>t.sessionId===e)}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){if(e===void 0)return this.nextCursor?this.refreshList(this.nextCursor):Promise.resolve();let t=this.workspaceHistory,n=t.get(e);if(n?.pending)return n.pending;let r=n?n.cursor:this.workspaceStartCursor;if(!r||this.disposed)return Promise.resolve();let i={cursor:r,state:`loading`};return t.set(e,i),this.notifier.markDirty(),i.pending=(async()=>{t===this.workspaceHistory&&await this.refreshList(r,e)})().finally(()=>{delete i.pending,t===this.workspaceHistory&&this.notifier.markDirty()}),i.pending}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null){if(t===this.activeWorkspacePage&&e===this.activeListCursor)return this.listInflight;let n=this.workspaceHistory;return this.listInflight.catch(()=>void 0).then(()=>{if(n===this.workspaceHistory)return this.refreshList(e,t)})}let n=this.includeArchived;this.activeWorkspacePage=t,this.activeListCursor=e;let r=t===void 0?void 0:this.workspaceHistory.get(t);r||(this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0);let a=e=>{r?r.state=`retry`:(this.listState=`error`,this.listError=e)},o=this.summaries,s=[];return this.listMutations=s,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==s)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),a=new Set(i.value.items.map(e=>e.sessionId)),c=r!==void 0||i.value.nextCursor!==void 0,l=i.value.nextCursor??null;if(r){let e=new Set(this.summaries.map(e=>e.sessionId)),t=i.value.items.filter(t=>!t.blank&&!e.has(t.sessionId));for(let e of t)this.workspaceOnlyIds.add(e.sessionId);r.cursor=l,r.state=l?t.length>0?`search`:`continue`:`done`}else{for(let e of a)this.workspaceOnlyIds.delete(e);(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=l),e===void 0&&this.workspaceStartCursor==null&&(this.workspaceStartCursor=l)}let u=[...i.value.items,...o.filter(e=>!a.has(e.sessionId)&&(c||!n&&t.has(e.sessionId)))],d=this.listPhase===`pending`?u:im(o,u,e=>e.sessionId),f=/* @__PURE__ */ new Set;for(let e of s)e.kind===`remove`&&f.add(e.sessionId);for(let e of d)e.running&&!f.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let p=s.reduce(oh,d);this.summaries=p;let m=new Set(p.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(a.has(e)||!m.has(e))&&this.summaryOnlyIds.delete(e);for(let e of this.workspaceOnlyIds)m.has(e)||this.workspaceOnlyIds.delete(e);let ee=this.retainedIds(p);for(let e of this.engagedSessions)this.pruneEngagement(e,ee);r||(this.listState=`idle`,this.listPhase=`ready`),this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===s&&(this.headRefreshRevision+=1)}else a(i.error)}catch(e){if(this.listMutations!==s)return;if(r)r.state=`retry`;else if((0,i.isRemoteFailure)(e))a(e);else throw e}finally{this.listMutations===s&&(this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t={...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.matchProjectDefault?{matchProjectDefault:!0}:{}},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=sh(r.error);e!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:e,updatedAt:Date.now(),running:!1,blank:!0}})}return r}async fork(e){let t=this.sessions.get(e.sessionId);if(t&&t.getSnapshot().openState!==`open`)return{ok:!1,error:new o(`session/syncing`,`Wait for the Session history to finish synchronizing.`,{})};let n=this.summaries.find(t=>t.sessionId===e.sessionId),r=await this.remote.session.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:e.atSeq}}),i=r.ok?r.value.sessionId:sh(r.error);return i!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:i,updatedAt:Date.now(),running:!1,blank:!0,parentSessionId:e.sessionId,...n?.cwd===void 0?{}:{cwd:n.cwd}}}),r}async rename(e,t){let n=await this.remote.session.rename({sessionId:e,title:t});return n.ok&&this.projectionStore(e).apply(`title`,n.value.title,p(n.value.seq))&&this.notifier.markDirty(),n}mergeSummary(e){let t=this.recordMutation({kind:`upsert`,summary:e},`frame`);return this.updateParentAvailability(),t}recordMutation(e,t=`microtask`){if(this.disposed)return!1;this.listMutations?.push(e);let n=oh(this.summaries,e);return n!==this.summaries&&(this.summaries=n,t===`frame`?this.notifier.markFrameDirty():this.notifier.markDirty(),!0)}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}projectionValues(e){return this.projectionStores.get(e)?.values()}handleControlFrame(e){e.type===`baseline`?this.replaceControlBaseline(e.value):this.projectionStore(e.sessionId).applyLive(e.key,e.value,p(e.seq))&&!ih.has(e.key)&&this.notifier.markFrameDirty()}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=nh(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,ap)}this.notifier.markFrameDirty()}handleSessionAdded(e,t=!0){let n=t&&this.summaryOnlyIds.delete(e.sessionId),r=t&&this.workspaceOnlyIds.delete(e.sessionId),i=this.mergeSummary(e);(n||r)&&!i&&this.notifier.markFrameDirty(),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let a=this.sessions.get(e.sessionId);a?.handleRestored(),a?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=nh(t.asOfSeq);for(let[r,i]of Object.entries(t.values))n.apply(r,i,e);return}case`cached`:n.applyCached(t.values);return;default:lm(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){let t=this.summaryOnlyIds.delete(e),n=this.workspaceOnlyIds.delete(e),r=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`),i=this.recordMutation(r?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e},`frame`),a=!1;if(r){let t=this.sessions.get(e);a=t?.getSnapshot().running===!0,t?.handleRunning(!1)}else this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved();let o=this.projectionStores.get(e)?.values().subagentCatalog,s=!r&&(o===void 0||o.length===0)&&this.projectionStores.delete(e);this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e);let c=this.projectionLoads.delete(e);!i&&(t||n||s||c||a)&&this.notifier.markFrameDirty();for(let[t,n]of this.addresses)n.parentSessionId===e&&this.sessions.get(t)?.handleSubagentParentAvailable(!1)}handleSessionStatus(e,t){!this.disposed&&t&&this.engagedSessions.add(e);let n=this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0},`frame`);this.updateParentAvailability();let r=this.sessions.get(e),i=r?.getSnapshot().running;r?.handleRunning(t),!n&&r!==void 0&&i!==t&&this.notifier.markFrameDirty()}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t},`frame`)}handleSessionError(e,t){this.sessions.get(e)?.handleAgentError(t)}handleConnected(){for(let e of this.sessions.values())e.getSnapshot().openState===`error`&&e.resync();for(let e of this.projectionStores.values())e.clear(rh);this.resetListQueries(),this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=vm(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e);let n=this.projectionSnapshotCache.size!==this.projectionStores.size;for(let[e,t]of this.projectionStores){let r=t.values(),i=this.projectionLoads.get(e),a=i?.state??`idle`,o=i?.error??null,s=this.projectionSnapshotCache.get(e);(s===void 0||s.values!==r||s.state!==a||s.error!==o)&&(this.projectionSnapshotCache.set(e,{values:r,state:a,error:o}),n=!0)}if(n){for(let e of this.projectionSnapshotCache.keys())this.projectionStores.has(e)||this.projectionSnapshotCache.delete(e);this.projectionsBySessionCache=Object.fromEntries(this.projectionSnapshotCache)}return{items:this.itemsCache,hasMore:!!this.nextCursor,canSearchWorkspaceHistory:!!this.workspaceStartCursor,workspaceHistory:Object.fromEntries([...this.workspaceHistory].map(([e,t])=>[e,t.pending?`loading`:t.state])),workspaceOnlyIds:[...this.workspaceOnlyIds],headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,projectionsBySession:this.projectionsBySessionCache}}};function oh(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.findIndex(e=>e.sessionId===t.summary.sessionId);if(n===-1)return[t.summary,...e];let r=e[n],i={...r,blank:r.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...r.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...r.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...r.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};if(i.cwd===r.cwd&&i.parentSessionId===r.parentSessionId&&i.origin===r.origin&&i.blank===r.blank&&i.agentAvailable===r.agentAvailable&&i.running===r.running)return e;let a=[...e];return a[n]=i,a}case`remove`:return e.findIndex(e=>e.sessionId===t.sessionId)===-1?e:e.filter(e=>e.sessionId!==t.sessionId);case`status`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(r.running===t.running&&r.agentAvailable===t.agentAvailable&&(!t.running||!r.blank))return e;let i=[...e];return i[n]={...r,running:t.running,agentAvailable:t.agentAvailable,blank:r.blank&&!t.running},i}case`activity`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!(t.updatedAt>r.updatedAt))return e;let i=[...e];return i[n]={...r,updatedAt:t.updatedAt},i}case`engaged`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!r.blank)return e;let i=[...e];return i[n]={...r,blank:!1},i}}}function sh(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var ch=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},lh=class extends Error{rpcError;sourceSessionId;name=`SessionForkError`;constructor(e,t){super(`session fork failed: ${e.code}: ${e.message}`),this.rpcError=e,this.sourceSessionId=t}};function uh(e,t,n){if(e!==void 0)return e;if(t!==void 0&&t!==``){let e=me(t);if(e!==``)return e}return n}function dh(e){let t=/^(.*?)\((\d+)\)$/u.exec(e);if(t?.[1]!==void 0&&t[2]!==void 0)return`${t[1]}(${BigInt(t[2])+1n})`;let n=/^(.*?)((\d+))$/u.exec(e);return n?.[1]!==void 0&&n[2]!==void 0?`${n[1]}(${BigInt(n[2])+1n})`:`${e} (1)`}function fh(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let ph=Object.freeze({referenceCount:0,retainedBy:fh({})});async function mh(e,t){if(t===void 0)return e;let n=Promise.withResolvers(),r=()=>{n.reject(t.reason)};t.addEventListener(`abort`,r,{once:!0});try{t.aborted&&r(),await Promise.race([e,n.promise])}finally{t.removeEventListener(`abort`,r)}}var hh=class{sessionId;record;releaseReference;released=new AbortController;readiness=Promise.withResolvers();ready=this.readiness.promise;constructor(e,t,n){this.sessionId=e,this.record=t,this.releaseReference=n,this.ready.catch(()=>{})}get binding(){if(this.record===void 0||!this.record.live)throw Error(`Session reference "${this.sessionId}" is released`);return this.record.binding}attachOpening(e,t){let n=t===void 0?this.released.signal:AbortSignal.any([this.released.signal,t]);mh(e,n).then(()=>{try{n.throwIfAborted(),this.readiness.resolve(this.binding)}catch(e){this.readiness.reject(e)}},e=>{this.readiness.reject(e)})}release(){let e=/* @__PURE__ */ Error(`Session reference "${this.sessionId}" is released`),t=this.releaseReference;this.released.abort(e),this.readiness.reject(e),this.record=void 0,this.releaseReference=void 0,t?.()}[Symbol.dispose](){this.release()}},gh=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;projectedItemCache=/* @__PURE__ */ new Map;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new ah(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}handoffSubmissions(e,t){let n=this.scopes.get(e)?.session;if(n===void 0||e===t||n.getSnapshot().pendingSubmissions.length===0&&!n.hasInFlightPrompts)return;let r=this.retain(t,{source:`controllerOperation`}),i=this.retain(e,{source:`controllerOperation`}),a=this.manager.get(t),o=new Set(n.handoffSubmissions(a)),s=[],c=!1,l=()=>{if(!c){c=!0;for(let e of s)e();r.release(),i.release()}},u=()=>{!n.hasInFlightPrompts&&!a.getSnapshot().pendingSubmissions.some(e=>o.has(e.requestId))&&l()};s.push(a.subscribe(u),n.subscribe(u)),r.ready.catch(l),i.ready.catch(l),u()}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}async loadSummary(e){await this.manager.loadSummary(e),this.closed||this.projectList()}syncSummary(e){return this.list.getSnapshot().byId[e]===void 0?this.closed||!this.manager.hasSummary(e)?!1:(this.projectList(),this.list.getSnapshot().byId[e]!==void 0):!0}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new ch(t.error,e.sessionId);return this.projectList(),t.value.sessionId}async fork(e){let 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:p(e.atSeq)}});if(!n.ok)throw new lh(n.error,e.sessionId);this.projectList();let r=n.value.sessionId;if(e.onCreated?.(r),t!==void 0){let e=await this.manager.rename(r,dh(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}estimatedBytes(e){return this.scopes.get(e)?.session.estimatedBytes()??0}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:fh({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new hh(e,n,()=>{if(!n.live)return;let r=n.retention.referenceCount-1,{[t]:i=0,...a}=n.retention.retainedBy,o=i>1?{...a,[t]:i-1}:a;n.retention=r===0?ph:Object.freeze({referenceCount:r,retainedBy:fh(o)}),r===0?this.retireScope(e,n):this.publishRetention(e)});return this.list.getSnapshot().byId[e]===void 0&&this.manager.subagentAddress(e)!==void 0&&this.projectList(),this.publishRetention(e),i}retentionSnapshot(e){return this.scopes.get(e)?.retention??ph}publishRetention(e){let t=this.list.getSnapshot(),n=t.byId[e],r=this.retentionSnapshot(e).retainedBy;n!==void 0&&n.retainedBy!==r&&this.list.set({...t,byId:{...t.byId,[e]:{...n,retainedBy:r}}});let i=this.retainObservers.get(e),o=this.retentionSnapshot(e);i!==void 0&&i.published!==o&&(i.published=o,(0,a.notifySubscribers)(i.listeners,`[session-controller] reference sources`))}retireScope(e,t,n=!0){if(!t.live)return;t.live=!1,this.scopes.get(e)===t&&this.scopes.delete(e),t.session.unbindScope();let r=this.manager.drop(e,t.session);this.projectList(),this.publishRetention(e),this.startScopeDrop(e,t,n,r)}materializeScope(e){let{fiber:t,ctx:n}=_e(this.rootCtx,e),r=this.manager.get(e);r.bindScope(n);let i={fiber:t,ctx:n,binding:{sessionId:e,session:r,eventSource:r.eventSource,ctx:n},session:r,retention:ph,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,state:c,error:l,errorPage:u,headRefreshRevision:d,summaryOnlyIds:f}=this.manager.getListSnapshot(),p=[],m={};for(let e of t){p.push(e.sessionId);let t=this.retentionSnapshot(e.sessionId).retainedBy,n=this.projectedItemCache.get(e.sessionId);if(n!==void 0&&n.entry===e&&n.retainedBy===t){m[e.sessionId]=n.summary;continue}let r={id:e.sessionId,displayTitle:uh(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:t,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};this.projectedItemCache.set(e.sessionId,{entry:e,retainedBy:t,summary:r}),m[e.sessionId]=r}if(this.projectedItemCache.size>t.length)for(let e of this.projectedItemCache.keys())m[e]===void 0&&this.projectedItemCache.delete(e);for(let e in r){let t=r[e]?.values.subagentCatalog;if(t!==void 0&&t.length!==0)for(let n of t){let t=n.id,r=m[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?m[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(m[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}}for(let[t,n]of this.scopes){if(m[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;m[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:p,byId:m,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,loading:c===`loading`,listError:l?.message??null,listErrorPage:u,headRefreshRevision:d??0,summaryOnlyIds:f??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let _h=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function vh(e){let t=e.remote,n=e.get(`connection`),r=new gh(e,t);e.remote.$on(`api-session/added`,e=>{r.handleSessionAdded(e)}),e.remote.$on(`api-session/removed`,e=>{r.handleSessionRemoved(e)}),e.remote.$on(`api-session/status`,(e,t)=>{r.handleSessionStatus(e,t)}),e.remote.$on(`api-session/activity`,(e,t)=>{r.handleSessionActivity(e,t)}),e.remote.$on(`api-session/error`,(e,t)=>{r.handleSessionError(e,t)});let i,a=()=>{if(n.generation.getSnapshot()===void 0)return;let e=i;i=void 0,e?.dispose(),r.handleConnected();let a=fe(t,{accept:e=>{i===a&&r.handleControlFrame(e)},failed:e=>{i===a&&console.error(`[session-controller] control stream failed:`,e)}});i=a,a.start()};e.effect(()=>n.generation.subscribe(a),`session-controller.client.generation`),a(),e.typert.contexts.registerClient(`agent`,{identity:e=>r.sessionOf(e)?.sessionId,resolve:e=>{let t=r.retainAgentScope(e);return c(t.binding.ctx,()=>{t.release()})}}),e.effect(()=>async()=>{await i?.dispose()},`session-controller.client.control`)}return n.MutableSessionEventSource=Lm,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=ch,n.SessionEventStream=pe,n.SessionForkError=lh,n.apply=vh,n.createScope=_e,n.createSessionControlStream=fe,n.inject=_h,n.scopeOf=ve,t.exports}});
129
+ n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function Qh(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function $h(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;(e.type===`image`||e.type===`file`)&&typeof e.attachment==`object`&&e.attachment!==null&&t.push(e.attachment)}return t}var eg=class{views=/* @__PURE__ */ new Map;maxEntries;maxBytes;estimateBytes;cachedBytes=0;constructor(e={}){this.maxEntries=Math.max(0,e.maxEntries??8),this.maxBytes=Math.max(0,e.maxBytes??25165824),this.estimateBytes=e.estimateBytes??kh}get size(){return this.views.size}get totalBytes(){return this.cachedBytes}take(e){let t=this.views.get(e);if(t!==void 0)return this.views.delete(e),this.cachedBytes-=t.bytes,t.view}remember(e,t){let n=this.views.get(e);n!==void 0&&(this.views.delete(e),this.cachedBytes-=n.bytes);let r=Math.max(0,this.estimateBytes(t));if(this.maxEntries===0||r>this.maxBytes)return[e];this.views.set(e,{view:t,bytes:r}),this.cachedBytes+=r;let i=[];for(;this.views.size>this.maxEntries||this.cachedBytes>this.maxBytes;){let t=this.views.entries().next().value;if(t[0]===e)break;this.views.delete(t[0]),this.cachedBytes-=t[1].bytes,i.push(t[0])}return i}delete(e){let t=this.views.get(e);t!==void 0&&(this.views.delete(e),this.cachedBytes-=t.bytes)}clear(){this.views.clear(),this.cachedBytes=0}};function tg(e){return e===-1?-1:p(e)}let ng=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]),rg=/* @__PURE__ */ new Set([...tm,`codexhostTurnTimes`,`codexhostUsage`,`contextPressure`,`contextBreakdown`,`inbox`,`queueState`,`turnOutline`,`sessionStats`,`compacting`,`goal`,`agentPreset`,`plan`,`todos`,`permissions`,`nativePermissions`,`modelSelection`,`draftSelectionExplicit`,`attachmentInput`,`imageLimits`,`sentMessageEdit`]);var ig=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new eg;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;workspaceOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;workspaceStartCursor;workspaceHistory=/* @__PURE__ */ new Map;activeWorkspacePage;activeListCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];projectionSnapshotCache=/* @__PURE__ */ new Map;projectionsBySessionCache={};notifier=new vh(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r)for(let t of this.recentViews.remember(e,r))this.projectionStores.get(t)?.discard(tm);return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.resetListQueries(),this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new Zh(e,this.remote,{...t===void 0?{}:{address:t,...n===void 0?{}:{parentAvailable:n}},onEngaged:e=>{!this.disposed&&this.retainedIds(this.summaries).has(e.sessionId)&&(this.engagedSessions.has(e.sessionId)||(this.engagedSessions.add(e.sessionId),this.recordMutation({kind:`engaged`,sessionId:e.sessionId})),this.sessions.get(e.sessionId)?.handleBlank(!1))},projections:this.projectionStore(e),cachedView:this.recentViews.take(e)})}effectiveBlank(e){return e.blank&&!this.engagedSessions.has(e.sessionId)}retainedIds(e){let t=new Set(e.map(e=>e.sessionId));for(let e of this.sessions.keys())t.add(e);for(let e of this.addresses.keys())t.add(e);return t}pruneEngagement(e,t){t.has(e)||this.engagedSessions.delete(e)}projectionStore(e){let t=this.projectionStores.get(e);if(t===void 0){t=new bh(rg);let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markFrameDirty()}),this.projectionStores.set(e,t)}return t}refreshProjections(e){let t=this.projectionInflight.get(e);if(t!==void 0)return t.promise;if(this.projectionLoads.get(e)?.state===`ready`)return Promise.resolve();let n=new AbortController,r=this.projectionStore(e),a=r.revision;this.projectionLoads.set(e,{state:`loading`,error:null}),this.notifier.markDirty();let o=(async()=>{try{let t=await this.remote.session.projections({sessionId:e},n.signal);if(n.signal.aborted)return;t.ok?(t.value===null?r.revision===a&&r.clear():r.seed({...t.value,asOfSeq:tg(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.resetListQueries(),this.refreshList())}resetListQueries(){this.nextCursor=void 0,this.workspaceStartCursor=void 0,this.workspaceHistory=/* @__PURE__ */ new Map,this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null}hasSummary(e){return this.summaries.some(t=>t.sessionId===e)}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){if(e===void 0)return this.nextCursor?this.refreshList(this.nextCursor):Promise.resolve();let t=this.workspaceHistory,n=t.get(e);if(n?.pending)return n.pending;let r=n?n.cursor:this.workspaceStartCursor;if(!r||this.disposed)return Promise.resolve();let i={cursor:r,state:`loading`};return t.set(e,i),this.notifier.markDirty(),i.pending=(async()=>{t===this.workspaceHistory&&await this.refreshList(r,e)})().finally(()=>{delete i.pending,t===this.workspaceHistory&&this.notifier.markDirty()}),i.pending}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null){if(t===this.activeWorkspacePage&&e===this.activeListCursor)return this.listInflight;let n=this.workspaceHistory;return this.listInflight.catch(()=>void 0).then(()=>{if(n===this.workspaceHistory)return this.refreshList(e,t)})}let n=this.includeArchived;this.activeWorkspacePage=t,this.activeListCursor=e;let r=t===void 0?void 0:this.workspaceHistory.get(t);r||(this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0);let a=e=>{r?r.state=`retry`:(this.listState=`error`,this.listError=e)},o=this.summaries,s=[];return this.listMutations=s,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==s)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),a=new Set(i.value.items.map(e=>e.sessionId)),c=r!==void 0||i.value.nextCursor!==void 0,l=i.value.nextCursor??null;if(r){let e=new Set(this.summaries.map(e=>e.sessionId)),t=i.value.items.filter(t=>!t.blank&&!e.has(t.sessionId));for(let e of t)this.workspaceOnlyIds.add(e.sessionId);r.cursor=l,r.state=l?t.length>0?`search`:`continue`:`done`}else{for(let e of a)this.workspaceOnlyIds.delete(e);(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=l),e===void 0&&this.workspaceStartCursor==null&&(this.workspaceStartCursor=l)}let u=[...i.value.items,...o.filter(e=>!a.has(e.sessionId)&&(c||!n&&t.has(e.sessionId)))],d=this.listPhase===`pending`?u:rh(o,u,e=>e.sessionId),f=/* @__PURE__ */ new Set;for(let e of s)e.kind===`remove`&&f.add(e.sessionId);for(let e of d)e.running&&!f.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let p=s.reduce(ag,d);this.summaries=p;let m=new Set(p.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(a.has(e)||!m.has(e))&&this.summaryOnlyIds.delete(e);for(let e of this.workspaceOnlyIds)m.has(e)||this.workspaceOnlyIds.delete(e);let ee=this.retainedIds(p);for(let e of this.engagedSessions)this.pruneEngagement(e,ee);r||(this.listState=`idle`,this.listPhase=`ready`),this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===s&&(this.headRefreshRevision+=1)}else a(i.error)}catch(e){if(this.listMutations!==s)return;if(r)r.state=`retry`;else if((0,i.isRemoteFailure)(e))a(e);else throw e}finally{this.listMutations===s&&(this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t={...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.matchProjectDefault?{matchProjectDefault:!0}:{},...e.roleSlug===void 0?{}:{roleSlug:e.roleSlug}},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=og(r.error);e!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:e,updatedAt:Date.now(),running:!1,blank:!0}})}return r}async fork(e){let t=this.sessions.get(e.sessionId);if(t&&t.getSnapshot().openState!==`open`)return{ok:!1,error:new o(`session/syncing`,`Wait for the Session history to finish synchronizing.`,{})};let n=this.summaries.find(t=>t.sessionId===e.sessionId),r=await this.remote.session.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:e.atSeq}}),i=r.ok?r.value.sessionId:og(r.error);return i!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:i,updatedAt:Date.now(),running:!1,blank:!0,parentSessionId:e.sessionId,...n?.cwd===void 0?{}:{cwd:n.cwd}}}),r}async rename(e,t){let n=await this.remote.session.rename({sessionId:e,title:t});return n.ok&&this.projectionStore(e).apply(`title`,n.value.title,p(n.value.seq))&&this.notifier.markDirty(),n}mergeSummary(e){let t=this.recordMutation({kind:`upsert`,summary:e},`frame`);return this.updateParentAvailability(),t}recordMutation(e,t=`microtask`){if(this.disposed)return!1;this.listMutations?.push(e);let n=ag(this.summaries,e);return n!==this.summaries&&(this.summaries=n,t===`frame`?this.notifier.markFrameDirty():this.notifier.markDirty(),!0)}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}projectionValues(e){return this.projectionStores.get(e)?.values()}handleControlFrame(e){e.type===`baseline`?this.replaceControlBaseline(e.value):this.projectionStore(e.sessionId).applyLive(e.key,e.value,p(e.seq))&&!rg.has(e.key)&&this.notifier.markFrameDirty()}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=tg(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,tm)}this.notifier.markFrameDirty()}handleSessionAdded(e,t=!0){let n=t&&this.summaryOnlyIds.delete(e.sessionId),r=t&&this.workspaceOnlyIds.delete(e.sessionId),i=this.mergeSummary(e);(n||r)&&!i&&this.notifier.markFrameDirty(),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let a=this.sessions.get(e.sessionId);a?.handleRestored(),a?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=tg(t.asOfSeq);for(let[r,i]of Object.entries(t.values))n.apply(r,i,e);return}case`cached`:n.applyCached(t.values);return;default:ch(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){let t=this.summaryOnlyIds.delete(e),n=this.workspaceOnlyIds.delete(e),r=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`),i=this.recordMutation(r?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e},`frame`),a=!1;if(r){let t=this.sessions.get(e);a=t?.getSnapshot().running===!0,t?.handleRunning(!1)}else this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved();let o=this.projectionStores.get(e)?.values().subagentCatalog,s=!r&&(o===void 0||o.length===0)&&this.projectionStores.delete(e);this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e);let c=this.projectionLoads.delete(e);!i&&(t||n||s||c||a)&&this.notifier.markFrameDirty();for(let[t,n]of this.addresses)n.parentSessionId===e&&this.sessions.get(t)?.handleSubagentParentAvailable(!1)}handleSessionStatus(e,t){!this.disposed&&t&&this.engagedSessions.add(e);let n=this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0},`frame`);this.updateParentAvailability();let r=this.sessions.get(e),i=r?.getSnapshot().running;r?.handleRunning(t),!n&&r!==void 0&&i!==t&&this.notifier.markFrameDirty()}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t},`frame`)}handleSessionError(e,t){this.sessions.get(e)?.handleAgentError(t)}handleConnected(){for(let e of this.sessions.values())e.getSnapshot().openState===`error`&&e.resync();for(let e of this.projectionStores.values())e.clear(ng);this.resetListQueries(),this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=_h(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e);let n=this.projectionSnapshotCache.size!==this.projectionStores.size;for(let[e,t]of this.projectionStores){let r=t.values(),i=this.projectionLoads.get(e),a=i?.state??`idle`,o=i?.error??null,s=this.projectionSnapshotCache.get(e);(s===void 0||s.values!==r||s.state!==a||s.error!==o)&&(this.projectionSnapshotCache.set(e,{values:r,state:a,error:o}),n=!0)}if(n){for(let e of this.projectionSnapshotCache.keys())this.projectionStores.has(e)||this.projectionSnapshotCache.delete(e);this.projectionsBySessionCache=Object.fromEntries(this.projectionSnapshotCache)}return{items:this.itemsCache,hasMore:!!this.nextCursor,canSearchWorkspaceHistory:!!this.workspaceStartCursor,workspaceHistory:Object.fromEntries([...this.workspaceHistory].map(([e,t])=>[e,t.pending?`loading`:t.state])),workspaceOnlyIds:[...this.workspaceOnlyIds],headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,projectionsBySession:this.projectionsBySessionCache}}};function ag(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.findIndex(e=>e.sessionId===t.summary.sessionId);if(n===-1)return[t.summary,...e];let r=e[n],i={...r,blank:r.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...r.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...r.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...r.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};if(i.cwd===r.cwd&&i.parentSessionId===r.parentSessionId&&i.origin===r.origin&&i.blank===r.blank&&i.agentAvailable===r.agentAvailable&&i.running===r.running)return e;let a=[...e];return a[n]=i,a}case`remove`:return e.findIndex(e=>e.sessionId===t.sessionId)===-1?e:e.filter(e=>e.sessionId!==t.sessionId);case`status`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(r.running===t.running&&r.agentAvailable===t.agentAvailable&&(!t.running||!r.blank))return e;let i=[...e];return i[n]={...r,running:t.running,agentAvailable:t.agentAvailable,blank:r.blank&&!t.running},i}case`activity`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!(t.updatedAt>r.updatedAt))return e;let i=[...e];return i[n]={...r,updatedAt:t.updatedAt},i}case`engaged`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!r.blank)return e;let i=[...e];return i[n]={...r,blank:!1},i}}}function og(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var sg=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},cg=class extends Error{rpcError;sourceSessionId;name=`SessionForkError`;constructor(e,t){super(`session fork failed: ${e.code}: ${e.message}`),this.rpcError=e,this.sourceSessionId=t}};function lg(e,t,n){if(e!==void 0)return e;if(t!==void 0&&t!==``){let e=me(t);if(e!==``)return e}return n}function ug(e){let t=/^(.*?)\((\d+)\)$/u.exec(e);if(t?.[1]!==void 0&&t[2]!==void 0)return`${t[1]}(${BigInt(t[2])+1n})`;let n=/^(.*?)((\d+))$/u.exec(e);return n?.[1]!==void 0&&n[2]!==void 0?`${n[1]}(${BigInt(n[2])+1n})`:`${e} (1)`}function dg(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let fg=Object.freeze({referenceCount:0,retainedBy:dg({})});async function pg(e,t){if(t===void 0)return e;let n=Promise.withResolvers(),r=()=>{n.reject(t.reason)};t.addEventListener(`abort`,r,{once:!0});try{t.aborted&&r(),await Promise.race([e,n.promise])}finally{t.removeEventListener(`abort`,r)}}var mg=class{sessionId;record;releaseReference;released=new AbortController;readiness=Promise.withResolvers();ready=this.readiness.promise;constructor(e,t,n){this.sessionId=e,this.record=t,this.releaseReference=n,this.ready.catch(()=>{})}get binding(){if(this.record===void 0||!this.record.live)throw Error(`Session reference "${this.sessionId}" is released`);return this.record.binding}attachOpening(e,t){let n=t===void 0?this.released.signal:AbortSignal.any([this.released.signal,t]);pg(e,n).then(()=>{try{n.throwIfAborted(),this.readiness.resolve(this.binding)}catch(e){this.readiness.reject(e)}},e=>{this.readiness.reject(e)})}release(){let e=/* @__PURE__ */ Error(`Session reference "${this.sessionId}" is released`),t=this.releaseReference;this.released.abort(e),this.readiness.reject(e),this.record=void 0,this.releaseReference=void 0,t?.()}[Symbol.dispose](){this.release()}},hg=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;projectedItemCache=/* @__PURE__ */ new Map;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new ig(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}handoffSubmissions(e,t){let n=this.scopes.get(e)?.session;if(n===void 0||e===t||n.getSnapshot().pendingSubmissions.length===0&&!n.hasInFlightPrompts)return;let r=this.retain(t,{source:`controllerOperation`}),i=this.retain(e,{source:`controllerOperation`}),a=this.manager.get(t),o=new Set(n.handoffSubmissions(a)),s=[],c=!1,l=()=>{if(!c){c=!0;for(let e of s)e();r.release(),i.release()}},u=()=>{!n.hasInFlightPrompts&&!a.getSnapshot().pendingSubmissions.some(e=>o.has(e.requestId))&&l()};s.push(a.subscribe(u),n.subscribe(u)),r.ready.catch(l),i.ready.catch(l),u()}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}async loadSummary(e){await this.manager.loadSummary(e),this.closed||this.projectList()}syncSummary(e){return this.list.getSnapshot().byId[e]===void 0?this.closed||!this.manager.hasSummary(e)?!1:(this.projectList(),this.list.getSnapshot().byId[e]!==void 0):!0}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new sg(t.error,e.sessionId);return this.projectList(),t.value.sessionId}async fork(e){let 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:p(e.atSeq)}});if(!n.ok)throw new cg(n.error,e.sessionId);this.projectList();let r=n.value.sessionId;if(e.onCreated?.(r),t!==void 0){let e=await this.manager.rename(r,ug(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}estimatedBytes(e){return this.scopes.get(e)?.session.estimatedBytes()??0}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:dg({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new mg(e,n,()=>{if(!n.live)return;let r=n.retention.referenceCount-1,{[t]:i=0,...a}=n.retention.retainedBy,o=i>1?{...a,[t]:i-1}:a;n.retention=r===0?fg:Object.freeze({referenceCount:r,retainedBy:dg(o)}),r===0?this.retireScope(e,n):this.publishRetention(e)});return this.list.getSnapshot().byId[e]===void 0&&this.manager.subagentAddress(e)!==void 0&&this.projectList(),this.publishRetention(e),i}retentionSnapshot(e){return this.scopes.get(e)?.retention??fg}publishRetention(e){let t=this.list.getSnapshot(),n=t.byId[e],r=this.retentionSnapshot(e).retainedBy;n!==void 0&&n.retainedBy!==r&&this.list.set({...t,byId:{...t.byId,[e]:{...n,retainedBy:r}}});let i=this.retainObservers.get(e),o=this.retentionSnapshot(e);i!==void 0&&i.published!==o&&(i.published=o,(0,a.notifySubscribers)(i.listeners,`[session-controller] reference sources`))}retireScope(e,t,n=!0){if(!t.live)return;t.live=!1,this.scopes.get(e)===t&&this.scopes.delete(e),t.session.unbindScope();let r=this.manager.drop(e,t.session);this.projectList(),this.publishRetention(e),this.startScopeDrop(e,t,n,r)}materializeScope(e){let{fiber:t,ctx:n}=_e(this.rootCtx,e),r=this.manager.get(e);r.bindScope(n);let i={fiber:t,ctx:n,binding:{sessionId:e,session:r,eventSource:r.eventSource,ctx:n},session:r,retention:fg,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,state:c,error:l,errorPage:u,headRefreshRevision:d,summaryOnlyIds:f}=this.manager.getListSnapshot(),p=[],m={};for(let e of t){p.push(e.sessionId);let t=this.retentionSnapshot(e.sessionId).retainedBy,n=this.projectedItemCache.get(e.sessionId);if(n!==void 0&&n.entry===e&&n.retainedBy===t){m[e.sessionId]=n.summary;continue}let r={id:e.sessionId,displayTitle:lg(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:t,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};this.projectedItemCache.set(e.sessionId,{entry:e,retainedBy:t,summary:r}),m[e.sessionId]=r}if(this.projectedItemCache.size>t.length)for(let e of this.projectedItemCache.keys())m[e]===void 0&&this.projectedItemCache.delete(e);for(let e in r){let t=r[e]?.values.subagentCatalog;if(t!==void 0&&t.length!==0)for(let n of t){let t=n.id,r=m[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?m[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(m[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}}for(let[t,n]of this.scopes){if(m[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;m[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:p,byId:m,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,loading:c===`loading`,listError:l?.message??null,listErrorPage:u,headRefreshRevision:d??0,summaryOnlyIds:f??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let gg=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function _g(e){let t=e.remote,n=e.get(`connection`),r=new hg(e,t);e.remote.$on(`api-session/added`,e=>{r.handleSessionAdded(e)}),e.remote.$on(`api-session/removed`,e=>{r.handleSessionRemoved(e)}),e.remote.$on(`api-session/status`,(e,t)=>{r.handleSessionStatus(e,t)}),e.remote.$on(`api-session/activity`,(e,t)=>{r.handleSessionActivity(e,t)}),e.remote.$on(`api-session/error`,(e,t)=>{r.handleSessionError(e,t)});let i,a=()=>{if(n.generation.getSnapshot()===void 0)return;let e=i;i=void 0,e?.dispose(),r.handleConnected();let a=fe(t,{accept:e=>{i===a&&r.handleControlFrame(e)},failed:e=>{i===a&&console.error(`[session-controller] control stream failed:`,e)}});i=a,a.start()};e.effect(()=>n.generation.subscribe(a),`session-controller.client.generation`),a(),e.typert.contexts.registerClient(`agent`,{identity:e=>r.sessionOf(e)?.sessionId,resolve:e=>{let t=r.retainAgentScope(e);return c(t.binding.ctx,()=>{t.release()})}}),e.effect(()=>async()=>{await i?.dispose()},`session-controller.client.control`)}return n.MutableSessionEventSource=Ih,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=sg,n.SessionEventStream=pe,n.SessionForkError=cg,n.apply=_g,n.createScope=_e,n.createSessionControlStream=fe,n.inject=gg,n.scopeOf=ve,t.exports}});