@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,7 +1,7 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as ii}from"./chunk-I6OPDRVF.js";import{e as ti,f as ri}from"./chunk-LP72AF56.js";import{e as Se}from"./chunk-VBN2JSER.js";import{a as F,c as f}from"./chunk-WHC7AYZD.js";var ee=f(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.ErrorCode=void 0;U.errorWithCode=V;U.requestErrorWithOriginal=ni;U.httpErrorFromResponse=ai;U.platformErrorFromResult=oi;U.rateLimitedErrorWithDelay=li;var $;(function(r){r.RequestError="slack_webapi_request_error",r.HTTPError="slack_webapi_http_error",r.PlatformError="slack_webapi_platform_error",r.RateLimitedError="slack_webapi_rate_limited_error",r.FileUploadInvalidArgumentsError="slack_webapi_file_upload_invalid_args_error",r.FileUploadReadFileDataError="slack_webapi_file_upload_read_file_data_error"})($||(U.ErrorCode=$={}));function V(r,e){let t=r;return t.code=e,t}function ni(r,e){let t=V(new Error(`A request error occurred: ${r.message}`),$.RequestError);return e&&(t.original=r),t}function ai(r){let e=V(new Error(`An HTTP protocol error occurred: statusCode = ${r.status}`),$.HTTPError);e.statusCode=r.status,e.statusMessage=r.statusText;let t={};for(let i of Object.keys(r.headers))i&&r.headers[i]&&(t[i]=r.headers[i]);return e.headers=t,e.body=r.data,e}function oi(r){let e=V(new Error(`An API error occurred: ${r.error}`),$.PlatformError);return e.data=r,e}function li(r){let e=V(new Error(`A rate-limit has been reached, you may retry this request in ${r} seconds`),$.RateLimitedError);return e.retryAfter=r,e}});var Re=f((qs,ui)=>{ui.exports={name:"@slack/web-api",version:"7.19.0",description:"Official library for using the Slack Platform's Web API",author:"Slack Technologies, LLC",license:"MIT",keywords:["slack","web-api","bot","client","http","api","proxy","rate-limiting","pagination"],main:"dist/index.js",types:"./dist/index.d.ts",files:["dist/**/*"],engines:{node:">= 18",npm:">= 8.6.0"},repository:{type:"git",url:"git+https://github.com/slackapi/node-slack-sdk.git"},homepage:"https://docs.slack.dev/tools/node-slack-sdk/web-api/",publishConfig:{access:"public"},bugs:{url:"https://github.com/slackapi/node-slack-sdk/issues"},scripts:{build:"npm run build:clean && tsc","build:clean":"shx rm -rf ./dist",docs:"npx typedoc --plugin typedoc-plugin-markdown",prepack:"npm run build",test:"npm run build && bash -c 'node --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=test-results.xml --import tsx --test src/*.test.ts'","test:coverage":"npm run build && node --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=lcov.info --test-reporter=junit --test-reporter-destination=test-results.xml --import tsx --test src/*.test.ts","test:integration":"npm run build && node test/integration/commonjs-project/index.js && node test/integration/esm-project/index.mjs && npm run test:integration:ts","test:integration:ts":"cd test/integration/ts-4.7-project && npm i && npm run build","test:types":"tsd",watch:"npx nodemon --watch 'src' --ext 'ts' --exec npm run build"},dependencies:{"@slack/logger":"^4.0.1","@slack/types":"^2.21.0","@types/node":">=18","@types/retry":"0.12.0",axios:"^1.16.0",eventemitter3:"^5.0.1","form-data":"^4.0.4","is-electron":"2.2.2","is-stream":"^2","p-queue":"^6","p-retry":"^4",retry:"^0.13.1"},devDependencies:{"@types/busboy":"^1.5.4","@types/sinon":"^21",busboy:"^1",nock:"^14",sinon:"^21",tsd:"^0.33.0"},tsd:{directory:"test/types"}}});var ue=f(R=>{"use strict";var ci=R&&R.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),di=R&&R.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),hi=R&&R.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&ci(t,e,i[n]);return di(t,e),t}})();Object.defineProperty(R,"__esModule",{value:!0});R.addAppMetadata=_i;R.getUserAgent=vi;var Te=hi(F("node:os")),fi=F("node:path"),Ue=Re();function Le(r){return r.replace("/",":")}var pi=255;function mi(r){let e="";for(let t of r)e+=t.charCodeAt(0)<=pi?t:encodeURIComponent(t);return e}var gi=`${Le(Ue.name)}/${Ue.version} ${mi((0,fi.basename)(process.title))}/${process.version.replace("v","")} ${Te.platform()}/${Te.release()}`,Fe={};function _i({name:r,version:e}){Fe[Le(r)]=e}function vi(){let r=Object.entries(Fe).map(([e,t])=>`${e}/${t}`).join(" ");return(r.length>0?`${r} `:"")+gi}});var ce=f(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.ConsoleLogger=N.LogLevel=void 0;var P;(function(r){r.ERROR="error",r.WARN="warn",r.INFO="info",r.DEBUG="debug"})(P||(N.LogLevel=P={}));var J=class r{constructor(){this.level=P.INFO,this.name=""}getLevel(){return this.level}setLevel(e){this.level=e}setName(e){this.name=e}debug(...e){r.isMoreOrEqualSevere(P.DEBUG,this.level)&&console.debug(r.labels.get(P.DEBUG),this.name,...e)}info(...e){r.isMoreOrEqualSevere(P.INFO,this.level)&&console.info(r.labels.get(P.INFO),this.name,...e)}warn(...e){r.isMoreOrEqualSevere(P.WARN,this.level)&&console.warn(r.labels.get(P.WARN),this.name,...e)}error(...e){r.isMoreOrEqualSevere(P.ERROR,this.level)&&console.error(r.labels.get(P.ERROR),this.name,...e)}static isMoreOrEqualSevere(e,t){return r.severity[e]>=r.severity[t]}};N.ConsoleLogger=J;J.labels=(()=>{let e=Object.entries(P).map(([t,i])=>[i,`[${t}] `]);return new Map(e)})();J.severity={[P.ERROR]:400,[P.WARN]:300,[P.INFO]:200,[P.DEBUG]:100}});var de=f(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.LogLevel=void 0;G.getLogger=wi;var yi=ce(),bi=ce();Object.defineProperty(G,"LogLevel",{enumerable:!0,get:function(){return bi.LogLevel}});var De=0;function wi(r,e,t){let i=De;De+=1;let n=t!==void 0?t:new yi.ConsoleLogger;return n.setName(`web-api:${r}:${i}`),e!==void 0&&n.setLevel(e),n}});var he=f(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.rapidRetryPolicy=q.fiveRetriesInFiveMinutes=q.tenRetriesInAboutThirtyMinutes=void 0;q.tenRetriesInAboutThirtyMinutes={retries:10,factor:1.96821,randomize:!0};q.fiveRetriesInFiveMinutes={retries:5,factor:3.86};q.rapidRetryPolicy={minTimeout:0,maxTimeout:1};var Oi={tenRetriesInAboutThirtyMinutes:q.tenRetriesInAboutThirtyMinutes,fiveRetriesInFiveMinutes:q.fiveRetriesInFiveMinutes,rapidRetryPolicy:q.rapidRetryPolicy};q.default=Oi});var $e=f(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0})});var ze=f(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0})});var me=f(z=>{"use strict";var fe=z&&z.__rest||function(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(r);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(r,i[n])&&(t[i[n]]=r[i[n]]);return t};Object.defineProperty(z,"__esModule",{value:!0});z.ChatStreamer=void 0;var pe=class{constructor(e,t,i,n){var o;this.buffer="",this.client=e,this.logger=t,this.options={buffer_size:(o=n.buffer_size)!==null&&o!==void 0?o:256},this.state="starting",this.streamArgs=i}get ts(){return this.streamTs}async append(e){if(this.state==="completed")throw new Error(`failed to append stream: stream state is ${this.state}`);let{markdown_text:t,chunks:i}=e,n=fe(e,["markdown_text","chunks"]);if(n.token&&(this.token=n.token),t&&(this.buffer+=t),this.buffer.length>=this.options.buffer_size||i)return await this.flushBuffer(Object.assign({chunks:i},n));let o={bufferLength:this.buffer.length,bufferSize:this.options.buffer_size,channel:this.streamArgs.channel,recipientTeamId:this.streamArgs.recipient_team_id,recipientUserId:this.streamArgs.recipient_user_id,threadTs:this.streamArgs.thread_ts};return this.logger.debug(`ChatStreamer appended to buffer: ${JSON.stringify(o)}`),null}async stop(e){if(this.state==="completed")throw new Error(`failed to stop stream: stream state is ${this.state}`);let t=e??{},{markdown_text:i,chunks:n}=t,o=fe(t,["markdown_text","chunks"]);if(o.token&&(this.token=o.token),i&&(this.buffer+=i),!this.streamTs){let a=await this.client.chat.startStream(Object.assign(Object.assign({},this.streamArgs),{token:this.token}));if(!a.ts)throw new Error("failed to stop stream: stream not started");this.streamTs=a.ts,this.state="in_progress"}let l=[];this.buffer.length>0&&l.push({type:"markdown_text",text:this.buffer}),n&&l.push(...n);let u=await this.client.chat.stopStream(Object.assign({token:this.token,channel:this.streamArgs.channel,ts:this.streamTs,chunks:l},o));return this.state="completed",u}async flushBuffer(e){let t=e??{},{chunks:i}=t,n=fe(t,["chunks"]),o=[];if(this.buffer.length>0&&o.push({type:"markdown_text",text:this.buffer}),i&&o.push(...i),!this.streamTs){let u=await this.client.chat.startStream(Object.assign(Object.assign(Object.assign({},this.streamArgs),{token:this.token,chunks:o}),n));return this.buffer="",this.streamTs=u.ts,this.state="in_progress",u}let l=await this.client.chat.appendStream(Object.assign({token:this.token,channel:this.streamArgs.channel,ts:this.streamTs,chunks:o},n));return this.buffer="",l}};z.ChatStreamer=pe});var Ve=f((Ls,Be)=>{function Ei(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}Be.exports=Ei});var Ge=f((Fs,Je)=>{"use strict";var T=r=>r!==null&&typeof r=="object"&&typeof r.pipe=="function";T.writable=r=>T(r)&&r.writable!==!1&&typeof r._write=="function"&&typeof r._writableState=="object";T.readable=r=>T(r)&&r.readable!==!1&&typeof r._read=="function"&&typeof r._readableState=="object";T.duplex=r=>T.writable(r)&&T.readable(r);T.transform=r=>T.duplex(r)&&typeof r._transform=="function";Je.exports=T});var He=f((Ds,ge)=>{"use strict";var Pi=Object.prototype.hasOwnProperty,M="~";function K(){}Object.create&&(K.prototype=Object.create(null),new K().__proto__||(M=!1));function ki(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ke(r,e,t,i,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new ki(t,i||r,n),l=M?M+e:e;return r._events[l]?r._events[l].fn?r._events[l]=[r._events[l],o]:r._events[l].push(o):(r._events[l]=o,r._eventsCount++),r}function te(r,e){--r._eventsCount===0?r._events=new K:delete r._events[e]}function k(){this._events=new K,this._eventsCount=0}k.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)Pi.call(t,i)&&e.push(M?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};k.prototype.listeners=function(e){var t=M?M+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,l=new Array(o);n<o;n++)l[n]=i[n].fn;return l};k.prototype.listenerCount=function(e){var t=M?M+e:e,i=this._events[t];return i?i.fn?1:i.length:0};k.prototype.emit=function(e,t,i,n,o,l){var u=M?M+e:e;if(!this._events[u])return!1;var a=this._events[u],h=arguments.length,d,c;if(a.fn){switch(a.once&&this.removeListener(e,a.fn,void 0,!0),h){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,t),!0;case 3:return a.fn.call(a.context,t,i),!0;case 4:return a.fn.call(a.context,t,i,n),!0;case 5:return a.fn.call(a.context,t,i,n,o),!0;case 6:return a.fn.call(a.context,t,i,n,o,l),!0}for(c=1,d=new Array(h-1);c<h;c++)d[c-1]=arguments[c];a.fn.apply(a.context,d)}else{var E=a.length,p;for(c=0;c<E;c++)switch(a[c].once&&this.removeListener(e,a[c].fn,void 0,!0),h){case 1:a[c].fn.call(a[c].context);break;case 2:a[c].fn.call(a[c].context,t);break;case 3:a[c].fn.call(a[c].context,t,i);break;case 4:a[c].fn.call(a[c].context,t,i,n);break;default:if(!d)for(p=1,d=new Array(h-1);p<h;p++)d[p-1]=arguments[p];a[c].fn.apply(a[c].context,d)}}return!0};k.prototype.on=function(e,t,i){return Ke(this,e,t,i,!1)};k.prototype.once=function(e,t,i){return Ke(this,e,t,i,!0)};k.prototype.removeListener=function(e,t,i,n){var o=M?M+e:e;if(!this._events[o])return this;if(!t)return te(this,o),this;var l=this._events[o];if(l.fn)l.fn===t&&(!n||l.once)&&(!i||l.context===i)&&te(this,o);else{for(var u=0,a=[],h=l.length;u<h;u++)(l[u].fn!==t||n&&!l[u].once||i&&l[u].context!==i)&&a.push(l[u]);a.length?this._events[o]=a.length===1?a[0]:a:te(this,o)}return this};k.prototype.removeAllListeners=function(e){var t;return e?(t=M?M+e:e,this._events[t]&&te(this,t)):(this._events=new K,this._eventsCount=0),this};k.prototype.off=k.prototype.removeListener;k.prototype.addListener=k.prototype.on;k.prefixed=M;k.EventEmitter=k;typeof ge<"u"&&(ge.exports=k)});var Qe=f((Ws,Ye)=>{"use strict";Ye.exports=(r,e)=>(e=e||(()=>{}),r.then(t=>new Promise(i=>{i(e())}).then(()=>t),t=>new Promise(i=>{i(e())}).then(()=>{throw t})))});var Ze=f(($s,ie)=>{"use strict";var Ci=Qe(),re=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Xe=(r,e,t)=>new Promise((i,n)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){i(r);return}let o=setTimeout(()=>{if(typeof t=="function"){try{i(t())}catch(a){n(a)}return}let l=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new re(l);typeof r.cancel=="function"&&r.cancel(),n(u)},e);Ci(r.then(i,n),()=>{clearTimeout(o)})});ie.exports=Xe;ie.exports.default=Xe;ie.exports.TimeoutError=re});var et=f(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});function Mi(r,e,t){let i=0,n=r.length;for(;n>0;){let o=n/2|0,l=i+o;t(r[l],e)<=0?(i=++l,n-=o+1):n=o}return i}_e.default=Mi});var tt=f(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});var ji=et(),ve=class{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);let i={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(i);return}let n=ji.default(this._queue,i,(o,l)=>l.priority-o.priority);this._queue.splice(n,0,i)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this._queue.length}};ye.default=ve});var it=f(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});var qi=He(),rt=Ze(),Ii=tt(),se=()=>{},Ai=new rt.TimeoutError,be=class extends qi{constructor(e){var t,i,n,o;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=se,this._resolveIdle=se,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Ii.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(i=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&i!==void 0?i:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(n=e.interval)===null||n===void 0?void 0:n.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=se,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=se,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return t?(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((i,n)=>{let o=async()=>{this._pendingCount++,this._intervalCount++;try{let l=this._timeout===void 0&&t.timeout===void 0?e():rt.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&n(Ai)});i(await l)}catch(l){n(l)}this._next()};this._queue.enqueue(o,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async i=>this.add(i,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};we.default=be});var Et=f(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.getFileUploadJob=Oe;v.getMultipleFileUploadJobs=Ri;v.getFileData=st;v.getFileDataLength=nt;v.getFileDataAsStream=at;v.getAllFileUploadsToComplete=Ti;v.warnIfNotUsingFilesUploadV2=Ui;v.warnIfChannels=ot;v.errorIfChannelsCsv=lt;v.errorIfInvalidOrMissingFileData=ut;v.warnIfMissingOrInvalidFileNameAndDefault=ct;v.warnIfLegacyFileType=dt;v.buildMissingFileIdError=ht;v.buildFileSizeErrorMsg=ft;v.buildLegacyFileTypeWarning=pt;v.buildMissingFileNameWarning=mt;v.buildMissingExtensionWarning=gt;v.buildLegacyMethodWarning=_t;v.buildGeneralFilesUploadWarning=vt;v.buildFilesUploadMissingMessage=yt;v.buildChannelsWarning=bt;v.buildMultipleChannelsErrorMsg=wt;v.buildInvalidFilesUploadParamError=Ot;var Si=F("node:fs"),xi=F("node:stream"),w=ee();async function Oe(r,e){var t,i,n,o;dt(r,e),ot(r,e),lt(r);let l=ct(r,e),u=await st(r),a=nt(u),h={alt_text:r.alt_text,blocks:r.blocks,channel_id:(t=r.channels)!==null&&t!==void 0?t:r.channel_id,filename:(i=r.filename)!==null&&i!==void 0?i:l,highlight_type:r.highlight_type,initial_comment:r.initial_comment,snippet_type:r.snippet_type,title:(o=(n=r.title)!==null&&n!==void 0?n:r.filename)!==null&&o!==void 0?o:l,data:u,length:a};if("thread_ts"in r&&(h.thread_ts=r.thread_ts),"token"in r&&(h.token=r.token),"content"in r)return Object.assign({content:r.content},h);if("file"in r)return Object.assign({file:r.file},h);throw(0,w.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"),w.ErrorCode.FileUploadInvalidArgumentsError)}async function Ri(r,e){if("file_uploads"in r)return Promise.all(r.file_uploads.map(t=>{let{blocks:i,channel_id:n,channels:o,initial_comment:l,thread_ts:u}=t;if(i||n||o||l||u)throw(0,w.errorWithCode)(new Error(Ot()),w.ErrorCode.FileUploadInvalidArgumentsError);let a=Object.assign(Object.assign({},t),{blocks:r.blocks,channels:r.channels,channel_id:r.channel_id,initial_comment:r.initial_comment});if("thread_ts"in r&&(a.thread_ts=r.thread_ts),"token"in r&&(a.token=r.token),"content"in t)return Oe(Object.assign({content:t.content},a),e);if("file"in t)return Oe(Object.assign({file:t.file},a),e);throw(0,w.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"),w.ErrorCode.FileUploadInvalidArgumentsError)}));throw new Error(yt())}async function st(r){if(ut(r),"file"in r){let{file:e}=r;if(Buffer.isBuffer(e))return e;if(typeof e=="string")try{return(0,Si.readFileSync)(e)}catch{throw(0,w.errorWithCode)(new Error(`Unable to resolve file data for ${e}. Please supply a filepath string, or binary data Buffer or String directly.`),w.ErrorCode.FileUploadInvalidArgumentsError)}let t=await at(e);if(t)return t}if("content"in r)return Buffer.from(r.content);throw(0,w.errorWithCode)(new Error("There was an issue getting the file data for the file or content supplied"),w.ErrorCode.FileUploadReadFileDataError)}function nt(r){if(r)return Buffer.byteLength(r,"utf8");throw(0,w.errorWithCode)(new Error(ft()),w.ErrorCode.FileUploadReadFileDataError)}async function at(r){let e=[];return new Promise((t,i)=>{r.on("readable",()=>{let n=r.read();for(;n!==null;)e.push(n),n=r.read()}),r.on("end",()=>{if(e.length>0){let n=Buffer.concat(e);t(n)}else i(Error("No data in supplied file"))})})}function Ti(r){let e={};for(let t of r){let{blocks:i,channel_id:n,thread_ts:o,highlight_type:l,initial_comment:u,file_id:a,title:h}=t;if(a){let d=`:::${n}:::${o}:::${u}:::${JSON.stringify(i)}`;if(Object.prototype.hasOwnProperty.call(e,d))e[d].files.push({id:a,title:h,highlight_type:l});else{if(e[d]={files:[{id:a,title:h,highlight_type:l}],channel_id:n,blocks:i,initial_comment:u},o&&n){let c={channel_id:n,thread_ts:o};e[d]=Object.assign(Object.assign({},e[d]),c)}"token"in t&&(e[d].token=t.token)}}else throw new Error(ht())}return e}function Ui(r,e){let i=["files.upload"].includes(r);r==="files.upload"&&e.warn(_t(r)),i&&e.info(vt())}function ot(r,e){r.channels&&e.warn(bt())}function lt(r){if((r.channels?r.channels.split(","):[]).length>1)throw(0,w.errorWithCode)(new Error(wt()),w.ErrorCode.FileUploadInvalidArgumentsError)}function ut(r){let e="file"in r,t="content"in r;if(!(e||t)||e&&t)throw(0,w.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You cannot supply both"),w.ErrorCode.FileUploadInvalidArgumentsError);if("file"in r){let{file:i}=r;if(i&&!(typeof i=="string"||Buffer.isBuffer(i)||i instanceof xi.Readable))throw(0,w.errorWithCode)(new Error("file must be a valid string path, buffer or Readable"),w.ErrorCode.FileUploadInvalidArgumentsError)}if("content"in r&&r.content&&typeof r.content!="string")throw(0,w.errorWithCode)(new Error("content must be a string"),w.ErrorCode.FileUploadInvalidArgumentsError)}function ct(r,e){var t;let n=`file.${(t=r.filetype)!==null&&t!==void 0?t:"txt"}`,{filename:o}=r;return o?(o.split(".").length<2&&e.warn(gt(o)),o):(e.warn(mt()),n)}function dt(r,e){r.filetype&&e.warn(pt())}function ht(){return"Missing required file id for file upload completion"}function ft(){return"There was an issue calculating the size of your file"}function pt(){return`filetype is no longer a supported field in files.uploadV2.
4
+ import{a as ii}from"./chunk-I6OPDRVF.js";import{e as ti,f as ri}from"./chunk-LP72AF56.js";import{e as Se}from"./chunk-7W7VYUTK.js";import{a as F,c as f}from"./chunk-WHC7AYZD.js";var ee=f(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.ErrorCode=void 0;U.errorWithCode=V;U.requestErrorWithOriginal=ni;U.httpErrorFromResponse=ai;U.platformErrorFromResult=oi;U.rateLimitedErrorWithDelay=li;var $;(function(r){r.RequestError="slack_webapi_request_error",r.HTTPError="slack_webapi_http_error",r.PlatformError="slack_webapi_platform_error",r.RateLimitedError="slack_webapi_rate_limited_error",r.FileUploadInvalidArgumentsError="slack_webapi_file_upload_invalid_args_error",r.FileUploadReadFileDataError="slack_webapi_file_upload_read_file_data_error"})($||(U.ErrorCode=$={}));function V(r,e){let t=r;return t.code=e,t}function ni(r,e){let t=V(new Error(`A request error occurred: ${r.message}`),$.RequestError);return e&&(t.original=r),t}function ai(r){let e=V(new Error(`An HTTP protocol error occurred: statusCode = ${r.status}`),$.HTTPError);e.statusCode=r.status,e.statusMessage=r.statusText;let t={};for(let i of Object.keys(r.headers))i&&r.headers[i]&&(t[i]=r.headers[i]);return e.headers=t,e.body=r.data,e}function oi(r){let e=V(new Error(`An API error occurred: ${r.error}`),$.PlatformError);return e.data=r,e}function li(r){let e=V(new Error(`A rate-limit has been reached, you may retry this request in ${r} seconds`),$.RateLimitedError);return e.retryAfter=r,e}});var Re=f((qs,ui)=>{ui.exports={name:"@slack/web-api",version:"7.19.0",description:"Official library for using the Slack Platform's Web API",author:"Slack Technologies, LLC",license:"MIT",keywords:["slack","web-api","bot","client","http","api","proxy","rate-limiting","pagination"],main:"dist/index.js",types:"./dist/index.d.ts",files:["dist/**/*"],engines:{node:">= 18",npm:">= 8.6.0"},repository:{type:"git",url:"git+https://github.com/slackapi/node-slack-sdk.git"},homepage:"https://docs.slack.dev/tools/node-slack-sdk/web-api/",publishConfig:{access:"public"},bugs:{url:"https://github.com/slackapi/node-slack-sdk/issues"},scripts:{build:"npm run build:clean && tsc","build:clean":"shx rm -rf ./dist",docs:"npx typedoc --plugin typedoc-plugin-markdown",prepack:"npm run build",test:"npm run build && bash -c 'node --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=test-results.xml --import tsx --test src/*.test.ts'","test:coverage":"npm run build && node --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=lcov.info --test-reporter=junit --test-reporter-destination=test-results.xml --import tsx --test src/*.test.ts","test:integration":"npm run build && node test/integration/commonjs-project/index.js && node test/integration/esm-project/index.mjs && npm run test:integration:ts","test:integration:ts":"cd test/integration/ts-4.7-project && npm i && npm run build","test:types":"tsd",watch:"npx nodemon --watch 'src' --ext 'ts' --exec npm run build"},dependencies:{"@slack/logger":"^4.0.1","@slack/types":"^2.21.0","@types/node":">=18","@types/retry":"0.12.0",axios:"^1.16.0",eventemitter3:"^5.0.1","form-data":"^4.0.4","is-electron":"2.2.2","is-stream":"^2","p-queue":"^6","p-retry":"^4",retry:"^0.13.1"},devDependencies:{"@types/busboy":"^1.5.4","@types/sinon":"^21",busboy:"^1",nock:"^14",sinon:"^21",tsd:"^0.33.0"},tsd:{directory:"test/types"}}});var ue=f(R=>{"use strict";var ci=R&&R.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),di=R&&R.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),hi=R&&R.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&ci(t,e,i[n]);return di(t,e),t}})();Object.defineProperty(R,"__esModule",{value:!0});R.addAppMetadata=_i;R.getUserAgent=vi;var Te=hi(F("node:os")),fi=F("node:path"),Ue=Re();function Le(r){return r.replace("/",":")}var pi=255;function mi(r){let e="";for(let t of r)e+=t.charCodeAt(0)<=pi?t:encodeURIComponent(t);return e}var gi=`${Le(Ue.name)}/${Ue.version} ${mi((0,fi.basename)(process.title))}/${process.version.replace("v","")} ${Te.platform()}/${Te.release()}`,Fe={};function _i({name:r,version:e}){Fe[Le(r)]=e}function vi(){let r=Object.entries(Fe).map(([e,t])=>`${e}/${t}`).join(" ");return(r.length>0?`${r} `:"")+gi}});var ce=f(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.ConsoleLogger=N.LogLevel=void 0;var P;(function(r){r.ERROR="error",r.WARN="warn",r.INFO="info",r.DEBUG="debug"})(P||(N.LogLevel=P={}));var J=class r{constructor(){this.level=P.INFO,this.name=""}getLevel(){return this.level}setLevel(e){this.level=e}setName(e){this.name=e}debug(...e){r.isMoreOrEqualSevere(P.DEBUG,this.level)&&console.debug(r.labels.get(P.DEBUG),this.name,...e)}info(...e){r.isMoreOrEqualSevere(P.INFO,this.level)&&console.info(r.labels.get(P.INFO),this.name,...e)}warn(...e){r.isMoreOrEqualSevere(P.WARN,this.level)&&console.warn(r.labels.get(P.WARN),this.name,...e)}error(...e){r.isMoreOrEqualSevere(P.ERROR,this.level)&&console.error(r.labels.get(P.ERROR),this.name,...e)}static isMoreOrEqualSevere(e,t){return r.severity[e]>=r.severity[t]}};N.ConsoleLogger=J;J.labels=(()=>{let e=Object.entries(P).map(([t,i])=>[i,`[${t}] `]);return new Map(e)})();J.severity={[P.ERROR]:400,[P.WARN]:300,[P.INFO]:200,[P.DEBUG]:100}});var de=f(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.LogLevel=void 0;G.getLogger=wi;var yi=ce(),bi=ce();Object.defineProperty(G,"LogLevel",{enumerable:!0,get:function(){return bi.LogLevel}});var De=0;function wi(r,e,t){let i=De;De+=1;let n=t!==void 0?t:new yi.ConsoleLogger;return n.setName(`web-api:${r}:${i}`),e!==void 0&&n.setLevel(e),n}});var he=f(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.rapidRetryPolicy=q.fiveRetriesInFiveMinutes=q.tenRetriesInAboutThirtyMinutes=void 0;q.tenRetriesInAboutThirtyMinutes={retries:10,factor:1.96821,randomize:!0};q.fiveRetriesInFiveMinutes={retries:5,factor:3.86};q.rapidRetryPolicy={minTimeout:0,maxTimeout:1};var Oi={tenRetriesInAboutThirtyMinutes:q.tenRetriesInAboutThirtyMinutes,fiveRetriesInFiveMinutes:q.fiveRetriesInFiveMinutes,rapidRetryPolicy:q.rapidRetryPolicy};q.default=Oi});var $e=f(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0})});var ze=f(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0})});var me=f(z=>{"use strict";var fe=z&&z.__rest||function(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(r);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(r,i[n])&&(t[i[n]]=r[i[n]]);return t};Object.defineProperty(z,"__esModule",{value:!0});z.ChatStreamer=void 0;var pe=class{constructor(e,t,i,n){var o;this.buffer="",this.client=e,this.logger=t,this.options={buffer_size:(o=n.buffer_size)!==null&&o!==void 0?o:256},this.state="starting",this.streamArgs=i}get ts(){return this.streamTs}async append(e){if(this.state==="completed")throw new Error(`failed to append stream: stream state is ${this.state}`);let{markdown_text:t,chunks:i}=e,n=fe(e,["markdown_text","chunks"]);if(n.token&&(this.token=n.token),t&&(this.buffer+=t),this.buffer.length>=this.options.buffer_size||i)return await this.flushBuffer(Object.assign({chunks:i},n));let o={bufferLength:this.buffer.length,bufferSize:this.options.buffer_size,channel:this.streamArgs.channel,recipientTeamId:this.streamArgs.recipient_team_id,recipientUserId:this.streamArgs.recipient_user_id,threadTs:this.streamArgs.thread_ts};return this.logger.debug(`ChatStreamer appended to buffer: ${JSON.stringify(o)}`),null}async stop(e){if(this.state==="completed")throw new Error(`failed to stop stream: stream state is ${this.state}`);let t=e??{},{markdown_text:i,chunks:n}=t,o=fe(t,["markdown_text","chunks"]);if(o.token&&(this.token=o.token),i&&(this.buffer+=i),!this.streamTs){let a=await this.client.chat.startStream(Object.assign(Object.assign({},this.streamArgs),{token:this.token}));if(!a.ts)throw new Error("failed to stop stream: stream not started");this.streamTs=a.ts,this.state="in_progress"}let l=[];this.buffer.length>0&&l.push({type:"markdown_text",text:this.buffer}),n&&l.push(...n);let u=await this.client.chat.stopStream(Object.assign({token:this.token,channel:this.streamArgs.channel,ts:this.streamTs,chunks:l},o));return this.state="completed",u}async flushBuffer(e){let t=e??{},{chunks:i}=t,n=fe(t,["chunks"]),o=[];if(this.buffer.length>0&&o.push({type:"markdown_text",text:this.buffer}),i&&o.push(...i),!this.streamTs){let u=await this.client.chat.startStream(Object.assign(Object.assign(Object.assign({},this.streamArgs),{token:this.token,chunks:o}),n));return this.buffer="",this.streamTs=u.ts,this.state="in_progress",u}let l=await this.client.chat.appendStream(Object.assign({token:this.token,channel:this.streamArgs.channel,ts:this.streamTs,chunks:o},n));return this.buffer="",l}};z.ChatStreamer=pe});var Ve=f((Ls,Be)=>{function Ei(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}Be.exports=Ei});var Ge=f((Fs,Je)=>{"use strict";var T=r=>r!==null&&typeof r=="object"&&typeof r.pipe=="function";T.writable=r=>T(r)&&r.writable!==!1&&typeof r._write=="function"&&typeof r._writableState=="object";T.readable=r=>T(r)&&r.readable!==!1&&typeof r._read=="function"&&typeof r._readableState=="object";T.duplex=r=>T.writable(r)&&T.readable(r);T.transform=r=>T.duplex(r)&&typeof r._transform=="function";Je.exports=T});var He=f((Ds,ge)=>{"use strict";var Pi=Object.prototype.hasOwnProperty,M="~";function K(){}Object.create&&(K.prototype=Object.create(null),new K().__proto__||(M=!1));function ki(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ke(r,e,t,i,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new ki(t,i||r,n),l=M?M+e:e;return r._events[l]?r._events[l].fn?r._events[l]=[r._events[l],o]:r._events[l].push(o):(r._events[l]=o,r._eventsCount++),r}function te(r,e){--r._eventsCount===0?r._events=new K:delete r._events[e]}function k(){this._events=new K,this._eventsCount=0}k.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)Pi.call(t,i)&&e.push(M?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};k.prototype.listeners=function(e){var t=M?M+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,l=new Array(o);n<o;n++)l[n]=i[n].fn;return l};k.prototype.listenerCount=function(e){var t=M?M+e:e,i=this._events[t];return i?i.fn?1:i.length:0};k.prototype.emit=function(e,t,i,n,o,l){var u=M?M+e:e;if(!this._events[u])return!1;var a=this._events[u],h=arguments.length,d,c;if(a.fn){switch(a.once&&this.removeListener(e,a.fn,void 0,!0),h){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,t),!0;case 3:return a.fn.call(a.context,t,i),!0;case 4:return a.fn.call(a.context,t,i,n),!0;case 5:return a.fn.call(a.context,t,i,n,o),!0;case 6:return a.fn.call(a.context,t,i,n,o,l),!0}for(c=1,d=new Array(h-1);c<h;c++)d[c-1]=arguments[c];a.fn.apply(a.context,d)}else{var E=a.length,p;for(c=0;c<E;c++)switch(a[c].once&&this.removeListener(e,a[c].fn,void 0,!0),h){case 1:a[c].fn.call(a[c].context);break;case 2:a[c].fn.call(a[c].context,t);break;case 3:a[c].fn.call(a[c].context,t,i);break;case 4:a[c].fn.call(a[c].context,t,i,n);break;default:if(!d)for(p=1,d=new Array(h-1);p<h;p++)d[p-1]=arguments[p];a[c].fn.apply(a[c].context,d)}}return!0};k.prototype.on=function(e,t,i){return Ke(this,e,t,i,!1)};k.prototype.once=function(e,t,i){return Ke(this,e,t,i,!0)};k.prototype.removeListener=function(e,t,i,n){var o=M?M+e:e;if(!this._events[o])return this;if(!t)return te(this,o),this;var l=this._events[o];if(l.fn)l.fn===t&&(!n||l.once)&&(!i||l.context===i)&&te(this,o);else{for(var u=0,a=[],h=l.length;u<h;u++)(l[u].fn!==t||n&&!l[u].once||i&&l[u].context!==i)&&a.push(l[u]);a.length?this._events[o]=a.length===1?a[0]:a:te(this,o)}return this};k.prototype.removeAllListeners=function(e){var t;return e?(t=M?M+e:e,this._events[t]&&te(this,t)):(this._events=new K,this._eventsCount=0),this};k.prototype.off=k.prototype.removeListener;k.prototype.addListener=k.prototype.on;k.prefixed=M;k.EventEmitter=k;typeof ge<"u"&&(ge.exports=k)});var Qe=f((Ws,Ye)=>{"use strict";Ye.exports=(r,e)=>(e=e||(()=>{}),r.then(t=>new Promise(i=>{i(e())}).then(()=>t),t=>new Promise(i=>{i(e())}).then(()=>{throw t})))});var Ze=f(($s,ie)=>{"use strict";var Ci=Qe(),re=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Xe=(r,e,t)=>new Promise((i,n)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){i(r);return}let o=setTimeout(()=>{if(typeof t=="function"){try{i(t())}catch(a){n(a)}return}let l=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new re(l);typeof r.cancel=="function"&&r.cancel(),n(u)},e);Ci(r.then(i,n),()=>{clearTimeout(o)})});ie.exports=Xe;ie.exports.default=Xe;ie.exports.TimeoutError=re});var et=f(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});function Mi(r,e,t){let i=0,n=r.length;for(;n>0;){let o=n/2|0,l=i+o;t(r[l],e)<=0?(i=++l,n-=o+1):n=o}return i}_e.default=Mi});var tt=f(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});var ji=et(),ve=class{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);let i={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(i);return}let n=ji.default(this._queue,i,(o,l)=>l.priority-o.priority);this._queue.splice(n,0,i)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this._queue.length}};ye.default=ve});var it=f(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});var qi=He(),rt=Ze(),Ii=tt(),se=()=>{},Ai=new rt.TimeoutError,be=class extends qi{constructor(e){var t,i,n,o;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=se,this._resolveIdle=se,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Ii.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(i=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&i!==void 0?i:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(n=e.interval)===null||n===void 0?void 0:n.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=se,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=se,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return t?(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((i,n)=>{let o=async()=>{this._pendingCount++,this._intervalCount++;try{let l=this._timeout===void 0&&t.timeout===void 0?e():rt.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&n(Ai)});i(await l)}catch(l){n(l)}this._next()};this._queue.enqueue(o,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async i=>this.add(i,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};we.default=be});var Et=f(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.getFileUploadJob=Oe;v.getMultipleFileUploadJobs=Ri;v.getFileData=st;v.getFileDataLength=nt;v.getFileDataAsStream=at;v.getAllFileUploadsToComplete=Ti;v.warnIfNotUsingFilesUploadV2=Ui;v.warnIfChannels=ot;v.errorIfChannelsCsv=lt;v.errorIfInvalidOrMissingFileData=ut;v.warnIfMissingOrInvalidFileNameAndDefault=ct;v.warnIfLegacyFileType=dt;v.buildMissingFileIdError=ht;v.buildFileSizeErrorMsg=ft;v.buildLegacyFileTypeWarning=pt;v.buildMissingFileNameWarning=mt;v.buildMissingExtensionWarning=gt;v.buildLegacyMethodWarning=_t;v.buildGeneralFilesUploadWarning=vt;v.buildFilesUploadMissingMessage=yt;v.buildChannelsWarning=bt;v.buildMultipleChannelsErrorMsg=wt;v.buildInvalidFilesUploadParamError=Ot;var Si=F("node:fs"),xi=F("node:stream"),w=ee();async function Oe(r,e){var t,i,n,o;dt(r,e),ot(r,e),lt(r);let l=ct(r,e),u=await st(r),a=nt(u),h={alt_text:r.alt_text,blocks:r.blocks,channel_id:(t=r.channels)!==null&&t!==void 0?t:r.channel_id,filename:(i=r.filename)!==null&&i!==void 0?i:l,highlight_type:r.highlight_type,initial_comment:r.initial_comment,snippet_type:r.snippet_type,title:(o=(n=r.title)!==null&&n!==void 0?n:r.filename)!==null&&o!==void 0?o:l,data:u,length:a};if("thread_ts"in r&&(h.thread_ts=r.thread_ts),"token"in r&&(h.token=r.token),"content"in r)return Object.assign({content:r.content},h);if("file"in r)return Object.assign({file:r.file},h);throw(0,w.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"),w.ErrorCode.FileUploadInvalidArgumentsError)}async function Ri(r,e){if("file_uploads"in r)return Promise.all(r.file_uploads.map(t=>{let{blocks:i,channel_id:n,channels:o,initial_comment:l,thread_ts:u}=t;if(i||n||o||l||u)throw(0,w.errorWithCode)(new Error(Ot()),w.ErrorCode.FileUploadInvalidArgumentsError);let a=Object.assign(Object.assign({},t),{blocks:r.blocks,channels:r.channels,channel_id:r.channel_id,initial_comment:r.initial_comment});if("thread_ts"in r&&(a.thread_ts=r.thread_ts),"token"in r&&(a.token=r.token),"content"in t)return Oe(Object.assign({content:t.content},a),e);if("file"in t)return Oe(Object.assign({file:t.file},a),e);throw(0,w.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"),w.ErrorCode.FileUploadInvalidArgumentsError)}));throw new Error(yt())}async function st(r){if(ut(r),"file"in r){let{file:e}=r;if(Buffer.isBuffer(e))return e;if(typeof e=="string")try{return(0,Si.readFileSync)(e)}catch{throw(0,w.errorWithCode)(new Error(`Unable to resolve file data for ${e}. Please supply a filepath string, or binary data Buffer or String directly.`),w.ErrorCode.FileUploadInvalidArgumentsError)}let t=await at(e);if(t)return t}if("content"in r)return Buffer.from(r.content);throw(0,w.errorWithCode)(new Error("There was an issue getting the file data for the file or content supplied"),w.ErrorCode.FileUploadReadFileDataError)}function nt(r){if(r)return Buffer.byteLength(r,"utf8");throw(0,w.errorWithCode)(new Error(ft()),w.ErrorCode.FileUploadReadFileDataError)}async function at(r){let e=[];return new Promise((t,i)=>{r.on("readable",()=>{let n=r.read();for(;n!==null;)e.push(n),n=r.read()}),r.on("end",()=>{if(e.length>0){let n=Buffer.concat(e);t(n)}else i(Error("No data in supplied file"))})})}function Ti(r){let e={};for(let t of r){let{blocks:i,channel_id:n,thread_ts:o,highlight_type:l,initial_comment:u,file_id:a,title:h}=t;if(a){let d=`:::${n}:::${o}:::${u}:::${JSON.stringify(i)}`;if(Object.prototype.hasOwnProperty.call(e,d))e[d].files.push({id:a,title:h,highlight_type:l});else{if(e[d]={files:[{id:a,title:h,highlight_type:l}],channel_id:n,blocks:i,initial_comment:u},o&&n){let c={channel_id:n,thread_ts:o};e[d]=Object.assign(Object.assign({},e[d]),c)}"token"in t&&(e[d].token=t.token)}}else throw new Error(ht())}return e}function Ui(r,e){let i=["files.upload"].includes(r);r==="files.upload"&&e.warn(_t(r)),i&&e.info(vt())}function ot(r,e){r.channels&&e.warn(bt())}function lt(r){if((r.channels?r.channels.split(","):[]).length>1)throw(0,w.errorWithCode)(new Error(wt()),w.ErrorCode.FileUploadInvalidArgumentsError)}function ut(r){let e="file"in r,t="content"in r;if(!(e||t)||e&&t)throw(0,w.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You cannot supply both"),w.ErrorCode.FileUploadInvalidArgumentsError);if("file"in r){let{file:i}=r;if(i&&!(typeof i=="string"||Buffer.isBuffer(i)||i instanceof xi.Readable))throw(0,w.errorWithCode)(new Error("file must be a valid string path, buffer or Readable"),w.ErrorCode.FileUploadInvalidArgumentsError)}if("content"in r&&r.content&&typeof r.content!="string")throw(0,w.errorWithCode)(new Error("content must be a string"),w.ErrorCode.FileUploadInvalidArgumentsError)}function ct(r,e){var t;let n=`file.${(t=r.filetype)!==null&&t!==void 0?t:"txt"}`,{filename:o}=r;return o?(o.split(".").length<2&&e.warn(gt(o)),o):(e.warn(mt()),n)}function dt(r,e){r.filetype&&e.warn(pt())}function ht(){return"Missing required file id for file upload completion"}function ft(){return"There was an issue calculating the size of your file"}function pt(){return`filetype is no longer a supported field in files.uploadV2.
5
5
  Please remove this field. To indicate file type, please do so via the required filename property using the appropriate file extension, e.g. image.png, text.txt`}function mt(){return`filename is a required field for files.uploadV2.
6
6
  For backwards compatibility and ease of migration, defaulting the filename. For best experience and consistent unfurl behavior, you should set the filename property with correct file extension, e.g. image.png, text.txt`}function gt(r){return`filename supplied '${r}' may be missing a proper extension. Missing extenions may result in unexpected unfurl behavior when shared`}function _t(r){return`${r} may cause some issues like timeouts for relatively large files.`}function vt(){return"Our latest recommendation is to use client.files.uploadV2() method, which is mostly compatible and much stabler, instead."}function yt(){return"Something went wrong with processing file_uploads"}function bt(){return"Although the 'channels' parameter is still supported for smoother migration from legacy files.upload, we recommend using the new channel_id parameter with a single str value instead (e.g. 'C12345')."}function wt(){return"Sharing files with multiple channels is no longer supported in v2. Share files in each channel separately instead."}function Ot(){return"You may supply file_uploads only for a single channel, message, or thread respectively. Therefore, please supply any channel_id, initial_comment or blocks, or thread_ts in the top-layer."}});var Pt=f(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.default=Li;function Li(r){return new Promise(e=>{setTimeout(e,r)})}});var Ct=f((Gs,Pe)=>{"use strict";var Fi=Object.prototype.hasOwnProperty,j="~";function H(){}Object.create&&(H.prototype=Object.create(null),new H().__proto__||(j=!1));function Di(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function kt(r,e,t,i,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Di(t,i||r,n),l=j?j+e:e;return r._events[l]?r._events[l].fn?r._events[l]=[r._events[l],o]:r._events[l].push(o):(r._events[l]=o,r._eventsCount++),r}function ne(r,e){--r._eventsCount===0?r._events=new H:delete r._events[e]}function C(){this._events=new H,this._eventsCount=0}C.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)Fi.call(t,i)&&e.push(j?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};C.prototype.listeners=function(e){var t=j?j+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,l=new Array(o);n<o;n++)l[n]=i[n].fn;return l};C.prototype.listenerCount=function(e){var t=j?j+e:e,i=this._events[t];return i?i.fn?1:i.length:0};C.prototype.emit=function(e,t,i,n,o,l){var u=j?j+e:e;if(!this._events[u])return!1;var a=this._events[u],h=arguments.length,d,c;if(a.fn){switch(a.once&&this.removeListener(e,a.fn,void 0,!0),h){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,t),!0;case 3:return a.fn.call(a.context,t,i),!0;case 4:return a.fn.call(a.context,t,i,n),!0;case 5:return a.fn.call(a.context,t,i,n,o),!0;case 6:return a.fn.call(a.context,t,i,n,o,l),!0}for(c=1,d=new Array(h-1);c<h;c++)d[c-1]=arguments[c];a.fn.apply(a.context,d)}else{var E=a.length,p;for(c=0;c<E;c++)switch(a[c].once&&this.removeListener(e,a[c].fn,void 0,!0),h){case 1:a[c].fn.call(a[c].context);break;case 2:a[c].fn.call(a[c].context,t);break;case 3:a[c].fn.call(a[c].context,t,i);break;case 4:a[c].fn.call(a[c].context,t,i,n);break;default:if(!d)for(p=1,d=new Array(h-1);p<h;p++)d[p-1]=arguments[p];a[c].fn.apply(a[c].context,d)}}return!0};C.prototype.on=function(e,t,i){return kt(this,e,t,i,!1)};C.prototype.once=function(e,t,i){return kt(this,e,t,i,!0)};C.prototype.removeListener=function(e,t,i,n){var o=j?j+e:e;if(!this._events[o])return this;if(!t)return ne(this,o),this;var l=this._events[o];if(l.fn)l.fn===t&&(!n||l.once)&&(!i||l.context===i)&&ne(this,o);else{for(var u=0,a=[],h=l.length;u<h;u++)(l[u].fn!==t||n&&!l[u].once||i&&l[u].context!==i)&&a.push(l[u]);a.length?this._events[o]=a.length===1?a[0]:a:ne(this,o)}return this};C.prototype.removeAllListeners=function(e){var t;return e?(t=j?j+e:e,this._events[t]&&ne(this,t)):(this._events=new H,this._eventsCount=0),this};C.prototype.off=C.prototype.removeListener;C.prototype.addListener=C.prototype.on;C.prefixed=j;C.EventEmitter=C;typeof Pe<"u"&&(Pe.exports=C)});var jt=f(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0})});var It=f(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0})});var St=f(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0})});var Rt=f(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0})});var Ut=f(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0})});var Ft=f(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0})});var Wt=f(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0})});var Nt=f($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0})});var Bt=f(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0})});var Jt=f(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0})});var Kt=f(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0})});var Yt=f(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0})});var Xt=f(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0})});var er=f(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0})});var rr=f(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0})});var sr=f(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0})});var ar=f(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0})});var lr=f(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0})});var cr=f(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0})});var hr=f(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0})});var pr=f(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0})});var gr=f(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0})});var vr=f(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0})});var br=f(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0})});var Or=f(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0})});var Pr=f(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0})});var Cr=f(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0})});var jr=f(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0})});var Ir=f(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0})});var Sr=f(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0})});var Rr=f(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0})});var Ur=f(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0})});var Fr=f(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0})});var Dr=f(g=>{"use strict";var Wi=g&&g.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),_=g&&g.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Wi(e,r,t)};Object.defineProperty(g,"__esModule",{value:!0});_(Nt(),g);_(Bt(),g);_(Jt(),g);_(Kt(),g);_(Yt(),g);_(Xt(),g);_(er(),g);_(rr(),g);_(sr(),g);_(ar(),g);_(lr(),g);_(cr(),g);_(hr(),g);_(pr(),g);_(gr(),g);_(vr(),g);_(br(),g);_(Or(),g);_(Pr(),g);_(Cr(),g);_(jr(),g);_(Ir(),g);_(Sr(),g);_(Rr(),g);_(Ur(),g);_(Fr(),g)});var $r=f(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0})});var Br=f(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.CustomFieldType=B.EntityType=void 0;var Nr;(function(r){r.Task="slack#/entities/task",r.File="slack#/entities/file",r.Item="slack#/entities/item",r.Incident="slack#/entities/incident",r.ContentItem="slack#/entities/content_item"})(Nr||(B.EntityType=Nr={}));var zr;(function(r){r.Integer="integer",r.String="string",r.Array="array",r.Date="slack#/types/date",r.Timestamp="slack#/types/timestamp",r.Image="slack#/types/image",r.ChannelId="slack#/types/channel_id",r.User="slack#/types/user",r.EntityRef="slack#/types/entity_ref",r.Boolean="boolean",r.Link="slack#/types/link",r.Email="slack#/types/email"})(zr||(B.CustomFieldType=zr={}))});var Jr=f(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0})});var Gr=f(O=>{"use strict";var $i=O&&O.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),A=O&&O.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&$i(e,r,t)};Object.defineProperty(O,"__esModule",{value:!0});A(jt(),O);A(It(),O);A(St(),O);A(Rt(),O);A(Ut(),O);A(Ft(),O);A(Wt(),O);A(Dr(),O);A($r(),O);A(Br(),O);A(Jr(),O)});var Ce=f(L=>{"use strict";var Ni=L&&L.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),zi=L&&L.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Ni(e,r,t)};Object.defineProperty(L,"__esModule",{value:!0});L.Methods=void 0;var Bi=Ct(),Kr=Me();function s(r,e){return r.apiCall.bind(r,e)}function m(r,e){return r.apiCall.bind(r,e)}function Vi(r){return r.filesUploadV2.bind(r)}var ke=class extends Bi.EventEmitter{constructor(){if(super(),this.admin={analytics:{getFile:s(this,"admin.analytics.getFile")},apps:{activities:{list:m(this,"admin.apps.activities.list")},approve:s(this,"admin.apps.approve"),approved:{list:s(this,"admin.apps.approved.list")},clearResolution:s(this,"admin.apps.clearResolution"),config:{lookup:s(this,"admin.apps.config.lookup"),set:s(this,"admin.apps.config.set")},requests:{cancel:s(this,"admin.apps.requests.cancel"),list:s(this,"admin.apps.requests.list")},restrict:s(this,"admin.apps.restrict"),restricted:{list:s(this,"admin.apps.restricted.list")},uninstall:s(this,"admin.apps.uninstall")},auth:{policy:{assignEntities:s(this,"admin.auth.policy.assignEntities"),getEntities:s(this,"admin.auth.policy.getEntities"),removeEntities:s(this,"admin.auth.policy.removeEntities")}},barriers:{create:s(this,"admin.barriers.create"),delete:s(this,"admin.barriers.delete"),list:m(this,"admin.barriers.list"),update:s(this,"admin.barriers.update")},conversations:{archive:s(this,"admin.conversations.archive"),bulkArchive:s(this,"admin.conversations.bulkArchive"),bulkDelete:s(this,"admin.conversations.bulkDelete"),bulkMove:s(this,"admin.conversations.bulkMove"),convertToPrivate:s(this,"admin.conversations.convertToPrivate"),convertToPublic:s(this,"admin.conversations.convertToPublic"),create:s(this,"admin.conversations.create"),delete:s(this,"admin.conversations.delete"),disconnectShared:s(this,"admin.conversations.disconnectShared"),ekm:{listOriginalConnectedChannelInfo:m(this,"admin.conversations.ekm.listOriginalConnectedChannelInfo")},getConversationPrefs:s(this,"admin.conversations.getConversationPrefs"),getCustomRetention:s(this,"admin.conversations.getCustomRetention"),getTeams:s(this,"admin.conversations.getTeams"),invite:s(this,"admin.conversations.invite"),lookup:s(this,"admin.conversations.lookup"),removeCustomRetention:s(this,"admin.conversations.removeCustomRetention"),rename:s(this,"admin.conversations.rename"),restrictAccess:{addGroup:s(this,"admin.conversations.restrictAccess.addGroup"),listGroups:s(this,"admin.conversations.restrictAccess.listGroups"),removeGroup:s(this,"admin.conversations.restrictAccess.removeGroup")},search:m(this,"admin.conversations.search"),setConversationPrefs:s(this,"admin.conversations.setConversationPrefs"),setCustomRetention:s(this,"admin.conversations.setCustomRetention"),setTeams:s(this,"admin.conversations.setTeams"),unarchive:s(this,"admin.conversations.unarchive")},emoji:{add:s(this,"admin.emoji.add"),addAlias:s(this,"admin.emoji.addAlias"),list:m(this,"admin.emoji.list"),remove:s(this,"admin.emoji.remove"),rename:s(this,"admin.emoji.rename")},functions:{list:s(this,"admin.functions.list"),permissions:{lookup:s(this,"admin.functions.permissions.lookup"),set:s(this,"admin.functions.permissions.set")}},inviteRequests:{approve:s(this,"admin.inviteRequests.approve"),approved:{list:s(this,"admin.inviteRequests.approved.list")},denied:{list:s(this,"admin.inviteRequests.denied.list")},deny:s(this,"admin.inviteRequests.deny"),list:s(this,"admin.inviteRequests.list")},roles:{addAssignments:s(this,"admin.roles.addAssignments"),listAssignments:m(this,"admin.roles.listAssignments"),removeAssignments:s(this,"admin.roles.removeAssignments")},teams:{admins:{list:s(this,"admin.teams.admins.list")},create:s(this,"admin.teams.create"),list:m(this,"admin.teams.list"),owners:{list:s(this,"admin.teams.owners.list")},settings:{info:s(this,"admin.teams.settings.info"),setDefaultChannels:s(this,"admin.teams.settings.setDefaultChannels"),setDescription:s(this,"admin.teams.settings.setDescription"),setDiscoverability:s(this,"admin.teams.settings.setDiscoverability"),setIcon:s(this,"admin.teams.settings.setIcon"),setName:s(this,"admin.teams.settings.setName")}},usergroups:{addChannels:s(this,"admin.usergroups.addChannels"),addTeams:s(this,"admin.usergroups.addTeams"),listChannels:s(this,"admin.usergroups.listChannels"),removeChannels:s(this,"admin.usergroups.removeChannels")},users:{assign:s(this,"admin.users.assign"),invite:s(this,"admin.users.invite"),list:m(this,"admin.users.list"),remove:s(this,"admin.users.remove"),session:{clearSettings:s(this,"admin.users.session.clearSettings"),getSettings:s(this,"admin.users.session.getSettings"),invalidate:s(this,"admin.users.session.invalidate"),list:m(this,"admin.users.session.list"),reset:s(this,"admin.users.session.reset"),resetBulk:s(this,"admin.users.session.resetBulk"),setSettings:s(this,"admin.users.session.setSettings")},setAdmin:s(this,"admin.users.setAdmin"),setExpiration:s(this,"admin.users.setExpiration"),setOwner:s(this,"admin.users.setOwner"),setRegular:s(this,"admin.users.setRegular"),unsupportedVersions:{export:s(this,"admin.users.unsupportedVersions.export")}},workflows:{collaborators:{add:s(this,"admin.workflows.collaborators.add"),remove:s(this,"admin.workflows.collaborators.remove")},permissions:{lookup:s(this,"admin.workflows.permissions.lookup")},search:m(this,"admin.workflows.search"),unpublish:s(this,"admin.workflows.unpublish")}},this.api={test:m(this,"api.test")},this.assistant={threads:{setStatus:s(this,"assistant.threads.setStatus"),setSuggestedPrompts:s(this,"assistant.threads.setSuggestedPrompts"),setTitle:s(this,"assistant.threads.setTitle")}},this.apps={connections:{open:m(this,"apps.connections.open")},event:{authorizations:{list:s(this,"apps.event.authorizations.list")}},manifest:{create:s(this,"apps.manifest.create"),delete:s(this,"apps.manifest.delete"),export:s(this,"apps.manifest.export"),update:s(this,"apps.manifest.update"),validate:s(this,"apps.manifest.validate")},uninstall:s(this,"apps.uninstall"),user:{connection:{update:s(this,"apps.user.connection.update")}}},this.auth={revoke:m(this,"auth.revoke"),teams:{list:m(this,"auth.teams.list")},test:m(this,"auth.test")},this.bookmarks={add:s(this,"bookmarks.add"),edit:s(this,"bookmarks.edit"),list:s(this,"bookmarks.list"),remove:s(this,"bookmarks.remove")},this.bots={info:m(this,"bots.info")},this.calls={add:s(this,"calls.add"),end:s(this,"calls.end"),info:s(this,"calls.info"),update:s(this,"calls.update"),participants:{add:s(this,"calls.participants.add"),remove:s(this,"calls.participants.remove")}},this.canvases={access:{delete:s(this,"canvases.access.delete"),set:s(this,"canvases.access.set")},create:m(this,"canvases.create"),delete:s(this,"canvases.delete"),edit:s(this,"canvases.edit"),sections:{lookup:s(this,"canvases.sections.lookup")}},this.chat={appendStream:s(this,"chat.appendStream"),delete:s(this,"chat.delete"),deleteScheduledMessage:s(this,"chat.deleteScheduledMessage"),getPermalink:s(this,"chat.getPermalink"),meMessage:s(this,"chat.meMessage"),postEphemeral:s(this,"chat.postEphemeral"),postMessage:s(this,"chat.postMessage"),scheduleMessage:s(this,"chat.scheduleMessage"),scheduledMessages:{list:m(this,"chat.scheduledMessages.list")},startStream:s(this,"chat.startStream"),stopStream:s(this,"chat.stopStream"),unfurl:s(this,"chat.unfurl"),update:s(this,"chat.update")},this.conversations={acceptSharedInvite:s(this,"conversations.acceptSharedInvite"),approveSharedInvite:s(this,"conversations.approveSharedInvite"),archive:s(this,"conversations.archive"),canvases:{create:s(this,"conversations.canvases.create")},close:s(this,"conversations.close"),create:s(this,"conversations.create"),declineSharedInvite:s(this,"conversations.declineSharedInvite"),externalInvitePermissions:{set:s(this,"conversations.externalInvitePermissions.set")},history:s(this,"conversations.history"),info:s(this,"conversations.info"),invite:s(this,"conversations.invite"),inviteShared:s(this,"conversations.inviteShared"),join:s(this,"conversations.join"),kick:s(this,"conversations.kick"),leave:s(this,"conversations.leave"),list:m(this,"conversations.list"),listConnectInvites:m(this,"conversations.listConnectInvites"),mark:s(this,"conversations.mark"),members:s(this,"conversations.members"),open:s(this,"conversations.open"),rename:s(this,"conversations.rename"),replies:s(this,"conversations.replies"),requestSharedInvite:{approve:s(this,"conversations.requestSharedInvite.approve"),deny:s(this,"conversations.requestSharedInvite.deny"),list:m(this,"conversations.requestSharedInvite.list")},setPurpose:s(this,"conversations.setPurpose"),setTopic:s(this,"conversations.setTopic"),unarchive:s(this,"conversations.unarchive")},this.dialog={open:s(this,"dialog.open")},this.dnd={endDnd:m(this,"dnd.endDnd"),endSnooze:m(this,"dnd.endSnooze"),info:m(this,"dnd.info"),setSnooze:s(this,"dnd.setSnooze"),teamInfo:s(this,"dnd.teamInfo")},this.emoji={list:m(this,"emoji.list")},this.entity={presentDetails:s(this,"entity.presentDetails")},this.files={completeUploadExternal:s(this,"files.completeUploadExternal"),delete:s(this,"files.delete"),getUploadURLExternal:s(this,"files.getUploadURLExternal"),info:s(this,"files.info"),list:s(this,"files.list"),revokePublicURL:s(this,"files.revokePublicURL"),sharedPublicURL:s(this,"files.sharedPublicURL"),upload:s(this,"files.upload"),uploadV2:Vi(this),comments:{delete:s(this,"files.comments.delete")},remote:{add:s(this,"files.remote.add"),info:s(this,"files.remote.info"),list:s(this,"files.remote.list"),remove:s(this,"files.remote.remove"),share:s(this,"files.remote.share"),update:s(this,"files.remote.update")}},this.functions={completeError:s(this,"functions.completeError"),completeSuccess:s(this,"functions.completeSuccess")},this.migration={exchange:s(this,"migration.exchange")},this.oauth={access:s(this,"oauth.access"),v2:{access:s(this,"oauth.v2.access"),exchange:s(this,"oauth.v2.exchange")}},this.openid={connect:{token:s(this,"openid.connect.token"),userInfo:m(this,"openid.connect.userInfo")}},this.pins={add:s(this,"pins.add"),list:s(this,"pins.list"),remove:s(this,"pins.remove")},this.reactions={add:s(this,"reactions.add"),get:s(this,"reactions.get"),list:m(this,"reactions.list"),remove:s(this,"reactions.remove")},this.reminders={add:s(this,"reminders.add"),complete:s(this,"reminders.complete"),delete:s(this,"reminders.delete"),info:s(this,"reminders.info"),list:m(this,"reminders.list")},this.rtm={connect:m(this,"rtm.connect"),start:m(this,"rtm.start")},this.search={all:s(this,"search.all"),files:s(this,"search.files"),messages:s(this,"search.messages")},this.slackLists={access:{delete:s(this,"slackLists.access.delete"),set:s(this,"slackLists.access.set")},create:s(this,"slackLists.create"),download:{get:s(this,"slackLists.download.get"),start:s(this,"slackLists.download.start")},items:{create:s(this,"slackLists.items.create"),delete:s(this,"slackLists.items.delete"),deleteMultiple:s(this,"slackLists.items.deleteMultiple"),info:s(this,"slackLists.items.info"),list:s(this,"slackLists.items.list"),update:s(this,"slackLists.items.update")},update:s(this,"slackLists.update")},this.team={accessLogs:m(this,"team.accessLogs"),billableInfo:m(this,"team.billableInfo"),billing:{info:s(this,"team.billing.info")},externalTeams:{disconnect:s(this,"team.externalTeams.disconnect"),list:s(this,"team.externalTeams.list")},info:m(this,"team.info"),integrationLogs:m(this,"team.integrationLogs"),preferences:{list:m(this,"team.preferences.list")},profile:{get:m(this,"team.profile.get")}},this.tooling={tokens:{rotate:s(this,"tooling.tokens.rotate")}},this.usergroups={create:s(this,"usergroups.create"),disable:s(this,"usergroups.disable"),enable:s(this,"usergroups.enable"),list:m(this,"usergroups.list"),update:s(this,"usergroups.update"),users:{list:s(this,"usergroups.users.list"),update:s(this,"usergroups.users.update")}},this.users={conversations:s(this,"users.conversations"),deletePhoto:s(this,"users.deletePhoto"),discoverableContacts:{lookup:s(this,"users.discoverableContacts.lookup")},getPresence:s(this,"users.getPresence"),identity:s(this,"users.identity"),info:s(this,"users.info"),list:s(this,"users.list"),lookupByEmail:s(this,"users.lookupByEmail"),setPhoto:s(this,"users.setPhoto"),setPresence:s(this,"users.setPresence"),profile:{get:s(this,"users.profile.get"),set:s(this,"users.profile.set")}},this.views={open:s(this,"views.open"),publish:s(this,"views.publish"),push:s(this,"views.push"),update:s(this,"views.update")},this.stars={add:s(this,"stars.add"),list:s(this,"stars.list"),remove:s(this,"stars.remove")},this.workflows={featured:{add:s(this,"workflows.featured.add"),list:s(this,"workflows.featured.list"),remove:s(this,"workflows.featured.remove"),set:s(this,"workflows.featured.set")},stepCompleted:s(this,"workflows.stepCompleted"),stepFailed:s(this,"workflows.stepFailed"),updateStep:s(this,"workflows.updateStep")},new.target!==Kr.WebClient&&!(new.target.prototype instanceof Kr.WebClient))throw new Error("Attempt to inherit from WebClient methods without inheriting from WebClient")}};L.Methods=ke;zi(Gr(),L)});var Me=f(b=>{"use strict";var Ji=b&&b.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),Gi=b&&b.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ki=b&&b.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&Ji(t,e,i[n]);return Gi(t,e),t}})(),Q=b&&b.__await||function(r){return this instanceof Q?(this.v=r,this):new Q(r)},Hi=b&&b.__asyncGenerator||function(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(r,e||[]),n,o=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",l),n[Symbol.asyncIterator]=function(){return this},n;function l(p){return function(I){return Promise.resolve(I).then(p,c)}}function u(p,I){i[p]&&(n[p]=function(S){return new Promise(function(x,D){o.push([p,S,x,D])>1||a(p,S)})},I&&(n[p]=I(n[p])))}function a(p,I){try{h(i[p](I))}catch(S){E(o[0][3],S)}}function h(p){p.value instanceof Q?Promise.resolve(p.value.v).then(d,c):E(o[0][2],p)}function d(p){a("next",p)}function c(p){a("throw",p)}function E(p,I){p(I),o.shift(),o.length&&a(o[0][0],o[0][1])}},Yi=b&&b.__asyncValues||function(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof __values=="function"?__values(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(o){t[o]=r[o]&&function(l){return new Promise(function(u,a){l=r[o](l),n(u,a,l.done,l.value)})}}function n(o,l,u,a){Promise.resolve(a).then(function(h){o({value:h,done:u})},l)}},Qi=b&&b.__rest||function(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(r);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(r,i[n])&&(t[i[n]]=r[i[n]]);return t},W=b&&b.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(b,"__esModule",{value:!0});b.WebClient=b.WebClientEvent=void 0;b.buildThreadTsWarningMessage=Zr;var Hr=F("node:path"),Xi=F("node:querystring"),Zi=F("node:util"),es=W(F("node:zlib")),ts=W(ri()),rs=W(ti()),is=W(Ve()),qe=W(Ge()),ss=W(it()),je=Ki(ii()),ns=me(),Y=ee(),ae=Et(),as=W(Pt()),os=ue(),Yr=de(),ls=Ce(),us=he(),cs=["delete","common","get","put","head","post","link","patch","purge","unlink","options"],ds="Untitled",hs=200,fs=()=>{},Ie;(function(r){r.RATE_LIMITED="rate_limited"})(Ie||(b.WebClientEvent=Ie={}));var X=class r extends ls.Methods{constructor(e,{slackApiUrl:t="https://slack.com/api/",logger:i=void 0,logLevel:n=void 0,maxRequestConcurrency:o=100,retryConfig:l=us.tenRetriesInAboutThirtyMinutes,agent:u=void 0,tls:a=void 0,timeout:h=0,rejectRateLimitedCalls:d=!1,headers:c={},teamId:E=void 0,allowAbsoluteUrls:p=!0,attachOriginalToWebAPIRequestError:I=!0,requestInterceptor:S=void 0,adapter:x=void 0}={}){super(),this.token=e,this.slackApiUrl=t,this.slackApiUrl.endsWith("/")||(this.slackApiUrl+="/"),this.retryConfig=l,this.requestQueue=new ss.default({concurrency:o}),this.tlsConfig=a!==void 0?a:{},this.rejectRateLimitedCalls=d,this.teamId=E,this.allowAbsoluteUrls=p,this.attachOriginalToWebAPIRequestError=I,typeof i<"u"?(this.logger=i,typeof n<"u"&&this.logger.debug("The logLevel given to WebClient was ignored as you also gave logger")):this.logger=(0,Yr.getLogger)(r.loggerName,n??Yr.LogLevel.INFO,i),this.token&&!c.Authorization&&(c.Authorization=`Bearer ${this.token}`),this.axios=ts.default.create({adapter:x?D=>x(Object.assign(Object.assign({},D),{adapter:void 0})):void 0,timeout:h,baseURL:this.slackApiUrl,headers:(0,is.default)()?c:Object.assign({"User-Agent":(0,os.getUserAgent)()},c),httpAgent:u,httpsAgent:u,validateStatus:()=>!0,maxRedirects:0,proxy:!1}),this.axios.defaults.headers.post["Content-Type"]=void 0,S&&this.axios.interceptors.request.use(S,null),this.axios.interceptors.request.use(this.serializeApiCallData.bind(this),null),this.logger.debug("initialized")}async apiCall(e,t={}){if(this.logger.debug(`apiCall('${e}') start`),ms(e,this.logger),gs(e,this.logger,t),_s(e,this.logger,t),typeof t=="string"||typeof t=="number"||typeof t=="boolean")throw new TypeError(`Expected an options argument but instead received a ${typeof t}`);if((0,ae.warnIfNotUsingFilesUploadV2)(e,this.logger),e==="files.uploadV2")return this.filesUploadV2(t);let i={};t.token&&(i.Authorization=`Bearer ${t.token}`);let n=this.deriveRequestUrl(e),o=await this.makeRequest(n,Object.assign({team_id:this.teamId},t),i),l=await this.buildResult(o);if(this.logger.debug(`http request result: ${JSON.stringify(l)}`),l.response_metadata!==void 0&&l.response_metadata.warnings!==void 0&&l.response_metadata.warnings.forEach(this.logger.warn.bind(this.logger)),l.response_metadata!==void 0&&l.response_metadata.messages!==void 0)for(let u of l.response_metadata.messages){let a=/\[ERROR\](.*)/,h=/\[WARN\](.*)/;if(a.test(u)){let d=u.match(a);d!=null&&this.logger.error(d[1].trim())}else if(h.test(u)){let d=u.match(h);d!=null&&this.logger.warn(d[1].trim())}}if(!l.ok&&o.headers["content-type"]!=="application/gzip"||"ok"in l&&l.ok===!1)throw(0,Y.platformErrorFromResult)(l);return this.logger.debug(`apiCall('${e}') end`),l}paginate(e,t,i,n){let o=(()=>{if(t!==void 0&&typeof t.limit=="number"){let{limit:h}=t;return t.limit=void 0,h}return hs})();function l(){return Hi(this,arguments,function*(){let d,c={limit:o};for(t!==void 0&&t.cursor!==void 0&&(c.cursor=t.cursor);d===void 0||c!==void 0;)d=yield Q(this.apiCall(e,Object.assign(t!==void 0?t:{},c))),yield yield Q(d),c=ps(d,o)})}if(i===void 0)return l.call(this);let u=n!==void 0?n:fs,a=0;return(async()=>{var h,d,c,E;let p=l.call(this),S=(await p.next(void 0)).value,x=u(void 0,S,a);if(a+=1,i(S))return x;try{for(var D=!0,oe=Yi(p),le;le=await oe.next(),h=le.done,!h;D=!0){E=le.value,D=!1;let Z=E;if(x=u(x,Z,a),i(Z))return x;a+=1}}catch(Z){d={error:Z}}finally{try{!D&&!h&&(c=oe.return)&&await c.call(oe)}finally{if(d)throw d.error}}return x})()}chatStream(e){let{buffer_size:t}=e,i=Qi(e,["buffer_size"]),n={buffer_size:t};return new ns.ChatStreamer(this,this.logger,i,n)}async filesUploadV2(e){this.logger.debug("files.uploadV2() start");let t=await this.getAllFileUploads(e);return(await this.fetchAllUploadURLExternal(t)).forEach((o,l)=>{t[l].upload_url=o.upload_url,t[l].file_id=o.file_id}),await this.postFileUploadsToExternalURL(t,e),{ok:!0,files:await this.completeFileUploads(t)}}async fetchAllUploadURLExternal(e){return Promise.all(e.map(t=>{let i={filename:t.filename,length:t.length,alt_text:t.alt_text,snippet_type:t.snippet_type};return"token"in t&&(i.token=t.token),this.files.getUploadURLExternal(i)}))}async completeFileUploads(e){let t=Object.values((0,ae.getAllFileUploadsToComplete)(e));return Promise.all(t.map(i=>this.files.completeUploadExternal(i)))}async postFileUploadsToExternalURL(e,t){return Promise.all(e.map(async i=>{let{upload_url:n,file_id:o,filename:l,data:u}=i,a=u;if(n){let h={};t.token&&(h.Authorization=`Bearer ${t.token}`);let d=await this.makeRequest(n,{body:a},h);if(d.status!==200)return Promise.reject(Error(`Failed to upload file (id:${o}, filename: ${l})`));let c={ok:!0,body:d.data};return Promise.resolve(c)}return Promise.reject(Error(`No upload url found for file (id: ${o}, filename: ${l}`))}))}async getAllFileUploads(e){let t=[];return("file"in e||"content"in e)&&t.push(await(0,ae.getFileUploadJob)(e,this.logger)),"file_uploads"in e&&(t=t.concat(await(0,ae.getMultipleFileUploadJobs)(e,this.logger))),t}async makeRequest(e,t,i={}){let n=()=>this.requestQueue.add(async()=>{try{let o=Object.assign({headers:i},this.tlsConfig);e.endsWith("admin.analytics.getFile")&&(o.responseType="arraybuffer"),e.endsWith("apps.event.authorizations.list")&&(t.token=void 0),this.logger.debug(`http request url: ${e}`),this.logger.debug(`http request body: ${JSON.stringify(Xr(t))}`);let l=Object.keys(this.axios.defaults.headers).reduce((a,h)=>(cs.includes(h)||(a[h]=this.axios.defaults.headers[h]),a),{});l=Object.assign(Object.assign(Object.assign({},this.axios.defaults.headers.common),l),i),this.logger.debug(`http request headers: ${JSON.stringify(Xr(l))}`);let u=await this.axios.post(e,t,o);if(this.logger.debug("http response received"),u.status===429){let a=Qr(u);throw a!==void 0?(this.emit(Ie.RATE_LIMITED,a,{url:e,body:t}),this.rejectRateLimitedCalls?new je.AbortError((0,Y.rateLimitedErrorWithDelay)(a)):(this.logger.info(`API Call failed due to rate limiting. Will retry in ${a} seconds.`),this.requestQueue.pause(),await(0,as.default)(a*1e3),this.requestQueue.start(),new Error(`A rate limit was exceeded (url: ${e}, retry-after: ${a})`))):new je.AbortError(new Error(`Retry header did not contain a valid timeout (url: ${e}, retry-after header: ${u.headers["retry-after"]})`))}if(u.status!==200)throw(0,Y.httpErrorFromResponse)(u);return u}catch(o){let l=o;throw this.logger.warn("http request failed",l.message),l.request?(0,Y.requestErrorWithOriginal)(l,this.attachOriginalToWebAPIRequestError):o}});return(0,je.default)(n,this.retryConfig)}deriveRequestUrl(e){return(e.startsWith("https://")||e.startsWith("http://"))&&this.allowAbsoluteUrls?e:`${this.axios.getUri()+e}`}serializeApiCallData(e){let{data:t,headers:i}=e,n=!1,o=Object.entries(t).map(([u,a])=>{if(a==null)return[];let h=a;return Buffer.isBuffer(a)||(0,qe.default)(a)?n=!0:typeof a!="string"&&typeof a!="number"&&typeof a!="boolean"&&(h=JSON.stringify(a)),[u,h]});if(n){this.logger.debug("Request arguments contain binary data");let u=o.reduce((a,[h,d])=>{if(Buffer.isBuffer(d)||(0,qe.default)(d)){let c={};c.filename=(()=>{let E=d;return typeof E.name=="string"?(0,Hr.basename)(E.name):typeof E.path=="string"?(0,Hr.basename)(E.path):ds})(),a.append(h,d,c)}else h!==void 0&&d!==void 0&&a.append(h,d);return a},new rs.default);if(i)for(let[a,h]of Object.entries(u.getHeaders()))i[a]=h;return e.data=u,e.headers=i,e}i&&(i["Content-Type"]="application/x-www-form-urlencoded");let l={};return e.data=(0,Xi.stringify)(o.reduce((u,[a,h])=>(a!==void 0&&h!==void 0&&(u[a]=h),u),l)),e.headers=i,e}async buildResult(e){let{data:t}=e,i=e.headers["content-type"]==="application/gzip";if(i)try{let o=await new Promise((u,a)=>{es.default.unzip(t,(h,d)=>h?a(h):u(d.toString().split(`
7
7
  `)))}).then(u=>u).catch(u=>{throw u}),l=[];if(Array.isArray(o))for(let u of o)u&&u.length>0&&l.push(JSON.parse(u));t={file_data:l}}catch(o){t={ok:!1,error:o}}else!i&&e.request.path==="/api/admin.analytics.getFile"&&(t=JSON.parse(new Zi.TextDecoder().decode(t)));if(typeof t=="string")try{t=JSON.parse(t)}catch{t={ok:!1,error:t}}t.response_metadata===void 0&&(t.response_metadata={}),e.headers["x-oauth-scopes"]!==void 0&&(t.response_metadata.scopes=e.headers["x-oauth-scopes"].trim().split(/\s*,\s*/)),e.headers["x-accepted-oauth-scopes"]!==void 0&&(t.response_metadata.acceptedScopes=e.headers["x-accepted-oauth-scopes"].trim().split(/\s*,\s*/));let n=Qr(e);return n!==void 0&&(t.response_metadata.retryAfter=n),t}};b.WebClient=X;X.loggerName="WebClient";b.default=X;function ps(r,e){if(r!==void 0&&r.response_metadata!==void 0&&r.response_metadata.next_cursor!==void 0&&r.response_metadata.next_cursor!=="")return{limit:e,cursor:r.response_metadata.next_cursor}}function Qr(r){if(r.headers["retry-after"]!==void 0){let e=Number.parseInt(r.headers["retry-after"],10);if(!Number.isNaN(e))return e}}function ms(r,e){["workflows.stepCompleted","workflows.stepFailed","workflows.updateStep"].some(n=>new RegExp(`^${n}`).test(r))&&e.warn(`${r} is deprecated. Please check on https://docs.slack.dev/reference/methods for an alternative.`)}function gs(r,e,t){let n=["chat.postEphemeral","chat.postMessage","chat.scheduleMessage"].includes(r),o=d=>Array.isArray(d.attachments)&&d.attachments.length,l=d=>Array.isArray(d.attachments)&&d.attachments.some(c=>!c.fallback||c.fallback.trim()===""),u=d=>(d.text===void 0||d.text===null||d.text==="")&&(d.markdown_text===void 0||d.markdown===null||d.markdown_text===""),a=()=>`The top-level \`text\` argument is missing in the request payload for a ${r} call - It's a best practice to always provide a \`text\` argument when posting a message. The \`text\` is used in places where the content cannot be rendered such as: system push notifications, assistive technology such as screen readers, etc.`,h=()=>`Additionally, the attachment-level \`fallback\` argument is missing in the request payload for a ${r} call - To avoid this warning, it is recommended to always provide a top-level \`text\` argument when posting a message. Alternatively, you can provide an attachment-level \`fallback\` argument, though this is now considered a legacy field (see https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments for more details).`;n&&typeof t=="object"&&(o(t)?l(t)&&u(t)&&(e.warn(a()),e.warn(h())):u(t)&&e.warn(a()))}function _s(r,e,t){["chat.postEphemeral","chat.postMessage","chat.scheduleMessage","files.upload"].includes(r)&&t?.thread_ts!==void 0&&typeof t?.thread_ts!="string"&&e.warn(Zr(r))}function Zr(r){return`The given thread_ts value in the request payload for a ${r} call is a float value. We highly recommend using a string value instead.`}function Xr(r){let e=Object.entries(r).map(([i,n])=>{if(n==null)return[];let o=n;return(i.match(/.*token.*/)!==null||i.match(/[Aa]uthorization/))&&(o="[[REDACTED]]"),Buffer.isBuffer(n)||(0,qe.default)(n)?o="[[BINARY VALUE OMITTED]]":typeof n!="string"&&typeof n!="number"&&typeof n!="boolean"&&(o=JSON.stringify(n)),[i,o]}),t={};return e.reduce((i,[n,o])=>(n!==void 0&&o!==void 0&&(i[n]=o),i),t)}});var ks=f(y=>{"use strict";var vs=y&&y.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),Ae=y&&y.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&vs(e,r,t)},ys=y&&y.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(y,"__esModule",{value:!0});y.WebClientEvent=y.WebClient=y.ChatStreamer=y.retryPolicies=y.LogLevel=y.addAppMetadata=y.ErrorCode=void 0;var bs=ee();Object.defineProperty(y,"ErrorCode",{enumerable:!0,get:function(){return bs.ErrorCode}});var ws=ue();Object.defineProperty(y,"addAppMetadata",{enumerable:!0,get:function(){return ws.addAppMetadata}});var Os=de();Object.defineProperty(y,"LogLevel",{enumerable:!0,get:function(){return Os.LogLevel}});var Es=he();Object.defineProperty(y,"retryPolicies",{enumerable:!0,get:function(){return ys(Es).default}});Ae($e(),y);Ae(ze(),y);var Ps=me();Object.defineProperty(y,"ChatStreamer",{enumerable:!0,get:function(){return Ps.ChatStreamer}});var ei=Me();Object.defineProperty(y,"WebClient",{enumerable:!0,get:function(){return ei.WebClient}});Object.defineProperty(y,"WebClientEvent",{enumerable:!0,get:function(){return ei.WebClientEvent}});Ae(Ce(),y)});var si=Se("rate-limiter"),xe=class{globalCapacity;globalRefillPerSec;perChannelCapacity;perChannelRefillPerSec;cleanupIntervalMs;buckets=new Map;cleanupTimer=null;constructor(e={}){this.globalCapacity=e.globalCapacity??20,this.globalRefillPerSec=e.globalRefillPerSec??1,this.perChannelCapacity=e.perChannelCapacity??1,this.perChannelRefillPerSec=e.perChannelRefillPerSec??1,this.cleanupIntervalMs=e.cleanupIntervalMs??6e4,this.cleanupTimer=setInterval(()=>this._cleanup(),this.cleanupIntervalMs),typeof this.cleanupTimer.unref=="function"&&this.cleanupTimer.unref()}tryAcquire(e,t){let{globalKey:i,channelKey:n}=this._keys(e,t),o=this._tryConsume(i);if(!o.ok)return o;if(n!==i){let l=this._tryConsume(n);if(!l.ok)return this._refund(i),l}return{ok:!0}}async acquire(e,t){for(;;){let i=this.tryAcquire(e,t);if(i.ok)return;await this._sleep(Math.min(i.retryAfterMs??200,200))}}reportThrottled(e,t,i){let n=i&&i>0?i*1e3+1e3:1e4,o=Date.now()+n,{globalKey:l,channelKey:u}=this._keys(e,t);this._getOrCreate(l).backoffUntil=o,u!==l&&(this._getOrCreate(u).backoffUntil=o),si.warn(`${e}${t?`:${t}`:""} received 429, backing off ${n}ms`)}dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.buckets.clear()}_bucketCount(){return this.buckets.size}_advanceTime(e){let t=Date.now();for(let i of this.buckets.values())i.lastRefill=t-e}_keys(e,t){let i=`__global__:${e}`,n=t?`${e}:${t}`:i;return{globalKey:i,channelKey:n}}_tryConsume(e){let t=this._getOrCreate(e),i=Date.now();if(t.backoffUntil>i)return{ok:!1,retryAfterMs:t.backoffUntil-i};if(this._refill(t,i,e),t.tokens>=1)return t.tokens-=1,{ok:!0};let n=this._refillPerSecForKey(e),o=n>0?Math.ceil((1-t.tokens)/n*1e3):1e3;return{ok:!1,retryAfterMs:Math.min(o,5e3)}}_refund(e){let t=this.buckets.get(e);if(!t)return;let i=this._capacityForKey(e);t.tokens=Math.min(t.tokens+1,i)}_getOrCreate(e){let t=this.buckets.get(e);return t||(t={tokens:this._capacityForKey(e),lastRefill:Date.now(),backoffUntil:0},this.buckets.set(e,t)),t}_refill(e,t,i){let n=(t-e.lastRefill)/1e3;if(n<=0)return;let o=this._refillPerSecForKey(i),l=this._capacityForKey(i);e.tokens=Math.min(e.tokens+n*o,l),e.lastRefill=t}_capacityForKey(e){return e.startsWith("__global__")?this.globalCapacity:this.perChannelCapacity}_refillPerSecForKey(e){return e.startsWith("__global__")?this.globalRefillPerSec:this.perChannelRefillPerSec}_cleanup(){let e=Date.now()-3e5;for(let[t,i]of this.buckets)i.lastRefill<e&&i.backoffUntil<e&&this.buckets.delete(t)}_sleep(e){return new Promise(t=>setTimeout(t,e))}};export{xe as a,ce as b,Ct as c,Gr as d,ks as e};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{e as m}from"./chunk-AVXDF7AG.js";import{e as x}from"./chunk-VBN2JSER.js";import{i as C}from"./chunk-Z24SBRJK.js";import{readFileSync as I}from"node:fs";import*as k from"node:path";var a=x("connections"),f=k.join(C,"connections.json"),p="subscription",A="plan",d=/^[a-zA-Z0-9_-]+$/;function u(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function c(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n){if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.length>0)}function E(n){if(!u(n))return;let t=Object.entries(n).filter(([,e])=>typeof e=="string");return t.length>0?Object.fromEntries(t):void 0}function K(n){return"api"in n}function h(n){return"type"in n&&n.type==="account"}function B(n){return n.filter(t=>t.backend==="claude"&&!h(t))}function G(n){return n.filter(t=>t.backend==="pi"&&!h(t))}function $(n,t){let e=c(n.key);if(!e||t===p)return null;let r={id:t,backend:"claude",label:c(n.label)??t,authStyle:n.authStyle==="bearer"?"bearer":"x-api-key",key:e,billing:n.billing==="subscription"?"subscription":"metered"},o=c(n.baseUrl);o&&(r.baseUrl=o);let i=S(n.models);return i&&(r.models=i),r}function j(n){return Array.isArray(n)?n.filter(t=>u(t)&&!!c(t.id)):[]}function _(n,t){let e=c(n.provider)??t,r=c(n.baseUrl);if(!d.test(e)||!r)return null;let o={id:e,backend:"pi",provider:e,baseUrl:r},i=c(n.label);i&&(o.label=i);let b=c(n.key);b&&(o.key=b);let y=c(n.api);if(!y)return o;let l={...o,api:y,models:j(n.models)},g=E(n.headers);return g&&(l.headers=g),u(n.compat)&&Object.keys(n.compat).length>0&&(l.compat=n.compat),l}function U(n,t){let e=c(n.label)??t,r=n.pending===!0?{pending:!0}:{};if(n.backend==="claude")return t===p?null:{id:t,backend:"claude",type:"account",label:e,...r};let o=c(n.provider);return!o||!d.test(o)||o===t?null:{id:t,backend:"pi",type:"account",label:e,provider:o,...r}}function L(n){if(!u(n))return null;let t=c(n.id);return!t||!d.test(t)?null:n.type==="account"&&(n.backend==="claude"||n.backend==="pi")?U(n,t):n.backend==="claude"?$(n,t):n.backend==="pi"?_(n,t):null}function s(n){return`${n.backend}:${n.id}`}function T(n){let t=u(n)&&Array.isArray(n.connections)?n.connections:[],e=new Set,r=[];for(let o of t){let i=L(o);if(!i||e.has(s(i))){a.warn("Ignoring an invalid or duplicate entry in connections.json");continue}e.add(s(i)),r.push(i)}return r}function O(n=f){let t;try{t=I(n,"utf8")}catch(e){return e.code!=="ENOENT"&&a.warn(`Could not read ${n}: ${e.message}`),[]}try{return T(JSON.parse(t))}catch(e){return a.warn(`Ignoring corrupt ${n}: ${e.message}`),[]}}function N(n,t=f){m(t,`${JSON.stringify({version:1,connections:n},null,2)}
4
+ import{e as m}from"./chunk-TRXLIL7V.js";import{e as x}from"./chunk-7W7VYUTK.js";import{j as C}from"./chunk-T54CZKNJ.js";import{readFileSync as I}from"node:fs";import*as k from"node:path";var a=x("connections"),f=k.join(C,"connections.json"),p="subscription",A="plan",d=/^[a-zA-Z0-9_-]+$/;function u(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function c(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n){if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.length>0)}function E(n){if(!u(n))return;let t=Object.entries(n).filter(([,e])=>typeof e=="string");return t.length>0?Object.fromEntries(t):void 0}function K(n){return"api"in n}function h(n){return"type"in n&&n.type==="account"}function B(n){return n.filter(t=>t.backend==="claude"&&!h(t))}function G(n){return n.filter(t=>t.backend==="pi"&&!h(t))}function $(n,t){let e=c(n.key);if(!e||t===p)return null;let r={id:t,backend:"claude",label:c(n.label)??t,authStyle:n.authStyle==="bearer"?"bearer":"x-api-key",key:e,billing:n.billing==="subscription"?"subscription":"metered"},o=c(n.baseUrl);o&&(r.baseUrl=o);let i=S(n.models);return i&&(r.models=i),r}function j(n){return Array.isArray(n)?n.filter(t=>u(t)&&!!c(t.id)):[]}function _(n,t){let e=c(n.provider)??t,r=c(n.baseUrl);if(!d.test(e)||!r)return null;let o={id:e,backend:"pi",provider:e,baseUrl:r},i=c(n.label);i&&(o.label=i);let b=c(n.key);b&&(o.key=b);let y=c(n.api);if(!y)return o;let l={...o,api:y,models:j(n.models)},g=E(n.headers);return g&&(l.headers=g),u(n.compat)&&Object.keys(n.compat).length>0&&(l.compat=n.compat),l}function U(n,t){let e=c(n.label)??t,r=n.pending===!0?{pending:!0}:{};if(n.backend==="claude")return t===p?null:{id:t,backend:"claude",type:"account",label:e,...r};let o=c(n.provider);return!o||!d.test(o)||o===t?null:{id:t,backend:"pi",type:"account",label:e,provider:o,...r}}function L(n){if(!u(n))return null;let t=c(n.id);return!t||!d.test(t)?null:n.type==="account"&&(n.backend==="claude"||n.backend==="pi")?U(n,t):n.backend==="claude"?$(n,t):n.backend==="pi"?_(n,t):null}function s(n){return`${n.backend}:${n.id}`}function T(n){let t=u(n)&&Array.isArray(n.connections)?n.connections:[],e=new Set,r=[];for(let o of t){let i=L(o);if(!i||e.has(s(i))){a.warn("Ignoring an invalid or duplicate entry in connections.json");continue}e.add(s(i)),r.push(i)}return r}function O(n=f){let t;try{t=I(n,"utf8")}catch(e){return e.code!=="ENOENT"&&a.warn(`Could not read ${n}: ${e.message}`),[]}try{return T(JSON.parse(t))}catch(e){return a.warn(`Ignoring corrupt ${n}: ${e.message}`),[]}}function N(n,t=f){m(t,`${JSON.stringify({version:1,connections:n},null,2)}
5
5
  `,{mode:384})}function J(n,t=f){let e=s(n),r=O(t),o=r.findIndex(i=>s(i)===e);o>=0?r[o]=n:r.push(n),N(r,t)}function v(n,t=f){let e=s(n),r=O(t),o=r.filter(i=>s(i)!==e);return o.length===r.length?!1:(N(o,t),!0)}function z(n){return n&&n!==p?n:null}function W(n){return n?n.length<12?"\u2022\u2022\u2022\u2022":`${n.slice(0,3)}\u2026${n.slice(-4)}`:null}function P(n,t){return n!=="claude"||typeof t!="string"||!t?null:t===A?p:t}function Y(n){if(!u(n)||!("mode"in n)||"connection"in n)return n;let{mode:t,...e}=n;return{...e,connection:P(e.backend,t)}}export{f as a,p as b,A as c,d,K as e,h as f,B as g,G as h,s as i,O as j,N as k,J as l,v as m,z as n,W as o,P as p,Y as q};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{qa as o}from"./chunk-CK3P345X.js";var m=31,G=36,c=m,u=G,g=[255,255,255,127,255,240,255,127,255,237,255,127,255,219,255,127,255,183,255,127,255,119,254,127,63,248,254,127,223,255,254,127,223,63,252,127,159,195,251,127,111,252,244,127,247,15,247,127,247,255,247,127,247,255,227,127,247,7,232,127,239,248,103,112,15,255,187,111,241,0,208,91,253,63,236,83,193,255,239,87,159,253,238,95,159,252,174,95,31,120,172,95,63,0,80,108,127,0,220,119,255,192,63,120,255,1,248,127,255,3,156,120,255,7,140,124,255,15,206,120,255,255,207,127,255,255,207,120,255,255,223,120,255,255,223,125,255,255,63,126,255,255,255,127],M=Math.ceil(c/8),s=Math.ceil(u/2),h=["typewriter","scanline","rain","fade","crt","glitch","dissolve"];function l(a,t){if(t>=u)return!1;let e=t*M+Math.floor(a/8),i=a%8;return(g[e]>>i&1)===0}function k(a,t){let e=l(a,t*2),i=l(a,t*2+1);return e&&i?"\u2588":e?"\u2580":i?"\u2584":" "}function S(){let a=[];for(let t=0;t<s;t++){let e=[];for(let i=0;i<c;i++)e.push(k(i,t));a.push(e)}return a}var d=class{ui;interval=null;effect;finalGrid;currentGrid;effectState={};cachedLines=[];cachedWidth=0;gridVersion=0;cachedVersion=-1;constructor(t){this.ui=t,this.effect=h[Math.floor(Math.random()*h.length)],this.finalGrid=S(),this.currentGrid=this.createEmptyGrid(),this.initEffect(),this.startAnimation()}invalidate(){this.cachedWidth=0}render(t){if(t===this.cachedWidth&&this.cachedVersion===this.gridVersion)return this.cachedLines;let e=1,i=t-e;this.cachedLines=this.currentGrid.map(n=>{let x=n.slice(0,i).join(""),p=Math.max(0,t-e-x.length);return` ${o.fg("accent",x)}${" ".repeat(p)}`});let r="ARMIN SAYS HI",f=Math.max(0,t-e-r.length);return this.cachedLines.push(` ${o.fg("accent",r)}${" ".repeat(f)}`),this.cachedWidth=t,this.cachedVersion=this.gridVersion,this.cachedLines}createEmptyGrid(){return Array.from({length:s},()=>Array(c).fill(" "))}initEffect(){switch(this.effect){case"typewriter":this.effectState={pos:0};break;case"scanline":this.effectState={row:0};break;case"rain":this.effectState={drops:Array.from({length:c},()=>({y:-Math.floor(Math.random()*s*2),settled:0}))};break;case"fade":{let t=[];for(let e=0;e<s;e++)for(let i=0;i<c;i++)t.push([e,i]);for(let e=t.length-1;e>0;e--){let i=Math.floor(Math.random()*(e+1));[t[e],t[i]]=[t[i],t[e]]}this.effectState={positions:t,idx:0};break}case"crt":this.effectState={expansion:0};break;case"glitch":this.effectState={phase:0,glitchFrames:8};break;case"dissolve":{this.currentGrid=Array.from({length:s},()=>Array.from({length:c},()=>{let e=[" ","\u2591","\u2592","\u2593","\u2588","\u2580","\u2584"];return e[Math.floor(Math.random()*e.length)]}));let t=[];for(let e=0;e<s;e++)for(let i=0;i<c;i++)t.push([e,i]);for(let e=t.length-1;e>0;e--){let i=Math.floor(Math.random()*(e+1));[t[e],t[i]]=[t[i],t[e]]}this.effectState={positions:t,idx:0};break}}}startAnimation(){let t=this.effect==="glitch"?60:30;this.interval=setInterval(()=>{let e=this.tickEffect();this.updateDisplay(),this.ui.requestRender(),e&&this.stopAnimation()},1e3/t)}stopAnimation(){this.interval&&(clearInterval(this.interval),this.interval=null)}tickEffect(){switch(this.effect){case"typewriter":return this.tickTypewriter();case"scanline":return this.tickScanline();case"rain":return this.tickRain();case"fade":return this.tickFade();case"crt":return this.tickCrt();case"glitch":return this.tickGlitch();case"dissolve":return this.tickDissolve();default:return!0}}tickTypewriter(){let t=this.effectState,e=3;for(let i=0;i<e;i++){let r=Math.floor(t.pos/c),f=t.pos%c;if(r>=s)return!0;this.currentGrid[r][f]=this.finalGrid[r][f],t.pos++}return!1}tickScanline(){let t=this.effectState;if(t.row>=s)return!0;for(let e=0;e<c;e++)this.currentGrid[t.row][e]=this.finalGrid[t.row][e];return t.row++,!1}tickRain(){let t=this.effectState,e=!0;this.currentGrid=this.createEmptyGrid();for(let i=0;i<c;i++){let r=t.drops[i];for(let n=s-1;n>=s-r.settled;n--)n>=0&&(this.currentGrid[n][i]=this.finalGrid[n][i]);if(r.settled>=s)continue;e=!1;let f=-1;for(let n=s-1-r.settled;n>=0;n--)if(this.finalGrid[n][i]!==" "){f=n;break}r.y++,r.y>=0&&r.y<s&&(f>=0&&r.y>=f?(r.settled=s-f,r.y=-Math.floor(Math.random()*5)-1):this.currentGrid[r.y][i]="\u2593")}return e}tickFade(){let t=this.effectState,e=15;for(let i=0;i<e;i++){if(t.idx>=t.positions.length)return!0;let[r,f]=t.positions[t.idx];this.currentGrid[r][f]=this.finalGrid[r][f],t.idx++}return!1}tickCrt(){let t=this.effectState,e=Math.floor(s/2);this.currentGrid=this.createEmptyGrid();let i=e-t.expansion,r=e+t.expansion;for(let f=Math.max(0,i);f<=Math.min(s-1,r);f++)for(let n=0;n<c;n++)this.currentGrid[f][n]=this.finalGrid[f][n];return t.expansion++,t.expansion>s}tickGlitch(){let t=this.effectState;return t.phase<t.glitchFrames?(this.currentGrid=this.finalGrid.map(e=>{let i=Math.floor(Math.random()*7)-3,r=[...e];if(Math.random()<.3)return r.slice(i).concat(r.slice(0,i)).slice(0,c);if(Math.random()<.2){let f=Math.floor(Math.random()*s);return[...this.finalGrid[f]]}return r}),t.phase++,!1):(this.currentGrid=this.finalGrid.map(e=>[...e]),!0)}tickDissolve(){let t=this.effectState,e=20;for(let i=0;i<e;i++){if(t.idx>=t.positions.length)return!0;let[r,f]=t.positions[t.idx];this.currentGrid[r][f]=this.finalGrid[r][f],t.idx++}return!1}updateDisplay(){this.gridVersion++}dispose(){this.stopAnimation()}};export{m as a,G as b,l as c,d};
4
+ import{ta as o}from"./chunk-GOS3P7KS.js";var m=31,G=36,c=m,u=G,g=[255,255,255,127,255,240,255,127,255,237,255,127,255,219,255,127,255,183,255,127,255,119,254,127,63,248,254,127,223,255,254,127,223,63,252,127,159,195,251,127,111,252,244,127,247,15,247,127,247,255,247,127,247,255,227,127,247,7,232,127,239,248,103,112,15,255,187,111,241,0,208,91,253,63,236,83,193,255,239,87,159,253,238,95,159,252,174,95,31,120,172,95,63,0,80,108,127,0,220,119,255,192,63,120,255,1,248,127,255,3,156,120,255,7,140,124,255,15,206,120,255,255,207,127,255,255,207,120,255,255,223,120,255,255,223,125,255,255,63,126,255,255,255,127],M=Math.ceil(c/8),s=Math.ceil(u/2),h=["typewriter","scanline","rain","fade","crt","glitch","dissolve"];function l(a,t){if(t>=u)return!1;let e=t*M+Math.floor(a/8),i=a%8;return(g[e]>>i&1)===0}function k(a,t){let e=l(a,t*2),i=l(a,t*2+1);return e&&i?"\u2588":e?"\u2580":i?"\u2584":" "}function S(){let a=[];for(let t=0;t<s;t++){let e=[];for(let i=0;i<c;i++)e.push(k(i,t));a.push(e)}return a}var d=class{ui;interval=null;effect;finalGrid;currentGrid;effectState={};cachedLines=[];cachedWidth=0;gridVersion=0;cachedVersion=-1;constructor(t){this.ui=t,this.effect=h[Math.floor(Math.random()*h.length)],this.finalGrid=S(),this.currentGrid=this.createEmptyGrid(),this.initEffect(),this.startAnimation()}invalidate(){this.cachedWidth=0}render(t){if(t===this.cachedWidth&&this.cachedVersion===this.gridVersion)return this.cachedLines;let e=1,i=t-e;this.cachedLines=this.currentGrid.map(n=>{let x=n.slice(0,i).join(""),p=Math.max(0,t-e-x.length);return` ${o.fg("accent",x)}${" ".repeat(p)}`});let r="ARMIN SAYS HI",f=Math.max(0,t-e-r.length);return this.cachedLines.push(` ${o.fg("accent",r)}${" ".repeat(f)}`),this.cachedWidth=t,this.cachedVersion=this.gridVersion,this.cachedLines}createEmptyGrid(){return Array.from({length:s},()=>Array(c).fill(" "))}initEffect(){switch(this.effect){case"typewriter":this.effectState={pos:0};break;case"scanline":this.effectState={row:0};break;case"rain":this.effectState={drops:Array.from({length:c},()=>({y:-Math.floor(Math.random()*s*2),settled:0}))};break;case"fade":{let t=[];for(let e=0;e<s;e++)for(let i=0;i<c;i++)t.push([e,i]);for(let e=t.length-1;e>0;e--){let i=Math.floor(Math.random()*(e+1));[t[e],t[i]]=[t[i],t[e]]}this.effectState={positions:t,idx:0};break}case"crt":this.effectState={expansion:0};break;case"glitch":this.effectState={phase:0,glitchFrames:8};break;case"dissolve":{this.currentGrid=Array.from({length:s},()=>Array.from({length:c},()=>{let e=[" ","\u2591","\u2592","\u2593","\u2588","\u2580","\u2584"];return e[Math.floor(Math.random()*e.length)]}));let t=[];for(let e=0;e<s;e++)for(let i=0;i<c;i++)t.push([e,i]);for(let e=t.length-1;e>0;e--){let i=Math.floor(Math.random()*(e+1));[t[e],t[i]]=[t[i],t[e]]}this.effectState={positions:t,idx:0};break}}}startAnimation(){let t=this.effect==="glitch"?60:30;this.interval=setInterval(()=>{let e=this.tickEffect();this.updateDisplay(),this.ui.requestRender(),e&&this.stopAnimation()},1e3/t)}stopAnimation(){this.interval&&(clearInterval(this.interval),this.interval=null)}tickEffect(){switch(this.effect){case"typewriter":return this.tickTypewriter();case"scanline":return this.tickScanline();case"rain":return this.tickRain();case"fade":return this.tickFade();case"crt":return this.tickCrt();case"glitch":return this.tickGlitch();case"dissolve":return this.tickDissolve();default:return!0}}tickTypewriter(){let t=this.effectState,e=3;for(let i=0;i<e;i++){let r=Math.floor(t.pos/c),f=t.pos%c;if(r>=s)return!0;this.currentGrid[r][f]=this.finalGrid[r][f],t.pos++}return!1}tickScanline(){let t=this.effectState;if(t.row>=s)return!0;for(let e=0;e<c;e++)this.currentGrid[t.row][e]=this.finalGrid[t.row][e];return t.row++,!1}tickRain(){let t=this.effectState,e=!0;this.currentGrid=this.createEmptyGrid();for(let i=0;i<c;i++){let r=t.drops[i];for(let n=s-1;n>=s-r.settled;n--)n>=0&&(this.currentGrid[n][i]=this.finalGrid[n][i]);if(r.settled>=s)continue;e=!1;let f=-1;for(let n=s-1-r.settled;n>=0;n--)if(this.finalGrid[n][i]!==" "){f=n;break}r.y++,r.y>=0&&r.y<s&&(f>=0&&r.y>=f?(r.settled=s-f,r.y=-Math.floor(Math.random()*5)-1):this.currentGrid[r.y][i]="\u2593")}return e}tickFade(){let t=this.effectState,e=15;for(let i=0;i<e;i++){if(t.idx>=t.positions.length)return!0;let[r,f]=t.positions[t.idx];this.currentGrid[r][f]=this.finalGrid[r][f],t.idx++}return!1}tickCrt(){let t=this.effectState,e=Math.floor(s/2);this.currentGrid=this.createEmptyGrid();let i=e-t.expansion,r=e+t.expansion;for(let f=Math.max(0,i);f<=Math.min(s-1,r);f++)for(let n=0;n<c;n++)this.currentGrid[f][n]=this.finalGrid[f][n];return t.expansion++,t.expansion>s}tickGlitch(){let t=this.effectState;return t.phase<t.glitchFrames?(this.currentGrid=this.finalGrid.map(e=>{let i=Math.floor(Math.random()*7)-3,r=[...e];if(Math.random()<.3)return r.slice(i).concat(r.slice(0,i)).slice(0,c);if(Math.random()<.2){let f=Math.floor(Math.random()*s);return[...this.finalGrid[f]]}return r}),t.phase++,!1):(this.currentGrid=this.finalGrid.map(e=>[...e]),!0)}tickDissolve(){let t=this.effectState,e=20;for(let i=0;i<e;i++){if(t.idx>=t.positions.length)return!0;let[r,f]=t.positions[t.idx];this.currentGrid[r][f]=this.finalGrid[r][f],t.idx++}return!1}updateDisplay(){this.gridVersion++}dispose(){this.stopAnimation()}};export{m as a,G as b,l as c,d};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{i as m}from"./chunk-Z24SBRJK.js";import*as d from"path";import{readFileSync as y,writeFileSync as S,mkdirSync as v,existsSync as w,unlinkSync as b}from"fs";var h=class extends Error{constructor(t){super(t),this.name="FeishuUserTokenError"}};function u(e){return e==="lark"?{authorizeBase:"https://accounts.larksuite.com",tokenBase:"https://open.larksuite.com"}:{authorizeBase:"https://accounts.feishu.cn",tokenBase:"https://open.feishu.cn"}}var k="/open-apis/authen/v2/oauth/token",P="/open-apis/authen/v1/authorize",U="/oauth/v1/device_authorization",E="urn:ietf:params:oauth:grant-type:device_code",z="offline_access",N="docx:document sheets:spreadsheet bitable:app wiki:wiki space:document:delete im:resource";function f(){return d.join(m,"feishu-user-token.json")}function T(e){let t=new Set((e??"").split(/\s+/).filter(Boolean));return t.add(z),[...t].join(" ")}function B(e){let{authorizeBase:t}=u(e.domain),n=new URL(t+P);return n.searchParams.set("client_id",e.appId),n.searchParams.set("redirect_uri",e.redirectUri),n.searchParams.set("response_type","code"),n.searchParams.set("scope",T(e.scope)),e.state&&n.searchParams.set("state",e.state),n.toString()}function R(e){let t=(e??"").trim();if(!t)return null;if(/^https?:\/\//i.test(t))try{return new URL(t).searchParams.get("code")}catch{return null}return t}function p(e,t,n){let o=Number(e.expires_in??0)*1e3,r=Number(e.refresh_token_expires_in??0)*1e3;return{access_token:String(e.access_token??""),refresh_token:String(e.refresh_token??n??""),access_expires_at:t+o,refresh_expires_at:t+r,scope:e.scope,obtained_at:t}}async function x(e,t,n){let o=await n(e.tokenBase+k,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(t)}),r=await o.json().catch(()=>({}));if(!o.ok||typeof r.code=="number"&&r.code!==0||r.error){let i=r.error_description||r.error||r.msg||`HTTP ${o.status}`,c=r.code??r.error??o.status;throw new Error(`Feishu OAuth error ${c}: ${i}`)}return r}async function j(e){let t=e.fetchImpl??globalThis.fetch,n=(e.now??Date.now)(),o={grant_type:"authorization_code",client_id:e.appId,client_secret:e.appSecret,code:e.code};e.redirectUri&&(o.redirect_uri=e.redirectUri);let r=await x(u(e.domain),o,t);return p(r,n)}function O(e,t){return Buffer.from(`${e}:${t}`,"utf8").toString("base64")}function g(e){return Object.entries(e).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&")}async function H(e){let t=e.fetchImpl??globalThis.fetch,n=u(e.domain),o=await t(n.authorizeBase+U,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${O(e.appId,e.appSecret)}`},body:g({client_id:e.appId,scope:T(e.scope)})}),r=await o.json().catch(()=>({}));if(!o.ok||r.error||!r.device_code){let c=r.error_description||r.error||r.msg||`HTTP ${o.status}`;throw new Error(`Feishu device authorization failed: ${c}`)}let i=String(r.verification_uri??"");return{device_code:String(r.device_code),user_code:String(r.user_code??""),verification_uri:i,verification_uri_complete:String(r.verification_uri_complete||i),expires_in:Number(r.expires_in??300),interval:Number(r.interval??5)}}async function L(e){let t=e.fetchImpl??globalThis.fetch,n=e.sleep??(l=>new Promise(s=>setTimeout(s,l))),o=e.now??Date.now,r=u(e.domain),i=60,c=Math.max(1,e.interval??5),I=o()+(e.expiresIn??300)*1e3;for(;;){await n(c*1e3);let s=await(await t(r.tokenBase+k,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:g({grant_type:E,device_code:e.deviceCode,client_id:e.appId,client_secret:e.appSecret})})).json().catch(()=>({})),a=s.error;if(!a&&s.access_token)return p(s,o());if(a==="authorization_pending")e.onPending?.();else if(a==="slow_down")c=Math.min(i,c+5),e.onPending?.();else if(a)throw new Error(`Feishu device login failed: ${s.error_description||a}`);if(o()>=I)throw new Error("Feishu device login timed out before authorization completed.")}}async function C(e){let t=e.fetchImpl??globalThis.fetch,n=(e.now??Date.now)(),o=await x(u(e.domain),{grant_type:"refresh_token",client_id:e.appId,client_secret:e.appSecret,refresh_token:e.refreshToken},t);return p(o,n,e.refreshToken)}function A(e,t=f()){v(d.dirname(t),{recursive:!0}),S(t,JSON.stringify(e,null,2),{mode:384})}function F(e=f()){if(!w(e))return null;try{return JSON.parse(y(e,"utf8"))}catch{return null}}function G(e=f()){if(!w(e))return!1;try{return b(e),!0}catch{return!1}}var _="Run `cortex feishu login` to authorize a Feishu user account.";async function J(e){let t=e.file??f(),n=(e.now??Date.now)(),o=e.bufferMs??12e4,r=F(t);if(!r||!r.access_token)throw new h(`No Feishu user token found. ${_}`);if(n<r.access_expires_at-o)return r.access_token;if(!r.refresh_token||n>=r.refresh_expires_at)throw new h(`Feishu user token expired and cannot be refreshed. ${_}`);let i=await C({appId:e.appId,appSecret:e.appSecret,refreshToken:r.refresh_token,domain:e.domain,fetchImpl:e.fetchImpl,now:()=>n});return A(i,t),i.access_token}export{N as a,f as b,B as c,R as d,j as e,H as f,L as g,A as h,F as i,G as j,J as k};
4
+ import{j as m}from"./chunk-T54CZKNJ.js";import*as d from"path";import{readFileSync as y,writeFileSync as S,mkdirSync as v,existsSync as w,unlinkSync as b}from"fs";var h=class extends Error{constructor(t){super(t),this.name="FeishuUserTokenError"}};function u(e){return e==="lark"?{authorizeBase:"https://accounts.larksuite.com",tokenBase:"https://open.larksuite.com"}:{authorizeBase:"https://accounts.feishu.cn",tokenBase:"https://open.feishu.cn"}}var k="/open-apis/authen/v2/oauth/token",P="/open-apis/authen/v1/authorize",U="/oauth/v1/device_authorization",E="urn:ietf:params:oauth:grant-type:device_code",z="offline_access",N="docx:document sheets:spreadsheet bitable:app wiki:wiki space:document:delete im:resource";function f(){return d.join(m,"feishu-user-token.json")}function T(e){let t=new Set((e??"").split(/\s+/).filter(Boolean));return t.add(z),[...t].join(" ")}function B(e){let{authorizeBase:t}=u(e.domain),n=new URL(t+P);return n.searchParams.set("client_id",e.appId),n.searchParams.set("redirect_uri",e.redirectUri),n.searchParams.set("response_type","code"),n.searchParams.set("scope",T(e.scope)),e.state&&n.searchParams.set("state",e.state),n.toString()}function R(e){let t=(e??"").trim();if(!t)return null;if(/^https?:\/\//i.test(t))try{return new URL(t).searchParams.get("code")}catch{return null}return t}function p(e,t,n){let o=Number(e.expires_in??0)*1e3,r=Number(e.refresh_token_expires_in??0)*1e3;return{access_token:String(e.access_token??""),refresh_token:String(e.refresh_token??n??""),access_expires_at:t+o,refresh_expires_at:t+r,scope:e.scope,obtained_at:t}}async function x(e,t,n){let o=await n(e.tokenBase+k,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(t)}),r=await o.json().catch(()=>({}));if(!o.ok||typeof r.code=="number"&&r.code!==0||r.error){let i=r.error_description||r.error||r.msg||`HTTP ${o.status}`,c=r.code??r.error??o.status;throw new Error(`Feishu OAuth error ${c}: ${i}`)}return r}async function j(e){let t=e.fetchImpl??globalThis.fetch,n=(e.now??Date.now)(),o={grant_type:"authorization_code",client_id:e.appId,client_secret:e.appSecret,code:e.code};e.redirectUri&&(o.redirect_uri=e.redirectUri);let r=await x(u(e.domain),o,t);return p(r,n)}function O(e,t){return Buffer.from(`${e}:${t}`,"utf8").toString("base64")}function g(e){return Object.entries(e).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&")}async function H(e){let t=e.fetchImpl??globalThis.fetch,n=u(e.domain),o=await t(n.authorizeBase+U,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${O(e.appId,e.appSecret)}`},body:g({client_id:e.appId,scope:T(e.scope)})}),r=await o.json().catch(()=>({}));if(!o.ok||r.error||!r.device_code){let c=r.error_description||r.error||r.msg||`HTTP ${o.status}`;throw new Error(`Feishu device authorization failed: ${c}`)}let i=String(r.verification_uri??"");return{device_code:String(r.device_code),user_code:String(r.user_code??""),verification_uri:i,verification_uri_complete:String(r.verification_uri_complete||i),expires_in:Number(r.expires_in??300),interval:Number(r.interval??5)}}async function L(e){let t=e.fetchImpl??globalThis.fetch,n=e.sleep??(l=>new Promise(s=>setTimeout(s,l))),o=e.now??Date.now,r=u(e.domain),i=60,c=Math.max(1,e.interval??5),I=o()+(e.expiresIn??300)*1e3;for(;;){await n(c*1e3);let s=await(await t(r.tokenBase+k,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:g({grant_type:E,device_code:e.deviceCode,client_id:e.appId,client_secret:e.appSecret})})).json().catch(()=>({})),a=s.error;if(!a&&s.access_token)return p(s,o());if(a==="authorization_pending")e.onPending?.();else if(a==="slow_down")c=Math.min(i,c+5),e.onPending?.();else if(a)throw new Error(`Feishu device login failed: ${s.error_description||a}`);if(o()>=I)throw new Error("Feishu device login timed out before authorization completed.")}}async function C(e){let t=e.fetchImpl??globalThis.fetch,n=(e.now??Date.now)(),o=await x(u(e.domain),{grant_type:"refresh_token",client_id:e.appId,client_secret:e.appSecret,refresh_token:e.refreshToken},t);return p(o,n,e.refreshToken)}function A(e,t=f()){v(d.dirname(t),{recursive:!0}),S(t,JSON.stringify(e,null,2),{mode:384})}function F(e=f()){if(!w(e))return null;try{return JSON.parse(y(e,"utf8"))}catch{return null}}function G(e=f()){if(!w(e))return!1;try{return b(e),!0}catch{return!1}}var _="Run `cortex feishu login` to authorize a Feishu user account.";async function J(e){let t=e.file??f(),n=(e.now??Date.now)(),o=e.bufferMs??12e4,r=F(t);if(!r||!r.access_token)throw new h(`No Feishu user token found. ${_}`);if(n<r.access_expires_at-o)return r.access_token;if(!r.refresh_token||n>=r.refresh_expires_at)throw new h(`Feishu user token expired and cannot be refreshed. ${_}`);let i=await C({appId:e.appId,appSecret:e.appSecret,refreshToken:r.refresh_token,domain:e.domain,fetchImpl:e.fetchImpl,now:()=>n});return A(i,t),i.access_token}export{N as a,f as b,B as c,R as d,j as e,H as f,L as g,A as h,F as i,G as j,J as k};
@@ -0,0 +1,4 @@
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 l}from"./chunk-CXT5IR5T.js";function h(r,a,s,t){return{role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:t,errorMessage:a instanceof Error?a.message:String(a),timestamp:s}}function m(r){return typeof r.result=="function"}async function w(r,a,s,t){let n;for await(let e of a)r.push(e),s?.onEvent?.(e),e.type==="done"?n=e.message:e.type==="error"&&(n=e.error);m(a)&&(n=await a.result()),r.end(n),t(n)}function f(r,a,s,t){let n=Date.now(),e=new l,c=!1,u=o=>{c||(c=!0,s?.onResult?.(o))};return a().then(o=>w(e,o,s,u)).catch(o=>{let d=t?.aborted?"aborted":"error",i=h(r,o,n,d),p={type:"error",reason:d,error:i};e.push(p),s?.onEvent?.(p),e.end(i),u(i)}),e}function g(r,a){let s={stream:(t,n,e)=>f(t,async()=>(await r()).stream(t,n,e),void 0,e?.signal),streamSimple:(t,n,e)=>f(t,async()=>(await r()).streamSimple(t,n,e),void 0,e?.signal)};return a?.fetchDeferred&&(s.fetchDeferred=(t,n,e)=>f(t,async()=>{let c=await r();if(!c.fetchDeferred)throw new Error("API does not support deferred responses");return c.fetchDeferred(t,n,e)},void 0,e?.signal)),a?.cancelDeferred&&(s.cancelDeferred=async(t,n,e)=>{let c=await r();if(!c.cancelDeferred)throw new Error("API cannot cancel deferred responses");await c.cancelDeferred(t,n,e)}),s}export{f as a,g as b};
@@ -0,0 +1,60 @@
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{G as pe,H as It,K as wt,L as xt,a as le,b as ue,c as Ee,i as ht,m as bt}from"./chunk-ZAVX7G2M.js";import{a as it}from"./chunk-TCAEECDI.js";import{a as lt,b as ut,c as pt,d as W,e as dt,f as mt,g as ft,i as gt}from"./chunk-ZFPMIQA3.js";import{a as rt,b as ce}from"./chunk-LEAV3FFG.js";import{a as yt}from"./chunk-4HRI75GU.js";import{a as J}from"./chunk-BKYP6AGM.js";import{k as st,w as ct,x as $e,z as Q}from"./chunk-KST6OY76.js";import{a as nt,b as ot,f as Z}from"./chunk-AXYAZTTN.js";import{a as P}from"./chunk-R2CCD4OF.js";import{K as e}from"./chunk-W34AK4SK.js";import{e as _}from"./chunk-7GGPYU5E.js";import{e as $}from"./chunk-7W7VYUTK.js";import{f as at,g as ve}from"./chunk-JGUEIW2W.js";import{e as et,k as tt}from"./chunk-T54CZKNJ.js";var kn=[["permission",/\b(EACCES|EPERM)\b|permission denied/i],["disk",/\bENOSPC\b|no space left/i],["timeout",/\bETIMEDOUT\b|timed? ?out|killed by SIG/i],["network",/\b(ENOTFOUND|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENETUNREACH)\b|network|fetch failed/i],["npm",/npm (ERR|error)|exited with code|could not start/i]];function Tn(t){return kn.find(([,n])=>n.test(t))?.[0]??"other"}function St(t,n){return Math.max(0,Math.round((n-t)/1e3))}function de(t,n=new Date){return{type:"upgrade",at:n.toISOString(),...t}}function Rn(t,n){let o=St(Date.parse(t.startedAt),Date.now()),{from:r,to:i,method:a}=t;if(n===null){$e(u=>({...u,pendingUpgrade:t})),Q(de({from:r,to:i,method:a,stage:"installed",durationS:o,failure:null}));return}let c={class:Tn(n),message:J(n)};Q(de({from:r,to:i,method:a,stage:"failed",durationS:o,failure:c}),{urgent:!0})}function vt(t){return(n,o)=>{let r={from:P,to:n,startedAt:new Date().toISOString(),method:Z().serverAutoUpdate?"auto":"prompt"};t(n,i=>{try{Rn(r,i)}catch{}o(i)})}}function jn(t,n,o){if(t){let r=t.to===P?"confirmed":"unconfirmed",i=St(Date.parse(t.startedAt),o);return de({...t,stage:r,durationS:i,failure:null},new Date(o))}return!n||n===P?null:de({from:n,to:P,method:"manual",stage:"version-changed",durationS:null,failure:null},new Date(o))}function Ns(t=Date.now()){let n=ct(),o=jn(n.pendingUpgrade,n.lastVersion,t);$e(r=>({...r,pendingUpgrade:null,lastVersion:P})),o&&Q(o)}function Cn(t){let n=t?.code;return n==="EACCES"||n==="EPERM"?"permission":t instanceof SyntaxError?"parse":typeof n=="string"&&n.startsWith("E")?"io":"other"}function Us(t){let n=t.error instanceof Error?t.error.message:String(t.error);Q({type:"migration_failure",at:new Date().toISOString(),migration:t.migration.replace(/[^A-Za-z0-9._:/@[\]-]/g,"_").slice(0,80),errorClass:Cn(t.error),message:J(n)})}import*as he from"node:fs";import*as je from"node:os";import{spawn as Mn}from"node:child_process";var U=class extends Error{failure;detail;constructor(n,o){super(o?`${n}: ${o}`:n),this.failure=n,this.detail=o,this.name="UpdateLookupError"}};function G(t,n){let o=n?.trim();return{status:"error",reason:"check_failed",failure:t,...o?{detail:J(o)}:{}}}function me(t){return t instanceof U?G(t.failure,t.detail):t instanceof Error?G(`exception:${t.name}`,t.message):G(`exception:${typeof t}`,String(t))}var Et={available:null,state:"idle"},x=Et,A=null;function $t(){return x}function Hs(t,n){let o=A;A=null,o?.(null),A=n,x={available:t,state:"prompting"}}function kt(t){let n=A;return n?(A=null,n(t),!0):!1}function qs(t){A=null,x=t==="apply"?{available:x.available,state:"waiting"}:Et}function Tt(t){let n=A;A=null,n?.(null),x={available:t,state:"waiting",auto:!0}}function Rt(){return x.auto?{auto:!0}:{}}function jt(){x={available:x.available,state:"installing",...Rt()}}function Ct(){x={available:x.available,state:"restarting",...Rt()}}function ee(t){x={available:x.available,state:"failed",error:t}}var _n=2e4,_t=Symbol("timed out"),Pn=/^\d+\.\d+\.\d+(?:-\d+)?$/;function ke(t){return{status:"available",update:{version:t}}}async function An(t){let n,o=new Promise(r=>{n=setTimeout(()=>r(_t),_n),n.unref?.()});try{return await Promise.race([Promise.resolve().then(t),o])}finally{clearTimeout(n)}}var fe=class{deps;inFlight=null;pending=null;latestVersion=null;promptFailure=null;decision=Promise.resolve(null);constructor(n){this.deps=n}check(){return this.inFlight?this.inFlight:(this.inFlight=this.discover().catch(me).finally(()=>{this.inFlight=null}),this.inFlight)}async checkAndWait(){return await this.check(),{action:await this.decision,latestVersion:this.latestVersion}}skipReason(){if(Z().serverUpdateDisable)return"disabled";if(this.deps.isDevMode())return"dev_mode";let{state:n}=$t();return n==="waiting"||n==="installing"||n==="restarting"?"update_in_progress":null}async discover(){let n=this.skipReason();return n?{status:"skipped",reason:n}:this.lookup()}async lookup(){let n=await An(this.deps.getLatest);if(n===_t)return G("timeout");if(!n||!Pn.test(n))return G("bad_version",n??void 0);let o=this.skipReason();return o?{status:"skipped",reason:o}:(this.latestVersion=n,this.resolveVersion(n))}resolveVersion(n){if(it(n,P)<=0)return this.current();let o=this.deps.loadState()??{};return o.skippedVersion===n?{status:"skipped",reason:"version_skipped"}:Z().serverAutoUpdate?this.autoInstall(n,o):this.pending?.version===n?ke(n):this.openPrompt(n,o)}autoInstall(n,o){this.deps.saveState({...o,lastCheckedAt:this.deps.now()}),this.pending=null,Tt(n);try{this.deps.installWhenIdle(n)}catch(r){return ee(r instanceof Error?r.message:String(r)),this.decision=Promise.resolve(null),me(r)}return this.decision=Promise.resolve("apply"),{...ke(n),reason:"auto_install"}}current(){return this.pending&&(this.pending=null,kt("cancel"),this.decision=Promise.resolve(null)),{status:"current"}}async openPrompt(n,o){let r={...o,lastCheckedAt:this.deps.now(),lastPromptedVersion:n};this.deps.saveState(r);let i=this.deps.prompt.ask({latestVersion:n});return this.pending={version:n,answer:i},this.promptFailure=null,this.decision=this.handleDecision(this.pending,r),await Promise.resolve(),this.promptFailure??ke(n)}async handleDecision(n,o){try{let r=await n.answer;return this.pending!==n?null:this.acceptChoice(r,n.version,o)}catch(r){return this.failDecision(n,r)}finally{this.pending===n&&(this.pending=null)}}failDecision(n,o){return this.pending!==n||(this.promptFailure=me(o),ee(o instanceof Error?o.message:String(o))),null}acceptChoice(n,o,r){return n==="apply"&&(this.deps.saveState({...r,skippedVersion:void 0}),this.deps.installWhenIdle(o)),n==="skip"&&this.deps.saveState({...r,skippedVersion:o}),n}};import{execFile as On}from"node:child_process";var Dn=1024*1024;function Ln(t,n,o,r,i){let a=n&&typeof n.code=="number"?n.code:n?null:0,c=n?.signal??null,u=!!n&&(n?.killed===!0||c==="SIGTERM")&&i!==void 0;t({ok:a===0,code:a,signal:c,timedOut:u,stdout:o,stderr:r,...n&&typeof n.code=="string"?{error:n.message}:{}})}function H(t,n=[],o={}){return new Promise(r=>{let i=On(t,[...n],{cwd:o.cwd,shell:o.shell,env:o.env??process.env,timeout:o.timeoutMs,killSignal:"SIGTERM",maxBuffer:o.maxBuffer??Dn,encoding:"utf8",windowsHide:!0},(a,c,u)=>Ln(r,a,c,u,o.timeoutMs));o.stdin!==void 0?i.stdin?.end(o.stdin):i.stdin?.end()})}function er(t,n={}){let o=process.platform==="win32"?process.env.ComSpec??"cmd.exe":"/bin/sh",r=process.platform==="win32"?"/c":"-c";return H(o,[r,t],n)}import*as q from"fs";import*as ge from"path";var Te=ge.join(tt,"update-state.json");function Pt(){try{return JSON.parse(q.readFileSync(Te,"utf8"))}catch{return null}}function At(t){let n=ge.dirname(Te);q.mkdirSync(n,{recursive:!0}),q.writeFileSync(Te,JSON.stringify(t,null,2))}var Fn=6e4,Ot={isIdle:()=>!0,onIdle:()=>()=>{}};function Dt(t,n,o={}){let r=o.supervised??(()=>!!process.send),i=o.renewMs??Fn,a=null,c=!1,u=null,f=(b,g)=>{if(clearInterval(b),c=!1,g!==null){Ee(),ee(g);return}Ct(),r()?ue({phase:le}):Ee()},m=()=>{if(c||a===null||!t.isIdle())return;let b=a;a=null,u?.(),u=null,c=!0,ue({phase:le});let g=setInterval(()=>ue({phase:le}),i);g.unref?.(),jt();let N=!1,K=C=>{N||(N=!0,f(g,C))};try{n(b,K)}catch(C){K(C instanceof Error?C.message:String(C))}};return b=>{if(a=b,t.isIdle()){m();return}u??=t.onIdle(m)}}function Nn(){let t=process.env.CORTEX_REPO;if(!t)return!1;try{return he.existsSync(t)&&he.statSync(t).isDirectory()}catch{return!1}}async function Un(){let t=ve(["view","@cortex-agent/server","version"]),n=await H(t.command,t.args,{shell:t.shell,timeoutMs:15e3,cwd:je.tmpdir()});if(!n.ok)throw Bn(n);return n.stdout.trim()||null}function Bn(t){return t.timedOut?new U("timeout",Re(t.stderr)):t.error?new U("npm_spawn",t.error):new U(`npm_exit:${t.code??t.signal}`,Re(t.stderr))}var Wn=2e3;function Re(t){return t.trim().split(`
5
+ `).slice(-6).join(`
6
+ `).trim()}function Gn(t,n,o){let r=n!==null?`killed by ${n}`:`exited with code ${t}`,i=Re(o);return i?`npm install -g ${r}
7
+ ${i}`:`npm install -g ${r}`}function Hn(t,n){let o=ve(at(["install","-g",`@cortex-agent/server@${t}`])),r=Mn(o.command,o.args,{shell:o.shell,detached:!0,stdio:["ignore","ignore","pipe"],cwd:je.tmpdir()}),i="";r.stderr?.on("data",a=>{i.length<Wn&&(i+=String(a))}),r.stderr?.unref?.(),r.on("error",a=>n(`npm install -g could not start: ${a.message}`)),r.on("exit",(a,c)=>n(a===0?null:Gn(a,c,i))),r.unref()}function qn(){return new Date().toISOString()}function gr(t){return new fe({prompt:t.prompt,getLatest:t.getLatest??Un,installWhenIdle:t.installWhenIdle??Dt(t.idle??Ot,vt(Hn)),loadState:t.loadState??Pt,saveState:t.saveState??At,now:t.now??qn,isDevMode:Nn})}import*as Ft from"net";var O=$("device-port"),Lt="127.0.0.1",Mt="127.0.0.1",Vn=32,Xn=64,D=new Map;function Nt(t,n,o){return`${t}|${n}|${o}`}function zn(t,n,o){let r=!1,i=a=>{if(!r){r=!0,O.debug(`${o} closed: ${a}`);try{n.close()}catch{}try{t.destroy()}catch{}}};n.on("message",a=>{let c=Array.isArray(a)?Buffer.concat(a):Buffer.from(a);t.write(c)||(n.pause?.(),t.once("drain",()=>n.resume?.()))}),n.on("error",a=>i(`ws error: ${a.message}`)),n.on("close",()=>i("ws closed")),t.on("data",a=>{t.pause(),n.send(a,c=>{c?i(`send failed: ${c.message}`):t.resume()})}),t.on("error",a=>i(`tcp error: ${a.message}`)),t.on("close",()=>i("tcp closed")),t.resume()}var Yn=wt;async function Kn(t,n){let{device:o,remoteHost:r,remotePort:i}=t.info;if(n.pause(),n.setNoDelay(!0),t.connections.add(n),n.once("close",()=>t.connections.delete(n)),t.connections.size>Xn){O.warn(`${o}:${i} \u2014 connection cap reached, refusing`),n.destroy();return}let a;try{a=bt(o,r,i)}catch(u){O.warn(`${o}:${i} \u2014 ${u.message}`),n.destroy();return}a.socket.catch(()=>{});try{Yn(o,a.message)}catch(u){O.warn(`${o}:${i} \u2014 cannot ask device to open a stream: ${u.message}`),n.destroy();return}let c;try{c=await a.socket}catch(u){O.warn(`${o}:${i} \u2014 ${u.message}`),n.destroy();return}if(n.destroyed){try{c.close()}catch{}return}zn(n,c,`${o}:${i} stream ${a.id.slice(0,8)}`)}async function Ut(t,n){let o=Mt,r=Nt(t,o,n),i=D.get(r);if(i)return i.info;if(D.size>=Vn)throw new Error(`too many device ports open (${D.size})`);let a=Ft.createServer(),c={info:{device:t,remoteHost:o,remotePort:n,localPort:0,openedAt:new Date},server:a,connections:new Set};await new Promise((f,m)=>{a.once("error",m),a.listen(0,Lt,()=>{a.removeListener("error",m),f()})});let u=a.address();if(!u||typeof u=="string")throw a.close(),new Error("failed to bind a local port");return c.info.localPort=u.port,a.on("connection",f=>{Kn(c,f)}),a.on("error",f=>O.warn(`listener for ${t}:${n} failed: ${f.message}`)),D.set(r,c),O.info(`device port ${Lt}:${u.port} \u2192 ${t} ${o}:${n}`),c.info}function V(t,n){let o=Mt,r=Nt(t,o,n),i=D.get(r);if(!i)return!1;D.delete(r);for(let a of i.connections)a.destroy();return i.connections.clear(),i.server.close(),O.info(`closed device port ${i.info.localPort} \u2192 ${t} ${o}:${n}`),!0}function xr(){return[...D.values()].map(t=>({...t.info}))}function yr(){for(let t of[...D.values()])V(t.info.device,t.info.remotePort)}import*as oe from"fs";import*as Yt from"net";import*as Kt from"path";import{spawn as Zt}from"child_process";import*as X from"fs";import*as Ce from"path";import{execFile as Zn,spawn as Jn}from"child_process";import{promisify as Qn}from"util";var eo=Qn(Zn),Bt=$("browser-display");function to(t){if(t.override)return{mode:"attached",display:t.override,takeover:"remote-desktop",reason:`display pinned by configuration (${t.override})`};if(t.platform==="linux"){if(t.envDisplay&&t.usableDisplays.includes(t.envDisplay))return{mode:"attached",display:t.envDisplay,takeover:"remote-desktop",reason:`$DISPLAY ${t.envDisplay} is reachable`};if(t.usableDisplays.length>0){let n=t.usableDisplays[0];return{mode:"attached",display:n,takeover:"remote-desktop",reason:`graphical session ${n} belongs to this user and is reachable`}}return t.hasXvfb?{mode:"virtual",display:null,takeover:"vnc-required",reason:"no reachable session; a virtual display will be created (a VNC bridge is needed to watch it)"}:{mode:"headless",display:null,takeover:"none",reason:"no graphical session and no Xvfb \u2014 the agent can browse, but nobody can take over"}}return t.platform==="darwin"||t.platform==="win32"?t.interactiveSession?{mode:"attached",display:null,takeover:"remote-desktop",reason:"running inside an interactive desktop session"}:{mode:"headless",display:null,takeover:"none",reason:t.platform==="win32"?"service session (Session 0) cannot show a window \u2014 CDP still works, takeover cannot":"no Aqua session (daemon context) \u2014 CDP still works, takeover cannot"}:{mode:"headless",display:null,takeover:"none",reason:`unsupported platform ${t.platform}`}}async function no(){let t;try{t=await X.promises.readdir("/tmp/.X11-unix")}catch{return[]}let n=typeof process.getuid=="function"?process.getuid():-1;return(await Promise.all(t.filter(r=>/^X\d+$/.test(r)).map(async r=>{try{let a=await X.promises.stat(`/tmp/.X11-unix/${r}`);if(n>=0&&a.uid!==n)return null}catch{return null}let i=`:${r.slice(1)}`;return await oo(i)?i:null}))).filter(r=>r!==null).sort((r,i)=>Number(r.slice(1))-Number(i.slice(1)))}async function oo(t){let n=[["xdpyinfo",["-display",t]],["xset",["-display",t,"q"]]];for(let[o,r]of n){let i=await Wt(o,r,3e3);if(i!=="missing")return i===0}return Bt.warn("neither xdpyinfo nor xset is installed \u2014 trusting X socket ownership"),!0}function Wt(t,n,o){return new Promise(r=>{let i=Jn(t,n,{stdio:"ignore",timeout:o});i.once("error",a=>r(a.code==="ENOENT"?"missing":-1)),i.once("exit",a=>r(a??-1))})}async function _e(t){return await Wt("which",[t],2e3)===0}async function so(t,n=process.env){if(t==="darwin")try{let{stdout:o}=await eo("launchctl",["managername"],{encoding:"utf8",timeout:2e3});return o.trim()==="Aqua"}catch{return!1}if(t==="win32"){let o=n.SESSIONNAME;return!!o&&o.toLowerCase()!=="services"}return!1}function Gt(t,n="/tmp"){for(let o=t;o<t+100;o++)if(!(X.existsSync(Ce.join(n,`.X${o}-lock`))||X.existsSync(Ce.join(n,".X11-unix",`X${o}`))))return o;return null}async function Ht(t=process.env){let n=process.platform,o=t.CORTEX_BROWSER_DISPLAY,r=n==="linux"&&!o,[i,a,c]=await Promise.all([r?no():[],r?_e("Xvfb"):!1,o?!1:so(n,t)]),u=to({platform:n,override:o,envDisplay:t.DISPLAY,usableDisplays:i,hasXvfb:a,interactiveSession:c});return Bt.info(`display \u2192 ${u.mode}${u.display?` (${u.display})`:""}: ${u.reason}`),u}var R=$("managed-browser"),qt=Kt.join(et,"browser","profile"),ro=9222,io=600*1e3,Vt=3e4,Xt=1e4,ao=99,co=3,Pe="browser stopped while starting",lo=6e4,uo=3,h=null,te=null,z=null,E=0,v=null,ne=[],k="server";async function Ae(){E++,v&&(clearTimeout(v),v=null);try{return await en()}catch(t){throw E>0&&E--,t}}function Oe(){E!==0&&(E--,E===0&&po())}function Jt(){return{running:!!h,refs:E,browser:h?{cdpEndpoint:h.cdpEndpoint,port:h.port,display:h.display,pid:h.pid}:null}}function _r(){v&&(clearTimeout(v),v=null),E=0,z&&(z.cancelled=!0,be(z.procs,"SIGTERM")),Qt()}function po(){v&&clearTimeout(v),v=setTimeout(()=>{v=null,E===0&&(R.info("no browser sessions left \u2014 reclaiming Chrome"),Qt())},io),v.unref?.()}function Qt(){let t=h;h=null,t&&be([t.proc,...t.xvfb?[t.xvfb]:[]],"SIGTERM")}function be(t,n){for(let o of t)try{o.kill(n)}catch{}}async function en(){return h||te||(te=mo().finally(()=>{te=null}),te)}async function mo(){let t={cancelled:!1,procs:[]};z=t;try{return await fo(t)}catch(n){throw be(t.procs,"SIGKILL"),n}finally{z===t&&(z=null)}}async function fo(t){let n=()=>{if(t.cancelled)throw new Error(Pe)},o=await Io();if(!o)throw new Error("no Chrome/Chromium found \u2014 install Google Chrome, or set CORTEX_BROWSER_BINARY to its path");let r=await Ht();n(),oe.mkdirSync(qt,{recursive:!0});let i=await wo(ro);n();let a,c=r.display;if(r.mode==="virtual"){let g=await ho(t);a=g.proc,c=g.display}let u=[`--remote-debugging-port=${i}`,`--user-data-dir=${qt}`,"--no-first-run","--no-default-browser-check","--disable-features=Translate","--remote-debugging-address=127.0.0.1"];r.mode==="headless"&&u.push("--headless=new"),process.platform==="linux"&&u.push("--password-store=basic");let f={...process.env};c?f.DISPLAY=c:delete f.DISPLAY,R.info(`launching ${o} on port ${i} (${r.mode}${c?` ${c}`:""})`);let m=Zt(o,u,{env:f,stdio:"ignore",detached:!1});t.procs.push(m);let b=null;return m.on("exit",(g,N)=>go(m,g,N)),m.on("error",g=>{b=g.message,R.error(`Chrome failed to spawn: ${g.message}`)}),await xo(i,()=>t.cancelled?Pe:b?`Chrome failed to spawn: ${b}`:m.exitCode!==null||m.signalCode!==null?`Chrome exited during startup (code=${m.exitCode} signal=${m.signalCode})`:null),n(),h={cdpEndpoint:`http://127.0.0.1:${i}`,port:i,display:{...r,display:c},pid:m.pid??-1,proc:m,xvfb:a},R.info(`Chrome ready at ${h.cdpEndpoint} (pid ${h.pid})`),h}function go(t,n,o){if(!h||h.proc!==t||(R.warn(`Chrome exited (code=${n} signal=${o})`),h.xvfb?.kill("SIGTERM"),h=null,E===0))return;let r=Date.now();if(ne=ne.filter(i=>r-i<lo),ne.length>=uo){R.error("Chrome crashed repeatedly \u2014 giving up until the next acquire"),ne=[];return}ne.push(r),R.info(`${E} session(s) still need a browser \u2014 restarting`),en().catch(i=>R.error(`restart failed: ${String(i)}`))}async function ho(t){let n=ao,o="no free display number";for(let r=0;r<co;r++){let i=Gt(n);if(i===null)break;let a=`:${i}`,c=Zt("Xvfb",[a,"-screen","0","1920x1080x24","-nolisten","tcp","-displayfd","3"],{stdio:["ignore","ignore","ignore","pipe"]});t.procs.push(c);let u=await bo(c);if(t.cancelled)throw new Error(Pe);if(!u)return{proc:c,display:a};o=`${a}: ${u}`,R.warn(`Xvfb ${o}`),be([c],"SIGKILL"),n=i+1}throw new Error(`Xvfb could not start a virtual display (${o})`)}function bo(t){return new Promise(n=>{let o=!1,r="",i=u=>{o||(o=!0,clearTimeout(a),n(u))},a=setTimeout(()=>i(`not ready within ${Xt}ms`),Xt),c=t.stdio[3];c?.on("data",u=>{r+=String(u),r.includes(`
8
+ `)&&i(null)}),c?.on("error",()=>{}),t.once("exit",(u,f)=>i(`exited (code=${u} signal=${f})`)),t.once("error",u=>i(u.message))})}async function Io(t=process.env){if(t.CORTEX_BROWSER_BINARY)return oe.existsSync(t.CORTEX_BROWSER_BINARY)?t.CORTEX_BROWSER_BINARY:null;let n=process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:process.platform==="win32"?[`${t.ProgramFiles??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${t["ProgramFiles(x86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${t.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`]:[];for(let o of n)try{if(oe.existsSync(o))return o}catch{}for(let o of["google-chrome","google-chrome-stable","chromium","chromium-browser","chrome"])if(await _e(o))return o;return null}async function wo(t){if(await zt(t))return t;for(let n=t+1;n<t+20;n++)if(await zt(n))return n;throw new Error(`no free CDP port near ${t}`)}function zt(t){return new Promise(n=>{let o=Yt.createServer();o.once("error",()=>n(!1)),o.once("listening",()=>o.close(()=>n(!0))),o.listen(t,"127.0.0.1")})}async function xo(t,n){let o=Date.now()+Vt,r="";for(;Date.now()<o;){let i=n();if(i)throw new Error(i);try{let a=await fetch(`http://127.0.0.1:${t}/json/version`,{signal:AbortSignal.timeout(2e3)});if(a.ok)return;r=`HTTP ${a.status}`}catch(a){r=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,250))}throw new Error(`Chrome did not expose CDP on ${t} within ${Vt}ms (${r})`)}var tn=".cortex/browser/profile",Ie="DevToolsActivePort";function yo(t){return t==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:[]}var So=["google-chrome","google-chrome-stable","chromium","chromium-browser","chrome"],De="Cortex Managed Browser",vo=`
9
+ $ErrorActionPreference = "Stop"
10
+ $profile = Join-Path $env:USERPROFILE ".cortex\\browser\\profile"
11
+ $portFile = Join-Path $profile "${Ie}"
12
+ New-Item -ItemType Directory -Force -Path $profile | Out-Null
13
+ if ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0) {
14
+ Get-Content -LiteralPath $portFile -TotalCount 1
15
+ exit 0
16
+ }
17
+ $candidates = @(
18
+ (Join-Path $env:ProgramFiles "Google\\Chrome\\Application\\chrome.exe"),
19
+ (Join-Path ([Environment]::GetEnvironmentVariable("ProgramFiles(x86)")) "Google\\Chrome\\Application\\chrome.exe"),
20
+ (Join-Path $env:LOCALAPPDATA "Google\\Chrome\\Application\\chrome.exe")
21
+ )
22
+ $chrome = $candidates | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
23
+ if (-not $chrome) {
24
+ foreach ($name in @("google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome")) {
25
+ $found = Get-Command $name -ErrorAction SilentlyContinue
26
+ if ($found) { $chrome = $found.Source; break }
27
+ }
28
+ }
29
+ if (-not $chrome) { [Console]::Error.WriteLine("chrome-not-found"); exit 3 }
30
+ $user = (Get-CimInstance Win32_ComputerSystem).UserName
31
+ if (-not $user) { [Console]::Error.WriteLine("no-interactive-user"); exit 5 }
32
+ $current = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
33
+ if ($user -ine $current) { [Console]::Error.WriteLine("interactive-user-mismatch"); exit 6 }
34
+ $quote = [char]34
35
+ $arguments = "--remote-debugging-port=0 --remote-debugging-address=127.0.0.1 --user-data-dir=$quote$profile$quote --no-first-run --no-default-browser-check about:blank"
36
+ $action = New-ScheduledTaskAction -Execute $chrome -Argument $arguments
37
+ $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
38
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew
39
+ Register-ScheduledTask -TaskName "${De}" -Action $action -Principal $principal -Settings $settings -Force | Out-Null
40
+ Start-ScheduledTask -TaskName "${De}"
41
+ for ($i = 0; $i -lt 60; $i++) {
42
+ if ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0) { break }
43
+ Start-Sleep -Milliseconds 500
44
+ }
45
+ if (-not ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0)) {
46
+ [Console]::Error.WriteLine("chrome-did-not-listen")
47
+ exit 4
48
+ }
49
+ Get-Content -LiteralPath $portFile -TotalCount 1
50
+ `.trim();function Eo(t){let n=yo(t).map(o=>` [ -f "${o}" ] && { CHROME="${o}"; }`).join(`
51
+ `);return[`PROFILE="$HOME/${tn}"`,`PORTFILE="$PROFILE/${Ie}"`,'mkdir -p "$PROFILE"','if [ -s "$PORTFILE" ]; then head -1 "$PORTFILE"; exit 0; fi','CHROME=""',...n?[`if [ -z "$CHROME" ]; then :
52
+ ${n}
53
+ fi`]:[],`for b in ${So.join(" ")}; do`,' [ -n "$CHROME" ] && break',' p=$(command -v "$b" 2>/dev/null) && CHROME="$p"',"done",'[ -n "$CHROME" ] || { echo "chrome-not-found" >&2; exit 3; }','nohup "$CHROME" --remote-debugging-port=0 --remote-debugging-address=127.0.0.1 --user-data-dir="$PROFILE" --no-first-run --no-default-browser-check --password-store=basic about:blank >/dev/null 2>&1 &','for _ in $(seq 1 60); do [ -s "$PORTFILE" ] && break; sleep 0.5; done','[ -s "$PORTFILE" ] || { echo "chrome-did-not-listen" >&2; exit 4; }','head -1 "$PORTFILE"'].join(`
54
+ `)}function nn(t){return t==="win32"?`powershell.exe -NoProfile -Command '${vo}' </dev/null`:Eo(t)}function Le(t){let n=`"$HOME/${tn}"`;return t==="win32"?[`powershell.exe -NoProfile -Command '${['$ErrorActionPreference = "SilentlyContinue"',`Stop-ScheduledTask -TaskName "${De}" -ErrorAction SilentlyContinue`,"Get-CimInstance Win32_Process | Where-Object {",' $_.Name -eq "chrome.exe" -and $_.CommandLine -like "*.cortex*browser*profile*"',"} | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"].join(`
55
+ `)}' </dev/null >/dev/null 2>&1 || true`,`rm -f ${n}/${Ie}`].join(`
56
+ `):[`pkill -f -- ${n} >/dev/null 2>&1 || true`,`rm -f ${n}/${Ie}`].join(`
57
+ `)}var se=$("device-browser"),$o=9e4,ko=5e3,To=10*6e4,L=new Map;async function Me(t,n,o){let r=await xt(t,{action:"bash",params:{command:n},timeout:o});if(r?.exitCode!==void 0&&r.exitCode!==0){let i=String(r.stderr??"").trim()||`exit ${r.exitCode}`;throw new Error(i)}return typeof r?.stdout=="string"?r.stdout:""}function Ro(t){let n=t.split(`
58
+ `).map(r=>r.trim()).filter(r=>/^\d+$/.test(r));if(n.length===0)return null;let o=Number(n[n.length-1]);return o>0&&o<=65535?o:null}function sn(t){return pe().find(n=>n.device===t)?.platform??""}async function Fe(t){try{return(await fetch(`${t}/json/version`,{signal:AbortSignal.timeout(ko)})).ok}catch{return!1}}async function on(t,n){let o=await Me(t,nn(n),$o),r=Ro(o);if(r===null)throw new Error(`device ${t} reported no debugging port`);let i=await Ut(t,r);return{device:t,remotePort:r,cdpEndpoint:`http://127.0.0.1:${i.localPort}`,refs:0,idleTimer:null}}async function Ne(t){let n=sn(t),o=L.get(t);if(o){if(o.idleTimer&&(clearTimeout(o.idleTimer),o.idleTimer=null),await Fe(o.cdpEndpoint))return o.refs++,{device:t,remotePort:o.remotePort,cdpEndpoint:o.cdpEndpoint};se.info(`${t}: mapped browser no longer answers \u2014 relaunching`),V(t,o.remotePort),L.delete(t)}let r=await on(t,n);if(!await Fe(r.cdpEndpoint)&&(se.info(`${t}: adopted debugging port ${r.remotePort} is dead \u2014 stopping and relaunching`),V(t,r.remotePort),await Me(t,Le(n),3e4),r=await on(t,n),!await Fe(r.cdpEndpoint)))throw V(t,r.remotePort),new Error(`device ${t} launched Chrome but its debugging port is unreachable`);return r.refs=1,L.set(t,r),se.info(`${t}: browser on device port ${r.remotePort} \u2192 ${r.cdpEndpoint}`),{device:t,remotePort:r.remotePort,cdpEndpoint:r.cdpEndpoint}}function jo(t){t.idleTimer=setTimeout(()=>{t.refs>0||(se.info(`${t.device}: no browser sessions left \u2014 reclaiming Chrome`),Co(t.device).catch(n=>se.warn(`${t.device}: could not stop Chrome: ${n.message}`)))},To),t.idleTimer.unref?.()}function rn(t){let n=L.get(t);n&&(n.refs=Math.max(0,n.refs-1),n.refs===0&&!n.idleTimer&&jo(n))}async function Co(t){let n=L.get(t);n?.idleTimer&&clearTimeout(n.idleTimer),L.delete(t),n&&V(t,n.remotePort),await Me(t,Le(sn(t)),3e4)}function Mr(){for(let t of L.values())t.idleTimer&&clearTimeout(t.idleTimer);L.clear()}var F=$("browser-broker"),_o=10*6e4,Po=15e3,Ao=5e3,y=class extends Error{code;hint;constructor(n,o,r){super(o),this.name="BrowserLeaseError",this.code=n,this.hint=r}};function we(t){return typeof t=="string"?t.trim():""}function Oo(t,n){let o=n.trim(),r="or run without --device to use the server's browser";return o.includes("chrome-not-found")?{message:`Chrome is not installed on ${t}`,hint:`install Google Chrome on ${t}, ${r}`}:o.includes("no-interactive-user")?{message:`nobody is logged in to the desktop on ${t}`,hint:`log in on ${t}, ${r}`}:o.includes("interactive-user-mismatch")?{message:`the Cortex client on ${t} runs as a different user than the desktop session`,hint:`run the Cortex client as the logged-in user on ${t}`}:o.includes("chrome-did-not-listen")?{message:`Chrome on ${t} did not open its debugging port in time`,hint:`close any Chrome window still using the Cortex profile on ${t} and retry`}:/timed out/i.test(o)?{message:`${t} did not answer while starting Chrome (${o})`,hint:`check that ${t} is awake and its Cortex client is connected`}:{message:`could not start Chrome on ${t}: ${o||"unknown error"}`}}function Do(t){let n=new Map,o=new Map,r=new Map,i=new Map,a=new Set,c=null;function u(){for(let s of a)try{s()}catch(l){F.warn(`listener failed: ${l.message}`)}}function f(s,l,p){let I=(s.get(l)??Promise.resolve()).catch(()=>{}).then(p),w=I.catch(()=>{});return s.set(l,w),w.then(()=>{s.get(l)===w&&s.delete(l)}),I}function m(){if(c)return c;try{c={bin:t.resolveBin(),env:t.baseEnv()}}catch(s){throw s instanceof lt?new y("engine-missing",s.message,s.hint):s}return c}function b(s){s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{if(s.idleTimer=null,s.takenOver){b(s);return}n.get(s.sessionId)===s&&(F.info(`${s.sessionId}: browser idle for ${Math.round(t.idleMs/6e4)} min \u2014 releasing`),f(o,s.sessionId,async()=>{n.get(s.sessionId)===s&&!s.takenOver&&await N(s)}))},t.idleMs),s.idleTimer.unref?.()}function g(s){s.lastUsedAt=t.now(),b(s)}async function N(s){if(s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=null,n.get(s.sessionId)===s&&n.delete(s.sessionId),i.delete(s),s.holdsRef&&(s.holdsRef=!1,t.release(s.device)),u(),!(!s.cdpEndpoint||!c))for(let l of[["tab","close"],["close"]])await t.run(c.bin,W(s.cdpEndpoint,s.abSession,l),c.env).catch(()=>{})}function K(s,l){return s.holdsRef&&(s.holdsRef=!1,t.release(s.device)),i.delete(s),s.state="error",s.error=l.hint?`${l.message} \u2014 ${l.hint}`:l.message,s.cdpEndpoint=null,u(),l}function C(s){if(s===k)return;let{state:l,online:p}=t.availability(s);if(l==="online")return;let d=p.length?`online devices: ${["server",...p].join(", ")}`:"no devices are online";throw l==="offline"?new y("device-offline",`device "${s}" is offline`,`start its Cortex client, or pick another device (${d})`):new y("unknown-device",`unknown device "${s}"`,`use one of: server${p.length?`, ${p.join(", ")}`:""}`)}function ze(s,l){if(l instanceof y)return l;let p=l?.message??String(l);if(s===k)return new y("chrome-failed",`could not start Chrome on the server: ${p}`);let{message:d,hint:I}=Oo(s,p);return new y("chrome-failed",d,I)}function yn(s){return s===k?t.acquire(s):f(r,s,()=>t.acquire(s))}async function Sn(s){try{C(s.device),m(),s.cdpEndpoint=await yn(s.device),s.holdsRef=!0,await Ze(s),s.state="ready",s.error=void 0,i.set(s,t.now()),F.info(`${s.sessionId}: browser ready on ${s.device} (${s.abSession})`)}catch(l){throw K(s,ze(s.device,l))}u()}async function vn(s){if(!(!(s.device===k||t.now()-(i.get(s)??0)>=Po)||!s.cdpEndpoint))try{C(s.device);let p=await(s.device===k?t.refresh(s.device,s.cdpEndpoint):f(r,s.device,()=>t.refresh(s.device,s.cdpEndpoint)));i.set(s,t.now()),p!==s.cdpEndpoint&&(F.info(`${s.sessionId}: ${s.device} browser moved to ${p}`),s.cdpEndpoint=p,u())}catch(p){throw K(s,ze(s.device,p))}}function Ye(s,l,p){return f(o,s,async()=>{let d=n.get(s);if(p&&d?.takenOver)throw new y("taken-over","the user is controlling this browser right now","wait for them to hand it back, or ask them; do not retry in a loop");let I=l||d?.device||k;if(d&&(d.device!==I||d.state==="error")){let $n=d.takenOver;await N(d),d=void 0,$n&&F.info(`${s}: switching device ends the takeover`)}if(d?.state==="ready")return await vn(d),g(d),d;let w={sessionId:s,device:I,abSession:pt(s,I),state:"starting",cdpEndpoint:null,holdsRef:!1,takenOver:!1,lastUsedAt:t.now(),idleTimer:null,refreshing:!1,refreshAgain:!1};return n.set(s,w),g(w),u(),await Sn(w),w})}function Ke(s){let l=n.get(s);if(!l)throw new y("no-lease",`session ${s} has no browser`);return l}function En(s){let l=Ke(s);if(l.state!=="ready"||!l.cdpEndpoint)throw new y("no-lease",`the browser for session ${s} is ${l.state}`);return l}async function ae(s,l){let p=m(),d=()=>t.run(p.bin,W(s.cdpEndpoint,s.abSession,l),p.env),I=await d();return I.code===0||!mt(I.stderr)||(F.info(`${s.sessionId}: bound tab is gone \u2014 opening a new one`),(await t.run(p.bin,W(s.cdpEndpoint,s.abSession,["tab","new"]),p.env)).code!==0)?I:(await Ze(s),d())}async function Ze(s){let l=m(),p=await t.run(l.bin,W(s.cdpEndpoint,s.abSession,dt),l.env).catch(d=>({code:-1,stdout:"",stderr:String(d)}));p.code!==0&&F.warn(`${s.sessionId}: could not set the viewport: ${p.stderr.trim().slice(0,200)}`)}async function Je(s){if(s.refreshing){s.refreshAgain=!0;return}s.refreshing=!0;try{do{if(s.refreshAgain=!1,n.get(s.sessionId)!==s||s.state!=="ready"||!c)return;let l=async I=>{let w=await t.run(c.bin,W(s.cdpEndpoint,s.abSession,["--json","get",I]),c.env);if(w.code===0)try{return we(JSON.parse(w.stdout)?.data?.[I])||void 0}catch{return}},[p,d]=[await l("url"),await l("title")];(p!==s.url||d!==s.title)&&(s.url=p,s.title=d,u())}while(s.refreshAgain)}finally{s.refreshing=!1}}function Qe(s){try{return JSON.parse(s)}catch{return null}}return{async leaseBrowser({sessionId:s,device:l}){let p=we(s);if(!p)throw new y("bad-request","no session id","cortex-browser must run inside a Cortex session (CORTEX_SESSION_ID is unset)");let d=await Ye(p,we(l)||null,!0);return{device:d.device,cdpEndpoint:d.cdpEndpoint,abSession:d.abSession}},listBrowserSessions(){return[...n.values()].sort((s,l)=>l.lastUsedAt-s.lastUsedAt).map(s=>({sessionId:s.sessionId,device:s.device,abSession:s.abSession,state:s.state,...s.error?{error:s.error}:{},...s.url?{url:s.url}:{},...s.title?{title:s.title}:{},takenOver:s.takenOver,lastUsedAt:s.lastUsedAt}))},async runAgentBrowser(s,l){let p=await Ye(s,null,!1),d=await ae(p,l);return Je(p),d},async streamPort(s){let l=n.get(s);if(!l||l.state!=="ready")return null;let p=Qe((await ae(l,["--json","stream","status"])).stdout);if(p?.data?.enabled&&typeof p.data.port=="number")return p.data.port;let d=Qe((await ae(l,["--json","stream","enable"])).stdout);return typeof d?.data?.port=="number"?d.data.port:null},setTakeover(s,l){let p=Ke(s);p.takenOver!==l&&(p.takenOver=l,g(p),F.info(`${s}: browser ${l?"taken over by the user":"handed back to the agent"}`),u())},isTakenOver(s){return n.get(s)?.takenOver??!1},async insertText(s,l){let p=En(s),d=await ae(p,["keyboard","inserttext",l]);if(d.code!==0)throw new Error(d.stderr.trim()||`agent-browser exited ${d.code}`)},noteBrowserCommand(s){let l=n.get(we(s));l&&(g(l),Je(l))},agentBrowserRuntime(){return m()},onBrowserSessionsChanged(s){return a.add(s),()=>{a.delete(s)}},shutdown(){for(let s of n.values())s.idleTimer&&clearTimeout(s.idleTimer);n.clear(),a.clear()}}}async function Lo(t){try{return(await fetch(`${t}/json/version`,{signal:AbortSignal.timeout(Ao)})).ok}catch{return!1}}function Fo(){return{async acquire(t){return t===k?(await Ae()).cdpEndpoint:(await Ne(t)).cdpEndpoint},release(t){t===k?Oe():rn(t)},async refresh(t,n){if(t===k){let o=Jt().browser?.cdpEndpoint;if(o)return o;let r=(await Ae()).cdpEndpoint;return Oe(),r}return await Lo(n)?n:(await Ne(t)).cdpEndpoint},availability(t){let n=pe().map(o=>o.device).sort();return It(t)?{state:"online",online:n}:{state:Object.hasOwn(ht(),t)?"offline":"unknown",online:n}},resolveBin:()=>ut(),baseEnv:()=>ft(),run:(t,n,o)=>gt(t,n,{env:o}),now:()=>Date.now(),idleMs:_o}}var Ue=null;function M(){return Ue??=Do(Fo()),Ue}var Vr=t=>M().leaseBrowser(t),Xr=()=>M().listBrowserSessions();var zr=t=>M().streamPort(t),Yr=(t,n)=>M().setTakeover(t,n),Kr=t=>M().isTakenOver(t),Zr=(t,n)=>M().insertText(t,n),Jr=t=>M().noteBrowserCommand(t),Qr=()=>M().agentBrowserRuntime();function ei(){Ue?.shutdown()}import*as S from"node:fs";import*as T from"node:path";var Mo=["mission.md","roadmap.md","STATUS.md"],No=["experiments","knowledge","patterns","decisions"];function Be(t){return Object.assign(new Error(t),{code:"not-found"})}function xe(t){return Object.assign(new Error(t),{code:"invalid-args"})}function cn(t,n){let o=t.projectStore.get(n);if(!o)throw Be(`project not found: ${n}`);try{return S.realpathSync(o.contextDir)}catch{throw Be(`project directory not found: ${n}`)}}function an(t,n){return n===t||n.startsWith(t+T.sep)}function Uo(t,n){if(T.isAbsolute(n))throw xe(`absolute path not allowed: ${n}`);let o=T.resolve(t,n);if(!an(t,o))throw xe(`path escapes project root: ${n}`);let r;try{r=S.realpathSync(o)}catch{throw Be(`file not found: ${n}`)}if(!an(t,r))throw xe(`path escapes project root: ${n}`);if(!S.statSync(r).isFile())throw xe(`not a file: ${n}`);return r}async function si(t,n){let o=cn(t,n.projectId),r=Mo.flatMap(a=>{let c=T.join(o,a),u;try{u=S.statSync(c)}catch{return[]}return u.isFile()?[{name:a,sizeBytes:u.size,modifiedAt:u.mtime.toISOString()}]:[]}),i=No.flatMap(a=>{let c=T.join(o,a),u;try{u=S.readdirSync(c,{withFileTypes:!0})}catch{return[]}let f=u.filter(m=>m.isFile()&&m.name.endsWith(".md")&&m.name!=="index.md"&&m.name!=="AGENTS.md").map(m=>{let b=S.statSync(T.join(c,m.name));return{name:m.name,sizeBytes:b.size,modifiedAt:b.mtime.toISOString()}}).sort((m,b)=>m.name.localeCompare(b.name));return[{name:a,entryCount:f.length,entries:f}]});return{projectId:n.projectId,files:r,dirs:i}}async function Bo(t,n){let o=await H("git",["diff","--numstat","HEAD","--",n],{cwd:t,timeoutMs:5e3,maxBuffer:1048576,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});if(!o.ok)return null;let i=o.stdout.split(`
59
+ `).find(m=>m.trim().length>0);if(!i)return{added:0,removed:0};let[a,c]=i.split(" "),u=Number(a),f=Number(c);return!Number.isFinite(u)||!Number.isFinite(f)?null:{added:u,removed:f}}var Wo=/\b(?:task|manager|gate)\s+([0-9a-f]{4})\b/i;function Go(t){let n=Wo.exec(t);return n?n[1].toLowerCase():null}function Ho(t){let n=[],o=new Map,r=null,i=0;for(let a of t.split(`
60
+ `)){if(a.startsWith(" ")){r&&n.push({line:i,commit:r.slice(0,8),taskRef:o.get(r)??null}),r=null;continue}let c=/^([0-9a-f]{40}) \d+ (\d+)(?: \d+)?$/.exec(a);if(c){r=c[1],i=Number(c[2]);continue}r&&a.startsWith("summary ")&&o.set(r,Go(a.slice(8)))}return n}async function qo(t,n){let o=await H("git",["blame","--line-porcelain","HEAD","--",n],{cwd:t,timeoutMs:5e3,maxBuffer:8388608,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return o.ok?Ho(o.stdout):null}async function ri(t,n){let o=cn(t,n.projectId),r=Uo(o,n.path),i=S.statSync(r),a=S.readFileSync(r,"utf8"),[c,u]=yt()?await Promise.all([Bo(o,n.path),qo(o,n.path)]):[null,null];return{projectId:n.projectId,path:n.path,content:a,sizeBytes:i.size,modifiedAt:i.mtime.toISOString(),lineDiff:c,blame:u}}var ln={feishu:["FEISHU_APP_ID","FEISHU_APP_SECRET","FEISHU_DOMAIN","FEISHU_ENCRYPT_KEY","FEISHU_VERIFICATION_TOKEN"],slack:["SLACK_BOT_TOKEN","SLACK_SIGNING_SECRET","SLACK_APP_TOKEN"]},ci={feishu:["FEISHU_APP_ID","FEISHU_APP_SECRET"],slack:ln.slack},li=["FEISHU_APP_ID","FEISHU_DOMAIN"],B=e.string().min(1).max(4096).regex(/^[^\s'\\\u0000-\u001f\u007f]+$/,"Invalid credential characters"),Vo=e.object({FEISHU_APP_ID:B.nullable().optional(),FEISHU_APP_SECRET:B.nullable().optional(),FEISHU_DOMAIN:e.enum(["feishu","lark"]).nullable().optional(),FEISHU_ENCRYPT_KEY:B.nullable().optional(),FEISHU_VERIFICATION_TOKEN:B.nullable().optional(),SLACK_BOT_TOKEN:B.nullable().optional(),SLACK_SIGNING_SECRET:B.nullable().optional(),SLACK_APP_TOKEN:B.nullable().optional()}).strict(),un=e.object({platform:e.enum(["feishu","slack"]),enabled:e.boolean().optional(),fields:Vo}).strict().refine(t=>Object.keys(t.fields).every(n=>ln[t.platform].includes(n)),"Fields must belong to the selected platform");var We=["openai-codex","anthropic"];function pi(t){return We.includes(t)}var pn=e.object({sessionId:e.string().min(1),starred:e.boolean()}),dn=e.object({sessionId:e.string().min(1),label:e.string().trim().min(1).max(60)});var Xo=e.object({projectId:e.string().optional(),resumable:e.boolean().optional(),origin:e.enum(["direct","thread","scheduled"]).optional(),boardId:e.string().max(128).optional()}),zo=e.object({perProject:e.number().int().min(1).max(200).optional(),fullProjects:e.array(e.string().max(128)).max(200).optional(),include:e.array(e.string().max(128)).max(50).optional(),depth:e.record(e.string().max(128),e.number().int().min(1).max(1e4)).optional(),projectId:e.string().max(128).optional()}),Yo=e.object({sessionId:e.string().min(1).max(128)}),Ko=e.object({query:e.string().trim().min(1).max(200),origin:e.enum(["direct","thread","scheduled"]).optional(),limit:e.number().int().min(1).max(200).optional()}),Zo=e.object({sessionId:e.string(),compactSubagents:e.boolean().optional(),since:e.string().max(64).optional(),tailRows:e.number().int().positive().optional(),beforeRow:e.number().int().nonnegative().optional(),pageRows:e.number().int().positive().optional()}),Jo=e.object({sessionId:e.string(),subagentId:e.string().min(1).max(512)}),Qo=e.object({sessionId:e.string(),ref:e.string().min(1).max(512)}),es=e.object({sessionId:e.string().min(1)}),ts=e.object({sessionId:e.string().min(1)}),ns=e.object({projectId:e.string().optional(),paused:e.boolean().optional()}),os=e.object({projectId:e.string().optional()}),ss=e.object({boardId:e.string()}),rs=e.object({boardId:e.string()}),is=e.object({}),as=e.object({sessionId:e.string().min(1)}),cs=e.object({sessionId:e.string().min(1)}),ls=e.object({status:e.array(e.string()).optional(),limit:e.number().optional()}),us=e.object({executionId:e.string()}),ps=e.object({projectId:e.string()}),ds=e.object({projectId:e.string(),path:e.string()}),ms=e.object({status:e.enum(["pending","approved","rejected","failed"]).optional()}),fs=e.object({projectId:e.string()}),gs=e.object({projectId:e.string()});var ki=e.object({}),Ti=e.object({projectId:e.string().nullish()}),hs=e.enum(["24h","7d","30d","90d"]),bs=e.object({range:hs,page:e.number().int().min(0).max(400).optional(),projectId:e.string().nullish()}),Ri=bs.extend({kind:e.enum(["tool","skill","mcp"]).optional()}),ji=e.object({provider:e.string().nullish(),route:e.string().nullish()}),Ci=e.object({}),_i=e.object({}),Pi=e.object({flowId:e.string().min(1)}),Ai=e.object({}),Oi=e.object({enabled:e.boolean(),name:e.string().trim().optional(),org:e.string().trim().optional(),email:e.string().trim().optional()}),Di=e.object({}),Li=st,Ge=e.number().nonnegative().max(6e5),Fi=e.object({sessionId:e.string().min(1).max(128),totalMs:Ge,transcriptMs:Ge.optional(),cached:e.boolean(),rows:e.number().int().nonnegative().max(1e6),longTaskMs:Ge.optional()}),Mi=e.object({}),Ni=e.object({}),Is=50,qe=e.string().min(1).optional(),Ui=e.object({device:qe,path:e.string().min(1),showHidden:e.boolean().optional()}),Bi=e.object({}),Wi=e.object({device:qe,path:e.string().min(1),kind:e.enum(["dir","file"])}),ws=e.object({device:qe,path:e.string().min(1),write:e.boolean()}),bn=e.array(ws).max(Is),Gi=e.object({machine:e.string().min(1)}),Hi=e.object({}),qi=e.object({sessionId:e.string().min(1).optional(),agentName:e.string().min(1).nullable().optional()}),Vi=e.object({}),Xi=e.object({}),zi=e.object({}),Yi=e.object({}),Ki=e.object({}),Zi=e.object({}),Ji=e.object({limit:e.number().int().positive().max(50).optional()}),Qi=e.object({}),ea=e.object({}),ta=e.object({}),Ve=e.string().min(1).regex(ce).nullable().optional(),na=e.object({backend:e.enum(["claude","pi"]),provider:e.string().min(1),connection:Ve,authType:e.enum(["api_key","oauth"]),noticeId:e.string().min(1).optional()}),oa=e.object({backend:e.enum(["claude","pi"]),label:e.string().trim().min(1).max(64),provider:e.string().min(1).optional(),authType:e.enum(["api_key","oauth"]).optional()}),sa=e.object({backend:e.enum(["claude","pi"]),id:e.string().min(1).regex(ce)}),ra=e.object({flowId:e.string().min(1),value:e.string(),promptId:e.number().int().nonnegative().optional()}),ia=e.object({flowId:e.string().min(1)}),aa=e.object({backend:e.enum(["claude","pi"]).optional()}),ca=e.object({backend:e.enum(["claude","pi"]),provider:e.string().min(1),connection:Ve,authType:e.enum(["api_key","oauth"])}),ye=e.string().min(1).regex(ce),mn=e.array(e.string().min(1)),la=e.object({}),ua=e.discriminatedUnion("kind",[e.object({kind:e.literal("claude"),id:ye,label:e.string().optional(),baseUrl:e.string().optional(),authStyle:e.enum(["x-api-key","bearer"]).optional(),billing:e.enum(["metered","subscription"]).optional(),models:mn.optional(),key:e.string().optional(),create:e.boolean().optional()}),e.object({kind:e.literal("pi-override"),provider:ye,baseUrl:e.string(),key:e.string().optional(),create:e.boolean().optional()}),e.object({kind:e.literal("pi-custom"),provider:ye,api:e.enum(rt),baseUrl:e.string(),models:mn.min(1),key:e.string().optional(),create:e.boolean().optional()})]),pa=e.object({backend:e.enum(["claude","pi"]),id:ye}),da=e.object({name:e.string()}),ma=e.object({projectId:e.string().min(1)}),fa=e.object({sessionId:e.string().min(1)}),ga=e.object({projectId:e.string().optional()}),ha=e.object({sessionId:e.string(),text:e.string(),attachments:e.array(e.object({name:e.string(),path:e.string(),size:e.number(),mimeType:e.string(),type:e.enum(["image","video","file","view"])})).optional()}),ba=e.object({sessionId:e.string()}),Ia=e.object({sessionId:e.string(),pendingId:e.string(),action:e.enum(["send","edit"])}),wa=e.object({sessionId:e.string()}),xa=e.object({sessionId:e.string()}),ya=e.object({sessionIds:e.array(e.string()).min(1).max(500)}),Sa=e.object({sessionId:e.string(),agentName:e.string().min(1).nullable().optional()}),In=e.object({backend:e.enum(["claude","pi"]),provider:e.string().min(1).nullable(),model:e.string().min(1),thinking:e.string().min(1).nullable(),connection:e.string().min(1).nullable()}).strict(),re=In,va=e.object({sessionId:e.string(),selection:re}).strict(),Ea=e.object({requestId:e.string().min(1),answers:e.record(e.string(),e.string()),sessionId:e.string().min(1).optional()}),$a=e.object({requestId:e.string().min(1),approved:e.boolean(),feedback:e.string().optional()}),ka=e.object({sessionId:e.string().min(1),decisionId:e.string().min(1),action:e.enum(["approve","explain","revise"]),message:e.string().optional()}),Ta=e.object({sessionId:e.string().regex(/^[\w-]+$/),ts:e.string().min(1),src:e.string().min(1)}),Ra=e.object({sessionId:e.string().min(1),allowedPaths:bn}),ja=e.object({sessionId:e.string()}),Ca=e.object({sessionId:e.string(),turnIndex:e.number().int().min(0),text:e.string().min(1)}),_a=e.object({projectId:e.string(),agentName:e.string().min(1).optional(),selection:re.optional(),clean:e.boolean().optional(),allowedPaths:bn.optional(),text:e.string(),draftUploadId:e.string().uuid().optional(),attachments:e.array(e.object({name:e.string(),path:e.string(),size:e.number(),mimeType:e.string(),type:e.enum(["image","video","file"])})).optional()}),Pa=e.object({waitpointId:e.string().min(1)}),Aa=e.object({monitorId:e.string().min(1)}),Oa=e.object({executionId:e.string()}),Da=e.object({scheduleId:e.string()}),La=e.object({type:e.enum(["interval","daily","weekly","once"]),message:e.string().min(1),projectId:e.string().optional(),selection:re.optional(),intervalMs:e.number().int().positive().optional(),time:e.string().regex(/^\d{2}:\d{2}$/).optional(),dayOfWeek:e.number().int().min(0).max(6).optional(),delay:e.number().int().positive().optional()}).superRefine((t,n)=>{t.type==="interval"&&t.intervalMs===void 0&&n.addIssue({code:e.ZodIssueCode.custom,path:["intervalMs"],message:_("ui.schedule.intervalRequired")}),(t.type==="daily"||t.type==="weekly")&&t.time===void 0&&n.addIssue({code:e.ZodIssueCode.custom,path:["time"],message:_("ui.schedule.timeRequired",{type:t.type})}),t.type==="weekly"&&t.dayOfWeek===void 0&&n.addIssue({code:e.ZodIssueCode.custom,path:["dayOfWeek"],message:_("ui.schedule.dayOfWeekRequired")}),t.type==="once"&&t.delay===void 0&&n.addIssue({code:e.ZodIssueCode.custom,path:["delay"],message:_("ui.schedule.delayRequired")})}),Fa=e.object({scheduleId:e.string(),message:e.string().min(1).optional(),projectId:e.string().optional(),selection:re.optional(),intervalMs:e.number().int().positive().optional(),time:e.string().regex(/^\d{2}:\d{2}$/).optional(),dayOfWeek:e.number().int().min(0).max(6).optional()}),fn=new Set(["__proto__","prototype","constructor"]),He=120,xs={boolean:e.boolean(),number:e.number().finite(),"number|null":e.number().finite().nullable(),"string[]":e.array(e.string()),"string|null":e.string().nullable()};function ys(t){let n=xs[t.type];return!("validate"in t)||typeof t.validate!="function"?n:n.superRefine((o,r)=>{let i=t.validate(o);i&&r.addIssue({code:e.ZodIssueCode.custom,message:i})})}var Ss=Object.fromEntries(Object.entries(ot).filter(([t])=>t!=="providerRateLimits").map(([t,n])=>[t,ys(n)]));function vs(t,n){for(let[o,r]of Object.entries(t))r===void 0&&n.addIssue({code:e.ZodIssueCode.custom,path:[o],message:"setting must not be undefined"})}var Es=e.object(Ss).partial().strict().superRefine(vs),Ma=e.discriminatedUnion("section",[e.object({section:e.literal("budget"),project:e.string().min(1).nullish(),value:e.object({daily_usd:e.number().finite().positive(),monthly_usd:e.number().finite().positive()}).nullish()}).superRefine((t,n)=>{t.value==null&&!t.project&&n.addIssue({code:e.ZodIssueCode.custom,path:["value"],message:"a budget write without a value clears a per-project override and requires `project`"})}),e.object({section:e.literal("settings"),value:Es}),e.object({section:e.literal("preferences"),value:e.object({lang:e.enum(["en","zh"])})})]),Na=e.object({provider:e.string().trim().min(1).max(He).refine(t=>!fn.has(t),"provider key is reserved"),windowType:e.string().trim().min(1).nullish(),windowLabel:e.string().trim().min(1).nullish(),account:e.string().trim().min(1).max(He).refine(t=>!fn.has(t),"account key is reserved").nullish(),enabled:e.boolean(),threshold:e.union([e.number().finite().gt(0).lte(1),e.null()]).optional(),stopThreshold:e.union([e.number().finite().gt(0).lte(1),e.null()]).optional()}).superRefine((t,n)=>{t.stopThreshold!==void 0&&!nt.has(t.windowType??"")&&n.addIssue({code:e.ZodIssueCode.custom,path:["stopThreshold"],message:"stopThreshold applies only to five_hour and codex_primary windows"}),t.windowLabel&&!t.windowType&&n.addIssue({code:e.ZodIssueCode.custom,path:["windowType"],message:"windowType is required when windowLabel is set"}),t.account&&!t.windowType&&n.addIssue({code:e.ZodIssueCode.custom,path:["windowType"],message:"windowType is required when account is set"})}),Ua=e.object({}),$s=e.union([e.string(),e.number(),e.boolean(),e.null()]),wn={event:e.string().min(1),matcher:e.string().optional(),matcherFilters:e.record(e.string(),$s).optional(),script:e.string().min(1).optional(),command:e.string().min(1).optional(),timeoutSec:e.number().finite().positive().optional(),backends:e.array(e.enum(["claude","pi"])).optional(),requiresTool:e.string().min(1).optional(),result:e.enum(["stdout-as-prompt","none"]).optional(),enabled:e.boolean().optional()};function xn(t,n){let o=t.script!==void 0,r=t.command!==void 0;o===r&&n.addIssue({code:e.ZodIssueCode.custom,path:["script"],message:_("ui.hook.exactlyOneRun")})}var Ba=e.object({id:e.string().min(1),...wn}).superRefine(xn),Wa=e.object({id:e.string().min(1),...wn}).superRefine(xn),Ga=e.object({id:e.string().min(1),enabled:e.boolean()}),Ha=e.object({id:e.string().min(1)}),qa=e.object({id:e.string().min(1),payload:e.string()}),ks=In.pick({backend:!0,provider:!0,model:!0}),Va=e.object({backend:e.enum(["claude","pi"]),provider:e.string().min(1).nullable().optional(),model:e.string().min(1)}).strict(),Xa=e.object({ref:ks,thinking:e.string().nullable()}).strict(),za=e.object({selection:re}).strict(),gn=e.array(e.string().trim().min(1).max(200)).max(200),Ya=e.object({allow:e.union([e.literal("all"),e.literal("favorites"),gn]),deny:gn}).strict(),Ts=t=>new TextEncoder().encode(t).byteLength<=255,Rs=t=>t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0"),js=e.string().max(240).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),Cs=e.string().min(1).refine(Ts).refine(Rs),Xe=e.string().regex(/^[a-f0-9]{64}$/),_s=e.object({kind:e.literal("agent"),name:js,baseHash:Xe}),Ka=e.object({target:_s,pluginIds:e.array(Cs),acknowledgeMcp:e.boolean().optional()}),j=e.string().min(1).max(64).regex(/^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/),Y={pluginId:j,skill:j},Za=e.object(Y),Ja=e.object({...Y,content:e.string().max(512*1024),baseHash:Xe}),Qa=e.object({...Y,description:e.string().min(1).max(1024)}),ec=e.object({...Y,toPluginId:j,toSkill:j}),tc=e.object(Y),nc=e.object(Y),oc=e.object({id:j,description:e.string().max(1024).optional()}),sc=e.object({id:j}),rc=e.object({id:j}),ic=e.object({pluginId:j}),hn=e.record(e.string().min(1).max(200),e.string().max(4096).nullable()),ac=e.object({pluginId:j,servers:e.array(e.object({name:e.string().min(1).max(64).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),type:e.enum(["stdio","streamable-http","sse"]),command:e.string().max(1024).optional(),args:e.array(e.string().max(1024)).max(64).optional(),cwd:e.string().max(1024).optional(),url:e.string().max(2048).optional(),env:hn.optional(),headers:hn.optional()})).max(32),baseHash:Xe}),ie=e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),cc=e.object({name:ie}),lc=e.object({name:ie,body:e.record(e.string(),e.unknown())}),uc=e.object({name:ie,body:e.record(e.string(),e.unknown()),baseHash:e.string().optional()}),pc=e.object({name:ie}),dc=e.object({name:ie,text:e.string().max(65536)}),mc=e.object({id:e.string()}),fc=e.object({projectId:e.string(),id:e.string()}),Ps=e.string().trim().min(1).max(1e3).refine(t=>!/[\r\n]/.test(t),{error:()=>_("ui.note.oneLine")}),As=e.object({projectId:e.string(),text:Ps}),gc=As.extend({id:e.string()}),hc=e.object({projectId:e.string(),id:e.string(),completed:e.boolean()}),bc=e.object({projectId:e.string(),id:e.string()}),Ic=e.object({projectId:e.string()}),wc=e.object({id:e.string(),feedback:e.string().optional()}),xc=e.object({kind:e.enum(["soft","hard","force"])}),yc=e.object({provider:e.string().optional()}),Sc=e.object({}),Se=e.string().trim().min(1).max(He),vc=e.object({provider:Se,route:Se.nullable(),until:e.number().int().positive().nullish()}),Ec=e.object({provider:Se,route:Se}),$c=e.object({sessionId:e.string().trim().min(1)}),kc=e.object({provider:e.enum(We),connection:Ve,creditId:e.string().min(1).optional()}),Tc=e.object({}),Rc=e.object({}),jc=e.object({}),Cc=e.object({}),_c=e.object({}),Pc=e.object({kind:e.enum(["reconnect-platform","add-machine"]),platform:e.enum(["slack","feishu"]).optional(),machineName:e.string().min(1).optional()}).superRefine((t,n)=>{t.kind==="reconnect-platform"&&t.platform===void 0&&n.addIssue({code:e.ZodIssueCode.custom,path:["platform"],message:"platform is required for kind=reconnect-platform"}),t.kind==="add-machine"&&(t.machineName===void 0||t.machineName.trim()==="")&&n.addIssue({code:e.ZodIssueCode.custom,path:["machineName"],message:_("ui.approval.machineNameRequired")})});export{ln as a,ci as b,li as c,un as d,We as e,pi as f,pn as g,dn as h,Xo as i,zo as j,Yo as k,Ko as l,Zo as m,Jo as n,Qo as o,es as p,ts as q,ns as r,os as s,ss as t,rs as u,is as v,as as w,cs as x,ls as y,us as z,ps as A,ds as B,ms as C,fs as D,gs as E,ki as F,Ti as G,bs as H,Ri as I,ji as J,Ci as K,_i as L,Pi as M,Ai as N,Oi as O,Di as P,Li as Q,Fi as R,Mi as S,Ni as T,Ui as U,Bi as V,Wi as W,Gi as X,Hi as Y,qi as Z,Vi as _,Xi as $,zi as aa,Yi as ba,Ki as ca,Zi as da,Ji as ea,Qi as fa,ea as ga,ta as ha,na as ia,oa as ja,sa as ka,ra as la,ia as ma,aa as na,ca as oa,la as pa,ua as qa,pa as ra,da as sa,ma as ta,fa as ua,ga as va,ha as wa,ba as xa,Ia as ya,wa as za,xa as Aa,ya as Ba,Sa as Ca,re as Da,va as Ea,Ea as Fa,$a as Ga,ka as Ha,Ta as Ia,Ra as Ja,ja as Ka,Ca as La,_a as Ma,Pa as Na,Aa as Oa,Oa as Pa,Da as Qa,La as Ra,Fa as Sa,Ma as Ta,Na as Ua,Ua as Va,Ba as Wa,Wa as Xa,Ga as Ya,Ha as Za,qa as _a,ks as $a,Va as ab,Xa as bb,za as cb,Ya as db,Ka as eb,Za as fb,Ja as gb,Qa as hb,ec as ib,tc as jb,nc as kb,oc as lb,sc as mb,rc as nb,ic as ob,ac as pb,cc as qb,lc as rb,uc as sb,pc as tb,dc as ub,mc as vb,fc as wb,As as xb,gc as yb,hc as zb,bc as Ab,Ic as Bb,wc as Cb,xc as Db,yc as Eb,Sc as Fb,vc as Gb,Ec as Hb,$c as Ib,kc as Jb,Tc as Kb,Rc as Lb,jc as Mb,Cc as Nb,_c as Ob,Pc as Pb,$t as Qb,Hs as Rb,kt as Sb,qs as Tb,H as Ub,er as Vb,Ns as Wb,Us as Xb,Nn as Yb,gr as Zb,_r as _b,Ut as $b,V as ac,xr as bc,yr as cc,Mr as dc,y as ec,Vr as fc,Xr as gc,zr as hc,Yr as ic,Kr as jc,Zr as kc,Jr as lc,Qr as mc,ei as nc,cn as oc,Uo as pc,si as qc,Go as rc,ri as sc};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ var s=new Set;function t(e){return s.add(e),()=>{s.delete(e)}}function c(e){let r=[];for(let o of s)try{o(e)}catch(n){r.push(n)}if(r.length>0)throw new AggregateError(r,"Failed to cleanup session resources")}export{t as a,c as b};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{e as a}from"./chunk-VK5J556O.js";import{d as p}from"./chunk-TX46YMGI.js";import{d as n,m as s}from"./chunk-Z24SBRJK.js";import*as o from"path";var c=o.join(n,"data","pi"),j=o.join(n,"logs","sessions-pi");function l(r=c){return o.resolve(r)===o.resolve(c)?a():o.join(r,"auth.json")}function I(r){return o.join(r,"models.json")}function x(r,t=s){if(!p.test(r))throw new Error(`Invalid account id: ${r}`);return o.join(t,r)}import{existsSync as u,readFileSync as f}from"fs";function h(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let t=r;return typeof t.api=="string"&&Array.isArray(t.models)}function A(r){if(!u(r))return{};try{let t=JSON.parse(f(r,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t.providers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return{}}}function E(r){let t={};for(let[e,i]of Object.entries(A(r)))h(i)&&(t[e]=i);return t}export{h as a,A as b,E as c,c as d,j as e,l as f,I as g,x as h};
4
+ import{e as a}from"./chunk-B3NB243Z.js";import{d as p}from"./chunk-LIIZI3HY.js";import{e as n,o as s}from"./chunk-T54CZKNJ.js";import*as o from"path";var c=o.join(n,"data","pi"),j=o.join(n,"logs","sessions-pi");function l(r=c){return o.resolve(r)===o.resolve(c)?a():o.join(r,"auth.json")}function I(r){return o.join(r,"models.json")}function x(r,t=s){if(!p.test(r))throw new Error(`Invalid account id: ${r}`);return o.join(t,r)}import{existsSync as u,readFileSync as f}from"fs";function h(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let t=r;return typeof t.api=="string"&&Array.isArray(t.models)}function A(r){if(!u(r))return{};try{let t=JSON.parse(f(r,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t.providers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return{}}}function E(r){let t={};for(let[e,i]of Object.entries(A(r)))h(i)&&(t[e]=i);return t}export{h as a,A as b,E as c,c as d,j as e,l as f,I as g,x as h};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as _}from"./chunk-RA2BUYI3.js";import{c as P}from"./chunk-T73GHMFB.js";import{a as w}from"./chunk-OKRK6JPY.js";import{a as g}from"./chunk-VK5J556O.js";import{a as i,b as l,c as S,v as T,w as b,x as v,z as E}from"./chunk-BUZQBTV2.js";import{e as m,h as f,j as h}from"./chunk-TX46YMGI.js";import{mkdtempSync as x,rmSync as R,writeFileSync as A}from"node:fs";import C from"node:os";import u from"node:path";var O=new Set(["Bash","Read","Write","Edit","MultiEdit","Grep","Glob","LS","WebFetch","WebSearch","AskUserQuestion","EnterPlanMode","ExitPlanMode","TodoWrite","Skill","Agent","Task","TaskOutput","TaskStop","NotebookEdit","NotebookRead","BashOutput","KillShell","KillBash","SlashCommand","ToolSearch","ListMcpResourcesTool","ReadMcpResourceTool","bash","read","write","edit","grep","glob","find","ls","powershell","web_fetch","web_search","todo_write","skill","agent","agent_stop"]),I=/[^A-Za-z0-9._:/@[\]-]/g;function a(e){return e.replace(I,"_").slice(0,80)||i}function V(e){return O.has(e)?e:e.startsWith("mcp__cortex-")?a(e):e.startsWith("mcp__")?S:i}function L(e,r,t){return e==="claude"?{provider:"anthropic",customApi:null}:t.customProviders.has(r)?{provider:l,customApi:a(t.customProviders.get(r))}:{provider:t.piProviders.has(r)?r:i,customApi:null}}function X(e,r,t,n){return e==="claude"?w.includes(t)||n.modelIds.has(t.replace(/\[1m\]$/,""))?a(t):i:n.customProviders.has(r)?l:n.piModels.has(`${r}/${t}`)?a(t):i}function k(e,r){return[...new Set(e.map(t=>L("pi",t,r).provider))]}function N(e){let r=P(e),t=new Map(Object.entries(r).map(([n,o])=>[n,String(o.api)]));for(let n of f(h()))m(n)&&t.set(n.provider,n.api);return t}async function j(){let e=x(u.join(C.tmpdir(),"cortex-telemetry-catalog-"));try{let r=u.join(e,"auth.json");return A(r,""),(await(await g()).ModelRuntime.create({authPath:r,modelsPath:u.join(e,"absent","models.json"),allowModelNetwork:!1})).getAllModels().map(o=>({provider:String(o.provider),id:String(o.id)}))}finally{R(e,{recursive:!0,force:!0})}}function H(e,r){return{piProviders:new Set(e.map(t=>t.provider)),piModels:new Set(e.map(t=>`${t.provider}/${t.id}`)),modelIds:new Set(e.map(t=>t.id)),customProviders:r}}var d=null;function ee(e,r=_){if(d?.day===e)return d.catalog;let t=j().catch(()=>[]).then(n=>H(n,N(r)));return d={day:e,catalog:t},t}var W=["teamEnabled","serverAutoUpdate","serverUpdateDisable","autoResume","bgContinuation","streamDeltas","clientHotReloadEnabled","storeArchiveEnabled","providerUsageCollectionEnabled","claudeWindowWarmupEnabled","feishuSkillsInWeb","memoryIndexRegenEnabled"];function c(e){return e.state==="logged-in"||e.state==="expiring"}function D(e){let r=e.find(t=>t.backend==="claude"&&c(t));return r?r.authType==="api_key"?"api":"plan":"none"}function B(e){let r={};for(let{platform:t}of e){let n=["linux","darwin","win32"].includes(t)?t:"other";r[n]=(r[n]??0)+1}return r}function U(e){return Object.fromEntries(W.filter(r=>typeof e[r]=="boolean").map(r=>[a(r),e[r]]))}async function ne(e,r=new Date){let n=(await e.authStatus().catch(()=>null))?.accounts.filter(c)??[],o=e.onlineDevices(),y=n.filter(s=>s.backend==="pi").map(s=>s.provider);return{type:"heartbeat",at:r.toISOString(),backends:[...new Set(n.map(s=>s.backend))],claudeBilling:D(n),piProviders:k(y,await e.catalog()).slice(0,60),projects:e.projects(),onlineClients:o.length,clientPlatforms:B(o),activeSessions24h:await e.activeSessions24h().catch(()=>0),uptimeH:Math.round(e.uptimeS()/3600*100)/100,settings:U(e.settings())}}var p=new Set;function M(e){return p.has(e)?!0:b().funnelSent.includes(e)?(p.add(e),!0):!1}function z(e,r=null){M(e)||!E({type:"funnel",at:new Date().toISOString(),source:"server",step:e,detail:r})||(p.add(e),v(n=>({...n,funnelSent:[...new Set([...n.funnelSent,e])]})))}async function le(e){if(!T()||M("provider_authed"))return;let t=(await e().catch(()=>null))?.accounts.find(c);t&&z("provider_authed",t.backend)}export{a,V as b,L as c,X as d,ee as e,ne as f,z as g,le as h};
4
+ import{a as _}from"./chunk-PTS3J4DQ.js";import{c as P}from"./chunk-OJ37ZWBG.js";import{a as w}from"./chunk-OKRK6JPY.js";import{a as g}from"./chunk-B3NB243Z.js";import{a as i,b as l,c as S,v as T,w as b,x as v,z as E}from"./chunk-KST6OY76.js";import{e as m,h as f,j as h}from"./chunk-LIIZI3HY.js";import{mkdtempSync as x,rmSync as R,writeFileSync as A}from"node:fs";import C from"node:os";import u from"node:path";var O=new Set(["Bash","Read","Write","Edit","MultiEdit","Grep","Glob","LS","WebFetch","WebSearch","AskUserQuestion","EnterPlanMode","ExitPlanMode","TodoWrite","Skill","Agent","Task","TaskOutput","TaskStop","NotebookEdit","NotebookRead","BashOutput","KillShell","KillBash","SlashCommand","ToolSearch","ListMcpResourcesTool","ReadMcpResourceTool","bash","read","write","edit","grep","glob","find","ls","powershell","web_fetch","web_search","todo_write","skill","agent","agent_stop"]),I=/[^A-Za-z0-9._:/@[\]-]/g;function a(e){return e.replace(I,"_").slice(0,80)||i}function V(e){return O.has(e)?e:e.startsWith("mcp__cortex-")?a(e):e.startsWith("mcp__")?S:i}function L(e,r,t){return e==="claude"?{provider:"anthropic",customApi:null}:t.customProviders.has(r)?{provider:l,customApi:a(t.customProviders.get(r))}:{provider:t.piProviders.has(r)?r:i,customApi:null}}function X(e,r,t,n){return e==="claude"?w.includes(t)||n.modelIds.has(t.replace(/\[1m\]$/,""))?a(t):i:n.customProviders.has(r)?l:n.piModels.has(`${r}/${t}`)?a(t):i}function k(e,r){return[...new Set(e.map(t=>L("pi",t,r).provider))]}function N(e){let r=P(e),t=new Map(Object.entries(r).map(([n,o])=>[n,String(o.api)]));for(let n of f(h()))m(n)&&t.set(n.provider,n.api);return t}async function j(){let e=x(u.join(C.tmpdir(),"cortex-telemetry-catalog-"));try{let r=u.join(e,"auth.json");return A(r,""),(await(await g()).ModelRuntime.create({authPath:r,modelsPath:u.join(e,"absent","models.json"),allowModelNetwork:!1})).getAllModels().map(o=>({provider:String(o.provider),id:String(o.id)}))}finally{R(e,{recursive:!0,force:!0})}}function H(e,r){return{piProviders:new Set(e.map(t=>t.provider)),piModels:new Set(e.map(t=>`${t.provider}/${t.id}`)),modelIds:new Set(e.map(t=>t.id)),customProviders:r}}var d=null;function ee(e,r=_){if(d?.day===e)return d.catalog;let t=j().catch(()=>[]).then(n=>H(n,N(r)));return d={day:e,catalog:t},t}var W=["teamEnabled","serverAutoUpdate","serverUpdateDisable","autoResume","bgContinuation","streamDeltas","clientHotReloadEnabled","storeArchiveEnabled","providerUsageCollectionEnabled","claudeWindowWarmupEnabled","feishuSkillsInWeb","memoryIndexRegenEnabled"];function c(e){return e.state==="logged-in"||e.state==="expiring"}function D(e){let r=e.find(t=>t.backend==="claude"&&c(t));return r?r.authType==="api_key"?"api":"plan":"none"}function B(e){let r={};for(let{platform:t}of e){let n=["linux","darwin","win32"].includes(t)?t:"other";r[n]=(r[n]??0)+1}return r}function U(e){return Object.fromEntries(W.filter(r=>typeof e[r]=="boolean").map(r=>[a(r),e[r]]))}async function ne(e,r=new Date){let n=(await e.authStatus().catch(()=>null))?.accounts.filter(c)??[],o=e.onlineDevices(),y=n.filter(s=>s.backend==="pi").map(s=>s.provider);return{type:"heartbeat",at:r.toISOString(),backends:[...new Set(n.map(s=>s.backend))],claudeBilling:D(n),piProviders:k(y,await e.catalog()).slice(0,60),projects:e.projects(),onlineClients:o.length,clientPlatforms:B(o),activeSessions24h:await e.activeSessions24h().catch(()=>0),uptimeH:Math.round(e.uptimeS()/3600*100)/100,settings:U(e.settings())}}var p=new Set;function M(e){return p.has(e)?!0:b().funnelSent.includes(e)?(p.add(e),!0):!1}function z(e,r=null){M(e)||!E({type:"funnel",at:new Date().toISOString(),source:"server",step:e,detail:r})||(p.add(e),v(n=>({...n,funnelSent:[...new Set([...n.funnelSent,e])]})))}async function le(e){if(!T()||M("provider_authed"))return;let t=(await e().catch(()=>null))?.accounts.find(c);t&&z("provider_authed",t.backend)}export{a,V as b,L as c,X as d,ee as e,ne as f,z as g,le as h};