@cortex-agent/server 2026.10.28 → 2026.11.17

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 (258) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +36 -7
  3. package/THIRD_PARTY_NOTICES.txt +1109 -278
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  6. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  7. package/dist/chunks/{anthropic-messages-M3SMXACA.js → anthropic-messages-M732OMEE.js} +1 -1
  8. package/dist/chunks/{azure-openai-responses-76YWXHSB.js → azure-openai-responses-RAKTV6JY.js} +1 -1
  9. package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +62 -0
  10. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  11. package/dist/chunks/child-runner-MO5RT6FH.js +4 -0
  12. package/dist/chunks/chunk-2ATTYCRJ.js +4 -0
  13. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-2ROGTDM2.js} +1 -1
  14. package/dist/chunks/chunk-2VVRTJQN.js +4 -0
  15. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  16. package/dist/chunks/chunk-3CPIMAYX.js +30 -0
  17. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-3CZPBLB3.js} +1 -1
  18. package/dist/chunks/chunk-3ORG56I5.js +8 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-4YLAGSDM.js} +1 -1
  20. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-53TQNK7Z.js} +1 -1
  21. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-5A6CA5TM.js} +1 -1
  22. package/dist/chunks/{chunk-PBJ5MPPX.js → chunk-5DF5WJNM.js} +1 -1
  23. package/dist/chunks/chunk-5PAW3DEU.js +50 -0
  24. package/dist/chunks/{chunk-DXBSQXJL.js → chunk-7GAYFN52.js} +1 -1
  25. package/dist/chunks/chunk-7GEBDPTT.js +4 -0
  26. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-AFTBQRPN.js} +1 -1
  27. package/dist/chunks/chunk-AVXDF7AG.js +4 -0
  28. package/dist/chunks/chunk-BDLKI2NT.js +4 -0
  29. package/dist/chunks/{chunk-P52RMIYX.js → chunk-BJGYGEZO.js} +1 -1
  30. package/dist/chunks/chunk-BUZQBTV2.js +10 -0
  31. package/dist/chunks/chunk-BZDIAI5M.js +125 -0
  32. package/dist/chunks/{chunk-A34TDMIC.js → chunk-CEGSDGYQ.js} +1 -1
  33. package/dist/chunks/{chunk-Q7CE3UIE.js → chunk-CK3P345X.js} +69 -69
  34. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-EE3WT25T.js} +1 -1
  35. package/dist/chunks/chunk-ETIBCA2S.js +4 -0
  36. package/dist/chunks/{chunk-REBNWCKI.js → chunk-FP7ML72L.js} +1 -1
  37. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-H4QZ2P3Z.js} +1 -1
  38. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  39. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-IKLTEWA3.js} +1 -1
  40. package/dist/chunks/chunk-IYVZHGUQ.js +5 -0
  41. package/dist/chunks/chunk-JJDEQ6N2.js +4 -0
  42. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  43. package/dist/chunks/chunk-KDPY2YA3.js +129 -0
  44. package/dist/chunks/{chunk-SUFW24P4.js → chunk-KUDK7GPS.js} +1 -1
  45. package/dist/chunks/chunk-LAWOWPZX.js +363 -0
  46. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  47. package/dist/chunks/chunk-LP72AF56.js +45 -0
  48. package/dist/chunks/{chunk-KENCMLRE.js → chunk-LP7T32PW.js} +1 -1
  49. package/dist/chunks/chunk-LQTFDC67.js +4 -0
  50. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-MGYYSX7Y.js} +1 -1
  51. package/dist/chunks/chunk-NNBSSISP.js +4 -0
  52. package/dist/chunks/chunk-NNTQUHLO.js +877 -0
  53. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-NRD57ICT.js} +1 -1
  54. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-NXZS5PEW.js} +1 -1
  55. package/dist/chunks/chunk-OFEPDNRB.js +4 -0
  56. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-P7TVR4GY.js} +1 -1
  57. package/dist/chunks/chunk-QEL6CMLE.js +4 -0
  58. package/dist/chunks/chunk-QMSSIDRQ.js +70 -0
  59. package/dist/chunks/chunk-QUXPMNFQ.js +4 -0
  60. package/dist/chunks/chunk-R52AVUQB.js +5 -0
  61. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  62. package/dist/chunks/chunk-RA2BUYI3.js +6 -0
  63. package/dist/chunks/chunk-RDW6FRF5.js +4 -0
  64. package/dist/chunks/chunk-RF4JLYBX.js +6 -0
  65. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-ROVKOIHF.js} +1 -1
  66. package/dist/chunks/chunk-RYLSRII6.js +7 -0
  67. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-S3MR37DL.js} +1 -1
  68. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  69. package/dist/chunks/chunk-SFX7V5O2.js +10 -0
  70. package/dist/chunks/chunk-STCNHXPJ.js +6 -0
  71. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-SY2HV3V5.js} +1 -1
  72. package/dist/chunks/chunk-T73GHMFB.js +4 -0
  73. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  74. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  75. package/dist/chunks/chunk-TX46YMGI.js +5 -0
  76. package/dist/chunks/chunk-U23S37TT.js +6 -0
  77. package/dist/chunks/chunk-UT6DGZDO.js +4 -0
  78. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  79. package/dist/chunks/chunk-V6X7Y62J.js +7 -0
  80. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  81. package/dist/chunks/{chunk-NAA7GF6Q.js → chunk-VBN2JSER.js} +1 -1
  82. package/dist/chunks/chunk-VIMHSW6J.js +4 -0
  83. package/dist/chunks/chunk-VK5J556O.js +4 -0
  84. package/dist/chunks/chunk-VPVSKJGX.js +6 -0
  85. package/dist/chunks/chunk-VTL3Z2OP.js +23 -0
  86. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  87. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  88. package/dist/chunks/chunk-W6AKCEYF.js +8 -0
  89. package/dist/chunks/chunk-WBSE3EF3.js +27 -0
  90. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  91. package/dist/chunks/{chunk-UNVEZI57.js → chunk-XEBEWR6Y.js} +1 -1
  92. package/dist/chunks/chunk-XPPZ6Y3X.js +8 -0
  93. package/dist/chunks/chunk-XYSXL3KX.js +4 -0
  94. package/dist/chunks/chunk-YAAKL3QS.js +80 -0
  95. package/dist/chunks/chunk-YB5LUJHS.js +65 -0
  96. package/dist/chunks/chunk-Z24SBRJK.js +4 -0
  97. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +1 -1
  98. package/dist/chunks/context-GQKWKFRM.js +4 -0
  99. package/dist/chunks/cost-OOO32GLC.js +5 -0
  100. package/dist/chunks/dist-V5FRMUFH.js +4 -0
  101. package/dist/chunks/easter-egg-3d-CZH7AYZ7.js +4 -0
  102. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  103. package/dist/chunks/execution-repo-XXL4FXC6.js +4 -0
  104. package/dist/chunks/{executions-6ARGR3IO.js → executions-BN6OLLVM.js} +1 -1
  105. package/dist/chunks/file-H572PL2Z.js +4 -0
  106. package/dist/chunks/google-generative-ai-2G4ITOZL.js +4 -0
  107. package/dist/chunks/google-vertex-PACHCMRZ.js +4 -0
  108. package/dist/chunks/init-75F4V7SK.js +4 -0
  109. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-ABBD7DO5.js} +1 -1
  110. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-EE2UPR3Q.js} +1 -1
  111. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-C446T2GZ.js} +1 -1
  112. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-IA2F2H7A.js} +1 -1
  113. package/dist/chunks/local-client-stop-5YOLXGYT.js +4 -0
  114. package/dist/chunks/memory-cli-5SSF6YJM.js +11 -0
  115. package/dist/chunks/{mistral-conversations-34F66L3O.js → mistral-conversations-VHP63CDS.js} +1 -1
  116. package/dist/chunks/{model-resolver-N3DTAQ2S.js → model-resolver-FVJNZ6NA.js} +1 -1
  117. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  118. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  119. package/dist/chunks/{openai-codex-responses-ZBVHREB3.js → openai-codex-responses-EHJ4AZBE.js} +1 -1
  120. package/dist/chunks/{openai-completions-VVIB26SH.js → openai-completions-CRAGQFCE.js} +1 -1
  121. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-P5UX7BWY.js} +1 -1
  122. package/dist/chunks/{openai-responses-735XA2ZX.js → openai-responses-IZ22NVQ7.js} +1 -1
  123. package/dist/chunks/{openrouter-images-3IKETHAC.js → openrouter-images-W2JAMSRH.js} +1 -1
  124. package/dist/chunks/{pi-messages-I3E4ZFHA.js → pi-messages-MJEEQU2R.js} +1 -1
  125. package/dist/chunks/{radius-HXRZVBDB.js → radius-ZM7ZRMXF.js} +1 -1
  126. package/dist/chunks/{remote-ops-BALZYKH6.js → remote-ops-O5CR4RGA.js} +1 -1
  127. package/dist/chunks/runner-S6R3US24.js +4 -0
  128. package/dist/chunks/schedule-cli-4T4YC5V5.js +4 -0
  129. package/dist/chunks/slack-2CGM4SMY.js +4 -0
  130. package/dist/chunks/start-ui-http-3D7QNHGB.js +43 -0
  131. package/dist/chunks/subagent-OZGUOV3J.js +4 -0
  132. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  133. package/dist/chunks/tool-shims-IA2WELXJ.js +4 -0
  134. package/dist/chunks/typesafe-system-one-6ULACYD4.js +1 -1
  135. package/dist/chunks/ui-board-H4INJD6C.js +5 -0
  136. package/dist/chunks/ui-decision-6HHNROIT.js +4 -0
  137. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-6PLXHSTB.js} +1 -1
  138. package/dist/chunks/ui-view-6MDU4GXY.js +4 -0
  139. package/dist/chunks/virtual-modules-OFI7QKYH.js +4 -0
  140. package/dist/chunks/waitpoint-W5M3BE55.js +5 -0
  141. package/dist/chunks/workers-GTFP75MS.js +4 -0
  142. package/dist/client-bundle/client.mjs +44 -31
  143. package/dist/client-bundle/manifest.json +2 -2
  144. package/dist/core/pi-sdk.js +1 -1
  145. package/dist/domain/auth/cc-auth-cli.js +1 -1
  146. package/dist/domain/mcp/bundled-server.js +1 -1
  147. package/dist/domain/mcp/feishu/client.js +4 -0
  148. package/dist/entry/app.js +201 -191
  149. package/dist/entry/browser-cli.js +10 -10
  150. package/dist/entry/cli.js +1 -1
  151. package/dist/entry/cortex-cli.js +1 -1
  152. package/dist/entry/daemon.js +4 -4
  153. package/dist/entry/hook-cli.js +2 -2
  154. package/dist/entry/production-app-bootstrap.js +1 -1
  155. package/dist/entry/production-evidence-export-cli.js +1 -1
  156. package/dist/entry/signal-cli.js +2 -2
  157. package/dist/tui/index.js +41 -41
  158. package/package.json +3 -3
  159. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  160. package/vendor/pi/dist/extensions/codemode/execute.js +1 -1
  161. package/vendor/pi-ai/bedrock.js +1 -1
  162. package/vendor/pi-ai/oauth-load.js +1 -1
  163. package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-BgIyUG-C.js} +1 -1
  164. package/web/dist/assets/index-9lyu2S6W.css +1 -0
  165. package/web/dist/assets/index-C-hpzey7.js +532 -0
  166. package/web/dist/assets/{index-WCm6wwmM.js → index-C2eMpcuI.js} +1 -1
  167. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  168. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  169. package/web/dist/index.html +2 -2
  170. package/web/dist/theme.css +22 -0
  171. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  172. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  173. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  174. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  175. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  176. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  177. package/dist/chunks/chunk-3THJYAEF.js +0 -4
  178. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  179. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  180. package/dist/chunks/chunk-52T37Y47.js +0 -8
  181. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  182. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  183. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  184. package/dist/chunks/chunk-BGVHA2D4.js +0 -4
  185. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  186. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  187. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  188. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  189. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  190. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  191. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  192. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  193. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  194. package/dist/chunks/chunk-FH74NME3.js +0 -115
  195. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  196. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  197. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  198. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  199. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  200. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  201. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  202. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  203. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  204. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  205. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  206. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  207. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  208. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  209. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  210. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  211. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  212. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  213. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  214. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  215. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  216. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  217. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  218. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  219. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  220. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  221. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  222. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  223. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  224. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  225. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  226. package/dist/chunks/client-XOGYH5UR.js +0 -4
  227. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  228. package/dist/chunks/context-VCQH5OB6.js +0 -4
  229. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  230. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  231. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  232. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  233. package/dist/chunks/execution-repo-ZLJTBWFC.js +0 -4
  234. package/dist/chunks/file-7BN7RCAY.js +0 -4
  235. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  236. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  237. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  238. package/dist/chunks/init-HA7FAQ73.js +0 -4
  239. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  240. package/dist/chunks/memory-cli-PYOILNN5.js +0 -11
  241. package/dist/chunks/models-L5VF4I5O-XXNJYQMQ.js +0 -4
  242. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  243. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  244. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  245. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  246. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  247. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  248. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  249. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  250. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  251. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  252. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  253. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  254. package/vendor/aistatus/gateway-cli.js +0 -21
  255. package/web/dist/assets/index-BHZpFXhc.js +0 -525
  256. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  257. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  258. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -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 l}from"./chunk-NAA7GF6Q.js";import{f as s}from"./chunk-J5DVLUKY.js";import{spawn as f}from"node:child_process";var i=l("hook-exec"),c=2e3;function u(r,n){r.settled||(r.settled=!0,r.resolve(n))}function d(r,n,e,o=null){r.settled||(i.error(e),u(r,{stdout:r.stdout.trim(),stderr:r.stderr.slice(-c),exitCode:o,error:n}))}function m(r,n,e,o){if(o==="SIGTERM"||o==="SIGKILL"){let t=`timed out after ${n.timeoutMs}ms`;d(r,t,`${t} (${n.label})`);return}if(e!==0){let t=`exited with code ${e}`,a=r.stderr?`: ${r.stderr.trim()}`:"";d(r,t,`${t} (${n.label})${a}`,e);return}u(r,{stdout:r.stdout.trim(),stderr:r.stderr.slice(-c),exitCode:0})}function $(r,n){r.on("error",e=>{i.warn(`stdin write failed (${n.label}): ${e.message}`)});try{r.write(n.stdinPayload)}catch(e){i.warn(`stdin write failed (${n.label}): ${String(e)}`)}try{r.end()}catch(e){i.warn(`stdin end failed (${n.label}): ${String(e)}`)}}function w(r){return f("sh",["-c",`${r.command} "$@"`,"hook",...r.args??[]],{stdio:["pipe","pipe","pipe"],cwd:s,timeout:r.timeoutMs,...r.env?{env:r.env}:{}})}function g(r,n){try{let e=w(r);e.stdout.on("data",o=>{n.stdout+=o.toString()}),e.stderr.on("data",o=>{n.stderr+=o.toString()}),e.on("error",o=>{d(n,o.message,`spawn error (${r.label}): ${o.message}`)}),e.on("close",(o,t)=>m(n,r,o,t)),$(e.stdin,r)}catch(e){let o=e instanceof Error?e.message:String(e);d(n,o,`spawn error (${r.label}): ${o}`)}}function I(r){return new Promise(n=>{g(r,{stdout:"",stderr:"",settled:!1,resolve:n})})}export{I as a};
