@cortex-agent/server 2026.10.28 → 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.
- package/LICENSE +255 -21
- package/README.md +36 -7
- package/THIRD_PARTY_NOTICES.txt +1990 -593
- package/defaults/hooks/cortex-hook-api.mjs +2 -1
- package/defaults/hooks/quota-stop.mjs +37 -0
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
- package/defaults/prompts/clean-workspace.md +5 -0
- package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
- package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
- package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
- package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
- package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
- package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
- package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
- package/dist/chunks/chunk-24DH4IR5.js +4 -0
- package/dist/chunks/chunk-25XKBRDT.js +70 -0
- package/dist/chunks/chunk-2ABET62E.js +23 -0
- package/dist/chunks/chunk-2BVUA256.js +4 -0
- package/dist/chunks/{chunk-LEUENXI2.js → chunk-2WFL62UO.js} +1 -1
- package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
- package/dist/chunks/chunk-335SSANX.js +4 -0
- package/dist/chunks/chunk-377OPTXX.js +17 -0
- package/dist/chunks/chunk-3EZNVLBF.js +129 -0
- package/dist/chunks/chunk-3O6ZG5HA.js +7 -0
- package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
- package/dist/chunks/chunk-4HRI75GU.js +4 -0
- package/dist/chunks/chunk-4JBYLRPM.js +57 -0
- package/dist/chunks/chunk-4KKV7VKE.js +4 -0
- package/dist/chunks/chunk-4KQHDDC5.js +4 -0
- package/dist/chunks/chunk-4SWD4JMP.js +33 -0
- package/dist/chunks/chunk-52VCLZS5.js +4 -0
- package/dist/chunks/chunk-54P7TSY3.js +10 -0
- package/dist/chunks/chunk-5DVSAXOI.js +7 -0
- package/dist/chunks/chunk-5F3A62YS.js +4 -0
- package/dist/chunks/{chunk-XNSSUVT6.js → chunk-5FHETFZM.js} +1 -1
- package/dist/chunks/{chunk-A34TDMIC.js → chunk-5LBLRAHS.js} +1 -1
- package/dist/chunks/chunk-5UYVNA3W.js +4 -0
- package/dist/chunks/chunk-6G3OYMCV.js +21 -0
- package/dist/chunks/chunk-7GGPYU5E.js +30 -0
- package/dist/chunks/chunk-7TYSMLUV.js +4 -0
- package/dist/chunks/chunk-7W7VYUTK.js +5 -0
- package/dist/chunks/chunk-AXYAZTTN.js +6 -0
- package/dist/chunks/{chunk-BGVHA2D4.js → chunk-B3NB243Z.js} +1 -1
- package/dist/chunks/chunk-BKYP6AGM.js +8 -0
- package/dist/chunks/chunk-BVEDNESB.js +4 -0
- package/dist/chunks/chunk-BWDJS6A4.js +12 -0
- package/dist/chunks/chunk-C6YVF7EI.js +4 -0
- package/dist/chunks/chunk-CEJIYYVE.js +15 -0
- package/dist/chunks/chunk-CI2RHH74.js +50 -0
- package/dist/chunks/chunk-CMSOOLJB.js +4 -0
- package/dist/chunks/chunk-CSVTYYLP.js +4 -0
- package/dist/chunks/chunk-DE5EGVKG.js +6 -0
- package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
- package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-DK4UCK7L.js} +1 -1
- package/dist/chunks/chunk-DYLBVUAU.js +4 -0
- package/dist/chunks/chunk-FDC2GRBK.js +27 -0
- package/dist/chunks/chunk-FE7HH5JS.js +18 -0
- package/dist/chunks/chunk-FYD57YRO.js +436 -0
- package/dist/chunks/chunk-G264APQN.js +5 -0
- package/dist/chunks/chunk-G4JYZFEO.js +11 -0
- package/dist/chunks/chunk-GFFM56U2.js +4 -0
- package/dist/chunks/chunk-GOS3P7KS.js +132 -0
- package/dist/chunks/chunk-HVN37UXD.js +4 -0
- package/dist/chunks/chunk-IA6IODY3.js +4 -0
- package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-IGZWZP7Z.js} +1 -1
- package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-IJ7XFQMI.js} +1 -1
- package/dist/chunks/chunk-IMMGYDAB.js +6 -0
- package/dist/chunks/chunk-IOWBF7UK.js +10 -0
- package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-ITGCWQFK.js} +1 -1
- package/dist/chunks/chunk-IVZ7QUEG.js +4 -0
- package/dist/chunks/{chunk-YAEVYJAR.js → chunk-IWY2HIFK.js} +1 -1
- package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
- package/dist/chunks/{chunk-QWAQHHRS.js → chunk-JGUEIW2W.js} +1 -1
- package/dist/chunks/chunk-JKL3AK5D.js +106 -0
- package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
- package/dist/chunks/chunk-KJUQCCB5.js +4 -0
- package/dist/chunks/chunk-KST6OY76.js +10 -0
- package/dist/chunks/chunk-KZSAFVSY.js +129 -0
- package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
- package/dist/chunks/chunk-LE6QPXN6.js +7 -0
- package/dist/chunks/chunk-LEAV3FFG.js +4 -0
- package/dist/chunks/chunk-LIIZI3HY.js +5 -0
- package/dist/chunks/chunk-LP72AF56.js +45 -0
- package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-MJQ2D2OP.js} +1 -1
- package/dist/chunks/{chunk-6LZK4DDH.js → chunk-NHHR4DCF.js} +1 -1
- package/dist/chunks/chunk-NW4GW47L.js +4 -0
- package/dist/chunks/chunk-OALEJ6FG.js +60 -0
- package/dist/chunks/chunk-OIV4DIMB.js +4 -0
- package/dist/chunks/chunk-OJ37ZWBG.js +4 -0
- package/dist/chunks/chunk-OZXMPBUX.js +4 -0
- package/dist/chunks/{chunk-3THJYAEF.js → chunk-PG7452XE.js} +1 -1
- package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
- package/dist/chunks/chunk-PTS3J4DQ.js +6 -0
- package/dist/chunks/{chunk-PXS5SHOV.js → chunk-PVVEEBUU.js} +1 -1
- package/dist/chunks/chunk-Q7BZLPBU.js +8 -0
- package/dist/chunks/{chunk-FOJQXLL2.js → chunk-QC66ZXPP.js} +1 -1
- package/dist/chunks/chunk-QXFWIL4C.js +4 -0
- package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-R2CCD4OF.js} +1 -1
- package/dist/chunks/chunk-R6CGBSTC.js +22 -0
- package/dist/chunks/chunk-RG5GP4RB.js +5 -0
- package/dist/chunks/{chunk-D3NXKK2L.js → chunk-RW2F2QNP.js} +1 -1
- package/dist/chunks/{models-L5VF4I5O-XXNJYQMQ.js → chunk-RWPO3NZ3.js} +1 -1
- package/dist/chunks/chunk-SAJD4EKE.js +10 -0
- package/dist/chunks/chunk-SDUS2H3E.js +4 -0
- package/dist/chunks/chunk-SIHGKM4E.js +4 -0
- package/dist/chunks/chunk-SKHFU5DI.js +4 -0
- package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
- package/dist/chunks/chunk-T54CZKNJ.js +6 -0
- package/dist/chunks/chunk-TKFFQNAP.js +19 -0
- package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
- package/dist/chunks/chunk-TRXLIL7V.js +4 -0
- package/dist/chunks/{chunk-SUFW24P4.js → chunk-UEEW2R4E.js} +1 -1
- package/dist/chunks/chunk-UHXPRU6G.js +10 -0
- package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
- package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
- package/dist/chunks/chunk-V7K3KNDM.js +4 -0
- package/dist/chunks/chunk-VHX2GHBF.js +4 -0
- package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
- package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
- package/dist/chunks/chunk-W34AK4SK.js +65 -0
- package/dist/chunks/{chunk-REBNWCKI.js → chunk-WU7RNAZD.js} +1 -1
- package/dist/chunks/chunk-WZC4TDDM.js +6 -0
- package/dist/chunks/chunk-WZYS2HAK.js +4 -0
- package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
- package/dist/chunks/{chunk-H2FP6DG4.js → chunk-X5ND4H4P.js} +1 -1
- package/dist/chunks/{chunk-4U7XXM4W.js → chunk-Y3AOGNDT.js} +1 -1
- package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
- package/dist/chunks/{chunk-KENCMLRE.js → chunk-YAEHSSR4.js} +1 -1
- package/dist/chunks/chunk-YWPBE5LP.js +4 -0
- package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
- package/dist/chunks/chunk-ZD2M73XA.js +19 -0
- package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
- package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
- package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
- package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
- package/dist/chunks/cli-VB2N7HEK.js +55 -0
- package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
- package/dist/chunks/context-CI2FKEQE.js +4 -0
- package/dist/chunks/cost-CZRRSIUF.js +5 -0
- package/dist/chunks/dist-QCNQN6DY.js +4 -0
- package/dist/chunks/easter-egg-3d-XR5S2O3T.js +4 -0
- package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
- package/dist/chunks/{execution-repo-ZLJTBWFC.js → execution-repo-5TLV2NM4.js} +1 -1
- package/dist/chunks/{executions-6ARGR3IO.js → executions-I3UUIGSL.js} +1 -1
- package/dist/chunks/file-Y5G56IUT.js +4 -0
- package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
- package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
- package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
- package/dist/chunks/init-A6GY656J.js +4 -0
- package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-FALWKQYO.js} +1 -1
- package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-O5HGF6CH.js} +1 -1
- package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-JTVDN3BC.js} +1 -1
- package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
- package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
- package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
- package/dist/chunks/{memory-cli-PYOILNN5.js → memory-cli-DIT4DQF3.js} +1 -1
- package/dist/chunks/meta-JQH66YU7.js +4 -0
- package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
- package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
- package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
- package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
- package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
- package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
- package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
- package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-JU6QQKEM.js} +1 -1
- package/dist/chunks/openai-responses-2SG757TL.js +6 -0
- package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
- package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
- package/dist/chunks/radius-THYKWV4E.js +4 -0
- package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
- package/dist/chunks/runner-5MKMRTIN.js +4 -0
- package/dist/chunks/runtime-DST3H5JP.js +4 -0
- package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
- package/dist/chunks/slack-R7SEJYMY.js +4 -0
- package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
- package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
- package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
- package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
- package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
- package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
- package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
- package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-SRD4ILBS.js} +1 -1
- package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
- package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
- package/dist/chunks/waitpoint-M6JZBSLT.js +5 -0
- package/dist/chunks/workers-SQ2R32TK.js +4 -0
- package/dist/client-bundle/client.mjs +273 -93
- package/dist/client-bundle/manifest.json +2 -2
- package/dist/core/pi-sdk.js +1 -1
- package/dist/domain/auth/cc-auth-cli.js +1 -1
- package/dist/domain/mcp/bundled-server.js +1 -1
- package/dist/domain/mcp/feishu/client.js +4 -0
- package/dist/entry/app.js +151 -559
- package/dist/entry/browser-cli.js +10 -10
- package/dist/entry/cli.js +1 -1
- package/dist/entry/cortex-cli.js +1 -1
- package/dist/entry/daemon.js +4 -4
- package/dist/entry/hook-cli.js +2 -2
- package/dist/entry/production-app-bootstrap.js +1 -1
- package/dist/entry/production-evidence-export-cli.js +1 -1
- package/dist/entry/signal-cli.js +2 -2
- package/dist/tui/index.js +41 -41
- package/package.json +3 -3
- package/vendor/pi/CHANGELOG.md +330 -0
- package/vendor/pi/dist/codemode-worker.js +2 -0
- package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
- package/vendor/pi/dist/core/export-html/template.css +9 -0
- package/vendor/pi/dist/core/export-html/template.js +166 -46
- package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
- package/vendor/pi/dist/core/extensions/loader.js +1 -1
- package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
- package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
- package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
- package/vendor/pi/dist/utils/image-resize.js +1 -1
- package/vendor/pi/docs/cli.md +35 -12
- package/vendor/pi/docs/custom-provider.md +2 -0
- package/vendor/pi/docs/environment-variables.md +2 -0
- package/vendor/pi/docs/extensions.md +3192 -225
- package/vendor/pi/docs/keybindings.md +2 -2
- package/vendor/pi/docs/llama-cpp.md +27 -19
- package/vendor/pi/docs/mcp.md +6 -4
- package/vendor/pi/docs/message-types.md +1 -1
- package/vendor/pi/docs/models-configuration.md +9 -3
- package/vendor/pi/docs/models.md +2 -1
- package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
- package/vendor/pi/docs/packages.md +24 -0
- package/vendor/pi/docs/prompt-templates.md +1 -1
- package/vendor/pi/docs/providers.md +4 -2
- package/vendor/pi/docs/quickstart.md +7 -3
- package/vendor/pi/docs/rpc-commands.md +1 -1
- package/vendor/pi/docs/rpc.md +4 -2
- package/vendor/pi/docs/sessions.md +17 -3
- package/vendor/pi/docs/settings.md +6 -5
- package/vendor/pi/docs/slash-commands.md +3 -2
- package/vendor/pi/docs/terminal-setup.md +3 -1
- package/vendor/pi/docs/tmux.md +6 -0
- package/vendor/pi/docs/tui.md +4 -0
- package/vendor/pi/docs/windows.md +27 -0
- package/vendor/pi/examples/extensions/README.md +2 -1
- package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
- package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
- package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
- package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
- package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
- package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
- package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
- package/vendor/pi/examples/extensions/preset.ts +2 -0
- package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
- package/vendor/pi/examples/extensions/subagent/README.md +14 -11
- package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
- package/vendor/pi/examples/extensions/todo.ts +7 -0
- package/vendor/pi/examples/extensions/tools.ts +2 -0
- package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
- package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
- package/vendor/pi/examples/tsconfig.json +208 -0
- package/vendor/pi/package.json +15 -16
- package/vendor/pi/schemas/models.schema.json +66 -37
- package/vendor/pi/schemas/settings.schema.json +18 -1
- package/vendor/pi-ai/bedrock.js +1 -1
- package/vendor/pi-ai/oauth-load.js +1 -1
- package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-DKX6FcUS.js} +1 -1
- package/web/dist/assets/index-D11wi0uG.js +540 -0
- package/web/dist/assets/index-JedYumhY.css +1 -0
- package/web/dist/assets/{index-WCm6wwmM.js → index-jl30Gy8P.js} +1 -1
- package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
- package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
- package/web/dist/index.html +2 -2
- package/web/dist/theme.css +22 -0
- package/dist/chunks/anthropic-messages-M3SMXACA.js +0 -8
- package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
- package/dist/chunks/azure-openai-responses-76YWXHSB.js +0 -4
- package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
- package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
- package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
- package/dist/chunks/chunk-3F6WW7HR.js +0 -13
- package/dist/chunks/chunk-3OKHUVEM.js +0 -7
- package/dist/chunks/chunk-3YHOCPQU.js +0 -10
- package/dist/chunks/chunk-4EX2JJWB.js +0 -4
- package/dist/chunks/chunk-4LLH5OWM.js +0 -10
- package/dist/chunks/chunk-52T37Y47.js +0 -8
- package/dist/chunks/chunk-7MU2AKNM.js +0 -4
- package/dist/chunks/chunk-AAA3UBIS.js +0 -4
- package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
- package/dist/chunks/chunk-BKHDWCRT.js +0 -79
- package/dist/chunks/chunk-CQLH4UVX.js +0 -4
- package/dist/chunks/chunk-CVC66CFV.js +0 -33
- package/dist/chunks/chunk-D6UA4BZC.js +0 -19
- package/dist/chunks/chunk-DGMNI4AO.js +0 -4
- package/dist/chunks/chunk-DHSA5ACV.js +0 -125
- package/dist/chunks/chunk-DPQPXBTP.js +0 -68
- package/dist/chunks/chunk-DXBSQXJL.js +0 -18
- package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
- package/dist/chunks/chunk-EQITBTJC.js +0 -10
- package/dist/chunks/chunk-EXJA5RIX.js +0 -357
- package/dist/chunks/chunk-FF7UELTU.js +0 -4
- package/dist/chunks/chunk-FH74NME3.js +0 -115
- package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
- package/dist/chunks/chunk-FX6MOGLR.js +0 -11
- package/dist/chunks/chunk-G2V65UBA.js +0 -4
- package/dist/chunks/chunk-HGPBHTVD.js +0 -6
- package/dist/chunks/chunk-J5DVLUKY.js +0 -6
- package/dist/chunks/chunk-JW2HFMTF.js +0 -4
- package/dist/chunks/chunk-KDYEGGMW.js +0 -4
- package/dist/chunks/chunk-KIGMAATV.js +0 -23
- package/dist/chunks/chunk-KIU5FAPY.js +0 -5
- package/dist/chunks/chunk-KIWMQPH7.js +0 -739
- package/dist/chunks/chunk-L6VCIGWS.js +0 -11
- package/dist/chunks/chunk-LACGULCN.js +0 -10
- package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
- package/dist/chunks/chunk-MEPASGPP.js +0 -6
- package/dist/chunks/chunk-MFAEUHMV.js +0 -28
- package/dist/chunks/chunk-NAA7GF6Q.js +0 -5
- package/dist/chunks/chunk-NKDMKRSB.js +0 -68
- package/dist/chunks/chunk-NKXV32S6.js +0 -4
- package/dist/chunks/chunk-NVX5IPRN.js +0 -4
- package/dist/chunks/chunk-O3JW2F7D.js +0 -8
- package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
- package/dist/chunks/chunk-OISO5JXB.js +0 -4
- package/dist/chunks/chunk-OPYXNSMY.js +0 -4
- package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
- package/dist/chunks/chunk-P52RMIYX.js +0 -6
- package/dist/chunks/chunk-PBJ5MPPX.js +0 -60
- package/dist/chunks/chunk-PZMGBKUR.js +0 -13
- package/dist/chunks/chunk-PZMXHA6X.js +0 -9
- package/dist/chunks/chunk-Q7CE3UIE.js +0 -133
- package/dist/chunks/chunk-QBKCAIJG.js +0 -4
- package/dist/chunks/chunk-QEOFEETJ.js +0 -4
- package/dist/chunks/chunk-QUUEQRIT.js +0 -4
- package/dist/chunks/chunk-RA6HKFBV.js +0 -4
- package/dist/chunks/chunk-REPYBMQS.js +0 -4
- package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
- package/dist/chunks/chunk-TAWLERZA.js +0 -4
- package/dist/chunks/chunk-TWAEABGG.js +0 -52
- package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
- package/dist/chunks/chunk-UD3NMUHR.js +0 -12
- package/dist/chunks/chunk-UNVEZI57.js +0 -4
- package/dist/chunks/chunk-VQUPKMDR.js +0 -4
- package/dist/chunks/chunk-W25TB3PU.js +0 -4
- package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
- package/dist/chunks/chunk-WEZWKMYU.js +0 -4
- package/dist/chunks/chunk-XAJLZR7C.js +0 -28
- package/dist/chunks/chunk-XH6FMP3N.js +0 -71
- package/dist/chunks/chunk-XSRZHN63.js +0 -4
- package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
- package/dist/chunks/chunk-YG7OEPR2.js +0 -6
- package/dist/chunks/chunk-YHIWOGVL.js +0 -4
- package/dist/chunks/chunk-YKKEI5GI.js +0 -4
- package/dist/chunks/chunk-YZSHTWNM.js +0 -92
- package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
- package/dist/chunks/cli-5DBTRMHU.js +0 -53
- package/dist/chunks/client-XOGYH5UR.js +0 -4
- package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
- package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
- package/dist/chunks/context-VCQH5OB6.js +0 -4
- package/dist/chunks/cost-PGGFI7QJ.js +0 -5
- package/dist/chunks/dist-PUKMZ7GW.js +0 -4
- package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
- package/dist/chunks/es5-VNTQPCKX.js +0 -4
- package/dist/chunks/file-7BN7RCAY.js +0 -4
- package/dist/chunks/gateway-UCRPMR75.js +0 -36
- package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
- package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
- package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
- package/dist/chunks/init-HA7FAQ73.js +0 -4
- package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
- package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
- package/dist/chunks/meta-KY3LNFV2.js +0 -4
- package/dist/chunks/mistral-conversations-34F66L3O.js +0 -7
- package/dist/chunks/model-resolver-N3DTAQ2S.js +0 -4
- package/dist/chunks/openai-codex-responses-ZBVHREB3.js +0 -12
- package/dist/chunks/openai-completions-VVIB26SH.js +0 -9
- package/dist/chunks/openai-responses-735XA2ZX.js +0 -6
- package/dist/chunks/openrouter-images-3IKETHAC.js +0 -4
- package/dist/chunks/pi-messages-I3E4ZFHA.js +0 -10
- package/dist/chunks/radius-HXRZVBDB.js +0 -4
- package/dist/chunks/remote-ops-BALZYKH6.js +0 -14
- package/dist/chunks/runner-PLVZDGHB.js +0 -4
- package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
- package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
- package/dist/chunks/slack-WAGSPZUX.js +0 -4
- package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
- package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
- package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
- package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
- package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
- package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
- package/dist/chunks/ui-view-O7PLANT7.js +0 -4
- package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
- package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
- package/dist/chunks/workers-XN4PSTH6.js +0 -4
- package/vendor/aistatus/gateway-cli.js +0 -21
- package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
- package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
- package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
- package/web/dist/assets/index-BHZpFXhc.js +0 -525
- package/web/dist/assets/index-DqWMdMkh.css +0 -1
- package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
- package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{e as Nt,g as Jt,h as P,i as Qt}from"./chunk-4U7XXM4W.js";import{a as Lt}from"./chunk-TCAEECDI.js";import{a as Rt,b as jt}from"./chunk-OZGBWAT2.js";import{a as Ht,b as Wt,c as Gt,d as K,e as Vt,f as qt,g as zt,i as Xt}from"./chunk-ZFPMIQA3.js";import{a as Yt}from"./chunk-YAEVYJAR.js";import{a as Zt,c as Kt}from"./chunk-D3NXKK2L.js";import{a as Pt,b as At}from"./chunk-YHIWOGVL.js";import{a as en}from"./chunk-QEOFEETJ.js";import{a as de}from"./chunk-DGMNI4AO.js";import{a as Dt,d as Ot,e as Mt}from"./chunk-SUFW24P4.js";import{a as X}from"./chunk-LCKVYFMD.js";import{a as He,d as Ge}from"./chunk-52T37Y47.js";import{d as $e,j as _t,t as Ut,u as Bt,v as We,x as ue}from"./chunk-3YHOCPQU.js";import{a as Tt,d as le}from"./chunk-MEPASGPP.js";import{c as Ct}from"./chunk-STUHNKQS.js";import{a as F}from"./chunk-PFMEUFJ7.js";import{J as n}from"./chunk-DPQPXBTP.js";import{d as xt}from"./chunk-W5LGYSPZ.js";import{e as I}from"./chunk-E7ZMYIY6.js";import{e as h}from"./chunk-NAA7GF6Q.js";import{f as Ft,g as Be}from"./chunk-QWAQHHRS.js";import{f as vt,l as Et,m as $t,t as kt}from"./chunk-J5DVLUKY.js";var _o=[["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 Po(e){return _o.find(([,t])=>t.test(e))?.[0]??"other"}function tn(e,t){return Math.max(0,Math.round((t-e)/1e3))}function ke(e,t=new Date){return{type:"upgrade",at:t.toISOString(),...e}}function Ao(e,t){let o=tn(Date.parse(e.startedAt),Date.now()),{from:r,to:i,method:a}=e;if(t===null){We(l=>({...l,pendingUpgrade:e})),ue(ke({from:r,to:i,method:a,stage:"installed",durationS:o,failure:null}));return}let c={class:Po(t),message:He(t)};ue(ke({from:r,to:i,method:a,stage:"failed",durationS:o,failure:c}),{urgent:!0})}function nn(e){return(t,o)=>{let r={from:F,to:t,startedAt:new Date().toISOString(),method:le().serverAutoUpdate?"auto":"prompt"};e(t,i=>{try{Ao(r,i)}catch{}o(i)})}}function Do(e,t,o){if(e){let r=e.to===F?"confirmed":"unconfirmed",i=tn(Date.parse(e.startedAt),o);return ke({...e,stage:r,durationS:i,failure:null},new Date(o))}return!t||t===F?null:ke({from:t,to:F,method:"manual",stage:"version-changed",durationS:null,failure:null},new Date(o))}function Pi(e=Date.now()){let t=Bt(),o=Do(t.pendingUpgrade,t.lastVersion,e);We(r=>({...r,pendingUpgrade:null,lastVersion:F})),o&&ue(o)}function Oo(e){let t=e?.code;return t==="EACCES"||t==="EPERM"?"permission":e instanceof SyntaxError?"parse":typeof t=="string"&&t.startsWith("E")?"io":"other"}function Ai(e){let t=e.error instanceof Error?e.error.message:String(e.error);ue({type:"migration_failure",at:new Date().toISOString(),migration:e.migration.replace(/[^A-Za-z0-9._:/@[\]-]/g,"_").slice(0,80),errorClass:Oo(e.error),message:He(t)})}import*as _e from"node:fs";import*as Xe from"node:os";import{spawn as Go}from"node:child_process";var on={available:null,state:"idle"},v=on,N=null;function rn(){return v}function Oi(e,t){let o=N;N=null,o?.(null),N=t,v={available:e,state:"prompting"}}function sn(e){let t=N;return t?(N=null,t(e),!0):!1}function Mi(e){N=null,v=e==="apply"?{available:v.available,state:"waiting"}:on}function an(e){let t=N;N=null,t?.(null),v={available:e,state:"waiting",auto:!0}}function cn(){return v.auto?{auto:!0}:{}}function ln(){v={available:v.available,state:"installing",...cn()}}function un(){v={available:v.available,state:"restarting",...cn()}}function pe(e){v={available:v.available,state:"failed",error:e}}var Ce={status:"error",reason:"check_failed"},Mo=15e3;function Ve(e){return{status:"available",update:{version:e}}}async function Lo(e){let t,o=new Promise(r=>{t=setTimeout(()=>r(null),Mo),t.unref?.()});try{return await Promise.race([Promise.resolve().then(e),o])}finally{clearTimeout(t)}}var Te=class{deps;inFlight=null;pending=null;latestVersion=null;promptFailed=!1;decision=Promise.resolve(null);constructor(t){this.deps=t}check(){return this.inFlight?this.inFlight:(this.inFlight=this.discover().catch(()=>Ce).finally(()=>{this.inFlight=null}),this.inFlight)}async checkAndWait(){return await this.check(),{action:await this.decision,latestVersion:this.latestVersion}}skipReason(){if(le().serverUpdateDisable)return"disabled";if(this.deps.isDevMode())return"dev_mode";let{state:t}=rn();return t==="waiting"||t==="installing"||t==="restarting"?"update_in_progress":null}async discover(){let t=this.skipReason();return t?{status:"skipped",reason:t}:this.lookup()}async lookup(){let t=await Lo(this.deps.getLatest);if(!t||!/^\d+\.\d+\.\d+(?:-\d+)?$/.test(t))return Ce;let o=this.skipReason();return o?{status:"skipped",reason:o}:(this.latestVersion=t,this.resolveVersion(t))}resolveVersion(t){if(Lt(t,F)<=0)return this.current();let o=this.deps.loadState()??{};return o.skippedVersion===t?{status:"skipped",reason:"version_skipped"}:le().serverAutoUpdate?this.autoInstall(t,o):this.pending?.version===t?Ve(t):this.openPrompt(t,o)}autoInstall(t,o){this.deps.saveState({...o,lastCheckedAt:this.deps.now()}),this.pending=null,an(t);try{this.deps.installWhenIdle(t)}catch(r){return pe(r instanceof Error?r.message:String(r)),this.decision=Promise.resolve(null),Ce}return this.decision=Promise.resolve("apply"),{...Ve(t),reason:"auto_install"}}current(){return this.pending&&(this.pending=null,sn("cancel"),this.decision=Promise.resolve(null)),{status:"current"}}async openPrompt(t,o){let r={...o,lastCheckedAt:this.deps.now(),lastPromptedVersion:t};this.deps.saveState(r);let i=this.deps.prompt.ask({latestVersion:t});return this.pending={version:t,answer:i},this.promptFailed=!1,this.decision=this.handleDecision(this.pending,r),await Promise.resolve(),this.promptFailed?Ce:Ve(t)}async handleDecision(t,o){try{let r=await t.answer;return this.pending!==t?null:this.acceptChoice(r,t.version,o)}catch(r){return this.failDecision(t,r)}finally{this.pending===t&&(this.pending=null)}}failDecision(t,o){return this.pending!==t||(this.promptFailed=!0,pe(o instanceof Error?o.message:String(o))),null}acceptChoice(t,o,r){return t==="apply"&&(this.deps.saveState({...r,skippedVersion:void 0}),this.deps.installWhenIdle(o)),t==="skip"&&this.deps.saveState({...r,skippedVersion:o}),t}};import{execFile as Fo}from"node:child_process";var No=1024*1024;function Uo(e,t,o,r,i){let a=t&&typeof t.code=="number"?t.code:t?null:0,c=t?.signal??null,l=!!t&&(t?.killed===!0||c==="SIGTERM")&&i!==void 0;e({ok:a===0,code:a,signal:c,timedOut:l,stdout:o,stderr:r,...t&&typeof t.code=="string"?{error:t.message}:{}})}function J(e,t=[],o={}){return new Promise(r=>{let i=Fo(e,[...t],{cwd:o.cwd,shell:o.shell,env:o.env??process.env,timeout:o.timeoutMs,killSignal:"SIGTERM",maxBuffer:o.maxBuffer??No,encoding:"utf8",windowsHide:!0},(a,c,l)=>Uo(r,a,c,l,o.timeoutMs));o.stdin!==void 0?i.stdin?.end(o.stdin):i.stdin?.end()})}function Gi(e,t={}){let o=process.platform==="win32"?process.env.ComSpec??"cmd.exe":"/bin/sh",r=process.platform==="win32"?"/c":"-c";return J(o,[r,e],t)}import*as Q from"fs";import*as Re from"path";var qe=Re.join($t,"update-state.json");function dn(){try{return JSON.parse(Q.readFileSync(qe,"utf8"))}catch{return null}}function pn(e){let t=Re.dirname(qe);Q.mkdirSync(t,{recursive:!0}),Q.writeFileSync(qe,JSON.stringify(e,null,2))}var me="server-update",Bo=5*6e4,ee=null;function je(e){let t=e.now??Date.now();ee={phase:e.phase??null,expiresAt:t+Bo}}function ze(){ee=null}function fn(e=Date.now()){return ee?e>=ee.expiresAt?(ee=null,null):{phase:ee.phase}:null}function Ki(e=Date.now()){return fn(e)!==null}var mn=160;function Ho(e){let t=e.replace(/\s+/g," ").trim();return t?t.length>mn?`${t.slice(0,mn)}\u2026`:t:"(no text)"}async function Ji(e){let t=fn()?.phase??"restart",o=t===me;if(e.interactive){let i={type:"interactive-reply",conduit:e.channel,sessionId:""},a=o?I("startup.updateHold"):I("startup.rebuildHold",{phase:t});await e.adapter.postMessage(i,{text:`${X.warning} ${a}`}).catch(()=>{});return}let r={channel:e.channel,preview:Ho(e.text)};await Nt(e.adapter,{level:"warning",title:o?I("notice.serverUpdate.title"):I("notice.rebuild.title"),text:o?I("startup.updateHoldDropped",r):I("startup.rebuildHoldDropped",{phase:t,...r})}).catch(()=>{})}var Wo=6e4,hn={isIdle:()=>!0,onIdle:()=>()=>{}};function gn(e,t,o={}){let r=o.supervised??(()=>!!process.send),i=o.renewMs??Wo,a=null,c=!1,l=null,f=(w,g)=>{if(clearInterval(w),c=!1,g!==null){ze(),pe(g);return}un(),r()?je({phase:me}):ze()},m=()=>{if(c||a===null||!e.isIdle())return;let w=a;a=null,l?.(),l=null,c=!0,je({phase:me});let g=setInterval(()=>je({phase:me}),i);g.unref?.(),ln();let z=!1,ce=L=>{z||(z=!0,f(g,L))};try{t(w,ce)}catch(L){ce(L instanceof Error?L.message:String(L))}};return w=>{if(a=w,e.isIdle()){m();return}l??=e.onIdle(m)}}function Vo(){let e=process.env.CORTEX_REPO;if(!e)return!1;try{return _e.existsSync(e)&&_e.statSync(e).isDirectory()}catch{return!1}}async function qo(){let e=Be(["view","@cortex-agent/server","version"]),t=await J(e.command,e.args,{shell:e.shell,timeoutMs:15e3,cwd:Xe.tmpdir()});return t.ok&&t.stdout.trim()||null}var zo=2e3;function Xo(e,t,o){let r=t!==null?`killed by ${t}`:`exited with code ${e}`,i=o.trim().split(`
|
|
5
|
-
`).slice(-6).join(`
|
|
6
|
-
`).trim();return i?`npm install -g ${r}
|
|
7
|
-
${i}`:`npm install -g ${r}`}function Yo(e,t){let o=Be(Ft(["install","-g",`@cortex-agent/server@${e}`])),r=Go(o.command,o.args,{shell:o.shell,detached:!0,stdio:["ignore","ignore","pipe"],cwd:Xe.tmpdir()}),i="";r.stderr?.on("data",a=>{i.length<zo&&(i+=String(a))}),r.stderr?.unref?.(),r.on("error",a=>t(`npm install -g could not start: ${a.message}`)),r.on("exit",(a,c)=>t(a===0?null:Xo(a,c,i))),r.unref()}function Zo(){return new Date().toISOString()}function ua(e){return new Te({prompt:e.prompt,getLatest:e.getLatest??qo,installWhenIdle:e.installWhenIdle??gn(e.idle??hn,nn(Yo)),loadState:e.loadState??dn,saveState:e.saveState??pn,now:e.now??Zo,isDevMode:Vo})}import{readFileSync as wn,existsSync as Ko}from"fs";import*as Sn from"path";var U=h("machine-registry"),te=Sn.join(Et,"machines.json"),fe={},bn=!1,Pe=null,Y=null;function Jo(e,t){if(typeof t.cortexPath!="string"||typeof t.gpuCount!="number")throw new Error(`Invalid machine entry "${e}": requires cortexPath (string) and gpuCount (number)`);let o=t.clientConnection??"direct";if(o!=="direct"&&o!=="ssh-reverse")throw new Error(`Invalid machine entry "${e}": clientConnection must be direct or ssh-reverse`);if(o==="ssh-reverse"&&!t.ssh?.trim())throw new Error(`Invalid machine entry "${e}": ssh-reverse requires ssh`);if(t.clientReversePort!==void 0){if(o!=="ssh-reverse")throw new Error(`Invalid machine entry "${e}": clientReversePort requires ssh-reverse`);if(!Number.isInteger(t.clientReversePort)||t.clientReversePort<1024||t.clientReversePort>65535)throw new Error(`Invalid machine entry "${e}": clientReversePort must be an integer in 1024..65535`)}}var he=null;function wa(e){he=e}var In=null;function Sa(e){In=e}function Qo(e,t,o){e!==t?(U.info(`Hot-reload: machines changed [${e}] \u2192 [${t}]`),he?.(`${X.refresh} \`machines.json\` hot-reloaded: [${e}] \u2192 [${t}]`)):(U.info(`Hot-reload: ${o} machines reloaded`),he?.(`${X.refresh} \`machines.json\` hot-reloaded (${o} machines)`)),In?.()}function yn(e=!0){try{let t=wn(te,"utf-8"),o=JSON.parse(t);for(let[c,l]of Object.entries(o))Jo(c,l);let r=Object.keys(fe).sort().join(","),i=Object.keys(o).sort().join(","),a=bn;fe=o,bn=!0,a?Qo(r,i,Object.keys(o).length):U.info(`Loaded ${Object.keys(o).length} machines: ${Object.keys(o).join(", ")}`)}catch(t){let o=`[machine-registry] Failed to load ${te}: ${t.message}`;if(e)throw new Error(o);U.error(o+" \u2014 keeping previous config"),he?.(`${X.warning} \`machines.json\` hot-reload FAILED \u2014 keeping previous config`)}}function Ae(){return fe}var er=64;function tr(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=er}function nr(e,t){try{let o=JSON.parse(wn(te,"utf-8"));return o[e]?(o[e].gpuCount=t,xt(te,`${JSON.stringify(o,null,2)}
|
|
8
|
-
`),!0):!1}catch(o){return U.error(`Failed to persist gpuCount for ${e}: ${o.message}`),!1}}function xn(e,t){let o=fe[e];if(!o||!tr(t))return"skipped";if(o.gpuCount===t)return"unchanged";if(!nr(e,t))return"skipped";let r=o.gpuCount;return o.gpuCount=t,U.info(`${e}: gpuCount ${r} \u2192 ${t} (client-reported)`),he?.(`${X.refresh} \`${e}\` gpuCount ${r} \u2192 ${t} (reported by its client)`),"updated"}function Ia(){return Object.keys(fe)[0]||"local"}function or(){Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=null,yn(!1)},300)}function ya(){Pe?.close(),Pe=Ct({label:"machines.json",filePath:te,onChange:or,warn:e=>U.error(e)})}function xa(){Pe?.close(),Pe=null,Y&&clearTimeout(Y),Y=null}if(Ko(te))try{yn()}catch(e){U.error(`Auto-load failed: ${e.message}`)}var rr=3e4,sr=h("hook-bus"),vn=[],En=null;function ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ar(e,t){return e===void 0?!0:ir(e)?Object.entries(e).every(([o,r])=>Object.hasOwn(t,o)&&t[o]===r):!1}function cr(e,t){let o=e.run.script===void 0?void 0:Kt(e.run.script,En??Zt());return{id:e.id,command:o===void 0?e.run.command:"node",args:o,timeoutMs:e.run.timeout===void 0?t:e.run.timeout*1e3,result:e.result}}function lr(e,t,o){return vn.filter(r=>r.enabled!==!1).filter(r=>r.event===e).filter(r=>ar(r.matcher,t)).map(r=>cr(r,o))}function Ye(e,t){let o=t instanceof Error?t.message:String(t);return sr.error(`Hook ${e} failed: ${o}`),{id:e,error:o}}function ur(e,t){return e.result==="stdout-as-prompt"?{id:e.id,result:t.trim()}:{id:e.id}}function dr(e,t,o){let r=ur(e,t);return o?{...r,stderr:o}:r}async function pr(e,t,o){try{let r=await Yt({command:e.command,args:e.args,timeoutMs:e.timeoutMs,stdinPayload:t,env:o,label:e.id});return r.error?Ye(e.id,r.error):dr(e,r.stdout,r.stderr)}catch(r){return Ye(e.id,r)}}function Ca(e){vn=[...e.entries],En=e.scriptDirs??null}function mr(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("Hook payload is not JSON-serializable");return t}async function Ze(e,t,o){let r=[...lr(e,t,o?.defaultTimeoutMs??rr),...o?.scopedHooks??[]];if(r.length===0)return[];let i;try{i=mr(t)}catch(c){return r.map(l=>Ye(l.id,c))}let a=[];for(let c of r)a.push(await pr(c,i,o?.env));return a}var Ke=null;function $n(e){Ke=e}function ja(e,t){if(!(!Ke||!Ut()))try{Ke(e,t)}catch{}}function ge(e,t=1){t<=0||P(o=>{o.features[e]=(o.features[e]??0)+t})}function fr(e){P(t=>{t.messagesByChannel[e]=(t.messagesByChannel[e]??0)+1})}function La(e){return e.startsWith("slack")?"slack":e.startsWith("feishu")?"feishu":e.startsWith("tui")?"tui":"other"}function hr(e){P(t=>{t.uiOps[e]=(t.uiOps[e]??0)+1})}var gr=new Set(["sessions.send","sessions.createAndSend"]),br=new Set(["sessions.create","sessions.createAndSend"]);function Fa(e,t,o){hr(e),t&&(gr.has(e)&&fr(o??"other"),br.has(e)&&(ge("session_created"),de("first_session")))}var wr={"/webhook/subagent":{start:"subagent_run"},"/webhook/team":{spawn:"worker_spawned"},"/webhook/board":{open:"board_opened"},"/webhook/waitpoint":{create:"waitpoint_created"}},De={day:"",ids:new Set};function Sr(e){let t=Jt(Date.now());De.day!==t&&Object.assign(De,{day:t,ids:new Set});let o=typeof e=="string"?e:"";De.ids.has(o)||(De.ids.add(o),ge("browser_session"))}function Na(e,t){let o=t??{};if(e==="/webhook/browser"&&o.action==="lease")return Sr(o.sessionId);let r=wr[e??""]?.[String(o.action)];r&&(ge(r),r==="worker_spawned"&&de("first_worker"))}function Ua(e=1){e<=0||(ge("schedule_created",e),de("first_schedule"))}function kn(){ge("remote_client_connected"),de("first_remote_client")}function Cn(){P(e=>{e.perf.remoteClientDisconnects+=1})}function Ba(e){P(t=>Qt(t,e))}var Tn=[];function Ha(e,t=performance.now()){Tn.push([e,t])}function Wa(e,t=performance.now()){let o={imports:Math.round(e)},r=e;for(let[i,a]of Tn)o[i]=Math.max(0,Math.round(a-r)),r=a;o.total=Math.round(t),P(i=>{i.perf.startups.push(o),i.perf.startups.length>10&&i.perf.startups.shift()})}var Ir=/^(?::[A-Za-z][A-Za-z0-9_]{0,30}|\*|[a-z][a-z-]{0,23})$/;function yr(e){return!e||e.length>80||!e.startsWith("/")?null:e.split("/").filter(o=>o!=="").every(o=>Ir.test(o))?e:null}function xr(e){P(({perf:{web:t}})=>{t.loads+=1,e.ttfbMs!==null&&(t.ttfbMs[$e("webLoadMs",e.ttfbMs)]+=1),e.firstRenderMs!==null&&(t.firstRenderMs[$e("webLoadMs",e.firstRenderMs)]+=1),e.interactiveMs!==null&&(t.interactiveMs[$e("webLoadMs",e.interactiveMs)]+=1)})}function vr(e,t){if(e.kind==="crash"){let{crashKind:r,errorName:i,message:a,stack:c,buildStamp:l,uptimeS:f}=e;return Ge({component:"web",kind:r,errorName:i,message:a,stack:c,buildStamp:l,uptimeS:f,client:t,route:yr(e.route)})}if(e.kind!=="native_crash")return;let o=new Date(e.at);Ge({component:e.component,kind:"panic",errorName:"panic",message:e.message,stack:e.stack,buildStamp:e.appVersion,client:t,at:Number.isNaN(o.getTime())?new Date:o})}function Er(e,t){if(e.kind==="load")return xr(e);if(e.kind==="sse_reconnect")return P(o=>{o.perf.sseReconnects+=e.count});vr(e,t)}function Ga(){$n(Er)}import*as Mn from"crypto";import*as jn from"crypto";var $r=h("reverse-stream"),kr="/reverse",Rn=1e4,Cr=64,B=new Map;function _n(e){if(!e)return null;let t=new URL(e,"http://placeholder");if(t.pathname!==kr)return null;let o=t.searchParams.get("stream");return o&&/^[0-9a-f]{32}$/.test(o)?o:null}function Pn(e,t){if(B.size>=Cr)throw new Error(`too many pending reverse streams (${B.size})`);let o=jn.randomBytes(16).toString("hex"),r,i,a=new Promise((l,f)=>{r=l,i=f}),c=setTimeout(()=>{B.delete(o),i(new Error(`device ${e} did not open a stream to ${t} within ${Rn}ms`))},Rn);return c.unref?.(),B.set(o,{device:e,target:t,resolve:r,reject:i,timer:c}),{id:o,socket:a}}function An(e,t,o){let{id:r,socket:i}=Pn(e,`${t}:${o}`);return{id:r,message:{type:"open-stream",streamId:r,host:t,port:o},socket:i}}function za(e,t){let{id:o,socket:r}=Pn(e,t);return{id:o,message:{type:"open-file-stream",streamId:o,path:t},socket:r}}function Dn(e,t){let o=B.get(e);return o?(clearTimeout(o.timer),B.delete(e),$r.info(`stream ${e.slice(0,8)} claimed by ${o.device} \u2192 ${o.target}`),o.resolve(t),!0):!1}function On(e){let t=0;for(let[o,r]of B)r.device===e&&(clearTimeout(r.timer),B.delete(o),r.reject(new Error(`device ${e} disconnected before opening the stream`)),t++);return t}var y=h("client-manager"),Je=null;function nc(e){Je=e}var be=null;function oc(e){be=e}var E=new Map,A=new Map,ne=null,Oe=null,Qe=null,Ln="Server shutting down",Tr=15e3,Rr=12e4,jr=3e4;function Fn(e,t){t!==Ln&&Cn(),Ze("cortex:client.disconnected",t?{device:e,reason:t}:{device:e}).catch(()=>{})}function _r(e,t){for(let[o,r]of A)r.device===e&&(clearTimeout(r.timer),r.reject(t),A.delete(o))}function et(e,t){E.delete(e),y.info(`Device disconnected: ${e}${t?` (${t})`:""}`),Fn(e,t);let o=On(e);o>0&&y.info(`cancelled ${o} pending reverse stream(s) for ${e}`),_r(e,new Error(`Device "${e}" disconnected${t?` (${t})`:""}`)),be?.onDeviceGone(e)}function Nn(e){let t=E.get(e);if(!t)throw new Error(`Device "${e}" is not online`);if(t.ws.readyState!==Rt.default.OPEN)throw et(e,"WebSocket is not open"),new Error(`Device "${e}" WebSocket is not open`);return t.ws}function Pr(e){return!!e&&(e==="::1"||/^(::ffff:)?127\./.test(e))}function Ar(e,t){if(!t)return e.close(4001,"Missing device name"),!1;if(!Object.hasOwn(Ae(),t))return e.close(4005,"Unknown device"),!1;let o=E.get(t);return o&&o.ws!==e?(y.info(`Device ${t} already connected, rejecting new connection`),e.close(4002,"Device already connected"),!1):!0}function Dr(e,t,o){let r=t.device;if(!Ar(e,r))return null;let i=typeof t.bundleHash=="string"&&t.bundleHash?t.bundleHash:null,a=t.platform||"unknown";E.set(r,{device:r,platform:a,capabilities:t.capabilities||[],connectedAt:new Date,lastHeartbeat:new Date,bundleHash:i,ws:e}),y.info(`Device connected: ${r} (${a})`),kn(),Ze("cortex:client.connected",{device:r}).catch(()=>{}),xn(r,typeof t.gpuCount=="number"?t.gpuCount:null);try{Je?.onHello(r,i)}catch(l){y.warn(`onHello hook failed for ${r}: ${l.message}`)}let c=typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0?t.pid:null;try{be?.onHello?.(r,{pid:c,loopback:Pr(o)})}catch(l){y.warn(`lifecycle hello hook failed for ${r}: ${l.message}`)}return r}function Or(e){try{let t=JSON.parse(e);return t&&typeof t.type=="string"?t:null}catch{return null}}function Mr(e){let t=e.commandId?A.get(e.commandId):void 0;t&&(A.delete(e.commandId),clearTimeout(t.timer),e.success?t.resolve(e.data):t.reject(new Error(e.error||"Command failed")))}function Lr(e,t){try{Je?.onUpdateResult(e,{ok:!!t.ok,hash:typeof t.hash=="string"?t.hash:void 0,error:typeof t.error=="string"?t.error:void 0})}catch(o){y.warn(`onUpdateResult hook failed for ${e}: ${o.message}`)}}function Fr(e,t){if(e.type==="result")return Mr(e);if(t)if(e.type==="heartbeat"){let o=E.get(t);o&&(o.lastHeartbeat=new Date)}else e.type==="update-result"&&Lr(t,e)}function Nr(e,t){let o=e.req.headers[Dt],r=Array.isArray(o)?o[0]:o;if(Ot(Mt(),r))return t(!0);let i=e.req.socket?.remoteAddress||"unknown";y.warn(`WS auth rejected from ${i}: ${r?"invalid token":"missing token"}`),t(!1,401,"Unauthorized")}function Ur(e,t){let o=null;e.on("message",r=>{let i=Or(r.toString());i?.type==="hello"?o=Dr(e,i,t):i&&Fr(i,o)}),e.on("close",(r,i)=>{o&&E.get(o)?.ws===e&&et(o,i.toString().trim()||void 0)}),e.on("error",r=>{y.error(`WebSocket error for ${o||"unknown"}: ${r.message}`)})}function Br(e,t){let o=_n(t.url);if(!o)return Ur(e,t.socket?.remoteAddress);Dn(o,e)||(y.warn("reverse callback with an unknown stream id \u2014 closing"),e.close(4004,"Unknown stream"))}function Hr(){let e=Date.now(),t=[...E.values()].filter(o=>e-o.lastHeartbeat.getTime()>Tr);for(let o of t)if(E.get(o.device)===o){try{o.ws.close(4003,"Heartbeat timeout")}catch{}et(o.device,"Heartbeat timeout")}}function rc(e,t){if(ne){y.warn("Already running");return}Qe=e,be?.onStart(),ne=new jt.default({port:e,host:t,verifyClient:Nr}),y.info(`WebSocket server started on port ${e}`),ne.on("connection",Br),ne.on("error",o=>{y.error(`Server error: ${o.message}`)}),Oe=setInterval(Hr,5e3)}async function sc(){Oe&&clearInterval(Oe),Oe=null;for(let[t,o]of A)clearTimeout(o.timer),o.reject(new Error("Client manager shutting down")),A.delete(t);for(let[,t]of E){try{t.ws.close(1001,"Server shutting down")}catch{}Fn(t.device,Ln)}E.clear();let e=ne;ne=null,e&&e.close(),await be?.onStop(),Qe=null,e&&y.info("WebSocket server stopped")}function Me(){let e=[];for(let[,t]of E)e.push({device:t.device,platform:t.platform,connectedAt:t.connectedAt,lastHeartbeat:t.lastHeartbeat,capabilities:t.capabilities,bundleHash:t.bundleHash});return e}function Un(e){return E.has(e)}function ic(){return Qe}function Bn(e,t){Nn(e).send(JSON.stringify(t))}function Hn(e,t){let o;try{o=Nn(e)}catch(a){return Promise.reject(a)}let r=Mn.randomBytes(8).toString("hex"),i=t.timeout||(t.action==="bash"?Rr:jr);return new Promise((a,c)=>{let l=setTimeout(()=>{A.delete(r),c(new Error(`Command to "${e}" timed out after ${i/1e3}s`))},i);A.set(r,{resolve:a,reject:c,timer:l,device:e});try{let f={type:"command",commandId:r,action:t.action,params:t.params};o.send(JSON.stringify(f))}catch(f){A.delete(r),clearTimeout(l),c(new Error(`Failed to send command to "${e}": ${f.message}`))}})}import*as Gn from"net";var H=h("device-port"),Wn="127.0.0.1",Vn="127.0.0.1",Wr=32,Gr=64,W=new Map;function qn(e,t,o){return`${e}|${t}|${o}`}function Vr(e,t,o){let r=!1,i=a=>{if(!r){r=!0,H.debug(`${o} closed: ${a}`);try{t.close()}catch{}try{e.destroy()}catch{}}};t.on("message",a=>{let c=Array.isArray(a)?Buffer.concat(a):Buffer.from(a);e.write(c)||(t.pause?.(),e.once("drain",()=>t.resume?.()))}),t.on("error",a=>i(`ws error: ${a.message}`)),t.on("close",()=>i("ws closed")),e.on("data",a=>{e.pause(),t.send(a,c=>{c?i(`send failed: ${c.message}`):e.resume()})}),e.on("error",a=>i(`tcp error: ${a.message}`)),e.on("close",()=>i("tcp closed")),e.resume()}var qr=Bn;async function zr(e,t){let{device:o,remoteHost:r,remotePort:i}=e.info;if(t.pause(),t.setNoDelay(!0),e.connections.add(t),t.once("close",()=>e.connections.delete(t)),e.connections.size>Gr){H.warn(`${o}:${i} \u2014 connection cap reached, refusing`),t.destroy();return}let a;try{a=An(o,r,i)}catch(l){H.warn(`${o}:${i} \u2014 ${l.message}`),t.destroy();return}a.socket.catch(()=>{});try{qr(o,a.message)}catch(l){H.warn(`${o}:${i} \u2014 cannot ask device to open a stream: ${l.message}`),t.destroy();return}let c;try{c=await a.socket}catch(l){H.warn(`${o}:${i} \u2014 ${l.message}`),t.destroy();return}if(t.destroyed){try{c.close()}catch{}return}Vr(t,c,`${o}:${i} stream ${a.id.slice(0,8)}`)}async function zn(e,t){let o=Vn,r=qn(e,o,t),i=W.get(r);if(i)return i.info;if(W.size>=Wr)throw new Error(`too many device ports open (${W.size})`);let a=Gn.createServer(),c={info:{device:e,remoteHost:o,remotePort:t,localPort:0,openedAt:new Date},server:a,connections:new Set};await new Promise((f,m)=>{a.once("error",m),a.listen(0,Wn,()=>{a.removeListener("error",m),f()})});let l=a.address();if(!l||typeof l=="string")throw a.close(),new Error("failed to bind a local port");return c.info.localPort=l.port,a.on("connection",f=>{zr(c,f)}),a.on("error",f=>H.warn(`listener for ${e}:${t} failed: ${f.message}`)),W.set(r,c),H.info(`device port ${Wn}:${l.port} \u2192 ${e} ${o}:${t}`),c.info}function oe(e,t){let o=Vn,r=qn(e,o,t),i=W.get(r);if(!i)return!1;W.delete(r);for(let a of i.connections)a.destroy();return i.connections.clear(),i.server.close(),H.info(`closed device port ${i.info.localPort} \u2192 ${e} ${o}:${t}`),!0}function dc(){return[...W.values()].map(e=>({...e.info}))}function pc(){for(let e of[...W.values()])oe(e.info.device,e.info.remotePort)}import*as Ie from"fs";import*as no from"net";import*as oo from"path";import{spawn as ro}from"child_process";import*as re from"fs";import*as tt from"path";import{execFile as Xr,spawn as Yr}from"child_process";import{promisify as Zr}from"util";var Kr=Zr(Xr),Xn=h("browser-display");function Jr(e){if(e.override)return{mode:"attached",display:e.override,takeover:"remote-desktop",reason:`display pinned by configuration (${e.override})`};if(e.platform==="linux"){if(e.envDisplay&&e.usableDisplays.includes(e.envDisplay))return{mode:"attached",display:e.envDisplay,takeover:"remote-desktop",reason:`$DISPLAY ${e.envDisplay} is reachable`};if(e.usableDisplays.length>0){let t=e.usableDisplays[0];return{mode:"attached",display:t,takeover:"remote-desktop",reason:`graphical session ${t} belongs to this user and is reachable`}}return e.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 e.platform==="darwin"||e.platform==="win32"?e.interactiveSession?{mode:"attached",display:null,takeover:"remote-desktop",reason:"running inside an interactive desktop session"}:{mode:"headless",display:null,takeover:"none",reason:e.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 ${e.platform}`}}async function Qr(){let e;try{e=await re.promises.readdir("/tmp/.X11-unix")}catch{return[]}let t=typeof process.getuid=="function"?process.getuid():-1;return(await Promise.all(e.filter(r=>/^X\d+$/.test(r)).map(async r=>{try{let a=await re.promises.stat(`/tmp/.X11-unix/${r}`);if(t>=0&&a.uid!==t)return null}catch{return null}let i=`:${r.slice(1)}`;return await es(i)?i:null}))).filter(r=>r!==null).sort((r,i)=>Number(r.slice(1))-Number(i.slice(1)))}async function es(e){let t=[["xdpyinfo",["-display",e]],["xset",["-display",e,"q"]]];for(let[o,r]of t){let i=await Yn(o,r,3e3);if(i!=="missing")return i===0}return Xn.warn("neither xdpyinfo nor xset is installed \u2014 trusting X socket ownership"),!0}function Yn(e,t,o){return new Promise(r=>{let i=Yr(e,t,{stdio:"ignore",timeout:o});i.once("error",a=>r(a.code==="ENOENT"?"missing":-1)),i.once("exit",a=>r(a??-1))})}async function nt(e){return await Yn("which",[e],2e3)===0}async function ts(e,t=process.env){if(e==="darwin")try{let{stdout:o}=await Kr("launchctl",["managername"],{encoding:"utf8",timeout:2e3});return o.trim()==="Aqua"}catch{return!1}if(e==="win32"){let o=t.SESSIONNAME;return!!o&&o.toLowerCase()!=="services"}return!1}function Zn(e,t="/tmp"){for(let o=e;o<e+100;o++)if(!(re.existsSync(tt.join(t,`.X${o}-lock`))||re.existsSync(tt.join(t,".X11-unix",`X${o}`))))return o;return null}async function Kn(e=process.env){let t=process.platform,o=e.CORTEX_BROWSER_DISPLAY,r=t==="linux"&&!o,[i,a,c]=await Promise.all([r?Qr():[],r?nt("Xvfb"):!1,o?!1:ts(t,e)]),l=Jr({platform:t,override:o,envDisplay:e.DISPLAY,usableDisplays:i,hasXvfb:a,interactiveSession:c});return Xn.info(`display \u2192 ${l.mode}${l.display?` (${l.display})`:""}: ${l.reason}`),l}var D=h("managed-browser"),Jn=oo.join(vt,"browser","profile"),ns=9222,os=600*1e3,Qn=3e4,eo=1e4,rs=99,ss=3,ot="browser stopped while starting",is=6e4,as=3,b=null,we=null,se=null,R=0,T=null,Se=[],j="server";async function rt(){R++,T&&(clearTimeout(T),T=null);try{return await ao()}catch(e){throw R>0&&R--,e}}function st(){R!==0&&(R--,R===0&&cs())}function so(){return{running:!!b,refs:R,browser:b?{cdpEndpoint:b.cdpEndpoint,port:b.port,display:b.display,pid:b.pid}:null}}function xc(){T&&(clearTimeout(T),T=null),R=0,se&&(se.cancelled=!0,Le(se.procs,"SIGTERM")),io()}function cs(){T&&clearTimeout(T),T=setTimeout(()=>{T=null,R===0&&(D.info("no browser sessions left \u2014 reclaiming Chrome"),io())},os),T.unref?.()}function io(){let e=b;b=null,e&&Le([e.proc,...e.xvfb?[e.xvfb]:[]],"SIGTERM")}function Le(e,t){for(let o of e)try{o.kill(t)}catch{}}async function ao(){return b||we||(we=ls().finally(()=>{we=null}),we)}async function ls(){let e={cancelled:!1,procs:[]};se=e;try{return await us(e)}catch(t){throw Le(e.procs,"SIGKILL"),t}finally{se===e&&(se=null)}}async function us(e){let t=()=>{if(e.cancelled)throw new Error(ot)},o=await fs();if(!o)throw new Error("no Chrome/Chromium found \u2014 install Google Chrome, or set CORTEX_BROWSER_BINARY to its path");let r=await Kn();t(),Ie.mkdirSync(Jn,{recursive:!0});let i=await hs(ns);t();let a,c=r.display;if(r.mode==="virtual"){let g=await ps(e);a=g.proc,c=g.display}let l=[`--remote-debugging-port=${i}`,`--user-data-dir=${Jn}`,"--no-first-run","--no-default-browser-check","--disable-features=Translate","--remote-debugging-address=127.0.0.1"];r.mode==="headless"&&l.push("--headless=new"),process.platform==="linux"&&l.push("--password-store=basic");let f={...process.env};c?f.DISPLAY=c:delete f.DISPLAY,D.info(`launching ${o} on port ${i} (${r.mode}${c?` ${c}`:""})`);let m=ro(o,l,{env:f,stdio:"ignore",detached:!1});e.procs.push(m);let w=null;return m.on("exit",(g,z)=>ds(m,g,z)),m.on("error",g=>{w=g.message,D.error(`Chrome failed to spawn: ${g.message}`)}),await gs(i,()=>e.cancelled?ot:w?`Chrome failed to spawn: ${w}`:m.exitCode!==null||m.signalCode!==null?`Chrome exited during startup (code=${m.exitCode} signal=${m.signalCode})`:null),t(),b={cdpEndpoint:`http://127.0.0.1:${i}`,port:i,display:{...r,display:c},pid:m.pid??-1,proc:m,xvfb:a},D.info(`Chrome ready at ${b.cdpEndpoint} (pid ${b.pid})`),b}function ds(e,t,o){if(!b||b.proc!==e||(D.warn(`Chrome exited (code=${t} signal=${o})`),b.xvfb?.kill("SIGTERM"),b=null,R===0))return;let r=Date.now();if(Se=Se.filter(i=>r-i<is),Se.length>=as){D.error("Chrome crashed repeatedly \u2014 giving up until the next acquire"),Se=[];return}Se.push(r),D.info(`${R} session(s) still need a browser \u2014 restarting`),ao().catch(i=>D.error(`restart failed: ${String(i)}`))}async function ps(e){let t=rs,o="no free display number";for(let r=0;r<ss;r++){let i=Zn(t);if(i===null)break;let a=`:${i}`,c=ro("Xvfb",[a,"-screen","0","1920x1080x24","-nolisten","tcp","-displayfd","3"],{stdio:["ignore","ignore","ignore","pipe"]});e.procs.push(c);let l=await ms(c);if(e.cancelled)throw new Error(ot);if(!l)return{proc:c,display:a};o=`${a}: ${l}`,D.warn(`Xvfb ${o}`),Le([c],"SIGKILL"),t=i+1}throw new Error(`Xvfb could not start a virtual display (${o})`)}function ms(e){return new Promise(t=>{let o=!1,r="",i=l=>{o||(o=!0,clearTimeout(a),t(l))},a=setTimeout(()=>i(`not ready within ${eo}ms`),eo),c=e.stdio[3];c?.on("data",l=>{r+=String(l),r.includes(`
|
|
9
|
-
`)&&i(null)}),c?.on("error",()=>{}),e.once("exit",(l,f)=>i(`exited (code=${l} signal=${f})`)),e.once("error",l=>i(l.message))})}async function fs(e=process.env){if(e.CORTEX_BROWSER_BINARY)return Ie.existsSync(e.CORTEX_BROWSER_BINARY)?e.CORTEX_BROWSER_BINARY:null;let t=process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:process.platform==="win32"?[`${e.ProgramFiles??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${e["ProgramFiles(x86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${e.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`]:[];for(let o of t)try{if(Ie.existsSync(o))return o}catch{}for(let o of["google-chrome","google-chrome-stable","chromium","chromium-browser","chrome"])if(await nt(o))return o;return null}async function hs(e){if(await to(e))return e;for(let t=e+1;t<e+20;t++)if(await to(t))return t;throw new Error(`no free CDP port near ${e}`)}function to(e){return new Promise(t=>{let o=no.createServer();o.once("error",()=>t(!1)),o.once("listening",()=>o.close(()=>t(!0))),o.listen(e,"127.0.0.1")})}async function gs(e,t){let o=Date.now()+Qn,r="";for(;Date.now()<o;){let i=t();if(i)throw new Error(i);try{let a=await fetch(`http://127.0.0.1:${e}/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 ${e} within ${Qn}ms (${r})`)}var co=".cortex/browser/profile",Fe="DevToolsActivePort";function bs(e){return e==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:[]}var ws=["google-chrome","google-chrome-stable","chromium","chromium-browser","chrome"],it="Cortex Managed Browser",Ss=`
|
|
10
|
-
$ErrorActionPreference = "Stop"
|
|
11
|
-
$profile = Join-Path $env:USERPROFILE ".cortex\\browser\\profile"
|
|
12
|
-
$portFile = Join-Path $profile "${Fe}"
|
|
13
|
-
New-Item -ItemType Directory -Force -Path $profile | Out-Null
|
|
14
|
-
if ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0) {
|
|
15
|
-
Get-Content -LiteralPath $portFile -TotalCount 1
|
|
16
|
-
exit 0
|
|
17
|
-
}
|
|
18
|
-
$candidates = @(
|
|
19
|
-
(Join-Path $env:ProgramFiles "Google\\Chrome\\Application\\chrome.exe"),
|
|
20
|
-
(Join-Path ([Environment]::GetEnvironmentVariable("ProgramFiles(x86)")) "Google\\Chrome\\Application\\chrome.exe"),
|
|
21
|
-
(Join-Path $env:LOCALAPPDATA "Google\\Chrome\\Application\\chrome.exe")
|
|
22
|
-
)
|
|
23
|
-
$chrome = $candidates | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
|
|
24
|
-
if (-not $chrome) {
|
|
25
|
-
foreach ($name in @("google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome")) {
|
|
26
|
-
$found = Get-Command $name -ErrorAction SilentlyContinue
|
|
27
|
-
if ($found) { $chrome = $found.Source; break }
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
if (-not $chrome) { [Console]::Error.WriteLine("chrome-not-found"); exit 3 }
|
|
31
|
-
$user = (Get-CimInstance Win32_ComputerSystem).UserName
|
|
32
|
-
if (-not $user) { [Console]::Error.WriteLine("no-interactive-user"); exit 5 }
|
|
33
|
-
$current = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
|
34
|
-
if ($user -ine $current) { [Console]::Error.WriteLine("interactive-user-mismatch"); exit 6 }
|
|
35
|
-
$quote = [char]34
|
|
36
|
-
$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"
|
|
37
|
-
$action = New-ScheduledTaskAction -Execute $chrome -Argument $arguments
|
|
38
|
-
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
|
|
39
|
-
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew
|
|
40
|
-
Register-ScheduledTask -TaskName "${it}" -Action $action -Principal $principal -Settings $settings -Force | Out-Null
|
|
41
|
-
Start-ScheduledTask -TaskName "${it}"
|
|
42
|
-
for ($i = 0; $i -lt 60; $i++) {
|
|
43
|
-
if ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0) { break }
|
|
44
|
-
Start-Sleep -Milliseconds 500
|
|
45
|
-
}
|
|
46
|
-
if (-not ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0)) {
|
|
47
|
-
[Console]::Error.WriteLine("chrome-did-not-listen")
|
|
48
|
-
exit 4
|
|
49
|
-
}
|
|
50
|
-
Get-Content -LiteralPath $portFile -TotalCount 1
|
|
51
|
-
`.trim();function Is(e){let t=bs(e).map(o=>` [ -f "${o}" ] && { CHROME="${o}"; }`).join(`
|
|
52
|
-
`);return[`PROFILE="$HOME/${co}"`,`PORTFILE="$PROFILE/${Fe}"`,'mkdir -p "$PROFILE"','if [ -s "$PORTFILE" ]; then head -1 "$PORTFILE"; exit 0; fi','CHROME=""',...t?[`if [ -z "$CHROME" ]; then :
|
|
53
|
-
${t}
|
|
54
|
-
fi`]:[],`for b in ${ws.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(`
|
|
55
|
-
`)}function lo(e){return e==="win32"?`powershell.exe -NoProfile -Command '${Ss}' </dev/null`:Is(e)}function at(e){let t=`"$HOME/${co}"`;return e==="win32"?[`powershell.exe -NoProfile -Command '${['$ErrorActionPreference = "SilentlyContinue"',`Stop-ScheduledTask -TaskName "${it}" -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(`
|
|
56
|
-
`)}' </dev/null >/dev/null 2>&1 || true`,`rm -f ${t}/${Fe}`].join(`
|
|
57
|
-
`):[`pkill -f -- ${t} >/dev/null 2>&1 || true`,`rm -f ${t}/${Fe}`].join(`
|
|
58
|
-
`)}var ye=h("device-browser"),ys=9e4,xs=5e3,vs=10*6e4,G=new Map;async function lt(e,t,o){let r=await Hn(e,{action:"bash",params:{command:t},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 Es(e){let t=e.split(`
|
|
59
|
-
`).map(r=>r.trim()).filter(r=>/^\d+$/.test(r));if(t.length===0)return null;let o=Number(t[t.length-1]);return o>0&&o<=65535?o:null}function po(e){return Me().find(t=>t.device===e)?.platform??""}async function ct(e){try{return(await fetch(`${e}/json/version`,{signal:AbortSignal.timeout(xs)})).ok}catch{return!1}}async function uo(e,t){let o=await lt(e,lo(t),ys),r=Es(o);if(r===null)throw new Error(`device ${e} reported no debugging port`);let i=await zn(e,r);return{device:e,remotePort:r,cdpEndpoint:`http://127.0.0.1:${i.localPort}`,refs:0,idleTimer:null}}async function ut(e){let t=po(e),o=G.get(e);if(o){if(o.idleTimer&&(clearTimeout(o.idleTimer),o.idleTimer=null),await ct(o.cdpEndpoint))return o.refs++,{device:e,remotePort:o.remotePort,cdpEndpoint:o.cdpEndpoint};ye.info(`${e}: mapped browser no longer answers \u2014 relaunching`),oe(e,o.remotePort),G.delete(e)}let r=await uo(e,t);if(!await ct(r.cdpEndpoint)&&(ye.info(`${e}: adopted debugging port ${r.remotePort} is dead \u2014 stopping and relaunching`),oe(e,r.remotePort),await lt(e,at(t),3e4),r=await uo(e,t),!await ct(r.cdpEndpoint)))throw oe(e,r.remotePort),new Error(`device ${e} launched Chrome but its debugging port is unreachable`);return r.refs=1,G.set(e,r),ye.info(`${e}: browser on device port ${r.remotePort} \u2192 ${r.cdpEndpoint}`),{device:e,remotePort:r.remotePort,cdpEndpoint:r.cdpEndpoint}}function $s(e){e.idleTimer=setTimeout(()=>{e.refs>0||(ye.info(`${e.device}: no browser sessions left \u2014 reclaiming Chrome`),ks(e.device).catch(t=>ye.warn(`${e.device}: could not stop Chrome: ${t.message}`)))},vs),e.idleTimer.unref?.()}function mo(e){let t=G.get(e);t&&(t.refs=Math.max(0,t.refs-1),t.refs===0&&!t.idleTimer&&$s(t))}async function ks(e){let t=G.get(e);t?.idleTimer&&clearTimeout(t.idleTimer),G.delete(e),t&&oe(e,t.remotePort),await lt(e,at(po(e)),3e4)}function Rc(){for(let e of G.values())e.idleTimer&&clearTimeout(e.idleTimer);G.clear()}var V=h("browser-broker"),Cs=10*6e4,Ts=15e3,Rs=5e3,$=class extends Error{code;hint;constructor(t,o,r){super(o),this.name="BrowserLeaseError",this.code=t,this.hint=r}};function Ne(e){return typeof e=="string"?e.trim():""}function js(e,t){let o=t.trim(),r="or run without --device to use the server's browser";return o.includes("chrome-not-found")?{message:`Chrome is not installed on ${e}`,hint:`install Google Chrome on ${e}, ${r}`}:o.includes("no-interactive-user")?{message:`nobody is logged in to the desktop on ${e}`,hint:`log in on ${e}, ${r}`}:o.includes("interactive-user-mismatch")?{message:`the Cortex client on ${e} runs as a different user than the desktop session`,hint:`run the Cortex client as the logged-in user on ${e}`}:o.includes("chrome-did-not-listen")?{message:`Chrome on ${e} did not open its debugging port in time`,hint:`close any Chrome window still using the Cortex profile on ${e} and retry`}:/timed out/i.test(o)?{message:`${e} did not answer while starting Chrome (${o})`,hint:`check that ${e} is awake and its Cortex client is connected`}:{message:`could not start Chrome on ${e}: ${o||"unknown error"}`}}function _s(e){let t=new Map,o=new Map,r=new Map,i=new Map,a=new Set,c=null;function l(){for(let s of a)try{s()}catch(u){V.warn(`listener failed: ${u.message}`)}}function f(s,u,d){let S=(s.get(u)??Promise.resolve()).catch(()=>{}).then(d),x=S.catch(()=>{});return s.set(u,x),x.then(()=>{s.get(u)===x&&s.delete(u)}),S}function m(){if(c)return c;try{c={bin:e.resolveBin(),env:e.baseEnv()}}catch(s){throw s instanceof Ht?new $("engine-missing",s.message,s.hint):s}return c}function w(s){s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{if(s.idleTimer=null,s.takenOver){w(s);return}t.get(s.sessionId)===s&&(V.info(`${s.sessionId}: browser idle for ${Math.round(e.idleMs/6e4)} min \u2014 releasing`),f(o,s.sessionId,async()=>{t.get(s.sessionId)===s&&!s.takenOver&&await z(s)}))},e.idleMs),s.idleTimer.unref?.()}function g(s){s.lastUsedAt=e.now(),w(s)}async function z(s){if(s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=null,t.get(s.sessionId)===s&&t.delete(s.sessionId),i.delete(s),s.holdsRef&&(s.holdsRef=!1,e.release(s.device)),l(),!(!s.cdpEndpoint||!c))for(let u of[["tab","close"],["close"]])await e.run(c.bin,K(s.cdpEndpoint,s.abSession,u),c.env).catch(()=>{})}function ce(s,u){return s.holdsRef&&(s.holdsRef=!1,e.release(s.device)),i.delete(s),s.state="error",s.error=u.hint?`${u.message} \u2014 ${u.hint}`:u.message,s.cdpEndpoint=null,l(),u}function L(s){if(s===j)return;let{state:u,online:d}=e.availability(s);if(u==="online")return;let p=d.length?`online devices: ${["server",...d].join(", ")}`:"no devices are online";throw u==="offline"?new $("device-offline",`device "${s}" is offline`,`start its Cortex client, or pick another device (${p})`):new $("unknown-device",`unknown device "${s}"`,`use one of: server${d.length?`, ${d.join(", ")}`:""}`)}function gt(s,u){if(u instanceof $)return u;let d=u?.message??String(u);if(s===j)return new $("chrome-failed",`could not start Chrome on the server: ${d}`);let{message:p,hint:S}=js(s,d);return new $("chrome-failed",p,S)}function ko(s){return s===j?e.acquire(s):f(r,s,()=>e.acquire(s))}async function Co(s){try{L(s.device),m(),s.cdpEndpoint=await ko(s.device),s.holdsRef=!0,await St(s),s.state="ready",s.error=void 0,i.set(s,e.now()),V.info(`${s.sessionId}: browser ready on ${s.device} (${s.abSession})`)}catch(u){throw ce(s,gt(s.device,u))}l()}async function To(s){if(!(!(s.device===j||e.now()-(i.get(s)??0)>=Ts)||!s.cdpEndpoint))try{L(s.device);let d=await(s.device===j?e.refresh(s.device,s.cdpEndpoint):f(r,s.device,()=>e.refresh(s.device,s.cdpEndpoint)));i.set(s,e.now()),d!==s.cdpEndpoint&&(V.info(`${s.sessionId}: ${s.device} browser moved to ${d}`),s.cdpEndpoint=d,l())}catch(d){throw ce(s,gt(s.device,d))}}function bt(s,u,d){return f(o,s,async()=>{let p=t.get(s);if(d&&p?.takenOver)throw new $("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 S=u||p?.device||j;if(p&&(p.device!==S||p.state==="error")){let jo=p.takenOver;await z(p),p=void 0,jo&&V.info(`${s}: switching device ends the takeover`)}if(p?.state==="ready")return await To(p),g(p),p;let x={sessionId:s,device:S,abSession:Gt(s,S),state:"starting",cdpEndpoint:null,holdsRef:!1,takenOver:!1,lastUsedAt:e.now(),idleTimer:null,refreshing:!1,refreshAgain:!1};return t.set(s,x),g(x),l(),await Co(x),x})}function wt(s){let u=t.get(s);if(!u)throw new $("no-lease",`session ${s} has no browser`);return u}function Ro(s){let u=wt(s);if(u.state!=="ready"||!u.cdpEndpoint)throw new $("no-lease",`the browser for session ${s} is ${u.state}`);return u}async function Ee(s,u){let d=m(),p=()=>e.run(d.bin,K(s.cdpEndpoint,s.abSession,u),d.env),S=await p();return S.code===0||!qt(S.stderr)||(V.info(`${s.sessionId}: bound tab is gone \u2014 opening a new one`),(await e.run(d.bin,K(s.cdpEndpoint,s.abSession,["tab","new"]),d.env)).code!==0)?S:(await St(s),p())}async function St(s){let u=m(),d=await e.run(u.bin,K(s.cdpEndpoint,s.abSession,Vt),u.env).catch(p=>({code:-1,stdout:"",stderr:String(p)}));d.code!==0&&V.warn(`${s.sessionId}: could not set the viewport: ${d.stderr.trim().slice(0,200)}`)}async function It(s){if(s.refreshing){s.refreshAgain=!0;return}s.refreshing=!0;try{do{if(s.refreshAgain=!1,t.get(s.sessionId)!==s||s.state!=="ready"||!c)return;let u=async S=>{let x=await e.run(c.bin,K(s.cdpEndpoint,s.abSession,["--json","get",S]),c.env);if(x.code===0)try{return Ne(JSON.parse(x.stdout)?.data?.[S])||void 0}catch{return}},[d,p]=[await u("url"),await u("title")];(d!==s.url||p!==s.title)&&(s.url=d,s.title=p,l())}while(s.refreshAgain)}finally{s.refreshing=!1}}function yt(s){try{return JSON.parse(s)}catch{return null}}return{async leaseBrowser({sessionId:s,device:u}){let d=Ne(s);if(!d)throw new $("bad-request","no session id","cortex-browser must run inside a Cortex session (CORTEX_SESSION_ID is unset)");let p=await bt(d,Ne(u)||null,!0);return{device:p.device,cdpEndpoint:p.cdpEndpoint,abSession:p.abSession}},listBrowserSessions(){return[...t.values()].sort((s,u)=>u.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,u){let d=await bt(s,null,!1),p=await Ee(d,u);return It(d),p},async streamPort(s){let u=t.get(s);if(!u||u.state!=="ready")return null;let d=yt((await Ee(u,["--json","stream","status"])).stdout);if(d?.data?.enabled&&typeof d.data.port=="number")return d.data.port;let p=yt((await Ee(u,["--json","stream","enable"])).stdout);return typeof p?.data?.port=="number"?p.data.port:null},setTakeover(s,u){let d=wt(s);d.takenOver!==u&&(d.takenOver=u,g(d),V.info(`${s}: browser ${u?"taken over by the user":"handed back to the agent"}`),l())},isTakenOver(s){return t.get(s)?.takenOver??!1},async insertText(s,u){let d=Ro(s),p=await Ee(d,["keyboard","inserttext",u]);if(p.code!==0)throw new Error(p.stderr.trim()||`agent-browser exited ${p.code}`)},noteBrowserCommand(s){let u=t.get(Ne(s));u&&(g(u),It(u))},agentBrowserRuntime(){return m()},onBrowserSessionsChanged(s){return a.add(s),()=>{a.delete(s)}},shutdown(){for(let s of t.values())s.idleTimer&&clearTimeout(s.idleTimer);t.clear(),a.clear()}}}async function Ps(e){try{return(await fetch(`${e}/json/version`,{signal:AbortSignal.timeout(Rs)})).ok}catch{return!1}}function As(){return{async acquire(e){return e===j?(await rt()).cdpEndpoint:(await ut(e)).cdpEndpoint},release(e){e===j?st():mo(e)},async refresh(e,t){if(e===j){let o=so().browser?.cdpEndpoint;if(o)return o;let r=(await rt()).cdpEndpoint;return st(),r}return await Ps(t)?t:(await ut(e)).cdpEndpoint},availability(e){let t=Me().map(o=>o.device).sort();return Un(e)?{state:"online",online:t}:{state:Object.hasOwn(Ae(),e)?"offline":"unknown",online:t}},resolveBin:()=>Wt(),baseEnv:()=>zt(),run:(e,t,o)=>Xt(e,t,{env:o}),now:()=>Date.now(),idleMs:Cs}}var dt=null;function q(){return dt??=_s(As()),dt}var Lc=e=>q().leaseBrowser(e),Fc=()=>q().listBrowserSessions();var Nc=e=>q().streamPort(e),Uc=(e,t)=>q().setTakeover(e,t),Bc=e=>q().isTakenOver(e),Hc=(e,t)=>q().insertText(e,t),Wc=e=>q().noteBrowserCommand(e),Gc=()=>q().agentBrowserRuntime();function Vc(){dt?.shutdown()}import*as k from"node:fs";import*as O from"node:path";var ie=h("project-store"),Ds=1e3;function fo(e,t,o){return[`# ${e} Status`,"","Updated: \u2014","","## Current Situation",t,"","## In Flight & New Variables","none","","## Blockers & Pending Decisions","none","","## Next Step",o,""].join(`
|
|
60
|
-
`)}var Os=fo("general","Synthetic umbrella project \u2014 collects work not scoped to a specific project.","none"),Ms=`# general
|
|
61
|
-
|
|
62
|
-
Synthetic umbrella project \u2014 always present. Created automatically by the system.
|
|
63
|
-
`,Ls=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,pt=class{projectsDir;watchEnabled;projects=[];initialized=!1;watcher=null;debounceTimer=null;constructor(t={}){this.projectsDir=t.projectsDir??kt,this.watchEnabled=t.watchEnabled??!0}async initialize(){this.initialized||(this.scaffoldGeneral(),this.scan(),this.initialized=!0,this.watchEnabled&&this.startWatcher(),ie.info(`ProjectStore initialized: ${this.projects.length} projects (${this.projectsDir})`))}list(){return[...this.projects]}get(t){return this.projects.find(o=>o.id===t)}exists(t){return this.projects.some(o=>o.id===t)}getDefault(){return this.projects.find(t=>t.kind==="general")}resolveFromMessage(t){if(!t)return this.getDefault();let o=t.match(/\[project:([^\]]+)\]/);if(o)return this.get(o[1])??this.getDefault();let r=t.toLowerCase(),i=null,a=0;for(let c of this.projects){if(c.kind==="general")continue;let l=c.id.toLowerCase();r.includes(l)&&c.id.length>a&&(i=c,a=c.id.length)}return i??this.getDefault()}refresh(){this.scan()}createProject(t){let o=typeof t=="string"?t.trim():"";if(!o||o==="general"||!Ls.test(o)||O.basename(o)!==o)return{ok:!1,code:"invalid-name",message:`Invalid project name: ${JSON.stringify(t)}`};let r=O.join(this.projectsDir,o);if(this.exists(o)||k.existsSync(r))return{ok:!1,code:"already-exists",message:`Project already exists: ${o}`};this.scaffoldProject(r,fo(o,"New project \u2014 not yet oriented.","Define mission.md and roadmap.md."),`# ${o}
|
|
64
|
-
|
|
65
|
-
${o} project.
|
|
66
|
-
`),ie.info(`Created project at ${r}`),this.scan();let i=this.get(o);return i?{ok:!0,project:i}:{ok:!1,code:"invalid-name",message:`Project not registered after creation: ${o}`}}destroy(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.watcher&&(this.watcher.close(),this.watcher=null),this.initialized=!1}scaffoldGeneral(){let t=O.join(this.projectsDir,"general");k.existsSync(t)||(this.scaffoldProject(t,Os,Ms),ie.info(`Scaffolded general project at ${t}`))}scaffoldProject(t,o,r){k.mkdirSync(t,{recursive:!0}),k.writeFileSync(O.join(t,"STATUS.md"),o,"utf8"),k.writeFileSync(O.join(t,"AGENTS.md"),r,"utf8")}scan(){let t=[];t.push(this.makeGeneralProject());try{let o=k.readdirSync(this.projectsDir,{withFileTypes:!0});for(let r of o)r.isDirectory()&&(r.name.startsWith(".")||r.name!=="general"&&t.push({id:r.name,name:r.name,kind:"user",contextDir:O.join(this.projectsDir,r.name)}))}catch{}this.projects=t}makeGeneralProject(){return{id:"general",name:"general",kind:"general",contextDir:O.join(this.projectsDir,"general")}}startWatcher(){try{this.watcher=k.watch(this.projectsDir,(t,o)=>{o&&(o.startsWith(".")||this.debouncedRescan())}),this.watcher.on("error",t=>{ie.error(`Watcher error for ${this.projectsDir}:`,t.message)})}catch(t){ie.error(`Failed to start watcher for ${this.projectsDir}:`,t)}}debouncedRescan(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan(),ie.debug("Rescanned projects after directory change")},Ds)}},Yc=new pt;import*as C from"node:fs";import*as _ from"node:path";var Fs=["mission.md","roadmap.md","STATUS.md"],Ns=["experiments","knowledge","patterns","decisions"];function mt(e){return Object.assign(new Error(e),{code:"not-found"})}function Ue(e){return Object.assign(new Error(e),{code:"invalid-args"})}function go(e,t){let o=e.projectStore.get(t);if(!o)throw mt(`project not found: ${t}`);try{return C.realpathSync(o.contextDir)}catch{throw mt(`project directory not found: ${t}`)}}function ho(e,t){return t===e||t.startsWith(e+_.sep)}function Us(e,t){if(_.isAbsolute(t))throw Ue(`absolute path not allowed: ${t}`);let o=_.resolve(e,t);if(!ho(e,o))throw Ue(`path escapes project root: ${t}`);let r;try{r=C.realpathSync(o)}catch{throw mt(`file not found: ${t}`)}if(!ho(e,r))throw Ue(`path escapes project root: ${t}`);if(!C.statSync(r).isFile())throw Ue(`not a file: ${t}`);return r}async function Qc(e,t){let o=go(e,t.projectId),r=Fs.flatMap(a=>{let c=_.join(o,a),l;try{l=C.statSync(c)}catch{return[]}return l.isFile()?[{name:a,sizeBytes:l.size,modifiedAt:l.mtime.toISOString()}]:[]}),i=Ns.flatMap(a=>{let c=_.join(o,a),l;try{l=C.readdirSync(c,{withFileTypes:!0})}catch{return[]}let f=l.filter(m=>m.isFile()&&m.name.endsWith(".md")&&m.name!=="index.md"&&m.name!=="AGENTS.md").map(m=>{let w=C.statSync(_.join(c,m.name));return{name:m.name,sizeBytes:w.size,modifiedAt:w.mtime.toISOString()}}).sort((m,w)=>m.name.localeCompare(w.name));return[{name:a,entryCount:f.length,entries:f}]});return{projectId:t.projectId,files:r,dirs:i}}async function Bs(e,t){let o=await J("git",["diff","--numstat","HEAD","--",t],{cwd:e,timeoutMs:5e3,maxBuffer:1048576,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});if(!o.ok)return null;let i=o.stdout.split(`
|
|
67
|
-
`).find(m=>m.trim().length>0);if(!i)return{added:0,removed:0};let[a,c]=i.split(" "),l=Number(a),f=Number(c);return!Number.isFinite(l)||!Number.isFinite(f)?null:{added:l,removed:f}}var Hs=/\b(?:task|manager|gate)\s+([0-9a-f]{4})\b/i;function Ws(e){let t=Hs.exec(e);return t?t[1].toLowerCase():null}function Gs(e){let t=[],o=new Map,r=null,i=0;for(let a of e.split(`
|
|
68
|
-
`)){if(a.startsWith(" ")){r&&t.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,Ws(a.slice(8)))}return t}async function Vs(e,t){let o=await J("git",["blame","--line-porcelain","HEAD","--",t],{cwd:e,timeoutMs:5e3,maxBuffer:8388608,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return o.ok?Gs(o.stdout):null}async function el(e,t){let o=go(e,t.projectId),r=Us(o,t.path),i=C.statSync(r),a=C.readFileSync(r,"utf8"),[c,l]=en()?await Promise.all([Bs(o,t.path),Vs(o,t.path)]):[null,null];return{projectId:t.projectId,path:t.path,content:a,sizeBytes:i.size,modifiedAt:i.mtime.toISOString(),lineDiff:c,blame:l}}var bo={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"]},ol={feishu:["FEISHU_APP_ID","FEISHU_APP_SECRET"],slack:bo.slack},rl=["FEISHU_APP_ID","FEISHU_DOMAIN"],Z=n.string().min(1).max(4096).regex(/^[^\s'\\\u0000-\u001f\u007f]+$/,"Invalid credential characters"),qs=n.object({FEISHU_APP_ID:Z.nullable().optional(),FEISHU_APP_SECRET:Z.nullable().optional(),FEISHU_DOMAIN:n.enum(["feishu","lark"]).nullable().optional(),FEISHU_ENCRYPT_KEY:Z.nullable().optional(),FEISHU_VERIFICATION_TOKEN:Z.nullable().optional(),SLACK_BOT_TOKEN:Z.nullable().optional(),SLACK_SIGNING_SECRET:Z.nullable().optional(),SLACK_APP_TOKEN:Z.nullable().optional()}).strict(),wo=n.object({platform:n.enum(["feishu","slack"]),enabled:n.boolean().optional(),fields:qs}).strict().refine(e=>Object.keys(e.fields).every(t=>bo[e.platform].includes(t)),"Fields must belong to the selected platform");var ft=["openai-codex","anthropic"];function il(e){return ft.includes(e)}var So=n.object({sessionId:n.string().min(1),starred:n.boolean()}),Io=n.object({sessionId:n.string().min(1),label:n.string().trim().min(1).max(60)});var zs=n.object({projectId:n.string().optional(),resumable:n.boolean().optional(),origin:n.enum(["direct","thread","scheduled"]).optional()}),Xs=n.object({sessionId:n.string(),compactSubagents:n.boolean().optional(),since:n.string().max(64).optional()}),Ys=n.object({sessionId:n.string(),subagentId:n.string().min(1).max(512)}),Zs=n.object({sessionId:n.string(),ref:n.string().min(1).max(512)}),Ks=n.object({sessionId:n.string().min(1)}),Js=n.object({projectId:n.string().optional(),paused:n.boolean().optional()}),Qs=n.object({projectId:n.string().optional()}),ei=n.object({boardId:n.string()}),ti=n.object({boardId:n.string()}),ni=n.object({}),oi=n.object({sessionId:n.string().min(1)}),ri=n.object({status:n.array(n.string()).optional(),limit:n.number().optional()}),si=n.object({executionId:n.string()}),ii=n.object({projectId:n.string()}),ai=n.object({projectId:n.string(),path:n.string()}),ci=n.object({status:n.enum(["pending","approved","rejected","failed"]).optional()}),li=n.object({projectId:n.string()}),ui=n.object({projectId:n.string()});var yl=n.object({}),xl=n.object({projectId:n.string().nullish()}),vl=n.object({}),El=n.object({}),$l=n.object({flowId:n.string().min(1)}),kl=n.object({}),Cl=n.object({}),Tl=n.object({enabled:n.boolean(),name:n.string().trim().optional(),org:n.string().trim().optional(),email:n.string().trim().optional()}),Rl=n.object({}),jl=_t,_l=n.object({}),Pl=n.object({}),Al=n.object({machine:n.string().min(1)}),Dl=n.object({}),Ol=n.object({sessionId:n.string().min(1).optional(),agentName:n.string().min(1).nullable().optional()}),Ml=n.object({}),Ll=n.object({}),Fl=n.object({}),Nl=n.object({}),Ul=n.object({}),Bl=n.object({limit:n.number().int().positive().max(50).optional()}),Hl=n.object({}),Wl=n.object({}),Gl=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1),authType:n.enum(["api_key","oauth"]),noticeId:n.string().min(1).optional()}),Vl=n.object({flowId:n.string().min(1),value:n.string(),promptId:n.number().int().nonnegative().optional()}),ql=n.object({flowId:n.string().min(1)}),zl=n.object({backend:n.enum(["claude","pi"]).optional()}),Xl=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1),authType:n.enum(["api_key","oauth"])}),xo=n.string().min(1).regex(At),Yl=n.object({name:xo,api:n.enum(Pt),upstreamUrl:n.string().min(1),apiKey:n.string().optional(),models:n.array(n.object({id:n.string().min(1),contextWindow:n.number().int().positive().optional(),maxTokens:n.number().int().positive().optional(),reasoning:n.boolean().optional()})).min(1),headers:n.record(n.string(),n.string()).optional(),compat:n.record(n.string(),n.unknown()).optional()}),Zl=n.object({name:xo}),Kl=n.object({name:n.string()}),Jl=n.object({projectId:n.string().optional()}),Ql=n.object({sessionId:n.string(),text:n.string(),attachments:n.array(n.object({name:n.string(),path:n.string(),size:n.number(),mimeType:n.string(),type:n.enum(["image","video","file","view"])})).optional()}),eu=n.object({sessionId:n.string()}),tu=n.object({sessionId:n.string()}),nu=n.object({sessionId:n.string()}),ou=n.object({sessionIds:n.array(n.string()).min(1).max(500)}),ru=n.object({sessionId:n.string(),agentName:n.string().min(1).nullable().optional()}),vo=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1).nullable(),model:n.string().min(1),thinking:n.string().min(1).nullable(),mode:n.string().min(1)}).strict(),xe=vo,su=n.object({sessionId:n.string(),selection:xe}).strict(),iu=n.object({requestId:n.string().min(1),answers:n.record(n.string(),n.string())}),au=n.object({requestId:n.string().min(1),approved:n.boolean(),feedback:n.string().optional()}),cu=n.object({sessionId:n.string().min(1),decisionId:n.string().min(1),action:n.enum(["approve","explain","revise"]),message:n.string().optional()}),lu=n.object({sessionId:n.string().regex(/^[\w-]+$/),ts:n.string().min(1),src:n.string().min(1)}),uu=n.object({sessionId:n.string()}),du=n.object({sessionId:n.string(),turnIndex:n.number().int().min(0),text:n.string().min(1)}),pu=n.object({projectId:n.string(),agentName:n.string().min(1).optional(),selection:xe.optional(),clean:n.boolean().optional(),text:n.string(),draftUploadId:n.string().uuid().optional(),attachments:n.array(n.object({name:n.string(),path:n.string(),size:n.number(),mimeType:n.string(),type:n.enum(["image","video","file"])})).optional()}),mu=n.object({waitpointId:n.string().min(1)}),fu=n.object({executionId:n.string()}),hu=n.object({scheduleId:n.string()}),gu=n.object({type:n.enum(["interval","daily","weekly","once"]),message:n.string().min(1),projectId:n.string().optional(),selection:xe.optional(),intervalMs:n.number().int().positive().optional(),time:n.string().regex(/^\d{2}:\d{2}$/).optional(),dayOfWeek:n.number().int().min(0).max(6).optional(),delay:n.number().int().positive().optional()}).superRefine((e,t)=>{e.type==="interval"&&e.intervalMs===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["intervalMs"],message:I("ui.schedule.intervalRequired")}),(e.type==="daily"||e.type==="weekly")&&e.time===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["time"],message:I("ui.schedule.timeRequired",{type:e.type})}),e.type==="weekly"&&e.dayOfWeek===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["dayOfWeek"],message:I("ui.schedule.dayOfWeekRequired")}),e.type==="once"&&e.delay===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["delay"],message:I("ui.schedule.delayRequired")})}),bu=n.object({scheduleId:n.string(),message:n.string().min(1).optional(),projectId:n.string().optional(),selection:xe.optional(),intervalMs:n.number().int().positive().optional(),time:n.string().regex(/^\d{2}:\d{2}$/).optional(),dayOfWeek:n.number().int().min(0).max(6).optional()}),di=new Set(["__proto__","prototype","constructor"]),pi=120,mi={boolean:n.boolean(),number:n.number().finite(),"number|null":n.number().finite().nullable(),"string[]":n.array(n.string()),"string|null":n.string().nullable()};function fi(e){let t=mi[e.type];return!("validate"in e)||typeof e.validate!="function"?t:t.superRefine((o,r)=>{let i=e.validate(o);i&&r.addIssue({code:n.ZodIssueCode.custom,message:i})})}var hi=Object.fromEntries(Object.entries(Tt).filter(([e])=>e!=="providerRateLimits").map(([e,t])=>[e,fi(t)]));function gi(e,t){for(let[o,r]of Object.entries(e))r===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:[o],message:"setting must not be undefined"})}var bi=n.object(hi).partial().strict().superRefine(gi),wu=n.discriminatedUnion("section",[n.object({section:n.literal("budget"),project:n.string().min(1).nullish(),value:n.object({daily_usd:n.number().finite().positive(),monthly_usd:n.number().finite().positive()}).nullish()}).superRefine((e,t)=>{e.value==null&&!e.project&&t.addIssue({code:n.ZodIssueCode.custom,path:["value"],message:"a budget write without a value clears a per-project override and requires `project`"})}),n.object({section:n.literal("settings"),value:bi}),n.object({section:n.literal("preferences"),value:n.object({lang:n.enum(["en","zh"])})})]),Su=n.object({provider:n.string().trim().min(1).max(pi).refine(e=>!di.has(e),"provider key is reserved"),windowType:n.string().trim().min(1).nullish(),windowLabel:n.string().trim().min(1).nullish(),enabled:n.boolean(),threshold:n.union([n.number().finite().gt(0).lte(1),n.null()]).optional()}).superRefine((e,t)=>{e.windowLabel&&!e.windowType&&t.addIssue({code:n.ZodIssueCode.custom,path:["windowType"],message:"windowType is required when windowLabel is set"})}),Iu=n.object({}),wi=n.union([n.string(),n.number(),n.boolean(),n.null()]),Eo={event:n.string().min(1),matcher:n.string().optional(),matcherFilters:n.record(n.string(),wi).optional(),script:n.string().min(1).optional(),command:n.string().min(1).optional(),timeoutSec:n.number().finite().positive().optional(),backends:n.array(n.enum(["claude","pi"])).optional(),requiresTool:n.string().min(1).optional(),result:n.enum(["stdout-as-prompt","none"]).optional(),enabled:n.boolean().optional()};function $o(e,t){let o=e.script!==void 0,r=e.command!==void 0;o===r&&t.addIssue({code:n.ZodIssueCode.custom,path:["script"],message:I("ui.hook.exactlyOneRun")})}var yu=n.object({id:n.string().min(1),...Eo}).superRefine($o),xu=n.object({id:n.string().min(1),...Eo}).superRefine($o),vu=n.object({id:n.string().min(1),enabled:n.boolean()}),Eu=n.object({id:n.string().min(1)}),$u=n.object({id:n.string().min(1),payload:n.string()}),Si=vo.pick({backend:!0,provider:!0,model:!0}),ku=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1).nullable().optional(),model:n.string().min(1)}).strict(),Cu=n.object({ref:Si,thinking:n.string().nullable()}).strict(),Tu=n.object({selection:xe}).strict(),Ii=e=>new TextEncoder().encode(e).byteLength<=255,yi=e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),xi=n.string().max(240).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),vi=n.string().min(1).refine(Ii).refine(yi),ht=n.string().regex(/^[a-f0-9]{64}$/),Ei=n.object({kind:n.literal("agent"),name:xi,baseHash:ht}),Ru=n.object({target:Ei,pluginIds:n.array(vi),acknowledgeMcp:n.boolean().optional()}),M=n.string().min(1).max(64).regex(/^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/),ae={pluginId:M,skill:M},ju=n.object(ae),_u=n.object({...ae,content:n.string().max(512*1024),baseHash:ht}),Pu=n.object({...ae,description:n.string().min(1).max(1024)}),Au=n.object({...ae,toPluginId:M,toSkill:M}),Du=n.object(ae),Ou=n.object(ae),Mu=n.object({id:M,description:n.string().max(1024).optional()}),Lu=n.object({id:M}),Fu=n.object({id:M}),Nu=n.object({pluginId:M}),yo=n.record(n.string().min(1).max(200),n.string().max(4096).nullable()),Uu=n.object({pluginId:M,servers:n.array(n.object({name:n.string().min(1).max(64).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),type:n.enum(["stdio","streamable-http","sse"]),command:n.string().max(1024).optional(),args:n.array(n.string().max(1024)).max(64).optional(),cwd:n.string().max(1024).optional(),url:n.string().max(2048).optional(),env:yo.optional(),headers:yo.optional()})).max(32),baseHash:ht}),ve=n.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),Bu=n.object({name:ve}),Hu=n.object({name:ve,body:n.record(n.string(),n.unknown())}),Wu=n.object({name:ve,body:n.record(n.string(),n.unknown()),baseHash:n.string().optional()}),Gu=n.object({name:ve}),Vu=n.object({name:ve,text:n.string().max(65536)}),qu=n.object({id:n.string()}),zu=n.object({projectId:n.string(),id:n.string()}),$i=n.string().trim().min(1).max(1e3).refine(e=>!/[\r\n]/.test(e),{error:()=>I("ui.note.oneLine")}),ki=n.object({projectId:n.string(),text:$i}),Xu=ki.extend({id:n.string()}),Yu=n.object({projectId:n.string(),id:n.string(),completed:n.boolean()}),Zu=n.object({projectId:n.string(),id:n.string()}),Ku=n.object({projectId:n.string()}),Ju=n.object({id:n.string(),feedback:n.string().optional()}),Qu=n.object({kind:n.enum(["soft","hard","force"])}),ed=n.object({provider:n.string().optional()}),td=n.object({}),nd=n.object({provider:n.enum(ft),creditId:n.string().min(1).optional()}),od=n.object({}),rd=n.object({}),sd=n.object({}),id=n.object({kind:n.enum(["reconnect-platform","add-machine"]),platform:n.enum(["slack","feishu"]).optional(),machineName:n.string().min(1).optional()}).superRefine((e,t)=>{e.kind==="reconnect-platform"&&e.platform===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["platform"],message:"platform is required for kind=reconnect-platform"}),e.kind==="add-machine"&&(e.machineName===void 0||e.machineName.trim()==="")&&t.addIssue({code:n.ZodIssueCode.custom,path:["machineName"],message:I("ui.approval.machineNameRequired")})});export{bo as a,ol as b,rl as c,wo as d,ft as e,il as f,So as g,Io as h,zs as i,Xs as j,Ys as k,Zs as l,Ks as m,Js as n,Qs as o,ei as p,ti as q,ni as r,oi as s,ri as t,si as u,ii as v,ai as w,ci as x,li as y,ui as z,yl as A,xl as B,vl as C,El as D,$l as E,kl as F,Cl as G,Tl as H,Rl as I,jl as J,_l as K,Pl as L,Al as M,Dl as N,Ol as O,Ml as P,Ll as Q,Fl as R,Nl as S,Ul as T,Bl as U,Hl as V,Wl as W,Gl as X,Vl as Y,ql as Z,zl as _,Xl as $,Yl as aa,Zl as ba,Kl as ca,Jl as da,Ql as ea,eu as fa,tu as ga,nu as ha,ou as ia,ru as ja,xe as ka,su as la,iu as ma,au as na,cu as oa,lu as pa,uu as qa,du as ra,pu as sa,mu as ta,fu as ua,hu as va,gu as wa,bu as xa,wu as ya,Su as za,Iu as Aa,yu as Ba,xu as Ca,vu as Da,Eu as Ea,$u as Fa,Si as Ga,ku as Ha,Cu as Ia,Tu as Ja,Ru as Ka,ju as La,_u as Ma,Pu as Na,Au as Oa,Du as Pa,Ou as Qa,Mu as Ra,Lu as Sa,Fu as Ta,Nu as Ua,Uu as Va,Bu as Wa,Hu as Xa,Wu as Ya,Gu as Za,Vu as _a,qu as $a,zu as ab,ki as bb,Xu as cb,Yu as db,Zu as eb,Ku as fb,Ju as gb,Qu as hb,ed as ib,td as jb,nd as kb,od as lb,rd as mb,sd as nb,id as ob,rn as pb,Oi as qb,sn as rb,Mi as sb,J as tb,Gi as ub,je as vb,ze as wb,Ki as xb,Ji as yb,Pi as zb,Ai as Ab,Vo as Bb,ua as Cb,xc as Db,wa as Eb,Sa as Fb,yn as Gb,Ae as Hb,Ia as Ib,ya as Jb,xa as Kb,za as Lb,Ca as Mb,Ze as Nb,ja as Ob,ge as Pb,fr as Qb,La as Rb,Fa as Sb,Na as Tb,Ua as Ub,Ba as Vb,Ha as Wb,Wa as Xb,Ga as Yb,nc as Zb,oc as _b,rc as $b,sc as ac,Me as bc,Un as cc,ic as dc,Bn as ec,Hn as fc,zn as gc,oe as hc,dc as ic,pc as jc,Rc as kc,$ as lc,Lc as mc,Fc as nc,Nc as oc,Uc as pc,Bc as qc,Hc as rc,Wc as sc,Gc as tc,Vc as uc,Yc as vc,go as wc,Us as xc,Qc as yc,Ws as zc,el as Ac};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{existsSync as i,readFileSync as n}from"fs";function s(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.api=="string"&&Array.isArray(r.models)}function c(e){if(!i(e))return{};try{let r=JSON.parse(n(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))return{};let t=r.providers;return!t||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}}function a(e){let r={};for(let[t,o]of Object.entries(c(e)))s(o)&&(r[t]=o);return r}export{a};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{c as I}from"./chunk-TAWLERZA.js";import{m as B}from"./chunk-CQLH4UVX.js";import{a as J,b as Y}from"./chunk-Z4H3VDHI.js";import{$ as H,A as k,D as E,F as C,I as P,L,V as x,W as Z,X as D,_ as p,b as f,d as T,e as R,f as g,g as b,h as G,i as W,j as F,o as u,w as _,y as v}from"./chunk-FOQ7VLIL.js";import{a as U,b as z,d as X}from"./chunk-5T7IX5KN.js";import{i as V}from"./chunk-OE4KH3NJ.js";import{a as N}from"./chunk-PFMEUFJ7.js";import{D as j}from"./chunk-DPQPXBTP.js";import{e as O}from"./chunk-NAA7GF6Q.js";import{b as q}from"./chunk-QWAQHHRS.js";var Q=Symbol.for("mcp.completable");function A(o){return!!o&&typeof o=="object"&&Q in o}function ee(o){return o[Q]?.complete}var K;(function(o){o.Completable="McpCompletable"})(K||(K={}));var ce=/^[A-Za-z0-9._-]{1,128}$/;function de(o){let e=[];if(o.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(o.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${o.length})`]};if(o.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),o.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(o.startsWith("-")||o.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(o.startsWith(".")||o.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!ce.test(o)){let t=o.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,n,a)=>a.indexOf(r)===n);return e.push(`Tool name contains invalid characters: ${t.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function ue(o,e){if(e.length>0){console.warn(`Tool name validation warning for "${o}":`);for(let t of e)console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function M(o){let e=de(o);return ue(o,e.warnings),e.isValid}var S=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}};var y=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new J(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new S(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(h(P)),this.server.assertCanSetRequestHandler(h(L)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(P,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=g(t.inputSchema);return n?H(n,{strictUnions:!0,pipeStrategy:"input"}):pe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=g(t.outputSchema);n&&(r.outputSchema=H(n,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(L,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new p(u.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,a=r.execution?.taskSupport,s="createTask"in r.handler;if((a==="required"||a==="optional")&&!s)throw new p(u.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!n)throw new p(u.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!n&&s)return await this.handleAutomaticTaskPolling(r,e,t);let i=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,i,t);return n||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof p&&r.code===u.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let a=g(e.inputSchema)??e.inputSchema,s=await T(a,t);if(!s.success){let i="error"in s?s.error:"Unknown error",c=b(i);throw new p(u.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return s.data}async validateToolOutput(e,t,r){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new p(u.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=g(e.outputSchema),a=await T(n,t.structuredContent);if(!a.success){let s="error"in a?a.error:"Unknown error",i=b(s);throw new p(u.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${i}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw new Error("No task store provided.");let s={...r,taskStore:r.taskStore};if(e.inputSchema){let i=n;return await Promise.resolve(i.createTask(t,s))}else{let i=n;return await Promise.resolve(i.createTask(s))}}if(e.inputSchema){let s=n;return await Promise.resolve(s(t,r))}else{let s=n;return await Promise.resolve(s(r))}}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,s={...r,taskStore:r.taskStore},i=n?await Promise.resolve(a.createTask(n,s)):await Promise.resolve(a.createTask(s)),c=i.task.taskId,l=i.task,m=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(le=>setTimeout(le,m));let d=await r.taskStore.getTask(c);if(!d)throw new p(u.InternalError,`Task ${c} not found during polling`);l=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(h(x)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(x,async e=>{switch(e.params.ref.type){case"ref/prompt":return Z(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return D(e),this.handleResourceCompletion(e,e.params.ref);default:throw new p(u.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new p(u.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return w;let a=R(r.argsSchema)?.[e.params.argument.name];if(!A(a))return w;let s=ee(a);if(!s)return w;let i=await s(e.params.argument.value,e.params.context);return re(i)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return w;throw new p(u.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return w;let a=await n(e.params.argument.value,e.params.context);return re(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(h(_)),this.server.assertCanSetRequestHandler(h(v)),this.server.assertCanSetRequestHandler(h(k)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([a,s])=>s.enabled).map(([a,s])=>({uri:a,name:s.name,...s.metadata})),n=[];for(let a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;let s=await a.resourceTemplate.listCallback(t);for(let i of s.resources)n.push({...a.metadata,...i})}return{resources:[...r,...n]}}),this.server.setRequestHandler(v,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(k,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new p(u.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let a of Object.values(this._registeredResourceTemplates)){let s=a.resourceTemplate.uriTemplate.match(r.toString());if(s)return a.readCallback(r,s,t)}throw new p(u.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(h(E)),this.server.assertCanSetRequestHandler(h(C)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(E,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?me(t.argsSchema):void 0}))})),this.server.setRequestHandler(C,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new p(u.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=g(r.argsSchema),a=await T(n,e.params.arguments);if(!a.success){let c="error"in a?a.error:"Unknown error",l=b(c);throw new p(u.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let s=a.data,i=r.callback;return await Promise.resolve(i(s,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let n;typeof r[0]=="object"&&(n=r.shift());let a=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,n,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,n,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,r,n){if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,t,r,n,a){let s={name:e,title:t,metadata:n,readCallback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==r&&(delete this._registeredResources[r],i.uri&&(this._registeredResources[i.uri]=s)),typeof i.name<"u"&&(s.name=i.name),typeof i.title<"u"&&(s.title=i.title),typeof i.metadata<"u"&&(s.metadata=i.metadata),typeof i.callback<"u"&&(s.readCallback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=s,s}_createRegisteredResourceTemplate(e,t,r,n,a){let s={resourceTemplate:r,title:t,metadata:n,readCallback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=s)),typeof l.title<"u"&&(s.title=l.title),typeof l.template<"u"&&(s.resourceTemplate=l.template),typeof l.metadata<"u"&&(s.metadata=l.metadata),typeof l.callback<"u"&&(s.readCallback=l.callback),typeof l.enabled<"u"&&(s.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let i=r.uriTemplate.variableNames;return Array.isArray(i)&&i.some(l=>!!r.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,t,r,n,a){let s={title:t,description:r,argsSchema:n===void 0?void 0:f(n),callback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=s)),typeof i.title<"u"&&(s.title=i.title),typeof i.description<"u"&&(s.description=i.description),typeof i.argsSchema<"u"&&(s.argsSchema=f(i.argsSchema)),typeof i.callback<"u"&&(s.callback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,n&&Object.values(n).some(c=>{let l=c instanceof j?c._def?.innerType:c;return A(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,t,r,n,a,s,i,c,l){M(e);let m={title:t,description:r,inputSchema:te(n),outputSchema:te(a),annotations:s,execution:i,_meta:c,handler:l,enabled:!0,disable:()=>m.update({enabled:!1}),enable:()=>m.update({enabled:!0}),remove:()=>m.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&M(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=m)),typeof d.title<"u"&&(m.title=d.title),typeof d.description<"u"&&(m.description=d.description),typeof d.paramsSchema<"u"&&(m.inputSchema=f(d.paramsSchema)),typeof d.outputSchema<"u"&&(m.outputSchema=f(d.outputSchema)),typeof d.callback<"u"&&(m.handler=d.callback),typeof d.annotations<"u"&&(m.annotations=d.annotations),typeof d._meta<"u"&&(m._meta=d._meta),typeof d.enabled<"u"&&(m.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=m,this.setToolRequestHandlers(),this.sendToolListChanged(),m}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,n,a,s;if(typeof t[0]=="string"&&(r=t.shift()),t.length>1){let c=t[0];if($(c))n=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!$(t[0])&&(s=t.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=t.shift()}}let i=t[0];return this._createRegisteredTool(e,void 0,r,n,a,s,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:a,inputSchema:s,outputSchema:i,annotations:c,_meta:l}=t;return this._createRegisteredTool(e,n,a,s,i,c,{taskSupport:"forbidden"},l,r)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let n;t.length>1&&(n=t.shift());let a=t[0],s=this._createRegisteredPrompt(e,void 0,r,n,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:a,argsSchema:s}=t,i=this._createRegisteredPrompt(e,n,a,s,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var pe={type:"object",properties:{}};function se(o){return o!==null&&typeof o=="object"&&"parse"in o&&typeof o.parse=="function"&&"safeParse"in o&&typeof o.safeParse=="function"}function oe(o){return"_def"in o||"_zod"in o||se(o)}function $(o){return typeof o!="object"||o===null||oe(o)?!1:Object.keys(o).length===0?!0:Object.values(o).some(se)}function te(o){if(o){if($(o))return f(o);if(!oe(o))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return o}}function me(o){let e=R(o);return e?Object.entries(e).map(([t,r])=>{let n=G(r),a=W(r);return{name:t,description:n,required:!a}}):[]}function h(o){let t=R(o)?.method;if(!t)throw new Error("Schema is missing a method literal");let r=F(t);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function re(o){return{completion:{values:o.slice(0,100),total:o.length,hasMore:o.length>100}}}var w={completion:{values:[],hasMore:!1}};function ne(o,e){let t=o.tool,r=new Map;o.tool=((...s)=>{let i=t.apply(o,s);return i&&(s[0]==="agent"||s[0]==="worker_spawn")&&r.set(s[0],i),i});try{e()}finally{o.tool=t}let n=r.get("worker_spawn");r.get("agent")&&n&&n.update({description:B(n.description??"")})}var ae=O("mcp-bundled"),he=async o=>{let[{registerRemoteOpsTools:e},{registerTimeTools:t},{registerSubagentTools:r}]=await Promise.all([import("./remote-ops-BALZYKH6.js"),import("./time-KEHDQT6K.js"),import("./subagent-E3UC7ZHC.js")]);return n=>{e(n,o),t(n),r(n,o)}},fe=async o=>{let[{registerCostTools:e},{registerExecutionTools:t},{registerContextTools:r},{registerWaitpointTools:n}]=await Promise.all([import("./cost-PGGFI7QJ.js"),import("./executions-6ARGR3IO.js"),import("./context-VCQH5OB6.js"),import("./waitpoint-2FGQBIAC.js")]);return a=>{e(a),t(a),r(a,o),n(a,o)}},ge=async o=>{let[{registerInteractionPlanTools:e,interactionDepsFor:t},{registerInteractionAskTools:r}]=await Promise.all([import("./interaction-plan-E5V42MUP.js"),import("./interaction-ask-G5T3H3CG.js")]),n=t(o);return a=>{e(a,n),r(a,n)}},we=async o=>{let{registerSlackTools:e,slackDepsFor:t}=await import("./slack-WAGSPZUX.js"),r=t(o);return n=>e(n,r)},Te=async o=>{let[{registerFileTools:e},{buildFeishuClientFromEnv:t}]=await Promise.all([import("./file-7BN7RCAY.js"),import("./client-XOGYH5UR.js")]),r=t();return n=>e(n,{client:r,fallbackChannel:o.channel,ctx:o})},Re=async o=>{let[{registerUiFileTools:e},{registerUiViewTools:t},{registerUiDecisionTools:r},{registerUiBoardTools:n}]=await Promise.all([import("./ui-file-GVH53O3X.js"),import("./ui-view-O7PLANT7.js"),import("./ui-decision-U2FXSEC2.js"),import("./ui-board-4GYW6KKW.js")]);return a=>{e(a,o),t(a,o),r(a,o),n(a,o)}},be=async o=>{let{registerWorkerTools:e}=await import("./workers-XN4PSTH6.js");return t=>e(t,o)},Se=async o=>{let{registerWorkerReportTools:e}=await import("./workers-XN4PSTH6.js");return t=>e(t,o)},ye={"cortex-core":he,"cortex-ext":fe,"cortex-interaction-bridge":ge,"cortex-slack":we,"cortex-feishu":Te,"cortex-web":Re,"cortex-workers":be,"cortex-worker-report":Se};function _e(o,e){let t=e instanceof Error?e.message:String(e);ae.error(`Skipping MCP bundle ${o}: ${t}`)}async function ve(o,e,t=(n,a)=>ye[n](a),r=_e){return(await Promise.all(o.map(async a=>{try{let s=await t(a,e);return i=>{try{s(i)}catch(c){r(a,c)}}}catch(s){return r(a,s),null}}))).filter(a=>a!==null)}async function ie(o,e){let t=await ve(o,e),r=new y({name:z,version:N});return V(r,n=>ne(n,()=>t.forEach(a=>a(n))),e.toolAllowlist),r}async function ke(){let o=process.env[U]??process.argv[2],e=X(o);if(e.includes("cortex-ext")){let{executionRepo:r}=await import("./execution-repo-ZLJTBWFC.js");r.follow()}await(await ie(e,I())).connect(new Y)}q(new URL("dist/domain/mcp/bundled-server.js",__cortexPackageRoot).href)&&ke().catch(o=>{ae.error(o),process.exit(1)});async function Ke(o,e){return ie(o,I(e))}export{ve as a,ie as b,ke as c,Ke as d};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{I as re,V as K,a as U,b as k,c as ee,g as te,v as ne}from"./chunk-TZFLHVOQ.js";import{a as Z,b as S,c as D,d as L}from"./chunk-5T7IX5KN.js";import{a as q,b as z,f as J,g as Q}from"./chunk-OE4KH3NJ.js";import{a as N}from"./chunk-5M4PFLRW.js";import{b as x}from"./chunk-W5LGYSPZ.js";import{e as E}from"./chunk-NAA7GF6Q.js";import{h as X}from"./chunk-QWAQHHRS.js";import{d as V,e as A,f as T,j as d,l}from"./chunk-J5DVLUKY.js";import{createHash as Re}from"node:crypto";import{chmodSync as oe,mkdirSync as we,readFileSync as He,writeFileSync as ie}from"fs";import*as s from"path";var be=E("config-generator"),xe=s.join(l,"mcp-config.json"),Ne=s.join(l,"mcp-config-core.json"),De=s.join(l,"mcp-config-empty.json"),Le=s.join(l,"mcp-config-interaction.json"),Ue=s.join(l,"mcp-config-slack.json"),ke=s.join(l,"mcp-config-feishu.json"),Ke=s.join(l,"mcp-config-web.json");function Ge(e,t,n){return{command:"node",args:[s.join(t,e)],cwd:t,...n?{env:n}:{}}}function m(e,t){let n=Ge("dist/domain/mcp/bundled-server.js",t);return{...n,args:[...n.args,D(e)]}}function Me(e){return JSON.parse(He(e,"utf8"))}function je(e){let t=e.env?.[Z];if(t!==void 0)return L(t);let n=Array.isArray(e.args)?e.args:[],r=typeof n[0]=="string"?n[0].replaceAll("\\","/"):"";return s.basename(r)==="bundled-server.js"&&typeof n[1]=="string"?L(n[1]):null}function $e(e){let t={external:{},template:null};for(let n of e)for(let[r,o]of Object.entries(n.mcpServers)){if(je(o)===null){t.external[r]=o;continue}t.template??=o}return t}function Fe(e,t,n){let{external:r,template:o}=$e(e);if(!o)return{mcpServers:r};if(r[S])throw new Error(`User MCP server name conflicts with reserved ${S}`);let c=Array.isArray(o.args)?[...o.args]:[];c[1]=D(n);let p={...o.env??{},...t?{[q]:t}:{}};return{mcpServers:{[S]:{...o,args:c,env:p},...r}}}function Ye(e,t,n,r,o){let c=Re("sha256").update(JSON.stringify({configPaths:t,documents:n,encodedAllowlist:r,selectedBundles:o})).digest("hex").slice(0,16);return s.join(e,`mcp-composition-${c}.json`)}function Be(e,t){return Q(e),e.filter(n=>t.has(n))}function Vt(e,t,n=s.join(l,"mcp-tool-gates"),r){if(t===void 0)return[...e];let o=e.map(Me),c=new Set(r.flatMap(Se=>z[Se]??[])),p=Be(J(t),c),W=JSON.stringify(p),ve=Fe(o,W,r);we(n,{recursive:!0,mode:448}),oe(n,448);let b=Ye(n,e,o,W,r);return ie(b,JSON.stringify(ve,null,2),{mode:384}),oe(b,384),[b]}function We(e){return{mcpServers:{"cortex-core":m(["cortex-core","cortex-ext"],e)}}}function Ve(e){return{mcpServers:{"cortex-core":m(["cortex-core"],e)}}}function Xe(){return{mcpServers:{}}}function qe(e){return{mcpServers:{"cortex-interaction-bridge":m(["cortex-interaction-bridge"],e)}}}function ze(e){return{mcpServers:{"cortex-slack":m(["cortex-slack"],e)}}}function Je(e){return{mcpServers:{"cortex-feishu":m(["cortex-feishu"],e)}}}function Qe(e){return{mcpServers:{"cortex-web":m(["cortex-web"],e)}}}function Xt(){let e=[["full",xe,We(A)],["core",Ne,Ve(A)],["empty",De,Xe()],["interaction",Le,qe(A)],["Slack",Ue,ze(A)],["Feishu",ke,Je(A)],["Web",Ke,Qe(A)]];for(let[t,n,r]of e)ie(n,JSON.stringify(r,null,2)),be.info(`Generated ${t} MCP config at ${n}`)}import{fileURLToPath as Ze}from"node:url";import{spawn as et}from"child_process";import{createWriteStream as tt,mkdirSync as ce,existsSync as nt}from"fs";import*as w from"path";import*as ue from"http";import{createRequire as rt}from"module";var ot=E("gateway-mgr"),O=d.url,nn=rt(new URL("dist/domain/costs/gateway-manager.js",__cortexPackageRoot).href),it=Ze(new URL("vendor/aistatus/",__cortexPackageRoot)),G=w.join(it,"gateway-cli.js"),le=w.join(T,"logs"),at=w.join(le,"gateway.log"),M=1e3,st=3e4,ct=1e4,ae=3e4,ut=5e3,u=null,fe=0,h=M,C=null,R=null,y=!1,f=!1,g=null;function i(e){ot.info(e);try{let t=new Date().toLocaleTimeString("en-GB",{hour12:!1});pe().write(`[gateway-mgr ${t}] ${e}
|
|
5
|
-
`)}catch{}}function pe(){return g||(ce(le,{recursive:!0}),g=tt(at,{flags:"a"})),g}var lt=globalThis.__mockHttpGet||ue.get,ft=globalThis.__mockChildProcessSpawn||et;function j(){return new Promise(e=>{let t=lt(`${O}/status`,{timeout:ut},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{e(n.statusCode===200)})});t.on("error",()=>e(!1)),t.on("timeout",()=>{t.destroy(),e(!1)})})}async function pt(){if(y||!u&&!f)return;let e=f;f=await j(),e&&!f?i("Health check failed \u2014 gateway may be unresponsive"):!e&&f&&i("Health check passed \u2014 gateway is responsive")}function _e(){return se!==null?se:f}async function _t(){return await j()?(f=!0,h=M,i(`Gateway already healthy on ${O} \u2014 reusing existing process`),!0):!1}async function de(){if(!y){if(u){i("spawnGateway called but child already running \u2014 skipping");return}if(!nt(G)){i(`Gateway CLI not found at ${G} \u2014 cannot start gateway`);return}await _t()||At()}}function dt(){return d.home?(ce(d.home,{recursive:!0}),{...process.env,HOME:d.home,USERPROFILE:d.home}):{...process.env}}function At(){i("Starting aistatus gateway (TS)..."),fe=Date.now(),f=!1;let e=pe();u=ft(process.execPath,[G,"start","-c",d.configPath,"-p",String(d.port)],{cwd:T,stdio:["ignore","pipe","pipe"],detached:!1,env:dt()}),u.stdout?.on("data",t=>{e.write(t)}),u.stderr?.on("data",t=>{e.write(t)}),i(`Gateway started \u2014 PID ${u.pid}`),u.on("exit",Et),setTimeout(mt,2e3)}function Et(e,t){let n=u?.pid;if(u=null,f=!1,y){i(`Gateway exited (shutdown) \u2014 PID ${n}`);return}Date.now()-fe>ct&&(h=M),i(t?`Gateway killed by signal ${t} \u2014 PID ${n}`:`Gateway exited with code ${e} \u2014 PID ${n}`),i(`Restarting gateway in ${h}ms...`),C=setTimeout(()=>{C=null,de()},h),h=Math.min(h*2,st)}async function mt(){u&&(f=await j(),i(f?"Gateway is healthy after startup":"Gateway not yet healthy after startup (will retry via periodic check)"))}function ht(){return new Promise(e=>{if(!u)return e();let t=u;i(`Stopping gateway (PID ${t.pid})...`);let n=setTimeout(()=>{i("Force killing gateway...");try{t.kill("SIGKILL")}catch{}},5e3);t.once("exit",()=>{clearTimeout(n),e()}),t.kill("SIGTERM")})}function rn(){y=!1,de(),R=setInterval(pt,ae),i(`Gateway manager started (health check interval: ${ae/1e3}s)`)}async function on(){y=!0,C&&(clearTimeout(C),C=null),R&&(clearInterval(R),R=null),await ht(),g&&(g.end(),g=null),i("Gateway manager stopped")}var se=null;var gt=[[/(?:\blogin_required\b|please\s+run\s+\/login\b)/i,"login_required"],[/(?:\boauth_expired\b|oauth\s+(?:token|session)\s+(?:has\s+)?expired\b)/i,"oauth_expired"],[/(?:\bauthentication_error\b|\bauthentication\b|\binvalid[_ -]api[_ -]key\b|\binvalid\s+x-api-key\b)/i,"invalid_api_key"],[/(?:\bunauthorized\b|\b401\b)/i,"unauthorized"],[/\binvalid_grant\b/i,"invalid_grant"]],I=null,$=new Set;function Ae(e,t){return`${e}:${t}`}function sn(e){for(let[t,n]of gt)if(t.test(e))return n;return null}function cn(e){I=e,$.clear()}function un(e){I&&($.add(Ae(e.backend,e.provider)),I.publish({type:"auth.required",...e}))}function ln(e){!I||!$.delete(Ae(e.backend,e.provider))||I.publish({type:"auth.recovered",...e})}import*as Ee from"node:path";var me=Ee.join(l,".env");function he(){let e=ee(),n=U(process.env.CLAUDE_CODE_OAUTH_TOKEN)||e.CLAUDE_CODE_OAUTH_TOKEN,r=n!==void 0&&n===e.CLAUDE_CODE_OAUTH_TOKEN;return{ANTHROPIC_API_KEY:k(process.env.ANTHROPIC_API_KEY)||e.ANTHROPIC_API_KEY,ANTHROPIC_BASE_URL:U(process.env.ANTHROPIC_BASE_URL)||e.ANTHROPIC_BASE_URL,CLAUDE_CODE_OAUTH_TOKEN:n,CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT:r?e.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT:void 0}}var _=he();function H(){let e=he();return e.ANTHROPIC_API_KEY&&(_.ANTHROPIC_API_KEY=e.ANTHROPIC_API_KEY),e.ANTHROPIC_BASE_URL&&(_.ANTHROPIC_BASE_URL=e.ANTHROPIC_BASE_URL),_.CLAUDE_CODE_OAUTH_TOKEN=e.CLAUDE_CODE_OAUTH_TOKEN,_.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT=e.CLAUDE_CODE_OAUTH_TOKEN?e.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT:void 0,{..._}}function Tt(e){let t=k(e);if(!t||/[\s"\\]/.test(t))throw new Error("Enter a valid Anthropic API key.");return t}function Y(e,t){return new RegExp(`^[ \\t]*(?:export[ \\t]+)?${e}[ \\t]*=.*$`,t)}function Ct(e,t,n){let r=`${t}=${JSON.stringify(n)}`;if(Y(t,"m").test(e))return e.replace(Y(t,"gm"),r);let c=e.length===0||e.endsWith(`
|
|
6
|
-
`)?"":`
|
|
7
|
-
`;return`${e}${c}${r}
|
|
8
|
-
`}function Ot(e,t){let n=Y(t,"gm");return e.replace(new RegExp(`${n.source}(?:\\r?\\n|$)`,"gm"),"")}async function yt(e,t){await x(me,n=>Ct(n,e,t),{mode:384})}async function ge(e){await x(me,t=>e.reduce(Ot,t),{mode:384})}async function An(e){let t=Tt(e);await yt("ANTHROPIC_API_KEY",t),_.ANTHROPIC_API_KEY=t,process.env.ANTHROPIC_API_KEY=t}async function En(){await ge(["ANTHROPIC_API_KEY"]),_.ANTHROPIC_API_KEY=void 0,delete process.env.ANTHROPIC_API_KEY}async function mn(){await ge(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT"]),_.CLAUDE_CODE_OAUTH_TOKEN=void 0,_.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT=void 0,delete process.env.CLAUDE_CODE_OAUTH_TOKEN}function It(e){return te()?null:e.CLAUDE_CODE_OAUTH_TOKEN??null}function F(e,t){t!==void 0&&(t===null?delete process.env[e]:process.env[e]=t)}function hn(){let e=H(),t=It(e);F("ANTHROPIC_API_KEY",e.ANTHROPIC_API_KEY??null),F("CLAUDE_CODE_OAUTH_TOKEN",t),t===null&&F("CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT",null)}var Pt=E("mode-env");function vt(e,t){if(t&&Object.keys(t).length>0){let n=Object.entries(t).map(([r,o])=>`${encodeURIComponent(r)}=${encodeURIComponent(o)}`).join(",");return`${O}/m/${e}/${n}/anthropic`}return`${O}/m/${e}/anthropic`}function St(e,t){let n=vt(e,t);if(e==="plan")return{ANTHROPIC_BASE_URL:n,ANTHROPIC_API_KEY:null};let r=H();return{ANTHROPIC_BASE_URL:n,ANTHROPIC_API_KEY:r.ANTHROPIC_API_KEY||X}}function Rt(e){if(e==="plan")return{ANTHROPIC_API_KEY:null};let t=H();return{ANTHROPIC_BASE_URL:t.ANTHROPIC_BASE_URL,ANTHROPIC_API_KEY:t.ANTHROPIC_API_KEY||null,CLAUDE_CODE_OAUTH_TOKEN:t.CLAUDE_CODE_OAUTH_TOKEN||null}}function Te(e,t){return _e()?St(e,t):(Pt.debug(`Gateway unhealthy \u2014 using direct Anthropic connection (mode=${e})`),Rt(e))}function wn(e={}){let t=e.selection??e.session?.selection??re(e.channel??void 0)??K(),n=e.session;if((n?.backendSessionId===void 0?n?.sessionId:n.backendSessionId)&&n?.backend&&t.backend!==n.backend)throw new Error(`Cannot resume ${n.backend} session on ${t.backend} backend`);return t}function Hn(){return ne.readIfPresent()?.default?K():null}function wt(e,t={}){let n={};return t.project&&(n.project=t.project),t.trigger&&(n.trigger=t.trigger),Te(e.mode||"api",Object.keys(n).length?n:void 0)}function bn(e,t){let{project:n,trigger:r,routeTrigger:o}=e.context;return wt(t,{project:n,trigger:o??r})}import v from"node:path";import P from"node:fs";import a from"node:path";function Ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ce(e,t){let n=a.resolve(e),r=a.resolve(t);return r===n||r.startsWith(n+a.sep)}function B(e){try{return P.lstatSync(e),!0}catch{return!1}}function Ht(e){let t=[],n=a.resolve(e);for(;!B(n);){let r=a.dirname(n);if(r===n)return null;t.unshift(a.basename(n)),n=r}return{base:n,tail:t}}function bt(e,t){return t.reduce((n,r)=>a.join(n,r),e)}function Oe(e){try{return P.realpathSync(e)}catch{return null}}function xt(e){let t=Ht(e),n=t?Oe(t.base):null;return n&&t?bt(n,t.tail):null}function Nt(e,t){let n=a.relative(a.resolve(e),a.resolve(t));return n===""?[]:n===".."||n.startsWith(`..${a.sep}`)||a.isAbsolute(n)?null:n.split(a.sep).filter(Boolean)}function Dt(e,t,n){let r=a.join(t,n);if(!B(r))return r;let o=Oe(r);return o&&Ce(e,o)?o:null}function Lt(e,t){return Ce(e,t)?t:null}function Ut(e,t){let n=xt(e),r=Nt(e,t);if(!n||!r)return null;let o=n;for(let c of r)if(o=Dt(n,o,c),!o)return null;return Lt(n,o)}function Un(e,t){return Ut(e,a.resolve(e,t))}function kn(e){try{return P.statSync(e).isFile()}catch{return!1}}function Kn(e){try{return P.statSync(e).isDirectory()}catch{return!1}}function ye(e){return B(e)?P.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()||n.isSymbolicLink()).map(n=>n.name).sort():[]}var Pe=v.join(V,"plugins");function kt(){return N()?Pe:null}function Kt(e=kt()){return e?ye(e):[]}function Gt(e){return v.posix.join("plugins",e)}function Mt(e){return e.skills!==!1&&N()}function Ie(e,t){return v.isAbsolute(e)?v.resolve(e):v.resolve(t,e)}function Yn(e,t={}){let n=t.dataDir??T,r=(e.pluginDirs??[]).map(p=>Ie(p,n));if(!Mt(e))return e.pluginDirs?r:void 0;let o=new Set(e.disabledPlugins??[]),c=(t.builtinIds??Kt(Pe)).filter(p=>!o.has(p)).map(p=>Ie(Gt(p),n));return[...new Set([...r,...c])]}export{Vt as a,We as b,Ve as c,Xe as d,qe as e,Xt as f,O as g,rn as h,on as i,Ln as j,Ce as k,B as l,Oe as m,Ut as n,Un as o,kn as p,Kn as q,ye as r,kt as s,Kt as t,Mt as u,Yn as v,sn as w,cn as x,un as y,ln as z,H as A,An as B,En as C,mn as D,hn as E,wn as F,Hn as G,wt as H,bn as I};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
var s="CORTEX_MCP_TOOL_ALLOWLIST",i={"cortex-core":["remote_bash","remote_read","remote_write","remote_edit","remote_glob","remote_grep","current_time","agent","agent_stop"],"cortex-ext":["cost_query","query_executions","cortex_context","wait_create","wait_check","wait_cancel"],"cortex-interaction-bridge":["cortex_plan_enter","cortex_plan_exit","cortex_ask_user"],"cortex-slack":["slack_send_file"],"cortex-feishu":["feishu_send_file"],"cortex-web":["send_file","send_view","send_decision","board_open"],"cortex-workers":["worker_spawn","worker_send","worker_list","worker_stop","worker_answer"],"cortex-worker-report":["mark_routine"]},l=new Set(Object.values(i).flat()),u=new Set(["cortex_schedule_add","cortex_schedule_list","cortex_schedule_get","cortex_schedule_remove","cortex_schedule_pause","cortex_schedule_resume","task_status","task_result","task_list","answer_subtask","thread_abort","thread_split","thread_wait","ask_manager","thread_run","cortex_commission_start","cortex_commission_submit","board_close"]),d=["agent","agent_stop"];function w(e,t){let o=e??t.flatMap(n=>i[n]??[]),r=new Set(d);return _(o.filter(n=>!r.has(n)))}function _(e){return[...new Set(e)].filter(t=>!u.has(t)).sort()}function x(e,t=l){let o=_(e).filter(r=>!t.has(r));if(o.length>0)throw new Error(`Unknown MCP tool name(s): ${o.join(", ")}`)}function p(e=process.env[s]){if(e===void 0)return null;let t;try{t=JSON.parse(e)}catch{throw new Error(`${s} must be a JSON string array`)}if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error(`${s} must be a JSON string array`);let o=_(t);return x(o),new Set(o)}function a(e,t){return(...o)=>t.has(o[0])?e(...o):void 0}function h(e,t,o=p()){if(o===null){t(e);return}let r=e,n=r.tool.bind(e),c=r.registerTool.bind(e);r.tool=a(n,o),r.registerTool=a(c,o);try{t(e)}finally{r.tool=n,r.registerTool=c}}export{s as a,i as b,u as c,d,w as e,_ as f,x as g,p as h,h as i};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
var s=(e=>(e.OPERATIONAL="operational",e.DEGRADED="degraded",e.DOWN="down",e.UNKNOWN="unknown",e))(s||{}),t=class{provider;status;statusDetail;model;alternatives;constructor(e){this.provider=e.provider,this.status=e.status,this.statusDetail=e.statusDetail??null,this.model=e.model??null,this.alternatives=e.alternatives??[]}get isAvailable(){return this.status==="operational"}},a=class{content;modelUsed;providerUsed;wasFallback;fallbackReason;inputTokens;outputTokens;cacheCreationInputTokens;cacheReadInputTokens;costUsd;raw;constructor(e){this.content=e.content,this.modelUsed=e.modelUsed,this.providerUsed=e.providerUsed,this.wasFallback=e.wasFallback,this.fallbackReason=e.fallbackReason??null,this.inputTokens=e.inputTokens??0,this.outputTokens=e.outputTokens??0,this.cacheCreationInputTokens=e.cacheCreationInputTokens??0,this.cacheReadInputTokens=e.cacheReadInputTokens??0,this.costUsd=e.costUsd??0,this.raw=e.raw??null}toString(){return this.content}};export{s as a,t as b,a as c};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
var f=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],m=12288,d=65510,h=[12288,12288,65281,65376,65504,65510];var x=4352,w=262141,s=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var a=(t,i)=>{let n=0,e=Math.floor(t.length/2)-1;for(;n<=e;){let r=Math.floor((n+e)/2),o=r*2;if(i<t[o])e=r-1;else if(i>t[o+1])n=r+1;else return!0}return!1};var p=19968,[c,R]=W(s);function W(t){let i=t[0],n=t[1];for(let e=0;e<t.length;e+=2){let r=t[e],o=t[e+1];if(p>=r&&p<=o)return[r,o];o-r>n-i&&(i=r,n=o)}return[i,n]}var g=t=>t<161||t>1114109?!1:a(f,t),u=t=>t<m||t>d?!1:a(h,t);var l=t=>t>=c&&t<=R?!0:t<x||t>w?!1:a(s,t);function b(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function H(t,{ambiguousAsWide:i=!1}={}){return b(t),u(t)||l(t)||i&&g(t)?2:1}export{u as a,l as b,H as c};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{b as p}from"./chunk-CXT5IR5T.js";function d(r,a,s){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:"error",errorMessage:a instanceof Error?a.message:String(a),timestamp:s}}function l(r){return typeof r.result=="function"}async function h(r,a,s,n){let e;for await(let t of a)r.push(t),s?.onEvent?.(t),t.type==="done"?e=t.message:t.type==="error"&&(e=t.error);l(a)&&(e=await a.result()),r.end(e),n(e)}function f(r,a,s){let n=Date.now(),e=new p,t=!1,o=c=>{t||(t=!0,s?.onResult?.(c))};return a().then(c=>h(e,c,s,o)).catch(c=>{let i=d(r,c,n),u={type:"error",reason:"error",error:i};e.push(u),s?.onEvent?.(u),e.end(i),o(i)}),e}function w(r,a){let s={stream:(n,e,t)=>f(n,async()=>(await r()).stream(n,e,t)),streamSimple:(n,e,t)=>f(n,async()=>(await r()).streamSimple(n,e,t))};return a?.fetchDeferred&&(s.fetchDeferred=(n,e,t)=>f(n,async()=>{let o=await r();if(!o.fetchDeferred)throw new Error("API does not support deferred responses");return o.fetchDeferred(n,e,t)})),a?.cancelDeferred&&(s.cancelDeferred=async(n,e,t)=>{let o=await r();if(!o.cancelDeferred)throw new Error("API cannot cancel deferred responses");await o.cancelDeferred(n,e,t)}),s}export{f as a,w as b};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{f as k,h as U,i as F}from"./chunk-RA6HKFBV.js";import{G as D,M as _,c as $,h as w,m as N,n as b,o as V}from"./chunk-QUUEQRIT.js";import*as v from"node:fs";import{createRequire as le}from"node:module";import*as p from"node:path";import{fileURLToPath as A}from"node:url";import{EventEmitter as ne}from"node:events";function z(){let e=new ne;return{emit:(r,l)=>{e.emit(r,l)},on:(r,l)=>{let n=async c=>{try{await l(c)}catch(a){console.error(`Event handler error (${r}):`,a)}};return e.on(r,n),()=>e.off(r,n)},clear:()=>{e.removeAllListeners()}}}import{spawn as se}from"node:child_process";async function B(e,r,l,n){return new Promise(c=>{let a=se(e,r,{cwd:l,shell:!1,stdio:["ignore","pipe","pipe"]}),i="",d="",o=!1,u,g=()=>{o||(o=!0,a.kill("SIGTERM"),setTimeout(()=>{a.killed||a.kill("SIGKILL")},5e3))};n?.signal&&(n.signal.aborted?g():n.signal.addEventListener("abort",g,{once:!0})),n?.timeout&&n.timeout>0&&(u=setTimeout(()=>{g()},n.timeout)),a.stdout?.on("data",h=>{i+=h.toString()}),a.stderr?.on("data",h=>{d+=h.toString()}),$(a).then(h=>{u&&clearTimeout(u),n?.signal&&n.signal.removeEventListener("abort",g),c({stdout:i,stderr:d,code:h??0,killed:o})}).catch(h=>{u&&clearTimeout(u),n?.signal&&n.signal.removeEventListener("abort",g),c({stdout:i,stderr:d,code:1,killed:o})})})}import{readFileSync as ie}from"node:fs";var oe=["extensions","skills","prompts","themes"];function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function W(e){try{let r=JSON.parse(N(ie(e,"utf-8")));if(!O(r)||!O(r.pi))return null;let l={};for(let n of oe){let c=r.pi[n];Array.isArray(c)&&c.every(a=>typeof a=="string")&&(l[n]=c)}return l}catch{return null}}var J="builtin:";function G(e){if(e.startsWith(J))return"builtin";if(e.startsWith("<")&&e.endsWith(">"))return e.slice(1,-1).split(":")[0]||"temporary"}function q(e){return e.startsWith(J)||e.startsWith("<")}function Ie(e,r){return{path:e,source:r.source,scope:r.scope,origin:r.origin,baseDir:r.baseDir}}function H(e,r){return{path:e,source:r.source,scope:r.scope??"temporary",origin:r.origin??"top-level",baseDir:r.baseDir}}var P=process.env.PI_TIMING==="1",S=new Map;function ae(e="main"){P&&S.set(e,{timings:[],lastTime:Date.now()})}function T(e,r="main"){if(!P)return;let l=Date.now();S.has(r)||ae(r);let n=S.get(r);n.timings.push({label:e,ms:l-n.lastTime}),n.lastTime=l}function ce(e,r){let l=r.filter(n=>n.ms>=0);if(l.length!==0){console.error(`
|
|
5
|
-
--- ${e} ---`);for(let n of l)console.error(` ${n.label}: ${n.ms}ms`);console.error(` TOTAL: ${l.reduce((n,c)=>n+c.ms,0)}ms`),console.error(`${"-".repeat(e.length+8)}
|
|
6
|
-
`)}}function je(){if(P)for(let[e,r]of S)ce(`Startup Timings: ${e}`,r.timings)}var R=le(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href),de="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,ue=!b&&p.extname(A(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href))===".ts",Z=b||de||V,K;function fe(){return K??=(Z?import("./jiti-static-loader-W3QZ4GDS.js"):import("./jiti-loader-WANUXUDO.js")).then(e=>e.createJiti),K}var X;function Q(){return X??=import("./virtual-modules-IDC5YKZJ.js").then(e=>e.VIRTUAL_MODULES),X}var M=null;function pe(){if(M)return M;let e=p.dirname(A(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href)),r=p.resolve(e,"../..","index.js"),l=R.resolve("typebox"),n=R.resolve("typebox/compile"),c=R.resolve("typebox/value"),a=p.resolve(e,"../../../../"),i=(f,y)=>{let m=p.join(a,f);return v.existsSync(m)?m:A(import.meta.resolve(y))},d=r,o=i("agent/dist/index.js","@earendil-works/pi-agent-core"),u=i("tui/dist/index.js","@earendil-works/pi-tui"),g=i("ai/dist/compat.js","@earendil-works/pi-ai/compat"),h=i("ai/dist/models.js","@earendil-works/pi-ai/models"),t=i("ai/dist/oauth.js","@earendil-works/pi-ai/oauth"),s=i("ai/dist/providers/all.js","@earendil-works/pi-ai/providers/all");return M={"@earendil-works/pi-coding-agent":d,"@earendil-works/pi-agent-core":o,"@earendil-works/pi-tui":u,"@earendil-works/pi-ai/providers/all":s,"@earendil-works/pi-ai/compat":g,"@earendil-works/pi-ai/models":h,"@earendil-works/pi-ai/oauth":t,"@earendil-works/pi-ai":g,"@mariozechner/pi-coding-agent":d,"@mariozechner/pi-agent-core":o,"@mariozechner/pi-tui":u,"@mariozechner/pi-ai/providers/all":s,"@mariozechner/pi-ai/compat":g,"@mariozechner/pi-ai/models":h,"@mariozechner/pi-ai/oauth":t,"@mariozechner/pi-ai":g,typebox:l,"typebox/compile":n,"typebox/value":c,"@sinclair/typebox":l,"@sinclair/typebox/compile":n,"@sinclair/typebox/value":c},M}var x,L=0,I=new Map;function ge(){I.clear(),x=void 0,L++}function he(e){let r=w(e);return x!==void 0&&x!==r&&ge(),x=r,{cwd:r,generation:L}}function me(){let e=()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},r={},l=new Set,n=()=>{if(r.staleMessage)throw new Error(r.staleMessage)},c={sendMessage:e,sendUserMessage:e,appendEntry:e,setSessionName:e,getSessionName:e,setLabel:e,getActiveTools:e,getAllTools:e,getSettings:e,setActiveTools:e,refreshTools:()=>{},getCommands:e,setModel:()=>Promise.reject(new Error("Extension runtime not initialized")),getThinkingLevel:e,setThinkingLevel:e,flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],mcpServers:new F,pendingVirtualModelRegistrations:[],createContext:e,assertActive:n,invalidate:a=>{if(!r.staleMessage){r.staleMessage=a??"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";for(let i of l)i();l.clear()}},trackEventBusSubscription:a=>{let i=!0,d=()=>{i&&(i=!1,l.delete(d),a())};return l.add(d),d},registerProvider:(a,i,d="<unknown>")=>{c.pendingProviderRegistrations.push({name:a,config:i,extensionPath:d})},registerNativeProvider:(a,i="<unknown>")=>{c.pendingNativeProviderRegistrations.push({provider:a,extensionPath:i})},unregisterProvider:a=>{c.pendingProviderRegistrations=c.pendingProviderRegistrations.filter(i=>i.name!==a),c.pendingNativeProviderRegistrations=c.pendingNativeProviderRegistrations.filter(i=>i.provider.id!==a)},registerVirtualModel:(a,i="<unknown>")=>{c.pendingVirtualModelRegistrations.push({definition:a,extensionPath:i})},unregisterVirtualModel:(a,i)=>{c.pendingVirtualModelRegistrations=c.pendingVirtualModelRegistrations.filter(({definition:d})=>d.provider!==a||d.id!==i)}};return c}function ve(e,r,l,n){let c=new Map,a=[],i=[],d="loading",o=()=>{if(d==="failed")throw new Error(`Extension "${e.path}" failed to load and its API is no longer active.`);r.assertActive()},u=t=>{d==="loading"?a.push(t):t()},g=()=>{c.clear(),a.length=0,i.length=0};return{api:{on(t,s){o();let f=(...m)=>s(...m),y=e.handlers.get(t)??[];return y.push(f),e.handlers.set(t,y),()=>{let m=e.handlers.get(t);if(!m)return;let E=m.indexOf(f);E!==-1&&(m.splice(E,1),m.length===0&&e.handlers.delete(t))}},registerTool(t){if(o(),typeof t.parameters!="object"||t.parameters===null||Array.isArray(t.parameters))throw new Error(`Tool "${t.name}" registered by extension "${e.path}" must define an object parameter schema.`);e.tools.set(t.name,{definition:t,sourceInfo:e.sourceInfo}),r.refreshTools()},registerCommand(t,s){if(o(),typeof t!="string"||t.length===0)throw new Error(`Command registered by extension "${e.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof s?.handler!="function")throw new Error(`Command "/${t}" registered by extension "${e.path}" must define handler().`);e.commands.set(t,{name:t,sourceInfo:e.sourceInfo,...s})},registerShortcut(t,s){o(),e.shortcuts.set(t,{shortcut:t,extensionPath:e.path,...s})},registerFlag(t,s){if(o(),s.default!==void 0&&typeof s.default!==s.type)throw new Error(`Invalid default for flag "${t}": expected ${s.type}, got ${typeof s.default}`);e.flags.set(t,{name:t,extensionPath:e.path,...s}),s.default!==void 0&&!r.flagValues.has(t)&&(d==="loading"?c.has(t)||c.set(t,s.default):r.flagValues.set(t,s.default))},registerMessageRenderer(t,s){o(),e.messageRenderers.set(t,s)},registerMarkdownTransformer(t){o(),e.markdownTransformer=t},registerEntryRenderer(t,s){o(),e.entryRenderers??=new Map,e.entryRenderers.set(t,s)},registerToolRenderer(t){o(),e.toolRenderers??=[],e.toolRenderers.push(t)},getFlag(t){if(o(),!!e.flags.has(t))return r.flagValues.has(t)?r.flagValues.get(t):c.get(t)},sendMessage(t,s){o(),r.sendMessage(t,s)},sendUserMessage(t,s){o(),r.sendUserMessage(t,s)},appendEntry(t,s){o(),r.appendEntry(t,s)},setSessionName(t){o(),r.setSessionName(t)},getSessionName(){return o(),r.getSessionName()},setLabel(t,s){o(),r.setLabel(t,s)},exec(t,s,f){return o(),B(t,s,f?.cwd??l,f)},getActiveTools(){return o(),r.getActiveTools()},getAllTools(){return o(),r.getAllTools()},getSettings(){return o(),r.getSettings()},setActiveTools(t){o(),r.setActiveTools(t)},getCommands(){return o(),r.getCommands()},setModel(t){return o(),r.setModel(t)},getThinkingLevel(){return o(),r.getThinkingLevel()},setThinkingLevel(t){o(),r.setThinkingLevel(t)},registerProvider(t,s){if(o(),typeof t=="string"){if(!s)throw new Error("Provider config is required when registering by name");u(()=>r.registerProvider(t,s,e.path));return}u(()=>r.registerNativeProvider(t,e.path))},unregisterProvider(t){o(),u(()=>r.unregisterProvider(t,e.path))},registerMcpServer(t,s){o();let f=U(t,s);if(typeof f=="string")throw new Error(`Invalid MCP server registered by extension "${e.path}": ${f}`);let y=r.mcpServers.get(t)?.extensionPath;if(y!==void 0&&y!==e.path)throw new Error(`MCP server "${t}" is already registered by extension "${y}"`);let m=r.mcpServers.list().find(j=>j.name!==t&&k(j.name)===k(t));if(m)throw new Error(`MCP server "${t}" conflicts with registered server "${m.name}"`);let E={name:t,config:structuredClone(f),extensionPath:e.path};u(()=>r.mcpServers.register(E))},unregisterMcpServer(t){o(),u(()=>r.mcpServers.unregister(t,e.path))},getMcpServers(){return o(),r.mcpServers.list()},registerVirtualModel(t){o();let s={...t,route:f=>t.route(f,r.createContext())};u(()=>r.registerVirtualModel(s,e.path))},unregisterVirtualModel(t,s){o(),u(()=>r.unregisterVirtualModel(t,s))},events:{emit(t,s){o(),n.emit(t,s)},on(t,s){o();let f=r.trackEventBusSubscription(n.on(t,s));return d==="loading"&&i.push(f),f}}},commit:()=>{if(d==="loading"){r.assertActive();for(let[t,s]of c)r.flagValues.has(t)||r.flagValues.set(t,s);for(let t of a)t();d="active",g()}},discard:()=>{if(d==="loading"){d="failed";for(let t of i)t();g()}}}}function Y(e){return e!==void 0&&x===e.cwd&&L===e.generation}async function ye(e,r){if(Y(r)){let d=I.get(e);if(d)return d}let l=await fe(),n=Z?{virtualModules:await Q(),tryNative:!1}:ue?{virtualModules:await Q(),tsconfigPaths:!0}:{alias:pe()},i=await l(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href,{moduleCache:!1,...n}).import(e,{default:!0});if(typeof i=="function")return Y(r)&&I.set(e,i),i}function we(e,r){let l=G(e)??"local",n=q(e)?void 0:p.dirname(r);return{path:e,resolvedPath:r,sourceInfo:H(e,{source:l,baseDir:n}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}async function ee(e,r,l,n,c,a){let i=we(r,l),d=ve(i,a,n,c);try{await e(d.api),d.commit()}catch(o){throw d.discard(),o}return T(`${r} factory`,"extensions"),i}async function xe(e,r,l,n,c){let a=w(e,r,{normalizeUnicodeSpaces:!0});try{let i=await ye(a,c);return T(`${e} module import`,"extensions"),i?{extension:await ee(i,e,a,r,l,n),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${e}`}}catch(i){return{extension:null,error:`Failed to load extension: ${i instanceof Error?i.message:String(i)}`}}}async function Je(e,r,l,n,c="<inline>"){let a=w(r);return ee(e,c,c,a,l,n)}async function te(e,r,l,n,c=!1){let a=[],i=[],d=[],o=c?he(r):void 0,u=o?.cwd??w(r),g=l??z(),h=n??me();for(let t of e){let{extension:s,error:f}=await xe(t,u,g,h,o);if(f){i.push({path:t,error:f});continue}s&&a.push(s)}return{extensions:a,errors:i,warnings:d,runtime:h}}async function Ee(e,r,l,n){return te(e,r,l,n)}async function Ge(e,r,l,n){return te(e,r,l,n,!0)}function Se(e){return e.endsWith(".ts")||e.endsWith(".js")}function re(e){let r=p.join(e,"package.json");if(v.existsSync(r)){let c=W(r);if(c?.extensions?.length){let a=[];for(let i of c.extensions){let d=p.resolve(e,i);v.existsSync(d)&&a.push(d)}if(a.length>0)return a}}let l=p.join(e,"index.ts"),n=p.join(e,"index.js");return v.existsSync(l)?[l]:v.existsSync(n)?[n]:null}function C(e){if(!v.existsSync(e))return[];let r=[];try{let l=v.readdirSync(e,{withFileTypes:!0});for(let n of l){let c=p.join(e,n.name);if((n.isFile()||n.isSymbolicLink())&&Se(n.name)){r.push(c);continue}if(n.isDirectory()||n.isSymbolicLink()){let a=re(c);a&&r.push(...a)}}}catch{return[]}return r}async function qe(e,r,l=_(),n){let c=w(r),a=w(l),i=[],d=new Set,o=h=>{for(let t of h){let s=p.resolve(t);d.has(s)||(d.add(s),i.push(t))}},u=p.join(c,D,"extensions");o(C(u));let g=p.join(a,"extensions");o(C(g));for(let h of e){let t=w(h,c,{normalizeUnicodeSpaces:!0});if(v.existsSync(t)&&v.statSync(t).isDirectory()){let s=re(t);if(s){o(s);continue}o(C(t));continue}o([t])}return Ee(i,c,n)}export{z as a,W as b,J as c,G as d,q as e,Ie as f,H as g,ae as h,T as i,je as j,ge as k,me as l,Je as m,Ee as n,Ge as o,qe as p};
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{e as k,na as x}from"./chunk-LACGULCN.js";import{d as X}from"./chunk-FX6MOGLR.js";import{F as h,Ia as R,R as w,f as W,s as I,v as F,w as G,x as H,y as N,za as J}from"./chunk-Q7CE3UIE.js";import{h as P,w as U}from"./chunk-QUUEQRIT.js";import{randomBytes as be}from"node:crypto";import{createWriteStream as Le}from"node:fs";import{writeFile as Ce}from"node:fs/promises";import{tmpdir as Me}from"node:os";import{join as ke}from"node:path";var q=384;function z(e,t){return ke(Me(),`${e}-${be(8).toString("hex")}${t}`)}async function Pt(e,t,n){let r=z(e,t);return await Ce(r,n,{mode:q,flag:"wx"}),r}function Ut(e,t){let n=z(e,t);return{path:n,stream:Le(n,{mode:q,flags:"wx"})}}var Ft=2e3,Gt=51200;function B(e){if(e.length===0)return[];let t=e.split(`
|
|
5
|
-
`);return e.endsWith(`
|
|
6
|
-
`)&&t.pop(),t}function Ht(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function Jt(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,o=Buffer.byteLength(e,"utf-8"),i=B(e),s=i.length;if(s<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:s,totalBytes:o,outputLines:s,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};if(Buffer.byteLength(i[0],"utf-8")>r)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines:s,totalBytes:o,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:r};let l=[],c=0,p="lines";for(let d=0;d<i.length&&d<n;d++){let m=i[d],y=Buffer.byteLength(m,"utf-8")+(d>0?1:0);if(c+y>r){p="bytes";break}l.push(m),c+=y}l.length>=n&&c<=r&&(p="lines");let u=l.join(`
|
|
7
|
-
`),f=Buffer.byteLength(u,"utf-8");return{content:u,truncated:!0,truncatedBy:p,totalLines:s,totalBytes:o,outputLines:l.length,outputBytes:f,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function Xt(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,o=Buffer.byteLength(e,"utf-8"),i=B(e),s=i.length;if(s<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:s,totalBytes:o,outputLines:s,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let a=[],l=0,c="lines",p=!1;for(let d=i.length-1;d>=0&&a.length<n;d--){let m=i[d],y=Buffer.byteLength(m,"utf-8")+(a.length>0?1:0);if(l+y>r){if(c="bytes",a.length===0){let A=Ie(m,r);a.unshift(A),l=Buffer.byteLength(A,"utf-8"),p=!0}break}a.unshift(m),l+=y}a.length>=n&&l<=r&&(c="lines");let u=a.join(`
|
|
8
|
-
`),f=Buffer.byteLength(u,"utf-8");return{content:u,truncated:!0,truncatedBy:c,totalLines:s,totalBytes:o,outputLines:a.length,outputBytes:f,lastLinePartial:p,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function Ie(e,t){let n=Buffer.from(e,"utf-8");if(n.length<=t)return e;let r=n.length-t;for(;r<n.length&&(n[r]&192)===128;)r++;return n.slice(r).toString("utf-8")}function qt(e,t=500){return e.length<=t?{text:e,wasTruncated:!1}:{text:`${e.slice(0,t)}... [truncated]`,wasTruncated:!0}}function zt(e,t){let n=Buffer.from(e,"utf-8"),r=B(e).length;if(n.length<=t)return{content:e,truncated:!1,removedChars:0,totalBytes:n.length,totalLines:r};let o=p=>p>=n.length||(n[p]&192)!==128,i=Math.floor(t/2);for(;i>0&&!o(i);)i--;let s=n.length-(t-Math.floor(t/2));for(;s<n.length&&!o(s);)s++;let a=n.subarray(0,i).toString("utf-8"),l=n.subarray(s).toString("utf-8"),c=Array.from(n.subarray(i,s).toString("utf-8")).length;return{content:`${a}\u2026${c} chars truncated\u2026${l}`,truncated:!0,removedChars:c,totalBytes:n.length,totalLines:r}}function Ne(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function Re(e,t){e.input+=t.input,e.output+=t.output,e.cacheRead+=t.cacheRead,e.cacheWrite+=t.cacheWrite,e.cost+=t.cost.total}function Yt(e,t){return{input:e.input+t.input,output:e.output+t.output,cacheRead:e.cacheRead+t.cacheRead,cacheWrite:e.cacheWrite+t.cacheWrite,...e.cacheWrite1h!==void 0||t.cacheWrite1h!==void 0?{cacheWrite1h:(e.cacheWrite1h??0)+(t.cacheWrite1h??0)}:{},...e.reasoning!==void 0||t.reasoning!==void 0?{reasoning:(e.reasoning??0)+(t.reasoning??0)}:{},totalTokens:e.totalTokens+t.totalTokens,cost:{input:e.cost.input+t.cost.input,output:e.cost.output+t.cost.output,cacheRead:e.cost.cacheRead+t.cost.cacheRead,cacheWrite:e.cost.cacheWrite+t.cost.cacheWrite,total:e.cost.total+t.cost.total}}}function Vt(e){let t=new Map;for(let n of e){let r,o;if(n.type==="message"&&n.message.role==="assistant"?(r=`${n.message.provider}/${n.message.responseModel??n.message.model}`,o=n.message.usage):n.type==="usage"?(r=`${n.provider}/${n.model}`,o=n.usage):n.type==="message"&&n.message.role==="toolResult"&&n.message.usage?(r="Tools/summaries",o=n.message.usage):(n.type==="branch_summary"||n.type==="compaction")&&n.usage&&(r="Tools/summaries",o=n.usage),!r||!o)continue;let i=t.get(r);i||(i=Ne(),t.set(r,i)),Re(i,o)}return Array.from(t,([n,r])=>({key:n,cost:r.cost,tokens:r.input+r.output+r.cacheRead+r.cacheWrite})).filter(n=>n.cost>0||n.tokens>0).sort((n,r)=>r.cost-n.cost)}function Be(e,t,n,r=0,o="end"){if(!e)return{visualLines:[],skippedCount:0};let s=new h(e,r,0).render(n);if(s.length<=t)return{visualLines:s,skippedCount:0};let a=o==="start"?s.slice(0,t):s.slice(-t),l=s.length-t;return{visualLines:a,skippedCount:l}}var S=class{options;cachedWidth;cachedLines;constructor(t){this.options=t}render(t){if(this.cachedLines===void 0||this.cachedWidth!==t){let{text:n,maxVisualLines:r,keep:o,formatHint:i}=this.options,s=Be(n,r,t,0,o),a=s.visualLines;if(s.skippedCount>0){let l=W(i(s.skippedCount),t,"...");this.cachedLines=o==="start"?[...a,l]:[l,...a]}else this.cachedLines=a;this.cachedWidth=t}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};import*as te from"node:os";import{pathToFileURL as We}from"node:url";var De="(?:\\u0007|\\u001B\\u005C|\\u009C)",Z="\\u001B\\]",Y="[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",je="[\\dA-PR-TZcf-nq-uy=><~]",ve=new RegExp(`(?:${Z}[\\s\\S]*?${De})|${Y}${je}`,"g"),Pe=new RegExp(`(?:${Z}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${Y})$`),Ue=256;function tn(e){if(!e.includes("\x1B")&&!e.includes("\x9B"))return{complete:e,pending:""};let t=Math.max(0,e.length-Ue),n=Pe.exec(e.slice(t));if(!n)return{complete:e,pending:""};let r=t+n.index;return{complete:e.slice(0,r),pending:e.slice(r)}}function V(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return!e.includes("\x1B")&&!e.includes("\x9B")?e:e.replace(ve,"")}function Fe(e){if(typeof e!="string")return"";let t=te.homedir();return e.startsWith(t)?`~${e.slice(t.length)}`:e}function Ge(e,t,n){if(!I().hyperlinks)return e;let r=P(t,n);return G(e,We(r).href)}function ne(e){return typeof e=="string"?e:e==null?"":null}function K(e){return typeof e=="string"&&e.trim()!==""&&(e=Number(e)),typeof e=="number"&&Number.isFinite(e)?e:void 0}function cn(e,t){if(e==null&&t==null)return"";let n=e==null?1:K(e);if(n===void 0)return"";if(t==null)return`:${n}`;let r=K(t);if(r===void 0)return"";let o=n+r-1;return`:${n}${o?`-${o}`:""}`}function _(e){return e.replace(/\t/g," ")}function ln(e){return e.replace(/\r/g,"")}function re(e,t){if(!e)return"";let n=e.content.filter(s=>s.type==="text"),r=e.content.filter(s=>s.type==="image"),o=n.map(s=>X(V(s.text||"")).replace(/\r/g,"")).join(`
|
|
9
|
-
`),i=I();if(r.length>0&&(!i.images||!t)){let s=r.map(a=>{let l=a.mimeType??"image/unknown",c=a.data&&a.mimeType?F(a.data,a.mimeType)??void 0:void 0;return H(l,c)}).join(`
|
|
10
|
-
`);o=o?`${o}
|
|
11
|
-
${s}`:s}return o}var Q=100;function pn(e,t,n,r){let o=n.fg("toolTitle",n.bold(e));if(t==null)return o;let i=typeof t=="object"&&!Array.isArray(t)?Object.entries(t):[["args",t]];if(i.length===0)return o;if(r){let l=i.map(([c,p])=>{let u=typeof p=="string"?p:JSON.stringify(p,null,2)??String(p);return` ${c}: ${_(u).replace(/\r/g,"").split(`
|
|
12
|
-
`).join(`
|
|
13
|
-
`)}`});return`${o}
|
|
14
|
-
${n.fg("muted",l.join(`
|
|
15
|
-
`))}`}let s=i.map(([l,c])=>`${l}=${JSON.stringify(c)??String(c)}`).join(" "),a=s.length>Q?`${s.slice(0,Q-3)}...`:s;return`${o} ${n.fg("muted",a)}`}function ee(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t),r=Math.floor(n/60),o=n%60;return r<60?`${r}m ${o}s`:`${Math.floor(r/60)}h ${r%60}m ${o}s`}function oe(e){let t=e.state;e.executionStarted&&t.startedAt===void 0&&(t.startedAt=Date.now(),t.endedAt=void 0)}function ie(e,t){let n=e.state;if(n.startedAt!==void 0&&t&&!n.interval&&(n.interval=setInterval(()=>e.invalidate(),1e3)),(!t||e.isError)&&(n.endedAt??=Date.now(),n.interval&&(clearInterval(n.interval),n.interval=void 0)),!t&&e.durationMs!==void 0)return`Took ${ee(e.durationMs)}`;if(n.startedAt===void 0)return;let r=n.endedAt??Date.now();return`${t?"Elapsed":"Took"} ${ee(r-n.startedAt)}`}function He(e){return e.fg("error","[invalid arg]")}function fn(e,t,n,r){if(e===null)return He(t);let o=e||r?.emptyFallback;return o?Ge(t.fg("accent",Fe(o)),o,n):t.fg("toolOutput","...")}function T(e){let t="";for(let n of e){let r=t===""?/^[A-Za-z_$]$/.test(n):/^[A-Za-z0-9_$]$/.test(n);t+=r?n:"_"}return t===""?"_":t}var Je=/^[A-Za-z_$][A-Za-z0-9_$]*$/,E=" ",Xe=16e3,qe=32,ze=["minimum","exclusiveMinimum","maximum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","minItems","maxItems"],se=new Set(["minimum","exclusiveMinimum","minLength","minItems"]),Ze=new Set(["maximum","exclusiveMaximum","maxLength","maxItems"]),Ye=80,ce=/[\r\n\u2028\u2029]/g;function Ve(e,t={}){let n=e.inputSchema===void 0?"unknown":pe(e.inputSchema,{maxChars:t.inputMaxChars??Xe});return`${T(e.name)}(args: ${n}): Promise<${j(e.outputSchema)}>;`}function le(e,t={}){let n=`declare const tools: { ${Ve(e,t)} };`;return`${e.description?.trim()??""}
|
|
16
|
-
|
|
17
|
-
codemode tool declaration:
|
|
18
|
-
\`\`\`ts
|
|
19
|
-
${n}
|
|
20
|
-
\`\`\``}function j(e){return e===void 0?"unknown":pe(e)}function Ke(e){return Je.test(e)?e:JSON.stringify(e)}function D(e){let t=[...new Set(e)];return t.includes("unknown")?"unknown":t.length===0?"never":t.join(" | ")}function pe(e,t={}){let n=i=>$(e,{root:e,resolving:new Set,expansions:0,tags:i}),r=n(!0);if(t.maxChars===void 0||r.length<=t.maxChars)return r;let o=n(!1);return o.length<=t.maxChars?o:"unknown"}function Qe(e,t){if(e!=="#"&&!e.startsWith("#/"))return;let n=t;for(let r of e.slice(2).split("/").filter(Boolean)){let o=decodeURIComponent(r).replaceAll("~1","/").replaceAll("~0","~");if(typeof n!="object"||n===null||Array.isArray(n)||!(o in n))return;n=n[o]}return typeof n=="boolean"||typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}function $(e,t){if(e===!0)return"unknown";if(e===!1)return"never";if(typeof e!="object"||e===null||Array.isArray(e))return"unknown";if(typeof e.$ref=="string"){let o=e.$ref;if(t.resolving.has(o)||t.expansions>=qe)return"unknown";let i=Qe(o,t.root);if(i===void 0)return"unknown";t.expansions++,t.resolving.add(o);try{return $(i,t)}finally{t.resolving.delete(o)}}if("const"in e)return JSON.stringify(e.const)??"unknown";if(Array.isArray(e.enum))return D(e.enum.map(o=>JSON.stringify(o)??"unknown"));let n=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(n)return D(n.map(o=>$(o,t)));if(Array.isArray(e.allOf)){let o=e.allOf.map(i=>$(i,t)).filter(i=>i!=="unknown");return o.length===0?"unknown":o.map(i=>i.includes(" | ")?`(${i})`:i).join(" & ")}let r=e.type;if(Array.isArray(r))return D(r.map(o=>$({...e,type:o},t)));switch(r){case"string":return"string";case"number":case"integer":return"number";case"boolean":return"boolean";case"null":return"null";case"array":return ae(e,t);case"object":return ue(e,t);case void 0:return"properties"in e||"additionalProperties"in e||"required"in e?ue(e,t):"items"in e||"prefixItems"in e?ae(e,t):"unknown";default:return"unknown"}}function ae(e,t){if(e.items!==void 0&&!Array.isArray(e.items))return`Array<${$(e.items,t)}>`;let n=Array.isArray(e.prefixItems)?e.prefixItems:Array.isArray(e.items)?e.items:[];return n.length>0?`[${n.map(r=>$(r,t)).join(", ")}]`:"unknown[]"}function et(e){let t=e?.description;return typeof t=="string"?t.trim():""}function tt(e){if(typeof e!="object"||e===null||Array.isArray(e))return"";let t=e,n=Array.isArray(t.anyOf)?t.anyOf:t.oneOf,r=Array.isArray(n)?n.filter(c=>c?.type!=="null"):[],o=r.length===1?r[0]:void 0,s=(typeof o=="object"&&o!==null&&!Array.isArray(o)?[t,o]:[t]).map(c=>({...c,...c.exclusiveMinimum===!0?{minimum:void 0,exclusiveMinimum:c.minimum}:{},...c.exclusiveMaximum===!0?{maximum:void 0,exclusiveMaximum:c.maximum}:{}})),a=[],l=c=>c==="integer"||Array.isArray(c)&&c.includes("integer");s.some(c=>l(c.type))&&a.push("@integer");for(let c of ze){let p=s.map(u=>u[c]);if(se.has(c)||Ze.has(c)){let u=p.filter(f=>typeof f=="number");if(u.length===0)continue;a.push(`@${c} ${se.has(c)?Math.max(...u):Math.min(...u)}`);continue}for(let u of new Set(p))(typeof u=="number"||typeof u=="string")&&a.push(`@${c} ${u}`)}return s.some(c=>c.uniqueItems===!0)&&a.push("@uniqueItems"),t.default!==void 0&&t.default!==null&&a.push(`@default ${JSON.stringify(t.default)}`),t.deprecated===!0&&a.push("@deprecated"),a.filter(c=>c.length<=Ye).map(c=>c.replace(ce,p=>`\\u${p.charCodeAt(0).toString(16).padStart(4,"0")}`)).join(" ")}function ue(e,t){let n=typeof e.properties=="object"&&e.properties!==null&&!Array.isArray(e.properties)?e.properties:{},r=new Set(Array.isArray(e.required)?e.required:[]),o=Object.keys(n).sort(),i=o.map(c=>{let p=r.has(c)?"":"?";return`${Ke(c)}${p}: ${$(n[c],t)};`}),s=e.additionalProperties;if(s!==void 0&&s!==!1){let c=s===!0?"unknown":$(s,t);i.push(`[key: string]: ${c};`)}else s===void 0&&o.length===0&&i.push("[key: string]: unknown;");if(i.length===0)return"{}";let a=o.map(c=>{let p=et(n[c]).split(ce).map(f=>f.trim()).filter(Boolean),u=t.tags?tt(n[c]):"";return u?[...p,u]:p});if(!a.some(c=>c.length>0))return`{ ${i.join(" ")} }`;let l=["{"];a.forEach((c,p)=>{for(let u of c)l.push(`${E}// ${u}`);l.push(`${E}${i[p].replaceAll(`
|
|
21
|
-
`,`
|
|
22
|
-
${E}`)}`)});for(let c of i.slice(o.length))l.push(`${E}${c}`);return l.push("}"),l.join(`
|
|
23
|
-
`)}var O="// @options:",nt=["max_output_tokens","timeout_ms"],b="`max_output_tokens` and `timeout_ms`";var de=String.raw`
|
|
24
|
-
start: options_source | plain_source
|
|
25
|
-
options_source: OPTIONS_LINE NEWLINE SOURCE
|
|
26
|
-
plain_source: SOURCE
|
|
27
|
-
|
|
28
|
-
OPTIONS_LINE: /[ \t]*\/\/ @options:[^\r\n]*/
|
|
29
|
-
NEWLINE: /\r?\n/
|
|
30
|
-
SOURCE: /[\s\S]+/
|
|
31
|
-
`,g=class extends Error{constructor(t){super(t),this.name="CodemodeSourceError"}};function fe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function rt(e){if(e==="")throw new g(`@options must be a JSON object with supported fields ${b}`);let t;try{t=JSON.parse(e)}catch(s){throw new g(`@options must be valid JSON with supported fields ${b}: ${s instanceof Error?s.message:String(s)}`)}if(typeof t!="object"||t===null||Array.isArray(t))throw new g(`@options must be a JSON object with supported fields ${b}`);let n=t;for(let s of Object.keys(n))if(!nt.includes(s))throw new g(`@options only supports ${b}; got \`${s}\``);let r={},{max_output_tokens:o,timeout_ms:i}=n;if(o!==void 0){if(!fe(o))throw new g("@options field `max_output_tokens` must be a non-negative safe integer");r.maxOutputTokens=o}if(i!==void 0){if(!fe(i)||i===0||i>2147483647)throw new g("@options field `timeout_ms` must be a positive integer up to 2147483647");r.timeoutMs=i}return r}function yn(e){if(e.trim()==="")throw new g('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {"max_output_tokens": 1000}`.');let t=e.split(`
|
|
32
|
-
`),n=t.findIndex((a,l)=>l>0&&a.trimStart().startsWith(O));if(n!==-1)throw new g(`The ${O} line must be the first line of the input; found one on line ${n+1}`);let r=e.indexOf(`
|
|
33
|
-
`),i=t[0].replace(/\r$/,"").trimStart();if(!i.startsWith(O))return{code:e,options:{}};let s=r===-1?"":e.slice(r);if(s.trim()==="")throw new g("The @options line must be followed by JavaScript source on subsequent lines");return{code:s,options:rt(i.slice(O.length).trim())}}var C="tool_search",he=8,ot=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function it(e){return e.length>4&&e.endsWith("ies")?`${e.slice(0,-3)}y`:e.length>4&&/(ches|shes|sses|xes|zes)$/.test(e)?e.slice(0,-2):e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}function me(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>0&&!ot.has(t)).map(it)}function ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function L(e,t){if(ge(e)){if(typeof e.description=="string"&&t.push(e.description),ge(e.properties))for(let[n,r]of Object.entries(e.properties))t.push(n),L(r,t);L(e.items,t);for(let n of["anyOf","oneOf","allOf"]){let r=e[n];if(Array.isArray(r))for(let o of r)L(o,t)}}}function st(e,t){let n=[e.name,e.name.replaceAll("_"," "),e.description];return L(e.parameters,n),t&&n.push(t.name,t.description??"",t.instructions??""),{name:e.name,text:n.filter(r=>r.trim()).join(" ")}}var v=class{k1;b;constructor(t={}){this.k1=t.k1??1.2,this.b=t.b??.75}rank(t,n,r){let o=[...new Set(me(t))];if(o.length===0||n.length===0||r<=0)return[];let i=n.map(p=>{let u=new Map;for(let f of me(p.text))u.set(f,(u.get(f)??0)+1);return u}),s=i.map(p=>[...p.values()].reduce((u,f)=>u+f,0)),a=s.reduce((p,u)=>p+u,0)/n.length||1,l=new Map(o.map(p=>{let u=i.filter(f=>f.has(p)).length;return[p,Math.log(1+(n.length-u+.5)/(u+.5))]})),c=[];return n.forEach((p,u)=>{let f=0;for(let d of o){let m=i[u].get(d);if(!m)continue;let y=this.k1*(1-this.b+this.b*s[u]/a);f+=(l.get(d)??0)*(m*(this.k1+1)/(m+y))}f>0&&c.push({name:p.name,score:f})}),c.sort((p,u)=>u.score-p.score).slice(0,r)}},at=x.Object({query:x.String({description:"Search query for deferred tools."}),limit:x.Optional(x.Number({description:`Maximum number of tools to return. Defaults to ${he}.`}))});function ut(e){return e==="codemode"||e==="deferred"}function ct(e,t,n){let r=e.getActiveTools(),o=e.getAllTools().filter(a=>ut(a.exposure)&&!r.includes(a.name)),i=o.map(a=>st(a,a.namespace)),s=new v().rank(t,i,n);return s.length>0&&e.setActiveTools([...r,...s.map(a=>a.name)]),s.map(a=>({name:a.name,description:o.find(l=>l.name===a.name)?.description??""}))}var lt=`# Tool discovery
|
|
34
|
-
|
|
35
|
-
Searches over deferred tool metadata with BM25 and exposes matching tools for the next model call.
|
|
36
|
-
|
|
37
|
-
Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${C}\`) to search for the required tools. For MCP tool discovery, always use \`${C}\`.`;function Sn(e={}){return{name:C,label:C,description:lt,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:at,exposure:"model-only",reachesTools:()=>"all",async execute(t,{query:n,limit:r}){if(n.trim()==="")throw new Error("query must not be empty");let o=r??he;if(!Number.isInteger(o)||o<=0)throw new Error("limit must be a positive integer");let i=e.tools?ct(e.tools,n,o):[];return{content:[{type:"text",text:i.length===0?"No matching tools found.":`Loaded ${i.length} tool${i.length===1?"":"s"}. They are available from your next call:
|
|
38
|
-
${i.map(a=>`- ${a.name}: ${a.description.trim().split(/\r?\n/)[0]}`).join(`
|
|
39
|
-
`)}`}],details:{loaded:i.map(a=>a.name)}}}}}import{join as xt}from"node:path";function pt(e,t){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,outputSchema:e.outputSchema,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,execute:(n,r,o,i,s)=>e.execute(n,r,o,i,s??t?.(n,o))}}function An(e){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,outputSchema:e.outputSchema,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,execute:async(t,n,r,o)=>e.execute(t,n,r,o)}}var ye=()=>import("../../vendor/pi/dist/extensions/codemode/execute.js");var ft=10,dt=8,mt=5,$e=80,gt=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function xe(e,t,n){return`${e.fg("muted",`... (${t} more ${n},`)} ${R("app.tools.expand","to expand")}${e.fg("muted",")")}`}function ht(e){return e===void 0?"":e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}function Se(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}function yt(e,t){switch(e.status){case"running":return t.fg("warning","\u2026");case"ok":return t.fg("success","\u2713");case"error":return t.fg("error","\u2717");case"cancelled":return t.fg("muted","\u2298")}}function $t(e,t,n){let r=!n&&e.args.length>$e?`${e.args.slice(0,$e-3)}...`:e.args,o=ht(e.durationMs),i=`${yt(e,t)} ${t.fg("toolTitle",e.name)}`;return r&&(i+=` ${t.fg("muted",r)}`),o&&(i+=` ${t.fg("dim",o)}`),e.cost&&(i+=` ${t.fg("dim",Se(e.cost))}`),n&&e.error&&(i+=`
|
|
40
|
-
${t.fg("error",e.error.split(`
|
|
41
|
-
`).join(`
|
|
42
|
-
`))}`),i}var Te={renderCall(e,t,n){oe(n);let r=ne(e?.code),o=t.fg("toolTitle",t.bold("codemode")),i=n.lastComponent??new N;if(i.clear(),r===null)return i.addChild(new h(`${o} ${t.fg("error","[invalid arg]")}`,0,0)),i;if(i.addChild(new h(o,0,0)),r){let s=J(_(r.replace(/\r/g,"").trimEnd()),"javascript").join(`
|
|
43
|
-
`);i.addChild(n.expanded?new h(s,0,0):new S({text:s,maxVisualLines:ft,keep:"start",formatHint:a=>xe(t,a,"lines")}))}return i},renderResult(e,t,n,r){let o=ie(r,t.isPartial),i=r.lastComponent??new N;i.clear();let s=e.details?.calls??[];if(s.length>0){let u=t.expanded?s:s.slice(-dt),f=u.map(m=>$t(m,n,t.expanded));u.length<s.length&&f.unshift(`${n.fg("muted",`... (${s.length-u.length} earlier calls,`)} ${R("app.tools.expand","to expand")}${n.fg("muted",")")}`);let d=s.filter(m=>m.cost);if(d.length>1){let m=d.reduce((y,A)=>y+(A.cost??0),0);f.push(n.fg("muted",`Model calls: ${Se(m)}`))}i.addChild(new w(1)),i.addChild(new h(f.join(`
|
|
44
|
-
`),0,0))}let[a,...l]=e.content,c=a?.type==="text"&>.test(a.text),p=t.isPartial?"":re({...e,content:c?l:e.content},r.showImages).trim();if(p){let u=r.isError?"error":"toolOutput",f=_(p).split(`
|
|
45
|
-
`).map(d=>n.fg(u,d)).join(`
|
|
46
|
-
`);if(i.addChild(new w(1)),t.expanded)i.addChild(new h(f,0,0));else{i.addChild(new S({text:f,maxVisualLines:mt,keep:"start",formatHint:m=>xe(n,m,"lines")}));let d=e.details?.fullOutputPath;d&&i.addChild(new h(n.fg("muted",`Full output: ${d}`),0,0))}}return o&&(i.addChild(new w(1)),i.addChild(new h(n.fg("muted",o),0,0))),i}};var M="codemode",Un="codemode-store",St={type:"string"},Tt=x.Object({code:x.String({description:"Raw JavaScript source."})}),Ae={snippet:"Run JavaScript that calls other tools",guidelines:["Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls."]},At=xt(U(),"codemode.md"),wt='Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file system, network, or timers.\n- `await tools.<name>({ ...args })` resolves to a string, or an object if the tool\'s declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; check its fields. Calls still running when the script ends are cancelled.\n- Optional first line: `// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}`';function _t(e){let t=["Globals:","- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.","- `store(key, value)` and `load(key)` keep JSON values across codemode calls.","- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools."];return e&&t.push(`- \`models\`: classifiers and image generation. Read ${At} first.`),t.join(`
|
|
47
|
-
`)}var Et=k.codemode.inlineBudget,Ot=4;function we(e,t=[]){let n=t.flatMap(r=>r.trim()?[`- ${r.trim()}`]:[]);return{name:e.name,description:n.length>0?`${e.description.trim()}
|
|
48
|
-
|
|
49
|
-
${n.join(`
|
|
50
|
-
`)}`:e.description,inputSchema:e.parameters,outputSchema:e.outputSchema??St}}function _e(e){return e.filter(t=>t.name!==M)}function bt(e){let t=T(e.name);return`${t===e.name?`### \`${t}\``:`### \`${t}\` (\`${e.name}\`)`}
|
|
51
|
-
${le(e).trim()}`}function Lt(e,t){if(t===void 0)return new Set(e.flatMap(s=>s.entries.map(a=>a.name)));let n=e.map(s=>[...s.entries].sort((a,l)=>a.cost-l.cost)),r=new Set,o=t,i=n.filter(s=>s.length>0);for(;i.length>0;)i=i.filter(s=>{let a=s[0];return a.cost>o?!1:(o-=a.cost,r.add(a.name),s.shift(),s.length>0)});return r}function Ee(e,t={}){let n=_e(e).filter(l=>!t.deferred?.has(l.name)).map(l=>we(l,t.guidelines?.get(l.name))),r=new Map([["",{namespace:void 0,entries:[]}]]);for(let l of n){let c=t.namespaces?.get(l.name),p=c?`ns:${c.name}`:"",u=r.get(p)??{namespace:c,entries:[]};r.set(p,u);let f=bt(l);u.entries.push({name:l.name,section:f,cost:Math.ceil(f.length/Ot)})}let o=[...r.values()].sort((l,c)=>l.namespace===void 0?-1:c.namespace===void 0?1:l.namespace.name.localeCompare(c.namespace.name)),i=Lt(o,t.inlineBudget),s=[wt,_t(t.models===!0)];if(n.length===0)return s.join(`
|
|
52
|
-
|
|
53
|
-
`);let a=["Nested tools:"];for(let{namespace:l,entries:c}of o){let p=c.filter(u=>i.has(u.name));if(l){let u=p.length===c.length?"":p.length===0?" (tools not listed)":" (some tools not listed)",f=l.description?.trim();a.push(`## ${l.name}${u}${f?`
|
|
54
|
-
${f}`:""}`)}for(let u of p)a.push(u.section)}return s.push(a.join(`
|
|
55
|
-
|
|
56
|
-
`)),s.join(`
|
|
57
|
-
|
|
58
|
-
`)}function Oe(e,t){if(typeof e!="object"||e===null)return;let{type:n,properties:r,required:o}=e;if(n!=="object"||typeof r!="object"||r===null)return;let i=new Set(Array.isArray(o)?o:[]);return`{ ${Object.entries(r).map(([a,l])=>{let c=t>0?Oe(l,t-1):void 0;return`${a}${i.has(a)?"":"?"}${c?`: ${c}`:""}`}).join(", ")} }`}function Ct(e){let t=j(e);return t==="string"?"a string":`\`${Oe(e,1)??t.replace(/\s+/g," ")}\``}function Mt(e){return`${e.description.trim()}
|
|
59
|
-
|
|
60
|
-
Codemode: \`tools.${T(e.name)}(args)\` resolves to ${Ct(we(e).outputSchema)}.`}function kt(e,t){let n=t.getMode?.()??k.codemode.mode,r=u=>e.getExposure(u.name)==="direct",o=_e(e.callable),i=new Set(o.map(u=>u.name)),s={};if(n==="on")for(let u of e.declared)i.has(u.name)&&(s[u.name]=Mt(u));let a=n==="only"?o:o.filter(u=>!r(u)),l=new Map(a.flatMap(u=>{let f=e.getNamespace(u.name);return f?[[u.name,f]]:[]})),c=new Map(a.map(u=>[u.name,e.getPromptGuidelines(u.name)]));s[M]=Ee(a,{models:t.models===!0,namespaces:l,guidelines:c,deferred:new Set(a.filter(u=>e.getExposure(u.name)==="deferred").map(u=>u.name)),inlineBudget:t.getInlineBudget?.()??Et});let p=new Set(e.declared.map(u=>u.name));return{descriptions:s,hiddenDeclarations:n==="only"?o.filter(u=>r(u)&&p.has(u.name)).map(u=>u.name):[]}}var It=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function Nt(e){return typeof e!="string"?[]:It.test(e)?"all":e.match(/\w+/g)??[]}function Wn(e={}){return{name:M,label:M,description:Ee([],{models:e.models===!0}),promptSnippet:Ae.snippet,promptGuidelines:[...Ae.guidelines],parameters:Tt,exposure:"model-only",prepareLoadout:t=>kt(t,e),reachesTools:t=>Nt(t.code),constrainedSampling:{type:"grammar",variants:{openai_lark:de}},execute:async(t,n,r,o,i)=>(await ye()).executeCodemode(t,n,r,o,i,e),...Te}}export{tn as a,V as b,Pt as c,Ut as d,Ft as e,Gt as f,Ht as g,Jt as h,Xt as i,qt as j,zt as k,Ne as l,Re as m,Yt as n,Vt as o,pt as p,An as q,Be as r,S as s,Fe as t,ne as u,cn as v,_ as w,ln as x,re as y,pn as z,oe as A,ie as B,He as C,fn as D,T as E,le as F,yn as G,C as H,he as I,st as J,v as K,Sn as L,M,Un as N,At as O,we as P,_e as Q,Wn as R};
|