@cortex-agent/server 2026.11.17 → 2026.12.5

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 (338) hide show
  1. package/README.md +5 -5
  2. package/THIRD_PARTY_NOTICES.txt +860 -294
  3. package/defaults/hooks/quota-stop.mjs +37 -0
  4. package/defaults/prompts/clean-workspace.md +5 -0
  5. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  6. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  7. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  8. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  9. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  10. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  11. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  12. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  13. package/dist/chunks/{chunk-VTL3Z2OP.js → chunk-2ABET62E.js} +1 -1
  14. package/dist/chunks/chunk-2BVUA256.js +4 -0
  15. package/dist/chunks/{chunk-4YLAGSDM.js → chunk-2WFL62UO.js} +1 -1
  16. package/dist/chunks/{chunk-LQTFDC67.js → chunk-335SSANX.js} +1 -1
  17. package/dist/chunks/chunk-377OPTXX.js +17 -0
  18. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  19. package/dist/chunks/{chunk-V6X7Y62J.js → chunk-3O6ZG5HA.js} +1 -1
  20. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  21. package/dist/chunks/{chunk-2ATTYCRJ.js → chunk-4HRI75GU.js} +1 -1
  22. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  23. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  24. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  25. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  26. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  27. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  28. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  29. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  30. package/dist/chunks/{chunk-S3MR37DL.js → chunk-5FHETFZM.js} +1 -1
  31. package/dist/chunks/{chunk-CEGSDGYQ.js → chunk-5LBLRAHS.js} +1 -1
  32. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  33. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  34. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  35. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  36. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  37. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  38. package/dist/chunks/chunk-B3NB243Z.js +4 -0
  39. package/dist/chunks/{chunk-XPPZ6Y3X.js → chunk-BKYP6AGM.js} +1 -1
  40. package/dist/chunks/{chunk-QUXPMNFQ.js → chunk-BVEDNESB.js} +1 -1
  41. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  42. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  43. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  44. package/dist/chunks/{chunk-5PAW3DEU.js → chunk-CI2RHH74.js} +4 -4
  45. package/dist/chunks/{chunk-OFEPDNRB.js → chunk-CMSOOLJB.js} +1 -1
  46. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  47. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  48. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  49. package/dist/chunks/{chunk-ROVKOIHF.js → chunk-DK4UCK7L.js} +1 -1
  50. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  51. package/dist/chunks/{chunk-WBSE3EF3.js → chunk-FDC2GRBK.js} +1 -1
  52. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  53. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  54. package/dist/chunks/chunk-G264APQN.js +5 -0
  55. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  56. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  57. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  58. package/dist/chunks/{chunk-2VVRTJQN.js → chunk-HVN37UXD.js} +1 -1
  59. package/dist/chunks/{chunk-53TQNK7Z.js → chunk-IGZWZP7Z.js} +1 -1
  60. package/dist/chunks/{chunk-AFTBQRPN.js → chunk-IJ7XFQMI.js} +1 -1
  61. package/dist/chunks/{chunk-U23S37TT.js → chunk-IMMGYDAB.js} +1 -1
  62. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  63. package/dist/chunks/{chunk-MGYYSX7Y.js → chunk-ITGCWQFK.js} +1 -1
  64. package/dist/chunks/{chunk-QEL6CMLE.js → chunk-IVZ7QUEG.js} +1 -1
  65. package/dist/chunks/{chunk-EE3WT25T.js → chunk-IWY2HIFK.js} +1 -1
  66. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  67. package/dist/chunks/{chunk-NXZS5PEW.js → chunk-JGUEIW2W.js} +1 -1
  68. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  69. package/dist/chunks/{chunk-VIMHSW6J.js → chunk-KJUQCCB5.js} +1 -1
  70. package/dist/chunks/{chunk-BUZQBTV2.js → chunk-KST6OY76.js} +1 -1
  71. package/dist/chunks/{chunk-KDPY2YA3.js → chunk-KZSAFVSY.js} +2 -2
  72. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  73. package/dist/chunks/{chunk-RYLSRII6.js → chunk-LE6QPXN6.js} +1 -1
  74. package/dist/chunks/{chunk-TX46YMGI.js → chunk-LIIZI3HY.js} +1 -1
  75. package/dist/chunks/{chunk-3CZPBLB3.js → chunk-MJQ2D2OP.js} +1 -1
  76. package/dist/chunks/{chunk-P7TVR4GY.js → chunk-NHHR4DCF.js} +1 -1
  77. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  78. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  79. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  80. package/dist/chunks/{chunk-T73GHMFB.js → chunk-OJ37ZWBG.js} +1 -1
  81. package/dist/chunks/{chunk-7GEBDPTT.js → chunk-OZXMPBUX.js} +1 -1
  82. package/dist/chunks/chunk-PG7452XE.js +4 -0
  83. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  84. package/dist/chunks/{chunk-RA2BUYI3.js → chunk-PTS3J4DQ.js} +1 -1
  85. package/dist/chunks/{chunk-2ROGTDM2.js → chunk-PVVEEBUU.js} +1 -1
  86. package/dist/chunks/{chunk-W6AKCEYF.js → chunk-Q7BZLPBU.js} +1 -1
  87. package/dist/chunks/{chunk-SY2HV3V5.js → chunk-QC66ZXPP.js} +1 -1
  88. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  89. package/dist/chunks/{chunk-NRD57ICT.js → chunk-R2CCD4OF.js} +1 -1
  90. package/dist/chunks/{chunk-R52AVUQB.js → chunk-RG5GP4RB.js} +1 -1
  91. package/dist/chunks/{chunk-IKLTEWA3.js → chunk-RW2F2QNP.js} +1 -1
  92. package/dist/chunks/{chunk-XEBEWR6Y.js → chunk-RWPO3NZ3.js} +1 -1
  93. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  94. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  95. package/dist/chunks/{chunk-NNBSSISP.js → chunk-SKHFU5DI.js} +1 -1
  96. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  97. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  98. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  99. package/dist/chunks/{chunk-KUDK7GPS.js → chunk-UEEW2R4E.js} +1 -1
  100. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  101. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  102. package/dist/chunks/{chunk-BDLKI2NT.js → chunk-VHX2GHBF.js} +1 -1
  103. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  104. package/dist/chunks/{chunk-FP7ML72L.js → chunk-WU7RNAZD.js} +1 -1
  105. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  106. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  107. package/dist/chunks/{chunk-H4QZ2P3Z.js → chunk-X5ND4H4P.js} +1 -1
  108. package/dist/chunks/{chunk-5A6CA5TM.js → chunk-Y3AOGNDT.js} +1 -1
  109. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  110. package/dist/chunks/{chunk-LP7T32PW.js → chunk-YAEHSSR4.js} +1 -1
  111. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  112. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  113. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  114. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  115. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  116. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  117. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  118. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  119. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  120. package/dist/chunks/context-CI2FKEQE.js +4 -0
  121. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  122. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  123. package/dist/chunks/{easter-egg-3d-CZH7AYZ7.js → easter-egg-3d-XR5S2O3T.js} +1 -1
  124. package/dist/chunks/execution-repo-5TLV2NM4.js +4 -0
  125. package/dist/chunks/{executions-BN6OLLVM.js → executions-I3UUIGSL.js} +1 -1
  126. package/dist/chunks/file-Y5G56IUT.js +4 -0
  127. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  128. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  129. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  130. package/dist/chunks/init-A6GY656J.js +4 -0
  131. package/dist/chunks/{install-cli-ABBD7DO5.js → install-cli-FALWKQYO.js} +1 -1
  132. package/dist/chunks/{interaction-ask-EE2UPR3Q.js → interaction-ask-O5HGF6CH.js} +1 -1
  133. package/dist/chunks/{interaction-plan-C446T2GZ.js → interaction-plan-JTVDN3BC.js} +1 -1
  134. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  135. package/dist/chunks/{llama-cpp-classify-IA2F2H7A.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  136. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  137. package/dist/chunks/memory-cli-DIT4DQF3.js +11 -0
  138. package/dist/chunks/meta-JQH66YU7.js +4 -0
  139. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  140. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  141. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  142. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  143. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  144. package/dist/chunks/{openai-decisions-P5UX7BWY.js → openai-decisions-JU6QQKEM.js} +1 -1
  145. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  146. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  147. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  148. package/dist/chunks/radius-THYKWV4E.js +4 -0
  149. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  150. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  151. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  152. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  153. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  154. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  155. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  156. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  157. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  158. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  159. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  160. package/dist/chunks/{ui-file-6PLXHSTB.js → ui-file-SRD4ILBS.js} +1 -1
  161. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  162. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  163. package/dist/chunks/{waitpoint-W5M3BE55.js → waitpoint-M6JZBSLT.js} +1 -1
  164. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  165. package/dist/client-bundle/client.mjs +229 -62
  166. package/dist/client-bundle/manifest.json +2 -2
  167. package/dist/core/pi-sdk.js +1 -1
  168. package/dist/domain/auth/cc-auth-cli.js +1 -1
  169. package/dist/domain/mcp/bundled-server.js +1 -1
  170. package/dist/domain/mcp/feishu/client.js +1 -1
  171. package/dist/entry/app.js +138 -556
  172. package/dist/entry/browser-cli.js +1 -1
  173. package/dist/entry/cli.js +1 -1
  174. package/dist/entry/cortex-cli.js +1 -1
  175. package/dist/entry/daemon.js +3 -3
  176. package/dist/entry/hook-cli.js +1 -1
  177. package/dist/entry/production-app-bootstrap.js +1 -1
  178. package/dist/entry/production-evidence-export-cli.js +1 -1
  179. package/dist/entry/signal-cli.js +1 -1
  180. package/dist/tui/index.js +1 -1
  181. package/package.json +1 -1
  182. package/vendor/pi/CHANGELOG.md +330 -0
  183. package/vendor/pi/dist/codemode-worker.js +2 -0
  184. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  185. package/vendor/pi/dist/core/export-html/template.css +9 -0
  186. package/vendor/pi/dist/core/export-html/template.js +166 -46
  187. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  188. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  189. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  190. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  191. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  192. package/vendor/pi/dist/utils/image-resize.js +1 -1
  193. package/vendor/pi/docs/cli.md +35 -12
  194. package/vendor/pi/docs/custom-provider.md +2 -0
  195. package/vendor/pi/docs/environment-variables.md +2 -0
  196. package/vendor/pi/docs/extensions.md +3192 -225
  197. package/vendor/pi/docs/keybindings.md +2 -2
  198. package/vendor/pi/docs/llama-cpp.md +27 -19
  199. package/vendor/pi/docs/mcp.md +6 -4
  200. package/vendor/pi/docs/message-types.md +1 -1
  201. package/vendor/pi/docs/models-configuration.md +9 -3
  202. package/vendor/pi/docs/models.md +2 -1
  203. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  204. package/vendor/pi/docs/packages.md +24 -0
  205. package/vendor/pi/docs/prompt-templates.md +1 -1
  206. package/vendor/pi/docs/providers.md +4 -2
  207. package/vendor/pi/docs/quickstart.md +7 -3
  208. package/vendor/pi/docs/rpc-commands.md +1 -1
  209. package/vendor/pi/docs/rpc.md +4 -2
  210. package/vendor/pi/docs/sessions.md +17 -3
  211. package/vendor/pi/docs/settings.md +6 -5
  212. package/vendor/pi/docs/slash-commands.md +3 -2
  213. package/vendor/pi/docs/terminal-setup.md +3 -1
  214. package/vendor/pi/docs/tmux.md +6 -0
  215. package/vendor/pi/docs/tui.md +4 -0
  216. package/vendor/pi/docs/windows.md +27 -0
  217. package/vendor/pi/examples/extensions/README.md +2 -1
  218. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  219. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  220. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  221. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  222. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  223. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  224. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  225. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  226. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  227. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  228. package/vendor/pi/examples/extensions/preset.ts +2 -0
  229. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  230. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  231. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  232. package/vendor/pi/examples/extensions/todo.ts +7 -0
  233. package/vendor/pi/examples/extensions/tools.ts +2 -0
  234. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  236. package/vendor/pi/examples/tsconfig.json +208 -0
  237. package/vendor/pi/package.json +15 -16
  238. package/vendor/pi/schemas/models.schema.json +66 -37
  239. package/vendor/pi/schemas/settings.schema.json +18 -1
  240. package/vendor/pi-ai/bedrock.js +1 -1
  241. package/vendor/pi-ai/oauth-load.js +1 -1
  242. package/web/dist/assets/{board-math-css-BgIyUG-C.js → board-math-css-DKX6FcUS.js} +1 -1
  243. package/web/dist/assets/index-D11wi0uG.js +540 -0
  244. package/web/dist/assets/index-JedYumhY.css +1 -0
  245. package/web/dist/assets/{index-C2eMpcuI.js → index-jl30Gy8P.js} +1 -1
  246. package/web/dist/index.html +2 -2
  247. package/dist/chunks/anthropic-messages-M732OMEE.js +0 -8
  248. package/dist/chunks/azure-openai-responses-RAKTV6JY.js +0 -4
  249. package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +0 -62
  250. package/dist/chunks/child-runner-MO5RT6FH.js +0 -4
  251. package/dist/chunks/chunk-3CPIMAYX.js +0 -30
  252. package/dist/chunks/chunk-3ORG56I5.js +0 -8
  253. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  254. package/dist/chunks/chunk-5DF5WJNM.js +0 -60
  255. package/dist/chunks/chunk-7GAYFN52.js +0 -18
  256. package/dist/chunks/chunk-AVXDF7AG.js +0 -4
  257. package/dist/chunks/chunk-BJGYGEZO.js +0 -6
  258. package/dist/chunks/chunk-BZDIAI5M.js +0 -125
  259. package/dist/chunks/chunk-CK3P345X.js +0 -133
  260. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  261. package/dist/chunks/chunk-ETIBCA2S.js +0 -4
  262. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  263. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  264. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  265. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  266. package/dist/chunks/chunk-IYVZHGUQ.js +0 -5
  267. package/dist/chunks/chunk-JJDEQ6N2.js +0 -4
  268. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  269. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  270. package/dist/chunks/chunk-LACGULCN.js +0 -10
  271. package/dist/chunks/chunk-LAWOWPZX.js +0 -363
  272. package/dist/chunks/chunk-NNTQUHLO.js +0 -877
  273. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  274. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  275. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  276. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  277. package/dist/chunks/chunk-QMSSIDRQ.js +0 -70
  278. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  279. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  280. package/dist/chunks/chunk-RDW6FRF5.js +0 -4
  281. package/dist/chunks/chunk-RF4JLYBX.js +0 -6
  282. package/dist/chunks/chunk-SFX7V5O2.js +0 -10
  283. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  284. package/dist/chunks/chunk-STCNHXPJ.js +0 -6
  285. package/dist/chunks/chunk-UT6DGZDO.js +0 -4
  286. package/dist/chunks/chunk-VBN2JSER.js +0 -5
  287. package/dist/chunks/chunk-VK5J556O.js +0 -4
  288. package/dist/chunks/chunk-VPVSKJGX.js +0 -6
  289. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  290. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  291. package/dist/chunks/chunk-XYSXL3KX.js +0 -4
  292. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  293. package/dist/chunks/chunk-YAAKL3QS.js +0 -80
  294. package/dist/chunks/chunk-YB5LUJHS.js +0 -65
  295. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  296. package/dist/chunks/chunk-Z24SBRJK.js +0 -4
  297. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  298. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  299. package/dist/chunks/context-GQKWKFRM.js +0 -4
  300. package/dist/chunks/cost-OOO32GLC.js +0 -5
  301. package/dist/chunks/dist-V5FRMUFH.js +0 -4
  302. package/dist/chunks/execution-repo-XXL4FXC6.js +0 -4
  303. package/dist/chunks/file-H572PL2Z.js +0 -4
  304. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  305. package/dist/chunks/google-generative-ai-2G4ITOZL.js +0 -4
  306. package/dist/chunks/google-vertex-PACHCMRZ.js +0 -4
  307. package/dist/chunks/init-75F4V7SK.js +0 -4
  308. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  309. package/dist/chunks/local-client-stop-5YOLXGYT.js +0 -4
  310. package/dist/chunks/memory-cli-5SSF6YJM.js +0 -11
  311. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  312. package/dist/chunks/mistral-conversations-VHP63CDS.js +0 -7
  313. package/dist/chunks/model-resolver-FVJNZ6NA.js +0 -4
  314. package/dist/chunks/openai-codex-responses-EHJ4AZBE.js +0 -12
  315. package/dist/chunks/openai-completions-CRAGQFCE.js +0 -9
  316. package/dist/chunks/openai-responses-IZ22NVQ7.js +0 -6
  317. package/dist/chunks/openrouter-images-W2JAMSRH.js +0 -4
  318. package/dist/chunks/pi-messages-MJEEQU2R.js +0 -10
  319. package/dist/chunks/radius-ZM7ZRMXF.js +0 -4
  320. package/dist/chunks/remote-ops-O5CR4RGA.js +0 -14
  321. package/dist/chunks/runner-S6R3US24.js +0 -4
  322. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  323. package/dist/chunks/schedule-cli-4T4YC5V5.js +0 -4
  324. package/dist/chunks/slack-2CGM4SMY.js +0 -4
  325. package/dist/chunks/start-ui-http-3D7QNHGB.js +0 -43
  326. package/dist/chunks/subagent-OZGUOV3J.js +0 -4
  327. package/dist/chunks/tool-shims-IA2WELXJ.js +0 -4
  328. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  329. package/dist/chunks/ui-board-H4INJD6C.js +0 -5
  330. package/dist/chunks/ui-decision-6HHNROIT.js +0 -4
  331. package/dist/chunks/ui-view-6MDU4GXY.js +0 -4
  332. package/dist/chunks/virtual-modules-OFI7QKYH.js +0 -4
  333. package/dist/chunks/workers-GTFP75MS.js +0 -4
  334. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  335. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  336. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  337. package/web/dist/assets/index-9lyu2S6W.css +0 -1
  338. package/web/dist/assets/index-C-hpzey7.js +0 -532
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{b as _}from"./chunk-WEZWKMYU.js";import{a as f}from"./chunk-ILEML5IP.js";import{a as p}from"./chunk-XBJOYU5Y.js";import{a as w}from"./chunk-XAXWLYH5.js";import"./chunk-IRWZ7UPF.js";import"./chunk-WHC7AYZD.js";var v="127.0.0.1",m=1456,E="/oauth/callback",d=`http://${v}:${m}${E}`,A=6e4,g="browser",y="device-code",a="pi-gateway",O="gateway offline_access",S="urn:ietf:params:oauth:grant-type:device_code";async function L(o,r){let e=await fetch(new URL("/v1/oauth",o),{headers:{accept:"application/json"},signal:r});if(!e.ok)throw new Error(`Could not load Radius OAuth config from ${o}: ${e.status} ${await e.text()}`);let t=await e.json();if(typeof t.authorizationEndpoint!="string")throw new Error(`Invalid Radius OAuth config from ${o}`);return{authorizationEndpoint:t.authorizationEndpoint}}var c=class extends Error{status;oauthError;constructor(r,e,t,n){let i=e?t?`${e}: ${t}`:e:t||String(r);super(`${n}: ${i}`),this.status=r,this.oauthError=e}};async function R(o,r){let e=await o.text().catch(()=>""),t,n;if(e)try{let i=JSON.parse(e);t=typeof i.error=="string"?i.error:void 0,n=typeof i.error_description=="string"?i.error_description:void 0}catch{n=e}return new c(o.status,t,n,r)}async function u(o,r,e){let t;try{t=await fetch(new URL("/v1/oauth/token",o),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:r,signal:e})}catch(i){throw e.aborted?new Error("Login cancelled"):i}if(!t.ok)throw await R(t,"Radius OAuth token request failed");let n=await t.json();return{type:"oauth",access:n.access_token,refresh:n.refresh_token,expires:Date.now()+n.expires_in*1e3-A,scope:n.scope}}async function C(o,r,e){let{verifier:t,challenge:n}=await w(),i=crypto.randomUUID(),l=new URL(r);l.search=new URLSearchParams({response_type:"code",client_id:a,redirect_uri:d,scope:O,code_challenge:n,code_challenge_method:"S256",handoff:"url",state:i}).toString();let h=await p({providerName:"Radius",host:v,port:m,path:E,state:i,complete:s=>u(o,new URLSearchParams({grant_type:"authorization_code",client_id:a,redirect_uri:d,code:s,code_verifier:t}),e.signal),signal:e.signal});e.notify({type:"progress",message:`Listening for OAuth callback on ${d}`}),e.notify({type:"auth_url",url:l.toString(),instructions:"Continue in your browser."});try{let s=await h.wait();if(!s)throw new Error("OAuth callback did not complete.");return s}finally{h.close()}}async function U(o,r){let e;try{e=await fetch(new URL("/v1/oauth/device",o),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:a,scope:O}),signal:r})}catch(n){throw r.aborted?new Error("Login cancelled"):n}if(!e.ok)throw await R(e,"Radius OAuth device authorization failed");let t=await e.json();if(!t.device_code||!t.user_code||!t.verification_uri||!t.expires_in)throw new Error("Radius OAuth device authorization response is missing required fields");return{device_code:t.device_code,user_code:t.user_code,verification_uri:t.verification_uri,expires_in:t.expires_in,interval:t.interval}}async function x(o,r){let e=await U(o,r.signal);return r.notify({type:"device_code",userCode:e.user_code,verificationUri:e.verification_uri,intervalSeconds:e.interval,expiresInSeconds:e.expires_in}),f({intervalSeconds:e.interval,expiresInSeconds:e.expires_in,signal:r.signal,poll:async()=>{try{return{status:"complete",value:await u(o,new URLSearchParams({grant_type:S,client_id:a,device_code:e.device_code}),r.signal)}}catch(t){if(!(t instanceof c))throw t;switch(t.oauthError){case"authorization_pending":return{status:"pending"};case"slow_down":return{status:"slow_down"};case"expired_token":return{status:"failed",message:"Device authorization expired."};case"access_denied":return{status:"failed",message:"Device authorization was denied."};default:throw t}}}})}function b(o){let r=_(o.gateway);return{name:o.name,async login(e){let t=await e.prompt({type:"select",message:`Sign in to ${o.name}:`,options:[{id:g,label:"Sign in with browser (recommended)"},{id:y,label:"Sign in with device code (when signing in from another device)"}]});if(t===y)return x(r,e);if(t===g){let n=await L(r,e.signal);return C(r,n.authorizationEndpoint,e)}throw new Error(`Unknown ${o.name} sign-in method: ${t}`)},async refresh(e,t){return await u(r,new URLSearchParams({grant_type:"refresh_token",client_id:a,refresh_token:e.refresh}),t)},async toAuth(e){return{apiKey:e.access}}}}export{b as createRadiusOAuth};
@@ -1,14 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as E}from"./chunk-S3MR37DL.js";import{a as R,b as L,c as N,d as P,e as K,f as G}from"./chunk-TJ4GQRT6.js";import{a as j,c as F}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as r}from"./chunk-W34AK4SK.js";import{d as A,i as I,t as O}from"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as B from"fs";import*as v from"path";import*as Z from"crypto";import{pathToFileURL as ee}from"url";var k=class{memoryCache=new Map;cacheDir;sessionId;constructor(e={}){this.cacheDir=e.cacheDir??R(A),this.sessionId=e.sessionId??process.env.CORTEX_SESSION_ID,N(this.cacheDir)}buildBlocks(e,l,f){if(!l||l.length===0)return[];let h=c=>L(c.deviceId?.trim()||e,c.path);return P(this.cacheDir,this.sessionId,c=>{let n=!1,o=[];for(let t of l)c.get(h(t))!==t.mtimeMs&&(f?.has(t.path)?(c.set(h(t),t.mtimeMs),n=!0):o.push(t));let{included:u,blocks:m,truncated:a}=K(o,t=>this.formatBlock(e,t));for(let t of u)c.set(h(t),t.mtimeMs),n=!0;return{value:(a.length>0?[...m,G(a.map(t=>`${e}:${t.path}`))]:m).map(t=>({type:"text",text:t})),changed:n}},this.memoryCache)}formatBlock(e,l){return`<system-reminder>
5
- Auto-loaded AGENTS.md from ${e}:${l.path} (ancestor of accessed path on remote device). These instructions apply to files under this directory on that device.
6
-
7
- `+l.content+`
8
- </system-reminder>`}},T=null;function q(){return T||(T=new k),T}function S(s,e,l){if(!e||e.length===0)return[];let f;if(l){let h=e.filter(c=>Q(c.path,l));h.length>0&&(f=new Set(h.map(c=>c.path)))}return q().buildBlocks(s,e,f)}function Q(s,e){return s===e?!0:s.replace(/\\/g,"/")===e.replace(/\\/g,"/")}import{readFileSync as V}from"fs";import*as z from"path";var Y=z.join(I,"machines.json");function H(s=Y){try{let e=JSON.parse(V(s,"utf-8"));return Object.entries(e).map(([l,f])=>({name:l,windows:f?.win===!0}))}catch{return[]}}function W(s){return s.length===0?"":` Known devices: ${s.map(l=>l.windows?`${l.name} (Windows)`:l.name).join(", ")}. May be offline; failed calls list currently online devices.`}function U(s,e){return Array.isArray(e)?`${s}. Online devices: ${e.length>0?e.join(", "):"none"}`:s}async function $(s,e,l,f,h){let{body:c}=await j("POST",`${s.webhookBaseUrl}/webhook/remote-command`,{device:e,action:l,params:f,timeout:h},F(s));if(!c.success)throw new Error(U(c.error||"Command failed",c.onlineDevices));return c.data}var J=v.join(O,"tool-results"),te={remote_bash:3e4,remote_grep:2e4,remote_glob:1e5};function C(s,e){let l=te[s];if(e.length<=l)return e;B.mkdirSync(J,{recursive:!0});let f=`${s}-${Date.now()}-${Z.randomBytes(4).toString("hex")}`,h=v.join(J,`${f}.txt`);B.writeFileSync(h,e,"utf8");let c=(e.length/1024).toFixed(2),n=e.slice(0,2e3);return["<persisted-output>",`Output too large (${c} KB). Full output saved to local file:`,` ${h}`,"","Preview (first 2 KB):",n,"...","</persisted-output>"].join(`
9
- `)}var w=null;try{w=(await import("sharp")).default}catch{}var M=25e3,X=1568;function D(s){return Math.ceil(s*.125)}async function re(s,e,l,f){if(!w)return{data:s,mimeType:e,width:l||0,height:f||0};let h=Buffer.from(s,"base64"),c=await w(h).metadata(),n=c.width||l||0,o=c.height||f||0,u=e,m=Math.max(n,o),a=h;if(m>X){let g=X/m;n=Math.round(n*g),o=Math.round(o*g),a=await w(h).resize(n,o,{fit:"inside",withoutEnlargement:!0}).toBuffer()}let i;u==="image/png"?i=await w(a).png({compressionLevel:6}).toBuffer():u==="image/webp"?i=await w(a).webp({quality:85}).toBuffer():(i=await w(a).jpeg({quality:85}).toBuffer(),u="image/jpeg");let t=i.toString("base64"),d=D(t.length);if(d>M){(u==="image/png"||u==="image/webp")&&(i=await w(i).jpeg({quality:80}).toBuffer(),u="image/jpeg",t=i.toString("base64"),d=D(t.length));let g=[70,55,40,30];for(let p of g){if(d<=M)break;i=await w(a).resize(n,o,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:p}).toBuffer(),u="image/jpeg",t=i.toString("base64"),d=D(t.length)}let b=[.75,.5,.35];for(let p of b){if(d<=M)break;let x=Math.round(n*p),_=Math.round(o*p);i=await w(h).resize(x,_,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:30}).toBuffer(),t=i.toString("base64"),d=D(t.length)}}let y=await w(i).metadata();return{data:t,mimeType:u,width:y.width||n,height:y.height||o}}function we(s,e){let f=["remote_bash","remote_read","remote_write","remote_edit","remote_glob","remote_grep"].find(n=>!e.toolAllowlist||e.toolAllowlist.has(n)),h=W(H()),c=(n,o)=>o+(n===f?h:"");s.tool("remote_bash",c("remote_bash","Run a remote shell command via cortex-client; Windows uses git-bash."),{device:r.string().describe("Target device name."),command:r.string().describe("Shell command to execute"),timeout:r.number().int().min(1).max(600).optional().describe("Timeout in seconds (default: 120, max: 600)"),description:r.string().optional().describe("Command summary for logging"),run_in_background:r.boolean().optional().describe("Run command in background, return PID immediately; timeout is ignored")},async({device:n,command:o,timeout:u,description:m,run_in_background:a})=>{try{let i=(u??120)*1e3,t=await $(e,n,"bash",{command:o,timeout:i,run_in_background:a||!1},i+5e3),d=[];t.stdout&&d.push(t.stdout),t.stderr&&d.push(`[stderr]
10
- ${t.stderr}`),t.exitCode!==0&&d.push(`[exit code: ${t.exitCode}]`);let y=d.join(`
11
- `)||"(no output)",g=C("remote_bash",y),b=t.exitCode!==void 0&&t.exitCode!==0;return{content:[{type:"text",text:g}],...b?{isError:!0}:{}}}catch(i){return{content:[{type:"text",text:`remote_bash error: ${i.message}`}],isError:!0}}}),s.tool("remote_read",c("remote_read","Read a remote absolute path: numbered text, inline images (PNG/JPEG/GIF/WebP/BMP), or PDF documents."),{device:r.string().describe("Target device name."),file_path:r.string().describe("Absolute path to the file to read"),offset:r.number().optional().describe("Line number to start reading from (0-based)"),limit:r.number().optional().describe("Number of lines to read")},{readOnlyHint:!0},async({device:n,file_path:o,offset:u,limit:m})=>{try{if(!E(o))return{content:[{type:"text",text:"file_path must be absolute"}],isError:!0};let a=await $(e,n,"read",{file_path:o,offset:u,limit:m}),i=S(n,a.cortexMDs,o);if(a.image){let{data:t,mimeType:d,width:y,height:g,originalSize:b}=a.image;try{let p=await re(t,d,y,g),x=D(p.data.length),_=[`Image: ${o}`,`Original: ${y||"?"}x${g||"?"} ${d} (${(b/1024).toFixed(1)} KB)`];return p.width!==y||p.height!==g||p.mimeType!==d?_.push(`Processed: ${p.width}x${p.height} ${p.mimeType} (~${x} tokens)`):_.push(`~${x} tokens`),{content:[{type:"text",text:_.join(`
12
- `)},{type:"image",data:p.data,mimeType:p.mimeType},...i]}}catch(p){return{content:[{type:"text",text:`Image detected (${d}, ${y||"?"}x${g||"?"}, ${(b/1024).toFixed(1)} KB) but processing failed: ${p.message}`},...i]}}}if(a.pdf){let{data:t,originalSize:d}=a.pdf;return{content:[{type:"text",text:`PDF: ${o} (${(d/1024).toFixed(1)} KB)`},{type:"resource",resource:{uri:ee(o).href,mimeType:"application/pdf",blob:t}},...i]}}return{content:[{type:"text",text:a.content||"(empty file)"},...i]}}catch(a){return{content:[{type:"text",text:`remote_read error: ${a.message}`}],isError:!0}}}),s.tool("remote_write",c("remote_write","Write/overwrite a remote file at an absolute path; creates parent directories."),{device:r.string().describe("Target device name."),file_path:r.string().describe("Absolute path to the file to write"),content:r.string().describe("Content to write to the file")},async({device:n,file_path:o,content:u})=>{try{if(!E(o))return{content:[{type:"text",text:"file_path must be absolute"}],isError:!0};let m=await $(e,n,"write",{file_path:o,content:u}),a=S(n,m?.cortexMDs,o);return{content:[{type:"text",text:`File written: ${o}`},...a]}}catch(m){return{content:[{type:"text",text:`remote_write error: ${m.message}`}],isError:!0}}}),s.tool("remote_edit",c("remote_edit","Replace text in a remote file at an absolute path. old_string must be unique unless replace_all=true."),{device:r.string().describe("Target device name."),file_path:r.string().describe("Absolute path to the file to edit"),old_string:r.string().describe("The text to replace"),new_string:r.string().describe("The replacement text"),replace_all:r.boolean().optional().describe("Replace all occurrences (default: false)")},async({device:n,file_path:o,old_string:u,new_string:m,replace_all:a})=>{try{if(!E(o))return{content:[{type:"text",text:"file_path must be absolute"}],isError:!0};let i=await $(e,n,"edit",{file_path:o,old_string:u,new_string:m,replace_all:a||!1}),t=S(n,i?.cortexMDs,o);return{content:[{type:"text",text:`File edited: ${o}`},...t]}}catch(i){return{content:[{type:"text",text:`remote_edit error: ${i.message}`}],isError:!0}}}),s.tool("remote_glob",c("remote_glob","List remote file paths matching a glob."),{device:r.string().describe("Target device name."),pattern:r.string().describe("Glob pattern to match files against"),path:r.string().optional().describe("Directory to search in (absolute path)")},{readOnlyHint:!0},async({device:n,pattern:o,path:u})=>{try{let m=await $(e,n,"glob",{pattern:o,path:u}),a=m.files||[];if(a.length===0)return{content:[{type:"text",text:"No files matched the pattern."}]};let i=a.join(`
13
- `);return m.truncated&&(i+=`
14
- [... truncated at ${a.length} results]`),{content:[{type:"text",text:C("remote_glob",i)}]}}catch(m){return{content:[{type:"text",text:`remote_glob error: ${m.message}`}],isError:!0}}}),s.tool("remote_grep",c("remote_grep","Search remote file contents with ripgrep; return matching lines, paths, or counts."),{device:r.string().describe("Target device name."),pattern:r.string().describe("Regex pattern to search for"),path:r.string().optional().describe("File or directory to search in"),glob:r.string().optional().describe('Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}")'),type:r.string().optional().describe('File type to search (e.g. "js", "py", "rust")'),output_mode:r.enum(["content","files_with_matches","count"]).optional().describe("Output mode (default: files_with_matches)"),"-A":r.number().optional().describe("Lines to show after each match"),"-B":r.number().optional().describe("Lines to show before each match"),"-C":r.number().optional().describe("Context lines before and after each match"),context:r.number().optional().describe("Alias for -C"),"-i":r.boolean().optional().describe("Case insensitive search"),"-n":r.boolean().optional().describe("Show line numbers (default: true for content mode)"),head_limit:r.number().optional().describe("Limit output entries (default: 250, 0 for unlimited)"),offset:r.number().optional().describe("Skip first N entries before applying head_limit"),multiline:r.boolean().optional().describe("Enable multiline matching (pattern can span lines)")},{readOnlyHint:!0},async({device:n,pattern:o,path:u,glob:m,type:a,output_mode:i,context:t,head_limit:d,offset:y,multiline:g,...b})=>{try{let x=(await $(e,n,"grep",{pattern:o,path:u,glob:m,type:a,output_mode:i,"-A":b["-A"],"-B":b["-B"],"-C":b["-C"],context:t,"-i":b["-i"],"-n":b["-n"],head_limit:d,offset:y,multiline:g})).output||"(no matches)";return{content:[{type:"text",text:C("remote_grep",x)}]}}catch(p){return{content:[{type:"text",text:`remote_grep error: ${p.message}`}],isError:!0}}})}export{we as registerRemoteOpsTools};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{qa as a,ra as b,sa as c}from"./chunk-YAAKL3QS.js";import"./chunk-QEL6CMLE.js";import"./chunk-TJ4GQRT6.js";import"./chunk-5A6CA5TM.js";import"./chunk-LMDWRRX4.js";import"./chunk-BZDIAI5M.js";import"./chunk-IA6IODY3.js";import"./chunk-IYVZHGUQ.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-B3XBQEFM.js";import"./chunk-OFEPDNRB.js";import"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-R6CGBSTC.js";import"./chunk-WZYS2HAK.js";import"./chunk-TMV2ZDOI.js";import"./chunk-SFX7V5O2.js";import"./chunk-VTL3Z2OP.js";import"./chunk-4YLAGSDM.js";import"./chunk-RDW6FRF5.js";import"./chunk-IKLTEWA3.js";import"./chunk-2VVRTJQN.js";import"./chunk-RF4JLYBX.js";import"./chunk-7GEBDPTT.js";import"./chunk-V7K3KNDM.js";import"./chunk-5T7IX5KN.js";import"./chunk-BDLKI2NT.js";import"./chunk-JJDEQ6N2.js";import"./chunk-MGYYSX7Y.js";import"./chunk-RA2BUYI3.js";import"./chunk-U23S37TT.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import"./chunk-QUXPMNFQ.js";import"./chunk-BUZQBTV2.js";import"./chunk-STCNHXPJ.js";import"./chunk-STUHNKQS.js";import"./chunk-NRD57ICT.js";import"./chunk-KRXTI4JO.js";import"./chunk-W34AK4SK.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import"./chunk-3CPIMAYX.js";import"./chunk-VBN2JSER.js";import"./chunk-NXZS5PEW.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";export{c as _test,b as runSubagent,a as supportsSubagents};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a,b,c,d,e,f}from"./chunk-L6VCIGWS.js";import"./chunk-Y3GFB5XM.js";import"./chunk-EQIMHXC4.js";import"./chunk-IRWZ7UPF.js";import"./chunk-RA6HKFBV.js";import"./chunk-FX6MOGLR.js";import"./chunk-QUUEQRIT.js";import"./chunk-AWFUHWQK.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";export{a as McpOAuthCredentialStore,f as McpServerConnection,d as McpServerLog,b as McpSignInCancelledError,e as createDefaultTransport,c as signInMcpServer};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{c as S,d as w,e as p,f as v,h as g,k as h,l as m,p as A,r as j,s as C,t as M,u as D}from"./chunk-VIMHSW6J.js";import"./chunk-QEL6CMLE.js";import"./chunk-IA6IODY3.js";import{g as O}from"./chunk-W6AKCEYF.js";import"./chunk-RF4JLYBX.js";import"./chunk-JJDEQ6N2.js";import"./chunk-MGYYSX7Y.js";import"./chunk-RA2BUYI3.js";import"./chunk-U23S37TT.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import{b as E,c as x}from"./chunk-PMG4YGDU.js";import"./chunk-STUHNKQS.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import"./chunk-3CPIMAYX.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";var f=["list","get","add","edit","pause","resume","remove"],_={"--type":"type","--interval":"interval","--time":"time","--day":"day","--delay":"delay","--message":"message","--project":"project","--model":"model","--thinking":"thinking","--pre-check":"preCheck","--idempotency-key":"idempotencyKey"},I=["interval","time","day","delay","message","project","model","thinking","preCheck"],L={list:["project"],get:[],add:["type",...I,"idempotencyKey"],edit:I,pause:[],resume:[],remove:[]},T={interval:["interval"],daily:["time"],weekly:["day","time"],once:["delay"]},N=new Set(["get","edit","pause","resume","remove"]),c=class extends Error{validValues;hint;constructor(t,n,r="cortex schedule --help"){super(t),this.validValues=n,this.hint=r}};function y(e){return Object.entries(_).filter(([,t])=>e.includes(t)).map(([t])=>t)}function R(e,t,n,r){let i=_[t[n]];if(!i||!L[e].includes(i)){let o=[...y(L[e]),...e==="remove"?["--dry-run"]:[]];throw new c(`Unknown option for '${e}': '${t[n]}'.`,o.length?o:["(none)"])}if(t[n+1]===void 0||t[n+1].startsWith("--"))throw new c(`Missing value for ${t[n]}.`);r[i]=t[n+1]}function b(e,t,n){let r={id:"",flags:{},dryRun:!1},i=[];for(let s=0;s<t.length;s+=1)e==="remove"&&t[s]==="--dry-run"?r.dryRun=!0:t[s].startsWith("-")?R(e,t,s++,r.flags):i.push(t[s]);let o=N.has(e)?1:0;if(i.length!==o)throw new c(o?`'${e}' takes one schedule id.`:`Unexpected argument: '${i[0]}'.`,void 0,o?`cortex schedule ${e} <id>`:void 0);return r.id=i[0]??"",r.flags.message==="-"&&(r.flags.message=n()),r}var G=["createdAt","nextRun","lastRun","runAt","pausedAt","lastSkipped"];function k(e){let t={...e};for(let n of G)typeof e[n]=="number"&&(t[n]=new Date(e[n]).toISOString());return t}function u(e,t){if(!e)throw new c(`Schedule not found: '${t}'.`,void 0,"cortex schedule list");return k(e)}async function W({flags:e},t){if(!e.type)throw new c("Missing --type.",[...S]);let n=h(e.model,e.thinking);m(e.model,n);let r=g({type:e.type,message:e.message,projectId:e.project,selection:n,preCheck:e.preCheck,interval:e.interval,time:e.time,dayOfWeek:e.day,delay:e.delay}),i=T[r.type],o=["interval","time","day","delay"].filter(d=>e[d]!==void 0&&!i.includes(d));if(o.length)throw new c(`${y(o).join(", ")} does not apply to --type ${r.type}.`,y(i));let{task:s,created:l}=await j(t,r,{idempotencyKey:e.idempotencyKey});return{ok:!0,created:l,schedule:k(s)}}var K={message:e=>({message:e}),project:e=>({projectId:e}),preCheck:e=>({preCheck:e}),interval:e=>({intervalMs:p(e,"interval")}),time:e=>({time:e}),day:e=>({dayOfWeek:v(e)}),delay:e=>({runAt:Date.now()+p(e,"delay")})};async function U({id:e,flags:t},n){let r=await n.findTask(e);u(r,e);let{model:i,thinking:o,...s}=t,l=Object.assign({},...Object.entries(s).map(([$,F])=>K[$](F))),d=h(i,o,r?.selection);return m(i,d),d&&(l.selection=d),{ok:!0,schedule:u(await C(n,e,l),e)}}async function V({id:e,dryRun:t},n){return t?{ok:!0,dry_run:!0,would_remove:u(await n.findTask(e),e)}:{ok:!0,id:e,removed:await n.removeTask(e)}}async function H({flags:e},t){let n=(await t.read()).tasks.filter(r=>!e.project||r.projectId===e.project);return{ok:!0,count:n.length,schedules:n.map(k)}}var P={list:H,get:async({id:e},t)=>({ok:!0,schedule:u(await t.findTask(e),e)}),add:W,edit:U,pause:async({id:e},t)=>({ok:!0,schedule:u(await M(t,e),e)}),resume:async({id:e},t)=>({ok:!0,schedule:u(await D(t,e),e)}),remove:V};function a(e,t,n){return{exitCode:1,stdout:"",stderr:E(e,{validValues:t,hint:n})}}function z(e){return e instanceof c?a(e.message,e.validValues,e.hint):e instanceof w?a(e.message,void 0,"cortex schedule --help"):a(e.message)}async function Z(e,t={}){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:O(),stderr:""};let[n,...r]=e;if(!n)return a("Missing subcommand for 'schedule'.",[...f]);if(!f.includes(n))return a(`Unknown subcommand: '${n}'.`,[...f]);try{let i=b(n,r,t.readStdin??x),o=await P[n](i,t.repo??A);return{exitCode:0,stdout:JSON.stringify(o,null,2),stderr:""}}catch(i){return z(i)}}export{Z as runScheduleCli};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{b as w,c as E}from"./chunk-S3MR37DL.js";import{a as C,e as x}from"./chunk-RYLSRII6.js";import{a as L}from"./chunk-NT32UURL.js";import"./chunk-I6OPDRVF.js";import"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-LP72AF56.js";import"./chunk-N6BTQN7R.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as r}from"./chunk-W34AK4SK.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import{e as T}from"./chunk-WHC7AYZD.js";var k=T(x(),1);import*as S from"fs";import*as b from"path";function v(e){return{slack:e.slackBotToken?new k.WebClient(e.slackBotToken):null,fallbackChannel:e.channel??void 0,ctx:e}}function y(){return new C({globalCapacity:m("CORTEX_SLACK_RL_GLOBAL_CAPACITY",20),globalRefillPerSec:m("CORTEX_SLACK_RL_GLOBAL_REFILL_PER_SEC",1),perChannelCapacity:m("CORTEX_SLACK_RL_CHANNEL_CAPACITY",1),perChannelRefillPerSec:m("CORTEX_SLACK_RL_CHANNEL_REFILL_PER_SEC",1)})}function m(e,t){let l=process.env[e];return l?Number(l):t}var R=null;async function A(e,{channel:t,filePath:l,fileName:s,title:h,initialComment:p}){let a=R??(R=y()),{resolved:o,size:c}=L(l),f=S.readFileSync(o),i=s||b.basename(o),n=w(t,"slack:");p&&(await a.acquire("chat.postMessage",n),await e.chat.postMessage({channel:n,text:p})),await a.acquire("files.getUploadURLExternal",n);let d=await e.files.getUploadURLExternal({filename:i,length:c});if(!d?.upload_url||!d?.file_id)throw new Error("Slack upload initialization failed: missing upload_url or file_id");let u=await fetch(d.upload_url,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:f});if(!u.ok){let _=await u.text().catch(()=>""),g=_?`: ${_.slice(0,300)}`:"";throw new Error(`Slack file upload failed (${u.status} ${u.statusText})${g}`)}return await a.acquire("files.completeUploadExternal",n),await e.files.completeUploadExternal({files:[{id:d.file_id,title:h||i}],channel_id:n}),{path:o,fileName:i,size:c}}function $(e,t){e.tool("slack_send_file","Share a local or remote-device file in the Slack chat.",{file_path:r.string().describe("File path to upload. Local path, or an absolute path on `device`."),file_name:r.string().optional().describe("Optional filename override shown in Slack"),title:r.string().optional().describe("Optional file title shown in Slack"),comment:r.string().optional().describe("Optional comment to accompany the file"),device:r.string().optional().describe("Connected device to read from; omit for this server.")},async({file_path:l,file_name:s,title:h,comment:p,device:a})=>{try{let o=t.fallbackChannel;if(!o)throw new Error("No routing channel available");if(!t.slack)throw new Error("Missing SLACK_BOT_TOKEN");let c=(i,n)=>A(t.slack,{channel:o,filePath:i,fileName:n,title:h,initialComment:p||void 0}),f=a?await E(t.ctx,a,l,i=>c(i.localPath,s||i.name)):await c(l,s);return{content:[{type:"text",text:`File uploaded${a?` from ${a}`:""}: ${f.fileName} (${f.size} bytes)`}]}}catch(o){return{content:[{type:"text",text:`Failed to upload file: ${o.message}`}],isError:!0}}})}export{$ as registerSlackTools,v as slackDepsFor,A as uploadFileToSlack};
@@ -1,43 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{$ as Pn,$a as Ao,A as tn,Aa as to,Ab as qo,Ac as ps,B as rn,Ba as ro,Bc as ms,C as nn,Ca as no,Cc as ys,D as on,Da as oo,Dc as hs,E as sn,Ea as tt,Ec as gs,F as an,Fa as so,G as cn,Ga as io,H as un,Ha as ao,I as ln,Ia as co,Ic as Es,J as dn,Ja as uo,K as fn,Ka as lo,Kc as Ss,L as pn,La as fo,M as mn,Ma as po,N as yn,Na as mo,Nb as os,O as hn,Oa as yo,P as gn,Q as wn,Qa as Et,R as En,Ra as ho,S as Sn,Sa as go,T as vn,Ta as wo,U as bn,Ua as Eo,V as _n,Va as So,W as Tn,Wa as vo,X as Rn,Xa as bo,Y as An,Ya as _o,Z as On,Za as To,_ as In,_a as Ro,aa as Cn,ab as Oo,ba as xn,bb as Io,ca as Nn,cb as Po,d as Ur,da as Dn,db as Co,ea as Un,eb as xo,fa as kn,fb as No,g as kr,ga as Ln,gb as Do,h as Lr,ha as Mn,hb as Uo,i as Mr,ia as jn,ib as ko,j as jr,ja as Hn,jb as Lo,k as Hr,ka as Fn,kb as St,l as Fr,la as Jn,lb as Mo,m as Jr,ma as Wn,mb as jo,n as Wr,na as Bn,nb as Ho,o as Br,oa as $n,ob as Fo,oc as cs,p as $r,pa as Kn,pb as Jo,q as Kr,qa as zn,qb as Wo,r as zr,ra as Vn,rb as Bo,s as Vr,sa as Gn,sb as $o,sc as us,t as Gr,tb as Ko,tc as ls,u as Yr,ua as Yn,ub as zo,uc as ds,v as Qr,va as Qn,vb as Vo,vc as fs,w as Xr,wa as Xn,wb as Go,x as qr,xa as qn,xb as Yo,y as Zr,ya as Zn,yb as Qo,z as en,za as eo,zb as Xo}from"./chunk-QMSSIDRQ.js";import"./chunk-5A6CA5TM.js";import{a as vt}from"./chunk-TCAEECDI.js";import{e as qe,f as Ze}from"./chunk-LMDWRRX4.js";import{a as ss,b as is,c as as}from"./chunk-Y6ZEVVL5.js";import{a as ne,b as et}from"./chunk-2YTYYG4K.js";import"./chunk-SAJD4EKE.js";import"./chunk-ZFPMIQA3.js";import"./chunk-EE3WT25T.js";import"./chunk-IKLTEWA3.js";import{a as es,c as ts,d as rs}from"./chunk-FP7ML72L.js";import"./chunk-LEAV3FFG.js";import{b as vs}from"./chunk-2ATTYCRJ.js";import"./chunk-7GEBDPTT.js";import{a as ke,d as Z,e as Zo}from"./chunk-KUDK7GPS.js";import"./chunk-RA2BUYI3.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import{b as ws}from"./chunk-QUXPMNFQ.js";import"./chunk-XPPZ6Y3X.js";import{f as Nr,l as Dr}from"./chunk-BUZQBTV2.js";import{e as Cr}from"./chunk-STCNHXPJ.js";import"./chunk-STUHNKQS.js";import{a as ns}from"./chunk-NRD57ICT.js";import"./chunk-KRXTI4JO.js";import{K as _e}from"./chunk-W34AK4SK.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import{e as xr}from"./chunk-3CPIMAYX.js";import{e as N}from"./chunk-VBN2JSER.js";import"./chunk-NXZS5PEW.js";import{j as Xe,t as Ir,v as Pr}from"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as te from"node:path";import*as xa from"node:fs";import{fileURLToPath as yf}from"node:url";function bs(e){let r=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return Nr.includes(r??"")?r:null}function rt(e,...t){let r=Object.assign(Y(),e);for(let n of t)for(let o in n){if(o in r&&r[o]!==n[o])throw new Error(`Duplicate key ${o}`);r[o]=n[o]}return r}function F(e){return!!e&&!Array.isArray(e)&&typeof e=="object"}function nt(e){return typeof e=="function"}function Y(){return Object.create(null)}var Da=typeof Symbol=="function"&&!!Symbol.asyncIterator;function Le(e){return Da&&F(e)&&Symbol.asyncIterator in e}var oe=e=>e();function _s(e){return e}function Ts(e){if(typeof AbortSignal.any=="function")return AbortSignal.any(e);let t=new AbortController;for(let n of e){if(n.aborted){r();break}n.addEventListener("abort",r,{once:!0})}return t.signal;function r(){t.abort();for(let n of e)n.removeEventListener("abort",r)}}var Te={PARSE_ERROR:-32700,BAD_REQUEST:-32600,INTERNAL_SERVER_ERROR:-32603,NOT_IMPLEMENTED:-32603,BAD_GATEWAY:-32603,SERVICE_UNAVAILABLE:-32603,GATEWAY_TIMEOUT:-32603,UNAUTHORIZED:-32001,PAYMENT_REQUIRED:-32002,FORBIDDEN:-32003,NOT_FOUND:-32004,METHOD_NOT_SUPPORTED:-32005,TIMEOUT:-32008,CONFLICT:-32009,PRECONDITION_FAILED:-32012,PAYLOAD_TOO_LARGE:-32013,UNSUPPORTED_MEDIA_TYPE:-32015,UNPROCESSABLE_CONTENT:-32022,PRECONDITION_REQUIRED:-32028,TOO_MANY_REQUESTS:-32029,CLIENT_CLOSED_REQUEST:-32099},Rs={[-32700]:"PARSE_ERROR",[-32600]:"BAD_REQUEST",[-32603]:"INTERNAL_SERVER_ERROR",[-32001]:"UNAUTHORIZED",[-32002]:"PAYMENT_REQUIRED",[-32003]:"FORBIDDEN",[-32004]:"NOT_FOUND",[-32005]:"METHOD_NOT_SUPPORTED",[-32008]:"TIMEOUT",[-32009]:"CONFLICT",[-32012]:"PRECONDITION_FAILED",[-32013]:"PAYLOAD_TOO_LARGE",[-32015]:"UNSUPPORTED_MEDIA_TYPE",[-32022]:"UNPROCESSABLE_CONTENT",[-32028]:"PRECONDITION_REQUIRED",[-32029]:"TOO_MANY_REQUESTS",[-32099]:"CLIENT_CLOSED_REQUEST"},Af=[Te.BAD_GATEWAY,Te.SERVICE_UNAVAILABLE,Te.GATEWAY_TIMEOUT,Te.INTERNAL_SERVER_ERROR];var Ua=()=>{},As=e=>{Object.freeze&&Object.freeze(e)};function Is(e,t,r){var n;let o=t.join(".");return(n=r[o])!==null&&n!==void 0||(r[o]=new Proxy(Ua,{get(i,s){if(!(typeof s!="string"||s==="then"))return Is(e,[...t,s],r)},apply(i,s,a){let c=t[t.length-1];if(c==="valueOf"||c==="toString"||c==="toJSON")return`tRPC.proxy(${t.slice(0,-1).join(".")})`;let u={args:a,path:t};return c==="call"?u={args:a.length>=2?[a[1]]:[],path:t.slice(0,-1)}:c==="apply"&&(u={args:a.length>=2?a[1]:[],path:t.slice(0,-1)}),As(u.args),As(u.path),e(u)}})),r[o]}var Ps=e=>Is(e,[],Y());var ka={PARSE_ERROR:400,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_SUPPORTED:405,TIMEOUT:408,CONFLICT:409,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,UNSUPPORTED_MEDIA_TYPE:415,UNPROCESSABLE_CONTENT:422,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,CLIENT_CLOSED_REQUEST:499,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504};function Cs(e){var t;return(t=ka[e])!==null&&t!==void 0?t:500}function xs(e){let t=new Set((Array.isArray(e)?e:[e]).map(r=>{if("error"in r&&F(r.error.data)){var n;if(typeof((n=r.error.data)===null||n===void 0?void 0:n.httpStatus)=="number")return r.error.data.httpStatus;let o=Rs[r.error.code];return Cs(o)}return 200}));return t.size!==1?207:t.values().next().value}function La(e){return Cs(e.code)}function Me(e){"@babel/helpers - typeof";return Me=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Me(e)}function Ma(e,t){if(Me(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Me(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ja(e){var t=Ma(e,"string");return Me(t)=="symbol"?t:t+""}function X(e,t,r){return(t=ja(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Os(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),r.push.apply(r,n)}return r}function S(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Os(Object(r),!0).forEach(function(n){X(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Os(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function se(e){let{path:t,error:r,config:n}=e,{code:o}=e.error,i={message:r.message,code:Te[o],data:{code:o,httpStatus:La(r)}};return n.isDev&&typeof e.error.stack=="string"&&(i.data.stack=e.error.stack),typeof t=="string"&&(i.data.path=t),n.errorFormatter(S(S({},e),{},{shape:i}))}var Re=({shape:e})=>e,Ha=class extends Error{constructor(e){super(Fa(e)),Object.assign(this,e)}};function Fa(e){if("message"in e)return String(e.message)}function Ja(e){if(e instanceof Error)return e;let t=typeof e;if(!(t==="undefined"||t==="function"||e===null)){if(t!=="object")return new Error(String(e));if(F(e))return new Ha(e)}}function B(e){if(e instanceof O||e instanceof Error&&e.name==="TRPCError")return e;let t=new O({code:"INTERNAL_SERVER_ERROR",cause:e});return e instanceof Error&&e.stack&&(t.stack=e.stack),t}var O=class extends Error{constructor(e){var t,r,n;let o=Ja(e.cause),i=(t=(r=e.message)!==null&&r!==void 0?r:o?.message)!==null&&t!==void 0?t:e.code;super(i,{cause:o}),X(this,"cause",void 0),X(this,"code",void 0),this.code=e.code,this.name="TRPCError",(n=this.cause)!==null&&n!==void 0||(this.cause=o)}};function Ds(e){return"input"in e?e:{input:e,output:e}}var Ae={input:{serialize:e=>e,deserialize:e=>e},output:{serialize:e=>e,deserialize:e=>e}};function Ns(e,t){return"error"in t?S(S({},t),{},{error:e.transformer.output.serialize(t.error)}):"data"in t.result?S(S({},t),{},{result:S(S({},t.result),{},{data:e.transformer.output.serialize(t.result.data)})}):t}function me(e,t){return Array.isArray(t)?t.map(r=>Ns(e,r)):Ns(e,t)}var Wa="lazyMarker";function Ba(e){let t=Symbol(),r=t;return()=>(r===t&&(r=e()),r)}function $a(e){return typeof e=="function"&&Wa in e}function Ka(e){return F(e)&&F(e._def)&&"router"in e._def}var za={_ctx:null,_errorShape:null,_meta:null,queries:{},mutations:{},subscriptions:{},errorFormatter:Re,transformer:Ae},Va=["then","call","apply"];function bt(e){function t(r){let n=new Set(Object.keys(r).filter(l=>Va.includes(l)));if(n.size>0)throw new Error("Reserved words used in `router({})` call: "+Array.from(n).join(", "));let o=Y(),i=Y();function s(l){return{ref:l.ref,load:Ba(async()=>{let p=await l.ref(),m=[...l.path,l.key],y=m.join(".");l.aggregate[l.key]=a(p._def.record,m),delete i[y];for(let[d,f]of Object.entries(p._def.lazy)){let w=[...m,d].join(".");i[w]=s({ref:f.ref,path:m,key:d,aggregate:l.aggregate[l.key]})}})}}function a(l,p=[]){let m=Y();for(let[y,d]of Object.entries(l??{})){if($a(d)){i[[...p,y].join(".")]=s({path:p,ref:d,key:y,aggregate:m});continue}if(Ka(d)){m[y]=a(d._def.record,[...p,y]);continue}if(!Ga(d)){m[y]=a(d,[...p,y]);continue}let f=[...p,y].join(".");if(o[f])throw new Error(`Duplicate key: ${f}`);o[f]=d,m[y]=d}return m}let c=a(r),u=S(S({_config:e,router:!0,procedures:o,lazy:i},za),{},{record:c});return S(S({},c),{},{_def:u,createCaller:_t()({_def:u})})}return t}function Ga(e){return typeof e=="function"}async function je(e,t){let{_def:r}=e,n=r.procedures[t];for(;!n;){let o=Object.keys(r.lazy).find(i=>t===i||t.startsWith(i+"."));if(!o)return null;await r.lazy[o].load(),n=r.procedures[t]}return n}function _t(){return function(t){let{_def:r}=t;return function(o,i){return Ps(async s=>{let{path:a,args:c}=s,u=a.join(".");if(a.length===1&&a[0]==="_def")return r;let l=await je(t,u),p;try{if(!l)throw new O({code:"NOT_FOUND",message:`No procedure found on path "${a}"`});return p=nt(o)?await Promise.resolve(o()):o,await l({path:u,getRawInput:async()=>c[0],ctx:p,type:l._def.type,signal:i?.signal,batchIndex:0})}catch(d){var m,y;throw i==null||(m=i.onError)===null||m===void 0||m.call(i,{ctx:p,error:B(d),input:c[0],path:u,type:(y=l?._def.type)!==null&&y!==void 0?y:"unknown"}),d}})}}}function Us(...e){var t,r;let n=rt({},...e.map(o=>o._def.record));return bt({errorFormatter:e.reduce((o,i)=>{if(i._def._config.errorFormatter&&i._def._config.errorFormatter!==Re){if(o!==Re&&o!==i._def._config.errorFormatter)throw new Error("You seem to have several error formatters");return i._def._config.errorFormatter}return o},Re),transformer:e.reduce((o,i)=>{if(i._def._config.transformer&&i._def._config.transformer!==Ae){if(o!==Ae&&o!==i._def._config.transformer)throw new Error("You seem to have several transformers");return i._def._config.transformer}return o},Ae),isDev:e.every(o=>o._def._config.isDev),allowOutsideOfServer:e.every(o=>o._def._config.allowOutsideOfServer),isServer:e.every(o=>o._def._config.isServer),$types:(t=e[0])===null||t===void 0?void 0:t._def._config.$types,sse:(r=e[0])===null||r===void 0?void 0:r._def._config.sse})(n)}var Ya=Symbol();function Tt(e){return Array.isArray(e)&&e[2]===Ya}var Ms="middlewareMarker";function Qa(){function e(r){return{_middlewares:r,unstable_pipe(n){let o="_middlewares"in n?n._middlewares:[n];return e([...r,...o])}}}function t(r){return e([r])}return t}function Xa(e){let t=async function(n){let o,i=await n.getRawInput();try{o=await e(i)}catch(a){throw new O({code:"BAD_REQUEST",cause:a})}let s=F(n.input)&&F(o)?S(S({},n.input),o):o;return n.next({input:s})};return t._type="input",t}function qa(e){let t=async function({next:n}){let o=await n();if(!o.ok)return o;try{let i=await e(o.data);return S(S({},o),{},{data:i})}catch(i){throw new O({message:"Output validation failed",code:"INTERNAL_SERVER_ERROR",cause:i})}};return t._type="output",t}var js=class extends Error{constructor(e){var t;super((t=e[0])===null||t===void 0?void 0:t.message),X(this,"issues",void 0),this.name="SchemaError",this.issues=e}};function ks(e){let t=e,r="~standard"in t;if(typeof t=="function"&&typeof t.assert=="function")return t.assert.bind(t);if(typeof t=="function"&&!r)return t;if(typeof t.parseAsync=="function")return t.parseAsync.bind(t);if(typeof t.parse=="function")return t.parse.bind(t);if(typeof t.validateSync=="function")return t.validateSync.bind(t);if(typeof t.create=="function")return t.create.bind(t);if(typeof t.assert=="function")return n=>(t.assert(n),n);if(r)return async n=>{let o=await t["~standard"].validate(n);if(o.issues)throw new js(o.issues);return o.value};throw new Error("Could not find a validator fn")}function Za(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.includes(n))continue;r[n]=e[n]}return r}function ec(e,t){if(e==null)return{};var r,n,o=Za(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.includes(r)||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}var tc=["middlewares","inputs","meta"];function de(e,t){let{middlewares:r=[],inputs:n,meta:o}=t,i=ec(t,tc);return Hs(S(S({},rt(e,i)),{},{inputs:[...e.inputs,...n??[]],middlewares:[...e.middlewares,...r],meta:e.meta&&o?S(S({},e.meta),o):o??e.meta}))}function Hs(e={}){let t=S({procedure:!0,inputs:[],middlewares:[]},e);return{_def:t,input(r){let n=ks(r);return de(t,{inputs:[r],middlewares:[Xa(n)]})},output(r){let n=ks(r);return de(t,{output:r,middlewares:[qa(n)]})},meta(r){return de(t,{meta:r})},use(r){let n="_middlewares"in r?r._middlewares:[r];return de(t,{middlewares:n})},unstable_concat(r){return de(t,r._def)},concat(r){return de(t,r._def)},query(r){return Rt(S(S({},t),{},{type:"query"}),r)},mutation(r){return Rt(S(S({},t),{},{type:"mutation"}),r)},subscription(r){return Rt(S(S({},t),{},{type:"subscription"}),r)},experimental_caller(r){return de(t,{caller:r})}}}function Rt(e,t){let r=de(e,{resolver:t,middlewares:[async function(c){let u=await t(c);return{marker:Ms,ok:!0,data:u,ctx:c.ctx}}]}),n=S(S({},r._def),{},{type:e.type,experimental_caller:!!r._def.caller,meta:r._def.meta,$types:null}),o=nc(r._def),i=r._def.caller;if(!i)return o;let s=async(...a)=>await i({args:a,invoke:o,_def:n});return s._def=n,s}var rc=`
5
- This is a client-only function.
6
- If you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls
7
- `.trim();async function Fs(e,t,r){try{let n=t.middlewares[e];return await n(S(S({},r),{},{meta:t.meta,input:r.input,next(o){var i;let s=o;return Fs(e+1,t,S(S({},r),{},{ctx:s?.ctx?S(S({},r.ctx),s.ctx):r.ctx,input:s&&"input"in s?s.input:r.input,getRawInput:(i=s?.getRawInput)!==null&&i!==void 0?i:r.getRawInput}))}}))}catch(n){return{ok:!1,error:B(n),marker:Ms}}}function nc(e){async function t(r){if(!r||!("getRawInput"in r))throw new Error(rc);let n=await Fs(0,e,r);if(!n)throw new O({code:"INTERNAL_SERVER_ERROR",message:"No result from middlewares - did you forget to `return next()`?"});if(!n.ok)throw n.error;return n.data}return t._def=e,t.procedure=!0,t.meta=e.meta,t}var Oe,Ie,Pe,Ls=typeof window>"u"||"Deno"in window||((Oe=globalThis.process)===null||Oe===void 0||(Oe=Oe.env)===null||Oe===void 0?void 0:Oe.NODE_ENV)==="test"||!!(!((Ie=globalThis.process)===null||Ie===void 0||(Ie=Ie.env)===null||Ie===void 0)&&Ie.JEST_WORKER_ID)||!!(!((Pe=globalThis.process)===null||Pe===void 0||(Pe=Pe.env)===null||Pe===void 0)&&Pe.VITEST_WORKER_ID),Ot=new class At{context(){return new At}meta(){return new At}create(t){var r,n,o,i,s,a;let c=S(S({},t),{},{transformer:Ds((r=t?.transformer)!==null&&r!==void 0?r:Ae),isDev:(n=t?.isDev)!==null&&n!==void 0?n:((o=globalThis.process)===null||o===void 0?void 0:o.env.NODE_ENV)!=="production",allowOutsideOfServer:(i=t?.allowOutsideOfServer)!==null&&i!==void 0?i:!1,errorFormatter:(s=t?.errorFormatter)!==null&&s!==void 0?s:Re,isServer:(a=t?.isServer)!==null&&a!==void 0?a:Ls,$types:null});var u;if(!((u=t?.isServer)!==null&&u!==void 0?u:Ls)&&t?.allowOutsideOfServer!==!0)throw new Error("You're trying to use @trpc/server in a non-server environment. This is not supported by default.");return{_config:c,procedure:Hs({meta:t?.defaultMeta}),middleware:Qa(),router:bt(c),mergeRouters:Us,createCallerFactory:_t()}}};var oc={ping:{enabled:!0,intervalMs:15e3},client:{reconnectAfterInactivityMs:45e3}},It=Ot.context().create({sse:oc,errorFormatter({shape:e,path:t}){return t!=="config.setPlatform"?e:{...e,message:xr("ui.platform.requestFailed"),data:{...e.data,stack:void 0}}}}),C=It.router,ot=It.procedure,Qf=It.createCallerFactory;var sc=_e.object({events:_e.array(_e.string()),projectId:_e.string().nullish(),sessionId:_e.string().nullish()}),ic={"not-found":"NOT_FOUND","invalid-args":"BAD_REQUEST","invalid-name":"BAD_REQUEST","invalid-notes-file":"BAD_REQUEST","already-terminal":"CONFLICT","already-exists":"CONFLICT",conflict:"CONFLICT","backend-locked":"CONFLICT","session-running":"CONFLICT","not-available":"BAD_REQUEST",not_manageable:"BAD_REQUEST",runtime_unavailable:"BAD_REQUEST",logout_failed:"INTERNAL_SERVER_ERROR",internal:"INTERNAL_SERVER_ERROR"};function ac(e){return new O({code:ic[e.code]??"INTERNAL_SERVER_ERROR",message:e.message,cause:e})}function Js(e){if(e.ok)return e.data;throw ac(e)}function _(e,t,r){return ot.input(r).query(async({input:n})=>Js(await e.query(t,n)))}function h(e,t,r){return ot.input(r).mutation(async({input:n,ctx:o})=>Js(await e.mutate(t,n,{client:o.client??null})))}function cc(e){return C({list:_(e,"projects.list",tn),create:h(e,"projects.create",jn),delete:h(e,"projects.delete",Hn)})}function uc(e){return C({list:_(e,"sessions.list",Mr),transcript:_(e,"sessions.transcript",jr),subagentTranscript:_(e,"sessions.subagentTranscript",Hr),debugDetails:_(e,"sessions.debugDetails",Fr),pendingInteraction:_(e,"sessions.pendingInteraction",Jr),create:h(e,"sessions.create",Jn),delete:h(e,"sessions.delete",Fn),send:h(e,"sessions.send",Wn),cancel:h(e,"sessions.cancel",Bn),resolveUnsent:h(e,"sessions.resolveUnsent",$n),compact:h(e,"sessions.compact",Kn),setAgent:h(e,"sessions.setAgent",Gn),setSelection:h(e,"sessions.setSelection",Yn),createAndSend:h(e,"sessions.createAndSend",ro),setStarred:h(e,"sessions.setStarred",kr),rename:h(e,"sessions.rename",Lr),markRead:h(e,"sessions.markRead",zn),markManyRead:h(e,"sessions.markManyRead",Vn),answerQuestion:h(e,"sessions.answerQuestion",Qn),respondPlan:h(e,"sessions.respondPlan",Xn),respondDecision:h(e,"sessions.respondDecision",qn),cancelResume:h(e,"sessions.cancelResume",eo),rewind:h(e,"sessions.rewind",to),resolveMedia:h(e,"sessions.resolveMedia",Zn)})}function lc(e){return C({list:_(e,"schedules.list",Wr),pause:h(e,"schedules.pause",tt),resume:h(e,"schedules.resume",tt),remove:h(e,"schedules.remove",tt),add:h(e,"schedules.add",so),update:h(e,"schedules.update",io)})}function dc(e){return C({list:_(e,"boards.list",Br),get:_(e,"boards.get",$r),decisions:_(e,"boards.decisions",Kr),style:_(e,"boards.style",zr)})}function fc(e){return C({list:_(e,"waitpoints.list",Vr),cancel:h(e,"waitpoints.cancel",no)})}function pc(e){return C({list:_(e,"executions.list",Gr),get:_(e,"executions.get",Yr),cancel:h(e,"executions.cancel",oo)})}function mc(e){return C({tree:_(e,"memory.tree",Qr),file:_(e,"memory.file",Xr)})}function yc(e){return C({list:_(e,"approvals.list",qr),approve:h(e,"approvals.approve",Lo),reject:h(e,"approvals.reject",Wo),request:h(e,"approvals.request",qo)})}function hc(e){return C({list:_(e,"issues.list",Zr),handle:h(e,"issues.handle",St),delete:h(e,"issues.delete",St)})}function gc(e){return C({list:_(e,"notes.list",en),add:h(e,"notes.add",Mo),update:h(e,"notes.update",jo),setCompleted:h(e,"notes.setCompleted",Ho),delete:h(e,"notes.delete",Fo),clearCompleted:h(e,"notes.clearCompleted",Jo)})}function wc(e){return C({list:_(e,"hooks.list",uo),create:h(e,"hooks.create",lo),update:h(e,"hooks.update",fo),setEnabled:h(e,"hooks.setEnabled",po),remove:h(e,"hooks.remove",mo),test:h(e,"hooks.test",yo)})}function Ec(e){return C({catalog:_(e,"models.catalog",mn),favorites:C({add:h(e,"models.favorites.add",Et),remove:h(e,"models.favorites.remove",Et)}),setDefault:h(e,"models.setDefault",go),setThinking:h(e,"models.setThinking",ho),setDelegation:h(e,"models.setDelegation",wo)})}function Sc(e){return C({status:_(e,"auth.status",cn),flowState:_(e,"auth.flowState",un),startLogin:h(e,"auth.startLogin",In),respondPrompt:h(e,"auth.respondPrompt",xn),cancelFlow:h(e,"auth.cancelFlow",Nn),logout:h(e,"auth.logout",Un),syncModels:h(e,"auth.syncModels",Dn),addAccount:h(e,"auth.addAccount",Pn),removeAccount:h(e,"auth.removeAccount",Cn)})}function vc(e){return C({list:_(e,"connections.list",kn),upsert:h(e,"connections.upsert",Ln),remove:h(e,"connections.remove",Mn)})}function bc(e){return C({get:_(e,"usageSharing.get",ln),set:h(e,"usageSharing.set",dn)})}function _c(e){return C({info:_(e,"telemetry.info",fn),report:h(e,"telemetry.report",pn)})}function Tc(e){return C({daemonStatus:_(e,"system.daemonStatus",vn),rateLimitStatus:_(e,"system.rateLimitStatus",bn),usageStatus:_(e,"system.usageStatus",_n),notices:_(e,"system.notices",Tn),restart:h(e,"system.restart",Bo),clearRateLimit:h(e,"system.clearRateLimit",$o),refreshUsage:h(e,"system.refreshUsage",Ko),redeemUsageReset:h(e,"system.redeemUsageReset",zo),updateStatus:_(e,"system.updateStatus",Rn),checkUpdate:h(e,"system.checkUpdate",Vo),applyUpdate:h(e,"system.applyUpdate",Go),skipUpdate:h(e,"system.skipUpdate",Yo),version:_(e,"system.version",An),claudeCode:_(e,"system.claudeCode",On),checkClaudeCode:h(e,"system.checkClaudeCode",Qo),updateClaudeCode:h(e,"system.updateClaudeCode",Xo)})}function Rc(e){return C({summary:_(e,"cost.summary",rn)})}function Ac(e){return C({usage:_(e,"stats.usage",nn),tools:_(e,"stats.tools",on),quotaWindows:_(e,"stats.quotaWindows",sn)})}function Oc(e){return C({get:_(e,"config.get",an),set:h(e,"config.set",ao),setPlatform:h(e,"config.setPlatform",Ur),setProviderRateLimitPolicy:h(e,"config.setProviderRateLimitPolicy",co)})}function Ic(e){return C({list:_(e,"machines.list",yn),detail:_(e,"machines.detail",hn)})}function Pc(e){return C({list:_(e,"skills.list",gn),session:_(e,"skills.session",wn)})}function Cc(e){return C({list:_(e,"plugins.list",En),assign:h(e,"plugins.assign",Eo),skillFile:_(e,"plugins.skillFile",So),skillWrite:h(e,"plugins.skillWrite",vo),skillCreate:h(e,"plugins.skillCreate",bo),skillMove:h(e,"plugins.skillMove",_o),skillRemove:h(e,"plugins.skillRemove",To),skillRevert:h(e,"plugins.skillRevert",Ro),create:h(e,"plugins.create",Ao),remove:h(e,"plugins.remove",Oo),convertToPortable:h(e,"plugins.convertToPortable",Io),mcpRead:_(e,"plugins.mcpRead",Po),mcpWrite:h(e,"plugins.mcpWrite",Co)})}function xc(e){return C({list:_(e,"environments.list",Sn),get:_(e,"environments.get",xo),validate:h(e,"environments.validate",No),save:h(e,"environments.save",Do),delete:h(e,"environments.delete",Uo),savePrompt:h(e,"environments.savePrompt",ko)})}function Nc(e){return ot.input(sc).subscription(async function*({input:t,signal:r}){let n=e.subscribe(t);r?.addEventListener("abort",()=>n.close());try{for await(let o of n)yield o}finally{n.close()}})}function Ws(e){return C({projects:cc(e),sessions:uc(e),schedules:lc(e),boards:dc(e),executions:pc(e),waitpoints:fc(e),memory:mc(e),approvals:yc(e),issues:hc(e),notes:gc(e),cost:Rc(e),stats:Ac(e),config:Oc(e),models:Ec(e),auth:Sc(e),connections:vc(e),usageSharing:bc(e),telemetry:_c(e),hooks:wc(e),machines:Ic(e),skills:Pc(e),plugins:Cc(e),environments:xc(e),system:Tc(e),subscribe:Nc(e)})}import*as _i from"http";import*as fe from"fs";import*as ge from"path";function st(e){return typeof e=="object"&&e!==null&&"subscribe"in e}function Dc(e,t){let r=null,n=()=>{r?.unsubscribe(),r=null,t.removeEventListener("abort",n)};return new ReadableStream({start(o){r=e.subscribe({next(i){o.enqueue({ok:!0,value:i})},error(i){o.enqueue({ok:!1,error:i}),o.close()},complete(){o.close()}}),t.aborted?n():t.addEventListener("abort",n,{once:!0})},cancel(){n()}})}function Pt(e,t){let r=Dc(e,t).getReader(),n={async next(){let o=await r.read();if(o.done)return{value:void 0,done:!0};let{value:i}=o;if(!i.ok)throw i.error;return{value:i.value,done:!1}},async return(){return await r.cancel(),{value:void 0,done:!0}}};return{[Symbol.asyncIterator](){return n}}}function Uc(e){try{if(e===null)return null;if(!F(e))throw new Error("Expected object");let t=Object.entries(e).filter(([r,n])=>typeof n!="string");if(t.length>0)throw new Error(`Expected connectionParams to be string values. Got ${t.map(([r,n])=>`${r}: ${typeof n}`).join(", ")}`);return e}catch(t){throw new O({code:"PARSE_ERROR",message:"Invalid connection params shape",cause:t})}}function kc(e){let t;try{t=JSON.parse(e)}catch(r){throw new O({code:"PARSE_ERROR",message:"Not JSON-parsable query params",cause:r})}return Uc(t)}function Qs(e){var t,r;return(t=e.get("trpc-accept"))!==null&&t!==void 0?t:!((r=e.get("accept"))===null||r===void 0)&&r.split(",").some(n=>n.trim()==="application/jsonl")?"application/jsonl":null}function Nt(e){let t=null,r=Symbol.for("@trpc/server/http/memo"),n=r;return{read:async()=>{var o;return n!==r||((o=t)!==null&&o!==void 0||(t=e().catch(i=>{throw i instanceof O?i:new O({code:"BAD_REQUEST",message:i instanceof Error?i.message:"Invalid input",cause:i})})),n=await t,t=null),n},result:()=>n!==r?n:void 0}}var Xs={isMatch(e){var t;return!!(!((t=e.headers.get("content-type"))===null||t===void 0)&&t.startsWith("application/json"))},async parse(e){var t;let{req:r}=e,n=e.searchParams.get("batch")==="1",o=e.maxBatchSize,i=n?e.path.split(","):[e.path];if(n&&typeof o=="number"&&i.length>o)throw new O({code:"BAD_REQUEST",message:"Batch call exceeds maximum size"});let s=Nt(async()=>{let p;if(r.method==="GET"){let y=e.searchParams.get("input");y&&(p=JSON.parse(y))}else p=await r.json();if(p===void 0)return Y();if(!n){let y=Y();return y[0]=e.router._def._config.transformer.input.deserialize(p),y}if(!F(p))throw new O({code:"BAD_REQUEST",message:'"input" needs to be an object when doing a batch call'});let m=Y();for(let y of i.keys()){let d=p[y];d!==void 0&&(m[y]=e.router._def._config.transformer.input.deserialize(d))}return m}),a=await Promise.all(i.map(async(p,m)=>{let y=await je(e.router,p);return{batchIndex:m,path:p,procedure:y,getRawInput:async()=>{let d=(await s.read())[m];if(y?._def.type==="subscription"){var f,w;let g=(f=(w=e.headers.get("last-event-id"))!==null&&w!==void 0?w:e.searchParams.get("lastEventId"))!==null&&f!==void 0?f:e.searchParams.get("Last-Event-Id");if(g)if(F(d))d=S(S({},d),{},{lastEventId:g});else{var b;(b=d)!==null&&b!==void 0||(d={lastEventId:g})}}return d},result:()=>{var d;return(d=s.result())===null||d===void 0?void 0:d[m]}}})),c=new Set(a.map(p=>{var m;return(m=p.procedure)===null||m===void 0?void 0:m._def.type}).filter(Boolean));if(c.size>1)throw new O({code:"BAD_REQUEST",message:`Cannot mix procedure types in call: ${Array.from(c).join(", ")}`});let u=(t=c.values().next().value)!==null&&t!==void 0?t:"unknown",l=e.searchParams.get("connectionParams");return{isBatchCall:n,accept:Qs(r.headers),calls:a,type:u,connectionParams:l===null?null:kc(l),signal:r.signal,url:e.url}}},Lc=[Xs,{isMatch(e){var t;return!!(!((t=e.headers.get("content-type"))===null||t===void 0)&&t.startsWith("multipart/form-data"))},async parse(e){let{req:t}=e;if(t.method!=="POST")throw new O({code:"METHOD_NOT_SUPPORTED",message:"Only POST requests are supported for multipart/form-data requests"});let r=Nt(async()=>await t.formData()),n=await je(e.router,e.path);return{accept:null,calls:[{batchIndex:0,path:e.path,getRawInput:r.read,result:r.result,procedure:n}],isBatchCall:!1,type:"mutation",connectionParams:null,signal:t.signal,url:e.url}}},{isMatch(e){var t;return!!(!((t=e.headers.get("content-type"))===null||t===void 0)&&t.startsWith("application/octet-stream"))},async parse(e){let{req:t}=e;if(t.method!=="POST")throw new O({code:"METHOD_NOT_SUPPORTED",message:"Only POST requests are supported for application/octet-stream requests"});let r=Nt(async()=>t.body);return{calls:[{batchIndex:0,path:e.path,getRawInput:r.read,result:r.result,procedure:await je(e.router,e.path)}],isBatchCall:!1,accept:null,type:"mutation",connectionParams:null,signal:t.signal,url:e.url}}}];function Mc(e){let t=Lc.find(r=>r.isMatch(e));if(t)return t;if(!t&&e.method==="GET")return Xs;throw new O({code:"UNSUPPORTED_MEDIA_TYPE",message:e.headers.has("content-type")?`Unsupported content-type "${e.headers.get("content-type")}`:"Missing content-type header"})}async function jc(e){return await Mc(e.req).parse(e)}function Mt(e){return F(e)&&e.name==="AbortError"}function Hc(e="AbortError"){throw new DOMException(e,"AbortError")}function Bs(e){return Object.prototype.toString.call(e)==="[object Object]"}function Fc(e){var t,r;return Bs(e)===!1?!1:(t=e.constructor,t===void 0?!0:(r=t.prototype,!(Bs(r)===!1||r.hasOwnProperty("isPrototypeOf")===!1)))}var qs,Ct=new WeakMap,Jc=()=>{};qs=Symbol.toStringTag;var jt=class ye{constructor(t){X(this,"promise",void 0),X(this,"subscribers",[]),X(this,"settlement",null),X(this,qs,"Unpromise"),typeof t=="function"?this.promise=new Promise(t):this.promise=t;let r=this.promise.then(n=>{let{subscribers:o}=this;this.subscribers=null,this.settlement={status:"fulfilled",value:n},o?.forEach(({resolve:i})=>{i(n)})});"catch"in r&&r.catch(n=>{let{subscribers:o}=this;this.subscribers=null,this.settlement={status:"rejected",reason:n},o?.forEach(({reject:i})=>{i(n)})})}subscribe(){let t,r,{settlement:n}=this;if(n===null){if(this.subscribers===null)throw new Error("Unpromise settled but still has subscribers");let o=Bc();this.subscribers=$c(this.subscribers,o),t=o.promise,r=()=>{this.subscribers!==null&&(this.subscribers=zc(this.subscribers,o))}}else{let{status:o}=n;o==="fulfilled"?t=Promise.resolve(n.value):t=Promise.reject(n.reason),r=Jc}return Object.assign(t,{unsubscribe:r})}then(t,r){let n=this.subscribe(),{unsubscribe:o}=n;return Object.assign(n.then(t,r),{unsubscribe:o})}catch(t){let r=this.subscribe(),{unsubscribe:n}=r;return Object.assign(r.catch(t),{unsubscribe:n})}finally(t){let r=this.subscribe(),{unsubscribe:n}=r;return Object.assign(r.finally(t),{unsubscribe:n})}static proxy(t){let r=ye.getSubscribablePromise(t);return typeof r<"u"?r:ye.createSubscribablePromise(t)}static createSubscribablePromise(t){let r=new ye(t);return Ct.set(t,r),Ct.set(r,r),r}static getSubscribablePromise(t){return Ct.get(t)}static resolve(t){let r=typeof t=="object"&&t!==null&&"then"in t&&typeof t.then=="function"?t:Promise.resolve(t);return ye.proxy(r).subscribe()}static async any(t){let r=(Array.isArray(t)?t:[...t]).map(ye.resolve);try{return await Promise.any(r)}finally{r.forEach(({unsubscribe:n})=>{n()})}}static async race(t){let r=(Array.isArray(t)?t:[...t]).map(ye.resolve);try{return await Promise.race(r)}finally{r.forEach(({unsubscribe:n})=>{n()})}}static async raceReferences(t){let r=t.map(Wc);try{return await Promise.race(r)}finally{for(let n of r)n.unsubscribe()}}};function Wc(e){return jt.proxy(e).then(()=>[e])}function Bc(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}function $c(e,t){return[...e,t]}function Kc(e,t){return[...e.slice(0,t),...e.slice(t+1)]}function zc(e,t){let r=e.indexOf(t);return r!==-1?Kc(e,r):e}var $s,Ks,zs,Vs;(Ks=($s=Symbol).dispose)!==null&&Ks!==void 0||($s.dispose=Symbol());(Vs=(zs=Symbol).asyncDispose)!==null&&Vs!==void 0||(zs.asyncDispose=Symbol());function Vc(e,t){let r=e,n=r[Symbol.dispose];return r[Symbol.dispose]=()=>{t(),n?.call(r)},r}function Zs(e,t){let r=e,n=r[Symbol.asyncDispose];return r[Symbol.asyncDispose]=async()=>{await t(),await n?.call(r)},r}var Ht=Symbol();function ei(e){let t=null;return Vc({start(){if(t)throw new Error("Timer already started");return new Promise(r=>{t=setTimeout(()=>r(Ht),e)})}},()=>{t&&clearTimeout(t)})}function We(){var e=typeof SuppressedError=="function"?SuppressedError:function(o,i){var s=Error();return s.name="SuppressedError",s.error=o,s.suppressed=i,s},t={},r=[];function n(o,i){if(i!=null){if(Object(i)!==i)throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");if(o)var s=i[Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose")];if(s===void 0&&(s=i[Symbol.dispose||Symbol.for("Symbol.dispose")],o))var a=s;if(typeof s!="function")throw new TypeError("Object is not disposable.");a&&(s=function(){try{a.call(i)}catch(u){return Promise.reject(u)}}),r.push({v:i,d:s,a:o})}else o&&r.push({d:i,a:o});return i}return{e:t,u:n.bind(null,!1),a:n.bind(null,!0),d:function(){var i,s=this.e,a=0;function c(){for(;i=r.pop();)try{if(!i.a&&a===1)return a=0,r.push(i),Promise.resolve().then(c);if(i.d){var l=i.d.call(i.v);if(i.a)return a|=2,Promise.resolve(l).then(c,u)}else a|=1}catch(p){return u(p)}if(a===1)return s!==t?Promise.reject(s):Promise.resolve();if(s!==t)throw s}function u(l){return s=s!==t?new e(l,s):l,c()}return c()}}}function Ft(e,t){this.v=e,this.k=t}function Q(e){return new Ft(e,0)}function ie(e){return function(){return new Fe(e.apply(this,arguments))}}function Fe(e){var t,r;function n(i,s){try{var a=e[i](s),c=a.value,u=c instanceof Ft;Promise.resolve(u?c.v:c).then(function(l){if(u){var p=i==="return"?"return":"next";if(!c.k||l.done)return n(p,l);l=e[p](l).value}o(a.done?"return":"normal",l)},function(l){n("throw",l)})}catch(l){o("throw",l)}}function o(i,s){switch(i){case"return":t.resolve({value:s,done:!0});break;case"throw":t.reject(s);break;default:t.resolve({value:s,done:!1})}(t=t.next)?n(t.key,t.arg):r=null}this._invoke=function(i,s){return new Promise(function(a,c){var u={key:i,arg:s,resolve:a,reject:c,next:null};r?r=r.next=u:(t=r=u,n(i,s))})},typeof e.return!="function"&&(this.return=void 0)}Fe.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Fe.prototype.next=function(e){return this._invoke("next",e)},Fe.prototype.throw=function(e){return this._invoke("throw",e)},Fe.prototype.return=function(e){return this._invoke("return",e)};function Jt(e){let t=e[Symbol.asyncIterator]();return t[Symbol.asyncDispose]?t:Zs(t,async()=>{var r;await((r=t.return)===null||r===void 0?void 0:r.call(t))})}function Gc(e,t){return Dt.apply(this,arguments)}function Dt(){return Dt=ie(function*(e,t){try{var r=We();let n=r.a(Jt(e)),o,i=r.u(ei(t.gracePeriodMs)),s=t.count,a=new Promise(()=>{});for(;;){if(o=yield Q(jt.race([n.next(),a])),o===Ht&&Hc(),o.done)return o.value;yield o.value,--s===0&&(a=i.start()),o=null}}catch(n){r.e=n}finally{yield Q(r.d())}}),Dt.apply(this,arguments)}function Gs(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}function Yc(e,t){let r=e[Symbol.asyncIterator](),n="idle";function o(){n="done",t=()=>{}}function i(){n==="idle"&&(n="pending",r.next().then(s=>{if(s.done){n="done",t({status:"return",value:s.value}),o();return}n="idle",t({status:"yield",value:s.value})}).catch(s=>{t({status:"error",error:s}),o()}))}return{pull:i,destroy:async()=>{var s;o(),await((s=r.return)===null||s===void 0?void 0:s.call(r))}}}function Qc(){let e="idle",t=Gs(),r=[],n=new Set,o=[];function i(s){if(e!=="pending")return;let a=Yc(s,c=>{if(e==="pending"){switch(c.status){case"yield":o.push([a,c]);break;case"return":n.delete(a);break;case"error":o.push([a,c]),n.delete(a)}t.resolve()}});n.add(a),a.pull()}return{add(s){switch(e){case"idle":r.push(s);break;case"pending":i(s)}},[Symbol.asyncIterator](){return ie(function*(){try{var s=We();if(e!=="idle")throw new Error("Cannot iterate twice");for(e="pending",s.a(Zs({},async()=>{e="done";let a=[];if(await Promise.all(Array.from(n.values()).map(async c=>{try{await c.destroy()}catch(u){a.push(u)}})),o.length=0,n.clear(),t.resolve(),a.length>0)throw new AggregateError(a)}));r.length>0;)i(r.shift());for(;n.size>0;){for(yield Q(t.promise);o.length>0;){let[a,c]=o.shift();switch(c.status){case"yield":yield c.value,a.pull();break;case"error":throw c.error}}t=Gs()}}catch(a){s.e=a}finally{yield Q(s.d())}})()}}}function ti(e){let t=e[Symbol.asyncIterator]();return new ReadableStream({async cancel(){var r;await((r=t.return)===null||r===void 0?void 0:r.call(t))},async pull(r){let n=await t.next();if(n.done){r.close();return}r.enqueue(n.value)}})}var Je=Symbol("ping");function ri(e,t){return Ut.apply(this,arguments)}function Ut(){return Ut=ie(function*(e,t){try{var r=We();let o=r.a(Jt(e)),i,s=o.next();for(;;)try{var n=We();let a=n.u(ei(t));if(i=yield Q(jt.race([s,a.start()])),i===Ht){yield Je;continue}if(i.done)return i.value;s=o.next(),yield i.value,i=null}catch(a){n.e=a}finally{n.d()}}catch(o){r.e=o}finally{yield Q(r.d())}}),Ut.apply(this,arguments)}function kt(e){var t,r,n,o=2;for(typeof Symbol<"u"&&(r=Symbol.asyncIterator,n=Symbol.iterator);o--;){if(r&&(t=e[r])!=null)return t.call(e);if(n&&(t=e[n])!=null)return new it(t.call(e));r="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function it(e){function t(r){if(Object(r)!==r)return Promise.reject(new TypeError(r+" is not an object."));var n=r.done;return Promise.resolve(r.value).then(function(o){return{value:o,done:n}})}return it=function(n){this.s=n,this.n=n.next},it.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(n){var o=this.s.return;return o===void 0?Promise.resolve({value:n,done:!0}):t(o.apply(this.s,arguments))},throw:function(n){var o=this.s.return;return o===void 0?Promise.reject(n):t(o.apply(this.s,arguments))}},new it(e)}var Xc=0,qc=1,Zc=0,eu=1,tu=0,ru=1,nu=2;function ni(e){return(F(e)||nt(e))&&typeof e?.then=="function"&&typeof e?.catch=="function"}var ou=class extends Error{constructor(e){super("Max depth reached at path: "+e.join(".")),this.path=e}};function su(e){return Lt.apply(this,arguments)}function Lt(){return Lt=ie(function*(e){let{data:t}=e,r=0,n=0,o=Qc();function i(g){let v=r++,T=g(v);return o.add(T),v}function s(g,v){return i((function(){var T=ie(function*(E){let P=c(v);P&&(g.catch(H=>{var re;(re=e.onError)===null||re===void 0||re.call(e,{error:H,path:v})}),g=Promise.reject(P));try{let H=yield Q(g);yield[E,Zc,l(H,v)]}catch(H){var L,K;(L=e.onError)===null||L===void 0||L.call(e,{error:H,path:v}),yield[E,eu,(K=e.formatError)===null||K===void 0?void 0:K.call(e,{error:H,path:v})]}});return function(E){return T.apply(this,arguments)}})())}function a(g,v){return i((function(){var T=ie(function*(E){try{var P=We();let H=c(v);if(H)throw H;let re=P.a(Jt(g));try{for(;;){let R=yield Q(re.next());if(R.done){yield[E,tu,l(R.value,v)];break}yield[E,ru,l(R.value,v)]}}catch(R){var L,K;(L=e.onError)===null||L===void 0||L.call(e,{error:R,path:v}),yield[E,nu,(K=e.formatError)===null||K===void 0?void 0:K.call(e,{error:R,path:v})]}}catch(H){P.e=H}finally{yield Q(P.d())}});return function(E){return T.apply(this,arguments)}})())}function c(g){return e.maxDepth&&g.length>e.maxDepth?new ou(g):null}function u(g,v){if(ni(g))return[Xc,s(g,v)];if(Le(g)){if(e.maxDepth&&v.length>=e.maxDepth)throw new Error("Max depth reached");return[qc,a(g,v)]}return null}function l(g,v){if(g===void 0)return[[]];let T=u(g,v);if(T)return[[n],[null,...T]];if(!Fc(g))return[[g]];let E=Y(),P=[];for(let[L,K]of Object.entries(g)){let H=u(K,[...v,L]);if(!H){E[L]=K;continue}E[L]=n,P.push([L,...H])}return[[E],...P]}let p=Y();for(let[g,v]of Object.entries(t))p[g]=l(v,[g]);yield p;let m=o;e.pingMs&&(m=ri(o,e.pingMs));var y=!1,d=!1,f;try{for(var w=kt(m),b;y=!(b=yield Q(w.next())).done;y=!1)yield b.value}catch(g){d=!0,f=g}finally{try{y&&w.return!=null&&(yield Q(w.return()))}finally{if(d)throw f}}}),Lt.apply(this,arguments)}function iu(e){let t=ti(su(e)),{serialize:r}=e;return r&&(t=t.pipeThrough(new TransformStream({transform(n,o){n===Je?o.enqueue(Je):o.enqueue(r(n))}}))),t.pipeThrough(new TransformStream({transform(n,o){n===Je?o.enqueue(" "):o.enqueue(JSON.stringify(n)+`
8
- `)}})).pipeThrough(new TextEncoderStream)}function au(e){var t={},r=!1;function n(o,i){return r=!0,i=new Promise(function(s){s(e[o](i))}),{done:!1,value:new Ft(i,1)}}return t[typeof Symbol<"u"&&Symbol.iterator||"@@iterator"]=function(){return this},t.next=function(o){return r?(r=!1,o):n("next",o)},typeof e.throw=="function"&&(t.throw=function(o){if(r)throw r=!1,o;return n("throw",o)}),typeof e.return=="function"&&(t.return=function(o){return r?(r=!1,o):n("return",o)}),t}var cu="ping",uu="serialized-error",lu="connected",du="return";function fu(e){var t,r,n,o,i;let{serialize:s=_s}=e,a={enabled:(t=(r=e.ping)===null||r===void 0?void 0:r.enabled)!==null&&t!==void 0?t:!1,intervalMs:(n=(o=e.ping)===null||o===void 0?void 0:o.intervalMs)!==null&&n!==void 0?n:1e3},c=(i=e.client)!==null&&i!==void 0?i:{};if(a.enabled&&c.reconnectAfterInactivityMs&&a.intervalMs>c.reconnectAfterInactivityMs)throw new Error(`Ping interval must be less than client reconnect interval to prevent unnecessary reconnection - ping.intervalMs: ${a.intervalMs} client.reconnectAfterInactivityMs: ${c.reconnectAfterInactivityMs}`);function u(){return l.apply(this,arguments)}function l(){return l=ie(function*(){yield{event:lu,data:JSON.stringify(c)};let y=e.data;e.emitAndEndImmediately&&(y=Gc(y,{count:1,gracePeriodMs:1})),a.enabled&&a.intervalMs!==1/0&&a.intervalMs>0&&(y=ri(y,a.intervalMs));let d,f;var w=!1,b=!1,g;try{for(var v=kt(y),T;w=!(T=yield Q(v.next())).done;w=!1){if(d=T.value,d===Je){yield{event:cu,data:""};continue}f=Tt(d)?{id:d[0],data:d[1]}:{data:d},f.data=JSON.stringify(s(f.data)),yield f,d=null,f=null}}catch(E){b=!0,g=E}finally{try{w&&v.return!=null&&(yield Q(v.return()))}finally{if(b)throw g}}}),l.apply(this,arguments)}function p(){return m.apply(this,arguments)}function m(){return m=ie(function*(){try{yield*au(kt(u())),yield{event:du,data:""}}catch(f){var y,d;if(Mt(f))return;let w=B(f),b=(y=(d=e.formatError)===null||d===void 0?void 0:d.call(e,{error:w}))!==null&&y!==void 0?y:null;yield{event:uu,data:JSON.stringify(s(b))}}}),m.apply(this,arguments)}return ti(p()).pipeThrough(new TransformStream({transform(y,d){"event"in y&&d.enqueue(`event: ${y.event}
9
- `),"data"in y&&d.enqueue(`data: ${y.data}
10
- `),"id"in y&&d.enqueue(`id: ${y.id}
11
- `),"comment"in y&&d.enqueue(`: ${y.comment}
12
- `),d.enqueue(`
13
-
14
- `)}})).pipeThrough(new TextEncoderStream)}var pu={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no",Connection:"keep-alive"};function xt(e){return oe(ie(function*(){throw e}))}function mu(e){let t=new AbortController;return{signal:Ts([e,t.signal]),controller:t}}var yu={mutation:["POST"],query:["GET"],subscription:["GET"]},hu={mutation:["POST"],query:["GET","POST"],subscription:["GET","POST"]};function He(e){var t,r,n;let{ctx:o,info:i,responseMeta:s,untransformedJSON:a,errors:c=[],headers:u}=e,l=a?xs(a):200,p=!a,m=p?[]:Array.isArray(a)?a:[a],y=(t=s?.({ctx:o,info:i,paths:i?.calls.map(d=>d.path),data:m,errors:c,eagerGeneration:p,type:(r=i==null||(n=i.calls.find(d=>{var f;return(f=d.procedure)===null||f===void 0?void 0:f._def.type}))===null||n===void 0||(n=n.procedure)===null||n===void 0?void 0:n._def.type)!==null&&r!==void 0?r:"unknown"}))!==null&&t!==void 0?t:{};if(y.headers)if(y.headers instanceof Headers)for(let[d,f]of y.headers.entries())u.append(d,f);else for(let[d,f]of Object.entries(y.headers))if(Array.isArray(f))for(let w of f)u.append(d,w);else typeof f=="string"&&u.set(d,f);return y.status&&(l=y.status),{status:l}}function gu(e,t){let{router:r,req:n,onError:o}=t.opts,i=B(e);o?.({error:i,path:t.path,input:t.input,ctx:t.ctx,type:t.type,req:n});let s={error:se({config:r._def._config,error:i,type:t.type,path:t.path,input:t.input,ctx:t.ctx})},a=me(r._def._config,s);return{error:i,untransformedJSON:s,body:JSON.stringify(a)}}function Ys(e){return F(e)?Le(e)?!0:Object.values(e).some(ni)||Object.values(e).some(Le):!1}async function oi(e){var t,r,n,o,i,s;let{router:a,req:c}=e,u=new Headers([["vary","trpc-accept, accept"]]),l=a._def._config,p=new URL(c.url);if(c.method==="HEAD")return new Response(null,{status:204});let m=(t=(r=e.allowBatching)!==null&&r!==void 0?r:(n=e.batching)===null||n===void 0?void 0:n.enabled)!==null&&t!==void 0?t:!0,y=((o=e.allowMethodOverride)!==null&&o!==void 0?o:!1)&&c.method==="POST",d=await oe(async()=>{try{return[void 0,await jc({req:c,path:decodeURIComponent(e.path),router:a,searchParams:p.searchParams,headers:e.req.headers,url:p,maxBatchSize:e.maxBatchSize})]}catch(T){return[B(T),void 0]}}),f=oe(()=>{let T;return{valueOrUndefined:()=>{if(T)return T[1]},value:()=>{let[E,P]=T;if(E)throw E;return P},create:async E=>{if(T)throw new Error("This should only be called once - report a bug in tRPC");try{T=[void 0,await e.createContext({info:E})]}catch(P){T=[B(P),void 0]}}}}),w=y?hu:yu,b=Qs(c.headers)==="application/jsonl",g=(i=(s=l.sse)===null||s===void 0?void 0:s.enabled)!==null&&i!==void 0?i:!0;try{let[T,E]=d;if(T)throw T;if(E.isBatchCall&&!m)throw new O({code:"BAD_REQUEST",message:"Batching is not enabled on the server"});if(b&&!E.isBatchCall)throw new O({message:"Streaming requests must be batched (you can do a batch of 1)",code:"BAD_REQUEST"});await f.create(E);let P=E.calls.map(async R=>{let M=R.procedure,I=mu(e.req.signal);try{if(e.error)throw e.error;if(!M)throw new O({code:"NOT_FOUND",message:`No procedure found on path "${R.path}"`});if(!w[M._def.type].includes(c.method))throw new O({code:"METHOD_NOT_SUPPORTED",message:`Unsupported ${c.method}-request to ${M._def.type} procedure at path "${R.path}"`});if(M._def.type==="subscription"){var k;if(E.isBatchCall)throw new O({code:"BAD_REQUEST",message:"Cannot batch subscription calls"});if(!((k=l.sse)===null||k===void 0)&&k.maxDurationMs){let G=function(){clearTimeout(j),I.signal.removeEventListener("abort",G),I.controller.abort()},j=setTimeout(G,l.sse.maxDurationMs);I.signal.addEventListener("abort",G)}}return[void 0,{data:await M({path:R.path,getRawInput:R.getRawInput,ctx:f.value(),type:M._def.type,signal:I.signal,batchIndex:R.batchIndex}),signal:M._def.type==="subscription"?I.signal:void 0}]}catch(G){var D,U,z;let j=B(G),W=R.result();return(D=e.onError)===null||D===void 0||D.call(e,{error:j,path:R.path,input:W,ctx:f.valueOrUndefined(),type:(U=(z=R.procedure)===null||z===void 0?void 0:z._def.type)!==null&&U!==void 0?U:"unknown",req:e.req}),[j,void 0]}});if(!E.isBatchCall){let[R]=E.calls,[M,I]=await P[0];switch(E.type){case"unknown":case"mutation":case"query":{if(u.set("content-type","application/json"),Ys(I?.data))throw new O({code:"UNSUPPORTED_MEDIA_TYPE",message:"Cannot use stream-like response in non-streaming request - use httpBatchStreamLink"});let k=M?{error:se({config:l,ctx:f.valueOrUndefined(),error:M,input:R.result(),path:R.path,type:E.type})}:{result:{data:I.data}},D=He({ctx:f.valueOrUndefined(),info:E,responseMeta:e.responseMeta,errors:M?[M]:[],headers:u,untransformedJSON:[k]});return new Response(JSON.stringify(me(l,k)),{status:D.status,headers:u})}case"subscription":{let k=oe(()=>M?xt(M):g?!st(I.data)&&!Le(I.data)?xt(new O({message:`Subscription ${R.path} did not return an observable or a AsyncGenerator`,code:"INTERNAL_SERVER_ERROR"})):st(I.data)?Pt(I.data,e.req.signal):I.data:xt(new O({code:"METHOD_NOT_SUPPORTED",message:'Missing experimental flag "sseSubscriptions"'}))),D=fu(S(S({},l.sse),{},{data:k,serialize:j=>l.transformer.output.serialize(j),formatError(j){var W,ve,be;let Tr=B(j.error),Rr=R?.result(),Ar=R?.path,Or=(W=R==null||(ve=R.procedure)===null||ve===void 0?void 0:ve._def.type)!==null&&W!==void 0?W:"unknown";return(be=e.onError)===null||be===void 0||be.call(e,{error:Tr,path:Ar,input:Rr,ctx:f.valueOrUndefined(),req:e.req,type:Or}),se({config:l,ctx:f.valueOrUndefined(),error:Tr,input:Rr,path:Ar,type:Or})}}));for(let[j,W]of Object.entries(pu))u.set(j,W);let U=He({ctx:f.valueOrUndefined(),info:E,responseMeta:e.responseMeta,errors:[],headers:u,untransformedJSON:null}),z=I?.signal,G=D;if(z){let j=D.getReader(),W=()=>{j.cancel()};z.aborted?W():z.addEventListener("abort",W,{once:!0}),G=new ReadableStream({async pull(ve){let be=await j.read();be.done?(z.removeEventListener("abort",W),ve.close()):ve.enqueue(be.value)},cancel(){return z.removeEventListener("abort",W),j.cancel()}})}return new Response(G,{headers:u,status:U.status})}}}if(E.accept==="application/jsonl"){u.set("content-type","application/json"),u.set("transfer-encoding","chunked");let R=He({ctx:f.valueOrUndefined(),info:E,responseMeta:e.responseMeta,errors:[],headers:u,untransformedJSON:null}),M=iu(S(S({},l.jsonl),{},{maxDepth:1/0,data:P.map(async(I,k)=>{let[D,U]=await I,z=E.calls[k];if(D){var G,j;return{error:se({config:l,ctx:f.valueOrUndefined(),error:D,input:z.result(),path:z.path,type:(G=(j=z.procedure)===null||j===void 0?void 0:j._def.type)!==null&&G!==void 0?G:"unknown"})}}let W=st(U.data)?Pt(U.data,e.req.signal):Promise.resolve(U.data);return{result:Promise.resolve({data:W})}}),serialize:I=>l.transformer.output.serialize(I),onError:I=>{var k,D;(k=e.onError)===null||k===void 0||k.call(e,{error:B(I.error),path:void 0,input:void 0,ctx:f.valueOrUndefined(),req:e.req,type:(D=E?.type)!==null&&D!==void 0?D:"unknown"})},formatError(I){var k,D;let U=E?.calls[I.path[0]],z=B(I.error),G=U?.result(),j=U?.path,W=(k=U==null||(D=U.procedure)===null||D===void 0?void 0:D._def.type)!==null&&k!==void 0?k:"unknown";return se({config:l,ctx:f.valueOrUndefined(),error:z,input:G,path:j,type:W})}}));return new Response(M,{headers:u,status:R.status})}u.set("content-type","application/json");let L=(await Promise.all(P)).map(R=>{let[M,I]=R;return M?R:Ys(I.data)?[new O({code:"UNSUPPORTED_MEDIA_TYPE",message:"Cannot use stream-like response in non-streaming request - use httpBatchStreamLink"}),void 0]:R}),K=L.map(([R,M],I)=>{let k=E.calls[I];if(R){var D,U;return{error:se({config:l,ctx:f.valueOrUndefined(),error:R,input:k.result(),path:k.path,type:(D=(U=k.procedure)===null||U===void 0?void 0:U._def.type)!==null&&D!==void 0?D:"unknown"})}}return{result:{data:M.data}}}),H=L.map(([R])=>R).filter(Boolean),re=He({ctx:f.valueOrUndefined(),info:E,responseMeta:e.responseMeta,untransformedJSON:K,errors:H,headers:u});return new Response(JSON.stringify(me(l,K)),{status:re.status,headers:u})}catch(T){var v;let[E,P]=d,L=f.valueOrUndefined(),{error:K,untransformedJSON:H,body:re}=gu(T,{opts:e,ctx:f.valueOrUndefined(),type:(v=P?.type)!==null&&v!==void 0?v:"unknown"}),R=He({ctx:L,info:P,responseMeta:e.responseMeta,untransformedJSON:H,errors:[K],headers:u});return new Response(re,{status:R.status,headers:u})}}import{IncomingMessage as wu}from"node:http";function Eu(e,t){if("body"in e)return e.body===void 0?void 0:typeof e.body=="string"||e.body instanceof wu?e.body:JSON.stringify(e.body);let r=0,n=!1;return new ReadableStream({start(o){let i=a=>{if(r+=a.length,!t.maxBodySize||r<=t.maxBodySize){o.enqueue(new Uint8Array(a.buffer,a.byteOffset,a.byteLength));return}o.error(new O({code:"PAYLOAD_TOO_LARGE"})),n=!0,e.off("data",i),e.off("end",s)},s=()=>{n||(n=!0,e.off("data",i),e.off("end",s),o.close())};e.on("data",i),e.on("end",s)},cancel(){e.destroy()}})}function Wt(e){try{var t,r;let n=e.headers[":scheme"]&&e.headers[":scheme"]==="https"||e.socket&&"encrypted"in e.socket&&e.socket.encrypted?"https:":"http:",o=(t=(r=e.headers.host)!==null&&r!==void 0?r:e.headers[":authority"])!==null&&t!==void 0?t:"localhost";return new URL(e.url,`${n}//${o}`)}catch(n){throw new O({code:"BAD_REQUEST",message:"Invalid URL",cause:n})}}function Su(e){let t=new Headers;for(let r in e){let n=e[r];if(!(typeof r=="string"&&r.startsWith(":")))if(Array.isArray(n))for(let o of n)t.append(r,o);else n!=null&&t.append(r,n)}return t}function vu(e,t,r){let n=new AbortController,o=()=>{t.off("close",o),e.off("aborted",o),n.abort()};t.once("close",o),e.once("aborted",o);let i=Wt(e),s={headers:Su(e.headers),method:e.method,signal:n.signal};return e.method!=="GET"&&e.method!=="HEAD"&&(s.body=Eu(e,r),s.duplex="half"),new Request(i,s)}async function bu(e,t){e.write(t)===!1&&await new Promise((r,n)=>{let o=a=>{n(a),s()},i=()=>{r(),s()},s=()=>{e.off("error",o),e.off("drain",i)};e.once("error",o),e.once("drain",i)})}async function _u(e){let{res:t}=e;try{let r=new WritableStream({async write(n){var o;await bu(t,n),(o=t.flush)===null||o===void 0||o.call(t)}});await e.body.pipeTo(r,{signal:e.signal})}catch(r){if(Mt(r))return;throw r}}async function Tu(e){let{response:t,rawResponse:r}=e;r.statusCode===200&&(r.statusCode=t.status);for(let[o,i]of t.headers)o.toLowerCase()!=="set-cookie"&&r.setHeader(o,i);let n=t.headers.getSetCookie();n.length>0&&r.setHeader("set-cookie",n);try{t.body&&await _u({res:r,signal:e.request.signal,body:t.body})}catch(o){throw r.headersSent||(r.statusCode=500),o}finally{r.end()}}function Bt(e){return t=>{var r;let{res:n,req:o}=e,i=B(t),s=se({config:e.router._def._config,error:i,type:"unknown",path:void 0,input:void 0,ctx:void 0});(r=e.onError)===null||r===void 0||r.call(e,{req:o,error:i,type:"unknown",path:void 0,input:void 0,ctx:void 0});let a=me(e.router._def._config,{error:s});n.statusCode=s.data.httpStatus,n.end(JSON.stringify(a))}}async function si(e){return new Promise(t=>{var r;let n=(r=e.middleware)!==null&&r!==void 0?r:((o,i,s)=>s());return e.res.once("finish",()=>{t()}),n(e.req,e.res,o=>{oe(async()=>{var i;let s=vu(e.req,e.res,{maxBodySize:(i=e.maxBodySize)!==null&&i!==void 0?i:null}),a=async c=>{var u;return await((u=e.createContext)===null||u===void 0?void 0:u.call(e,S(S({},e),c)))};await Tu({request:s,response:await oi(S(S({},e),{},{req:s,error:o?B(o):null,createContext:a,onError(c){var u;e==null||(u=e.onError)===null||u===void 0||u.call(e,S(S({},c),{},{req:e.req}))}})),rawResponse:e.res})}).catch(Bt(e))})})}function Ru(e){var t;let r=((t=e.basePath)!==null&&t!==void 0?t:"/").length;return(n,o)=>{let i="";oe(async()=>{i=Wt(n).pathname.slice(r),await si(S(S({},e),{},{req:n,res:o,path:i}))}).catch(Bt(S({req:n,res:o,path:i},e)))}}function ii(e){return Ru(e)}function x(e,t,r,n={}){if(e.headersSent)return;let o=Buffer.from(JSON.stringify(r),"utf8");e.writeHead(t,{"Content-Type":"application/json; charset=utf-8","Content-Length":String(o.length),...n}),e.end(o)}function A(e,t,r,n,o={}){x(e,t,{ok:!1,code:r,message:n},o)}function he(e,t,r){x(e,t,r,{"Cache-Control":"no-store"})}function V(e,t){A(e,405,"method-not-allowed",`Use ${t}`,{Allow:t})}function $t(e){let t=e.headers["content-length"];if(t===void 0)return null;let r=Number(t);return Number.isFinite(r)&&r>=0?r:null}function Kt(e,t,r,n,o,i){let s=0;e.on("data",a=>{s+=a.length,s>i&&e.socket.destroy()}),e.on("error",()=>{}),e.resume(),A(t,r,n,o)}async function ae(e,t){let r=()=>(Kt(e,t,413,"too-large","Body exceeds 8192 bytes",8192),null);if(($t(e)??0)>8192)return r();let n=await new Promise((i,s)=>{let a=[],c=0,u=y=>{if(c+=y.length,c<=8192){a.push(y);return}m(),i(null)},l=()=>{m(),i(Buffer.concat(a))},p=y=>{m(),s(y)},m=()=>{e.off("data",u),e.off("end",l),e.off("error",p)};e.on("data",u),e.on("end",l),e.on("error",p)});if(n===null)return r();if(n.length===0)return{};let o;try{o=JSON.parse(n.toString("utf8"))}catch{return A(t,400,"bad-json","Body is not valid JSON"),null}return o===null||typeof o!="object"||Array.isArray(o)?(A(t,400,"bad-json","Body must be a JSON object"),null):o}import*as ui from"net";import{execFile as Mu}from"child_process";import{promisify as ju}from"util";var ci="#--tasklist--#",Au=`netstat -ano; echo '${ci}'; MSYS_NO_PATHCONV=1 tasklist /FO CSV /NH`,Ou=new Set(["0.0.0.0:0","[::]:0","*:*"]),zt=new Set(["0.0.0.0","127.0.0.1","[::]","[::1]","*"]);function Iu(e){let t=new Map;for(let r of e.split(`
15
- `)){let n=/^"([^"]*)","(\d+)"/.exec(r.trim());n&&t.set(Number(n[2]),n[1].replace(/\.exe$/i,""))}return t}function Pu(e){let[t,r]=e.split(ci),n=r?Iu(r):new Map,o=new Map;for(let i of t.split(`
16
- `)){let s=i.trim().split(/\s+/);if(s.length<4||s[0]!=="TCP"||!Ou.has(s[2]))continue;let a=s[1],c=a.lastIndexOf(":");if(c<0)continue;let u=Number(a.slice(c+1));if(!Number.isInteger(u)||u<1024)continue;let l=a.slice(0,c);if(!zt.has(l))continue;let p=Number(s[s.length-1]),m=n.get(p)??null,y=o.get(u);(!y||!y.process&&m)&&o.set(u,{port:u,address:l,process:m})}return[...o.values()].sort((i,s)=>i.port-s.port)}function ai(e){let t=new Map;for(let r of e.split(`
17
- `)){let n=r.trim().split(/\s+/);if(n.length<4)continue;let o=n[3],i=o.lastIndexOf(":");if(i<0)continue;let s=Number(o.slice(i+1));if(!Number.isInteger(s)||s<1024)continue;let a=o.slice(0,i);if(!zt.has(a))continue;let c=/users:\(\("([^"]+)"/.exec(r),u=t.get(s);(!u||!u.process&&c)&&t.set(s,{port:s,address:a,process:c?c[1]:null})}return[...t.values()].sort((r,n)=>r.port-n.port)}var Cu="lsof -nP -iTCP -sTCP:LISTEN -F cn";function xu(e){let t=new Map,r=null;for(let n of e.split(`
18
- `)){let o=n.trim(),i=o[0],s=o.slice(1);if(i==="p")r=null;else if(i==="c")r=s||null;else if(i==="n"){let a=s.lastIndexOf(":");if(a<0)continue;let c=Number(s.slice(a+1));if(!Number.isInteger(c)||c<1024)continue;let u=s.slice(0,a);if(!zt.has(u))continue;let l=t.get(c);(!l||!l.process&&r)&&t.set(c,{port:c,address:u,process:r})}}return[...t.values()].sort((n,o)=>n.port-o.port)}var Nu="0A",Du=new Map([["00000000","0.0.0.0"],["0100007F","127.0.0.1"],["00000000000000000000000000000000","[::]"],["00000000000000000000000001000000","[::1]"]]);function Uu(e){let t=new Map;for(let r of e.split(`
19
- `)){let n=r.trim().split(/\s+/);if(n.length<4||n[3]!==Nu)continue;let[o,i]=n[1].split(":"),s=Du.get(o?.toUpperCase()??"");if(!s)continue;let a=parseInt(i,16);!Number.isInteger(a)||a<1024||t.has(a)||t.set(a,{port:a,address:s,process:null})}return[...t.values()].sort((r,n)=>r.port-n.port)}var ku="cat /proc/net/tcp /proc/net/tcp6 2>/dev/null";function Lu(e){return e==="win32"?[{command:Au,parse:Pu}]:e==="darwin"?[{command:Cu,parse:xu}]:[{command:"ss -ltnpH",parse:ai},{command:"ss -ltnH",parse:ai},{command:ku,parse:Uu}]}async function at(e,t){let r="no probe produced output";for(let n of Lu(e))try{let o=await t(n.command);if(o.trim()!=="")return{ports:n.parse(o)}}catch(o){r=o.message}return{ports:[],error:r}}var ct=N("port-forward"),Hu=ju(Mu),li="/forward",Fu="/api/forward/ports",Ju=64,Wu=4004;function Bu(e){let t;try{t=new URL(e,"http://localhost")}catch{return null}let r=Number(t.searchParams.get("port"));if(!Number.isInteger(r)||r<1024||r>65535)return null;let n=t.searchParams.get("host")??"127.0.0.1";return n!=="127.0.0.1"&&n!=="localhost"&&n!=="::1"?null:{host:n,port:r}}async function $u(){if(process.platform==="win32")return ct.warn("port discovery is not implemented for a Windows-hosted daemon"),[];let{ports:e,error:t}=await at(process.platform,async r=>(await Hu("sh",["-c",r],{timeout:3e3})).stdout);return t&&ct.warn(`port discovery unavailable: ${t}`),e}function di(){return{[Fu]:async(e,t)=>{x(t,200,{ok:!0,data:{ports:await $u()}})}}}function fi(){let e=new et.default({noServer:!0}),t=0;return{handleUpgrade:(n,o,i)=>{let s=Bu(n.url??"");if(!s){o.destroy();return}if(t>=Ju){ct.warn(`forward refused (${t} already open): ${s.host}:${s.port}`),o.destroy();return}e.handleUpgrade(n,o,i,a=>{t+=1,Ku(a,s,()=>{t-=1})})},close:()=>e.close()}}function Ku(e,t,r){let n=ui.connect({host:t.host,port:t.port});n.setNoDelay(!0);let o=!1,i=(s,a)=>{if(!o){o=!0,n.destroy();try{e.close(s,a)}catch{}r()}};n.on("connect",()=>{ct.info(`forward open \u2192 ${t.host}:${t.port}`)}),n.on("error",s=>i(Wu,s.code??"error")),n.on("close",()=>i(1e3,"target closed")),n.on("data",s=>{n.pause(),e.send(s,{binary:!0},()=>n.resume())}),e.on("message",s=>{let a=Array.isArray(s)?Buffer.concat(s):Buffer.from(s);n.write(a)}),e.on("close",()=>i(1e3,"client closed")),e.on("error",()=>i(1011,"socket error"))}import*as pi from"crypto";import{readFileSync as zu,writeFileSync as Vu,mkdirSync as Gu,renameSync as Yu}from"fs";import*as mi from"path";var Qu=N("ui-http"),Gt=720*60*60*1e3;function yi(e,t){let r=Array.isArray(e)?e[0]:e;if(r)for(let n of r.split(";")){let o=n.indexOf("=");if(o<0||n.slice(0,o).trim()!==t)continue;let i=n.slice(o+1).trim();try{return decodeURIComponent(i)}catch{return i}}}function hi(e={}){let t=e.ttlMs&&e.ttlMs>0?e.ttlMs:Gt,r=e.now??(()=>Date.now()),n=e.file,o=new Map,i=()=>{if(!n)return;let c;try{c=JSON.parse(zu(n,"utf8"))}catch{return}if(!c||typeof c!="object")return;let u=r();for(let[l,p]of Object.entries(c))typeof p=="number"&&p>u&&o.set(l,p)},s=()=>{if(n)try{Gu(mi.dirname(n),{recursive:!0});let c=`${n}.tmp`;Vu(c,JSON.stringify(Object.fromEntries(o)),{mode:384}),Yu(c,n)}catch(c){Qu.warn(`could not persist UI sessions: ${c.message}`)}},a=()=>{let c=r(),u=!1;for(let[l,p]of o)p<=c&&(o.delete(l),u=!0);return u};return i(),{create(){a();let c=pi.randomBytes(32).toString("hex");return o.set(c,r()+t),s(),c},verify(c){if(!c)return!1;let u=r(),l=!1;for(let[p,m]of o)Z(p,c)&&m>u&&(l=!0);return l},revoke(c){if(!c)return;let u=o.delete(c),l=a();(u||l)&&s()},size(){return a(),o.size}}}var Yt=N("ui-http"),Si="cortex_ui",Qt="/api/ui/login",Xu="/api/ui/logout",Be="/api/ui/session",Xt=250;function gi(e){return Array.isArray(e)?e[0]:e}function wi(e){if(gi(e.headers["x-forwarded-proto"])?.split(",")[0].trim()==="https"||e.socket.encrypted)return!0;let t=(gi(e.headers.host)??"").replace(/:\d+$/,"").toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function Ei(e,t,r){let n=[`${Si}=${e}`,"Path=/","HttpOnly","SameSite=Strict",`Max-Age=${t}`];return r&&n.push("Secure"),n.join("; ")}function qt(e){return yi(e.headers.cookie,Si)}function qu(e,t){return e.redeemCode&&ts(t)?e.redeemCode(t):Z(e.getToken(),t)}function vi(e){let t=Math.floor(e.ttlMs/1e3);return{[Qt]:async(r,n)=>{if(r.method!=="POST")return V(n,"POST");let o=await ae(r,n);if(!o)return;let i=typeof o.token=="string"?o.token.trim():"";if(!qu(e,i))return await new Promise(c=>setTimeout(c,Xt)),Yt.warn("ui login rejected: wrong token or pairing code"),A(n,401,"invalid-token","Invalid token");let s=e.store.create(),a=wi(r);a||Yt.warn("ui login over plain HTTP to a non-loopback host \u2014 the session cookie is issued without Secure, so anyone on this network path can read it. Use HTTPS (a tunnel) for real use."),Yt.info("ui login accepted \u2014 session issued"),x(n,200,{ok:!0},{"Set-Cookie":Ei(s,t,a)})},[Xu]:async(r,n)=>{if(r.method!=="POST")return V(n,"POST");e.store.revoke(qt(r)),x(n,200,{ok:!0},{"Set-Cookie":Ei("",0,wi(r))})},[Be]:async(r,n)=>{x(n,200,{ok:!0,data:{authenticated:await e.authorize(r),tokenLogin:!0}})}}}function bi(e){return{[Be]:async(t,r)=>{x(r,200,{ok:!0,data:{authenticated:await e(t),tokenLogin:!1}})}}}var we=N("ui-http"),Zu="cf-access-jwt-assertion",Zt="/trpc/",el="GET, POST, OPTIONS",tl=`${ke}, content-type, x-session-id, x-file-name, x-cortex-client`,rl="86400",nl=16*1024*1024,ol=new Set(["GET","HEAD","OPTIONS"]);function Ti(e,t,r){let n=e.headers[ke],o=Array.isArray(n)?n[0]:n;return Z(t(),o)||r?.(o)===!0}async function sl(e,t){if(!t)return!1;let r=e.headers[Zu],n=Array.isArray(r)?r[0]:r;return n?t(n):!1}function Ri(e){return async t=>Ti(t,e.getToken,e.matchDeviceToken)||e.verifySession?.(qt(t))?!0:sl(t,e.verifyAccessJwt)}function $e(e){return Array.isArray(e)?e[0]:e}function Ai(e,t){let r=$e(e.headers.origin);if(r===void 0||t?.includes(r))return!0;try{return new URL(r).host===$e(e.headers.host)}catch{return!1}}function il(e,t,r){if(!r||r.length===0)return;let n=$e(e.headers.origin);if(!(!n||!r.includes(n)))return t.setHeader("Access-Control-Allow-Origin",n),t.setHeader("Vary","Origin"),t.setHeader("Access-Control-Allow-Methods",el),t.setHeader("Access-Control-Allow-Headers",tl),t.setHeader("Access-Control-Max-Age",rl),n}function al(e,t,r){if(!r||!fe.existsSync(r)){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("Cortex UI not built");return}let n;try{n=decodeURIComponent((e.url??"/").split("?")[0])}catch{t.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),t.end("Bad request");return}let o=ge.resolve(r),i=ge.resolve(o,"."+(n==="/"?"/index.html":n));if(i!==o&&!i.startsWith(o+ge.sep)){t.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),t.end("Forbidden");return}let s=ge.join(o,"index.html"),a=fe.existsSync(i)&&fe.statSync(i).isFile()?i:s;if(!fe.existsSync(a)){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("Not found");return}let c=fe.createReadStream(a);c.on("error",()=>{t.headersSent||t.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),t.end()}),t.writeHead(200,{"Content-Type":Ze(qe(a))}),c.pipe(t)}function Oi(e){return typeof e.corsOrigins=="function"?e.corsOrigins():e.corsOrigins}function Ii(e){e.writeHead(401,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Unauthorized")}function cl(e,t){let r=e.url??"/",n=r.split("?")[0],o=!!(t.customRoutes&&n in t.customRoutes);return{url:r,pathname:n,isCustomRoute:o,isApi:o||r.startsWith(Zt)}}function ul(e,t,r,n){return e.method==="OPTIONS"&&r.isApi?(t.writeHead(204),t.end(),!0):r.isApi&&!ol.has(e.method??"GET")&&!Ai(e,n)?(we.warn(`ui-http cross-origin request refused: ${e.method} ${r.pathname} from ${$e(e.headers.origin)}`),A(t,403,"cross-origin","Cross-origin request refused"),!0):!1}async function ll(e,t,r,n,o){if(!(o.has(n.pathname)||await r.authorize(e))){we.warn(`ui-http auth rejected (custom route): ${e.method} ${n.url}`),Ii(t);return}try{await r.customRoutes[n.pathname](e,t)}catch(s){we.error(`Custom route ${n.url} error:`,s.message),A(t,500,"internal","Internal server error")}}async function dl(e,t,r,n,o){if(!await n(e)){we.warn(`ui-http auth rejected: ${e.method} ${o}`),Ii(t);return}r()}function fl(e){let t=new Set(e.publicRoutes??[]);return async(r,n,o)=>{let i=Oi(e);il(r,n,i);let s=cl(r,e);if(!ul(r,n,s,i)){if(s.isCustomRoute)return ll(r,n,e,s,t);if(s.isApi)return dl(r,n,o,e.authorize,s.url);al(r,n,e.spaDir)}}}function pl(e,t,r,n,o){if(!Ti(e,n.getToken,n.matchDeviceToken)){we.warn(`forward auth rejected: ${e.url}`),t.write(`HTTP/1.1 401 Unauthorized\r
20
- \r
21
- `),t.destroy();return}o.handleUpgrade(e,t,r)}function ml(e,t,r,n,o){if(!Ai(e,Oi(n))){we.warn(`ui-http cross-origin upgrade refused: ${(e.url??"").split("?")[0]} from ${$e(e.headers.origin)}`),t.write(`HTTP/1.1 403 Forbidden\r
22
- \r
23
- `),t.destroy();return}o.handleUpgrade(e,t,r)}function er(e){let t=ii({router:e.router,basePath:Zt,createContext:({req:s})=>e.createContext?.(s)??{},maxBodySize:nl,middleware:fl(e)}),r=e.portForward===!1?null:fi(),n=e.upgradeRoutes??{};return{handleRequest:t,handleUpgrade:(s,a,c)=>{let u=(s.url??"").split("?")[0];if(r&&u===li)pl(s,a,c,e,r);else if(Object.hasOwn(n,u))ml(s,a,c,e,n[u]);else return!1;return!0},close:()=>{r?.close();for(let s of Object.values(n))s.close()}}}function Pi(e){let t=e.host??"127.0.0.1",r=er(e),n=_i.createServer(r.handleRequest);return n.on("upgrade",(i,s,a)=>{r.handleUpgrade(i,s,a)||s.destroy()}),n.listen(e.port,t,()=>{let i=n.address(),s=i&&typeof i!="string"?i.port:e.port;we.info(`Listening on ${t}:${s}${Zt}`)}),{server:n,close:()=>new Promise(i=>{r.close(),n.closeAllConnections?.(),n.close(()=>i())})}}var tr=N("ui-http"),rr="/api/ui/pair",yl="/api/ui/pairing-code",hl="/api/ui/devices",gl="/api/ui/devices/revoke";function wl(e){let t=e.headers[ke];return Array.isArray(t)?t[0]:t}function El(e,t){return async(r,n)=>{if(r.method!=="POST")return V(n,"POST");let o=await ae(r,n);if(!o)return;let i=typeof o.code=="string"?o.code:"";if(!t.redeem(i))return await new Promise(c=>setTimeout(c,Xt)),tr.warn("app pairing rejected: wrong or expired code"),A(n,401,"invalid-code","Invalid or expired pairing code");let{device:s,token:a}=e.issue(typeof o.name=="string"?o.name:"");tr.info(`app paired: ${s.name} (${s.id})`),x(n,200,{ok:!0,data:{token:a,device:s}})}}function Sl(e){return async(t,r)=>{if(t.method!=="POST")return V(r,"POST");x(r,200,{ok:!0,data:e.create()},{"Cache-Control":"no-store"})}}function vl(e){return async(t,r)=>{if(t.method!=="GET")return V(r,"GET");let n=e.devices.match(wl(t))?.id,o=e.devices.list().map(i=>({...i,current:i.id===n}));x(r,200,{ok:!0,data:{devices:o,pairing:!!e.pairing}},{"Cache-Control":"no-store"})}}function bl(e){return async(t,r)=>{if(t.method!=="POST")return V(r,"POST");let n=await ae(t,r);if(!n)return;let o=typeof n.id=="string"?n.id:"";if(!e.revoke(o))return A(r,404,"not-found","No such device");tr.info(`paired app revoked: ${o}`),x(r,200,{ok:!0})}}function Ci(e){return{...e.pairing?{[rr]:El(e.devices,e.pairing),[yl]:Sl(e.pairing)}:{},[hl]:vl(e),[gl]:bl(e.devices)}}import*as Ke from"crypto";import{mkdirSync as _l,readFileSync as Tl,renameSync as Rl,writeFileSync as Al}from"fs";import*as Ni from"path";var Ol=N("ui-http"),Il=600*1e3,Pl=60,Cl="App";function xi(e){return Ke.createHash("sha256").update(e).digest("hex")}function xl(e){return e.trim().slice(0,Pl)||Cl}function Nl(e){let t=e;return typeof t?.id=="string"&&typeof t.name=="string"&&typeof t.tokenHash=="string"&&typeof t.createdAt=="number"&&typeof t.lastSeenAt=="number"}function Dl(e){if(!e)return[];try{let t=JSON.parse(Tl(e,"utf8"));return Array.isArray(t?.devices)?t.devices.filter(Nl):[]}catch{return[]}}function nr(e){return{id:e.id,name:e.name,createdAt:e.createdAt,lastSeenAt:e.lastSeenAt}}function Di(e={}){let t=e.now??(()=>Date.now()),r=Dl(e.file),n=new Map(r.map(s=>[s.id,s.lastSeenAt])),o=()=>{if(e.file)try{_l(Ni.dirname(e.file),{recursive:!0});let s=`${e.file}.tmp`;Al(s,JSON.stringify({devices:r}),{mode:384}),Rl(s,e.file);for(let a of r)n.set(a.id,a.lastSeenAt)}catch(s){Ol.warn(`could not persist paired devices: ${s.message}`)}},i=s=>{let a=xi(s),c;for(let u of r)Z(u.tokenHash,a)&&(c=u);return c};return{issue(s){let a=t(),c=Ke.randomBytes(32).toString("hex"),u={id:Ke.randomBytes(6).toString("hex"),name:xl(s),createdAt:a,lastSeenAt:a,tokenHash:xi(c)};return r.push(u),o(),{device:nr(u),token:c}},match(s){if(!s)return;let a=i(s);if(a)return a.lastSeenAt=t(),a.lastSeenAt-(n.get(a.id)??0)>=Il&&o(),nr(a)},list(){return r.map(nr)},revoke(s){let a=r.findIndex(c=>c.id===s);return a<0?!1:(r.splice(a,1),n.delete(s),o(),!0)}}}import*as q from"node:fs";import*as ut from"node:path";import*as lt from"node:crypto";import*as Mi from"node:zlib";var Ul=67324752,kl=33639248,Ll=101010256,Ui=8,or=20,ki=33,Li=0,Ml=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function jl(e){let t=4294967295;for(let r=0;r<e.length;r++)t=Ml[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function ji(e){let t=[...e].sort((c,u)=>c.name<u.name?-1:c.name>u.name?1:0),r=[],n=[],o=0;for(let c of t){let u=Buffer.from(c.name,"utf8"),l=jl(c.data),p=Mi.deflateRawSync(c.data),m=c.data.length,y=p.length,d=Buffer.alloc(30);d.writeUInt32LE(Ul,0),d.writeUInt16LE(or,4),d.writeUInt16LE(0,6),d.writeUInt16LE(Ui,8),d.writeUInt16LE(Li,10),d.writeUInt16LE(ki,12),d.writeUInt32LE(l,14),d.writeUInt32LE(y,18),d.writeUInt32LE(m,22),d.writeUInt16LE(u.length,26),d.writeUInt16LE(0,28),r.push(d,u,p);let f=Buffer.alloc(46);f.writeUInt32LE(kl,0),f.writeUInt16LE(or,4),f.writeUInt16LE(or,6),f.writeUInt16LE(0,8),f.writeUInt16LE(Ui,10),f.writeUInt16LE(Li,12),f.writeUInt16LE(ki,14),f.writeUInt32LE(l,16),f.writeUInt32LE(y,20),f.writeUInt32LE(m,24),f.writeUInt16LE(u.length,28),f.writeUInt16LE(0,30),f.writeUInt16LE(0,32),f.writeUInt16LE(0,34),f.writeUInt16LE(0,36),f.writeUInt32LE(0,38),f.writeUInt32LE(o,42),n.push(f,u),o+=d.length+u.length+p.length}let i=Buffer.concat(r),s=Buffer.concat(n),a=Buffer.alloc(22);return a.writeUInt32LE(Ll,0),a.writeUInt16LE(0,4),a.writeUInt16LE(0,6),a.writeUInt16LE(t.length,8),a.writeUInt16LE(t.length,10),a.writeUInt32LE(s.length,12),a.writeUInt32LE(i.length,16),a.writeUInt16LE(0,20),Buffer.concat([i,s,a])}var Hi=N("ui-ota"),Hl="/api/ui-ota/manifest.json",Ji="/api/ui-ota/bundle.zip";function Fl(e){let t=[],r=(n,o)=>{for(let i of q.readdirSync(n,{withFileTypes:!0})){let s=ut.join(n,i.name),a=o?`${o}/${i.name}`:i.name;i.isDirectory()?r(s,a):i.isFile()&&!i.name.endsWith(".map")&&t.push({name:a,data:q.readFileSync(s)})}};return r(e,""),t.sort((n,o)=>n.name<o.name?-1:n.name>o.name?1:0),t}function Jl(e){let t=lt.createHash("sha256");for(let r of e)t.update(r.name),t.update("\0"),t.update(lt.createHash("sha256").update(r.data).digest("hex")),t.update("\0");return t.digest("hex")}function Wl(e){let t=Fl(e),r=ji(t),n=lt.createHash("sha256").update(r).digest("hex"),o=Jl(t);return{zip:r,manifest:{version:o,sha256:n,size:r.length,url:`${Ji}?v=${o}`}}}var Bl=2e3;function Fi(e){let t=0,r=0,n=0,o=i=>{n=Math.max(n,q.statSync(i).mtimeMs);for(let s of q.readdirSync(i,{withFileTypes:!0})){let a=ut.join(i,s.name);if(s.isDirectory())o(a);else if(s.isFile()){let c=q.statSync(a);t+=1,r+=c.size,n=Math.max(n,c.mtimeMs)}}};try{o(e)}catch{n=Date.now()}return{key:`${t}:${r}:${n}`,newestMs:n,hasIndex:q.existsSync(ut.join(e,"index.html"))}}function Wi(e){if(!e||!q.existsSync(e))return{};let t,r=()=>{let i=Fi(e);if(t&&(t.key===i.key||!i.hasIndex||Date.now()-i.newestMs<Bl))return t.bundle;let s=Wl(e);return t={key:Fi(e).key===i.key?i.key:null,bundle:s},s},n=async(i,s)=>{if(i.method!=="GET"&&i.method!=="HEAD"){he(s,405,{ok:!1,code:"method-not-allowed",message:"Use GET"});return}let a=r().manifest;Hi.info(`manifest served: version=${a.version.slice(0,12)} size=${a.size} method=${i.method}`),he(s,200,a)},o=async(i,s)=>{if(i.method!=="GET"&&i.method!=="HEAD"){he(s,405,{ok:!1,code:"method-not-allowed",message:"Use GET"});return}let{zip:a}=r();Hi.info(`bundle served: size=${a.length} method=${i.method}`),s.writeHead(200,{"Content-Type":"application/zip","Content-Length":String(a.length),"Cache-Control":"no-store"}),s.end(i.method==="HEAD"?void 0:a)};return{[Hl]:n,[Ji]:o}}var Bi=N("app-update"),$l="/api/app-update/manifest.json",Kl="fangxm233",zl="cortex-agent",Vl=`https://api.github.com/repos/${Kl}/${zl}/releases?per_page=100`,Gl=360*60*1e3,Yl=8e3,Ql=/^Cortex-(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)-(Linux|Windows|macOS|Android)-([A-Za-z0-9_]+?)(?:-setup)?\.(AppImage|deb|rpm|exe|dmg|apk)$/,Xl={AppImage:"appimage",deb:"deb",rpm:"rpm",exe:"nsis",dmg:"dmg",apk:"apk"},ql={amd64:"x86_64",arm64:"aarch64"};function Zl(e){let t=Ql.exec(e);if(!t)return null;let[,r,n,o,i]=t;return{version:r,os:n.toLowerCase(),arch:ql[o]??o,kind:Xl[i]}}function ed(e){if(!e)return null;let t=/^sha256:([0-9a-fA-F]{64})$/.exec(e);return t?t[1].toLowerCase():null}function td(e){let t=/^server-v(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)$/.exec(e);return t?t[1]:null}function rd(e){let t=[];for(let r of e.assets){let n=Zl(r.name),o=ed(r.digest);!n||!o||t.push({name:r.name,os:n.os,arch:n.arch,kind:n.kind,url:r.browser_download_url,size:r.size,sha256:o})}return t}function nd(e,t){let r=null;for(let n of e){let o=td(n.tag_name);if(!o||vt(o,t)>0)continue;let i=rd(n);i.length!==0&&(!r||vt(o,r.version)>0)&&(r={version:o,release:n,assets:i})}return r?{version:r.version,releaseUrl:r.release.html_url,publishedAt:r.release.published_at,notes:(r.release.body??"").slice(0,Yl),assets:r.assets}:null}async function od(){let e=await fetch(Vl,{headers:{Accept:"application/vnd.github+json","User-Agent":"cortex-agent"}});if(!e.ok)throw new Error(`GitHub releases API ${e.status}`);return await e.json()}function $i(e={}){let t=e.serverVersion??ns,r=e.devMode??!1,n=e.fetchReleases??od,o=e.ttlMs??Gl,i=e.now??Date.now,s=null,a=null,c=async()=>{if(r)return null;if(a!==null&&i()-a<o)return s;a=i();try{s=nd(await n(),t)}catch(l){Bi.warn(`release fetch failed: ${l.message}`)}return s},u=async(l,p)=>{if(l.method!=="GET"&&l.method!=="HEAD"){he(p,405,{ok:!1,code:"method-not-allowed",message:"Use GET"});return}let m=await c();m&&Bi.info(`manifest served: version=${m.version} assets=${m.assets.length}`),he(p,200,m??{})};return{[$l]:u}}var sd=N("device-ports"),id="/api/forward/devices",ad="/api/forward/device-ports",cd="/api/forward/device-port",ud="/api/forward/device-port/close";async function ld(e,t){let r=e.listDevices().find(i=>i.device===t)?.platform??"",{ports:n,error:o}=await at(r,i=>e.runOnDevice(t,i));return o&&sd.warn(`port discovery on ${t} unavailable: ${o}`),n}async function Ki(e,t){if(e.method!=="POST")return V(t,"POST"),null;let r=await ae(e,t);if(!r)return null;let n=typeof r.device=="string"?r.device:"",o=Number(r.port);return n?!Number.isInteger(o)||o<1024||o>65535?(A(t,400,"bad-port","port must be an integer in 1024..65535"),null):{device:n,port:o}:(A(t,400,"missing-device","device is required"),null)}function zi(e){let t=new Map,r=(n,o)=>`${n}\0${o}`;return{[id]:async(n,o)=>{let i=e.listDevices().map(s=>({device:s.device,platform:s.platform}));x(o,200,{ok:!0,data:{devices:i}})},[ad]:async(n,o)=>{let i=new URL(n.url??"","http://localhost").searchParams.get("device");if(!i)return A(o,400,"missing-device","device is required");x(o,200,{ok:!0,data:{ports:await ld(e,i)}})},[cd]:async(n,o)=>{let i=await Ki(n,o);if(!i)return;let s=r(i.device,i.port),a=e.listDevicePorts().some(u=>u.device===i.device&&u.remotePort===i.port),c;try{c=await e.openDevicePort(i.device,i.port)}catch(u){return A(o,500,"open-failed",u.message)}t.has(s)?t.set(s,t.get(s)+1):a||t.set(s,1),x(o,200,{ok:!0,data:c})},[ud]:async(n,o)=>{let i=await Ki(n,o);if(!i)return;let s=r(i.device,i.port),a=t.get(s)??0;a>1?t.set(s,a-1):t.delete(s);let c=a===1&&e.closeDevicePort(i.device,i.port);x(o,200,{ok:!0,data:{closed:c}})}}}import*as ce from"node:path";import*as ue from"node:fs";var dd="/api/attachments/upload",fd="/api/files/download",pd="/api/boards/asset",md=100*1024*1024,yd=/^[A-Za-z0-9_-]{1,128}$/,hd=new Set(["text/html","application/xhtml+xml","image/svg+xml","application/xml"]),gd="sandbox allow-scripts";function sr(e,t){let r=e.headers[t];return(Array.isArray(r)?r[0]:r)?.trim()||void 0}function wd(e){try{return decodeURIComponent(e)}catch{return e}}function Ed(e){return e.startsWith("image/")?"image":e.startsWith("video/")?"video":"file"}async function Sd(e,t,r){let n;try{n=await ue.promises.open(t,"wx")}catch(i){return e.resume(),{kind:"failed",error:i}}let o=n.createWriteStream();return new Promise(i=>{let s=0,a=!1,c=p=>{if(!a){if(a=!0,e.off("data",u),e.off("end",l),p.kind==="stored")return i(p);o.destroy(),e.resume(),ue.promises.unlink(t).catch(()=>{}).then(()=>i(p))}},u=p=>{if(s+=p.length,s>r)return c({kind:"too-large"});o.write(p)||(e.pause(),o.once("drain",()=>{a||e.resume()}))},l=()=>{o.end()};e.on("data",u),e.on("end",l),e.on("error",p=>c({kind:"failed",error:p})),e.on("close",()=>{e.complete||c({kind:"failed",error:new Error("upload aborted")})}),o.on("error",p=>c({kind:"failed",error:p})),o.on("finish",()=>c({kind:"stored",size:s}))})}async function Vi(e,t,r){let n;try{let a=await ue.promises.stat(t);if(!a.isFile())throw new Error("not a file");n=a.size}catch{A(e,404,"not-found","File not found");return}let o=qe(t),i=ce.basename(t);e.writeHead(200,{"Content-Type":Ze(o),"Content-Length":String(n),"Content-Disposition":`${r}; filename="${i.replace(/"/g,"")}"`,"Cache-Control":"private, max-age=3600","X-Content-Type-Options":"nosniff",...hd.has(o)?{"Content-Security-Policy":gd}:{}});let s=ue.createReadStream(t);s.on("error",()=>{e.headersSent||e.writeHead(500),e.end()}),s.pipe(e)}function Gi(e,t){try{return new URL(e.url??"","http://localhost").searchParams}catch{return A(t,400,"bad-request","Malformed URL"),null}}function Yi(e){let t=e.maxUploadBytes??md,r=(s,a)=>Kt(s,a,413,"too-large",`File exceeds ${t/1024/1024}MB limit`,t),n=async(s,a)=>{if(s.method!=="POST")return V(a,"POST");let c=sr(s,"x-session-id"),u=sr(s,"x-file-name"),l=(sr(s,"content-type")??"application/octet-stream").split(";")[0].trim();if(!c)return A(a,400,"missing-session","X-Session-Id header required");if(!u)return A(a,400,"missing-name","X-File-Name header required");let p=ce.resolve(e.attachmentsDir),m=ce.resolve(p,c);if(!yd.test(c)||ce.dirname(m)!==p)return A(a,400,"bad-session","X-Session-Id is not a session id");if(($t(s)??0)>t)return r(s,a);let y=ss(wd(u));await ue.promises.mkdir(m,{recursive:!0});let{destPath:d,finalName:f}=await as(m,is(y)),w=await Sd(s,d,t);if(w.kind==="too-large")return r(s,a);if(w.kind==="failed")return A(a,500,"upload-failed",w.error.message);x(a,200,{ok:!0,data:{name:y,path:`workspace/attachments/${c}/${f}`,size:w.size,mimeType:l,type:Ed(l)}})},o=async(s,a)=>{let c=Gi(s,a);if(!c)return;let u=(c.get("path")??"").trim(),l=c.get("disposition")==="inline"?"inline":"attachment";if(!u)return A(a,400,"missing-path","path query param required");let p=e.resolveWorkspaceRelPath(u);if(!p)return A(a,403,"forbidden","Path escapes the workspace root");await Vi(a,p,l)},i=async(s,a)=>{let c=Gi(s,a);if(!c)return;let u=(c.get("projectId")??"").trim(),l=(c.get("path")??"").trim(),p=c.get("disposition")==="attachment"?"attachment":"inline";if(!u||!l)return A(a,400,"missing-params","projectId and path query params required");if(!l.startsWith("boards/"))return A(a,403,"forbidden","path must be under boards/");let m=e.projectContextDir(u),y;try{if(!m)throw new Error("unknown project");let d=ue.realpathSync(ce.join(m,"boards"));y=e.resolveMemoryFilePath(d,l.slice(7))}catch{return A(a,404,"not-found","File not found")}await Vi(a,y,p)};return{[dd]:n,[fd]:o,[pd]:i}}import*as ea from"crypto";var Ee=N("browser-stream"),vd="/api/browser/sessions",bd="/api/browser/stream-ticket",ta="/api/browser/stream",_d="/api/browser/takeover",Td="/api/browser/insert-text",ir=4004,Qi=4010,Rd=3e4,Ad=256,Od=32,Id=10,Pd=15,Cd=16*1024,Xi=4e3,xd=4*1024*1024,Nd=5e3,Dd=3e4,Ud=10*6e4,qi="cortex_takeover",kd=/^[A-Za-z0-9_-]{1,64}$/,Ld=new Set(["input_mouse","input_keyboard","input_touch"]);function Md(e,t){let r;try{r=JSON.parse(e)}catch{return null}if(!r||typeof r!="object")return null;let n=r.type;if(n==="ack"){let o=r.seq;return typeof o=="number"&&Number.isFinite(o)?{message:JSON.stringify({type:"ack",seq:o}),input:!1}:null}return typeof n=="string"&&Ld.has(n)&&t?{message:e,input:!0}:null}function Zi(e){return e==null||e===""?"":typeof e=="string"&&kd.test(e)?e:null}function jd(e){let t=Number(e);return!e||!Number.isFinite(t)||t<=0?Id:Math.min(Pd,Math.max(1,Math.round(t)))}function Hd(e){let t;try{t=new URL(e,"http://localhost")}catch{return null}let r=t.searchParams.get("session")??"",n=t.searchParams.get("ticket")??"";return!r||!n?null:{sessionId:r,ticket:n,fps:jd(t.searchParams.get("maxFps"))}}function Fd(e=Date.now){let t=new Map,r=()=>{let n=e();for(let[o,i]of t)i.expiresAt<=n&&t.delete(o)};return{mint(n,o=""){for(r();t.size>=Ad;)t.delete(t.keys().next().value);let i=ea.randomBytes(32).toString("hex");return t.set(i,{sessionId:n,client:o,expiresAt:e()+Rd}),i},redeem(n,o){r();let i=null;for(let a of t.keys())Z(a,n)&&(i=a);if(i===null)return null;let s=t.get(i);return t.delete(i),s.sessionId===o?{client:s.client}:null},size:()=>(r(),t.size)}}function Jd(e){let t=new Map,r=s=>{s.grace&&clearTimeout(s.grace),s.idle&&clearTimeout(s.idle),s.grace=null,s.idle=null},n=(s,a,c)=>{t.get(s)===a&&(r(a),t.delete(s),e.isTakenOver(s)&&e.release(s,c))},o=(s,a)=>{let c=Math.max(0,a.lastInputAt+e.idleMs-e.now());a.idle=setTimeout(()=>{a.idle=null,e.now()-a.lastInputAt>=e.idleMs?n(s,a,"idle"):o(s,a)},c),a.idle.unref?.()},i=(s,a)=>{a.grace||(a.grace=setTimeout(()=>{a.grace=null,n(s,a,"disconnected")},e.graceMs),a.grace.unref?.())};return{begin(s,a){let c=t.get(s);c&&r(c);let u={client:a,lastInputAt:e.now(),grace:null,idle:null};t.set(s,u),o(s,u),e.hasClient(s,a)||i(s,u)},end(s){let a=t.get(s);a&&(r(a),t.delete(s))},holder:s=>t.get(s)?.client??null,connected(s,a){let c=t.get(s);c?.client===a&&c.grace&&(clearTimeout(c.grace),c.grace=null)},disconnected(s,a){let c=t.get(s);c?.client===a&&!e.hasClient(s,a)&&i(s,c)},input(s){let a=t.get(s);a&&(a.lastInputAt=e.now())},close(){for(let s of t.values())r(s);t.clear()}}}function Wd(e){return{sessionId:e.sessionId,device:e.device,state:e.state,...e.error?{error:e.error}:{},...e.url?{url:e.url}:{},...e.title?{title:e.title}:{},takenOver:e.takenOver,lastUsedAt:e.lastUsedAt}}async function ar(e,t,r){if(e.method!=="POST")return V(t,"POST"),null;let n=await ae(e,t);if(!n)return null;let o=typeof n.session=="string"?n.session:"";return o?r.listSessions().some(i=>i.sessionId===o)?{sessionId:o,body:n}:(A(t,404,"no-browser","This session has no browser"),null):(A(t,400,"missing-session","session is required"),null)}function ra(e,t={}){let r=e.now??Date.now,n=Fd(r),o=new et.default({noServer:!0,maxPayload:Cd}),i=new Set,s=d=>[...i].filter(f=>f.sessionId===d),a=d=>d.client!==""&&e.isTakenOver(d.sessionId)&&u.holder(d.sessionId)===d.client,c=d=>{for(let f of s(d))f.ws.readyState===ne.default.OPEN&&f.ws.send(JSON.stringify({type:qi,takenOver:e.isTakenOver(d),mine:a(f)}))},u=Jd({isTakenOver:e.isTakenOver,hasClient:(d,f)=>f!==""&&s(d).some(w=>w.client===f),now:r,graceMs:t.graceMs??Dd,idleMs:t.idleMs??Ud,release:(d,f)=>{(async()=>{try{await e.setTakeover(d,!1)}catch(w){Ee.warn(`could not hand ${d} back: ${w.message}`);return}Ee.info(`browser handed back automatically (${f==="idle"?"no input":"window gone"}): ${d}`),c(d)})()}}),l={[vd]:async(d,f)=>{if(d.method!=="GET")return V(f,"GET");x(f,200,{ok:!0,data:{sessions:e.listSessions().map(Wd)}},{"Cache-Control":"no-store"})},[bd]:async(d,f)=>{let w=await ar(d,f,e);if(!w)return;let b=Zi(w.body.client);if(b===null)return A(f,400,"bad-client","client must be 1-64 letters, digits, _ or -");x(f,200,{ok:!0,data:{ticket:n.mint(w.sessionId,b)}},{"Cache-Control":"no-store"})},[_d]:async(d,f)=>{let w=await ar(d,f,e);if(!w)return;let b=w.body.on;if(typeof b!="boolean")return A(f,400,"bad-on","on must be a boolean");let g=Zi(w.body.client);if(g===null||b&&g==="")return A(f,400,"bad-client","client must be 1-64 letters, digits, _ or -");await e.setTakeover(w.sessionId,b),b?u.begin(w.sessionId,g):u.end(w.sessionId),Ee.info(`browser ${b?"taken over":"handed back"}: ${w.sessionId}`),c(w.sessionId),x(f,200,{ok:!0,data:{takenOver:e.isTakenOver(w.sessionId)}})},[Td]:async(d,f)=>{let w=await ar(d,f,e);if(!w)return;let b=typeof w.body.text=="string"?w.body.text:"";if(!b)return A(f,400,"missing-text","text is required");if(b.length>Xi)return A(f,400,"text-too-long",`text exceeds ${Xi} characters`);if(!e.isTakenOver(w.sessionId))return A(f,409,"not-taken-over","Take over the browser first");u.input(w.sessionId);try{await e.insertText(w.sessionId,b)}catch(g){return A(f,502,"insert-failed",g.message)}x(f,200,{ok:!0,data:{}})}},p=async(d,f)=>{let{ws:w}=d,b=null;try{b=await e.streamPort(f.sessionId)}catch(E){Ee.warn(`stream port lookup failed for ${f.sessionId}: ${E.message}`)}if(w.readyState!==ne.default.OPEN)return;if(b===null){w.close(ir,"no stream");return}let g=new ne.default(`ws://127.0.0.1:${b}/?maxFps=${f.fps}&pacing=ack`,{handshakeTimeout:Nd}),v=!1,T=(E,P)=>{(g.readyState===ne.default.OPEN||g.readyState===ne.default.CONNECTING)&&g.terminate(),w.readyState===ne.default.OPEN&&w.close(E,P)};g.on("open",()=>{v=!0}),g.on("message",(E,P)=>{w.readyState===ne.default.OPEN&&(w.bufferedAmount>xd||w.send(E,{binary:P}))}),g.on("close",()=>T(v?Qi:ir,v?"stream ended":"no stream")),g.on("error",E=>{Ee.warn(`upstream stream error for ${f.sessionId}: ${E.message}`),T(v?Qi:ir,v?"stream ended":"no stream")}),w.on("message",(E,P)=>{if(P||g.readyState!==ne.default.OPEN)return;let L=Md(E.toString(),a(d));L&&(L.input&&u.input(f.sessionId),g.send(L.message))}),w.on("close",()=>T(1e3,"viewer closed"))};return{routes:l,handleUpgrade:(d,f,w)=>{let b=Hd(d.url??""),g=b?n.redeem(b.ticket,b.sessionId):null;if(!b||!g){Ee.warn("browser stream refused: missing or invalid ticket"),f.write(`HTTP/1.1 401 Unauthorized\r
24
- Connection: close\r
25
- \r
26
- `),f.destroy();return}if(i.size>=Od){Ee.warn(`browser stream refused (${i.size} already open)`),f.write(`HTTP/1.1 503 Service Unavailable\r
27
- Connection: close\r
28
- \r
29
- `),f.destroy();return}o.handleUpgrade(d,f,w,v=>{let T={ws:v,sessionId:b.sessionId,client:g.client};i.add(T),u.connected(T.sessionId,T.client),v.on("close",()=>{i.delete(T),u.disconnected(T.sessionId,T.client)}),v.on("error",()=>v.terminate()),v.send(JSON.stringify({type:qi,takenOver:e.isTakenOver(T.sessionId),mine:a(T)})),p(T,b)})},close:()=>{u.close();for(let d of i)d.ws.terminate();i.clear(),o.close()}}}var dt=new TextEncoder,ft=new TextDecoder,pt=new TextDecoder("utf-8",{fatal:!0}),Am=2**32;function na(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var Bd=/[^\x00-\x7f]/;function Ce(e){if(typeof e=="string"&&e.length>=128){if(Bd.test(e))throw new TypeError("non-ASCII string encountered in encode()");return dt.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function oa(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return n}var $=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},le=class extends ${static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},ze=class extends ${static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},mt=class extends ${static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},ee=class extends ${static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var J=class extends ${static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Se=class extends ${static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var xe=class extends ${static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Ne=class extends ${static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},yt=class extends ${[Symbol.asyncIterator]=async function*(){};static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}},ht=class extends ${static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",r){super(t,r)}},Ve=class extends ${static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var $d="The input to be decoded is not correctly encoded.";function Ge(e){try{return oa(typeof e=="string"?e:ft.decode(e),!0)}catch(t){throw new TypeError($d,{cause:t})}}function pe(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function gt(e){return pe(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(pe)}function sa(...e){let t=new Set;for(let r of e)if(r)for(let n of Object.keys(r)){if(t.has(n))return!1;t.add(n)}return!0}function cr(e,t,r){try{return Ge(e)}catch(n){throw new r(`Failed to base64url decode the ${t}`,{cause:n})}}function ia(e,t,r){try{return Ce(e)}catch(n){throw new r(`The ${t} is not a valid base64url string`,{cause:n})}}function aa(e,t,r){let n;try{n=JSON.parse(pt.decode(Ge(e)))}catch(o){throw new t(r,{cause:o})}if(!pe(n))throw new t(r);return n}var ca={__proto__:null,b64:!0};function ua(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function la(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return[];if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?t:{__proto__:null,...r,...t};for(let s of n.crit){if(!(s in i))throw new ee(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(o,s)||o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(n,s)||n[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return n.crit}function da(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new J('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}var Kd=e=>e[Symbol.toStringTag],zd=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let o=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==o)throw new TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(t.alg!==void 0&&t.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){let o=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(o&&!t.key_ops.includes(o))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};async function pa(e,t,r){let{alg:n,secret:o}=e,i=r==="decrypt"||r==="sign";if(o&&t instanceof Uint8Array)return t;let s,a;if(pe(t)){if(s=Zd(t),typeof s.kty!="string")throw fa(n,t,o);if(!(o?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(zd(e,s,r),s.kty==="oct")return Ge(s.k);if(!Object.isFrozen(t)){let{key_ops:l}=t;Array.isArray(l)&&Object.freeze(l),Object.freeze(t)}}else{if(!Yd(t))throw fa(n,t,o);let l=o?"secret":i?"private":"public";if(t.type!==l&&(o||["secret","public","private"].includes(t.type)))throw new TypeError(`${Kd(t)} instances must be of type "${l}" for the ${n} algorithm`);if(ma(t))return t;if(a=t,a.type==="secret")return a.export()}ur||=new WeakMap;let c=t,u=ur.get(c);if(u?.[n])return u[n];if(u||ur.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",p=Vd[a.asymmetricKeyDetails?.namedCurve],m=e.resolve?.({crv:p,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return u[n]=a.toCryptoKey(m,l,e.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=n,u[n]=await dr(e,s)}var ur,Vd={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};var ma=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Gd=e=>e?.[Symbol.toStringTag]==="KeyObject",Yd=e=>ma(e)||Gd(e);function Qd(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function fa(e,t,r){let n=["CryptoKey","KeyObject","JSON Web Key"];return r&&n.push("Uint8Array"),new TypeError(Qd(`Key for the ${e} algorithm must be `,t,...n))}var wt=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Xd(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ya(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function qd(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw wt(t.name);if(t.hash&&n.hash?.name!==t.hash)throw wt(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw wt(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw wt(t.length,"algorithm.length");Xd(e,r)}function lr(e){return{__proto__:null,...e}}function Zd(e){let t=lr(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,n=Array.isArray(r)?[...r]:void 0;if(!n||n.some(o=>typeof o!="string")||new Set(n).size!==n.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=n}return t}async function dr(e,t,r){if(!e.kty.includes(t.kty))throw new ee('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,o=!!(t.d||t.priv),i={...t,ext:r??t.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,n,i.ext??!o,t.key_ops??e.usages[o?1:0])}async function ha(e,t,r,n=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,n,[r])),qd(e,t,r),e}function ga(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Ye=[["verify"],["sign"]];function fr(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Ye}}function De(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Ye,minRsaBits:2048}}function pr(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Ye}}function wa(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Ye}}function mr(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Ye}}var yr=ga({HS256:fr(256),HS384:fr(384),HS512:fr(512),RS256:De(256),RS384:De(384),RS512:De(512),PS256:De(256,32),PS384:De(384,48),PS512:De(512,64),ES256:pr("P-256",256),ES384:pr("P-384",384),ES512:pr("P-521",512),EdDSA:wa(),Ed25519:wa(),"ML-DSA-44":mr(44),"ML-DSA-65":mr(65),"ML-DSA-87":mr(87)});function Ea(e){let t=typeof e=="string"?yr[e]:void 0;if(!t)throw new ee(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function Sa(e){return[e&&ua("algorithms",e.algorithms),e?.crit]}function ef(e){return e===void 0?{}:aa(e,J,"JWS Protected Header is invalid")}function tf(e){try{return Ce(e)}catch(t){throw new J("JWS Compact Serialization payload must use only ASCII characters",{cause:t})}}async function rf(e,t,r,n,o){let{protected:i,header:s,payload:a}=e,c=o??ef(i);if(!sa(c,s))throw new J("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=da(c,la(J,ca,t[1],c,u)),{alg:p}=u;if(typeof p!="string"||!p)throw new J('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(p))throw new mt('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new J("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new J("JWS Payload must be a string or an Uint8Array instance");let m=l||typeof a!="string"?a:n(a),y=!1;typeof r=="function"&&(r=await r(c,e),y=!0);let d=Ea(p),f=na(i!==void 0?Ce(i):new Uint8Array,Ce("."),typeof m=="string"?t[2]??=ia(m,"payload",J):m),w=cr(e.signature,"signature",J),b=await pa(d,r,"verify"),g=await ha(b,d.subtle,"verify");d.minRsaBits&&ya(d.alg,g);let v=!1;try{v=await crypto.subtle.verify(d.signing,g,w,f)}catch(E){throw new Ve(void 0,{cause:E})}if(!v)throw new Ve;let T={payload:typeof m=="string"?cr(m,"payload",J):m};return i!==void 0&&(T.protectedHeader=c),s!==void 0&&(T.unprotectedHeader=s),y?[{...T,key:b},l]:[T,l]}async function va(e,t,r){if(e instanceof Uint8Array&&(e=ft.decode(e)),typeof e!="string")throw new J("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new J("Invalid Compact JWS");return rf({payload:o,protected:n,signature:i},t,r,tf)}var nf=e=>Math.floor(e.getTime()/1e3),of={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},sf=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ue="check_failed";function hr(){throw new TypeError("Invalid time period format")}function ba(e){typeof e!="string"&&hr();let t=sf.exec(e);(!t||t[4]&&t[1])&&hr();let r=parseFloat(t[2]),n=Math.round(r*of[t[3][0].toLowerCase()]);return Number.isFinite(n)||hr(),t[1]==="-"||t[4]==="ago"?-n:n}function gr(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var _a=e=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`},af=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(r=>e.includes(r)):!1;function wr(e,t,r=!1){let n=e[t];if(!(n===void 0&&!r)){if(typeof n!="number")throw new le(`"${t}" claim must be a number`,e,t,"invalid");return n}}function Er(e,t){throw new le(`unexpected "${t}" claim value`,e,t,Ue)}function Ta(e,t,r={}){let n;try{n=JSON.parse(pt.decode(t))}catch(g){throw new Se("JWT Claims Set must be a top-level JSON object",{cause:g})}if(!pe(n))throw new Se("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o!==void 0&&(typeof e.typ!="string"||_a(e.typ)!==_a(o)))throw new le('unexpected "typ" JWT header value',n,"typ",Ue);let{requiredClaims:i=[],issuer:s,subject:a,audience:c,maxTokenAge:u}=r,l=[...i];u!==void 0&&l.push("iat"),c!==void 0&&l.push("aud"),a!==void 0&&l.push("sub"),s!==void 0&&l.push("iss");for(let g of new Set(l.reverse()))if(!Object.hasOwn(n,g))throw new le(`missing required "${g}" claim`,n,g,"missing");s!==void 0&&!(Array.isArray(s)?s:[s]).includes(n.iss)&&Er(n,"iss"),a!==void 0&&n.sub!==a&&Er(n,"sub"),c!==void 0&&!af(n.aud,typeof c=="string"?[c]:c)&&Er(n,"aud");let{clockTolerance:p}=r,m=0;if(typeof p=="string")m=ba(p);else if(p!==void 0){if(typeof p!="number")throw new TypeError("Invalid clockTolerance option type");m=p}gr("clockTolerance option",m);let{currentDate:y}=r,d=gr("currentDate option",nf(y===void 0?new Date:y)),f=wr(n,"iat",u!==void 0),w=wr(n,"nbf");if(w!==void 0&&w>d+m)throw new le('"nbf" claim timestamp check failed',n,"nbf",Ue);let b=wr(n,"exp");if(b!==void 0&&b<=d-m)throw new ze('"exp" claim timestamp check failed',n,"exp",Ue);if(u!==void 0){let g=d-f,v=gr("maxTokenAge option",typeof u=="number"?u:ba(u));if(g-m>v)throw new ze('"iat" claim timestamp check failed (too far in the past)',n,"iat",Ue);if(g<-m)throw new le('"iat" claim timestamp check failed (it should be in the past)',n,"iat",Ue)}return n}async function Sr(e,t,r){let[n,o]=await va(e,Sa(r),t);if(!o)throw new Se("JWTs MUST NOT use unencoded payload");let i=Ta(n.protectedHeader,n.payload,r);return{...n,payload:i}}function cf(e,t,r,n){let{kty:o,key_ops:i,ext:s,kid:a,alg:c,use:u,crv:l}=e;return(s===void 0||typeof s=="boolean")&&(i===void 0||Array.isArray(i)&&i.every((p,m)=>typeof p=="string"&&i.indexOf(p)===m)&&i.includes("verify"))&&t.kty.includes(o)&&(n===void 0||typeof n=="string"&&n===a)&&(c===void 0?o!=="AKP":r===c)&&(u===void 0||u==="sig")&&(!t.crv||l===t.crv)}async function Ra(e,t,r){let n=e.get(t)||e.set(t,{}).get(t),{alg:o}=r;if(n[o]===void 0){let i=dr(r,t,!0).then(s=>{if(s.type!=="public")throw new xe("JSON Web Key Set members must be public keys");return n[o]=s,s}).catch(s=>{throw n[o]===i&&delete n[o],s});n[o]=i}return n[o]}function vr(e){let t;try{t=structuredClone(e)}catch(o){throw new xe("JSON Web Key Set malformed",{cause:o})}if(!gt(t))throw new xe("JSON Web Key Set malformed");let r=t.keys.map(o=>{let i=lr(o);return Array.isArray(i.key_ops)&&(i.key_ops=[...i.key_ops]),i}),n=new WeakMap;return Object.defineProperty(async(o,i)=>{let{alg:s,kid:a}={...o,...i?.header},c=typeof s=="string"?yr[s]:void 0;if(!c||c.secret)throw new ee('Unsupported "alg" value for a JSON Web Key Set');let u=t.keys.filter((m,y)=>cf(r[y],c,s,a)),{0:l,length:p}=u;if(!p)throw new Ne;if(p!==1){let m=new yt;throw m[Symbol.asyncIterator]=async function*(){for(let y of u)try{yield await Ra(n,y,c)}catch{}},m}return Ra(n,l,c)},"jwks",{value:()=>structuredClone(t)})}function uf(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var br;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(br="jose/v6.2.13");var Oa=Symbol();async function lf(e,t,r,n=fetch){let o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(i=>{throw i.name==="TimeoutError"?new ht(void 0,{cause:i}):i});if(o.status!==200)throw new $("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch(i){throw new $("Failed to parse the JSON Web Key Set HTTP response as JSON",{cause:i})}}var Ia=Symbol();function Qe(e,t){return Number.isFinite(e)&&Date.now()<e+t}function Aa(e,t,r){if(Number.isNaN(e))throw new TypeError(`"${r}" option must not be NaN`);return typeof e=="number"?e:t}function _r(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");let r=new URL(e.href).href,n=t??{},o=n.timeoutDuration;if(typeof o=="number"&&(!Number.isInteger(o)||o<0))throw new TypeError('"timeoutDuration" option must be a non-negative integer');let i=typeof o=="number"?o:5e3,s=Aa(n.cooldownDuration,3e4,"cooldownDuration"),a=Aa(n.cacheMaxAge,6e5,"cacheMaxAge"),c=new Headers(n.headers);br&&!c.has("User-Agent")&&c.set("User-Agent",br),c.has("accept")||c.set("accept","application/json, application/jwk-set+json");let u=n[Oa],l=n[Ia],p,m,y=0,d=0,f;if(l&&typeof l=="object"){let{uat:b,jwks:g}=l;Qe(b,a)&&gt(g)&&(p=b,f=vr(g))}let w=async()=>{if(m&&uf()&&(m=void 0),!m){let b=++y,g=m=lf(r,c,AbortSignal.timeout(i),u).then(v=>{let T=vr(v);if(b<=d)return;f=T;let E=Date.now();l&&(l.uat=E,l.jwks=v),p=E,d=b}).finally(()=>{m===g&&(m=void 0)})}await m};return Object.defineProperties(async(b,g)=>{(!f||!Qe(p,a))&&await w();try{return await f(b,g)}catch(v){if(v instanceof Ne&&!Qe(p,s))return await w(),f(b,g);throw v}},{coolingDown:{get:()=>Qe(p,s),enumerable:!0},fresh:{get:()=>Qe(p,a),enumerable:!0},reload:{value:w,enumerable:!0},reloading:{get:()=>!!m,enumerable:!0},jwks:{value:()=>f?.jwks(),enumerable:!0}})}var df=N("ui-http"),ff=["RS256","ES256"];function pf(e){let t=_r(new URL(e.jwksUrl));return async r=>{try{return await Sr(r,t,{audience:e.audience,issuer:e.issuer,algorithms:ff}),!0}catch{return!1}}}function mf(e){let t=e.trim().replace(/^https?:\/\//,"").replace(/\/+$/,"");return t.includes(".")?t:`${t}.cloudflareaccess.com`}function Pa(e){let t=(e.CORTEX_ACCESS_TEAM_DOMAIN||"").trim(),r=(e.CORTEX_ACCESS_AUD||"").trim();if(!t||!r)return;let o=`https://${mf(t)}`,i=(e.CORTEX_ACCESS_CERTS_URL||"").trim()||`${o}/cdn-cgi/access/certs`;return df.info(`Cloudflare Access JWT verification enabled (iss: ${o})`),pf({jwksUrl:i,audience:r,issuer:o})}var hf=N("ui-http"),gf=te.join(Xe,"ui-sessions.json"),wf=te.join(Xe,"ui-devices.json");function Ef(e){let t=(e.CORTEX_UI_TOKEN_LOGIN??"").trim().toLowerCase();return!(t==="0"||t==="false"||t==="off"||t==="no")}function Ca(e){let t=Number((e.CORTEX_UI_SESSION_TTL_DAYS??"").trim());return Number.isFinite(t)&&t>0?t*24*60*60*1e3:Gt}function Sf(){try{let e=te.dirname(yf(new URL("dist/entry/start-ui-http.js",__cortexPackageRoot).href));return[te.resolve(e,"../../web/dist"),te.resolve(e,"../../../web/dist")].find(r=>xa.existsSync(r))}catch{return}}function vf(e,t,r){let n=Ef(e),o=Di({file:wf}),i=p=>o.match(p)!==void 0,s=n?hi({file:gf,ttlMs:Ca(e)}):void 0,a=n?rs({file:te.join(Xe,es)}):void 0,u=Ri({getToken:t,matchDeviceToken:i,verifySession:s?p=>s.verify(p):void 0,verifyAccessJwt:r}),l=s&&a?vi({store:s,getToken:t,authorize:u,ttlMs:Ca(e),redeemCode:p=>a.redeem(p)}):bi(u);return{authorize:u,matchDeviceToken:i,tokenLogin:n,publicRoutes:n?[Qt,Be,rr]:[Be],routes:{...l,...Ci({devices:o,pairing:a})}}}function bf(e,t){return{...Yi({attachmentsDir:te.join(Ir,"attachments"),resolveWorkspaceRelPath:Pr,projectContextDir:r=>Es.get(r)?.contextDir,resolveMemoryFilePath:Ss}),...Wi(e),...$i({devMode:os()}),...di(),...zi({listDevices:cs,runOnDevice:async(r,n)=>{let o=await us(r,{action:"bash",params:{command:n},timeout:1e4});return typeof o?.stdout=="string"?o.stdout:""},openDevicePort:ls,closeDevicePort:ds,listDevicePorts:fs}),...t}}function _f(e,t,r,n,o){hf.info(`Web UI enabled \u2014 tRPC HTTP+SSE on ${e}`+(t?` (SPA: ${t})`:" (SPA: not built \u2014 non-tRPC paths 404)")+(r.length>0?` (CORS allow-list: ${r.join(", ")})`:"")+(n?" (Cloudflare Access JWT path enabled)":"")+(o?" (browser token login enabled)":" (browser token login disabled)"))}function Na(e,t){let r=e.env??process.env;if(!vs(r))return null;let n=e.corsOrigins??(()=>Cr().uiCorsOrigins),o=e.spaDir??r.CORTEX_UI_SPA_DIR??Sf(),i=Pa(r),s=e.getToken??Zo,a=vf(r,s,i),c=ra({listSessions:ps,streamPort:ms,setTakeover:ys,isTakenOver:hs,insertText:gs}),u=typeof n=="function"?n():n;return _f(t,o,u,!!i,a.tokenLogin),{router:Ws(e.uiService),getToken:s,matchDeviceToken:a.matchDeviceToken,spaDir:o,corsOrigins:n,authorize:a.authorize,createContext:l=>({client:bs(l.headers[Dr])}),publicRoutes:a.publicRoutes,customRoutes:{...a.routes,...bf(o,c.routes)},upgradeRoutes:{[ta]:c},portForward:r.CORTEX_PORT_FORWARD!=="0"}}function Gy(e,t){let r=Na(e,t);return r?er(r):null}function Yy(e){let t=e.env??process.env,r=parseInt(t.CORTEX_UI_PORT??"",10),n=Number.isNaN(r)?ws:r,o=Na(e,`127.0.0.1:${n}`);return o?Pi({...o,port:n,host:"127.0.0.1"}):null}export{Gy as createUiHttp,Yy as startUiHttpServer};
30
- /*! Bundled license information:
31
-
32
- @trpc/server/dist/resolveResponse-JtMyT9TQ.mjs:
33
- (* istanbul ignore if -- @preserve *)
34
- (*!
35
- * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
36
- *
37
- * Copyright (c) 2014-2017, Jon Schlinkert.
38
- * Released under the MIT License.
39
- *)
40
-
41
- @trpc/server/dist/resolveResponse-JtMyT9TQ.mjs:
42
- (* istanbul ignore if -- @preserve *)
43
- */
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as _,c as y}from"./chunk-UT6DGZDO.js";import{a as m,b,c as f,e as h,f as l,g as w}from"./chunk-ETIBCA2S.js";import{c as g}from"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-5M4PFLRW.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as r}from"./chunk-W34AK4SK.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";var $=40*1e3,F=1800*1e3,E=1500*1e3;function k(t){return{model:r.string().optional().describe(t.model),backend:r.enum(["claude","pi"]).optional().describe(t.backend),clean:r.boolean().optional().describe(b),files:r.array(r.string()).optional().describe(f)}}function I(t){let e=r.object({description:r.string().describe("Short description of the delegated task."),prompt:r.string().describe("Complete task prompt for the subagent."),subagent_type:r.string().describe(t.subagentType),...k(t)});return{description:r.string().optional().describe("Short description for single mode."),prompt:r.string().optional().describe("Complete prompt for single mode."),subagent_type:r.string().optional().describe(t.subagentTypeSingle),...k(t),parallel:r.array(e).min(1).max(8).optional().describe("Tasks to execute concurrently."),chain:r.array(e).min(1).max(8).optional().describe("Tasks to execute sequentially; {previous} inserts the prior output."),run_in_background:r.boolean().optional().describe("Return agent_id immediately; results arrive later. Default: wait for completion.")}}function R(t){let e=h(t);try{return l({roles:w(g()),models:e})}catch{return l({models:e})}}async function d(t,e,n,i){let{body:o}=await _("POST",`${t.webhookBaseUrl}/webhook/subagent`,{action:e,sessionId:t.sessionId,...n},y(t),i);if(!o?.success)throw new Error(o?.error||`subagent ${e} failed`);return o.data}async function N(t,e){try{await d(t,"detach",{runId:e})}catch{}}function u(t,e=!1){return{content:[{type:"text",text:t}],...e?{isError:!0}:{}}}function D(t,e){let n=t?._meta?.progressToken,i=t?.sendNotification;return n===void 0||!i?()=>{}:o=>{try{Promise.resolve(i({method:"notifications/progress",params:{progressToken:n,progress:o,message:`agent ${e} still running`}})).catch(()=>{})}catch{}}}async function C(t,e,n=()=>{}){let i=Date.now()+E;for(let o=1;;o++){let s=await d(t,"wait",{runId:e},$);if(s.status!=="running")return s;if(Date.now()>=i)return{...s,timedOut:!0};n(o)}}function U(t,e){if(t.timedOut){let n=Math.round(E/6e4);return{text:`Agent ${e} passed the ${n}-minute foreground limit and now runs in the background: it keeps going, and its result will be delivered to you when it lands. Stop it with agent_stop("${e}") if it is no longer useful.`,isError:!1}}return t.status==="completed"?{text:t.text??"(no output)",isError:!1}:t.status==="stopped"?{text:`Agent ${e} was stopped.`,isError:!0}:{text:`Agent ${e} failed: ${t.error??"unknown error"}`,isError:!0}}function G(t,e){let n=R(e),i=I(n);t.tool("agent",m+n.catalog,i,async(o,s)=>{try{let{run_in_background:c,...T}=o,a=await d(e,"start",{params:T,background:!!c,cwd:process.cwd(),selection:e.selection,project:e.project,channel:e.channel,backend:e.backend});if(c)return u(`Agent ${a.id} started in the background. Its result will be delivered to you when it is ready. Stop it early with agent_stop("${a.id}").`);let p=await C(e,a.id,D(s,a.id));p.timedOut&&await N(e,a.id);let{text:A,isError:O}=U(p,a.id);return u(A,O)}catch(c){return u(`agent error: ${c.message}`,!0)}}),t.tool("agent_stop","Stop a subagent and discard its output; not for collecting results.",{agent_id:r.string().describe("The agent_id returned when the subagent was started.")},async({agent_id:o})=>{try{let s=await d(e,"stop",{runId:o});return u(`Agent ${s.id} is now ${s.status}.`)}catch(s){return u(`agent_stop error: ${s.message}`,!0)}})}export{F as CLIENT_IDLE_FLOOR_MS,E as FOREGROUND_DEADLINE_MS,$ as WAIT_REQUEST_TIMEOUT_MS,G as registerSubagentTools};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{p as a,q as b}from"./chunk-BZDIAI5M.js";import"./chunk-IA6IODY3.js";import"./chunk-IYVZHGUQ.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-B3XBQEFM.js";import"./chunk-ETIBCA2S.js";import"./chunk-R6CGBSTC.js";import"./chunk-TMV2ZDOI.js";import"./chunk-V7K3KNDM.js";import"./chunk-RA2BUYI3.js";import"./chunk-U23S37TT.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-5M4PFLRW.js";import"./chunk-STCNHXPJ.js";import"./chunk-STUHNKQS.js";import"./chunk-W34AK4SK.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";export{a as childExtensions,b as installToolShims};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as s}from"./chunk-E6BYRULL.js";import{a as r}from"./chunk-KGJZAYQD.js";import"./chunk-FF7UELTU.js";import"./chunk-23PRJECN.js";import"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-K4NTZEDJ.js";import"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var n={api:"typesafe-system-one",label:"System One API",detectCompat:e=>e.provider==="openrouter"||e.baseUrl.includes("openrouter.ai")?{imageInput:"state-image-urls",sendImageOptInHeader:!1}:{imageInput:"assets",sendImageOptInHeader:!0},url:e=>new URL("systemone",`${e.baseUrl.replace(/\/+$/u,"")}/`),payload:(e,t)=>({model:e.id,...t}),output:e=>{if(!r(e))throw new Error("System One API returned an unexpected response");return e}},m=(e,t,a)=>s(n,e,t,a);export{m as classify};
@@ -1,5 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{b as c}from"./chunk-TURBFBYN.js";import{a as i,c as a,d}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as s}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";var b="Open a board: a live HTML status page shown in the Web UI, worth it when you dispatch several workers or the task spans many turns or hours. Give `title` to create one, or `board` (id or slug) to attach to an existing one. Binds this session, and your active workers that have no board yet if you lead a team. Returns the board directory.";async function l(o,e){let r=d(o);if(!r)throw new Error("No web session in context \u2014 boards are only available in Web UI sessions");let{body:t}=await i("POST",`${o.webhookBaseUrl}/webhook/board`,{sessionId:r,...e},a(o));if(!t?.success)throw new Error(t?.error||`board ${String(e.action)} failed`);return t.data}function h(o,e=!1){return{content:[{type:"text",text:o}],...e?{isError:!0}:{}}}function u(o){let e=o.bound.length-1;return[c(o),`Board directory: ${o.dir}`,`Edit ${o.dir}/board.html (body content only); put images in ${o.dir}/assets/.`,e>0?`Bound this session and ${e} worker(s).`:"Bound this session.","Write with the preset classes from the board skill; the scaffold has an example of every component."].join(`
5
- `)}function y(o,e){o.tool("board_open",b,{title:s.string().optional().describe("Title of a new board."),board:s.string().optional().describe("Id or slug of an existing board.")},async({title:r,board:t})=>{try{if(!!r?.trim()==!!t?.trim())throw new Error("give exactly one of title or board");let n=await l(e,{action:"open",...r?.trim()?{title:r}:{board:t}});return h(u(n))}catch(n){return h(`board_open failed: ${n.message}`,!0)}})}export{u as openedText,y as registerUiBoardTools};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as r,c as a,d as c}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as e}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";var h="Record choices the user did not dictate: approach, plan/scope changes, tools, or parameters. Skip mechanical steps. Non-blocking; for approval before proceeding use cortex_ask_user. Batch related decisions. Explain what and why briefly in plain language for a reader new to the work, using the conversation language.",m=e.object({title:e.string().min(1).max(120).describe("Decision in one short line."),decision:e.string().min(1).max(1e3).describe("What you decided, in 1-2 plain sentences a non-expert can follow."),context:e.string().min(1).max(1e3).describe("Task and alternatives: why a choice was needed."),reasoning:e.string().min(1).max(1e3).describe("Decisive trade-off, in 1-2 sentences.")});function g(d,i){d.tool("send_decision",h,{decisions:e.array(m).min(1).max(10).describe("Decisions, one card each.")},async({decisions:s})=>{try{let n=c(i);if(!n)throw new Error("No web session in context \u2014 send_decision is only usable inside a Web UI chat session");let{body:o}=await r("POST",`${i.webhookBaseUrl}/webhook/ui-decision`,{sessionId:n,decisions:s},a(i));if(!o.success)throw new Error(o.error||"send_decision failed");let t=o.data?.titles??s.map(l=>l.title);return{content:[{type:"text",text:`Recorded ${t.length} decision(s) in the chat: ${t.join(" \xB7 ")}`}]}}catch(n){return{content:[{type:"text",text:`Failed to send decisions: ${n.message}`}],isError:!0}}})}export{g as registerUiDecisionTools};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as h,c as w,d as f}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as e}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as i from"fs";import*as n from"path";var x="Render an interactive HTML card, not a download. Use when visuals convey more than Markdown; not for plain text, single numbers, or decoration. Sandboxed: no Cortex, parent DOM, credentials, storage, cookies, or same-origin requests. HTTPS resources allowed. Inline CSS/JS; relative paths fail.";function T(p,s){p.tool("send_view",x,{title:e.string().describe("Short card title."),html:e.string().optional().describe("Self-contained HTML, max 256KB. Use html OR file_path."),file_path:e.string().optional().describe("Existing .html file, max 2MB. Use file_path OR html."),caption:e.string().optional().describe("Optional one-line note shown above the view."),height:e.number().optional().describe("First-paint height in px (160-900, default 360). The view auto-resizes after load."),width:e.enum(["narrow","wide","full"]).optional().describe("Card width: narrow (default, text column), wide (~1.5x), or full chat pane.")},async({title:m,html:a,file_path:o,caption:u,height:b,width:g})=>{try{let r=f(s);if(!r)throw new Error("No web session in context \u2014 send_view is only usable inside a Web UI chat session");let v=typeof a=="string"&&a.length>0,d=typeof o=="string"&&o.length>0;if(v===d)throw new Error("Provide exactly one of `html` or `file_path`");let t;if(d){if(t=n.isAbsolute(o)?o:n.resolve(process.cwd(),o),!i.existsSync(t))throw new Error(`File not found: ${t}`);if(!i.statSync(t).isFile())throw new Error(`Not a file: ${t}`)}let{body:l}=await h("POST",`${s.webhookBaseUrl}/webhook/ui-view`,{sessionId:r,title:m,html:a,filePath:t,caption:u,height:b,width:g},w(s));if(!l.success)throw new Error(l.error||"send_view failed");let c=l.data;return{content:[{type:"text",text:`Rendered view in the chat: ${c.name} (${c.size} bytes)`}]}}catch(r){return{content:[{type:"text",text:`Failed to send view: ${r.message}`}],isError:!0}}})}export{T as registerUiViewTools};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as p,b as n,c as i,lb as m}from"./chunk-NNTQUHLO.js";import"./chunk-HGPBHTVD.js";import"./chunk-Y3GFB5XM.js";import"./chunk-3CZPBLB3.js";import{B as a,z as r}from"./chunk-LAWOWPZX.js";import"./chunk-EQIMHXC4.js";import"./chunk-VQUPKMDR.js";import"./chunk-WEZWKMYU.js";import"./chunk-YKKEI5GI.js";import"./chunk-ZNZFWSPH.js";import"./chunk-4EX2JJWB.js";import"./chunk-BJGYGEZO.js";import"./chunk-RA6HKFBV.js";import"./chunk-AFTBQRPN.js";import"./chunk-XEBEWR6Y.js";import"./chunk-5DF5WJNM.js";import"./chunk-FX6MOGLR.js";import{Z as d}from"./chunk-CK3P345X.js";import"./chunk-ZQ7LGTSN.js";import{oa as e}from"./chunk-LACGULCN.js";import"./chunk-3TGQSGG4.js";import"./chunk-QUUEQRIT.js";import"./chunk-KDYEGGMW.js";import"./chunk-SKHLZ6XY.js";import"./chunk-6R73ICDB.js";import{N as o}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import"./chunk-AWFUHWQK.js";import"./chunk-G2V65UBA.js";import"./chunk-NHD2ESHA.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";var l={};var t={typebox:e,"typebox/compile":a,"typebox/value":r,"@sinclair/typebox":e,"@sinclair/typebox/compile":a,"@sinclair/typebox/value":r,"@earendil-works/pi-agent-core":p,"@earendil-works/pi-tui":d,"@earendil-works/pi-ai":i,"@earendil-works/pi-ai/compat":i,"@earendil-works/pi-ai/models":o,"@earendil-works/pi-ai/oauth":l,"@earendil-works/pi-ai/providers/all":n,"@earendil-works/pi-coding-agent":m,"@mariozechner/pi-agent-core":p,"@mariozechner/pi-tui":d,"@mariozechner/pi-ai":i,"@mariozechner/pi-ai/compat":i,"@mariozechner/pi-ai/models":o,"@mariozechner/pi-ai/oauth":l,"@mariozechner/pi-ai/providers/all":n,"@mariozechner/pi-coding-agent":m};export{t as VIRTUAL_MODULES};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as l,c as d}from"./chunk-UT6DGZDO.js";import{e as a,l as i}from"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as o}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";var p=30*1e3;async function w(e,r,s){let{body:t}=await l("POST",`${e.webhookBaseUrl}/webhook/team`,{action:r,sessionId:e.sessionId,...s},d(e),p);if(!t?.success)throw new Error(t?.error||`${r} failed`);return t.data}function u(e,r=!1){return{content:[{type:"text",text:e}],...r?{isError:!0}:{}}}var c="Returns immediately; reports and questions arrive as messages. After dispatch, end your turn; do not wait or poll.",k={model:"Model override: pi provider/model[:thinking], claude model ID. Default: your model on the same backend, otherwise that backend's default.",backend:"Backend override. Default: your backend."};function m(e){try{return i(a(e))}catch{return""}}function n(e,r){return async s=>{try{let t=await w(e,r,s);return u(typeof t?.text=="string"?t.text:JSON.stringify(t,null,2))}catch(t){return u(`${r} error: ${t.message}`,!0)}}}function y(e,r){let s=k;e.tool("worker_spawn",`Start a persistent, isolated session with full tools for follow-up or long-running work. Use for multiple/splittable tasks or a new task; keep single tasks here. For bounded work whose result you need now, use agent. Provide a self-contained prompt; workers cannot see this conversation. The user can talk to them directly. Final replies report back except routine updates; questions and approvals route to you (worker_answer). ${c}${m(r)}`,{name:o.string().describe("Unique slug: lowercase letters, digits, hyphens; max 32 characters."),prompt:o.string().describe("Complete, self-contained task for the worker."),backend:o.enum(["claude","pi"]).optional().describe(s.backend),model:o.string().optional().describe(s.model)},n(r,"spawn")),e.tool("worker_send","Continue or redirect a worker; injects into a running turn or starts a new one. Reaches inactive workers too. Reuse a relevant worker rather than spawning another. "+c,{worker:o.string().describe("The worker name."),message:o.string().describe("The message to deliver.")},n(r,"send")),e.tool("worker_list","List your workers, or inspect one with its full last report. Completion reports arrive automatically.",{worker:o.string().optional().describe("A worker name for its detail view.")},n(r,"list")),e.tool("worker_stop","Stop a worker's current turn. worker_send continues it later.",{worker:o.string().describe("The worker name.")},n(r,"stop")),e.tool("worker_answer","Answer a worker question or approve/reject its plan. Ask cortex_ask_user first if unsure of user intent. The user may also answer; first answer wins.",{request_id:o.string().describe("The request_id from the worker notice."),answers:o.record(o.string(),o.string()).optional().describe("Exact question text \u2192 answer, for a question."),approved:o.boolean().optional().describe("Approve or reject a plan."),feedback:o.string().optional().describe("Feedback for the worker, mainly when rejecting a plan.")},n(r,"answer"))}function _(e,r){e.tool("mark_routine","Before your final reply, mark a no-change or duplicate update so it does not wake the lead. Never use for results, milestones, failures, blockers, or needed action. Ask for decisions with cortex_ask_user.",{},n(r,"routine"))}export{_ as registerWorkerReportTools,y as registerWorkerTools};