4
+ import{e as l}from"./chunk-VBN2JSER.js";import{d as s}from"./chunk-Z24SBRJK.js";import{spawn as f}from"node:child_process";var i=l("hook-exec"),c=2e3;function u(r,n){r.settled||(r.settled=!0,r.resolve(n))}function d(r,n,e,o=null){r.settled||(i.error(e),u(r,{stdout:r.stdout.trim(),stderr:r.stderr.slice(-c),exitCode:o,error:n}))}function m(r,n,e,o){if(o==="SIGTERM"||o==="SIGKILL"){let t=`timed out after ${n.timeoutMs}ms`;d(r,t,`${t} (${n.label})`);return}if(e!==0){let t=`exited with code ${e}`,a=r.stderr?`: ${r.stderr.trim()}`:"";d(r,t,`${t} (${n.label})${a}`,e);return}u(r,{stdout:r.stdout.trim(),stderr:r.stderr.slice(-c),exitCode:0})}function $(r,n){r.on("error",e=>{i.warn(`stdin write failed (${n.label}): ${e.message}`)});try{r.write(n.stdinPayload)}catch(e){i.warn(`stdin write failed (${n.label}): ${String(e)}`)}try{r.end()}catch(e){i.warn(`stdin end failed (${n.label}): ${String(e)}`)}}function w(r){return f("sh",["-c",`${r.command} "$@"`,"hook",...r.args??[]],{stdio:["pipe","pipe","pipe"],cwd:s,timeout:r.timeoutMs,...r.env?{env:r.env}:{}})}function g(r,n){try{let e=w(r);e.stdout.on("data",o=>{n.stdout+=o.toString()}),e.stderr.on("data",o=>{n.stderr+=o.toString()}),e.on("error",o=>{d(n,o.message,`spawn error (${r.label}): ${o.message}`)}),e.on("close",(o,t)=>m(n,r,o,t)),$(e.stdin,r)}catch(e){let o=e instanceof Error?e.message:String(e);d(n,o,`spawn error (${r.label}): ${o}`)}}function I(r){return new Promise(n=>{g(r,{stdout:"",stderr:"",settled:!1,resolve:n})})}export{I as a};
@@ -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{a as d}from"./chunk-OKRK6JPY.js";var h="Model override: pi provider/model[:thinking], claude model ID. Default: role model, then parent model.",A="Backend override. Default: role backend, then parent backend.",D="Delegate isolated, one-shot work; children cannot delegate. Give self-contained prompts. Choose one mode: single, parallel, or chain. Supports both backends. Set clean for work that must not be shaped by Cortex context: the child runs in a fresh workspace with its brief and the files you list in files, copied to inputs/. Its brief must stand alone, name those files as inputs/<name>, and include external paths only when the user explicitly authorizes access, stating the allowed operations. Its result ends with the workspace path, where it leaves its output.",G="Run in a fresh workspace without Cortex context. Implied by files.",P="Files or directories (absolute or ~ paths) copied into the workspace inputs/. Implies clean.",g=["description","prompt","subagent_type"];function T(e,n){if(e!=null){if(e==="claude"||e==="pi")return e;throw new Error(`${n} backend must be "claude" or "pi".`)}}function S(e){for(let n of g)if(typeof e[n]!="string"||e[n].trim()==="")throw new Error(`Agent task requires a non-empty ${n}.`);T(e.backend,"Agent task"),y(e)}function y(e){if(e.clean!==void 0&&typeof e.clean!="boolean")throw new Error("Agent task clean must be a boolean.");let n=e.files;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string"||o.trim()==="")))throw new Error("Agent task files must be a list of non-empty paths.")}function f(e,n){if(n.length===0)throw new Error(`${e} requires at least one task.`);if(n.length>8)throw new Error(`Agent ${e} task maximum is 8.`);for(let o of n)S(o);return{mode:e,tasks:n}}function v(e){let n=e??{},o=g.some(s=>s in n),t=Array.isArray(n.parallel),r=Array.isArray(n.chain);if(Number(o)+Number(t)+Number(r)!==1)throw new Error("Provide exactly one Agent mode: single fields, parallel, or chain.");if(t)return f("parallel",n.parallel);if(r)return f("chain",n.chain);let i=n;return S(i),{mode:"single",tasks:[i]}}var N=24,u=480;function j(e){let n=e.subagentClaudeModels;return[...n?E(n.map(t=>({backend:"claude",id:t.id})),e.claudeModel):I(e.claudeModel),...e.subagentPiModels??[]]}var x={model:h,backend:A},k="Role name, such as explore, general-purpose, or plan.",C="Role name for single mode, such as explore, general-purpose, or plan.";function X(e){let n=(e.roles??[]).map(r=>({name:r.name.trim(),summary:r.summary.trim()})).filter(r=>r.name!=="").sort((r,i)=>r.name.localeCompare(i.name)),o=e.models??[],t=n.length>0?` Available here: ${U(n)}.`:"";return{subagentType:n.length>0?`Role name.${t}`:k,subagentTypeSingle:n.length>0?`Role name for single mode.${t}`:C,...x,catalog:$(o)}}function H(e){let n=[];for(let o of e){let t=o.name.trim();t&&n.push({name:t,summary:O(o.description)})}return n}function I(e,n=d){let o=n.length>0?n:d;return E(o.map(t=>({backend:"claude",id:t})),e)}function E(e,n){let o=n?.trim();return!o||e.some(t=>t.id===o)?e:[...e,{backend:"claude",id:o}]}function Y(e){let n=[];for(let o of e){let t=o.id.trim();if(!t)continue;let r=o.provider.trim();n.push(r?{backend:"pi",provider:r,id:t}:{backend:"pi",id:t})}return n}function q(e){return JSON.stringify(e)}function z(e){return e?M(e):null}function M(e){if(!e)return[];let n;try{n=JSON.parse(e)}catch{return[]}if(!Array.isArray(n))return[];let o=n,t=[];for(let r of o){if(!w(r))continue;let{backend:i,provider:s,id:c}=r;if(i!=="claude"&&i!=="pi"||typeof c!="string"||!c.trim())continue;let l={backend:i,id:c.trim()};typeof s=="string"&&s.trim()&&(l.provider=s.trim()),t.push(l)}return t}function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function O(e){let n=e.trim(),o=n.indexOf(". "),t=o>=0?n.slice(0,o):n;return t.endsWith(".")&&(t=t.slice(0,-1)),t.length>80&&(t=`${t.slice(0,80)}\u2026`),t}function R(e){let n=e.id.trim();if(!n)return null;if(e.backend==="claude")return n;let o=e.provider?.trim()??"";return o?`${o}/${n}`:n}function B(e){let n=new Set,o=[];for(let t of e){let r=R(t);if(!r)continue;let i=`${t.backend}:${r}`;n.has(i)||(n.add(i),o.push({backend:t.backend,name:r}))}return o.sort((t,r)=>t.backend===r.backend?t.name.localeCompare(r.name):t.backend==="claude"?-1:1),o}var b=" Known models \u2014 ";function $(e){let n=B(e),o=["claude","pi"].flatMap(t=>{let r=n.filter(i=>i.backend===t).map(i=>i.name);return r.length?[`${t}: ${r.join(", ")}`]:[]});return o.length?`${b}${o.join("; ")}.`:""}function J(e){return e.split(b)[0]}function U(e){let n=e.slice(0,N),o=e.length-n.length,t=o>0?` (+${o} more)`:"",r=n.map(a=>a.summary?`${a.name} \u2014 ${a.summary}`:a.name).join("; ");if(r.length+t.length<=u)return r+t;let i=n.map(a=>a.name).join(", ");if(i.length+t.length<=u)return i+t;let s=[],c=0;for(let a of n){let p=a.name.length+(s.length>0?2:0),m=e.length-(s.length+1),_=m>0?` (+${m} more)`.length:0;if(c+p+_>u)break;s.push(a.name),c+=p}let l=e.length-s.length;return s.join(", ")+(l>0?` (+${l} more)`:"")}export{D as a,G as b,P as c,v as d,j as e,X as f,H as g,Y as h,q as i,z as j,M as k,$ as l,J as m};
@@ -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-NAA7GF6Q.js";import*as p from"crypto";import{mkdirSync as m,readFileSync as y,renameSync as g,writeFileSync as S}from"fs";import*as d from"path";var f=a("ui-http"),x="ui-pairing.json",A=600*1e3,w=20,i="0123456789ABCDEFGHJKMNPQRSTVWXYZ",l=8,I={O:"0",I:"1",L:"1"};function E(r){let n=r.toUpperCase().replace(/[\s-]/g,"");if(n.length!==l)return null;let e=[...n].map(o=>I[o]??o).join("");return[...e].every(o=>i.includes(o))?e:null}function L(r){return`${r.slice(0,4)}-${r.slice(4)}`}function N(){return[...p.randomBytes(l)].map(n=>i[n%i.length]).join("")}function u(r,n){let e=null;try{e=JSON.parse(y(r,"utf8"))}catch{}let o={};for(let[t,s]of Object.entries(e?.codes??{}))typeof s=="number"&&s>n&&(o[t]=s);return{codes:o,failures:typeof e?.failures=="number"?e.failures:0}}function c(r,n){try{m(d.dirname(r),{recursive:!0});let e=`${r}.${process.pid}.tmp`;S(e,JSON.stringify(n),{mode:384}),g(e,r)}catch(e){f.warn(`could not persist pairing codes: ${e.message}`)}}function C(r){let n=r.now??(()=>Date.now()),{file:e}=r;return{create(){let o=n(),t=u(e,o),s=N();return t.codes[s]=o+A,t.failures=0,c(e,t),{code:L(s),expiresAt:t.codes[s]}},redeem(o){let t=u(e,n()),s=E(o);return s&&s in t.codes?(delete t.codes[s],c(e,t),!0):(t.failures+=1,t.failures>=w&&(f.warn("too many wrong pairing codes \u2014 voiding every outstanding code"),t.codes={},t.failures=0),c(e,t),!1)}}}export{x as a,A as b,E as c,C as d};
4
+ import{e as a}from"./chunk-VBN2JSER.js";import*as p from"crypto";import{mkdirSync as m,readFileSync as y,renameSync as g,writeFileSync as S}from"fs";import*as d from"path";var f=a("ui-http"),x="ui-pairing.json",A=600*1e3,w=20,i="0123456789ABCDEFGHJKMNPQRSTVWXYZ",l=8,I={O:"0",I:"1",L:"1"};function E(r){let n=r.toUpperCase().replace(/[\s-]/g,"");if(n.length!==l)return null;let e=[...n].map(o=>I[o]??o).join("");return[...e].every(o=>i.includes(o))?e:null}function L(r){return`${r.slice(0,4)}-${r.slice(4)}`}function N(){return[...p.randomBytes(l)].map(n=>i[n%i.length]).join("")}function u(r,n){let e=null;try{e=JSON.parse(y(r,"utf8"))}catch{}let o={};for(let[t,s]of Object.entries(e?.codes??{}))typeof s=="number"&&s>n&&(o[t]=s);return{codes:o,failures:typeof e?.failures=="number"?e.failures:0}}function c(r,n){try{m(d.dirname(r),{recursive:!0});let e=`${r}.${process.pid}.tmp`;S(e,JSON.stringify(n),{mode:384}),g(e,r)}catch(e){f.warn(`could not persist pairing codes: ${e.message}`)}}function C(r){let n=r.now??(()=>Date.now()),{file:e}=r;return{create(){let o=n(),t=u(e,o),s=N();return t.codes[s]=o+A,t.failures=0,c(e,t),{code:L(s),expiresAt:t.codes[s]}},redeem(o){let t=u(e,n()),s=E(o);return s&&s in t.codes?(delete t.codes[s],c(e,t),!0):(t.failures+=1,t.failures>=w&&(f.warn("too many wrong pairing codes \u2014 voiding every outstanding code"),t.codes={},t.failures=0),c(e,t),!1)}}}export{x as a,A as b,E as c,C as d};
@@ -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{a as t,c as f}from"./chunk-E7ZMYIY6.js";import{l as s}from"./chunk-J5DVLUKY.js";import*as r from"fs";import*as o from"path";var c=o.join(s,"preferences.json");function i(){try{let e=JSON.parse(r.readFileSync(c,"utf8"));return e&&typeof e=="object"?e:{}}catch{return{}}}function d(){return t(i().lang)}function p(e){let a=t(e),l={...i(),lang:a};r.mkdirSync(o.dirname(c),{recursive:!0}),r.writeFileSync(c,JSON.stringify(l,null,2)+`
4
+ import{a as t,c as f}from"./chunk-3CPIMAYX.js";import{i as s}from"./chunk-Z24SBRJK.js";import*as r from"fs";import*as o from"path";var c=o.join(s,"preferences.json");function i(){try{let e=JSON.parse(r.readFileSync(c,"utf8"));return e&&typeof e=="object"?e:{}}catch{return{}}}function d(){return t(i().lang)}function p(e){let a=t(e),l={...i(),lang:a};r.mkdirSync(o.dirname(c),{recursive:!0}),r.writeFileSync(c,JSON.stringify(l,null,2)+`
5
5
  `)}function g(e=process.env){return e.CORTEX_LANG?"env":i().lang?"file":"default"}function x(e,a){let n=t(e);return p(n),f(n),a?.(n),n}export{d as a,g as b,x as c};
@@ -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
+ function c(e){let r=e?.trim();if(!r)return{};let t=r.lastIndexOf(":"),n=t>0&&r.slice(t+1).trim()||void 0,o=t>0?r.slice(0,t):r,i=o.indexOf("/");return i<0?{model:o||void 0,thinking:n}:{provider:o.slice(0,i)||void 0,model:o.slice(i+1)||void 0,thinking:n}}function p(e,r,t){let n=c(e.model?.trim()||r.model?.trim());return n.model?n:t?.model?{model:t.model,...t.provider?{provider:t.provider}:{}}:{}}var d={allow:"favorites",deny:[]};function x(e){let r=e.model.trim(),t=e.provider?.trim();return e.backend==="pi"&&t?`${t}/${r}`:r}function f(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s(e,r){let t=e.trim().split("*").map(f).join(".*");return new RegExp(`^${t}$`,"i").test(r)}function u(e,r,t){return e==="all"?!0:e==="favorites"?t.includes(r):e.some(n=>s(n,r))}function y(e,r,t){return u(e.allow,r,t)?!e.deny.some(n=>s(n,r)):!1}function l(e){return Array.isArray(e)?e.flatMap(t=>typeof t=="string"&&t.trim()?[t.trim()]:[]):null}function m(e){return e==="all"||e==="favorites"?e:l(e)??d.allow}function g(e){if(!e||typeof e!="object"||Array.isArray(e))return{...d,deny:[]};let r=e;return{allow:m(r.allow),deny:l(r.deny)??[]}}function A(e,r,t,n){if(e)for(let o of r)o.model?.trim()&&e({backend:t(o),model:o.model,parent:n})}export{x as a,y as b,g as c,A as d,c as e,p as f};
@@ -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 u}from"./chunk-5M4PFLRW.js";import{d as n,z as p}from"./chunk-J5DVLUKY.js";import{existsSync as s}from"node:fs";import*as o from"node:path";import{pathToFileURL as l}from"node:url";var a=o.join(n,"hooks"),f=o.join(a,"overlay","register.mjs");function h(){return{user:p,builtin:u()?a:null}}function m(e,r=h()){let t=o.join(r.user,e);if(s(t)||!r.builtin)return{path:t,user:!0};let i=o.join(r.builtin,e);return s(i)?{path:i,user:!1}:{path:t,user:!0}}function O(e,r=h()){let t=m(e,r);return!t.user||!r.builtin?[t.path]:["--import",l(f).href,t.path]}export{h as a,m as b,O as c};
4
+ import{a as u}from"./chunk-5M4PFLRW.js";import{b as n,y as p}from"./chunk-Z24SBRJK.js";import{existsSync as s}from"node:fs";import*as o from"node:path";import{pathToFileURL as l}from"node:url";var a=o.join(n,"hooks"),f=o.join(a,"overlay","register.mjs");function h(){return{user:p,builtin:u()?a:null}}function m(e,r=h()){let t=o.join(r.user,e);if(s(t)||!r.builtin)return{path:t,user:!0};let i=o.join(r.builtin,e);return s(i)?{path:i,user:!1}:{path:t,user:!0}}function O(e,r=h()){let t=m(e,r);return!t.user||!r.builtin?[t.path]:["--import",l(f).href,t.path]}export{h as a,m as b,O as c};
@@ -0,0 +1,5 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as B,c as v}from"./chunk-Y6ZEVVL5.js";import{d as V}from"./chunk-U23S37TT.js";import{f as G}from"./chunk-T73GHMFB.js";import{a as _,b as $,e as H}from"./chunk-NNBSSISP.js";import{a as A}from"./chunk-OE4KH3NJ.js";import{a as K}from"./chunk-VK5J556O.js";import{e as j}from"./chunk-STCNHXPJ.js";import{e as F}from"./chunk-VBN2JSER.js";import{b as L,u as X,x as W}from"./chunk-Z24SBRJK.js";function S(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,contextTokens:0,turns:0}}function g(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function z(t,e){t.input+=e.input,t.output+=e.output,t.cacheRead+=e.cacheRead,t.cacheWrite+=e.cacheWrite,t.cost+=e.cost,t.contextTokens=e.contextTokens||t.contextTokens,t.turns+=e.turns}function mt(t,e){t.input+=e.input,t.output+=e.output,t.cacheRead+=e.cacheRead,t.cacheWrite+=e.cacheWrite,t.cost+=e.cost,t.contextTokens+=e.contextTokens,t.turns+=e.turns}function ge(t){let e=S();for(let n of t)mt(e,n.usage);return e}import*as Y from"node:path";function gt(t,e,n){return t.hasTrustRequiringProjectResources(e)?new t.ProjectTrustStore(n).get(e)===!0:!0}function _t(t,e,n){return n===null||!e||e<=n?t:e-n+Math.min(t,Math.floor(n/2))}function yt(t){let e=t.getCompactionReserveTokens.bind(t);t.getCompactionReserveTokens=n=>_t(e(n),n?.contextWindow,j().maxContextTokens)}function Et(t){if(process.platform!=="win32")return;let e=process.env.CORTEX_GIT_BASH_PATH;if(!e)return;let n=t.getShellPath.bind(t);t.getShellPath=()=>n()??e}function J(t,e,n){let o=t.SettingsManager.create(e,n,{projectTrusted:gt(t,e,n)});return o.getCacheWarmingMode=()=>"off",yt(o),Et(o),o}var b=F("pi-subagent");function Tt(t,e,n){if(!e.model)return{model:void 0,thinkingLevel:void 0};let o=e.provider?`${e.provider}/${e.model}`:e.model,r=t.resolveCliModel({cliModel:e.thinking?`${o}:${e.thinking}`:o,modelRuntime:n});if(r.error)throw new Error(r.error);return r.warning&&b.warn(`PI subagent model resolution: ${r.warning}`),{model:r.model,thinkingLevel:r.thinkingLevel}}async function ht(t,e){let n=J(t,e.cwd,e.agentDir),o=await t.ModelRuntime.create({authPath:G(e.agentDir),modelsPath:Y.join(e.agentDir,"models.json"),allowModelNetwork:!1});return await V(o,e.agentDir),t.createAgentSessionServices({cwd:e.cwd,agentDir:e.agentDir,settingsManager:n,modelRuntime:o,resourceLoaderOptions:{noExtensions:!0,extensionFactories:e.extensions,appendSystemPrompt:e.appendSystemPrompt,noContextFiles:e.noContextFiles===!0}})}async function Q(t){let e=await K(),n=await ht(e,t);for(let i of n.diagnostics)i.type==="error"&&b.warn(`PI subagent session: ${i.message}`);let{model:o,thinkingLevel:r}=Tt(e,t,n.modelRuntime),s=await e.createAgentSessionFromServices({services:n,sessionManager:e.SessionManager.inMemory(t.cwd),model:o,thinkingLevel:r,tools:t.tools});return await s.session.bindExtensions({mode:"print",onError:i=>b.warn(`PI subagent extension ${i.extensionPath} failed on ${i.event}: ${String(i.error)}`)}),{session:s.session,dispose:()=>s.session.dispose()}}function T(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||n.type!=="image")continue;let o=n,r=o.source;r&&r.type==="base64"&&typeof r.data=="string"&&r.data?e.push({mimeType:typeof r.media_type=="string"?r.media_type:"",data:r.data}):typeof o.data=="string"&&o.data&&e.push({mimeType:typeof o.mimeType=="string"?o.mimeType:"",data:o.data})}return e}function Z(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.mimeType=="string"&&typeof e.data=="string"&&e.data.length>0}function Ae(t,e,n=!1){if(!e||!t)return;let o=r=>{try{e(r)}catch{}};return{forChild(r,s){let i=`${t}#${r}`,c=n&&r>0;return(a,m)=>{let d=Rt(i,s,m,a);for(let f=0;f<d.length;f++)o(c&&f===0?{...d[f],prompt:s.prompt}:d[f]);d.length&&(c=!1)}}}}function Ct(t,e,n){return{ref:t,type:e.subagent_type,description:e.description,model:n.model??null,backend:"pi",...e.clean?{clean:!0}:{}}}function Rt(t,e,n,o){let r=Ct(t,e,n),s=o.type;if(s==="tool_execution_start"){let m=o.toolCallId,d=o.toolName;return typeof m!="string"||typeof d!="string"?[]:[{...r,kind:"tool_use",toolUseId:`${t}:${m}`,name:d,input:o.args??{}}]}if(s==="tool_execution_end")return It(r,o);let i=N(o);if(!i||i.role!=="assistant")return[];let c=typeof i.model=="string"?i.model:r.model,a=P(i);return a?[{...r,model:c,kind:"assistant_text",text:a}]:[]}function It(t,e){let n=e.toolCallId;if(typeof n!="string")return[];let o=T(e.result?.content);return[{...t,kind:"tool_result",toolUseId:`${t.ref}:${n}`,ok:e.isError!==!0,content:kt(e.result),...o.length?{images:o}:{}}]}function N(t){return t.type!=="message_end"||!t.message||typeof t.message!="object"?null:t.message}function P(t){let e=t.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>!!n&&typeof n=="object"&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join(`
5
+ `):""}function kt(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return"";let e=t.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>n&&typeof n=="object"&&n.type==="text").map(n=>String(n.text??"")).join(""):""}function Ne(t,e,n,o){return{ref:t,type:e.subagent_type,description:e.description,model:null,backend:n,kind:"end",status:o}}function xt(t){let e=t.name;return t.backend==="claude"?e:_("pi",e)??e}function q(t){if(t.kind==="end")return t.status?[{type:"subagent_end",parentToolUseId:t.ref,status:t.status}]:[];let e={parentToolUseId:t.ref,type:t.type||null,description:t.description||null,...t.prompt?{prompt:t.prompt}:{},model:t.model,...t.clean?{clean:!0}:{}};return t.kind==="tool_use"?[{type:"tool_use",toolUseId:t.toolUseId,name:xt(t),input:t.input??{},subagent:e}]:t.kind==="tool_result"?[{type:"tool_result",toolUseId:t.toolUseId,ok:t.ok!==!1,content:t.content??"",subagent:e,...t.images?.length?{images:t.images}:{}}]:[{type:"assistant_text",text:t.text,subagent:e}]}var Ot=new Set(["pending","in_progress","completed"]);function tt(t){return typeof t=="string"?t:""}function At(t){return typeof t=="string"&&Ot.has(t)?t:"pending"}function St(t){if(!t||typeof t!="object")return null;let e=t,n=tt(e.content).trim(),o=tt(e.activeForm).trim()||n;return!n&&!o?null:{content:n||o,activeForm:o,status:At(e.status)}}function bt(t,e=Date.now()){if(!t||typeof t!="object")return null;let n=t.todos;if(!Array.isArray(n))return null;let o=[];for(let i of n){let c=St(i);c&&o.push(c)}let r=0,s=null;for(let i of o)i.status==="completed"?r+=1:i.status==="in_progress"&&s===null&&(s=i.activeForm);return{items:o,total:o.length,completed:r,activeLabel:s,updatedAt:e}}function et(t,e,n,o=Date.now()){return _(t,e)!=="todo_write"?null:bt(n,o)}function Ue(t,e=40){if(!t||t.total===0)return"";let n=`${t.completed}/${t.total}`,o=t.activeLabel?.trim();if(!o)return n;let r=o.length>e?`${o.slice(0,e-1).trimEnd()}\u2026`:o;return`${n} \xB7 ${r}`}function je(){return{turnProgressCount:0,pendingCompletion:D()}}function $e(t,e){let n=t;if(typeof n.type!="string")return[];let o=n.type;if(o==="message_update")return wt(n);if(o==="tool_execution_start")return Dt(n);if(o==="tool_execution_end")return Ut(n);if(o==="agent_end")return Lt(n,e);if(o==="agent_settled")return Xt(e);if(o==="compaction_start")return[{type:"context_compacted",trigger:typeof n.reason=="string"&&n.reason.length>0?n.reason:"auto"}];if(o==="message_end")return e.turnProgressCount++,[{type:"turn_progress",numTurns:e.turnProgressCount}];if(o==="cortex_subagent_event"){let r=Vt(n.notice);return r?q(r):[]}if(o==="cortex_subagent_usage")return Ht(n.report,e);if(o==="auto_retry_start")return Pt(n);if(o==="extension_error"){let r=n.error;return[{type:"error",message:typeof r=="string"&&r.length>0?r:"extension error",fatal:!1}]}return o==="extension_ui_request"?zt(n):[]}function R(t){return t!==null&&typeof t=="object"?t:void 0}function ot(t){let e=R(t),n=e?.id??e?.responseId;return typeof n=="string"?n:void 0}function nt(t,e){let n=R(t)?.content;return!Array.isArray(n)||typeof e!="number"?!1:R(n[e])?.redacted===!0}function Nt(t,e){let n=e.redacted===!0||nt(t.message,e.contentIndex)||nt(e.partial,e.contentIndex),o=e.type==="thinking_end"?e.content:e.delta;if(n||typeof o!="string"||o.length===0)return[];let r=ot(t.message),s=r!==void 0&&typeof e.contentIndex=="number"?`${r}:t${e.contentIndex}`:void 0;return e.type==="thinking_end"?[{type:"assistant_thinking",text:o,...s!==void 0?{blockId:s}:{}}]:s!==void 0?[{type:"assistant_thinking_delta",text:o,blockId:s}]:[]}function Pt(t){let e=t.attempt;if(typeof e!="number")return[];let n=typeof t.errorMessage=="string"?t.errorMessage:null;return[{type:"api_retry",attempt:e,error:n}]}function wt(t){let e=R(t.assistantMessageEvent);if(!e)return[];if(e.type==="thinking_delta"||e.type==="thinking_end")return Nt(t,e);if(e.type!=="text_delta"||typeof e.delta!="string"||e.delta.length===0)return[];let n=ot(t.message);return[{type:"assistant_text",text:e.delta,...n!==void 0?{blockId:n}:{}}]}function Dt(t){let e=t.toolCallId,n=t.toolName,o=t.args??{};if(typeof e!="string"||typeof n!="string")return[];let r=_("pi",n)??n,s=[{type:"tool_use",toolUseId:e,name:r,input:o}],i=et("pi",n,o);return i&&s.push({type:"todo_update",toolUseId:e,snapshot:i}),s}function Ut(t){let e=t.toolCallId;if(typeof e!="string")return[];let n=t.isError===!0,o=t.result,r="",s=[];if(o&&typeof o=="object"){let c=o.content;Array.isArray(c)?(r=c.filter(a=>l(a).type==="text").map(a=>String(l(a).text??"")).join(""),s=T(c)):typeof c=="string"&&(r=c)}return[{type:"tool_result",toolUseId:e,ok:!n,content:r,...s.length?{images:s}:{}}]}function rt(t,e){if(t.type!=="tool_execution_end"||!e?.input||e.input.includes("image"))return t;let n=l(t.result),o=n.content;return!Array.isArray(o)||!o.some(r=>l(r).type==="image")?t:{...t,result:{...n,content:o.filter(r=>l(r).type!=="image")}}}function D(){return{numTurns:0,totalCostUsd:null,error:null}}function Mt(){return{...D(),provider:"",model:"",tokensIn:0,tokensOut:0,cacheReadTokens:0,cacheWriteTokens:0,inputReported:!0,outputReported:!0,cacheReadReported:!0,cacheWriteReported:!0}}function Lt(t,e){let n=Array.isArray(t.messages)?t.messages:[],o=Wt(n);if(Kt(e,o),o.provider==="")return[];let r=C(o.tokensIn,o.inputReported),s=C(o.tokensOut,o.outputReported),i=C(o.cacheReadTokens,o.cacheReadReported),c=C(o.cacheWriteTokens,o.cacheWriteReported),a=vt(r,i,c);return[{type:"cost_record",provider:o.provider,model:o.model,tokens_in:o.tokensIn,tokens_out:o.tokensOut,prompt_tokens:a,cached_tokens:i,input_tokens:r,output_tokens:s,cache_read_tokens:i,cache_creation_tokens:c,provider_requests:o.numTurns>0?o.numTurns:null,cost_usd:o.totalCostUsd}]}function Xt(t){let e=t.pendingCompletion;t.pendingCompletion=D();let n={type:"turn_complete",numTurns:e.numTurns,totalCostUsd:e.totalCostUsd};return e.error===null?[n]:[{...n,error:e.error}]}function Wt(t){let e=Mt();for(let n of t){let o=l(n);o.role==="assistant"&&(e.numTurns++,Ft(e,o),jt(e,o),Bt(e,o))}return e}function Ft(t,e){let n=e.provider,o=e.model;t.provider===""&&typeof n=="string"&&n.length>0&&(t.provider=n),t.model===""&&typeof o=="string"&&o.length>0&&(t.model=o)}function jt(t,e){if(t.error!==null||e.stopReason!=="error")return;let n=e.errorMessage;t.error=typeof n=="string"&&n.length>0?n:"PI agent reported an error during execution"}function $t(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function h(t,e,n){return $t(n)?[t+n,e]:[t,!1]}function Bt(t,e){let n=l(e.usage);[t.tokensIn,t.inputReported]=h(t.tokensIn,t.inputReported,n.input),[t.tokensOut,t.outputReported]=h(t.tokensOut,t.outputReported,n.output),[t.cacheReadTokens,t.cacheReadReported]=h(t.cacheReadTokens,t.cacheReadReported,n.cacheRead),[t.cacheWriteTokens,t.cacheWriteReported]=h(t.cacheWriteTokens,t.cacheWriteReported,n.cacheWrite);let o=l(n.cost).total;typeof o=="number"&&isFinite(o)&&(t.totalCostUsd=(t.totalCostUsd??0)+o)}function C(t,e){return e?t:null}function vt(...t){return t.some(e=>e===null)?null:t.reduce((e,n)=>e+n,0)}function Kt(t,e){let n=t.pendingCompletion;n.numTurns+=e.numTurns,n.totalCostUsd=st(n.totalCostUsd,e.totalCostUsd),n.error=e.error}function st(t,e){return t===null&&e===null?null:(t??0)+(e??0)}function Ht(t,e){let n=l(t),o=n.provider;if(typeof o!="string"||o==="")return[];let r=l(n.usage),s=E(r.input),i=E(r.output),c=E(r.cacheRead),a=E(r.cacheWrite),m=E(r.turns),d=w(r.cost);e.pendingCompletion.totalCostUsd=st(e.pendingCompletion.totalCostUsd,d);let f=n.model,O=n.connection;return[{type:"cost_record",provider:o,connection:typeof O=="string"&&O!==""?O:o,model:typeof f=="string"?f:"",tokens_in:s,tokens_out:i,prompt_tokens:s+c+a,cached_tokens:c,input_tokens:s,output_tokens:i,cache_read_tokens:c,cache_creation_tokens:a,provider_requests:m>0?m:null,cost_usd:d}]}function Gt(t){return t==="completed"||t==="failed"||t==="killed"}function Vt(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,{ref:n,kind:o}=e;if(typeof n!="string"||!n||o!=="tool_use"&&o!=="tool_result"&&o!=="assistant_text"&&o!=="end")return null;let r={ref:n,kind:o,type:typeof e.type=="string"?e.type:"",description:typeof e.description=="string"?e.description:"",...typeof e.prompt=="string"?{prompt:e.prompt}:{},model:typeof e.model=="string"?e.model:null};if(o==="tool_use")return typeof e.name!="string"||typeof e.toolUseId!="string"?null:(r.name=e.name,r.toolUseId=e.toolUseId,r.input=e.input??{},r);if(o==="tool_result"){if(typeof e.toolUseId!="string")return null;r.toolUseId=e.toolUseId,r.ok=e.ok!==!1,r.content=typeof e.content=="string"?e.content:"";let s=Array.isArray(e.images)?e.images.filter(Z):[];return s.length&&(r.images=s),r}return o==="end"?Gt(e.status)?(r.status=e.status,r):null:typeof e.text!="string"||!e.text?null:(r.text=e.text,r)}function zt(t){let e=t.id,n=t.method;if(typeof e!="string"||typeof n!="string")return[];if(n!=="select"&&n!=="confirm"&&n!=="input"&&n!=="editor")return[];let o=t.title,r=typeof o=="string"&&o.length>0?o:`${n} request`,s;if(n==="select"){let i=t.options,c=Array.isArray(i)?i.map(String):void 0;s={question:r},c&&(s.options=c)}else if(n==="confirm"){let i=t.message,c=typeof i=="string"&&i.length>0?`: ${i}`:"";s={question:r+c,options:["Yes","No"]}}else n==="editor"?s={question:r,multi:!0}:s={question:r};return[{type:"ask_user_question",toolUseId:e,questions:[s]}]}function Be(t,e=null){let n=l(l(t).contextUsage),o=n.contextWindow;if(typeof o!="number"||!Number.isFinite(o)||o<=0)return null;let r=w(n.tokens);if(e===null||o<=e){let i=w(n.percent);return{usedTokens:r,contextWindow:o,percent:i,accuracy:"estimate"}}let s=r===null?null:r/e*100;return{usedTokens:r,contextWindow:e,percent:s,accuracy:"estimate"}}function E(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):0}function w(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function l(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function it(t){return t??"direct"}var ct="CORTEX_PI_MCP_COMPOSITION",I="CORTEX_PI_INTERACTION_BRIDGE",k="CORTEX_PI_TEAM_LEAD",x="CORTEX_PI_TEAM_WORKER",at="CORTEX_PI_CLEAN_WORKSPACE",ut="CORTEX_PI_HOME_AGENT_DIR",Jt=["SLACK_CHANNEL","FEISHU_CHANNEL","CORTEX_SESSION_ID","CORTEX_PROFILE","CORTEX_MODE","CORTEX_BACKEND","CORTEX_MODEL","CORTEX_PROVIDER","CORTEX_THINKING","CORTEX_CONNECTION","CORTEX_PROJECT","CORTEX_SESSION_NAME","CORTEX_EXECUTION_ID","CORTEX_CALLBACK_SOURCE","CORTEX_SCHEDULE_TASK_ID","CORTEX_CONFIG_IMMUTABLE","CORTEX_PRODUCTION_AUTH_FILE","CORTEX_WEBHOOK_BENCHMARK_ONLY","CORTEX_PI_ALLOWED_TOOLS","CORTEX_PI_SUBAGENT",ct,I,k,x,at,ut,A];function u(t,e,n){n!=null&&n!==""&&(t[e]=String(n))}function Yt(t,e){let n=e.context;u(t,"CORTEX_MODEL",n?.selection?.model),u(t,"CORTEX_PROVIDER",n?.selection?.provider),u(t,"CORTEX_THINKING",n?.selection?.thinking),u(t,"CORTEX_CONNECTION",n?.selection?.connection),u(t,"CORTEX_SESSION_ID",n?.trackSessionId??e.sessionId),u(t,"CORTEX_CALLBACK_SOURCE",e.callbackSource),u(t,"CORTEX_SCHEDULE_TASK_ID",e.scheduleTaskId),u(t,"CORTEX_PROJECT",n?.project),u(t,"CORTEX_EXECUTION_ID",n?.executionId)}function Qt(t,e=process.env){let n={...e,...t.routeEnv??{}};for(let o of Jt)delete n[o];for(let o of t.unsetEnv??[])delete n[o];return n.PI_CODING_AGENT_DIR=t.piAgentDir,t.piHomeAgentDir&&t.piHomeAgentDir!==t.piAgentDir&&(n[ut]=t.piHomeAgentDir),n.CORTEX_BACKEND="pi",t.channel&&(n.SLACK_CHANNEL=t.channel,n.FEISHU_CHANNEL=t.channel),u(n,"CORTEX_PI_ALLOWED_TOOLS",t.allowedTools),u(n,ct,t.mcpComposition),t.mcpToolAllowlist!==void 0&&t.mcpToolAllowlist!==null&&(n[A]=JSON.stringify(t.mcpToolAllowlist)),t.enableInteractionBridge===!0&&(n[I]="1"),t.enableTeamLead===!0&&(n[k]="1"),t.enableTeamWorker===!0&&(n[x]="1"),u(n,"CORTEX_PI_SUBAGENT",t.subagentMarker),u(n,at,t.cleanWorkspace),Yt(n,t),n}function Zt(t){return t.replace(/\[.*?\]$/,"")}function qt(t){return t?(Array.isArray(t)?t:[t]).filter(e=>e.length>0):[]}function te(t){let e=t.tools.canonical&&t.tools.canonical.length>0?t.tools.canonical.map(n=>$("claude",n)).filter(n=>!!n).join(","):void 0;return t.tools.rawClaude??e}function ee(t){return t.env.sets?.CORTEX_PI_SUBAGENT==="1"?"1":void 0}function ne(t,e){return e!=="direct"?[]:[...t.mcp.servers??[]]}function ze(t,e){let n=it(t.mcp.composition),o=ee(t),r=Qt({sessionId:t.resume.backendSessionId,channel:t.context.channel,callbackSource:t.context.callbackSource,scheduleTaskId:t.context.scheduleTaskId,routeEnv:t.env.sets,unsetEnv:t.env.unsets,context:t.env.context,piAgentDir:e.agentDir,piHomeAgentDir:e.homeAgentDir,allowedTools:te(t),mcpComposition:n,mcpToolAllowlist:t.mcp.allowlist,enableInteractionBridge:n==="direct"&&t.flags.isUserInitiated===!0&&o===void 0,enableTeamLead:n==="direct"&&t.flags.teamLead===!0&&o===void 0,enableTeamWorker:n==="direct"&&t.flags.teamWorker===!0&&o===void 0,subagentMarker:o,cleanWorkspace:t.flags.clean?e.cwd:null},t.env.pinned);return{sessionKey:t.engineKey,cwd:e.cwd,agentDir:e.agentDir,sessionDir:e.sessionDir,sessionPath:e.sessionPath,provider:t.model.provider??null,model:t.model.id?Zt(t.model.id):null,benchmarkMaxOutputTokens:t.model.benchmarkMaxOutputTokens,thinking:t.model.thinking??null,systemPrompt:t.prompt.system||null,appendSystemPrompt:qt(t.prompt.append),skillPaths:t.flags.disableSkills?[]:[...t.plugins.skillDirs??[],...t.plugins.dirs??[]],disableHooks:t.flags.disableHooks===!0,...t.flags.clean?{noContextFiles:!0}:{},reportsProviderQuota:!0,pluginMcpServers:ne(t,n),env:r,streamDeltas:e.streamDeltas}}var oe=new Set(["CORTEX_EXECUTION_ID"]);function Je(t){let{sessionPath:e,env:n,...o}=t,r=Object.entries(n).filter(([s])=>!oe.has(s)).sort(([s],[i])=>s<i?-1:s>i?1:0);return JSON.stringify({...o,env:r})}import{existsSync as re,mkdirSync as U,readFileSync as se,promises as y}from"node:fs";import*as pt from"node:os";import*as p from"node:path";var dt="inputs",lt="clean-workspace.md";function tn(t){return t?.clean===!0&&t.workspaceDir?t.workspaceDir:null}function en(t,e=X){U(e,{recursive:!0});for(let n=1;;n++){let o=p.join(e,n===1?t:`${t}-${n}`);if(ie(o))return U(p.join(o,dt)),o}}function ie(t){try{return U(t),!0}catch(e){if(e.code==="EEXIST")return!1;throw e}}async function nn(t,e,n){let o=p.join(t,dt);await y.mkdir(o,{recursive:!0});let r=B(n||p.basename(e)),s=p.join(o,r);if(await ce(e,s))return s;let{destPath:i}=await v(o,r);return await y.cp(e,i,{recursive:!0}),i}async function ce(t,e){let[n,o]=await Promise.all([y.stat(t).catch(()=>null),y.stat(e).catch(()=>null)]);if(!n?.isFile()||!o?.isFile()||n.size!==o.size)return!1;let[r,s]=await Promise.all([y.readFile(t),y.readFile(e)]);return r.equals(s)}function on(t,e){let n=t==="~"||t.startsWith("~/")?p.join(pt.homedir(),t.slice(1)):t;return p.resolve(e,n)}function ft(t){let e=p.join(W,lt),n=re(e)?e:p.join(L,"prompts",lt);return se(n,"utf8").replaceAll("{{workspace}}",t).trim()}function ae(t,e){let n={...t,PI_CODING_AGENT_DIR:e,CORTEX_PI_SUBAGENT:"1"};return delete n[I],delete n[k],delete n[x],n}async function fn(t){let{task:e,role:n}=t,o=t.model??{},r=t.createSession??Q,s=t.workspace??null,i=await r({cwd:s??t.cwd,agentDir:t.agentDir,provider:o.provider??null,model:o.model??null,thinking:o.thinking??null,tools:H(n,"pi"),appendSystemPrompt:[...n.systemPrompt?[n.systemPrompt]:[],...s?[ft(s)]:[]],...s?{noContextFiles:!0}:{},extensions:t.childExtensions(ae(t.parentEnv,t.agentDir),o.provider??null)});try{let c=await ue(i,e,t.signal,t.forward);return c.model||(c.model=o.model),c}finally{i.dispose()}}async function ue(t,e,n,o){if(n?.aborted)throw new Error("Subagent was aborted.");let r={output:"",usage:S()},s=t.session.subscribe(c=>{pe(r,rt(c,t.session.model),o)}),i=()=>{t.session.abort().catch(()=>{})};n?.addEventListener("abort",i,{once:!0});try{await t.session.prompt(`Task: ${e.prompt}`)}finally{n?.removeEventListener("abort",i),s()}if(n?.aborted)throw new Error("Subagent was aborted.");return le(e,r)}function le(t,e){return{description:t.description,prompt:t.prompt,subagentType:t.subagent_type,output:e.output,usage:e.usage,model:e.model,provider:e.provider,backend:"pi",stopReason:e.stopReason,errorMessage:e.errorMessage}}function pe(t,e,n){if(n)try{n(e,t)}catch{}let o=N(e);o&&(de(t,o),me(t,o))}function de(t,e){if(e.role!=="assistant")return;let n=e.usage,o=n?.cost;z(t.usage,{input:g(n?.input),output:g(n?.output),cacheRead:g(n?.cacheRead),cacheWrite:g(n?.cacheWrite),cost:g(o?.total),contextTokens:g(n?.totalTokens),turns:1})}function M(t,e){return typeof t=="string"?t:e}function fe(t,e){let n=typeof e.stopReason=="string"?e.stopReason:void 0;if(!n){t.errorMessage=M(e.errorMessage,t.errorMessage);return}t.stopReason=n,t.errorMessage=typeof e.errorMessage=="string"?e.errorMessage:void 0}function me(t,e){e.role==="assistant"&&(t.output=P(e)||t.output,t.model=M(e.model,t.model),t.provider=M(e.provider,t.provider),fe(t,e))}export{bt as a,et as b,Ue as c,it as d,T as e,Ne as f,q as g,je as h,$e as i,rt as j,Be as k,ct as l,I as m,k as n,x as o,at as p,ut as q,ze as r,Je as s,J as t,Q as u,S as v,ge as w,Ae as x,Rt as y,tn as z,en as A,nn as B,on as C,ft as D,ae as E,fn as F,le as G};
@@ -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{d as ae}from"./chunk-RA2BUYI3.js";import{a as de,b as fe,d as pe}from"./chunk-U23S37TT.js";import{f as g,h as M}from"./chunk-T73GHMFB.js";import{a as D}from"./chunk-OKRK6JPY.js";import{a as ue,f as le}from"./chunk-VK5J556O.js";import{a,b as _,d as ie,e as ce,f as C,g as x,h as se,j as f,l as T,m as P,o as Y}from"./chunk-TX46YMGI.js";import{c as te}from"./chunk-AVXDF7AG.js";import{e as m}from"./chunk-VBN2JSER.js";import{i as w,k as N,l as re,m as oe}from"./chunk-Z24SBRJK.js";import{a as We}from"./chunk-VPVSKJGX.js";import{e as qe}from"./chunk-WHC7AYZD.js";import*as Te from"node:path";var he=qe(We(),1);import{execFile as Qe,execFileSync as Je}from"child_process";import{createHash as Ze}from"crypto";import{readFileSync as en}from"fs";import*as L from"path";var nn="oauth-2025-04-20",ke="2023-06-01",tn=6e4,rn=2e3,on=5e3;function G(e,n){try{return e(n)}catch{return null}}function z(e){return e.readFile??(n=>en(n,"utf8"))}function v(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n==="undefined"||n==="null"))return n}function cn(e){let n=G(e,L.join(w,".env"));if(n===null)return{};try{return(0,he.parse)(n)}catch{return{}}}function sn(e={}){let n=cn(z(e)),t=v(n.CLAUDE_CODE_OAUTH_TOKEN);return{ANTHROPIC_API_KEY:v(n.ANTHROPIC_API_KEY),ANTHROPIC_BASE_URL:v(n.ANTHROPIC_BASE_URL),CLAUDE_CODE_OAUTH_TOKEN:t,CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT:t?v(n.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT):void 0}}function un(e={}){return x(f(e.connectionsFile??a)).find(n=>!n.baseUrl&&n.authStyle==="x-api-key")??null}function ln(e){return{"x-api-key":e,"anthropic-version":ke}}function R(e){return{authorization:`Bearer ${e}`,"anthropic-beta":nn,"anthropic-version":ke}}function X(e={}){return e.claudeConfigDir??N}function an(e={}){return L.join(X(e),".credentials.json")}function y(e){return typeof e=="string"&&e.trim()?e.trim():null}function me(e){return typeof e!="number"||!Number.isFinite(e)||Number.isNaN(new Date(e).getTime())?null:e}function ge(e){let n;try{n=JSON.parse(e)?.claudeAiOauth}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let t=n,r={accessToken:y(t.accessToken),refreshToken:y(t.refreshToken),expiresAt:me(t.expiresAt),refreshExpiresAt:me(t.refreshTokenExpiresAt)};return r.accessToken||r.refreshToken?r:null}function ve(e={}){let n=G(z(e),an(e));return n===null?null:ge(n)}function ye(e,n){if(!e?.accessToken)return null;let t=(n.now??Date.now)();return e.expiresAt!==null&&e.expiresAt-tn<=t?null:e.accessToken}function Ae(e){return ye(ve(e),e)}function Ut(e={}){let n=Ae(e);return n?R(n):null}function _e(e){let n=G(z(e),L.join(X(e),".claude.json"));if(n===null)return null;try{let t=JSON.parse(n)?.oauthAccount;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Ht(e={}){return y(_e(e)?.organizationUuid)}function Ft(e={}){let n=_e(e);return n?{email:y(n.emailAddress),organization:y(n.organizationName),plan:y(n.organizationType)??y(n.billingType)}:null}function A(e={}){if(q(e))return{source:"claude-store",token:null};let n=v((e.env??process.env).CLAUDE_CODE_OAUTH_TOKEN);if(n)return{source:"env-oauth-token",token:n};let t=sn(e).CLAUDE_CODE_OAUTH_TOKEN;return t?{source:"dotenv-oauth-token",token:t}:null}function Ce(e={}){let n=un(e);if(n)return{headers:ln(n.key),source:"connection-api-key"};let t=A(e);if(!t)return null;if(t.source!=="claude-store")return{headers:R(t.token),source:t.source};let r=Ae(e);return r?{headers:R(r),source:"claude-credentials"}:null}function Ee(e={}){return`Claude Code-credentials-${Ze("sha256").update(X(e).normalize("NFC")).digest("hex").slice(0,8)}`}function dn(e){try{return Je("security",["find-generic-password","-s",e],{stdio:"ignore",timeout:rn}),!0}catch{return!1}}function fn(e){return new Promise(n=>{try{Qe("security",["find-generic-password","-s",e,"-w"],{encoding:"utf8",timeout:on},(t,r)=>n(t?null:r.trim()||null))}catch{n(null)}})}async function be(e={}){if((e.platform??process.platform)!=="darwin")return null;let r=await(e.readKeychain??fn)(Ee(e)),o=ye(r===null?null:ge(r),e);return o?{headers:R(o),source:"claude-keychain"}:null}function q(e={}){return ve(e)?!0:(e.platform??process.platform)!=="darwin"?!1:(e.probeKeychain??dn)(Ee(e))}var pn=Te.join(w,".env"),E="api";function Oe(){return x(f()).find(e=>e.id===E)??null}function Yt(){return[Oe()?.key,A()?.token].filter(e=>!!e)}function mn(e){let n=v(e);if(!n||/[\s"\\]/.test(n))throw new Error("Enter a valid Anthropic API key.");return n}function hn(e,n){return new RegExp(`^[ \\t]*(?:export[ \\t]+)?${e}[ \\t]*=.*$`,n)}function kn(e,n){let t=hn(n,"gm");return e.replace(new RegExp(`${t.source}(?:\\r?\\n|$)`,"gm"),"")}async function Ie(e){await te(pn,n=>e.reduce(kn,n),{mode:384})}async function Gt(e){let n=mn(e),t=Oe();T(t?{...t,key:n}:{id:E,backend:"claude",label:E,authStyle:"x-api-key",key:n,billing:"metered"})}async function zt(){P({backend:"claude",id:E}),await Ie(["ANTHROPIC_API_KEY"])}async function Xt(){await Ie(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT"]),delete process.env.CLAUDE_CODE_OAUTH_TOKEN,delete process.env.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT}var gn=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL"];function qt(e=process.env){for(let n of gn)delete e[n];A()?.source==="claude-store"&&(delete e.CLAUDE_CODE_OAUTH_TOKEN,delete e.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT)}import Se from"node:fs";import U from"node:path";var vn=32,yn=[_,E];function An(e,n){let r=e.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").slice(0,vn).replace(/-+$/,"")||"account";if(!n.has(r))return r;for(let o=2;;o++)if(!n.has(`${r}-${o}`))return`${r}-${o}`}function _n(e,n){let t=f(n.file??a).map(o=>o.id),r=[...yn,e.provider?.trim()??"",...n.reservedIds??[]];return new Set([...t,...r].filter(Boolean))}function Cn(e){let n=[];return e.label.trim()||n.push("label-required"),e.backend==="pi"&&!e.provider?.trim()&&n.push("provider-required"),n}function En(e,n){let t=e.label.trim();return e.backend==="claude"?{id:n,backend:"claude",type:"account",label:t,pending:!0}:{id:n,backend:"pi",type:"account",label:t,provider:e.provider.trim(),pending:!0}}function Zt(e,n={}){let t=Cn(e);if(t.length>0)return{ok:!1,errors:t};let r=En(e,An(e.label.trim(),_n(e,n)));try{T(r,n.file??a)}catch{return{ok:!1,errors:["write-failed"]}}return{ok:!0,account:r}}function O(e,n=a){let t=f(n).find(r=>r.backend===e.backend&&r.id===e.id);return t&&C(t)?t:null}function er(e,n=a){let t=O(e,n);if(!t?.pending)return;let{pending:r,...o}=t;T(o,n)}function nr(e,n=a){return O(e,n)?P(e,n):!1}function tr(e=a){return f(e).filter(n=>C(n)&&!!n.pending)}function bn(e,n={}){let t=M(e,n.accountsDir);return Se.mkdirSync(t,{recursive:!0,mode:448}),ae({agentDir:t}),t}function fr(e,n={}){Se.rmSync(M(e,n.accountsDir),{recursive:!0,force:!0})}function Tn(e,n={}){return g(M(e,n.accountsDir))}function we(e,n={}){return fe(Tn(e.id,n),e.provider)}function pr(e,n={}){if(e.backend!=="pi"||!e.connection)return;let t=O({backend:"pi",id:e.connection},n.file??a);if(!(t?.backend!=="pi"||t.pending||t.provider!==e.provider))return{connection:t.id,agentDir:bn(t.id,n)}}function mr(e,n={}){let t=U.resolve(e);if(U.dirname(t)!==U.resolve(n.accountsDir??oe))return null;let r=O({backend:"pi",id:U.basename(t)},n.file??a);return r?.backend==="pi"?r:null}function Ne(e){return new Promise(n=>{setTimeout(n,e).unref?.()})}var b=class{options;entries=[];nextRefreshAt=0;inFlight=null;refreshQueued=!1;now;constructor(n){this.options=n,this.now=n.now??Date.now}peek(){let n=this.options.clone;return n?this.entries.map(n):[...this.entries]}get(){let n=this.peek();return this.now()>=this.nextRefreshAt&&!this.inFlight&&this.startRefresh(),n}async ensure(n){if(this.entries.length>0)return this.get();!this.inFlight&&this.now()>=this.nextRefreshAt&&this.startRefresh();let t=this.inFlight;return t&&await Promise.race([t,Ne(n)]),this.peek()}async settle(n){this.refresh();let t=!1,r=Ne(n).then(()=>{t=!0});for(;this.inFlight&&!t;)await Promise.race([this.inFlight,r]);return this.peek()}refresh(){if(!this.inFlight){this.startRefresh();return}this.refreshQueued=!0}startRefresh(){let n=Promise.resolve().then(this.options.scan).then(t=>this.accept(t)).catch(t=>this.reject(t)).finally(()=>this.finishRefresh(n));this.inFlight=n}finishRefresh(n){this.inFlight===n&&(this.inFlight=null,this.refreshQueued&&(this.refreshQueued=!1,this.startRefresh()))}accept(n){let{key:t,clone:r}=this.options,o=new Set,i=[];for(let c of n){if(t){let s=t(c);if(o.has(s))continue;o.add(s)}i.push(r?r(c):c)}this.entries=i,this.nextRefreshAt=this.now()+this.options.cacheTtlMs}reject(n){this.nextRefreshAt=this.now()+this.options.retryMs;let t=n instanceof Error?n.message:"unknown";this.options.logFailure?.(t)}};import*as xe from"node:path";var On=["off","minimal","low","medium","high","xhigh","max"];function In(e){let n=e;if(!n||typeof n!="object"||!("reasoning"in n)&&!("thinkingLevelMap"in n))return;if(!n.reasoning)return[];let t=n.thinkingLevelMap;return On.filter(r=>{let o=t?.[r];return o===null?!1:r==="xhigh"||r==="max"?o!==void 0:!0})}async function Pe(e){let{ModelRuntime:n}=await ue(),t=await n.create({authPath:e.authPath,modelsPath:e.modelsPath,allowModelNetwork:!1});return e.agentDir&&await pe(t,e.agentDir),(await t.getAvailable()).map(o=>{let i=In(o);return{provider:o.provider,model:o.id,...i?{thinkingLevels:i}:{}}})}function W(){return Pe({authPath:g(),modelsPath:le()})}function Ar(e){return Pe({authPath:g(e),modelsPath:xe.join(e,"models.json"),agentDir:e})}var Sn=m("pi-adapter"),wn=5*6e4,Nn=3e4,De=12e3;function xn(e={}){let n=new b({scan:e.scan??W,now:e.now,cacheTtlMs:e.cacheTtlMs??wn,retryMs:e.retryMs??Nn,key:r=>`${r.provider}\0${r.model}`,clone:r=>({...r}),logFailure:r=>Sn.info(`PI provider refresh failed: ${r}`)}),t=()=>n.get();return{getProviders:()=>Array.from(new Set(t().map(r=>r.provider))),getModels:t,peekModels:()=>n.peek(),ensureModels:(r=De)=>n.ensure(r),refresh:()=>n.refresh(),rescan:(r=De)=>n.settle(r)}}var Me=W;function Tr(e){Me=e}var H=xn({scan:()=>Me()});function I(e){return JSON.stringify([e.backend,e.provider,e.model])}var F={claude:["low","medium","high","xhigh","max"],pi:["off","minimal","low","medium","high","xhigh","max"]};function Pn(e,n){return F[e]?.includes(n)??!1}var Re=/^[a-zA-Z0-9_-]+$/;function Dn(e){let n=e;if(!n||n.backend!=="claude"&&n.backend!=="pi")throw new Error("Invalid backend");if(typeof n.model!="string"||!n.model.trim())throw new Error("Model must be a non-empty string");if(!(n.backend==="claude"?n.provider===null:typeof n.provider=="string"&&Re.test(n.provider)))throw new Error("Invalid provider: PI requires a provider; Claude requires null")}function Ir(e){Dn(e);let n=e;if(n.thinking!==null&&!Pn(n.backend,n.thinking))throw new Error(`Invalid thinking for backend '${n.backend}'`);Mn(n)}function Mn(e){let{backend:n,connection:t}=e;if(t!==null){if(t===void 0)throw new Error("Invalid connection: a selection must name one, or null for the default");if(typeof t!="string"||!Re.test(t))throw new Error("Invalid connection")}}function Sr(e){let{backend:n,provider:t,model:r,thinking:o}=e;return{backend:n,provider:t,model:r,thinking:o,connection:e.connection??null}}import d from"node:fs";import p from"node:path";var Rn=m("claude-account-dir"),Ln=new Set([".credentials.json",".claude.json","backups"]),Un=["projects"],Le="settings.json";function K(e,n={}){if(!ie.test(e))throw new Error(`Invalid account id: ${e}`);return p.join(n.accountsDir??re,e)}function Hn(e){try{return d.lstatSync(e)}catch{return null}}function Fn(e){try{return p.resolve(p.dirname(e),d.readlinkSync(e))}catch{return null}}function Kn(e,n){let t=Hn(n);return t?t.isSymbolicLink()?Fn(n)===e?!1:(d.unlinkSync(n),!0):p.basename(n)!==Le?!1:(d.rmSync(n,{force:!0}),!0):!0}function $n(e,n,t,r){if(!Kn(e,n))return;let o=t?r==="win32"?"junction":"dir":"file";try{d.symlinkSync(e,n,o)}catch(i){p.basename(n)===Le?d.copyFileSync(e,n):Rn.warn(`Could not link ${n}: ${i.message}`)}}function jn(e){for(let n of d.readdirSync(e,{withFileTypes:!0})){let t=p.join(e,n.name);n.isSymbolicLink()&&!d.existsSync(t)&&d.unlinkSync(t)}}function Rr(e,n={}){let t=K(e,n),r=n.sharedDir??N,o=n.platform??process.platform;d.mkdirSync(t,{recursive:!0,mode:448});for(let i of Un)d.mkdirSync(p.join(r,i),{recursive:!0});jn(t);for(let i of d.readdirSync(r,{withFileTypes:!0}))Ln.has(i.name)||$n(p.join(r,i.name),p.join(t,i.name),i.isDirectory(),o);return t}function Lr(e,n={}){let t=K(e,n),r;try{r=d.readdirSync(t,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(let o of r)o.isSymbolicLink()&&d.unlinkSync(p.join(t,o.name));d.rmSync(t,{recursive:!0,force:!0})}function Vn(){return{id:_,backend:"claude",provider:null,kind:"subscription",label:"Claude subscription",baseUrl:null,billing:"subscription",authenticated:!0,keyHint:null,models:null}}function Bn(e){return{id:e.id,backend:"claude",provider:null,kind:"key",label:e.label,baseUrl:e.baseUrl??null,authStyle:e.authStyle,billing:e.billing,authenticated:!0,keyHint:Y(e.key),models:e.models??null}}function Yn(e){return{id:e.id,backend:"claude",provider:null,kind:"account",label:e.label,baseUrl:null,billing:"subscription",authenticated:!0,keyHint:null,models:null}}function Gn(e){let n=ce(e);return{id:e.id,backend:"pi",provider:e.provider,kind:n?"custom":"override",label:e.label??e.provider,baseUrl:e.baseUrl,...n?{api:e.api}:{},billing:"metered",authenticated:n?!0:!!e.key,keyHint:Y(e.key),models:n?e.models.map(t=>t.id):null}}function zn(e,n){return{id:e.id,backend:"pi",provider:e.provider,kind:"account",label:e.label,baseUrl:null,billing:Jn(e.provider,n),authenticated:!0,keyHint:null,models:null}}function Xn(e,n){let t=[];for(let r of n){if(r.backend!=="pi")continue;let o=we(r,{accountsDir:e.piAccountsDir});o&&t.push(zn(r,o))}return t}function qn(e){let n=e.claude??{},t=o=>q({...n,claudeConfigDir:K(o.id,{accountsDir:e.claudeAccountsDir})}),r=A(n)?[Vn()]:[];for(let o of f(e.file??a))o.backend==="claude"&&(C(o)?!o.pending&&t(o)&&r.push(Yn(o)):r.push(Bn(o)));return r}function Wn(e={}){let n=e.claude??{},t=()=>f(e.file??a),r=()=>A(n)?.source??null,o=()=>qn(e),i=()=>se(t()).map(Gn),c=()=>t().filter(l=>C(l)&&!l.pending),s=l=>o().find(k=>k.id===l)??null,u=l=>i().find(k=>k.provider===l)??null,h=()=>de(e.piAuthPath??g()),B=l=>Xn(e,c()).filter(k=>l===void 0||k.provider===l);return{list:()=>[...o(),...i(),...B()],claudeConnections:o,piConnections:i,findClaude:s,findPi:u,piAccounts:B,accounts:c,hasClaude:()=>o().length>0,claudeSubscriptionSource:r,defaultClaudeConnection:()=>o()[0]?.id??null,billingOf:l=>l.backend==="claude"?Qn(l.connection,o(),c()):B(l.provider??void 0).find(k=>k.id===l.connection)?.billing??Zn(l.provider,u,h)}}function Qn(e,n,t){let r=e??n[0]?.id??_;return r===_||t.some(o=>o.backend==="claude"&&o.id===r)?"subscription":n.find(o=>o.id===r)?.billing??"metered"}var Ue=new Set(["openai-codex","google-gemini-cli","google-antigravity"]);function Jn(e,n){return Ue.has(e)||n==="oauth"?"subscription":"metered"}function Zn(e,n,t){return!e||n(e)?.keyHint?"metered":Ue.has(e)||t().has(e)?"subscription":"metered"}var $=Wn();var He=m("anthropic-models"),et=30*6e4,nt=5*6e4,tt=8e3,rt=1e4,ot=1e3,it=1e6,j="[1m]",ct=["low","medium","high","xhigh","max"];function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var st="https://api.anthropic.com";function ut(e){if(!S(e))return null;let n=e.effort;if(!S(n)||n.supported!==!0)return null;let t=ct.filter(r=>{let o=n[r];return S(o)&&o.supported===!0});return t.length>0?[...t]:null}function lt(e){if(!S(e))return null;let n=typeof e.id=="string"?e.id.trim():"";if(!n)return null;let t=typeof e.display_name=="string"?e.display_name.trim():"",r=e.max_input_tokens;return{id:n,displayName:t||null,maxInputTokens:typeof r=="number"&&Number.isFinite(r)?r:null,effortLevels:ut(e.capabilities)}}async function at(e={}){let n=Ce(e)??await be(e);if(!n)throw new Error("no Anthropic credential available to the daemon");let t=e.fetchImpl??fetch,r=`${st}/v1/models?limit=${ot}`,o=await t(r,{method:"GET",headers:n.headers,signal:AbortSignal.timeout(rt)});if(!o.ok)throw new Error(`models request failed: HTTP ${o.status}`);let i=await o.json(),c=S(i)?i.data:null;if(!Array.isArray(c))throw new Error("models response carried no data array");let s=[];for(let u of c){let h=lt(u);h&&s.push(h)}return He.debug(`discovered ${s.length} Anthropic models via ${n.source}`),s}function dt(e){return e.endsWith(j)?e.slice(0,-j.length):e}function ft(e,n){return e.startsWith(`${n}-`)&&/^\d{8}$/.test(e.slice(n.length+1))}function Fe(e,n=D){let t=[],r=new Set,o=i=>{r.has(i)||(r.add(i),t.push(i))};for(let i of e)o(i.id),(i.maxInputTokens??0)>=it&&o(`${i.id}${j}`);for(let i of n){let c=dt(i);e.some(u=>u.id===c||ft(u.id,c))||o(i)}return t}function Ke(e){let n={};for(let t of e)t.effortLevels&&(n[t.id]=[...t.effortLevels],n[`${t.id}${j}`]=[...t.effortLevels]);return n}function pt(e={}){let n=new b({scan:e.fetchModels??(()=>at()),now:e.now,cacheTtlMs:e.cacheTtlMs??et,retryMs:e.retryMs??nt,key:t=>t.id,clone:t=>({...t,effortLevels:t.effortLevels?[...t.effortLevels]:null}),logFailure:t=>He.info(`Anthropic model discovery failed: ${t}`)});return{get:()=>n.get(),ensure:(t=tt)=>n.ensure(t)}}var Q=pt();var V=class{routes=new Map;claude;pi;piAccounts;constructor(n){this.claude=n.filter(t=>t.backend==="claude"),this.pi=n.filter(t=>t.backend==="pi"&&t.kind!=="account"),this.piAccounts=n.filter(t=>t.backend==="pi"&&t.kind==="account")}addClaude(n,t){if(this.claude.length===0)return;let r=this.claude.flatMap(i=>i.models??[]),o=this.add({backend:"claude",provider:null},"builtin",[...n,...r],t);o.modelConnections=kt(this.claude,o.models,new Set(n))}addPiScan(n){for(let[t,r]of mt(n)){let o=Object.fromEntries(r.filter(i=>i.thinkingLevels).map(i=>[i.model,i.thinkingLevels]));this.add({backend:"pi",provider:t},"pi",r.map(i=>i.model),o)}}addPiConnections(){for(let n of this.pi){let t=this.add({backend:"pi",provider:n.provider},"connection",n.models??[]);n.kind==="custom"&&(t.source="custom")}}build(){return[...this.routes.values()]}add(n,t,r,o={}){let i=JSON.stringify([n.backend,n.provider]),c=this.routes.get(i)??this.newRoute(n,t);this.routes.set(i,c);for(let s of r)c.models.includes(s)||c.models.push(s);for(let[s,u]of Object.entries(o))c.modelThinking[s]??=[...u];return c}newRoute(n,t){let r=n.backend==="claude"?this.claude.map(o=>o.id):[n.provider,...this.piAccounts.filter(o=>o.provider===n.provider).map(o=>o.id)];return{...n,connections:r,models:[],source:t,modelThinking:{},modelConnections:{}}}};function mt(e){let n=new Map;for(let t of e){let r=n.get(t.provider)??[];r.some(o=>o.model===t.model)||r.push(t),n.set(t.provider,r)}return n}function ht(e,n,t,r){return e.models?e.models.includes(n):r.has(n)||!t.some(o=>o.models?.includes(n))}function kt(e,n,t){let r={};for(let o of n){let i=e.filter(c=>ht(c,o,e,t));i.length>0&&i.length<e.length&&(r[o]=i.map(c=>c.id))}return r}function gt(){return{connections:()=>$.list(),claudeModels:{get:()=>Q.get(),ensure:()=>Q.ensure()},piModels:{peek:()=>H.peekModels(),ensure:()=>H.ensureModels(),rescan:()=>H.rescan()}}}function vt(){return{claude:[...F.claude],pi:[...F.pi]}}function $e(e,n,t){let r=new V(e),o=Fe(n,D);return r.addClaude(o,Ke(n)),r.addPiScan(t),r.addPiConnections(),{routes:r.build(),piPending:t.length===0,thinkingLevels:vt()}}function yt(e={}){let n={...gt(),...e},t=o=>o.some(i=>i.backend==="claude"),r=async o=>{let i=n.connections(),[c,s]=await Promise.all([t(i)?n.claudeModels.ensure():Promise.resolve([]),o()]);return $e(i,c,s)};return{load:()=>r(()=>n.piModels.ensure()),reload:()=>r(()=>n.piModels.rescan?n.piModels.rescan():n.piModels.ensure()),peek(){let o=n.connections(),i=t(o)?n.claudeModels.get():[];return $e(o,i,n.piModels.peek())}}}var je=yt();function Ve(e,n){return e.routes.find(t=>t.backend===n.backend&&t.provider===n.provider)}function Be(e,n){return Ve(e,n)?.modelThinking[n.model]??e.thinkingLevels[n.backend]}function J(e,n){let t=Ve(e,{backend:"claude",provider:null});return t?t.modelConnections[n]??t.connections:[]}function ro(e,n){return e.routes.filter(t=>t.models.includes(n)).map(t=>({backend:t.backend,provider:t.provider,model:n}))}var ee=m("selection");function Ye(e){let n=null,t=e.catalog??(()=>je.peek());return{inventory:e.inventory??$,catalog:()=>n??=t(),memory:e.memory,defaults:e.defaults}}function At(e){return e.request??e.session??e.draft??e.defaults.selection()}function _t(e,n,t){if(!(e.backend!==void 0&&e.model===void 0&&e.provider===void 0)&&(e.backend===void 0||e.backend===n?.backend))return n;let o=t.defaults.selection();if(o?.backend===e.backend)return o;let i=t.defaults.forBackend(e.backend);return i?{...i,thinking:t.memory()[I(i)]?.thinking??null,connection:null}:null}var Ct=/^[a-zA-Z0-9_-]+$/;function Et(e,n){let t=e.backend??n?.backend,r=e.model??n?.model;if(!t||r===void 0)return{ok:!1,reason:"no-model-for-backend"};let o=e.provider!==void 0?e.provider:t==="claude"?null:n?.provider??null;return typeof r!="string"||!r.trim()?{ok:!1,reason:"invalid-model"}:(t==="claude"?o===null:t==="pi"&&typeof o=="string"&&Ct.test(o))?{ok:!0,value:{backend:t,provider:o,model:r}}:{ok:!1,reason:"provider-not-supported"}}function ne(e,n){return!!e&&I(e)===I(n)}function bt(e,n,t,r,o){return ne(n,r)&&(t||e.model===void 0)?n.thinking:o.memory()[I(r)]?.thinking??null}function Tt(e,n,t,r,o){let i=bt(e,n,t,r,o),c=ne(n,r),s=e.thinking!==void 0&&!(c&&e.thinking===i),u=s?e.thinking:i;if(u===null)return{ok:!0,value:null};let h=Be(o.catalog(),r);return h.includes(u)?{ok:!0,value:u}:s?{ok:!1,reason:"invalid-thinking",allowed:h}:{ok:!0,value:null}}function Ot(e){return e.inventory.claudeConnections().map(n=>n.id)}function It(e,n){return!e||e.backend!==n.backend||n.backend==="pi"&&e.provider!==n.provider?null:e.connection??null}function St(e,n,t,r){let o=It(n,t);return e.connection!==void 0&&e.connection!==o?wt(e.connection,t,r):t.backend==="pi"?{ok:!0,value:ze(o,t.provider,r)}:{ok:!0,value:Nt(o,ne(n,t),t.model,r)}}function Ge(e,n){return n.inventory.piAccounts(e).map(t=>t.id)}function wt(e,n,t){if(e===null)return{ok:!0,value:null};let r=n.backend==="pi"?[n.provider,...Ge(n.provider,t)]:Ot(t);return r.includes(e)?{ok:!0,value:e===n.provider?null:e}:{ok:!1,reason:"invalid-connection",allowed:r}}function Nt(e,n,t,r){return e===null?null:r.inventory.findClaude(e)?n||J(r.catalog(),t).includes(e)?e:null:(ee.warn(`Connection '${e}' no longer exists; the selection falls back to the default connection`),null)}function ze(e,n,t){return e===null||Ge(n,t).includes(e)?e:(ee.warn(`Account '${e}' is not signed in to ${n}; the selection falls back to its default login`),null)}function Xe(e,n){if(e.backend==="pi")return ze(e.connection,e.provider??"",n);if(e.connection&&n.inventory.findClaude(e.connection))return e.connection;e.connection&&ee.warn(`Connection '${e.connection}' no longer exists; using the default connection`);let t=n.inventory.defaultClaudeConnection(),r=J(n.catalog(),e.model);return t!==null&&r.includes(t)?t:r[0]??t}function Z(e,n){let t=e;return{ok:!1,reason:t.reason,...t.allowed?{allowed:t.allowed}:{},base:n}}function lo(e,n={}){let t=Ye(e),r=At(e),o=_t(n,r,t),i=Et(n,o);if(!i.ok)return Z(i,r);let c=Tt(n,o,o===r,i.value,t);if(!c.ok)return Z(c,r);let s=St(n,o,i.value,t);if(!s.ok)return Z(s,r);let u={...i.value,thinking:c.value,connection:s.value};return{ok:!0,selection:u,effective:{...u,connection:Xe(u,t)},base:r}}function ao(e,n={}){let t=Ye({...n,defaults:xt,memory:()=>({})}),r={backend:"claude",provider:null,model:e.model??"",thinking:null,connection:e.connection};return Xe(r,t)}var xt={selection:()=>null,forBackend:()=>null};export{ve as a,Ut as b,Ht as c,Ft as d,A as e,q as f,Fe as g,Q as h,Ar as i,Tr as j,H as k,I as l,Pn as m,Dn as n,Ir as o,Sr as p,K as q,Rr as r,Lr as s,E as t,Yt as u,Gt as v,zt as w,Xt as x,qt as y,Zt as z,O as A,er as B,nr as C,tr as D,bn as E,fr as F,Tn as G,we as H,pr as I,mr as J,Wn as K,$ as L,je as M,Ve as N,J as O,ro as P,lo as Q,ao as R};