agent-afk 5.208.3 → 5.209.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/session-ledger-project.d.ts +3 -0
- package/dist/agent/types/session-types.d.ts +3 -0
- package/dist/cli.mjs +618 -618
- package/dist/index.mjs +18 -18
- package/dist/telegram.mjs +49 -49
- package/dist/web-server/routes.config.d.ts +12 -0
- package/dist/web-server/shared/ledger-adapter.d.ts +3 -0
- package/dist/web-ui-assets/assets/abap-BdImnpbu.js +1 -0
- package/dist/web-ui-assets/assets/actionscript-3-B3316cI-.js +1 -0
- package/dist/web-ui-assets/assets/ada-bCR0ucgS.js +1 -0
- package/dist/web-ui-assets/assets/ahk-CsyLZFj1.js +1 -0
- package/dist/web-ui-assets/assets/ahk2-8Zs4aa1G.js +1 -0
- package/dist/web-ui-assets/assets/andromeeda-C4gqWexZ.js +1 -0
- package/dist/web-ui-assets/assets/angular-html-DA-rfuFy.js +1 -0
- package/dist/web-ui-assets/assets/angular-ts-BrjP3tb8.js +1 -0
- package/dist/web-ui-assets/assets/apache-Pmp26Uib.js +1 -0
- package/dist/web-ui-assets/assets/apex-DhZFqWV2.js +1 -0
- package/dist/web-ui-assets/assets/apl-CORt7UWP.js +1 -0
- package/dist/web-ui-assets/assets/applescript-Co6uUVPk.js +1 -0
- package/dist/web-ui-assets/assets/ara-BRHolxvo.js +1 -0
- package/dist/web-ui-assets/assets/asciidoc-CSVQ5wI8.js +1 -0
- package/dist/web-ui-assets/assets/asm-D_Q5rh1f.js +1 -0
- package/dist/web-ui-assets/assets/astro-HNnZUWAn.js +1 -0
- package/dist/web-ui-assets/assets/aurora-x-D-2ljcwZ.js +1 -0
- package/dist/web-ui-assets/assets/awk-DMzUqQB5.js +1 -0
- package/dist/web-ui-assets/assets/ayu-dark-DYE7WIF3.js +1 -0
- package/dist/web-ui-assets/assets/ayu-light-BA47KaF1.js +1 -0
- package/dist/web-ui-assets/assets/ayu-mirage-32ctXXKs.js +1 -0
- package/dist/web-ui-assets/assets/ballerina-BFfxhgS-.js +1 -0
- package/dist/web-ui-assets/assets/bat-CickPsom.js +1 -0
- package/dist/web-ui-assets/assets/beancount-k_qm7-4y.js +1 -0
- package/dist/web-ui-assets/assets/berry-uYugtg8r.js +1 -0
- package/dist/web-ui-assets/assets/bibtex-CHM0blh-.js +1 -0
- package/dist/web-ui-assets/assets/bicep-Bmn6On1c.js +1 -0
- package/dist/web-ui-assets/assets/bird2-Bx8U0n9b.js +1 -0
- package/dist/web-ui-assets/assets/blade-2xfisSek.js +1 -0
- package/dist/web-ui-assets/assets/bsl-DlhNcFeZ.js +1 -0
- package/dist/web-ui-assets/assets/c-BIGW1oBm.js +1 -0
- package/dist/web-ui-assets/assets/c3-Dp5svz6Z.js +1 -0
- package/dist/web-ui-assets/assets/cadence-Bv_4Rxtq.js +1 -0
- package/dist/web-ui-assets/assets/cairo-KRGpt6FW.js +1 -0
- package/dist/web-ui-assets/assets/catppuccin-frappe-CZL1YF0i.js +1 -0
- package/dist/web-ui-assets/assets/catppuccin-latte-DH-8KZSZ.js +1 -0
- package/dist/web-ui-assets/assets/catppuccin-macchiato-B7yYVSCf.js +1 -0
- package/dist/web-ui-assets/assets/catppuccin-mocha-Ct7hS0mc.js +1 -0
- package/dist/web-ui-assets/assets/chapel-DTp_pixX.js +1 -0
- package/dist/web-ui-assets/assets/clarity-Dn5IMItf.js +1 -0
- package/dist/web-ui-assets/assets/clojure-P80f7IUj.js +1 -0
- package/dist/web-ui-assets/assets/cmake-D1j8_8rp.js +1 -0
- package/dist/web-ui-assets/assets/cobol-nBiQ_Alo.js +1 -0
- package/dist/web-ui-assets/assets/codeowners-Bp6g37R7.js +1 -0
- package/dist/web-ui-assets/assets/codeql-DsOJ9woJ.js +1 -0
- package/dist/web-ui-assets/assets/coffee-Ch7k5sss.js +1 -0
- package/dist/web-ui-assets/assets/common-lisp-Cg-RD9OK.js +1 -0
- package/dist/web-ui-assets/assets/coq-C7JzOVbR.js +1 -0
- package/dist/web-ui-assets/assets/cpp-BMRokrvK.js +1 -0
- package/dist/web-ui-assets/assets/crystal-DGywbUpC.js +1 -0
- package/dist/web-ui-assets/assets/csharp-DSvCPggb.js +1 -0
- package/dist/web-ui-assets/assets/css-CLj8gQPS.js +1 -0
- package/dist/web-ui-assets/assets/csv-fuZLfV_i.js +1 -0
- package/dist/web-ui-assets/assets/cue-D82EKSYY.js +1 -0
- package/dist/web-ui-assets/assets/cypher-COkxafJQ.js +1 -0
- package/dist/web-ui-assets/assets/d-85-TOEBH.js +1 -0
- package/dist/web-ui-assets/assets/dark-plus-C3mMm8J8.js +1 -0
- package/dist/web-ui-assets/assets/dart-bE4Kk8sk.js +1 -0
- package/dist/web-ui-assets/assets/dax-CEL-wOlO.js +1 -0
- package/dist/web-ui-assets/assets/desktop-BmXAJ9_W.js +1 -0
- package/dist/web-ui-assets/assets/diff-D97Zzqfu.js +1 -0
- package/dist/web-ui-assets/assets/docker-BcOcwvcX.js +1 -0
- package/dist/web-ui-assets/assets/dotenv-Da5cRb03.js +1 -0
- package/dist/web-ui-assets/assets/dracula-BzJJZx-M.js +1 -0
- package/dist/web-ui-assets/assets/dracula-soft-BXkSAIEj.js +1 -0
- package/dist/web-ui-assets/assets/dream-maker-BtqSS_iP.js +1 -0
- package/dist/web-ui-assets/assets/edge-FbVlp4U3.js +1 -0
- package/dist/web-ui-assets/assets/elixir-CkH2-t6x.js +1 -0
- package/dist/web-ui-assets/assets/elm-DbKCFpqz.js +1 -0
- package/dist/web-ui-assets/assets/emacs-lisp-C_m_b--Z.js +1 -0
- package/dist/web-ui-assets/assets/erb-DXfck5VN.js +1 -0
- package/dist/web-ui-assets/assets/erlang-DsQrWhSR.js +1 -0
- package/dist/web-ui-assets/assets/everforest-dark-BgDCqdQA.js +1 -0
- package/dist/web-ui-assets/assets/everforest-light-C8M2exoo.js +1 -0
- package/dist/web-ui-assets/assets/fennel-BYunw83y.js +1 -0
- package/dist/web-ui-assets/assets/fish-BvzEVeQv.js +1 -0
- package/dist/web-ui-assets/assets/fluent-C4IJs8-o.js +1 -0
- package/dist/web-ui-assets/assets/fortran-fixed-form-CkoXwp7k.js +1 -0
- package/dist/web-ui-assets/assets/fortran-free-form-BxgE0vQu.js +1 -0
- package/dist/web-ui-assets/assets/fsharp-CXgrBDvD.js +1 -0
- package/dist/web-ui-assets/assets/gdresource-TyuKm33G.js +1 -0
- package/dist/web-ui-assets/assets/gdscript-DqcFQ5yU.js +1 -0
- package/dist/web-ui-assets/assets/gdshader-DkwncUOv.js +1 -0
- package/dist/web-ui-assets/assets/genie-D0YGMca9.js +1 -0
- package/dist/web-ui-assets/assets/gherkin-DyxjwDmM.js +1 -0
- package/dist/web-ui-assets/assets/git-commit-F4YmCXRG.js +1 -0
- package/dist/web-ui-assets/assets/git-rebase-r7XF79zn.js +1 -0
- package/dist/web-ui-assets/assets/github-dark-DHJKELXO.js +1 -0
- package/dist/web-ui-assets/assets/github-dark-default-Cuk6v7N8.js +1 -0
- package/dist/web-ui-assets/assets/github-dark-dimmed-DH5Ifo-i.js +1 -0
- package/dist/web-ui-assets/assets/github-dark-high-contrast-E3gJ1_iC.js +1 -0
- package/dist/web-ui-assets/assets/github-light-DAi9KRSo.js +1 -0
- package/dist/web-ui-assets/assets/github-light-default-D7oLnXFd.js +1 -0
- package/dist/web-ui-assets/assets/github-light-high-contrast-BfjtVDDH.js +1 -0
- package/dist/web-ui-assets/assets/gleam-BspZqrRM.js +1 -0
- package/dist/web-ui-assets/assets/glimmer-js-ByusRIyA.js +1 -0
- package/dist/web-ui-assets/assets/glimmer-ts-BfAWNZQY.js +1 -0
- package/dist/web-ui-assets/assets/glsl-DplSGwfg.js +1 -0
- package/dist/web-ui-assets/assets/gn-n2N0HUVH.js +1 -0
- package/dist/web-ui-assets/assets/gnuplot-DdkO51Og.js +1 -0
- package/dist/web-ui-assets/assets/go-C27-OAKa.js +1 -0
- package/dist/web-ui-assets/assets/graphql-ChdNCCLP.js +1 -0
- package/dist/web-ui-assets/assets/groovy-gcz8RCvz.js +1 -0
- package/dist/web-ui-assets/assets/gruvbox-dark-hard-CFHQjOhq.js +1 -0
- package/dist/web-ui-assets/assets/gruvbox-dark-medium-GsRaNv29.js +1 -0
- package/dist/web-ui-assets/assets/gruvbox-dark-soft-CVdnzihN.js +1 -0
- package/dist/web-ui-assets/assets/gruvbox-light-hard-CH1njM8p.js +1 -0
- package/dist/web-ui-assets/assets/gruvbox-light-medium-DRw_LuNl.js +1 -0
- package/dist/web-ui-assets/assets/gruvbox-light-soft-hJgmCMqR.js +1 -0
- package/dist/web-ui-assets/assets/hack-BWmVpMyf.js +1 -0
- package/dist/web-ui-assets/assets/haml-D5jkg6IW.js +1 -0
- package/dist/web-ui-assets/assets/handlebars-BpdQsYii.js +1 -0
- package/dist/web-ui-assets/assets/haskell-Df6bDoY_.js +1 -0
- package/dist/web-ui-assets/assets/haxe-CfZj7gIn.js +1 -0
- package/dist/web-ui-assets/assets/hcl-BWvSN4gD.js +1 -0
- package/dist/web-ui-assets/assets/hjson-D5-asLiD.js +1 -0
- package/dist/web-ui-assets/assets/hlsl-D3lLCCz7.js +1 -0
- package/dist/web-ui-assets/assets/horizon-BUw7H-hv.js +1 -0
- package/dist/web-ui-assets/assets/horizon-bright-CUuTKBJd.js +1 -0
- package/dist/web-ui-assets/assets/houston-DnULxvSX.js +1 -0
- package/dist/web-ui-assets/assets/html-derivative-DlHx6ybY.js +1 -0
- package/dist/web-ui-assets/assets/html-pp8916En.js +1 -0
- package/dist/web-ui-assets/assets/http-jrhK8wxY.js +1 -0
- package/dist/web-ui-assets/assets/hurl-irOxFIW8.js +1 -0
- package/dist/web-ui-assets/assets/hxml-2-FPmUDs.js +1 -0
- package/dist/web-ui-assets/assets/hy-DFXneXwc.js +1 -0
- package/dist/web-ui-assets/assets/imba-DGztddWO.js +1 -0
- package/dist/web-ui-assets/assets/index-B2zr9aOB.js +13 -0
- package/dist/web-ui-assets/assets/index-DThJH7ut.js +380 -0
- package/dist/web-ui-assets/assets/index-DoWw28qv.css +1 -0
- package/dist/web-ui-assets/assets/ini-BEwlwnbL.js +1 -0
- package/dist/web-ui-assets/assets/java-CylS5w8V.js +1 -0
- package/dist/web-ui-assets/assets/javascript-wDzz0qaB.js +1 -0
- package/dist/web-ui-assets/assets/jinja-f2NsQr07.js +1 -0
- package/dist/web-ui-assets/assets/jison-wvAkD_A8.js +1 -0
- package/dist/web-ui-assets/assets/json-Cp-IABpG.js +1 -0
- package/dist/web-ui-assets/assets/json5-C9tS-k6U.js +1 -0
- package/dist/web-ui-assets/assets/jsonc-Des-eS-w.js +1 -0
- package/dist/web-ui-assets/assets/jsonl-DcaNXYhu.js +1 -0
- package/dist/web-ui-assets/assets/jsonnet-DFQXde-d.js +1 -0
- package/dist/web-ui-assets/assets/jssm-C2t-YnRu.js +1 -0
- package/dist/web-ui-assets/assets/jsx-g9-lgVsj.js +1 -0
- package/dist/web-ui-assets/assets/julia-5Bft2YPA.js +1 -0
- package/dist/web-ui-assets/assets/just-Cwhn7H3k.js +1 -0
- package/dist/web-ui-assets/assets/kanagawa-dragon-BuwD2xS4.js +1 -0
- package/dist/web-ui-assets/assets/kanagawa-lotus-C3DzagqV.js +1 -0
- package/dist/web-ui-assets/assets/kanagawa-wave-DFGoQZhC.js +1 -0
- package/dist/web-ui-assets/assets/kdl-DV7GczEv.js +1 -0
- package/dist/web-ui-assets/assets/kotlin-BdnUsdx6.js +1 -0
- package/dist/web-ui-assets/assets/kusto-wEQ09or8.js +1 -0
- package/dist/web-ui-assets/assets/laserwave-DUszq2jm.js +1 -0
- package/dist/web-ui-assets/assets/latex-D5pSuvFb.js +1 -0
- package/dist/web-ui-assets/assets/lean-BZvkOJ9d.js +1 -0
- package/dist/web-ui-assets/assets/less-B1dDrJ26.js +1 -0
- package/dist/web-ui-assets/assets/light-plus-B7mTdjB0.js +1 -0
- package/dist/web-ui-assets/assets/liquid-C0sCDyMI.js +1 -0
- package/dist/web-ui-assets/assets/llvm-BZoOZj88.js +1 -0
- package/dist/web-ui-assets/assets/log-2UxHyX5q.js +1 -0
- package/dist/web-ui-assets/assets/logo-BtOb2qkB.js +1 -0
- package/dist/web-ui-assets/assets/lua-BaeVxFsk.js +1 -0
- package/dist/web-ui-assets/assets/luau-BnpPk5vE.js +1 -0
- package/dist/web-ui-assets/assets/make-CHLpvVh8.js +1 -0
- package/dist/web-ui-assets/assets/markdown-Cvjx9yec.js +1 -0
- package/dist/web-ui-assets/assets/marko-DjSrsDqO.js +1 -0
- package/dist/web-ui-assets/assets/material-theme-D5KoaKCx.js +1 -0
- package/dist/web-ui-assets/assets/material-theme-darker-BfHTSMKl.js +1 -0
- package/dist/web-ui-assets/assets/material-theme-lighter-B0m2ddpp.js +1 -0
- package/dist/web-ui-assets/assets/material-theme-ocean-CyktbL80.js +1 -0
- package/dist/web-ui-assets/assets/material-theme-palenight-Csfq5Kiy.js +1 -0
- package/dist/web-ui-assets/assets/matlab-D7o27uSR.js +1 -0
- package/dist/web-ui-assets/assets/mdc-D1_yUvq7.js +1 -0
- package/dist/web-ui-assets/assets/mdx-Cmh6b_Ma.js +1 -0
- package/dist/web-ui-assets/assets/mermaid-CQcHuHx7.js +1 -0
- package/dist/web-ui-assets/assets/min-dark-CafNBF8u.js +1 -0
- package/dist/web-ui-assets/assets/min-light-CTRr51gU.js +1 -0
- package/dist/web-ui-assets/assets/mipsasm-CKIfxQSi.js +1 -0
- package/dist/web-ui-assets/assets/mojo-DJz3ZmWd.js +1 -0
- package/dist/web-ui-assets/assets/monokai-BRVnQi9A.js +1 -0
- package/dist/web-ui-assets/assets/moonbit-CHtswR0a.js +1 -0
- package/dist/web-ui-assets/assets/move-el3G9tDJ.js +1 -0
- package/dist/web-ui-assets/assets/narrat-DRg8JJMk.js +1 -0
- package/dist/web-ui-assets/assets/nextflow-C-mBbutL.js +1 -0
- package/dist/web-ui-assets/assets/nextflow-groovy-vE_lwT2v.js +1 -0
- package/dist/web-ui-assets/assets/nginx-BpAMiNFr.js +1 -0
- package/dist/web-ui-assets/assets/night-owl-C39BiMTA.js +1 -0
- package/dist/web-ui-assets/assets/night-owl-light-CMTm3GFP.js +1 -0
- package/dist/web-ui-assets/assets/nim-BIad80T-.js +1 -0
- package/dist/web-ui-assets/assets/nix-CwoSXNpI.js +1 -0
- package/dist/web-ui-assets/assets/nord-Ddv68eIx.js +1 -0
- package/dist/web-ui-assets/assets/nsis-BlV79W_Q.js +1 -0
- package/dist/web-ui-assets/assets/nushell-D3jzshHO.js +1 -0
- package/dist/web-ui-assets/assets/objective-c-DXmwc3jG.js +1 -0
- package/dist/web-ui-assets/assets/objective-cpp-CLxacb5B.js +1 -0
- package/dist/web-ui-assets/assets/ocaml-C0hk2d4L.js +1 -0
- package/dist/web-ui-assets/assets/odin-BBf5iR-q.js +1 -0
- package/dist/web-ui-assets/assets/one-dark-pro-DVMEJ2y_.js +1 -0
- package/dist/web-ui-assets/assets/one-light-C3Wv6jpd.js +1 -0
- package/dist/web-ui-assets/assets/openscad-C4EeE6gA.js +1 -0
- package/dist/web-ui-assets/assets/org-DM6o9KBp.js +1 -0
- package/dist/web-ui-assets/assets/pascal-D93ZcfNL.js +1 -0
- package/dist/web-ui-assets/assets/perl-B9cMNwum.js +1 -0
- package/dist/web-ui-assets/assets/php-Csjmro_R.js +1 -0
- package/dist/web-ui-assets/assets/pkl-u5AG7uiY.js +1 -0
- package/dist/web-ui-assets/assets/plastic-3e1v2bzS.js +1 -0
- package/dist/web-ui-assets/assets/plsql-ChMvpjG-.js +1 -0
- package/dist/web-ui-assets/assets/po-BTJTHyun.js +1 -0
- package/dist/web-ui-assets/assets/poimandres-CS3Unz2-.js +1 -0
- package/dist/web-ui-assets/assets/polar-C0HS_06l.js +1 -0
- package/dist/web-ui-assets/assets/postcss-CXtECtnM.js +1 -0
- package/dist/web-ui-assets/assets/powerquery-CEu0bR-o.js +1 -0
- package/dist/web-ui-assets/assets/powershell-BmBUJMz7.js +1 -0
- package/dist/web-ui-assets/assets/prisma-Vru482bI.js +1 -0
- package/dist/web-ui-assets/assets/prolog-CbFg5uaA.js +1 -0
- package/dist/web-ui-assets/assets/proto-C7zT0LnQ.js +1 -0
- package/dist/web-ui-assets/assets/pug-DKIMFp6K.js +1 -0
- package/dist/web-ui-assets/assets/puppet-BMWR74SV.js +1 -0
- package/dist/web-ui-assets/assets/purescript-CklMAg4u.js +1 -0
- package/dist/web-ui-assets/assets/python-B6aJPvgy.js +1 -0
- package/dist/web-ui-assets/assets/qml-3beO22l8.js +1 -0
- package/dist/web-ui-assets/assets/qmldir-C8lEn-DE.js +1 -0
- package/dist/web-ui-assets/assets/qss-IeuSbFQv.js +1 -0
- package/dist/web-ui-assets/assets/r-Cf5RLm7j.js +1 -0
- package/dist/web-ui-assets/assets/racket-BqYA7rlc.js +1 -0
- package/dist/web-ui-assets/assets/raku-DXvB9xmW.js +1 -0
- package/dist/web-ui-assets/assets/razor-BjBPvh-w.js +1 -0
- package/dist/web-ui-assets/assets/rbs-CpoqiR4B.js +1 -0
- package/dist/web-ui-assets/assets/red-hvxz__6c.js +1 -0
- package/dist/web-ui-assets/assets/reg-C-SQnVFl.js +1 -0
- package/dist/web-ui-assets/assets/regexp-CDVJQ6XC.js +1 -0
- package/dist/web-ui-assets/assets/rel-C3B-1QV4.js +1 -0
- package/dist/web-ui-assets/assets/riscv-BM1_JUlF.js +1 -0
- package/dist/web-ui-assets/assets/ron-D8l8udqQ.js +1 -0
- package/dist/web-ui-assets/assets/rose-pine-5qJOZa0Y.js +1 -0
- package/dist/web-ui-assets/assets/rose-pine-dawn-zx0QlTCp.js +1 -0
- package/dist/web-ui-assets/assets/rose-pine-moon-C9pEdX9L.js +1 -0
- package/dist/web-ui-assets/assets/rosmsg-BJDFO7_C.js +1 -0
- package/dist/web-ui-assets/assets/rst-bs7f0vWN.js +1 -0
- package/dist/web-ui-assets/assets/ruby-C0TQ7zu5.js +1 -0
- package/dist/web-ui-assets/assets/rust-B1yitclQ.js +1 -0
- package/dist/web-ui-assets/assets/sas-DEy46yEz.js +1 -0
- package/dist/web-ui-assets/assets/sass-Cj5Yp3dK.js +1 -0
- package/dist/web-ui-assets/assets/scala-CqE71os6.js +1 -0
- package/dist/web-ui-assets/assets/scheme-C98Dy4si.js +1 -0
- package/dist/web-ui-assets/assets/scss-D5BDwBP9.js +1 -0
- package/dist/web-ui-assets/assets/sdbl-DVxCFoDh.js +1 -0
- package/dist/web-ui-assets/assets/shaderlab-Dg9Lc6iA.js +1 -0
- package/dist/web-ui-assets/assets/shellscript-Yzrsuije.js +1 -0
- package/dist/web-ui-assets/assets/shellsession-BADoaaVG.js +1 -0
- package/dist/web-ui-assets/assets/slack-dark-BthQWCQV.js +1 -0
- package/dist/web-ui-assets/assets/slack-ochin-DqwNpetd.js +1 -0
- package/dist/web-ui-assets/assets/smalltalk-BOQMe2GC.js +1 -0
- package/dist/web-ui-assets/assets/smithy-cds9vsN8.js +1 -0
- package/dist/web-ui-assets/assets/snazzy-light-Bw305WKR.js +1 -0
- package/dist/web-ui-assets/assets/solarized-dark-CpvCGNkr.js +1 -0
- package/dist/web-ui-assets/assets/solarized-light-Dlz6yCKv.js +1 -0
- package/dist/web-ui-assets/assets/solidity-DijEV5ha.js +1 -0
- package/dist/web-ui-assets/assets/soy-8wufbnw4.js +1 -0
- package/dist/web-ui-assets/assets/sparql-rVzFXLq3.js +1 -0
- package/dist/web-ui-assets/assets/splunk-BtCnVYZw.js +1 -0
- package/dist/web-ui-assets/assets/sql-CRqJ_cUM.js +1 -0
- package/dist/web-ui-assets/assets/ssh-config-_ykCGR6B.js +1 -0
- package/dist/web-ui-assets/assets/stata-DI20mbqo.js +1 -0
- package/dist/web-ui-assets/assets/stylus-BEDo0Tqx.js +1 -0
- package/dist/web-ui-assets/assets/surrealql-Cjom0U5J.js +1 -0
- package/dist/web-ui-assets/assets/svelte-Cy7k_4gC.js +1 -0
- package/dist/web-ui-assets/assets/swift-C2oV4EkX.js +1 -0
- package/dist/web-ui-assets/assets/synthwave-84-CbfX1IO0.js +1 -0
- package/dist/web-ui-assets/assets/system-verilog-0hqHdDBg.js +1 -0
- package/dist/web-ui-assets/assets/systemd-4A_iFExJ.js +1 -0
- package/dist/web-ui-assets/assets/talonscript-CkByrt1z.js +1 -0
- package/dist/web-ui-assets/assets/tasl-QIJgUcNo.js +1 -0
- package/dist/web-ui-assets/assets/tcl-dwOrl1Do.js +1 -0
- package/dist/web-ui-assets/assets/templ-DhtptRzy.js +1 -0
- package/dist/web-ui-assets/assets/terraform-BETggiCN.js +1 -0
- package/dist/web-ui-assets/assets/tex-D96PA37w.js +1 -0
- package/dist/web-ui-assets/assets/tokyo-night-hegEt444.js +1 -0
- package/dist/web-ui-assets/assets/toml-vGWfd6FD.js +1 -0
- package/dist/web-ui-assets/assets/ts-tags-D351s5mN.js +1 -0
- package/dist/web-ui-assets/assets/tsv-B_m7g4N7.js +1 -0
- package/dist/web-ui-assets/assets/tsx-COt5Ahok.js +1 -0
- package/dist/web-ui-assets/assets/turtle-BsS91CYL.js +1 -0
- package/dist/web-ui-assets/assets/twig-27uCiNez.js +1 -0
- package/dist/web-ui-assets/assets/typescript-BPQ3VLAy.js +1 -0
- package/dist/web-ui-assets/assets/typespec-CAFt9gP4.js +1 -0
- package/dist/web-ui-assets/assets/typst-BUadGCkm.js +1 -0
- package/dist/web-ui-assets/assets/v-BGw2Nkan.js +1 -0
- package/dist/web-ui-assets/assets/vala-CsfeWuGM.js +1 -0
- package/dist/web-ui-assets/assets/vb-Cu-pLBUe.js +1 -0
- package/dist/web-ui-assets/assets/verilog-nZwndyjY.js +1 -0
- package/dist/web-ui-assets/assets/vesper-DRje8inN.js +1 -0
- package/dist/web-ui-assets/assets/vhdl-CeAyd5Ju.js +1 -0
- package/dist/web-ui-assets/assets/viml-CJc9bBzg.js +1 -0
- package/dist/web-ui-assets/assets/vitesse-black-Bkuqu6BP.js +1 -0
- package/dist/web-ui-assets/assets/vitesse-dark-D0r3Knsf.js +1 -0
- package/dist/web-ui-assets/assets/vitesse-light-CVO1_9PV.js +1 -0
- package/dist/web-ui-assets/assets/vue-BqiEGhQt.js +1 -0
- package/dist/web-ui-assets/assets/vue-html-AaS7Mt5G.js +1 -0
- package/dist/web-ui-assets/assets/vue-vine-BoDAl6tE.js +1 -0
- package/dist/web-ui-assets/assets/vyper-CDx5xZoG.js +1 -0
- package/dist/web-ui-assets/assets/wasm-CG6Dc4jp.js +1 -0
- package/dist/web-ui-assets/assets/wasm-MzD3tlZU.js +1 -0
- package/dist/web-ui-assets/assets/wenyan-BV7otONQ.js +1 -0
- package/dist/web-ui-assets/assets/wgsl-Dx-B1_4e.js +1 -0
- package/dist/web-ui-assets/assets/wikitext-BhOHFoWU.js +1 -0
- package/dist/web-ui-assets/assets/wit-5i3qLPDT.js +1 -0
- package/dist/web-ui-assets/assets/wolfram-lXgVvXCa.js +1 -0
- package/dist/web-ui-assets/assets/xml-sdJ4AIDG.js +1 -0
- package/dist/web-ui-assets/assets/xsl-CtQFsRM5.js +1 -0
- package/dist/web-ui-assets/assets/yaml-Buea-lGh.js +1 -0
- package/dist/web-ui-assets/assets/zenscript-DVFEvuxE.js +1 -0
- package/dist/web-ui-assets/assets/zig-VOosw3JB.js +1 -0
- package/dist/web-ui-assets/index.html +2 -2
- package/package.json +1 -1
- package/dist/web-ui-assets/assets/index-3YQ3Lxgf.css +0 -1
- package/dist/web-ui-assets/assets/index-CXeZ1OEr.js +0 -298
package/dist/telegram.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var YW=Object.defineProperty;var h=(t,e)=>()=>(t&&(e=t(t=0)),e);var mo=(t,e)=>{for(var n in e)YW(t,n,{get:e[n],enumerable:!0})};function ti(t){return ni.find(e=>e.name===t)}function $c(t){return process.env[t]!==void 0}function Am(t){return/^(0|false|no|off)$/i.test(t.trim())}function or(t){return/^(1|true|yes|on)$/i.test(t.trim())}var fv=h(()=>{"use strict";F()});var ni,mv,k,F=h(()=>{"use strict";fv();ni=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",description:"Maximum concurrency-safe tool calls run simultaneously within one dispatcher batch. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"4",category:"model"},{name:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",description:"Maximum subagent calls run simultaneously from one compose/DAG layer or skill wave. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"2",category:"model"},{name:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",description:"Maximum background subagent jobs running simultaneously in one registry. Default 10; accepted range 1-64; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"10",example:"5",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. When unset, falls back to the model output ceiling (AFK's own per-model limit, 64k\u2013128k \u2014 NOT a small provider default), so every request advertises the full ceiling by default. An over-ceiling value is clamped down with a warning.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an evidence citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. On by default. Set to 0 to disable.',type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-ROUND time-to-first-token budget (ms) for the anthropic-direct streaming loop. Bounds how long a round may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. The budget is divided into 3 shorter first-byte ATTEMPTS (each ~2/3 of this value, so the worst-case wall time per round is unchanged from the previous 2-attempt regime while a transient stall gets 3 chances instead of 2). NOTE: a request whose FIRST token takes longer than the per-attempt bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted and re-driven, then surfaces as an error once the budget is spent (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb), i.e. 3 \xD7 120s. Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. On by default. Set to 0/false/no/off to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_PROMPT",description:"Enable LLM-generated empty-prompt suggestions \u2014 a proposed next action shown as ghost text when the prompt is blank, accepted with Tab or Right-arrow. Fires only after a turn has completed in the session: the startup prompt (and the prompt right after /clear) is left clean because there is no session context to ground a proposal in. On by default. Set to 0/false/no/off to disable. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | max | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"AFK_WORKSPACE_DISABLED",description:"Disable the shared agent workspace (WorkspaceStore + workspace_publish/workspace_query tools + preamble injection). When set to 1, subagents do not get workspace tools and no workspace preamble is injected at fork time \u2014 each agent works in full isolation as before v5.133. Used as the control arm of the file-read deduplication A/B experiment. Default: workspace enabled (unset or 0).",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"XAI_API_KEY",description:"xAI API key for the xai provider (Grok models) in API-key mode. Metered; distinct from SuperGrok / SuperGrok Heavy / X Premium+ OAuth.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_XAI_BASE_URL",description:"Base URL for xAI API-key mode. Default https://api.x.ai/v1. The OpenAI SDK appends /chat/completions.",type:"string",required:!1,example:"https://api.x.ai/v1",category:"model"},{name:"AFK_XAI_OAUTH_BASE_URL",description:"Base URL for xAI SuperGrok / SuperGrok Heavy / X Premium+ OAuth inference. Default https://cli-chat-proxy.grok.com/v1 (subscription path). Some accounts work on https://api.x.ai/v1 with OAuth \u2014 override if needed. Distinct from AFK_XAI_BASE_URL (API-key mode).",type:"string",required:!1,example:"https://cli-chat-proxy.grok.com/v1",category:"model"},{name:"AFK_XAI_GROK_CLIENT_VERSION",description:"Override the semver sent as x-grok-client-version to the xAI OAuth CLI chat proxy. Use only if the proxy raises its required Grok CLI version before agent-afk is updated; invalid values fall back to the official Grok Build version file or built-in compatible default.",type:"string",required:!1,example:"1.0.6",category:"model"},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Use ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. Set to 1/true/yes/on to enable. READ-ONLY: AFK never refreshes these tokens \u2014 re-run codex when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex | xai | xai-oauth). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"TMUX",description:"OS-level tmux session identifier. Set automatically by tmux to the socket path and session info (e.g. /tmp/tmux-501/default,12345,0) inside any tmux pane. Not set by AFK. Read by configureColor() to detect a tmux environment; for truecolor support on Node \u2264 24, set FORCE_COLOR=3 in your shell or ~/.afk/config/afk.env.",type:"string",required:!1,example:"/tmp/tmux-501/default,12345,0",category:"process"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"APPDATA",description:"Windows %APPDATA% (Roaming). Used for VS Code/Cursor settings discovery and credential denylist paths.",type:"string",required:!1,category:"process"},{name:"LOCALAPPDATA",description:"Windows %LOCALAPPDATA%. Used for browser credential denylist paths (Chrome, Firefox, Edge, etc.).",type:"string",required:!1,category:"process"},{name:"USERPROFILE",description:"Windows %USERPROFILE%. Used for credential denylist paths (.ssh, .aws, .gnupg) on win32.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WEB_PORT",description:"Port for the `afk web` browser surface. Defaults to 4141; falls back to an ephemeral port when taken. Overridden by --port.",type:"number",required:!1,example:"4141",category:"daemon"},{name:"AFK_WEB_HOST",description:"Bind address for the `afk web` browser surface. Defaults to 127.0.0.1. Unlike the daemon control surface, a non-loopback bind is REFUSED unless AFK_WEB_TOKEN (or --token) is also set, because this surface can submit prompts and approve tool use. Overridden by --host.",type:"string",required:!1,example:"127.0.0.1",category:"daemon"},{name:"AFK_WEB_TOKEN",description:"Bearer token for the `afk web` surface. When unset, a random per-run token is minted and printed in the startup URL. Setting this explicitly is also what permits a non-loopback bind.",type:"string",required:!1,category:"daemon",secret:!0},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BASH_PREVIEW_HEAD_LINES",description:"Number of leading non-empty lines shown in the bash output head block of the TUI outcome preview. 0 (default) disables the head block entirely. Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_TAIL_LINES).",type:"number",required:!1,default:"0",example:"3",category:"misc"},{name:"AFK_BASH_PREVIEW_TAIL_LINES",description:"Number of trailing non-empty lines shown in the bash output tail block of the TUI outcome preview. Default 7 (compact tail-first preview). Accepted range 0\u2013200; non-integer, negative, or out-of-range input falls back to the default. When head + tail >= total non-empty lines, all lines are shown without a hidden-line notice. Keep preview preferences separate from model-context caps (AFK_BASH_PREVIEW_HEAD_LINES).",type:"number",required:!1,default:"7",example:"10",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_TURN_SEPARATOR",description:"Render a dim horizontal rule between conversation turns in the REPL. 0 = off, unset/1 = on (default). TTY-only: piped/one-shot output (afk chat) never emits the rule.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",category:"misc"},{name:"AFK_PROSE_MEASURE",description:"Maximum line length (columns) for prose-only blocks (paragraphs, list items, blockquotes) in the interactive REPL. Code fences use the wider AFK_TEXT_MEASURE (default 100). When AFK_TEXT_MEASURE is explicitly set, it overrides this value for backward compatibility. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable. Unparseable or below-minimum values fall back to the default.",type:"string",required:!1,default:"80",example:"72",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",category:"debug"},{name:"AFK_SESSION_RETENTION_DISABLE",description:"Disable the session sidecar retention sweep entirely, so no state/sessions/*.json file is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_MAX_AGE_DAYS",description:"Evict a session sidecar file once it is older than this many days (based on savedAt). Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_SESSION_MAX_COUNT",description:"Count-based safety valve: evict oldest session sidecars first once the total exceeds this number. Default 1000.",type:"number",required:!1,default:"1000",category:"debug"},{name:"AFK_WAVE_MANIFEST_DISABLED",description:"Disable the wave manifest system entirely. When set to 1, no manifest is written for parallel subagent waves, and no resumption offer is made at session start.",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{name:"AFK_WAVE_MANIFEST_TTL_HOURS",description:"Time-to-live for wave manifests in hours. Manifests older than this are deleted on reconciliation and by the witness sweep. Default 48 (two days).",type:"number",required:!1,default:"48",example:"24",category:"misc"},{name:"AFK_WAVE_RESUME_UNATTENDED",description:"When set to 1, surface wave resumption offers even on non-interactive surfaces (daemon, one-shot chat). By default, offers are only made on interactive surfaces (REPL, Telegram).",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_PROMPTS",description:"Opt-in: when set to 1, every prompt a parent session sends to a subagent is written as a redacted markdown file under state/witness/<label>/prompts/. Off by default because nothing prunes the witness tree and prompts may carry secrets the regex redactor cannot catch (connection strings, PEM blocks, PII).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_OUTPUT",description:"Capture subagent conversational OUTPUT (assistant text plus each tool call with its arguments) as a redacted markdown transcript under state/witness/<label>/outputs/. Flushed at every tool-call boundary, so a child killed by a timeout still leaves a usable partial record \u2014 the case where final-message capture yields nothing. Off by default. Set to 1 to enable. Note: best-effort regex redaction only \u2014 connection strings, PEM blocks, and PII are not caught.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SUBAGENT_RESULT_CAP_BYTES",description:"Foreground subagent result size cap in bytes. When a subagent's final message exceeds this threshold, the full output is spilled to a sidecar file (state/sessions/<id>/subagent-handoffs/<subagentId>.txt) and the parent receives a head+tail slice with a read_file pointer. Prevents large subagent outputs from bloating parent context. Set to 0 to disable the cap entirely. Default 32768 (32KB). Note: sidecar files contain unredacted subagent output (same caveats as AFK_CAPTURE_SUBAGENT_OUTPUT). No automatic GC covers subagent-handoffs/ today; retention is tied to session-directory cleanup.",type:"number",required:!1,default:"32768",example:"16384",category:"model"},{name:"AFK_SUBAGENT_LOG",description:"Opt-in per-subagent conversation log. Writes OutputEvent JSONL to state/subagent-logs/<sessionLabel>/<subagentId>.jsonl for both foreground and background subagents. Powers /tasks:view replay. OFF by default (raw tool arguments are written without redaction \u2014 consistent with AFK_CAPTURE_SUBAGENT_PROMPTS / AFK_CAPTURE_SUBAGENT_OUTPUT). Set to 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Browser provider backend: auto (default, prefer Agent Browser, fall back to Playwright), agent-browser (require Agent Browser), or playwright (headless only).",type:"string",required:!1,default:"auto",example:"agent-browser",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_RATE_LIMIT_ADMISSION_DISABLED",description:"Bypass the process-wide rate-limit admission gate (issue #941). Set to 1 to skip pre-request capacity checks. Default 0 (gate active). OAuth subscription accounts already pass through automatically when no per-minute headers are returned.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_RATE_LIMIT_STAGGER_MAX_MS",description:"Jitter ceiling (ms) for the rate-limit admission bucket: each waiter at a window boundary wakes at reset + random(0..ceiling) to avoid re-storming the API. Default 500. Set to 0 in tests for deterministic timing.",type:"number",required:!1,default:"500",example:"0",category:"model"},{name:"AFK_WEB_ALLOW_PRIVATE_HOSTS",description:"Opt out of the web_scrape SSRF egress guard. When unset (default) the guard is ACTIVE: the markdown, raw, and headless-render paths refuse loopback (127/8, ::1), link-local (169.254/16 \u2014 including the 169.254.169.254 cloud instance-metadata endpoint), RFC1918 (10/8, 172.16/12, 192.168/16), carrier-grade NAT (100.64/10), IPv6 unique-local (fc00::/7), 0.0.0.0/8, and the IPv4-mapped/compatible IPv6 forms of all of those. Hostnames are resolved and the RESOLVED addresses are classified (DNS-rebinding guard), and the check is re-applied on every redirect hop. Set to 1/true to allow private-host access \u2014 needed only to scrape a local dev server. Enabling it restores a model-reachable SSRF path (issue #575).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"},{name:"AFK_LEASE_TTL_MS",description:"Lease TTL in milliseconds for durable task execution (issue #1411). A leased task whose lease expires before it completes is recovered and re-enqueued (or dead-lettered if maxAttempts is exhausted). Default: 600000 (10 minutes).",type:"number",required:!1,example:"600000",category:"misc"}],mv={};for(let t of ni){let e=t.name;Object.defineProperty(mv,e,{get(){return process.env[e]},enumerable:!("secret"in t&&t.secret),configurable:!0})}k=mv});import{basename as QW,dirname as ZW,join as sr}from"path";function ri(t){if(!e1.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function go(){return sr(te(),"witness")}function it(t){return ri(t),sr(go(),t)}function xm(t){return sr(it(t),"inbound-attachments")}function Rm(t){return sr(it(t),"prompts")}function Im(t){return sr(it(t),"outputs")}function Cm(t){if(!(!t||t===""))return sr(it(t),"bash-captures")}function ir(t){return!t||t.startsWith("in-memory:")?null:QW(ZW(t))}function Uc(){return sr(te(),"receipts")}var e1,gv=h(()=>{"use strict";B();e1=/^[a-zA-Z0-9_-]+$/});import{existsSync as hv,mkdirSync as t1,renameSync as n1,cpSync as r1,rmSync as o1}from"fs";import{join as W,dirname as wv,isAbsolute as Pm}from"path";import{homedir as Mm}from"os";import{fileURLToPath as s1}from"url";function oe(){let t=k.AFK_HOME;if(t!==void 0&&t!==""){if(!Pm(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return W(Mm(),".afk")}function vt(){let t=k.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!Pm(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return W(oe(),"agent-framework")}function Bc(){return W(vt(),"forge-telemetry.jsonl")}function Sv(){return W(vt(),"briefs")}function kv(){return W(vt(),"facets")}function jc(){return W(oe(),"skills")}function Lt(){return W(oe(),"plugins")}function vv(t=process.cwd()){return W(t,".afk")}function Tv(t=process.cwd()){return W(vv(t),"skills")}function Ev(t=process.cwd()){return W(vv(t),"plugins")}function _v(t=process.cwd()){return W(t,".afk","plans")}function Hc(){return W(Lt(),".index.json")}function Om(){return W(rn(),"schedules.json")}function Av(){let t=s1(import.meta.url),e=wv(t);return W(e,"bundled-plugins")}function rn(){return W(oe(),"config")}function te(){let t=k.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Pm(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return W(oe(),"state")}function ce(){return W(te(),"sessions")}function Wc(){return W(te(),"presence")}function Kc(){return W(te(),"memory")}function ho(){return W(te(),"kv","kv.db")}function yo(){return W(te(),"handoffs")}function qc(){return W(te(),"session-grants.jsonl")}function oi(){return W(rn(),"permissions.json")}function xv(){return W(oe(),"farms")}function Rv(t){return W(xv(),t)}function Iv(t="default"){return W(te(),"daemon",`agent-afk@${t}`)}function Cv(){return W(te(),"worktree-sweep.lock")}function Gc(){return W(te(),"worktree-roots.json")}function ar(){return W(rn(),"afk.env")}function on(){return W(rn(),"afk.config.json")}function Dm(){return W(rn(),"settings.json")}function Pv(t=process.cwd()){return W(t,".afk","settings.json")}function Mv(){return W(oe(),"AFK.md")}function Ov(t=process.cwd()){return W(t,"AFK.md")}function Dv(){return W(Mm(),".afk.env")}function Xc(){return W(Mm(),".afk.config.json")}function i1(){return W(oe(),"sessions")}function a1(t,e){if(t!==e&&hv(t)&&!hv(e))try{t1(wv(e),{recursive:!0});try{n1(t,e)}catch(n){if(n.code==="EXDEV")try{r1(t,e,{recursive:!0}),o1(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
|
|
3
|
-
`)}}}catch{}}function Fv(){a1(i1(),ce())}function cr(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(t.length>yv)throw new Error(`Invalid jobId: exceeds ${yv} chars`);if(!c1.test(t))throw new Error(`Invalid jobId: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function zc(){return W(te(),"bg")}function bo(t){return cr(t),W(zc(),t)}function Lv(t){return W(bo(t),"events.jsonl")}function Nv(t){return W(bo(t),"meta.json")}function Fm(){return W(te(),"subagent-logs")}function Lm(t){return cr(t),W(Fm(),t)}function $v(t,e){return cr(e),W(Lm(t),`${e}.jsonl`)}function Nm(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>bv)throw new Error(`Invalid browser profile: exceeds ${bv} chars`);if(!l1.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function d1(){return W(te(),"browser")}function u1(t){return Nm(t),W(d1(),t)}function $m(t){return W(u1(t),"storageState.json")}function lr(t){return typeof t=="string"&&t.length>0&&t.length<=f1&&p1.test(t)}function wo(t){if(!lr(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return W(ce(),t)}function So(t){return W(wo(t),"events.jsonl")}function Uv(t){return W(wo(t),"session.key")}function Jc(){return W(te(),"mcp","server-status.json")}function ko(){return W(te(),"waves")}function vo(t){return W(ko(),`${t}.json`)}function Bv(){return W(te(),"effect-ledger.jsonl")}var c1,yv,l1,bv,p1,f1,B=h(()=>{"use strict";F();gv();c1=/^[A-Za-z0-9_-]+$/,yv=128;l1=/^[A-Za-z0-9_-]+$/,bv=128;p1=/^[A-Za-z0-9_-]+$/,f1=128});function m1(){return k.AFK_DEBUG==="1"||k.DEBUG==="1"}function
|
|
4
|
-
`)){let i=s.trim();if(i==="")continue;let a;try{a=JSON.parse(i)}catch{r?.(i);continue}if(n!==void 0){if(!n(a))continue;o.push(a)}else o.push(a)}return o}var Vc=h(()=>{"use strict"});import g1 from"better-sqlite3";import{existsSync as si,mkdirSync as jv,readFileSync as Yc,writeFileSync as Hv,readdirSync as h1,appendFileSync as y1,unlinkSync as Wv,copyFileSync as b1,renameSync as w1}from"fs";import{join as at,basename as Kv,resolve as Qc,relative as S1}from"path";function Yv(t){return Math.ceil(t.length/3.5)}function x1(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Xv(t){if(!t||t.length>100||!R1.test(t))throw new Error(`Invalid procedure name "${t}": must be 1-100 chars, alphanumeric/hyphens/underscores only`);return t}function P1(t){if(!t||typeof t!="object")return!1;let e=t;if(typeof e.type!="string"||!I1.has(e.type)||typeof e.timestamp!="string"||!e.data||typeof e.data!="object")return!1;if(e.type==="fact"){let n=e.data;if(typeof n.category!="string"||!C1.has(n.category))return!1}return!0}function zv(t,e){let n=S1(e,t);if(n.startsWith("..")||n.startsWith("/"))throw new Error("Path traversal detected")}function Jv(t,e){let n=e.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!n)return{name:Kv(t,".md"),content:e,created:"",source_session:null,access_count:0};let r=n[1]??"",o=n[2]??"",s=l=>l.match(/^name:\s*(.+)$/m)?.[1]?.trim()??Kv(t,".md"),i=l=>l.match(/^created:\s*(.+)$/m)?.[1]?.trim()??"",a=l=>l.match(/^source_session:\s*(.+)$/m)?.[1]?.trim()??null,c=l=>{let d=l.match(/^access_count:\s*(\d+)$/m);return d?parseInt(d[1],10):0};return{name:s(r),content:o.trim(),created:i(r),source_session:a(r),access_count:c(r)}}var qv,k1,v1,Gv,Zc,T1,tl,E1,_1,Vv,Um,el,A1,Ze,R1,I1,C1,nl=h(()=>{"use strict";B();
|
|
3
|
+
`)}}}catch{}}function Fv(){a1(i1(),ce())}function cr(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(t.length>yv)throw new Error(`Invalid jobId: exceeds ${yv} chars`);if(!c1.test(t))throw new Error(`Invalid jobId: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function zc(){return W(te(),"bg")}function bo(t){return cr(t),W(zc(),t)}function Lv(t){return W(bo(t),"events.jsonl")}function Nv(t){return W(bo(t),"meta.json")}function Fm(){return W(te(),"subagent-logs")}function Lm(t){return cr(t),W(Fm(),t)}function $v(t,e){return cr(e),W(Lm(t),`${e}.jsonl`)}function Nm(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>bv)throw new Error(`Invalid browser profile: exceeds ${bv} chars`);if(!l1.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function d1(){return W(te(),"browser")}function u1(t){return Nm(t),W(d1(),t)}function $m(t){return W(u1(t),"storageState.json")}function lr(t){return typeof t=="string"&&t.length>0&&t.length<=f1&&p1.test(t)}function wo(t){if(!lr(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return W(ce(),t)}function So(t){return W(wo(t),"events.jsonl")}function Uv(t){return W(wo(t),"session.key")}function Jc(){return W(te(),"mcp","server-status.json")}function ko(){return W(te(),"waves")}function vo(t){return W(ko(),`${t}.json`)}function Bv(){return W(te(),"effect-ledger.jsonl")}var c1,yv,l1,bv,p1,f1,B=h(()=>{"use strict";F();gv();c1=/^[A-Za-z0-9_-]+$/,yv=128;l1=/^[A-Za-z0-9_-]+$/,bv=128;p1=/^[A-Za-z0-9_-]+$/,f1=128});function m1(){return k.AFK_DEBUG==="1"||k.DEBUG==="1"}function O(...t){m1()&&console.log(...t)}var se=h(()=>{"use strict";F()});function dr(t,e={}){let{guard:n,onParseError:r}=e,o=[];for(let s of t.split(`
|
|
4
|
+
`)){let i=s.trim();if(i==="")continue;let a;try{a=JSON.parse(i)}catch{r?.(i);continue}if(n!==void 0){if(!n(a))continue;o.push(a)}else o.push(a)}return o}var Vc=h(()=>{"use strict"});import g1 from"better-sqlite3";import{existsSync as si,mkdirSync as jv,readFileSync as Yc,writeFileSync as Hv,readdirSync as h1,appendFileSync as y1,unlinkSync as Wv,copyFileSync as b1,renameSync as w1}from"fs";import{join as at,basename as Kv,resolve as Qc,relative as S1}from"path";function Yv(t){return Math.ceil(t.length/3.5)}function x1(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Xv(t){if(!t||t.length>100||!R1.test(t))throw new Error(`Invalid procedure name "${t}": must be 1-100 chars, alphanumeric/hyphens/underscores only`);return t}function P1(t){if(!t||typeof t!="object")return!1;let e=t;if(typeof e.type!="string"||!I1.has(e.type)||typeof e.timestamp!="string"||!e.data||typeof e.data!="object")return!1;if(e.type==="fact"){let n=e.data;if(typeof n.category!="string"||!C1.has(n.category))return!1}return!0}function zv(t,e){let n=S1(e,t);if(n.startsWith("..")||n.startsWith("/"))throw new Error("Path traversal detected")}function Jv(t,e){let n=e.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!n)return{name:Kv(t,".md"),content:e,created:"",source_session:null,access_count:0};let r=n[1]??"",o=n[2]??"",s=l=>l.match(/^name:\s*(.+)$/m)?.[1]?.trim()??Kv(t,".md"),i=l=>l.match(/^created:\s*(.+)$/m)?.[1]?.trim()??"",a=l=>l.match(/^source_session:\s*(.+)$/m)?.[1]?.trim()??null,c=l=>{let d=l.match(/^access_count:\s*(\d+)$/m);return d?parseInt(d[1],10):0};return{name:s(r),content:o.trim(),created:i(r),source_session:a(r),access_count:c(r)}}var qv,k1,v1,Gv,Zc,T1,tl,E1,_1,Vv,Um,el,A1,Ze,R1,I1,C1,nl=h(()=>{"use strict";B();se();Vc();qv="HOT.md",k1="HOT.md.bak",v1="memory.db",Gv="memory-wal.jsonl",Zc="procedures",T1="HOT.md.tmp",tl=5250,E1=Math.ceil(tl/3.5),_1=600,Vv=.8,Um='<!-- HOT TRUNCATED to fit the ~1,500-token cap; move durable detail to the fact archive (memory_update target:"fact"). -->',el=4,A1=`
|
|
5
5
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
6
6
|
session_id TEXT PRIMARY KEY,
|
|
7
7
|
surface TEXT NOT NULL,
|
|
@@ -78,7 +78,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_facts_fingerprint
|
|
|
78
78
|
`),this.db.exec("INSERT INTO facts_fts(facts_fts) VALUES('rebuild');"),this.db.exec(`
|
|
79
79
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_facts_fingerprint
|
|
80
80
|
ON facts(content, created_at, COALESCE(session_id, ''), category);
|
|
81
|
-
`),this.db.pragma("user_version = 2")})(),
|
|
81
|
+
`),this.db.pragma("user_version = 2")})(),O("memory-store: migrated schema v1 \u2192 v2 (added fingerprint UNIQUE index)")),n<3&&(this.db.transaction(()=>{this.db.pragma("table_info(sessions)").some(o=>o.name==="actor")||this.db.exec("ALTER TABLE sessions ADD COLUMN actor TEXT;"),this.db.pragma("user_version = 3")})(),O("memory-store: migrated schema v2 \u2192 v3 (added sessions.actor column)")),n<4&&(this.db.transaction(()=>{this.db.pragma("table_info(facts)").some(o=>o.name==="evidence")||this.db.exec("ALTER TABLE facts ADD COLUMN evidence TEXT;"),this.db.pragma("user_version = 4")})(),O("memory-store: migrated schema v3 \u2192 v4 (added facts.evidence column)"));else throw this.db.close(),new Error(`memory.db schema version ${n} is newer than this build supports (${el}). Upgrade agent-afk to a version that understands schema v${n}.`);this.replayWAL()}enableWalMode(){for(let r=1;;r++)try{if(this.db.pragma("journal_mode",{simple:!0})==="wal")return;this.db.pragma("journal_mode = WAL");return}catch(o){if(!(o?.code==="SQLITE_BUSY")||r>=50)throw o;x1(20)}}loadHot(){let e=at(this.dir,qv);if(!si(e))return null;try{return Yc(e,"utf-8")}catch{return null}}saveHot(e){let n=at(this.dir,qv),r=e,o=!1;if(e.length>tl){o=!0;let i=tl-Um.length-2,a=e.slice(0,i),c=a.lastIndexOf(`
|
|
82
82
|
`);c>=_1&&(a=a.slice(0,c)),r=`${a.replace(/\s+$/,"")}
|
|
83
83
|
${Um}
|
|
84
84
|
`}si(n)&&b1(n,at(this.dir,k1));let s=at(this.dir,T1);return Hv(s,r,"utf-8"),w1(s,n),this.computeHotUsage(r,o)}hotUsage(){let e=this.loadHot()??"";return this.computeHotUsage(e,e.includes(Um))}computeHotUsage(e,n){let r=e.length;return{chars:r,tokens:Yv(e),maxTokens:E1,pct:Math.min(100,Math.round(r/tl*100)),truncated:n}}storeFact(e){let n=new Date().toISOString();this.appendWAL({type:"fact",timestamp:n,data:{...e,created_at:n}});let o=this.db.prepare(`
|
|
@@ -107,7 +107,7 @@ ${Um}
|
|
|
107
107
|
SET ended_at = ?, summary = ?, outcome = ?, token_count = ?, cost_usd = ?
|
|
108
108
|
WHERE session_id = ?
|
|
109
109
|
`).run(i,n,r,o??null,s??null,e)}getSession(e){return this.db.prepare("SELECT * FROM sessions WHERE session_id = ?").get(e)??null}recentSessions(e=5){return this.db.prepare("SELECT * FROM sessions ORDER BY started_at DESC LIMIT ?").all(e)}writeProcedure(e,n,r){let o=Xv(e),s=Qc(at(this.dir,Zc)),i=Qc(s,`${o}.md`);zv(i,s);let a=["---",`name: ${o}`,`created: ${new Date().toISOString()}`,`source_session: ${r??"unknown"}`,"access_count: 0","---",""].join(`
|
|
110
|
-
`);Hv(i,a+n,"utf-8")}loadProcedure(e){let n=Xv(e),r=Qc(at(this.dir,Zc)),o=Qc(r,`${n}.md`);if(zv(o,r),!si(o))return null;try{return Jv(o,Yc(o,"utf-8"))}catch{return null}}searchProcedures(e){let n=at(this.dir,Zc);if(!si(n))return[];let r=e.toLowerCase().split(/\s+/),o=[];for(let s of h1(n)){if(!s.endsWith(".md"))continue;let i=Yc(at(n,s),"utf-8"),a=i.toLowerCase();if(r.some(c=>a.includes(c))){let c=Jv(s,i);c&&o.push(c)}}return o}search(e,n){let r=[];try{let s=this.searchFacts(e,n);for(let i of s)r.push({type:"fact",content:i.content,category:i.category,created_at:i.created_at,source_session:i.session_id,confidence:i.confidence,evidence:i.evidence??null})}catch{}if(!n?.category){let s=this.searchProcedures(e);for(let i of s)r.push({type:"procedure",content:i.content,created_at:i.created,source_session:i.source_session,confidence:1})}let o=n?.limit??10;return r.slice(0,o)}replayWAL(){let e=at(this.dir,Gv);if(!si(e))return 0;let n=0;try{let r=Yc(e,"utf-8").trim();if(!r)return Wv(e),0;for(let o of dr(r,{onParseError:s=>
|
|
110
|
+
`);Hv(i,a+n,"utf-8")}loadProcedure(e){let n=Xv(e),r=Qc(at(this.dir,Zc)),o=Qc(r,`${n}.md`);if(zv(o,r),!si(o))return null;try{return Jv(o,Yc(o,"utf-8"))}catch{return null}}searchProcedures(e){let n=at(this.dir,Zc);if(!si(n))return[];let r=e.toLowerCase().split(/\s+/),o=[];for(let s of h1(n)){if(!s.endsWith(".md"))continue;let i=Yc(at(n,s),"utf-8"),a=i.toLowerCase();if(r.some(c=>a.includes(c))){let c=Jv(s,i);c&&o.push(c)}}return o}search(e,n){let r=[];try{let s=this.searchFacts(e,n);for(let i of s)r.push({type:"fact",content:i.content,category:i.category,created_at:i.created_at,source_session:i.session_id,confidence:i.confidence,evidence:i.evidence??null})}catch{}if(!n?.category){let s=this.searchProcedures(e);for(let i of s)r.push({type:"procedure",content:i.content,created_at:i.created,source_session:i.source_session,confidence:1})}let o=n?.limit??10;return r.slice(0,o)}replayWAL(){let e=at(this.dir,Gv);if(!si(e))return 0;let n=0;try{let r=Yc(e,"utf-8").trim();if(!r)return Wv(e),0;for(let o of dr(r,{onParseError:s=>O("WAL replay: skipping malformed line:",s.slice(0,200))})){if(!P1(o)){O("WAL replay: skipping invalid entry:",JSON.stringify(o).slice(0,200));continue}let s=o;try{if(s.type==="session_start"){let i=s.data;this.db.prepare(`
|
|
111
111
|
INSERT OR IGNORE INTO sessions (session_id, surface, started_at, actor)
|
|
112
112
|
VALUES (?, ?, ?, ?)
|
|
113
113
|
`).run(i.session_id,i.surface,i.started_at,i.actor??null),n++}else if(s.type==="session_end"){let i=s.data;this.db.prepare(`
|
|
@@ -116,8 +116,8 @@ ${Um}
|
|
|
116
116
|
`).run(i.ended_at,i.summary,i.outcome,i.session_id),n++}else if(s.type==="fact"){let i=s.data;this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ? AND COALESCE(session_id,'') = ? AND category = ?").get(i.content,i.created_at,i.session_id??"",i.category??"")||(this.db.prepare(`
|
|
117
117
|
INSERT INTO facts (session_id, created_at, category, content, source_surface, evidence)
|
|
118
118
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
119
|
-
`).run(i.session_id??null,i.created_at,i.category,i.content,i.source_surface??"cli",i.evidence??null),n++)}else if(s.type==="supersede"){let i=s.data,a,c;if(typeof i.old_content=="string"&&typeof i.old_created_at=="string"){let l;(typeof i.old_session_id<"u"||typeof i.old_category=="string")&&(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ? AND COALESCE(session_id,'') = ? AND category = ?").get(i.old_content,i.old_created_at,i.old_session_id??"",i.old_category??"")),l||(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ?").get(i.old_content,i.old_created_at)),a=l?.id}else typeof i.old_fact_id=="number"&&(a=i.old_fact_id);if(typeof i.new_content=="string"&&typeof i.new_created_at=="string"){let l;(typeof i.new_session_id<"u"||typeof i.new_category=="string")&&(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ? AND COALESCE(session_id,'') = ? AND category = ?").get(i.new_content,i.new_created_at,i.new_session_id??"",i.new_category??"")),l||(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ?").get(i.new_content,i.new_created_at)),c=l?.id}else typeof i.new_fact_id=="number"&&(c=i.new_fact_id);typeof a=="number"&&typeof c=="number"&&(this.db.prepare("UPDATE facts SET superseded_by = ? WHERE id = ? AND superseded_by IS NULL").run(c,a),n++)}}catch(i){
|
|
120
|
-
`,"utf-8")}catch(r){
|
|
119
|
+
`).run(i.session_id??null,i.created_at,i.category,i.content,i.source_surface??"cli",i.evidence??null),n++)}else if(s.type==="supersede"){let i=s.data,a,c;if(typeof i.old_content=="string"&&typeof i.old_created_at=="string"){let l;(typeof i.old_session_id<"u"||typeof i.old_category=="string")&&(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ? AND COALESCE(session_id,'') = ? AND category = ?").get(i.old_content,i.old_created_at,i.old_session_id??"",i.old_category??"")),l||(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ?").get(i.old_content,i.old_created_at)),a=l?.id}else typeof i.old_fact_id=="number"&&(a=i.old_fact_id);if(typeof i.new_content=="string"&&typeof i.new_created_at=="string"){let l;(typeof i.new_session_id<"u"||typeof i.new_category=="string")&&(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ? AND COALESCE(session_id,'') = ? AND category = ?").get(i.new_content,i.new_created_at,i.new_session_id??"",i.new_category??"")),l||(l=this.db.prepare("SELECT id FROM facts WHERE content = ? AND created_at = ?").get(i.new_content,i.new_created_at)),c=l?.id}else typeof i.new_fact_id=="number"&&(c=i.new_fact_id);typeof a=="number"&&typeof c=="number"&&(this.db.prepare("UPDATE facts SET superseded_by = ? WHERE id = ? AND superseded_by IS NULL").run(c,a),n++)}}catch(i){O("WAL replay: skipping malformed line:",String(i))}}Wv(e)}catch(r){O("WAL file unreadable, skipping recovery:",String(r))}return n}close(){this.db.close()}appendWAL(e){let n=at(this.dir,Gv);try{y1(n,JSON.stringify(e)+`
|
|
120
|
+
`,"utf-8")}catch(r){O("WAL append failed (non-fatal):",String(r))}}};R1=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;I1=new Set(["fact","session_start","session_end","supersede"]),C1=new Set(["preference","convention","decision","learning"])});import{existsSync as M1,readFileSync as O1}from"fs";import{join as D1}from"path";function Qv(){let t=D1(Kc(),"HOT.md");if(!M1(t))return null;try{let e=O1(t,"utf-8");return e.trim().length>0?e:null}catch{return null}}function Bm(t){let e=Qv();if(!e)return t;let r=`<cross-session-memory>
|
|
121
121
|
${e.replace(/<\/?cross-session-memory\b[^>]*>/gi,"")}
|
|
122
122
|
</cross-session-memory>`;return{...t,hotMemory:r}}var Zv=h(()=>{"use strict";B()});function wn(t){switch(t){case"cli":case"repl":return"cli";case"telegram":return"telegram";case"daemon":return"daemon";case"web":return"web";case"subagent":case"unknown":case void 0:return"unknown"}}function rl(t){return t==null?"main":"subagent"}function Sn(t){return(t??0)>0?"subagent":"main"}var ur=h(()=>{"use strict"});function jm(t,e="cli"){return n=>{if(n.event!=="SessionEnd")return{};if(n.parentSessionId)return{};try{let r=n.sessionId;r&&(t.startSession({session_id:r,surface:e,actor:rl(n.parentSessionId)}),t.endSession(r,n.reason??"session ended","completed"))}catch{}return{}}}var eT=h(()=>{"use strict";ur()});function nT(t){return F1.has(t)}function ol(){let t=k.AFK_MEMORY_EVIDENCE_GATE;return t?!Am(t):!0}function Hm(t){return nT(t)}function sl(t){if(typeof t!="string")return null;let e=t.trim();return e.length>0?e:null}function rT(t,e){return nT(t)?sl(e)?"verified":"unverified":"not-applicable"}function oT(t,e){return e!=="unverified"||t.startsWith(tT)?t:`${tT} ${t}`}var F1,tT,sT=h(()=>{"use strict";F();F1=new Set(["convention"]),tT="[unverified]"});function N1(t,e){return e?t.map(n=>{if(n.type!=="fact"||!n.category)return{...n,verification:"not-applicable"};let r=rT(n.category,n.evidence);return{...n,verification:r,content:oT(n.content,r)}}):t.map(n=>{let r={...n};return delete r.evidence,delete r.verification,r})}function ii(t,e,n){let r=async i=>{try{let a=$1(i),c=t.search(a.query,{category:a.category,since:a.since,limit:a.limit??10});return{content:JSON.stringify(N1(c,ol()))}}catch(a){return{content:`memory_search error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},o=async i=>{try{let a=U1(i);if(a.target==="hot"){if(a.action!=="set")return{content:'Hot memory only supports action: "set". Use supersede/remove only for facts.',isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let c=t.saveHot(a.content),l={saved:!0,target:"hot",usage:{tokens:c.tokens,maxTokens:c.maxTokens,pct:c.pct}};return c.truncated?(l.truncated=!0,l.note='Hot memory exceeded the ~1,500-token cap and was truncated from the end (lowest-priority lines dropped; a sentinel marks the cut). Keep hot memory to a few durable essentials \u2014 move detail to the fact archive with target:"fact".'):c.pct>=Vv*100&&(l.warning=`Hot memory is at ${c.pct}% of the ~1,500-token cap. Move non-essential lines to the fact archive (target:"fact") before it truncates.`),{content:JSON.stringify(l)}}if(a.action==="set"){if(!a.category)return{content:"category is required for fact storage",isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let c=a.category,l=sl(a.evidence),u={id:t.storeFact({session_id:e,category:c,content:a.content,source_surface:n??"cli",evidence:l}),action:"set",target:"fact"};return ol()&&Hm(c)&&!l&&(u.warning=iT),{content:JSON.stringify(u)}}if(a.action==="supersede"){if(!a.supersedes)return{content:'supersedes (fact ID) is required for action: "supersede"',isError:!0};if(!a.content)return{content:'content is required for action: "supersede"',isError:!0};let c=t.getFact(a.supersedes),l=a.evidence===void 0?void 0:sl(a.evidence),u={id:t.supersedeFact(a.supersedes,a.content,a.category??void 0,l),action:"supersede",target:"fact",supersedes:a.supersedes};if(ol()){let p=a.category??c?.category;p&&Hm(p)&&((l===void 0?c?.evidence??null:l)?l===void 0&&(u.warning=L1):u.warning=iT)}return{content:JSON.stringify(u)}}if(a.action==="remove"){if(!a.id)return{content:'id (fact ID) is required for action: "remove"',isError:!0};let c=t.removeFact(a.id);return{content:JSON.stringify({removed:c,action:"remove",target:"fact"})}}return{content:`Unknown action: ${a.action}`,isError:!0}}catch(a){return{content:`memory_update error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},s=async i=>{try{let a=B1(i);return t.writeProcedure(a.name,a.content,e),{content:JSON.stringify({name:a.name,written:!0})}}catch(a){return{content:`procedure_write error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}};return new Map([["memory_search",r],["memory_update",o],["procedure_write",s]])}function $1(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.query!="string")throw new Error("query (string) is required");let n={query:e.query};if(e.category!==void 0){if(typeof e.category!="string")throw new Error("category must be a string");let r=["preference","convention","decision","learning"];if(!r.includes(e.category))throw new Error(`category must be one of: ${r.join(", ")}`);n.category=e.category}if(e.since!==void 0){if(typeof e.since!="string")throw new Error("since must be a string (ISO date)");n.since=e.since}if(e.limit!==void 0){if(typeof e.limit!="number"||e.limit<=0)throw new Error("limit must be a positive number");n.limit=e.limit}return n}function U1(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t,n=["hot","fact"];if(typeof e.target!="string"||!n.includes(e.target))throw new Error(`target must be one of: ${n.join(", ")}`);let r=["set","supersede","remove"];if(typeof e.action!="string"||!r.includes(e.action))throw new Error(`action must be one of: ${r.join(", ")}`);let o={target:e.target,action:e.action};if(e.content!==void 0){if(typeof e.content!="string")throw new Error("content must be a string");o.content=e.content}if(e.category!==void 0){if(typeof e.category!="string")throw new Error("category must be a string");let s=["preference","convention","decision","learning"];if(!s.includes(e.category))throw new Error(`category must be one of: ${s.join(", ")}`);o.category=e.category}if(e.evidence!==void 0){if(typeof e.evidence!="string")throw new Error("evidence must be a string");o.evidence=e.evidence}if(e.supersedes!==void 0){if(typeof e.supersedes!="number"||e.supersedes<=0)throw new Error("supersedes must be a positive fact ID");o.supersedes=e.supersedes}if(e.id!==void 0){if(typeof e.id!="number"||e.id<=0)throw new Error("id must be a positive fact ID");o.id=e.id}return o}function B1(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.name!="string")throw new Error("name (string) is required");if(typeof e.content!="string")throw new Error("content (string) is required");return{name:e.name,content:e.content}}var To,aT,cT,kn,il,iT,L1,Wm=h(()=>{"use strict";nl();sT();To={name:"memory_search",category:"read",concurrencySafe:!0,description:'Search cross-session memory for facts and procedures. Returns results ranked by relevance. Use this to recall information from prior sessions. Supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*',input_schema:{type:"object",properties:{query:{type:"string",description:'Search query (supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*)'},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Optional: filter by fact category"},since:{type:"string",description:"Optional: ISO date \u2014 only return facts created after this date"},limit:{type:"number",description:"Max results (default 10)"}},required:["query"]}},aT={name:"memory_update",category:"write",concurrencySafe:!1,description:'Store a fact in cross-session memory or update hot memory. Hot memory (target: "hot") persists in the system prompt across all future sessions. Facts (target: "fact") are stored in the searchable archive.',input_schema:{type:"object",properties:{target:{type:"string",enum:["hot","fact"],description:'"hot" writes to HOT.md (system prompt), "fact" writes to the searchable archive'},action:{type:"string",enum:["set","supersede","remove"],description:"Operation: set (create/overwrite), supersede (replace while keeping history), remove (delete)"},content:{type:"string",description:"The content to store (for set/supersede)"},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Required for fact target"},evidence:{type:"string",description:'Optional provenance citation backing a codebase fact \u2014 a file:line, commit SHA, or trace-event id. When the evidence gate is enabled, a "convention" fact stored without it is recalled as [unverified]; preferences and reflections never need it.'},supersedes:{type:"number",description:"Fact ID being superseded (for supersede action)"},id:{type:"number",description:"Fact ID to remove (for remove action)"}},required:["target","action"]}},cT={name:"procedure_write",category:"write",concurrencySafe:!1,description:"Write a reusable procedure to memory. Procedures are markdown files describing how to perform recurring tasks. They persist across sessions and are searchable via memory_search.",input_schema:{type:"object",properties:{name:{type:"string",description:"Procedure name (kebab-case, becomes the filename)"},content:{type:"string",description:"Procedure content (markdown)"}},required:["name","content"]}},kn=[To,aT,cT],il=kn.map(t=>t.name),iT='Stored without evidence \u2014 this codebase fact (category "convention") will be recalled as [unverified]. Supply `evidence` (a file:line, commit SHA, or trace-event id) so future sessions can trust it as ground truth rather than an unverified agent claim.',L1='Superseded without fresh evidence \u2014 the prior citation is carried forward and this codebase fact (category "convention") is still recalled as verified against the OLD evidence, which may not back the changed content. Re-supply `evidence` if the claim changed (or pass an empty string to clear it and recall as [unverified]).'});var Nt=h(()=>{"use strict";nl();Zv();eT();Wm()});import{existsSync as K1}from"node:fs";function Jm(t){let e=t.indexOf(zm);if(e===-1)return;let n=t.slice(e+zm.length),r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);if(o.length!==0)return t.slice(0,e+zm.length)+o}function fT(t){return t===void 0||K1(t)?"ok":"missing"}var zm,Vm=h(()=>{"use strict";zm="/.afk-worktrees/"});function qe(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>Ym(e)||q1(e)?e:"[REDACTED]")}function Ym(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function q1(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var vn=h(()=>{"use strict"});import{createHash as G1,randomUUID as X1}from"node:crypto";import{mkdirSync as z1,readFileSync as J1,writeFileSync as V1,renameSync as Y1}from"node:fs";import{join as Q1,dirname as Z1}from"node:path";function rK(t){let e=G1("sha256").update(t,"utf8").digest("hex"),n=qe(t.slice(0,tK)),r=Buffer.byteLength(t,"utf8");return{sha256:e,head:n,byteLen:r}}function oK(){let t=k.AFK_WAVE_MANIFEST_TTL_HOURS;if(t!==void 0&&t!==""){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>0)return e}return eK}function ll(t){let e=t.cwd!==void 0?Jm(t.cwd):void 0;return{id:t.id,status:"pending",promptDigest:rK(t.prompt),cwd:t.cwd,model:t.model,startedAt:void 0,settledAt:void 0,errorMessage:void 0,upstreamIds:t.upstreamIds??[],worktreePath:e}}function dl(t){if(k.AFK_WAVE_MANIFEST_DISABLED!=="1")try{let e=X1().replace(/-/g,""),n=new Date,r=new Date(n.getTime()+oK()*60*60*1e3),o={version:1,waveId:e,parentSessionId:t.parentSessionId,traceLabel:t.traceLabel,createdAt:n.toISOString(),updatedAt:n.toISOString(),expiresAt:r.toISOString(),source:t.source,units:t.units};return ul(o),e}catch{return}}function ul(t){try{let e=ko();z1(e,{recursive:!0});let n=vo(t.waveId),r=Q1(Z1(n),`.${t.waveId}.tmp`);V1(r,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),Y1(r,n)}catch{}}function pl(t){try{let e=J1(vo(t),"utf8"),n=JSON.parse(e);return typeof n!="object"||n===null||n.version!==1?void 0:n}catch{return}}function pr(t,e,n,r){try{let o=pl(t);if(o===void 0)return;let s=new Date().toISOString(),i=o.units.find(a=>a.id===e);if(i===void 0)return;i.status=n,n==="running"&&(i.startedAt=s),(n==="done"||n==="failed"||n==="skipped")&&(i.settledAt=s),r?.errorMessage!==void 0&&(i.errorMessage=r.errorMessage.slice(0,nK)),r?.cwd!==void 0&&(i.cwd=r.cwd,i.worktreePath=Jm(r.cwd)),o.updatedAt=s,ul(o)}catch{}}var eK,tK,nK,fl=h(()=>{"use strict";F();B();Vm();vn();eK=48,tK=512,nK=500});function Q(t){return t.replace(mT,"").replace(sK," ").trim()}function ve(t){return t.replace(mT,"")}var mT,sK,et=h(()=>{"use strict";mT=/\x1B\][^\x07\x1B\x9C]*(?:\x07|\x1B\\|\x9C)|\x1B[P^_X][^\x1B\x9C]*(?:\x1B\\|\x9C)|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[6-_]/g,sK=/[\x00-\x1F\x7F-\x9F]/g});import{readdirSync as gT,unlinkSync as hT}from"node:fs";function yT(t){let e={offers:[],deletedExpired:0};try{let n=ko(),r;try{r=gT(n)}catch{return e}let o=Date.now();for(let s of r){if(!s.endsWith(".json"))continue;let i=s.slice(0,-5);if(!/^[A-Za-z0-9]+$/.test(i))continue;let a=pl(i);if(a===void 0)continue;let c=new Date(a.expiresAt).getTime();if(!Number.isFinite(c)||c<o){try{hT(vo(i)),e.deletedExpired+=1}catch{}continue}if(a.offeredAt!==void 0)continue;let l=new Date(a.createdAt).getTime(),d=Number.isFinite(l)?l:0,u=o-d<aK,p=a.parentSessionId===t.sessionId;if(!u&&!p)continue;let f=a.units.filter(b=>iK.has(b.status));if(f.length===0)continue;let m=new Set(a.units.filter(b=>b.status==="done").map(b=>b.id)),g=[],y=[];for(let b of f){if(b.upstreamIds.length>0&&b.upstreamIds.some(_=>!m.has(_))){g.push(b);continue}let v=fT(b.worktreePath);y.push({unit:b,worktreeStatus:v})}(y.length>0||g.length>0)&&e.offers.push({manifest:a,resumable:y,blocked:g})}}catch{}return e}function bT(t){let{manifest:e,resumable:n,blocked:r}=t,o=new Date(e.createdAt),s=Date.now()-o.getTime(),i=cK(s),a=[`[wave-resume] Wave ${e.waveId} from ${i} ago has ${n.length+r.length} unsettled unit(s).`,` Source: ${e.source}`];if(n.length>0){a.push(" Units ready to resume:");for(let{unit:c,worktreeStatus:l}of n){let d=ve(c.promptDigest.head.slice(0,80)).replace(/\n/g," "),u=c.cwd!==void 0?` (cwd: ${ve(c.cwd)})`:"",p=l==="missing"?" \u26A0 worktree was swept \u2014 cannot re-dispatch without its working directory":"";a.push(` \xB7 ${c.id}: ${d}...${u}${p}`)}}if(r.length>0){a.push(" Units blocked on failed upstream deps:");for(let c of r)a.push(` \xB7 ${c.id} (depends on: ${c.upstreamIds.join(", ")})`)}return a.push(" To retry, re-dispatch each ready unit's prompt from its listed cwd; this notice does not accept yes/no replies."),a.join(`
|
|
123
123
|
`)}function wT(t){return t||k.AFK_WAVE_RESUME_UNATTENDED==="1"}function ST(t){try{let e=new Date().toISOString();t.offeredAt=e,t.updatedAt=e,ul(t)}catch{}}function cK(t){let e=Math.floor(t/6e4);if(e<60)return`${e}m`;let n=Math.floor(e/60);return n<24?`${n}h`:`${Math.floor(n/24)}d`}function kT(){let t=0;try{let e=ko(),n;try{n=gT(e)}catch{return{deleted:t}}let r=Date.now();for(let o of n){if(!o.endsWith(".json"))continue;let s=o.slice(0,-5);if(!/^[A-Za-z0-9]+$/.test(s))continue;let i=pl(s);if(i===void 0)continue;let a=new Date(i.expiresAt).getTime();if(!(Number.isFinite(a)&&a>=r))try{hT(vo(s)),t+=1}catch{}}}catch{}return{deleted:t}}var iK,aK,Qm=h(()=>{"use strict";fl();Vm();B();F();et();iK=new Set(["pending","running"]),aK=2880*60*1e3});function Ge(t,e=4096){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let o=e,s=r.lastIndexOf(`
|
|
@@ -150,7 +150,7 @@ ${e.join(`
|
|
|
150
150
|
|
|
151
151
|
Tap one to switch. /new starts a fresh session.`}function GT(){return`\u{1F5C2}\uFE0F No saved sessions yet.
|
|
152
152
|
|
|
153
|
-
Send a message to start one, or /new for a fresh session.`}function XT(t){return`\u21A9\uFE0F Switched to ${t.name?`<b>${ge(t.name)}</b>`:"that session"}. Your next message continues it.`}function zT(){return"\u{1F195} Started a fresh session. Your previous one is saved \u2014 /sessions to switch back."}function sg(){return"\u23F3 Finish or wait for the current turn before switching sessions."}function JT(){return X("That session could no longer be found. /sessions to see the current list.")}function VT(){return"\u2705 You're already on that session."}var Te=h(()=>{"use strict"});var nt,Ie,Tl,ee,ct,_n,_o,se=h(()=>{"use strict";nt=class extends Error{constructor(e){super(e),this.name="AbortError"}},Ie=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Tl=class extends Ie{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},ee=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause),s?.injectContext!==void 0&&(this.injectContext=s.injectContext)}event;reason;cause;injectContext},ct=class extends Error{toolResultsGathered;constructor(e){super(e),this.name="StreamIncompleteError"}},_n=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd},_o=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}}});function YT(t){let e=[...t.oauthEntries??[],...t.effort?[t.effortEntry]:[],...t.extendedCacheTtl?[t.extendedCacheEntry]:[],...t.fast?[EK]:[]].filter(Boolean);return[...new Set(e)].join(",")||void 0}var EK,QT=h(()=>{"use strict";EK="fast-mode-2026-02-01"});function Ao(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function pi(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function An(t,e,n,r,o,s){let i=YT({oauthEntries:t==="oauth"?_K.split(","):[],effort:t==="oauth"&&r===!0,extendedCacheTtl:o,fast:s,effortEntry:AK,extendedCacheEntry:ZT});return t!=="oauth"?i?{"anthropic-beta":i}:{}:{"anthropic-beta":i,"x-app":"cli","User-Agent":xK,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function eE(t){return t!=="oauth"?null:[{type:"text",text:RK}]}var ZT,_K,AK,xK,RK,xn=h(()=>{"use strict";QT();ZT="extended-cache-ttl-2025-04-11",_K=`claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,${ZT}`,AK="effort-2025-11-24",xK="claude-cli/1.0.0 (external, cli)",RK="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function _l(t){dg=t}function cg(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function El(t,e,n){let r={},o=cg(t);o&&(r.id=o);let s=cg(e);s&&(r.baseUrl=s);let i=cg(n);return i&&(r.apiKey=i),r}function PK(){return{local:El(k.AFK_MODEL_LOCAL,k.AFK_MODEL_LOCAL_BASE_URL,k.AFK_MODEL_LOCAL_API_KEY),small:El(k.AFK_MODEL_SMALL,k.AFK_MODEL_SMALL_BASE_URL,k.AFK_MODEL_SMALL_API_KEY),medium:El(k.AFK_MODEL_MEDIUM,k.AFK_MODEL_MEDIUM_BASE_URL,k.AFK_MODEL_MEDIUM_API_KEY),large:El(k.AFK_MODEL_LARGE,k.AFK_MODEL_LARGE_BASE_URL,k.AFK_MODEL_LARGE_API_KEY)}}function fg(t){let e=PK(),n={};for(let r of mi){let o=fr[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Ro(t){return t||dg||fg()}function Io(t,e=Ro()){let n=t.trim().toLowerCase();if(!(!n||n===rE)){for(let r of mi){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function gr(t,e=Ro()){if(t===void 0)return{id:""};let n=Io(t,e);if(n)return e[n];let r=pg[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function Ut(t,e=Ro()){if(t!==void 0)return gr(t,e).id}function oE(t,e=Ro()){if(t===void 0)return;let n=Io(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function sE(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of mi){let o=OK(n[r]);o&&(e[r]=o)}return e}function iE(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth";if(e==="xai")return"xai";if(e==="xai-oauth"||e==="xai_oauth")return"xai-oauth"}function xo(t){return typeof t=="string"?t.trim():""}function tE(t){return/[\x00-\x1f\x7f]/.test(t)}function OK(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=xo(e.id);if(!n)return;let r={id:n},o=xo(e.name);o&&(r.name=o);let s=iE(e.provider);s&&(r.provider=s);let i=xo(e.baseUrl);i&&(r.baseUrl=i);let a=xo(e.apiKey);return a&&(r.apiKey=a),r}}function aE(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=xo(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(tE(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=xo(e.name);if(o){if(tE(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(MK.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=iE(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var mi,nE,fi,lg,ug,IK,fr,rE,pg,CK,mr,dg,MK,Fe=h(()=>{"use strict";F();mi=["local","small","medium","large"],nE="claude-haiku-4-5-20251001",fi="claude-sonnet-4-6",lg="claude-opus-5",ug="claude-fable-5",IK="grok-4.6",fr={local:{id:""},small:{id:nE},medium:{id:fi},large:{id:lg}},rE="auto",pg={opus:lg,opus_1m:lg,sonnet:fi,sonnet_1m:fi,haiku:nE,fable:ug,grok:IK},CK=["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-5.5"],mr=[...mi,...Object.keys(pg),...CK];MK=new Set([...mi,rE,...Object.keys(pg)])});function gi(t){return t in mg}function Ee(t){return Ut(t)}var mg,lt=h(()=>{"use strict";Fe();mg={opus:fr.large.id,opus_1m:fr.large.id,sonnet:fr.medium.id,sonnet_1m:fr.medium.id,haiku:fr.small.id,fable:ug}});import DK from"@anthropic-ai/sdk";import{randomUUID as cE}from"node:crypto";async function lE(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=Ao(e),l=pi(e,c),d=a?a(l):new DK(l),u=cE(),p=cE(),f=An(c,u,p),m=Ee(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let y=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),b=[];for(let v of y.content)v.type==="text"&&b.push(v.text);let w=b.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}var dE=h(()=>{"use strict";xn();lt()});function NK(){let t=k.AFK_VISION_MODELS,e=[],n=[];if(t)for(let r of t.split(",")){let o=r.trim().toLowerCase();if(o)if(o.startsWith("!")){let s=o.slice(1).trim();s&&n.push(s)}else e.push(o)}return{enable:e,disable:n}}function uE(t,e){return t===e||t.includes(e)}function Al(t){if(!t)return!1;let e=(Ut(t)??t).trim();if(!e)return!1;let n=e.toLowerCase(),{enable:r,disable:o}=NK();return o.some(s=>uE(n,s))?!1:r.some(s=>uE(n,s))||FK.has(n)?!0:LK.some(s=>s.test(e))}function pE(t){let e=t.trim().toLowerCase();return e.includes("/")?e.slice(e.lastIndexOf("/")+1):e}function hr(t){return t?/^o[0-9]/.test(pE(t)):!1}function hi(t){if(!t)return!1;if(hr(t))return!0;let e=pE(t);return $K.some(n=>n.test(e))}var FK,LK,$K,yr=h(()=>{"use strict";F();Fe();FK=new Set(["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4-turbo","o1","o3","o4-mini"]),LK=[/^claude-/i,/^gpt-4o/i,/^gpt-4\.1/i,/^gpt-4-turbo/i,/^gpt-4-vision/i,/^gpt-5/i,/(?:^|[/_-])(?:vl|vlm)(?:[/_.-]|$)/i,/(?:^|[/_-])(?:llava|pixtral|internvl|cogvlm|idefics|moondream|janus)/i,/(?:vision|minicpm-?[vo]|qwen[\d.]*-?vl|llama-?3\.2-\d+b-vision|gemma-3|phi-3\.5-vision|phi-4-multimodal)/i];$K=[/^gpt-5/]});function yg(t){let e=String(t).trim().toLowerCase(),n=gg[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=Ut(t)??String(t);return gg[r]??gg[r.toLowerCase()]}function Co(t){return yg(t)??UK}function HK(t){if(!t)return!1;let e=t.trim().toLowerCase();return e?!!(e.includes("/")||e.startsWith("gpt-")||e.startsWith("gpt_")||hr(e)||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"||e==="grok"||e.startsWith("grok-")||e.startsWith("grok_")):!1}function Tt(t){let e=String(t).trim().toLowerCase(),n=hg[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=Ut(t)??String(t),o=hg[r]??hg[r.toLowerCase()];return o!==void 0?o:HK(r)?jK:BK}function sn(t){let e=Tt(t);if(String(t).trim().toLowerCase().endsWith("_1m"))return e;let r=Ut(t)??String(t),o=fE[r]??fE[r.toLowerCase()];return o!==void 0?Math.min(e,o):e}var gg,UK,hg,BK,jK,fE,Bt=h(()=>{"use strict";Fe();yr();gg={opus:128e3,opus_1m:128e3,sonnet:128e3,sonnet_1m:128e3,haiku:64e3,fable:128e3,"claude-opus-5":128e3,"claude-opus-4-8":128e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-5":128e3,"claude-sonnet-4-6":128e3,"claude-haiku-4-5-20251001":64e3,"claude-fable-5":128e3,"gpt-5.5":128e3,"gpt-5.6":128e3,"gpt-5.6-sol":128e3,"gpt-5.6-terra":128e3,"gpt-5.6-luna":128e3},UK=64e3;hg={opus:1e6,opus_1m:1e6,sonnet:1e6,sonnet_1m:1e6,haiku:2e5,fable:1e6,"claude-fable-5":1e6,"claude-sonnet-5":1e6,"claude-opus-5":1e6,"claude-opus-4-8":1e6,"claude-opus-4-7":1e6,"claude-opus-4-6":1e6,"claude-sonnet-4-6":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4.1":1e6,"gpt-4.1-mini":1e6,"gpt-5.5":1e6,"gpt-5.6":1e6,"gpt-5.6-sol":1e6,"gpt-5.6-terra":1e6,"gpt-5.6-luna":1e6,o1:2e5,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"mlx-community/qwen3-30b-a3b-4bit":128e3,"mlx-community/qwen3-32b-4bit":128e3,"mlx-community/qwen2.5-coder-32b-instruct-4bit":131072,"grok-4.6":5e5,"grok-4.5":5e5,"grok-4.3":1e6,"grok-4.20-0309-reasoning":1e6,"grok-4.20-0309-non-reasoning":1e6,"grok-4.20-multi-agent-0309":1e6,"grok-build-0.1":256e3},BK=2e5,jK=262144;fE={"claude-sonnet-5":2e5,"claude-opus-5":2e5,"claude-sonnet-4-6":2e5,"claude-opus-4-8":2e5,"claude-opus-4-7":2e5,"claude-opus-4-6":2e5}});function mE(t){return(t.inputTokens??0)+(t.outputTokens??0)}function _e(t){return t.contextWindowTokens??mE(t)}function yi(t){return t?{totalTokens:_e(t),apiUsage:{input_tokens:t.inputTokens??0,output_tokens:t.outputTokens??0,cache_read_input_tokens:t.cachedInputTokens??0,cache_creation_input_tokens:t.cacheCreationTokens??0,context_window_tokens:_e(t)}}:{totalTokens:0,apiUsage:null}}function bi(t,e,n){return e<=0||t<=0||n<=0||n>=1?!1:t/e>=n}function wi(t,e){return e<=0||t<=0?0:t/e}function gE(t){let e=Tt(t),n=sn(t),r=Co(t);if(e<=0||r<=0||n<e)return xl;let o=(e-r)/e-WK;return o>0?o:xl}function Si(t,e,n,r){if(t<=0||n<=0||e<=0)return;let o=t+e;if(!(o<=n))throw new Error(`[afk] Context-window overflow: the conversation already used ~${t.toLocaleString()} tokens (last-turn API count) and the configured output ceiling is ${e.toLocaleString()} tokens \u2014 together they exceed the ${r} context window of ${n.toLocaleString()} tokens by ${(o-n).toLocaleString()} tokens. The provider would reject this request with HTTP 400. To continue: run /compact to summarise the conversation history, or start a new session.`)}function ki(t,e){if(t===void 0||t===!1)return;let n=e!==void 0?gE(e):1;if(t===!0)return Math.min(xl,n);let r=t.threshold;if(!(typeof r!="number"||!Number.isFinite(r)||r<=0||r>=1))return Math.min(r,n)}var xl,WK,Po=h(()=>{"use strict";Bt();xl=.9,WK=.04});function yE(t){if(t!==void 0&&!(!Number.isFinite(t)||t<0)){if(t>Rl){let e=`temp:${t}`;return hE.has(e)||(hE.add(e),console.warn(`[afk] temperature ${t} exceeds the Anthropic maximum (${Rl}); clamping to ${Rl}.`)),Rl}return t}}function Cl(t,e){let n=Co(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Il.has(s)||(Il.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function bE(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function Pl(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&qK(n))return{type:"adaptive",display:"summarized"};if(e<=1024)throw new Error(`[afk] Extended thinking requires max_tokens > 1024 (the API constraint is 1024 <= budget_tokens < max_tokens), but the resolved output cap is ${e}. Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS above 1024, or disable thinking with --thinking disabled.`);let r=Math.floor(e*GK),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Il.has(a)||(Il.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function Ml(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-(4-[678]|5)/.test(n))return"max"}var KK,qK,Il,hE,Rl,GK,Ol=h(()=>{"use strict";Bt();Po();KK=t=>/opus-4-(7|[89])/.test(t),qK=t=>KK(t)||/(claude-)?(opus|sonnet)-5/.test(t),Il=new Set,hE=new Set,Rl=1;GK=.25});import bg from"path";import{dirname as XK}from"path";import{appendFileSync as zK,mkdirSync as JK}from"fs";var Rn,Dl=h(()=>{"use strict";B();Rn=class{hooks;constructor(e){this.hooks=e}addReadRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots();if(!o)return;let s=bg.resolve(e);o.includes(s)||(o.push(s),this.appendAuditLog({action:"grant-read",path:s,source:n,sessionId:r}))}addWriteRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots(),s=this.hooks.getWriteRoots();if(!o||!s)return;let i=bg.resolve(e);o.includes(i)||o.push(i),s.includes(i)||(s.push(i),this.appendAuditLog({action:"grant-write",path:i,source:n,sessionId:r}))}revokeRoot(e,n="slash",r){let o=this.hooks.getReadRoots();if(!o)return;let s=bg.resolve(e),i=this.hooks.getProtectedRoot();if(i!==void 0&&s===i)return;let a=o.indexOf(s),c=a!==-1;c&&o.splice(a,1);let l=this.hooks.getWriteRoots(),d=!1;if(l){let u=l.indexOf(s);d=u!==-1,d&&l.splice(u,1)}(c||d)&&this.appendAuditLog({action:"revoke",path:s,source:n,sessionId:r})}getGrants(){return{resolveBase:this.hooks.getDisplayResolveBase?this.hooks.getDisplayResolveBase():this.hooks.getProtectedRoot(),readRoots:this.hooks.getReadRoots()?.slice()??[],writeRoots:this.hooks.getWriteRoots()?.slice()??[],allowAll:this.hooks.getAllowAll()}}appendAuditLog(e){try{let n=qc();JK(XK(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??this.hooks.getDefaultSessionId?.()??null,action:e.action,path:e.path,source:e.source});zK(n,r+`
|
|
153
|
+
Send a message to start one, or /new for a fresh session.`}function XT(t){return`\u21A9\uFE0F Switched to ${t.name?`<b>${ge(t.name)}</b>`:"that session"}. Your next message continues it.`}function zT(){return"\u{1F195} Started a fresh session. Your previous one is saved \u2014 /sessions to switch back."}function sg(){return"\u23F3 Finish or wait for the current turn before switching sessions."}function JT(){return X("That session could no longer be found. /sessions to see the current list.")}function VT(){return"\u2705 You're already on that session."}var Te=h(()=>{"use strict"});var nt,Ie,Tl,ee,ct,_n,_o,ie=h(()=>{"use strict";nt=class extends Error{constructor(e){super(e),this.name="AbortError"}},Ie=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Tl=class extends Ie{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},ee=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause),s?.injectContext!==void 0&&(this.injectContext=s.injectContext)}event;reason;cause;injectContext},ct=class extends Error{toolResultsGathered;constructor(e){super(e),this.name="StreamIncompleteError"}},_n=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd},_o=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}}});function YT(t){let e=[...t.oauthEntries??[],...t.effort?[t.effortEntry]:[],...t.extendedCacheTtl?[t.extendedCacheEntry]:[],...t.fast?[EK]:[]].filter(Boolean);return[...new Set(e)].join(",")||void 0}var EK,QT=h(()=>{"use strict";EK="fast-mode-2026-02-01"});function Ao(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function pi(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function An(t,e,n,r,o,s){let i=YT({oauthEntries:t==="oauth"?_K.split(","):[],effort:t==="oauth"&&r===!0,extendedCacheTtl:o,fast:s,effortEntry:AK,extendedCacheEntry:ZT});return t!=="oauth"?i?{"anthropic-beta":i}:{}:{"anthropic-beta":i,"x-app":"cli","User-Agent":xK,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function eE(t){return t!=="oauth"?null:[{type:"text",text:RK}]}var ZT,_K,AK,xK,RK,xn=h(()=>{"use strict";QT();ZT="extended-cache-ttl-2025-04-11",_K=`claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,${ZT}`,AK="effort-2025-11-24",xK="claude-cli/1.0.0 (external, cli)",RK="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function _l(t){dg=t}function cg(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function El(t,e,n){let r={},o=cg(t);o&&(r.id=o);let s=cg(e);s&&(r.baseUrl=s);let i=cg(n);return i&&(r.apiKey=i),r}function PK(){return{local:El(k.AFK_MODEL_LOCAL,k.AFK_MODEL_LOCAL_BASE_URL,k.AFK_MODEL_LOCAL_API_KEY),small:El(k.AFK_MODEL_SMALL,k.AFK_MODEL_SMALL_BASE_URL,k.AFK_MODEL_SMALL_API_KEY),medium:El(k.AFK_MODEL_MEDIUM,k.AFK_MODEL_MEDIUM_BASE_URL,k.AFK_MODEL_MEDIUM_API_KEY),large:El(k.AFK_MODEL_LARGE,k.AFK_MODEL_LARGE_BASE_URL,k.AFK_MODEL_LARGE_API_KEY)}}function fg(t){let e=PK(),n={};for(let r of mi){let o=fr[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Ro(t){return t||dg||fg()}function Io(t,e=Ro()){let n=t.trim().toLowerCase();if(!(!n||n===rE)){for(let r of mi){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function gr(t,e=Ro()){if(t===void 0)return{id:""};let n=Io(t,e);if(n)return e[n];let r=pg[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function Ut(t,e=Ro()){if(t!==void 0)return gr(t,e).id}function oE(t,e=Ro()){if(t===void 0)return;let n=Io(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function sE(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of mi){let o=OK(n[r]);o&&(e[r]=o)}return e}function iE(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth";if(e==="xai")return"xai";if(e==="xai-oauth"||e==="xai_oauth")return"xai-oauth"}function xo(t){return typeof t=="string"?t.trim():""}function tE(t){return/[\x00-\x1f\x7f]/.test(t)}function OK(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=xo(e.id);if(!n)return;let r={id:n},o=xo(e.name);o&&(r.name=o);let s=iE(e.provider);s&&(r.provider=s);let i=xo(e.baseUrl);i&&(r.baseUrl=i);let a=xo(e.apiKey);return a&&(r.apiKey=a),r}}function aE(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=xo(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(tE(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=xo(e.name);if(o){if(tE(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(MK.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=iE(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var mi,nE,fi,lg,ug,IK,fr,rE,pg,CK,mr,dg,MK,Fe=h(()=>{"use strict";F();mi=["local","small","medium","large"],nE="claude-haiku-4-5-20251001",fi="claude-sonnet-4-6",lg="claude-opus-5",ug="claude-fable-5",IK="grok-4.6",fr={local:{id:""},small:{id:nE},medium:{id:fi},large:{id:lg}},rE="auto",pg={opus:lg,opus_1m:lg,sonnet:fi,sonnet_1m:fi,haiku:nE,fable:ug,grok:IK},CK=["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-5.5"],mr=[...mi,...Object.keys(pg),...CK];MK=new Set([...mi,rE,...Object.keys(pg)])});function gi(t){return t in mg}function Ee(t){return Ut(t)}var mg,lt=h(()=>{"use strict";Fe();mg={opus:fr.large.id,opus_1m:fr.large.id,sonnet:fr.medium.id,sonnet_1m:fr.medium.id,haiku:fr.small.id,fable:ug}});import DK from"@anthropic-ai/sdk";import{randomUUID as cE}from"node:crypto";async function lE(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=Ao(e),l=pi(e,c),d=a?a(l):new DK(l),u=cE(),p=cE(),f=An(c,u,p),m=Ee(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let y=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),b=[];for(let v of y.content)v.type==="text"&&b.push(v.text);let w=b.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}var dE=h(()=>{"use strict";xn();lt()});function NK(){let t=k.AFK_VISION_MODELS,e=[],n=[];if(t)for(let r of t.split(",")){let o=r.trim().toLowerCase();if(o)if(o.startsWith("!")){let s=o.slice(1).trim();s&&n.push(s)}else e.push(o)}return{enable:e,disable:n}}function uE(t,e){return t===e||t.includes(e)}function Al(t){if(!t)return!1;let e=(Ut(t)??t).trim();if(!e)return!1;let n=e.toLowerCase(),{enable:r,disable:o}=NK();return o.some(s=>uE(n,s))?!1:r.some(s=>uE(n,s))||FK.has(n)?!0:LK.some(s=>s.test(e))}function pE(t){let e=t.trim().toLowerCase();return e.includes("/")?e.slice(e.lastIndexOf("/")+1):e}function hr(t){return t?/^o[0-9]/.test(pE(t)):!1}function hi(t){if(!t)return!1;if(hr(t))return!0;let e=pE(t);return $K.some(n=>n.test(e))}var FK,LK,$K,yr=h(()=>{"use strict";F();Fe();FK=new Set(["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4-turbo","o1","o3","o4-mini"]),LK=[/^claude-/i,/^gpt-4o/i,/^gpt-4\.1/i,/^gpt-4-turbo/i,/^gpt-4-vision/i,/^gpt-5/i,/(?:^|[/_-])(?:vl|vlm)(?:[/_.-]|$)/i,/(?:^|[/_-])(?:llava|pixtral|internvl|cogvlm|idefics|moondream|janus)/i,/(?:vision|minicpm-?[vo]|qwen[\d.]*-?vl|llama-?3\.2-\d+b-vision|gemma-3|phi-3\.5-vision|phi-4-multimodal)/i];$K=[/^gpt-5/]});function yg(t){let e=String(t).trim().toLowerCase(),n=gg[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=Ut(t)??String(t);return gg[r]??gg[r.toLowerCase()]}function Co(t){return yg(t)??UK}function HK(t){if(!t)return!1;let e=t.trim().toLowerCase();return e?!!(e.includes("/")||e.startsWith("gpt-")||e.startsWith("gpt_")||hr(e)||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"||e==="grok"||e.startsWith("grok-")||e.startsWith("grok_")):!1}function Tt(t){let e=String(t).trim().toLowerCase(),n=hg[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=Ut(t)??String(t),o=hg[r]??hg[r.toLowerCase()];return o!==void 0?o:HK(r)?jK:BK}function sn(t){let e=Tt(t);if(String(t).trim().toLowerCase().endsWith("_1m"))return e;let r=Ut(t)??String(t),o=fE[r]??fE[r.toLowerCase()];return o!==void 0?Math.min(e,o):e}var gg,UK,hg,BK,jK,fE,Bt=h(()=>{"use strict";Fe();yr();gg={opus:128e3,opus_1m:128e3,sonnet:128e3,sonnet_1m:128e3,haiku:64e3,fable:128e3,"claude-opus-5":128e3,"claude-opus-4-8":128e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-5":128e3,"claude-sonnet-4-6":128e3,"claude-haiku-4-5-20251001":64e3,"claude-fable-5":128e3,"gpt-5.5":128e3,"gpt-5.6":128e3,"gpt-5.6-sol":128e3,"gpt-5.6-terra":128e3,"gpt-5.6-luna":128e3},UK=64e3;hg={opus:1e6,opus_1m:1e6,sonnet:1e6,sonnet_1m:1e6,haiku:2e5,fable:1e6,"claude-fable-5":1e6,"claude-sonnet-5":1e6,"claude-opus-5":1e6,"claude-opus-4-8":1e6,"claude-opus-4-7":1e6,"claude-opus-4-6":1e6,"claude-sonnet-4-6":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4.1":1e6,"gpt-4.1-mini":1e6,"gpt-5.5":1e6,"gpt-5.6":1e6,"gpt-5.6-sol":1e6,"gpt-5.6-terra":1e6,"gpt-5.6-luna":1e6,o1:2e5,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"mlx-community/qwen3-30b-a3b-4bit":128e3,"mlx-community/qwen3-32b-4bit":128e3,"mlx-community/qwen2.5-coder-32b-instruct-4bit":131072,"grok-4.6":5e5,"grok-4.5":5e5,"grok-4.3":1e6,"grok-4.20-0309-reasoning":1e6,"grok-4.20-0309-non-reasoning":1e6,"grok-4.20-multi-agent-0309":1e6,"grok-build-0.1":256e3},BK=2e5,jK=262144;fE={"claude-sonnet-5":2e5,"claude-opus-5":2e5,"claude-sonnet-4-6":2e5,"claude-opus-4-8":2e5,"claude-opus-4-7":2e5,"claude-opus-4-6":2e5}});function mE(t){return(t.inputTokens??0)+(t.outputTokens??0)}function _e(t){return t.contextWindowTokens??mE(t)}function yi(t){return t?{totalTokens:_e(t),apiUsage:{input_tokens:t.inputTokens??0,output_tokens:t.outputTokens??0,cache_read_input_tokens:t.cachedInputTokens??0,cache_creation_input_tokens:t.cacheCreationTokens??0,context_window_tokens:_e(t)}}:{totalTokens:0,apiUsage:null}}function bi(t,e,n){return e<=0||t<=0||n<=0||n>=1?!1:t/e>=n}function wi(t,e){return e<=0||t<=0?0:t/e}function gE(t){let e=Tt(t),n=sn(t),r=Co(t);if(e<=0||r<=0||n<e)return xl;let o=(e-r)/e-WK;return o>0?o:xl}function Si(t,e,n,r){if(t<=0||n<=0||e<=0)return;let o=t+e;if(!(o<=n))throw new Error(`[afk] Context-window overflow: the conversation already used ~${t.toLocaleString()} tokens (last-turn API count) and the configured output ceiling is ${e.toLocaleString()} tokens \u2014 together they exceed the ${r} context window of ${n.toLocaleString()} tokens by ${(o-n).toLocaleString()} tokens. The provider would reject this request with HTTP 400. To continue: run /compact to summarise the conversation history, or start a new session.`)}function ki(t,e){if(t===void 0||t===!1)return;let n=e!==void 0?gE(e):1;if(t===!0)return Math.min(xl,n);let r=t.threshold;if(!(typeof r!="number"||!Number.isFinite(r)||r<=0||r>=1))return Math.min(r,n)}var xl,WK,Po=h(()=>{"use strict";Bt();xl=.9,WK=.04});function yE(t){if(t!==void 0&&!(!Number.isFinite(t)||t<0)){if(t>Rl){let e=`temp:${t}`;return hE.has(e)||(hE.add(e),console.warn(`[afk] temperature ${t} exceeds the Anthropic maximum (${Rl}); clamping to ${Rl}.`)),Rl}return t}}function Cl(t,e){let n=Co(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Il.has(s)||(Il.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function bE(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function Pl(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&qK(n))return{type:"adaptive",display:"summarized"};if(e<=1024)throw new Error(`[afk] Extended thinking requires max_tokens > 1024 (the API constraint is 1024 <= budget_tokens < max_tokens), but the resolved output cap is ${e}. Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS above 1024, or disable thinking with --thinking disabled.`);let r=Math.floor(e*GK),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Il.has(a)||(Il.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function Ml(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-(4-[678]|5)/.test(n))return"max"}var KK,qK,Il,hE,Rl,GK,Ol=h(()=>{"use strict";Bt();Po();KK=t=>/opus-4-(7|[89])/.test(t),qK=t=>KK(t)||/(claude-)?(opus|sonnet)-5/.test(t),Il=new Set,hE=new Set,Rl=1;GK=.25});import bg from"path";import{dirname as XK}from"path";import{appendFileSync as zK,mkdirSync as JK}from"fs";var Rn,Dl=h(()=>{"use strict";B();Rn=class{hooks;constructor(e){this.hooks=e}addReadRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots();if(!o)return;let s=bg.resolve(e);o.includes(s)||(o.push(s),this.appendAuditLog({action:"grant-read",path:s,source:n,sessionId:r}))}addWriteRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots(),s=this.hooks.getWriteRoots();if(!o||!s)return;let i=bg.resolve(e);o.includes(i)||o.push(i),s.includes(i)||(s.push(i),this.appendAuditLog({action:"grant-write",path:i,source:n,sessionId:r}))}revokeRoot(e,n="slash",r){let o=this.hooks.getReadRoots();if(!o)return;let s=bg.resolve(e),i=this.hooks.getProtectedRoot();if(i!==void 0&&s===i)return;let a=o.indexOf(s),c=a!==-1;c&&o.splice(a,1);let l=this.hooks.getWriteRoots(),d=!1;if(l){let u=l.indexOf(s);d=u!==-1,d&&l.splice(u,1)}(c||d)&&this.appendAuditLog({action:"revoke",path:s,source:n,sessionId:r})}getGrants(){return{resolveBase:this.hooks.getDisplayResolveBase?this.hooks.getDisplayResolveBase():this.hooks.getProtectedRoot(),readRoots:this.hooks.getReadRoots()?.slice()??[],writeRoots:this.hooks.getWriteRoots()?.slice()??[],allowAll:this.hooks.getAllowAll()}}appendAuditLog(e){try{let n=qc();JK(XK(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??this.hooks.getDefaultSessionId?.()??null,action:e.action,path:e.path,source:e.source});zK(n,r+`
|
|
154
154
|
`)}catch{}}}});function Et(t){return t==="bypassPermissions"||t==="autonomous"}var Mo=h(()=>{"use strict"});var Fl,wE=h(()=>{"use strict";Dl();Mo();Fl=class{_readRoots;_writeRoots;_currentCwd;_permissionMode="default";manager=new Rn({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,ensureInitialized:()=>this.ensureInitialized(),getProtectedRoot:()=>this._currentCwd,getAllowAll:()=>Et(this._permissionMode)});get readRoots(){return this._readRoots}get writeRoots(){return this._writeRoots}get currentCwd(){return this._currentCwd}set currentCwd(e){this._currentCwd=e}get permissionMode(){return this._permissionMode}set permissionMode(e){this._permissionMode=e}ensureInitialized(e){if(!this._readRoots){let n=e?[e]:[];this._readRoots=n.slice(),this._writeRoots=n.slice(),e&&!this._currentCwd&&(this._currentCwd=e)}}}});import{z as Le}from"zod";function Ll(t,e){let n=new Map;return n.set("state_get",async r=>{try{let{namespace:o,key:s}=VK.parse(r),i=t.get(o,s);return{content:JSON.stringify(i)}}catch(o){return{content:String(o),isError:!0}}}),n.set("state_put",async r=>{try{let{namespace:o,key:s,value:i,ttl_ms:a,metadata:c}=YK.parse(r),l=t.put(o,s,i,{ttl_ms:a,metadata:c},e);return{content:JSON.stringify(l)}}catch(o){return{content:String(o),isError:!0}}}),n.set("state_cas",async r=>{try{let{namespace:o,key:s,expected_version:i,value:a,ttl_ms:c,metadata:l}=QK.parse(r),d=t.cas(o,s,i,a,{ttl_ms:c,metadata:l},e);return{content:JSON.stringify(d)}}catch(o){return{content:String(o),isError:!0}}}),n.set("state_delete",async r=>{try{let{namespace:o,key:s}=ZK.parse(r),i=t.del(o,s);return{content:JSON.stringify(i)}}catch(o){return{content:String(o),isError:!0}}}),n.set("state_query",async r=>{try{let o=eq.parse(r),s=Math.min(o.limit??20,100),i=t.query(o.namespace,{key_prefix:o.key_prefix,limit:s});return{content:JSON.stringify(i)}}catch(o){return{content:String(o),isError:!0}}}),n}var an,VK,YK,QK,ZK,eq,wg,vi=h(()=>{"use strict";an=Le.string().min(1,"namespace/key must be non-empty").max(128,"namespace/key must not exceed 128 characters").regex(/^[A-Za-z0-9_.-]+$/,"namespace/key may only contain [A-Za-z0-9_.-]"),VK=Le.object({namespace:an,key:an}),YK=Le.object({namespace:an,key:an,value:Le.unknown(),ttl_ms:Le.number().int().positive().optional(),metadata:Le.unknown().optional()}),QK=Le.object({namespace:an,key:an,expected_version:Le.number(),value:Le.unknown(),ttl_ms:Le.number().int().positive().optional(),metadata:Le.unknown().optional()}),ZK=Le.object({namespace:an,key:an}),eq=Le.object({namespace:an,key_prefix:Le.string().optional(),limit:Le.number().int().positive().max(100).optional()}),wg=["state_get","state_put","state_cas","state_delete","state_query"]});var Nl=h(()=>{"use strict"});function kg(t,e){for(let n of t.values())e.seq<=n.lastDeliveredSeq||n.type!==void 0&&e.type!==n.type||n.subject!==void 0&&!(e.subject??"").toLowerCase().includes(n.subject.toLowerCase())||(n.deliveryFn(e),n.lastDeliveredSeq=e.seq)}function vg(t,e=0){if(t.length===0)return;let n=(i,a)=>{let c=new Date().toISOString(),l=i.length,d=e>0?` dropped="${e}"`:"",u=i.map(f=>{let m=f.subject!==null&&f.subject!==void 0?` subject="${SE(f.subject)}"`:"",g=` confidence="${f.confidence.toFixed(2)}"`;return`<entry id="${f.id}" type="${SE(f.type)}"${m}${g}>`+tq(f.content)+"</entry>"}).join(`
|
|
155
155
|
`),p=a?`
|
|
156
156
|
<truncated-delivery omitted="${t.length-i.length}" />`:"";return`<workspace-delivery count="${l}"${d} timestamp="${c}">
|
|
@@ -223,8 +223,8 @@ ${n}`}:{...t,systemPrompt:n};if(r&&typeof r=="object"&&"type"in r&&r.type==="pre
|
|
|
223
223
|
|
|
224
224
|
${n}`:n}}}return{...t,systemPrompt:n}}function pq(t){return t.length===0?t:(t[0]?.toUpperCase()??"")+t.slice(1)}var uq,AE=h(()=>{"use strict";uq=["# Workspace (shared agent scratchpad)","","No entries published yet \u2014 you may be the first. Call `workspace_publish` when you:","- confirm an architectural invariant or key export surface of a module,","- rule out a hypothesis (so siblings skip the same dead end),","- read a file another sibling will likely need (publish the insight, not the raw content).","","Call `workspace_query` before reading a file or grepping a module \u2014 a sibling may have","already analyzed it. Publishing is free to batch alongside other tools in the same reply."].join(`
|
|
225
225
|
`)});var In=h(()=>{"use strict";Eg();EE();Nl();Ti();AE()});function bq(t){return k[t]}function wq(t,e=!0){let n=bq(t.key);if(n===void 0)return{...t,rawValue:n,effectiveValue:t.defaultValue,source:"default",valid:!0};let r=n.trim(),o=Number(r);return/^\d+$/.test(r)&&Number.isInteger(o)&&o>0&&o<=t.maxValue?{...t,rawValue:n,effectiveValue:o,source:"environment",valid:!0}:(e&&!RE.has(t.key)&&(RE.add(t.key),process.stderr.write(`[afk] Invalid ${t.key}=${JSON.stringify(n)}; using default ${t.defaultValue}. Expected an integer in [1, ${t.maxValue}].
|
|
226
|
-
`)),{...t,rawValue:n,effectiveValue:t.defaultValue,source:"fallback",valid:!1})}function Ig(t){let e=yq.find(n=>n.key===t);if(!e)throw new Error(`Unknown concurrency setting: ${t}`);return wq(e).effectiveValue}function PE(){return Ig("AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS")}function Ri(){return Ig("AFK_MAX_CONCURRENT_SUBAGENT_CALLS")}function ME(){return Ig("AFK_MAX_CONCURRENT_BACKGROUND_JOBS")}var IE,CE,fq,mq,gq,hq,yq,RE,Ul=h(()=>{"use strict";F();IE=8,CE=8,fq=10,mq=32,gq=32,hq=64,yq=[{key:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",defaultValue:IE,maxValue:mq},{key:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",defaultValue:CE,maxValue:gq},{key:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",defaultValue:fq,maxValue:hq}],RE=new Set});function Cg(t){if(t instanceof Ie)return"timeout";if(t instanceof _n)return"budget";if(typeof t=="string"){if(t==="budget"||t.startsWith("Budget "))return"budget";if(t==="timeout"||t.includes("timed out"))return"timeout";if(t==="closed")return"closed"}return"interrupted"}function Ne(t){let e=Cg(t.reason);return e==="timeout"||e==="budget"?e:"abort"}var Cn=h(()=>{"use strict";
|
|
227
|
-
`);i={...i,...c,...l.length>0?{injectContext:l}:{}}}return i}}});function Tq(t){return t instanceof Error?t.message:String(t)}function Eq(t,e){if(typeof e=="object"&&e!==null){let r=DE.get(e);return r||(r=new Set,DE.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(Ii.has(n))return!1;if(Ii.set(n,!0),Ii.size>vq){let r=Ii.keys().next().value;r!==void 0&&Ii.delete(r)}return!0}function he(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${Tq(r)}`;if(!Eq(t,e)){
|
|
226
|
+
`)),{...t,rawValue:n,effectiveValue:t.defaultValue,source:"fallback",valid:!1})}function Ig(t){let e=yq.find(n=>n.key===t);if(!e)throw new Error(`Unknown concurrency setting: ${t}`);return wq(e).effectiveValue}function PE(){return Ig("AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS")}function Ri(){return Ig("AFK_MAX_CONCURRENT_SUBAGENT_CALLS")}function ME(){return Ig("AFK_MAX_CONCURRENT_BACKGROUND_JOBS")}var IE,CE,fq,mq,gq,hq,yq,RE,Ul=h(()=>{"use strict";F();IE=8,CE=8,fq=10,mq=32,gq=32,hq=64,yq=[{key:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",defaultValue:IE,maxValue:mq},{key:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",defaultValue:CE,maxValue:gq},{key:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",defaultValue:fq,maxValue:hq}],RE=new Set});function Cg(t){if(t instanceof Ie)return"timeout";if(t instanceof _n)return"budget";if(typeof t=="string"){if(t==="budget"||t.startsWith("Budget "))return"budget";if(t==="timeout"||t.includes("timed out"))return"timeout";if(t==="closed")return"closed"}return"interrupted"}function Ne(t){let e=Cg(t.reason);return e==="timeout"||e==="budget"?e:"abort"}var Cn=h(()=>{"use strict";ie()});function Sq(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new br(n,e)))},e);i.unref(),Promise.resolve(t).then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}function kq(t){return t.continue===!1||t.decision==="block"}function Pg(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new nt(r)}}function OE(){return new Mg}var wr,br,Mg,Bl=h(()=>{"use strict";ie();wr=3e4;br=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"},Mg=class{handlers=new Map;register(e,n,r={}){let o=this.handlers.get(e);o||(o=[],this.handlers.set(e,o));let s={handler:n,options:r};return o.push(s),()=>{let i=this.handlers.get(e);if(!i)return;let a=i.indexOf(s);a>=0&&i.splice(a,1)}}count(e){return this.handlers.get(e)?.length??0}async dispatch(e,n,r=wr){Pg(n,e.event);let o=this.handlers.get(e.event);if(!o||o.length===0)return{};let s=o.slice(),i={};for(let a of s){Pg(n,e.event);let c;try{let d=a.handler(e,n);c=!a.options.longRunning&&r>0&&Number.isFinite(r)?await Sq(d,r,e.event):await d}catch(d){throw d instanceof br?d:new ee(`hook handler threw during ${e.event}`,e.event,d instanceof Error?d.message:String(d),{cause:d})}if(Pg(n,e.event),kq(c))throw new ee(`hook handler blocked ${e.event}${c.reason?`: ${c.reason}`:""}`,e.event,c.reason,c.injectContext!==void 0?{injectContext:c.injectContext}:void 0);let l=[i.injectContext,c.injectContext].filter(d=>typeof d=="string"&&d.length>0).join(`
|
|
227
|
+
`);i={...i,...c,...l.length>0?{injectContext:l}:{}}}return i}}});function Tq(t){return t instanceof Error?t.message:String(t)}function Eq(t,e){if(typeof e=="object"&&e!==null){let r=DE.get(e);return r||(r=new Set,DE.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(Ii.has(n))return!1;if(Ii.set(n,!0),Ii.size>vq){let r=Ii.keys().next().value;r!==void 0&&Ii.delete(r)}return!0}function he(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${Tq(r)}`;if(!Eq(t,e)){O(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}var vq,DE,Ii,jl=h(()=>{"use strict";se();vq=256,DE=new WeakMap,Ii=new Map});async function Sr(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){he("trace.emit",t,"tool_call",n)}}async function dt(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){he("trace.emit",t,"hook_decision",n)}}async function kr(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){he("trace.emit",t,"subagent_lifecycle",n)}}async function vr(t,e){if(t)try{await t.write({kind:"background_agent",payload:e})}catch(n){he("trace.emit",t,"background_agent",n)}}async function FE(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){he("trace.emit",t,"budget",n)}}async function LE(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){he("trace.emit",t,"abort",n)}}async function Hl(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){he("trace.emit",t,"compaction",n)}}async function NE(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){he("trace.emit",t,"closure",n)}}async function ye(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){he("trace.emit",t,"browser_event",n)}}async function Wl(t,e){if(t)try{await t.write({kind:"queued_user_message",payload:e})}catch(n){he("trace.emit",t,"queued_user_message",n)}}async function q(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){he("trace.emit",t,"session_phase",n)}}var J=h(()=>{"use strict";jl()});async function jt(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await dt(t,{hookEvent:e,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...e==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await dt(t,{hookEvent:e,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function $E(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await jt(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof ee&&await jt(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function _q(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new br(n,e)))},e);i.unref(),t.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function UE(t,e,n={}){if(!t)return{};try{let r=await _q(t.dispatch(e,n.signal,wr),wr,"SubagentStop");return await jt(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof br?(console.warn(`[afk] SubagentStop hook timed out after ${wr}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof ee&&await jt(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof ee||r instanceof nt?(O(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(O(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function BE(t,e,n={}){if(!t)return{};try{let r=await t.dispatch(e,n.signal);return await jt(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"decision",decision:r}),r}catch(r){throw r instanceof ee&&await jt(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r}}async function jE(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await jt(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof ee&&await jt(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof ee||r instanceof nt){O(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}O(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function HE(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await jt(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof ee&&await jt(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof ee||r instanceof nt){O(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}O(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Kl=h(()=>{"use strict";se();ie();Bl();J()});function WE(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}function ql(t,e){return KE(t,e)}function Gl(t,e){return KE(t,e)}function KE(t,e){if(!t?.allowedTools||e.length===0)return t;let n=new Set(t.allowedTools),r=!1;for(let o of e)n.has(o)||(n.add(o),r=!0);return r?{...t,allowedTools:[...n]}:t}var Xl=h(()=>{"use strict"});import*as zE from"node:os";import*as zl from"node:path";function eG(t){let e=zE.tmpdir(),n=!1,r;for(qE.lastIndex=0;(r=qE.exec(t))!==null;){let o=r[2];if(/`/.test(o))return!1;if(o==="/dev/null"||/^&?\d+$/.test(o))continue;if(Zq.test(o))return!1;let s=GE.test(o)?o.replace(GE,e+"/"):o;if(!zl.resolve(s).startsWith(e+zl.sep))return!1;n=!0}return n}function rG(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}function Og(t){return(t.split("/").pop()??t).replace(/^\\+/,"")}function JE(t){let e=[],n=[],r=[],o="",s=!1,i=()=>{s&&(r.push(o),o="",s=!1)},a=()=>{i(),r.length>0&&(e.push(r),r=[])},c=u=>{let p=u,f=1,m="";for(;p<t.length&&f>0;){let g=t[p];if(g==="(")f++;else if(g===")"&&(f--,f===0)){p++;break}m+=g,p++}return n.push(m),p},l=0,d=t.length;for(;l<d;){let u=t[l];if(u==="'"){for(s=!0,l++;l<d&&t[l]!=="'";)o+=t[l],l++;l++;continue}if(u==='"'){for(s=!0,l++;l<d&&t[l]!=='"';)if(t[l]==="$"&&t[l+1]==="(")l=c(l+2);else if(t[l]==="`"){l++;let p="";for(;l<d&&t[l]!=="`";)p+=t[l],l++;l++,n.push(p)}else o+=t[l],l++;l++;continue}if(u==="`"){i(),l++;let p="";for(;l<d&&t[l]!=="`";)p+=t[l],l++;l++,n.push(p);continue}if(u==="$"&&t[l+1]==="("){i(),l=c(l+2);continue}if(u===";"||u===`
|
|
228
228
|
`||u==="&"||u==="|"||u==="("||u===")"){a(),l++;continue}if(u===" "||u===" "||u==="\r"){i(),l++;continue}o+=u,s=!0,l++}a();for(let u of n)for(let p of JE(u))e.push(p);return e}function aG(t,e){let n=[...t],r=0,o=n[r];for((o==="export"||o==="local"||o==="declare")&&r++;r<n.length;){let s=/^([A-Za-z_]\w*)=(.*)$/.exec(n[r]);if(s===null)break;e.set(s[1],s[2]),r++}for(let s=0;r<n.length&&s<12;s++){let i=n[r],a=/^\$\{?([A-Za-z_]\w*)\}?$/.exec(i);if(a!==null){let l=e.get(a[1]);if(l!==void 0){let d=l.split(/\s+/).filter(Boolean);n=[...n.slice(0,r),...d,...n.slice(r+1)];continue}}let c=Og(i);if(!oG.has(c))break;if(r++,c==="env")for(;r<n.length;){let l=n[r],d=/^([A-Za-z_]\w*)=(.*)$/.exec(l);if(d!==null){e.set(d[1],d[2]),r++;continue}if(!l.startsWith("-"))break;r++,sG.has(l)&&r<n.length&&r++}else if(c==="xargs")for(;r<n.length&&n[r].startsWith("-");){let l=n[r];r++,iG.has(l)&&r<n.length&&r++}else if(c==="timeout"){for(;r<n.length&&n[r].startsWith("-");){let l=n[r];r++,(l==="-k"||l==="--kill-after"||l==="-s"||l==="--signal")&&r<n.length&&r++}r<n.length&&/^[\d.]+[smhd]?$/.test(n[r])&&r++}else if(c==="nice")for(;r<n.length&&n[r].startsWith("-");){let l=n[r];r++,l==="-n"&&r<n.length&&r++}else for(;r<n.length&&n[r].startsWith("-");){let l=n[r];r++,(l==="-u"||l==="--user")&&r<n.length&&r++}}return r>=n.length?null:{command:n[r],argv:n.slice(r+1)}}function dG(t){let e=0;for(;e<t.length;){let n=t[e];if(cG.has(n)){e+=2;continue}if(!n.startsWith("-"))break;e++}return{sub:t[e],rest:t.slice(e+1)}}function VE(t){if(t.includes("--help")||t.includes("-h"))return null;let{sub:e,rest:n}=dG(t);if(e===void 0||e==="help"||e==="config")return null;if(lG.has(e))return"git repository mutation";let r=n[0]??"";switch(e){case"tag":return r.startsWith("-")?"git tag create/delete":null;case"branch":return/^-[dDmMcC]/.test(r)||/^--(delete|move|copy|force)/.test(r)?"git branch delete/rename":null;case"remote":return["add","remove","rm","set-url","rename"].includes(r)?"git remote mutation":null;case"worktree":return["add","remove","prune","move","lock","unlock"].includes(r)?"git worktree mutation (add/remove/prune/move)":null;case"stash":return r==="list"||r==="show"?null:"git stash mutation (only `stash list`/`stash show` allowed)";default:return null}}function pG(t){if((t.command.split("/").pop()??t.command)!=="curl")return!1;for(let n=0;n<t.argv.length;n++){let r=t.argv[n];if((r==="-X"||r==="--request")&&uG.test(t.argv[n+1]??"")||/^-X(POST|PUT|PATCH|DELETE)$/i.test(r)||/^--request=(POST|PUT|PATCH|DELETE)$/i.test(r))return!0}return!1}function XE(t){for(let e=0;e<t.length-1;e++)if(Og(t[e])==="git"){let n=VE(t.slice(e+1));if(n!==null)return n}return null}function fG(t){let e=new Map;for(let n of JE(t)){let r=aG(n,e);if(r===null){let i=XE(n);if(i!==null)return i;continue}let o=Og(r.command);if(o==="git"){let i=VE(r.argv);if(i!==null)return i;continue}if(o==="curl"&&pG(r))return"curl write method (POST/PUT/PATCH/DELETE)";let s=XE(n);if(s!==null)return s}return null}function Vl(t){if(typeof t!="string"||t.trim().length===0)return{mutating:!1};for(let s of tG)if(s.re.test(t))return{mutating:!0,reason:s.reason};let e=t.match(Kq)?.[1];if(e&&qq.test(e))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let n=fG(t);if(n!==null)return{mutating:!0,reason:n};let r=rG(t);for(let s of nG)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(Yq," ").replace(Vq," ").replace(/&(>>?)/g,"$1");return Qq.test(o)&&!eG(t)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}var Aq,xq,Rq,Iq,Cq,Pq,Mq,Oq,Dq,Fq,Jl,Lq,Nq,$q,Uq,Bq,jq,Hq,Wq,Kq,qq,Gq,Xq,zq,Jq,Vq,Yq,Qq,qE,GE,Zq,tG,nG,oG,sG,iG,cG,lG,uG,Dg=h(()=>{"use strict";Aq=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,xq=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,Rq=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,Iq=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,Cq=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,Pq=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,Mq=/\|\s*(sh|bash|zsh|dash|ksh|mksh|csh|tcsh|fish|ash|python3?|node|nodejs|perl|ruby|php|bun)\b/i,Oq=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,Dq=/\bfind\b[^|;&]*\s-delete\b/i,Fq=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Jl=String.raw`(?:^|[\n;|&(]|\$\()\s*`,Lq=new RegExp(Jl+String.raw`patch\b`,"i"),Nq=new RegExp(Jl+String.raw`install\b`,"i"),$q=new RegExp(Jl+String.raw`(?:source\b|\.\s+\S)`,"i"),Uq=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,Bq=new RegExp(Jl+String.raw`unzip\b`,"i"),jq=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,Hq=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,Wq=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,Kq=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,qq=/open\s*\([^)]*,\s*['"][wax]|writeFileSync|writeFile\b|appendFileSync|appendFile\b|createWriteStream|File\.(?:write|delete)\b|IO\.write\b|FileUtils\.|\bBun\.write\b|os\.remove\b|os\.system\b|os\.popen\b|\bsubprocess\.|\bDeno\.(?:write|writeFile|writeTextFile|remove)\b|shutil\.\w|\.write_text\b|\.write_bytes\b/i,Gq=/\b(npm|pnpm|yarn|pip|pip3|brew|cargo|go|apt|apt-get|gem|poetry|bundle|composer)\s+(install|add|remove|uninstall|i|ci|up|update|upgrade|dlx|get|require)\b/i,Xq=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,zq=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,Jq=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,Vq=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,Yq=/\$\(\(.*?\)\)/g,Qq=/(?<![=<>-])>>?(?!&)/,qE=/(?<![=<>-])>>?[ \t]*(['"]?)(\/?[^\s;|&'"]+)\1/g,GE=/^\$\{?TMPDIR\}?\//,Zq=/\$(?!\{?TMPDIR\}?[/}]|$)/;tG=[{re:xq,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:Fq,reason:"find -exec with mutating verb"}],nG=[{re:Mq,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:Oq,reason:"filesystem mutation"},{re:Dq,reason:"find -delete (file removal)"},{re:Lq,reason:"patch (applies a diff to files)"},{re:Nq,reason:"install (writes files)"},{re:$q,reason:"source/dot-source executes a script"},{re:Uq,reason:"tar create/extract/append/update (writes files/archive)"},{re:Bq,reason:"unzip (writes files)"},{re:jq,reason:"cpio extract (-i mode writes files)"},{re:Aq,reason:"git config write flag (only reads allowed)"},{re:Rq,reason:"gh write operation"},{re:Iq,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:Cq,reason:"gh api field payload (-f/-F/--field)"},{re:Pq,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:Hq,reason:"sed in-place edit (-i)"},{re:Wq,reason:"perl in-place edit (-i)"},{re:Gq,reason:"package install/modify"},{re:Xq,reason:"curl/wget output-to-file"},{re:zq,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:Jq,reason:"curl data/form payload"}];oG=new Set(["env","xargs","command","sudo","nice","time","timeout","nohup","stdbuf","busybox","eval"]);sG=new Set(["-u","--unset","-C","--chdir","-S","--split-string"]),iG=new Set(["-a","--arg-file","-E","--eof","-I","--replace","-i","-L","--max-lines","-l","-n","--max-args","-P","--max-procs","-s","--max-chars","-d","--delimiter","--process-slot-var"]);cG=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),lG=new Set(["commit","push","pull","fetch","merge","rebase","reset","checkout","switch","restore","cherry-pick","revert","am","apply","clean","add","rm","mv","init","clone"]);uG=/^(POST|PUT|PATCH|DELETE)$/i});function mG(t,e){if(t.length<=e)return t;let n=e;for(;n>0&&(t[n]&192)===128;)n--;return t.subarray(0,n)}function gG(t,e){if(t.length<=e)return t;let n=t.length-e;for(;n<t.length&&(t[n]&192)===128;)n++;return t.subarray(n)}function _t(t,e){let n=Buffer.from(t,"utf8");if(n.length<=e)return t;let r=Math.max(0,e-hG),o=Math.ceil(r/2),s=r-o,i=mG(n,o),a=gG(n,s),l=`
|
|
229
229
|
|
|
230
230
|
\u2026 [${n.length-i.length-a.length} bytes truncated: showing first ${i.length} + last ${a.length} of ${n.length}] \u2026
|
|
@@ -266,9 +266,9 @@ ${n}
|
|
|
266
266
|
Remedy: these paths are outside the fork's granted read roots. Re-dispatch with the needed paths inside the child's cwd/worktree, or pass explicit readRoots granting them. If this worker is deliberately confined (e.g. an \`afk farm\` branch worker), this failure is expected \u2014 the paths are outside its assigned scope; widen the scope or narrow the task.`}var Fo,E_,nh,Fi=h(()=>{"use strict";Fo="denial-breaker",E_=new Set(["read_file","list_directory","glob","grep"]),nh="Sub-agent path access denied:"});import{createHash as c2}from"node:crypto";function R_(){return{recent:[],firedFingerprints:new Set}}function ad(t){let e;try{e=d2(t.input)}catch{e=String(t.input)}return c2("sha256").update(t.name).update("\0").update(e).digest("hex")}function d2(t){return JSON.stringify(rh(t))??"null"}function rh(t){if(Array.isArray(t))return t.map(rh);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=rh(e[r]);return n}return t}function u2(t,e){let n=0;for(let r of t)r===e&&(n+=1);return n}function I_(t,e){t.recent.push(e),t.recent.length>oh&&t.recent.shift();let n=u2(t.recent,e);return n>=l2&&!t.firedFingerprints.has(e)?(t.firedFingerprints.add(e),{fired:!0,count:n}):{fired:!1,count:n}}var l2,oh,sh=h(()=>{"use strict";l2=5,oh=20});function f2(t){if(t===null||typeof t!="object"||Array.isArray(t))return t;let e={};for(let[n,r]of Object.entries(t))p2.has(n)||(e[n]=r);return e}function Li(t){return ad({...t,input:f2(t.input)})}function m2(t){let e=t.content.split(`
|
|
267
267
|
`).find(n=>n.trim()!=="")?.trim()??"";return e.length<=C_?e:`${e.slice(0,C_)}\u2026`}var ih,p2,C_,cd,ah=h(()=>{"use strict";sh();ih=3,p2=new Set(["timeout_ms","timeoutMs","timeout"]),C_=240;cd=class{streaks=new Map;check(e){let n=this.streaks.get(Li(e));return n===void 0||n.count<ih?null:{count:n.count,tool:e.name,result:{content:`Repeat-failure guard: "${e.name}" has already failed ${n.count} times in a row with the same arguments, so this call was NOT executed again. The last failure was: ${n.lastError}
|
|
268
268
|
|
|
269
|
-
Retrying it verbatim will fail the same way. Fix the underlying cause, change the arguments, use a different tool, or stop and report the blocker.`,isError:!0,failureClass:"repeat-failure"}}}note(e,n){let r=Li(e);if(n.isError!==!0){this.streaks.delete(r);return}let o=this.streaks.get(r);this.streaks.set(r,{count:(o?.count??0)+1,lastError:m2(n)})}streakFor(e){return this.streaks.get(Li(e))?.count??0}}});async function Lo(t,e,n){let r=new Array(t.length),o=Math.min(Math.max(1,Math.floor(e)),t.length),s=0,i=[];for(let a=0;a<o;a++)i.push((async()=>{for(;s<t.length;){let c=s++;try{r[c]={status:"fulfilled",value:await n(t[c])}}catch(l){r[c]={status:"rejected",reason:l}}}})());return await Promise.all(i),r}var ld=h(()=>{"use strict";Ul()});function P_(t,e,n){if(n.has(t.name))return null;let r=e.check(t);return r===null?null:(D(`[repeat-failure-guard #723] refused ${r.tool} after ${r.count} identical failures`),r.result)}function g2(t){if(!t)return{enter:()=>{},leave:()=>{}};let e=new Set,n=()=>{try{t([...e])}catch{}};return{enter:r=>{e.add(r),n()},leave:r=>{e.delete(r),n()}}}async function h2(t,e,n,r){let{call:o,originalIndex:s}=e[t];if(o.signal.aborted)return{result:{content:"Tool call aborted",isError:!0,failureClass:Ne(o.signal)},originalIndex:s};r?.enter(o.id);try{return{result:await n(o),originalIndex:s}}finally{r?.leave(o.id)}}function y2(t,e,n,r){for(let o of t)if(o.status==="fulfilled")r[o.value.originalIndex]=o.value.result;else{let s=o.reason instanceof Error?o.reason.message:String(o.reason),i=e[t.indexOf(o)];r[n[i].originalIndex]={content:`Tool execution error: ${s}`,isError:!0}}}function M_(t,e,n){let r=t.indices.length;for(let o=0;o<t.indices.length;o++){let s=t.indices[o],i=n[e[s].originalIndex];i&&(i.batchIndex=o+1,i.batchSize=r)}}async function O_(t,e,n,r){let o=[...t.indices];for(;o.length>0;){let s=new Map,i=[],a=[];for(let u of o){let{call:p,originalIndex:f}=e[u],m=P_(p,r.repeatFailureGuard,r.repeatBreakerExemptTools);if(m){n[f]=m;continue}if(r.repeatBreakerExemptTools.has(p.name)){i.push(u);continue}let g=Li(p),y=ih-r.repeatFailureGuard.streakFor(p),b=s.get(g)??0;b<y?(s.set(g,b+1),i.push(u)):a.push(u)}o=a;let c=i.map(u=>e[u]?.call).filter(u=>u!==void 0&&u.name==="agent");if(c.length>=2&&r.subagentExecutor)try{r.subagentExecutor.notifyWaveStart(c,r.sessionId??"",null)}catch{}let l=g2(r.onActivity),d=await Lo(i,r.maxConcurrentSafeCalls,u=>h2(u,e,r.executeCore,l));y2(d,i,e,n);for(let u of i){let{call:p,originalIndex:f}=e[u],m=n[f];m!==void 0&&m.failureClass!=="abort"&&r.repeatFailureGuard.note(p,m)}if(c.length>=2&&r.subagentExecutor)try{r.subagentExecutor.notifyWaveEnd()}catch{}}}async function D_(t,e,n,r){for(let o of t.indices){let{call:s,originalIndex:i}=e[o];if(s.signal.aborted){n[i]={content:"Tool call aborted",isError:!0,failureClass:Ne(s.signal)};continue}let a=P_(s,r.repeatFailureGuard,r.repeatBreakerExemptTools);if(a){n[i]=a;continue}let c=await r.executeCore(s);n[i]=c,r.repeatFailureGuard.note(s,c)}}var F_=h(()=>{"use strict";Cn();ld();ie();ah()});function L_(t){return t==="agent"||t==="cancel_background_job"||t==="send_message_to_agent"}async function N_(t,e){if(!t)return{result:{content:e.name==="agent"?"Agent tool is not available in this session configuration":"Background mode is not available in this session configuration",isError:!0}};try{return{result:e.name==="agent"?await t.execute(e):e.name==="send_message_to_agent"?await t.sendMessageToAgent(e):await t.cancelBackgroundJob(e)}}catch(n){let r=n instanceof Error?n.message:String(n);return{result:{content:`${e.name==="agent"?"Agent":e.name==="send_message_to_agent"?"Steering":"Background cancellation"} tool error: ${r}`,isError:!0},thrownMessage:r}}}var $_=h(()=>{"use strict"});var w2,ch,Kt,dd=h(()=>{"use strict";Ul();ie();se();Cn();Kl();Xl();Dg();Ht();Dl();J();th();T_();Fi();sh();ah();F_();$_();th();w2=8,ch=new Set,Kt=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;subagentId;sessionGrantManager;traceWriter;readOnlyBash;maxOutputBytes;spawnedPidRegistry;bashOutputTailReporter;repeatBreaker=null;repeatFailureGuard=new cd;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.composeExecutor=e.composeExecutor,this.classifier=e.concurrencyClassifier??eh,this.maxConcurrentSafeCalls=typeof e.maxConcurrentSafeCalls=="number"&&Number.isFinite(e.maxConcurrentSafeCalls)&&e.maxConcurrentSafeCalls>=1?Math.floor(e.maxConcurrentSafeCalls):PE(),this.resolveBase=e.cwd,this._env=e.env,this.sessionId=e.sessionId,this.parentSessionId=e.parentSessionId,this.subagentId=e.subagentId,this.sessionGrantManager=e.sessionGrantManager,this.traceWriter=e.traceWriter,this.readOnlyBash=e.readOnlyBash===!0,this.maxOutputBytes=typeof e.maxOutputBytes=="number"&&Number.isFinite(e.maxOutputBytes)&&e.maxOutputBytes>0?e.maxOutputBytes:void 0,this._allowAll=e.allowAll===!0,this.spawnedPidRegistry=e.spawnedPidRegistry,this.bashOutputTailReporter=e.bashOutputTailReporter;let n=e.cwd?[e.cwd]:[];this._readRoots=e.readRoots??n.slice(),this._writeRoots=e.writeRoots??n.slice(),this.grantManager=new Rn({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.spawnedPidRegistry!==void 0?{spawnedPidRegistry:this.spawnedPidRegistry}:{}}}callHandlerContext(e){let n=e.name==="bash"&&this.bashOutputTailReporter!==void 0&&e.id?this.bashOutputTailReporter(e.id):void 0;return{...this.handlerContext,toolUseId:e.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{},...n!==void 0?{onBashOutputTail:n}:{}}}addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}setAllowAll(e){this._allowAll=e}setResolveBase(e){let n=this.resolveBase;if(n!==e){if(this.resolveBase=e,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=e:this._readRoots.includes(e)||this._readRoots.push(e);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=e:this._writeRoots.includes(e)||this._writeRoots.push(e)}else this._readRoots.includes(e)||this._readRoots.push(e),this._writeRoots.includes(e)||this._writeRoots.push(e);this.subagentExecutor?.setCwd(e),this.skillExecutor?.setCwd(e),this.composeExecutor?.setCwd(e)}}get toolDefs(){let e=this.subagentExecutor?.supportsBackgroundJobs?.()?this.schemas:this.schemas.filter(o=>o.name!=="cancel_background_job"&&o.name!=="send_message_to_agent"),n=this.permissions?.allowedTools;if(!n)return e;let r=new Set(n);return e.filter(o=>r.has(o.name))}denialReason(e,n){return this.isRegisteredTool(e)?n??`Tool "${e}" is not permitted`:this.unknownToolMessage(e)}isRegisteredTool(e){return this.handlers.has(e)||e==="agent"&&this.subagentExecutor!==void 0||e==="cancel_background_job"&&this.subagentExecutor?.supportsBackgroundJobs?.()===!0||e==="send_message_to_agent"&&this.subagentExecutor?.supportsBackgroundJobs?.()===!0||e==="skill"&&this.skillExecutor!==void 0||e==="compose"&&this.composeExecutor!==void 0}unknownToolMessage(e){let n=this.toolDefs.map(o=>o.name).join(", "),r=n.length>0?`Available tools: ${n}. Do NOT retry "${e}" or a variant of it; use one of the tools listed above.`:`Do NOT retry "${e}" or a variant of it.`;return`Unknown tool "${e}" \u2014 it does not exist in this session. ${r}`}async checkReadOnlyBash(e){if(!this.readOnlyBash||e.name!=="bash")return null;let n=e.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Vl(r);if(!o.mutating)return null;let s=`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff/show/ls-remote, ls, cat, find, grep, gh pr view/diff). For a remote ref you have not fetched, \`gh pr diff <n>\`, \`gh pr view <n>\` and \`git ls-remote\` need no local ref \u2014 \`git fetch\` is blocked. Do NOT retry variants of a blocked command: if the task genuinely requires a mutation, stop and report that requirement to your caller instead.`;return await this.emitPreToolUseBlock(e.name,s),{content:s,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(e,n){await dt(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:e,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(e){if(ch.has(e.name))return null;let n=v_(e);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<w2?null:{content:`Loop circuit breaker: "${e.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}checkRepeatFailureGuard(e){if(ch.has(e.name))return null;let n=this.repeatFailureGuard.check(e);return n===null?null:(D(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(e){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=R_());let n=ad(e),r=I_(this.suspectedLoopWindow,n);r.fired&&q(this.traceWriter,{phase:"suspected_loop",metadata:{tool:e.name,count:r.count,windowSize:oh}})}recordForkReadDenial(e,n,r){if(this.parentSessionId===void 0||!E_.has(e.name)||!__(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let s=A_(e);return o.deniedPaths.includes(s)||o.deniedPaths.push(s),this.denialBreaker=o,o.count<5?r:{content:x_(o.deniedPaths,o.count),isError:!0,failureClass:Fo}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(e){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(e.name,e.input??{},{signal:e.signal,toolUseID:e.id})}catch(r){let o=`Tool "${e.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(e.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${e.name}" denied by permission policy`;return await this.emitPreToolUseBlock(e.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(e.input=n.updatedInput),null}async runPreDispatchGates(e){if(this.hookRegistry){let a={event:"PreToolUse",toolName:e.name,input:e.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...e.id!==void 0?{toolUseId:e.id}:{}};try{await BE(this.hookRegistry,a,{signal:e.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof ee)return this.recordForkReadDenial(e,c.reason,{content:`Tool "${e.name}" blocked by PreToolUse hook${c.reason?`: ${c.reason}`:""}${c.injectContext?`
|
|
269
|
+
Retrying it verbatim will fail the same way. Fix the underlying cause, change the arguments, use a different tool, or stop and report the blocker.`,isError:!0,failureClass:"repeat-failure"}}}note(e,n){let r=Li(e);if(n.isError!==!0){this.streaks.delete(r);return}let o=this.streaks.get(r);this.streaks.set(r,{count:(o?.count??0)+1,lastError:m2(n)})}streakFor(e){return this.streaks.get(Li(e))?.count??0}}});async function Lo(t,e,n){let r=new Array(t.length),o=Math.min(Math.max(1,Math.floor(e)),t.length),s=0,i=[];for(let a=0;a<o;a++)i.push((async()=>{for(;s<t.length;){let c=s++;try{r[c]={status:"fulfilled",value:await n(t[c])}}catch(l){r[c]={status:"rejected",reason:l}}}})());return await Promise.all(i),r}var ld=h(()=>{"use strict";Ul()});function P_(t,e,n){if(n.has(t.name))return null;let r=e.check(t);return r===null?null:(O(`[repeat-failure-guard #723] refused ${r.tool} after ${r.count} identical failures`),r.result)}function g2(t){if(!t)return{enter:()=>{},leave:()=>{}};let e=new Set,n=()=>{try{t([...e])}catch{}};return{enter:r=>{e.add(r),n()},leave:r=>{e.delete(r),n()}}}async function h2(t,e,n,r){let{call:o,originalIndex:s}=e[t];if(o.signal.aborted)return{result:{content:"Tool call aborted",isError:!0,failureClass:Ne(o.signal)},originalIndex:s};r?.enter(o.id);try{return{result:await n(o),originalIndex:s}}finally{r?.leave(o.id)}}function y2(t,e,n,r){for(let o of t)if(o.status==="fulfilled")r[o.value.originalIndex]=o.value.result;else{let s=o.reason instanceof Error?o.reason.message:String(o.reason),i=e[t.indexOf(o)];r[n[i].originalIndex]={content:`Tool execution error: ${s}`,isError:!0}}}function M_(t,e,n){let r=t.indices.length;for(let o=0;o<t.indices.length;o++){let s=t.indices[o],i=n[e[s].originalIndex];i&&(i.batchIndex=o+1,i.batchSize=r)}}async function O_(t,e,n,r){let o=[...t.indices];for(;o.length>0;){let s=new Map,i=[],a=[];for(let u of o){let{call:p,originalIndex:f}=e[u],m=P_(p,r.repeatFailureGuard,r.repeatBreakerExemptTools);if(m){n[f]=m;continue}if(r.repeatBreakerExemptTools.has(p.name)){i.push(u);continue}let g=Li(p),y=ih-r.repeatFailureGuard.streakFor(p),b=s.get(g)??0;b<y?(s.set(g,b+1),i.push(u)):a.push(u)}o=a;let c=i.map(u=>e[u]?.call).filter(u=>u!==void 0&&u.name==="agent");if(c.length>=2&&r.subagentExecutor)try{r.subagentExecutor.notifyWaveStart(c,r.sessionId??"",null)}catch{}let l=g2(r.onActivity),d=await Lo(i,r.maxConcurrentSafeCalls,u=>h2(u,e,r.executeCore,l));y2(d,i,e,n);for(let u of i){let{call:p,originalIndex:f}=e[u],m=n[f];m!==void 0&&m.failureClass!=="abort"&&r.repeatFailureGuard.note(p,m)}if(c.length>=2&&r.subagentExecutor)try{r.subagentExecutor.notifyWaveEnd()}catch{}}}async function D_(t,e,n,r){for(let o of t.indices){let{call:s,originalIndex:i}=e[o];if(s.signal.aborted){n[i]={content:"Tool call aborted",isError:!0,failureClass:Ne(s.signal)};continue}let a=P_(s,r.repeatFailureGuard,r.repeatBreakerExemptTools);if(a){n[i]=a;continue}let c=await r.executeCore(s);n[i]=c,r.repeatFailureGuard.note(s,c)}}var F_=h(()=>{"use strict";Cn();ld();se();ah()});function L_(t){return t==="agent"||t==="cancel_background_job"||t==="send_message_to_agent"}async function N_(t,e){if(!t)return{result:{content:e.name==="agent"?"Agent tool is not available in this session configuration":"Background mode is not available in this session configuration",isError:!0}};try{return{result:e.name==="agent"?await t.execute(e):e.name==="send_message_to_agent"?await t.sendMessageToAgent(e):await t.cancelBackgroundJob(e)}}catch(n){let r=n instanceof Error?n.message:String(n);return{result:{content:`${e.name==="agent"?"Agent":e.name==="send_message_to_agent"?"Steering":"Background cancellation"} tool error: ${r}`,isError:!0},thrownMessage:r}}}var $_=h(()=>{"use strict"});var w2,ch,Kt,dd=h(()=>{"use strict";Ul();se();ie();Cn();Kl();Xl();Dg();Ht();Dl();J();th();T_();Fi();sh();ah();F_();$_();th();w2=8,ch=new Set,Kt=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;subagentId;sessionGrantManager;traceWriter;readOnlyBash;maxOutputBytes;spawnedPidRegistry;bashOutputTailReporter;repeatBreaker=null;repeatFailureGuard=new cd;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.composeExecutor=e.composeExecutor,this.classifier=e.concurrencyClassifier??eh,this.maxConcurrentSafeCalls=typeof e.maxConcurrentSafeCalls=="number"&&Number.isFinite(e.maxConcurrentSafeCalls)&&e.maxConcurrentSafeCalls>=1?Math.floor(e.maxConcurrentSafeCalls):PE(),this.resolveBase=e.cwd,this._env=e.env,this.sessionId=e.sessionId,this.parentSessionId=e.parentSessionId,this.subagentId=e.subagentId,this.sessionGrantManager=e.sessionGrantManager,this.traceWriter=e.traceWriter,this.readOnlyBash=e.readOnlyBash===!0,this.maxOutputBytes=typeof e.maxOutputBytes=="number"&&Number.isFinite(e.maxOutputBytes)&&e.maxOutputBytes>0?e.maxOutputBytes:void 0,this._allowAll=e.allowAll===!0,this.spawnedPidRegistry=e.spawnedPidRegistry,this.bashOutputTailReporter=e.bashOutputTailReporter;let n=e.cwd?[e.cwd]:[];this._readRoots=e.readRoots??n.slice(),this._writeRoots=e.writeRoots??n.slice(),this.grantManager=new Rn({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.spawnedPidRegistry!==void 0?{spawnedPidRegistry:this.spawnedPidRegistry}:{}}}callHandlerContext(e){let n=e.name==="bash"&&this.bashOutputTailReporter!==void 0&&e.id?this.bashOutputTailReporter(e.id):void 0;return{...this.handlerContext,toolUseId:e.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{},...n!==void 0?{onBashOutputTail:n}:{}}}addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}setAllowAll(e){this._allowAll=e}setResolveBase(e){let n=this.resolveBase;if(n!==e){if(this.resolveBase=e,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=e:this._readRoots.includes(e)||this._readRoots.push(e);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=e:this._writeRoots.includes(e)||this._writeRoots.push(e)}else this._readRoots.includes(e)||this._readRoots.push(e),this._writeRoots.includes(e)||this._writeRoots.push(e);this.subagentExecutor?.setCwd(e),this.skillExecutor?.setCwd(e),this.composeExecutor?.setCwd(e)}}get toolDefs(){let e=this.subagentExecutor?.supportsBackgroundJobs?.()?this.schemas:this.schemas.filter(o=>o.name!=="cancel_background_job"&&o.name!=="send_message_to_agent"),n=this.permissions?.allowedTools;if(!n)return e;let r=new Set(n);return e.filter(o=>r.has(o.name))}denialReason(e,n){return this.isRegisteredTool(e)?n??`Tool "${e}" is not permitted`:this.unknownToolMessage(e)}isRegisteredTool(e){return this.handlers.has(e)||e==="agent"&&this.subagentExecutor!==void 0||e==="cancel_background_job"&&this.subagentExecutor?.supportsBackgroundJobs?.()===!0||e==="send_message_to_agent"&&this.subagentExecutor?.supportsBackgroundJobs?.()===!0||e==="skill"&&this.skillExecutor!==void 0||e==="compose"&&this.composeExecutor!==void 0}unknownToolMessage(e){let n=this.toolDefs.map(o=>o.name).join(", "),r=n.length>0?`Available tools: ${n}. Do NOT retry "${e}" or a variant of it; use one of the tools listed above.`:`Do NOT retry "${e}" or a variant of it.`;return`Unknown tool "${e}" \u2014 it does not exist in this session. ${r}`}async checkReadOnlyBash(e){if(!this.readOnlyBash||e.name!=="bash")return null;let n=e.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Vl(r);if(!o.mutating)return null;let s=`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff/show/ls-remote, ls, cat, find, grep, gh pr view/diff). For a remote ref you have not fetched, \`gh pr diff <n>\`, \`gh pr view <n>\` and \`git ls-remote\` need no local ref \u2014 \`git fetch\` is blocked. Do NOT retry variants of a blocked command: if the task genuinely requires a mutation, stop and report that requirement to your caller instead.`;return await this.emitPreToolUseBlock(e.name,s),{content:s,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(e,n){await dt(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:e,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(e){if(ch.has(e.name))return null;let n=v_(e);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<w2?null:{content:`Loop circuit breaker: "${e.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}checkRepeatFailureGuard(e){if(ch.has(e.name))return null;let n=this.repeatFailureGuard.check(e);return n===null?null:(O(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(e){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=R_());let n=ad(e),r=I_(this.suspectedLoopWindow,n);r.fired&&q(this.traceWriter,{phase:"suspected_loop",metadata:{tool:e.name,count:r.count,windowSize:oh}})}recordForkReadDenial(e,n,r){if(this.parentSessionId===void 0||!E_.has(e.name)||!__(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let s=A_(e);return o.deniedPaths.includes(s)||o.deniedPaths.push(s),this.denialBreaker=o,o.count<5?r:{content:x_(o.deniedPaths,o.count),isError:!0,failureClass:Fo}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(e){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(e.name,e.input??{},{signal:e.signal,toolUseID:e.id})}catch(r){let o=`Tool "${e.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(e.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${e.name}" denied by permission policy`;return await this.emitPreToolUseBlock(e.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(e.input=n.updatedInput),null}async runPreDispatchGates(e){if(this.hookRegistry){let a={event:"PreToolUse",toolName:e.name,input:e.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...e.id!==void 0?{toolUseId:e.id}:{}};try{await BE(this.hookRegistry,a,{signal:e.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof ee)return this.recordForkReadDenial(e,c.reason,{content:`Tool "${e.name}" blocked by PreToolUse hook${c.reason?`: ${c.reason}`:""}${c.injectContext?`
|
|
270
270
|
|
|
271
|
-
${c.injectContext}`:""}`,isError:!0,failureClass:"hook-block"});throw c}}let n=WE(e.name,this.permissions);if(!n.allowed){let a=this.denialReason(e.name,n.reason);return await this.emitPreToolUseBlock(e.name,a),{content:a,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(e);if(r)return r;let o=await this.checkReadOnlyBash(e);if(o)return o;let s=this.checkRepeatCircuitBreaker(e);if(s)return s;let i=this.checkRepeatFailureGuard(e);return i||(this.observeSuspectedLoop(e),null)}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:Ne(e.signal)};let n=await this.runPreDispatchGates(e);if(n)return n;let r=await this.executeCore(e);return this.repeatFailureGuard.note(e,r),r.isError!==!0&&this.resetDenialBreaker(),r}async executeBatch(e,n){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let r=new Array(e.length),o=new Set;for(let c=0;c<e.length;c++){let l=e[c];if(l.signal.aborted){r[c]={content:"Tool call aborted",isError:!0,failureClass:Ne(l.signal)},o.add(c);continue}let d=await this.runPreDispatchGates(l);if(d){r[c]=d,o.add(c);continue}}let s=e.map((c,l)=>({call:c,originalIndex:l})).filter((c,l)=>!o.has(l));if(s.length===0)return r;let i=k_(s.map(c=>c.call),this.classifier),a={repeatFailureGuard:this.repeatFailureGuard,repeatBreakerExemptTools:ch,executeCore:c=>this.executeCore(c),subagentExecutor:this.subagentExecutor,sessionId:this.sessionId,maxConcurrentSafeCalls:this.maxConcurrentSafeCalls,onActivity:n};for(let c of i)c.isConcurrencySafe?await O_(c,s,r,a):await D_(c,s,r,a),M_(c,s,r);return r.some(c=>c!==void 0&&c.isError!==!0)&&this.resetDenialBreaker(),r}async executeCore(e){let n=await this.executeCoreInner(e);return this.applyOutputCap(n)}applyOutputCap(e){let n=this.maxOutputBytes;if(n===void 0)return e;let r=Buffer.byteLength(e.content,"utf8");return r<=n||(e.content=_t(e.content,n),e.truncated=!0,
|
|
271
|
+
${c.injectContext}`:""}`,isError:!0,failureClass:"hook-block"});throw c}}let n=WE(e.name,this.permissions);if(!n.allowed){let a=this.denialReason(e.name,n.reason);return await this.emitPreToolUseBlock(e.name,a),{content:a,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(e);if(r)return r;let o=await this.checkReadOnlyBash(e);if(o)return o;let s=this.checkRepeatCircuitBreaker(e);if(s)return s;let i=this.checkRepeatFailureGuard(e);return i||(this.observeSuspectedLoop(e),null)}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:Ne(e.signal)};let n=await this.runPreDispatchGates(e);if(n)return n;let r=await this.executeCore(e);return this.repeatFailureGuard.note(e,r),r.isError!==!0&&this.resetDenialBreaker(),r}async executeBatch(e,n){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let r=new Array(e.length),o=new Set;for(let c=0;c<e.length;c++){let l=e[c];if(l.signal.aborted){r[c]={content:"Tool call aborted",isError:!0,failureClass:Ne(l.signal)},o.add(c);continue}let d=await this.runPreDispatchGates(l);if(d){r[c]=d,o.add(c);continue}}let s=e.map((c,l)=>({call:c,originalIndex:l})).filter((c,l)=>!o.has(l));if(s.length===0)return r;let i=k_(s.map(c=>c.call),this.classifier),a={repeatFailureGuard:this.repeatFailureGuard,repeatBreakerExemptTools:ch,executeCore:c=>this.executeCore(c),subagentExecutor:this.subagentExecutor,sessionId:this.sessionId,maxConcurrentSafeCalls:this.maxConcurrentSafeCalls,onActivity:n};for(let c of i)c.isConcurrencySafe?await O_(c,s,r,a):await D_(c,s,r,a),M_(c,s,r);return r.some(c=>c!==void 0&&c.isError!==!0)&&this.resetDenialBreaker(),r}async executeCore(e){let n=await this.executeCoreInner(e);return this.applyOutputCap(n)}applyOutputCap(e){let n=this.maxOutputBytes;if(n===void 0)return e;let r=Buffer.byteLength(e.content,"utf8");return r<=n||(e.content=_t(e.content,n),e.truncated=!0,O(`[output-cap #661] fork tool result capped: original=${r}B capped=${Buffer.byteLength(e.content,"utf8")}B (cap=${n}B)`)),e}async executeCoreInner(e){if(L_(e.name)){let i=await N_(this.subagentExecutor,e);return i.thrownMessage!==void 0?this.firePostToolUseFailure(e.name,i.thrownMessage,e.signal,e.input):this.firePostToolUse(e.name,i.result.content,e.signal,e.input,i.result),i.result}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let i,a=!1,c="";try{i=await this.skillExecutor.execute(e)}catch(l){a=!0,c=l instanceof Error?l.message:String(l),i={content:`Skill tool error: ${c}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,c,e.signal,e.input):this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}if(e.name==="compose"){let i=await this.executeCompose(e);return this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}let n=this.handlers.get(e.name);if(!n){let i=this.unknownToolMessage(e.name);return await this.emitPreToolUseBlock(e.name,i),{content:i,isError:!0,failureClass:"permission-denied"}}let r,o=!1,s="";try{r=await n(e.input,e.signal,this.callHandlerContext(e))}catch(i){o=!0,s=i instanceof Error?i.message:String(i),r={content:`Tool execution error: ${s}`,isError:!0}}return o?this.firePostToolUseFailure(e.name,s,e.signal,e.input):this.firePostToolUse(e.name,r.content,e.signal,e.input,r),r}async executeCompose(e){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(e)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(e,n,r,o,s){if(!this.hookRegistry)return;let i={event:"PostToolUse",toolName:e,output:n,...o!==void 0?{input:o}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager?{grantManager:this.sessionGrantManager}:{},...s?.isError===!0?{isError:!0}:{},...s?.incomplete===!0?{incomplete:!0,...s.incompleteReason?{incompleteReason:s.incompleteReason}:{}}:{}};jE(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(e,n,r,o){if(!this.hookRegistry)return;let s={event:"PostToolUseFailure",toolName:e,error:n,...o!==void 0?{input:o}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};HE(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(i=>{O(`firePostToolUseFailure outer catch (tool=${e}): ${String(i)}`)})}}});import{mkdir as S2,writeFile as k2}from"fs/promises";import{dirname as v2,join as T2}from"path";function E2(){return T2(vt(),"routing-decisions.jsonl")}function _2(t){let e={surface:"afk"};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}async function ne(t){if(!(k.VITEST||k.NODE_ENV==="test"))try{let e=E2();await S2(v2(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,..._2(t)})+`
|
|
272
272
|
`;await k2(e,r,{flag:"a"})}catch{}}var Rt=h(()=>{"use strict";F();B()});function L2(t){let e=t.match(A2);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function N2(t){let e=t.match(x2);if(!e)return null;let n=parseInt(e[1]??"0",10);return{runner:"jest",passed:parseInt(e[2]??"0",10),failed:n}}function $2(t){let e=t.match(R2);if(!e)return null;if(e[2]!==void 0){let n=parseInt(e[2],10),r=parseInt(e[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return e[4]!==void 0?{runner:"pytest",passed:parseInt(e[4],10),failed:0}:null}function U2(t){let e=t.match(I2);if(!e)return null;let n=parseInt(e[1]??"0",10),r=t.match(C2),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function B2(t){let e=[...t.matchAll(P2)];if(e.length===0)return null;let n=0,r=0;for(let o of e)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function j2(t){let e=t.match(M2);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function H2(t){let e=t.match(O2);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function W2(t){let e=t.match(D2);if(e)return{runner:"phpunit",passed:parseInt(e[1]??"0",10),failed:0};let n=t.match(F2);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function Ni(t){return L2(t)??N2(t)??$2(t)??U2(t)??B2(t)??j2(t)??H2(t)??W2(t)??null}var A2,x2,R2,I2,C2,P2,M2,O2,D2,F2,lh=h(()=>{"use strict";A2=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,x2=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,R2=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,I2=/(\d+)\s+passing/,C2=/(\d+)\s+failing/,P2=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,M2=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,O2=/(\d+) examples?, (\d+) failures?/,D2=/OK \((\d+) tests?/,F2=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});import{statSync as K2}from"node:fs";function $i(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.code==="ENOENT"&&typeof e.syscall=="string"&&e.syscall.startsWith("spawn")}function q2(t){if(t===void 0)return!1;try{return K2(t),!1}catch{return!0}}function No(t,e){let n=t instanceof Error?t.message:typeof t?.message=="string"?String(t.message):String(t);return $i(t)&&q2(e)?`working directory does not exist: ${e} (deleted worktree?) \u2014 underlying: ${n}`:n}var dh=h(()=>{"use strict"});function qt(t){let e=t instanceof Error?t.message:String(t);U_.has(e)||(U_.add(e),console.warn(`[afk-home] Malformed AFK home/state env var ignored while deriving the credential floor: ${e}. The relocated tree is NOT protected \u2014 the default ~/.afk entries still apply. Fix the env var to restore coverage.`))}var U_,Ui=h(()=>{"use strict";U_=new Set});import{statSync as ph}from"node:fs";import{homedir as G2}from"node:os";import{basename as X2,dirname as j_,join as z2}from"node:path";function H_(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function J2(t){let e=X2(t),n=e===e.toLowerCase()?e.toUpperCase():e.toLowerCase();if(n===e)return;let r;try{r=ph(t)}catch{return}let o=uh.get(r.dev);if(o!==void 0)return o;try{let s=ph(z2(j_(t),n)),i=r.dev===s.dev&&r.ino===s.ino;return uh.set(r.dev,i),i}catch(s){let i=H_(s);return i==="ENOENT"||i==="ENOTDIR"?(uh.set(r.dev,!1),!1):void 0}}function W_(t=G2()){if(B_!==void 0)return B_;let e=t;for(;;)try{return ph(e),J2(e)??!0}catch(n){let r=H_(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=j_(e);if(o===e)return!0;e=o}}function $o(t,e,n=e){if(t===e||t.startsWith(e+"/")||t.startsWith(e+"\\"))return!0;if(!W_(n))return!1;let r=t.toLowerCase(),o=e.toLowerCase();return r===o||r.startsWith(o+"/")||r.startsWith(o+"\\")}function ud(t,e){return t.includes(e)?!0:W_(e)?t.toLowerCase().includes(e.toLowerCase()):!1}var B_,uh,pd=h(()=>{"use strict";uh=new Map});import{realpathSync as K_}from"fs";import{dirname as V2,resolve as xr,join as md}from"path";import{homedir as pt}from"os";function Q2(){let t=[];try{let e=oe();t.push(xr(md(e,"config"))),t.push(xr(md(e,"state")))}catch(e){qt(e)}try{t.push(xr(te()))}catch(e){qt(e)}return t}function fh(){let t=`${k.AFK_WRITE_DENYLIST??""}\0${k.AFK_HOME??""}\0${k.AFK_STATE_DIR??""}`;if(!fd||fd.key!==t){let e=k.AFK_WRITE_DENYLIST,n=process.platform==="win32"?";":":",r=e?e.split(n).map(o=>o.trim()).filter(Boolean).map(o=>o==="~"||o.startsWith("~/")||o.startsWith("~\\")?md(pt(),o.slice(2)):o).map(o=>xr(o)).filter(Boolean):[];fd={key:t,unresolved:[...new Set([...Y2.map(o=>xr(o)),...Q2()]),...r]}}return[...new Set(fd.unresolved.map(e=>Be(e)))]}function Be(t){let e=xr(t);try{return K_(e)}catch{}let n=[],r=e;for(let o=0;o<64;o++){let s=V2(r);if(s===r)break;n.unshift(r.slice(s.length+1)),r=s;try{let i=K_(r);return md(i,...n)}catch{}}return e}function Uo(t,e="write_file"){let n=Be(xr(t));for(let r of fh())if($o(n,r))throw new Error(`${e}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}var Y2,fd,Rr=h(()=>{"use strict";F();B();Ui();pd();Y2=[`${pt()}/.ssh`,`${pt()}/.aws`,`${pt()}/.gnupg`,`${pt()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${pt()}/.afk/config`,`${pt()}/.afk/state`,`${pt()}/.npmrc`,`${pt()}/.docker/config.json`,`${pt()}/Library/LaunchAgents`,`${pt()}/Library/LaunchDaemons`,"/Library/LaunchAgents","/Library/LaunchDaemons",`${pt()}/.config/systemd`,...process.platform==="win32"&&k.APPDATA?[`${k.APPDATA}\\gcloud`,`${k.APPDATA}\\Docker`]:[],...process.platform==="win32"&&k.USERPROFILE?[`${k.USERPROFILE}\\.ssh`,`${k.USERPROFILE}\\.aws`,`${k.USERPROFILE}\\.gnupg`]:[]]});import{isAbsolute as Z2,relative as eX,sep as tX}from"node:path";import{homedir as gd}from"node:os";function nX(t,e){let n=eX(e,t);return n===""||n!==".."&&!n.startsWith(`..${tX}`)&&!Z2(n)}function mh(t,e){return t.filter(n=>!e.some(r=>nX(n,r)))}function rX(t,e){return t.filter(({source:n})=>n!==e).map(({root:n})=>n)}function q_(t,e){return t.flatMap(({rel:n,resolved:r})=>mh([r],rX(e,oX[n])))}var oX,G_=h(()=>{"use strict";oX={".afk/config/mcp.json":`${gd()}/.afk/config`,".afk/config/schedules.json":`${gd()}/.afk/config`,".ssh/config":`${gd()}/.ssh`,".ssh/known_hosts":`${gd()}/.ssh`}});import{isAbsolute as Efe,resolve as sX}from"path";import{homedir as X_}from"os";function Bo(t){return t==="~"?X_():t.startsWith("~/")?sX(X_(),t.slice(2)):t}var gh=h(()=>{"use strict"});import{basename as iX,dirname as aX,join as hd,relative as cX,resolve as jo,sep as Bi}from"path";import{homedir as pe}from"os";function J_(t){let e=jo(t);return hd(Be(aX(e)),iX(e))}function yh(t){if(!t)return[];let e=process.platform==="win32"?";":":";return t.split(e).map(n=>n.trim()).filter(Boolean).map(n=>n==="~"||n.startsWith("~/")||n.startsWith("~\\")?Bo(n.replace(/^~[/\\]+/,"~/")):n).map(n=>jo(n))}function dX(){try{return[Be(jo(hd(oe(),"config")))]}catch(t){return qt(t),[]}}function uX(){try{let t=oe();return Ir.filter(e=>e.startsWith(z_)).map(e=>J_(hd(t,e.slice(z_.length))))}catch(t){return qt(t),[]}}function V_(){let t=`${k.AFK_READ_DENYLIST??""}\0${k.AFK_HOME??""}`;if(ji&&ji.key===t)return ji;let e=yh(k.AFK_READ_DENYLIST).map(i=>Be(i)).filter(Boolean),n=hh.map(i=>({source:i,root:Be(jo(i))})),r=dX(),o=[...new Set([...n.map(({root:i})=>i),...r])],s=n.filter(({source:i,root:a})=>i!==lX||!r.includes(a)).map(({root:i})=>i);return ji={key:t,builtins:o,extras:e,allow:[...new Set([...q_(Ir.map(i=>({rel:i,resolved:J_(`${pe()}/${i}`)})),n),...mh(uX(),s)])]},ji}function bh(){let{builtins:t,extras:e}=V_();return[...t,...e]}function Y_(t){let e=Be(jo(t));return bh().filter(n=>n!==e&&$o(n,e,n)).map(n=>(n.startsWith(e+Bi)?cX(e,n):n.split(Bi).slice(e.split(Bi).length).join(Bi)).split(Bi).join("/"))}function ft(t){let e=Be(jo(t)),{builtins:n,extras:r,allow:o}=V_();for(let s of r)if($o(e,s))return{denied:!0,matched:s};if(o.includes(e))return{denied:!1};for(let s of n)if($o(e,s))return{denied:!0,matched:s};return{denied:!1}}var hh,Ir,lX,Lfe,ji,z_,Ho,yd,Pn=h(()=>{"use strict";F();Rr();B();Ui();G_();pd();gh();hh=[`${pe()}/.ssh`,`${pe()}/.aws`,`${pe()}/.gnupg`,`${pe()}/.config/gcloud`,`${pe()}/.afk/config`,`${pe()}/.npmrc`,`${pe()}/.docker/config.json`,`${pe()}/.git-credentials`,`${pe()}/.netrc`,`${pe()}/.config/gh/hosts.yml`,`${pe()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${pe()}/.password-store`,`${pe()}/Library/Application Support/Google/Chrome`,`${pe()}/Library/Application Support/Chromium`,`${pe()}/Library/Application Support/BraveSoftware`,`${pe()}/Library/Application Support/Microsoft Edge`,`${pe()}/Library/Application Support/Arc`,`${pe()}/Library/Application Support/Firefox`,...process.platform==="win32"&&k.USERPROFILE?[`${k.USERPROFILE}\\.ssh`,`${k.USERPROFILE}\\.aws`,`${k.USERPROFILE}\\.gnupg`]:[],...process.platform==="win32"&&k.APPDATA?[`${k.APPDATA}\\gcloud`,`${k.APPDATA}\\Docker`,`${k.APPDATA}\\Mozilla\\Firefox`]:[],...process.platform==="win32"&&k.LOCALAPPDATA?[`${k.LOCALAPPDATA}\\Google\\Chrome`,`${k.LOCALAPPDATA}\\Chromium`,`${k.LOCALAPPDATA}\\BraveSoftware`,`${k.LOCALAPPDATA}\\Microsoft\\Edge`]:[]],Ir=[".afk/config/mcp.json",".afk/config/schedules.json",".ssh/config",".ssh/known_hosts"],lX=`${pe()}/.afk/config`,Lfe=Ir.map(t=>hd(pe(),t));z_=".afk/";Ho="read-denylist entry:",yd="is a protected credential/secret path"});import Cr from"path";import{realpathSync as pX}from"fs";function je(t){try{return pX.native(t)}catch{let e=Cr.dirname(t),n=Cr.basename(t);return e===t?t:Cr.join(je(e),n)}}function fX(t){let e=Q_.get(t);if(e!==void 0)return e;let n=je(t);return Q_.set(t,n),n}function Z_(t,e,n,r){let o=e?.resolveBase??e?.cwd??r,s=Cr.isAbsolute(t)?t:Cr.resolve(o??process.cwd(),t);if(e?.allowAll===!0)return{restricted:!1,resolved:s,roots:[]};if(o===void 0)return{restricted:!1,resolved:s,roots:[]};let i=je(s),a=n==="read"?e?.readRoots??[o]:e?.writeRoots??[o];for(let c of a){let l=fX(c),d=Cr.relative(l,i);if(!d.startsWith("..")&&!Cr.isAbsolute(d))return{restricted:!1,resolved:s,roots:a}}return{restricted:!0,resolved:s,roots:a}}function de(t,e,n="read",r){let{restricted:o,resolved:s,roots:i}=Z_(t,e,n,r);if(n==="read"){let a=ft(s);if(a.denied)throw new Error(`Path \`${t}\` ${yd} (${Ho} \`${a.matched}\`) and cannot be read.`)}if(o){let a=i.map(l=>`\`${l}\``).join(", "),c=n==="read"?"read roots":"write roots";throw new Error(`Path \`${t}\` is outside the allowed ${c} [${a}].`)}return s}function Hi(t,e,n="read",r){return Z_(t,e,n,r)}function eA(t){let e=new Set,n=[];for(let r of t.split(/\s+/)){if(r.length===0)continue;let o=r.replace(/^\d*[<>|&]+/,"").replace(/^['"]/,"").replace(/['";,)]+$/,"");if(o.length===0)continue;let s=o.startsWith("/"),i=o==="~"||o.startsWith("~/");!s&&!i||e.has(o)||(e.add(o),n.push(o))}return n}var Q_,Ae=h(()=>{"use strict";Pn();Q_=new Map});import{execFileSync as mX}from"node:child_process";function cn(t,e="SIGKILL"){if(!(t<=0))try{process.platform==="win32"?mX("taskkill",["/F","/T","/PID",String(t)],{stdio:"ignore",timeout:5e3}):process.kill(-t,e)}catch{}}var bd=h(()=>{"use strict"});import{mkdirSync as gX,openSync as hX,writeSync as yX,closeSync as bX}from"fs";function wh(t,e,n){try{let r=Cm(t);if(r===void 0)return;gX(r,{recursive:!0,mode:448});let o=e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,128)||"capture",s=`${r}/${o}.txt`,i=Buffer.from(n,"utf8"),a=i.length<=tA?i:i.subarray(0,tA),c=hX(s,"wx",384);try{yX(c,a)}finally{bX(c)}return s}catch{return}}var tA,nA=h(()=>{"use strict";B();tA=8e6});var wX,SX,wd,rA=h(()=>{"use strict";et();wX=5,SX=300,wd=class{constructor(e,n=wX,r=SX){this.onChange=e;this.maxLines=n;this.throttleMs=r}onChange;maxLines;throttleMs;lines=[];lastNotifiedAt=0;pendingFlush;cleared=!1;atLineBoundary=!0;push(e){if(this.cleared||e.length===0)return;let n=e.split(`
|
|
273
273
|
`);for(let r=0;r<n.length;r++){let s=n[r].split("\r"),i=s[s.length-1];if(r===0){if(this.atLineBoundary||this.lines.length===0)i.length>0&&this.lines.push(i);else{let a=this.lines[this.lines.length-1];this.lines[this.lines.length-1]=s.length>1?i:a+i}i.length>0&&(this.atLineBoundary=!1)}else{if(this.lines.length>0){let a=Q(this.lines[this.lines.length-1]);a.length>0?this.lines[this.lines.length-1]=a:this.lines.pop()}i.length>0?(this.lines.push(i),this.atLineBoundary=!1):this.atLineBoundary=!0}}this.lines.length>this.maxLines&&(this.lines=this.lines.slice(this.lines.length-this.maxLines)),this.scheduleNotify()}peek(){if(!(this.cleared||this.lines.length===0))return this.lines.map(e=>Q(e)).filter(e=>e.length>0).join(`
|
|
274
274
|
`)||void 0}clear(){this.cleared||(this.cleared=!0,this.lines=[],this.pendingFlush!==void 0&&(clearTimeout(this.pendingFlush),this.pendingFlush=void 0),this.onChange(void 0))}scheduleNotify(){let e=Date.now(),n=e-this.lastNotifiedAt;if(n>=this.throttleMs)this.lastNotifiedAt=e,this.pendingFlush!==void 0&&(clearTimeout(this.pendingFlush),this.pendingFlush=void 0),this.fireNotify();else if(this.pendingFlush===void 0){let r=this.throttleMs-n;this.pendingFlush=setTimeout(()=>{this.pendingFlush=void 0,!this.cleared&&(this.lastNotifiedAt=Date.now(),this.fireNotify())},r),typeof this.pendingFlush=="object"&&"unref"in this.pendingFlush&&this.pendingFlush.unref()}}fireNotify(){let e=this.peek();!this.cleared&&e===void 0||this.onChange(e)}}});import{spawn as oA}from"child_process";import kX from"os";function vX(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(e.timeout_ms<0||e.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=e.timeout_ms}return{command:e.command,timeout_ms:n}}function Sd(t,e){let n=!1,r=!1;function o(){n||t==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}function s(i,a){if(r)return;let c=a.resolveBase??a.cwd??e,l=kX.homedir(),d=[];for(let u of eA(i)){let p=u==="~"?l:u.startsWith("~/")?l+u.slice(1):u,f=Hi(p,a,"write",c);f.restricted&&d.push(f.resolved)}d.length!==0&&(r=!0,console.warn(`[security] bash: command references path(s) outside writeRoots: ${d.join(", ")} \u2014 bash containment is best-effort (tracked C4); use file tools for contained writes.`),ne({event:"tool.bash_path_escape",tool:"bash",restricted_count:d.length,mode:"write"}))}return async(i,a,c)=>{let{command:l,timeout_ms:d}=vX(i);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),c!==void 0)try{s(l,c)}catch{}let u=Date.now();return new Promise(p=>{let f=!1,m=c?.onBashOutputTail!==void 0?new wd(E=>{try{c.onBashOutputTail(E)}catch{}}):void 0;function g(E){f||(f=!0,clearTimeout(_),a.removeEventListener("abort",R),m?.clear(),p(E))}let y=process.platform==="win32",b=Yl(),w={detached:!y,stdio:["ignore","pipe","pipe"],...(c?.resolveBase??c?.cwd??e)!==void 0?{cwd:c?.resolveBase??c?.cwd??e}:{},...c?.env!==void 0?{env:{...process.env,...c.env}}:{}},v=b.shell===!0?oA(l,{shell:!0,...w}):oA(b.shell,[...b.args??[],l],w);v.unref(),c?.spawnedPidRegistry!==void 0&&v.pid!==void 0&&c.spawnedPidRegistry.register(v.pid);let _=setTimeout(()=>{v.pid!==void 0&&cn(v.pid),g({content:`Command timed out after ${d}ms`,isError:!0,durationMs:Date.now()-u})},d),x="",A="",I=0,C=!1;function T(E){if(C||f||I<8e6)return;C=!0,console.warn(`[bash] overflow kill: stream=${E} totalBytes=${I} command="${l}"`),ne({event:"tool.overflow_kill",tool:"bash",total_bytes:I,stream:E}),v.kill("SIGKILL");let P=ve((x+A).trimEnd()),H=Ni(P)??void 0,M=_t(P,1e5)+YE;g({content:M,truncated:!0,durationMs:Date.now()-u,...H!==void 0?{testResult:H}:{}})}v.stdout.on("data",E=>{let P=8e6-I,H=E.length<=P?E:E.subarray(0,Math.max(0,P));I+=H.length;let M=H.toString("utf8");x+=M,m?.push(M),T("stdout")}),v.stderr.on("data",E=>{let P=8e6-I,H=E.length<=P?E:E.subarray(0,Math.max(0,P));I+=H.length;let M=H.toString("utf8");A+=M,m?.push(M),T("stderr")});let R=()=>{v.pid!==void 0&&cn(v.pid),g({content:"Command aborted",isError:!0,durationMs:Date.now()-u})};a.addEventListener("abort",R),a.aborted&&R(),v.on("close",E=>{if(a.aborted){g({content:"Command aborted",isError:!0,durationMs:Date.now()-u});return}if(E!==null&&E!==0){let U=A.trimEnd()||x.trimEnd(),j=Tr(U),K=Date.now()-u,Y=j.truncated?wh(c?.sessionId,c?.toolUseId??"",U):void 0;g({content:`Command exited with code ${E}${j.content?`
|
|
@@ -313,7 +313,7 @@ ${o.text}`)}return n.join(`
|
|
|
313
313
|
`)}return n.accessToken}function BA(){if(process.platform==="darwin")try{return LA("security",["find-generic-password","-s","Claude Code-credentials","-a",$A().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=UA(NA(),".claude",".credentials.json");if(!fz(t))return;try{return mz(t,"utf-8")}catch{return}}}function jA(t){let e;try{e=JSON.parse(t)}catch{return}if(typeof e!="object"||e===null)return;let n=e.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let s={accessToken:o},i=r.refreshToken;typeof i=="string"&&i.length>0&&(s.refreshToken=i);let a=r.expiresAt;return typeof a=="number"&&(s.expiresAt=a),s}async function Sz(t){try{let e=await fetch(yz,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:hz}),signal:AbortSignal.timeout(wz)});if(!e.ok)return;let n=await e.json(),r=n.access_token,o=n.expires_in;if(typeof r!="string"||typeof o!="number")return;let s=n.refresh_token;return{accessToken:r,expiresAt:Date.now()+o*1e3,...typeof s=="string"&&s.length>0?{refreshToken:s}:{}}}catch{return}}function Ko(t){if(!t||t.length<3)return"token:(unknown)";try{let n=t.split(".");if(n.length<2)throw new Error("not a JWT");let r=Buffer.from(n[1],"base64url").toString("utf-8"),o=JSON.parse(r),s=typeof o.email=="string"&&o.email||typeof o.sub=="string"&&o.sub||typeof o.account_id=="string"&&o.account_id||typeof o.preferred_username=="string"&&o.preferred_username;if(s)return s}catch{}return`token:${t.length>=8?t.slice(-8):t}`}function kz(t){if(process.platform==="darwin")LA("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",$A().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=UA(NA(),".claude",".credentials.json");vz(e,t)}}function vz(t,e){gz(t,e,{encoding:"utf-8",mode:384})}var hz,yz,bz,wz,qo=h(()=>{"use strict";hz="9d1c250a-e61b-44d9-88ed-5944d1962f5e",yz="https://platform.claude.com/v1/oauth/token",bz=300*1e3,wz=1e4});function zi(){return k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN||HA||Xe()}async function WA(t){if(t!=="anthropic-direct"||k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN)return;let e=await Xi();return e&&(HA=e),e}function Td(){return k.OPENAI_API_KEY||k.CODEX_API_KEY||void 0}function Mh(){let t=k.XAI_API_KEY;return t&&t.length>0?t:void 0}function re(t,e){let n=z(t,e);return n==="openai-compatible"||n==="openai-codex"?Td():n==="xai"||n==="xai-oauth"?Mh():zi()}var HA,be=h(()=>{"use strict";fe();qo();F()});import{existsSync as Tz,readFileSync as Ez}from"fs";import{join as _z}from"path";import{config as Az,parse as xz}from"dotenv";function Go(){return zi()}function XA(t){let e=t.trim();if(!e)return e;let n="/chat/completions";if(e.endsWith(n)){let r=e.slice(0,-n.length);return qA.has(e)||(qA.add(e),console.warn(`[afk] AFK_OPENAI_BASE_URL: stripped trailing "/chat/completions" \u2014 the OpenAI SDK appends it automatically.
|
|
314
314
|
Effective base URL: ${r}`)),r}return e}function Rz(t){let e;try{e=xz(Ez(t))}catch{return[]}let n=[];for(let r of Object.keys(e)){let o=process.env[r];if(o!==void 0&&o.trim()===""){if((e[r]??"").trim()==="")continue;delete process.env[r],n.push(r)}}return n}function zA(){if(Oh!==void 0)return Oh;if(!KA){let o=[_z(process.cwd(),".env"),ar(),Dv()];for(let s of o)if(Tz(s)){let i=Rz(s);Az({path:s,override:!1});for(let a of i)GA.has(a)||(GA.add(a),console.warn(`[afk] ${a} is set to an empty value in your shell environment; using the value from ${s} instead.
|
|
315
315
|
Remove the blank \`export ${a}=""\` from your shell profile to silence this.`))}KA=!0}let t={},e=k.AFK_MODEL??k.CLAUDE_MODEL;if(e){let o=e.toLowerCase();t.model=gi(o)?o:e}if(z(e)==="anthropic-direct"){let o=Go();o!==void 0&&(t.apiKey=o)}let r=k.AFK_LOCAL_BASE_URL;if(r&&r.length>0&&(t.baseUrl=r,t.apiKey=k.AFK_LOCAL_API_KEY||"local"),k.AFK_MAX_TOKENS){let o=Number(k.AFK_MAX_TOKENS);Number.isInteger(o)&&(t.maxTokens=o)}if(k.AFK_TEMPERATURE){let o=Number(k.AFK_TEMPERATURE);Number.isFinite(o)&&(t.temperature=o)}if(k.AFK_SYSTEM_PROMPT&&(t.systemPrompt=k.AFK_SYSTEM_PROMPT),k.AFK_AUTO_ROUTING){let o=k.AFK_AUTO_ROUTING.toLowerCase()==="true";t.autoRouting={interactive:o,chat:o,telegram:o,daemon:o}}return k.AFK_OPENAI_BASE_URL&&(t.openaiBaseUrl=XA(k.AFK_OPENAI_BASE_URL)),Oh=t,t}var KA,Oh,qA,GA,Dh=h(()=>{"use strict";lt();fe();B();be();F();KA=!1;qA=new Set;GA=new Set});import{join as Iz}from"path";function JA(){return[{tier:"project",path:Iz(process.cwd(),"afk.config.json")},{tier:"user",path:on()},{tier:"legacy",path:Xc()}]}var VA=h(()=>{"use strict";B()});var Fh=h(()=>{"use strict";F();B()});var YA=h(()=>{"use strict";F();Fh()});function Dz(t){let e=t.replace(/\\/g,"/").replace(/^\.\//,"");return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function QA(t){let e=t.replace(/\/+$/,""),n=e.lastIndexOf("/");return n===-1?e:e.slice(n+1)}function Lz(t,e){return!Mz.test(e)||Fz.some(n=>n.test(t))?!1:ZA.some(n=>n.test(t))||ex.some(n=>n.test(t))}function Nz(t){return Cz.some(e=>e.test(t))}function On(t){let e=Dz(t);if(e==="")return"protected";let n=QA(e).toLowerCase();return Nz(n)||!Lz(e,n)&&Pz.some(o=>o.test(n))?"protected":!e.endsWith("/")&&Oz.some(o=>o.test(QA(e)))||ZA.some(o=>o.test(e))?"opaque":ex.some(o=>o.test(e))?"inspectable":"protected"}var Cz,Pz,Mz,ZA,ex,Oz,Fz,Ed=h(()=>{"use strict";Cz=[/\.env$/,/^\.env\./,/\.pem$/,/\.key$/,/\.p12$/,/\.keystore$/,/\.jks$/,/^id_rsa/,/^id_ed25519/,/^\.netrc$/,/\.sqlite3?$/,/\.db$/],Pz=[/credential/,/secret/],Mz=/\.(?:js|mjs|cjs|jsx|ts|tsx|mts|cts|map|html?|css|svg)$/,ZA=[/(?:^|\/)node_modules\//,/(?:^|\/)\.pnpm(-store)?\//,/(?:^|\/)\.yarn\//,/(?:^|\/)bower_components\//,/(?:^|\/)vendor\/bundle\//,/(?:^|\/)\.venv\//,/(?:^|\/)venv\//,/(?:^|\/)__pycache__\//,/(?:^|\/)\.turbo\//,/(?:^|\/)\.parcel-cache\//,/(?:^|\/)\.vite\//,/(?:^|\/)\.cache\//,/(?:^|\/)\.gradle\//,/(?:^|\/)\.pytest_cache\//,/(?:^|\/)\.mypy_cache\//,/(?:^|\/)\.ruff_cache\//,/(?:^|\/)\.nyc_output\//],ex=[/(?:^|\/)dist\//,/(?:^|\/)build\//,/(?:^|\/)out\//,/(?:^|\/)lib-cov\//,/(?:^|\/)\.next\//,/(?:^|\/)\.nuxt\//,/(?:^|\/)\.svelte-kit\//,/(?:^|\/)\.output\//,/(?:^|\/)target\//,/(?:^|\/)coverage\//,/(?:^|\/)logs\//],Oz=[/^\.afk-worktree-meta\.json$/,/\.tsbuildinfo$/,/^\.eslintcache$/,/^\.stylelintcache$/,/^\.DS_Store$/,/^debug\.log$/,/^npm-debug\.log$/,/^yarn-error\.log$/,/^yarn-debug\.log$/,/^pnpm-debug\.log$/,/^lerna-debug\.log$/];Fz=[/(?:^|\/)logs\//]});import{stat as $z}from"node:fs/promises";import{join as Uz}from"node:path";async function tx(t,e){let n=On(e);if(n!=="protected"||e.endsWith("/"))return{verdict:n,resolvedEntry:e};try{if((await $z(Uz(t,e))).isDirectory()){let o=`${e}/`;return{verdict:On(o),resolvedEntry:o}}}catch{}return{verdict:n,resolvedEntry:e}}async function nx(t,e,n){let r=[...Bz,"-C",e,"status","--porcelain","--ignored"];n!==void 0&&r.push("--untracked-files=all","--",n);try{let{stdout:o}=await t("git",r,jz);return{entries:o.split(`
|
|
316
|
-
`).filter(s=>s.startsWith("!!")).map(s=>s.slice(2).trim()).filter(s=>s!=="")}}catch(o){let s=o instanceof Error?o.message:String(o);return{failure:n===void 0?s:`expanding ${n}: ${s}`}}}async function Hz(t,e,n){let r=await nx(t,e,n);if("failure"in r)return{protect:!0,because:"git-failed",detail:r.failure};for(let o of r.entries){if(o===n)continue;let{verdict:s}=await tx(e,o);if(s==="protected")return{protect:!0,because:"non-rebuildable-entry",detail:o}}return{protect:!1}}async function _d(t,e){let n=await nx(t,e);if("failure"in n)return{protect:!0,because:"git-failed",detail:n.failure};for(let r of n.entries){let{verdict:o,resolvedEntry:s}=await tx(e,r);if(o==="protected")return{protect:!0,because:"non-rebuildable-entry",detail:r};if(o==="inspectable"&&s.endsWith("/")){let i=await Hz(t,e,s);if(i.protect)return i}}return{protect:!1}}async function rx(t,e){return(await _d(t,e)).protect}var Bz,jz,Ad=h(()=>{"use strict";Ed();Ed();Bz=["-c","core.quotePath=false"],jz={maxBuffer:64*1024*1024,timeout:1e4}});var ox=h(()=>{"use strict";ie()});import{promises as Wz}from"node:fs";import{resolve as Kz}from"node:path";async function sx(t){let e=Kz(t);try{return await Wz.realpath(e)}catch{return e}}var ix=h(()=>{"use strict"});import{promises as Gt}from"node:fs";import{setTimeout as qz}from"node:timers/promises";import{dirname as cx,isAbsolute as Gz,resolve as Xz}from"node:path";function Vz(t){try{let e=JSON.parse(t);return e.version!==lx?[]:Array.isArray(e.roots)?e.roots.filter(n=>typeof n=="object"&&n!==null&&typeof n.path=="string"&&n.path.length>0&&Gz(n.path)):[]}catch{return[]}}async function Yz(){try{return Vz(await Gt.readFile(Gc(),"utf-8"))}catch{return[]}}function Qz(t){let e=ax.then(t,t).catch(()=>{});return ax=e,e}async function Zz(t){try{let e=Number.parseInt((await Gt.readFile(t,"utf-8")).trim(),10);if(Number.isInteger(e)&&e>0){process.kill(e,0);return}}catch{}await Gt.unlink(t).catch(()=>{})}async function eJ(t){let e=Date.now()+zz;for(;;)try{let n=await Gt.open(t,"wx",dx);return await n.writeFile(String(process.pid),"utf-8"),await n.close(),async()=>{await Gt.unlink(t).catch(()=>{})}}catch(n){if(n.code!=="EEXIST"||Date.now()>=e)return null;await Zz(t),await qz(Jz)}}async function tJ(t){let e=Gc();await Gt.mkdir(cx(e),{recursive:!0,mode:ux});let n={version:lx,roots:t},r=`${e}.tmp-${process.pid}-${Date.now()}`;try{await Gt.writeFile(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:dx}),await Gt.rename(r,e)}catch(o){throw await Gt.rm(r,{force:!0}).catch(()=>{}),o}}async function nJ(t){await Qz(async()=>{let e=Gc();await Gt.mkdir(cx(e),{recursive:!0,mode:ux}).catch(()=>{});let n=await eJ(`${e}.lock`);try{await tJ(t(await Yz()))}catch{}finally{n!==null&&await n()}})}function rJ(t){if(t.length<=xd)return t;t=[...t].sort((n,r)=>n.lastSeenAt.localeCompare(r.lastSeenAt));let e=t.slice(0,t.length-xd);return D(`[worktree-root-registry] cap ${xd} reached \u2014 evicting ${e.length} least-recently-seen root(s); their managed worktrees will no longer be swept: `+e.map(n=>n.path).join(", ")),t.slice(-xd)}async function Lh(t){if(t==="")return;let e=await sx(t),n=new Date().toISOString();await nJ(r=>{let o=r.filter(s=>Xz(s.path)!==e);return rJ([...o,{path:e,lastSeenAt:n}])})}var lx,xd,dx,ux,zz,Jz,ax,Nh=h(()=>{"use strict";B();ie();ox();ix();lx=1,xd=64,dx=384,ux=448,zz=2e3,Jz=25;ax=Promise.resolve()});import{execFile as oJ}from"node:child_process";import{promisify as sJ}from"node:util";function fx(t,e){if(t.length>px)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${px}.`);if(!iJ.test(t))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 only [A-Za-z0-9_-./] are allowed.`);if(t.startsWith("-"))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);return t}function mx(t,e){if(t.trim().length===0)throw new Error(`Invalid worktree base ref from ${e}: '' \u2014 base ref cannot be empty.`);if(t.startsWith("-"))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(t.includes("\0"))throw new Error(`Invalid worktree base ref from ${e}: contains a NUL byte.`);if(/\s/.test(t))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not contain whitespace.`)}var mhe,iJ,px,gx=h(()=>{"use strict";F();Fh();YA();Ad();Nh();mhe=sJ(oJ),iJ=/^[A-Za-z0-9_\-./]*$/,px=64});import{existsSync as Vi,readdirSync as yhe,readFileSync as hx,realpathSync as bhe,statSync as whe}from"fs";import{homedir as yx}from"os";import{join as ln,basename as vhe}from"path";function $h(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of bx){let r=t[n];if(r!==void 0){if(r===!0){e[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;e[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(e).length>0?e:void 0}function Uh(){return[on(),Xc()]}function Yi(t=Uh()){for(let e of t)if(Vi(e))try{let n=JSON.parse(hx(e,"utf-8")),r=$h(n.importFrom);if(r!==void 0)return r}catch{}}function Qi(t,e=yx()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!t)return n;for(let r of bx){let o=t[r];if(!o)continue;let s=Rd[r];if(o.plugins)for(let i of s.pluginRoots(e))Vi(i)&&n.pluginRoots.push({dir:i,binary:r});if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(e))Vi(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=aJ(s.mcpConfigCandidates(e));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function wx(t,e=yx()){return Rd[t].pluginEnabledState(e)}function aJ(t){for(let e of t)if(Vi(e))return e;return null}function cJ(t){let e=ln(t,".claude","settings.json");if(!Vi(e))return Ji;let n;try{n=JSON.parse(hx(e,"utf-8"))}catch{return Ji}if(!n||typeof n!="object")return Ji;let r=n.enabledPlugins;if(!r||typeof r!="object"||Array.isArray(r))return Ji;let o=new Map;for(let[s,i]of Object.entries(r))typeof i=="boolean"&&o.set(s,i);return o}var bx,Ji,Rd,Ehe,Id=h(()=>{"use strict";B();bx=["claude-code","codex"],Ji=new Map,Rd={"claude-code":{label:"Claude Code",pluginRoots:t=>[ln(t,".claude","plugins")],skillRoots:t=>[ln(t,".claude","skills")],mcpConfigCandidates:t=>[ln(t,".claude","mcp.json"),ln(t,".claude",".mcp.json"),ln(t,".claude","claude-code","mcp.json")],mcpFormat:"json",pluginEnabledState:t=>cJ(t)},codex:{label:"Codex",pluginRoots:t=>[ln(t,".codex","plugins")],skillRoots:t=>[ln(t,".codex","skills")],mcpConfigCandidates:t=>[ln(t,".codex","config.toml")],mcpFormat:"toml",pluginEnabledState:()=>Ji}},Ehe={"claude-code":Rd["claude-code"].label,codex:Rd.codex.label}});import{readFileSync as lJ,existsSync as dJ}from"fs";function Sx(t){if(!dJ(t))return;let e=lJ(t,"utf-8"),n=JSON.parse(e),r={},o=sE(n.models);if(typeof n.model=="string"&&n.model.length>0){let s=n.model.toLowerCase();r.model=gi(s)?s:n.model}if(typeof n.maxTokens=="number"&&(r.maxTokens=n.maxTokens),typeof n.temperature=="number"&&(r.temperature=n.temperature),typeof n.systemPrompt=="string"&&n.systemPrompt.length>0&&(r.systemPrompt=n.systemPrompt),typeof n.permissionMode=="string"){let s=n.permissionMode;(s==="default"||s==="plan"||s==="autonomous"||s==="bypassPermissions")&&(r.permissionMode=s)}if(n.autoRouting&&typeof n.autoRouting=="object"){let s={};typeof n.autoRouting.interactive=="boolean"&&(s.interactive=n.autoRouting.interactive),typeof n.autoRouting.chat=="boolean"&&(s.chat=n.autoRouting.chat),typeof n.autoRouting.telegram=="boolean"&&(s.telegram=n.autoRouting.telegram),typeof n.autoRouting.daemon=="boolean"&&(s.daemon=n.autoRouting.daemon),r.autoRouting=s}if(n.daemon&&typeof n.daemon=="object"){let s={};typeof n.daemon.task=="string"&&(s.task=n.daemon.task),typeof n.daemon.taskId=="string"&&(s.taskId=n.daemon.taskId);let i=n.daemon.worktreePrune;i&&typeof i=="object"&&(s.worktreePrune={enabled:typeof i.enabled=="boolean"?i.enabled:!0,cron:typeof i.cron=="string"?i.cron:"0 4 * * *",maxAgeDaysClean:typeof i.maxAgeDaysClean=="number"?i.maxAgeDaysClean:14,maxAgeDaysDirty:typeof i.maxAgeDaysDirty=="number"?i.maxAgeDaysDirty:30,scope:typeof i.scope=="string"?i.scope:"all"}),typeof n.daemon.verifyDone=="boolean"&&(s.verifyDone=n.daemon.verifyDone),r.daemon=s}if(n.telegram&&typeof n.telegram=="object"){let s={},i=n.telegram.notify;if(i&&typeof i=="object"){let a={};if((i.mode==="primary"||i.mode==="broadcast"||i.mode==="custom")&&(a.mode=i.mode),typeof i.primaryChatId=="number"&&Number.isFinite(i.primaryChatId)&&(a.primaryChatId=i.primaryChatId),Array.isArray(i.targets)){let c=i.targets.filter(l=>typeof l=="number"&&Number.isFinite(l));c.length>0&&(a.targets=c)}s.notify=a}if(typeof n.telegram.verifyDone=="boolean"&&(s.verifyDone=n.telegram.verifyDone),Array.isArray(n.telegram.tagOnlyChats)){let a=n.telegram.tagOnlyChats.filter(c=>typeof c=="number"&&Number.isFinite(c));a.length>0&&(s.tagOnlyChats=a)}if(n.telegram.chatAliases&&typeof n.telegram.chatAliases=="object"&&!Array.isArray(n.telegram.chatAliases)){let a={};for(let[c,l]of Object.entries(n.telegram.chatAliases))typeof l=="number"&&Number.isFinite(l)&&l!==0&&(a[c]=l);Object.keys(a).length>0&&(s.chatAliases=a)}r.telegram=s}if(n.updatePolicy&&["notify","auto","off"].includes(n.updatePolicy)&&(r.updatePolicy=n.updatePolicy),n.theme&&["dark","light","umber","auto"].includes(n.theme)&&(r.theme=n.theme),typeof n.autoResumeOnUsageLimit=="boolean"&&(r.autoResumeOnUsageLimit=n.autoResumeOnUsageLimit),typeof n.enforceDoneEvidence=="boolean"&&(r.enforceDoneEvidence=n.enforceDoneEvidence),typeof n.bgSummaries=="boolean"&&(r.bgSummaries=n.bgSummaries),typeof n.maxSummaryCallsPerSession=="number"&&(r.maxSummaryCallsPerSession=Math.min(500,Math.max(1,n.maxSummaryCallsPerSession))),n.hooks!==null&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)&&(r.hooks=n.hooks),typeof n.enableShellHooks=="boolean"&&(r.enableShellHooks=n.enableShellHooks),typeof n.enablePluginHooks=="boolean"&&(r.enablePluginHooks=n.enablePluginHooks),Uh().includes(t)){let s=$h(n.importFrom);s!==void 0&&(r.importFrom=s)}if(n.interactive&&typeof n.interactive=="object"){let s={};typeof n.interactive.worktreeAutoname=="boolean"&&(s.worktreeAutoname=n.interactive.worktreeAutoname),typeof n.interactive.worktreeBranchPrefix=="string"&&(s.worktreeBranchPrefix=fx(n.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof n.interactive.worktreeBase=="string"&&n.interactive.worktreeBase.trim().length>0&&(mx(n.interactive.worktreeBase,`${t}#/interactive/worktreeBase`),s.worktreeBase=n.interactive.worktreeBase),(n.interactive.worktreeOnExit==="ask"||n.interactive.worktreeOnExit==="keep"||n.interactive.worktreeOnExit==="remove")&&(s.worktreeOnExit=n.interactive.worktreeOnExit),typeof n.interactive.suggestGhost=="boolean"&&(s.suggestGhost=n.interactive.suggestGhost),(n.interactive.thinkingUi==="summary"||n.interactive.thinkingUi==="live"||n.interactive.thinkingUi==="digest"||n.interactive.thinkingUi==="off")&&(s.thinkingUi=n.interactive.thinkingUi),Object.keys(s).length>0&&(r.interactive=s)}return{config:r,modelsPartial:o}}var kx=h(()=>{"use strict";lt();Fe();gx();Id()});function Bh(){if(Cd!==void 0)return Cd;let t=JA().map(r=>r.path),e=!1;for(let r of t){let o;try{o=Sx(r)}catch(i){console.error(`Warning: Failed to parse ${r}:`,i),e=!0;continue}if(o===void 0)continue;let s={...o,sourcePath:r};return e||(Cd=s),s}let n={config:{},sourcePath:void 0,modelsPartial:{}};return e||(Cd=n),n}var Cd,vx=h(()=>{"use strict";VA();kx()});import{readFileSync as uJ,existsSync as jh,realpathSync as Tx}from"fs";function Ex(t){if(!jh(t))return null;try{let e=uJ(t,"utf-8").trim();return e.length>0?e:null}catch{return null}}function pJ(t,e){if(t===e)return!0;if(!jh(t)||!jh(e))return!1;try{return Tx(t)===Tx(e)}catch{return!1}}function Hh(t=process.cwd()){if(Pd?.cwd===t)return Pd.value;let e=Mv(),n=Ov(t),r=Ex(e),o=pJ(n,e)?null:Ex(n),s;return r!==null&&o!==null?s={content:`${fJ(e)}
|
|
316
|
+
`).filter(s=>s.startsWith("!!")).map(s=>s.slice(2).trim()).filter(s=>s!=="")}}catch(o){let s=o instanceof Error?o.message:String(o);return{failure:n===void 0?s:`expanding ${n}: ${s}`}}}async function Hz(t,e,n){let r=await nx(t,e,n);if("failure"in r)return{protect:!0,because:"git-failed",detail:r.failure};for(let o of r.entries){if(o===n)continue;let{verdict:s}=await tx(e,o);if(s==="protected")return{protect:!0,because:"non-rebuildable-entry",detail:o}}return{protect:!1}}async function _d(t,e){let n=await nx(t,e);if("failure"in n)return{protect:!0,because:"git-failed",detail:n.failure};for(let r of n.entries){let{verdict:o,resolvedEntry:s}=await tx(e,r);if(o==="protected")return{protect:!0,because:"non-rebuildable-entry",detail:r};if(o==="inspectable"&&s.endsWith("/")){let i=await Hz(t,e,s);if(i.protect)return i}}return{protect:!1}}async function rx(t,e){return(await _d(t,e)).protect}var Bz,jz,Ad=h(()=>{"use strict";Ed();Ed();Bz=["-c","core.quotePath=false"],jz={maxBuffer:64*1024*1024,timeout:1e4}});var ox=h(()=>{"use strict";se()});import{promises as Wz}from"node:fs";import{resolve as Kz}from"node:path";async function sx(t){let e=Kz(t);try{return await Wz.realpath(e)}catch{return e}}var ix=h(()=>{"use strict"});import{promises as Gt}from"node:fs";import{setTimeout as qz}from"node:timers/promises";import{dirname as cx,isAbsolute as Gz,resolve as Xz}from"node:path";function Vz(t){try{let e=JSON.parse(t);return e.version!==lx?[]:Array.isArray(e.roots)?e.roots.filter(n=>typeof n=="object"&&n!==null&&typeof n.path=="string"&&n.path.length>0&&Gz(n.path)):[]}catch{return[]}}async function Yz(){try{return Vz(await Gt.readFile(Gc(),"utf-8"))}catch{return[]}}function Qz(t){let e=ax.then(t,t).catch(()=>{});return ax=e,e}async function Zz(t){try{let e=Number.parseInt((await Gt.readFile(t,"utf-8")).trim(),10);if(Number.isInteger(e)&&e>0){process.kill(e,0);return}}catch{}await Gt.unlink(t).catch(()=>{})}async function eJ(t){let e=Date.now()+zz;for(;;)try{let n=await Gt.open(t,"wx",dx);return await n.writeFile(String(process.pid),"utf-8"),await n.close(),async()=>{await Gt.unlink(t).catch(()=>{})}}catch(n){if(n.code!=="EEXIST"||Date.now()>=e)return null;await Zz(t),await qz(Jz)}}async function tJ(t){let e=Gc();await Gt.mkdir(cx(e),{recursive:!0,mode:ux});let n={version:lx,roots:t},r=`${e}.tmp-${process.pid}-${Date.now()}`;try{await Gt.writeFile(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:dx}),await Gt.rename(r,e)}catch(o){throw await Gt.rm(r,{force:!0}).catch(()=>{}),o}}async function nJ(t){await Qz(async()=>{let e=Gc();await Gt.mkdir(cx(e),{recursive:!0,mode:ux}).catch(()=>{});let n=await eJ(`${e}.lock`);try{await tJ(t(await Yz()))}catch{}finally{n!==null&&await n()}})}function rJ(t){if(t.length<=xd)return t;t=[...t].sort((n,r)=>n.lastSeenAt.localeCompare(r.lastSeenAt));let e=t.slice(0,t.length-xd);return O(`[worktree-root-registry] cap ${xd} reached \u2014 evicting ${e.length} least-recently-seen root(s); their managed worktrees will no longer be swept: `+e.map(n=>n.path).join(", ")),t.slice(-xd)}async function Lh(t){if(t==="")return;let e=await sx(t),n=new Date().toISOString();await nJ(r=>{let o=r.filter(s=>Xz(s.path)!==e);return rJ([...o,{path:e,lastSeenAt:n}])})}var lx,xd,dx,ux,zz,Jz,ax,Nh=h(()=>{"use strict";B();se();ox();ix();lx=1,xd=64,dx=384,ux=448,zz=2e3,Jz=25;ax=Promise.resolve()});import{execFile as oJ}from"node:child_process";import{promisify as sJ}from"node:util";function fx(t,e){if(t.length>px)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${px}.`);if(!iJ.test(t))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 only [A-Za-z0-9_-./] are allowed.`);if(t.startsWith("-"))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);return t}function mx(t,e){if(t.trim().length===0)throw new Error(`Invalid worktree base ref from ${e}: '' \u2014 base ref cannot be empty.`);if(t.startsWith("-"))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(t.includes("\0"))throw new Error(`Invalid worktree base ref from ${e}: contains a NUL byte.`);if(/\s/.test(t))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not contain whitespace.`)}var mhe,iJ,px,gx=h(()=>{"use strict";F();Fh();YA();Ad();Nh();mhe=sJ(oJ),iJ=/^[A-Za-z0-9_\-./]*$/,px=64});import{existsSync as Vi,readdirSync as yhe,readFileSync as hx,realpathSync as bhe,statSync as whe}from"fs";import{homedir as yx}from"os";import{join as ln,basename as vhe}from"path";function $h(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of bx){let r=t[n];if(r!==void 0){if(r===!0){e[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;e[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(e).length>0?e:void 0}function Uh(){return[on(),Xc()]}function Yi(t=Uh()){for(let e of t)if(Vi(e))try{let n=JSON.parse(hx(e,"utf-8")),r=$h(n.importFrom);if(r!==void 0)return r}catch{}}function Qi(t,e=yx()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!t)return n;for(let r of bx){let o=t[r];if(!o)continue;let s=Rd[r];if(o.plugins)for(let i of s.pluginRoots(e))Vi(i)&&n.pluginRoots.push({dir:i,binary:r});if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(e))Vi(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=aJ(s.mcpConfigCandidates(e));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function wx(t,e=yx()){return Rd[t].pluginEnabledState(e)}function aJ(t){for(let e of t)if(Vi(e))return e;return null}function cJ(t){let e=ln(t,".claude","settings.json");if(!Vi(e))return Ji;let n;try{n=JSON.parse(hx(e,"utf-8"))}catch{return Ji}if(!n||typeof n!="object")return Ji;let r=n.enabledPlugins;if(!r||typeof r!="object"||Array.isArray(r))return Ji;let o=new Map;for(let[s,i]of Object.entries(r))typeof i=="boolean"&&o.set(s,i);return o}var bx,Ji,Rd,Ehe,Id=h(()=>{"use strict";B();bx=["claude-code","codex"],Ji=new Map,Rd={"claude-code":{label:"Claude Code",pluginRoots:t=>[ln(t,".claude","plugins")],skillRoots:t=>[ln(t,".claude","skills")],mcpConfigCandidates:t=>[ln(t,".claude","mcp.json"),ln(t,".claude",".mcp.json"),ln(t,".claude","claude-code","mcp.json")],mcpFormat:"json",pluginEnabledState:t=>cJ(t)},codex:{label:"Codex",pluginRoots:t=>[ln(t,".codex","plugins")],skillRoots:t=>[ln(t,".codex","skills")],mcpConfigCandidates:t=>[ln(t,".codex","config.toml")],mcpFormat:"toml",pluginEnabledState:()=>Ji}},Ehe={"claude-code":Rd["claude-code"].label,codex:Rd.codex.label}});import{readFileSync as lJ,existsSync as dJ}from"fs";function Sx(t){if(!dJ(t))return;let e=lJ(t,"utf-8"),n=JSON.parse(e),r={},o=sE(n.models);if(typeof n.model=="string"&&n.model.length>0){let s=n.model.toLowerCase();r.model=gi(s)?s:n.model}if(typeof n.maxTokens=="number"&&(r.maxTokens=n.maxTokens),typeof n.temperature=="number"&&(r.temperature=n.temperature),typeof n.systemPrompt=="string"&&n.systemPrompt.length>0&&(r.systemPrompt=n.systemPrompt),typeof n.permissionMode=="string"){let s=n.permissionMode;(s==="default"||s==="plan"||s==="autonomous"||s==="bypassPermissions")&&(r.permissionMode=s)}if(n.autoRouting&&typeof n.autoRouting=="object"){let s={};typeof n.autoRouting.interactive=="boolean"&&(s.interactive=n.autoRouting.interactive),typeof n.autoRouting.chat=="boolean"&&(s.chat=n.autoRouting.chat),typeof n.autoRouting.telegram=="boolean"&&(s.telegram=n.autoRouting.telegram),typeof n.autoRouting.daemon=="boolean"&&(s.daemon=n.autoRouting.daemon),r.autoRouting=s}if(n.daemon&&typeof n.daemon=="object"){let s={};typeof n.daemon.task=="string"&&(s.task=n.daemon.task),typeof n.daemon.taskId=="string"&&(s.taskId=n.daemon.taskId);let i=n.daemon.worktreePrune;i&&typeof i=="object"&&(s.worktreePrune={enabled:typeof i.enabled=="boolean"?i.enabled:!0,cron:typeof i.cron=="string"?i.cron:"0 4 * * *",maxAgeDaysClean:typeof i.maxAgeDaysClean=="number"?i.maxAgeDaysClean:14,maxAgeDaysDirty:typeof i.maxAgeDaysDirty=="number"?i.maxAgeDaysDirty:30,scope:typeof i.scope=="string"?i.scope:"all"}),typeof n.daemon.verifyDone=="boolean"&&(s.verifyDone=n.daemon.verifyDone),r.daemon=s}if(n.telegram&&typeof n.telegram=="object"){let s={},i=n.telegram.notify;if(i&&typeof i=="object"){let a={};if((i.mode==="primary"||i.mode==="broadcast"||i.mode==="custom")&&(a.mode=i.mode),typeof i.primaryChatId=="number"&&Number.isFinite(i.primaryChatId)&&(a.primaryChatId=i.primaryChatId),Array.isArray(i.targets)){let c=i.targets.filter(l=>typeof l=="number"&&Number.isFinite(l));c.length>0&&(a.targets=c)}s.notify=a}if(typeof n.telegram.verifyDone=="boolean"&&(s.verifyDone=n.telegram.verifyDone),Array.isArray(n.telegram.tagOnlyChats)){let a=n.telegram.tagOnlyChats.filter(c=>typeof c=="number"&&Number.isFinite(c));a.length>0&&(s.tagOnlyChats=a)}if(n.telegram.chatAliases&&typeof n.telegram.chatAliases=="object"&&!Array.isArray(n.telegram.chatAliases)){let a={};for(let[c,l]of Object.entries(n.telegram.chatAliases))typeof l=="number"&&Number.isFinite(l)&&l!==0&&(a[c]=l);Object.keys(a).length>0&&(s.chatAliases=a)}r.telegram=s}if(n.updatePolicy&&["notify","auto","off"].includes(n.updatePolicy)&&(r.updatePolicy=n.updatePolicy),n.theme&&["dark","light","umber","auto"].includes(n.theme)&&(r.theme=n.theme),typeof n.autoResumeOnUsageLimit=="boolean"&&(r.autoResumeOnUsageLimit=n.autoResumeOnUsageLimit),typeof n.enforceDoneEvidence=="boolean"&&(r.enforceDoneEvidence=n.enforceDoneEvidence),typeof n.bgSummaries=="boolean"&&(r.bgSummaries=n.bgSummaries),typeof n.maxSummaryCallsPerSession=="number"&&(r.maxSummaryCallsPerSession=Math.min(500,Math.max(1,n.maxSummaryCallsPerSession))),n.hooks!==null&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)&&(r.hooks=n.hooks),typeof n.enableShellHooks=="boolean"&&(r.enableShellHooks=n.enableShellHooks),typeof n.enablePluginHooks=="boolean"&&(r.enablePluginHooks=n.enablePluginHooks),Uh().includes(t)){let s=$h(n.importFrom);s!==void 0&&(r.importFrom=s)}if(n.interactive&&typeof n.interactive=="object"){let s={};typeof n.interactive.worktreeAutoname=="boolean"&&(s.worktreeAutoname=n.interactive.worktreeAutoname),typeof n.interactive.worktreeBranchPrefix=="string"&&(s.worktreeBranchPrefix=fx(n.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof n.interactive.worktreeBase=="string"&&n.interactive.worktreeBase.trim().length>0&&(mx(n.interactive.worktreeBase,`${t}#/interactive/worktreeBase`),s.worktreeBase=n.interactive.worktreeBase),(n.interactive.worktreeOnExit==="ask"||n.interactive.worktreeOnExit==="keep"||n.interactive.worktreeOnExit==="remove")&&(s.worktreeOnExit=n.interactive.worktreeOnExit),typeof n.interactive.suggestGhost=="boolean"&&(s.suggestGhost=n.interactive.suggestGhost),(n.interactive.thinkingUi==="summary"||n.interactive.thinkingUi==="live"||n.interactive.thinkingUi==="digest"||n.interactive.thinkingUi==="off")&&(s.thinkingUi=n.interactive.thinkingUi),Object.keys(s).length>0&&(r.interactive=s)}return{config:r,modelsPartial:o}}var kx=h(()=>{"use strict";lt();Fe();gx();Id()});function Bh(){if(Cd!==void 0)return Cd;let t=JA().map(r=>r.path),e=!1;for(let r of t){let o;try{o=Sx(r)}catch(i){console.error(`Warning: Failed to parse ${r}:`,i),e=!0;continue}if(o===void 0)continue;let s={...o,sourcePath:r};return e||(Cd=s),s}let n={config:{},sourcePath:void 0,modelsPartial:{}};return e||(Cd=n),n}var Cd,vx=h(()=>{"use strict";VA();kx()});import{readFileSync as uJ,existsSync as jh,realpathSync as Tx}from"fs";function Ex(t){if(!jh(t))return null;try{let e=uJ(t,"utf-8").trim();return e.length>0?e:null}catch{return null}}function pJ(t,e){if(t===e)return!0;if(!jh(t)||!jh(e))return!1;try{return Tx(t)===Tx(e)}catch{return!1}}function Hh(t=process.cwd()){if(Pd?.cwd===t)return Pd.value;let e=Mv(),n=Ov(t),r=Ex(e),o=pJ(n,e)?null:Ex(n),s;return r!==null&&o!==null?s={content:`${fJ(e)}
|
|
317
317
|
|
|
318
318
|
${r}
|
|
319
319
|
|
|
@@ -323,9 +323,9 @@ ${o}`,paths:[e,n]}:o!==null?s={content:o,paths:[n]}:r!==null?s={content:r,paths:
|
|
|
323
323
|
|
|
324
324
|
`).trim()}function EJ(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}async function Lx(t,e){let{JSDOM:n,Readability:r,turndown:o}=await TJ(),i=new n(t,{url:e}).window.document,a=(i.title??"").trim(),c=(()=>{try{let p=i.cloneNode(!0);return new r(p).parse()}catch{return null}})();if(c&&typeof c.content=="string"&&c.content.trim().length>0){let p=Fx(o.turndown(c.content)),f=(c.title??"").trim()||a,m=typeof c.length=="number"&&c.length>0?c.length:(c.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:p,textLength:m,usedFallback:!1}}let l=i.body,d=l?.innerHTML??"",u=Fx(o.turndown(d));return{title:a,markdown:u,textLength:EJ(l),usedFallback:!0}}var qh,Nx=h(()=>{"use strict";qh=null});function AJ(t){let e=[],n=new Map,r=0,o=0;for(;o<t.length;){let s=t.indexOf("<",o);if(s===-1){r===0&&e.push(t.slice(o));break}if(r===0&&e.push(t.slice(o,s)," "),t.startsWith("<!--",s)){let p=t.indexOf("-->",s+4);o=p===-1?t.length:p+3;continue}let i=t.indexOf(">",s+1);if(i===-1)break;let a=t.slice(s+1,i).trimStart(),c=a.startsWith("/"),l=c?1:0,u=/^[a-z][\w:-]*/i.exec(a.slice(l))?.[0].toLowerCase();if(u!==void 0&&_J.has(u))if(c){let p=n.get(u)??0;p>0&&(r--,p===1?n.delete(u):n.set(u,p-1))}else a.endsWith("/")||(r++,n.set(u,(n.get(u)??0)+1));o=i+1}return e.join("").replace(/\s+/g," ").trim().length}function Gh(t){let e=AJ(t.html);if(e<2e3)return;let n=t.extractedTextLength/e;return!Number.isFinite(n)||n>=.5?void 0:`[web_scrape: extraction kept ~${Math.round(n*100)}% of this page's visible text (${t.extractedTextLength} of ~${e} chars). Readability strips collapsed, tabbed, and accordion sections along with page chrome, so a section you expect may be absent from the markdown above. If something specific is missing, re-request this url once with mode: "raw" and read the HTML \u2014 do not re-fetch it in markdown mode.]`}function $x(t,e){return e===void 0||e===""?t:`${t}
|
|
325
325
|
|
|
326
|
-
${e}`}var _J,Xh=h(()=>{"use strict";_J=new Set(["script","style","noscript","template","svg"])});function RJ(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function Ux(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function IJ(t,e){let n=t.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,e)}async function Bx(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??RJ,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!xJ.has(u.status)||d===o)return u;let p=IJ(u,i)??Ux(d,s,i);D("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=Ux(d,s,i);D("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var xJ,jx=h(()=>{"use strict";ie();xJ=new Set([429,502,503,504])});import{BlockList as CJ,isIP as Jh}from"node:net";import{lookup as PJ}from"node:dns/promises";import{Agent as MJ}from"undici";function Wx(){let t=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function LJ(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function zh(t){let e=Jh(t);return e===0?!1:FJ.check(t,e===4?"ipv4":"ipv6")}async function Kx(t){return PJ(t,{all:!0,verbatim:!0})}async function Fr(t,e={}){if(e.allowPrivateHosts??Wx())return{allowed:!0};let n;try{n=new URL(t)}catch{return{allowed:!1,reason:`"${t}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{allowed:!1,reason:`protocol "${n.protocol}" not supported (http/https only)`};let r=LJ(n.hostname),o=(a,c)=>`refusing to fetch ${c} \u2014 internal/private address ${a} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`;if(Jh(r)!==0)return zh(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??Kx,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(zh(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function ea(t,e={}){let n=await Fr(t,e);if(!n.allowed)throw new Ce(n.reason)}async function Fn(t,e,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},s=e;for(let i=0;i<=Hx;i++){await ea(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??Wx())?{dispatcher:NJ}:{}},c=await Bx(t,s,a,r.retry??{});if(!$J.has(c.status))return c;let l=c.headers.get("location");if(l===null||l.trim()==="")return c;let d;try{d=new URL(l,c.url||s).toString()}catch{return c}await c.body?.cancel().catch(()=>{}),s=d}throw new Ce(`too many redirects (>${Hx}) starting from ${e}`)}var OJ,DJ,FJ,Ce,NJ,Hx,$J,Lr=h(()=>{"use strict";F();jx();OJ=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.168.0.0",16]],DJ=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],FJ=(()=>{let t=new CJ;for(let[e,n]of OJ)t.addSubnet(e,n,"ipv4");for(let[e,n]of DJ)t.addSubnet(e,n,"ipv6");return t})(),Ce=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};NJ=new MJ({connect:{lookup(t,e,n){Kx(t).then(r=>{let o=r.find(i=>zh(i.address));if(o!==void 0){n(new Ce(`refusing to connect to ${t} (resolved) \u2014 internal/private address ${o.address} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`),"",0);return}let s=r[0];if(s===void 0){n(new Error(`DNS lookup returned no addresses for ${t}`),"",0);return}n(null,s.address,Jh(s.address))},r=>n(r,"",0))}}});Hx=20,$J=new Set([301,302,303,307,308])});var Yh={};mo(Yh,{enforceDomainPolicy:()=>It,loadBrowserConfig:()=>Vh});import{readFileSync as UJ}from"node:fs";import{join as BJ}from"path";function jJ(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function qx(t,e){return jJ(e).test(t)}function KJ(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(HJ.has(e))return!0;if(WJ.has(e))return!1}return!1}function Gx(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function qJ(t){if(t===void 0||t==="")return"auto";if(t==="playwright"||t==="agent-browser"||t==="auto")return t;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${t}`)}function Xx(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Nm(e),e}function GJ(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function XJ(t){try{return UJ(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function zJ(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright"||e.backend==="agent-browser"||e.backend==="auto")n.backend=e.backend;else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Xx(e.defaultProfile)),n}function Vh(t){let e=t?.env??k,n=t?.readFileSync??XJ,r=t?.surface??e.AGENT_SURFACE,o=KJ(e.AFK_BROWSER_HEADLESS,r),s=Gx(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Gx(e.AFK_BROWSER_BLOCKED_DOMAINS),a=GJ(e.AFK_BROWSER_DOM_SNAPSHOTS),c=qJ(e.AFK_BROWSER_BACKEND),l=Xx(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():BJ(rn(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=zJ(d,m);return g.configPath=p,g}function It(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(qx(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>qx(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var HJ,WJ,Ln=h(()=>{"use strict";F();B();HJ=new Set(["daemon","subagent","telegram","afk"]),WJ=new Set(["repl","interactive","cli"])});import{readFileSync as JJ}from"node:fs";import{join as VJ}from"node:path";import{homedir as YJ}from"node:os";function ZJ(t){let e=t??QJ,n;try{n=JJ(e,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(typeof r!="object"||r===null||Array.isArray(r))return null;let o=r;if(typeof o.url!="string"||typeof o.token!="string"||typeof o.pid!="number")return null;let s;try{s=new URL(o.url)}catch{return null}let{hostname:i,protocol:a}=s;if(!(i==="127.0.0.1"||i==="localhost"||i==="::1")||a!=="http:")throw new Error(`Agent Browser connection file contains an untrusted URL: ${o.url}. Only http://127.0.0.1 or http://localhost is permitted.`);return{url:o.url,token:o.token,pid:o.pid,version:typeof o.version=="string"?o.version:"unknown"}}function eV(t){try{return process.kill(t,0),!0}catch{return!1}}async function tV(t,e,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),s=await fetch(`${t}/health`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),s.ok}catch{return!1}}async function Qh(t){let e=ZJ(t);return e===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:eV(e.pid)?await tV(e.url,e.token)?{available:!0,connection:e,reason:null}:{available:!1,connection:e,reason:`health probe failed at ${e.url}`}:{available:!1,connection:e,reason:`stale connection file: PID ${e.pid} not alive`}}var QJ,zx=h(()=>{"use strict";QJ=VJ(YJ(),".config","agent-browser","connection.json")});async function Jx(t){let{config:e,surface:n}=t;if(e.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(e.backend==="agent-browser"){let i=Date.now(),a=await Qh(),c=Date.now()-i;if(!a.available)throw new Error(`AFK_BROWSER_BACKEND=agent-browser but Agent Browser is not available: ${a.reason}`);return{backend:"agent-browser",reason:"explicit config: backend=agent-browser",probeMs:c,availability:a}}if(n&&nV.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(e.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await Qh(),s=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:s,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:s,availability:o}}var nV,Vx=h(()=>{"use strict";zx();nV=new Set(["daemon","subagent"])});import{createHash as rV}from"crypto";function Yx(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&oV.test(t.label))}function Qx(t){return rV("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Zx(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var oV,Od=h(()=>{"use strict";oV=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as sV}from"crypto";import{mkdir as iV,stat as aV,writeFile as cV}from"fs/promises";import{join as Zh}from"path";import{gzip as lV}from"zlib";import{promisify as dV}from"util";function uV(t){return Zh(it(t),"browser")}function pV(t){return Zh(uV(t),"screenshots")}function fV(){return new Date().toISOString().replace(/[:.]/g,"-")}function mV(){return sV(3).toString("hex")}async function Jo(t,e,n){if(e.length>eR)throw new Error(`writeScreenshotSidecar: buffer exceeds ${eR} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=pV(t);await iV(r,{recursive:!0});let o=`${fV()}-${mV()}-${n}.png`,s=Zh(r,o);await cV(s,e);let{size:i}=await aV(s);return{path:s,bytes:i}}var jye,eR,ey=h(()=>{"use strict";B();Od();jye=dV(lV);eR=5*1024*1024});var Dd,tR=h(()=>{"use strict";Dd=class{baseUrl;token;constructor(e){this.baseUrl=e.url,this.token=e.token}async call(e,n,r=3e4){let o={version:1,method:e,params:n},s=new AbortController,i=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${this.baseUrl}/agent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,Host:new URL(this.baseUrl).host},body:JSON.stringify(o),signal:s.signal});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(`Agent Browser ${e} failed (HTTP ${a.status}): ${l}`)}let c=await a.json();if(c.ok===!1){let l=c.error,d=l?.code??"UNKNOWN",u=l?.message??JSON.stringify(c);throw new Error(`Agent Browser ${e} failed: [${String(d)}] ${String(u)}`)}return c.result}finally{clearTimeout(i)}}async listTabs(){return this.call("tabs.list",null)}async openTab(e){return{tabId:(await this.call("tabs.open",{url:e},6e4)).id}}async closeTab(e){await this.call("page.eval",{id:e,script:"window.close()"}).catch(()=>{})}async read(e,n){return this.call("page.read",{id:e,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(e,n){return this.call("page.inspect",{id:e,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(e,n){await this.call("page.click",{id:e,elementId:n})}async fill(e,n,r){await this.call("page.fill",{id:e,elementId:n,value:r})}async press(e,n,r){await this.call("page.press",{id:e,key:n,...r?{elementId:r}:{}})}async select(e,n,r){await this.call("page.select",{id:e,elementId:n,value:r})}async waitFor(e,n,r){await this.call("page.wait",{id:e,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(e,n){return this.call("page.eval",{id:e,script:n})}async screenshot(e){return this.call("page.screenshot",{id:e})}}});function ty(t){return{id:t.id,role:t.role,label:t.label,kind:t.kind,value:t.value,state:{disabled:t.disabled,...t.checked!==void 0?{checked:t.checked}:{},...t.selected!==void 0?{selected:t.selected}:{},...t.expanded!==void 0?{expanded:t.expanded}:{}},bbox:t.bbox,...t.selector?{selector:t.selector}:{}}}function nR(t,e){switch(e.kind){case"element_id":if(t.has(e.elementId))return e.elementId;throw new Error(`Element ${e.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function ny(t,e,n,r,o,s){switch(n){case"click":await t.click(e,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await t.fill(e,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await t.press(e,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await t.select(e,r,o);break;case"hover":throw new Error("hover is not supported by Agent Browser; use element_id from a prior observation to target clicks instead");case"scroll_to":{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await t.evalScript(e,`document.querySelector('[data-element-id="${i}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await t.waitFor(e,"element",{value:r,timeout:s??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function rR(t,e){if(e.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await t.client.inspect(t.tabId,{mode:"interactive",query:e.target.text,limit:10}),r=n;if(e.target.role){let c=e.target.role.toLowerCase();r=n.filter(l=>l.role.toLowerCase()===c)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${e.target.text}"`+(e.target.role?`, role="${e.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:e.target.text,...e.target.role?{role:e.target.role}:{}},candidates:r.slice(0,5).map(ty)};let s=r[0].id;await ny(t.client,t.tabId,e.action,s,e.value,e.timeoutMs);let i=await t.client.read(t.tabId,{mode:"main"}),a=It(i.url,t.config);return a.allowed?{elementId:s}:{outcome:"blocked_by_policy",url:i.url,reason:`action navigated to blocked domain: ${a.reason}`}}var oR=h(()=>{"use strict";Ln()});var sR={};mo(sR,{AgentBrowserProvider:()=>ry});var ry,iR=h(()=>{"use strict";Ln();ey();tR();oR();ry=class{name="agent-browser";config;client;sessions=new Map;constructor(e,n){this.config=e,this.client=new Dd(n)}async open(e){let n=It(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let r=this.sessions.get(e.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(e.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:e.timeoutMs??3e4});else{let{tabId:i}=await this.client.openTab(e.url);await this.client.waitFor(i,"load",{timeout:e.timeoutMs??3e4}),r={tabId:i,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(e.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),s=It(o.url,this.config);return s.allowed?this.buildObservation(r,e.sessionId,e.screenshot,void 0,"browser_open"):(await this.client.evalScript(r.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`redirected to blocked domain: ${s.reason}`})}async observe(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);return this.buildObservation(n,e.sessionId,e.screenshot,e.maxElements,"browser_observe")}async act(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);let r=nR(n.knownElements,e.target);if(r===null){if(e.target.kind==="semantic"){let i=await rR({client:this.client,config:this.config,tabId:n.tabId},e);return"outcome"in i?i:(n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"))}throw e.target.kind==="selector"?new Error("selector targets are not supported by Agent Browser; use element_id or semantic targets"):new Error(`Cannot resolve target: ${JSON.stringify(e.target)}`)}await ny(this.client,n.tabId,e.action,r,e.value,e.timeoutMs),n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),s=It(o.url,this.config);return s.allowed?this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"):(await this.client.evalScript(n.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`action navigated to blocked domain: ${s.reason}`})}async render(e){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);if(e.target!==void 0||e.fullPage)throw new Error("Agent Browser does not support element or full-page screenshots; omit target and fullPage.");let r=await this.client.screenshot(n.tabId),o=Buffer.from(r.data,"base64"),s=o.length>=24?o.readUInt32BE(16):0,i=o.length>=24?o.readUInt32BE(20):0;return{path:(await Jo(e.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:s,height:i,dataBase64:r.data,mediaType:"image/png"}}async extract(e){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(e){let n=this.sessions.get(e.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(e.sessionId)}}describe(e){let n=this.sessions.get(e);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let e=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(e),this.sessions.clear()}async buildObservation(e,n,r,o,s="browser_open"){let[i,a]=await Promise.all([this.client.read(e.tabId,{mode:"main",budget:4e3}),this.client.inspect(e.tabId,{mode:"interactive",limit:o??80})]),c=a.elements.map(ty),l=o??80,d=c.slice(0,l);e.observationCounter+=1,e.knownElements=new Map(d.map(g=>[g.id,g])),e.currentUrl=i.url,e.currentTitle=i.title;let u=[];c.length>l&&u.push(`page has ${c.length} interactive elements; showing first ${l}`);let p=null;if(r)try{let g=await this.client.screenshot(e.tabId),y=Buffer.from(g.data,"base64");p=(await Jo(n,y,s)).path}catch{u.push("screenshot capture failed")}let f=`obs_${e.observationCounter.toString(36)}`,m={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:i.url,title:i.title,textSummary:i.content.slice(0,4e3),interactive:d,status:m,warnings:u,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as gV,readFileSync as hV}from"node:fs";import{createRequire as yV}from"node:module";import{dirname as bV,join as wV}from"node:path";function lR(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<kV&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function ze(t){let e=lR(t);return cR.some(n=>e.includes(n))}function vV(){try{let e=yV(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(hV(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=wV(bV(e),o);return gV(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function ta(){return aR??=vV()??SV,aR}function oy(t){return t.includes("install chromium")}function gt(t,e){let n=lR(t),r=e?.latched===!0?` ${TV}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${ta()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${ta()}). Or pick a different tool.${r}`}function Fd(t,e,n=!1){if(!ze(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
326
|
+
${e}`}var _J,Xh=h(()=>{"use strict";_J=new Set(["script","style","noscript","template","svg"])});function RJ(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function Ux(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function IJ(t,e){let n=t.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,e)}async function Bx(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??RJ,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!xJ.has(u.status)||d===o)return u;let p=IJ(u,i)??Ux(d,s,i);O("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=Ux(d,s,i);O("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var xJ,jx=h(()=>{"use strict";se();xJ=new Set([429,502,503,504])});import{BlockList as CJ,isIP as Jh}from"node:net";import{lookup as PJ}from"node:dns/promises";import{Agent as MJ}from"undici";function Wx(){let t=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function LJ(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function zh(t){let e=Jh(t);return e===0?!1:FJ.check(t,e===4?"ipv4":"ipv6")}async function Kx(t){return PJ(t,{all:!0,verbatim:!0})}async function Fr(t,e={}){if(e.allowPrivateHosts??Wx())return{allowed:!0};let n;try{n=new URL(t)}catch{return{allowed:!1,reason:`"${t}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{allowed:!1,reason:`protocol "${n.protocol}" not supported (http/https only)`};let r=LJ(n.hostname),o=(a,c)=>`refusing to fetch ${c} \u2014 internal/private address ${a} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`;if(Jh(r)!==0)return zh(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??Kx,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(zh(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function ea(t,e={}){let n=await Fr(t,e);if(!n.allowed)throw new Ce(n.reason)}async function Fn(t,e,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},s=e;for(let i=0;i<=Hx;i++){await ea(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??Wx())?{dispatcher:NJ}:{}},c=await Bx(t,s,a,r.retry??{});if(!$J.has(c.status))return c;let l=c.headers.get("location");if(l===null||l.trim()==="")return c;let d;try{d=new URL(l,c.url||s).toString()}catch{return c}await c.body?.cancel().catch(()=>{}),s=d}throw new Ce(`too many redirects (>${Hx}) starting from ${e}`)}var OJ,DJ,FJ,Ce,NJ,Hx,$J,Lr=h(()=>{"use strict";F();jx();OJ=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.168.0.0",16]],DJ=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],FJ=(()=>{let t=new CJ;for(let[e,n]of OJ)t.addSubnet(e,n,"ipv4");for(let[e,n]of DJ)t.addSubnet(e,n,"ipv6");return t})(),Ce=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};NJ=new MJ({connect:{lookup(t,e,n){Kx(t).then(r=>{let o=r.find(i=>zh(i.address));if(o!==void 0){n(new Ce(`refusing to connect to ${t} (resolved) \u2014 internal/private address ${o.address} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`),"",0);return}let s=r[0];if(s===void 0){n(new Error(`DNS lookup returned no addresses for ${t}`),"",0);return}n(null,s.address,Jh(s.address))},r=>n(r,"",0))}}});Hx=20,$J=new Set([301,302,303,307,308])});var Yh={};mo(Yh,{enforceDomainPolicy:()=>It,loadBrowserConfig:()=>Vh});import{readFileSync as UJ}from"node:fs";import{join as BJ}from"path";function jJ(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function qx(t,e){return jJ(e).test(t)}function KJ(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(HJ.has(e))return!0;if(WJ.has(e))return!1}return!1}function Gx(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function qJ(t){if(t===void 0||t==="")return"auto";if(t==="playwright"||t==="agent-browser"||t==="auto")return t;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${t}`)}function Xx(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Nm(e),e}function GJ(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function XJ(t){try{return UJ(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function zJ(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright"||e.backend==="agent-browser"||e.backend==="auto")n.backend=e.backend;else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Xx(e.defaultProfile)),n}function Vh(t){let e=t?.env??k,n=t?.readFileSync??XJ,r=t?.surface??e.AGENT_SURFACE,o=KJ(e.AFK_BROWSER_HEADLESS,r),s=Gx(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Gx(e.AFK_BROWSER_BLOCKED_DOMAINS),a=GJ(e.AFK_BROWSER_DOM_SNAPSHOTS),c=qJ(e.AFK_BROWSER_BACKEND),l=Xx(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():BJ(rn(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=zJ(d,m);return g.configPath=p,g}function It(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(qx(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>qx(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var HJ,WJ,Ln=h(()=>{"use strict";F();B();HJ=new Set(["daemon","subagent","telegram","afk"]),WJ=new Set(["repl","interactive","cli"])});import{readFileSync as JJ}from"node:fs";import{join as VJ}from"node:path";import{homedir as YJ}from"node:os";function ZJ(t){let e=t??QJ,n;try{n=JJ(e,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(typeof r!="object"||r===null||Array.isArray(r))return null;let o=r;if(typeof o.url!="string"||typeof o.token!="string"||typeof o.pid!="number")return null;let s;try{s=new URL(o.url)}catch{return null}let{hostname:i,protocol:a}=s;if(!(i==="127.0.0.1"||i==="localhost"||i==="::1")||a!=="http:")throw new Error(`Agent Browser connection file contains an untrusted URL: ${o.url}. Only http://127.0.0.1 or http://localhost is permitted.`);return{url:o.url,token:o.token,pid:o.pid,version:typeof o.version=="string"?o.version:"unknown"}}function eV(t){try{return process.kill(t,0),!0}catch{return!1}}async function tV(t,e,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),s=await fetch(`${t}/health`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),s.ok}catch{return!1}}async function Qh(t){let e=ZJ(t);return e===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:eV(e.pid)?await tV(e.url,e.token)?{available:!0,connection:e,reason:null}:{available:!1,connection:e,reason:`health probe failed at ${e.url}`}:{available:!1,connection:e,reason:`stale connection file: PID ${e.pid} not alive`}}var QJ,zx=h(()=>{"use strict";QJ=VJ(YJ(),".config","agent-browser","connection.json")});async function Jx(t){let{config:e,surface:n}=t;if(e.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(e.backend==="agent-browser"){let i=Date.now(),a=await Qh(),c=Date.now()-i;if(!a.available)throw new Error(`AFK_BROWSER_BACKEND=agent-browser but Agent Browser is not available: ${a.reason}`);return{backend:"agent-browser",reason:"explicit config: backend=agent-browser",probeMs:c,availability:a}}if(n&&nV.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(e.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await Qh(),s=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:s,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:s,availability:o}}var nV,Vx=h(()=>{"use strict";zx();nV=new Set(["daemon","subagent"])});import{createHash as rV}from"crypto";function Yx(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&oV.test(t.label))}function Qx(t){return rV("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Zx(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var oV,Od=h(()=>{"use strict";oV=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as sV}from"crypto";import{mkdir as iV,stat as aV,writeFile as cV}from"fs/promises";import{join as Zh}from"path";import{gzip as lV}from"zlib";import{promisify as dV}from"util";function uV(t){return Zh(it(t),"browser")}function pV(t){return Zh(uV(t),"screenshots")}function fV(){return new Date().toISOString().replace(/[:.]/g,"-")}function mV(){return sV(3).toString("hex")}async function Jo(t,e,n){if(e.length>eR)throw new Error(`writeScreenshotSidecar: buffer exceeds ${eR} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=pV(t);await iV(r,{recursive:!0});let o=`${fV()}-${mV()}-${n}.png`,s=Zh(r,o);await cV(s,e);let{size:i}=await aV(s);return{path:s,bytes:i}}var jye,eR,ey=h(()=>{"use strict";B();Od();jye=dV(lV);eR=5*1024*1024});var Dd,tR=h(()=>{"use strict";se();Dd=class{baseUrl;token;constructor(e){this.baseUrl=e.url,this.token=e.token}async call(e,n,r=3e4){let o={version:1,method:e,params:n},s=new AbortController,i=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${this.baseUrl}/agent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,Host:new URL(this.baseUrl).host},body:JSON.stringify(o),signal:s.signal});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(`Agent Browser ${e} failed (HTTP ${a.status}): ${l}`)}let c=await a.json();if(c.ok===!1){let l=c.error,d=l?.code??"UNKNOWN",u=l?.message??JSON.stringify(c);throw new Error(`Agent Browser ${e} failed: [${String(d)}] ${String(u)}`)}return c.result}finally{clearTimeout(i)}}async listTabs(){return this.call("tabs.list",null)}async openTab(e){return{tabId:(await this.call("tabs.open",{url:e},6e4)).id}}async closeTab(e){await this.call("page.eval",{id:e,script:"window.close()"}).catch(n=>{O("[browser/agent-browser] closeTab window.close() failed (tab leak expected)",{tabId:e,err:n})})}async read(e,n){return this.call("page.read",{id:e,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(e,n){return this.call("page.inspect",{id:e,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(e,n){await this.call("page.click",{id:e,elementId:n})}async fill(e,n,r){await this.call("page.fill",{id:e,elementId:n,value:r})}async press(e,n,r){await this.call("page.press",{id:e,key:n,...r?{elementId:r}:{}})}async select(e,n,r){await this.call("page.select",{id:e,elementId:n,value:r})}async waitFor(e,n,r){await this.call("page.wait",{id:e,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(e,n){return this.call("page.eval",{id:e,script:n})}async screenshot(e){return this.call("page.screenshot",{id:e})}}});function ty(t){return{id:t.id,role:t.role,label:t.label,kind:t.kind,value:t.value,state:{disabled:t.disabled,...t.checked!==void 0?{checked:t.checked}:{},...t.selected!==void 0?{selected:t.selected}:{},...t.expanded!==void 0?{expanded:t.expanded}:{}},bbox:t.bbox,...t.selector?{selector:t.selector}:{}}}function nR(t,e){switch(e.kind){case"element_id":if(t.has(e.elementId))return e.elementId;throw new Error(`Element ${e.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function ny(t,e,n,r,o,s){switch(n){case"click":await t.click(e,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await t.fill(e,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await t.press(e,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await t.select(e,r,o);break;case"hover":throw new Error("hover is not supported by Agent Browser; use element_id from a prior observation to target clicks instead");case"scroll_to":{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await t.evalScript(e,`document.querySelector('[data-element-id="${i}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await t.waitFor(e,"element",{value:r,timeout:s??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function rR(t,e){if(e.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await t.client.inspect(t.tabId,{mode:"interactive",query:e.target.text,limit:10}),r=n;if(e.target.role){let c=e.target.role.toLowerCase();r=n.filter(l=>l.role.toLowerCase()===c)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${e.target.text}"`+(e.target.role?`, role="${e.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:e.target.text,...e.target.role?{role:e.target.role}:{}},candidates:r.slice(0,5).map(ty)};let s=r[0].id;await ny(t.client,t.tabId,e.action,s,e.value,e.timeoutMs);let i=await t.client.read(t.tabId,{mode:"main"}),a=It(i.url,t.config);return a.allowed?{elementId:s}:{outcome:"blocked_by_policy",url:i.url,reason:`action navigated to blocked domain: ${a.reason}`}}var oR=h(()=>{"use strict";Ln()});var sR={};mo(sR,{AgentBrowserProvider:()=>ry});var ry,iR=h(()=>{"use strict";Ln();ey();tR();oR();ry=class{name="agent-browser";config;client;sessions=new Map;constructor(e,n){this.config=e,this.client=new Dd(n)}async open(e){let n=It(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let r=this.sessions.get(e.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(e.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:e.timeoutMs??3e4});else{let{tabId:i}=await this.client.openTab(e.url);await this.client.waitFor(i,"load",{timeout:e.timeoutMs??3e4}),r={tabId:i,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(e.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),s=It(o.url,this.config);return s.allowed?this.buildObservation(r,e.sessionId,e.screenshot,void 0,"browser_open"):(await this.client.evalScript(r.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`redirected to blocked domain: ${s.reason}`})}async observe(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);return this.buildObservation(n,e.sessionId,e.screenshot,e.maxElements,"browser_observe")}async act(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);let r=nR(n.knownElements,e.target);if(r===null){if(e.target.kind==="semantic"){let i=await rR({client:this.client,config:this.config,tabId:n.tabId},e);return"outcome"in i?i:(n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"))}throw e.target.kind==="selector"?new Error("selector targets are not supported by Agent Browser; use element_id or semantic targets"):new Error(`Cannot resolve target: ${JSON.stringify(e.target)}`)}await ny(this.client,n.tabId,e.action,r,e.value,e.timeoutMs),n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),s=It(o.url,this.config);return s.allowed?this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"):(await this.client.evalScript(n.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`action navigated to blocked domain: ${s.reason}`})}async render(e){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);if(e.target!==void 0||e.fullPage)throw new Error("Agent Browser does not support element or full-page screenshots; omit target and fullPage.");let r=await this.client.screenshot(n.tabId),o=Buffer.from(r.data,"base64"),s=o.length>=24?o.readUInt32BE(16):0,i=o.length>=24?o.readUInt32BE(20):0;return{path:(await Jo(e.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:s,height:i,dataBase64:r.data,mediaType:"image/png"}}async extract(e){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(e){let n=this.sessions.get(e.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(e.sessionId)}}describe(e){let n=this.sessions.get(e);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let e=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(e),this.sessions.clear()}async buildObservation(e,n,r,o,s="browser_open"){let[i,a]=await Promise.all([this.client.read(e.tabId,{mode:"main",budget:4e3}),this.client.inspect(e.tabId,{mode:"interactive",limit:o??80})]),c=a.elements.map(ty),l=o??80,d=c.slice(0,l);e.observationCounter+=1,e.knownElements=new Map(d.map(g=>[g.id,g])),e.currentUrl=i.url,e.currentTitle=i.title;let u=[];c.length>l&&u.push(`page has ${c.length} interactive elements; showing first ${l}`);let p=null;if(r)try{let g=await this.client.screenshot(e.tabId),y=Buffer.from(g.data,"base64");p=(await Jo(n,y,s)).path}catch{u.push("screenshot capture failed")}let f=`obs_${e.observationCounter.toString(36)}`,m={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:i.url,title:i.title,textSummary:i.content.slice(0,4e3),interactive:d,status:m,warnings:u,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as gV,readFileSync as hV}from"node:fs";import{createRequire as yV}from"node:module";import{dirname as bV,join as wV}from"node:path";function lR(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<kV&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function ze(t){let e=lR(t);return cR.some(n=>e.includes(n))}function vV(){try{let e=yV(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(hV(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=wV(bV(e),o);return gV(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function ta(){return aR??=vV()??SV,aR}function oy(t){return t.includes("install chromium")}function gt(t,e){let n=lR(t),r=e?.latched===!0?` ${TV}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${ta()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${ta()}). Or pick a different tool.${r}`}function Fd(t,e,n=!1){if(!ze(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
327
327
|
|
|
328
|
-
${gt(t,{headless:e,latched:n})}`,{cause:t})}var cR,SV,kV,aR,TV,sy=h(()=>{"use strict";cR=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],SV="pnpm exec playwright install chromium",kV=4;TV="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Nr from"node:fs";import Ld from"node:path";import{randomBytes as EV}from"node:crypto";function _V(){try{return"5.208.3"}catch{}try{let t=Ld.resolve(import.meta.dirname,"../../../package.json"),e=Nr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var AV,Nd,dR=h(()=>{"use strict";sy();B();ie();AV=_V(),Nd=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Fd(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Fd(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${AV}`}}loadStorageState(e){let n=$m(e);try{if(!Nr.existsSync(n))return;let r=JSON.parse(Nr.readFileSync(n,"utf8"));return D("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){D("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=$m(e);if(!Nr.existsSync(r))return;let o=await n.storageState(),s=Ld.join(Ld.dirname(r),`.${Ld.basename(r)}.${process.pid}.${EV(4).toString("hex")}.tmp`);Nr.writeFileSync(s,JSON.stringify(o),{mode:384}),Nr.chmodSync(s,384),Nr.renameSync(s,r),D("[browser/vault] saved session",{profile:e,file:r})}catch(r){D("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as xV}from"node:crypto";function RV(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function IV(t,e,n){return`el_${xV("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function CV(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function uR(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function fR(t,e){let n=t.role??"",r=t.name??"";pR.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])fR(s,e)}async function PV(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},mR).catch(()=>[])}async function MV(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},mR).catch(()=>[])}function OV(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function $d(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=OV(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=PV(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],fR(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await MV(t)).filter(P=>pR.has(P.role??"")));let w=new Map;for(let E of p){let P=uR(E.name),H=w.get(P);(!H||H.bbox.w===0&&E.bbox.w>0)&&w.set(P,E)}let v=y.map(E=>({ax:E,dom:w.get(uR(E.name??""))})),_=r?v:v.filter(E=>E.dom?E.dom.bbox.w>0||E.dom.bbox.h>0:!0);_.sort((E,P)=>{let H=E.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(H!==M)return H-M;let N=E.dom?.bbox.x??0,$=P.dom?.bbox.x??0;return N-$}),_.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=_.slice(0,n).map((E,P)=>{let H=E.ax.role??"generic",M=E.ax.name??"",N=IV(H,M,P),$=E.dom?.bbox??{x:0,y:0,w:0,h:0},U=E.dom?.type??null,j=null;E.ax.value!==void 0&&E.ax.value!==null&&(j=String(E.ax.value)),E.ax.checked!==void 0&&(j=String(E.ax.checked)),Yx({role:H,kind:U})&&(j="[redacted]");let K={disabled:E.ax.disabled??!1};E.ax.checked!==void 0&&(K.checked=E.ax.checked===!0||E.ax.checked==="mixed"),E.ax.selected!==void 0&&(K.selected=E.ax.selected),E.ax.expanded!==void 0&&(K.expanded=E.ax.expanded);let Y;E.dom?.testId?Y=`[data-testid="${E.dom.testId}"]`:E.dom?.id&&(Y=`#${E.dom.id}`);let Ft={id:N,role:H,label:RV(M),kind:U,value:j,state:K,bbox:$};return Y!==void 0&&(Ft.selector=Y),Ft}),I="idle";try{let E=await t.evaluate(()=>document.readyState);E==="loading"?I="loading":E==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=CV(f),T=`obs_${e.observationCounter.toString(36)}`,R=new Date().toISOString();return{observationId:T,url:m,title:g,textSummary:C,interactive:A,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:R}}var pR,mR,gR=h(()=>{"use strict";Od();pR=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);mR="a[href], button, input, select, textarea, [role], [tabindex], label"});async function hR(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function iy(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>hR(t,s)))).filter(o=>o!==null)}async function DV(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function ay(t,e,n){switch(e.kind){case"element_id":return FV(t,e,n);case"selector":return LV(t,e);case"semantic":return NV(t,e)}}async function FV(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await iy(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function LV(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await iy(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function NV(t,e){return e.role!==void 0?$V(t,e.text,e.role):UV(t,e.text,e)}async function $V(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await iy(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function UV(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await DV(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await hR(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${g}`,v=0;for(let _=0;_<w.length;_++)v=v*31+w.charCodeAt(_)>>>0;f.push({...b,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var yR=h(()=>{"use strict"});async function cy(t,e,n,r){let o=t.url();if(o===n)return null;let s=It(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var bR=h(()=>{"use strict";Ln()});var dy={};mo(dy,{PlaywrightProvider:()=>ly});function wR(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var ly,uy=h(()=>{"use strict";dR();gR();yR();Ln();bR();ey();ly=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Nd(e)}async open(e){let n=It(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await cy(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await $d(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await $d(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await ay(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${wR(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await cy(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await $d(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await ay(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${wR(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Jo(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Jo(n,o,r);return s}catch{return null}}}});var Ur={};mo(Ur,{__resetBrowserRegistryForTests:()=>qV,browserProviderActive:()=>HV,closeBrowserProvider:()=>fy,getBrowserProvider:()=>jV,getLastRoutingDecision:()=>KV,peekBrowserProvider:()=>WV});function SR(){Promise.resolve(fy()).then(()=>{process.exit(130)})}function kR(){Promise.resolve(fy()).then(()=>{process.exit(143)})}function vR(){Xt=null}function BV(){Ud||(process.on("SIGINT",SR),process.on("SIGTERM",kR),process.on("exit",vR),Ud=!0)}function TR(){Ud&&(process.removeListener("SIGINT",SR),process.removeListener("SIGTERM",kR),process.removeListener("exit",vR),Ud=!1)}async function jV(t){return Xt!==null?Xt:($r!==null||($r=(async()=>{let e=Vh(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await Jx({config:e,surface:n});py=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(iR(),sR)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(uy(),dy));o=new s(e)}return BV(),Xt=o,$r=null,o})()),$r)}async function fy(){if(Xt===null)return;let t=Xt;Xt=null,$r=null,TR(),await t.shutdown()}function HV(){return Xt!==null}function WV(){return Xt}function KV(){return py}function qV(){Xt=null,$r=null,py=null,TR()}var Xt,$r,Ud,py,Br=h(()=>{"use strict";Ln();Vx();F();Xt=null,$r=null,Ud=!1,py=null});async function ER(t,e){try{return await Lx(t,e)}catch(n){return D("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function YV(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Br(),Ur)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(uy(),dy)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(Ln(),Yh)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function _R(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??YV,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Fn(n,t,{headers:VV,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(JV.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(zV.test(p)&&!XV.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await ER(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof Ce||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=Gh({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await ea(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>ea(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await ea(u.finalUrl,o);let p=await ER(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Gh({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof Ce)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var XV,zV,JV,VV,AR=h(()=>{"use strict";Nx();Xh();Lr();ie();XV=/(text\/html|application\/xhtml\+xml)/i,zV=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,JV=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,VV={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function e4(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(QV,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),ZV),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Q(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function xR(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?e4({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function RR(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
328
|
+
${gt(t,{headless:e,latched:n})}`,{cause:t})}var cR,SV,kV,aR,TV,sy=h(()=>{"use strict";cR=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],SV="pnpm exec playwright install chromium",kV=4;TV="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Nr from"node:fs";import Ld from"node:path";import{randomBytes as EV}from"node:crypto";function _V(){try{return"5.209.0"}catch{}try{let t=Ld.resolve(import.meta.dirname,"../../../package.json"),e=Nr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var AV,Nd,dR=h(()=>{"use strict";sy();B();se();AV=_V(),Nd=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Fd(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Fd(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${AV}`}}loadStorageState(e){let n=$m(e);try{if(!Nr.existsSync(n))return;let r=JSON.parse(Nr.readFileSync(n,"utf8"));return O("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){O("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=$m(e);if(!Nr.existsSync(r))return;let o=await n.storageState(),s=Ld.join(Ld.dirname(r),`.${Ld.basename(r)}.${process.pid}.${EV(4).toString("hex")}.tmp`);Nr.writeFileSync(s,JSON.stringify(o),{mode:384}),Nr.chmodSync(s,384),Nr.renameSync(s,r),O("[browser/vault] saved session",{profile:e,file:r})}catch(r){O("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as xV}from"node:crypto";function RV(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function IV(t,e,n){return`el_${xV("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function CV(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function uR(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function fR(t,e){let n=t.role??"",r=t.name??"";pR.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])fR(s,e)}async function PV(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},mR).catch(()=>[])}async function MV(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},mR).catch(()=>[])}function OV(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function $d(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=OV(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=PV(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],fR(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await MV(t)).filter(P=>pR.has(P.role??"")));let w=new Map;for(let E of p){let P=uR(E.name),H=w.get(P);(!H||H.bbox.w===0&&E.bbox.w>0)&&w.set(P,E)}let v=y.map(E=>({ax:E,dom:w.get(uR(E.name??""))})),_=r?v:v.filter(E=>E.dom?E.dom.bbox.w>0||E.dom.bbox.h>0:!0);_.sort((E,P)=>{let H=E.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(H!==M)return H-M;let N=E.dom?.bbox.x??0,$=P.dom?.bbox.x??0;return N-$}),_.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=_.slice(0,n).map((E,P)=>{let H=E.ax.role??"generic",M=E.ax.name??"",N=IV(H,M,P),$=E.dom?.bbox??{x:0,y:0,w:0,h:0},U=E.dom?.type??null,j=null;E.ax.value!==void 0&&E.ax.value!==null&&(j=String(E.ax.value)),E.ax.checked!==void 0&&(j=String(E.ax.checked)),Yx({role:H,kind:U})&&(j="[redacted]");let K={disabled:E.ax.disabled??!1};E.ax.checked!==void 0&&(K.checked=E.ax.checked===!0||E.ax.checked==="mixed"),E.ax.selected!==void 0&&(K.selected=E.ax.selected),E.ax.expanded!==void 0&&(K.expanded=E.ax.expanded);let Y;E.dom?.testId?Y=`[data-testid="${E.dom.testId}"]`:E.dom?.id&&(Y=`#${E.dom.id}`);let Ft={id:N,role:H,label:RV(M),kind:U,value:j,state:K,bbox:$};return Y!==void 0&&(Ft.selector=Y),Ft}),I="idle";try{let E=await t.evaluate(()=>document.readyState);E==="loading"?I="loading":E==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=CV(f),T=`obs_${e.observationCounter.toString(36)}`,R=new Date().toISOString();return{observationId:T,url:m,title:g,textSummary:C,interactive:A,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:R}}var pR,mR,gR=h(()=>{"use strict";Od();pR=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);mR="a[href], button, input, select, textarea, [role], [tabindex], label"});async function hR(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function iy(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>hR(t,s)))).filter(o=>o!==null)}async function DV(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function ay(t,e,n){switch(e.kind){case"element_id":return FV(t,e,n);case"selector":return LV(t,e);case"semantic":return NV(t,e)}}async function FV(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await iy(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function LV(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await iy(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function NV(t,e){return e.role!==void 0?$V(t,e.text,e.role):UV(t,e.text,e)}async function $V(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await iy(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function UV(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await DV(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await hR(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${g}`,v=0;for(let _=0;_<w.length;_++)v=v*31+w.charCodeAt(_)>>>0;f.push({...b,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var yR=h(()=>{"use strict"});async function cy(t,e,n,r){let o=t.url();if(o===n)return null;let s=It(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var bR=h(()=>{"use strict";Ln()});var dy={};mo(dy,{PlaywrightProvider:()=>ly});function wR(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var ly,uy=h(()=>{"use strict";dR();gR();yR();Ln();bR();ey();ly=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Nd(e)}async open(e){let n=It(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await cy(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await $d(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await $d(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await ay(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${wR(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await cy(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await $d(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await ay(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${wR(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Jo(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Jo(n,o,r);return s}catch{return null}}}});var Ur={};mo(Ur,{__resetBrowserRegistryForTests:()=>qV,browserProviderActive:()=>HV,closeBrowserProvider:()=>fy,getBrowserProvider:()=>jV,getLastRoutingDecision:()=>KV,peekBrowserProvider:()=>WV});function SR(){Promise.resolve(fy()).then(()=>{process.exit(130)})}function kR(){Promise.resolve(fy()).then(()=>{process.exit(143)})}function vR(){Xt=null}function BV(){Ud||(process.on("SIGINT",SR),process.on("SIGTERM",kR),process.on("exit",vR),Ud=!0)}function TR(){Ud&&(process.removeListener("SIGINT",SR),process.removeListener("SIGTERM",kR),process.removeListener("exit",vR),Ud=!1)}async function jV(t){return Xt!==null?Xt:($r!==null||($r=(async()=>{let e=Vh(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??k.AGENT_SURFACE,r=await Jx({config:e,surface:n});py=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(iR(),sR)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(uy(),dy));o=new s(e)}return BV(),Xt=o,$r=null,o})()),$r)}async function fy(){if(Xt===null)return;let t=Xt;Xt=null,$r=null,TR(),await t.shutdown()}function HV(){return Xt!==null}function WV(){return Xt}function KV(){return py}function qV(){Xt=null,$r=null,py=null,TR()}var Xt,$r,Ud,py,Br=h(()=>{"use strict";Ln();Vx();F();Xt=null,$r=null,Ud=!1,py=null});async function ER(t,e){try{return await Lx(t,e)}catch(n){return O("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function YV(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Br(),Ur)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(uy(),dy)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(Ln(),Yh)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function _R(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??YV,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Fn(n,t,{headers:VV,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(JV.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(zV.test(p)&&!XV.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await ER(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof Ce||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=Gh({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await ea(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>ea(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await ea(u.finalUrl,o);let p=await ER(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Gh({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof Ce)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var XV,zV,JV,VV,AR=h(()=>{"use strict";Nx();Xh();Lr();se();XV=/(text\/html|application\/xhtml\+xml)/i,zV=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,JV=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,VV={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function e4(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(QV,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),ZV),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Q(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function xR(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?e4({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function RR(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
329
329
|
|
|
330
330
|
(no results)`;let n=[`# Search results for "${t}"`,""];return e.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
331
331
|
`).trimEnd()}var QV,ZV,IR=h(()=>{"use strict";et();QV="https://api.exa.ai/search",ZV=10});function Bd(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var jr=h(()=>{"use strict";sy()});function i4(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=t4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,n4)}let a=r4;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,o4)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function my(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:_t(t,e),truncated:!0}}function a4(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env,r=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{};return async(o,s)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let i=i4(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let u=s.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,c=()=>{a.abort(s.reason)},l,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(s.addEventListener("abort",c,{once:!0}),l=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.url!==void 0){let p=await Fr(i.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(i.mode==="raw"){let p;try{let g={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await Fn(e,i.url,g,r)}catch(g){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:g instanceof Ce?{content:`web_scrape blocked: ${g.message}`,isError:!0}:{content:`web_scrape network error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let f;try{f=await p.text()}catch(g){return{content:`web_scrape read error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}let m=my(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await _R(i.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:i.timeoutMs,signal:a.signal,...t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0};let f=my($x(p.markdown,p.advisory),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(p instanceof Ce)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=ze(p)&&!oy(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${ta()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=xR({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in u)return{content:u.error,isError:!0};try{let p=await u.search(i.query,{limit:s4,timeoutMs:i.timeoutMs,signal:a.signal}),f=my(RR(i.query,p),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),s.removeEventListener("abort",c)}}}var t4,n4,r4,o4,s4,CR,PR=h(()=>{"use strict";AR();IR();Lr();Ht();Xh();jr();t4=3e4,n4=12e4,r4=1e5,o4=1e6,s4=10;CR=a4()});function d4(t){return c4.has(t)?"low":t==="DELETE"?"high":"medium"}function u4(t){return l4.has(t)}function m4(t){let e={};return t.forEach((n,r)=>{let o=r.toLowerCase();f4.has(o)||p4.some(s=>o.startsWith(s))||(e[r]=n)}),e}function g4(t,e){if(t==null)return{serialized:void 0,inferredContentType:void 0};let n=Object.keys(e).some(o=>o.toLowerCase()==="content-type");return typeof t=="string"?{serialized:t,inferredContentType:n?void 0:"text/plain"}:{serialized:JSON.stringify(t),inferredContentType:n?void 0:"application/json"}}function h4(t,e,n){let r=Buffer.byteLength(t,"utf8"),o=t,s=!1;if(r>n&&(o=_t(t,n),s=!0),!s&&/application\/json/i.test(e))try{return{body:JSON.parse(o),truncated:!1}}catch{}return{body:o,truncated:s}}async function DR(t){let{url:e,method:n,signal:r,domainCheck:o,recordEffect:s}=t,i=Math.min(t.maxResponseBytes??gy,hy),a={...t.headers},c=t.fetchFn??globalThis.fetch,l=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},d=d4(n);if(o!==void 0){let T=o(e);if(!T.allowed)throw Object.assign(new Error(`web_request blocked by domain policy: ${T.reason}`),{name:"DomainPolicyError"})}let u=await Fr(e,l);if(!u.allowed)throw new Ce(u.reason);let{serialized:p,inferredContentType:f}=g4(t.body,a);f!==void 0&&(a["content-type"]=f);let m={method:n,headers:Object.keys(a).length>0?a:void 0,body:p,signal:r},y=u4(n)?{retries:2,baseDelayMs:300,maxDelayMs:5e3}:{retries:0},b=Date.now(),w;try{w=await Fn(c,e,m,{...l,retry:y})}catch(T){throw T instanceof Ce,T}let v=Date.now()-b,_=w.headers.get("content-type")??"",x;try{let T=w.body?.getReader();if(!T)x="";else{let R=[],E=0,P=i*2;for(;;){let{done:H,value:M}=await T.read();if(H||!M)break;if(R.push(M),E+=M.byteLength,E>=P){await T.cancel();break}}x=new TextDecoder().decode(Buffer.concat(R,E))}}catch{x=""}let{body:A,truncated:I}=h4(x,_,i),C=m4(w.headers);return s!==void 0&&Promise.resolve(s({url:e,method:n,status:w.status,risk:d,timing_ms:v})).catch(()=>{}),{status:w.status,headers:C,body:A,truncated:I,timing_ms:v,risk:d}}function FR(t){if(typeof t!="string"||t.trim().length===0)return{error:"method must be a non-empty string (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)"};let e=t.trim().toUpperCase(),n=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];return n.includes(e)?e:{error:`method "${t}" is not supported \u2014 must be one of: ${n.join(", ")}`}}var MR,OR,gy,hy,c4,l4,p4,f4,LR=h(()=>{"use strict";Lr();Ht();MR=3e4,OR=12e4,gy=1e5,hy=1e6,c4=new Set(["GET","HEAD","OPTIONS"]),l4=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]);p4=["set-cookie","x-"],f4=new Set(["server","via","age","vary","authorization","www-authenticate"])});function y4(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t;if(typeof e.url!="string"||e.url.length===0)return{error:'Invalid input: "url" must be a non-empty string'};let n;try{n=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{error:`Invalid input: protocol "${n.protocol}" not supported (http/https only)`};n.username="",n.password="";let r=n.toString(),o=FR(e.method);if(typeof o=="object"&&"error"in o)return{error:`Invalid input: ${o.error}`};let s=o,i;if(e.body!==void 0&&e.body!==null){if(typeof e.body!="string"&&typeof e.body!="object")return{error:'Invalid input: "body" must be a string, object, or array'};i=e.body}let a={};if(e.headers!==void 0){if(typeof e.headers!="object"||e.headers===null||Array.isArray(e.headers))return{error:'Invalid input: "headers" must be a string-keyed object'};let u=e.headers;for(let[p,f]of Object.entries(u)){if(typeof f!="string")return{error:`Invalid input: header value for "${p}" must be a string`};a[p]=f}}let c=MR;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'Invalid input: "timeout_ms" must be a positive finite number'};c=Math.min(e.timeout_ms,OR)}let l=gy;if(e.max_response_bytes!==void 0){if(typeof e.max_response_bytes!="number"||!Number.isFinite(e.max_response_bytes)||e.max_response_bytes<=0)return{error:'Invalid input: "max_response_bytes" must be a positive finite number'};l=Math.min(e.max_response_bytes,hy)}let d;if(e.credential!==void 0){if(typeof e.credential!="string"||e.credential.length===0)return{error:'Invalid input: "credential" must be a non-empty string (an env var name)'};d=e.credential}return{url:r,method:s,body:i,headers:a,timeoutMs:c,maxResponseBytes:l,credential:d}}function b4(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;async function r(){if(t.domainCheck!==void 0)return t.domainCheck;try{let{loadBrowserConfig:o,enforceDomainPolicy:s}=await Promise.resolve().then(()=>(Ln(),Yh)),i=o();return a=>s(a,i)}catch{return}}return async(o,s)=>{if(typeof e!="function")return{content:"web_request unavailable: global fetch() is not present (agent-afk requires Node 20+).",isError:!0};let i=y4(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let p=s.reason;return{content:`web_request aborted: ${p instanceof Error?p.message:String(p??"aborted")}`,isError:!0}}let a={...i.headers};if(i.credential!==void 0){let p=n[i.credential];if(p===void 0||p.trim().length===0)return{content:`web_request credential error: environment variable "${i.credential}" is not set. Set it in afk.env or export it in the shell before starting AFK.`,isError:!0};if(Object.keys(a).some(m=>m.toLowerCase()==="authorization"))return{content:'web_request credential error: both "credential" and an explicit Authorization header were provided. Use one or the other.',isError:!0};a.Authorization=`Bearer ${p}`}let c=new AbortController,l=()=>c.abort(s.reason),d,u=()=>{let p=c.signal.reason;return p instanceof Error?p.message:String(p??"aborted")};try{s.addEventListener("abort",l,{once:!0}),d=setTimeout(()=>{c.abort(new Error(`web_request timeout after ${i.timeoutMs}ms`))},i.timeoutMs);let p=await r(),f={url:i.url,method:i.method,body:i.body,headers:a,maxResponseBytes:i.maxResponseBytes,signal:c.signal,fetchFn:e,lookupFn:t.lookupFn,domainCheck:p,recordEffect:t.recordEffect},m;try{m=await DR(f)}catch(w){if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};if(w instanceof Ce)return{content:`web_request blocked: ${w.message}`,isError:!0};let v=w instanceof Error&&w.name==="DomainPolicyError"?"blocked":"network error",_=w instanceof Error?w.message:String(w);return{content:`web_request ${v}: ${_}`,isError:!0}}if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};let g=m.body;if(typeof g=="string")g=qe(g);else if(typeof g=="object"&&g!==null){let w=qe(JSON.stringify(g));try{g=JSON.parse(w)}catch{g=w}}let y={status:m.status,headers:m.headers,body:g,timing_ms:m.timing_ms,...m.truncated?{truncated:!0}:{}};return{content:JSON.stringify(y,null,2),...m.truncated?{truncated:!0}:{}}}finally{d!==void 0&&clearTimeout(d),s.removeEventListener("abort",l)}}}var NR,$R=h(()=>{"use strict";LR();Lr();vn();NR=b4()});import{existsSync as BR,mkdirSync as w4,readFileSync as S4,renameSync as k4,unlinkSync as v4,writeFileSync as T4}from"node:fs";import{dirname as UR,join as E4}from"node:path";import{randomBytes as _4}from"node:crypto";function Hr(t){let e=t??Om();if(!BR(e))return[];try{let n=S4(e,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${e}: ${r}`),[]}}function na(t,e){let n=e??Om();w4(UR(n),{recursive:!0});let r=E4(UR(n),`.schedules.json.${process.pid}.${_4(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{T4(r,o,"utf-8"),k4(r,n)}catch(s){try{BR(r)&&v4(r)}catch{}throw s}}function jR(t,e){let n=Hr(e),r=n.map(c=>c.id),o=A4(t.name),s=x4(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),na(n,e),a}function HR(t,e){let n=Hr(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(na(o,e),!0)}function WR(t,e){return Hr(e).find(n=>n.id===t)}function A4(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function x4(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}function KR(t){return{taskId:t.id,command:t.command,trigger:t.trigger??"cron",...t.cron!==void 0?{cronExpression:t.cron}:{},...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{},...t.notifyChat!==void 0?{notifyChat:t.notifyChat}:{}}}var qR=h(()=>{"use strict";B()});import{existsSync as R4,readFileSync as I4}from"node:fs";import{join as C4}from"node:path";async function Vo(t,e,n){let r,o;try{let s=C4(Iv("default"),"port");if(!R4(s))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=I4(s,"utf-8").trim(),a=P4(i);if(!a)return{synced:!1,detail:"daemon-not-detected (invalid port file)"};({host:r,port:o}=a)}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let s=r.includes(":")?`[${r}]`:r,i=await fetch(`http://${s}:${o}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return i.ok?{synced:!0,detail:"synced"}:t==="POST"&&i.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&i.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${i.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function P4(t){let e=parseInt(t,10);if(String(e)===t&&!Number.isNaN(e))return e<1||e>65535?null:{host:"localhost",port:e};let n=t.lastIndexOf(":");if(n<1)return null;let r=t.slice(0,n),o=t.slice(n+1);if(!/^\d+$/.test(o))return null;let s=parseInt(o,10);return Number.isNaN(s)||s<1||s>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:s}}var yy,GR=h(()=>{"use strict";B();yy="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as M4}from"node:fs";import{readFile as O4}from"node:fs/promises";var XR,zR,JR,VR,YR=h(()=>{"use strict";qR();B();GR();XR=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let s=jR({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),i=s.enabled?await Vo("POST","/tasks",{taskId:s.id,command:s.command,cron:s.cron,trigger:s.trigger,notifyOn:s.notifyOn,...s.notifyChat!==void 0?{notifyChat:s.notifyChat}:{}}):await Vo("DELETE",`/tasks/${s.id}`);return{content:JSON.stringify({id:s.id,name:s.name,cron:s.cron,enabled:s.enabled,daemonSynced:i.synced,syncDetail:i.detail,...i.synced?{}:{syncNote:yy}})}},zR=async(t,e)=>{let n=Hr();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},JR=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,s=Bc();if(!M4(s))return{content:JSON.stringify([])};let i;try{let l=await O4(s);i=(l.length>1048576?l.subarray(l.length-1048576):l).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
|
|
@@ -343,7 +343,7 @@ ${gt(t,{headless:e,latched:n})}`,{cause:t})}var cR,SV,kV,aR,TV,sy=h(()=>{"use st
|
|
|
343
343
|
?`,"m");if(!r.test(n))return!1;let o=n.replace(r,"");return Vd(t,o,384),!0}function EI(t,e){if(!sa(t))return;let r=Jd(t,"utf-8").match(new RegExp(`^${Pe(e)}=(.*)$`,"m"));return r?r[1]:void 0}function _I(t){let e={};if(!sa(t))return e;let n=Jd(t,"utf-8");for(let r of n.split(`
|
|
344
344
|
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s<=0)continue;let i=o.slice(0,s).trim(),a=o.slice(s+1);e[i]=a}return e}var My=h(()=>{"use strict";Kr()});function Yd(t){let e=ti(t);return e?M5.has(t)?"non-config":e.secret?"secret":O5.has(t)||t.endsWith("_BASE_URL")?"protected":"settable":"unknown"}function AI(t,e=D5,n=F5){let r=t.trim().toLowerCase();if(e.includes(r))return!0;if(n.includes(r))return!1}function xI(t){let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:void 0}function RI(t,e){if(e.includes(`
|
|
345
345
|
`))return{ok:!1,error:`value for ${t.name} must not contain newlines`};switch(t.type){case"number":return xI(e)===void 0?{ok:!1,error:`${t.name} expects a number, got ${JSON.stringify(e)}`}:{ok:!0,value:e.trim()};case"boolean":{let n=e.trim().toLowerCase();return AI(n)===void 0?{ok:!1,error:`${t.name} expects a boolean (true/false/1/0/yes/no/on/off), got ${JSON.stringify(e)}`}:{ok:!0,value:n}}case"json":{try{JSON.parse(e)}catch{return{ok:!1,error:`${t.name} expects valid JSON`}}return{ok:!0,value:e}}default:return{ok:!0,value:e}}}function CI(t){return II.get(t)}function Oy(t){let e=II.get(t);return e?e.tier:"unknown"}function PI(t,e){switch(t.type){case"boolean":{if(typeof e=="boolean")return{ok:!0,value:e};if(typeof e=="string"){let n=AI(e);if(n!==void 0)return{ok:!0,value:n}}return{ok:!1,error:`${t.path} expects a boolean`}}case"number":{let n=typeof e=="number"||typeof e=="string"?xI(e):void 0;return n===void 0?{ok:!1,error:`${t.path} expects a number`}:t.clamp?t.clamp.integer&&!Number.isInteger(n)?{ok:!1,error:`${t.path} expects an integer`}:{ok:!0,value:Math.min(t.clamp.max,Math.max(t.clamp.min,n))}:{ok:!0,value:n}}case"enum":return typeof e=="string"&&t.enumValues?.includes(e)?{ok:!0,value:e}:{ok:!1,error:`${t.path} expects one of: ${t.enumValues?.join(", ")}`};case"number-array":{let n;if(Array.isArray(e))n=e;else if(typeof e=="string")n=e.split(",").map(o=>o.trim()).filter(o=>o.length>0).map(o=>Number(o));else return{ok:!1,error:`${t.path} expects an array of numbers`};let r=[];for(let o of n){let s=typeof o=="number"?o:Number(o);if(!Number.isFinite(s))return{ok:!1,error:`${t.path} contains a non-number`};r.push(s)}return{ok:!0,value:r}}case"model-slot":{if(typeof e=="string")return e.trim().length===0?{ok:!1,error:`${t.path} must not be empty`}:{ok:!0,value:e.trim()};let n=aE(e);return n.ok?{ok:!0,value:n.value}:{ok:!1,error:`${t.path}: ${n.error}`}}default:return typeof e!="string"?{ok:!1,error:`${t.path} expects a string`}:e.trim().length===0?{ok:!1,error:`${t.path} must not be empty`}:{ok:!0,value:e}}}function MI(t,e){let n=t;for(let r of e.split(".")){if(n===null||typeof n!="object")return;n=n[r]}return n}function OI(t,e,n){let r=e.split("."),o=t;for(let s=0;s<r.length-1;s++){let i=r[s],a=o[i];(a===null||typeof a!="object"||Array.isArray(a))&&(o[i]={}),o=o[i]}o[r[r.length-1]]=n}function DI(t,e){let n=e.split("."),r=[t],o=t;for(let i=0;i<n.length-1;i++){let a=n[i],c=o[a];if(c===null||typeof c!="object"||Array.isArray(c))return!1;o=c,r.push(o)}let s=n[n.length-1];if(!(s in o))return!1;delete o[s];for(let i=r.length-1;i>=1;i--){let a=r[i];if(Object.keys(a).length===0){let c=n[i-1];delete r[i-1][c]}else break}return!0}var M5,O5,D5,F5,L5,II,FI=h(()=>{"use strict";F();Fe();M5=new Set(["HOME","PATH","SHELL","PAGER","NODE_ENV","CI","VITEST","DEBUG","FORCE_COLOR","NO_COLOR","AGENT_SURFACE","AFK_SESSION_ID","NO_UPDATE_NOTIFIER","SCRIPT","ASCIINEMA_REC"]),O5=new Set(["AFK_MODEL_SMALL_BASE_URL","AFK_MODEL_MEDIUM_BASE_URL","AFK_MODEL_LARGE_BASE_URL","AFK_LOCAL_BASE_URL","AFK_OPENAI_BASE_URL","AFK_SYSTEM_PROMPT","AFK_DAEMON_TASK","AFK_DAEMON_TASK_ID","AFK_DAEMON_CWD","AFK_DAEMON_HOST","AFK_BROWSER_ALLOWED_DOMAINS","AFK_BROWSER_BLOCKED_DOMAINS","AFK_BROWSER_CONFIG","AFK_ALLOW_PROJECT_MCP","AFK_INTERNAL","AFK_WORKTREE_BASE","AFK_WORKTREE_BRANCH_PREFIX","AFK_WORKTREE_ON_EXIT","AFK_TELEGRAM_ALLOWED_CHAT_IDS","AFK_TELEGRAM_TAG_ONLY_CHAT_IDS","AFK_TELEGRAM_NOTIFY_MODE","AFK_TELEGRAM_PRIMARY_CHAT_ID","AFK_HOME","AFK_STATE_DIR","AFK_FRAMEWORK_DIR","TELEGRAM_DATA_DIR","AFK_TELEGRAM_CWD"]);D5=["true","1","yes","on"],F5=["false","0","no","off"];L5=[{path:"model",tier:"agent",type:"string",description:"Default model id / alias."},{path:"models.local",tier:"agent",type:"model-slot",description:"Local-tier model id (OpenAI-compatible shim: Ollama, LM Studio, vLLM, MLX). Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth | xai | xai-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"models.small",tier:"agent",type:"model-slot",description:"Small-tier model id. Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth | xai | xai-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"models.medium",tier:"agent",type:"model-slot",description:"Medium-tier model id. Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth | xai | xai-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"models.large",tier:"agent",type:"model-slot",description:"Large-tier model id. Accepts a bare id string or a { id, provider, name } object (provider: anthropic | openai | chatgpt-oauth | xai | xai-oauth \u2014 chatgpt is accepted shorthand; baseUrl/apiKey are human-gated: set them via the AFK_MODEL_<TIER>_BASE_URL / _API_KEY env vars, not here)."},{path:"maxTokens",tier:"agent",type:"number",clamp:{min:1,max:1e6,integer:!0},description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS or --max-output-tokens to cap per-response output."},{path:"temperature",tier:"agent",type:"number",clamp:{min:0,max:2},description:"Sampling temperature."},{path:"autoRouting.interactive",tier:"agent",type:"boolean",description:"Auto-route model in the REPL."},{path:"autoRouting.chat",tier:"agent",type:"boolean",description:"Auto-route model for chat."},{path:"autoRouting.telegram",tier:"agent",type:"boolean",description:"Auto-route model for Telegram."},{path:"autoRouting.daemon",tier:"agent",type:"boolean",description:"Auto-route model for the daemon."},{path:"telegram.notify.mode",tier:"human",type:"enum",enumValues:["primary","broadcast","custom"],description:"Telegram notify routing mode (human-tier: notification-redirect vector)."},{path:"telegram.notify.primaryChatId",tier:"human",type:"number",clamp:{min:-1e15,max:1e15,integer:!0},description:"Primary Telegram chat id (human-tier: notification-redirect vector)."},{path:"telegram.notify.targets",tier:"human",type:"number-array",description:"Custom Telegram target chat ids (human-tier: notification-redirect vector)."},{path:"telegram.tagOnlyChats",tier:"human",type:"number-array",description:"Chat ids where the bot answers only when addressed (reply to the bot, @mention, or text_mention resolving to the bot). Human-tier: it governs which chats the bot will respond in \u2014 a message-routing / who-can-drive-the-bot control, same class as the allowlist and telegram.notify.*. Requires Telegram privacy mode OFF for the bot to matter in groups."},{path:"telegram.verifyDone",tier:"human",type:"boolean",description:`Opt-in AFK "Done" verification gate (human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as enableShellHooks/permissionMode).`},{path:"enforceDoneEvidence",tier:"human",type:"boolean",description:'Opt-in AFK terminal-state enforcement gate: in autonomous mode a turn that self-certifies "Done" with no corroborating evidence (a successful file write/edit or executed command) gets a framework correction injected into the next turn, which must substantiate or downgrade the claim (issue #237). Human-tier: a self-honesty check the agent must not be able to disable on its own config, same rationale as telegram.verifyDone. Sibling of telegram.verifyDone (which only relabels the Telegram push; this one bounces the turn).'},{path:"interactive.worktreeAutoname",tier:"agent",type:"boolean",description:"Auto-name worktrees."},{path:"interactive.suggestGhost",tier:"agent",type:"boolean",description:"Ghost-text suggestions in the REPL."},{path:"interactive.thinkingUi",tier:"agent",type:"enum",enumValues:["summary","live","digest","off"],description:"Default REPL thinking-display mode."},{path:"theme",tier:"agent",type:"enum",enumValues:["dark","light","umber","auto"],description:"TUI color palette (dark | light | umber | auto). Display-only; auto detects a light/dark background from the terminal and falls back to dark. umber matches the Umber terminal and is dark-only, so auto never selects it."},{path:"updatePolicy",tier:"human",type:"enum",enumValues:["notify","auto","off"],description:"Self-update policy (human-tier: auto self-update is scope-widening)."},{path:"autoResumeOnUsageLimit",tier:"agent",type:"boolean",description:"Auto-resume after a usage-limit pause."},{path:"bgSummaries",tier:"agent",type:"boolean",description:"Background summarisation."},{path:"maxSummaryCallsPerSession",tier:"agent",type:"number",clamp:{min:1,max:500,integer:!0},description:"Cap on summary calls per session."},{path:"systemPrompt",tier:"human",type:"string",description:"Operator system-prompt overlay."},{path:"permissionMode",tier:"human",type:"enum",enumValues:["default","plan","autonomous","bypassPermissions"],description:"Session permission mode for afk chat/interactive (human-tier: privilege-escalation vector). Unset \u2192 bypassPermissions (new-install default); set `default` to re-enable path containment + the approval prompt."},{path:"enableShellHooks",tier:"human",type:"boolean",description:"Enable shell hooks (trust gate)."},{path:"enablePluginHooks",tier:"human",type:"boolean",description:"Enable Claude Code plugin-contributed hooks (trust gate for third-party plugin hooks.json; independent of enableShellHooks)."},{path:"interactive.worktreeBranchPrefix",tier:"human",type:"string",description:"Worktree branch prefix (git-flag sensitive)."},{path:"interactive.worktreeBase",tier:"human",type:"string",description:"Worktree base ref (git-flag sensitive)."},{path:"interactive.worktreeOnExit",tier:"human",type:"enum",enumValues:["ask","keep","remove"],description:"Clean-worktree quit policy (ask | keep | remove)."},{path:"daemon.task",tier:"human",type:"string",description:"Daemon task prompt."},{path:"daemon.taskId",tier:"human",type:"string",description:"Daemon task id."},{path:"daemon.verifyDone",tier:"human",type:"boolean",description:`Opt-in daemon-surface "Done" verification gate: a cron-tick completion push whose response self-certifies "Done" with no corroborating evidence (a successful file write/edit or executed command) is relabelled "\u26A0\uFE0F Done (unverified)" with a caveat line. The daemon analog of telegram.verifyDone (which is REPL-only); the daemon is single-turn-per-tick, so the only honest enforcement is relabelling the outgoing push rather than bouncing a next turn. Human-tier: a self-honesty check on the agent's own completion reporting \u2014 the agent must not be able to disable it on its own config, same rationale as telegram.verifyDone.`}],II=new Map(L5.map(t=>[t.path,t]))});import{existsSync as LI,readFileSync as N5,copyFileSync as $5,chmodSync as U5}from"fs";function $y(t){return t===void 0||t.length===0?"<unset>":t.length<=4?"set (****)":`set (****${t.slice(-4)})`}function eu(t){return t?.filePath??ar()}function NI(t,e,n){let r=Yd(t);if(r==="unknown")throw new ia(t);if(r==="non-config")throw new Dy(t);if(r==="secret"&&!e)throw new Fy(t);if(r==="protected"&&!n)throw new Ly(t);return r}function $I(t,e,n){let r=NI(t,n?.allowSecret,n?.allowProtected),o=ti(t),s=RI(o,e);if(!s.ok)throw new Qd(s.error);let i=eu(n);return Py(i,t,s.value),{key:t,class:r,persistedTo:i,display:r==="secret"?$y(s.value):s.value}}function UI(t,e){let n=NI(t,e?.allowSecret,e?.allowProtected),r=eu(e),o=TI(r,t);return{key:t,class:n,removed:o,persistedTo:r}}function BI(t,e){let n=Yd(t);if(n==="unknown")throw new ia(t);let r=eu(e),o=EI(r,t),s=$c(t),i=n==="secret"?o!==void 0?$y(o):void 0:o;return{key:t,class:n,persisted:i,activeInProcess:s}}function jI(t){let e=eu(t),n=_I(e),r=[];for(let o of ni){let s=o.name,i=Yd(s),a=n[s],c=$c(s);if(!t?.all&&a===void 0&&!c)continue;let l=i==="secret"?a!==void 0?$y(a):void 0:a;r.push({key:s,class:i,persisted:l,activeInProcess:c})}return r}function tu(t){return t?.filePath??on()}function nu(t){if(!LI(t))return{};let e;try{e=JSON.parse(N5(t,"utf-8"))}catch{throw new Zd(t)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Zd(t);return e}function HI(t,e){if(LI(t))try{$5(t,`${t}.bak`),U5(`${t}.bak`,384)}catch{}Vd(t,JSON.stringify(e,null,2)+`
|
|
346
|
-
`,384)}function WI(t,e){let n=Oy(t);if(n==="unknown")throw new ia(t);if(n==="human"&&!e)throw new Ny(t);return n}function KI(t,e,n){let r=WI(t,n?.allowHumanOnly),o=CI(t),s=PI(o,e);if(!s.ok)throw new Qd(s.error);let i=tu(n),a=nu(i);return OI(a,t,s.value),HI(i,a),{path:t,class:r,value:s.value,persistedTo:i}}function qI(t,e){let n=WI(t,e?.allowHumanOnly),r=tu(e),o=nu(r),s=DI(o,t);return s&&HI(r,o),{path:t,class:n,removed:s,persistedTo:r}}function GI(t,e){let n=Oy(t),r=tu(e),o=nu(r);return{path:t,class:n,value:MI(o,t)}}function XI(t){return nu(tu(t))}var aa,ia,Dy,Fy,Ly,Ny,Qd,Zd,zI=h(()=>{"use strict";B();F();My();FI();aa="effective on the next session/daemon restart; the current session is unchanged",ia=class extends Error{constructor(e){super(`unknown config key: ${e}`),this.name="UnknownKeyError"}},Dy=class extends Error{constructor(e){super(`${e} is a process/inherited env var and is not afk-configurable`),this.name="NonConfigKeyError"}},Fy=class extends Error{constructor(e){super(`${e} holds a credential; the agent cannot set it. A human must run \`afk config env set ${e}\` (the value is entered masked and never enters the model context).`),this.name="SecretWriteRefused"}},Ly=class extends Error{constructor(e){super(`${e} controls identity, safety, capability, autonomous runs, request routing, or where AFK's own state lives; the agent cannot set it. A human must run \`afk config env set ${e}\`.`),this.name="ProtectedEnvKeyRefused"}},Ny=class extends Error{constructor(e){super(`${e} is human-gated (prompt/hooks/identity); the agent cannot set it. A human must run \`afk config set ${e}\`.`),this.name="HumanOnlyKeyRefused"}},Qd=class extends Error{constructor(e){super(e),this.name="ConfigValidationError"}},Zd=class extends Error{constructor(e){super(`refusing to write: existing ${e} is not valid JSON (fix or remove it by hand first)`),this.name="MalformedConfigError"}}});function JI(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function VI(t){return t==="env"||t==="config"?t:void 0}function dn(t){return{content:t,isError:!0}}var YI,QI,ZI=h(()=>{"use strict";zI();YI=async t=>{let e=JI(t);if(!e)return dn("config_get: expected an object input");let n=VI(e.target);if(!n)return dn("config_get: `target` must be 'env' or 'config'");let r=typeof e.key=="string"?e.key:void 0,o=e.all===!0;try{if(n==="env"){if(r){let s=BI(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(jI({all:o}),null,2)}}if(r){let s=GI(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(XI(),null,2)}}catch(s){return dn(`config_get: ${s.message}`)}},QI=async t=>{let e=JI(t);if(!e)return dn("config_set: expected an object input");let n=VI(e.target);if(!n)return dn("config_set: `target` must be 'env' or 'config'");let r=typeof e.key=="string"?e.key:void 0;if(!r)return dn("config_set: `key` is required");let o=e.action==="unset"?"unset":"set",s=e.value;try{if(o==="unset"){if(n==="env"){let c=UI(r);return{content:c.removed?`Removed ${c.key} from afk.env (${c.persistedTo}). ${aa}.`:`${c.key} was not set in afk.env; nothing to remove.`}}let a=qI(r);return{content:a.removed?`Removed ${a.path} from afk.config.json (${a.persistedTo}). ${aa}.`:`${a.path} was not set in afk.config.json; nothing to remove.`}}if(s==null)return dn(`config_set: \`value\` is required to set ${r}`);if(n==="env"){if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")return dn("config_set: env values must be a string, number, or boolean");let a=$I(r,String(s));return{content:`Set ${a.key} = ${a.display} in afk.env (${a.persistedTo}). ${aa}.`}}let i=KI(r,s);return{content:`Set ${i.path} = ${JSON.stringify(i.value)} in afk.config.json (${i.persistedTo}). ${aa}.`}}catch(i){return dn(`config_set: ${i.message}`)}}});function qr(t,e){return t.length>e?`${t.slice(0,e)}\u2026 [truncated]`:t}function Uy(t){switch(t.type){case"message":return t.message.role!=="assistant"||!t.message.content?null:{kind:"assistant",text:qr(t.message.content,8e3)};case"chunk":{let e=t.chunk;return e.type==="tool_use_detail"?e.pending?null:{kind:"tool",toolName:e.toolName,toolUseId:e.toolUseId,input:qr(e.toolInput,400)}:e.type==="tool_result"?e.isError===!0?{kind:"tool_error",content:qr(e.content,400),...e.metadata?.toolName!==void 0?{toolName:String(e.metadata.toolName)}:{}}:{kind:"tool_result",toolUseId:e.toolUseId,content:qr(e.content,400),...typeof e.durationMs=="number"?{durationMs:e.durationMs}:{},...e.metadata?.toolName!==void 0?{toolName:String(e.metadata.toolName)}:{}}:e.type==="thinking"?{kind:"thinking",text:qr(e.content,8e3)}:null}case"done":{let e=t.metadata,n=e?.totalCostUsd,r=e?.durationMs,o=e?.usage,s=typeof o?.input_tokens=="number"?o.input_tokens:void 0,i=typeof o?.output_tokens=="number"?o.output_tokens:void 0,a=typeof o?.cache_read_input_tokens=="number"?o.cache_read_input_tokens:void 0,c=typeof e?.stopReason=="string"?e.stopReason:void 0;return{kind:"done",...typeof n=="number"?{costUsd:n}:{},...typeof r=="number"?{durationMs:r}:{},...s!==void 0?{inputTokens:s}:{},...i!==void 0?{outputTokens:i}:{},...a!==void 0?{cacheReadTokens:a}:{},...c!==void 0?{stopReason:c}:{}}}case"error":return{kind:"error",message:t.error.message};case"paused":return{kind:"paused",...t.resetsAt?{resetsAt:t.resetsAt.toISOString()}:{}};case"resumed":return{kind:"resumed"};case"notice":return null;case"tool-activity":return{kind:"tool_activity",activeCount:t.activeCount,activeToolUseIds:t.activeToolUseIds};case"rate_limit":return{kind:"rate_limit",...typeof t.retryAfterMs=="number"?{retryAfterMs:t.retryAfterMs}:{}};case"progress":return{kind:"progress",message:t.progress.summary??t.progress.description};case"subagent_lifecycle":return{kind:"subagent_lifecycle",subagentId:t.subagentId,status:t.status,...t.model!==void 0?{model:t.model}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.totalCostUsd!==void 0?{totalCostUsd:t.totalCostUsd}:{},...t.outputBytes!==void 0?{outputBytes:t.outputBytes}:{},...t.errorClass!==void 0?{errorClass:t.errorClass}:{},...t.errorMessage!==void 0?{errorMessage:t.errorMessage}:{},...t.promptHead!==void 0?{promptHead:t.promptHead}:{}};case"background_job":return{kind:"background_job",jobId:t.jobId,status:t.status,...t.label!==void 0?{label:t.label}:{}};case"plan_mode":return{kind:"plan_mode",mode:t.mode};default:return null}}var By=h(()=>{"use strict"});import*as eC from"node:fs";import*as Gr from"node:fs/promises";import*as tC from"node:readline";function nC(t){let e=t.trim();if(!e)return null;try{let n=JSON.parse(e);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function ca(t){if(!lr(t))return!1;try{return await Gr.access(So(t)),!0}catch{return!1}}async function*jy(t){if(!lr(t))return;let e;try{e=await Gr.open(So(t),"r")}catch(n){if(n.code==="ENOENT")return;throw n}try{let n=tC.createInterface({input:e.createReadStream({encoding:"utf8"}),crlfDelay:1/0});for await(let r of n){let o=nC(r);o&&(yield o)}}finally{await e.close()}}async function*Hy(t,e){if(!lr(t))return;let n=So(t),r=wo(t),{fromStart:o=!1,signal:s}=e??{},i=0,a="",c=!1;async function*l(){let f=null;try{f=await Gr.open(n,"r");let m=await f.stat();if(m.size<=i)return;let g=m.size-i,y=Buffer.allocUnsafe(g),{bytesRead:b}=await f.read(y,0,g,i);if(b===0)return;i+=b,a+=y.toString("utf8",0,b);let w=a.split(`
|
|
346
|
+
`,384)}function WI(t,e){let n=Oy(t);if(n==="unknown")throw new ia(t);if(n==="human"&&!e)throw new Ny(t);return n}function KI(t,e,n){let r=WI(t,n?.allowHumanOnly),o=CI(t),s=PI(o,e);if(!s.ok)throw new Qd(s.error);let i=tu(n),a=nu(i);return OI(a,t,s.value),HI(i,a),{path:t,class:r,value:s.value,persistedTo:i}}function qI(t,e){let n=WI(t,e?.allowHumanOnly),r=tu(e),o=nu(r),s=DI(o,t);return s&&HI(r,o),{path:t,class:n,removed:s,persistedTo:r}}function GI(t,e){let n=Oy(t),r=tu(e),o=nu(r);return{path:t,class:n,value:MI(o,t)}}function XI(t){return nu(tu(t))}var aa,ia,Dy,Fy,Ly,Ny,Qd,Zd,zI=h(()=>{"use strict";B();F();My();FI();aa="effective on the next session/daemon restart; the current session is unchanged",ia=class extends Error{constructor(e){super(`unknown config key: ${e}`),this.name="UnknownKeyError"}},Dy=class extends Error{constructor(e){super(`${e} is a process/inherited env var and is not afk-configurable`),this.name="NonConfigKeyError"}},Fy=class extends Error{constructor(e){super(`${e} holds a credential; the agent cannot set it. A human must run \`afk config env set ${e}\` (the value is entered masked and never enters the model context).`),this.name="SecretWriteRefused"}},Ly=class extends Error{constructor(e){super(`${e} controls identity, safety, capability, autonomous runs, request routing, or where AFK's own state lives; the agent cannot set it. A human must run \`afk config env set ${e}\`.`),this.name="ProtectedEnvKeyRefused"}},Ny=class extends Error{constructor(e){super(`${e} is human-gated (prompt/hooks/identity); the agent cannot set it. A human must run \`afk config set ${e}\`.`),this.name="HumanOnlyKeyRefused"}},Qd=class extends Error{constructor(e){super(e),this.name="ConfigValidationError"}},Zd=class extends Error{constructor(e){super(`refusing to write: existing ${e} is not valid JSON (fix or remove it by hand first)`),this.name="MalformedConfigError"}}});function JI(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function VI(t){return t==="env"||t==="config"?t:void 0}function dn(t){return{content:t,isError:!0}}var YI,QI,ZI=h(()=>{"use strict";zI();YI=async t=>{let e=JI(t);if(!e)return dn("config_get: expected an object input");let n=VI(e.target);if(!n)return dn("config_get: `target` must be 'env' or 'config'");let r=typeof e.key=="string"?e.key:void 0,o=e.all===!0;try{if(n==="env"){if(r){let s=BI(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(jI({all:o}),null,2)}}if(r){let s=GI(r);return{content:JSON.stringify(s,null,2)}}return{content:JSON.stringify(XI(),null,2)}}catch(s){return dn(`config_get: ${s.message}`)}},QI=async t=>{let e=JI(t);if(!e)return dn("config_set: expected an object input");let n=VI(e.target);if(!n)return dn("config_set: `target` must be 'env' or 'config'");let r=typeof e.key=="string"?e.key:void 0;if(!r)return dn("config_set: `key` is required");let o=e.action==="unset"?"unset":"set",s=e.value;try{if(o==="unset"){if(n==="env"){let c=UI(r);return{content:c.removed?`Removed ${c.key} from afk.env (${c.persistedTo}). ${aa}.`:`${c.key} was not set in afk.env; nothing to remove.`}}let a=qI(r);return{content:a.removed?`Removed ${a.path} from afk.config.json (${a.persistedTo}). ${aa}.`:`${a.path} was not set in afk.config.json; nothing to remove.`}}if(s==null)return dn(`config_set: \`value\` is required to set ${r}`);if(n==="env"){if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")return dn("config_set: env values must be a string, number, or boolean");let a=$I(r,String(s));return{content:`Set ${a.key} = ${a.display} in afk.env (${a.persistedTo}). ${aa}.`}}let i=KI(r,s);return{content:`Set ${i.path} = ${JSON.stringify(i.value)} in afk.config.json (${i.persistedTo}). ${aa}.`}}catch(i){return dn(`config_set: ${i.message}`)}}});function qr(t,e){return t.length>e?`${t.slice(0,e)}\u2026 [truncated]`:t}function Uy(t){switch(t.type){case"message":return t.message.role!=="assistant"||!t.message.content?null:{kind:"assistant",text:qr(t.message.content,8e3)};case"chunk":{let e=t.chunk;return e.type==="tool_use_detail"?e.pending?null:{kind:"tool",toolName:e.toolName,toolUseId:e.toolUseId,input:qr(e.toolInput,400)}:e.type==="tool_result"?e.isError===!0?{kind:"tool_error",content:qr(e.content,400),...e.metadata?.toolName!==void 0?{toolName:String(e.metadata.toolName)}:{}}:{kind:"tool_result",toolUseId:e.toolUseId,content:qr(e.content,400),...typeof e.durationMs=="number"?{durationMs:e.durationMs}:{},...e.metadata?.toolName!==void 0?{toolName:String(e.metadata.toolName)}:{}}:e.type==="thinking"?{kind:"thinking",text:qr(e.content,8e3)}:null}case"done":{let e=t.metadata,n=e?.totalCostUsd,r=e?.durationMs,o=e?.usage,s=typeof o?.input_tokens=="number"?o.input_tokens:void 0,i=typeof o?.output_tokens=="number"?o.output_tokens:void 0,a=typeof o?.cache_read_input_tokens=="number"?o.cache_read_input_tokens:void 0,c=typeof e?.stopReason=="string"?e.stopReason:void 0;return{kind:"done",...typeof n=="number"?{costUsd:n}:{},...typeof r=="number"?{durationMs:r}:{},...s!==void 0?{inputTokens:s}:{},...i!==void 0?{outputTokens:i}:{},...a!==void 0?{cacheReadTokens:a}:{},...c!==void 0?{stopReason:c}:{}}}case"error":return{kind:"error",message:t.error.message};case"paused":return{kind:"paused",...t.resetsAt?{resetsAt:t.resetsAt.toISOString()}:{}};case"resumed":return{kind:"resumed"};case"notice":return null;case"tool-activity":return{kind:"tool_activity",activeCount:t.activeCount,activeToolUseIds:t.activeToolUseIds};case"rate_limit":return{kind:"rate_limit",...typeof t.retryAfterMs=="number"?{retryAfterMs:t.retryAfterMs}:{}};case"progress":return{kind:"progress",message:t.progress.summary??t.progress.description};case"subagent_lifecycle":return{kind:"subagent_lifecycle",subagentId:t.subagentId,status:t.status,...t.model!==void 0?{model:t.model}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.totalCostUsd!==void 0?{totalCostUsd:t.totalCostUsd}:{},...t.outputBytes!==void 0?{outputBytes:t.outputBytes}:{},...t.errorClass!==void 0?{errorClass:t.errorClass}:{},...t.errorMessage!==void 0?{errorMessage:t.errorMessage}:{},...t.promptHead!==void 0?{promptHead:t.promptHead}:{},...t.turnCount!=null?{turnCount:t.turnCount}:{},...t.stopReason?{stopReason:t.stopReason}:{},...t.parentToolUseId?{parentToolUseId:t.parentToolUseId}:{}};case"background_job":return{kind:"background_job",jobId:t.jobId,status:t.status,...t.label!==void 0?{label:t.label}:{}};case"plan_mode":return{kind:"plan_mode",mode:t.mode};default:return null}}var By=h(()=>{"use strict"});import*as eC from"node:fs";import*as Gr from"node:fs/promises";import*as tC from"node:readline";function nC(t){let e=t.trim();if(!e)return null;try{let n=JSON.parse(e);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function ca(t){if(!lr(t))return!1;try{return await Gr.access(So(t)),!0}catch{return!1}}async function*jy(t){if(!lr(t))return;let e;try{e=await Gr.open(So(t),"r")}catch(n){if(n.code==="ENOENT")return;throw n}try{let n=tC.createInterface({input:e.createReadStream({encoding:"utf8"}),crlfDelay:1/0});for await(let r of n){let o=nC(r);o&&(yield o)}}finally{await e.close()}}async function*Hy(t,e){if(!lr(t))return;let n=So(t),r=wo(t),{fromStart:o=!1,signal:s}=e??{},i=0,a="",c=!1;async function*l(){let f=null;try{f=await Gr.open(n,"r");let m=await f.stat();if(m.size<=i)return;let g=m.size-i,y=Buffer.allocUnsafe(g),{bytesRead:b}=await f.read(y,0,g,i);if(b===0)return;i+=b,a+=y.toString("utf8",0,b);let w=a.split(`
|
|
347
347
|
`);a=w.pop()??"";for(let v of w){let _=nC(v);if(_&&(_.kind==="closed"&&(c=!0),yield _,c))return}}catch(m){m.code!=="ENOENT"&&process.stderr.write(`[afk] session-ledger: tail read error for ${t}: ${String(m)}
|
|
348
348
|
`)}finally{f&&await f.close().catch(()=>{})}}if(o){if(yield*l(),c)return}else try{i=(await Gr.stat(n)).size}catch{}let d=null,u=null,p=()=>new Promise(f=>{let m=setTimeout(()=>{u=null,f()},B5);u=()=>{clearTimeout(m),u=null,f()},s?.addEventListener("abort",()=>{clearTimeout(m),u=null,f()},{once:!0})});try{d=eC.watch(r,{persistent:!1},()=>{u?.()})}catch{}try{for(;!s?.aborted&&!c&&(await p(),!s?.aborted);)yield*l()}finally{d?.close()}}var B5,rC=h(()=>{"use strict";B();B5=250});import*as ru from"node:fs";var Nn,la=h(()=>{"use strict";B();By();By();rC();Nn=class{sessionId;ledgerPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;constructor(e){if(this.sessionId=e,!lr(e)){this.errored=!0,this.ledgerPath="";return}this.ledgerPath=So(e);try{ru.mkdirSync(wo(e),{recursive:!0})}catch(n){process.stderr.write(`[afk] session-ledger: mkdir failed for ${e}: ${String(n)}
|
|
349
349
|
`),this.errored=!0}}get active(){return!this.errored&&!this.closed}record(e){if(this.errored||this.closed)return;let n={v:1,ts:Date.now(),...e},r=JSON.stringify(n)+`
|
|
@@ -354,7 +354,7 @@ ${gt(t,{headless:e,latched:n})}`,{cause:t})}var cR,SV,kV,aR,TV,sy=h(()=>{"use st
|
|
|
354
354
|
`),this.errored=!0}}async close(e){if(!this.closed)return this.record({kind:"closed",...e!==void 0?{reason:e}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}}});import{readdir as H5,stat as W5}from"node:fs/promises";import{join as K5}from"node:path";async function Wy(){let t=go(),e;try{e=await H5(t)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of e){let o=K5(t,r,"trace.jsonl");try{let s=await W5(o);s.isFile()&&n.push({sessionId:r,tracePath:o,mtimeMs:s.mtimeMs,exists:!0})}catch{}}return n.sort((r,o)=>o.mtimeMs-r.mtimeMs),n}async function oC(){return(await Wy())[0]?.sessionId??null}var sC=h(()=>{"use strict";B()});import{existsSync as q5,readdirSync as G5,readFileSync as X5}from"node:fs";import{basename as z5,join as J5}from"node:path";function Y5(t){try{let e=JSON.parse(X5(t,"utf-8"));if(typeof e!="object"||e===null)return;let n=e;return{sessionId:typeof n.sessionId=="string"?n.sessionId:void 0,name:typeof n.name=="string"?n.name:void 0,savedAt:typeof n.savedAt=="number"?n.savedAt:void 0}}catch{return}}function Q5(t){if(!q5(t))return[];let e;try{e=G5(t)}catch{return[]}let n=[];for(let r of e){if(!r.endsWith(".json"))continue;let o=J5(t,r),s=Y5(o);s&&n.push({sidecarId:z5(r,".json"),filePath:o,data:s})}return n}function ou(t,e=ce()){let n=Q5(e);n.sort((r,o)=>{let s=r.data.savedAt??-1/0;return(o.data.savedAt??-1/0)-s});for(let r of n){if(r.sidecarId===t)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-id"};if(r.data.sessionId===t)return{sessionId:r.data.sessionId,sidecarId:r.sidecarId,reason:"exact-session-id"};if(r.data.name===t)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-name"}}if(t.length>=V5){let r=n.filter(o=>o.data.name!==void 0&&o.data.name.startsWith(t));if(r.length===1){let o=r[0];return{sessionId:o.data.sessionId??o.sidecarId,sidecarId:o.sidecarId,reason:"prefix-name"}}}}var V5,Ky=h(()=>{"use strict";B();V5=3});import{existsSync as Z5}from"node:fs";import{readFile as eY}from"node:fs/promises";async function qy(t){if(!Z5(t))return{content:"",truncated:!1};try{let e=await eY(t);if(e.length<=iC)return{content:e.toString("utf-8"),truncated:!1};let n=e.subarray(e.length-iC),r=n.indexOf(10);return r!==-1&&(n=n.subarray(r+1)),{content:n.toString("utf-8"),truncated:!0}}catch{return{content:"",truncated:!1}}}var iC,aC=h(()=>{"use strict";iC=2097152});import{existsSync as Gy}from"node:fs";import{join as cC}from"node:path";function lC(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.kind=="string"&&typeof e.seq=="number"&&typeof e.payload=="object"&&e.payload!==null}function iY(t){return dr(t,{guard:lC})}function aY(t){return typeof t!="number"?tY:Math.min(Math.max(1,Math.round(t)),nY)}function cY(t){return typeof t!="number"?oY:Math.min(Math.max(1,Math.round(t)),sY)}function lY(t,e){if(e.kinds&&!e.kinds.has(t.kind)||e.toolName&&(t.kind!=="tool_call"||t.payload.name!==e.toolName))return!1;if(e.errorsOnly)if(t.kind==="tool_call"){let n=t.payload;if(n.phase!=="completed"||!n.isError)return!1}else if(t.kind==="subagent_lifecycle"){if(t.payload.transition!=="failed")return!1}else if(t.kind==="background_agent"){if(t.payload.transition!=="failed")return!1}else return!1;return!0}async function dY(t){let e=async r=>{let o=cC(it(r),"trace.jsonl");if(!Gy(o))try{for await(let s of jy(r))if(s.kind==="meta"){if(s.traceLabel===null)return{tracePath:o,disabledNote:r};if(typeof s.traceLabel=="string"&&s.traceLabel.length>0){let i=cC(it(s.traceLabel),"trace.jsonl");Gy(i)&&(o=i)}break}}catch{}return{tracePath:o,disabledNote:void 0}},n=await e(t);if(n.disabledNote!==void 0||Gy(n.tracePath))return n;try{let r=ou(t);if(r&&r.sessionId!==t){let o=await e(r.sessionId);return o.disabledNote!==void 0?{tracePath:o.tracePath,disabledNote:r.sessionId}:o}}catch{}return n}async function dC(t){let e=t.session==="latest"||!t.session?await oC():t.session;if(!e)return{sessionId:"(none)",events:[],totalInTrace:0,filtered:0};let{tracePath:n,disabledNote:r}=await dY(e);if(r!==void 0)return{sessionId:e,events:[],totalInTrace:0,filtered:0,note:`Session "${r}" ran with tracing disabled (traceLabel: null).`};let{content:o}=await qy(n),s=iY(o),i={kinds:t.kinds?new Set(t.kinds):void 0,toolName:t.toolName,errorsOnly:t.errorsOnly},a=aY(t.limit),c=[];for(let l=s.length-1;l>=0;l--){let d=s[l];if(lY(d,i)&&(c.push(d),c.length>=a))break}return c.reverse(),{sessionId:e,events:c,totalInTrace:s.length,filtered:c.length}}async function uC(t){let e=cY(t.sessions),r=(await Wy()).slice(0,e),o=r.length,s=r;if(t.since){let p=Date.parse(t.since);if(Number.isNaN(p))throw new Error(`Invalid "since" date: ${t.since}`);s=r.filter(f=>f.mtimeMs>=p)}let i=t.kinds?new Set(t.kinds):void 0,a=t.query.toLowerCase(),c=[],l=rY,d=[],u=0;for(let p of s){if(c.length>=l)break;let{content:f,truncated:m}=await qy(p.tracePath);u++,m&&d.push(p.sessionId);let g=f.split(`
|
|
355
355
|
`).filter(y=>y.trim()!==""&&y.toLowerCase().includes(a));for(let y of g){if(c.length>=l)break;let[b]=dr(y,{guard:lC});b&&(i&&!i.has(b.kind)||t.toolName&&(b.kind!=="tool_call"||b.payload.name!==t.toolName)||c.push({sessionId:p.sessionId,event:b,matchLine:y.length>500?y.slice(0,500)+"\u2026":y}))}}return{query:t.query,sessionsAvailable:o,sessionsSearched:u,sessionsScanned:u,matches:c,...d.length>0?{truncatedSessions:d}:{}}}var tY,nY,rY,oY,sY,pC=h(()=>{"use strict";B();la();sC();Ky();aC();Vc();tY=50,nY=200,rY=200,oY=20,sY=100});function fC(t){return!t||typeof t!="object"?null:t}function mC(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string")}var gC,hC,yC=h(()=>{"use strict";pC();gC=async t=>{let e=fC(t);if(!e)return{content:"Invalid input: expected object",isError:!0};let n=typeof e.session=="string"?e.session:void 0,r=mC(e.kinds),o=typeof e.tool_name=="string"?e.tool_name:void 0,s=typeof e.errors_only=="boolean"?e.errors_only:!1,i=typeof e.limit=="number"?e.limit:void 0;try{let a=await dC({session:n,kinds:r,toolName:o,errorsOnly:s,limit:i});return{content:JSON.stringify(a)}}catch(a){return{content:`read_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},hC=async t=>{let e=fC(t);if(!e)return{content:"Invalid input: expected object",isError:!0};if(typeof e.query!="string"||!e.query)return{content:"Invalid input: query (string) is required",isError:!0};let n=e.query,r=typeof e.sessions=="number"?e.sessions:void 0,o=mC(e.kinds),s=typeof e.since=="string"?e.since:void 0,i=typeof e.tool_name=="string"?e.tool_name:void 0;try{let a=await uC({query:n,sessions:r,kinds:o,since:s,toolName:i});return{content:JSON.stringify(a)}}catch(a){return{content:`search_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}}});function uY(t){return t.length<=bC?t:`${t.slice(0,bC)}\u2026(truncated)`}function pY(t){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${t.title??t.serverName}`,uY(t.message)];t.url!==void 0&&t.url!==""&&n.push(t.url),Dn(n.join(`
|
|
356
356
|
`)).catch(()=>{})}catch{}}function wC(t,e){if(!(t===void 0||t===""))try{Zg(t,e).catch(()=>{})}catch{}}var Yo,bC,Xy,He,$n=h(()=>{"use strict";Dr();Ar();Yo={action:"decline"},bC=300;Xy=class{handler=null;queue=Promise.resolve();queueDepth=0;install(e){this.handler=e}uninstall(){this.handler=null}hasHandler(){return this.handler!==null}pendingCount(){return this.queueDepth}route(e,n){if(n.signal.aborted)return Promise.resolve(Yo);this.queueDepth+=1;let r,o=new Promise(i=>{r=i}),s=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(Yo);return}if(!s){pY(e),r(Yo);return}let i,a=new Promise(c=>{i=()=>c(Yo),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}wC(n.sessionId,!0);let c=await Promise.race([s(e,n).catch(()=>Yo),a]);r(c)}finally{wC(n.sessionId,!1),n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(Yo)}}).catch(()=>{}),o}},He=new Xy});var SC,kC=h(()=>{"use strict";$n();SC=async(t,e,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let r=t,o=r.question;if(typeof o!="string"||o.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let s=new Set(["text","confirm","choice","multi_choice","number"]),i=r.type??"text";if(typeof i!="string"||!s.has(i))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(i==="choice"||i==="multi_choice"){let m=r.choices;if(!Array.isArray(m)||m.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${i}"`,isError:!0};if(m.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${m.length}`,isError:!0};for(let g of m)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let a=r.min,c=r.max;if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: min must be a finite number",isError:!0};if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)))return{content:"Invalid input: max must be a finite number",isError:!0};if(a!==void 0&&c!==void 0&&a>c)return{content:`Invalid input: min (${a}) must be \u2264 max (${c})`,isError:!0};let l=r.min_length,d=r.max_length;if(l!==void 0&&typeof l!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(d!==void 0&&typeof d!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((l!==void 0||d!==void 0)&&i!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${i}"`,isError:!0};if(r.allow_custom!==void 0&&i!=="choice"&&i!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${i}"`,isError:!0};let u={serverName:"agent",message:o.trim(),origin:"agent",type:i,...r.choices!==void 0&&{choices:r.choices},...r.context!==void 0&&typeof r.context=="string"&&{context:r.context},...r.default!==void 0&&{questionDefault:r.default},...l!==void 0&&{minLength:l},...d!==void 0&&{maxLength:d},...a!==void 0&&{min:a},...c!==void 0&&{max:c},...r.allow_skip!==void 0&&{allowSkip:!!r.allow_skip},...r.allow_custom!==void 0&&{allowCustom:!!r.allow_custom}},p=await He.route(u,{signal:e,...n?.sessionId!==void 0?{sessionId:n.sessionId}:{}}),f=p.action==="decline"||p.action==="cancel";return{content:JSON.stringify(p),...f&&{isError:!0,failureClass:"elicitation-declined"}}}});function fY(t){if(!t||typeof t!="object")return{error:"browser_open: input must be an object"};let e=t,n=e.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(e.wait_for!==void 0){if(!vC.includes(e.wait_for))return{error:`browser_open: "wait_for" must be one of ${vC.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(e.wait_for)})`};o=e.wait_for}let s;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};s=e.screenshot}let i;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};i=e.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:s,timeoutMs:i}}function mY(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_open aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0,failureClass:Ne(n)}}let o=fY(e);if("error"in o)return{content:o.error,isError:!0};let s=k.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(Br(),Ur));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return ze(u)?{content:gt(u),isError:!0}:{content:`browser_open failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),u=Date.now()-l;if("outcome"in d&&d.outcome==="blocked_by_policy")return ye(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:u}),{content:`browser_open blocked: ${d.reason}`,isError:!0,failureClass:"policy-refusal"};let p=d;return ye(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:p.url,status:"ok",durationMs:u,...p.screenshotPath!==null?{screenshotPath:p.screenshotPath}:{}}),{content:JSON.stringify(p,null,2)}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);ye(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}});let f=Bd(d);return{content:`browser_open failed: ${p}`,isError:!0,...f?{failureClass:f}:{}}}}}var vC,TC,EC=h(()=>{"use strict";F();Cn();J();jr();vC=["load","domcontentloaded","networkidle"];TC=mY()});function gY(t){if(t!=null&&typeof t!="object")return{error:"browser_observe: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=e.screenshot}let r;if(e.include_hidden!==void 0){if(typeof e.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=e.include_hidden}let o;if(e.max_elements!==void 0){if(typeof e.max_elements!="number"||!Number.isFinite(e.max_elements)||e.max_elements<=0||!Number.isInteger(e.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=e.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function hY(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_observe aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=gY(e);if("error"in o)return{content:o.error,isError:!0};let s=k.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(Br(),Ur));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return ze(u)?{content:gt(u),isError:!0}:{content:`browser_observe failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),u=Date.now()-l;return ye(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:d.url,urlAfter:d.url,status:"ok",durationMs:u,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return ye(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_observe failed: ${p}`,isError:!0}}}}var _C,AC=h(()=>{"use strict";F();J();jr();_C=hY()});function yY(t){if(!t||typeof t!="object")return{error:"browser_act: input must be an object"};let e=t;if(typeof e.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!xC.includes(e.action))return{error:`browser_act: "action" must be one of ${xC.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(e.action)})`};let n=e.action,r=e.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!RC.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${RC.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let s,i=o.kind;if(i==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};s={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(i==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};s={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};s={kind:"selector",selector:o.selector}}let a;if(e.value!==void 0){if(typeof e.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=e.value}let c;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};c=e.timeout_ms}let l;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};l=e.screenshot}return{action:n,target:s,value:a,timeoutMs:c,screenshot:l}}function bY(t,e){let n=t.role?`"${t.text}" (role: ${t.role})`:`"${t.text}"`;return[`browser_act: ambiguous target \u2014 ${e.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...e.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
|
|
357
|
-
`)}function wY(t){return t.kind==="semantic"?{kind:"semantic",text:Zx(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:Qx(t.selector)}}function SY(t={}){return async(e,n,r)=>{if(n.aborted){let u=n.reason;return{content:`browser_act aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0,failureClass:Ne(n)}}let o=yY(e);if("error"in o)return{content:o.error,isError:!0};let s=wY(o.target),i=k.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a,c,l;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:u,getLastRoutingDecision:p}=await Promise.resolve().then(()=>(Br(),Ur));a=await u();let f=p();f&&(c=f.backend,l=f.reason)}}catch(u){let p=u instanceof Error?u.message:String(u);return ze(p)?{content:gt(p),isError:!0}:{content:`browser_act failed to get provider: ${p}`,isError:!0}}let d=Date.now();try{let u=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),p=Date.now()-d;if("outcome"in u){if(u.outcome==="ambiguous_target")return ye(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:p}),{content:bY(u.query,u.candidates),isError:!0};if(u.outcome==="blocked_by_policy")return ye(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:p}),{content:`browser_act blocked: ${u.reason}`,isError:!0,failureClass:"policy-refusal"}}return ye(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:u.url,urlAfter:u.url,status:"ok",durationMs:p,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(u){let p=Date.now()-d,f=u instanceof Error?u.message:String(u);ye(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:p,error:{reason:f,recoverable:!1}});let m=Bd(u);return{content:`browser_act failed: ${f}`,isError:!0,...m?{failureClass:m}:{}}}}}var xC,RC,IC,CC=h(()=>{"use strict";Od();F();Cn();J();jr();xC=["click","fill","press","select","hover","scroll_to","wait_for"],RC=["semantic","element_id","selector"];IC=SY()});function kY(t){if(typeof t.kind!="string"||!PC.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${PC.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.kind)})`};let e=t.kind;return e==="semantic"?typeof t.text!="string"||t.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:t.text,...typeof t.role=="string"&&t.role.length>0?{role:t.role}:{}}:e==="element_id"?typeof t.element_id!="string"||t.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:t.element_id}:typeof t.selector!="string"||t.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:t.selector}}function vY(t){if(t!=null&&typeof t!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.target!==void 0){if(!e.target||typeof e.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=kY(e.target);if("error"in o)return o;n=o}let r;if(e.full_page!==void 0){if(typeof e.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=e.full_page}return{target:n,fullPage:r}}function TY(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_screenshot aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=vY(e);if("error"in o)return{content:o.error,isError:!0};let s=k.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(Br(),Ur));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return ze(u)?{content:gt(u),isError:!0}:{content:`browser_screenshot failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),u=Date.now()-l,{dataBase64:p,mediaType:f,...m}=d;return ye(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:u,screenshotPath:m.path}),m.width>zy||m.height>zy?{content:JSON.stringify({...m,imageOmitted:`dimensions ${m.width}x${m.height}px exceed the ${zy}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(m,null,2),image:{mediaType:f,data:p}}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return ye(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_screenshot failed: ${p}`,isError:!0}}}}var PC,zy,MC,OC=h(()=>{"use strict";F();J();jr();PC=["semantic","element_id","selector"],zy=8e3;MC=TY()});function EY(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_close aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=k.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s,i,a;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:l,getLastRoutingDecision:d}=await Promise.resolve().then(()=>(Br(),Ur));s=await l();let u=d();u&&(i=u.backend,a=u.reason)}}catch(l){let d=l instanceof Error?l.message:String(l);return ze(d)?{content:gt(d),isError:!0}:{content:`browser_close failed to get provider: ${d}`,isError:!0}}let c=Date.now();try{await s.close({sessionId:o});let l=Date.now()-c;return ye(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:l}),{content:"Browser session closed."}}catch(l){let d=Date.now()-c,u=l instanceof Error?l.message:String(l);return ye(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}}),{content:`browser_close failed: ${u}`,isError:!0}}}}var DC,FC=h(()=>{"use strict";F();J();jr();DC=EY()});function Un(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}function su(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Un(_Y,t)?"read":Un(AY,t)?"write":Un(xY,t)?"shell":Un(LC,t)?"subagent":Un(NC,t)?"skill":Un($C,t)?"dag":Un(RY,t)?"web":IY.has(t)?"browser":Un(CY,t)?"planning":PY.has(t)?"schedule":"other"}var _Y,AY,xY,LC,NC,$C,mke,RY,IY,CY,PY,Jy,UC,da=h(()=>{"use strict";rd();_Y=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","workspace_query","read_witness","search_witness","get_facet","json_query","state_get","state_query"]),AY=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","patch_apply","memory_update","procedure_write","terminal_font_size","config_set","workspace_publish","state_put","state_cas","state_delete","clipboard_write"]),xY=new Set(["Bash","BashOutput","KillBash","bash","test_run","wait_for"]),LC=new Set(["Agent","Task","agent","cancel_background_job","send_message_to_agent"]),NC=new Set(["Skill","skill"]),$C=new Set(["Compose","compose"]),mke=new Set([...LC,...$C,...NC]),RY=new Set(["WebFetch","WebSearch","send_telegram","web_scrape","web_request"]),IY=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),CY=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),PY=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);Jy=["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness","workspace_publish","workspace_query","json_query","state_get","state_query",...$e],UC=[...Jy,"web_scrape","agent"]});import iu from"path";function FY(t){return typeof t=="object"&&t!==null&&"command"in t?String(t.command??""):typeof t=="string"?t:""}function LY(t){if(typeof t!="object"||t===null)return"";let e=t;return typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:""}function BC(t){for(let e of MY)if(t.includes(e))return"high";for(let e of OY)if(t.includes(e))return"medium";for(let e of DY)if(t.includes(e))return"safe";return"medium"}function jC(t,e){if(!t)return"safe";let n=Be(iu.resolve(e.cwd,t)),r=n.split(iu.sep).join("/"),o=fh();for(let s of o){let i=s.split(iu.sep).join("/");if(r===i||r.startsWith(i+"/"))return"high"}if(r.includes("/.git/"))return"high";if(e.workspaceRoot!==void 0){let s=Be(e.workspaceRoot);if(iu.relative(s,n).startsWith(".."))return"high"}return r.includes("/node_modules/")?"medium":"safe"}function $Y(t){return t.split("__").slice(1).join("__").split(/[_-]+/).filter(Boolean)}function au(t,e,n){let r=t.toLowerCase();if(r==="bash"){let o=FY(e);return BC(o)}if(r==="write_file"||r==="edit_file"){let o=LY(e);return jC(o,n)}if(r==="patch_apply"){let o=typeof e=="object"&&e!==null?e:{},s=Array.isArray(o.changes)?o.changes:[],i="safe";for(let a of s){if(typeof a!="object"||a===null)continue;let c=a.path,d=jC(typeof c=="string"?c:"",n);if(d==="high")return"high";d==="medium"&&(i="medium")}return i}if(su(t)==="read")return"safe";if(r==="send_telegram")return"medium";if(r.startsWith("mcp__"))return $Y(r).some(s=>NY.has(s))?"high":"medium";if(r==="create_schedule"||r==="cancel_schedule")return"high";if(r==="worktree"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.action=="string"?o.action:"";return s==="list"?"safe":s==="remove"&&o.force===!0?"high":"medium"}if(r==="browser_act"||r==="browser_open"||r==="web_scrape")return"medium";if(r==="web_request"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.method=="string"?o.method.toUpperCase():"";return s==="DELETE"?"high":s==="GET"||s==="HEAD"||s==="OPTIONS"?"safe":"medium"}if(r==="wait_for"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.type=="string"?o.type:"";if(s==="command"){let i=typeof o.command=="string"?o.command:"";return BC(i)}return s==="file"||s==="process"?"safe":"medium"}return"safe"}var MY,OY,DY,NY,Vy=h(()=>{"use strict";Rr();da();MY=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash","-X POST","-X PUT","-X PATCH","-X DELETE","-XPOST","-XPUT","-XPATCH","-XDELETE","--request POST","--request PUT","--request PATCH","--request DELETE","curl --data","curl -d","curl -F","wget --post-data","wget --post-file","launchctl load","launchctl bootstrap","launchctl submit","launchctl start ","launchctl kickstart","launchctl enable ","systemctl enable ","systemctl start ","systemctl daemon-reload"],OY=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],DY=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];NY=new Set(["delete","drop","remove","destroy","truncate","purge","wipe","write","create","update","insert","upsert","patch","rename","exec","execute","run","eval","send","push","publish","deploy","post","merge","rollback","reset","terminate","provision","scale","disable","charge","refund","revoke"])});import*as cu from"node:fs/promises";import{execSync as UY}from"node:child_process";async function HC(t,e){let n=t.method??"HEAD",r;try{r=await Fn(globalThis.fetch,t.url,{method:n,signal:e})}catch(a){let c=a instanceof Error?a.message:String(a);return{met:!1,detail:c.startsWith("refusing to")?`SSRF blocked: ${c}`:`fetch error: ${c}`,data:c.startsWith("refusing to")?{blocked:!0}:void 0}}let{status:o}=r,s={status:o};if(!(t.expected_status!==void 0?o===t.expected_status:o>=200&&o<300))return{met:!1,detail:`HTTP ${o} (want ${t.expected_status??"2xx"})`,data:s};if(t.body_contains!==void 0){let a=await r.text().catch(()=>"");if(s.bodyLength=a.length,!a.includes(t.body_contains))return{met:!1,detail:`body does not contain "${t.body_contains}"`,data:s}}else n==="HEAD"&&await r.body?.cancel().catch(()=>{});return{met:!0,detail:`HTTP ${o}`,data:s}}async function WC(t,e){let n;try{let o=t.workspaceRoot?{resolveBase:t.workspaceRoot,cwd:t.workspaceRoot}:void 0;n=de(t.path,o,"read")}catch(o){return{met:!1,detail:`path rejected: ${o instanceof Error?o.message:String(o)}`,data:{blocked:!0}}}let r;try{let o=await cu.stat(n);r={mtimeMs:o.mtimeMs,size:o.size}}catch{return{met:!1,detail:`file not found: ${t.path}`}}if(t.content_contains!==void 0){let o;try{o=await cu.readFile(n,{encoding:"utf8",signal:e})}catch(s){return{met:!1,detail:`read error: ${s instanceof Error?s.message:String(s)}`,data:r}}if(!o.includes(t.content_contains))return{met:!1,detail:`file exists but does not contain "${t.content_contains}"`,data:r}}return{met:!0,detail:`file exists (${r.size} bytes)`,data:r}}function KC(t,e){if(!Number.isInteger(t.pid)||t.pid<=1)return{met:!1,detail:`pid ${t.pid} is not a valid target (must be integer > 1)`,data:{pid:t.pid,blocked:!0}};if(e!==void 0&&!e.has(t.pid))return{met:!1,detail:`pid ${t.pid} is not a session-owned process (not in spawned PID registry)`,data:{pid:t.pid,blocked:!0}};try{return process.kill(t.pid,0),{met:!1,detail:`pid ${t.pid} is still alive`,data:{pid:t.pid}}}catch(n){let r=n.code;return r==="ESRCH"?{met:!0,detail:`pid ${t.pid} has exited`,data:{pid:t.pid}}:{met:!1,detail:`pid ${t.pid} is alive (${r??"unknown"})`,data:{pid:t.pid}}}}function qC(t){let e=au("bash",{command:t.command},{cwd:t.cwd??process.cwd()});if(e!=="safe")return{met:!1,detail:`command blocked by risk classifier (${e} risk): ${t.command}`,data:{command:t.command,blocked:!0}};try{return UY(t.command,{cwd:t.cwd,stdio:"pipe",timeout:3e4}),{met:!0,detail:"command exited 0",data:{command:t.command}}}catch(n){let r=n;if(r.killed===!0&&r.signal==="SIGTERM")return{met:!1,detail:"command timed out (30s limit)",data:{command:t.command,timedOut:!0}};let o=r.status??-1;return{met:!1,detail:`command exited ${o}`,data:{command:t.command,exitCode:o}}}}var GC=h(()=>{"use strict";Lr();Vy();Ae()});function We(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);o.unref(),e.addEventListener("abort",r,{once:!0})})}var Bn=h(()=>{"use strict"});function BY(t,e,n){switch(n){case"linear":return t+e*1e3;case"exponential":return Math.min(t*Math.pow(2,e),6e4);default:return t}}async function YC(t,e){let{timeout_ms:n,poll_interval_ms:r,backoff:o,signal:s}=e,i=Date.now()+n,a=0,c;for(;;){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};let l=i-Date.now(),d=AbortSignal.any([s,AbortSignal.timeout(Math.max(1,Math.min(r,l)))]),u;try{u=await t(d)}catch(m){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};if(m instanceof Error&&m.name==="AbortError"){if(Date.now()>=i)return{status:"timed_out",elapsed_ms:Date.now()-(i-n),attempts:a,result:c};continue}let g=m instanceof Error?m.message:String(m);return{status:"failed",elapsed_ms:Date.now()-(i-n),attempts:a,error:g}}if(c=u,a++,u.met)return{status:"succeeded",elapsed_ms:Date.now()-(i-n),attempts:a,result:u};let p=Date.now();if(p>=i)return{status:"timed_out",elapsed_ms:p-(i-n),attempts:a,result:c};let f=Math.min(BY(r,a-1,o),i-p);await We(f,s)}}var XC,zC,JC,VC,QC=h(()=>{"use strict";Bn();XC=12e4,zC=6e5,JC=5e3,VC=1e3});import ZC from"node:path";function jY(t,e){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let n=t,r=n.type;if(typeof r!="string")throw new Error('"type" is required and must be a string');let o=XC;if(n.timeout_ms!==void 0){if(typeof n.timeout_ms!="number"||!Number.isFinite(n.timeout_ms))throw new Error('"timeout_ms" must be a finite number');o=Math.min(Math.max(0,n.timeout_ms),zC)}let s=JC;if(n.poll_interval_ms!==void 0){if(typeof n.poll_interval_ms!="number"||!Number.isFinite(n.poll_interval_ms))throw new Error('"poll_interval_ms" must be a finite number');s=Math.max(VC,n.poll_interval_ms)}let i=["none","linear","exponential"],a="none";if(n.backoff!==void 0){if(!i.includes(n.backoff))throw new Error(`"backoff" must be one of: ${i.join(", ")}`);a=n.backoff}switch(r){case"url":{if(typeof n.url!="string"||n.url.trim()==="")throw new Error('"url" is required for type "url"');let c=n.body_contains!==void 0,l=n.method??(c?"GET":"HEAD");if(l!=="HEAD"&&l!=="GET")throw new Error('"method" must be "HEAD" or "GET"');return{condition:{type:"url",url:n.url,method:l,...n.expected_status!==void 0?{expected_status:Number(n.expected_status)}:{},...c?{body_contains:String(n.body_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"file":{if(typeof n.path!="string"||n.path.trim()==="")throw new Error('"path" is required for type "file"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"file",path:c!==void 0&&!ZC.isAbsolute(n.path)?ZC.resolve(c,n.path):n.path,workspaceRoot:c,...n.content_contains!==void 0?{content_contains:String(n.content_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"process":{if(typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=1)throw new Error('"pid" is required for type "process" and must be an integer > 1');return{condition:{type:"process",pid:n.pid},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"command":{if(typeof n.command!="string"||n.command.trim()==="")throw new Error('"command" is required for type "command"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"command",command:n.command,...c!==void 0?{cwd:c}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}default:throw new Error(`Unknown type "${r}". Must be one of: url, file, process, command`)}}var eP,tP=h(()=>{"use strict";Lr();GC();QC();eP=async(t,e,n)=>{let r;try{r=jY(t,n)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{condition:o,timeoutMs:s,pollIntervalMs:i,backoff:a}=r;if(o.type==="url"){let u=await Fr(o.url);if(!u.allowed)return{content:`SSRF guard blocked: ${u.reason}`,isError:!0}}let l=await YC(u=>{switch(o.type){case"url":return HC(o,u);case"file":return WC(o,u);case"process":return Promise.resolve(KC(o,n?.spawnedPidRegistry));case"command":return Promise.resolve(qC(o))}},{timeout_ms:s,poll_interval_ms:i,backoff:a,signal:e});return{content:`Wait ${l.status}: ${o.type} condition (${l.elapsed_ms}ms elapsed, ${l.attempts} attempt${l.attempts===1?"":"s"})`+(l.result?` \u2014 ${l.result.detail}`:"")+(l.error?` \u2014 error: ${l.error}`:""),isError:l.status==="failed"}}});import{createHash as HY}from"crypto";import{readFile as WY}from"fs/promises";function KY(t){return HY("sha256").update(t,"utf8").digest("hex")}function qY(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}async function nP(t,e,n){let r=[],o=new Map;for(let s of t){let i=s.path,a;try{a=de(i,n,"write",e)}catch(l){r.push({path:i,error:"path_containment",detail:l instanceof Error?l.message:String(l)});continue}try{Uo(a,"patch_apply")}catch(l){r.push({path:i,error:"write_denied",detail:l instanceof Error?l.message:String(l)});continue}if(s.edits!==void 0&&s.content!==void 0){r.push({path:i,error:"mutually_exclusive",detail:"`edits` and `content` cannot both be provided for the same file."});continue}if(s.edits===void 0&&s.content===void 0){r.push({path:i,error:"no_change_specified",detail:"At least one of `edits` or `content` must be provided."});continue}let c;try{c=await WY(a,"utf-8")}catch(l){if(s.expected_hash!==void 0||s.edits!==void 0){r.push({path:i,error:"file_read_failed",detail:l instanceof Error?l.message:String(l)});continue}o.set(a,null),c=""}if(o.has(a)||o.set(a,c),s.expected_hash!==void 0){let l="sha256:";if(!s.expected_hash.startsWith(l)){r.push({path:i,error:"invalid_hash_format",detail:`expected_hash must start with "sha256:". Got: "${s.expected_hash}"`});continue}let d=s.expected_hash.slice(l.length),u=KY(c);if(u!==d){r.push({path:i,error:"hash_mismatch",detail:`File hash mismatch. Expected sha256:${d}, got sha256:${u}. The file may have been modified.`});continue}}if(s.edits!==void 0){let l=c;for(let d=0;d<s.edits.length;d++){let u=s.edits[d],p=qY(l,u.old);if(p===0){r.push({path:i,error:"edit_not_found",detail:`Edit #${d+1}: \`old\` string not found in file.`});break}else if(p>1)r.push({path:i,error:"edit_ambiguous",detail:`Edit #${d+1}: \`old\` string matches ${p} locations. Provide enough context to make it unique.`});else{let f=l.indexOf(u.old);l=l.slice(0,f)+u.new+l.slice(f+u.old.length)}}}}return{valid:r.length===0,errors:r,fileContents:o}}var rP=h(()=>{"use strict";Rr();Ae()});import{createHash as GY,randomBytes as XY}from"crypto";import{writeFile as oP,rename as zY,mkdir as JY,unlink as Yy,chmod as VY,stat as YY}from"fs/promises";import{dirname as iP,join as QY,isAbsolute as ZY,resolve as e8}from"path";function sP(t){return GY("sha256").update(t,"utf8").digest("hex")}function t8(t,e,n){let r=Mn(e,n);if(!r)return{text:"",payload:null};let o=[`--- a/${t}`,`+++ b/${t}`];for(let s of r.hunks){o.push(`@@ -${s.oldStart},${s.oldLines} +${s.newStart},${s.newLines} @@`);for(let i of s.lines)o.push(`${i.kind}${i.text}`)}return{text:o.join(`
|
|
357
|
+
`)}function wY(t){return t.kind==="semantic"?{kind:"semantic",text:Zx(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:Qx(t.selector)}}function SY(t={}){return async(e,n,r)=>{if(n.aborted){let u=n.reason;return{content:`browser_act aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0,failureClass:Ne(n)}}let o=yY(e);if("error"in o)return{content:o.error,isError:!0};let s=wY(o.target),i=k.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a,c,l;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:u,getLastRoutingDecision:p}=await Promise.resolve().then(()=>(Br(),Ur));a=await u();let f=p();f&&(c=f.backend,l=f.reason)}}catch(u){let p=u instanceof Error?u.message:String(u);return ze(p)?{content:gt(p),isError:!0}:{content:`browser_act failed to get provider: ${p}`,isError:!0}}let d=Date.now();try{let u=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),p=Date.now()-d;if("outcome"in u){if(u.outcome==="ambiguous_target")return ye(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:p}),{content:bY(u.query,u.candidates),isError:!0};if(u.outcome==="blocked_by_policy")return ye(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:p}),{content:`browser_act blocked: ${u.reason}`,isError:!0,failureClass:"policy-refusal"}}return ye(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:u.url,urlAfter:u.url,status:"ok",durationMs:p,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(u){let p=Date.now()-d,f=u instanceof Error?u.message:String(u);ye(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:p,error:{reason:f,recoverable:!1}});let m=Bd(u);return{content:`browser_act failed: ${f}`,isError:!0,...m?{failureClass:m}:{}}}}}var xC,RC,IC,CC=h(()=>{"use strict";Od();F();Cn();J();jr();xC=["click","fill","press","select","hover","scroll_to","wait_for"],RC=["semantic","element_id","selector"];IC=SY()});function kY(t){if(typeof t.kind!="string"||!PC.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${PC.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.kind)})`};let e=t.kind;return e==="semantic"?typeof t.text!="string"||t.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:t.text,...typeof t.role=="string"&&t.role.length>0?{role:t.role}:{}}:e==="element_id"?typeof t.element_id!="string"||t.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:t.element_id}:typeof t.selector!="string"||t.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:t.selector}}function vY(t){if(t!=null&&typeof t!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.target!==void 0){if(!e.target||typeof e.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=kY(e.target);if("error"in o)return o;n=o}let r;if(e.full_page!==void 0){if(typeof e.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=e.full_page}return{target:n,fullPage:r}}function TY(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_screenshot aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=vY(e);if("error"in o)return{content:o.error,isError:!0};let s=k.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(Br(),Ur));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return ze(u)?{content:gt(u),isError:!0}:{content:`browser_screenshot failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),u=Date.now()-l,{dataBase64:p,mediaType:f,...m}=d;return ye(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:u,screenshotPath:m.path}),m.width>zy||m.height>zy?{content:JSON.stringify({...m,imageOmitted:`dimensions ${m.width}x${m.height}px exceed the ${zy}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(m,null,2),image:{mediaType:f,data:p}}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return ye(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_screenshot failed: ${p}`,isError:!0}}}}var PC,zy,MC,OC=h(()=>{"use strict";F();J();jr();PC=["semantic","element_id","selector"],zy=8e3;MC=TY()});function EY(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_close aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=k.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s,i,a;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:l,getLastRoutingDecision:d}=await Promise.resolve().then(()=>(Br(),Ur));s=await l();let u=d();u&&(i=u.backend,a=u.reason)}}catch(l){let d=l instanceof Error?l.message:String(l);return ze(d)?{content:gt(d),isError:!0}:{content:`browser_close failed to get provider: ${d}`,isError:!0}}let c=Date.now();try{await s.close({sessionId:o});let l=Date.now()-c;return ye(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:l}),{content:"Browser session closed."}}catch(l){let d=Date.now()-c,u=l instanceof Error?l.message:String(l);return ye(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}}),{content:`browser_close failed: ${u}`,isError:!0}}}}var DC,FC=h(()=>{"use strict";F();J();jr();DC=EY()});function Un(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}function su(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Un(_Y,t)?"read":Un(AY,t)?"write":Un(xY,t)?"shell":Un(LC,t)?"subagent":Un(NC,t)?"skill":Un($C,t)?"dag":Un(RY,t)?"web":IY.has(t)?"browser":Un(CY,t)?"planning":PY.has(t)?"schedule":"other"}var _Y,AY,xY,LC,NC,$C,gke,RY,IY,CY,PY,Jy,UC,da=h(()=>{"use strict";rd();_Y=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","workspace_query","read_witness","search_witness","get_facet","json_query","state_get","state_query"]),AY=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","patch_apply","memory_update","procedure_write","terminal_font_size","config_set","workspace_publish","state_put","state_cas","state_delete","clipboard_write"]),xY=new Set(["Bash","BashOutput","KillBash","bash","test_run","wait_for"]),LC=new Set(["Agent","Task","agent","cancel_background_job","send_message_to_agent"]),NC=new Set(["Skill","skill"]),$C=new Set(["Compose","compose"]),gke=new Set([...LC,...$C,...NC]),RY=new Set(["WebFetch","WebSearch","send_telegram","web_scrape","web_request"]),IY=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),CY=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),PY=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);Jy=["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness","workspace_publish","workspace_query","json_query","state_get","state_query",...$e],UC=[...Jy,"web_scrape","agent"]});import iu from"path";function FY(t){return typeof t=="object"&&t!==null&&"command"in t?String(t.command??""):typeof t=="string"?t:""}function LY(t){if(typeof t!="object"||t===null)return"";let e=t;return typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:""}function BC(t){for(let e of MY)if(t.includes(e))return"high";for(let e of OY)if(t.includes(e))return"medium";for(let e of DY)if(t.includes(e))return"safe";return"medium"}function jC(t,e){if(!t)return"safe";let n=Be(iu.resolve(e.cwd,t)),r=n.split(iu.sep).join("/"),o=fh();for(let s of o){let i=s.split(iu.sep).join("/");if(r===i||r.startsWith(i+"/"))return"high"}if(r.includes("/.git/"))return"high";if(e.workspaceRoot!==void 0){let s=Be(e.workspaceRoot);if(iu.relative(s,n).startsWith(".."))return"high"}return r.includes("/node_modules/")?"medium":"safe"}function $Y(t){return t.split("__").slice(1).join("__").split(/[_-]+/).filter(Boolean)}function au(t,e,n){let r=t.toLowerCase();if(r==="bash"){let o=FY(e);return BC(o)}if(r==="write_file"||r==="edit_file"){let o=LY(e);return jC(o,n)}if(r==="patch_apply"){let o=typeof e=="object"&&e!==null?e:{},s=Array.isArray(o.changes)?o.changes:[],i="safe";for(let a of s){if(typeof a!="object"||a===null)continue;let c=a.path,d=jC(typeof c=="string"?c:"",n);if(d==="high")return"high";d==="medium"&&(i="medium")}return i}if(su(t)==="read")return"safe";if(r==="send_telegram")return"medium";if(r.startsWith("mcp__"))return $Y(r).some(s=>NY.has(s))?"high":"medium";if(r==="create_schedule"||r==="cancel_schedule")return"high";if(r==="worktree"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.action=="string"?o.action:"";return s==="list"?"safe":s==="remove"&&o.force===!0?"high":"medium"}if(r==="browser_act"||r==="browser_open"||r==="web_scrape")return"medium";if(r==="web_request"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.method=="string"?o.method.toUpperCase():"";return s==="DELETE"?"high":s==="GET"||s==="HEAD"||s==="OPTIONS"?"safe":"medium"}if(r==="wait_for"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.type=="string"?o.type:"";if(s==="command"){let i=typeof o.command=="string"?o.command:"";return BC(i)}return s==="file"||s==="process"?"safe":"medium"}return"safe"}var MY,OY,DY,NY,Vy=h(()=>{"use strict";Rr();da();MY=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash","-X POST","-X PUT","-X PATCH","-X DELETE","-XPOST","-XPUT","-XPATCH","-XDELETE","--request POST","--request PUT","--request PATCH","--request DELETE","curl --data","curl -d","curl -F","wget --post-data","wget --post-file","launchctl load","launchctl bootstrap","launchctl submit","launchctl start ","launchctl kickstart","launchctl enable ","systemctl enable ","systemctl start ","systemctl daemon-reload"],OY=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],DY=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];NY=new Set(["delete","drop","remove","destroy","truncate","purge","wipe","write","create","update","insert","upsert","patch","rename","exec","execute","run","eval","send","push","publish","deploy","post","merge","rollback","reset","terminate","provision","scale","disable","charge","refund","revoke"])});import*as cu from"node:fs/promises";import{execSync as UY}from"node:child_process";async function HC(t,e){let n=t.method??"HEAD",r;try{r=await Fn(globalThis.fetch,t.url,{method:n,signal:e})}catch(a){let c=a instanceof Error?a.message:String(a);return{met:!1,detail:c.startsWith("refusing to")?`SSRF blocked: ${c}`:`fetch error: ${c}`,data:c.startsWith("refusing to")?{blocked:!0}:void 0}}let{status:o}=r,s={status:o};if(!(t.expected_status!==void 0?o===t.expected_status:o>=200&&o<300))return{met:!1,detail:`HTTP ${o} (want ${t.expected_status??"2xx"})`,data:s};if(t.body_contains!==void 0){let a=await r.text().catch(()=>"");if(s.bodyLength=a.length,!a.includes(t.body_contains))return{met:!1,detail:`body does not contain "${t.body_contains}"`,data:s}}else n==="HEAD"&&await r.body?.cancel().catch(()=>{});return{met:!0,detail:`HTTP ${o}`,data:s}}async function WC(t,e){let n;try{let o=t.workspaceRoot?{resolveBase:t.workspaceRoot,cwd:t.workspaceRoot}:void 0;n=de(t.path,o,"read")}catch(o){return{met:!1,detail:`path rejected: ${o instanceof Error?o.message:String(o)}`,data:{blocked:!0}}}let r;try{let o=await cu.stat(n);r={mtimeMs:o.mtimeMs,size:o.size}}catch{return{met:!1,detail:`file not found: ${t.path}`}}if(t.content_contains!==void 0){let o;try{o=await cu.readFile(n,{encoding:"utf8",signal:e})}catch(s){return{met:!1,detail:`read error: ${s instanceof Error?s.message:String(s)}`,data:r}}if(!o.includes(t.content_contains))return{met:!1,detail:`file exists but does not contain "${t.content_contains}"`,data:r}}return{met:!0,detail:`file exists (${r.size} bytes)`,data:r}}function KC(t,e){if(!Number.isInteger(t.pid)||t.pid<=1)return{met:!1,detail:`pid ${t.pid} is not a valid target (must be integer > 1)`,data:{pid:t.pid,blocked:!0}};if(e!==void 0&&!e.has(t.pid))return{met:!1,detail:`pid ${t.pid} is not a session-owned process (not in spawned PID registry)`,data:{pid:t.pid,blocked:!0}};try{return process.kill(t.pid,0),{met:!1,detail:`pid ${t.pid} is still alive`,data:{pid:t.pid}}}catch(n){let r=n.code;return r==="ESRCH"?{met:!0,detail:`pid ${t.pid} has exited`,data:{pid:t.pid}}:{met:!1,detail:`pid ${t.pid} is alive (${r??"unknown"})`,data:{pid:t.pid}}}}function qC(t){let e=au("bash",{command:t.command},{cwd:t.cwd??process.cwd()});if(e!=="safe")return{met:!1,detail:`command blocked by risk classifier (${e} risk): ${t.command}`,data:{command:t.command,blocked:!0}};try{return UY(t.command,{cwd:t.cwd,stdio:"pipe",timeout:3e4}),{met:!0,detail:"command exited 0",data:{command:t.command}}}catch(n){let r=n;if(r.killed===!0&&r.signal==="SIGTERM")return{met:!1,detail:"command timed out (30s limit)",data:{command:t.command,timedOut:!0}};let o=r.status??-1;return{met:!1,detail:`command exited ${o}`,data:{command:t.command,exitCode:o}}}}var GC=h(()=>{"use strict";Lr();Vy();Ae()});function We(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);o.unref(),e.addEventListener("abort",r,{once:!0})})}var Bn=h(()=>{"use strict"});function BY(t,e,n){switch(n){case"linear":return t+e*1e3;case"exponential":return Math.min(t*Math.pow(2,e),6e4);default:return t}}async function YC(t,e){let{timeout_ms:n,poll_interval_ms:r,backoff:o,signal:s}=e,i=Date.now()+n,a=0,c;for(;;){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};let l=i-Date.now(),d=AbortSignal.any([s,AbortSignal.timeout(Math.max(1,Math.min(r,l)))]),u;try{u=await t(d)}catch(m){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};if(m instanceof Error&&m.name==="AbortError"){if(Date.now()>=i)return{status:"timed_out",elapsed_ms:Date.now()-(i-n),attempts:a,result:c};continue}let g=m instanceof Error?m.message:String(m);return{status:"failed",elapsed_ms:Date.now()-(i-n),attempts:a,error:g}}if(c=u,a++,u.met)return{status:"succeeded",elapsed_ms:Date.now()-(i-n),attempts:a,result:u};let p=Date.now();if(p>=i)return{status:"timed_out",elapsed_ms:p-(i-n),attempts:a,result:c};let f=Math.min(BY(r,a-1,o),i-p);await We(f,s)}}var XC,zC,JC,VC,QC=h(()=>{"use strict";Bn();XC=12e4,zC=6e5,JC=5e3,VC=1e3});import ZC from"node:path";function jY(t,e){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let n=t,r=n.type;if(typeof r!="string")throw new Error('"type" is required and must be a string');let o=XC;if(n.timeout_ms!==void 0){if(typeof n.timeout_ms!="number"||!Number.isFinite(n.timeout_ms))throw new Error('"timeout_ms" must be a finite number');o=Math.min(Math.max(0,n.timeout_ms),zC)}let s=JC;if(n.poll_interval_ms!==void 0){if(typeof n.poll_interval_ms!="number"||!Number.isFinite(n.poll_interval_ms))throw new Error('"poll_interval_ms" must be a finite number');s=Math.max(VC,n.poll_interval_ms)}let i=["none","linear","exponential"],a="none";if(n.backoff!==void 0){if(!i.includes(n.backoff))throw new Error(`"backoff" must be one of: ${i.join(", ")}`);a=n.backoff}switch(r){case"url":{if(typeof n.url!="string"||n.url.trim()==="")throw new Error('"url" is required for type "url"');let c=n.body_contains!==void 0,l=n.method??(c?"GET":"HEAD");if(l!=="HEAD"&&l!=="GET")throw new Error('"method" must be "HEAD" or "GET"');return{condition:{type:"url",url:n.url,method:l,...n.expected_status!==void 0?{expected_status:Number(n.expected_status)}:{},...c?{body_contains:String(n.body_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"file":{if(typeof n.path!="string"||n.path.trim()==="")throw new Error('"path" is required for type "file"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"file",path:c!==void 0&&!ZC.isAbsolute(n.path)?ZC.resolve(c,n.path):n.path,workspaceRoot:c,...n.content_contains!==void 0?{content_contains:String(n.content_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"process":{if(typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=1)throw new Error('"pid" is required for type "process" and must be an integer > 1');return{condition:{type:"process",pid:n.pid},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"command":{if(typeof n.command!="string"||n.command.trim()==="")throw new Error('"command" is required for type "command"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"command",command:n.command,...c!==void 0?{cwd:c}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}default:throw new Error(`Unknown type "${r}". Must be one of: url, file, process, command`)}}var eP,tP=h(()=>{"use strict";Lr();GC();QC();eP=async(t,e,n)=>{let r;try{r=jY(t,n)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{condition:o,timeoutMs:s,pollIntervalMs:i,backoff:a}=r;if(o.type==="url"){let u=await Fr(o.url);if(!u.allowed)return{content:`SSRF guard blocked: ${u.reason}`,isError:!0}}let l=await YC(u=>{switch(o.type){case"url":return HC(o,u);case"file":return WC(o,u);case"process":return Promise.resolve(KC(o,n?.spawnedPidRegistry));case"command":return Promise.resolve(qC(o))}},{timeout_ms:s,poll_interval_ms:i,backoff:a,signal:e});return{content:`Wait ${l.status}: ${o.type} condition (${l.elapsed_ms}ms elapsed, ${l.attempts} attempt${l.attempts===1?"":"s"})`+(l.result?` \u2014 ${l.result.detail}`:"")+(l.error?` \u2014 error: ${l.error}`:""),isError:l.status==="failed"}}});import{createHash as HY}from"crypto";import{readFile as WY}from"fs/promises";function KY(t){return HY("sha256").update(t,"utf8").digest("hex")}function qY(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}async function nP(t,e,n){let r=[],o=new Map;for(let s of t){let i=s.path,a;try{a=de(i,n,"write",e)}catch(l){r.push({path:i,error:"path_containment",detail:l instanceof Error?l.message:String(l)});continue}try{Uo(a,"patch_apply")}catch(l){r.push({path:i,error:"write_denied",detail:l instanceof Error?l.message:String(l)});continue}if(s.edits!==void 0&&s.content!==void 0){r.push({path:i,error:"mutually_exclusive",detail:"`edits` and `content` cannot both be provided for the same file."});continue}if(s.edits===void 0&&s.content===void 0){r.push({path:i,error:"no_change_specified",detail:"At least one of `edits` or `content` must be provided."});continue}let c;try{c=await WY(a,"utf-8")}catch(l){if(s.expected_hash!==void 0||s.edits!==void 0){r.push({path:i,error:"file_read_failed",detail:l instanceof Error?l.message:String(l)});continue}o.set(a,null),c=""}if(o.has(a)||o.set(a,c),s.expected_hash!==void 0){let l="sha256:";if(!s.expected_hash.startsWith(l)){r.push({path:i,error:"invalid_hash_format",detail:`expected_hash must start with "sha256:". Got: "${s.expected_hash}"`});continue}let d=s.expected_hash.slice(l.length),u=KY(c);if(u!==d){r.push({path:i,error:"hash_mismatch",detail:`File hash mismatch. Expected sha256:${d}, got sha256:${u}. The file may have been modified.`});continue}}if(s.edits!==void 0){let l=c;for(let d=0;d<s.edits.length;d++){let u=s.edits[d],p=qY(l,u.old);if(p===0){r.push({path:i,error:"edit_not_found",detail:`Edit #${d+1}: \`old\` string not found in file.`});break}else if(p>1)r.push({path:i,error:"edit_ambiguous",detail:`Edit #${d+1}: \`old\` string matches ${p} locations. Provide enough context to make it unique.`});else{let f=l.indexOf(u.old);l=l.slice(0,f)+u.new+l.slice(f+u.old.length)}}}}return{valid:r.length===0,errors:r,fileContents:o}}var rP=h(()=>{"use strict";Rr();Ae()});import{createHash as GY,randomBytes as XY}from"crypto";import{writeFile as oP,rename as zY,mkdir as JY,unlink as Yy,chmod as VY,stat as YY}from"fs/promises";import{dirname as iP,join as QY,isAbsolute as ZY,resolve as e8}from"path";function sP(t){return GY("sha256").update(t,"utf8").digest("hex")}function t8(t,e,n){let r=Mn(e,n);if(!r)return{text:"",payload:null};let o=[`--- a/${t}`,`+++ b/${t}`];for(let s of r.hunks){o.push(`@@ -${s.oldStart},${s.oldLines} +${s.newStart},${s.newLines} @@`);for(let i of s.lines)o.push(`${i.kind}${i.text}`)}return{text:o.join(`
|
|
358
358
|
`)+`
|
|
359
359
|
`,payload:r}}function n8(t,e){let n=t;for(let r of e){let o=n.indexOf(r.old);if(o===-1)throw new Error("patch_apply engine: edit old-string not found at apply time (validation may have passed a stale snapshot).");n=n.slice(0,o)+r.new+n.slice(o+r.old.length)}return n}function r8(t){let e=XY(8).toString("hex");return QY(iP(t),`.patch-tmp-${e}`)}async function aP(t,e,n,r){let o=[];for(let g of t){let y=ZY(g.path)?g.path:e8(n,g.path),b=e.get(y),w=b===null,v=b??"",_;if(g.content!==void 0)_=g.content;else if(g.edits!==void 0)_=n8(v,g.edits);else throw new Error(`patch_apply engine: change for ${g.path} has neither content nor edits.`);let x=t8(g.path,v,_);o.push({resolvedPath:y,originalContent:v,newContent:_,diffBlock:x.text,diffPayload:x.payload,filePath:g.path,isNewFile:w})}let s=o.map(g=>g.diffBlock).filter(Boolean).join(`
|
|
360
360
|
`),i=[],a=0,c=0;for(let g of o)if(g.diffPayload){for(let y of g.diffPayload.hunks)i.push({...y,filePath:g.filePath});a+=g.diffPayload.addedLines,c+=g.diffPayload.removedLines}let l=i.length>0?{hunks:i,addedLines:a,removedLines:c}:void 0,d=o.map(g=>({path:g.resolvedPath,before_hash:`sha256:${sP(g.originalContent)}`,after_hash:`sha256:${sP(g.newContent)}`}));if(r)return{status:"dry_run",diff:s,structuredDiff:l,files_changed:d,errors:[]};let u=[],p=[];for(let g of o){let y=r8(g.resolvedPath);try{let b;if(!g.isNewFile)try{b=(await YY(g.resolvedPath)).mode}catch{}await JY(iP(g.resolvedPath),{recursive:!0}),await oP(y,g.newContent,"utf-8"),b!==void 0&&await VY(y,b),u.push({tempPath:y,targetPath:g.resolvedPath,originalMode:b})}catch(b){p.push({path:g.resolvedPath,error:"temp_write_failed",detail:b instanceof Error?b.message:String(b)})}}if(p.length>0){for(let g of u)try{await Yy(g.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:d,errors:p}}let f=[],m=[];for(let g=0;g<u.length;g++){let y=u[g];try{await zY(y.tempPath,y.targetPath),m.push({targetPath:y.targetPath,originalContent:o[g].originalContent,isNewFile:o[g].isNewFile})}catch(b){f.push({path:y.targetPath,error:"rename_failed",detail:b instanceof Error?b.message:String(b)})}}if(f.length>0){for(let g of m)try{g.isNewFile?await Yy(g.targetPath):await oP(g.targetPath,g.originalContent,"utf-8")}catch{}for(let g of u)try{await Yy(g.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:d,errors:f}}return{status:"applied",diff:s,structuredDiff:l,files_changed:d,errors:[]}}var cP=h(()=>{"use strict";Ki()});import{resolve as o8}from"path";function s8(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object.");let e=t;if(!Array.isArray(e.changes))throw new Error('Input must have a "changes" field of type array.');let n=[];for(let o=0;o<e.changes.length;o++){let s=e.changes[o];if(typeof s!="object"||s===null)throw new Error(`changes[${o}] must be an object.`);let i=s;if(typeof i.path!="string"||i.path.trim()==="")throw new Error(`changes[${o}].path must be a non-empty string.`);let a={path:i.path};if(i.expected_hash!==void 0){if(typeof i.expected_hash!="string")throw new Error(`changes[${o}].expected_hash must be a string.`);a.expected_hash=i.expected_hash}if(i.content!==void 0){if(typeof i.content!="string")throw new Error(`changes[${o}].content must be a string.`);a.content=i.content}if(i.edits!==void 0){if(!Array.isArray(i.edits))throw new Error(`changes[${o}].edits must be an array.`);let c=[];for(let l=0;l<i.edits.length;l++){let d=i.edits[l];if(typeof d!="object"||d===null)throw new Error(`changes[${o}].edits[${l}] must be an object.`);let u=d;if(typeof u.old!="string")throw new Error(`changes[${o}].edits[${l}].old must be a string.`);if(typeof u.new!="string")throw new Error(`changes[${o}].edits[${l}].new must be a string.`);c.push({old:u.old,new:u.new})}a.edits=c}n.push(a)}let r=!1;if(e.dry_run!==void 0){if(typeof e.dry_run!="boolean")throw new Error("dry_run must be a boolean.");r=e.dry_run}return{changes:n,dry_run:r}}function Qy(t){return async(e,n,r)=>{let o=r?.resolveBase??r?.cwd??t??o8(process.cwd()),s;try{s=s8(e)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{changes:i,dry_run:a}=s;if(i.length===0)return{content:JSON.stringify({status:"applied",diff:"",files_changed:[],errors:[]},null,2),isError:!1};let c=await nP(i,o,r);if(!c.valid){let u={status:"validation_failed",diff:"",files_changed:[],errors:c.errors};return{content:JSON.stringify(u,null,2),isError:!0}}let l=await aP(i,c.fileContents,o,a),d=l.status==="validation_failed"||l.status==="partial_failure";return{content:JSON.stringify({status:l.status,diff:l.diff,files_changed:l.files_changed,errors:l.errors},null,2),isError:d,...l.structuredDiff?{render:{diff:l.structuredDiff}}:{}}}}var lP,dP=h(()=>{"use strict";rP();cP();lP=Qy()});import Zy from"fs";import ot from"path";function zt(t){try{return Zy.accessSync(t),!0}catch{return!1}}function eb(t){try{return Zy.readFileSync(t,"utf8")}catch{return null}}function i8(t){return zt(ot.join(t,"pnpm-lock.yaml"))?"pnpm":zt(ot.join(t,"yarn.lock"))?"yarn":zt(ot.join(t,"bun.lockb"))?"bun":"npm"}function a8(t){return/\bvitest\b/.test(t)?"vitest":/\bjest\b/.test(t)?"jest":/\bmocha\b/.test(t)?"mocha":null}function c8(t){let e=ot.join(t,"package.json"),n=eb(e);if(!n)return null;let r;try{r=JSON.parse(n)}catch{return null}let o=r.scripts;if(!o||typeof o!="object")return null;let s=i8(t);for(let i of["test:unit","test:integration","test"]){let a=o[i];if(typeof a!="string"||!a.trim())continue;let c=a8(a)??"node-generic",l=`${s} run ${i}`;return{runner:c,command:l,args:[s,"run",i]}}return null}function l8(t){let e=ot.join(t,"pyproject.toml"),n=eb(e);return n?/\[tool\.pytest/.test(n)?{runner:"pytest",command:"pytest",args:["pytest"]}:zt(ot.join(t,"pytest.ini"))||zt(ot.join(t,"setup.cfg"))?{runner:"pytest",command:"pytest",args:["pytest"]}:null:null}function d8(t){return zt(ot.join(t,"Cargo.toml"))?{runner:"cargo",command:"cargo test",args:["cargo","test"]}:null}function u8(t){let n=(()=>{try{return Zy.readdirSync(t)}catch{return[]}})().some(r=>r.endsWith("_test.go"));return(n||zt(ot.join(t,"go.mod")))&&(n||zt(ot.join(t,"go.mod")))?{runner:"go-test",command:"go test ./...",args:["go","test","./..."]}:null}function p8(t){return zt(ot.join(t,"Gemfile"))&&zt(ot.join(t,"spec"))?{runner:"rspec",command:"bundle exec rspec",args:["bundle","exec","rspec"]}:null}function f8(t){let e=eb(ot.join(t,"Makefile"));return e&&/^test:/m.test(e)?{runner:"node-generic",command:"make test",args:["make","test"]}:null}function uP(t){return c8(t)??l8(t)??d8(t)??u8(t)??p8(t)??f8(t)??null}var pP=h(()=>{"use strict"});function m8(t){let e=[],n=/^\s*●\s+(.+?)\s*$/gm,r=/^FAIL\s+(.+\.(?:test|spec)\.[jt]sx?)\s*$/gm,o=t.split(`
|
|
@@ -374,7 +374,7 @@ Failed tests:
|
|
|
374
374
|
${b.map(A=>` \u2022 ${A.name}${A.file?` (${A.file}${A.line!==void 0?`:${A.line}`:""})`:""}: ${A.message}`).join(`
|
|
375
375
|
`)}`:"")+`
|
|
376
376
|
|
|
377
|
-
${gP(c)}`,x={runner:f,command:a,passed:m,failed:g,...y!==void 0?{skipped:y}:{},duration_ms:u,failures:b,raw_output:c};return{content:_,isError:l!==0&&l!==null,testResult:p??void 0,...x!==void 0?{testRunResult:x}:{}}}});import{z as
|
|
377
|
+
${gP(c)}`,x={runner:f,command:a,passed:m,failed:g,...y!==void 0?{skipped:y}:{},duration_ms:u,failures:b,raw_output:c};return{content:_,isError:l!==0&&l!==null,testResult:p??void 0,...x!==void 0?{testRunResult:x}:{}}}});import{z as D}from"zod";var ua,E8,_8,ob,bP,wP,SP,kP,vP,pa,lu=h(()=>{"use strict";ua=3,E8=D.object({toolName:D.string(),toolUseId:D.string().optional(),input:D.string().optional(),inputRaw:D.string().optional(),result:D.string().optional(),isError:D.boolean().optional()}).passthrough(),_8=D.object({user:D.string().default(""),assistant:D.string().default(""),timestamp:D.number().optional(),toolEvents:D.array(E8).optional()}).passthrough(),ob=D.object({sessionId:D.string().optional(),name:D.string().optional(),source:D.enum(["cli","telegram","web"]).optional(),telegramChatId:D.number().optional(),model:D.string(),startedAt:D.number(),savedAt:D.number(),totalTurns:D.number(),totalCostUsd:D.number().optional(),totalTokens:D.number().optional(),totalDurationMs:D.number().optional(),turns:D.array(_8).default([]),forkedFrom:D.string().optional(),forkedAt:D.number().optional()}).passthrough(),bP=D.enum(["fully_achieved","partially_achieved","not_achieved","aborted"]),wP=D.enum(["not_persisted","persisted","unknown"]),SP=D.object({tool:D.string(),label:D.string().optional()}),kP=D.object({files_written:D.number().int(),files_edited:D.number().int(),bash_commands:D.number().int(),commits:D.number().int(),mutated:D.boolean()}),vP=D.object({input:D.number().optional(),output:D.number().optional(),cache_read:D.number().optional(),cache_creation:D.number().optional(),cost_usd:D.number()}),pa=D.object({facet_version:D.number().int(),session_id:D.string(),source:D.enum(["cli","telegram","web","unknown"]),model:D.string(),derived_at:D.string(),derived_from:D.literal("afk-session"),source_session_path:D.string(),source_session_mtime_ms:D.number(),subagent_persistence:wP,start_time:D.string(),end_time:D.string(),duration_minutes:D.number(),underlying_goal:D.string(),first_prompt:D.string(),goal_categories:D.record(D.string(),D.number()),session_type:D.string(),brief_summary:D.string(),total_turns:D.number().int(),user_message_count:D.number().int(),assistant_message_count:D.number().int(),tool_counts:D.record(D.string(),D.number()),commands:D.array(D.string()),skills:D.array(D.string()),subagents:D.array(SP),tool_errors:D.number().int(),tool_error_categories:D.record(D.string(),D.number()),friction_counts:D.record(D.string(),D.number()),friction_detail:D.string(),outcome:bP,primary_success:D.string(),world_changes:kP,token_breakdown:vP.optional(),decisions:D.array(D.string()),evidence_pointers:D.array(D.string())}).passthrough()});import{basename as A8}from"path";function M8(t){if(t)try{let e=JSON.parse(t);return e&&typeof e=="object"?e:void 0}catch{return}}function du(t){return typeof t=="string"?t:void 0}function uu(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function O8(t){return t.replace(/[-_]+/g," ").trim()}function D8(t,e){return EP.test(t)?"slash_command":e==="telegram"?"chat":"task"}function F8(t){let e=new Map,n=[];for(let r of t)r.toolUseId===void 0?n.push(r):e.set(r.toolUseId,r);return[...e.values(),...n]}function fa(t,e={}){let n=t.turns??[],r=F8(n.flatMap($=>$.toolEvents??[])),o={},s={},i=[],a=[],c=[],l=0,d=0,u=0,p=0,f=0;for(let $ of r){let U=$.toolName;o[U]=(o[U]??0)+1,$.isError===!0&&(l+=1,s[U]=(s[U]??0)+1);let j=M8($.inputRaw??$.input);if(U==="write_file"&&(d+=1),U==="edit_file"&&(u+=1),U==="bash"){p+=1;let K=du(j?.command)??$.input;K&&P8.test(K)&&(f+=1)}if(R8.has(U)){let K=du(j?.file_path);K&&!c.includes(K)&&c.length<C8&&c.push(K)}if(x8.has(U)){let K;U==="skill"?(K=du(j?.name),K&&!a.includes(K)&&a.push(K)):U==="agent"?K=du(j?.id_prefix):K="compose",i.push(K?{tool:U,label:K}:{tool:U})}}let m=n[0]?.user??"",g=t.source??"cli",y=D8(m,g),b=[];for(let $ of n){let j=EP.exec($.user??"")?.[1];j&&!b.includes(j)&&b.push(j)}let w=n.filter($=>($.user??"").trim().length>0).length,v=n.filter($=>($.assistant??"").trim().length>0).length,_=[...n].reverse().find($=>($.assistant??"").trim().length>0)?.assistant??"",x;n.length===0?x="aborted":_.trim().length===0?x="partially_achieved":x="fully_achieved";let I=x==="fully_achieved"||x==="partially_achieved"?uu(_||m||y,160)||y:"none",C=l>0?`${l} tool error(s): ${Object.entries(s).map(([$,U])=>`${$}\xD7${U}`).join(", ")}`:"",T=t.name?O8(t.name):uu(m,80),R=uu(_||m,I8),E=uu(T?`${T} \u2014 ${R}`:R,400)||"empty session",P=t.sessionId??(e.sourceSessionPath?A8(e.sourceSessionPath,".json"):"unknown"),H=t.totalDurationMs&&t.totalDurationMs>0?t.totalDurationMs:Math.max(0,t.savedAt-t.startedAt),M=e.sourceSessionPath?[...c,e.sourceSessionPath]:c,N={facet_version:ua,session_id:P,source:g==="telegram"?"telegram":g==="web"?"web":"cli",model:t.model,derived_at:(e.derivedAt??new Date).toISOString(),derived_from:"afk-session",source_session_path:e.sourceSessionPath??"",source_session_mtime_ms:e.sourceSessionMtimeMs??t.savedAt,subagent_persistence:"not_persisted",start_time:new Date(t.startedAt).toISOString(),end_time:new Date(t.savedAt).toISOString(),duration_minutes:Number((H/6e4).toFixed(2)),underlying_goal:m.slice(0,TP),first_prompt:m.slice(0,TP),goal_categories:{[y]:1},session_type:y,brief_summary:E,total_turns:n.length,user_message_count:w,assistant_message_count:v,tool_counts:o,commands:b,skills:a,subagents:i,tool_errors:l,tool_error_categories:s,friction_counts:{...s},friction_detail:C,outcome:x,primary_success:I,world_changes:{files_written:d,files_edited:u,bash_commands:p,commits:f,mutated:d>0||u>0||f>0},decisions:[],evidence_pointers:M};return t.totalCostUsd!=null&&(N.token_breakdown={cost_usd:t.totalCostUsd}),pa.parse(N)}var x8,R8,TP,I8,C8,P8,EP,sb=h(()=>{"use strict";lu();x8=new Set(["agent","compose","skill"]),R8=new Set(["read_file","write_file","edit_file"]),TP=1e3,I8=240,C8=50,P8=/\bgit\s+commit(?![\w-])/,EP=/^\s*\/([a-zA-Z][\w-]*)/});import{existsSync as pu,mkdirSync as L8,readFileSync as _P,readdirSync as N8,renameSync as $8,statSync as U8,writeFileSync as B8}from"fs";import{basename as j8,dirname as H8,join as AP}from"path";function xP(t,e){return ri(t),AP(e,`${t}.json`)}function W8(t,e){return ri(t),AP(e,`${t}.json`)}function fu(t,e=ce()){let n=xP(t,e);if(pu(n))try{let r=JSON.parse(_P(n,"utf8")),o=ob.safeParse(r);return o.success?o.data:void 0}catch{return}}function K8(t){if(pu(t))try{let e=JSON.parse(_P(t,"utf8")),n=pa.safeParse(e);return n.success?n.data:void 0}catch{return}}function q8(t,e){L8(H8(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;B8(n,`${JSON.stringify(e,null,2)}
|
|
378
378
|
`,"utf8"),$8(n,t)}function G8(t,e){return t.facet_version===ua&&t.source_session_mtime_ms===e}function Xr(t,e={}){let n=e.sessionsDir??ce(),r=e.cacheDir??kv(),o=xP(t,n);if(!pu(o))return;let s=U8(o).mtimeMs,i=W8(t,r);if(!e.force){let l=K8(i);if(l&&G8(l,s))return l}let a=fu(t,n);if(!a)return;let c=fa(a,{sourceSessionPath:o,sourceSessionMtimeMs:s});return q8(i,c),c}function ma(t={}){let e=t.sessionsDir??ce();return pu(e)?N8(e).filter(n=>n.endsWith(".json")).map(n=>j8(n,".json")):[]}var ib=h(()=>{"use strict";B();sb();lu()});function ab(){return t=>{if(t.event!=="SessionEnd")return{};if(t.parentSessionId)return{};let e=t.sessionId;if(!e)return{};try{Xr(e)}catch{}return{}}}var cb=h(()=>{"use strict";ib()});var lb=h(()=>{"use strict";lu();sb();ib();cb()});import{statSync as X8}from"node:fs";import{join as z8}from"node:path";var RP,IP=h(()=>{"use strict";lb();B();Ky();Bg();RP=async(t,e)=>{let n=t??{},r=typeof n.session=="string"?n.session:"latest",o=Array.isArray(n.fields)?n.fields:null,s;if(r==="latest"){let d=ma();if(d.length>0){let u=ce(),p;for(let f of d)try{let m=X8(z8(u,`${f}.json`)).mtimeMs;(!p||m>p.mtimeMs)&&(p={id:f,mtimeMs:m})}catch{}s=p?.id}}else s=ou(r)?.sidecarId;if(!s)return{content:`Session not found: ${r}`,isError:!0};let i=Xr(s);if(!i)return{content:`Session not found: ${r}`,isError:!0};let a=i,c={},l=new Set(a_);if(o&&o.length>0)for(let d of o)c[d]=a[d];else for(let[d,u]of Object.entries(a))l.has(d)||(c[d]=u);return{content:JSON.stringify(c,null,2)}}});import{promises as CP}from"fs";function db(t){let e=t.trim();if(e==="keys")return{kind:"keys"};if(e==="length")return{kind:"length"};if(e===".")return{kind:"identity"};let n=Y8(e);if(n!==-1){let o=db(e.slice(0,n).trim()),s=db(e.slice(n+1).trim());return{kind:"pipe",left:o,right:s}}let r=e.match(/^\.\[(.+)\]$/);if(r){let o=(r[1]??"").trim(),s=o.match(/^(-?\d+)\s*:\s*(-?\d+)$/);if(s)return{kind:"slice",from:Number(s[1]??"0"),to:Number(s[2]??"0")};if(/^-?\d+$/.test(o))return{kind:"index",idx:Number(o)};throw new Error(`Unrecognised bracket expression: .[${o}]`)}if(e===".[]")return{kind:"iter"};if(e.startsWith(".")){let o=e.slice(1);if(o.length===0)return{kind:"identity"};if(/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(o)){let s=o.split("."),i=s[0]??"";if(s.length===1)return{kind:"field",name:i};let a={kind:"field",name:i};for(let c=1;c<s.length;c++)a={kind:"pipe",left:a,right:{kind:"field",name:s[c]??""}};return a}}throw new Error(`Unrecognised query expression: "${e}". Supported: . .field .field.nested .[N] .[N:M] .[] keys length .[] | .field`)}function Y8(t){let e=0;for(let n=0;n<t.length;n++){let r=t[n];if(r==="["||r==="(")e++;else if(r==="]"||r===")")e--;else if(r==="|"&&e===0)return n}return-1}function Q8(t){return t.kind==="iter"||t.kind==="pipe"&&t.left.kind==="iter"}function ub(t,e){switch(t.kind){case"identity":return[e];case"keys":{if(e===null||typeof e!="object")throw new Error(`keys requires an object or array, got ${Qo(e)}`);return Array.isArray(e)?[e.map((n,r)=>r)]:[Object.keys(e)]}case"length":{if(Array.isArray(e))return[e.length];if(e!==null&&typeof e=="object")return[Object.keys(e).length];if(typeof e=="string")return[e.length];if(e===null)return[0];throw new Error(`length not defined for ${Qo(e)}`)}case"field":{if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Cannot access field ".${t.name}" on ${Qo(e)}`);return[e[t.name]]}case"index":{if(!Array.isArray(e))throw new Error(`Cannot index non-array with .[${t.idx}]`);let n=e.length,r=t.idx<0?n+t.idx:t.idx;return[e[r]]}case"slice":{if(!Array.isArray(e)&&typeof e!="string")throw new Error(`Cannot slice ${Qo(e)} \u2014 expected array or string`);return Array.isArray(e)?[e.slice(t.from,t.to)]:[e.slice(t.from,t.to)]}case"iter":{if(!Array.isArray(e))throw new Error(`Cannot iterate (.[] ) over ${Qo(e)} \u2014 expected array`);return e}case"pipe":{let n=ub(t.left,e),r=[];for(let o of n){let s=ub(t.right,o);r.push(...s)}return r}}}function Qo(t){return t===null?"null":Array.isArray(t)?"array":typeof t}async function Z8(t,e,n,r){if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t,s=o.path,i=o.query,a=o.max_results??J8,c=o.max_bytes??V8;if(typeof s!="string"||s.length===0)return{content:"Invalid input: path must be a non-empty string",isError:!0};if(typeof i!="string"||i.length===0)return{content:"Invalid input: query must be a non-empty string",isError:!0};if(typeof a!="number"||a<1)return{content:"Invalid input: max_results must be a positive number",isError:!0};if(typeof c!="number"||c<1)return{content:"Invalid input: max_bytes must be a positive number",isError:!0};let l=Math.floor(a),d=Math.floor(c),u;try{u=de(s,n,"read",r)}catch(I){return{content:I instanceof Error?I.message:String(I),isError:!0}}let p;try{p=db(i)}catch(I){return{content:`Invalid query: ${I instanceof Error?I.message:String(I)}`,isError:!0}}let f;try{let I=await CP.stat(u);if(I.size>PP)return{content:`File too large (${I.size} bytes). json_query supports files up to ${PP} bytes.`,isError:!0};f=await CP.readFile(u)}catch(I){let C=mt(I,u,"File");return C||{content:`Error reading file: ${I instanceof Error?I.message:String(I)}`,isError:!0}}let m=f.length;if(m===0)return{content:JSON.stringify({result:null,type:"null",truncated:!1,source_size:0})};let g;try{g=JSON.parse(f.toString("utf-8"))}catch(I){return{content:`JSON parse error: ${I instanceof SyntaxError?I.message:String(I)}`,isError:!0}}let y;try{y=ub(p,g)}catch(I){return{content:`Query error: ${I instanceof Error?I.message:String(I)}`,isError:!0}}let b=Q8(p),w=!1,v;if(y.length===1&&!b){let I=y[0];Array.isArray(I)&&I.length>l?(v=I.slice(0,l),w=!0):v=I}else y.length>l?(v=y.slice(0,l),w=!0):v=y;let _=v===void 0?"null":JSON.stringify(v,null,2),x;Buffer.byteLength(_,"utf-8")>d?(w=!0,x=Buffer.from(_,"utf-8").slice(0,d).toString("utf-8")+`
|
|
379
379
|
\u2026 [truncated]`):x=v===void 0?null:v;let A={result:x,type:v===void 0?"null":Qo(v),truncated:w,source_size:m};return{content:JSON.stringify(A)}}function pb(t){return(e,n,r)=>Z8(e,n,r,t)}var J8,V8,PP,MP,OP=h(()=>{"use strict";Ae();Pr();J8=100,V8=50*1024,PP=10*1024*1024;MP=pb()});import{spawnSync as e6}from"node:child_process";function t6(t){switch(t){case"darwin":return[{cmd:"pbcopy",args:[]}];case"win32":return[{cmd:"clip",args:[]}];default:return[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}}function n6(t){return`\x1B]52;c;${Buffer.from(t,"utf8").toString("base64")}\x07`}function r6(t,e){return n6(t)}function o6(t,e=process.env,n=process.stdout){if(n.isTTY!==!0)return!1;try{return n.write(r6(t,e)),!0}catch{return!1}}function DP(t,e=process.platform,n=process.env,r=process.stdout){for(let o of t6(e))try{let s=e6(o.cmd,o.args,{input:t});if(!s.error&&s.status===0)return!0}catch{}return o6(t,n,r)}var FP=h(()=>{"use strict"});import{spawnSync as s6}from"node:child_process";function i6(t){switch(t){case"darwin":return[{cmd:"pbpaste",args:[]}];case"win32":return[{cmd:"powershell",args:["-NoProfile","-NonInteractive","-Command","Get-Clipboard"]}];default:return[{cmd:"wl-paste",args:["--no-newline"],checkStderr:!0},{cmd:"xclip",args:["-selection","clipboard","-o"]},{cmd:"xsel",args:["--clipboard","--output"]}]}}function a6(t=process.platform){for(let e of i6(t))try{let n=s6(e.cmd,e.args,{encoding:"utf8",timeout:5e3});if(!n.error&&n.status===0&&n.signal===null&&(!e.checkStderr||!n.stderr?.trim()))return n.stdout??""}catch{}return null}function LP(t={}){let e=t.writeFn??(n=>DP(n));return async(n,r)=>{if(!n||typeof n!="object")return{content:"Invalid input: expected an object",isError:!0};let s=n.text;if(typeof s!="string")return{content:"Invalid input: text must be a string",isError:!0};let i;try{i=e(s)}catch(a){return{content:`Clipboard write threw an error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}return i?{content:"Text copied to clipboard successfully."}:{content:"Clipboard write failed: no clipboard utility available in this environment (headless, SSH-only, or CI). The text was not written to the clipboard.",isError:!0}}}function $P(t={}){let e=t.readFn??(()=>a6());return async(n,r,o)=>{let s=await He.route({serverName:"agent",origin:"agent",message:"The model wants to read your clipboard contents. Clipboard may contain passwords, tokens, or other sensitive data. Allow the model to read the clipboard?",type:"confirm"},{signal:r,...o?.sessionId!==void 0?{sessionId:o.sessionId}:{}});if(s.action!=="accept"||s.content?.value!==!0)return{content:"Clipboard read was not approved by the operator.",isError:!0,failureClass:"elicitation-declined"};let i=e();if(i===null)return{content:"Clipboard read failed: no clipboard utility available in this environment (headless, SSH-only, or CI). No content was returned.",isError:!0};let a=qe(i),c=1e5,d=Buffer.byteLength(a,"utf8")>c;return{content:(()=>{if(!d)return a;let p=Buffer.from(a,"utf8"),f=c;for(;f>0&&(p[f]&192)===128;)f--;return p.slice(0,f).toString("utf8")})(),...d?{truncated:!0}:{}}}}var NP,UP,BP=h(()=>{"use strict";FP();vn();$n();NP=LP();UP=$P()});function mu(t,e){let n=t!==void 0?Sd(t,e):e!==void 0?Sd("default",e):sA,r=e!==void 0?_h(e):vA,o=e!==void 0?xh(e):CA,s=e!==void 0?kh(e):aA,i=e!==void 0?vh(e):fA,a=e!==void 0?Th(e):hA,c=e!==void 0?Eh(e):wA,l=e!==void 0?Ih(e):MA,d=Sy(),u=kI(e),p=e!==void 0?Qy(e):lP,f=e!==void 0?pb(e):MP;return new Map([["bash",n],["read_file",s],["extract_document",i],["write_file",a],["edit_file",c],["glob",r],["grep",o],["list_directory",l],["send_telegram",Ox],["web_scrape",CR],["web_request",NR],["create_schedule",XR],["list_schedules",zR],["get_schedule_history",JR],["cancel_schedule",VR],["read_witness",gC],["search_witness",hC],["worktree",u],["terminal_font_size",d],["config_get",YI],["config_set",QI],["ask_question",SC],["wait_for",eP],["browser_open",TC],["browser_observe",_C],["browser_act",IC],["browser_screenshot",MC],["browser_close",DC],["patch_apply",p],["test_run",hP],["get_facet",RP],["json_query",f],["clipboard_write",NP],["clipboard_read",UP]])}var fb=h(()=>{"use strict";iA();cA();mA();yA();SA();TA();PA();OA();Dx();PR();$R();YR();tI();vI();ZI();yC();kC();EC();AC();CC();OC();FC();tP();dP();yP();IP();OP();BP()});function jP(t){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${t}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${t}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
|
|
380
380
|
`)}var HP=h(()=>{"use strict"});function l6(t){switch(t){case"bypassPermissions":return"Approve \u2014 implement now (restore bypass mode: no prompts, read/write any path)";case"acceptEdits":return"Approve \u2014 implement now (restore accept-edits mode: edits auto-approved)";case"dontAsk":case"auto":return"Approve \u2014 implement now (restore your previous mode: no approval prompts)";default:return"Approve \u2014 implement now (restore default mode: writes ask for confirmation, contained to the workspace)"}}function hu(t){return async(e,n,r)=>{if(t.hasPendingUserMessage?.())return{content:"The user has a queued message waiting to be delivered. End your turn now so the message is delivered first. You can call exit_plan_mode again afterward."};let o=t.getPrePlanMode()??"default",s=l6(o),a={serverName:"agent",origin:"agent",type:"choice",message:"Plan ready. How do you want to proceed? (Your plan is in the conversation above.)",choices:o==="bypassPermissions"?[s,mb]:[s,c6,mb]},c=await He.route(a,{signal:n,...r?.sessionId!==void 0?{sessionId:r.sessionId}:{}});if(c.action!=="accept")return{content:"Plan exit not confirmed (the user did not approve). Stay in plan mode \u2014 keep refining the plan; do not implement. Call exit_plan_mode again when ready."};let l=typeof c.content?.value=="string"?c.content.value:"";if(l.startsWith("Keep")||l===mb)return{content:"User chose to keep planning. Stay in plan mode and refine the plan; do not implement. Call exit_plan_mode again when ready."};let d=l.includes("bypass")?"bypassPermissions":o,u=_v(r?.resolveBase??r?.cwd??process.cwd());return t.requestImplementSeed(jP(u),d),{content:`Plan approved (mode=${d}). The implementation instruction will follow as a new message \u2014 end your turn now.`}}}var yt,c6,mb,gu,zr=h(()=>{"use strict";$n();HP();B();yt="exit_plan_mode",c6="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",mb="Keep planning";gu={name:yt,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
|
|
@@ -452,7 +452,7 @@ After calling this tool, END YOUR TURN. On approval you will receive a separate
|
|
|
452
452
|
AND (expires_at IS NULL OR expires_at >= ?)
|
|
453
453
|
ORDER BY key ASC
|
|
454
454
|
LIMIT ? OFFSET ?
|
|
455
|
-
`,a=this.db.prepare(i).all(e,r,o,s);return a.map(c=>({key:c.key,value:JSON.parse(c.value),version:c.version,updated_at:c.updated_at}))}close(){try{this.db.close()}catch{}}}});var Zo,hb=h(()=>{"use strict";Zo=class{_pids=new Set;register(e){Number.isInteger(e)&&e>1&&this._pids.add(e)}has(e){return this._pids.has(e)}clear(){this._pids.clear()}get size(){return this._pids.size}}});function zP(t){let e=[...Wt];t.subagentExecutor&&e.push(t.subagentExecutor.describeAgentTool?.()??rt),t.skillExecutor&&e.push(Er),t.composeExecutor&&e.push(_r),t.readOnlyMemory===!0?e.push(To):e.push(...kn),t.readOnlyMemory===!0?e.push(...Zl):e.push(...Oo),t.workspaceStore!==void 0&&(e.push(_i),e.push(Ai),t.subscribeHandler!==void 0&&e.push(xg)),e.push(xt);for(let n of t.customTools??[])e.some(r=>r.name===n.schema.name)||e.push(n.schema);return e}var JP=h(()=>{"use strict";ut();Nt();In();Ue();ed()});function VP(t){let e=typeof t.baseUrl=="string"&&t.baseUrl.length>0,n=e?t.apiKey&&t.apiKey.length>0?t.apiKey:k.AFK_LOCAL_API_KEY||"local":t.apiKey&&t.apiKey.length>0?t.apiKey:k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN||"";return{localMode:e,token:n}}var YP=h(()=>{"use strict";F()});function Me(t,e){if(t===null||typeof t!="object")return;let n=t.headers;if(n==null)return;if(typeof n.get=="function")return n.get(e)??void 0;if(typeof n=="object"){let o=n,s=o[e]??o[e.toUpperCase()];return typeof s=="string"?s:void 0}}function Hn(t){let e=Me(t,"retry-after-ms");if(e!==void 0){let r=Number(e);if(Number.isFinite(r)&&r>=0)return r}let n=Me(t,"retry-after");if(n!==void 0){let r=Number(n);if(Number.isFinite(r)&&r>=0)return Math.round(r*1e3);let o=Date.parse(n);if(!Number.isNaN(o)){let s=o-Date.now();if(s>=0)return s}}}var yb=h(()=>{"use strict"});function QP(t){if(!Number.isFinite(t)||t<=0)return;let e=t*1e3;if(!(e>b6))return new Date(e)}function ga(t){if(!("status"in t))return null;let e=t.status;if(e===429){let n=t.message.split("|");if(n.length>=2){let c=QP(parseInt(n[1].trim(),10));if(c!==void 0)return{kind:"oauth-limit",resetsAt:c}}let r=Me(t,"anthropic-ratelimit-unified-representative-claim"),o=Me(t,"anthropic-ratelimit-unified-overage-status"),s=Me(t,"anthropic-ratelimit-unified-status");if(r!==void 0||o!==void 0||s==="rejected"){let c=Me(t,"anthropic-ratelimit-unified-reset");if(c!==void 0){let l=QP(Number(c));if(l!==void 0)return{kind:"oauth-limit",resetsAt:l}}return{kind:"oauth-limit-no-ts"}}if(Me(t,"anthropic-ratelimit-requests-remaining")!==void 0||Me(t,"anthropic-ratelimit-requests-limit")!==void 0||Me(t,"anthropic-ratelimit-requests-reset")!==void 0||Me(t,"anthropic-ratelimit-input-tokens-remaining")!==void 0||Me(t,"anthropic-ratelimit-input-tokens-limit")!==void 0||Me(t,"anthropic-ratelimit-input-tokens-reset")!==void 0||Me(t,"anthropic-ratelimit-output-tokens-remaining")!==void 0||Me(t,"anthropic-ratelimit-output-tokens-limit")!==void 0||Me(t,"anthropic-ratelimit-output-tokens-reset")!==void 0)return{kind:"rate-limit-transient",retryAfterMs:Hn(t)};let a=Hn(t);return a!==void 0&&a<=y6?{kind:"rate-limit-transient",retryAfterMs:a}:{kind:"oauth-limit-no-ts"}}return e===400&&t.message.includes("invalid_request_error")&&t.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function ZP(t){let{resetsAt:e,signal:n,readToken:r=Xe}=t,o=r(),s=e.getTime()+3e4;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>n.aborted?(l("aborted"),!0):Date.now()>=s?(l("timer"),!0):r()!==o?(l("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function eM(t){let{signal:e,readToken:n=Xe,retryAfterMs:r}=t,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),e.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>e.aborted?(l("aborted"),!0):n()!==o?(l("hot-swap"),!0):s!==void 0&&Date.now()>=s?(l("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),e.addEventListener("abort",d,{once:!0}))})}var y6,b6,ha=h(()=>{"use strict";qo();yb();y6=300*1e3,b6=864e13});function vu(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function v6(){let t=k.AFK_RATE_LIMIT_STAGGER_MAX_MS,e=t!==void 0?parseInt(t,10):500,n=Number.isFinite(e)&&e>=0?e:500;return Math.random()*n}function T6(){return k.AFK_RATE_LIMIT_ADMISSION_DISABLED==="1"}function Tu(t){let e=0;if(typeof t=="string")e=t.length;else if(t&&typeof t=="object"&&"body"in t){let n=t.body;typeof n=="string"?e=n.length:(n instanceof ArrayBuffer||n instanceof Uint8Array)&&(e=n.byteLength)}return Math.ceil(e/k6)+S6}var w6,S6,k6,bb,es,ya=h(()=>{"use strict";F();w6=12e4,S6=2e3,k6=3.5;bb=class{requestsRemaining=-1;requestsResetAt=0;requestsLimit=-1;inputTokensRemaining=-1;inputTokensResetAt=0;inputTokensLimit=-1;outputTokensRemainingVal=-1;frozenUntil=0;resetForTests(){this.requestsRemaining=-1,this.requestsResetAt=0,this.requestsLimit=-1,this.inputTokensRemaining=-1,this.inputTokensResetAt=0,this.inputTokensLimit=-1,this.outputTokensRemainingVal=-1,this.frozenUntil=0}get outputTokensRemaining(){return this.outputTokensRemainingVal}update(e){e.requestsRemaining!==void 0&&(this.requestsRemaining=e.requestsRemaining),e.requestsResetAt!==void 0&&(this.requestsResetAt=e.requestsResetAt),e.requestsLimit!==void 0&&(this.requestsLimit=e.requestsLimit),e.inputTokensRemaining!==void 0&&(this.inputTokensRemaining=e.inputTokensRemaining),e.inputTokensResetAt!==void 0&&(this.inputTokensResetAt=e.inputTokensResetAt),e.inputTokensLimit!==void 0&&(this.inputTokensLimit=e.inputTokensLimit),e.outputTokensRemaining!==void 0&&(this.outputTokensRemainingVal=e.outputTokensRemaining)}freeze(e){let n=Math.min(e,w6),r=Date.now()+n;r>this.frozenUntil&&(this.frozenUntil=r)}maybeResetWindows(e){this.requestsResetAt>0&&e>=this.requestsResetAt&&(this.requestsRemaining=this.requestsLimit,this.requestsResetAt=0),this.inputTokensResetAt>0&&e>=this.inputTokensResetAt&&(this.inputTokensRemaining=this.inputTokensLimit,this.inputTokensResetAt=0)}async acquirePermit(e,n){if(!T6())for(;;){if(n?.aborted)return;let r=Date.now();if(this.frozenUntil>r){let d=this.frozenUntil-r;n?await Promise.race([vu(d),new Promise(u=>n.addEventListener("abort",()=>u(),{once:!0}))]):await vu(d);continue}if(this.maybeResetWindows(r),this.requestsRemaining===-1&&this.inputTokensRemaining===-1)return;let o=this.inputTokensRemaining===-1||this.inputTokensRemaining>=e;if(this.requestsRemaining>=1&&o){this.requestsRemaining-=1,this.inputTokensRemaining>0&&this.inputTokensRemaining!==-1&&(this.inputTokensRemaining=Math.max(0,this.inputTokensRemaining-e));return}let s=[];this.requestsResetAt>r&&s.push(this.requestsResetAt),this.inputTokensResetAt>r&&s.push(this.inputTokensResetAt);let a=this.requestsRemaining===0||this.inputTokensRemaining===0?5e3:6e4,c=s.length>0?Math.min(...s):r+a,l=Math.max(1,c-r)+v6();n?await Promise.race([vu(l),new Promise(d=>n.addEventListener("abort",()=>d(),{once:!0}))]):await vu(l)}}},es=new bb});function wb(t,e=fetch,n,r,o,s){return!t&&!n&&!r&&!o&&!s?e:async(i,a)=>{if(s){let l=Tu(a),d=a?.signal instanceof AbortSignal?a.signal:void 0;await s.acquirePermit(l,d)}let c=await e(i,a);if(o)try{o(c.headers)}catch{}if(s&&c.status===429)try{let l=Hn({headers:c.headers});s.freeze(l??5e3)}catch{}if(r)try{r(c.headers)}catch{}if(E6.has(c.status)){let l=Hn({headers:c.headers});if(n)try{n({status:c.status,...l!==void 0?{retryAfterMs:l}:{}})}catch{}if(t){let d={status:c.status,reason:c.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};l!==void 0&&(d.retryAfterMs=l),q(t,{phase:"rate_limit",...l!==void 0?{durationMs:l}:{},metadata:d})}}return c}}var E6,tM=h(()=>{"use strict";J();ha();ya();E6=new Set([429,503,529])});var Eu,nM=h(()=>{"use strict";Eu=class{items=[];waiter=null;attempts=0;push(e){this.attempts+=1;let n={status:e.status,attempt:this.attempts,...e.retryAfterMs!==void 0?{retryAfterMs:e.retryAfterMs}:{}};this.items.push(n);let r=this.waiter;this.waiter=null,r&&r()}takeAll(){return this.items.length===0?[]:this.items.splice(0,this.items.length)}waitForItem(){return this.items.length>0?Promise.resolve():new Promise(e=>{this.waiter=e})}resetAttempts(){this.attempts=0}}});function rM(t){if(t===null)return;let e=Number(t);if(Number.isFinite(e))return Math.min(1,Math.max(0,e))}function oM(t){if(t===null)return;let e=Number(t);if(!(!Number.isFinite(e)||e<0||e>_6))return new Date(e*1e3)}function iM(t){try{let e=rM(t.get("anthropic-ratelimit-unified-5h-utilization")),n=oM(t.get("anthropic-ratelimit-unified-5h-reset")),r=rM(t.get("anthropic-ratelimit-unified-7d-utilization")),o=oM(t.get("anthropic-ratelimit-unified-7d-reset"));return e===void 0&&r===void 0?void 0:{...e!==void 0?{fiveHourUtilization:e}:{},...n!==void 0?{fiveHourResetsAt:n}:{},...r!==void 0?{sevenDayUtilization:r}:{},...o!==void 0?{sevenDayResetsAt:o}:{},observedAt:new Date}}catch{return}}function _u(t){return t===void 0?void 0:Math.round(t*100)}function aM(t){let e=sM,n=e===void 0||_u(e.fiveHourUtilization)!==_u(t.fiveHourUtilization)||_u(e.sevenDayUtilization)!==_u(t.sevenDayUtilization);if(sM=t,!!n)for(let r of A6)try{r()}catch{}}var _6,sM,A6,cM=h(()=>{"use strict";_6=Date.UTC(2100,0,1)/1e3;A6=new Set});function pn(t){if(t==null||t==="")return;let e=parseInt(t,10);return Number.isFinite(e)&&e>=0?e:void 0}function Au(t){if(t==null||t==="")return;let e=Date.parse(t);if(!(!Number.isFinite(e)||e<=0))return e}function lM(t,e=Date.now()){if(t==null||t==="")return;if(t.includes("T")||t.includes("-"))return Au(t);let n=0,r=!1,o=t.match(/(\d+)h/),s=t.match(/(\d+)m(?!s)/),i=t.match(/(\d+(?:\.\d+)?)s/);return o&&(n+=parseInt(o[1],10)*36e5,r=!0),s&&(n+=parseInt(s[1],10)*6e4,r=!0),i&&(n+=parseFloat(i[1])*1e3,r=!0),r?e+n:void 0}function dM(t){let e=pn(t.get(x6)),n=pn(t.get(R6)),r=Au(t.get(I6)),o=pn(t.get(C6)),s=pn(t.get(P6)),i=Au(t.get(M6)),a=pn(t.get(O6)),c=Au(t.get(D6));if(e===void 0&&n===void 0&&o===void 0&&a===void 0)return;let l={};return e!==void 0&&(l.requestsRemaining=e),n!==void 0&&(l.requestsLimit=n),r!==void 0&&(l.requestsResetAt=r),o!==void 0&&(l.inputTokensRemaining=o),s!==void 0&&(l.inputTokensLimit=s),i!==void 0&&(l.inputTokensResetAt=i),a!==void 0&&(l.outputTokensRemaining=a),c!==void 0&&(l.outputTokensResetAt=c),l}function uM(t){let e=Date.now(),n=pn(t.get(F6)),r=pn(t.get(L6)),o=lM(t.get(N6),e),s=pn(t.get($6)),i=pn(t.get(U6)),a=lM(t.get(B6),e);if(n===void 0&&s===void 0)return;let c={};return n!==void 0&&(c.requestsRemaining=n),r!==void 0&&(c.requestsLimit=r),o!==void 0&&(c.requestsResetAt=o),s!==void 0&&(c.inputTokensRemaining=s),i!==void 0&&(c.inputTokensLimit=i),a!==void 0&&(c.inputTokensResetAt=a),c}var x6,R6,I6,C6,P6,M6,O6,D6,F6,L6,N6,$6,U6,B6,Sb=h(()=>{"use strict";x6="anthropic-ratelimit-requests-remaining",R6="anthropic-ratelimit-requests-limit",I6="anthropic-ratelimit-requests-reset",C6="anthropic-ratelimit-input-tokens-remaining",P6="anthropic-ratelimit-input-tokens-limit",M6="anthropic-ratelimit-input-tokens-reset",O6="anthropic-ratelimit-output-tokens-remaining",D6="anthropic-ratelimit-output-tokens-reset",F6="x-ratelimit-remaining-requests",L6="x-ratelimit-limit-requests",N6="x-ratelimit-reset-requests",$6="x-ratelimit-remaining-tokens",U6="x-ratelimit-limit-tokens",B6="x-ratelimit-reset-tokens"});function pM(t){let{config:e,localMode:n,authMode:r,factory:o}=t,s=!n&&e.traceWriter?new Eu:void 0,i=n?void 0:f=>{let m=iM(f);m!==void 0&&aM(m)},a=n?void 0:f=>{let m=dM(f);m!==void 0&&es.update(m)},c=n?void 0:es,l=pi(t.token,r,e.baseUrl,n?void 0:wb(e.traceWriter,void 0,s?f=>s.push(f):void 0,i,a,c)),d=o?o(l):t.createClient(l),u=n?null:eE(r),p;return r==="oauth"&&!n&&(p=async()=>{let f=await Xi();if(!f)return null;let m=pi(f,"oauth",e.baseUrl,wb(e.traceWriter,void 0,s?g=>s.push(g):void 0,i,a,c));return o?o(m):t.createClient(m)}),{client:d,throttleQueue:s,systemPrefix:u,...p!==void 0?{tokenRefresher:p}:{}}}var fM=h(()=>{"use strict";xn();tM();nM();cM();qo();ya();Sb()});function kb(){for(let t of vb)Oi(t)}function j6(){if(mM)return;mM=!0,gM=()=>kb(),process.on("exit",gM);let t=process.listenerCount("SIGINT")>0;hM=()=>{kb(),t||process.exit(130)},process.on("SIGINT",hM);let e=process.listenerCount("SIGTERM")>0;yM=()=>{kb(),e||process.exit(143)},process.on("SIGTERM",yM)}function bM(t){j6(),vb.add(t)}function wM(t){vb.delete(t)}var vb,mM,gM,hM,yM,SM=h(()=>{"use strict";Ue();vb=new Set,mM=!1,gM=null,hM=null,yM=null});import{randomUUID as H6}from"node:crypto";function Tb(t,e){return(t===void 0||t===0)&&e===void 0}function ba(t){let e=t.sessionId??t.resume;if(e!==void 0)return{id:e,memoized:t.memoized};if(!Tb(t.depth,t.parentSessionId))return{id:void 0,memoized:t.memoized};if(t.surface===void 0||!W6.has(t.surface))return{id:void 0,memoized:t.memoized};let n=t.memoized??H6();return{id:n,memoized:n}}function wa(t){let e=t.sessionId;if(!Tb(t.depth,t.parentSessionId)||e===void 0)return t.currentPresenceSessionId;if(t.currentPresenceSessionId===e)return e;let n=t.currentPresenceSessionId;n!==null&&(D(`\u2691 presence: advertised id changed ${n} \u2192 ${e} \u2014 rewriting`),wM(n),Oi(n));let r=t.runtimeStateSource.getWorkspace();return Qg({sessionId:e,surface:t.surface,actor:Sn(t.depth),cwd:t.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:t.providerName,name:t.model},workspace:r,pid:process.pid}),bM(e),e}var W6,Eb=h(()=>{"use strict";Ue();ur();ie();SM();W6=new Set(["cli"])});var kM=h(()=>{"use strict";Eb()});function vM(t){let{config:e,surface:n}=t,r,o=Pi({surface:n,getCwd:t.getCwd,modelName:t.model,providerName:t.providerName,permissionMode:t.permissionMode,...e.sessionId!==void 0?{sessionId:e.sessionId}:{},...e.parentSessionId!==void 0?{parentSessionId:e.parentSessionId}:{},...e.depth!==void 0?{depth:e.depth}:{},...e.maxDepth!==void 0?{maxDepth:e.maxDepth}:{},...e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},getEnabledToolNames:()=>r instanceof Kt?r.toolDefs.map(c=>c.name):[],getMcpTools:t.getMcpTools,getSubagents:t.getSubagents}),s=ba({sessionId:e.sessionId,resume:e.resume,depth:e.depth,parentSessionId:e.parentSessionId,surface:n,memoized:t.getMintedSessionId()});t.setMintedSessionId(s.memoized),t.setPresenceSessionId(wa({depth:e.depth,parentSessionId:e.parentSessionId,sessionId:s.id,currentPresenceSessionId:t.getPresenceSessionId(),runtimeStateSource:o,surface:n,cwd:e.cwd,providerName:t.providerName,model:t.model})),r=t.externalTools?Mi(t.externalTools,o):t.buildDispatcher(t.permissionMode,{cwd:e.cwd,readRoots:t.sharedReadRoots,writeRoots:t.sharedWriteRoots,...e.env!==void 0?{env:e.env}:{},sessionId:e.sessionId,parentSessionId:e.parentSessionId,...e.subagentId!==void 0?{subagentId:e.subagentId}:{},...e.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:e.subagentToolOutputCapBytes}:{},traceWriter:e.traceWriter,...e.bashOutputTailReporter!==void 0?{bashOutputTailReporter:e.bashOutputTailReporter}:{},runtimeStateSource:o,hookRegistry:e.hookRegistry,planExitControls:e.planExitControls});let i=r instanceof Kt?[...r.toolDefs]:[...Wt,xt],a=e.isSkillDispatch?i.filter(c=>c.name!=="ask_question"&&c.name!=="terminal_font_size"&&c.name!=="clipboard_write"&&c.name!=="clipboard_read"):e.isNonInteractive?i.filter(c=>c.name!=="ask_question"&&c.name!=="clipboard_read"&&c.name!=="clipboard_write"):i;return{queryDispatcher:r,runtimeStateSource:o,toolDefs:a,resolvedSessionId:s.id}}var TM=h(()=>{"use strict";dd();Ue();ut();kM()});function ue(t){let e=EM[t];if(!e){let n=Object.keys(EM).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}var EM,bt=h(()=>{"use strict";EM={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
|
|
455
|
+
`,a=this.db.prepare(i).all(e,r,o,s);return a.map(c=>({key:c.key,value:JSON.parse(c.value),version:c.version,updated_at:c.updated_at}))}close(){try{this.db.close()}catch{}}}});var Zo,hb=h(()=>{"use strict";Zo=class{_pids=new Set;register(e){Number.isInteger(e)&&e>1&&this._pids.add(e)}has(e){return this._pids.has(e)}clear(){this._pids.clear()}get size(){return this._pids.size}}});function zP(t){let e=[...Wt];t.subagentExecutor&&e.push(t.subagentExecutor.describeAgentTool?.()??rt),t.skillExecutor&&e.push(Er),t.composeExecutor&&e.push(_r),t.readOnlyMemory===!0?e.push(To):e.push(...kn),t.readOnlyMemory===!0?e.push(...Zl):e.push(...Oo),t.workspaceStore!==void 0&&(e.push(_i),e.push(Ai),t.subscribeHandler!==void 0&&e.push(xg)),e.push(xt);for(let n of t.customTools??[])e.some(r=>r.name===n.schema.name)||e.push(n.schema);return e}var JP=h(()=>{"use strict";ut();Nt();In();Ue();ed()});function VP(t){let e=typeof t.baseUrl=="string"&&t.baseUrl.length>0,n=e?t.apiKey&&t.apiKey.length>0?t.apiKey:k.AFK_LOCAL_API_KEY||"local":t.apiKey&&t.apiKey.length>0?t.apiKey:k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN||"";return{localMode:e,token:n}}var YP=h(()=>{"use strict";F()});function Me(t,e){if(t===null||typeof t!="object")return;let n=t.headers;if(n==null)return;if(typeof n.get=="function")return n.get(e)??void 0;if(typeof n=="object"){let o=n,s=o[e]??o[e.toUpperCase()];return typeof s=="string"?s:void 0}}function Hn(t){let e=Me(t,"retry-after-ms");if(e!==void 0){let r=Number(e);if(Number.isFinite(r)&&r>=0)return r}let n=Me(t,"retry-after");if(n!==void 0){let r=Number(n);if(Number.isFinite(r)&&r>=0)return Math.round(r*1e3);let o=Date.parse(n);if(!Number.isNaN(o)){let s=o-Date.now();if(s>=0)return s}}}var yb=h(()=>{"use strict"});function QP(t){if(!Number.isFinite(t)||t<=0)return;let e=t*1e3;if(!(e>b6))return new Date(e)}function ga(t){if(!("status"in t))return null;let e=t.status;if(e===429){let n=t.message.split("|");if(n.length>=2){let c=QP(parseInt(n[1].trim(),10));if(c!==void 0)return{kind:"oauth-limit",resetsAt:c}}let r=Me(t,"anthropic-ratelimit-unified-representative-claim"),o=Me(t,"anthropic-ratelimit-unified-overage-status"),s=Me(t,"anthropic-ratelimit-unified-status");if(r!==void 0||o!==void 0||s==="rejected"){let c=Me(t,"anthropic-ratelimit-unified-reset");if(c!==void 0){let l=QP(Number(c));if(l!==void 0)return{kind:"oauth-limit",resetsAt:l}}return{kind:"oauth-limit-no-ts"}}if(Me(t,"anthropic-ratelimit-requests-remaining")!==void 0||Me(t,"anthropic-ratelimit-requests-limit")!==void 0||Me(t,"anthropic-ratelimit-requests-reset")!==void 0||Me(t,"anthropic-ratelimit-input-tokens-remaining")!==void 0||Me(t,"anthropic-ratelimit-input-tokens-limit")!==void 0||Me(t,"anthropic-ratelimit-input-tokens-reset")!==void 0||Me(t,"anthropic-ratelimit-output-tokens-remaining")!==void 0||Me(t,"anthropic-ratelimit-output-tokens-limit")!==void 0||Me(t,"anthropic-ratelimit-output-tokens-reset")!==void 0)return{kind:"rate-limit-transient",retryAfterMs:Hn(t)};let a=Hn(t);return a!==void 0&&a<=y6?{kind:"rate-limit-transient",retryAfterMs:a}:{kind:"oauth-limit-no-ts"}}return e===400&&t.message.includes("invalid_request_error")&&t.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function ZP(t){let{resetsAt:e,signal:n,readToken:r=Xe}=t,o=r(),s=e.getTime()+3e4;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>n.aborted?(l("aborted"),!0):Date.now()>=s?(l("timer"),!0):r()!==o?(l("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function eM(t){let{signal:e,readToken:n=Xe,retryAfterMs:r}=t,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,c=!1,l=p=>{c||(c=!0,a!==void 0&&clearInterval(a),e.removeEventListener("abort",d),i(p))},d=()=>{l("aborted")},u=()=>e.aborted?(l("aborted"),!0):n()!==o?(l("hot-swap"),!0):s!==void 0&&Date.now()>=s?(l("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),e.addEventListener("abort",d,{once:!0}))})}var y6,b6,ha=h(()=>{"use strict";qo();yb();y6=300*1e3,b6=864e13});function vu(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function v6(){let t=k.AFK_RATE_LIMIT_STAGGER_MAX_MS,e=t!==void 0?parseInt(t,10):500,n=Number.isFinite(e)&&e>=0?e:500;return Math.random()*n}function T6(){return k.AFK_RATE_LIMIT_ADMISSION_DISABLED==="1"}function Tu(t){let e=0;if(typeof t=="string")e=t.length;else if(t&&typeof t=="object"&&"body"in t){let n=t.body;typeof n=="string"?e=n.length:(n instanceof ArrayBuffer||n instanceof Uint8Array)&&(e=n.byteLength)}return Math.ceil(e/k6)+S6}var w6,S6,k6,bb,es,ya=h(()=>{"use strict";F();w6=12e4,S6=2e3,k6=3.5;bb=class{requestsRemaining=-1;requestsResetAt=0;requestsLimit=-1;inputTokensRemaining=-1;inputTokensResetAt=0;inputTokensLimit=-1;outputTokensRemainingVal=-1;frozenUntil=0;resetForTests(){this.requestsRemaining=-1,this.requestsResetAt=0,this.requestsLimit=-1,this.inputTokensRemaining=-1,this.inputTokensResetAt=0,this.inputTokensLimit=-1,this.outputTokensRemainingVal=-1,this.frozenUntil=0}get outputTokensRemaining(){return this.outputTokensRemainingVal}update(e){e.requestsRemaining!==void 0&&(this.requestsRemaining=e.requestsRemaining),e.requestsResetAt!==void 0&&(this.requestsResetAt=e.requestsResetAt),e.requestsLimit!==void 0&&(this.requestsLimit=e.requestsLimit),e.inputTokensRemaining!==void 0&&(this.inputTokensRemaining=e.inputTokensRemaining),e.inputTokensResetAt!==void 0&&(this.inputTokensResetAt=e.inputTokensResetAt),e.inputTokensLimit!==void 0&&(this.inputTokensLimit=e.inputTokensLimit),e.outputTokensRemaining!==void 0&&(this.outputTokensRemainingVal=e.outputTokensRemaining)}freeze(e){let n=Math.min(e,w6),r=Date.now()+n;r>this.frozenUntil&&(this.frozenUntil=r)}maybeResetWindows(e){this.requestsResetAt>0&&e>=this.requestsResetAt&&(this.requestsRemaining=this.requestsLimit,this.requestsResetAt=0),this.inputTokensResetAt>0&&e>=this.inputTokensResetAt&&(this.inputTokensRemaining=this.inputTokensLimit,this.inputTokensResetAt=0)}async acquirePermit(e,n){if(!T6())for(;;){if(n?.aborted)return;let r=Date.now();if(this.frozenUntil>r){let d=this.frozenUntil-r;n?await Promise.race([vu(d),new Promise(u=>n.addEventListener("abort",()=>u(),{once:!0}))]):await vu(d);continue}if(this.maybeResetWindows(r),this.requestsRemaining===-1&&this.inputTokensRemaining===-1)return;let o=this.inputTokensRemaining===-1||this.inputTokensRemaining>=e;if(this.requestsRemaining>=1&&o){this.requestsRemaining-=1,this.inputTokensRemaining>0&&this.inputTokensRemaining!==-1&&(this.inputTokensRemaining=Math.max(0,this.inputTokensRemaining-e));return}let s=[];this.requestsResetAt>r&&s.push(this.requestsResetAt),this.inputTokensResetAt>r&&s.push(this.inputTokensResetAt);let a=this.requestsRemaining===0||this.inputTokensRemaining===0?5e3:6e4,c=s.length>0?Math.min(...s):r+a,l=Math.max(1,c-r)+v6();n?await Promise.race([vu(l),new Promise(d=>n.addEventListener("abort",()=>d(),{once:!0}))]):await vu(l)}}},es=new bb});function wb(t,e=fetch,n,r,o,s){return!t&&!n&&!r&&!o&&!s?e:async(i,a)=>{if(s){let l=Tu(a),d=a?.signal instanceof AbortSignal?a.signal:void 0;await s.acquirePermit(l,d)}let c=await e(i,a);if(o)try{o(c.headers)}catch{}if(s&&c.status===429)try{let l=Hn({headers:c.headers});s.freeze(l??5e3)}catch{}if(r)try{r(c.headers)}catch{}if(E6.has(c.status)){let l=Hn({headers:c.headers});if(n)try{n({status:c.status,...l!==void 0?{retryAfterMs:l}:{}})}catch{}if(t){let d={status:c.status,reason:c.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};l!==void 0&&(d.retryAfterMs=l),q(t,{phase:"rate_limit",...l!==void 0?{durationMs:l}:{},metadata:d})}}return c}}var E6,tM=h(()=>{"use strict";J();ha();ya();E6=new Set([429,503,529])});var Eu,nM=h(()=>{"use strict";Eu=class{items=[];waiter=null;attempts=0;push(e){this.attempts+=1;let n={status:e.status,attempt:this.attempts,...e.retryAfterMs!==void 0?{retryAfterMs:e.retryAfterMs}:{}};this.items.push(n);let r=this.waiter;this.waiter=null,r&&r()}takeAll(){return this.items.length===0?[]:this.items.splice(0,this.items.length)}waitForItem(){return this.items.length>0?Promise.resolve():new Promise(e=>{this.waiter=e})}resetAttempts(){this.attempts=0}}});function rM(t){if(t===null)return;let e=Number(t);if(Number.isFinite(e))return Math.min(1,Math.max(0,e))}function oM(t){if(t===null)return;let e=Number(t);if(!(!Number.isFinite(e)||e<0||e>_6))return new Date(e*1e3)}function iM(t){try{let e=rM(t.get("anthropic-ratelimit-unified-5h-utilization")),n=oM(t.get("anthropic-ratelimit-unified-5h-reset")),r=rM(t.get("anthropic-ratelimit-unified-7d-utilization")),o=oM(t.get("anthropic-ratelimit-unified-7d-reset"));return e===void 0&&r===void 0?void 0:{...e!==void 0?{fiveHourUtilization:e}:{},...n!==void 0?{fiveHourResetsAt:n}:{},...r!==void 0?{sevenDayUtilization:r}:{},...o!==void 0?{sevenDayResetsAt:o}:{},observedAt:new Date}}catch{return}}function _u(t){return t===void 0?void 0:Math.round(t*100)}function aM(t){let e=sM,n=e===void 0||_u(e.fiveHourUtilization)!==_u(t.fiveHourUtilization)||_u(e.sevenDayUtilization)!==_u(t.sevenDayUtilization);if(sM=t,!!n)for(let r of A6)try{r()}catch{}}var _6,sM,A6,cM=h(()=>{"use strict";_6=Date.UTC(2100,0,1)/1e3;A6=new Set});function pn(t){if(t==null||t==="")return;let e=parseInt(t,10);return Number.isFinite(e)&&e>=0?e:void 0}function Au(t){if(t==null||t==="")return;let e=Date.parse(t);if(!(!Number.isFinite(e)||e<=0))return e}function lM(t,e=Date.now()){if(t==null||t==="")return;if(t.includes("T")||t.includes("-"))return Au(t);let n=0,r=!1,o=t.match(/(\d+)h/),s=t.match(/(\d+)m(?!s)/),i=t.match(/(\d+(?:\.\d+)?)s/);return o&&(n+=parseInt(o[1],10)*36e5,r=!0),s&&(n+=parseInt(s[1],10)*6e4,r=!0),i&&(n+=parseFloat(i[1])*1e3,r=!0),r?e+n:void 0}function dM(t){let e=pn(t.get(x6)),n=pn(t.get(R6)),r=Au(t.get(I6)),o=pn(t.get(C6)),s=pn(t.get(P6)),i=Au(t.get(M6)),a=pn(t.get(O6)),c=Au(t.get(D6));if(e===void 0&&n===void 0&&o===void 0&&a===void 0)return;let l={};return e!==void 0&&(l.requestsRemaining=e),n!==void 0&&(l.requestsLimit=n),r!==void 0&&(l.requestsResetAt=r),o!==void 0&&(l.inputTokensRemaining=o),s!==void 0&&(l.inputTokensLimit=s),i!==void 0&&(l.inputTokensResetAt=i),a!==void 0&&(l.outputTokensRemaining=a),c!==void 0&&(l.outputTokensResetAt=c),l}function uM(t){let e=Date.now(),n=pn(t.get(F6)),r=pn(t.get(L6)),o=lM(t.get(N6),e),s=pn(t.get($6)),i=pn(t.get(U6)),a=lM(t.get(B6),e);if(n===void 0&&s===void 0)return;let c={};return n!==void 0&&(c.requestsRemaining=n),r!==void 0&&(c.requestsLimit=r),o!==void 0&&(c.requestsResetAt=o),s!==void 0&&(c.inputTokensRemaining=s),i!==void 0&&(c.inputTokensLimit=i),a!==void 0&&(c.inputTokensResetAt=a),c}var x6,R6,I6,C6,P6,M6,O6,D6,F6,L6,N6,$6,U6,B6,Sb=h(()=>{"use strict";x6="anthropic-ratelimit-requests-remaining",R6="anthropic-ratelimit-requests-limit",I6="anthropic-ratelimit-requests-reset",C6="anthropic-ratelimit-input-tokens-remaining",P6="anthropic-ratelimit-input-tokens-limit",M6="anthropic-ratelimit-input-tokens-reset",O6="anthropic-ratelimit-output-tokens-remaining",D6="anthropic-ratelimit-output-tokens-reset",F6="x-ratelimit-remaining-requests",L6="x-ratelimit-limit-requests",N6="x-ratelimit-reset-requests",$6="x-ratelimit-remaining-tokens",U6="x-ratelimit-limit-tokens",B6="x-ratelimit-reset-tokens"});function pM(t){let{config:e,localMode:n,authMode:r,factory:o}=t,s=!n&&e.traceWriter?new Eu:void 0,i=n?void 0:f=>{let m=iM(f);m!==void 0&&aM(m)},a=n?void 0:f=>{let m=dM(f);m!==void 0&&es.update(m)},c=n?void 0:es,l=pi(t.token,r,e.baseUrl,n?void 0:wb(e.traceWriter,void 0,s?f=>s.push(f):void 0,i,a,c)),d=o?o(l):t.createClient(l),u=n?null:eE(r),p;return r==="oauth"&&!n&&(p=async()=>{let f=await Xi();if(!f)return null;let m=pi(f,"oauth",e.baseUrl,wb(e.traceWriter,void 0,s?g=>s.push(g):void 0,i,a,c));return o?o(m):t.createClient(m)}),{client:d,throttleQueue:s,systemPrefix:u,...p!==void 0?{tokenRefresher:p}:{}}}var fM=h(()=>{"use strict";xn();tM();nM();cM();qo();ya();Sb()});function kb(){for(let t of vb)Oi(t)}function j6(){if(mM)return;mM=!0,gM=()=>kb(),process.on("exit",gM);let t=process.listenerCount("SIGINT")>0;hM=()=>{kb(),t||process.exit(130)},process.on("SIGINT",hM);let e=process.listenerCount("SIGTERM")>0;yM=()=>{kb(),e||process.exit(143)},process.on("SIGTERM",yM)}function bM(t){j6(),vb.add(t)}function wM(t){vb.delete(t)}var vb,mM,gM,hM,yM,SM=h(()=>{"use strict";Ue();vb=new Set,mM=!1,gM=null,hM=null,yM=null});import{randomUUID as H6}from"node:crypto";function Tb(t,e){return(t===void 0||t===0)&&e===void 0}function ba(t){let e=t.sessionId??t.resume;if(e!==void 0)return{id:e,memoized:t.memoized};if(!Tb(t.depth,t.parentSessionId))return{id:void 0,memoized:t.memoized};if(t.surface===void 0||!W6.has(t.surface))return{id:void 0,memoized:t.memoized};let n=t.memoized??H6();return{id:n,memoized:n}}function wa(t){let e=t.sessionId;if(!Tb(t.depth,t.parentSessionId)||e===void 0)return t.currentPresenceSessionId;if(t.currentPresenceSessionId===e)return e;let n=t.currentPresenceSessionId;n!==null&&(O(`\u2691 presence: advertised id changed ${n} \u2192 ${e} \u2014 rewriting`),wM(n),Oi(n));let r=t.runtimeStateSource.getWorkspace();return Qg({sessionId:e,surface:t.surface,actor:Sn(t.depth),cwd:t.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:t.providerName,name:t.model},workspace:r,pid:process.pid}),bM(e),e}var W6,Eb=h(()=>{"use strict";Ue();ur();se();SM();W6=new Set(["cli"])});var kM=h(()=>{"use strict";Eb()});function vM(t){let{config:e,surface:n}=t,r,o=Pi({surface:n,getCwd:t.getCwd,modelName:t.model,providerName:t.providerName,permissionMode:t.permissionMode,...e.sessionId!==void 0?{sessionId:e.sessionId}:{},...e.parentSessionId!==void 0?{parentSessionId:e.parentSessionId}:{},...e.depth!==void 0?{depth:e.depth}:{},...e.maxDepth!==void 0?{maxDepth:e.maxDepth}:{},...e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},getEnabledToolNames:()=>r instanceof Kt?r.toolDefs.map(c=>c.name):[],getMcpTools:t.getMcpTools,getSubagents:t.getSubagents}),s=ba({sessionId:e.sessionId,resume:e.resume,depth:e.depth,parentSessionId:e.parentSessionId,surface:n,memoized:t.getMintedSessionId()});t.setMintedSessionId(s.memoized),t.setPresenceSessionId(wa({depth:e.depth,parentSessionId:e.parentSessionId,sessionId:s.id,currentPresenceSessionId:t.getPresenceSessionId(),runtimeStateSource:o,surface:n,cwd:e.cwd,providerName:t.providerName,model:t.model})),r=t.externalTools?Mi(t.externalTools,o):t.buildDispatcher(t.permissionMode,{cwd:e.cwd,readRoots:t.sharedReadRoots,writeRoots:t.sharedWriteRoots,...e.env!==void 0?{env:e.env}:{},sessionId:e.sessionId,parentSessionId:e.parentSessionId,...e.subagentId!==void 0?{subagentId:e.subagentId}:{},...e.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:e.subagentToolOutputCapBytes}:{},traceWriter:e.traceWriter,...e.bashOutputTailReporter!==void 0?{bashOutputTailReporter:e.bashOutputTailReporter}:{},runtimeStateSource:o,hookRegistry:e.hookRegistry,planExitControls:e.planExitControls});let i=r instanceof Kt?[...r.toolDefs]:[...Wt,xt],a=e.isSkillDispatch?i.filter(c=>c.name!=="ask_question"&&c.name!=="terminal_font_size"&&c.name!=="clipboard_write"&&c.name!=="clipboard_read"):e.isNonInteractive?i.filter(c=>c.name!=="ask_question"&&c.name!=="clipboard_read"&&c.name!=="clipboard_write"):i;return{queryDispatcher:r,runtimeStateSource:o,toolDefs:a,resolvedSessionId:s.id}}var TM=h(()=>{"use strict";dd();Ue();ut();kM()});function ue(t){let e=EM[t];if(!e){let n=Object.keys(EM).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}var EM,bt=h(()=>{"use strict";EM={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
|
|
456
456
|
|
|
457
457
|
You are an inspector auditing skills for correct type categorization. Skills come from two sources:
|
|
458
458
|
- **User-scope** \u2014 authored directly by the user under \`~/.afk/skills/<name>/SKILL.md\`
|
|
@@ -1107,21 +1107,21 @@ ${r}
|
|
|
1107
1107
|
`),o+=Buffer.byteLength(u,"utf8");let p=i?u:`${g3(t)}${u}`;i=!0,c=c.then(async()=>{await d3(e,{recursive:!0,mode:448}),await l3(n,p,{encoding:"utf8",mode:384})}).catch(f=>{he("subagent-output-capture",t.sessionId??"unknown","write",f)})},d=()=>{if(r.length===0)return;let u=r.join("").trim();r=[],u.length>0&&(l(Cu("say",{text:u})),a=!0)};return{observe(u){try{if(u.type==="chunk"){let p=u.chunk;if(p.type==="content"){r.push(p.content);return}if(p.type==="tool_use_detail"){if(p.pending)return;d(),l(Cu("tool",{toolName:p.toolName,toolInput:p.toolInputCapture??p.toolInputRaw??p.toolInput}))}return}if(u.type==="message"){if(!a&&r.length===0){let p=u.message.content.trim();p.length>0&&(l(Cu("say",{text:p})),a=!0)}return}(u.type==="done"||u.type==="error")&&(d(),a=!1)}catch(p){he("subagent-output-capture",t.sessionId??"unknown","observe",p)}},end(u){try{d(),l(Cu("end",{reason:u}))}catch(p){he("subagent-output-capture",t.sessionId??"unknown","end",p)}}}}var MM,OM,p3,LM=h(()=>{"use strict";F();B();jl();Sa();Ib();MM=4*1024,OM=512*1024,p3="<!-- Best-effort secret redaction only. Connection strings, PEM blocks, and PII are NOT caught. -->"});var Pu,NM=h(()=>{"use strict";Pu=class{subscribers=new Set;closed=!1;push(e){for(let n of this.subscribers)if(n.resolve){let r=n.resolve;n.resolve=null,r({value:e,done:!1})}else n.buffer.push(e)}close(){this.closed=!0;for(let e of this.subscribers)if(e.resolve){let n=e.resolve;e.resolve=null,n({value:void 0,done:!0})}}subscribe(){let e={buffer:[],resolve:null};this.subscribers.add(e);let n=this,r={next(){return e.buffer.length>0?Promise.resolve({value:e.buffer.shift(),done:!1}):n.closed?(n.subscribers.delete(e),Promise.resolve({value:void 0,done:!0})):new Promise(o=>{e.resolve=o})},return(){if(e.resolve){let o=e.resolve;e.resolve=null,o({value:void 0,done:!0})}return n.subscribers.delete(e),Promise.resolve({value:void 0,done:!0})}};return{[Symbol.asyncIterator]:()=>r}}}});var ns,Cb=h(()=>{"use strict";ns=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(e)}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessages.length>0){let n=e.bufferedMessages.shift(),r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}}});function Mu(t,e){let n=e??Ro(),r=Io(t.model,n);if(!r){t.forceChatgptOAuth=!1,t.forceXaiOAuth=!1,t.forceXaiApiKey=!1,t.xaiBaseUrl=void 0;return}let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"||o.provider==="chatgpt-oauth"?"openai-compatible":o.provider==="xai"||o.provider==="xai-oauth"?"xai":z(t.model,e?{slots:e}:void 0);t.forceChatgptOAuth=o.provider==="chatgpt-oauth",t.forceXaiOAuth=o.provider==="xai-oauth",t.forceXaiApiKey=o.provider==="xai",o.apiKey!==void 0?t.apiKey=o.apiKey:(s==="openai-compatible"||s==="xai"||o.baseUrl!==void 0)&&(t.apiKey=void 0),o.baseUrl!==void 0?s==="xai"?t.xaiBaseUrl=o.baseUrl:s==="openai-compatible"?t.openaiBaseUrl=o.baseUrl:t.baseUrl=o.baseUrl:s==="xai"&&(t.xaiBaseUrl=void 0)}var Pb=h(()=>{"use strict";fe();Fe()});function h3(t){return typeof t=="string"?t:t.map(e=>{let n=e;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(e=>e.length>0).join(`
|
|
1108
1108
|
`)}function y3(t,e,n,r){let o=n&&n!==r?` (provider ${n} \u2192 ${r})`:"";return`[System context \u2014 not from the user. Your model was switched at the start of this turn: ${t} \u2192 ${e}${o}. Earlier turns in this conversation were produced by ${t}; the history carried across the switch is plain text only, so any prior tool calls and extended reasoning are now prose \u2014 treat their structure as lost, not authoritative.]`}function b3(t,e){return typeof t=="string"?t.length>0?`${e}
|
|
1109
1109
|
|
|
1110
|
-
${t}`:e:[{type:"text",text:e},...t]}var Ou,$M=h(()=>{"use strict";Cb();Pb();
|
|
1111
|
-
`:"")+e.text)}commitShadowTurn(){this.pendingUserText!==void 0&&(this.shadowHistory.push({user:this.pendingUserText,assistant:this.pendingAssistantText}),this.pendingUserText=void 0,this.pendingAssistantText="")}async*[Symbol.asyncIterator](){try{for(this.active=this.buildInner(this.currentModel,!1),this.activeModel=this.currentModel,yield*this.driveUntilInit(!1);!this.closed;){let e=await this.outerIterator.next();if(e.done)break;let n=e.value;this.lastSessionId=n.sessionId;let r=this.currentModel!==this.activeModel,o=!this.active||r&&this.resolveInner(this.currentModel).signature!==this.active.signature,s=this.activeModel,i=this.active?.family;this.activeModel=this.currentModel;let a;if(o&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),D(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),s!==void 0&&s!==this.currentModel&&(a=y3(s,this.currentModel??"(unset)",i,this.active.family)),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=h3(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(a?b3(n.content,a):n.content);;){let c=await this.active.iterator.next();if(c.done){this.closed=!0;break}let l=c.value;if(this.observeEvent(l),yield l,l.type==="turn.completed"){this.commitShadowTurn();break}if(l.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(e){for(;;){let n=await this.active.iterator.next();if(n.done)return yield{type:"error",error:new Error("provider ended before initialization")},this.closed=!0,!0;let r=n.value;if(r.type==="session.init")return e||(yield r),!1;if(r.type==="error")return yield r,this.closed=!0,!0;yield r}}async interrupt(e="interrupted"){await this.active?.query.interrupt(e)}async setModel(e){typeof e=="string"&&e.length>0&&(this.currentModel=e,this.active&&this.resolveInner(e).signature===this.active.signature&&await this.active.query.setModel(e))}async setPermissionMode(e){this.currentPermissionMode=e,await this.active?.query.setPermissionMode(e)}setCwd(e){this.currentCwd=e,this.active?.query.setCwd?.(e)}setSystemPrompt(e){return this.currentSystemPrompt=e,this.systemPromptOverridden=!0,this.active?.query.setSystemPrompt?.(e)??!1}async reauth(){return await this.active?.query.reauth?.()??null}async supportedCommands(){return await this.active?.query.supportedCommands()??[]}async supportedModels(){return await this.active?.query.supportedModels()??[]}async supportedAgents(){return await this.active?.query.supportedAgents()??[]}async getContextUsage(){return await this.active?.query.getContextUsage()??{}}async mcpServerStatus(){return await this.active?.query.mcpServerStatus()??[]}async accountInfo(){return await this.active?.query.accountInfo()??{}}async rewindFiles(e,n){let r=this.active;return r?r.query.rewindFiles(e,n):{canRewind:!1,error:"no active provider"}}async compact(){let e=this.active;return e?.query.compact?e.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}listRewindTargets(){return this.active?.query.listRewindTargets?.()??[]}async rewindConversation(e){let n=this.active;return n?.query.rewindConversation?n.query.rewindConversation(e):{rewound:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...e){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...e)}async close(){this.closed=!0,await this.closeActive()}}});async function Du(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{let a=0,c=l=>{r=setTimeout(()=>{a+=l;let d=0;if(n.extender)try{d=n.extender.onDeadline()}catch{d=0}if(Number.isFinite(d)&&d>0){c(d);return}let u=n.label?` (${n.label})`:"",p="";if(n.extender?.describe)try{let m=n.extender.describe();m!==void 0&&m!==""&&(p=` ${m}`)}catch{}let f=new Ie(`Operation timed out after ${a}ms${u}${p}`,a);n.controller&&!n.controller.signal.aborted&&n.controller.abort(f),i(f)},l)};c(e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}var UM,Mb,Ob=h(()=>{"use strict";se();UM=0,Mb=5e3});async function Fu(t,e,n){if(!t)return;if(n.kind==="blocked"){await dt(t,{hookEvent:e,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await dt(t,{hookEvent:e,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function BM(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);return await Fu(n.traceWriter,"SessionStart",{kind:"decision",decision:r}),r.injectContext}catch(r){throw r instanceof ee&&await Fu(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function jM(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Fu(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof ee&&await Fu(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof ee||r instanceof nt){D(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}D(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var HM=h(()=>{"use strict";ie();se();J()});var st,rs=h(()=>{"use strict";st="overload_exhausted"});function WM(t){switch(t){case"abort":return w3;case"iteration_cap":return S3;case"timeout":return k3;case"truncated":return v3;default:return null}}var w3,S3,k3,v3,KM=h(()=>{"use strict";w3="Session ended via abort before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state, or re-run the task if the interruption was intentional.",S3="Session hit the tool-use iteration cap before reaching a terminal state. Partial work is preserved in the transcript and witness trace. Resume with `afk --resume <sessionId>` to continue from where it stopped, or re-run with a higher budget (`--max-turns` or `max_tool_use_iterations`).",k3="Session was terminated by the wall-clock timeout before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue, or re-run with a longer timeout. Check the trace for whether the timeout hit during active work or while waiting on a slow tool call.",v3="Session output was truncated by the model provider's output-token ceiling before the response completed. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from where the output was cut off."});function Nu(t){if(t===void 0||!Number.isFinite(t)||t<=0||t<=12e4)return 0;let e=t*.15,n=Math.min(3e5,Math.max(3e4,e));return Math.max(0,Math.floor(t-n))}function $u(t,e,n=Date.now()){return e>0&&n-t>=e}var Ct,Lu,Wn=h(()=>{"use strict";Ct="soft_deadline_wind_down",Lu="Your time budget for this turn is nearly spent. Do not request any more tools \u2014 give your final answer now using only the information already gathered. If your work is incomplete, say briefly what you established, what remains unresolved, and what you would check next."});function Vt(t){return t!=null&&T3.includes(t)}function E3(t){switch(t){case"max_tokens":return'stop_reason "max_tokens"';case"length":return'finish_reason "length"';case"max_output_tokens":return'incomplete_details.reason "max_output_tokens"';default:return"the provider output-token cap"}}function Uu(t,e,n={}){let r=`\u26A0 This turn was cut off at the output-token limit (${E3(e)}) before the model finished \u2014 anything above is partial, not a complete answer.`;if(t.length>0){let o=[...new Set(t)].join(", "),s=n.canIncreaseOutputLimit===!1?"Continue in a follow-up turn or retry so the model can finish the action.":"Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS, then retry.";return`${r} A tool call was truncated mid-request and was NOT dispatched (${o}); that action did not run. ${s}`}return n.canIncreaseOutputLimit===!1?`${r} Continue in a follow-up turn or retry the request.`:`${r} Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS to allow a longer reply.`}var T3,ka=h(()=>{"use strict";T3=["max_tokens","length","max_output_tokens"]});function qM(t){return t.maxTurnsHit?"max_turns_exceeded":t.hookBlocked?"hook_blocked":t.dispatchReason==="error"?"abort":t.abort!==null?t.abort:t.sawProviderError||t.lastStopReason===st?"abort":t.lastStopReason==="tool_use_loop_capped"?"iteration_cap":t.lastStopReason===Ct?"timeout":Vt(t.lastStopReason)?"truncated":"model_end_turn"}var GM=h(()=>{"use strict";rs();Wn();ka()});function _3(t){let e=null,n=t.signal;if(n.aborted&&n.reason!=="closed"){let r=n.reason;r instanceof _n?e="budget_exceeded":r instanceof Ie?e="timeout":typeof r=="string"&&r.startsWith("Budget ")?e="budget_exceeded":typeof r=="string"&&r.includes("timed out")?e="timeout":e="abort"}return qM({dispatchReason:t.dispatchReason,maxTurnsHit:t.maxTurnsHit,hookBlocked:t.hookBlocked,abort:e,lastStopReason:t.lastStopReason,sawProviderError:t.sawProviderError})}function A3(t){if(t.dispatchReason==="error")return"failed";let e=t.signal;return e.aborted&&e.reason!=="closed"?"cancelled":t.sawProviderError||t.lastStopReason===st?"failed":"succeeded"}async function XM(t,e){if(!t)return;let n=_3(e),r={},o=e.runningTokens;o.input>0&&(r.input=o.input),o.output>0&&(r.output=o.output),o.cacheRead>0&&(r.cacheRead=o.cacheRead),o.cacheCreation>0&&(r.cacheCreation=o.cacheCreation);let s=WM(n);await NE(t,{reason:n,finalTurnCount:e.finalTurnCount,finalCostUsd:e.finalCostUsd,finalTokens:r,...e.lastStopReason!==void 0?{lastStopReason:e.lastStopReason}:{},...s!==null?{guidance:s}:{}})}async function zM(t,e){if(!t)return;let n=A3(e),r=e.subagentCompletedCount>0?e.subagentCompletedCount:void 0,o=e.subagentRunningTokens,i=o.input>0||o.output>0||o.cacheRead>0||o.cacheCreation>0?{...o.input>0?{input:o.input}:{},...o.output>0?{output:o.output}:{},...o.cacheRead>0?{cacheRead:o.cacheRead}:{},...o.cacheCreation>0?{cacheCreation:o.cacheCreation}:{}}:void 0,a=e.subagentRunningCostUsd>0?e.subagentRunningCostUsd:void 0;await t.seal({status:n,finalCostUsd:e.finalCostUsd,finalTurnCount:e.finalTurnCount,closedAt:new Date().toISOString(),...r!==void 0?{subagentCount:r}:{},...i!==void 0?{subagentTokens:i}:{},...a!==void 0?{subagentCostUsd:a}:{}})}var JM=h(()=>{"use strict";se();rs();J();KM();GM()});function Bu(t){let e=x3(t);return e!==void 0?e:R3(t)}function x3(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return VM(n.trim())}function R3(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=I3(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=VM(r);if(o!==void 0)return o}}function I3(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function VM(t){try{return JSON.parse(t)}catch{return}}var Db=h(()=>{"use strict"});var ju,YM=h(()=>{"use strict";F();B();la();ju=class{writer=null;initAttempted=!1;ensure(e){if(this.initAttempted||(this.initAttempted=!0,e.depth!==void 0||e.parentSessionId!==void 0)||k.AFK_SESSION_LEDGER_DISABLED==="1")return;let n=e.sessionId;if(!n)return;let r=new Nn(n);if(!r.active)return;this.writer=r;let o=e.getMetadata();r.record({kind:"meta",sessionId:n,model:o.model??e.fallbackModel,...o.cwd!==void 0?{cwd:o.cwd}:{},traceLabel:ir(e.tracePath)})}recordUser(e){this.writer?.recordUser(e)}recordEvent(e){this.writer?.recordEvent(e)}recordElicitation(e,n){this.writer?.record({kind:"elicitation",reqId:e,request:n})}seal(e){let n=this.writer;return n?(this.writer=null,this.initAttempted=!1,n.close(e)):Promise.resolve()}}});var Hu,QM=h(()=>{"use strict";Hu=class{pendingSeed;prePlanMode;modeBeforeDefault;recordModeTransition(e,n){if(e==="plan"){if(n!=="plan"){let r=n==="default"&&this.modeBeforeDefault!==void 0?this.modeBeforeDefault:n;this.prePlanMode=r==="autonomous"?void 0:r}}else e==="default"?this.modeBeforeDefault=n!=="default"&&n!=="plan"?n:void 0:this.modeBeforeDefault=void 0}clearModeBeforeDefault(){this.modeBeforeDefault=void 0}getPrePlanMode(){return this.prePlanMode}requestImplementSeed(e,n){this.pendingSeed={message:e,mode:n}}takeSeed(){let e=this.pendingSeed;return this.pendingSeed=void 0,e}}});function ZM(t,e,n){t&&(t.aborted?e.abort(t.reason):t.addEventListener("abort",()=>{e.signal.aborted||e.abort(t.reason)},{once:!0})),e.signal.addEventListener("abort",n,{once:!0})}function e0(t,e){let n=t.permissionMode??"default",r=t.persistSession??!0,o={sessionId:t.sessionId,configuredSessionId:t.sessionId,resume:t.resume,resumeSessionAt:t.resumeSessionAt,continue:t.continue,forkSession:t.forkSession,persistSession:r},s={sessionId:t.sessionId,model:e,permissionMode:n};return{sessionIdentity:o,metadata:s}}var t0=h(()=>{"use strict"});var Wu,n0=h(()=>{"use strict";Wu=class{initializationPromise;resolveInitialization;rejectInitialization;initializationSettled=!1;sessionMetadata;sessionIdentity;constructor(e,n){this.sessionIdentity=e,this.sessionMetadata=n,this.initializationPromise=new Promise((r,o)=>{this.resolveInitialization=r,this.rejectInitialization=o})}waitForInitialization(){return this.initializationPromise}getSessionIdentity(){return{...this.sessionIdentity,sessionId:this.getSessionId()}}getSessionMetadata(){return{...this.sessionMetadata,sessionId:this.getSessionId()}}getSessionId(){return this.sessionMetadata.sessionId??this.sessionIdentity.sessionId}updateSessionIdentity(e){e&&(this.sessionIdentity={...this.sessionIdentity,sessionId:e},this.sessionMetadata={...this.sessionMetadata,sessionId:e})}setSessionMetadata(e){this.sessionMetadata=e(this.sessionMetadata)}resolveInitializationIfNeeded(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}resolveInitializationOnce(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}rejectInitializationOnce(e){this.initializationSettled||(this.initializationSettled=!0,this.rejectInitialization(e))}isInitializationSettled(){return this.initializationSettled}}});function r0(t){try{let e=JSON.parse(t);if(!Array.isArray(e))return null;let n=e.length;if(n===0)return"no results";let r=0,o=0;for(let a of e)if(a&&typeof a=="object"){let c=a.type;c==="fact"?r++:c==="procedure"&&o++}let s=`${n} result${n===1?"":"s"}`;if(r+o!==n)return s;let i=[];return r>0&&i.push(`${r} fact${r===1?"":"s"}`),o>0&&i.push(`${o} procedure${o===1?"":"s"}`),i.length===0?s:`${s} (${i.join(", ")})`}catch{return null}}function o0(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;if(n.target==="hot"&&n.saved===!0){if(n.truncated===!0)return"hot memory saved (truncated to fit cap)";let r=n.usage;if(r&&typeof r=="object"){let o=r.pct;if(typeof o=="number")return`hot memory saved (${o}% of cap)`}return"hot memory saved"}if(n.target==="fact"){if(n.action==="remove")return n.removed===!0?"fact removed":"fact not found";if(n.action==="set"&&typeof n.id=="number")return`fact #${n.id} set`;if(n.action==="supersede"&&typeof n.id=="number"&&typeof n.supersedes=="number")return`fact #${n.id} supersedes #${n.supersedes}`}return null}catch{return null}}function s0(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;return typeof n.name=="string"&&n.written===!0?`wrote procedure '${n.name}'`:null}catch{return null}}var i0=h(()=>{"use strict"});function Fb(t){let e=t.trim();if(e.length===0)return null;let n=e[0];if(n!=="{"&&n!=="[")return null;let r=e[e.length-1];if(n==="{"&&r!=="}"||n==="["&&r!=="]")return null;let o;try{o=JSON.parse(e)}catch{return null}return Array.isArray(o)?a0(C3(o)):o!==null&&typeof o=="object"?a0(P3(o)):null}function C3(t){return t.length===0?"[empty array]":t.length===1?"[1 item]":`[${t.length} items]`}function P3(t){let e=Object.keys(t);if(e.length===0)return"{empty object}";let n=e.slice(0,4),r=e.length>4?", \u2026":"";return`{${n.join(", ")}${r}}`}function a0(t){return t.length<=80?t:t.slice(0,79)+"\u2026"}var c0=h(()=>{"use strict"});function l0(t,e){if(!t)return null;let n=M3.get(t);if(!n)return null;try{let r=n(e);if(r===null)return null;let o=Q(r);return o.length>0?o:null}catch{return null}}var M3,d0=h(()=>{"use strict";i0();c0();et();M3=new Map([["memory_search",r0],["memory_update",o0],["procedure_write",s0],["bash",Fb],["Bash",Fb]])});function u0(t,e){if(t===void 0||t.trim()==="")return e;let n=Number(t.trim());return!Number.isInteger(n)||n<O3||n>D3?e:n}function p0(){return{tailCount:u0(k.AFK_BASH_PREVIEW_TAIL_LINES,F3),headCount:u0(k.AFK_BASH_PREVIEW_HEAD_LINES,L3)}}function f0(t,e,n){if(t.length===0)return{head:[],tail:[]};if(e+n>=t.length){let s=t.slice(0,e),i=t.slice(e);return{head:s,tail:i}}let r=e>0?t.slice(0,e):[],o=n>0?t.slice(t.length-n):[];return{head:r,tail:o}}var O3,D3,F3,L3,m0=h(()=>{"use strict";F();O3=0,D3=200,F3=7,L3=0});function N3(t){if(t<1024)return`${t}B`;let e=t/1024;if(e<1024)return e%1===0?`${Math.floor(e)}KB`:`${e.toFixed(1)}KB`;let n=e/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function g0(t){let e=Buffer.byteLength(t,"utf8"),n=N3(e),r=t.split(`
|
|
1112
|
-
`);if(r.length<=1)return t.length<=80?{content:t,truncated:!1,sizeBytes:e,sizeLabel:n}:{content:t.substring(0,80)+"\u2026",truncated:!0,sizeBytes:e,sizeLabel:n};let{tailCount:o,headCount:s}=p0(),i=r.filter(g=>g.trim()!==""),{head:a,tail:c}=f0(i,s,o),l=a.length+c.length,d=r.length-l,u=[...a,...c];if(t.length<=80)return{content:t,truncated:!1,lineCount:r.length,sizeBytes:e,sizeLabel:n,tailPreview:u,hiddenLineCount:d};let p=r[0]??"",f=p;return p.length>80&&(f=p.substring(0,80)+"\u2026"),{content:f+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:e,sizeLabel:n,tailPreview:u,hiddenLineCount:d}}var h0=h(()=>{"use strict";m0()});function $3(t){let e=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=t.match(e);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],i=parseFloat(r),a=i;o==="KB"?a=i*1024:o==="MB"?a=i*1024*1024:o==="GB"&&(a=i*1024*1024*1024);let c=r;return i%1===0&&(c=String(Math.floor(i))),c+=o,{sizeLabel:c,sizeBytes:Math.round(a),absolutePath:s.trim()}}function U3(t,e){let n={...t.raw??{}};return t.inputTokens!==void 0&&(n.input_tokens=t.inputTokens),t.outputTokens!==void 0&&(n.output_tokens=t.outputTokens),t.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=t.cachedInputTokens),t.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=t.cacheCreationTokens),t.totalTokens!==void 0&&(n.total_tokens=t.totalTokens),t.contextWindowTokens!==void 0&&(n.context_window_tokens=t.contextWindowTokens),{sessionId:e,stopReason:t.stopReason??void 0,resultSubtype:t.resultSubtype,durationMs:t.durationMs,durationApiMs:t.durationApiMs,totalCostUsd:t.totalCostUsd,isError:t.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:t.modelUsage,permissionDenials:t.permissionDenials,errors:t.errors}}function B3(t){let e=t.isError===!0?null:l0(t.toolName,t.content),n=e!==null?{display:e}:{},r=typeof t.batchIndex=="number"&&typeof t.batchSize=="number"?{batchIndex:t.batchIndex,batchSize:t.batchSize}:{},o=t.failureClass?{failureClass:t.failureClass}:{},s=$3(t.content);if(s)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${s.sizeLabel}) \u2192 ${s.absolutePath}`,isError:t.isError===!0,persistedPath:s.absolutePath,sizeBytes:s.sizeBytes,sizeLabel:s.sizeLabel,...n,...r,...o}};let{content:i,lineCount:a,sizeBytes:c,sizeLabel:l,tailPreview:d,hiddenLineCount:u}=g0(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:i,isError:t.isError===!0,sizeBytes:c,sizeLabel:l,...t.truncated===!0&&{truncated:!0},...t.capturePath!==void 0&&{capturePath:t.capturePath},...a!==void 0&&{lineCount:a},...d!==void 0&&d.length>0&&{tailPreview:d},...u!==void 0&&{hiddenLineCount:u},...t.exitCode!==void 0&&{exitCode:t.exitCode},...t.durationMs!==void 0&&{durationMs:t.durationMs},...n,...r,...o}}}function Lb(t,e){switch(t.type){case"session.init":{let n=t.info;return e.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),e.updateSessionIdentity(n.sessionId),e.resolveInitialization(),null}case"session.status":return e.setSessionMetadata(n=>({...n,sessionId:t.sessionId,...t.permissionMode!==void 0?{permissionMode:t.permissionMode}:{permissionMode:n.permissionMode},...t.status!==void 0?{status:t.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:t.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:t.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(t.sessionId&&e.updateSessionIdentity(t.sessionId),t.text){let n={role:"assistant",content:t.text,timestamp:new Date};return e.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:t.toolUseId,toolName:t.toolName,toolInput:t.toolInput,toolInputRaw:t.toolInputRaw,toolInputCapture:t.toolInputCapture,...t.pending?{pending:!0}:{}}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:t.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:t.toolUseIds}}};case"tool.output":return t.isError!==!0&&t.toolName&&(e._successfulToolNames??=[]).push(t.toolName),B3(t);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:t.toolUseId,diff:t.diff}};case"progress":return{type:"progress",progress:{taskId:t.progress.taskId,description:t.progress.description,...t.progress.summary!==void 0?{summary:t.progress.summary}:{},...t.progress.lastToolName!==void 0?{lastToolName:t.progress.lastToolName}:{},totalTokens:t.progress.totalTokens,toolUses:t.progress.toolUses,durationMs:t.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:t.suggestion};case"turn.completed":{let n=U3(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e._successfulToolNames!==void 0&&e._successfulToolNames.length>0&&(n.successfulToolNames=[...e._successfulToolNames]),e.setLastResponseMetadata(n);for(let r=e.conversationHistory.length-1;r>=0;r--){let o=e.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(e.maxBudgetUsd!==void 0&&e.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(e._runningCostUsd=(e._runningCostUsd??0)+n.totalCostUsd,e._runningCostUsd>=e.maxBudgetUsd)){FE(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new _n(e._runningCostUsd,e.maxBudgetUsd);return e.abortBudget(r),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:t.error};case"paused":return{type:"paused",reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:t.hotSwapped,...t.accountId!==void 0?{accountId:t.accountId}:{}};case"stream.retry":return{type:"stream_retry"};case"rate_limit":return{type:"rate_limit",...t.retryAfterMs!==void 0?{retryAfterMs:t.retryAfterMs}:{}};case"notice":return{type:"notice",text:t.text,kind:t.kind};case"tool.activity":return{type:"tool-activity",activeCount:t.activeCount,activeToolUseIds:t.activeToolUseIds};default:return null}}var y0=h(()=>{"use strict";
|
|
1110
|
+
${t}`:e:[{type:"text",text:e},...t]}var Ou,$M=h(()=>{"use strict";Cb();Pb();se();Ou=class{outerIterator;baseConfig;deps;currentModel;currentPermissionMode;currentCwd;currentSystemPrompt;systemPromptOverridden=!1;startupFamily;active;activeModel;closed=!1;shadowHistory;pendingUserText;pendingAssistantText="";lastSessionId;constructor(e,n){this.outerIterator=e.prompt[Symbol.asyncIterator](),this.baseConfig=e.config,this.deps=n,this.currentModel=typeof e.config.model=="string"?e.config.model:void 0,this.currentPermissionMode=e.config.permissionMode,this.currentCwd=e.config.cwd,this.startupFamily=n.providerNameForModel(this.currentModel),this.shadowHistory=[...e.config.resumeHistory??[]]}resolveInner(e){let n=this.deps.resolveProvider(e),r={...this.baseConfig};r.model=e??this.baseConfig.model;let o=n.name===this.startupFamily&&this.baseConfig.apiKey!==void 0?this.baseConfig.apiKey:this.deps.resolveApiKey(e);o!==void 0?r.apiKey=o:delete r.apiKey,Mu(r);let s=[n.name,r.baseUrl??"",r.openaiBaseUrl??"",r.apiKey??"",r.forceChatgptOAuth?"chatgpt-oauth":"",r.forceXaiOAuth?"xai-oauth":"",r.forceXaiApiKey?"xai-apikey":"",r.xaiBaseUrl??""].join("\0");return{provider:n,innerConfig:r,signature:s}}buildInner(e,n){let{provider:r,innerConfig:o,signature:s}=this.resolveInner(e),i=new ns(()=>this.lastSessionId);this.currentPermissionMode!==void 0&&(o.permissionMode=this.currentPermissionMode),this.currentCwd!==void 0&&(o.cwd=this.currentCwd),this.systemPromptOverridden&&(o.systemPrompt=this.currentSystemPrompt),n&&(o.resumeHistory=[...this.shadowHistory]);let a=r.query({prompt:i.createIterable(),config:o});return{family:r.name,signature:s,query:a,iterator:a[Symbol.asyncIterator](),input:i}}async closeActive(){let e=this.active;if(e){this.active=void 0;try{await e.iterator.return?.(void 0)}catch{}try{await e.query.close()}catch{}}}observeEvent(e){e.type==="assistant.message"&&(this.pendingAssistantText+=(this.pendingAssistantText?`
|
|
1111
|
+
`:"")+e.text)}commitShadowTurn(){this.pendingUserText!==void 0&&(this.shadowHistory.push({user:this.pendingUserText,assistant:this.pendingAssistantText}),this.pendingUserText=void 0,this.pendingAssistantText="")}async*[Symbol.asyncIterator](){try{for(this.active=this.buildInner(this.currentModel,!1),this.activeModel=this.currentModel,yield*this.driveUntilInit(!1);!this.closed;){let e=await this.outerIterator.next();if(e.done)break;let n=e.value;this.lastSessionId=n.sessionId;let r=this.currentModel!==this.activeModel,o=!this.active||r&&this.resolveInner(this.currentModel).signature!==this.active.signature,s=this.activeModel,i=this.active?.family;this.activeModel=this.currentModel;let a;if(o&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),O(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),s!==void 0&&s!==this.currentModel&&(a=y3(s,this.currentModel??"(unset)",i,this.active.family)),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=h3(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(a?b3(n.content,a):n.content);;){let c=await this.active.iterator.next();if(c.done){this.closed=!0;break}let l=c.value;if(this.observeEvent(l),yield l,l.type==="turn.completed"){this.commitShadowTurn();break}if(l.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(e){for(;;){let n=await this.active.iterator.next();if(n.done)return yield{type:"error",error:new Error("provider ended before initialization")},this.closed=!0,!0;let r=n.value;if(r.type==="session.init")return e||(yield r),!1;if(r.type==="error")return yield r,this.closed=!0,!0;yield r}}async interrupt(e="interrupted"){await this.active?.query.interrupt(e)}async setModel(e){typeof e=="string"&&e.length>0&&(this.currentModel=e,this.active&&this.resolveInner(e).signature===this.active.signature&&await this.active.query.setModel(e))}async setPermissionMode(e){this.currentPermissionMode=e,await this.active?.query.setPermissionMode(e)}setCwd(e){this.currentCwd=e,this.active?.query.setCwd?.(e)}setSystemPrompt(e){return this.currentSystemPrompt=e,this.systemPromptOverridden=!0,this.active?.query.setSystemPrompt?.(e)??!1}async reauth(){return await this.active?.query.reauth?.()??null}async supportedCommands(){return await this.active?.query.supportedCommands()??[]}async supportedModels(){return await this.active?.query.supportedModels()??[]}async supportedAgents(){return await this.active?.query.supportedAgents()??[]}async getContextUsage(){return await this.active?.query.getContextUsage()??{}}async mcpServerStatus(){return await this.active?.query.mcpServerStatus()??[]}async accountInfo(){return await this.active?.query.accountInfo()??{}}async rewindFiles(e,n){let r=this.active;return r?r.query.rewindFiles(e,n):{canRewind:!1,error:"no active provider"}}async compact(){let e=this.active;return e?.query.compact?e.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}listRewindTargets(){return this.active?.query.listRewindTargets?.()??[]}async rewindConversation(e){let n=this.active;return n?.query.rewindConversation?n.query.rewindConversation(e):{rewound:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...e){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...e)}async close(){this.closed=!0,await this.closeActive()}}});async function Du(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{let a=0,c=l=>{r=setTimeout(()=>{a+=l;let d=0;if(n.extender)try{d=n.extender.onDeadline()}catch{d=0}if(Number.isFinite(d)&&d>0){c(d);return}let u=n.label?` (${n.label})`:"",p="";if(n.extender?.describe)try{let m=n.extender.describe();m!==void 0&&m!==""&&(p=` ${m}`)}catch{}let f=new Ie(`Operation timed out after ${a}ms${u}${p}`,a);n.controller&&!n.controller.signal.aborted&&n.controller.abort(f),i(f)},l)};c(e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}var UM,Mb,Ob=h(()=>{"use strict";ie();UM=0,Mb=5e3});async function Fu(t,e,n){if(!t)return;if(n.kind==="blocked"){await dt(t,{hookEvent:e,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await dt(t,{hookEvent:e,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function BM(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);return await Fu(n.traceWriter,"SessionStart",{kind:"decision",decision:r}),r.injectContext}catch(r){throw r instanceof ee&&await Fu(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function jM(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Fu(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof ee&&await Fu(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof ee||r instanceof nt){O(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}O(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var HM=h(()=>{"use strict";se();ie();J()});var st,rs=h(()=>{"use strict";st="overload_exhausted"});function WM(t){switch(t){case"abort":return w3;case"iteration_cap":return S3;case"timeout":return k3;case"truncated":return v3;default:return null}}var w3,S3,k3,v3,KM=h(()=>{"use strict";w3="Session ended via abort before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state, or re-run the task if the interruption was intentional.",S3="Session hit the tool-use iteration cap before reaching a terminal state. Partial work is preserved in the transcript and witness trace. Resume with `afk --resume <sessionId>` to continue from where it stopped, or re-run with a higher budget (`--max-turns` or `max_tool_use_iterations`).",k3="Session was terminated by the wall-clock timeout before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue, or re-run with a longer timeout. Check the trace for whether the timeout hit during active work or while waiting on a slow tool call.",v3="Session output was truncated by the model provider's output-token ceiling before the response completed. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from where the output was cut off."});function Nu(t){if(t===void 0||!Number.isFinite(t)||t<=0||t<=12e4)return 0;let e=t*.15,n=Math.min(3e5,Math.max(3e4,e));return Math.max(0,Math.floor(t-n))}function $u(t,e,n=Date.now()){return e>0&&n-t>=e}var Ct,Lu,Wn=h(()=>{"use strict";Ct="soft_deadline_wind_down",Lu="Your time budget for this turn is nearly spent. Do not request any more tools \u2014 give your final answer now using only the information already gathered. If your work is incomplete, say briefly what you established, what remains unresolved, and what you would check next."});function Vt(t){return t!=null&&T3.includes(t)}function E3(t){switch(t){case"max_tokens":return'stop_reason "max_tokens"';case"length":return'finish_reason "length"';case"max_output_tokens":return'incomplete_details.reason "max_output_tokens"';default:return"the provider output-token cap"}}function Uu(t,e,n={}){let r=`\u26A0 This turn was cut off at the output-token limit (${E3(e)}) before the model finished \u2014 anything above is partial, not a complete answer.`;if(t.length>0){let o=[...new Set(t)].join(", "),s=n.canIncreaseOutputLimit===!1?"Continue in a follow-up turn or retry so the model can finish the action.":"Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS, then retry.";return`${r} A tool call was truncated mid-request and was NOT dispatched (${o}); that action did not run. ${s}`}return n.canIncreaseOutputLimit===!1?`${r} Continue in a follow-up turn or retry the request.`:`${r} Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS to allow a longer reply.`}var T3,ka=h(()=>{"use strict";T3=["max_tokens","length","max_output_tokens"]});function qM(t){return t.maxTurnsHit?"max_turns_exceeded":t.hookBlocked?"hook_blocked":t.dispatchReason==="error"?"abort":t.abort!==null?t.abort:t.sawProviderError||t.lastStopReason===st?"abort":t.lastStopReason==="tool_use_loop_capped"?"iteration_cap":t.lastStopReason===Ct?"timeout":Vt(t.lastStopReason)?"truncated":"model_end_turn"}var GM=h(()=>{"use strict";rs();Wn();ka()});function _3(t){let e=null,n=t.signal;if(n.aborted&&n.reason!=="closed"){let r=n.reason;r instanceof _n?e="budget_exceeded":r instanceof Ie?e="timeout":typeof r=="string"&&r.startsWith("Budget ")?e="budget_exceeded":typeof r=="string"&&r.includes("timed out")?e="timeout":e="abort"}return qM({dispatchReason:t.dispatchReason,maxTurnsHit:t.maxTurnsHit,hookBlocked:t.hookBlocked,abort:e,lastStopReason:t.lastStopReason,sawProviderError:t.sawProviderError})}function A3(t){if(t.dispatchReason==="error")return"failed";let e=t.signal;return e.aborted&&e.reason!=="closed"?"cancelled":t.sawProviderError||t.lastStopReason===st?"failed":"succeeded"}async function XM(t,e){if(!t)return;let n=_3(e),r={},o=e.runningTokens;o.input>0&&(r.input=o.input),o.output>0&&(r.output=o.output),o.cacheRead>0&&(r.cacheRead=o.cacheRead),o.cacheCreation>0&&(r.cacheCreation=o.cacheCreation);let s=WM(n);await NE(t,{reason:n,finalTurnCount:e.finalTurnCount,finalCostUsd:e.finalCostUsd,finalTokens:r,...e.lastStopReason!==void 0?{lastStopReason:e.lastStopReason}:{},...s!==null?{guidance:s}:{}})}async function zM(t,e){if(!t)return;let n=A3(e),r=e.subagentCompletedCount>0?e.subagentCompletedCount:void 0,o=e.subagentRunningTokens,i=o.input>0||o.output>0||o.cacheRead>0||o.cacheCreation>0?{...o.input>0?{input:o.input}:{},...o.output>0?{output:o.output}:{},...o.cacheRead>0?{cacheRead:o.cacheRead}:{},...o.cacheCreation>0?{cacheCreation:o.cacheCreation}:{}}:void 0,a=e.subagentRunningCostUsd>0?e.subagentRunningCostUsd:void 0;await t.seal({status:n,finalCostUsd:e.finalCostUsd,finalTurnCount:e.finalTurnCount,closedAt:new Date().toISOString(),...r!==void 0?{subagentCount:r}:{},...i!==void 0?{subagentTokens:i}:{},...a!==void 0?{subagentCostUsd:a}:{}})}var JM=h(()=>{"use strict";ie();rs();J();KM();GM()});function Bu(t){let e=x3(t);return e!==void 0?e:R3(t)}function x3(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return VM(n.trim())}function R3(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=I3(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=VM(r);if(o!==void 0)return o}}function I3(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function VM(t){try{return JSON.parse(t)}catch{return}}var Db=h(()=>{"use strict"});var ju,YM=h(()=>{"use strict";F();B();la();ju=class{writer=null;initAttempted=!1;ensure(e){if(this.initAttempted||(this.initAttempted=!0,e.depth!==void 0||e.parentSessionId!==void 0)||k.AFK_SESSION_LEDGER_DISABLED==="1")return;let n=e.sessionId;if(!n)return;let r=new Nn(n);if(!r.active)return;this.writer=r;let o=e.getMetadata();r.record({kind:"meta",sessionId:n,model:o.model??e.fallbackModel,...o.cwd!==void 0?{cwd:o.cwd}:{},traceLabel:ir(e.tracePath)})}recordUser(e){this.writer?.recordUser(e)}recordEvent(e){this.writer?.recordEvent(e)}recordElicitation(e,n){this.writer?.record({kind:"elicitation",reqId:e,request:n})}seal(e){let n=this.writer;return n?(this.writer=null,this.initAttempted=!1,n.close(e)):Promise.resolve()}}});var Hu,QM=h(()=>{"use strict";Hu=class{pendingSeed;prePlanMode;modeBeforeDefault;recordModeTransition(e,n){if(e==="plan"){if(n!=="plan"){let r=n==="default"&&this.modeBeforeDefault!==void 0?this.modeBeforeDefault:n;this.prePlanMode=r==="autonomous"?void 0:r}}else e==="default"?this.modeBeforeDefault=n!=="default"&&n!=="plan"?n:void 0:this.modeBeforeDefault=void 0}clearModeBeforeDefault(){this.modeBeforeDefault=void 0}getPrePlanMode(){return this.prePlanMode}requestImplementSeed(e,n){this.pendingSeed={message:e,mode:n}}takeSeed(){let e=this.pendingSeed;return this.pendingSeed=void 0,e}}});function ZM(t,e,n){t&&(t.aborted?e.abort(t.reason):t.addEventListener("abort",()=>{e.signal.aborted||e.abort(t.reason)},{once:!0})),e.signal.addEventListener("abort",n,{once:!0})}function e0(t,e){let n=t.permissionMode??"default",r=t.persistSession??!0,o={sessionId:t.sessionId,configuredSessionId:t.sessionId,resume:t.resume,resumeSessionAt:t.resumeSessionAt,continue:t.continue,forkSession:t.forkSession,persistSession:r},s={sessionId:t.sessionId,model:e,permissionMode:n};return{sessionIdentity:o,metadata:s}}var t0=h(()=>{"use strict"});var Wu,n0=h(()=>{"use strict";Wu=class{initializationPromise;resolveInitialization;rejectInitialization;initializationSettled=!1;sessionMetadata;sessionIdentity;constructor(e,n){this.sessionIdentity=e,this.sessionMetadata=n,this.initializationPromise=new Promise((r,o)=>{this.resolveInitialization=r,this.rejectInitialization=o})}waitForInitialization(){return this.initializationPromise}getSessionIdentity(){return{...this.sessionIdentity,sessionId:this.getSessionId()}}getSessionMetadata(){return{...this.sessionMetadata,sessionId:this.getSessionId()}}getSessionId(){return this.sessionMetadata.sessionId??this.sessionIdentity.sessionId}updateSessionIdentity(e){e&&(this.sessionIdentity={...this.sessionIdentity,sessionId:e},this.sessionMetadata={...this.sessionMetadata,sessionId:e})}setSessionMetadata(e){this.sessionMetadata=e(this.sessionMetadata)}resolveInitializationIfNeeded(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}resolveInitializationOnce(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}rejectInitializationOnce(e){this.initializationSettled||(this.initializationSettled=!0,this.rejectInitialization(e))}isInitializationSettled(){return this.initializationSettled}}});function r0(t){try{let e=JSON.parse(t);if(!Array.isArray(e))return null;let n=e.length;if(n===0)return"no results";let r=0,o=0;for(let a of e)if(a&&typeof a=="object"){let c=a.type;c==="fact"?r++:c==="procedure"&&o++}let s=`${n} result${n===1?"":"s"}`;if(r+o!==n)return s;let i=[];return r>0&&i.push(`${r} fact${r===1?"":"s"}`),o>0&&i.push(`${o} procedure${o===1?"":"s"}`),i.length===0?s:`${s} (${i.join(", ")})`}catch{return null}}function o0(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;if(n.target==="hot"&&n.saved===!0){if(n.truncated===!0)return"hot memory saved (truncated to fit cap)";let r=n.usage;if(r&&typeof r=="object"){let o=r.pct;if(typeof o=="number")return`hot memory saved (${o}% of cap)`}return"hot memory saved"}if(n.target==="fact"){if(n.action==="remove")return n.removed===!0?"fact removed":"fact not found";if(n.action==="set"&&typeof n.id=="number")return`fact #${n.id} set`;if(n.action==="supersede"&&typeof n.id=="number"&&typeof n.supersedes=="number")return`fact #${n.id} supersedes #${n.supersedes}`}return null}catch{return null}}function s0(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;return typeof n.name=="string"&&n.written===!0?`wrote procedure '${n.name}'`:null}catch{return null}}var i0=h(()=>{"use strict"});function Fb(t){let e=t.trim();if(e.length===0)return null;let n=e[0];if(n!=="{"&&n!=="[")return null;let r=e[e.length-1];if(n==="{"&&r!=="}"||n==="["&&r!=="]")return null;let o;try{o=JSON.parse(e)}catch{return null}return Array.isArray(o)?a0(C3(o)):o!==null&&typeof o=="object"?a0(P3(o)):null}function C3(t){return t.length===0?"[empty array]":t.length===1?"[1 item]":`[${t.length} items]`}function P3(t){let e=Object.keys(t);if(e.length===0)return"{empty object}";let n=e.slice(0,4),r=e.length>4?", \u2026":"";return`{${n.join(", ")}${r}}`}function a0(t){return t.length<=80?t:t.slice(0,79)+"\u2026"}var c0=h(()=>{"use strict"});function l0(t,e){if(!t)return null;let n=M3.get(t);if(!n)return null;try{let r=n(e);if(r===null)return null;let o=Q(r);return o.length>0?o:null}catch{return null}}var M3,d0=h(()=>{"use strict";i0();c0();et();M3=new Map([["memory_search",r0],["memory_update",o0],["procedure_write",s0],["bash",Fb],["Bash",Fb]])});function u0(t,e){if(t===void 0||t.trim()==="")return e;let n=Number(t.trim());return!Number.isInteger(n)||n<O3||n>D3?e:n}function p0(){return{tailCount:u0(k.AFK_BASH_PREVIEW_TAIL_LINES,F3),headCount:u0(k.AFK_BASH_PREVIEW_HEAD_LINES,L3)}}function f0(t,e,n){if(t.length===0)return{head:[],tail:[]};if(e+n>=t.length){let s=t.slice(0,e),i=t.slice(e);return{head:s,tail:i}}let r=e>0?t.slice(0,e):[],o=n>0?t.slice(t.length-n):[];return{head:r,tail:o}}var O3,D3,F3,L3,m0=h(()=>{"use strict";F();O3=0,D3=200,F3=7,L3=0});function N3(t){if(t<1024)return`${t}B`;let e=t/1024;if(e<1024)return e%1===0?`${Math.floor(e)}KB`:`${e.toFixed(1)}KB`;let n=e/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function g0(t){let e=Buffer.byteLength(t,"utf8"),n=N3(e),r=t.split(`
|
|
1112
|
+
`);if(r.length<=1)return t.length<=80?{content:t,truncated:!1,sizeBytes:e,sizeLabel:n}:{content:t.substring(0,80)+"\u2026",truncated:!0,sizeBytes:e,sizeLabel:n};let{tailCount:o,headCount:s}=p0(),i=r.filter(g=>g.trim()!==""),{head:a,tail:c}=f0(i,s,o),l=a.length+c.length,d=r.length-l,u=[...a,...c];if(t.length<=80)return{content:t,truncated:!1,lineCount:r.length,sizeBytes:e,sizeLabel:n,tailPreview:u,hiddenLineCount:d};let p=r[0]??"",f=p;return p.length>80&&(f=p.substring(0,80)+"\u2026"),{content:f+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:e,sizeLabel:n,tailPreview:u,hiddenLineCount:d}}var h0=h(()=>{"use strict";m0()});function $3(t){let e=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=t.match(e);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],i=parseFloat(r),a=i;o==="KB"?a=i*1024:o==="MB"?a=i*1024*1024:o==="GB"&&(a=i*1024*1024*1024);let c=r;return i%1===0&&(c=String(Math.floor(i))),c+=o,{sizeLabel:c,sizeBytes:Math.round(a),absolutePath:s.trim()}}function U3(t,e){let n={...t.raw??{}};return t.inputTokens!==void 0&&(n.input_tokens=t.inputTokens),t.outputTokens!==void 0&&(n.output_tokens=t.outputTokens),t.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=t.cachedInputTokens),t.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=t.cacheCreationTokens),t.totalTokens!==void 0&&(n.total_tokens=t.totalTokens),t.contextWindowTokens!==void 0&&(n.context_window_tokens=t.contextWindowTokens),{sessionId:e,stopReason:t.stopReason??void 0,resultSubtype:t.resultSubtype,durationMs:t.durationMs,durationApiMs:t.durationApiMs,totalCostUsd:t.totalCostUsd,isError:t.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:t.modelUsage,permissionDenials:t.permissionDenials,errors:t.errors}}function B3(t){let e=t.isError===!0?null:l0(t.toolName,t.content),n=e!==null?{display:e}:{},r=typeof t.batchIndex=="number"&&typeof t.batchSize=="number"?{batchIndex:t.batchIndex,batchSize:t.batchSize}:{},o=t.failureClass?{failureClass:t.failureClass}:{},s=$3(t.content);if(s)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${s.sizeLabel}) \u2192 ${s.absolutePath}`,isError:t.isError===!0,persistedPath:s.absolutePath,sizeBytes:s.sizeBytes,sizeLabel:s.sizeLabel,...n,...r,...o}};let{content:i,lineCount:a,sizeBytes:c,sizeLabel:l,tailPreview:d,hiddenLineCount:u}=g0(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:i,isError:t.isError===!0,sizeBytes:c,sizeLabel:l,...t.truncated===!0&&{truncated:!0},...t.capturePath!==void 0&&{capturePath:t.capturePath},...a!==void 0&&{lineCount:a},...d!==void 0&&d.length>0&&{tailPreview:d},...u!==void 0&&{hiddenLineCount:u},...t.exitCode!==void 0&&{exitCode:t.exitCode},...t.durationMs!==void 0&&{durationMs:t.durationMs},...n,...r,...o}}}function Lb(t,e){switch(t.type){case"session.init":{let n=t.info;return e.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),e.updateSessionIdentity(n.sessionId),e.resolveInitialization(),null}case"session.status":return e.setSessionMetadata(n=>({...n,sessionId:t.sessionId,...t.permissionMode!==void 0?{permissionMode:t.permissionMode}:{permissionMode:n.permissionMode},...t.status!==void 0?{status:t.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:t.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:t.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(t.sessionId&&e.updateSessionIdentity(t.sessionId),t.text){let n={role:"assistant",content:t.text,timestamp:new Date};return e.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:t.toolUseId,toolName:t.toolName,toolInput:t.toolInput,toolInputRaw:t.toolInputRaw,toolInputCapture:t.toolInputCapture,...t.pending?{pending:!0}:{}}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:t.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:t.toolUseIds}}};case"tool.output":return t.isError!==!0&&t.toolName&&(e._successfulToolNames??=[]).push(t.toolName),B3(t);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:t.toolUseId,diff:t.diff}};case"progress":return{type:"progress",progress:{taskId:t.progress.taskId,description:t.progress.description,...t.progress.summary!==void 0?{summary:t.progress.summary}:{},...t.progress.lastToolName!==void 0?{lastToolName:t.progress.lastToolName}:{},totalTokens:t.progress.totalTokens,toolUses:t.progress.toolUses,durationMs:t.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:t.suggestion};case"turn.completed":{let n=U3(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e._successfulToolNames!==void 0&&e._successfulToolNames.length>0&&(n.successfulToolNames=[...e._successfulToolNames]),e.setLastResponseMetadata(n);for(let r=e.conversationHistory.length-1;r>=0;r--){let o=e.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(e.maxBudgetUsd!==void 0&&e.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(e._runningCostUsd=(e._runningCostUsd??0)+n.totalCostUsd,e._runningCostUsd>=e.maxBudgetUsd)){FE(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new _n(e._runningCostUsd,e.maxBudgetUsd);return e.abortBudget(r),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:t.error};case"paused":return{type:"paused",reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:t.hotSwapped,...t.accountId!==void 0?{accountId:t.accountId}:{}};case"stream.retry":return{type:"stream_retry"};case"rate_limit":return{type:"rate_limit",...t.retryAfterMs!==void 0?{retryAfterMs:t.retryAfterMs}:{}};case"notice":return{type:"notice",text:t.text,kind:t.kind};case"tool.activity":return{type:"tool-activity",activeCount:t.activeCount,activeToolUseIds:t.activeToolUseIds};default:return null}}var y0=h(()=>{"use strict";ie();J();d0();h0()});import{stat as j3,readFile as H3,writeFile as W3,rename as K3,unlink as q3}from"node:fs/promises";async function S0(t,{maxBytes:e,keepTailLines:n}){let r={trimmed:!1,removedLines:0},o;try{if((await j3(t)).size<=e)return r;let a=(await H3(t,"utf8")).split(`
|
|
1113
1113
|
`);if(a.length>0&&a[a.length-1]===""&&a.pop(),a.length<=n)return r;let c=a.slice(a.length-n),l=a.length-c.length;return o=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,8)}`,await W3(o,c.join(`
|
|
1114
1114
|
`)+`
|
|
1115
1115
|
`,{mode:384}),await K3(o,t),o=void 0,{trimmed:!0,removedLines:l}}catch{if(o!==void 0)try{await q3(o)}catch{}return r}}var b0,w0,k0=h(()=>{"use strict";b0=5*1024*1024,w0=5e3});import{readdir as $b,stat as Nb,rm as E0,writeFile as G3}from"node:fs/promises";import{join as va}from"node:path";async function V3(t){try{let n=(await $b(t.root,{withFileTypes:!0})).filter(a=>a.isDirectory()&&a.name!==t.activeLabel),r=[];for(let a of n){let c=va(t.root,a.name);try{r.push({label:a.name,path:c,...await x0(c)})}catch{}}r.sort((a,c)=>a.newestMtimeMs-c.newestMtimeMs);let o=r.filter(a=>t.now-a.newestMtimeMs>=_0),s=r.reduce((a,c)=>a+c.bytes,0),i=new Set;for(let a of o)t.now-a.newestMtimeMs>t.maxAgeMs&&i.add(a.label);for(let a of o){if(s<=t.maxBytes)break;if(i.has(a.label)){s-=a.bytes;continue}i.add(a.label),s-=a.bytes}for(let a of r)if(i.has(a.label))try{await E0(a.path,{recursive:!0,force:!0})}catch{}}catch{}}function T0(t,e){let n=Number.parseFloat(t??"");return Number.isFinite(n)&&n>0?n:e}async function x0(t){let e=0,n=0,r=async o=>{let s=await $b(o,{withFileTypes:!0});for(let i of s){let a=va(o,i.name);if(i.isDirectory()){await r(a);continue}try{let c=await Nb(a);n+=c.size,c.mtimeMs>e&&(e=c.mtimeMs)}catch{}}};if(await r(t),e===0)try{e=(await Nb(t)).mtimeMs}catch{e=Date.now()}return{newestMtimeMs:e,bytes:n}}async function Y3(t,e){try{let n=await Nb(va(t,A0));return e-n.mtimeMs<J3}catch{return!1}}async function R0(t={}){if(k.AFK_WITNESS_RETENTION_DISABLE==="1")return v0();let e=t.root??go(),n=Date.now();try{if(t.force!==!0&&await Y3(e,n))return v0();let r=T0(t.maxAgeDays?.toString()??k.AFK_WITNESS_MAX_AGE_DAYS,X3)*24*60*60*1e3,o=T0(t.maxBytes?.toString()??k.AFK_WITNESS_MAX_BYTES,z3),i=(await $b(e,{withFileTypes:!0})).filter(p=>p.isDirectory()&&p.name!==t.activeLabel),a=[];for(let p of i){let f=va(e,p.name);try{a.push({label:p.name,path:f,...await x0(f)})}catch{}}a.sort((p,f)=>p.newestMtimeMs-f.newestMtimeMs);let c=a.filter(p=>n-p.newestMtimeMs>=_0),l=a.reduce((p,f)=>p+f.bytes,0),d=new Set;for(let p of c)n-p.newestMtimeMs>r&&d.add(p.label);for(let p of c){if(l<=o)break;if(d.has(p.label)){l-=p.bytes;continue}d.add(p.label),l-=p.bytes}let u={skipped:!1,scanned:a.length,evicted:0,freedBytes:0,evictedLabels:[]};for(let p of a)if(d.has(p.label))try{await E0(p.path,{recursive:!0,force:!0}),u.evicted+=1,u.freedBytes+=p.bytes,u.evictedLabels.push(p.label)}catch{}try{await G3(va(e,A0),`${new Date(n).toISOString()}
|
|
1116
1116
|
`,{mode:384})}catch{}return kT(),V3({root:Fm(),activeLabel:t.activeLabel,maxAgeMs:r,maxBytes:o,now:n}),u}catch{return{skipped:!1,scanned:0,evicted:0,freedBytes:0,evictedLabels:[]}}}var X3,z3,_0,J3,A0,v0,I0,C0=h(()=>{"use strict";F();B();Qm();X3=30,z3=2*1024*1024*1024,_0=3600*1e3,J3=360*60*1e3,A0=".last-sweep";v0=()=>({skipped:!0,scanned:0,evicted:0,freedBytes:0,evictedLabels:[]});I0=5e3});import{readdir as Q3,readFile as Z3,stat as Ku,unlink as eQ,writeFile as tQ,access as nQ}from"node:fs/promises";import{join as Ub}from"node:path";function M0(t,e){let n=Number.parseFloat(t??"");return Number.isFinite(n)&&n>0?n:e}async function aQ(t,e){try{let n=await Ku(Ub(t,D0));return e-n.mtimeMs<rQ}catch{return!1}}async function cQ(t){try{return await nQ(t),!0}catch{return!1}}async function L0(t){if(k.AFK_SESSION_RETENTION_DISABLE==="1")return O0("disabled");let e=t?.root??ce(),n=Date.now();try{if(t?.force!==!0&&await aQ(e,n))return O0("stamp");if(!await cQ(e))return{skipped:!1,evictedAge:0,evictedCount:0,remaining:0};let r=M0(k.AFK_SESSION_MAX_AGE_DAYS,oQ),o=M0(k.AFK_SESSION_MAX_COUNT,sQ),s=r*iQ,i=await Q3(e,{withFileTypes:!0}),a=[];for(let y of i){if(!y.isFile()||!y.name.endsWith(".json")||t?.activeSessionId!==void 0&&y.name===`${t.activeSessionId}.json`)continue;let b=Ub(e,y.name),w,v;try{let _=await Z3(b,"utf8"),x=JSON.parse(_);v=(await Ku(b)).mtimeMs,x!==null&&typeof x=="object"&&"savedAt"in x&&typeof x.savedAt=="number"?w=x.savedAt:w=v}catch{try{let _=await Ku(b);w=_.mtimeMs,v=_.mtimeMs}catch{continue}}a.push({name:y.name,path:b,ageMs:Math.max(0,n-w),savedAtMs:w,mtimeMs:v})}let c=a.filter(y=>y.ageMs>=P0);c.sort((y,b)=>y.savedAtMs-b.savedAtMs);let l=0,d=0,u=new Map;for(let y of c)y.ageMs>s&&(u.set(y.path,"age"),l+=1);let p=a.filter(y=>!u.has(y.path));if(p.length>o){let y=p.filter(w=>w.ageMs>=P0);y.sort((w,v)=>w.savedAtMs-v.savedAtMs);let b=p.length;for(let w of y){if(b<=o)break;u.has(w.path)||(u.set(w.path,"count"),d+=1,b-=1)}}let f=t?._unlink??eQ,m=0;for(let[y,b]of u)try{let w=a.find(v=>v.path===y);if(w!==void 0&&(await Ku(y)).mtimeMs!==w.mtimeMs){b==="age"?l-=1:d-=1;continue}await f(y),m+=1}catch{b==="age"?l-=1:d-=1}let g=a.length-m;try{await tQ(Ub(e,D0),`${new Date(n).toISOString()}
|
|
1117
|
-
`,{mode:384})}catch{}return{skipped:!1,evictedAge:l,evictedCount:d,remaining:g}}catch{return{skipped:!1,evictedAge:0,evictedCount:0,remaining:0}}}var rQ,P0,D0,oQ,sQ,iQ,F0,O0,N0=h(()=>{"use strict";B();F();rQ=360*60*1e3,P0=3600*1e3,D0=".last-sweep-sidecars",oQ=30,sQ=1e3,iQ=1440*60*1e3,F0=5e3;O0=t=>({skipped:!0,reason:t,evictedAge:0,evictedCount:0,remaining:0})});import{z as lQ}from"zod";var Yr,$0=h(()=>{"use strict";
|
|
1117
|
+
`,{mode:384})}catch{}return{skipped:!1,evictedAge:l,evictedCount:d,remaining:g}}catch{return{skipped:!1,evictedAge:0,evictedCount:0,remaining:0}}}var rQ,P0,D0,oQ,sQ,iQ,F0,O0,N0=h(()=>{"use strict";B();F();rQ=360*60*1e3,P0=3600*1e3,D0=".last-sweep-sidecars",oQ=30,sQ=1e3,iQ=1440*60*1e3,F0=5e3;O0=t=>({skipped:!0,reason:t,evictedAge:0,evictedCount:0,remaining:0})});import{z as lQ}from"zod";var Yr,$0=h(()=>{"use strict";se();Ib();LM();ie();NM();J();fe();$M();be();Ob();Cn();HM();ie();JM();Db();Cb();YM();QM();lt();ur();Ar();Fe();Pb();t0();n0();y0();B();k0();C0();N0();Yr=class{ownedTraceWriter;config;planExit=new Hu;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;inboundMessageCount=0;subagentOutputRecorder;pendingFrameworkContext=[];lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;ownsTraceSeal;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=new ju;outputBroadcast=new Pu;constructor(e,n){this.ownsTraceSeal=n!==void 0&&e.traceWriter===n,this.ownedTraceWriter=this.ownsTraceSeal?n:void 0,this.config=e.parentSessionId===void 0&&e.planExitControls===void 0?{...e,planExitControls:{setPermissionMode:o=>this.setPermissionMode(o),requestImplementSeed:(o,s)=>this.planExit.requestImplementSeed(o,s),getPrePlanMode:()=>this.planExit.getPrePlanMode()}}:e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,ZM(e.abortSignal,this.abortController,()=>{this.onAbort()});let r=String(e.model);q(e.traceWriter,{phase:"session_init_start",model:r,resolvedModel:Ee(e.model)??r,origin:wn(e.surface),actor:rl(e.parentSessionId)}),this.initSdkLifecycle(),this.config.parentSessionId===void 0&&(S0(qc(),{maxBytes:b0,keepTailLines:w0}),setTimeout(()=>{R0({activeLabel:ir(this.config.traceWriter?.getTracePath())??void 0})},I0).unref(),setTimeout(()=>{L0({activeSessionId:this.sessionId})},F0).unref())}initSdkLifecycle(){this.config.models&&_l(this.config.models),Mu(this.config);let e=Ee(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=e0(this.config,e);this.stateManager=new Wu(n,r),this.inputStream=new ns(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)O(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{O("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>U0(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new Ou({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>z(a),resolveApiKey:a=>re(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0,this.pendingFrameworkContext=[];let s=this.providerQuery;this.providerIterator=s[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{let e=await BM(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId,parentSessionId:this.config.parentSessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});for(e&&this.config.parentSessionId===void 0&&this.queueFrameworkContext(e);;){let n=await this.providerIterator.next();if(n.done){this.stateManager.resolveInitializationIfNeeded();return}let r=n.value,o=Lb(r,this.buildTransformDeps());if(r.type==="session.init"){await q(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(o&&o.type==="error"){this.sawProviderError=!0;return}}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof ee&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{_successfulToolNames:[],conversationHistory:this.conversationHistory,getSessionMetadata:()=>this.stateManager.getSessionMetadata(),setSessionMetadata:e=>this.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>this.stateManager.updateSessionIdentity(e),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:e=>{this.lastResponseMetadata=e,typeof e.totalCostUsd=="number"&&Number.isFinite(e.totalCostUsd)&&(this.sessionRunningCostUsd+=e.totalCostUsd);let n=e.usage;if(n&&typeof n=="object"){let r=n,o=(s,i)=>{let a=r[s];typeof a=="number"&&Number.isFinite(a)&&(this.sessionRunningTokens[i]+=a)};o("input_tokens","input"),o("output_tokens","output"),o("cache_read_input_tokens","cacheRead"),o("cache_creation_input_tokens","cacheCreation")}typeof e.stopReason=="string"&&(this.lastStopReason=e.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:e=>{this.abortController.signal.aborted||this.abortController.abort(e)},...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}}}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get cwd(){return this.config.cwd}get abortSignal(){return this.abortController.signal}get hookRegistry(){return this._hookRegistry}abort(e){if(e==="closed"||e.startsWith("Budget ")||e.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${e}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(e)}async sendMessage(e,n={}){this.assertCanSend();let r=this.config.timeoutMs??UM,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(e)){if(a.type==="chunk"&&a.chunk.type==="content"&&(i+=a.chunk.content),a.type==="message"&&a.message.role==="assistant"&&(s=a.message),a.type==="error")throw a.error;if(a.type==="done"){if(s)return{...s,metadata:a.metadata};if(i)return{role:"assistant",content:i,metadata:a.metadata,timestamp:new Date}}}if(s)return s;if(i)return{role:"assistant",content:i,timestamp:new Date};throw new Error("No assistant response received")};try{return await Du(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async sendMessageStructured(e,n,r={}){let{maxRetries:o=2,injectSchemaPrompt:s=!0,...i}=r,a=s?"\n\nRespond with ONLY a JSON object (optionally in a ```json fence) that conforms to this JSON Schema:\n```json\n"+JSON.stringify(lQ.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",c="";for(let l=0;l<=o;l++){let d=l===0?e+a:`Your previous response did not match the required JSON schema.
|
|
1118
1118
|
Validation error: ${c}
|
|
1119
|
-
Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,u=await this.sendMessage(d,i),p=Bu(u.content),f=n.safeParse(p);if(f.success)return f.data;c=f.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${c}`)}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(e)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(e){this.initPromise&&await this.initPromise,this.planExit.clearModeBeforeDefault();let n=this.withPendingFrameworkContext(e),r=typeof n=="string"?n:this.summarizeContentBlocks(n),o={role:"user",content:r,timestamp:new Date};this.conversationHistory.push(o),this.inputStream.pushUserMessage(n),this.ensureLedger(),this.ledger.recordUser(r);let s=++this.inboundMessageCount;PM({sessionId:ir(this.config.traceWriter?.getTracePath())??this.sessionId,subagentId:this.config.subagentId,isSubagentFork:this.config.isSubagentFork===!0,model:this.config.model===void 0?void 0:String(this.config.model),turn:s,prompt:r});let i=this.buildTransformDeps();this.subagentOutputRecorder===void 0&&(this.subagentOutputRecorder=FM({sessionId:ir(this.config.traceWriter?.getTracePath())??this.sessionId,subagentId:this.config.subagentId,isSubagentFork:this.config.isSubagentFork===!0,model:this.config.model===void 0?void 0:String(this.config.model)}));let a=this.subagentOutputRecorder;try{for(;;){let c=await this.providerIterator.next();if(c.done)break;let l=c.value,d=Lb(l,i);if(d&&(a?.observe(d),d.type==="done"?(this.turnCount++,this.sawProviderError=!1):d.type==="error"&&(this.sawProviderError=!0),this.ledger.recordEvent(d),this.outputBroadcast.push(d),yield d,d.type==="done"||d.type==="error"))break}a?.end("stream_complete")}finally{this.currentState==="streaming"&&(a?.end("aborted_or_incomplete"),this.currentState="idle")}}ensureLedger(){this.ledger.ensure({depth:this.config.depth,parentSessionId:this.config.parentSessionId,sessionId:this.sessionId,fallbackModel:String(this.config.model),tracePath:this.config.traceWriter?.getTracePath(),getMetadata:()=>this.getSessionMetadata()})}recordLedgerElicitation(e,n){this.ledger.recordElicitation(e,n)}summarizeContentBlocks(e){let n=[],r=0;for(let s of e)s.type==="text"?n.push(s.text):s.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}setBeforeNextRound(e){this.providerQuery.setBeforeNextRound?.(e)}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new nt("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.ledger.seal("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(e=>setTimeout(e,Mb))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;try{this.initSdkLifecycle()}catch(e){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async onAbort(){this.ledger.seal("abort");try{await this.providerQuery.interrupt(Cg(this.abortController.signal.reason))}catch{}}async setModel(e){let n=Ee(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){let n=this.stateManager.getSessionMetadata().permissionMode;this.planExit.recordModeTransition(e,n),await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(r=>({...r,permissionMode:e})),this.pushSidebandEvent({type:"plan_mode",mode:e==="plan"?"plan":"default"})}getPrePlanMode(){return this.planExit.getPrePlanMode()}setPlanExitQueueCheck(e){this.config.planExitControls&&(this.config.planExitControls.hasPendingUserMessage=e)}async takePendingPlanExitSeed(){let e=this.planExit.takeSeed();if(e!==void 0){try{await this.setPermissionMode(e.mode)}catch(n){
|
|
1119
|
+
Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,u=await this.sendMessage(d,i),p=Bu(u.content),f=n.safeParse(p);if(f.success)return f.data;c=f.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${c}`)}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(e)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(e){this.initPromise&&await this.initPromise,this.planExit.clearModeBeforeDefault();let n=this.withPendingFrameworkContext(e),r=typeof n=="string"?n:this.summarizeContentBlocks(n),o={role:"user",content:r,timestamp:new Date};this.conversationHistory.push(o),this.inputStream.pushUserMessage(n),this.ensureLedger(),this.ledger.recordUser(r);let s=++this.inboundMessageCount;PM({sessionId:ir(this.config.traceWriter?.getTracePath())??this.sessionId,subagentId:this.config.subagentId,isSubagentFork:this.config.isSubagentFork===!0,model:this.config.model===void 0?void 0:String(this.config.model),turn:s,prompt:r});let i=this.buildTransformDeps();this.subagentOutputRecorder===void 0&&(this.subagentOutputRecorder=FM({sessionId:ir(this.config.traceWriter?.getTracePath())??this.sessionId,subagentId:this.config.subagentId,isSubagentFork:this.config.isSubagentFork===!0,model:this.config.model===void 0?void 0:String(this.config.model)}));let a=this.subagentOutputRecorder;try{for(;;){let c=await this.providerIterator.next();if(c.done)break;let l=c.value,d=Lb(l,i);if(d&&(a?.observe(d),d.type==="done"?(this.turnCount++,this.sawProviderError=!1):d.type==="error"&&(this.sawProviderError=!0),this.ledger.recordEvent(d),this.outputBroadcast.push(d),yield d,d.type==="done"||d.type==="error"))break}a?.end("stream_complete")}finally{this.currentState==="streaming"&&(a?.end("aborted_or_incomplete"),this.currentState="idle")}}ensureLedger(){this.ledger.ensure({depth:this.config.depth,parentSessionId:this.config.parentSessionId,sessionId:this.sessionId,fallbackModel:String(this.config.model),tracePath:this.config.traceWriter?.getTracePath(),getMetadata:()=>this.getSessionMetadata()})}recordLedgerElicitation(e,n){this.ledger.recordElicitation(e,n)}summarizeContentBlocks(e){let n=[],r=0;for(let s of e)s.type==="text"?n.push(s.text):s.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}setBeforeNextRound(e){this.providerQuery.setBeforeNextRound?.(e)}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new nt("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.ledger.seal("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(e=>setTimeout(e,Mb))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;try{this.initSdkLifecycle()}catch(e){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async onAbort(){this.ledger.seal("abort");try{await this.providerQuery.interrupt(Cg(this.abortController.signal.reason))}catch{}}async setModel(e){let n=Ee(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){let n=this.stateManager.getSessionMetadata().permissionMode;this.planExit.recordModeTransition(e,n),await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(r=>({...r,permissionMode:e})),this.pushSidebandEvent({type:"plan_mode",mode:e==="plan"?"plan":"default"})}getPrePlanMode(){return this.planExit.getPrePlanMode()}setPlanExitQueueCheck(e){this.config.planExitControls&&(this.config.planExitControls.hasPendingUserMessage=e)}async takePendingPlanExitSeed(){let e=this.planExit.takeSeed();if(e!==void 0){try{await this.setPermissionMode(e.mode)}catch(n){O(`\u26A0\uFE0F AgentSession: deferred plan-exit mode flip to '${e.mode}' rejected; dropping implement-seed (staying in plan mode): ${n instanceof Error?n.message:String(n)}`);return}return{message:e.message,mode:e.mode}}}setSystemPrompt(e){return this.config={...this.config,systemPrompt:e},this.providerQuery.setSystemPrompt?.(e)??!1}setCwd(e){this.config={...this.config,cwd:e},this.providerQuery.setCwd?.(e),this.config.sessionId!==void 0&&S_(this.config.sessionId,e)}async reauth(){return await this.providerQuery.reauth?.()??null}waitForInitialization(){return this.stateManager.waitForInitialization()}getSessionIdentity(){return this.stateManager.getSessionIdentity()}getSessionMetadata(){return this.stateManager.getSessionMetadata()}getQuery(){return this.providerQuery}supportedCommands(){return this.providerQuery.supportedCommands()}supportedModels(){return this.providerQuery.supportedModels()}supportedAgents(){return this.providerQuery.supportedAgents()}getContextUsage(){return this.providerQuery.getContextUsage()}mcpServerStatus(){return this.providerQuery.mcpServerStatus()}accountInfo(){return this.providerQuery.accountInfo()}rewindFiles(e,n){return this.providerQuery.rewindFiles(e,n)}async compact(){if(this.currentState==="closed")throw new Error("Cannot compact: session is closed");if(this.currentState!=="idle")return{compacted:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let e=this.providerQuery.compact?.bind(this.providerQuery);if(!e)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await e()}finally{this.currentState="idle"}}listRewindTargets(){return this.currentState==="closed"?[]:this.providerQuery.listRewindTargets?.()??[]}async rewindConversation(e){if(this.currentState==="closed")throw new Error("Cannot rewind: session is closed");if(this.currentState!=="idle")return{rewound:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let n=this.providerQuery.rewindConversation?.bind(this.providerQuery);return n?n(e):{rewound:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){return this.outputBroadcast.subscribe()}queueFrameworkContext(e){let n=e.trim();n.length!==0&&(this.pendingFrameworkContext.push(n),O(`AgentSession: queued framework context (${n.length} chars) for the next user message`))}withPendingFrameworkContext(e){if(this.pendingFrameworkContext.length===0)return e;let n=this.pendingFrameworkContext.join(`
|
|
1120
1120
|
|
|
1121
1121
|
`);return this.pendingFrameworkContext=[],typeof e=="string"?`${n}
|
|
1122
1122
|
|
|
1123
1123
|
${e}`:[{type:"text",text:n},...e]}getInputStreamRef(){return{pushUserMessage:e=>this.inputStream.pushUserMessage(e),queueFrameworkContext:e=>this.queueFrameworkContext(e)}}getHistory(){return[...this.conversationHistory]}getTurnCount(){return this.turnCount}async close(){if(this.currentState!=="closed"){this.currentState="closed",this.outputBroadcast.close(),await this.ledger.seal("close"),this.abortController.signal.aborted||this.abortController.abort("closed"),this.stateManager.resolveInitializationIfNeeded();try{await this.providerQuery.close()}catch{}if(await this.providerIterator.return?.(),this.initPromise)try{await Promise.race([this.initPromise,new Promise(e=>setTimeout(e,Mb))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){if(this.sessionEndDispatched)return;this.sessionEndDispatched=!0,this.config.drainSubagents!==void 0&&await this.config.drainSubagents(e).catch(()=>{});let n=this.closureSignals(e);await XM(this.config.traceWriter,{...n,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,runningTokens:this.sessionRunningTokens}).catch(()=>{}),this.ownsTraceSeal&&await zM(this.ownedTraceWriter,{...n,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,subagentCompletedCount:this.subagentCompletedCount,subagentRunningTokens:this.subagentRunningTokens,subagentRunningCostUsd:this.subagentRunningCostUsd}).catch(()=>{}),await jM(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:e,parentSessionId:this.config.parentSessionId,...this.config.traceWriter?{tracePath:this.config.traceWriter.getTracePath()}:{}},this.config.traceWriter&&!this.ownsTraceSeal?{traceWriter:this.config.traceWriter}:{})}closureSignals(e){return{dispatchReason:e,signal:this.abortController.signal,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError}}recordSubagentCompletion(e,n){if(this.subagentCompletedCount++,e){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(e.inputTokens,"input"),r(e.outputTokens,"output"),r(e.cacheReadTokens,"cacheRead"),r(e.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}pushSidebandEvent(e){this.currentState!=="closed"&&(this.ledger.recordEvent(e),this.outputBroadcast.push(e))}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new nt("Cannot send message: session aborted");if(this.currentState==="processing"||this.currentState==="streaming"||this.currentState==="compacting")throw new Error("Cannot send message: session is busy");if(this.config.maxTurns&&this.turnCount>=this.config.maxTurns)throw this.maxTurnsHit=!0,new Error(`Maximum turns (${this.config.maxTurns}) exceeded`)}}});var Bb=h(()=>{"use strict";$0()});import{AsyncLocalStorage as dQ}from"node:async_hooks";function j0(t,e){return B0.run(t,e)}function Pt(){return B0.getStore()}var B0,Qr=h(()=>{"use strict";B0=new dQ});import{randomUUID as uQ}from"node:crypto";import{promises as Ta}from"node:fs";import{join as pQ,resolve as fQ,sep as Hb}from"node:path";function os(t){let e=fQ(t),n=e.indexOf(jb);if(n===-1)return;let o=e.slice(n+jb.length).split(Hb)[0];if(o)return e.slice(0,n+jb.length)+o}async function Wb(t,e){let n=os(t);if(n===void 0||e?.()===!0)return;let r=pQ(n,mQ),o=`${r}.${process.pid}.${uQ()}.tmp`;try{let s={};try{s=JSON.parse(await Ta.readFile(r,"utf-8"))}catch{s={owner:"agent"}}if(s.pid=process.pid,s.createdAt=new Date().toISOString(),await Ta.writeFile(o,JSON.stringify(s,null,2),"utf-8"),e?.()===!0){await Ta.rm(o,{force:!0}).catch(()=>{});return}await Ta.rename(o,r)}catch{await Ta.rm(o,{force:!0}).catch(()=>{})}}function H0(t,e=gQ){let n,r=!1,o=()=>{r=!0,n!==void 0&&(clearInterval(n),n=void 0)};return os(t)===void 0||(n=setInterval(()=>{Wb(t,()=>r)},e),n.unref()),o}var mQ,jb,gQ,Kb=h(()=>{"use strict";mQ=".afk-worktree-meta.json",jb=`${Hb}.afk-worktrees${Hb}`,gQ=6e5});import{execFile as hQ}from"node:child_process";import{promisify as yQ}from"node:util";import Kn from"node:path";function SQ(t){let e=Kn.resolve(t),n=`${Kn.sep}.afk-worktrees${Kn.sep}`,r=e.indexOf(n);if(!(r<=0))return e.slice(0,r)}async function W0(t,e=wQ){if(!(t===void 0||t===""))try{let{stdout:n}=await e("git",["-C",t,"rev-parse","--git-common-dir","--show-toplevel"]),r=n.split(`
|
|
1124
|
-
`).map(l=>l.trim()),o=r[0],s=r[1];if(!o||!s)return;let i=Kn.isAbsolute(o)?o:Kn.resolve(t,o),a=Kn.resolve(Kn.dirname(i)),c=Kn.resolve(s);return a===c?void 0:a}catch(n){let r=SQ(t);if(r!==void 0)return
|
|
1124
|
+
`).map(l=>l.trim()),o=r[0],s=r[1];if(!o||!s)return;let i=Kn.isAbsolute(o)?o:Kn.resolve(t,o),a=Kn.resolve(Kn.dirname(i)),c=Kn.resolve(s);return a===c?void 0:a}catch(n){let r=SQ(t);if(r!==void 0)return O(`[worktree-read-root] git rev-parse failed for cwd=${t}; recovered main root lexically as ${r} (afk worktree layout) \u2014 ${n instanceof Error?n.message:String(n)}`),r;O(`[worktree-read-root] git rev-parse failed for cwd=${t}; child confined to worktree only \u2014 ${n instanceof Error?n.message:String(n)}`);return}}var bQ,wQ,K0=h(()=>{"use strict";se();bQ=yQ(hQ),wQ=(t,e)=>bQ(t,e)});import qn from"path";function kQ(t){let e=qn.resolve(t??process.cwd());return qn.parse(e).root||qn.sep}function Gn(t,e){if(t!==void 0)return Ea({parentReadRoots:t.parentReadRoots,parentCwd:t.parentCwd,childCwd:e})}function Ea(t){let{parentReadRoots:e,parentCwd:n,childCwd:r,worktreeMainRoot:o,afkStateRoot:s,afkFrameworkRoot:i}=t,a=r!==void 0&&r!==""?qn.resolve(r):void 0;if(e===void 0&&n===void 0)return a!==void 0?[kQ(a)]:void 0;let c=e??(n!==void 0?[n]:[]),l=new Set;a!==void 0&&l.add(a);for(let d of c)d!==void 0&&d!==""&&l.add(qn.resolve(d));if(o!==void 0&&o!==""&&l.add(qn.resolve(o)),s!==void 0&&s!==""&&l.add(qn.resolve(s)),i!==void 0&&i!==""&&l.add(qn.resolve(i)),l.size!==0&&!(l.size===1&&a!==void 0&&l.has(a)))return[...l]}var Zr=h(()=>{"use strict"});import vQ from"path";async function q0(t){let{parentReadRoots:e,parentCwd:n,effectiveChildCwd:r,callerReadRoots:o,callerExtraReadRoots:s,resolveMainRoot:i}=t;if(o!==void 0)return;let a=e===void 0&&n===void 0,c;!a&&r!==void 0&&(c=await i(r),c===void 0&&n!==void 0&&n!==r&&(c=await i(n)));let l=Ea({parentReadRoots:e,parentCwd:n,childCwd:r,worktreeMainRoot:c,...a?{}:{afkStateRoot:te()},...a?{}:{afkFrameworkRoot:vt()}});if(s!==void 0&&s.length>0&&(l!==void 0||r!==void 0)){let u=l??(r!==void 0?[r]:[]);l=[...new Set([...u,...s.map(p=>vQ.resolve(p))])]}return l}function G0(t,e){if(t===void 0||t.length===0)return;let n=e!==void 0?[e]:[];return[...new Set([...n,...t])]}var X0=h(()=>{"use strict";Zr();B()});function z0(t){if(t.phaseRole!==void 0&&t.phaseRole!=="read-write"&&t.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${t.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`)}var J0=h(()=>{"use strict"});function qu(t){return t?V0:xQ}function Gu(t){return t?CQ:IQ}function Xu(t){return t?RQ:""}var V0,TQ,EQ,_Q,AQ,xQ,RQ,IQ,CQ,qb=h(()=>{"use strict";V0=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1125
1125
|
|
|
1126
1126
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1127
1127
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|
|
@@ -1204,11 +1204,11 @@ ${o}`:o}function jQ(t){let e=t.systemPrompt;if(e!==void 0){if(typeof e=="string"
|
|
|
1204
1204
|
`)});function yw(t){return t!=="autonomous"?null:{type:"text",text:pp}}var pp,bw=h(()=>{"use strict";pp=["## AFK mode is active","","The operator is away from keyboard. Your channel to them is Telegram via the `send_telegram` tool \u2014 not this transcript, which no one is watching live. At the end of each turn, push your terminal state (Done / Blocked / Asking) to Telegram so the operator can review asynchronously.","","Posture \u2014 bounded autonomy, not unchecked action:"," - Proceed autonomously on reversible work. Do not stop to confirm actions you are already authorized to take and can undo (edits, reads, tests, local commits, non-force pushes, installs)."," - At a one-way door \u2014 anything irreversible, externally visible, credential- or payment-touching, or where multiple readings lead to materially different work \u2014 do NOT guess. Push a concise Asking summary to Telegram naming the decision and your recommended default, then stop and end the turn in the Asking state."," - A mechanical gate refuses high-risk and irreversible operations at the hook layer regardless of this text. Treat a gate refusal as a signal to surface the decision to the operator, not an obstacle to work around.","","Communication discipline:"," - Batch updates. Send a Telegram message at terminal state (and at a genuinely blocking fork), not a play-by-play \u2014 the operator gets a push notification for every message."," - Keep pushes short and scannable: what happened, what changed, what (if anything) you need. Never paste raw tool output, logs, secrets, or full file contents into a push.","","Exit: the operator returns and runs `/afk off` (or Shift+Tab) to restore default permissions and terminal-channel interaction."].join(`
|
|
1205
1205
|
`)});function Vn(t,e){if(!e||typeof e!="object")return"";let n=e;if(t==="skill"||t==="Skill"){let i=n.name;return typeof i=="string"&&i.length>0?`(${i.length>60?i.slice(0,59)+"\u2026":i})`:""}let r=n.file_path??n.path??n.filePath;if(typeof r=="string")return" "+r;let o=n.command??n.cmd;if(typeof o=="string"){let i=qe(o.replace(/\\\r?\n/g," ").replace(/\s+/g," ").trim());return" "+(i.length>$O?i.slice(0,$O-1)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}var $O,$a=h(()=>{"use strict";vn();$O=160});function fp(t){if(!t||typeof t!="object")return;let e=t,n={};for(let r of m9){let o=e[r];o!==void 0&&(n[r]=typeof o=="string"&&o.length>UO?o.slice(0,UO):o)}return Object.keys(n).length>0?JSON.stringify(n):void 0}function mp(t){if(!t||typeof t!="object")return;let e=t;if(Object.keys(e).length===0)return;let n={};for(let[r,o]of Object.entries(e))if(typeof o=="string"){let s=o.length>BO?o.slice(0,BO):o;n[r]=qe(s)}else o!=null&&typeof o!="object"&&(n[r]=o);return Object.keys(n).length>0?JSON.stringify(n):void 0}var m9,UO,BO,ww=h(()=>{"use strict";vn();m9=["file_path","name","id_prefix"],UO=4096,BO=8192});import{createHash as Sw}from"crypto";function gp(t){let{toolUseId:e,name:n,input:r,subagentId:o}=t,s=r??{},i=JSON.stringify(s),a=JSON.stringify(g9(n,s)),c=h9(n,s);return{phase:"started",toolUseId:e,name:n,inputBytes:Buffer.byteLength(i,"utf8"),argsFingerprint:Sw("sha256").update(a).digest("hex"),...c!==void 0?{resourceFingerprint:c}:{},...o!==void 0?{subagentId:o}:{}}}function g9(t,e){if(typeof e!="object"||e===null)return e;let n=e;switch(t){case"browser_act":return n.action==="fill"&&"value"in n?{...n,value:"[REDACTED]"}:e;case"config_set":return n.target==="env"&&"value"in n?{...n,value:"[REDACTED]"}:e;default:return e}}function h9(t,e){if(typeof e!="object"||e===null)return;let n=e;switch(t){case"read_file":case"list_directory":{let r=n.file_path??n.path;if(typeof r!="string"||r.length===0)return;let o=r.trim().replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/,"");return Sw("sha256").update(o).digest("hex")}case"grep":{let r=n.path;if(typeof r!="string"||r.length===0)return;let o=r.trim().replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/,""),s=n.include,i=typeof s=="string"&&s.length>0?`${o}\0${s}`:o;return Sw("sha256").update(i).digest("hex")}default:return}}function hp(t){let{toolUseId:e,name:n,result:r,truncated:o,durationMs:s,subagentId:i}=t;return{phase:"completed",toolUseId:e,name:n,resultBytes:Buffer.byteLength(r.content,"utf8"),isError:r.isError===!0,truncated:o,durationMs:s,...r.incomplete===!0?{incomplete:!0}:{},...r.incompleteReason?{incompleteReason:r.incompleteReason}:{},...r.circuitBreaker===!0?{circuitBreaker:!0}:{},...r.failureClass?{failureClass:r.failureClass}:{},...typeof r.batchIndex=="number"&&typeof r.batchSize=="number"?{batchIndex:r.batchIndex,batchSize:r.batchSize}:{},...i!==void 0?{subagentId:i}:{},...r.testResult!==void 0?{testResult:r.testResult}:{}}}var yp=h(()=>{"use strict"});async function*bp(t){let e=[],n=!1,r=null,o=()=>{let l=r;r=null,l?.()},a=t(l=>{n||(e.push(l),o())}).finally(()=>{n=!0,o()}).then(l=>({ok:!0,value:l}),l=>({ok:!1,error:l}));for(;;){for(;e.length>0;)yield e.shift();if(n)break;await new Promise(l=>{r=l})}let c=await a;if(!c.ok)throw c.error;return c.value}var kw=h(()=>{"use strict"});import{randomUUID as y9}from"node:crypto";async function*jO({state:t,signal:e,vision:n,toolDispatcher:r,traceWriter:o,priorTurns:s,sessionId:i,subagentId:a}){if(!r)return void 0;let c=Ra(t);for(let m of c)m.id.length===0&&(m.id=y9());let{calls:l,parseErrors:d}=pO(c,e),u=new Map;for(let m of l){let g=Date.now();u.set(m.id,g),Sr(o,gp({toolUseId:m.id,name:m.name,input:m.input,subagentId:a})),yield{type:"tool.use.start",toolUseId:m.id,toolName:m.name,toolInput:Vn(m.name,m.input),toolInputRaw:fp(m.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT&&or(k.AFK_CAPTURE_SUBAGENT_OUTPUT)?mp(m.input):void 0,sessionId:i}}let p=[];if(e.aborted){let m=Ne(e);for(let g of l){let y={content:"Tool call aborted",isError:!0,failureClass:m};p.push({call:g,result:y}),yield{type:"tool.output",toolUseId:g.id,toolName:g.name,content:y.content,isError:!0,failureClass:m,sessionId:i}}}else{let m;try{if(r.executeBatch)m=yield*bp(g=>r.executeBatch(l,y=>{g({type:"tool.activity",activeCount:y.length,activeToolUseIds:[...y],sessionId:i})}));else{m=[];for(let g of l){if(e.aborted){m.push({content:"Tool call aborted",isError:!0,failureClass:Ne(e)});continue}try{m.push(await r.execute(g))}catch(y){let b=y instanceof Error?y.message:String(y);m.push({content:`Tool execution threw: ${b}`,isError:!0})}}}}catch(g){let y=g instanceof Error?g.message:String(g);m=l.map(()=>({content:`Tool batch execution failed: ${y}`,isError:!0}))}for(let g=0;g<l.length;g++){let y=l[g],b=m[g],w=d.get(y.id);w!==void 0&&(b={content:`${w}
|
|
1206
1206
|
--
|
|
1207
|
-
${b.content}`,isError:!0,...b.truncated===!0?{truncated:!0}:{}}),p.push({call:y,result:b});let v=u.get(y.id),_=typeof v=="number"?Date.now()-v:0,x=b.truncated===!0||b.content.includes("[output truncated");Sr(o,hp({toolUseId:y.id,name:y.name,result:b,truncated:x,durationMs:_,subagentId:a})),yield{type:"tool.output",toolUseId:y.id,toolName:y.name,content:b.content,...b.isError===!0?{isError:!0}:{},...b.truncated===!0?{truncated:!0}:{},...b.capturePath!==void 0?{capturePath:b.capturePath}:{},...b.incomplete===!0?{incomplete:!0}:{},...b.incompleteReason?{incompleteReason:b.incompleteReason}:{},...typeof b.batchIndex=="number"&&typeof b.batchSize=="number"?{batchIndex:b.batchIndex,batchSize:b.batchSize}:{},...b.failureClass?{failureClass:b.failureClass}:{},durationMs:b.durationMs!==void 0?b.durationMs:_,...b.exitCode!==void 0?{exitCode:b.exitCode}:{},sessionId:i},b.render?.diff&&(yield{type:"tool.diff",toolUseId:y.id,diff:b.render.diff,sessionId:i})}}s.push(fO(t.assistantText,c,t.reasoningText));for(let m of mO(p))s.push(m);for(let{result:m}of p)m.harnessUserMessage?.kind==="queued_user_message"&&s.push({role:"user",content:m.harnessUserMessage.text});let f=gO(p,{vision:n});return f&&s.push(f),p.find(m=>m.result.failureClass===Fo)?.result}var HO=h(()=>{"use strict";Cn();J();ww();F();Fi();$a();yp();kw();Ia();ew()});function Sp(t){return t!==void 0&&t>0?Math.floor(t):0}function kp(t,e){return e>0&&t>=e}function vp(t,e){return e>0?`round ${t}/${e}`:`round ${t}`}var Mt,wp,ms=h(()=>{"use strict";Mt="tool_use_loop_capped",wp="You have reached your tool-use budget for this turn. Do not request any more tools \u2014 give your final answer now using only the information already gathered."});function WO(t,e,n,r){try{return Si(_e(t??{}),Fa(e,n),Tt(e),r),null}catch(o){return o instanceof Error?o:new Error(String(o))}}var KO=h(()=>{"use strict";Po();Bt();La()});function qO(t){let e=t.get("retry-after");if(e==null)return;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(e);if(!Number.isNaN(r)){let o=r-Date.now();if(o>=0)return o}}function GO(t=fetch,e,n,r){return!e&&!n&&!r?t:async(o,s)=>{if(r){let a=Tu(s),c=s?.signal instanceof AbortSignal?s.signal:void 0;await r.acquirePermit(a,c)}let i=await t(o,s);if(n)try{n(i.headers)}catch{}if(r&&i.status===429)try{let a=qO(i.headers);r.freeze(a??5e3)}catch{}if(e&&b9.has(i.status))try{let a=qO(i.headers);e({status:i.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}return i}}var b9,XO=h(()=>{"use strict";ya();b9=new Set([429,503,529])});import w9 from"openai";function k9(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),t.defaultHeaders!==void 0&&(e.defaultHeaders=t.defaultHeaders),t.fetch!==void 0&&(e.fetch=t.fetch),new w9(e)}function zO(){return S9??k9}function E9(t){if(!t)return!1;let e;try{e=new URL(t).hostname}catch{return!1}return v9.has(e)||e.startsWith("127.")?!0:T9.some(n=>e===n.slice(1)||e.endsWith(n))}function JO(t){if(E9(t))return;let e=n=>{let r=uM(n);r!==void 0&&es.update(r)};return GO(globalThis.fetch,void 0,e,es)}var S9,v9,T9,vw=h(()=>{"use strict";ya();Sb();XO();S9=null;v9=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","chatgpt.com"]),T9=[".chatgpt.com"]});async function*Tw(t,e){let n=0;for(;;){let r=Qu(),o=Date.now(),s,i=null;for(let d=0;;d++)try{s=await e.createStream(t.controller.signal);break}catch(u){if(t.controller.signal.aborted)return null;if(lp(u)&&d<LO){let p=mw(u),f=p??fw(d);if(q(t.traceWriter,{phase:"rate_limit",durationMs:f,resolvedModel:t.currentModel,metadata:{source:"connection",reason:p!==void 0?"retry-after":"backoff",attempt:d}}),await We(f,t.controller.signal),t.controller.signal.aborted)return null;continue}i=u;break}if(i!==null)return yield{type:"error",error:e.clarifyError(i)},null;let a=null,c=!1;try{for await(let d of ps(s,t.controller.signal)){if(t.isClosed())return null;for(let u of e.translate(d,r))c||(c=!0,q(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-o,resolvedModel:t.currentModel})),yield u}}catch(d){if(t.controller.signal.aborted)return null;if(dp(d)&&n<NO){n++,yield{type:"stream.retry",sessionId:t.initSessionId};let u=mw(d),p=u??fw(n-1);if(q(t.traceWriter,{phase:"rate_limit",durationMs:p,resolvedModel:t.currentModel,metadata:{source:"stream",reason:u!==void 0?"retry-after":"backoff",attempt:n}}),await We(p,t.controller.signal),t.controller.signal.aborted)return null;continue}a=d}if(a!==null)return yield{type:"error",error:e.clarifyError(a)},null;if(t.controller.signal.aborted)return null;let l=dO(r)&&r.toolCallsByIndex.size>0;return r.finishReason===null&&r.assistantText.length===0&&!l?(yield{type:"error",error:new ct("the model stream ended without a finish_reason and without a dispatchable response (no visible answer text and no complete tool call): the response was empty or cut off before any usable content arrived. The turn is incomplete.")},null):{state:r,events:[],text:r.assistantText,needsToolDispatch:l}}}var VO=h(()=>{"use strict";J();ip();Bn();Ia();se();fs()});function YO(t){if(t instanceof Na||lp(t)||dp(t))return!1;let e=Jn(t);return e!==void 0&&_9.has(e)}var _9,QO=h(()=>{"use strict";fs();cp();_9=new Set([400,404,405,415,422,501])});import{randomUUID as x9}from"node:crypto";function ZO(t,e,n={}){let r=zn(t.apiKey,n.authDeps,t.forceChatgptOAuth??!1),o=n.sessionIdOverride??t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=Ee(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.defaultHeaders!==void 0&&(a.defaultHeaders=n.defaultHeaders),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.onPermissionMode!==void 0&&(a.onPermissionMode=n.onPermissionMode),n.onCwdChange!==void 0&&(a.onCwdChange=n.onCwdChange),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),t.traceWriter!==void 0&&(a.traceWriter=t.traceWriter),new Tp(a)}var Ew,Tp,_w=h(()=>{"use strict";J();Mo();Gb();Bt();lt();Xb();ka();zb();ie();xa();oO();yr();Ia();ew();nw();tp();F();Yu();Po();ow();se();Da();AO();cp();fs();hw();bw();zr();$a();HO();ms();Wn();La();KO();vw();VO();pw();fs();vw();La();QO();Ew="openai-compatible",Tp=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;onCwdChange;openAITools;wireMode;useOpenAIPricing;traceWriter;priorTurns=[];currentModel;currentPermissionMode;responsesCompactionUnavailable=!1;abort=new cs;closed=!1;lastUsage=null;autoCompactThreshold;constructor(e){if(this.opts=e,this.initSessionId=e.synthesizedSessionId,this.currentModel=e.model,this.currentPermissionMode=uw(e.config.permissionMode),this.toolDispatcher=e.toolDispatcher,this.onPermissionMode=e.onPermissionMode,this.onCwdChange=e.onCwdChange,this.traceWriter=e.traceWriter,this.autoCompactThreshold=ki(e.config.autoCompact,e.model),this.toolDispatcher){let s=this.toolDispatcher;Array.isArray(s.toolDefs)&&s.toolDefs.length>0&&(this.openAITools=uO(s.toolDefs))}let n=(e.useResponsesApi??!1)||yO(k.AFK_OPENAI_USE_RESPONSES),r=bO(e.auth,n);this.wireMode=r.mode,this.useOpenAIPricing=r.baseURL===void 0&&e.baseURL===void 0||Qb(e.model)&&e.config.forceXaiOAuth!==!0;let o=e.config.resumeHistory?.at(-1);if(o?.inputTokens!==void 0&&o.inputTokens>0&&(this.lastUsage={inputTokens:o.inputTokens,stopReason:null,resultSubtype:"success",isError:!1}),e.auth.apiKey===null)this.client=null;else{let s=zO(),i={apiKey:e.auth.apiKey},a=r.baseURL??e.baseURL;a!==void 0&&(i.baseURL=a),r.headers!==void 0?i.defaultHeaders=r.headers:e.defaultHeaders!==void 0&&(i.defaultHeaders=e.defaultHeaders);let c=JO(a);c!==void 0&&(i.fetch=c),this.client=s(i)}}activeOpenAITools(){if(!this.openAITools)return;if(this.currentPermissionMode==="plan")return this.openAITools;let e=this.openAITools.filter(n=>n.function.name!==yt);return e.length>0?e:void 0}async*[Symbol.asyncIterator](){if(yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:this.openAITools?this.openAITools.map(r=>r.function.name):[],slashCommands:[],skills:[],plugins:[],mcpServers:this.opts.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.opts.auth.source,version:Ew}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(Jb(this.opts.auth))};return}let n=this.opts.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r===rw)break;let o=r;if(o.done)break;if(yield*this.runTurn(o.value.content),this.autoCompactThreshold!==void 0&&!this.closed){let s=this.lastUsage,i=sn(this.currentModel);if(s!==null&&i>0){let a=_e(s);if(bi(a,i,this.autoCompactThreshold))try{await this.opts.config.hookRegistry?.dispatch({event:"PreCompact",sessionId:this.initSessionId,trigger:"auto"}),(await this.compactHistory("token_threshold")).compacted&&(this.lastUsage=null)}catch(c){if(!(c instanceof ee))throw c}}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(e){let n=this.abort.begin();if(n.signal.aborted)return;let r=Date.now(),o=x9(),s=new ss(n.signal,this.traceWriter,"openai-compatible");try{yield*this._runTurnInner(e,n,r,o)}finally{s.finish(Date.now()-r)}}async*_runTurnInner(e,n,r,o){let s=Al(this.currentModel),i=WO(this.lastUsage,this.currentModel,this.opts.config.maxOutputTokens,this.opts.config.model??this.currentModel);if(i){this.abort.clear(n),yield{type:"error",error:i};return}this.priorTurns.push({role:"user",content:nO(e,{vision:s,model:this.currentModel})});let a={stopReason:null,resultSubtype:"success",isError:!1},c="",l="",d=Sp(this.opts.config.maxToolUseIterations),u=this.opts.config.softDeadlineMs??0,p=null,f=0,m=0,g=[];for(;;){if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let b=yield*this.runIteration(n,s,p);if(b===null){this.abort.clear(n),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(a,r));return}let w=lO(b.state,this.useOpenAIPricing?this.currentModel:void 0);if(a=_a(a,w),a.contextWindowTokens=(w.inputTokens??0)+(w.outputTokens??0),this.lastUsage=a,b.text.length>0&&(c=b.text),l=b.state.reasoningText,!b.needsToolDispatch){Vt(b.state.finishReason)&&(g=Ra(b.state).map(A=>A.name));break}if(p!==null)break;let v=yield*this.dispatchAndAppend(b.state,n.signal,s);if(v){this.abort.clear(n),yield{type:"error",error:new _o(v.content)};return}f+=1;{let A=Ra(b.state);m+=A.length;let I=A.at(-1),C=I?.name,T;try{T=I?JSON.parse(I.argumentsRaw||"{}"):void 0}catch{T=void 0}let R=I?`${I.name}${Vn(I.name,T)}`:"unknown";yield{type:"progress",progress:{taskId:o,description:"Working",summary:`${vp(f,d)}: ${R}`,lastToolName:C,totalTokens:a.totalTokens??0,toolUses:m,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let _=kp(f,d),x=$u(r,u);if(_||x){p=_?Mt:Ct;continue}}if(this.abort.clear(n),c.length>0){let b={role:"assistant",content:c};l.length>0&&(b.reasoning_content=l),this.priorTurns.push(b)}let y=Vt(a.stopReason)?Uu(g,a.stopReason,{canIncreaseOutputLimit:!(this.opts.auth.source==="chatgpt-oauth"&&a.stopReason==="max_output_tokens")}):null;c.length>0?yield{type:"assistant.message",text:y?`${c}
|
|
1207
|
+
${b.content}`,isError:!0,...b.truncated===!0?{truncated:!0}:{}}),p.push({call:y,result:b});let v=u.get(y.id),_=typeof v=="number"?Date.now()-v:0,x=b.truncated===!0||b.content.includes("[output truncated");Sr(o,hp({toolUseId:y.id,name:y.name,result:b,truncated:x,durationMs:_,subagentId:a})),yield{type:"tool.output",toolUseId:y.id,toolName:y.name,content:b.content,...b.isError===!0?{isError:!0}:{},...b.truncated===!0?{truncated:!0}:{},...b.capturePath!==void 0?{capturePath:b.capturePath}:{},...b.incomplete===!0?{incomplete:!0}:{},...b.incompleteReason?{incompleteReason:b.incompleteReason}:{},...typeof b.batchIndex=="number"&&typeof b.batchSize=="number"?{batchIndex:b.batchIndex,batchSize:b.batchSize}:{},...b.failureClass?{failureClass:b.failureClass}:{},durationMs:b.durationMs!==void 0?b.durationMs:_,...b.exitCode!==void 0?{exitCode:b.exitCode}:{},sessionId:i},b.render?.diff&&(yield{type:"tool.diff",toolUseId:y.id,diff:b.render.diff,sessionId:i})}}s.push(fO(t.assistantText,c,t.reasoningText));for(let m of mO(p))s.push(m);for(let{result:m}of p)m.harnessUserMessage?.kind==="queued_user_message"&&s.push({role:"user",content:m.harnessUserMessage.text});let f=gO(p,{vision:n});return f&&s.push(f),p.find(m=>m.result.failureClass===Fo)?.result}var HO=h(()=>{"use strict";Cn();J();ww();F();Fi();$a();yp();kw();Ia();ew()});function Sp(t){return t!==void 0&&t>0?Math.floor(t):0}function kp(t,e){return e>0&&t>=e}function vp(t,e){return e>0?`round ${t}/${e}`:`round ${t}`}var Mt,wp,ms=h(()=>{"use strict";Mt="tool_use_loop_capped",wp="You have reached your tool-use budget for this turn. Do not request any more tools \u2014 give your final answer now using only the information already gathered."});function WO(t,e,n,r){try{return Si(_e(t??{}),Fa(e,n),Tt(e),r),null}catch(o){return o instanceof Error?o:new Error(String(o))}}var KO=h(()=>{"use strict";Po();Bt();La()});function qO(t){let e=t.get("retry-after");if(e==null)return;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(e);if(!Number.isNaN(r)){let o=r-Date.now();if(o>=0)return o}}function GO(t=fetch,e,n,r){return!e&&!n&&!r?t:async(o,s)=>{if(r){let a=Tu(s),c=s?.signal instanceof AbortSignal?s.signal:void 0;await r.acquirePermit(a,c)}let i=await t(o,s);if(n)try{n(i.headers)}catch{}if(r&&i.status===429)try{let a=qO(i.headers);r.freeze(a??5e3)}catch{}if(e&&b9.has(i.status))try{let a=qO(i.headers);e({status:i.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}return i}}var b9,XO=h(()=>{"use strict";ya();b9=new Set([429,503,529])});import w9 from"openai";function k9(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),t.defaultHeaders!==void 0&&(e.defaultHeaders=t.defaultHeaders),t.fetch!==void 0&&(e.fetch=t.fetch),new w9(e)}function zO(){return S9??k9}function E9(t){if(!t)return!1;let e;try{e=new URL(t).hostname}catch{return!1}return v9.has(e)||e.startsWith("127.")?!0:T9.some(n=>e===n.slice(1)||e.endsWith(n))}function JO(t){if(E9(t))return;let e=n=>{let r=uM(n);r!==void 0&&es.update(r)};return GO(globalThis.fetch,void 0,e,es)}var S9,v9,T9,vw=h(()=>{"use strict";ya();Sb();XO();S9=null;v9=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","chatgpt.com"]),T9=[".chatgpt.com"]});async function*Tw(t,e){let n=0;for(;;){let r=Qu(),o=Date.now(),s,i=null;for(let d=0;;d++)try{s=await e.createStream(t.controller.signal);break}catch(u){if(t.controller.signal.aborted)return null;if(lp(u)&&d<LO){let p=mw(u),f=p??fw(d);if(q(t.traceWriter,{phase:"rate_limit",durationMs:f,resolvedModel:t.currentModel,metadata:{source:"connection",reason:p!==void 0?"retry-after":"backoff",attempt:d}}),await We(f,t.controller.signal),t.controller.signal.aborted)return null;continue}i=u;break}if(i!==null)return yield{type:"error",error:e.clarifyError(i)},null;let a=null,c=!1;try{for await(let d of ps(s,t.controller.signal)){if(t.isClosed())return null;for(let u of e.translate(d,r))c||(c=!0,q(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-o,resolvedModel:t.currentModel})),yield u}}catch(d){if(t.controller.signal.aborted)return null;if(dp(d)&&n<NO){n++,yield{type:"stream.retry",sessionId:t.initSessionId};let u=mw(d),p=u??fw(n-1);if(q(t.traceWriter,{phase:"rate_limit",durationMs:p,resolvedModel:t.currentModel,metadata:{source:"stream",reason:u!==void 0?"retry-after":"backoff",attempt:n}}),await We(p,t.controller.signal),t.controller.signal.aborted)return null;continue}a=d}if(a!==null)return yield{type:"error",error:e.clarifyError(a)},null;if(t.controller.signal.aborted)return null;let l=dO(r)&&r.toolCallsByIndex.size>0;return r.finishReason===null&&r.assistantText.length===0&&!l?(yield{type:"error",error:new ct("the model stream ended without a finish_reason and without a dispatchable response (no visible answer text and no complete tool call): the response was empty or cut off before any usable content arrived. The turn is incomplete.")},null):{state:r,events:[],text:r.assistantText,needsToolDispatch:l}}}var VO=h(()=>{"use strict";J();ip();Bn();Ia();ie();fs()});function YO(t){if(t instanceof Na||lp(t)||dp(t))return!1;let e=Jn(t);return e!==void 0&&_9.has(e)}var _9,QO=h(()=>{"use strict";fs();cp();_9=new Set([400,404,405,415,422,501])});import{randomUUID as x9}from"node:crypto";function ZO(t,e,n={}){let r=zn(t.apiKey,n.authDeps,t.forceChatgptOAuth??!1),o=n.sessionIdOverride??t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=Ee(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.defaultHeaders!==void 0&&(a.defaultHeaders=n.defaultHeaders),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.onPermissionMode!==void 0&&(a.onPermissionMode=n.onPermissionMode),n.onCwdChange!==void 0&&(a.onCwdChange=n.onCwdChange),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),t.traceWriter!==void 0&&(a.traceWriter=t.traceWriter),new Tp(a)}var Ew,Tp,_w=h(()=>{"use strict";J();Mo();Gb();Bt();lt();Xb();ka();zb();se();xa();oO();yr();Ia();ew();nw();tp();F();Yu();Po();ow();ie();Da();AO();cp();fs();hw();bw();zr();$a();HO();ms();Wn();La();KO();vw();VO();pw();fs();vw();La();QO();Ew="openai-compatible",Tp=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;onCwdChange;openAITools;wireMode;useOpenAIPricing;traceWriter;priorTurns=[];currentModel;currentPermissionMode;responsesCompactionUnavailable=!1;abort=new cs;closed=!1;lastUsage=null;autoCompactThreshold;constructor(e){if(this.opts=e,this.initSessionId=e.synthesizedSessionId,this.currentModel=e.model,this.currentPermissionMode=uw(e.config.permissionMode),this.toolDispatcher=e.toolDispatcher,this.onPermissionMode=e.onPermissionMode,this.onCwdChange=e.onCwdChange,this.traceWriter=e.traceWriter,this.autoCompactThreshold=ki(e.config.autoCompact,e.model),this.toolDispatcher){let s=this.toolDispatcher;Array.isArray(s.toolDefs)&&s.toolDefs.length>0&&(this.openAITools=uO(s.toolDefs))}let n=(e.useResponsesApi??!1)||yO(k.AFK_OPENAI_USE_RESPONSES),r=bO(e.auth,n);this.wireMode=r.mode,this.useOpenAIPricing=r.baseURL===void 0&&e.baseURL===void 0||Qb(e.model)&&e.config.forceXaiOAuth!==!0;let o=e.config.resumeHistory?.at(-1);if(o?.inputTokens!==void 0&&o.inputTokens>0&&(this.lastUsage={inputTokens:o.inputTokens,stopReason:null,resultSubtype:"success",isError:!1}),e.auth.apiKey===null)this.client=null;else{let s=zO(),i={apiKey:e.auth.apiKey},a=r.baseURL??e.baseURL;a!==void 0&&(i.baseURL=a),r.headers!==void 0?i.defaultHeaders=r.headers:e.defaultHeaders!==void 0&&(i.defaultHeaders=e.defaultHeaders);let c=JO(a);c!==void 0&&(i.fetch=c),this.client=s(i)}}activeOpenAITools(){if(!this.openAITools)return;if(this.currentPermissionMode==="plan")return this.openAITools;let e=this.openAITools.filter(n=>n.function.name!==yt);return e.length>0?e:void 0}async*[Symbol.asyncIterator](){if(yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:this.openAITools?this.openAITools.map(r=>r.function.name):[],slashCommands:[],skills:[],plugins:[],mcpServers:this.opts.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.opts.auth.source,version:Ew}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(Jb(this.opts.auth))};return}let n=this.opts.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r===rw)break;let o=r;if(o.done)break;if(yield*this.runTurn(o.value.content),this.autoCompactThreshold!==void 0&&!this.closed){let s=this.lastUsage,i=sn(this.currentModel);if(s!==null&&i>0){let a=_e(s);if(bi(a,i,this.autoCompactThreshold))try{await this.opts.config.hookRegistry?.dispatch({event:"PreCompact",sessionId:this.initSessionId,trigger:"auto"}),(await this.compactHistory("token_threshold")).compacted&&(this.lastUsage=null)}catch(c){if(!(c instanceof ee))throw c}}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(e){let n=this.abort.begin();if(n.signal.aborted)return;let r=Date.now(),o=x9(),s=new ss(n.signal,this.traceWriter,"openai-compatible");try{yield*this._runTurnInner(e,n,r,o)}finally{s.finish(Date.now()-r)}}async*_runTurnInner(e,n,r,o){let s=Al(this.currentModel),i=WO(this.lastUsage,this.currentModel,this.opts.config.maxOutputTokens,this.opts.config.model??this.currentModel);if(i){this.abort.clear(n),yield{type:"error",error:i};return}this.priorTurns.push({role:"user",content:nO(e,{vision:s,model:this.currentModel})});let a={stopReason:null,resultSubtype:"success",isError:!1},c="",l="",d=Sp(this.opts.config.maxToolUseIterations),u=this.opts.config.softDeadlineMs??0,p=null,f=0,m=0,g=[];for(;;){if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let b=yield*this.runIteration(n,s,p);if(b===null){this.abort.clear(n),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(a,r));return}let w=lO(b.state,this.useOpenAIPricing?this.currentModel:void 0);if(a=_a(a,w),a.contextWindowTokens=(w.inputTokens??0)+(w.outputTokens??0),this.lastUsage=a,b.text.length>0&&(c=b.text),l=b.state.reasoningText,!b.needsToolDispatch){Vt(b.state.finishReason)&&(g=Ra(b.state).map(A=>A.name));break}if(p!==null)break;let v=yield*this.dispatchAndAppend(b.state,n.signal,s);if(v){this.abort.clear(n),yield{type:"error",error:new _o(v.content)};return}f+=1;{let A=Ra(b.state);m+=A.length;let I=A.at(-1),C=I?.name,T;try{T=I?JSON.parse(I.argumentsRaw||"{}"):void 0}catch{T=void 0}let R=I?`${I.name}${Vn(I.name,T)}`:"unknown";yield{type:"progress",progress:{taskId:o,description:"Working",summary:`${vp(f,d)}: ${R}`,lastToolName:C,totalTokens:a.totalTokens??0,toolUses:m,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let _=kp(f,d),x=$u(r,u);if(_||x){p=_?Mt:Ct;continue}}if(this.abort.clear(n),c.length>0){let b={role:"assistant",content:c};l.length>0&&(b.reasoning_content=l),this.priorTurns.push(b)}let y=Vt(a.stopReason)?Uu(g,a.stopReason,{canIncreaseOutputLimit:!(this.opts.auth.source==="chatgpt-oauth"&&a.stopReason==="max_output_tokens")}):null;c.length>0?yield{type:"assistant.message",text:y?`${c}
|
|
1208
1208
|
|
|
1209
1209
|
${y}`:c,sessionId:this.initSessionId}:(yield{type:"assistant.message",text:c,sessionId:this.initSessionId},y!==null&&(yield{type:"notice",text:y,kind:"truncation",sessionId:this.initSessionId})),yield*this.finishTurn(p!==null?{...a,stopReason:p}:a,r)}*finishTurn(e,n){this.lastUsage=e,yield{type:"turn.completed",usage:{...e,durationMs:Date.now()-n},sessionId:this.initSessionId}}clarifyResponsesError(e,n){let r=e instanceof Error?e:new Error(String(e));if(!n||(e&&typeof e=="object"&&"status"in e?e.status:void 0)!==400&&!/\b400\b/.test(r.message))return r;let s,i=e?.error;if(i&&typeof i=="object"){let a=i;typeof a.detail=="string"?s=a.detail:typeof a.message=="string"&&(s=a.message)}return new Error(`ChatGPT/Codex backend rejected model "${this.currentModel}" (HTTP 400). A ChatGPT subscription only serves certain OpenAI models on this backend (gpt-5.6 and gpt-5.5 work; gpt-5, gpt-5.1, gpt-5.2 and *-codex do not). `+(s?`Backend said: ${s}`:"No error body was returned."))}async*runIteration(e,n,r=null){let o=rO({config:this.opts.config,...this.opts.config.resumeHistory!==void 0?{resumeHistory:this.opts.config.resumeHistory}:{},priorTurns:this.priorTurns,vision:n});if(o[0]?.role==="system"){let a=this.currentPermissionMode==="plan"?up:this.currentPermissionMode==="autonomous"?pp:null;a!==null&&(o[0]={...o[0],content:o[0].content+`
|
|
1210
1210
|
|
|
1211
|
-
`+a})}if(r!==null){let a=r===Mt?wp:Lu;o.push({role:"user",content:a})}let s=r!==null?void 0:this.activeOpenAITools(),i={controller:e,traceWriter:this.traceWriter,initSessionId:this.initSessionId,currentModel:this.currentModel,isClosed:()=>this.closed};if(this.wireMode==="responses"){let a=this.opts.auth.source==="chatgpt-oauth";if(a&&ep(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"); for an auto-dispatched agent you can't pass a model to (e.g. git-investigator), set AFK_DEFAULT_SUBAGENT_MODEL to a gpt-5.x id. Or run it on a provider configured with the matching API key.`)},null;let c=sp({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,temperature:this.opts.config.temperature,isChatGptBackend:a});return yield*Tw(i,{createStream:async l=>await this.client.responses.create(c,{signal:l}),translate:(l,d)=>Zu(l,d,this.initSessionId),clarifyError:l=>this.clarifyResponsesError(l,a)})}else{let a=MO({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,temperature:this.opts.config.temperature});return yield*Tw(i,{createStream:async c=>await this.client.chat.completions.create(a,{signal:c}),translate:(c,l)=>cO(c,l,this.initSessionId),clarifyError:c=>c instanceof Error?c:new Error(String(c))})}}async*dispatchAndAppend(e,n,r){return yield*jO({state:e,signal:n,vision:r,toolDispatcher:this.toolDispatcher,traceWriter:this.traceWriter,priorTurns:this.priorTurns,sessionId:this.initSessionId,subagentId:this.opts.config.subagentId})}async interrupt(e="interrupted"){this.abort.requestAbort(e)}async compact(){let e=await this.compactHistory("manual");return e.compacted&&(this.lastUsage=null),e}async compactHistory(e){let n=this.priorTurns.length;if(this.opts.auth.apiKey===null)return{compacted:!1,reason:"no-usable-auth",messagesBefore:n,messagesAfter:n};if(this.wireMode==="responses"&&this.responsesCompactionUnavailable){let s=us(k.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,k.AFK_MICROCOMPACT_KEEP_LAST),{blocksCleared:i,bytesReclaimed:a}=dw(this.priorTurns,s);return i>0?{compacted:!1,reason:"microcompacted",messagesBefore:n,messagesAfter:this.priorTurns.length,microcompaction:{blocksCleared:i,bytesReclaimed:a}}:{compacted:!1,reason:"responses-compaction-unavailable",messagesBefore:n,messagesAfter:n}}let r=k.AFK_COMPACT_MODEL??this.currentModel,o=wi(_e(this.lastUsage??{}),sn(this.currentModel));return _O({priorTurns:this.priorTurns,usedFraction:o,shrinkAtFraction:EO(),summarize:(s,i)=>this.wireMode==="responses"?this.summarizeViaResponses(s,i,r):ap({client:this.client,model:r,system:Ca,user:Oa(s),maxTokens:1024,signal:i}),isClosed:this.closed,isIdle:this.abort.isIdle(),beginAbort:()=>this.abort.begin(),clearAbort:s=>this.abort.clear(s),trigger:e,traceWriter:this.traceWriter})}async summarizeViaResponses(e,n,r){try{return await DO({client:this.client,model:r,system:Ca,user:Oa(e),isChatGptBackend:this.opts.auth.source==="chatgpt-oauth",maxTokens:1024,signal:n})}catch(o){if(!n.aborted&&YO(o)){this.responsesCompactionUnavailable=!0;let s=Jn(o);q(this.traceWriter,{phase:"compaction_disabled",metadata:{wire:"responses",reason:"responses-compaction-unavailable",error:o instanceof Error?o.message:String(o),...s!==void 0?{status:s}:{}}})}throw o}}async setModel(e){e!==void 0&&(this.currentModel=Ee(e)??e)}async setPermissionMode(e){this.currentPermissionMode=uw(e);let n=Et(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e),this.onCwdChange?.(e)}async supportedCommands(){return zu()}async supportedModels(){return[{value:"gpt-5.6",displayName:"GPT-5.6 (Sol)",description:"OpenAI flagship \u2014 alias for gpt-5.6-sol"},{value:"gpt-5.6-sol",displayName:"GPT-5.6 Sol",description:"Frontier capability"},{value:"gpt-5.6-terra",displayName:"GPT-5.6 Terra",description:"Balanced intelligence/cost"},{value:"gpt-5.6-luna",displayName:"GPT-5.6 Luna",description:"Fast, high-volume workloads"},{value:"gpt-5.5",displayName:"GPT-5.5",description:"Prior flagship (ChatGPT backend)"},{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=Tt(this.currentModel),r;if(e&&n>0){let i=_e(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=yi(e);return{tools:[],agents:[],isAutoCompactEnabled:this.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${Ew} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed(),D(`\u{1F7E2} ${Ew}: closed`)}}});var Aw,xe,R9,gs=h(()=>{"use strict";bu();Xl();dd();Dl();Mo();fb();hb();zr();ut();Nt();In();ku();vi();ed();B();qb();Xn();_w();cp();Ue();Eb();xa();_w();Aw="openai-compatible",xe=class{name=Aw;providerOpts;memoryStore;workspaceStore;stateStore;schemas;_defaultHeaders;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_sharedCurrentCwd;_presenceSessionId=null;_mintedSessionId=null;_spawnedPidRegistry=new Zo;constructor(e={}){this.providerOpts=e,this._defaultHeaders=e.defaultHeaders,this.memoryStore=e.memoryStore??new Ze,this.workspaceStore=e.workspaceStore,this.stateStore=e.stateStore??new jn(ho());let n=[...Wt];e.subagentExecutor&&n.push(e.subagentExecutor.describeAgentTool?.()??rt),e.skillExecutor&&n.push(Er),e.composeExecutor&&n.push(_r),e.readOnlyMemory===!0?n.push(To):n.push(...kn),e.readOnlyMemory===!0?n.push(...Zl):n.push(...Oo),n.push(...this.workspaceStore!==void 0?[_i,Ai]:[],xt);for(let r of e.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);this.schemas=n}setEndpointDefaults(e){e.baseURL!==void 0&&(this.providerOpts.baseURL=e.baseURL),e.defaultHeaders!==void 0&&(this._defaultHeaders=e.defaultHeaders)}query(e){let n=e.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=n.cwd??process.cwd(),a=Pi({surface:this.providerOpts.surface??"cli",getCwd:()=>i,modelName:s,providerName:Aw,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof Kt?o.toolDefs.map(_=>_.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Mi(this.providerOpts.tools,a):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.subagentId!==void 0?{subagentId:n.subagentId}:{},...n.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:n.subagentToolOutputCapBytes}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},...n.bashOutputTailReporter!==void 0?{bashOutputTailReporter:n.bashOutputTailReporter}:{},runtimeStateSource:a,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...n.planExitControls!==void 0?{planExitControls:n.planExitControls}:{}});let c=ba({sessionId:n.sessionId,resume:n.resume,depth:n.depth,parentSessionId:n.parentSessionId,surface:this.providerOpts.surface??"cli",memoized:this._mintedSessionId});this._mintedSessionId=c.memoized;let l={};c.id!==void 0&&(l.sessionIdOverride=c.id);let d=n.openaiBaseUrl??this.providerOpts.baseURL;d!==void 0&&(l.baseURL=d),this._defaultHeaders!==void 0&&(l.defaultHeaders=this._defaultHeaders),l.toolDispatcher=o,l.onPermissionMode=_=>{this._currentPermissionMode=_},this.providerOpts.mcpManager!==void 0&&(l.mcpManager=this.providerOpts.mcpManager),this._presenceSessionId=wa({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:c.id,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:a,surface:this.providerOpts.surface??"cli",cwd:n.cwd,providerName:Aw,model:s});let u=qu(n.isSkillDispatch),p=Gu(this.providerOpts.readOnlyMemory),f=this.providerOpts.skillExecutor?Ep(void 0,{...typeof n.cwd=="string"&&n.cwd.length>0?{cwd:n.cwd}:{},...typeof n.skillDispatchName=="string"&&n.skillDispatchName.length>0?{excludeName:n.skillDispatchName}:{}}):"",m=typeof n.hotMemory=="string"?n.hotMemory:"",g=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,y=_=>{let x=[u];g!==void 0&&g.length>0&&x.push(g),x.push(p);let A=Xu(this.workspaceStore!==void 0);return A&&x.push(A),m.length>0&&x.push(m),x.push(_),f.length>0&&x.push(f),x.join(`
|
|
1211
|
+
`+a})}if(r!==null){let a=r===Mt?wp:Lu;o.push({role:"user",content:a})}let s=r!==null?void 0:this.activeOpenAITools(),i={controller:e,traceWriter:this.traceWriter,initSessionId:this.initSessionId,currentModel:this.currentModel,isClosed:()=>this.closed};if(this.wireMode==="responses"){let a=this.opts.auth.source==="chatgpt-oauth";if(a&&ep(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"); for an auto-dispatched agent you can't pass a model to (e.g. git-investigator), set AFK_DEFAULT_SUBAGENT_MODEL to a gpt-5.x id. Or run it on a provider configured with the matching API key.`)},null;let c=sp({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,temperature:this.opts.config.temperature,isChatGptBackend:a});return yield*Tw(i,{createStream:async l=>await this.client.responses.create(c,{signal:l}),translate:(l,d)=>Zu(l,d,this.initSessionId),clarifyError:l=>this.clarifyResponsesError(l,a)})}else{let a=MO({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,temperature:this.opts.config.temperature});return yield*Tw(i,{createStream:async c=>await this.client.chat.completions.create(a,{signal:c}),translate:(c,l)=>cO(c,l,this.initSessionId),clarifyError:c=>c instanceof Error?c:new Error(String(c))})}}async*dispatchAndAppend(e,n,r){return yield*jO({state:e,signal:n,vision:r,toolDispatcher:this.toolDispatcher,traceWriter:this.traceWriter,priorTurns:this.priorTurns,sessionId:this.initSessionId,subagentId:this.opts.config.subagentId})}async interrupt(e="interrupted"){this.abort.requestAbort(e)}async compact(){let e=await this.compactHistory("manual");return e.compacted&&(this.lastUsage=null),e}async compactHistory(e){let n=this.priorTurns.length;if(this.opts.auth.apiKey===null)return{compacted:!1,reason:"no-usable-auth",messagesBefore:n,messagesAfter:n};if(this.wireMode==="responses"&&this.responsesCompactionUnavailable){let s=us(k.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,k.AFK_MICROCOMPACT_KEEP_LAST),{blocksCleared:i,bytesReclaimed:a}=dw(this.priorTurns,s);return i>0?{compacted:!1,reason:"microcompacted",messagesBefore:n,messagesAfter:this.priorTurns.length,microcompaction:{blocksCleared:i,bytesReclaimed:a}}:{compacted:!1,reason:"responses-compaction-unavailable",messagesBefore:n,messagesAfter:n}}let r=k.AFK_COMPACT_MODEL??this.currentModel,o=wi(_e(this.lastUsage??{}),sn(this.currentModel));return _O({priorTurns:this.priorTurns,usedFraction:o,shrinkAtFraction:EO(),summarize:(s,i)=>this.wireMode==="responses"?this.summarizeViaResponses(s,i,r):ap({client:this.client,model:r,system:Ca,user:Oa(s),maxTokens:1024,signal:i}),isClosed:this.closed,isIdle:this.abort.isIdle(),beginAbort:()=>this.abort.begin(),clearAbort:s=>this.abort.clear(s),trigger:e,traceWriter:this.traceWriter})}async summarizeViaResponses(e,n,r){try{return await DO({client:this.client,model:r,system:Ca,user:Oa(e),isChatGptBackend:this.opts.auth.source==="chatgpt-oauth",maxTokens:1024,signal:n})}catch(o){if(!n.aborted&&YO(o)){this.responsesCompactionUnavailable=!0;let s=Jn(o);q(this.traceWriter,{phase:"compaction_disabled",metadata:{wire:"responses",reason:"responses-compaction-unavailable",error:o instanceof Error?o.message:String(o),...s!==void 0?{status:s}:{}}})}throw o}}async setModel(e){e!==void 0&&(this.currentModel=Ee(e)??e)}async setPermissionMode(e){this.currentPermissionMode=uw(e);let n=Et(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e),this.onCwdChange?.(e)}async supportedCommands(){return zu()}async supportedModels(){return[{value:"gpt-5.6",displayName:"GPT-5.6 (Sol)",description:"OpenAI flagship \u2014 alias for gpt-5.6-sol"},{value:"gpt-5.6-sol",displayName:"GPT-5.6 Sol",description:"Frontier capability"},{value:"gpt-5.6-terra",displayName:"GPT-5.6 Terra",description:"Balanced intelligence/cost"},{value:"gpt-5.6-luna",displayName:"GPT-5.6 Luna",description:"Fast, high-volume workloads"},{value:"gpt-5.5",displayName:"GPT-5.5",description:"Prior flagship (ChatGPT backend)"},{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=Tt(this.currentModel),r;if(e&&n>0){let i=_e(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=yi(e);return{tools:[],agents:[],isAutoCompactEnabled:this.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${Ew} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed(),O(`\u{1F7E2} ${Ew}: closed`)}}});var Aw,xe,R9,gs=h(()=>{"use strict";bu();Xl();dd();Dl();Mo();fb();hb();zr();ut();Nt();In();ku();vi();ed();B();qb();Xn();_w();cp();Ue();Eb();xa();_w();Aw="openai-compatible",xe=class{name=Aw;providerOpts;memoryStore;workspaceStore;stateStore;schemas;_defaultHeaders;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_sharedCurrentCwd;_presenceSessionId=null;_mintedSessionId=null;_spawnedPidRegistry=new Zo;constructor(e={}){this.providerOpts=e,this._defaultHeaders=e.defaultHeaders,this.memoryStore=e.memoryStore??new Ze,this.workspaceStore=e.workspaceStore,this.stateStore=e.stateStore??new jn(ho());let n=[...Wt];e.subagentExecutor&&n.push(e.subagentExecutor.describeAgentTool?.()??rt),e.skillExecutor&&n.push(Er),e.composeExecutor&&n.push(_r),e.readOnlyMemory===!0?n.push(To):n.push(...kn),e.readOnlyMemory===!0?n.push(...Zl):n.push(...Oo),n.push(...this.workspaceStore!==void 0?[_i,Ai]:[],xt);for(let r of e.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);this.schemas=n}setEndpointDefaults(e){e.baseURL!==void 0&&(this.providerOpts.baseURL=e.baseURL),e.defaultHeaders!==void 0&&(this._defaultHeaders=e.defaultHeaders)}query(e){let n=e.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=n.cwd??process.cwd(),a=Pi({surface:this.providerOpts.surface??"cli",getCwd:()=>i,modelName:s,providerName:Aw,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof Kt?o.toolDefs.map(_=>_.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Mi(this.providerOpts.tools,a):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.subagentId!==void 0?{subagentId:n.subagentId}:{},...n.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:n.subagentToolOutputCapBytes}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},...n.bashOutputTailReporter!==void 0?{bashOutputTailReporter:n.bashOutputTailReporter}:{},runtimeStateSource:a,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...n.planExitControls!==void 0?{planExitControls:n.planExitControls}:{}});let c=ba({sessionId:n.sessionId,resume:n.resume,depth:n.depth,parentSessionId:n.parentSessionId,surface:this.providerOpts.surface??"cli",memoized:this._mintedSessionId});this._mintedSessionId=c.memoized;let l={};c.id!==void 0&&(l.sessionIdOverride=c.id);let d=n.openaiBaseUrl??this.providerOpts.baseURL;d!==void 0&&(l.baseURL=d),this._defaultHeaders!==void 0&&(l.defaultHeaders=this._defaultHeaders),l.toolDispatcher=o,l.onPermissionMode=_=>{this._currentPermissionMode=_},this.providerOpts.mcpManager!==void 0&&(l.mcpManager=this.providerOpts.mcpManager),this._presenceSessionId=wa({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:c.id,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:a,surface:this.providerOpts.surface??"cli",cwd:n.cwd,providerName:Aw,model:s});let u=qu(n.isSkillDispatch),p=Gu(this.providerOpts.readOnlyMemory),f=this.providerOpts.skillExecutor?Ep(void 0,{...typeof n.cwd=="string"&&n.cwd.length>0?{cwd:n.cwd}:{},...typeof n.skillDispatchName=="string"&&n.skillDispatchName.length>0?{excludeName:n.skillDispatchName}:{}}):"",m=typeof n.hotMemory=="string"?n.hotMemory:"",g=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,y=_=>{let x=[u];g!==void 0&&g.length>0&&x.push(g),x.push(p);let A=Xu(this.workspaceStore!==void 0);return A&&x.push(A),m.length>0&&x.push(m),x.push(_),f.length>0&&x.push(f),x.join(`
|
|
1212
1212
|
|
|
1213
1213
|
`)},b=()=>Ci({cwd:i,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:a.getWorkspace()}),w={...n,systemPrompt:y(b())},v=_=>{i=_,this._sharedCurrentCwd=_,w.systemPrompt=y(b())};return l.onCwdChange=v,ZO(w,e.prompt,l)}buildDispatcher(e,n){let r=mu(e,n.cwd),o=ii(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[d,u]of o)this.providerOpts.readOnlyMemory===!0&&d!=="memory_search"||r.set(d,u);if(this.workspaceStore!==void 0)for(let[d,u]of xi(this.workspaceStore,n.sessionId??"",n.subagentId))r.set(d,u);for(let[d,u]of Ll(this.stateStore,n.sessionId))this.providerOpts.readOnlyMemory===!0&&d!=="state_get"&&d!=="state_query"||r.set(d,u);n.runtimeStateSource&&r.set("get_runtime_state",Do(n.runtimeStateSource));for(let d of this.providerOpts.customTools??[])r.has(d.schema.name)||r.set(d.schema.name,d.handler);let s=n.planExitControls;s&&r.set(yt,hu(s));let i=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[d,u]of this.providerOpts.mcpManager.getMcpHandlers())r.set(d,u);let a=n.isSkillDispatch?this.schemas.filter(d=>d.name!=="ask_question"&&d.name!=="terminal_font_size"&&d.name!=="clipboard_write"&&d.name!=="clipboard_read"):n.isNonInteractive?this.schemas.filter(d=>d.name!=="ask_question"&&d.name!=="clipboard_read"&&d.name!=="clipboard_write"):this.schemas,c={handlers:r,schemas:[...a,...i,...s?[gu]:[]],hookRegistry:yu(n.hookRegistry,this.providerOpts.hookRegistry)},l=Gl(this.providerOpts.mcpManager?ql(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(d=>d.schema.name));return l!==void 0&&(c.permissions=l),this.providerOpts.subagentExecutor!==void 0&&(c.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(c.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(c.composeExecutor=this.providerOpts.composeExecutor),this.providerOpts.canUseTool!==void 0&&(c.canUseTool=this.providerOpts.canUseTool),n.cwd!==void 0&&(c.cwd=n.cwd),n.readRoots!==void 0&&(c.readRoots=n.readRoots),n.writeRoots!==void 0&&(c.writeRoots=n.writeRoots),n.sessionId!==void 0&&(c.sessionId=n.sessionId),n.parentSessionId!==void 0&&(c.parentSessionId=n.parentSessionId),n.subagentId!==void 0&&(c.subagentId=n.subagentId),n.subagentToolOutputCapBytes!==void 0&&(c.maxOutputBytes=n.subagentToolOutputCapBytes),n.traceWriter!==void 0&&(c.traceWriter=n.traceWriter),n.bashOutputTailReporter!==void 0&&(c.bashOutputTailReporter=n.bashOutputTailReporter),this.providerOpts.readOnlyBash===!0&&(c.readOnlyBash=!0),c.allowAll=Et(e),c.sessionGrantManager=this,c.spawnedPidRegistry=this._spawnedPidRegistry,new Kt(c)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._sharedCurrentCwd&&(this._sharedCurrentCwd=e)}}grantManager=new Rn({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._sharedCurrentCwd,getAllowAll:()=>Et(this._currentPermissionMode)});addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}close(){this.memoryStore.close(),this.workspaceStore?.close(),this.stateStore.close()}async complete(e){let n={model:e.model??"gpt-4o-mini",system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.apiKey!==void 0&&(n.apiKey=e.apiKey);let r=e.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),this._defaultHeaders!==void 0&&(n.defaultHeaders=this._defaultHeaders),e.signal&&(n.signal=e.signal),ap(n)}},R9=new xe});function eD(t,e){return`Skill tool not available at nesting depth ${t} (max ${e}). ${xw}`}function tD(t,e){return`Agent tool not available at nesting depth ${t} (max ${e}). ${xw}`}function nD(t,e){return`Compose tool not available at nesting depth ${t} (max ${e}). ${xw}`}var xw,_p=h(()=>{"use strict";xw="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function rD(t){return I9.has(t)}var I9,oD=h(()=>{"use strict";I9=new Set});function sD(t){for(let e of C9)e(t)}function iD(t){for(let e of P9)e(t)}var C9,P9,aD=h(()=>{"use strict";C9=new Set,P9=new Set});function Ap(t){return M9.has(t)}function cD(t,e=O9){return t.length<=e?t:t.slice(0,e)+"\u2026"}function hs(t){return t.surface!==void 0?{origin:wn(t.surface),actor:Sn(t.depth)}:{}}var M9,O9,Rw=h(()=>{"use strict";ur();M9=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);O9=240});function lD(t){let e=[],n="",r=null,o=!1;for(let s of t){if(r!==null){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s,o=!0;continue}if(/\s/.test(s)){o&&(e.push(n),n="",o=!1);continue}n+=s,o=!0}return o&&e.push(n),e}function Yn(t,e){let n=e??"",r;return t.replace(/(\\?)\$(ARGUMENTS?\b|\{(\d+)\})/g,(o,s,i,a)=>{if(s==="\\")return o.slice(1);if(i==="ARGUMENT"||i==="ARGUMENTS")return n;let c=Number(a);return c<1?o:(r??=lD(n),r[c-1]??o)})}var xp=h(()=>{"use strict"});function dD(t,e,n){let r=n&&n.trim().length>0?n.trim():"(none)";return{content:`${`[Skill "${t}" loaded into your current context \u2014 act on it now]
|
|
1214
1214
|
The instructions below are your operating procedure for THIS task. Execute them immediately, in this session, using the tools you already have. This is an instruction set, not reference material: follow it directly \u2014 do not merely summarize or describe it. No sub-agent was forked; you are the one carrying it out.
|
|
@@ -1219,7 +1219,7 @@ Arguments: ${r}`}
|
|
|
1219
1219
|
${e}`}}function uD(t,e,n,r,o){let{ctx:s}=t,i=s.depth??0,a={...hs(s),requested_name:e,parent_session_id:s.parentSession.sessionId,depth:i,mode:"load",...o!==void 0?{model:o}:{}};ne({event:"skill.dispatched",...a,...Ap(e)?{is_gate:!0}:{}}).catch(()=>{}),ne({event:"skill.completed",status:"succeeded",duration_ms:r,content_chars:n,...a}).catch(()=>{})}function pD(t,e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=Date.now(),s;if(e.loadBody!==void 0)s=e.loadBody;else try{let c=ue(e.name)["system.md"];if(!c)return{content:`Skill "${e.name}" has context: "load" but no prompts/system.md found`,isError:!0};s=c}catch(a){return{content:`Failed to load skill prompts: ${a instanceof Error?a.message:String(a)}`,isError:!0}}let i=Yn(s,n);return uD(t,e.name,i.length,Date.now()-o,e.model),dD(e.name,i,n)}function fD(t,e,n,r,o){if(o.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=Date.now(),i=Yn(n,r);return uD(t,e,i.length,Date.now()-s,void 0),dD(e,i,r)}var Iw=h(()=>{"use strict";bt();Rt();Rw();xp();xp()});function Rp(t,e){t!==void 0&&e!==void 0&&e.length>0&&(t.content=`${t.content}
|
|
1220
1220
|
|
|
1221
1221
|
${e}`)}var Cw=h(()=>{"use strict"});function mD(t){return typeof t=="string"&&t.startsWith("sk-ant-")}function to(t){let{childModel:e,resolved:n,parentApiKey:r}=t;return n!==void 0&&n.length>0||z(e)==="openai-compatible"?n:mD(r)?r:n}function gD(t){let{childModel:e,configApiKey:n,parentApiKey:r,parentProvider:o}=t;if(n!==void 0&&n.length>0)return n;if(r===void 0)return;let s=o??(mD(r)?"anthropic-direct":void 0);if(s===void 0)return;let i=z(e);return D9(i,s)?r:void 0}function D9(t,e){let n=r=>r==="xai-oauth"?"xai":r==="openai-codex"?"openai-compatible":r==="anthropic"?"anthropic-direct":r;return n(t)===n(e)}var Ua=h(()=>{"use strict";fe()});import{realpathSync as hD}from"fs";import{sep as F9}from"path";function Ip(t){let n=t.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
1222
|
-
`).replace(/[\x00-\x08\x0B-\x1F]/g,"");return n.length>yD?n.slice(0,yD):n}function bD(t,e,n){let r,o;try{r=n??hD(t),o=hD(e)}catch{return}return o===r||o.startsWith(r+F9)?o:void 0}var yD,Pw=h(()=>{"use strict";yD=64*1024});import{existsSync as L9,mkdirSync as
|
|
1222
|
+
`).replace(/[\x00-\x08\x0B-\x1F]/g,"");return n.length>yD?n.slice(0,yD):n}function bD(t,e,n){let r,o;try{r=n??hD(t),o=hD(e)}catch{return}return o===r||o.startsWith(r+F9)?o:void 0}var yD,Pw=h(()=>{"use strict";yD=64*1024});import{existsSync as L9,mkdirSync as PCe,readFileSync as N9,renameSync as MCe,writeFileSync as OCe,unlinkSync as DCe}from"fs";function wD(t=Hc()){if(!L9(t))return Cp();try{let e=N9(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Cp();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Cp()}catch{return Cp()}}function Cp(){return{version:2,plugins:{},marketplaces:{}}}var SD=h(()=>{"use strict";B()});import{existsSync as Mw,readFileSync as TD,readdirSync as $9,realpathSync as U9,statSync as B9}from"fs";import{join as ys,resolve as kD}from"path";function Mp(t){H9.push(t)}function mn(t=Lt(),e={}){let n=e.trustAll===!0,r=e.sourceEnabled,o=n?`${t}\0trustAll`:t;if(n&&r&&r.size>0){let l=[...r.entries()].map(([d,u])=>`${d}=${u?1:0}`).sort().join(",");o=`${o}\0${l}`}Ba||(Ba=new Map);let s=Ba.get(o);if(s)return[...s];if(!Mw(t))return Ba.set(o,[]),[];let i=t===Lt()?Hc():ys(t,".index.json"),a=wD(i),c=[];return ED(t,t,0,c,new Set,a.plugins,n,r),Ba.set(o,c),[...c]}function ED(t,e,n,r,o,s,i,a){if(n>j9)return;let c;try{c=U9(e)}catch{c=e}if(o.has(c))return;if(o.add(c),Mw(ys(e,".claude-plugin","plugin.json"))){let d=Ow(t,e);if(d===null){Pp(r,e);return}if(i){if(a&&a.get(K9(d))===!1)return;Pp(r,e);return}if(d.layout==="cache"){let p=s[d.key];if(!p||p.enabled===!1)return;Pp(r,e);return}let u=s[d.key];if(u&&u.enabled===!1)return;Pp(r,e);return}let l;try{l=$9(e)}catch{return}for(let d of l){if(d.startsWith("."))continue;let u=ys(e,d),p;try{p=B9(u)}catch{continue}p.isDirectory()&&ED(t,u,n+1,r,o,s,i,a)}}function W9(t){try{let e=TD(ys(t,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(e);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function Pp(t,e){let n=W9(e);t.push(n!==void 0?{type:"local",path:e,main:n}:{type:"local",path:e})}function K9(t){if(t.layout!=="cache")return t.key;let e=t.key.indexOf(":");if(e<=0)return t.key;let n=t.key.slice(0,e);return`${t.key.slice(e+1)}@${n}`}function Ow(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^[/\\]+/,"");if(!n)return null;let r=n.split(/[/\\]/).filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===vD&&r.length>=3){let s=r[1];if(s){let i=ys(t,vD,s),c=q9(i,e)??r[2];if(c)return{layout:"cache",key:`${s}:${c}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function q9(t,e){let n=ys(t,".claude-plugin","marketplace.json");if(!Mw(n))return null;let r;try{r=JSON.parse(TD(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=kD(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&kD(t,a.source)===s)return a.name}return null}var j9,vD,Ba,H9,bs=h(()=>{"use strict";B();SD();j9=5,vD="cache",H9=[]});import{existsSync as G9,opendirSync as X9,readFileSync as z9,statSync as J9}from"fs";import{join as V9}from"path";function Q9(t,e){return JSON.stringify([t,e===void 0?null:[...e].sort()])}function ja(t,e){let n=t.trim();if(n.length===0)return;if(e.has(n))return n;let r=Z9[n.toLowerCase()];if(r!==void 0&&e.has(r))return r}function Op(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1).trim():e}function Dp(t,e){let n=t.trim();if(n.length>0)return n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1).split(",").map(i=>Op(i)).filter(i=>i.length>0):Op(n).split(",").map(s=>Op(s)).filter(s=>s.length>0);let r=[];for(let o of e){let s=o.trim();if(s.startsWith("- "))r.push(Op(s.slice(2)));else break}return r}function AD(t,e){let n=Q9(t,e),r=Dw.get(n);if(r!==void 0)return r;let o=[],s=0;function i(a,c=0){if(c>Y9||s>=_D||!G9(a))return;let l;try{l=X9(a)}catch{return}try{for(;s<_D;){let d=l.readSync();if(d===null)break;s++;let u=d.name;if(u.startsWith(".")||u==="node_modules")continue;let p=V9(a,u),f;try{f=J9(p)}catch{continue}if(f.isFile()&&u==="SKILL.md"){let m=Fw(p,e);m.name&&o.push(m)}else f.isDirectory()&&i(p,c+1)}}finally{l.closeSync()}}return i(t),Dw.set(n,o),o}function Fw(t,e){try{let n=Ip(z9(t,"utf-8"));if(!n.startsWith(`---
|
|
1223
1223
|
`))return{};let r=n.slice(4),o=r.indexOf(`
|
|
1224
1224
|
---`);if(o===-1)return{};let s=r.slice(0,o),i=r.slice(o+4).trim(),a={},c=s.split(`
|
|
1225
1225
|
`);for(let l=0;l<c.length;l++){let d=c[l];if(!d)continue;let u=d.indexOf(":");if(u===-1)continue;let p=d.slice(0,u).trim(),f=d.slice(u+1).trim();if(p==="name")a.name=f.replace(/^["']|["']$/g,"");else if(p==="description")a.description=f.replace(/^["']|["']$/g,"");else if(p==="argument-hint"||p==="argumentHint")a.argumentHint=f.replace(/^["']|["']$/g,"");else if(p==="when-to-use"||p==="whenToUse"||p==="when_to_use")a.whenToUse=f.replace(/^["']|["']$/g,"");else if(p==="tools"){let m=c.slice(l+1),g=Dp(f,m),y=Fp(e),b=[];for(let w of g){let v=ja(w,y);v!==void 0?b.includes(v)||b.push(v):process.stderr.write(`[afk] plugin skill at ${t}: unknown tool "${w}" in \`tools:\` frontmatter \u2014 ignored
|
|
@@ -1227,7 +1227,7 @@ ${e}`)}var Cw=h(()=>{"use strict"});function mD(t){return typeof t=="string"&&t.
|
|
|
1227
1227
|
`),a.allowedTools=b}else if(p==="audience"){let m=f.replace(/^["']|["']$/g,"");(m==="public"||m==="internal")&&(a.audience=m)}else if(p==="context")a.context=f.replace(/^["']|["']$/g,"");else if(p==="read-only"||p==="readOnly")f.replace(/^["']|["']$/g,"").trim()==="true"&&(a.readOnly=!0);else if(p==="model"){let m=f.replace(/^["']|["']$/g,"").trim();m.length>0&&(a.model=m)}}return i.length>0&&(a.body=i),a}catch{return{}}}function Fp(t){return t!==void 0?t:new Set([...At,...$e,"memory_search","agent","skill"])}var Y9,_D,Dw,Z9,ws=h(()=>{"use strict";Pw();ut();Ue();bs();Y9=10,_D=1e3,Dw=new Map;Mp(()=>Dw.clear());Z9={read:"read_file",edit:"edit_file",write:"write_file",bash:"bash",grep:"grep",glob:"glob",ls:"list_directory",list:"list_directory",webfetch:"web_scrape",websearch:"web_scrape",webbrowse:"web_scrape"}});function Ss(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&e.length>=2||e.startsWith("'")&&e.endsWith("'")&&e.length>=2?e.slice(1,-1).trim():e}function t7(t,e,n){let r=Ss(t);(r===">"||r===">-"||r==="|"||r==="|-")&&(r="");let s=0;for(let i=n;i<e.length;i++){let a=e[i];if(a===void 0||!/^\s+\S/.test(a))break;let c=a.trim();if(c.startsWith("- "))break;r=r.length>0?`${r} ${c}`:c,s++}return{value:r,consumed:s}}function no(t,e=()=>{}){if(!t.startsWith("---")){e("missing frontmatter (file must start with ---)");return}let n=t.slice(3),r=n.indexOf(`
|
|
1228
1228
|
---`);if(r===-1){e("unterminated frontmatter (no closing ---)");return}let o=n.slice(0,r),s=n.slice(r+4),i=s.startsWith(`
|
|
1229
1229
|
`)?s.slice(1):s,a=o.split(`
|
|
1230
|
-
`),c,l,d,u,p,f,m,g,y=[];for(let v=0;v<a.length;v++){let _=a[v];if(_===void 0||_.trim().length===0||/^\s/.test(_))continue;let x=_.indexOf(":");if(x===-1)continue;let A=_.slice(0,x).trim(),I=A.toLowerCase(),C=_.slice(x+1),T=a.slice(v+1);switch(I){case"name":{c=Ss(C);break}case"description":{let{value:R,consumed:E}=t7(C,a,v+1);l=R,v+=E;break}case"tools":case"allowed-tools":{m=xD(Dp(C,T));break}case"disallowedtools":case"disallowed-tools":{g=xD(Dp(C,T));break}case"model":{let R=Ss(C);R.length>0&&(d=R);break}case"maxturns":case"max-turns":{let R=Number.parseInt(Ss(C),10);Number.isFinite(R)&&R>0?u=R:e(`invalid ${A} value ${JSON.stringify(C.trim())} \u2014 ignored`);break}case"maxtooluseiterations":case"max-tool-use-iterations":{let R=Number.parseInt(Ss(C),10);Number.isFinite(R)&&R>0?p=R:e(`invalid ${A} value ${JSON.stringify(C.trim())} \u2014 ignored`);break}case"bash":{let R=Ss(C).toLowerCase();R==="read-only"||R==="readonly"?f=!0:e(`unrecognized bash value ${JSON.stringify(C.trim())} \u2014 ignored`);break}default:{e7.has(I)?y.push(A):e(`unknown frontmatter key ${JSON.stringify(A)} \u2014 ignored`);break}}}if(c===void 0||c.length===0){e('missing required frontmatter field "name"');return}if(l===void 0||l.length===0){e(`agent ${JSON.stringify(c)}: missing required frontmatter field "description"`);return}let b=i.trim();if(b.length===0){e(`agent ${JSON.stringify(c)}: empty body \u2014 an agent file's body is its system prompt`);return}let w={description:l,prompt:b,...m!==void 0&&m.length>0?{tools:m}:{},...g!==void 0&&g.length>0?{disallowedTools:g}:{},...d!==void 0?{model:d}:{},...u!==void 0?{maxTurns:u}:{},...p!==void 0?{maxToolUseIterations:p}:{}};return{name:c,definition:w,...f===!0?{bashReadOnly:!0}:{},...y.length>0?{ignoredKeys:y}:{}}}function xD(t){let e=[];for(let n of t){if(n.includes("(")){e.push(n);continue}for(let r of n.split(/\s+/))r.length>0&&e.push(r)}return e}var e7,Ha=h(()=>{"use strict";ws();e7=new Set(["permissionmode","permission-mode","skills","mcpservers","mcp-servers","hooks","memory","background","effort","isolation","color","initialprompt","initial-prompt"])});function o7(t){let e=t.trim();if(e.length===0)return null;let n=e.indexOf("(");if(n!==-1){if(e=e.slice(0,n).trim(),e.length===0)return null}else if(e.endsWith(")"))return null;if(e.startsWith("mcp__"))return e;let r=r7[e.toLowerCase()];return r!==void 0?r:ja(e,n7)}function RD(t){let e=[],n=new Set,r=[];for(let o of t){let s=o7(o);if(s!==null){if(s===void 0){r.push(o.trim());continue}n.has(s)||(n.add(s),e.push(s))}}return{names:e,dropped:r}}function s7(t){let e=[],n=0,r="";for(let o of t)o==="("?(n++,r+=o):o===")"?(n=Math.max(0,n-1),r+=o):o===","&&n===0?(e.push(r),r=""):r+=o;return r.length>0&&e.push(r),e}function i7(t){let e=s7(t.join(",")),n=!1,r=!1,o=new Set;for(let s of e){let i=s.trim();if(i.length===0)continue;let a=i.indexOf("("),c=(a===-1?i:i.slice(0,a)).trim().toLowerCase();if(c!=="agent"&&c!=="task")continue;if(a===-1){n=!0;continue}r=!0;let l=i.slice(a+1).replace(/\)\s*$/,"");for(let d of l.split(",")){let u=d.trim();u.length>0&&o.add(u)}}if(!n){if(o.size>0)return[...o];if(r)return[]}}function Lp(t,e){let{tools:n,disallowedTools:r}=t.definition,o=t.bashReadOnly===!0,s=r!==void 0?RD(r):void 0,i=n!==void 0?RD(n):void 0,a=[...i?.dropped??[],...s?.dropped??[]];if(i===void 0&&s===void 0)return{allowedTools:void 0,bashReadOnly:o,droppedTokens:a};let c=new Set(s?.names??[]),d=(i?.names??[...e]).filter(p=>!c.has(p)),u=n!==void 0&&d.includes("agent")?i7(n):void 0;return{allowedTools:d,bashReadOnly:o,droppedTokens:a,...u!==void 0?{nestedAgentTypes:u}:{}}}var n7,r7,ID=h(()=>{"use strict";ws();ut();Ue();n7=new Set([...At,...$e,"memory_search","agent","skill"]),r7={task:"agent",agent:"agent",skill:"skill"}});import{fileURLToPath as a7}from"node:url";import{dirname as c7}from"node:path";var l7,rPe,Yt,Lw=h(()=>{"use strict";l7=a7(import.meta.url),rPe=c7(l7),Yt={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: "CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Locked to Read, Grep, Glob, WebFetch, WebSearch. Delegates git queries to `git-investigator`. Use when task is findings-only."\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:'CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Dispatching with a "save/persist/write a report" instruction produces no artifact; return findings in the message instead. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Bash, commit, or push. Delegates git queries to `git-investigator`. Use for findings-only tasks.'}});import{fileURLToPath as d7}from"node:url";import{dirname as u7}from"node:path";var p7,cPe,ro,CD=h(()=>{"use strict";p7=d7(import.meta.url),cPe=u7(p7),ro={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"vendored/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"}});var Wa,Nw=h(()=>{"use strict";Wa=`Handoff contract: your final message is the ONLY thing the dispatching session receives \u2014 its intermediate tool calls, file reads, and exploration are invisible to the parent, so everything that matters must be in the reply itself.
|
|
1230
|
+
`),c,l,d,u,p,f,m,g,y=[];for(let v=0;v<a.length;v++){let _=a[v];if(_===void 0||_.trim().length===0||/^\s/.test(_))continue;let x=_.indexOf(":");if(x===-1)continue;let A=_.slice(0,x).trim(),I=A.toLowerCase(),C=_.slice(x+1),T=a.slice(v+1);switch(I){case"name":{c=Ss(C);break}case"description":{let{value:R,consumed:E}=t7(C,a,v+1);l=R,v+=E;break}case"tools":case"allowed-tools":{m=xD(Dp(C,T));break}case"disallowedtools":case"disallowed-tools":{g=xD(Dp(C,T));break}case"model":{let R=Ss(C);R.length>0&&(d=R);break}case"maxturns":case"max-turns":{let R=Number.parseInt(Ss(C),10);Number.isFinite(R)&&R>0?u=R:e(`invalid ${A} value ${JSON.stringify(C.trim())} \u2014 ignored`);break}case"maxtooluseiterations":case"max-tool-use-iterations":{let R=Number.parseInt(Ss(C),10);Number.isFinite(R)&&R>0?p=R:e(`invalid ${A} value ${JSON.stringify(C.trim())} \u2014 ignored`);break}case"bash":{let R=Ss(C).toLowerCase();R==="read-only"||R==="readonly"?f=!0:e(`unrecognized bash value ${JSON.stringify(C.trim())} \u2014 ignored`);break}default:{e7.has(I)?y.push(A):e(`unknown frontmatter key ${JSON.stringify(A)} \u2014 ignored`);break}}}if(c===void 0||c.length===0){e('missing required frontmatter field "name"');return}if(l===void 0||l.length===0){e(`agent ${JSON.stringify(c)}: missing required frontmatter field "description"`);return}let b=i.trim();if(b.length===0){e(`agent ${JSON.stringify(c)}: empty body \u2014 an agent file's body is its system prompt`);return}let w={description:l,prompt:b,...m!==void 0&&m.length>0?{tools:m}:{},...g!==void 0&&g.length>0?{disallowedTools:g}:{},...d!==void 0?{model:d}:{},...u!==void 0?{maxTurns:u}:{},...p!==void 0?{maxToolUseIterations:p}:{}};return{name:c,definition:w,...f===!0?{bashReadOnly:!0}:{},...y.length>0?{ignoredKeys:y}:{}}}function xD(t){let e=[];for(let n of t){if(n.includes("(")){e.push(n);continue}for(let r of n.split(/\s+/))r.length>0&&e.push(r)}return e}var e7,Ha=h(()=>{"use strict";ws();e7=new Set(["permissionmode","permission-mode","skills","mcpservers","mcp-servers","hooks","memory","background","effort","isolation","color","initialprompt","initial-prompt"])});function o7(t){let e=t.trim();if(e.length===0)return null;let n=e.indexOf("(");if(n!==-1){if(e=e.slice(0,n).trim(),e.length===0)return null}else if(e.endsWith(")"))return null;if(e.startsWith("mcp__"))return e;let r=r7[e.toLowerCase()];return r!==void 0?r:ja(e,n7)}function RD(t){let e=[],n=new Set,r=[];for(let o of t){let s=o7(o);if(s!==null){if(s===void 0){r.push(o.trim());continue}n.has(s)||(n.add(s),e.push(s))}}return{names:e,dropped:r}}function s7(t){let e=[],n=0,r="";for(let o of t)o==="("?(n++,r+=o):o===")"?(n=Math.max(0,n-1),r+=o):o===","&&n===0?(e.push(r),r=""):r+=o;return r.length>0&&e.push(r),e}function i7(t){let e=s7(t.join(",")),n=!1,r=!1,o=new Set;for(let s of e){let i=s.trim();if(i.length===0)continue;let a=i.indexOf("("),c=(a===-1?i:i.slice(0,a)).trim().toLowerCase();if(c!=="agent"&&c!=="task")continue;if(a===-1){n=!0;continue}r=!0;let l=i.slice(a+1).replace(/\)\s*$/,"");for(let d of l.split(",")){let u=d.trim();u.length>0&&o.add(u)}}if(!n){if(o.size>0)return[...o];if(r)return[]}}function Lp(t,e){let{tools:n,disallowedTools:r}=t.definition,o=t.bashReadOnly===!0,s=r!==void 0?RD(r):void 0,i=n!==void 0?RD(n):void 0,a=[...i?.dropped??[],...s?.dropped??[]];if(i===void 0&&s===void 0)return{allowedTools:void 0,bashReadOnly:o,droppedTokens:a};let c=new Set(s?.names??[]),d=(i?.names??[...e]).filter(p=>!c.has(p)),u=n!==void 0&&d.includes("agent")?i7(n):void 0;return{allowedTools:d,bashReadOnly:o,droppedTokens:a,...u!==void 0?{nestedAgentTypes:u}:{}}}var n7,r7,ID=h(()=>{"use strict";ws();ut();Ue();n7=new Set([...At,...$e,"memory_search","agent","skill"]),r7={task:"agent",agent:"agent",skill:"skill"}});import{fileURLToPath as a7}from"node:url";import{dirname as c7}from"node:path";var l7,oPe,Yt,Lw=h(()=>{"use strict";l7=a7(import.meta.url),oPe=c7(l7),Yt={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: "CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Locked to Read, Grep, Glob, WebFetch, WebSearch. Delegates git queries to `git-investigator`. Use when task is findings-only."\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:'CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Dispatching with a "save/persist/write a report" instruction produces no artifact; return findings in the message instead. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Bash, commit, or push. Delegates git queries to `git-investigator`. Use for findings-only tasks.'}});import{fileURLToPath as d7}from"node:url";import{dirname as u7}from"node:path";var p7,lPe,ro,CD=h(()=>{"use strict";p7=d7(import.meta.url),lPe=u7(p7),ro={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"vendored/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"}});var Wa,Nw=h(()=>{"use strict";Wa=`Handoff contract: your final message is the ONLY thing the dispatching session receives \u2014 its intermediate tool calls, file reads, and exploration are invisible to the parent, so everything that matters must be in the reply itself.
|
|
1231
1231
|
|
|
1232
1232
|
Keep that reply compact and lead with the answer: outcome/answer first, then the key evidence (file:line where it applies), risks or caveats, and anything you did not check.
|
|
1233
1233
|
|
|
@@ -1273,33 +1273,33 @@ ${t}`:t}function Zn(t){return Ye(t)?{incomplete:!0,incompleteReason:t}:{}}functi
|
|
|
1273
1273
|
`),this.errored=!0}}async close(){if(!this.closed)return this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(e=>{if(!this.stream){e();return}this.stream.end(()=>{e()})})}async writeMeta(e){this.metaWriteQueue=this.metaWriteQueue.then(()=>this._writeMetaInner(e)),await this.metaWriteQueue}async _writeMetaInner(e){let n=`${this.metaPath}.${z7(4).toString("hex")}.tmp`;try{await Dt.writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),await Dt.rename(n,this.metaPath)}catch(r){process.stderr.write(`[afk] bg-job-log: writeMeta failed for ${this.jobId}: ${String(r)}
|
|
1274
1274
|
`);try{await Dt.unlink(n)}catch{}}}}});function Gp(t){ne(t).catch(()=>{})}var sF=h(()=>{"use strict";Rt()});import*as er from"node:fs/promises";import*as iF from"node:path";async function aF(){let t=zc(),e;try{e=await er.readdir(t)}catch{return}for(let n of e){let r=bo(n),o=iF.join(r,"meta.json");try{if(!(await er.lstat(r)).isDirectory()){process.stderr.write(`[afk] bg sweep: skipping non-directory entry ${n}
|
|
1275
1275
|
`);continue}let i=await er.readFile(o,"utf8"),a=JSON.parse(i);if(a.status==="running"||a.endedAt===void 0||Date.now()-a.endedAt<J7)continue;await er.rm(r,{recursive:!0,force:!0})}catch(s){if(s.code==="ENOENT")continue;process.stderr.write(`[afk] bg sweep: error evicting ${n}: ${String(s)}
|
|
1276
|
-
`)}}}var J7,cF=h(()=>{"use strict";B();J7=10080*60*1e3});function lF(t){return t??ME()}var so,nS=h(()=>{"use strict";Ul();so=class extends Error{constructor(e,n){super(`Background job cap reached (${e}/${n} running). Wait for existing jobs to finish or use cancel_background_job on a model-owned job before spawning more.`),this.name="BackgroundJobCapError"}}});function dF(t,e){let n=t+e;return n.length<=4096?n:n.slice(n.length-4096)}var rS=h(()=>{"use strict"});import{EventEmitter as V7}from"node:events";import{createHash as Y7}from"node:crypto";var Q7,uF,Xp,oS=h(()=>{"use strict";Re();
|
|
1277
|
-
`)),5e3).unref()}setTraceWriter(e){this.traceWriter=e}register(e){let{job:n,jobId:r,writer:o,metaRecord:s}=this.createJobEntry(e);return e.handle.runInBackground(e.prompt,i=>{this.markTerminal(r,i,o,s).catch(a=>D(`markTerminal (register) rejected for ${r}: ${String(a)}`))},i=>{o.write(i),i.type==="chunk"&&i.chunk.type==="content"&&this.appendTranscript(r,i.chunk.content),i.type==="chunk"&&i.chunk.type==="tool_use_detail"&&!i.chunk.pending&&(i.chunk.toolName==="edit_file"||i.chunk.toolName==="write_file")&&this.recordTouchedFile(r,i.chunk.toolInputRaw??i.chunk.toolInput)}),this.snapshot(n)}adoptRunning(e){let{job:n,jobId:r,writer:o,metaRecord:s}=this.createJobEntry(e);return e.runPromise.then(i=>this.markTerminal(r,i,o,s)).catch(i=>(D("adoptRunning: unexpected rejection from in-flight runPromise",i),this.markTerminal(r,Kp(e.handle.id,"failed",i,_s()),o,s))),this.snapshot(n)}createJobEntry(e){let n=[...this.jobs.values()].filter(u=>u.status==="running").length;if(n>=this.maxConcurrentJobs)throw new so(n,this.maxConcurrentJobs);let r=this.nextJobId(),o=e.prompt.trim().slice(0,80),s=Date.now(),i,a=new Promise(u=>{i=u}),c={jobId:r,provenance:e.provenance??"user",subagentId:e.handle.id,label:o,model:e.model,startedAt:s,status:"running",handle:e.handle,joiners:[],terminalSettled:a,settle:i,transcriptTail:"",touchedFiles:[],parentSessionId:e.parentSessionId,onCleanup:e.onCleanup};this.jobs.set(r,c),vr(this.traceWriter,{transition:"started",jobId:r,subagentId:e.handle.id,label:o,model:e.model}),this.emit("started",this.snapshot(c));let l=new qp(r),d={jobId:r,subagentId:e.handle.id,label:o,promptHash:Y7("sha256").update(e.prompt).digest("hex"),model:e.model,startedAt:s,status:"running",...e.parentSessionId!==void 0?{parentSessionId:e.parentSessionId}:{},schemaVersion:1};return l.writeMeta(d),{job:c,jobId:r,writer:l,metaRecord:d}}get(e){let n=this.jobs.get(e);return n?this.snapshot(n):void 0}list(){return[...this.jobs.values()].map(e=>this.snapshot(e))}async join(e){let n=this.jobs.get(e);if(!n)throw new Error(`Background job not found: "${e}". Completed and cancelled jobs are evicted from the registry ~5 minutes after they settle. If the jobId looks correct, the job may have already been evicted.`);let r=await n.terminalSettled;return vr(this.traceWriter,{transition:"joined",jobId:e,subagentId:n.subagentId,jobStatus:n.status}),this.emit("joined",this.snapshot(n)),r}markDelivered(e){let n=this.jobs.get(e);!n||n.status==="running"||vr(this.traceWriter,{transition:"delivered",jobId:e,subagentId:n.subagentId,jobStatus:n.status})}async cancelJob(e){let n=this.jobs.get(e);return!n||n.status!=="running"?!1:(n.cancelSource="explicit",await n.handle.cancel(),!0)}async cancelModelJob(e,n){let r=this.jobs.get(e);return!r||r.status!=="running"||r.provenance!=="model"?!1:(r.cancelSource="explicit",r.modelCancelReason=n,await r.handle.cancel(),!0)}async cancelAll(){let e=[...this.jobs.values()].filter(n=>n.status==="running");for(let n of e)n.cancelSource="cascade";await Promise.allSettled(e.map(n=>n.handle.cancel())),await Promise.allSettled(e.map(n=>{let r=new Promise(o=>setTimeout(()=>{let s=n.touchedFiles.length>0?` \u2014 files touched: ${n.touchedFiles.join(", ")}`:"";console.warn(`[BackgroundAgentRegistry] cancelAll: job ${n.jobId} did not settle within ${uF}ms \u2014 continuing teardown${s}`),o()},uF).unref());return Promise.race([n.terminalSettled,r])}))}appendTranscript(e,n){let r=this.jobs.get(e);r&&(r.transcriptTail=dF(r.transcriptTail,n))}getTranscript(e){return this.jobs.get(e)?.transcriptTail}getHandle(e){return this.jobs.get(e)?.handle}getTouchedFiles(e){return this.jobs.get(e)?.touchedFiles}recordTouchedFile(e,n){let r=this.jobs.get(e);if(r)try{let o=JSON.parse(n);if(o!==null&&typeof o=="object"&&"file_path"in o&&typeof o.file_path=="string"){let s=o.file_path;s&&!r.touchedFiles.includes(s)&&r.touchedFiles.push(s)}}catch{}}nextJobId(){return this.counter+=1,`bg-${Date.now().toString(36)}-${this.counter}`}async markTerminal(e,n,r,o){let s=this.jobs.get(e);if(!s||s.status!=="running")return;s.result=n,s.endedAt=Date.now();let i=s.endedAt-s.startedAt;if(s.status=this.statusFromResult(n.status),s.status==="completed"){let c=n.message?.content,l=typeof c=="string"?c:c!==void 0?JSON.stringify(c):"";vr(this.traceWriter,{transition:"completed",jobId:e,subagentId:s.subagentId,durationMs:i,outputBytes:Buffer.byteLength(l,"utf8")}),Gp({event:"subagent.completed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,content_chars:l.length,stop_reason:hn(n.stopReason)}),this.emit("settled",this.snapshot(s))}else if(s.status==="failed"){let c=n.error;vr(this.traceWriter,{transition:"failed",jobId:e,subagentId:s.subagentId,durationMs:i,errorClass:c?.name??"Error",errorMessage:c?.message??"unknown"}),Gp({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,error_message:c?.message,stop_reason:hn(n.stopReason)}),this.emit("settled",this.snapshot(s))}else vr(this.traceWriter,{transition:"cancelled",jobId:e,subagentId:s.subagentId,source:s.cancelSource??"explicit",...s.modelCancelReason!==void 0?{cancelledBy:"model",reason:s.modelCancelReason}:{}}),Gp({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,stop_reason:hn(n.stopReason)}),this.emit("settled",this.snapshot(s));if(s.settle(n),r&&o){let c=s.status,l=s.endedAt;r.writeMeta({...o,status:c,...l!==void 0?{endedAt:l}:{},...hn(n.stopReason)!==void 0?{stopReason:hn(n.stopReason)}:{}}).then(()=>r.close())}setTimeout(()=>{this.jobs.delete(e)},Q7).unref();try{await s.handle.teardown()}catch(c){D(`markTerminal: handle.teardown() failed for job ${e}: ${String(c)}`)}if(s.onCleanup)try{await s.onCleanup()}catch(c){D(`markTerminal: onCleanup failed for job ${e}: ${String(c)}`)}}statusFromResult(e){return e==="succeeded"?"completed":e==="failed"?"failed":e==="cancelled"?"cancelled":"failed"}snapshot(e){return{jobId:e.jobId,provenance:e.provenance,subagentId:e.subagentId,label:e.label,model:e.model,startedAt:e.startedAt,status:e.status,...e.result!==void 0?{result:e.result}:{},...e.endedAt!==void 0?{endedAt:e.endedAt}:{},...e.parentSessionId!==void 0?{parentSessionId:e.parentSessionId}:{}}}}});import{execFile as Z7}from"node:child_process";import{promisify as eZ}from"node:util";async function zp(t,e){try{await sS("git",["-C",t,"worktree","lock","--reason","afk: background-isolated-worktree in use by detached child",e])}catch(n){D(`[isolation] failed to lock worktree for background child: ${String(n)}`)}}async function pF(t,e){await sS("git",["-C",t,"worktree","unlock",e])}async function en(t){try{await sS("git",["-C",t.repoRoot,"worktree","unlock",t.worktreePath])}catch{}return Xd(t)}var sS,Jp=h(()=>{"use strict";oa();ie();sS=eZ(Z7)});async function fF(t){let{handle:e,registry:n,prompt:r,model:o,parentSessionId:s,onSettled:i,onCleanup:a,isolationTeardown:c}=t;if(!n)return await e.teardown().catch(u=>D("subagent-executor: handle teardown failed: "+(u instanceof Error?u.message:String(u)))),c&&await en(c).catch(u=>D(`[isolation] background worktree teardown failed (no registry): ${String(u)}`)),i?.(!0),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let l;try{l=n.register({handle:e,prompt:r,model:o??"sonnet",provenance:"model",parentSessionId:s,onCleanup:a})}catch(u){if(u instanceof so)return await e.teardown().catch(p=>D("subagent-executor: handle teardown failed after cap error: "+(p instanceof Error?p.message:String(p)))),c&&await en(c).catch(p=>D(`[isolation] background worktree teardown failed (cap error): ${String(p)}`)),i?.(!0),{content:u.message,isError:!0};throw await e.teardown().catch(p=>D("subagent-executor: handle teardown failed after register error: "+(p instanceof Error?p.message:String(p)))),c&&await en(c).catch(p=>D(`[isolation] background worktree teardown failed (register error): ${String(p)}`)),u}if(i){let u=l.jobId,p=f=>{f.jobId===u&&(n.off("settled",p),i(f.status==="failed"||f.status==="cancelled"))};n.on("settled",p)}let d={status:"running",jobId:l.jobId,subagentId:l.subagentId,label:l.label,message:`Background subagent started (jobId=${l.jobId}). It is running detached; its result will be delivered into this context automatically with the next user message once it finishes. /bgsub:join ${l.jobId} remains available for manual replay.`};return{content:JSON.stringify(d)}}var mF=h(()=>{"use strict";oS();ie();Jp()});async function gF(t,e){let n=e.input,r=typeof n.jobId=="string"?n.jobId.trim():"",o=typeof n.reason=="string"?n.reason.trim():"";if(!r||!o)return{content:"cancel_background_job requires non-empty jobId and reason strings.",isError:!0};if(!t)return{content:"Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired.",isError:!0};let s=t.get(r);if(!s){let a=t.list().map(c=>c.jobId);return{content:`Background job not found: "${r}". Currently-known job ids: ${a.length>0?a.join(", "):"(none)"}.`,isError:!0}}return s.status!=="running"?{content:`Background job ${r} is already ${s.status}; nothing to cancel.`}:s.provenance!=="model"?{content:`Refused: background job ${r} was backgrounded by the user. Ask the user to run /bgsub:cancel ${r}.`,isError:!0}:await t.cancelModelJob(r,o)?{content:`Cancellation requested for background job ${r} (${s.label}).`}:{content:`Background job ${r} became terminal before cancellation was issued.`}}var hF=h(()=>{"use strict"});async function yF(t,e,n){let r=e.input,o=typeof r.jobId=="string"?r.jobId.trim():"",s=typeof r.message=="string"?r.message.trim():"";if(!o||!s)return{content:"send_message_to_agent requires non-empty jobId and message strings.",isError:!0};if(!t)return{content:"Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired.",isError:!0};let i=t.get(o);if(!i){let c=t.list().filter(l=>l.provenance==="model").map(l=>l.jobId);return{content:`Background job not found: "${o}". Currently-known job ids: ${c.length>0?c.join(", "):"(none)"}.`,isError:!0}}if(i.provenance!=="model")return{content:`Refused: background job ${o} was backgrounded by the user. Only model-created background jobs can be steered this way.`,isError:!0};if(n&&i.parentSessionId!==n)return{content:`Refused: background job ${o} belongs to a different session.`,isError:!0};if(i.status!=="running")return{content:`Background job ${o} is already ${i.status}; steering message was not delivered.`};let a=t.getHandle(o);if(!a)return{content:`Handle for job "${o}" is not available.`,isError:!0};if(typeof a.session.setBeforeNextRound!="function"){let c=a.session;return{content:`Steering is not supported on ${typeof c.providerName=="string"?c.providerName:"this provider"}. The message was not delivered. Use a model backed by the Anthropic provider to enable send_message_to_agent.`,isError:!0}}return a.steer(s),{content:`Steering message queued for background job ${o}.`}}var bF=h(()=>{"use strict"});function SF(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function tZ(t){if(SF(t)<=16384)return t;let e=Array.from(t),n=s=>SF(e.slice(0,s).join("")+wF)<=16384,r=0,o=e.length;for(;r<o;){let s=Math.ceil((r+o)/2);n(s)?r=s:o=s-1}return e.slice(0,r).join("")+wF}function nZ(t){return tZ(t)}function kF(t){if(!(t===void 0||t.claimed)&&t.text.trim().length!==0)return t.claimed=!0,nZ(t.text)}var wF,vF=h(()=>{"use strict";wF=`
|
|
1276
|
+
`)}}}var J7,cF=h(()=>{"use strict";B();J7=10080*60*1e3});function lF(t){return t??ME()}var so,nS=h(()=>{"use strict";Ul();so=class extends Error{constructor(e,n){super(`Background job cap reached (${e}/${n} running). Wait for existing jobs to finish or use cancel_background_job on a model-owned job before spawning more.`),this.name="BackgroundJobCapError"}}});function dF(t,e){let n=t+e;return n.length<=4096?n:n.slice(n.length-4096)}var rS=h(()=>{"use strict"});import{EventEmitter as V7}from"node:events";import{createHash as Y7}from"node:crypto";var Q7,uF,Xp,oS=h(()=>{"use strict";Re();se();J();oF();sF();Hp();cF();nS();rS();nS();rS();Q7=300*1e3,uF=5e3,Xp=class extends V7{jobs=new Map;counter=Math.floor(Math.random()*65536);traceWriter;maxConcurrentJobs;constructor(e={}){super(),this.traceWriter=e.traceWriter,this.maxConcurrentJobs=lF(e.maxConcurrentJobs),setTimeout(()=>aF().catch(r=>process.stderr.write(`[afk] bg sweep error: ${String(r)}
|
|
1277
|
+
`)),5e3).unref()}setTraceWriter(e){this.traceWriter=e}register(e){let{job:n,jobId:r,writer:o,metaRecord:s}=this.createJobEntry(e);return e.handle.runInBackground(e.prompt,i=>{this.markTerminal(r,i,o,s).catch(a=>O(`markTerminal (register) rejected for ${r}: ${String(a)}`))},i=>{o.write(i),i.type==="chunk"&&i.chunk.type==="content"&&this.appendTranscript(r,i.chunk.content),i.type==="chunk"&&i.chunk.type==="tool_use_detail"&&!i.chunk.pending&&(i.chunk.toolName==="edit_file"||i.chunk.toolName==="write_file")&&this.recordTouchedFile(r,i.chunk.toolInputRaw??i.chunk.toolInput)}),this.snapshot(n)}adoptRunning(e){let{job:n,jobId:r,writer:o,metaRecord:s}=this.createJobEntry(e);return e.runPromise.then(i=>this.markTerminal(r,i,o,s)).catch(i=>(O("adoptRunning: unexpected rejection from in-flight runPromise",i),this.markTerminal(r,Kp(e.handle.id,"failed",i,_s()),o,s))),this.snapshot(n)}createJobEntry(e){let n=[...this.jobs.values()].filter(u=>u.status==="running").length;if(n>=this.maxConcurrentJobs)throw new so(n,this.maxConcurrentJobs);let r=this.nextJobId(),o=e.prompt.trim().slice(0,80),s=Date.now(),i,a=new Promise(u=>{i=u}),c={jobId:r,provenance:e.provenance??"user",subagentId:e.handle.id,label:o,model:e.model,startedAt:s,status:"running",handle:e.handle,joiners:[],terminalSettled:a,settle:i,transcriptTail:"",touchedFiles:[],parentSessionId:e.parentSessionId,onCleanup:e.onCleanup};this.jobs.set(r,c),vr(this.traceWriter,{transition:"started",jobId:r,subagentId:e.handle.id,label:o,model:e.model}),this.emit("started",this.snapshot(c));let l=new qp(r),d={jobId:r,subagentId:e.handle.id,label:o,promptHash:Y7("sha256").update(e.prompt).digest("hex"),model:e.model,startedAt:s,status:"running",...e.parentSessionId!==void 0?{parentSessionId:e.parentSessionId}:{},schemaVersion:1};return l.writeMeta(d),{job:c,jobId:r,writer:l,metaRecord:d}}get(e){let n=this.jobs.get(e);return n?this.snapshot(n):void 0}list(){return[...this.jobs.values()].map(e=>this.snapshot(e))}async join(e){let n=this.jobs.get(e);if(!n)throw new Error(`Background job not found: "${e}". Completed and cancelled jobs are evicted from the registry ~5 minutes after they settle. If the jobId looks correct, the job may have already been evicted.`);let r=await n.terminalSettled;return vr(this.traceWriter,{transition:"joined",jobId:e,subagentId:n.subagentId,jobStatus:n.status}),this.emit("joined",this.snapshot(n)),r}markDelivered(e){let n=this.jobs.get(e);!n||n.status==="running"||vr(this.traceWriter,{transition:"delivered",jobId:e,subagentId:n.subagentId,jobStatus:n.status})}async cancelJob(e){let n=this.jobs.get(e);return!n||n.status!=="running"?!1:(n.cancelSource="explicit",await n.handle.cancel(),!0)}async cancelModelJob(e,n){let r=this.jobs.get(e);return!r||r.status!=="running"||r.provenance!=="model"?!1:(r.cancelSource="explicit",r.modelCancelReason=n,await r.handle.cancel(),!0)}async cancelAll(){let e=[...this.jobs.values()].filter(n=>n.status==="running");for(let n of e)n.cancelSource="cascade";await Promise.allSettled(e.map(n=>n.handle.cancel())),await Promise.allSettled(e.map(n=>{let r=new Promise(o=>setTimeout(()=>{let s=n.touchedFiles.length>0?` \u2014 files touched: ${n.touchedFiles.join(", ")}`:"";console.warn(`[BackgroundAgentRegistry] cancelAll: job ${n.jobId} did not settle within ${uF}ms \u2014 continuing teardown${s}`),o()},uF).unref());return Promise.race([n.terminalSettled,r])}))}appendTranscript(e,n){let r=this.jobs.get(e);r&&(r.transcriptTail=dF(r.transcriptTail,n))}getTranscript(e){return this.jobs.get(e)?.transcriptTail}getHandle(e){return this.jobs.get(e)?.handle}getTouchedFiles(e){return this.jobs.get(e)?.touchedFiles}recordTouchedFile(e,n){let r=this.jobs.get(e);if(r)try{let o=JSON.parse(n);if(o!==null&&typeof o=="object"&&"file_path"in o&&typeof o.file_path=="string"){let s=o.file_path;s&&!r.touchedFiles.includes(s)&&r.touchedFiles.push(s)}}catch{}}nextJobId(){return this.counter+=1,`bg-${Date.now().toString(36)}-${this.counter}`}async markTerminal(e,n,r,o){let s=this.jobs.get(e);if(!s||s.status!=="running")return;s.result=n,s.endedAt=Date.now();let i=s.endedAt-s.startedAt;if(s.status=this.statusFromResult(n.status),s.status==="completed"){let c=n.message?.content,l=typeof c=="string"?c:c!==void 0?JSON.stringify(c):"";vr(this.traceWriter,{transition:"completed",jobId:e,subagentId:s.subagentId,durationMs:i,outputBytes:Buffer.byteLength(l,"utf8")}),Gp({event:"subagent.completed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,content_chars:l.length,stop_reason:hn(n.stopReason)}),this.emit("settled",this.snapshot(s))}else if(s.status==="failed"){let c=n.error;vr(this.traceWriter,{transition:"failed",jobId:e,subagentId:s.subagentId,durationMs:i,errorClass:c?.name??"Error",errorMessage:c?.message??"unknown"}),Gp({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,error_message:c?.message,stop_reason:hn(n.stopReason)}),this.emit("settled",this.snapshot(s))}else vr(this.traceWriter,{transition:"cancelled",jobId:e,subagentId:s.subagentId,source:s.cancelSource??"explicit",...s.modelCancelReason!==void 0?{cancelledBy:"model",reason:s.modelCancelReason}:{}}),Gp({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,stop_reason:hn(n.stopReason)}),this.emit("settled",this.snapshot(s));if(s.settle(n),r&&o){let c=s.status,l=s.endedAt;r.writeMeta({...o,status:c,...l!==void 0?{endedAt:l}:{},...hn(n.stopReason)!==void 0?{stopReason:hn(n.stopReason)}:{}}).then(()=>r.close())}setTimeout(()=>{this.jobs.delete(e)},Q7).unref();try{await s.handle.teardown()}catch(c){O(`markTerminal: handle.teardown() failed for job ${e}: ${String(c)}`)}if(s.onCleanup)try{await s.onCleanup()}catch(c){O(`markTerminal: onCleanup failed for job ${e}: ${String(c)}`)}}statusFromResult(e){return e==="succeeded"?"completed":e==="failed"?"failed":e==="cancelled"?"cancelled":"failed"}snapshot(e){return{jobId:e.jobId,provenance:e.provenance,subagentId:e.subagentId,label:e.label,model:e.model,startedAt:e.startedAt,status:e.status,...e.result!==void 0?{result:e.result}:{},...e.endedAt!==void 0?{endedAt:e.endedAt}:{},...e.parentSessionId!==void 0?{parentSessionId:e.parentSessionId}:{}}}}});import{execFile as Z7}from"node:child_process";import{promisify as eZ}from"node:util";async function zp(t,e){try{await sS("git",["-C",t,"worktree","lock","--reason","afk: background-isolated-worktree in use by detached child",e])}catch(n){O(`[isolation] failed to lock worktree for background child: ${String(n)}`)}}async function pF(t,e){await sS("git",["-C",t,"worktree","unlock",e])}async function en(t){try{await sS("git",["-C",t.repoRoot,"worktree","unlock",t.worktreePath])}catch{}return Xd(t)}var sS,Jp=h(()=>{"use strict";oa();se();sS=eZ(Z7)});async function fF(t){let{handle:e,registry:n,prompt:r,model:o,parentSessionId:s,onSettled:i,onCleanup:a,isolationTeardown:c}=t;if(!n)return await e.teardown().catch(u=>O("subagent-executor: handle teardown failed: "+(u instanceof Error?u.message:String(u)))),c&&await en(c).catch(u=>O(`[isolation] background worktree teardown failed (no registry): ${String(u)}`)),i?.(!0),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let l;try{l=n.register({handle:e,prompt:r,model:o??"sonnet",provenance:"model",parentSessionId:s,onCleanup:a})}catch(u){if(u instanceof so)return await e.teardown().catch(p=>O("subagent-executor: handle teardown failed after cap error: "+(p instanceof Error?p.message:String(p)))),c&&await en(c).catch(p=>O(`[isolation] background worktree teardown failed (cap error): ${String(p)}`)),i?.(!0),{content:u.message,isError:!0};throw await e.teardown().catch(p=>O("subagent-executor: handle teardown failed after register error: "+(p instanceof Error?p.message:String(p)))),c&&await en(c).catch(p=>O(`[isolation] background worktree teardown failed (register error): ${String(p)}`)),u}if(i){let u=l.jobId,p=f=>{f.jobId===u&&(n.off("settled",p),i(f.status==="failed"||f.status==="cancelled"))};n.on("settled",p)}let d={status:"running",jobId:l.jobId,subagentId:l.subagentId,label:l.label,message:`Background subagent started (jobId=${l.jobId}). It is running detached; its result will be delivered into this context automatically with the next user message once it finishes. /bgsub:join ${l.jobId} remains available for manual replay.`};return{content:JSON.stringify(d)}}var mF=h(()=>{"use strict";oS();se();Jp()});async function gF(t,e){let n=e.input,r=typeof n.jobId=="string"?n.jobId.trim():"",o=typeof n.reason=="string"?n.reason.trim():"";if(!r||!o)return{content:"cancel_background_job requires non-empty jobId and reason strings.",isError:!0};if(!t)return{content:"Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired.",isError:!0};let s=t.get(r);if(!s){let a=t.list().map(c=>c.jobId);return{content:`Background job not found: "${r}". Currently-known job ids: ${a.length>0?a.join(", "):"(none)"}.`,isError:!0}}return s.status!=="running"?{content:`Background job ${r} is already ${s.status}; nothing to cancel.`}:s.provenance!=="model"?{content:`Refused: background job ${r} was backgrounded by the user. Ask the user to run /bgsub:cancel ${r}.`,isError:!0}:await t.cancelModelJob(r,o)?{content:`Cancellation requested for background job ${r} (${s.label}).`}:{content:`Background job ${r} became terminal before cancellation was issued.`}}var hF=h(()=>{"use strict"});async function yF(t,e,n){let r=e.input,o=typeof r.jobId=="string"?r.jobId.trim():"",s=typeof r.message=="string"?r.message.trim():"";if(!o||!s)return{content:"send_message_to_agent requires non-empty jobId and message strings.",isError:!0};if(!t)return{content:"Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired.",isError:!0};let i=t.get(o);if(!i){let c=t.list().filter(l=>l.provenance==="model").map(l=>l.jobId);return{content:`Background job not found: "${o}". Currently-known job ids: ${c.length>0?c.join(", "):"(none)"}.`,isError:!0}}if(i.provenance!=="model")return{content:`Refused: background job ${o} was backgrounded by the user. Only model-created background jobs can be steered this way.`,isError:!0};if(n&&i.parentSessionId!==n)return{content:`Refused: background job ${o} belongs to a different session.`,isError:!0};if(i.status!=="running")return{content:`Background job ${o} is already ${i.status}; steering message was not delivered.`};let a=t.getHandle(o);if(!a)return{content:`Handle for job "${o}" is not available.`,isError:!0};if(typeof a.session.setBeforeNextRound!="function"){let c=a.session;return{content:`Steering is not supported on ${typeof c.providerName=="string"?c.providerName:"this provider"}. The message was not delivered. Use a model backed by the Anthropic provider to enable send_message_to_agent.`,isError:!0}}return a.steer(s),{content:`Steering message queued for background job ${o}.`}}var bF=h(()=>{"use strict"});function SF(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function tZ(t){if(SF(t)<=16384)return t;let e=Array.from(t),n=s=>SF(e.slice(0,s).join("")+wF)<=16384,r=0,o=e.length;for(;r<o;){let s=Math.ceil((r+o)/2);n(s)?r=s:o=s-1}return e.slice(0,r).join("")+wF}function nZ(t){return tZ(t)}function kF(t){if(!(t===void 0||t.claimed)&&t.text.trim().length!==0)return t.claimed=!0,nZ(t.text)}var wF,vF=h(()=>{"use strict";wF=`
|
|
1278
1278
|
\u2026 [truncated at 16384 bytes]`});import{mkdirSync as rZ,writeFileSync as oZ}from"node:fs";import{basename as TF,join as EF}from"node:path";function sZ(){let t=k.AFK_SUBAGENT_RESULT_CAP_BYTES;if(t===void 0||t==="")return _F;let e=parseInt(t,10);if(Number.isNaN(e)||e<0)return _F;if(e!==0)return e}function iZ(t,e,n){try{let r=EF(ce(),TF(t),"subagent-handoffs");rZ(r,{recursive:!0});let o=EF(r,`${TF(e)}.txt`);return oZ(o,n,"utf8"),o}catch{return}}function AF(t,e,n){let r=sZ();if(r===void 0)return{content:t,capped:!1};let o=Buffer.byteLength(t,"utf8");if(o<=r)return{content:t,capped:!1};let s=e!==void 0?iZ(e,n,t):void 0,i=s!==void 0?`
|
|
1279
1279
|
|
|
1280
1280
|
[Subagent output was ${o} bytes \u2014 full result at ${s}. Use read_file to retrieve it.]`:`
|
|
1281
1281
|
|
|
1282
1282
|
[Subagent output was ${o} bytes \u2014 truncated to ${r} bytes. Full output could not be written to disk.]`,a=Buffer.byteLength(i,"utf8"),c=Math.max(r-a,Math.floor(r*.5));return{content:_t(t,c)+i,capped:!0}}var _F,xF=h(()=>{"use strict";B();Ht();F();_F=32768});function RF(t,e,n){return!e||!n||e===n?t:`[subagent result \xB7 model=${e} (parent: ${n})]
|
|
1283
1283
|
|
|
1284
|
-
${t}`}var IF=h(()=>{"use strict"});async function CF(t){let{handle:e,signal:n,prompt:r,backgroundPrompt:o,idPrefix:s,model:i,parentModel:a,childManager:c,identity:l,traceWriter:d,depth:u,parentSessionId:p,registry:f,promotionTriggers:m,activeForegroundHandles:g}=t,y=()=>{e.cancel()};n.addEventListener("abort",y,{once:!0});let b=Date.now(),w=!1,v,_=new Promise(T=>{v=T}),x,A=new Promise(T=>{x=T});m.set(e.id,{fire:v,ready:A}),g.set(e.id,e);let I,C=e.runToResult(r);try{let T=await Promise.race([C.then(M=>({kind:"result",result:M})),_.then(M=>({kind:"promote",queuedNote:M}))]);if(T.kind==="promote")if(f){let M=t.isolationTeardown;try{M&&await zp(M.repoRoot,M.worktreePath);let N=f.adoptRunning({handle:e,runPromise:C,prompt:o,model:i??"sonnet",provenance:"user",parentSessionId:p,...M?{onCleanup:async()=>{let K=await en(M);
|
|
1284
|
+
${t}`}var IF=h(()=>{"use strict"});async function CF(t){let{handle:e,signal:n,prompt:r,backgroundPrompt:o,idPrefix:s,model:i,parentModel:a,childManager:c,identity:l,traceWriter:d,depth:u,parentSessionId:p,registry:f,promotionTriggers:m,activeForegroundHandles:g}=t,y=()=>{e.cancel()};n.addEventListener("abort",y,{once:!0});let b=Date.now(),w=!1,v,_=new Promise(T=>{v=T}),x,A=new Promise(T=>{x=T});m.set(e.id,{fire:v,ready:A}),g.set(e.id,e);let I,C=e.runToResult(r);try{let T=await Promise.race([C.then(M=>({kind:"result",result:M})),_.then(M=>({kind:"promote",queuedNote:M}))]);if(T.kind==="promote")if(f){let M=t.isolationTeardown;try{M&&await zp(M.repoRoot,M.worktreePath);let N=f.adoptRunning({handle:e,runPromise:C,prompt:o,model:i??"sonnet",provenance:"user",parentSessionId:p,...M?{onCleanup:async()=>{let K=await en(M);O(`background worktree teardown: ${JSON.stringify(K)}`)}}:{}});w=!0,n.removeEventListener("abort",y),x({jobId:N.jobId,label:N.label,sharesWorktree:!M});let $={status:"running",jobId:N.jobId,subagentId:N.subagentId,label:N.label,message:`Subagent backgrounded by user (jobId=${N.jobId}). It keeps running detached; its result will be delivered into this context automatically with the next user message once it finishes. /bgsub:join ${N.jobId} remains available for manual replay.`},U=kF(T.queuedNote);return U!==void 0&&await Wl(d,{jobId:N.jobId,subagentId:N.subagentId,byteLength:Buffer.byteLength(U,"utf8")}),{content:JSON.stringify($),...U!==void 0?{harnessUserMessage:{kind:"queued_user_message",text:U}}:{}}}catch(N){if(O("subagent-executor: promotion failed, staying foreground: "+(N instanceof Error?N.message:String(N))),M)try{await pF(M.repoRoot,M.worktreePath)}catch($){O(`[isolation] failed to unlock worktree after promotion failure: ${String($)}`)}x(null)}}else x(null);let R=T.kind==="result"?T.result:await C;if(R.status==="succeeded"&&R.message){let M=R.message.content,N=typeof M=="string"?M:JSON.stringify(M),$=R.trace;ks({...l,event:"subagent.completed",subagent_id:e.id,parent_session_id:p,status:R.status,duration_ms:Date.now()-b,content_chars:N.length,stop_reason:hn(R.stopReason),depth:u,tool_call_count:$?.toolCalls.length,thinking_present:$?.thinkingPresent,tool_names:$?.toolCalls.length?JSON.stringify([...new Set($.toolCalls.map(Y=>Y.name))]):void 0});let U=RF(Es(N,R.stopReason),i,a),{content:j,capped:K}=AF(U,p,e.id);return I={content:j,...Zn(R.stopReason),...K?{truncated:!0}:{}},I}let E=R.error?.message??"Subagent failed with no output",P=R.trace;ks({...l,event:"subagent.failed",subagent_id:e.id,id_prefix:s,parent_session_id:p,status:R.status,duration_ms:Date.now()-b,error_message:gn(E),schema_error:R.schemaError?gn(R.schemaError.message):void 0,partial_output_chars:tS(R.partialOutput),stop_reason:hn(R.stopReason),depth:u,tool_call_count:P?.toolCalls.length,thinking_present:P?.thinkingPresent,tool_names:P?.toolCalls.length?JSON.stringify([...new Set(P.toolCalls.map(M=>M.name))]):void 0});let H=qD({status:R.status,errorMessage:E,schemaErrorMessage:R.schemaError?.message,partialOutput:R.partialOutput,subagentId:e.id});return I={content:JSON.stringify(H),isError:!0,...Zn(R.stopReason)},I}catch(T){let R=T instanceof Error?T.message:String(T);throw ks({...l,event:"subagent.failed",subagent_id:e.id,id_prefix:s,parent_session_id:p,status:"failed",duration_ms:Date.now()-b,error_message:gn(R),depth:u}),T}finally{if(m.delete(e.id),g.delete(e.id),x(null),!w){n.removeEventListener("abort",y),await c?.teardownAll(),await e.teardown({deferInjectContextToCaller:!0});let T=e.getLastStopInjectContext?.();if(Rp(I,T),t.isolationTeardown){let{repoRoot:R,worktreePath:E}=t.isolationTeardown,P=await Xd({repoRoot:R,worktreePath:E});P.preserved&&O(`[isolation] preserved worktree ${E} (${P.reason?Ry(P.reason):"unknown"}) \u2014 locked so the sweep will not reap it; recover via the worktree tool`)}}}}var PF=h(()=>{"use strict";Re();se();J();Hp();Cw();vF();xF();oa();Jp();IF()});function lZ(t){return t.isError===!0&&t.incompleteReason===Ts}async function MF(t){let e=t.maxRedispatch??aZ,n=t.delayMs??cZ,r=await t.dispatch(0);for(let o=1;o<=e;o+=1){if(!lZ(r)||t.signal.aborted||t.canRedispatch!==void 0&&!t.canRedispatch()||(n>0&&await We(n,t.signal),t.signal.aborted)||t.canRedispatch!==void 0&&!t.canRedispatch())return r;t.onRedispatch?.(o),r=await t.dispatch(o)}return r}var aZ,cZ,OF=h(()=>{"use strict";Bn();Re();aZ=1,cZ=1e3});function Vp(t,e){for(let n of e??[])t.push({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.bytes.toString("base64")}})}var iS=h(()=>{"use strict"});import{readFile as dZ,stat as uZ}from"node:fs/promises";import{extname as pZ,isAbsolute as fZ}from"node:path";function FF(){return new Error(`Agent tool image attachments exceed the ${aS} byte (5 MiB) total limit`)}async function LF(t){if(t.paths.length>DF)throw new Error(`Agent tool supports at most ${DF} image attachments per dispatch`);let e={...t.resolveBase!==void 0?{resolveBase:t.resolveBase}:{},...t.readRoots!==void 0?{readRoots:t.readRoots}:{}},n=[],r=0;for(let o of t.paths){let s;if(!fZ(o)&&(s=t.sessionId===void 0?void 0:t.registry?.get(t.sessionId,o),s===void 0)){let u=t.sessionId===void 0?[]:t.registry?.listIds(t.sessionId)??[];throw new Error(`Unknown inbound image id ${JSON.stringify(o)}; available ids for this session: `+(u.length>0?u.join(", "):"(none)"))}let i=s?.path??o,a=s?.mediaType??mZ.get(pZ(i).toLowerCase());if(a===void 0)throw new Error(`Unsupported image attachment ${JSON.stringify(o)}; expected .jpg, .jpeg, .png, .gif, or .webp`);let c=s===void 0?de(i,e,"read"):i;if(r+(await uZ(c)).size>aS)throw FF();let d=await dZ(c);if(r+=d.byteLength,r>aS)throw FF();n.push({mediaType:a,bytes:d})}return n}var DF,aS,mZ,NF=h(()=>{"use strict";Ae();DF=8,aS=5*1024*1024,mZ=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".gif","image/gif"],[".webp","image/webp"]])});import{createHash as gZ}from"node:crypto";import{mkdir as hZ,writeFile as yZ}from"node:fs/promises";import{join as bZ}from"node:path";function kZ(t){return gZ("sha256").update(t).digest("hex")}function vZ(t,e,n){let r=Math.max(1,Math.round(n/1024));return`[image ${t} \xB7 ${e} \xB7 ${r} KB]`}async function $F(t,e,n,r=io){for(let o of n){let s=await r.put(e,o.bytes,o.mediaType);t.push({type:"text",text:vZ(s.id,s.mediaType,s.sizeBytes)}),Vp(t,[o])}}function TZ(t){switch(t){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp"}}var wZ,SZ,cS,io,Ga=h(()=>{"use strict";B();iS();wZ=6,SZ=new Map;cS=class{constructor(e=SZ,n=kZ){this.entries=e;this.hashBytes=n}entries;hashBytes;get(e,n){return this.entries.get(e)?.get(n)}listIds(e){return[...this.entries.get(e)?.keys()??[]].sort()}clear(e){this.entries.delete(e)}async put(e,n,r){let o=this.hashBytes(n),s=this.entries.get(e)??new Map;this.entries.set(e,s);let i=wZ,a=0;for(;;){let c=`img_${o.slice(0,i)}`,l=a===0?c:`${c}_${a}`,d=s.get(l);if(d===void 0){let u=xm(e);await hZ(u,{recursive:!0});let p=bZ(u,`${l}${TZ(r)}`);await yZ(p,n);let f={path:p,mediaType:r,sizeBytes:n.byteLength,digest:o};return s.set(l,f),{id:l,...f}}if(d.mediaType===r&&d.digest===o)return{id:l,...d};i<o.length?i=Math.min(o.length,i+2):a+=1}}};io=new cS});function UF(t,e,n,r,o,s){let i="";return e&&!s(t)&&(i+=`WARNING: child model ${t} is not vision-capable; attached images were dropped.
|
|
1285
1285
|
|
|
1286
1286
|
`),!o&&n!==void 0&&EZ.test(r)&&(i+=`WARNING: ${n} is read-only \u2014 write instructions were ignored. Findings are in the message below, not a file. Use a general-purpose agent when the task requires file output.
|
|
1287
1287
|
|
|
1288
|
-
`),i}var EZ,BF=h(()=>{"use strict";EZ=/\b(write|save|persist|create|output|emit|dump|generate)\s+(a\s+)?(\w+\s+)?(file|report|artifact|doc|document|markdown|\.md)\b|\b(write|save|persist|create|output|emit|dump|generate)\s{1,5}.{0,40}\.(md|json|txt|ts|js|yaml|yml|csv|html)\b/i});var As,lS=h(()=>{"use strict";we();Zr();Ot();Up();et();ur();WD();Hp();YD();mF();hF();bF();PF();oa();Jp();OF();ie();iS();yr();NF();Ga();Rt();_p();BF();fl();F();Ot();As=class t{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;currentCwd;isolationCounter=0;setCwd(e){this.currentCwd=e,this.ctx.subagentManager.setCwd(e)}setTraceWriter(e){this.ctx.traceWriter=e,this.ctx.subagentManager.setTraceWriter(e)}describeAgentTool(){return qw(this.ctx.agentRegistry)}promotionTriggers=new Map;activeForegroundHandles=new Map;currentWaveId=void 0;currentWaveCallIds=new Set;notifyWaveStart(e,n,r){if(k.AFK_WAVE_MANIFEST_DISABLED!=="1"&&!(e.length<2)&&this.ctx.depth===0)try{let o=e.map(i=>{let a;try{a=eS(i.input)}catch{a=void 0}let c=a?.prompt??"",l=a?.model??"sonnet",d=a?.cwd??this.currentCwd;return ll({id:i.id,prompt:c,cwd:d,model:l})}),s=dl({source:"agent-tool",parentSessionId:n,traceLabel:r,units:o});s!==void 0&&(this.currentWaveId=s,this.currentWaveCallIds=new Set(e.map(i=>i.id)))}catch{}}notifyWaveEnd(){this.currentWaveId=void 0,this.currentWaveCallIds=new Set}updateCurrentWaveUnit(e,n,r,o){let s=this.currentWaveId;if(s===void 0||!this.currentWaveCallIds.has(e))return;let i=r!==void 0||o!==void 0?{...r!==void 0?{errorMessage:r}:{},...o!==void 0?{cwd:o}:{}}:void 0;pr(s,e,n,i)}supportsBackgroundJobs(){return this.ctx.backgroundRegistry!==void 0}hasPromotableForeground(){return this.supportsBackgroundJobs()&&this.promotionTriggers.size>0}async cancelBackgroundJob(e){return gF(this.ctx.backgroundRegistry,e)}async sendMessageToAgent(e){return yF(this.ctx.backgroundRegistry,e,this.ctx.parentSession.sessionId)}hasActiveForeground(){return this.activeForegroundHandles.size>0}cancelGeneration=0;async cancelActiveForeground(){this.cancelGeneration+=1;let e=[...this.activeForegroundHandles.values()];return e.length===0?0:(await Promise.all(e.map(n=>n.cancel().catch(()=>{}))),e.length)}async promoteActiveForeground(e){let n=[...this.promotionTriggers.values()];return n.forEach(o=>o.fire(e)),(await Promise.all(n.map(o=>o.ready))).filter(o=>o!==null)}getSubagentsLite(){let e=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:e,backgroundJobs:n}}async execute(e){let n={sideEffectFree:!1},r=this.cancelGeneration;return MF({dispatch:o=>this.executeOnce(e,n,o>0?r:void 0),signal:e.signal,canRedispatch:()=>n.sideEffectFree&&this.cancelGeneration===r,onRedispatch:o=>{D(`subagent-executor: read-only child stream cut with zero output; re-dispatching a fresh fork (attempt ${o+1})`)}})}async executeOnce(e,n,r){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let o;try{o=eS(e.input)}catch(A){return{content:`Agent tool input validation failed: ${A instanceof Error?A.message:String(A)}`,isError:!0}}let s;if(o.agent_type!==void 0&&(s=this.ctx.agentRegistry?.get(o.agent_type),s===void 0)){let A=[...this.ctx.agentRegistry?.keys()??[]].sort().join(", ");return{content:`Agent type "${o.agent_type}" not found. Available agent types: ${A.length>0?A:"(none)"}`,isError:!0}}let i=this.ctx.nestedAgentAllowlist;if(i!==void 0){let A=o.agent_type;if(A===void 0||!i.includes(A))return{content:i.length===0?"This agent is not permitted to dispatch any nested agents (its definition granted the dispatch tool but named zero allowed types, e.g. `Agent()`). Complete the task with your own tools.":`This agent may only dispatch the following agent type(s): ${i.join(", ")}. `+(A===void 0?"A bare dispatch with no agent_type is not permitted here \u2014 set agent_type to one of the allowed types, or complete the task with your own tools.":`agent_type "${A}" is out of scope.`),isError:!0}}let a=this.ctx.depth,c=this.ctx.maxDepth??tn(),l=this.ctx.surface!==void 0?{origin:wn(this.ctx.surface),actor:Sn(a)}:{};if(a>=c)return ne({...l,event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:a,...o.agent_type!==void 0?{requested_name:o.agent_type}:{}}).catch(()=>{}),{content:tD(a,c),isError:!0};let d=this.ctx.subagentManager.getReadScopeInputs?.()??{parentReadRoots:void 0,parentCwd:void 0},u=Ea({parentReadRoots:d.parentReadRoots,parentCwd:d.parentCwd,childCwd:o.cwd??this.currentCwd}),{childConfig:p,childParentSession:f,childManager:m,childWriteCapable:g,childSideEffectFree:y}=VD({parsed:o,namedAgent:s,depth:a,maxDepth:c,currentCwd:this.currentCwd,...u!==void 0?{childInheritedReadRoots:u}:{},signal:e.signal,defaultConfig:this.ctx.defaultConfig,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,...this.ctx.childProviderFactory!==void 0?{childProviderFactory:this.ctx.childProviderFactory}:{},...this.ctx.childSkillExecutorFactory!==void 0?{childSkillExecutorFactory:this.ctx.childSkillExecutorFactory}:{},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash!==void 0?{readOnlyBash:this.ctx.readOnlyBash}:{},...this.ctx.agentRegistry!==void 0?{agentRegistry:this.ctx.agentRegistry}:{},...this.ctx.parentModel!==void 0?{parentModel:this.ctx.parentModel}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.workspaceStore!==void 0?{workspaceStore:this.ctx.workspaceStore}:{},createChildExecutor:A=>new t(A)});n!==void 0&&(n.sideEffectFree=y);let b;if(o.isolation==="worktree")if(!g)D(`[isolation] skipped worktree for read-only ${o.agent_type??"generic"}`);else{let A=this.currentCwd??process.cwd();try{let I=await wI({cwd:A,slugHint:`iso-${o.id_prefix}-${++this.isolationCounter}-${Math.random().toString(36).slice(2,8)}`});p.cwd=I.path,b={repoRoot:I.repoRoot,worktreePath:I.path},o.mode==="background"&&await zp(I.repoRoot,I.path)}catch(I){return{content:`Failed to create isolated worktree for the subagent: ${I instanceof Error?I.message:String(I)}. isolation:"worktree" requires the dispatching session to run inside a git repository.`,isError:!0}}}o.mode==="background"&&p.timeoutMs===void 0&&(p.timeoutMs=dS);let w;try{if(w=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:p,idPrefix:o.id_prefix,agentType:s!==void 0?s.name:o.id_prefix&&o.id_prefix!=="agent-tool"?ve(o.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":ve(o.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",...s!==void 0?{resolvedAgentType:s.name}:{},promptHead:ve(o.prompt).replace(/[\r\n]+/g," ").slice(0,80).trim(),denyElicitations:!0,progressEvents:o.progress_events}),f!==void 0&&(f.sessionId=w.id),this.updateCurrentWaveUnit(e.id,"running",void 0,b!==void 0?p.cwd:void 0),r!==void 0&&this.cancelGeneration!==r)return await m?.teardownAll(),await w.cancel(),b&&o.mode==="background"&&await en(b).catch(A=>D(`[isolation] background worktree teardown failed after cancel: ${String(A)}`)),{content:"Agent tool call aborted",isError:!0}}catch(A){let I=A instanceof Error?A.message:String(A);return this.updateCurrentWaveUnit(e.id,"failed",I),ks({...l,event:"subagent.failed",subagent_id:"unknown",id_prefix:o.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:gn(I),depth:a}),b&&o.mode==="background"&&await en(b).catch(C=>D(`[isolation] background worktree teardown failed after fork error: ${String(C)}`)),{content:`Failed to fork subagent: ${I}`,isError:!0}}if(o.mode==="background"){let A=this.currentWaveId,I=e.id;return fF({handle:w,registry:this.ctx.backgroundRegistry,prompt:o.prompt,model:p.model,parentSessionId:this.ctx.parentSession.sessionId,onSettled:A!==void 0?C=>pr(A,I,C?"failed":"done"):void 0,onCleanup:b?async()=>{let C=await en(b);D(`background worktree teardown: ${JSON.stringify(C)}`)}:void 0,isolationTeardown:b})}let v=o.prompt;if(o.attachments!==void 0){let A;try{A=await LF({paths:o.attachments,resolveBase:d.parentCwd??this.currentCwd??d.parentReadRoots?.[0],readRoots:d.parentReadRoots,sessionId:this.ctx.parentSession.sessionId,registry:this.ctx.inboundAttachmentRegistry??io})}catch(C){return await w.teardown().catch(()=>{}),{content:`Agent tool attachment resolution failed: ${C instanceof Error?C.message:String(C)}`,isError:!0}}let I=[{type:"text",text:o.prompt}];Vp(I,A),v=I}let _=await CF({handle:w,signal:e.signal,prompt:v,backgroundPrompt:o.prompt,idPrefix:o.id_prefix,model:p.model,...this.ctx.parentModel!==void 0?{parentModel:this.ctx.parentModel}:{},childManager:m,identity:l,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},depth:a,parentSessionId:this.ctx.parentSession.sessionId,registry:this.ctx.backgroundRegistry,promotionTriggers:this.promotionTriggers,activeForegroundHandles:this.activeForegroundHandles,...b!==void 0?{isolationTeardown:b}:{}}),x=UF(p.model,o.attachments!==void 0,s?.name,o.prompt,g,Al);return x&&!_.isError&&(_.content=x+_.content),_.isError===!0?this.updateCurrentWaveUnit(e.id,"failed",typeof _.content=="string"?_.content.slice(0,500):void 0):this.updateCurrentWaveUnit(e.id,"done"),_}}});function uS(t,e,n,r=!1,o){let{ctx:s,currentCwd:i}=t,a=s.depth??0,c=s.maxDepth??tn(),l={...e},d=r&&o!==void 0?o.filter(b=>Qp.includes(b)):r?[...Qp]:o,u=r;if(!s.childProviderFactory||a>=c)return r?l.provider=HF(l.model,s.openaiBaseUrl,d):d!==void 0&&(l.provider=Wp(d,l.model,u,s.openaiBaseUrl)),{childConfig:l,childManager:void 0};let p=Gn(s.getReadScopeInputs?.(),i),f=new V({parentAbortSignal:n,...s.traceWriter!==void 0?{traceWriter:s.traceWriter}:{},...s.surface!==void 0?{surface:s.surface}:{},...i!==void 0?{cwd:i}:{},...p!==void 0?{parentReadRoots:p}:{},...s.workspaceStore!==void 0?{workspaceStore:s.workspaceStore}:{}}),m=new As({subagentManager:f,parentSession:Ka(n),defaultConfig:{model:l.model,apiKey:s.apiKey,...s.baseUrl!==void 0?{baseUrl:s.baseUrl}:{},...s.openaiBaseUrl!==void 0?{openaiBaseUrl:s.openaiBaseUrl}:{},...s.xaiBaseUrl!==void 0?{xaiBaseUrl:s.xaiBaseUrl}:{},...e.skillDispatchName!==void 0?{skillDispatchName:e.skillDispatchName}:{}},...s.surface!==void 0?{surface:s.surface}:{},defaultSubagentModel:s.defaultSubagentModel,childProviderFactory:s.childProviderFactory,childSkillExecutorFactory:s.childSkillExecutorFactory,...s.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:s.resolveApiKeyForModel}:{},depth:a+1,maxDepth:c,...i!==void 0?{cwd:i}:{},...s.traceWriter!==void 0?{traceWriter:s.traceWriter}:{},...s.workspaceStore!==void 0?{workspaceStore:s.workspaceStore}:{},...s.backgroundRegistry!==void 0?{backgroundRegistry:s.backgroundRegistry}:{},...d!==void 0?{allowedTools:d}:{},...u?{readOnlyBash:!0}:{},...s.agentRegistry!==void 0?{agentRegistry:s.agentRegistry}:{},...l.model!==void 0?{parentModel:l.model}:{}}),g={parentReadRoots:p,parentCwd:i},y=s.childSkillExecutorFactory?s.childSkillExecutorFactory(a+1,c,n,i,g,e.skillDispatchName):void 0;return l.provider=s.childProviderFactory({childExecutor:m,...y!==void 0?{childSkillExecutor:y}:{},...l.model!==void 0?{model:l.model}:{},...d!==void 0?{allowedTools:d}:{},...u?{readOnlyBash:!0}:{}}),{childConfig:l,childManager:f}}var jF=h(()=>{"use strict";we();Zr();Ot();lS()});function AZ(t){return`[skill failed: ${t} \u2014 partial output preserved below]`}function xZ(t){let e=t.partialOutput;return typeof e=="string"&&e.length>0?e:void 0}function WF(t,e){let n=Tr(`${t}
|
|
1288
|
+
`),i}var EZ,BF=h(()=>{"use strict";EZ=/\b(write|save|persist|create|output|emit|dump|generate)\s+(a\s+)?(\w+\s+)?(file|report|artifact|doc|document|markdown|\.md)\b|\b(write|save|persist|create|output|emit|dump|generate)\s{1,5}.{0,40}\.(md|json|txt|ts|js|yaml|yml|csv|html)\b/i});var As,lS=h(()=>{"use strict";we();Zr();Ot();Up();et();ur();WD();Hp();YD();mF();hF();bF();PF();oa();Jp();OF();se();iS();yr();NF();Ga();Rt();_p();BF();fl();F();Ot();As=class t{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;currentCwd;isolationCounter=0;setCwd(e){this.currentCwd=e,this.ctx.subagentManager.setCwd(e)}setTraceWriter(e){this.ctx.traceWriter=e,this.ctx.subagentManager.setTraceWriter(e)}describeAgentTool(){return qw(this.ctx.agentRegistry)}promotionTriggers=new Map;activeForegroundHandles=new Map;currentWaveId=void 0;currentWaveCallIds=new Set;notifyWaveStart(e,n,r){if(k.AFK_WAVE_MANIFEST_DISABLED!=="1"&&!(e.length<2)&&this.ctx.depth===0)try{let o=e.map(i=>{let a;try{a=eS(i.input)}catch{a=void 0}let c=a?.prompt??"",l=a?.model??"sonnet",d=a?.cwd??this.currentCwd;return ll({id:i.id,prompt:c,cwd:d,model:l})}),s=dl({source:"agent-tool",parentSessionId:n,traceLabel:r,units:o});s!==void 0&&(this.currentWaveId=s,this.currentWaveCallIds=new Set(e.map(i=>i.id)))}catch{}}notifyWaveEnd(){this.currentWaveId=void 0,this.currentWaveCallIds=new Set}updateCurrentWaveUnit(e,n,r,o){let s=this.currentWaveId;if(s===void 0||!this.currentWaveCallIds.has(e))return;let i=r!==void 0||o!==void 0?{...r!==void 0?{errorMessage:r}:{},...o!==void 0?{cwd:o}:{}}:void 0;pr(s,e,n,i)}supportsBackgroundJobs(){return this.ctx.backgroundRegistry!==void 0}hasPromotableForeground(){return this.supportsBackgroundJobs()&&this.promotionTriggers.size>0}async cancelBackgroundJob(e){return gF(this.ctx.backgroundRegistry,e)}async sendMessageToAgent(e){return yF(this.ctx.backgroundRegistry,e,this.ctx.parentSession.sessionId)}hasActiveForeground(){return this.activeForegroundHandles.size>0}cancelGeneration=0;async cancelActiveForeground(){this.cancelGeneration+=1;let e=[...this.activeForegroundHandles.values()];return e.length===0?0:(await Promise.all(e.map(n=>n.cancel().catch(()=>{}))),e.length)}async promoteActiveForeground(e){let n=[...this.promotionTriggers.values()];return n.forEach(o=>o.fire(e)),(await Promise.all(n.map(o=>o.ready))).filter(o=>o!==null)}getSubagentsLite(){let e=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:e,backgroundJobs:n}}async execute(e){let n={sideEffectFree:!1},r=this.cancelGeneration;return MF({dispatch:o=>this.executeOnce(e,n,o>0?r:void 0),signal:e.signal,canRedispatch:()=>n.sideEffectFree&&this.cancelGeneration===r,onRedispatch:o=>{O(`subagent-executor: read-only child stream cut with zero output; re-dispatching a fresh fork (attempt ${o+1})`)}})}async executeOnce(e,n,r){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let o;try{o=eS(e.input)}catch(A){return{content:`Agent tool input validation failed: ${A instanceof Error?A.message:String(A)}`,isError:!0}}let s;if(o.agent_type!==void 0&&(s=this.ctx.agentRegistry?.get(o.agent_type),s===void 0)){let A=[...this.ctx.agentRegistry?.keys()??[]].sort().join(", ");return{content:`Agent type "${o.agent_type}" not found. Available agent types: ${A.length>0?A:"(none)"}`,isError:!0}}let i=this.ctx.nestedAgentAllowlist;if(i!==void 0){let A=o.agent_type;if(A===void 0||!i.includes(A))return{content:i.length===0?"This agent is not permitted to dispatch any nested agents (its definition granted the dispatch tool but named zero allowed types, e.g. `Agent()`). Complete the task with your own tools.":`This agent may only dispatch the following agent type(s): ${i.join(", ")}. `+(A===void 0?"A bare dispatch with no agent_type is not permitted here \u2014 set agent_type to one of the allowed types, or complete the task with your own tools.":`agent_type "${A}" is out of scope.`),isError:!0}}let a=this.ctx.depth,c=this.ctx.maxDepth??tn(),l=this.ctx.surface!==void 0?{origin:wn(this.ctx.surface),actor:Sn(a)}:{};if(a>=c)return ne({...l,event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:a,...o.agent_type!==void 0?{requested_name:o.agent_type}:{}}).catch(()=>{}),{content:tD(a,c),isError:!0};let d=this.ctx.subagentManager.getReadScopeInputs?.()??{parentReadRoots:void 0,parentCwd:void 0},u=Ea({parentReadRoots:d.parentReadRoots,parentCwd:d.parentCwd,childCwd:o.cwd??this.currentCwd}),{childConfig:p,childParentSession:f,childManager:m,childWriteCapable:g,childSideEffectFree:y}=VD({parsed:o,namedAgent:s,depth:a,maxDepth:c,currentCwd:this.currentCwd,...u!==void 0?{childInheritedReadRoots:u}:{},signal:e.signal,defaultConfig:this.ctx.defaultConfig,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,...this.ctx.childProviderFactory!==void 0?{childProviderFactory:this.ctx.childProviderFactory}:{},...this.ctx.childSkillExecutorFactory!==void 0?{childSkillExecutorFactory:this.ctx.childSkillExecutorFactory}:{},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash!==void 0?{readOnlyBash:this.ctx.readOnlyBash}:{},...this.ctx.agentRegistry!==void 0?{agentRegistry:this.ctx.agentRegistry}:{},...this.ctx.parentModel!==void 0?{parentModel:this.ctx.parentModel}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.workspaceStore!==void 0?{workspaceStore:this.ctx.workspaceStore}:{},createChildExecutor:A=>new t(A)});n!==void 0&&(n.sideEffectFree=y);let b;if(o.isolation==="worktree")if(!g)O(`[isolation] skipped worktree for read-only ${o.agent_type??"generic"}`);else{let A=this.currentCwd??process.cwd();try{let I=await wI({cwd:A,slugHint:`iso-${o.id_prefix}-${++this.isolationCounter}-${Math.random().toString(36).slice(2,8)}`});p.cwd=I.path,b={repoRoot:I.repoRoot,worktreePath:I.path},o.mode==="background"&&await zp(I.repoRoot,I.path)}catch(I){return{content:`Failed to create isolated worktree for the subagent: ${I instanceof Error?I.message:String(I)}. isolation:"worktree" requires the dispatching session to run inside a git repository.`,isError:!0}}}o.mode==="background"&&p.timeoutMs===void 0&&(p.timeoutMs=dS);let w;try{if(w=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:p,idPrefix:o.id_prefix,agentType:s!==void 0?s.name:o.id_prefix&&o.id_prefix!=="agent-tool"?ve(o.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":ve(o.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",...s!==void 0?{resolvedAgentType:s.name}:{},promptHead:ve(o.prompt).replace(/[\r\n]+/g," ").slice(0,80).trim(),denyElicitations:!0,progressEvents:o.progress_events}),f!==void 0&&(f.sessionId=w.id),this.updateCurrentWaveUnit(e.id,"running",void 0,b!==void 0?p.cwd:void 0),r!==void 0&&this.cancelGeneration!==r)return await m?.teardownAll(),await w.cancel(),b&&o.mode==="background"&&await en(b).catch(A=>O(`[isolation] background worktree teardown failed after cancel: ${String(A)}`)),{content:"Agent tool call aborted",isError:!0}}catch(A){let I=A instanceof Error?A.message:String(A);return this.updateCurrentWaveUnit(e.id,"failed",I),ks({...l,event:"subagent.failed",subagent_id:"unknown",id_prefix:o.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:gn(I),depth:a}),b&&o.mode==="background"&&await en(b).catch(C=>O(`[isolation] background worktree teardown failed after fork error: ${String(C)}`)),{content:`Failed to fork subagent: ${I}`,isError:!0}}if(o.mode==="background"){let A=this.currentWaveId,I=e.id;return fF({handle:w,registry:this.ctx.backgroundRegistry,prompt:o.prompt,model:p.model,parentSessionId:this.ctx.parentSession.sessionId,onSettled:A!==void 0?C=>pr(A,I,C?"failed":"done"):void 0,onCleanup:b?async()=>{let C=await en(b);O(`background worktree teardown: ${JSON.stringify(C)}`)}:void 0,isolationTeardown:b})}let v=o.prompt;if(o.attachments!==void 0){let A;try{A=await LF({paths:o.attachments,resolveBase:d.parentCwd??this.currentCwd??d.parentReadRoots?.[0],readRoots:d.parentReadRoots,sessionId:this.ctx.parentSession.sessionId,registry:this.ctx.inboundAttachmentRegistry??io})}catch(C){return await w.teardown().catch(()=>{}),{content:`Agent tool attachment resolution failed: ${C instanceof Error?C.message:String(C)}`,isError:!0}}let I=[{type:"text",text:o.prompt}];Vp(I,A),v=I}let _=await CF({handle:w,signal:e.signal,prompt:v,backgroundPrompt:o.prompt,idPrefix:o.id_prefix,model:p.model,...this.ctx.parentModel!==void 0?{parentModel:this.ctx.parentModel}:{},childManager:m,identity:l,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},depth:a,parentSessionId:this.ctx.parentSession.sessionId,registry:this.ctx.backgroundRegistry,promotionTriggers:this.promotionTriggers,activeForegroundHandles:this.activeForegroundHandles,...b!==void 0?{isolationTeardown:b}:{}}),x=UF(p.model,o.attachments!==void 0,s?.name,o.prompt,g,Al);return x&&!_.isError&&(_.content=x+_.content),_.isError===!0?this.updateCurrentWaveUnit(e.id,"failed",typeof _.content=="string"?_.content.slice(0,500):void 0):this.updateCurrentWaveUnit(e.id,"done"),_}}});function uS(t,e,n,r=!1,o){let{ctx:s,currentCwd:i}=t,a=s.depth??0,c=s.maxDepth??tn(),l={...e},d=r&&o!==void 0?o.filter(b=>Qp.includes(b)):r?[...Qp]:o,u=r;if(!s.childProviderFactory||a>=c)return r?l.provider=HF(l.model,s.openaiBaseUrl,d):d!==void 0&&(l.provider=Wp(d,l.model,u,s.openaiBaseUrl)),{childConfig:l,childManager:void 0};let p=Gn(s.getReadScopeInputs?.(),i),f=new V({parentAbortSignal:n,...s.traceWriter!==void 0?{traceWriter:s.traceWriter}:{},...s.surface!==void 0?{surface:s.surface}:{},...i!==void 0?{cwd:i}:{},...p!==void 0?{parentReadRoots:p}:{},...s.workspaceStore!==void 0?{workspaceStore:s.workspaceStore}:{}}),m=new As({subagentManager:f,parentSession:Ka(n),defaultConfig:{model:l.model,apiKey:s.apiKey,...s.baseUrl!==void 0?{baseUrl:s.baseUrl}:{},...s.openaiBaseUrl!==void 0?{openaiBaseUrl:s.openaiBaseUrl}:{},...s.xaiBaseUrl!==void 0?{xaiBaseUrl:s.xaiBaseUrl}:{},...e.skillDispatchName!==void 0?{skillDispatchName:e.skillDispatchName}:{}},...s.surface!==void 0?{surface:s.surface}:{},defaultSubagentModel:s.defaultSubagentModel,childProviderFactory:s.childProviderFactory,childSkillExecutorFactory:s.childSkillExecutorFactory,...s.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:s.resolveApiKeyForModel}:{},depth:a+1,maxDepth:c,...i!==void 0?{cwd:i}:{},...s.traceWriter!==void 0?{traceWriter:s.traceWriter}:{},...s.workspaceStore!==void 0?{workspaceStore:s.workspaceStore}:{},...s.backgroundRegistry!==void 0?{backgroundRegistry:s.backgroundRegistry}:{},...d!==void 0?{allowedTools:d}:{},...u?{readOnlyBash:!0}:{},...s.agentRegistry!==void 0?{agentRegistry:s.agentRegistry}:{},...l.model!==void 0?{parentModel:l.model}:{}}),g={parentReadRoots:p,parentCwd:i},y=s.childSkillExecutorFactory?s.childSkillExecutorFactory(a+1,c,n,i,g,e.skillDispatchName):void 0;return l.provider=s.childProviderFactory({childExecutor:m,...y!==void 0?{childSkillExecutor:y}:{},...l.model!==void 0?{model:l.model}:{},...d!==void 0?{allowedTools:d}:{},...u?{readOnlyBash:!0}:{}}),{childConfig:l,childManager:f}}var jF=h(()=>{"use strict";we();Zr();Ot();lS()});function AZ(t){return`[skill failed: ${t} \u2014 partial output preserved below]`}function xZ(t){let e=t.partialOutput;return typeof e=="string"&&e.length>0?e:void 0}function WF(t,e){let n=Tr(`${t}
|
|
1289
1289
|
|
|
1290
1290
|
${e}`);return{content:n.content,...n.truncated?{truncated:!0}:{}}}function KF(t,e){if(t.status==="succeeded"&&t.message)return{content:Es(t.message.content,t.stopReason),...Zn(t.stopReason)};let n=xZ(t);if(t.status==="cancelled"&&n!==void 0)return{...WF(_Z,n),...Zn(t.stopReason)};let r=t.error?.message??e;return n!==void 0?{...WF(AZ(r),n),isError:!0,...Zn(t.stopReason)}:{content:r,isError:!0,...Zn(t.stopReason)}}var _Z,qF=h(()=>{"use strict";Re();Ht();_Z="[skill cancelled mid-flight \u2014 partial output preserved below]"});function GF(t,e){let{ctx:n,currentCwd:r}=t,o=Gn(n.getReadScopeInputs?.(),r);return new V({parentAbortSignal:e.parentAbortSignal,apiKey:e.apiKey,parentModel:e.parentModel,...n.baseUrl!==void 0?{baseUrl:n.baseUrl}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},...n.surface!==void 0?{surface:n.surface}:{},progressSink:Pt(),...r!==void 0?{cwd:r}:{},...o!==void 0?{parentReadRoots:o}:{},...n.workspaceStore!==void 0?{workspaceStore:n.workspaceStore}:{}})}async function XF(t,e,n,r){let{ctx:o}=t;if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=e.readOnly===!0||Zp.has(e.name),i;try{if(i=ue(e.name)["system.md"],!i)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(p){return{content:`Failed to load skill prompts: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let a=Ve({callSiteModel:e.model,defaultSubagentModel:o.defaultSubagentModel,defaultModel:o.defaultModel}),c=to({childModel:a,resolved:o.resolveApiKeyForModel?o.resolveApiKeyForModel(a):re(a),parentApiKey:o.apiKey}),l=GF(t,{apiKey:c,parentModel:a,parentAbortSignal:r.signal}),{childConfig:d,childManager:u}=uS(t,{model:a,systemPrompt:i,isSkillDispatch:!0,skillDispatchName:e.name,...o.traceWriter!==void 0?{traceWriter:o.traceWriter}:{}},r.signal,s);return JF(t,{manager:l,childManager:u,childConfig:d,label:e.name,idPrefix:`skill-fork-${e.name}`,parentId:r.id,args:n,noOutputError:"Forked skill failed with no output",errorPrefix:"Forked skill execution error"})}async function zF(t,e,n,r,o,s,i=!1,a,c){let{ctx:l}=t;if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let d=Ve({callSiteModel:c,defaultSubagentModel:l.defaultSubagentModel,defaultModel:l.defaultModel}),u=to({childModel:d,resolved:l.resolveApiKeyForModel?l.resolveApiKeyForModel(d):re(d),parentApiKey:l.apiKey}),p=GF(t,{apiKey:u,parentModel:d,parentAbortSignal:s.signal}),f={model:d,systemPrompt:Yn(n,o),env:{PLUGIN_ROOT:r},isSkillDispatch:!0,skillDispatchName:e,...l.traceWriter!==void 0?{traceWriter:l.traceWriter}:{}},{childConfig:m,childManager:g}=uS(t,f,s.signal,i,a);return JF(t,{manager:p,childManager:g,childConfig:m,label:e,idPrefix:`skill-${e}`,parentId:s.id,args:o,noOutputError:"Plugin skill failed with no output",errorPrefix:"Plugin skill execution error"})}async function JF(t,e){let{manager:n,childManager:r,childConfig:o,label:s,idPrefix:i,parentId:a,args:c,noOutputError:l,errorPrefix:d}=e,u,p;try{u=await n.forkSubagent({parent:t.ctx.parentSession,config:o,idPrefix:i,parentId:a,agentType:s});let f=`Run the ${s} skill now, following the instructions in your system prompt.`,m=c&&c.length>0?`${f}
|
|
1291
1291
|
|
|
1292
1292
|
Skill arguments:
|
|
1293
|
-
${c}`:f,g=await u.runToResult(m);return p=KF(g,l),p}catch(f){let m=f instanceof Error?f.message:String(f);return{content:`${d}: ${m}`,isError:!0}}finally{u&&await u.teardown({deferInjectContextToCaller:!0}).catch(
|
|
1293
|
+
${c}`:f,g=await u.runToResult(m);return p=KF(g,l),p}catch(f){let m=f instanceof Error?f.message:String(f);return{content:`${d}: ${m}`,isError:!0}}finally{u&&await u.teardown({deferInjectContextToCaller:!0}).catch(O);let f=u?.getLastStopInjectContext?.();Rp(p,f),await r?.teardownAll(),await n.teardownAll()}}var VF=h(()=>{"use strict";we();Zr();Cw();Ot();Ua();Jr();be();Qr();bt();se();jF();qF();Iw()});function RZ(t){if(typeof t!="object"||t===null)return;let e=t.name;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function IZ(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var xs,pS=h(()=>{"use strict";Jt();Xn();Ot();_p();Rt();oD();aD();Rw();Iw();VF();xs=class{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;pluginBodies=null;currentCwd;setCwd(e){this.currentCwd=e,this.pluginBodies=null}setTraceWriter(e){this.ctx.traceWriter=e}internals(){return{ctx:this.ctx,currentCwd:this.currentCwd}}async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??tn();if(n>=r){let l=RZ(e.input);return ne({...hs(this.ctx),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:eD(n,r),isError:!0}}let o;try{o=IZ(e.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}if(this.ctx.skillDispatchName!==void 0&&o.name===this.ctx.skillDispatchName)return{content:`Skill "${o.name}" cannot re-dispatch itself (already executing at this level). Return findings via your system prompt contract instead.`,isError:!0};let s=Aa(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0),i;try{i=fn(o.name)}catch{}if(i)return await this.executeRegistrySkill(i,o.arguments,e);let a=this.getPluginSkillBody(o.name);if(a){if(a.context==="fork"){let d=a.readOnly===!0||Zp.has(o.name);return await zF(this.internals(),o.name,a.body,a.pluginPath,o.arguments,e,d,a.allowedTools,a.model)}let l=a.body.replace(/\$\{PLUGIN_ROOT(?::-(?:[^{}]|\$\{[^{}]*\})*)?\}|\$PLUGIN_ROOT\b/g,()=>a.pluginPath);return fD(this.internals(),o.name,l,o.arguments,e)}let c=s.map(l=>l.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${c||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return XF(this.internals(),e,n,r);if(e.context==="load")return pD(this.internals(),e,n,r);let o=rD(e.name);o&&iD(e.name);let s=this.ctx.depth??0;ne({...hs(this.ctx),event:"skill.dispatched",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...Ap(e.name)?{is_gate:!0}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{});let i=Date.now(),a,c;try{c=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r),...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.getReadScopeInputs!==void 0?{getReadScopeInputs:this.ctx.getReadScopeInputs}:{},...this.ctx.workspaceStore!==void 0?{workspaceStore:this.ctx.workspaceStore}:{}})}catch(d){a=d}finally{let d=Date.now()-i;o&&sD({skillName:e.name,durationMs:d,...a!==void 0?{isError:!0}:{}});let u=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof c=="string"?c.length:c!=null?JSON.stringify(c).length:0:void 0;ne({...hs(this.ctx),event:"skill.completed",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:d,depth:s,...p!==void 0?{content_chars:p}:{},...u!==void 0?{error_message:cD(u)}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof c=="string"?c:c!=null?JSON.stringify(c):"Skill completed successfully."}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=Xa(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0)),this.pluginBodies.get(e)}createDispatchSkillCallback(e){return async(n,r)=>{let o={id:`${e.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:e.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}}});function tn(){let t=k.AFK_MAX_NESTING_DEPTH;if(t===void 0)return Yp;let e=t.trim();if(!/^\d+$/.test(e))return Yp;let n=Number(e);return!Number.isInteger(n)||n<0||n>CZ?Yp:n}function Ka(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}function YF(t={}){return({childExecutor:e,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s,customTools:i,subscribeHandler:a})=>{let c={permissions:{allowedTools:o??vs},subagentExecutor:e,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{},...i!==void 0&&i.length>0?{customTools:i}:{}};return z(typeof r=="string"?r:void 0)==="openai-compatible"?new xe({...c,...t.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{},...t.workspaceStore!==void 0?{workspaceStore:t.workspaceStore}:{},readOnlyMemory:!0}):new De({...c,...t.workspaceStore!==void 0?{workspaceStore:t.workspaceStore}:{},...a!==void 0?{subscribeHandler:a}:{},readOnlyMemory:!0})}}function HF(t,e,n){let r={allowedTools:[...n??Qp]};return z(typeof t=="string"?t:void 0)==="openai-compatible"?new xe({permissions:r,readOnlyBash:!0,readOnlyMemory:!0,...e!==void 0?{baseURL:e}:{}}):new De({permissions:r,readOnlyBash:!0,readOnlyMemory:!0})}function QF(t,e,n,r){let o={allowedTools:[...vs]};return z(typeof t=="string"?t:void 0)==="openai-compatible"?new xe({permissions:o,workspaceStore:e,readOnlyMemory:!0,...n!==void 0?{baseURL:n}:{},...r===!0?{readOnlyBash:!0}:{}}):new De({permissions:o,workspaceStore:e,readOnlyMemory:!0,...r===!0?{readOnlyBash:!0}:{}})}function ZF(t,e,n,r,o,s,i,a,c,l,d,u,p,f){let m=(g,y,b,w,v,_)=>{let x=w??i;return new xs({parentSession:Ka(b),defaultModel:t,defaultSubagentModel:l??"sonnet",apiKey:e,...r!==void 0?{baseUrl:r}:{},...u!==void 0?{openaiBaseUrl:u}:{},...p!==void 0?{xaiBaseUrl:p}:{},depth:g,maxDepth:y,childProviderFactory:n,childSkillExecutorFactory:m,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...x!==void 0?{cwd:x}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...c!==void 0?{surface:c}:{},...d!==void 0?{agentRegistry:d}:{},...v!==void 0?{getReadScopeInputs:()=>v}:{},...f!==void 0?{workspaceStore:f}:{},..._!==void 0?{skillDispatchName:_}:{}})};return m}function Wp(t,e,n=!1,r){let o={allowedTools:[...t]};return z(typeof e=="string"?e:void 0)==="openai-compatible"?new xe({permissions:o,...n?{readOnlyBash:!0}:{},...r!==void 0?{baseURL:r}:{}}):new De({permissions:o,...n?{readOnlyBash:!0}:{}})}function eL(t,e){let n={allowedTools:[...Jy]};return z(typeof e=="string"?e:void 0)==="openai-compatible"?new xe({permissions:n}):new De({permissions:n})}var Yp,CZ,vs,Qp,Zp,Ot=h(()=>{"use strict";F();ef();gs();In();fe();ut();Ue();da();pS();Yp=3,CZ=6;vs=[...At,...$e,"memory_search",...Ag,"agent","skill","state_get","state_query"],Qp=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...$e,"memory_search","workspace_publish","workspace_query","agent","skill","state_get","state_query"],Zp=new Set(["ground-state"])});function PZ(t){return["# Tool budget","",`You have ${t} tool-use rounds for this turn. A round is one reply that requests tools:`,"issuing five tool calls in a SINGLE reply costs 1 round, not 5. Batch independent reads,","greps, and commands into one reply instead of calling them one at a time \u2014 it is the",`difference between roughly ${t} and roughly ${t*10} tool calls on the same budget.`,"",`${t} is a hard ceiling, not a target. Aim to finish well under it. When the budget is`,"spent you get one final reply with tools removed and must answer from what you already","gathered, so a partial answer delivered early beats a complete one you never get to give.","If new evidence has stopped changing your conclusion, stop gathering and answer now.","When writing code, a partial result should be an internally consistent checkpoint --","not knowingly broken, unverified, or incoherent code returned merely to finish early."].join(`
|
|
1294
1294
|
`)}function tL(t){let e=t.maxToolUseIterations;if(typeof e!="number"||!Number.isFinite(e)||e<=0)return t;let n=PZ(Math.floor(e)),r=t.systemPrompt;if(typeof r=="string")return r.length>0?{...t,systemPrompt:`${r}
|
|
1295
1295
|
|
|
1296
1296
|
${n}`}:{...t,systemPrompt:n};if(r&&typeof r=="object"&&"type"in r&&r.type==="preset"){let o=r.append??"";return{...t,systemPrompt:{...r,append:o.length>0?`${o}
|
|
1297
1297
|
|
|
1298
|
-
${n}`:n}}}return{...t,systemPrompt:n}}var nL=h(()=>{"use strict"});function za(){let t=k.AFK_SUBAGENT_TIMEOUT_MS;if(t===void 0||t.trim()==="")return fS;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?fS:e}function rL(){let t=k.AFK_SUBAGENT_IDLE_TIMEOUT_MS;if(t===void 0||t.trim()==="")return mS;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?mS:e}var gS,hS,fS,mS,dS,oL,Rs=h(()=>{"use strict";F();gS=async(t,e)=>({action:"decline"}),hS=50,fS=45*6e4;mS=8*6e4;dS=60*6e4,oL=5e3});function sL(t){let{options:e,id:n,resume:r,registry:o,effectiveChildModel:s,effectiveTimeoutMs:i,inheritedReadRoots:a,composedWriteRoots:c,childController:l,parentCwd:d,parentApiKey:u,parentBaseUrl:p,parentProvider:f,parentTraceWriter:m,parentSurface:g,parentCanUseTool:y}=t,b=r??(typeof e.config.systemPrompt=="string"?e.config.systemPrompt:""),w=t.workspaceStore?t.workspaceStore.queryRelevant(null,b):[],v=tL({...e.config,isSubagentFork:!0,model:s,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:l.signal,apiKey:gD({childModel:s,configApiKey:e.config.apiKey,parentApiKey:u,parentProvider:f}),baseUrl:e.config.baseUrl??(z(s)==="openai-compatible"?void 0:p),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??hS,softDeadlineMs:e.config.softDeadlineMs??Nu(i),autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&d!==void 0?{cwd:d}:{},...a!==void 0?{readRoots:a}:{},...c!==void 0?{writeRoots:c}:{},...e.config.traceWriter===void 0&&m!==void 0?{traceWriter:m}:{},...e.config.surface===void 0&&g!==void 0?{surface:g}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(y!==void 0&&e.config.canUseTool===void 0?{canUseTool:y}:void 0),...e.denyElicitations===!1?{}:{onElicitation:gS},...e.phaseRole==="read-only"?{provider:eL("read-only",s)}:{}});return t.workspaceStore?Rg(v,w):v}var iL=h(()=>{"use strict";fe();Ot();Ht();Ua();nL();In();Rs();Wn()});function aL(t){let{effectiveTraceWriter:e,id:n,parentSessionId:r,rootId:o,effectiveChildModel:s,childConfig:i,promptHead:a,effectiveAgentType:c,effectiveResolvedAgentType:l}=t,d=typeof s=="string"?s:JSON.stringify(s);return kr(e,{transition:"started",subagentId:n,parentId:r??o,model:d,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{},...a&&a.trim()!==""?{promptHead:a.slice(0,80)}:{},...c?{agentType:c}:{},...l?{resolvedAgentType:l}:{}}),d}async function cL(t){let{modelString:e,id:n,idPrefix:r,parentSessionId:o,effectiveResolvedAgentType:s}=t;await ne({event:"subagent.dispatched",subagent_id:n,id_prefix:r,model:e,parent_session_id:o,resolved_agent_type:s})}var lL=h(()=>{"use strict";J();Rt()});function Ja(t,e=Date.now()){if(t.type==="paused")return t.resetsAt===void 0?void 0:t.resetsAt.getTime()-e+3e4;if(t.type==="rate_limit"){let n=t.retryAfterMs;return typeof n!="number"||!Number.isFinite(n)||n<=0?void 0:n+3e4}}function dL(t){if(t.type==="paused"){let e=t.resetsAt!==void 0?t.resetsAt.toISOString():"unknown";return`paused (${t.reason}, resetsAt=${e})`}if(t.type==="rate_limit"){let e=t.retryAfterMs;return`rate_limit (retryAfterMs=${typeof e=="number"?e:"unknown"})`}}var yS=h(()=>{"use strict"});var bS,MZ,tf,uL=h(()=>{"use strict";yS();bS=120*6e4,MZ=1e3,tf=class{constructor(e,n=bS,r){this.baseTimeoutMs=e;this.maxExtensionMs=n;this.onGrant=r}baseTimeoutMs;maxExtensionMs;pauseStartedAtMs;pauseWindowCapMs=0;closedCreditMs=0;lastPauseDescription;grantedMs=0;grantCount=0;onGrant;onEvent(e){if(e.type==="resumed"){this.closePause();return}if(e.type!=="paused"&&e.type!=="rate_limit")return;this.closeExpiredPause();let n=Ja(e);if(n===void 0||n<=0)return;let r=Date.now();if(this.pauseStartedAtMs===void 0)this.pauseStartedAtMs=r,this.pauseWindowCapMs=n;else{let o=r-this.pauseStartedAtMs;this.pauseWindowCapMs=Math.max(this.pauseWindowCapMs,o+n)}this.lastPauseDescription=dL(e)}openPauseCreditMs(){if(this.pauseStartedAtMs===void 0)return 0;let e=Date.now()-this.pauseStartedAtMs;return Math.max(0,Math.min(e,this.pauseWindowCapMs))}closePause(){this.pauseStartedAtMs!==void 0&&(this.closedCreditMs+=this.openPauseCreditMs(),this.pauseStartedAtMs=void 0,this.pauseWindowCapMs=0)}closeExpiredPause(){this.pauseStartedAtMs!==void 0&&Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs&&this.closePause()}onDeadline(){let e=this.maxExtensionMs-this.grantedMs;if(!(e>0))return 0;this.closeExpiredPause();let r=this.closedCreditMs+this.openPauseCreditMs()-this.grantedMs;if(r<=0)return 0;let o=Math.min(Math.max(r,MZ),e);if(this.grantedMs+=o,this.grantCount+=1,this.onGrant)try{this.onGrant({grantMs:o,totalGrantedMs:this.grantedMs,remainingCapMs:this.maxExtensionMs-this.grantedMs,grantCount:this.grantCount,pauseDescription:this.lastPauseDescription})}catch{}return o}describe(){if(this.lastPauseDescription===void 0)return;let e=[`base budget ${this.baseTimeoutMs}ms`,`pause extension granted ${this.grantedMs}ms across ${this.grantCount} extension${this.grantCount===1?"":"s"} (cap ${this.maxExtensionMs}ms${this.grantedMs>=this.maxExtensionMs?", EXHAUSTED":""})`,`last provider pause: ${this.lastPauseDescription}`];if(this.pauseStartedAtMs!==void 0){let r=Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs?"expired":"still open";e.push(`last pause ${r}, opened ${new Date(this.pauseStartedAtMs).toISOString()} (reported window ${this.pauseWindowCapMs}ms)`)}return`[pause-aware ceiling: ${e.join("; ")}]`}get totalGrantedMs(){return this.grantedMs}}});var wS=h(()=>{"use strict"});var nf,pL=h(()=>{"use strict";se();yS();nf=class{constructor(e,n,r,o){this.controller=e;this.idleTimeoutMs=n;this.label=r;this.onFire=o;this.isEnabled()&&this.arm(this.idleTimeoutMs,"none")}controller;idleTimeoutMs;label;onFire;timer;disposed=!1;fired=!1;inFlightTools=new Set;isEnabled(){return Number.isFinite(this.idleTimeoutMs)&&this.idleTimeoutMs>0}onEvent(e){if(!(!this.isEnabled()||this.disposed||this.fired)){if(e.type==="chunk"){if(e.chunk.type==="tool_use_detail"){this.inFlightTools.add(e.chunk.toolUseId),this.clearTimer();return}if(e.chunk.type==="tool_result"){this.inFlightTools.delete(e.chunk.toolUseId),this.inFlightTools.size===0&&this.arm(this.idleTimeoutMs,e.chunk.type);return}}if(!(this.inFlightTools.size>0)){if(e.type==="paused"){this.arm(this.pausedWindowMs(e),e.type);return}if(e.type==="rate_limit"){let n=Ja(e);if(n!==void 0&&n>0){this.arm(n,e.type);return}}this.arm(this.idleTimeoutMs,e.type)}}}pausedWindowMs(e){let n=Ja(e);return n===void 0?this.idleTimeoutMs:Math.max(this.idleTimeoutMs,n)}arm(e,n){this.timer!==void 0&&clearTimeout(this.timer);let r=e>0?e:this.idleTimeoutMs,o=Date.now(),s=setTimeout(()=>{this.fire(Date.now()-o,n)},r);s.unref(),this.timer=s}clearTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}fire(e,n){if(!(this.fired||this.disposed)){this.fired=!0,this.timer=void 0;try{this.onFire?.({idleTimeoutMs:this.idleTimeoutMs,elapsedSinceLastProgressMs:e,lastEventType:n})}catch{}this.controller.signal.aborted||this.controller.abort(new Tl(`subagent ${this.label} idle-watchdog fired: no observable progress for ${this.idleTimeoutMs}ms (last event: ${n}). The child stream produced no output for the idle window \u2014 typically a stalled model call under provider throttling with no detectable backoff bracket. Aborting so partial output (if any) is returned; the parent should retry or fall back.`,this.idleTimeoutMs))}}dispose(){this.disposed||(this.disposed=!0,this.inFlightTools.clear(),this.clearTimer())}}});function fL(t,e){let n=e.length,r=n>0?`subagent ${t} stream cut off after ${n} tool result(s); see partialOutput.`:`subagent ${t} produced no output \u2014 stream ended without a terminal message (stream_incomplete). No findings were produced; retry or fall back.`,o=new ct(r);return n>0&&(o.toolResultsGathered=n),o}function mL(t,e){if(e.length===0)return;let n=e.reduce((s,i)=>s+(i.sizeBytes??0),0),r=e.filter(s=>s.isError).length,o=r>0?` (${r} errored)`:"";return`[Stream cut off before any assistant text was produced. Subagent ${t} completed ${e.length} tool result(s)${o} (~${n} bytes total) before the cut. The run is failed \u2014 no final answer was produced \u2014 but tool evidence is available via result.trace for recovery or retry decisions.]`}var gL=h(()=>{"use strict";se()});async function SS(t,e,n){let r,o;t._lastStreamedContent="",t._currentTrace=_s();let s=n??t._progressSink??Pt(),i={subagentId:t.id,...t._parentId!==void 0&&{parentId:t._parentId},...t._agentType!==void 0&&{agentType:t._agentType}},a=new nf(t._controller,t._idleTimeoutMs,t.id,c=>{q(t._traceWriter,{phase:"idle_watchdog_fired",metadata:{idleTimeoutMs:c.idleTimeoutMs,elapsedSinceLastProgressMs:c.elapsedSinceLastProgressMs,lastEventType:c.lastEventType}})});t.session.setBeforeNextRound?.(t._beforeNextRound);try{for await(let c of t.session.sendMessageStream(e)){if(s&&s(c,i),t._logWriter?.write(c),a.onEvent(c),t._pauseCeiling?.onEvent(c),c.type==="chunk"){let l=c.chunk;l.type==="content"?t._lastStreamedContent+=l.content:l.type==="tool_use_detail"?t._currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?t._currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(t._currentTrace.thinkingPresent=!0)}if(c.type==="message")r=c.message,t._currentTrace.turnCount++;else if(c.type==="error"){o=c.error;break}else if(c.type==="done"){if(typeof c.metadata?.stopReason=="string"&&(t._lastStopReason=c.metadata.stopReason),typeof c.metadata?.usage=="object"&&c.metadata.usage!==null){let l=c.metadata.usage;t._currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}}finally{t.session.setBeforeNextRound?.(void 0),a.dispose()}if(o)throw o;if(r)return r;if(t._lastStreamedContent.length>0)return t._lastStopReason??=Ts,{role:"assistant",content:t._lastStreamedContent,timestamp:new Date};if(t._lastStopReason===Mt||t._lastStopReason===Ct){let c=t._lastStopReason===Mt?"tool-use iteration cap":"wall-clock budget";return{role:"assistant",content:`[subagent ${t.id} reached its ${c} before producing a final message; returning a partial result]`,timestamp:new Date}}throw t._controller.signal.aborted||t._currentStatus==="cancelled"?new Error(`Subagent ${t.id} produced no terminal message`):(t._lastStopReason=Ts,fL(t.id,t._currentTrace.toolResults))}async function hL(t,e,n){try{let r=await t.run(e,n);return nF(t.id,t._currentStatus,r,t._outputSchema,t._currentTrace,t._lastStopReason)}catch(r){let o=Kp(t.id,t._currentStatus,r,t._currentTrace,t._lastStopReason);if(t._lastStreamedContent.length>0)o.partialOutput=t._lastStreamedContent;else if(r instanceof ct){let s=mL(t.id,t._currentTrace.toolResults);s!==void 0&&(o.partialOutput=s)}return o}}function yL(t,e,n,r){let o;if(r){let s=t._progressSink??Pt();o=(i,a)=>{r(i),s?.(i,a)}}t.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{D("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async function kS(t,e,n){if(t._stopDispatched){t._onTerminal();return}t._stopDispatched=!0;let r=await UE(t._hookRegistry,{event:"SubagentStop",subagentId:t.id,status:e,lastMessage:t._lastMessage,agentType:t._agentType,durationMs:t._lastDurationMs,trace:t._currentTrace},t._traceWriter?{traceWriter:t._traceWriter}:{});if(r.injectContext){if(t._parentAbortSignal?.aborted)D(`Skipping SubagentStop injectContext for ${t.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)t._lastStopInjectContext=r.injectContext;else if(t._parentInputStreamRef)try{let o=t._parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){D(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}if(t._workspaceStore!==void 0)try{t._workspaceStore.unsubscribeAll(t.id)}catch{}t._onTerminal()}var bL=h(()=>{"use strict";ie();se();Qr();Kl();J();pL();ms();Wn();Re();gL()});var rf,SL=h(()=>{"use strict";se();Ob();J();uL();wS();Ti();Re();bL();rf=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,m,g,y=0){this.id=e;this.session=n;this._controller=r;this.abortGraph=o;this._outputSchema=s;this.timeoutMs=i;this._hookRegistry=a;this._onTerminal=c;this._parentInputStreamRef=l;this._parentAbortSignal=d;this._agentType=u;this._traceWriter=m;this.onSubagentSucceeded=g;this._idleTimeoutMs=y;this._progressSink=p,this._parentId=f}id;session;_controller;abortGraph;_outputSchema;timeoutMs;_hookRegistry;_onTerminal;_parentInputStreamRef;_parentAbortSignal;_agentType;_traceWriter;onSubagentSucceeded;_idleTimeoutMs;_currentStatus="idle";inFlight=null;_lastMessage;_lastDurationMs;latestTerminalStatus;_stopDispatched=!1;_lastStopInjectContext;_progressSink;_parentId;_currentTrace=_s();_lastStreamedContent="";_pauseCeiling;_lastStopReason;_logWriter;get status(){return this._currentStatus}get durationMs(){return this._lastDurationMs}async run(e,n){if(this._currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this._lastStopReason=void 0,this._currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this._currentStatus="running";let r=Date.now(),o=Number.isFinite(this.timeoutMs)&&this.timeoutMs>0?new tf(this.timeoutMs,bS,i=>{q(this._traceWriter,{phase:"pause_extension_granted",metadata:{subagentId:this.id,grantMs:i.grantMs,totalGrantedMs:i.totalGrantedMs,remainingCapMs:i.remainingCapMs,grantCount:i.grantCount,...i.pauseDescription!==void 0&&{pauseDescription:i.pauseDescription}}})}):void 0;this._pauseCeiling=o;let s=Du(SS(this,e,n),this.timeoutMs,{controller:this._controller,label:this.id,...o!==void 0&&{extender:o}});this.inFlight=s;try{let i=await s;this._lastMessage=i.content,this._lastDurationMs=Date.now()-r,this._currentStatus="succeeded",this.latestTerminalStatus="succeeded";let a=i;this._drainingMessages=!0;try{for(;this._pendingUserMessages.length>0&&!this._controller.signal.aborted;){let l=this._pendingUserMessages.shift();a=await SS(this,l,n),this._lastMessage=a.content,this._currentTrace.turnCount++}}catch{this._pendingUserMessages.length=0}this._drainingMessages=!1,await kr(this._traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:Date.now()-r,turnCount:this._currentTrace.turnCount,outputBytes:Buffer.byteLength(this._lastMessage,"utf8"),...this._lastStopReason!==void 0&&{stopReason:this._lastStopReason}});let c=typeof a.metadata?.totalCostUsd=="number"?a.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this._currentTrace.usage,c),this._onTerminal(),a}catch(i){this._lastDurationMs=Date.now()-r;let a=this._controller.signal.aborted&&this._controller.signal.reason instanceof Ie&&!this.abortGraph.isCascading(this.id)?this._controller.signal.reason:void 0,c=a??i;if(this._currentStatus!=="cancelled")if(this._controller.signal.aborted&&a===void 0){let l=this._controller.signal.reason instanceof Ie;await kr(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade",...l?{timeout:!0}:{}}),this._currentStatus="cancelled",this.latestTerminalStatus="cancelled"}else await kr(this._traceWriter,{transition:"failed",subagentId:this.id,errorClass:c instanceof Error?c.constructor.name:"Unknown",errorMessage:c instanceof Error?c.message:String(c),partialOutputBytes:Buffer.byteLength(this._lastStreamedContent,"utf8"),...a!==void 0?{failureClass:"timeout"}:{}}),this._currentStatus="failed",this.latestTerminalStatus="failed";throw this._onTerminal(),c}finally{this.inFlight=null}}async runToResult(e,n){return hL(this,e,n)}runInBackground(e,n,r){return yL(this,e,n,r)}async cancel(){if(this._currentStatus==="cancelled"||this._stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this._currentStatus="cancelled",kr(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"}),this._steeringMessages.length=0,this._progressEvents.length=0,this._pendingWorkspaceEntries.length=0;try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await kS(this,e)}}async teardown(e){if(this._stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}this._steeringMessages.length=0,this._progressEvents.length=0,this._pendingWorkspaceEntries.length=0;try{await this.session.close()}finally{await kS(this,n,e)}}getLastStopInjectContext(){return this._lastStopInjectContext}_pendingUserMessages=[];_drainingMessages=!1;sendMessage(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._pendingUserMessages.push(e))}_steeringMessages=[];_progressEvents=[];_pendingWorkspaceEntries=[];_workspaceDroppedSinceDrain=0;_workspaceStore=void 0;steer(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._controller.signal.aborted||(this._steeringMessages.length>=3&&this._steeringMessages.shift(),this._steeringMessages.push(e)))}emitProgress(e){this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled"||(this._progressEvents.length>=20&&this._progressEvents.shift(),this._progressEvents.push(e))}_drainWorkspaceDeliveries(){if(this._pendingWorkspaceEntries.length===0)return;let e=this._pendingWorkspaceEntries.splice(0),n=this._workspaceDroppedSinceDrain;return this._workspaceDroppedSinceDrain=0,vg(e,n)}get _beforeNextRound(){return()=>{let e=this._steeringMessages.shift(),n=this._drainWorkspaceDeliveries();return e!==void 0&&n!==void 0?e+`
|
|
1298
|
+
${n}`:n}}}return{...t,systemPrompt:n}}var nL=h(()=>{"use strict"});function za(){let t=k.AFK_SUBAGENT_TIMEOUT_MS;if(t===void 0||t.trim()==="")return fS;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?fS:e}function rL(){let t=k.AFK_SUBAGENT_IDLE_TIMEOUT_MS;if(t===void 0||t.trim()==="")return mS;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?mS:e}var gS,hS,fS,mS,dS,oL,Rs=h(()=>{"use strict";F();gS=async(t,e)=>({action:"decline"}),hS=50,fS=45*6e4;mS=8*6e4;dS=60*6e4,oL=5e3});function sL(t){let{options:e,id:n,resume:r,registry:o,effectiveChildModel:s,effectiveTimeoutMs:i,inheritedReadRoots:a,composedWriteRoots:c,childController:l,parentCwd:d,parentApiKey:u,parentBaseUrl:p,parentProvider:f,parentTraceWriter:m,parentSurface:g,parentCanUseTool:y}=t,b=r??(typeof e.config.systemPrompt=="string"?e.config.systemPrompt:""),w=t.workspaceStore?t.workspaceStore.queryRelevant(null,b):[],v=tL({...e.config,isSubagentFork:!0,model:s,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:l.signal,apiKey:gD({childModel:s,configApiKey:e.config.apiKey,parentApiKey:u,parentProvider:f}),baseUrl:e.config.baseUrl??(z(s)==="openai-compatible"?void 0:p),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??hS,softDeadlineMs:e.config.softDeadlineMs??Nu(i),autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&d!==void 0?{cwd:d}:{},...a!==void 0?{readRoots:a}:{},...c!==void 0?{writeRoots:c}:{},...e.config.traceWriter===void 0&&m!==void 0?{traceWriter:m}:{},...e.config.surface===void 0&&g!==void 0?{surface:g}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(y!==void 0&&e.config.canUseTool===void 0?{canUseTool:y}:void 0),...e.denyElicitations===!1?{}:{onElicitation:gS},...e.phaseRole==="read-only"?{provider:eL("read-only",s)}:{}});return t.workspaceStore?Rg(v,w):v}var iL=h(()=>{"use strict";fe();Ot();Ht();Ua();nL();In();Rs();Wn()});function aL(t){let{effectiveTraceWriter:e,id:n,parentSessionId:r,rootId:o,effectiveChildModel:s,childConfig:i,promptHead:a,effectiveAgentType:c,effectiveResolvedAgentType:l}=t,d=typeof s=="string"?s:JSON.stringify(s);return kr(e,{transition:"started",subagentId:n,parentId:r??o,model:d,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{},...a&&a.trim()!==""?{promptHead:a.slice(0,80)}:{},...c?{agentType:c}:{},...l?{resolvedAgentType:l}:{}}),d}async function cL(t){let{modelString:e,id:n,idPrefix:r,parentSessionId:o,effectiveResolvedAgentType:s}=t;await ne({event:"subagent.dispatched",subagent_id:n,id_prefix:r,model:e,parent_session_id:o,resolved_agent_type:s})}var lL=h(()=>{"use strict";J();Rt()});function Ja(t,e=Date.now()){if(t.type==="paused")return t.resetsAt===void 0?void 0:t.resetsAt.getTime()-e+3e4;if(t.type==="rate_limit"){let n=t.retryAfterMs;return typeof n!="number"||!Number.isFinite(n)||n<=0?void 0:n+3e4}}function dL(t){if(t.type==="paused"){let e=t.resetsAt!==void 0?t.resetsAt.toISOString():"unknown";return`paused (${t.reason}, resetsAt=${e})`}if(t.type==="rate_limit"){let e=t.retryAfterMs;return`rate_limit (retryAfterMs=${typeof e=="number"?e:"unknown"})`}}var yS=h(()=>{"use strict"});var bS,MZ,tf,uL=h(()=>{"use strict";yS();bS=120*6e4,MZ=1e3,tf=class{constructor(e,n=bS,r){this.baseTimeoutMs=e;this.maxExtensionMs=n;this.onGrant=r}baseTimeoutMs;maxExtensionMs;pauseStartedAtMs;pauseWindowCapMs=0;closedCreditMs=0;lastPauseDescription;grantedMs=0;grantCount=0;onGrant;onEvent(e){if(e.type==="resumed"){this.closePause();return}if(e.type!=="paused"&&e.type!=="rate_limit")return;this.closeExpiredPause();let n=Ja(e);if(n===void 0||n<=0)return;let r=Date.now();if(this.pauseStartedAtMs===void 0)this.pauseStartedAtMs=r,this.pauseWindowCapMs=n;else{let o=r-this.pauseStartedAtMs;this.pauseWindowCapMs=Math.max(this.pauseWindowCapMs,o+n)}this.lastPauseDescription=dL(e)}openPauseCreditMs(){if(this.pauseStartedAtMs===void 0)return 0;let e=Date.now()-this.pauseStartedAtMs;return Math.max(0,Math.min(e,this.pauseWindowCapMs))}closePause(){this.pauseStartedAtMs!==void 0&&(this.closedCreditMs+=this.openPauseCreditMs(),this.pauseStartedAtMs=void 0,this.pauseWindowCapMs=0)}closeExpiredPause(){this.pauseStartedAtMs!==void 0&&Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs&&this.closePause()}onDeadline(){let e=this.maxExtensionMs-this.grantedMs;if(!(e>0))return 0;this.closeExpiredPause();let r=this.closedCreditMs+this.openPauseCreditMs()-this.grantedMs;if(r<=0)return 0;let o=Math.min(Math.max(r,MZ),e);if(this.grantedMs+=o,this.grantCount+=1,this.onGrant)try{this.onGrant({grantMs:o,totalGrantedMs:this.grantedMs,remainingCapMs:this.maxExtensionMs-this.grantedMs,grantCount:this.grantCount,pauseDescription:this.lastPauseDescription})}catch{}return o}describe(){if(this.lastPauseDescription===void 0)return;let e=[`base budget ${this.baseTimeoutMs}ms`,`pause extension granted ${this.grantedMs}ms across ${this.grantCount} extension${this.grantCount===1?"":"s"} (cap ${this.maxExtensionMs}ms${this.grantedMs>=this.maxExtensionMs?", EXHAUSTED":""})`,`last provider pause: ${this.lastPauseDescription}`];if(this.pauseStartedAtMs!==void 0){let r=Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs?"expired":"still open";e.push(`last pause ${r}, opened ${new Date(this.pauseStartedAtMs).toISOString()} (reported window ${this.pauseWindowCapMs}ms)`)}return`[pause-aware ceiling: ${e.join("; ")}]`}get totalGrantedMs(){return this.grantedMs}}});var wS=h(()=>{"use strict"});var nf,pL=h(()=>{"use strict";ie();yS();nf=class{constructor(e,n,r,o){this.controller=e;this.idleTimeoutMs=n;this.label=r;this.onFire=o;this.isEnabled()&&this.arm(this.idleTimeoutMs,"none")}controller;idleTimeoutMs;label;onFire;timer;disposed=!1;fired=!1;inFlightTools=new Set;isEnabled(){return Number.isFinite(this.idleTimeoutMs)&&this.idleTimeoutMs>0}onEvent(e){if(!(!this.isEnabled()||this.disposed||this.fired)){if(e.type==="chunk"){if(e.chunk.type==="tool_use_detail"){this.inFlightTools.add(e.chunk.toolUseId),this.clearTimer();return}if(e.chunk.type==="tool_result"){this.inFlightTools.delete(e.chunk.toolUseId),this.inFlightTools.size===0&&this.arm(this.idleTimeoutMs,e.chunk.type);return}}if(!(this.inFlightTools.size>0)){if(e.type==="paused"){this.arm(this.pausedWindowMs(e),e.type);return}if(e.type==="rate_limit"){let n=Ja(e);if(n!==void 0&&n>0){this.arm(n,e.type);return}}this.arm(this.idleTimeoutMs,e.type)}}}pausedWindowMs(e){let n=Ja(e);return n===void 0?this.idleTimeoutMs:Math.max(this.idleTimeoutMs,n)}arm(e,n){this.timer!==void 0&&clearTimeout(this.timer);let r=e>0?e:this.idleTimeoutMs,o=Date.now(),s=setTimeout(()=>{this.fire(Date.now()-o,n)},r);s.unref(),this.timer=s}clearTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}fire(e,n){if(!(this.fired||this.disposed)){this.fired=!0,this.timer=void 0;try{this.onFire?.({idleTimeoutMs:this.idleTimeoutMs,elapsedSinceLastProgressMs:e,lastEventType:n})}catch{}this.controller.signal.aborted||this.controller.abort(new Tl(`subagent ${this.label} idle-watchdog fired: no observable progress for ${this.idleTimeoutMs}ms (last event: ${n}). The child stream produced no output for the idle window \u2014 typically a stalled model call under provider throttling with no detectable backoff bracket. Aborting so partial output (if any) is returned; the parent should retry or fall back.`,this.idleTimeoutMs))}}dispose(){this.disposed||(this.disposed=!0,this.inFlightTools.clear(),this.clearTimer())}}});function fL(t,e){let n=e.length,r=n>0?`subagent ${t} stream cut off after ${n} tool result(s); see partialOutput.`:`subagent ${t} produced no output \u2014 stream ended without a terminal message (stream_incomplete). No findings were produced; retry or fall back.`,o=new ct(r);return n>0&&(o.toolResultsGathered=n),o}function mL(t,e){if(e.length===0)return;let n=e.reduce((s,i)=>s+(i.sizeBytes??0),0),r=e.filter(s=>s.isError).length,o=r>0?` (${r} errored)`:"";return`[Stream cut off before any assistant text was produced. Subagent ${t} completed ${e.length} tool result(s)${o} (~${n} bytes total) before the cut. The run is failed \u2014 no final answer was produced \u2014 but tool evidence is available via result.trace for recovery or retry decisions.]`}var gL=h(()=>{"use strict";ie()});async function SS(t,e,n){let r,o;t._lastStreamedContent="",t._currentTrace=_s();let s=n??t._progressSink??Pt(),i={subagentId:t.id,...t._parentId!==void 0&&{parentId:t._parentId},...t._agentType!==void 0&&{agentType:t._agentType}},a=new nf(t._controller,t._idleTimeoutMs,t.id,c=>{q(t._traceWriter,{phase:"idle_watchdog_fired",metadata:{idleTimeoutMs:c.idleTimeoutMs,elapsedSinceLastProgressMs:c.elapsedSinceLastProgressMs,lastEventType:c.lastEventType}})});t.session.setBeforeNextRound?.(t._beforeNextRound);try{for await(let c of t.session.sendMessageStream(e)){if(s&&s(c,i),t._logWriter?.write(c),a.onEvent(c),t._pauseCeiling?.onEvent(c),c.type==="chunk"){let l=c.chunk;l.type==="content"?t._lastStreamedContent+=l.content:l.type==="tool_use_detail"?t._currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?t._currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(t._currentTrace.thinkingPresent=!0)}if(c.type==="message")r=c.message,t._currentTrace.turnCount++;else if(c.type==="error"){o=c.error;break}else if(c.type==="done"){if(typeof c.metadata?.stopReason=="string"&&(t._lastStopReason=c.metadata.stopReason),typeof c.metadata?.usage=="object"&&c.metadata.usage!==null){let l=c.metadata.usage;t._currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}}finally{t.session.setBeforeNextRound?.(void 0),a.dispose()}if(o)throw o;if(r)return r;if(t._lastStreamedContent.length>0)return t._lastStopReason??=Ts,{role:"assistant",content:t._lastStreamedContent,timestamp:new Date};if(t._lastStopReason===Mt||t._lastStopReason===Ct){let c=t._lastStopReason===Mt?"tool-use iteration cap":"wall-clock budget";return{role:"assistant",content:`[subagent ${t.id} reached its ${c} before producing a final message; returning a partial result]`,timestamp:new Date}}throw t._controller.signal.aborted||t._currentStatus==="cancelled"?new Error(`Subagent ${t.id} produced no terminal message`):(t._lastStopReason=Ts,fL(t.id,t._currentTrace.toolResults))}async function hL(t,e,n){try{let r=await t.run(e,n);return nF(t.id,t._currentStatus,r,t._outputSchema,t._currentTrace,t._lastStopReason)}catch(r){let o=Kp(t.id,t._currentStatus,r,t._currentTrace,t._lastStopReason);if(t._lastStreamedContent.length>0)o.partialOutput=t._lastStreamedContent;else if(r instanceof ct){let s=mL(t.id,t._currentTrace.toolResults);s!==void 0&&(o.partialOutput=s)}return o}}function yL(t,e,n,r){let o;if(r){let s=t._progressSink??Pt();o=(i,a)=>{r(i),s?.(i,a)}}t.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{O("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async function kS(t,e,n){if(t._stopDispatched){t._onTerminal();return}t._stopDispatched=!0;let r=await UE(t._hookRegistry,{event:"SubagentStop",subagentId:t.id,status:e,lastMessage:t._lastMessage,agentType:t._agentType,durationMs:t._lastDurationMs,trace:t._currentTrace},t._traceWriter?{traceWriter:t._traceWriter}:{});if(r.injectContext){if(t._parentAbortSignal?.aborted)O(`Skipping SubagentStop injectContext for ${t.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)t._lastStopInjectContext=r.injectContext;else if(t._parentInputStreamRef)try{let o=t._parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){O(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}if(t._workspaceStore!==void 0)try{t._workspaceStore.unsubscribeAll(t.id)}catch{}t._onTerminal()}var bL=h(()=>{"use strict";se();ie();Qr();Kl();J();pL();ms();Wn();Re();gL()});var rf,SL=h(()=>{"use strict";ie();Ob();J();uL();wS();Ti();Re();bL();rf=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,m,g,y=0){this.id=e;this.session=n;this._controller=r;this.abortGraph=o;this._outputSchema=s;this.timeoutMs=i;this._hookRegistry=a;this._onTerminal=c;this._parentInputStreamRef=l;this._parentAbortSignal=d;this._agentType=u;this._traceWriter=m;this.onSubagentSucceeded=g;this._idleTimeoutMs=y;this._progressSink=p,this._parentId=f}id;session;_controller;abortGraph;_outputSchema;timeoutMs;_hookRegistry;_onTerminal;_parentInputStreamRef;_parentAbortSignal;_agentType;_traceWriter;onSubagentSucceeded;_idleTimeoutMs;_currentStatus="idle";inFlight=null;_lastMessage;_lastDurationMs;latestTerminalStatus;_stopDispatched=!1;_lastStopInjectContext;_progressSink;_parentId;_currentTrace=_s();_lastStreamedContent="";_pauseCeiling;_lastStopReason;_logWriter;get status(){return this._currentStatus}get durationMs(){return this._lastDurationMs}async run(e,n){if(this._currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this._lastStopReason=void 0,this._currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this._currentStatus="running";let r=Date.now(),o=Number.isFinite(this.timeoutMs)&&this.timeoutMs>0?new tf(this.timeoutMs,bS,i=>{q(this._traceWriter,{phase:"pause_extension_granted",metadata:{subagentId:this.id,grantMs:i.grantMs,totalGrantedMs:i.totalGrantedMs,remainingCapMs:i.remainingCapMs,grantCount:i.grantCount,...i.pauseDescription!==void 0&&{pauseDescription:i.pauseDescription}}})}):void 0;this._pauseCeiling=o;let s=Du(SS(this,e,n),this.timeoutMs,{controller:this._controller,label:this.id,...o!==void 0&&{extender:o}});this.inFlight=s;try{let i=await s;this._lastMessage=i.content,this._lastDurationMs=Date.now()-r,this._currentStatus="succeeded",this.latestTerminalStatus="succeeded";let a=i;this._drainingMessages=!0;try{for(;this._pendingUserMessages.length>0&&!this._controller.signal.aborted;){let l=this._pendingUserMessages.shift();a=await SS(this,l,n),this._lastMessage=a.content,this._currentTrace.turnCount++}}catch{this._pendingUserMessages.length=0}this._drainingMessages=!1,await kr(this._traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:Date.now()-r,turnCount:this._currentTrace.turnCount,outputBytes:Buffer.byteLength(this._lastMessage,"utf8"),...this._lastStopReason!==void 0&&{stopReason:this._lastStopReason}});let c=typeof a.metadata?.totalCostUsd=="number"?a.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this._currentTrace.usage,c),this._onTerminal(),a}catch(i){this._lastDurationMs=Date.now()-r;let a=this._controller.signal.aborted&&this._controller.signal.reason instanceof Ie&&!this.abortGraph.isCascading(this.id)?this._controller.signal.reason:void 0,c=a??i;if(this._currentStatus!=="cancelled")if(this._controller.signal.aborted&&a===void 0){let l=this._controller.signal.reason instanceof Ie;await kr(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade",...l?{timeout:!0}:{}}),this._currentStatus="cancelled",this.latestTerminalStatus="cancelled"}else await kr(this._traceWriter,{transition:"failed",subagentId:this.id,errorClass:c instanceof Error?c.constructor.name:"Unknown",errorMessage:c instanceof Error?c.message:String(c),partialOutputBytes:Buffer.byteLength(this._lastStreamedContent,"utf8"),...a!==void 0?{failureClass:"timeout"}:{}}),this._currentStatus="failed",this.latestTerminalStatus="failed";throw this._onTerminal(),c}finally{this.inFlight=null}}async runToResult(e,n){return hL(this,e,n)}runInBackground(e,n,r){return yL(this,e,n,r)}async cancel(){if(this._currentStatus==="cancelled"||this._stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this._currentStatus="cancelled",kr(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"}),this._steeringMessages.length=0,this._progressEvents.length=0,this._pendingWorkspaceEntries.length=0;try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await kS(this,e)}}async teardown(e){if(this._stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}this._steeringMessages.length=0,this._progressEvents.length=0,this._pendingWorkspaceEntries.length=0;try{await this.session.close()}finally{await kS(this,n,e)}}getLastStopInjectContext(){return this._lastStopInjectContext}_pendingUserMessages=[];_drainingMessages=!1;sendMessage(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._pendingUserMessages.push(e))}_steeringMessages=[];_progressEvents=[];_pendingWorkspaceEntries=[];_workspaceDroppedSinceDrain=0;_workspaceStore=void 0;steer(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._controller.signal.aborted||(this._steeringMessages.length>=3&&this._steeringMessages.shift(),this._steeringMessages.push(e)))}emitProgress(e){this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled"||(this._progressEvents.length>=20&&this._progressEvents.shift(),this._progressEvents.push(e))}_drainWorkspaceDeliveries(){if(this._pendingWorkspaceEntries.length===0)return;let e=this._pendingWorkspaceEntries.splice(0),n=this._workspaceDroppedSinceDrain;return this._workspaceDroppedSinceDrain=0,vg(e,n)}get _beforeNextRound(){return()=>{let e=this._steeringMessages.shift(),n=this._drainWorkspaceDeliveries();return e!==void 0&&n!==void 0?e+`
|
|
1299
1299
|
|
|
1300
1300
|
`+n:e??n}}}});function kL(t){return ep(Ut(t))}function vL(t,e){return t===void 0||!kL(t)||z(t)!=="openai-compatible"?{model:t}:e===void 0||kL(e)||z(e)!=="openai-compatible"?{model:t}:{model:e,coercedFrom:t}}var TL=h(()=>{"use strict";fe();tp();Fe()});function EL(t){let{options:e,counter:n,managerHookRegistry:r,parentTraceWriter:o,parentModel:s}=t,a=`${(e.idPrefix??"subagent").replace(/[^A-Za-z0-9_-]/g,"-")}-${Date.now()}-${n}`,c=e.parent.sessionId,l=e.config.hookRegistry??r??e.parent.hookRegistry,d=e.config.traceWriter??o,u=vL(e.config.model,s),p=u.model??e.config.model,f=e.config.timeoutMs??za();return{id:a,resume:c,registry:l,effectiveTraceWriter:d,effectiveChildModel:p,coercedFrom:u.coercedFrom,effectiveTimeoutMs:f}}var _L=h(()=>{"use strict";TL();Rs()});var of,AL=h(()=>{"use strict";of=class{entries=new Map;capacity;constructor(e=30){this.capacity=Math.max(1,e)}add(e,n,r){this.entries.delete(e),this.entries.set(e,{handle:n,result:r,completedAt:Date.now()}),this.evictIfNeeded()}recordHandle(e,n,r,o,s){let i=r==="succeeded"?{id:e,status:r,trace:o,...s!==void 0&&{stopReason:s}}:{id:e,status:r,error:new Error(`subagent terminated with status: ${r}`),trace:o,...s!==void 0&&{stopReason:s}};this.add(e,n,i)}get(e){return this.entries.get(e)}list(){return[...this.entries.values()].reverse()}get size(){return this.entries.size}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}evictIfNeeded(){for(;this.entries.size>this.capacity;){let e=this.entries.keys().next().value;if(e!==void 0)this.entries.delete(e);else break}}}});import*as Is from"node:fs";var xL,RL,Va,IL=h(()=>{"use strict";F();B();xL=1048576,RL=new Set,Va=class{constructor(e,n){this.sessionLabel=e;this.subagentId=n;this.logPath=$v(e,n);let r=Lm(e);if(!RL.has(r))try{Is.mkdirSync(r,{recursive:!0}),RL.add(r)}catch{this.errored=!0}}sessionLabel;subagentId;logPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;bytesWritten=0;static isEnabled(){return k.AFK_SUBAGENT_LOG==="1"}write(e){if(this.errored||this.closed||this.bytesWritten>=xL)return;let n=JSON.stringify(e)+`
|
|
1301
1301
|
`;if(!this.stream){this.pendingLines.push(n),this.openStream();return}if(!this.streamReady){this.pendingLines.push(n);return}this.writeLine(n)}async close(){if(!this.closed)return this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(e=>{if(!this.stream||this.errored){e();return}this.stream.end(()=>e())})}openStream(){if(!this.stream){this.readyPromise=new Promise(e=>{this.readyResolve=e});try{let e=Is.createWriteStream(this.logPath,{flags:"a",encoding:"utf8",mode:384});this.stream=e,e.once("open",()=>{this.streamReady=!0;for(let n of this.pendingLines)this.writeLine(n);this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}),e.once("error",()=>{this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null})}catch{this.errored=!0,this.readyResolve?.(),this.readyResolve=null}}}writeLine(e){this.errored||!this.stream||this.bytesWritten>=xL||(this.bytesWritten+=Buffer.byteLength(e,"utf8"),this.stream.write(e))}}});import{z as OZ}from"zod";function CL(t,e,n,r){let s={...OZ.toJSONSchema(n,{target:"openapi-3.0"}),type:"object"};return{schema:{name:t,description:e,input_schema:s},handler:async(c,l,d)=>{let u=n.safeParse(c);if(!u.success){let p=u.error.issues.map(f=>`${f.path.join(".")||"<root>"}: ${f.message}`).join("; ");return{isError:!0,content:`Tool input validation failed for "${t}": ${p}`}}return r(u.data,l,d)}}}var PL=h(()=>{"use strict"});function DZ(t,e){let n=new Date().toISOString(),r=t.phase!==void 0?` phase="${OL(t.phase)}"`:"";return`<child-progress subagentId="${OL(e)}"${r} timestamp="${n}">`+FZ(t.message)+"</child-progress>"}function OL(t){return t.replace(/&/g,"&").replace(/"/g,""")}function FZ(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function FL(t,e,n){return async r=>{if(n?.aborted)return{content:JSON.stringify({delivered:!1,reason:"parent_aborted"})};if(typeof r!="object"||r===null)return{content:"emit_progress: input must be an object.",isError:!0};let o=r,s=o.message;if(typeof s!="string"||s.trim().length===0)return{content:'emit_progress: "message" must be a non-empty string.',isError:!0};let i=s;Buffer.byteLength(i,"utf8")>sf&&(i=DL(i,sf));let a=typeof o.phase=="string"&&o.phase.trim().length>0?o.phase.trim():void 0;a!==void 0&&Buffer.byteLength(a,"utf8")>256&&(a=DL(a,256));let c=typeof o.metadata=="object"&&o.metadata!==null&&!Array.isArray(o.metadata)?o.metadata:void 0,l={message:i,...a!==void 0?{phase:a}:{},...c!==void 0?{metadata:c}:{}};t.emitProgress(l);try{let d=DZ(l,t.id);e(d)}catch{return{content:JSON.stringify({delivered:!1,reason:"queue_error"})}}return{content:JSON.stringify({delivered:!0})}}}function DL(t,e){let n=Buffer.from(t,"utf8");if(n.byteLength<=e)return t;let r=Math.min(e,n.byteLength);for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.subarray(0,r).toString("utf8")}var sf,LL=h(()=>{"use strict";wS();sf=2048});import{z as Cs}from"zod";function NL(t,e,n,r){return e?LZ(t,n,r):()=>{}}function LZ(t,e,n){let r={current:void 0},o,s=CL("emit_progress",`Emit a structured progress event to the parent agent. The event is delivered to the parent at its next user-turn boundary, wrapped in a <child-progress> envelope. Use to report phase transitions, intermediate findings, or status updates so the parent stays informed without waiting for the full result. The "message" field is required (max ${sf} bytes). "phase" and "metadata" are optional. Note: this tool call counts as a tool-use round.`,Cs.object({message:Cs.string().describe("Progress message to deliver to the parent (required)."),phase:Cs.string().optional().describe('Optional phase label (e.g. "research", "planning", "done").'),metadata:Cs.record(Cs.string(),Cs.unknown()).optional().describe("Optional structured metadata for machine consumers.")}),async(i,a)=>r.current===void 0?{content:"emit_progress: handle not yet initialized.",isError:!0}:(o===void 0&&(o=FL(r.current,c=>{e?.queueFrameworkContext?e.queueFrameworkContext(c):e&&e.pushUserMessage(c)},n)),o(i,a)));return t.customTools=[...t.customTools??[],s],i=>{r.current=i,o=void 0}}var $L=h(()=>{"use strict";PL();LL()});function UL(t,e,n,r){if(t===void 0)return{subscribeHandler:async()=>({content:"workspace_subscribe: no store available.",isError:!0}),bindHandle:()=>{}};let o={current:void 0},s=async i=>{if(o.current===void 0)return{content:"workspace_subscribe: handle not yet initialized.",isError:!0};let a=i!=null&&typeof i=="object"?i:{},c=typeof a.subject=="string"&&a.subject.length>0?a.subject:void 0,l=a.type,u=typeof l=="string"&&new Set(["finding","evidence","hypothesis","decision","artifact","status"]).has(l)?l:void 0,p=Tg();return t.subscribe({id:p,agentId:e,subject:c,type:u,lastDeliveredSeq:0,deliveryFn:f=>{let m=o.current;if(m===void 0)return;let g=0;m._pendingWorkspaceEntries.length>=10&&(m._pendingWorkspaceEntries.shift(),g=1,m._workspaceDroppedSinceDrain++),m._pendingWorkspaceEntries.push(f),q(n,{phase:"workspace_delivery",metadata:{subscriptionId:p,agentId:e,entryId:String(f.id),droppedCount:g}})}}),q(n,{phase:"workspace_subscribed",metadata:{subscriptionId:p,agentId:e,...c!==void 0&&{query:c},...u!==void 0&&{type:u}}}),{content:JSON.stringify({subscriptionId:p,active:!0})}};return r?.setSubscribeHandler!==void 0&&r.setSubscribeHandler(s),{subscribeHandler:s,bindHandle:i=>{o.current=i,i._workspaceStore=t}}}var BL=h(()=>{"use strict";Nl();Ti();J()});var V,we=h(()=>{"use strict";xM();Bb();Kl();Qr();Kb();K0();X0();fe();J0();iL();lL();SL();_L();AL();IL();$L();BL();Rs();Rs();V=class{active=new Map;completed=new of;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentModel;parentCwd;parentReadRoots;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;parentAbortSignal;workspaceStore;sessionLabel;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;outputEventSink;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentProvider=e.parentModel!==void 0?z(e.parentModel):void 0,this.parentModel=e.parentModel,this.parentCwd=e.cwd,this.parentReadRoots=e.parentReadRoots,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.parentAbortSignal=e.parentAbortSignal,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.outputEventSink=e.outputEventSink,this.workspaceStore=e.workspaceStore,this.sessionLabel=e.sessionLabel,this.abortGraph=new xu(e.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),e.parentAbortSignal){let n=e.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)??this.completed.get(e)?.handle}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}setOutputEventSink(e){this.outputEventSink=e}setCwd(e){this.parentCwd=e,this.worktreeMainRootCache.delete(e)}setTraceWriter(e){this.parentTraceWriter=e,this.abortGraph.setTraceWriter(e)}getReadScopeInputs(){return{parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd}}async resolveMainRootForCwd(e){if(this.worktreeMainRootCache.has(e))return this.worktreeMainRootCache.get(e);let n=await W0(e);return this.worktreeMainRootCache.set(e,n),n}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){z0(e);let{id:n,resume:r,registry:o,effectiveTraceWriter:s,effectiveChildModel:i,coercedFrom:a,effectiveTimeoutMs:c}=EL({options:e,counter:++this.counter,managerHookRegistry:this.hookRegistry,parentTraceWriter:this.parentTraceWriter,parentModel:this.parentModel});o&&await $E(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...s?{traceWriter:s}:{}}),a!==void 0&&process.stderr.write(`[afk] subagent: child model "${a}" cannot run on this session's OpenAI/ChatGPT backend \u2014 running it as "${i??""}" instead (set AFK_DEFAULT_SUBAGENT_MODEL to choose a different one).
|
|
1302
|
-
`);let l=new AbortController;this.abortGraph.register(n,l),this.abortGraph.linkChild(this.rootId,n);let d=e.config.cwd??this.parentCwd,u=await q0({parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd,effectiveChildCwd:d,callerReadRoots:e.config.readRoots,callerExtraReadRoots:e.config.extraReadRoots,resolveMainRoot:A=>this.resolveMainRootForCwd(A)}),p=G0(e.config.writeRoots,d),f=sL({options:e,id:n,resume:r,registry:o,effectiveChildModel:i,effectiveTimeoutMs:c,inheritedReadRoots:u,composedWriteRoots:p,childController:l,parentCwd:this.parentCwd,parentApiKey:this.parentApiKey,parentBaseUrl:this.parentBaseUrl,parentProvider:this.parentProvider,parentTraceWriter:this.parentTraceWriter,parentSurface:this.parentSurface,parentCanUseTool:this.parentCanUseTool,workspaceStore:this.workspaceStore}),m=()=>{};f.cwd!==void 0&&(Wb(f.cwd),m=H0(f.cwd));let g=NL(f,e.progressEvents,e.parent.getInputStreamRef?.(),e.parent.abortSignal),y=UL(this.workspaceStore,n,s,f.provider),b,w,v,_;try{b=new Yr(f);let A=e.parent.getInputStreamRef?.(),I=e.parent.abortSignal,C=this.progressSink??Pt();v=e.agentType?.trim()||void 0,_=e.resolvedAgentType?.trim()||void 0;let T=e.parentId?.trim()||void 0,R=this.sessionLabel??e.parent.sessionId,E=Va.isEnabled()&&R?new Va(R,n):void 0;w=new rf(n,b,l,this.abortGraph,e.outputSchema,c,o,()=>{m();let P=w._currentStatus,H=P==="succeeded"||P==="failed"||P==="cancelled"?P:"succeeded";this.outputEventSink?.({type:"subagent_lifecycle",subagentId:n,status:H,...w._lastDurationMs!==void 0?{durationMs:w._lastDurationMs}:{}}),this.completed.add(n,w,{id:n,status:H}),this.active.delete(n),this.abortGraph.dispose(n),E?.close(),this.completed.recordHandle(n,w,w._currentStatus,w._currentTrace,w._lastStopReason)},A,I,v??e.idPrefix,C,T??e.parent.sessionId,s,this.onSubagentSucceededCb,e.config.idleTimeoutMs??rL()),E&&(w._logWriter=E),g(w),y.bindHandle(w),this.active.set(n,w)}catch(A){throw m(),this.abortGraph.dispose(n),A}let x=aL({effectiveTraceWriter:s,id:n,parentSessionId:e.parent.sessionId,rootId:this.rootId,effectiveChildModel:i,childConfig:f,promptHead:e.promptHead,effectiveAgentType:v,effectiveResolvedAgentType:_});return await cL({modelString:x,id:n,idPrefix:e.idPrefix,parentSessionId:e.parent.sessionId,effectiveResolvedAgentType:_}),this.outputEventSink?.({type:"subagent_lifecycle",subagentId:n,status:"started",...i!==void 0?{model:String(i)}:{},...v!==void 0?{agentType:v}:{},...e.promptHead!==void 0?{promptHead:e.promptHead}:{}}),w}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async abortAllAndDrain(e,n="user_signal",r=oL,o=!1){let s=[...this.active.values()];if(s.length===0)return o&&this.rootController.signal.aborted&&this.rearmRoot(),{drained:0,timedOut:!1};this.abortGraph.abort(this.rootId,e,n);let i=!1,a=new Promise(c=>setTimeout(()=>{i=!0,c()},r).unref());return await Promise.race([Promise.allSettled(s.map(c=>c.cancel())),a]),i&&console.warn(`[SubagentManager] abortAllAndDrain: ${s.length} child(ren) did not settle within ${r}ms \u2014 sealing anyway; their terminal rows may be missing`),o&&this.rearmRoot(),{drained:s.length,timedOut:i}}rearmRoot(){this.rootController=new AbortController,this.abortGraph.rearm(this.rootId,this.rootController),this.parentAbortSignal?.aborted&&this.rootController.abort(this.parentAbortSignal.reason)}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}}});async function jL(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=Ri()}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((c,l)=>l)),a=!1;return await Lo(t.map((c,l)=>l),o,async c=>{let l=t[c];n&&a&&await l.handle.cancel().catch(()=>{});let d=await l.handle.runToResult(l.prompt);if(s[c]=d,i.delete(c),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(c=>c.handle.teardown())),s}var HL=h(()=>{"use strict";ld()});function WL(t){let e=new Set;for(let n of t){let r=ja(n,NZ);r!==void 0&&e.add(r)}return e}var NZ,KL=h(()=>{"use strict";ws();ut();rd();NZ=new Set([...At,...$e,"memory_search","agent","skill"])});import{existsSync as tr,readdirSync as $Z,readFileSync as UZ}from"fs";import{join as yn}from"path";function GL(t=oe()){let e=[],n=yn(t,"skills");if(tr(n))for(let r of af(n)){let o=yn(n,r,"SKILL.md");tr(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of qL){let o=yn(t,`${r}s`);if(tr(o))for(let s of af(o))s.endsWith(".md")&&e.push({path:yn(o,s),type:r,source:"user"})}return e}function XL(t=Lt()){if(!tr(t))return[];let e=[],n=mn(t);for(let r of n){let s=Ow(t,r.path)?.key,i=yn(r.path,"skills");if(tr(i))for(let a of af(i)){let c=yn(i,a,"SKILL.md");if(!tr(c))continue;let l={path:c,type:"skill",source:"plugin"};s&&(l.plugin_key=s),e.push(l)}for(let a of qL){let c=yn(r.path,`${a}s`);if(tr(c))for(let l of af(c)){if(!l.endsWith(".md"))continue;let d={path:yn(c,l),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function zL(t=yn(oe(),"settings.json")){if(!tr(t))return[];try{let e=UZ(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function af(t){try{return $Z(t).filter(e=>!e.startsWith("."))}catch{return[]}}var qL,JL=h(()=>{"use strict";B();bs();qL=["command","agent"]});import{z as le}from"zod";import{mkdir as VL,appendFile as YL}from"fs/promises";import{join as vS}from"path";function HZ(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function WZ(t){let e=()=>{let s={};for(let i of eN)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function KZ(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function qZ(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
|
|
1302
|
+
`);let l=new AbortController;this.abortGraph.register(n,l),this.abortGraph.linkChild(this.rootId,n);let d=e.config.cwd??this.parentCwd,u=await q0({parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd,effectiveChildCwd:d,callerReadRoots:e.config.readRoots,callerExtraReadRoots:e.config.extraReadRoots,resolveMainRoot:A=>this.resolveMainRootForCwd(A)}),p=G0(e.config.writeRoots,d),f=sL({options:e,id:n,resume:r,registry:o,effectiveChildModel:i,effectiveTimeoutMs:c,inheritedReadRoots:u,composedWriteRoots:p,childController:l,parentCwd:this.parentCwd,parentApiKey:this.parentApiKey,parentBaseUrl:this.parentBaseUrl,parentProvider:this.parentProvider,parentTraceWriter:this.parentTraceWriter,parentSurface:this.parentSurface,parentCanUseTool:this.parentCanUseTool,workspaceStore:this.workspaceStore}),m=()=>{};f.cwd!==void 0&&(Wb(f.cwd),m=H0(f.cwd));let g=NL(f,e.progressEvents,e.parent.getInputStreamRef?.(),e.parent.abortSignal),y=UL(this.workspaceStore,n,s,f.provider),b,w,v,_;try{b=new Yr(f);let A=e.parent.getInputStreamRef?.(),I=e.parent.abortSignal,C=this.progressSink??Pt();v=e.agentType?.trim()||void 0,_=e.resolvedAgentType?.trim()||void 0;let T=e.parentId?.trim()||void 0,R=this.sessionLabel??e.parent.sessionId,E=Va.isEnabled()&&R?new Va(R,n):void 0;w=new rf(n,b,l,this.abortGraph,e.outputSchema,c,o,()=>{m();let P=w._currentStatus,H=P==="succeeded"||P==="failed"||P==="cancelled"?P:"succeeded";this.outputEventSink?.({type:"subagent_lifecycle",subagentId:n,status:H,...w._lastDurationMs!==void 0?{durationMs:w._lastDurationMs}:{},...w._currentTrace.turnCount>0?{turnCount:w._currentTrace.turnCount}:{},...w._lastStopReason!==void 0?{stopReason:w._lastStopReason}:{}}),this.completed.add(n,w,{id:n,status:H}),this.active.delete(n),this.abortGraph.dispose(n),E?.close(),this.completed.recordHandle(n,w,w._currentStatus,w._currentTrace,w._lastStopReason)},A,I,v??e.idPrefix,C,T??e.parent.sessionId,s,this.onSubagentSucceededCb,e.config.idleTimeoutMs??rL()),E&&(w._logWriter=E),g(w),y.bindHandle(w),this.active.set(n,w)}catch(A){throw m(),this.abortGraph.dispose(n),A}let x=aL({effectiveTraceWriter:s,id:n,parentSessionId:e.parent.sessionId,rootId:this.rootId,effectiveChildModel:i,childConfig:f,promptHead:e.promptHead,effectiveAgentType:v,effectiveResolvedAgentType:_});return await cL({modelString:x,id:n,idPrefix:e.idPrefix,parentSessionId:e.parent.sessionId,effectiveResolvedAgentType:_}),this.outputEventSink?.({type:"subagent_lifecycle",subagentId:n,status:"started",...i!==void 0?{model:String(i)}:{},...v!==void 0?{agentType:v}:{},...e.promptHead!==void 0?{promptHead:e.promptHead}:{},...e.parentId?{parentToolUseId:e.parentId}:{}}),w}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async abortAllAndDrain(e,n="user_signal",r=oL,o=!1){let s=[...this.active.values()];if(s.length===0)return o&&this.rootController.signal.aborted&&this.rearmRoot(),{drained:0,timedOut:!1};this.abortGraph.abort(this.rootId,e,n);let i=!1,a=new Promise(c=>setTimeout(()=>{i=!0,c()},r).unref());return await Promise.race([Promise.allSettled(s.map(c=>c.cancel())),a]),i&&console.warn(`[SubagentManager] abortAllAndDrain: ${s.length} child(ren) did not settle within ${r}ms \u2014 sealing anyway; their terminal rows may be missing`),o&&this.rearmRoot(),{drained:s.length,timedOut:i}}rearmRoot(){this.rootController=new AbortController,this.abortGraph.rearm(this.rootId,this.rootController),this.parentAbortSignal?.aborted&&this.rootController.abort(this.parentAbortSignal.reason)}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}}});async function jL(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=Ri()}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((c,l)=>l)),a=!1;return await Lo(t.map((c,l)=>l),o,async c=>{let l=t[c];n&&a&&await l.handle.cancel().catch(()=>{});let d=await l.handle.runToResult(l.prompt);if(s[c]=d,i.delete(c),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(c=>c.handle.teardown())),s}var HL=h(()=>{"use strict";ld()});function WL(t){let e=new Set;for(let n of t){let r=ja(n,NZ);r!==void 0&&e.add(r)}return e}var NZ,KL=h(()=>{"use strict";ws();ut();rd();NZ=new Set([...At,...$e,"memory_search","agent","skill"])});import{existsSync as tr,readdirSync as $Z,readFileSync as UZ}from"fs";import{join as yn}from"path";function GL(t=oe()){let e=[],n=yn(t,"skills");if(tr(n))for(let r of af(n)){let o=yn(n,r,"SKILL.md");tr(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of qL){let o=yn(t,`${r}s`);if(tr(o))for(let s of af(o))s.endsWith(".md")&&e.push({path:yn(o,s),type:r,source:"user"})}return e}function XL(t=Lt()){if(!tr(t))return[];let e=[],n=mn(t);for(let r of n){let s=Ow(t,r.path)?.key,i=yn(r.path,"skills");if(tr(i))for(let a of af(i)){let c=yn(i,a,"SKILL.md");if(!tr(c))continue;let l={path:c,type:"skill",source:"plugin"};s&&(l.plugin_key=s),e.push(l)}for(let a of qL){let c=yn(r.path,`${a}s`);if(tr(c))for(let l of af(c)){if(!l.endsWith(".md"))continue;let d={path:yn(c,l),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function zL(t=yn(oe(),"settings.json")){if(!tr(t))return[];try{let e=UZ(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function af(t){try{return $Z(t).filter(e=>!e.startsWith("."))}catch{return[]}}var qL,JL=h(()=>{"use strict";B();bs();qL=["command","agent"]});import{z as le}from"zod";import{mkdir as VL,appendFile as YL}from"fs/promises";import{join as vS}from"path";function HZ(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function WZ(t){let e=()=>{let s={};for(let i of eN)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function KZ(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function qZ(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
|
|
1303
1303
|
`)}function GZ(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
|
|
1304
1304
|
`);for(let r of e){let o=`${r.event}-${r.index}`;n.push(`### Hook \`${o}\``),n.push(""),n.push("```json"),n.push(JSON.stringify(r.raw,null,2)),n.push("```"),n.push("")}return n.join(`
|
|
1305
1305
|
`)}function XZ(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function zZ(t,e,n){let r=n?.apiKey,o=Ve({defaultSubagentModel:n?.defaultSubagentModel,defaultModel:n?.defaultModel}),s=n?.callId,i=typeof t=="object"&&t!==null?t:{},a=BZ.parse(i),c=a.writeBriefs??!0,l=a.scope??"all",d=HZ(l);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let u=e.sessionId,p=ue("audit-fit"),f={skill:p["01-skill-inspector.md"],command:p["02-command-inspector.md"],agent:p["03-agent-inspector.md"],hook:p["04-hook-inspector.md"]};for(let M of eN)if(!f[M])throw new Error(`audit-fit skill missing inspector prompt for ${M}`);let m=d.runUserDiscovery?GL():[],g=d.runPluginDiscovery?XL():[],y={skill:[],command:[],agent:[]};for(let M of[...m,...g])y[M.type].push(M);let b=new V({apiKey:r,...n?.defaultModel!==void 0?{parentModel:n.defaultModel}:{},...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},...n?.workspaceStore!==void 0?{workspaceStore:n.workspaceStore}:{}}),w=WL(Yt.allowedTools),v=()=>async M=>w.has(M)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${M} not allowed for audit-fit inspectors. Allowed tools: ${[...w].join(", ")}`},_=[];for(let M of jZ){let N=y[M];if(N.length===0)continue;let $=f[M];$&&_.push({type:M,prompt:`${$}
|
|
@@ -1331,7 +1331,7 @@ ${N.rationale}
|
|
|
1331
1331
|
---
|
|
1332
1332
|
Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
|
|
1333
1333
|
`;await YL(U,j),C++}}let T=vt();await VL(T,{recursive:!0});let R=M=>{let N=0;for(let $ of Object.values(M))for(let U of Object.values($))N+=U;return N},E=M=>{let N=A.user[M]??{},$=A.plugin[M]??{},U=j=>Object.values(j).reduce((K,Y)=>K+Y,0);return U(N)+U($)},P={timestamp:new Date().toISOString(),surface:"afk",scope:l,total_artifacts:x.length,misfits_count:I.length,briefs_written:C,by_source:{user:R(A.user),plugin:R(A.plugin)},by_type:{skill:E("skill"),command:E("command"),agent:E("agent"),hook:E("hook")}},H=vS(T,"audit-fit-telemetry.jsonl");return await YL(H,JSON.stringify(P)+`
|
|
1334
|
-
`),{inventory:A,misfits:I,briefs_written:C,total_artifacts:x.length}}var ZL,QL,
|
|
1334
|
+
`),{inventory:A,misfits:I,briefs_written:C,total_artifacts:x.length}}var ZL,QL,uLe,BZ,jZ,eN,JZ,tN=h(()=>{"use strict";bt();Jt();Jr();we();HL();Lw();KL();B();JL();ZL=le.object({path:le.string(),type:le.enum(["skill","command","agent","hook"]),source:le.enum(["user","plugin"]),plugin_key:le.string().optional(),verdict:le.enum(["correct","misfit","outlier"]),recommended_type:le.string(),rationale:le.string(),confidence:le.enum(["high","med","low"])}),QL=le.record(le.string(),le.record(le.string(),le.number())),uLe=le.object({inventory:le.object({user:QL,plugin:QL}),misfits:le.array(ZL),briefs_written:le.number(),total_artifacts:le.number()}),BZ=le.object({writeBriefs:le.boolean().optional(),scope:le.enum(["user","plugin","all"]).optional()}),jZ=["skill","command","agent"],eN=["skill","command","agent","hook"];JZ={name:"audit-fit",description:"Audit ~/.afk artifacts (skills, commands, agents, hooks) for correct type categorization. Walks user-scope dirs (~/.afk/{skills,commands,agents}/) and every plugin installed under ~/.afk/plugins/ (flat and marketplace-cache layouts), plus ~/.afk/settings.json for hooks. Dispatches per-type inspectors in parallel, applies decision heuristics (progressive-disclosure value, isolation need, deterministic vs. reasoning), flags misfits. Generates migration briefs only for user-scope misfits (plugin misfits are inventory-only \u2014 refactoring vendored plugin code is the maintainer's job). Optional `scope` input filters to `user`, `plugin`, or `all` (default). Use for inventory audits after bulk authoring, imports, or periodic hygiene.",handler:zZ,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"],audience:"internal",category:"Review & verify"};Je(JZ)});async function VZ(){throw new Error("get-started is a load skill; its handler should never be called directly. Invoke via the `skill` tool or `/get-started` slash command.")}var YZ,nN=h(()=>{"use strict";Jt();YZ={name:"get-started",description:"Guided first-run onboarding for AFK. Runs a preflight check (git repo, model provider, AFK.md, Exa/Telegram/service config), asks the user their name and gives a brief intro, detects importable Claude Code / Codex assets and offers `afk migrate`, walks optional capability setup (Exa Search, Telegram via /telegram-setup, background service via /service-setup), then recommends /init to generate project context and /clear to start fresh \u2014 ending by routing the user to their first task. Runs interactively in the current session.",handler:VZ,context:"load",audience:"public",whenToUse:"When someone is setting up AFK for the first time or asks how to get going \u2014 triggers on `/get-started`, 'how do I start', 'set me up', 'onboard me', or a fresh install with no AFK.md and unconfigured capabilities. Best run in the interactive REPL.",category:"Setup & ops"};Je(YZ)});async function rN(t,e,n,r,o="sonnet",s,i,a){let l=ue("mint")["spec.md"];if(!l)throw new Error("mint skill missing spec.md prompt");let p=await(await new V({...n!==void 0?{cwd:n}:{},...s!==void 0?{parentReadRoots:s}:{},...i!==void 0?{traceWriter:i}:{},...a!==void 0?{workspaceStore:a}:{}}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:l,apiKey:re(o)},idPrefix:"mint-spec",agentType:"mint-spec",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Create a detailed specification for: ${t}`);if(p.status!=="succeeded"||!p.message)throw new Error(`spec phase failed: ${Oe(p)}`);if(Ye(p.stopReason))throw new Error(`spec phase returned an incomplete result (stopReason=${p.stopReason})`);return p.message.content}var oN=h(()=>{"use strict";we();Re();be();bt()});async function sN(t,e,n,r,o="sonnet",s,i,a){let l=ue("mint")["research.md"];if(!l)throw new Error("mint skill missing research.md prompt");let p=await(await new V({...n!==void 0?{cwd:n}:{},...s!==void 0?{parentReadRoots:s}:{},...i!==void 0?{traceWriter:i}:{},...a!==void 0?{workspaceStore:a}:{}}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:l,apiKey:re(o)},idPrefix:"mint-research",agentType:"mint-research",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Gather context and research for this specification:
|
|
1335
1335
|
|
|
1336
1336
|
${t}`);if(p.status!=="succeeded"||!p.message)throw new Error(`research phase failed: ${Oe(p)}`);if(Ye(p.stopReason))throw new Error(`research phase returned an incomplete result (stopReason=${p.stopReason})`);return p.message.content}var iN=h(()=>{"use strict";we();Re();be();bt()});async function aN(t,e,n,r,o,s="sonnet",i,a,c){let d=ue("mint")["plan.md"];if(!d)throw new Error("mint skill missing plan.md prompt");let p=await new V({...r!==void 0?{cwd:r}:{},...i!==void 0?{parentReadRoots:i}:{},...a!==void 0?{traceWriter:a}:{},...c!==void 0?{workspaceStore:c}:{}}).forkSubagent({parent:{sessionId:n},config:{model:s,systemPrompt:d,apiKey:re(s)},idPrefix:"mint-plan",agentType:"mint-plan",phaseRole:"read-only",...o?{parentId:o}:{}}),f=`Specification:
|
|
1337
1337
|
${t}
|
|
@@ -1411,13 +1411,13 @@ ${e}`:s,a=new V({parentAbortSignal:n?.abortSignal,...r?.traceWriter!==void 0?{tr
|
|
|
1411
1411
|
`)}return c(o,[],0),i.sort((l,d)=>l.name<d.name?-1:l.name>d.name?1:0),Za.set(n,i),i}var Oee,df,Za,Fee,BN=h(()=>{"use strict";ws();Pw();F();et();bs();Oee=10,df=1e3,Za=new Map;Mp(()=>Za.clear());Fee=/[\u0000-\u001F\u007F-\u009F]/});import{existsSync as Lee,readFileSync as Nee}from"fs";import{join as $ee}from"path";function jN(t){let e=$ee(t,".claude-plugin","plugin.json");if(!Lee(e))return{name:null,version:null};try{let n=JSON.parse(Nee(e,"utf8"));return{name:typeof n.name=="string"&&n.name.trim()?n.name.trim():null,version:typeof n.version=="string"&&n.version.trim()?n.version.trim():null}}catch{return{name:null,version:null}}}var HN=h(()=>{"use strict"});import{readFileSync as Uee}from"node:fs";import{join as Bee}from"node:path";function Ep(t,e){let n=Aa(t,e),r=e?.excludeName,s=(r!==void 0&&r.length>0?n.filter(a=>a.name!==r&&!a.name.endsWith(`:${r}`)):n).filter(a=>a.source!=="command");if(s.length===0)return"";let i=[];for(let a of s){let c=a.argumentHint?`${a.argumentHint}`:"",l=c?`- \`${a.name} ${c}\`: ${a.description}`:`- ${a.name}: ${a.description}`;i.push(l),a.whenToUse&&i.push(` When to use: ${a.whenToUse}`)}return["Available skills (invoke via the `skill` tool):","","Each skill either forks an isolated subagent (delegation \u2014 preserves the main session's context) or loads its instructions directly into your current context for you to execute directly. The mode is fixed per-skill, not per-call. To run a skill N times in parallel with isolation, dispatch N subagents (via `agent` or `compose`) that each call `skill` once. Prefer a skill over inline investigation when the task shape matches.","",...i].join(`
|
|
1412
1412
|
`)}function WN(t,e){return[...AD(t,e),...UN(t,e)]}function Aa(t,e){let n=[],r=new Set,o=k.AFK_INTERNAL==="1",s=Qi(Yi());Ya(jc(),"user"),AM("project"),Ya(Tv(e?.cwd),"project");for(let{dir:c,origin:l}of s.skillRoots)Ya(c,l);for(let c of Ab()){let l=fn(c);_b(l,o)&&(n.push({name:c,description:l.description,source:l.origin==="user"?"user":l.origin==="project"?"project":l.origin?.startsWith("imported:")?"imported":"builtin",argumentHint:l.argumentHint,whenToUse:l.whenToUse}),r.add(c),c.includes(":")&&r.add(c.split(":").pop()))}let i=t??uf(e),a=Fp();for(let c of i){if(c.type!=="local")continue;let l=WN(c.path,a);for(let d of l)!d.name||r.has(d.name)||_b({audience:d.audience},o)&&(n.push({name:d.name,description:d.description??`Skill from plugin at ${c.path}`,source:d.origin==="command"?"command":"plugin",argumentHint:d.argumentHint,whenToUse:d.whenToUse}),r.add(d.name))}return n}function Xa(t,e){let n=new Map,r=t??uf(e),o=Fp();for(let s of r){if(s.type!=="local")continue;let i=WN(s.path,o);for(let a of i)a.name&&a.body&&a.body.length>0&&!n.has(a.name)&&n.set(a.name,{body:a.body,pluginPath:s.path,...a.allowedTools!==void 0?{allowedTools:a.allowedTools}:{},...a.context!==void 0?{context:a.context}:{},...a.readOnly===!0?{readOnly:!0}:{},...a.model!==void 0?{model:a.model}:{}})}return n}function KN(t,e=()=>{}){let n=t??uf(),r=[],o=new Set;for(let s of n){if(s.type!=="local")continue;let i=jN(s.path).name;if(i!==null)for(let a of $p(Bee(s.path,"agents"))){let c=Q(a),l;try{l=Uee(a,"utf8")}catch(p){let f=Q(p instanceof Error?p.message:String(p));e(`[afk] agents: cannot read ${c}: ${f}`);continue}let d=no(l,p=>e(`[afk] agents: ${c}: ${p}`));if(d===void 0)continue;let u=`${i}:${d.name}`;o.has(u)||(o.add(u),r.push({name:u,definition:d.definition,source:`plugin:${i}`,filePath:a,...d.bashReadOnly===!0?{bashReadOnly:!0}:{},...d.ignoredKeys!==void 0?{ignoredKeys:d.ignoredKeys}:{}}))}}return r}function uf(t){return[...mn(Ev(t?.cwd)),...mn(),...mn(Av()),...Qi(Yi()).pluginRoots.flatMap(({dir:e,binary:n})=>mn(e,{trustAll:!0,sourceEnabled:wx(n)}))]}async function qN(){await NN(uf(),{pluginApi:{registerSkill:Je,listSkills:Ab,getSkill:fn,loadSkillPrompts:ue,env:k,SubagentManager:V,describeFailure:Oe,discoverPluginSkillBodies:Xa,getAgentFrameworkDir:vt,getSkillsDir:jc,getSessionsDir:ce,getOrDeriveFacet:Xr,listSessionIds:ma,deriveSessionFacet:fa,loadStoredSession:fu}})}var Xn=h(()=>{"use strict";FN();Jt();bt();RS();bs();$N();ws();BN();HN();Ha();Kw();et();we();Re();lb();B();F();Id()});function Os(t,e,n){let r=Ci({cwd:e,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:n.surface,...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:n.workspace}),o=[t.toolBase];return t.userSystem&&o.push(t.userSystem),o.push(t.memoryPrompt),t.workspacePrompt.length>0&&o.push(t.workspacePrompt),t.hotMemory.length>0&&o.push(t.hotMemory),o.push(r),t.manifest.length>0&&o.push(t.manifest),o.join(`
|
|
1413
1413
|
|
|
1414
|
-
`)}var pf=h(()=>{"use strict";Ue()});function GN(t){let{config:e,cwd:n}=t,r=t.hasSkillExecutor?Ep(void 0,{cwd:n,...typeof e.skillDispatchName=="string"&&e.skillDispatchName.length>0?{excludeName:e.skillDispatchName}:{}}):"",o=qu(e.isSkillDispatch),s=Gu(t.readOnlyMemory),i=Xu(t.workspaceEnabled),a={surface:t.surface,sessionId:e.sessionId,depth:e.depth,maxDepth:e.maxDepth,workspace:t.runtimeStateSource.getWorkspace()},c={toolBase:o,memoryPrompt:s,workspacePrompt:i,hotMemory:e.hotMemory??"",manifest:r,userSystem:t.userSystem};return{stableSystemPrefix:c,toolSystemAppend:Os(c,n,a)}}var XN=h(()=>{"use strict";Xn();qb();pf()});import jee from"@anthropic-ai/sdk";function zN(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function JN(t,e,n,r){let o=e.config,{localMode:s,token:i}=VP(o);if(!i||i.length===0)throw new Error(`${n} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let a=Ao(i),{client:c,throttleQueue:l,systemPrefix:d,tokenRefresher:u}=pM({config:o,token:i,authMode:a,localMode:s,factory:t.providerFactory??wu(),createClient:T=>new jee(T)}),p=zN(o.systemPrompt),f=typeof o.model=="string"&&o.model.length>0?Ee(o.model)??o.model:r,m=Cl(o,f),g=o.permissionMode??"default";t.setCurrentPermissionMode(g),t.ensureSharedRoots(o.cwd),o.cwd&&t.setCurrentCwd(o.cwd);let y=t.getSharedReadRoots(),b=t.getSharedWriteRoots();o.readRoots&&y&&y.length<=1&&(y.length=0,y.push(...o.readRoots)),o.writeRoots&&b&&b.length<=1&&(b.length=0,b.push(...o.writeRoots));let{queryDispatcher:w,runtimeStateSource:v,toolDefs:_,resolvedSessionId:x}=vM({config:o,model:f,permissionMode:g,surface:t.surface,providerName:n,externalTools:t.externalTools,sharedReadRoots:y,sharedWriteRoots:b,getCwd:()=>t.getCurrentCwd()||o.cwd||process.cwd(),getMcpTools:()=>t.mcpManager?.getMcpTools()??[],getSubagents:()=>t.subagentExecutor?t.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>t.getMintedSessionId(),setMintedSessionId:T=>{t.setMintedSessionId(T)},getPresenceSessionId:()=>t.getPresenceSessionId(),setPresenceSessionId:T=>{t.setPresenceSessionId(T)},buildDispatcher:(T,R)=>t.buildDispatcher(T,R)}),A=o.cwd||process.cwd(),{stableSystemPrefix:I,toolSystemAppend:C}=GN({config:o,cwd:A,surface:t.surface,readOnlyMemory:t.readOnlyMemory,workspaceEnabled:t.workspaceStore!==void 0,hasSkillExecutor:!!t.skillExecutor,runtimeStateSource:v,userSystem:p});return IM({prompt:e.prompt,options:{model:f,maxTokens:m,system:C},provenance:{systemPrompt:{source:o.systemPromptSource??"none",shape:typeof o.systemPrompt=="string"?"string":Array.isArray(o.systemPrompt)?"string[]":o.systemPrompt!=null?"preset":"undefined",...typeof o.systemPrompt=="string"?{length:o.systemPrompt.length}:{}},...o.apiKey?{apiKey:{source:"config"}}:{}}}),{client:c,authMode:a,localMode:s,model:f,maxTokens:m,cwd:A,systemPrefix:d,throttleQueue:l,tokenRefresher:u,queryDispatcher:w,runtimeStateSource:v,toolDefs:_,resolvedSessionId:x,stableSystemPrefix:I,toolSystemAppend:C}}var IS=h(()=>{"use strict";xn();lt();Ol();YP();Su();fM();TM();XN();Sa()});function VN(t){let e=t.initialUsageInputTokens!==void 0&&t.initialUsageInputTokens>0?{inputTokens:t.initialUsageInputTokens,stopReason:null,resultSubtype:"success",isError:!1}:null;return{messages:t.initialMessages?[...t.initialMessages]:[],currentModel:t.model,requestedModel:t.requestedModel??t.model,currentPermissionMode:t.permissionMode,userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,lastUsage:e,closed:!1,autoCompactThreshold:t.autoCompactThreshold}}var YN=h(()=>{"use strict"});function ec(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=k.AFK_DISABLE_PROMPT_CACHE;if(e===void 0||e.length===0)return!0;let n=e.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function ao(){let t=k.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":Hee}function ff(t){return ec(t)&&ao()==="1h"}function QN(t,e){if(t.length===0)return t;let n=t[t.length-1],r=e$(n,e);return r===n?t:[...t.slice(0,-1),r]}function ZN(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Wee(n,e);return r===n?t:[...t.slice(0,-1),r]}function Wee(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=e$(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function e$(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var Hee,Ds=h(()=>{"use strict";F();Hee="1h"});var CS=h(()=>{"use strict";qo()});function Jee(t){let e=n=>n===void 0?void 0:n*PS;return{inputPerMTok:t.inputPerMTok*PS,outputPerMTok:t.outputPerMTok*PS,...e(t.cacheWrite5mPerMTok)!==void 0?{cacheWrite5mPerMTok:e(t.cacheWrite5mPerMTok)}:{},...e(t.cacheWrite1hPerMTok)!==void 0?{cacheWrite1hPerMTok:e(t.cacheWrite1hPerMTok)}:{},...e(t.cacheReadPerMTok)!==void 0?{cacheReadPerMTok:e(t.cacheReadPerMTok)}:{}}}function Vee(t){return t.responseSpeed??t.requestSpeed??"standard"}function Yee(t){return as(t,t$,Xee)}function MS(t,e,n,r,o,s,i={}){let a=Yee(t);if(!a)return;let c=Vee(i)==="fast"&&zee.test(t)?Jee(a):a,l=1e6,d=Ke(e),u=Ke(n),p=Ke(r),f=Ke(o),m=d/l*c.inputPerMTok,g=u/l*c.outputPerMTok,y=c.cacheWrite5mPerMTok??c.inputPerMTok*Kee,b=c.cacheWrite1hPerMTok??c.inputPerMTok*qee,w=c.cacheReadPerMTok??c.inputPerMTok*Gee,v=s??{ephemeral5m:f,ephemeral1h:0},_=Ke(v.ephemeral5m),x=Ke(v.ephemeral1h),A=Math.max(0,f-(_+x)),I=_/l*y+x/l*b+A/l*b,C=p/l*w;return m+g+I+C}var Kee,qee,Gee,t$,Xee,PS,zee,OS=h(()=>{"use strict";Vu();Kee=1.25,qee=2,Gee=.1,t$=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-5",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-8",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-7",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-6",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-sonnet-4-6",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-sonnet-4-5-20250929",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-4-5-20250929",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-haiku-4-5-20250929",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-haiku-4-5-20251001",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-3-7-sonnet-20250219",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20241022",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20240620",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-haiku-20241022",{inputPerMTok:.8,outputPerMTok:4,cacheWrite5mPerMTok:1,cacheWrite1hPerMTok:1.6,cacheReadPerMTok:.08}],["claude-3-opus-20240229",{inputPerMTok:15,outputPerMTok:75,cacheWrite5mPerMTok:18.75,cacheWrite1hPerMTok:30,cacheReadPerMTok:1.5}],["claude-3-sonnet-20240229",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-haiku-20240307",{inputPerMTok:.25,outputPerMTok:1.25,cacheWrite5mPerMTok:.3,cacheWrite1hPerMTok:.5,cacheReadPerMTok:.03}]]),Xee=/-\d{8}$/,PS=2,zee=/^claude-opus-(?:5|4-8)(?:-|$)/});function Qee(t){let e=t.speed;return e==="fast"||e==="standard"?e:void 0}function Zee(t){let e=o=>Number.isFinite(o)&&o>=0?o:0,n=t.cache_creation;if(n)return{ephemeral5m:e(n.ephemeral_5m_input_tokens??0),ephemeral1h:e(n.ephemeral_1h_input_tokens??0)};let r=e(t.cache_creation_input_tokens??0);return ao()==="1h"?{ephemeral5m:0,ephemeral1h:r}:{ephemeral5m:r,ephemeral1h:0}}function DS(t,e,n,r){if(!t)return{stopReason:e??null};let o=Qee(t),s={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null,raw:{...t,...o?{speed:o}:{}}};if(t.cache_read_input_tokens!=null&&(s.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(s.cacheCreationTokens=t.cache_creation_input_tokens),s.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n){let i=MS(n,t.input_tokens??0,t.output_tokens??0,t.cache_read_input_tokens??0,t.cache_creation_input_tokens??0,Zee(t),{...r?{requestSpeed:r}:{},...o?{responseSpeed:o}:{}});i!==void 0&&(s.totalCostUsd=i)}return s}var n$=h(()=>{"use strict";Ds();OS()});var FS=h(()=>{"use strict";OS();n$();Gb()});function tc(t){return t>2147483647?2147483647:t}var LS=h(()=>{"use strict"});function mf(){let t=k.AFK_MODEL_TTFB_TIMEOUT_MS;if(t===void 0||t.trim()==="")return r$;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?r$:tc(e)}function o$(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?void 0:(t<nte?t:rte)+tte}function s$(t,e){if(e<=0)return{signal:t,timedOut:()=>!1,firstByteSeen:()=>{},extend:()=>{},dispose:()=>{}};let n=new AbortController,r=AbortSignal.any([t,n.signal]),o=!1,s=!1,i=Date.now()+e,a,c=u=>{a=setTimeout(()=>{o=!0,n.abort(new Error(ete))},tc(u)),a.unref()};c(e);let l=()=>{s||(s=!0,clearTimeout(a))};return{signal:r,timedOut:()=>o,firstByteSeen:l,extend:u=>{s||o||typeof u!="number"||!Number.isFinite(u)||u<=0||(i+=u,clearTimeout(a),c(Math.max(1,i-Date.now())))},dispose:l}}var r$,ete,tte,nte,rte,gf=h(()=>{"use strict";F();LS();r$=18e4;ete="model_ttfb_timeout",tte=3e4,nte=6e4,rte=8e3});function a$(){let t=k.AFK_MODEL_STALL_TIMEOUT_MS;if(t===void 0||t.trim()==="")return i$;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?i$:tc(e)}function l$(t){return t instanceof Error&&t.message===c$}function NS(t){return new Error(`Model stream stalled: no output for ${Math.round(t/1e3)}s after the response had already started streaming. The round was aborted rather than left hanging (issue #762: two sessions hung 38 and 63 minutes with no terminal event). A round that keeps producing output is never cut off, no matter how long it runs. Raise AFK_MODEL_STALL_TIMEOUT_MS, or set it to 0 to disable this bound.`)}function d$(t,e,n){if(e<=0)return{signal:t,timedOut:()=>!1,progress:()=>{},dispose:()=>{}};let r=new AbortController,o=AbortSignal.any([t,r.signal]),s,i=!1,a=!1,c=u=>{if(!(a||i)){i=!0,s=void 0;try{n?.({stallTimeoutMs:e,elapsedSinceLastProgressMs:Date.now()-u})}catch{}r.signal.aborted||r.abort(new Error(c$))}};return{signal:o,timedOut:()=>i,progress:()=>{if(a||i)return;s!==void 0&&clearTimeout(s);let u=Date.now(),p=setTimeout(()=>c(u),e);p.unref(),s=p},dispose:()=>{a||(a=!0,s!==void 0&&clearTimeout(s),s=void 0)}}}var i$,c$,hf=h(()=>{"use strict";F();LS();i$=12e5;c$="model_stream_stall_timeout"});function yf(t,e=Math.random){return t+Math.floor(e()*t*ate)}function p$(t=Math.random){let e=ite-u$;return u$+Math.floor(t()*e)}function f$(t){return t.type==="turn.completed"&&t.usage.stopReason===st}function m$(t){let e=k.AFK_OVERLOAD_PAUSE_MS;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(Math.floor(n),ste)}return t!==void 0&&cte.has(t)?ote:0}var $S,ote,ste,u$,ite,ate,cte,nc=h(()=>{"use strict";F();rs();rs();$S="Anthropic is overloaded (HTTP 529) and did not recover within this turn's retry budget. This is an upstream capacity event, not an afk error. The turn was committed, so the conversation so far is preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state once capacity frees up.",ote=600*1e3,ste=7200*1e3,u$=60*1e3,ite=120*1e3,ate=.25;cte=new Set(["cli","repl","telegram","web"])});function wf(t){if(!Number.isFinite(t)||t<=0)return 0;let e=Math.floor(t*2/3);return Math.max(1,e)}function g$(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function rc(t){if(t===null||typeof t!="object")return!1;let e=t;if(e.status===529||e.status===503)return!0;let n=e.error;if(n===null||typeof n!="object")return!1;let r=n;return((r.error!==null&&typeof r.error=="object"?r.error.type:void 0)??r.type)==="overloaded_error"}var bf,Fs=h(()=>{"use strict";bf=class{overloadRetries=0;streamIncompleteRetries=0;ttfbRetries=0;canRetryOverload(){return this.overloadRetries<3}canRetryStreamIncomplete(){return this.streamIncompleteRetries<2}canRetryTtfb(){return this.ttfbRetries<2}reset(){this.overloadRetries=0,this.streamIncompleteRetries=0,this.ttfbRetries=0}}});async function*dte(t,e,n){q(t.traceWriter,{phase:"ttfb_timeout",durationMs:Date.now()-e,metadata:{reason:"ttfb-timeout",source:"first-byte",resolvedModel:t.model,attempt:n}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId}}async function*BS(t,{input:e,turn:n,retry:r,requestStartedAt:o}){return t==="ttfb"?(r.ttfbRetries+=1,yield*dte(e,o,r.ttfbRetries),"continue"):t==="overload"?(r.overloadRetries+=1,q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:r.overloadRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*h$(yf(5e3*Math.pow(2,r.overloadRetries-1)),e,n),e.signal.aborted?"terminated":"continue"):(r.streamIncompleteRetries+=1,q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"stream-incomplete",source:"mid-stream",attempt:r.streamIncompleteRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*h$(1e3*Math.pow(2,r.streamIncompleteRetries-1),e,n),e.signal.aborted?"terminated":"continue")}async function*h$(t,e,n){await We(t,e.signal),e.signal.aborted&&(yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId})}var y$=h(()=>{"use strict";J();Bn();nc();Fs()});function w$(t){let e=t.fastModeController?.snapshotTurn({resolvedModelId:t.model,providerFamily:"anthropic-direct",hasCustomEndpoint:t.baseUrl!==void 0,executionPath:"top-level"}),n=e?.effective===!0,r=An(t.authMode,t.sessionId,t.requestId,t.effort!==void 0,ff(t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{}),n);return{decision:e,runInput:{client:t.client,messages:t.messages,system:t.system,tools:t.tools,toolDispatcher:t.toolDispatcher,model:t.model,maxTokens:t.maxTokens,headers:r,signal:t.signal,ctx:{sessionId:t.sessionId},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...n?{fastMode:!0}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.onUsageProgress?{onUsageProgress:t.onUsageProgress}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{}}}}function Sf(t,e){let n=t instanceof Error?t:new Error(String(t));if(!e||n.message.startsWith(b$))return n;let r=new Error(`${b$} ${n.message}`,{cause:n});r.name=n.name,n.stack!==void 0&&(r.stack=n.stack);for(let o of Object.getOwnPropertyNames(n)){if(o==="message"||o==="stack")continue;let s=Object.getOwnPropertyDescriptor(n,o);s!==void 0&&Object.defineProperty(r,o,s)}return r}var b$,jS=h(()=>{"use strict";xn();Ds();b$="[Fast mode requested; no standard-mode fallback will be attempted]"});async function*S$(t,e,n){let r=e.throttleQueue;if(!r)return await t;r.resetAttempts();let o=Symbol("create-done"),s=!1,i=t.then(a=>(s=!0,a),a=>{throw s=!0,a});for(;;){for(let c of r.takeAll())n?.(c.retryAfterMs),yield{type:"rate_limit",sessionId:e.ctx.sessionId,status:c.status,attempt:c.attempt,...c.retryAfterMs!==void 0?{retryAfterMs:c.retryAfterMs}:{}};if(s)return await i;await Promise.race([i.then(()=>o,()=>o),r.waitForItem().then(()=>{})])}}var k$=h(()=>{"use strict"});function v$(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var T$=h(()=>{"use strict"});function ute(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}async function pte(t,e,n,r,o){for(let s=0;;s++){if(s>0){let i=yf(5e3*Math.pow(2,s-1));if(await We(i,o),o.aborted)throw new Error("aborted")}try{return await Promise.resolve(t.messages.create(e,{headers:n,signal:r}))}catch(i){if(r.aborted)throw i;let a=i instanceof Error?i:new Error(String(i));if(g$(a)){if(s<3)continue;throw new kf}throw a}}}function fte(t){return{model:t.model,max_tokens:t.maxTokens,messages:t.messages,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(ute)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.fastMode===!0?{speed:"fast"}:{}}}async function*E$({input:t,turn:e,retry:n,ttfbTimeoutMs:r,stallTimeoutMs:o}){let s=ec({baseUrl:t.baseUrl})?ZN(t.messages,ao()):t.messages,i=fte({...t,messages:s,tools:e.windDownReason!==null?null:t.tools}),a=Date.now(),c=s$(t.signal,r),l=d$(c.signal,o,d=>{q(t.traceWriter,{phase:"idle_watchdog_fired",durationMs:d.elapsedSinceLastProgressMs,resolvedModel:t.model,metadata:{source:"model-stream",stallTimeoutMs:d.stallTimeoutMs,elapsedSinceLastProgressMs:d.elapsedSinceLastProgressMs}})});try{return{kind:"opened",events:yield*S$(pte(t.client,i,t.headers,l.signal,t.signal),t,u=>{let p=o$(u);p!==void 0&&c.extend(p)}),ttfb:c,stall:l,requestStartedAt:a}}catch(d){if(c.timedOut()&&!t.signal.aborted&&n.canRetryTtfb())return c.dispose(),l.dispose(),{kind:"retry-ttfb",requestStartedAt:a};if(c.dispose(),l.dispose(),t.signal.aborted)return yield{type:"turn.completed",usage:e.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"terminated"};if(d instanceof kf)return{kind:"overload-exhausted"};let u=Sf(d,t.fastMode===!0);return u.message.includes("thinking")&&v$(t.messages,u),yield{type:"error",error:u},{kind:"terminated"}}}var kf,_$=h(()=>{"use strict";jS();Ds();J();Bn();gf();hf();nc();Fs();k$();T$();kf=class extends Error{constructor(){super("Connection-phase overload budget exhausted"),this.name="ConnectionOverloadExhaustedError"}}});function A$(t,e){return t||e!==null}function x$(){return new ct("the model stream ended without a terminal message (no message_stop and no stop_reason): the turn is incomplete. The cause is not knowable at this layer \u2014 a client-side abort carrying an AbortError reason (including the SDK request timeout) and an upstream peer close are indistinguishable here. Check the trace for a preceding ttfb_timeout, idle_watchdog_fired, or rate_limit phase before suspecting the network.")}var R$=h(()=>{"use strict";se()});function mte(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function gte(t,e,n){let r=[],o=[];for(let a of t)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?a.thinking&&a.signature&&r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):a.kind==="redacted_thinking"?r.push({type:"redacted_thinking",data:a.data}):r.push({type:"tool_use",id:a.id,name:a.name,input:mte(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*I$(t,e,n){let r=[],o=null,s=null,i=!1,a=!!k.AFK_TELEGRAM_TRACE;try{a&&console.log("[translate] starting SDK event iteration");for await(let c of t){switch(a&&console.log("[translate] SDK evt:",c.type),c.type){case"message_start":{let l=c.message?.usage;l&&(s={...l});break}case"content_block_start":{let l=c.content_block;l.type==="text"?r[c.index]={kind:"text",text:""}:l.type==="thinking"?r[c.index]={kind:"thinking",thinking:"",signature:""}:l.type==="redacted_thinking"?r[c.index]={kind:"redacted_thinking",data:l.data}:l.type==="tool_use"&&(r[c.index]={kind:"tool_use",id:l.id,name:l.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:l.id,toolName:l.name,toolInput:" \u2026",pending:!0,sessionId:e.sessionId}});break}case"content_block_delta":{let l=r[c.index],d=c.delta;d.type==="text_delta"?(l&&l.kind==="text"&&(l.text+=d.text),yield{kind:"event",event:{type:"delta.text",text:d.text,sessionId:e.sessionId}}):d.type==="input_json_delta"?(l&&l.kind==="tool_use"&&(l.partialJson+=d.partial_json),n?.()):d.type==="thinking_delta"?(l&&l.kind==="thinking"&&(l.thinking+=d.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:d.thinking,sessionId:e.sessionId}}):(d.type==="signature_delta"&&l&&l.kind==="thinking"&&(l.signature=d.signature),n?.());break}case"content_block_stop":{let l=r[c.index];l&&l.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:l.name,toolUseIds:[l.id],sessionId:e.sessionId}});break}case"message_delta":{c.delta&&c.delta.stop_reason!==void 0&&(o=c.delta.stop_reason);let l=c.usage;l&&(s!==null?(s.output_tokens=l.output_tokens,l.cache_creation_input_tokens!=null&&(s.cache_creation_input_tokens=l.cache_creation_input_tokens),l.cache_read_input_tokens!=null&&(s.cache_read_input_tokens=l.cache_read_input_tokens),l.input_tokens!=null&&(s.input_tokens=l.input_tokens)):s={cache_creation:null,cache_creation_input_tokens:l.cache_creation_input_tokens??null,cache_read_input_tokens:l.cache_read_input_tokens??null,inference_geo:null,input_tokens:l.input_tokens??0,output_tokens:l.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{i=!0;break}default:break}if(i)break}a&&console.log("[translate] SDK iteration ended naturally, stopped=",i)}catch(c){a&&console.log("[translate] SDK iteration threw:",c.message),yield{kind:"event",event:{type:"error",error:c instanceof Error?c:new Error(String(c))}};return}if(!A$(i,o)){yield{kind:"event",event:{type:"error",error:x$()}};return}a&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:gte(r,o,s)}}var C$=h(()=>{"use strict";F();R$()});async function*P$({events:t,input:e,turn:n,retry:r,ttfb:o,stall:s,stallTimeoutMs:i,requestStartedAt:a}){let c=null,l=!1,d=!1,u=!1,p=!1,f=!1,m=!1;try{k.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let g of I$(ps(t,e.signal),e.ctx,()=>s.progress()))if(!m&&(g.kind==="turn-result"||g.event.type!=="error")&&(m=!0,o.firstByteSeen(),q(e.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-a,resolvedModel:e.model})),s.progress(),k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",g.kind,g.kind==="event"?g.event.type:""),g.kind==="event"){if(g.event.type==="error"){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m){d=!0;break}if(s.timedOut()&&!e.signal.aborted){yield{type:"error",error:NS(i)},l=!0;break}if(rc(g.event.error)&&r.canRetryOverload()&&!e.signal.aborted){u=!0;break}if(rc(g.event.error)&&!e.signal.aborted){f=!0;break}if(e.signal.aborted)break;if(g.event.error instanceof ct&&r.canRetryStreamIncomplete()&&!e.signal.aborted){p=!0;break}yield g.event,l=!0;break}yield g.event}else{c=g.result;break}k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",c?"set":"null")}catch(g){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m)o.dispose(),s.dispose(),d=!0;else{if(o.dispose(),s.dispose(),e.signal.aborted)return yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"terminated"};let y=g instanceof Error?g:new Error(String(g));if((s.timedOut()||l$(y))&&!e.signal.aborted)return yield{type:"error",error:NS(i)},{kind:"terminated"};if(rc(y)&&r.canRetryOverload()&&!e.signal.aborted)u=!0;else if(rc(y)&&!e.signal.aborted)f=!0;else return yield{type:"error",error:y},{kind:"terminated"}}}return o.dispose(),s.dispose(),d?{kind:"retry",reason:"ttfb"}:u?{kind:"retry",reason:"overload"}:p?{kind:"retry",reason:"stream-incomplete"}:f?{kind:"overload-exhausted"}:l?{kind:"translator-errored"}:{kind:"streamed",turnResult:c}}var M$=h(()=>{"use strict";C$();se();ip();J();F();hf();Fs()});async function*O$(t,e,n){let r=[],o=new Map;for(let i of t.toolUseBlocks)r.push({id:i.id,name:i.name,input:i.input,signal:e.signal}),o.set(i.id,Date.now()),Sr(e.traceWriter,gp({toolUseId:i.id,name:i.name,input:i.input,subagentId:e.subagentId})),yield{type:"tool.use.start",toolUseId:i.id,toolName:i.name,toolInput:Vn(i.name,i.input),toolInputRaw:fp(i.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT&&or(k.AFK_CAPTURE_SUBAGENT_OUTPUT)?mp(i.input):void 0,sessionId:e.ctx.sessionId};if(e.signal.aborted){let i=r.map(a=>({type:"tool_result",tool_use_id:a.id,content:"Tool call aborted",is_error:!0}));return e.messages.push({role:"user",content:i}),yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"aborted"}}let s;if(e.toolDispatcher.executeBatch)s=yield*bp(async i=>{try{return await e.toolDispatcher.executeBatch(r,a=>{i({type:"tool.activity",activeCount:a.length,activeToolUseIds:[...a],sessionId:e.ctx.sessionId})})}catch(a){return r.map(()=>({content:`Tool batch execution failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}))}});else{s=[];for(let i of r){if(e.signal.aborted){s.push({content:"Tool call aborted",isError:!0,failureClass:Ne(e.signal)});continue}try{s.push(await e.toolDispatcher.execute(i))}catch(a){let c=a instanceof Error?a.message:String(a);s.push({content:`Tool execution threw: ${c}`,isError:!0})}}}return{kind:"dispatched",calls:r,results:s,startTimes:o}}var D$=h(()=>{"use strict";Cn();J();ww();F();$a();yp();kw()});async function*F$(t,e,n,r){let o=[];for(let c=0;c<t.length;c++){let l=t[c],d=e[c],u=n.get(l.id),p=typeof u=="number"?Date.now()-u:0,f=d.truncated===!0||d.content.includes("[output truncated");Sr(r.traceWriter,hp({toolUseId:l.id,name:l.name,result:d,truncated:f,durationMs:p,subagentId:r.subagentId})),yield{type:"tool.output",toolUseId:l.id,toolName:l.name,content:d.content,...d.isError===!0?{isError:!0}:{},...f?{truncated:!0}:{},...d.capturePath!==void 0?{capturePath:d.capturePath}:{},...d.incomplete===!0?{incomplete:!0}:{},...d.incompleteReason?{incompleteReason:d.incompleteReason}:{},...typeof d.batchIndex=="number"&&typeof d.batchSize=="number"?{batchIndex:d.batchIndex,batchSize:d.batchSize}:{},...d.failureClass?{failureClass:d.failureClass}:{},durationMs:d.durationMs!==void 0?d.durationMs:p,...d.exitCode!==void 0?{exitCode:d.exitCode}:{},sessionId:r.ctx.sessionId},d.render?.diff&&(yield{type:"tool.diff",toolUseId:l.id,diff:d.render.diff,sessionId:r.ctx.sessionId});let{content:m,isError:g,image:y}=d,b=y!==void 0?[{type:"image",source:{type:"base64",media_type:y.mediaType,data:y.data}},...m.length>0?[{type:"text",text:m}]:[]]:m;o.push({type:"tool_result",tool_use_id:l.id,content:b,...g===!0?{is_error:!0}:{}})}let s=e.flatMap(c=>c.harnessUserMessage?.kind==="queued_user_message"?[{type:"text",text:c.harnessUserMessage.text}]:[]),i={role:"user",content:[...o,...s]};r.messages.push(i);let a=e.find(c=>c.failureClass===Fo);return a?(yield{type:"error",error:new _o(a.content)},"denial-tripped"):"committed"}var L$=h(()=>{"use strict";J();yp();Fi();se()});async function*N$(t,e,n,r,o){let s=e.messages.length;e.messages.push({role:"assistant",content:t.assistantBlocks});try{n.toolCallCount+=t.toolUseBlocks.length;let d=yield*O$(t,e,n);if(d.kind==="aborted"||(yield*F$(d.calls,d.results,d.startTimes,e))==="denial-tripped")return"terminated"}catch(d){throw e.messages.splice(s),d}n.iterations+=1;let i=t.toolUseBlocks[t.toolUseBlocks.length-1],a=i?`${i.name}${Vn(i.name,i.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:n.taskId,description:"Working",summary:`${vp(n.iterations,r)}: ${a}`,lastToolName:i?.name,totalTokens:n.usage.totalTokens??0,toolUses:n.toolCallCount,durationMs:Date.now()-n.startedAt},sessionId:e.ctx.sessionId},n.windDownReason!==null)return yield{type:"turn.completed",usage:n.withDuration({...n.usage,stopReason:n.windDownReason}),sessionId:e.ctx.sessionId},"terminated";let c=kp(n.iterations,r),l=$u(n.startedAt,o);if(c||l){let d=c?wp:Lu,u=e.messages[e.messages.length-1];u!==void 0&&u.role==="user"&&Array.isArray(u.content)&&u.content.push({type:"text",text:d}),n.windDownReason=c?Mt:Ct}return"continue"}var $$=h(()=>{"use strict";$a();Wn();ms();D$();L$()});function*U$(t,e,n){if(t.stopReason==="refusal"){t.text.length>0&&(yield{type:"assistant.message",text:t.text,sessionId:e.ctx.sessionId}),yield{type:"notice",text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,kind:"refusal",sessionId:e.ctx.sessionId},yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId};return}let r=Vt(t.stopReason)?Uu(t.toolUseBlocks.map(s=>s.name),t.stopReason):null;t.text.length>0?(yield{type:"assistant.message",text:r?`${t.text}
|
|
1414
|
+
`)}var pf=h(()=>{"use strict";Ue()});function GN(t){let{config:e,cwd:n}=t,r=t.hasSkillExecutor?Ep(void 0,{cwd:n,...typeof e.skillDispatchName=="string"&&e.skillDispatchName.length>0?{excludeName:e.skillDispatchName}:{}}):"",o=qu(e.isSkillDispatch),s=Gu(t.readOnlyMemory),i=Xu(t.workspaceEnabled),a={surface:t.surface,sessionId:e.sessionId,depth:e.depth,maxDepth:e.maxDepth,workspace:t.runtimeStateSource.getWorkspace()},c={toolBase:o,memoryPrompt:s,workspacePrompt:i,hotMemory:e.hotMemory??"",manifest:r,userSystem:t.userSystem};return{stableSystemPrefix:c,toolSystemAppend:Os(c,n,a)}}var XN=h(()=>{"use strict";Xn();qb();pf()});import jee from"@anthropic-ai/sdk";function zN(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function JN(t,e,n,r){let o=e.config,{localMode:s,token:i}=VP(o);if(!i||i.length===0)throw new Error(`${n} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let a=Ao(i),{client:c,throttleQueue:l,systemPrefix:d,tokenRefresher:u}=pM({config:o,token:i,authMode:a,localMode:s,factory:t.providerFactory??wu(),createClient:T=>new jee(T)}),p=zN(o.systemPrompt),f=typeof o.model=="string"&&o.model.length>0?Ee(o.model)??o.model:r,m=Cl(o,f),g=o.permissionMode??"default";t.setCurrentPermissionMode(g),t.ensureSharedRoots(o.cwd),o.cwd&&t.setCurrentCwd(o.cwd);let y=t.getSharedReadRoots(),b=t.getSharedWriteRoots();o.readRoots&&y&&y.length<=1&&(y.length=0,y.push(...o.readRoots)),o.writeRoots&&b&&b.length<=1&&(b.length=0,b.push(...o.writeRoots));let{queryDispatcher:w,runtimeStateSource:v,toolDefs:_,resolvedSessionId:x}=vM({config:o,model:f,permissionMode:g,surface:t.surface,providerName:n,externalTools:t.externalTools,sharedReadRoots:y,sharedWriteRoots:b,getCwd:()=>t.getCurrentCwd()||o.cwd||process.cwd(),getMcpTools:()=>t.mcpManager?.getMcpTools()??[],getSubagents:()=>t.subagentExecutor?t.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>t.getMintedSessionId(),setMintedSessionId:T=>{t.setMintedSessionId(T)},getPresenceSessionId:()=>t.getPresenceSessionId(),setPresenceSessionId:T=>{t.setPresenceSessionId(T)},buildDispatcher:(T,R)=>t.buildDispatcher(T,R)}),A=o.cwd||process.cwd(),{stableSystemPrefix:I,toolSystemAppend:C}=GN({config:o,cwd:A,surface:t.surface,readOnlyMemory:t.readOnlyMemory,workspaceEnabled:t.workspaceStore!==void 0,hasSkillExecutor:!!t.skillExecutor,runtimeStateSource:v,userSystem:p});return IM({prompt:e.prompt,options:{model:f,maxTokens:m,system:C},provenance:{systemPrompt:{source:o.systemPromptSource??"none",shape:typeof o.systemPrompt=="string"?"string":Array.isArray(o.systemPrompt)?"string[]":o.systemPrompt!=null?"preset":"undefined",...typeof o.systemPrompt=="string"?{length:o.systemPrompt.length}:{}},...o.apiKey?{apiKey:{source:"config"}}:{}}}),{client:c,authMode:a,localMode:s,model:f,maxTokens:m,cwd:A,systemPrefix:d,throttleQueue:l,tokenRefresher:u,queryDispatcher:w,runtimeStateSource:v,toolDefs:_,resolvedSessionId:x,stableSystemPrefix:I,toolSystemAppend:C}}var IS=h(()=>{"use strict";xn();lt();Ol();YP();Su();fM();TM();XN();Sa()});function VN(t){let e=t.initialUsageInputTokens!==void 0&&t.initialUsageInputTokens>0?{inputTokens:t.initialUsageInputTokens,stopReason:null,resultSubtype:"success",isError:!1}:null;return{messages:t.initialMessages?[...t.initialMessages]:[],currentModel:t.model,requestedModel:t.requestedModel??t.model,currentPermissionMode:t.permissionMode,userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,lastUsage:e,closed:!1,autoCompactThreshold:t.autoCompactThreshold}}var YN=h(()=>{"use strict"});function ec(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=k.AFK_DISABLE_PROMPT_CACHE;if(e===void 0||e.length===0)return!0;let n=e.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function ao(){let t=k.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":Hee}function ff(t){return ec(t)&&ao()==="1h"}function QN(t,e){if(t.length===0)return t;let n=t[t.length-1],r=e$(n,e);return r===n?t:[...t.slice(0,-1),r]}function ZN(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Wee(n,e);return r===n?t:[...t.slice(0,-1),r]}function Wee(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=e$(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function e$(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var Hee,Ds=h(()=>{"use strict";F();Hee="1h"});var CS=h(()=>{"use strict";qo()});function Jee(t){let e=n=>n===void 0?void 0:n*PS;return{inputPerMTok:t.inputPerMTok*PS,outputPerMTok:t.outputPerMTok*PS,...e(t.cacheWrite5mPerMTok)!==void 0?{cacheWrite5mPerMTok:e(t.cacheWrite5mPerMTok)}:{},...e(t.cacheWrite1hPerMTok)!==void 0?{cacheWrite1hPerMTok:e(t.cacheWrite1hPerMTok)}:{},...e(t.cacheReadPerMTok)!==void 0?{cacheReadPerMTok:e(t.cacheReadPerMTok)}:{}}}function Vee(t){return t.responseSpeed??t.requestSpeed??"standard"}function Yee(t){return as(t,t$,Xee)}function MS(t,e,n,r,o,s,i={}){let a=Yee(t);if(!a)return;let c=Vee(i)==="fast"&&zee.test(t)?Jee(a):a,l=1e6,d=Ke(e),u=Ke(n),p=Ke(r),f=Ke(o),m=d/l*c.inputPerMTok,g=u/l*c.outputPerMTok,y=c.cacheWrite5mPerMTok??c.inputPerMTok*Kee,b=c.cacheWrite1hPerMTok??c.inputPerMTok*qee,w=c.cacheReadPerMTok??c.inputPerMTok*Gee,v=s??{ephemeral5m:f,ephemeral1h:0},_=Ke(v.ephemeral5m),x=Ke(v.ephemeral1h),A=Math.max(0,f-(_+x)),I=_/l*y+x/l*b+A/l*b,C=p/l*w;return m+g+I+C}var Kee,qee,Gee,t$,Xee,PS,zee,OS=h(()=>{"use strict";Vu();Kee=1.25,qee=2,Gee=.1,t$=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-5",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-8",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-7",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-6",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-sonnet-4-6",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-sonnet-4-5-20250929",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-4-5-20250929",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-haiku-4-5-20250929",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-haiku-4-5-20251001",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-3-7-sonnet-20250219",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20241022",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20240620",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-haiku-20241022",{inputPerMTok:.8,outputPerMTok:4,cacheWrite5mPerMTok:1,cacheWrite1hPerMTok:1.6,cacheReadPerMTok:.08}],["claude-3-opus-20240229",{inputPerMTok:15,outputPerMTok:75,cacheWrite5mPerMTok:18.75,cacheWrite1hPerMTok:30,cacheReadPerMTok:1.5}],["claude-3-sonnet-20240229",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-haiku-20240307",{inputPerMTok:.25,outputPerMTok:1.25,cacheWrite5mPerMTok:.3,cacheWrite1hPerMTok:.5,cacheReadPerMTok:.03}]]),Xee=/-\d{8}$/,PS=2,zee=/^claude-opus-(?:5|4-8)(?:-|$)/});function Qee(t){let e=t.speed;return e==="fast"||e==="standard"?e:void 0}function Zee(t){let e=o=>Number.isFinite(o)&&o>=0?o:0,n=t.cache_creation;if(n)return{ephemeral5m:e(n.ephemeral_5m_input_tokens??0),ephemeral1h:e(n.ephemeral_1h_input_tokens??0)};let r=e(t.cache_creation_input_tokens??0);return ao()==="1h"?{ephemeral5m:0,ephemeral1h:r}:{ephemeral5m:r,ephemeral1h:0}}function DS(t,e,n,r){if(!t)return{stopReason:e??null};let o=Qee(t),s={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null,raw:{...t,...o?{speed:o}:{}}};if(t.cache_read_input_tokens!=null&&(s.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(s.cacheCreationTokens=t.cache_creation_input_tokens),s.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n){let i=MS(n,t.input_tokens??0,t.output_tokens??0,t.cache_read_input_tokens??0,t.cache_creation_input_tokens??0,Zee(t),{...r?{requestSpeed:r}:{},...o?{responseSpeed:o}:{}});i!==void 0&&(s.totalCostUsd=i)}return s}var n$=h(()=>{"use strict";Ds();OS()});var FS=h(()=>{"use strict";OS();n$();Gb()});function tc(t){return t>2147483647?2147483647:t}var LS=h(()=>{"use strict"});function mf(){let t=k.AFK_MODEL_TTFB_TIMEOUT_MS;if(t===void 0||t.trim()==="")return r$;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?r$:tc(e)}function o$(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?void 0:(t<nte?t:rte)+tte}function s$(t,e){if(e<=0)return{signal:t,timedOut:()=>!1,firstByteSeen:()=>{},extend:()=>{},dispose:()=>{}};let n=new AbortController,r=AbortSignal.any([t,n.signal]),o=!1,s=!1,i=Date.now()+e,a,c=u=>{a=setTimeout(()=>{o=!0,n.abort(new Error(ete))},tc(u)),a.unref()};c(e);let l=()=>{s||(s=!0,clearTimeout(a))};return{signal:r,timedOut:()=>o,firstByteSeen:l,extend:u=>{s||o||typeof u!="number"||!Number.isFinite(u)||u<=0||(i+=u,clearTimeout(a),c(Math.max(1,i-Date.now())))},dispose:l}}var r$,ete,tte,nte,rte,gf=h(()=>{"use strict";F();LS();r$=18e4;ete="model_ttfb_timeout",tte=3e4,nte=6e4,rte=8e3});function a$(){let t=k.AFK_MODEL_STALL_TIMEOUT_MS;if(t===void 0||t.trim()==="")return i$;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?i$:tc(e)}function l$(t){return t instanceof Error&&t.message===c$}function NS(t){return new Error(`Model stream stalled: no output for ${Math.round(t/1e3)}s after the response had already started streaming. The round was aborted rather than left hanging (issue #762: two sessions hung 38 and 63 minutes with no terminal event). A round that keeps producing output is never cut off, no matter how long it runs. Raise AFK_MODEL_STALL_TIMEOUT_MS, or set it to 0 to disable this bound.`)}function d$(t,e,n){if(e<=0)return{signal:t,timedOut:()=>!1,progress:()=>{},dispose:()=>{}};let r=new AbortController,o=AbortSignal.any([t,r.signal]),s,i=!1,a=!1,c=u=>{if(!(a||i)){i=!0,s=void 0;try{n?.({stallTimeoutMs:e,elapsedSinceLastProgressMs:Date.now()-u})}catch{}r.signal.aborted||r.abort(new Error(c$))}};return{signal:o,timedOut:()=>i,progress:()=>{if(a||i)return;s!==void 0&&clearTimeout(s);let u=Date.now(),p=setTimeout(()=>c(u),e);p.unref(),s=p},dispose:()=>{a||(a=!0,s!==void 0&&clearTimeout(s),s=void 0)}}}var i$,c$,hf=h(()=>{"use strict";F();LS();i$=12e5;c$="model_stream_stall_timeout"});function yf(t,e=Math.random){return t+Math.floor(e()*t*ate)}function p$(t=Math.random){let e=ite-u$;return u$+Math.floor(t()*e)}function f$(t){return t.type==="turn.completed"&&t.usage.stopReason===st}function m$(t){let e=k.AFK_OVERLOAD_PAUSE_MS;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(Math.floor(n),ste)}return t!==void 0&&cte.has(t)?ote:0}var $S,ote,ste,u$,ite,ate,cte,nc=h(()=>{"use strict";F();rs();rs();$S="Anthropic is overloaded (HTTP 529) and did not recover within this turn's retry budget. This is an upstream capacity event, not an afk error. The turn was committed, so the conversation so far is preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state once capacity frees up.",ote=600*1e3,ste=7200*1e3,u$=60*1e3,ite=120*1e3,ate=.25;cte=new Set(["cli","repl","telegram","web"])});function wf(t){if(!Number.isFinite(t)||t<=0)return 0;let e=Math.floor(t*2/3);return Math.max(1,e)}function g$(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function rc(t){if(t===null||typeof t!="object")return!1;let e=t;if(e.status===529||e.status===503)return!0;let n=e.error;if(n===null||typeof n!="object")return!1;let r=n;return((r.error!==null&&typeof r.error=="object"?r.error.type:void 0)??r.type)==="overloaded_error"}var bf,Fs=h(()=>{"use strict";bf=class{overloadRetries=0;streamIncompleteRetries=0;ttfbRetries=0;canRetryOverload(){return this.overloadRetries<3}canRetryStreamIncomplete(){return this.streamIncompleteRetries<2}canRetryTtfb(){return this.ttfbRetries<2}reset(){this.overloadRetries=0,this.streamIncompleteRetries=0,this.ttfbRetries=0}}});async function*dte(t,e,n){q(t.traceWriter,{phase:"ttfb_timeout",durationMs:Date.now()-e,metadata:{reason:"ttfb-timeout",source:"first-byte",resolvedModel:t.model,attempt:n}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId}}async function*BS(t,{input:e,turn:n,retry:r,requestStartedAt:o}){return t==="ttfb"?(r.ttfbRetries+=1,yield*dte(e,o,r.ttfbRetries),"continue"):t==="overload"?(r.overloadRetries+=1,q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:r.overloadRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*h$(yf(5e3*Math.pow(2,r.overloadRetries-1)),e,n),e.signal.aborted?"terminated":"continue"):(r.streamIncompleteRetries+=1,q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"stream-incomplete",source:"mid-stream",attempt:r.streamIncompleteRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*h$(1e3*Math.pow(2,r.streamIncompleteRetries-1),e,n),e.signal.aborted?"terminated":"continue")}async function*h$(t,e,n){await We(t,e.signal),e.signal.aborted&&(yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId})}var y$=h(()=>{"use strict";J();Bn();nc();Fs()});function w$(t){let e=t.fastModeController?.snapshotTurn({resolvedModelId:t.model,providerFamily:"anthropic-direct",hasCustomEndpoint:t.baseUrl!==void 0,executionPath:"top-level"}),n=e?.effective===!0,r=An(t.authMode,t.sessionId,t.requestId,t.effort!==void 0,ff(t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{}),n);return{decision:e,runInput:{client:t.client,messages:t.messages,system:t.system,tools:t.tools,toolDispatcher:t.toolDispatcher,model:t.model,maxTokens:t.maxTokens,headers:r,signal:t.signal,ctx:{sessionId:t.sessionId},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...n?{fastMode:!0}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.onUsageProgress?{onUsageProgress:t.onUsageProgress}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{}}}}function Sf(t,e){let n=t instanceof Error?t:new Error(String(t));if(!e||n.message.startsWith(b$))return n;let r=new Error(`${b$} ${n.message}`,{cause:n});r.name=n.name,n.stack!==void 0&&(r.stack=n.stack);for(let o of Object.getOwnPropertyNames(n)){if(o==="message"||o==="stack")continue;let s=Object.getOwnPropertyDescriptor(n,o);s!==void 0&&Object.defineProperty(r,o,s)}return r}var b$,jS=h(()=>{"use strict";xn();Ds();b$="[Fast mode requested; no standard-mode fallback will be attempted]"});async function*S$(t,e,n){let r=e.throttleQueue;if(!r)return await t;r.resetAttempts();let o=Symbol("create-done"),s=!1,i=t.then(a=>(s=!0,a),a=>{throw s=!0,a});for(;;){for(let c of r.takeAll())n?.(c.retryAfterMs),yield{type:"rate_limit",sessionId:e.ctx.sessionId,status:c.status,attempt:c.attempt,...c.retryAfterMs!==void 0?{retryAfterMs:c.retryAfterMs}:{}};if(s)return await i;await Promise.race([i.then(()=>o,()=>o),r.waitForItem().then(()=>{})])}}var k$=h(()=>{"use strict"});function v$(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}var T$=h(()=>{"use strict"});function ute(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}async function pte(t,e,n,r,o){for(let s=0;;s++){if(s>0){let i=yf(5e3*Math.pow(2,s-1));if(await We(i,o),o.aborted)throw new Error("aborted")}try{return await Promise.resolve(t.messages.create(e,{headers:n,signal:r}))}catch(i){if(r.aborted)throw i;let a=i instanceof Error?i:new Error(String(i));if(g$(a)){if(s<3)continue;throw new kf}throw a}}}function fte(t){return{model:t.model,max_tokens:t.maxTokens,messages:t.messages,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(ute)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.fastMode===!0?{speed:"fast"}:{}}}async function*E$({input:t,turn:e,retry:n,ttfbTimeoutMs:r,stallTimeoutMs:o}){let s=ec({baseUrl:t.baseUrl})?ZN(t.messages,ao()):t.messages,i=fte({...t,messages:s,tools:e.windDownReason!==null?null:t.tools}),a=Date.now(),c=s$(t.signal,r),l=d$(c.signal,o,d=>{q(t.traceWriter,{phase:"idle_watchdog_fired",durationMs:d.elapsedSinceLastProgressMs,resolvedModel:t.model,metadata:{source:"model-stream",stallTimeoutMs:d.stallTimeoutMs,elapsedSinceLastProgressMs:d.elapsedSinceLastProgressMs}})});try{return{kind:"opened",events:yield*S$(pte(t.client,i,t.headers,l.signal,t.signal),t,u=>{let p=o$(u);p!==void 0&&c.extend(p)}),ttfb:c,stall:l,requestStartedAt:a}}catch(d){if(c.timedOut()&&!t.signal.aborted&&n.canRetryTtfb())return c.dispose(),l.dispose(),{kind:"retry-ttfb",requestStartedAt:a};if(c.dispose(),l.dispose(),t.signal.aborted)return yield{type:"turn.completed",usage:e.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"terminated"};if(d instanceof kf)return{kind:"overload-exhausted"};let u=Sf(d,t.fastMode===!0);return u.message.includes("thinking")&&v$(t.messages,u),yield{type:"error",error:u},{kind:"terminated"}}}var kf,_$=h(()=>{"use strict";jS();Ds();J();Bn();gf();hf();nc();Fs();k$();T$();kf=class extends Error{constructor(){super("Connection-phase overload budget exhausted"),this.name="ConnectionOverloadExhaustedError"}}});function A$(t,e){return t||e!==null}function x$(){return new ct("the model stream ended without a terminal message (no message_stop and no stop_reason): the turn is incomplete. The cause is not knowable at this layer \u2014 a client-side abort carrying an AbortError reason (including the SDK request timeout) and an upstream peer close are indistinguishable here. Check the trace for a preceding ttfb_timeout, idle_watchdog_fired, or rate_limit phase before suspecting the network.")}var R$=h(()=>{"use strict";ie()});function mte(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function gte(t,e,n){let r=[],o=[];for(let a of t)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?a.thinking&&a.signature&&r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):a.kind==="redacted_thinking"?r.push({type:"redacted_thinking",data:a.data}):r.push({type:"tool_use",id:a.id,name:a.name,input:mte(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*I$(t,e,n){let r=[],o=null,s=null,i=!1,a=!!k.AFK_TELEGRAM_TRACE;try{a&&console.log("[translate] starting SDK event iteration");for await(let c of t){switch(a&&console.log("[translate] SDK evt:",c.type),c.type){case"message_start":{let l=c.message?.usage;l&&(s={...l});break}case"content_block_start":{let l=c.content_block;l.type==="text"?r[c.index]={kind:"text",text:""}:l.type==="thinking"?r[c.index]={kind:"thinking",thinking:"",signature:""}:l.type==="redacted_thinking"?r[c.index]={kind:"redacted_thinking",data:l.data}:l.type==="tool_use"&&(r[c.index]={kind:"tool_use",id:l.id,name:l.name,partialJson:""},yield{kind:"event",event:{type:"tool.use.start",toolUseId:l.id,toolName:l.name,toolInput:" \u2026",pending:!0,sessionId:e.sessionId}});break}case"content_block_delta":{let l=r[c.index],d=c.delta;d.type==="text_delta"?(l&&l.kind==="text"&&(l.text+=d.text),yield{kind:"event",event:{type:"delta.text",text:d.text,sessionId:e.sessionId}}):d.type==="input_json_delta"?(l&&l.kind==="tool_use"&&(l.partialJson+=d.partial_json),n?.()):d.type==="thinking_delta"?(l&&l.kind==="thinking"&&(l.thinking+=d.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:d.thinking,sessionId:e.sessionId}}):(d.type==="signature_delta"&&l&&l.kind==="thinking"&&(l.signature=d.signature),n?.());break}case"content_block_stop":{let l=r[c.index];l&&l.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:l.name,toolUseIds:[l.id],sessionId:e.sessionId}});break}case"message_delta":{c.delta&&c.delta.stop_reason!==void 0&&(o=c.delta.stop_reason);let l=c.usage;l&&(s!==null?(s.output_tokens=l.output_tokens,l.cache_creation_input_tokens!=null&&(s.cache_creation_input_tokens=l.cache_creation_input_tokens),l.cache_read_input_tokens!=null&&(s.cache_read_input_tokens=l.cache_read_input_tokens),l.input_tokens!=null&&(s.input_tokens=l.input_tokens)):s={cache_creation:null,cache_creation_input_tokens:l.cache_creation_input_tokens??null,cache_read_input_tokens:l.cache_read_input_tokens??null,inference_geo:null,input_tokens:l.input_tokens??0,output_tokens:l.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{i=!0;break}default:break}if(i)break}a&&console.log("[translate] SDK iteration ended naturally, stopped=",i)}catch(c){a&&console.log("[translate] SDK iteration threw:",c.message),yield{kind:"event",event:{type:"error",error:c instanceof Error?c:new Error(String(c))}};return}if(!A$(i,o)){yield{kind:"event",event:{type:"error",error:x$()}};return}a&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:gte(r,o,s)}}var C$=h(()=>{"use strict";F();R$()});async function*P$({events:t,input:e,turn:n,retry:r,ttfb:o,stall:s,stallTimeoutMs:i,requestStartedAt:a}){let c=null,l=!1,d=!1,u=!1,p=!1,f=!1,m=!1;try{k.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let g of I$(ps(t,e.signal),e.ctx,()=>s.progress()))if(!m&&(g.kind==="turn-result"||g.event.type!=="error")&&(m=!0,o.firstByteSeen(),q(e.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-a,resolvedModel:e.model})),s.progress(),k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",g.kind,g.kind==="event"?g.event.type:""),g.kind==="event"){if(g.event.type==="error"){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m){d=!0;break}if(s.timedOut()&&!e.signal.aborted){yield{type:"error",error:NS(i)},l=!0;break}if(rc(g.event.error)&&r.canRetryOverload()&&!e.signal.aborted){u=!0;break}if(rc(g.event.error)&&!e.signal.aborted){f=!0;break}if(e.signal.aborted)break;if(g.event.error instanceof ct&&r.canRetryStreamIncomplete()&&!e.signal.aborted){p=!0;break}yield g.event,l=!0;break}yield g.event}else{c=g.result;break}k.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",c?"set":"null")}catch(g){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m)o.dispose(),s.dispose(),d=!0;else{if(o.dispose(),s.dispose(),e.signal.aborted)return yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"terminated"};let y=g instanceof Error?g:new Error(String(g));if((s.timedOut()||l$(y))&&!e.signal.aborted)return yield{type:"error",error:NS(i)},{kind:"terminated"};if(rc(y)&&r.canRetryOverload()&&!e.signal.aborted)u=!0;else if(rc(y)&&!e.signal.aborted)f=!0;else return yield{type:"error",error:y},{kind:"terminated"}}}return o.dispose(),s.dispose(),d?{kind:"retry",reason:"ttfb"}:u?{kind:"retry",reason:"overload"}:p?{kind:"retry",reason:"stream-incomplete"}:f?{kind:"overload-exhausted"}:l?{kind:"translator-errored"}:{kind:"streamed",turnResult:c}}var M$=h(()=>{"use strict";C$();ie();ip();J();F();hf();Fs()});async function*O$(t,e,n){let r=[],o=new Map;for(let i of t.toolUseBlocks)r.push({id:i.id,name:i.name,input:i.input,signal:e.signal}),o.set(i.id,Date.now()),Sr(e.traceWriter,gp({toolUseId:i.id,name:i.name,input:i.input,subagentId:e.subagentId})),yield{type:"tool.use.start",toolUseId:i.id,toolName:i.name,toolInput:Vn(i.name,i.input),toolInputRaw:fp(i.input),toolInputCapture:k.AFK_CAPTURE_SUBAGENT_OUTPUT&&or(k.AFK_CAPTURE_SUBAGENT_OUTPUT)?mp(i.input):void 0,sessionId:e.ctx.sessionId};if(e.signal.aborted){let i=r.map(a=>({type:"tool_result",tool_use_id:a.id,content:"Tool call aborted",is_error:!0}));return e.messages.push({role:"user",content:i}),yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"aborted"}}let s;if(e.toolDispatcher.executeBatch)s=yield*bp(async i=>{try{return await e.toolDispatcher.executeBatch(r,a=>{i({type:"tool.activity",activeCount:a.length,activeToolUseIds:[...a],sessionId:e.ctx.sessionId})})}catch(a){return r.map(()=>({content:`Tool batch execution failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}))}});else{s=[];for(let i of r){if(e.signal.aborted){s.push({content:"Tool call aborted",isError:!0,failureClass:Ne(e.signal)});continue}try{s.push(await e.toolDispatcher.execute(i))}catch(a){let c=a instanceof Error?a.message:String(a);s.push({content:`Tool execution threw: ${c}`,isError:!0})}}}return{kind:"dispatched",calls:r,results:s,startTimes:o}}var D$=h(()=>{"use strict";Cn();J();ww();F();$a();yp();kw()});async function*F$(t,e,n,r){let o=[];for(let c=0;c<t.length;c++){let l=t[c],d=e[c],u=n.get(l.id),p=typeof u=="number"?Date.now()-u:0,f=d.truncated===!0||d.content.includes("[output truncated");Sr(r.traceWriter,hp({toolUseId:l.id,name:l.name,result:d,truncated:f,durationMs:p,subagentId:r.subagentId})),yield{type:"tool.output",toolUseId:l.id,toolName:l.name,content:d.content,...d.isError===!0?{isError:!0}:{},...f?{truncated:!0}:{},...d.capturePath!==void 0?{capturePath:d.capturePath}:{},...d.incomplete===!0?{incomplete:!0}:{},...d.incompleteReason?{incompleteReason:d.incompleteReason}:{},...typeof d.batchIndex=="number"&&typeof d.batchSize=="number"?{batchIndex:d.batchIndex,batchSize:d.batchSize}:{},...d.failureClass?{failureClass:d.failureClass}:{},durationMs:d.durationMs!==void 0?d.durationMs:p,...d.exitCode!==void 0?{exitCode:d.exitCode}:{},sessionId:r.ctx.sessionId},d.render?.diff&&(yield{type:"tool.diff",toolUseId:l.id,diff:d.render.diff,sessionId:r.ctx.sessionId});let{content:m,isError:g,image:y}=d,b=y!==void 0?[{type:"image",source:{type:"base64",media_type:y.mediaType,data:y.data}},...m.length>0?[{type:"text",text:m}]:[]]:m;o.push({type:"tool_result",tool_use_id:l.id,content:b,...g===!0?{is_error:!0}:{}})}let s=e.flatMap(c=>c.harnessUserMessage?.kind==="queued_user_message"?[{type:"text",text:c.harnessUserMessage.text}]:[]),i={role:"user",content:[...o,...s]};r.messages.push(i);let a=e.find(c=>c.failureClass===Fo);return a?(yield{type:"error",error:new _o(a.content)},"denial-tripped"):"committed"}var L$=h(()=>{"use strict";J();yp();Fi();ie()});async function*N$(t,e,n,r,o){let s=e.messages.length;e.messages.push({role:"assistant",content:t.assistantBlocks});try{n.toolCallCount+=t.toolUseBlocks.length;let d=yield*O$(t,e,n);if(d.kind==="aborted"||(yield*F$(d.calls,d.results,d.startTimes,e))==="denial-tripped")return"terminated"}catch(d){throw e.messages.splice(s),d}n.iterations+=1;let i=t.toolUseBlocks[t.toolUseBlocks.length-1],a=i?`${i.name}${Vn(i.name,i.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:n.taskId,description:"Working",summary:`${vp(n.iterations,r)}: ${a}`,lastToolName:i?.name,totalTokens:n.usage.totalTokens??0,toolUses:n.toolCallCount,durationMs:Date.now()-n.startedAt},sessionId:e.ctx.sessionId},n.windDownReason!==null)return yield{type:"turn.completed",usage:n.withDuration({...n.usage,stopReason:n.windDownReason}),sessionId:e.ctx.sessionId},"terminated";let c=kp(n.iterations,r),l=$u(n.startedAt,o);if(c||l){let d=c?wp:Lu,u=e.messages[e.messages.length-1];u!==void 0&&u.role==="user"&&Array.isArray(u.content)&&u.content.push({type:"text",text:d}),n.windDownReason=c?Mt:Ct}return"continue"}var $$=h(()=>{"use strict";$a();Wn();ms();D$();L$()});function*U$(t,e,n){if(t.stopReason==="refusal"){t.text.length>0&&(yield{type:"assistant.message",text:t.text,sessionId:e.ctx.sessionId}),yield{type:"notice",text:`The model stopped with a content-safety refusal (stop_reason: "refusal") and returned no output. This is Anthropic's safety system declining the request \u2014 not an afk error. Because the flagged context stays in the conversation, follow-up messages will likely be refused the same way; rephrase the request or start a fresh session to continue.`,kind:"refusal",sessionId:e.ctx.sessionId},yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId};return}let r=Vt(t.stopReason)?Uu(t.toolUseBlocks.map(s=>s.name),t.stopReason):null;t.text.length>0?(yield{type:"assistant.message",text:r?`${t.text}
|
|
1415
1415
|
|
|
1416
|
-
${r}`:t.text,sessionId:e.ctx.sessionId},t.text.length<=hte&&(yield{type:"suggestion",suggestion:t.text,sessionId:e.ctx.sessionId})):r!==null&&(yield{type:"notice",text:r,kind:"truncation",sessionId:e.ctx.sessionId});let o=t.assistantBlocks.filter(s=>s.type!=="tool_use");o.length>0&&e.messages.push({role:"assistant",content:o}),yield{type:"turn.completed",usage:n.withDuration(n.windDownReason!==null?{...n.usage,stopReason:n.windDownReason}:n.usage),sessionId:e.ctx.sessionId}}var hte,B$=h(()=>{"use strict";ka();hte=200});import{randomUUID as yte}from"node:crypto";var Tf,j$=h(()=>{"use strict";FS();Tf=class{usage={stopReason:null};iterations=0;toolCallCount=0;windDownReason=null;taskId=yte();startedAt=Date.now();elapsedMs(){return Date.now()-this.startedAt}withDuration(e){return{...e,durationMs:this.elapsedMs()}}terminalUsage(){return this.withDuration(this.usage)}addRoundUsage(e){this.usage=_a(this.usage,e),this.usage.contextWindowTokens=(e.inputTokens??0)+(e.outputTokens??0)+(e.cachedInputTokens??0)+(e.cacheCreationTokens??0)}}});function H$(t,e){if(!e)return;let n=t.messages.at(-1);!n||n.role!=="user"||(Array.isArray(n.content)?n.content.push({type:"text",text:e}):n.content=[{type:"text",text:n.content},{type:"text",text:e}],Wl(t.traceWriter,{jobId:t.subagentId??"",subagentId:t.subagentId??"",byteLength:Buffer.byteLength(e,"utf8")}))}var W$=h(()=>{"use strict";J()});async function*HS(t){let e=Sp(t.maxToolUseIterations),n=t.softDeadlineMs??0,r=new Tf,o=new bf,s=l=>({input:t,turn:r,retry:o,requestStartedAt:l}),i=wf(mf()),a=a$(),c=new ss(t.signal,t.traceWriter,"anthropic-direct");try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId};return}let l=yield*E$({input:t,turn:r,retry:o,ttfbTimeoutMs:i,stallTimeoutMs:a});if(l.kind==="terminated")return;if(l.kind==="retry-ttfb"){if((yield*BS("ttfb",s(l.requestStartedAt)))==="terminated")return;continue}if(l.kind==="overload-exhausted"){q(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"connection-phase",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:$S,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:st}),sessionId:t.ctx.sessionId};return}let{events:d,ttfb:u,stall:p,requestStartedAt:f}=l,m=yield*P$({events:d,input:t,turn:r,retry:o,ttfb:u,stall:p,stallTimeoutMs:a,requestStartedAt:f});if(m.kind==="terminated")return;if(m.kind==="retry"){if((yield*BS(m.reason,s(f)))==="terminated")return;continue}if(o.reset(),m.kind==="overload-exhausted"){q(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:$S,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:st}),sessionId:t.ctx.sessionId};return}if(m.kind==="translator-errored"){t.signal.aborted&&(yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId});return}let g=m.turnResult;if(g===null){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId};return}if(r.addRoundUsage(DS(g.usage,g.stopReason,t.model,t.fastMode?"fast":void 0)),t.onUsageProgress?.(r.usage),g.stopReason!=="tool_use"){yield*U$(g,t,r);return}if((yield*N$(g,t,r,e,n))==="terminated")return;H$(t,t.beforeNextRound?.())}}finally{c.finish(r.elapsedMs())}}var K$=h(()=>{"use strict";FS();J();gf();hf();ms();nc();Fs();y$();_$();M$();$$();B$();j$();zb();W$()});function bte(t,e){return t.authMode==="oauth"&&t.tokenRefresher!==void 0&&"status"in e&&e.status===401}async function*q$(t,e,n){let r=null;for await(let s of HS(e)){if(n())return;if(s.type==="error"&&bte(t,s.error)){r=s;break}yield s}if(!r)return;if(!await t.forceClientRefresh()){yield r;return}e.client=t.getClient(),e.headers=t.rotateHeaders(e),yield*HS(e)}var G$=h(()=>{"use strict";K$()});var Ef=h(()=>{"use strict"});async function*X$(t,e,n,r,o){let s=Ko(Xe()??"");if(yield{type:"paused",reason:"usage-limit",accountId:s,autoResume:t.autoResumeOnUsageLimit},q(e.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!1,autoResume:t.autoResumeOnUsageLimit}}),!t.autoResumeOnUsageLimit){t.markCredentialSnapshotStale(),yield o;return}let i=Date.now(),a=!1;for(;;){let c;if(t.getUsageLimitWait())c="aborted";else{let p=eM({signal:e.signal,retryAfterMs:6e4});t.setUsageLimitWait(p);try{c=await p}finally{t.setUsageLimitWait(null)}}if(c==="aborted")return;let d=s;if(c==="hot-swap"){let p=await t.forceClientRefresh();p&&(e.client=t.getClient(),d=p.accountId)}e.headers=t.rotateHeaders(e);let u=null;for await(let p of r(t,e,n)){if(!a&&p.type==="error"){let f=ga(p.error);if(f&&(f.kind==="oauth-limit"||f.kind==="oauth-limit-no-ts")){u=p;break}}a||(yield{type:"resumed",hotSwapped:c==="hot-swap",accountId:d},q(e.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-i,metadata:{source:"retry-layer",hotSwapped:c==="hot-swap"}}),a=!0),yield p}if(!u)return;if(Date.now()-i>72e5){yield u;return}}}async function*z$(t,e,n,r,o,s){if(s.getTime()-Date.now()>72e5){t.markCredentialSnapshotStale(),yield o;return}let i=Ko(Xe()??""),a=Date.now();if(yield{type:"paused",reason:"usage-limit",resetsAt:s,accountId:i,autoResume:t.autoResumeOnUsageLimit},q(e.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!0,autoResume:t.autoResumeOnUsageLimit,resetsAt:s.toISOString()}}),!t.autoResumeOnUsageLimit){t.markCredentialSnapshotStale(),yield o;return}let c,l=t.getUsageLimitWait();if(l)c=await l;else{let u=ZP({resetsAt:s,signal:e.signal});t.setUsageLimitWait(u);try{c=await u}finally{t.setUsageLimitWait(null)}}if(c==="aborted")return;let d=i;if(c==="hot-swap"){let u=await t.forceClientRefresh();u&&(e.client=t.getClient(),d=u.accountId)}e.headers=t.rotateHeaders(e),yield{type:"resumed",hotSwapped:c==="hot-swap",accountId:d},q(e.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-a,metadata:{source:"retry-layer",hotSwapped:c==="hot-swap"}}),yield*r(t,e,n)}var J$=h(()=>{"use strict";ha();CS();J();Ef()});async function*Q$(t,e,n,r){let o=null,s=null,i=!1,a=0;for(;;){let c,l=!1;for await(let p of r(t,e,n)){if(p.type==="error"){let f=ga(p.error);if(f&&f.kind==="oauth-limit"){s=f.resetsAt,o=p;break}if(f&&f.kind==="oauth-limit-no-ts"){i=!0,o=p;break}if(f&&f.kind==="rate-limit-transient"&&a<3){l=!0,c=f.retryAfterMs;break}}yield p}if(!l)break;if(a+=1,n()||e.signal.aborted)return;let u=Math.min(c??5e3,12e4)+Math.floor(Math.random()*1e3);if(q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"retry-after",source:"retry-layer",attempt:a,waitMs:u}}),await We(u,e.signal),n()||e.signal.aborted)return;e.headers=t.rotateHeaders(e)}if(o){if(i){yield*X$(t,e,n,r,o);return}s&&(yield*z$(t,e,n,r,o,s))}}var Z$=h(()=>{"use strict";ha();Bn();J();Ef();J$()});async function*eU(t,e,n,r){let o=m$(t.surface),s=null,i=!1;for(;;){let a=null;for await(let l of r(t,e,n)){if(f$(l)){a=l;break}yield l}if(!a){i&&s!==null&&q(e.traceWriter,{phase:"overload_resume",durationMs:Date.now()-s,metadata:{source:"retry-layer",outcome:"recovered"}});return}if(n()||e.signal.aborted||o===0){yield a;return}s??=Date.now();let c=o-(Date.now()-s);if(c<=0){i&&q(e.traceWriter,{phase:"overload_resume",durationMs:Date.now()-s,metadata:{source:"retry-layer",outcome:"ceiling-reached"}}),yield a;return}if(i||(q(e.traceWriter,{phase:"overload_pause",metadata:{reason:"overloaded",source:"retry-layer",hasResetTimestamp:!1,ceilingMs:o,surface:t.surface??"unknown"}}),i=!0),await We(Math.min(p$(),c),e.signal),n()){yield a;return}if(e.signal.aborted)return;e.headers=t.rotateHeaders(e),yield{type:"stream.retry",sessionId:e.ctx.sessionId}}}var tU=h(()=>{"use strict";nc();Bn();J()});import{randomUUID as vte}from"node:crypto";var _f,nU=h(()=>{"use strict";xn();Ds();CS();G$();Z$();tU();Ef();_f=class{_client;_authMode;initSessionId;baseUrl;tokenRefresher;autoResumeOnUsageLimit;surface;refreshPromise=null;usageLimitWaitPromise=null;credentialSnapshotStale=!1;constructor(e){this._client=e.client,this._authMode=e.authMode,this.initSessionId=e.initSessionId,this.baseUrl=e.baseUrl,this.tokenRefresher=e.tokenRefresher,this.autoResumeOnUsageLimit=e.autoResumeOnUsageLimit,e.surface!==void 0&&(this.surface=e.surface)}get client(){return this._client}get authMode(){return this._authMode}rotateHeaders(e){return An(this._authMode,this.initSessionId,vte(),e.effort!==void 0,ff({...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{}}),e.fastMode===!0)}tierContext(){let e=this;return{get authMode(){return e._authMode},get surface(){return e.surface},get autoResumeOnUsageLimit(){return e.autoResumeOnUsageLimit},get tokenRefresher(){return e.tokenRefresher},getClient:()=>e._client,rotateHeaders:n=>e.rotateHeaders(n),forceClientRefresh:()=>e.forceClientRefresh(),getUsageLimitWait:()=>e.usageLimitWaitPromise,setUsageLimitWait:n=>{e.usageLimitWaitPromise=n},markCredentialSnapshotStale:()=>{e.credentialSnapshotStale=!0}}}async forceClientRefresh(){if(!this.tokenRefresher)return null;let e=Xe(),n=null;try{if(this.refreshPromise)n=await this.refreshPromise;else{this.refreshPromise=this.tokenRefresher();try{n=await this.refreshPromise??null}finally{this.refreshPromise=null}}}catch{return this.refreshPromise=null,null}if(!n)return null;this._client=n;let r=Xe();return{accountId:Ko(r??""),swapped:e!==r}}async*turnWithRetries(e,n){this.credentialSnapshotStale&&(await this.forceClientRefresh()&&(e.client=this._client,e.headers=this.rotateHeaders(e)),this.credentialSnapshotStale=!1);let r=this.tierContext();yield*eU(r,e,n,(o,s,i)=>Q$(o,s,i,q$))}}});function rU(){return Tte.map(t=>({...t}))}var Tte,oU=h(()=>{"use strict";Tte=[{value:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",description:"Balanced Claude \u2014 recommended default (1M context, 128k output)"},{value:"claude-sonnet-5",displayName:"Claude Sonnet 5",description:"Newer balanced Claude \u2014 adaptive thinking, new tokenizer"},{value:"claude-opus-5",displayName:"Claude Opus 5",description:"Highest-capability Claude for agentic coding"},{value:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}]});function Af(t){if(t.length===0)return;let e=t[t.length-1];if(!e||e.role!=="assistant"||typeof e.content=="string")return;let n=e.content,r=[];for(let s of n)s.type==="tool_use"&&typeof s.id=="string"&&r.push(s.id);if(r.length===0)return;let o={role:"user",content:r.map(s=>({type:"tool_result",tool_use_id:s,content:"Tool call interrupted before completing \u2014 no result recorded.",is_error:!0}))};t.push(o)}var KS=h(()=>{"use strict"});var xf=h(()=>{"use strict";Po()});async function*sU(t){if(t.state.autoCompactThreshold===void 0||t.state.closed)return;let e=t.state.lastUsage,n=sn(t.state.requestedModel);if(e===null||n<=0)return;let r=_e(e);if(bi(r,n,t.state.autoCompactThreshold))try{t.hookRegistry&&await t.hookRegistry.dispatch({event:"PreCompact",sessionId:t.initSessionId,trigger:"auto"}),(await t.compact()).compacted&&(t.state.lastUsage=null)}catch(o){if(!(o instanceof ee))throw o}}var iU=h(()=>{"use strict";Bt();xf();se()});import{randomUUID as Ete}from"node:crypto";async function*aU(t){yield{type:"session.init",info:{sessionId:t.initSessionId,model:t.state.currentModel,permissionMode:t.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:t.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:t.retry.authMode,version:"anthropic-direct-v1"}};let n=t.promptStream[Symbol.asyncIterator]();try{for(;!t.state.closed;){let r=await Promise.race([n.next(),t.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=t.abort.begin();if(i.signal.aborted){t.abort.clear(i);return}Af(t.state.messages);{let u;try{Si(_e(t.state.lastUsage??{}),t.maxTokens,Tt(t.state.requestedModel??t.state.currentModel),t.state.requestedModel??t.state.currentModel)}catch(p){u=p instanceof Error?p:new Error(String(p))}if(u!==void 0){t.abort.clear(i),yield{type:"error",error:u};continue}}t.state.messages.push({role:"user",content:s.content});let a=t.composeSystem(),{decision:c,runInput:l}=w$({client:t.retry.client,messages:t.state.messages,system:a,tools:t.state.currentPermissionMode==="plan"?t.tools:t.tools?.filter(u=>u.name!==yt)??null,toolDispatcher:t.state.toolDispatcher,model:t.state.currentModel,maxTokens:t.maxTokens,signal:i.signal,authMode:t.retry.authMode,sessionId:t.initSessionId,requestId:Ete(),...t.fastModeController?{fastModeController:t.fastModeController}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{},onUsageProgress:u=>{t.state.lastUsage=u}}),d=!1;try{for await(let u of t.retry.turnWithRetries(l,()=>t.state.closed)){if(u.type==="turn.completed"){if(t.state.lastUsage=u.usage,t.abort.clear(i),d=!0,yield u,t.state.closed)return;continue}if(t.state.closed)return;u.type==="error"&&(d=!0),yield u}}catch(u){if(t.state.closed)return;if(i.signal.aborted){t.abort.clear(i),d||(yield t.makeInterruptedTurnEvent());continue}yield{type:"error",error:Sf(u,c?.effective===!0)};return}finally{t.abort.clear(i)}if(t.state.closed)return;if(i.signal.aborted){d||(yield t.makeInterruptedTurnEvent());continue}yield*sU(t)}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}var cU=h(()=>{"use strict";zr();Bt();KS();xf();jS();iU()});function lU(t){let e=t.lastUsage,n=Tt(t.requestedModel),r;if(e&&n>0){let i=_e(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=yi(e);return{tools:[],agents:[],isAutoCompactEnabled:t.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}function dU(t){return t?t.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}function uU(t){return{subscriptionType:t==="oauth"?"claude-subscription":"api-key"}}var pU=h(()=>{"use strict";Bt();xf()});var fU=h(()=>{"use strict";bw()});var mU=h(()=>{"use strict";hw()});function gU(t){let{state:e,systemPrefix:n,baseUrl:r}=t;e.userSystem&&(e.userSystem=Ju(e.userSystem));let o=[];n&&n.length>0&&o.push(...n),e.userSystem&&e.userSystem.length>0&&o.push({type:"text",text:e.userSystem});let s=gw(e.currentPermissionMode);s!==null&&o.push(s);let i=yw(e.currentPermissionMode);return i!==null&&o.push(i),o.length===0?null:ec({baseUrl:r})?QN(o,ao()):o}var hU=h(()=>{"use strict";Ds();fU();mU();Yb()});function yU(t,e){e===void 0||e.length===0||(t.requestedModel=e,t.currentModel=Ee(e)??e)}function bU(t){let{state:e,mode:n,onPermissionMode:r}=t;e.currentPermissionMode=n,e.toolDispatcher.setAllowAll?.(Et(n)),r?.(n)}function wU(t){let{state:e,cwd:n,cwdDependentsFactory:r}=t;if(e.toolDispatcher.setResolveBase?.(n),!r)return;let{userSystem:o,dispatcher:s}=r(n);e.userSystem=o,e.toolDispatcher=s}function SU(t){let{state:e,basePrompt:n,systemPromptRebuildFactory:r}=t;return r?(e.userSystem=r(n),!0):!1}var kU=h(()=>{"use strict";Mo();lt()});function vU(t){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:t}}var TU=h(()=>{"use strict"});function _te(t){if(t.role!=="user")return!1;let e=t.content;if(typeof e=="string")return!0;if(!Array.isArray(e))return!1;for(let n of e)if(n.type==="tool_result")return!1;return!0}function Ate(t){let n=[(t.role==="user"?"User":"Assistant")+":"];if(typeof t.content=="string")n.push(t.content);else if(Array.isArray(t.content))for(let r of t.content){let o=r.type;if(o==="text"&&"text"in r)n.push(r.text);else if(o==="tool_use"){let s=r.name??"unknown",i=RU(r.input);n.push(`[tool call: ${s} ${i}]`)}else if(o==="tool_result"){let s=r.content;n.push(`[tool result: ${IU(s)}]`)}else o==="image"?n.push("[image]"):o==="document"&&n.push("[document]")}return n.join(`
|
|
1416
|
+
${r}`:t.text,sessionId:e.ctx.sessionId},t.text.length<=hte&&(yield{type:"suggestion",suggestion:t.text,sessionId:e.ctx.sessionId})):r!==null&&(yield{type:"notice",text:r,kind:"truncation",sessionId:e.ctx.sessionId});let o=t.assistantBlocks.filter(s=>s.type!=="tool_use");o.length>0&&e.messages.push({role:"assistant",content:o}),yield{type:"turn.completed",usage:n.withDuration(n.windDownReason!==null?{...n.usage,stopReason:n.windDownReason}:n.usage),sessionId:e.ctx.sessionId}}var hte,B$=h(()=>{"use strict";ka();hte=200});import{randomUUID as yte}from"node:crypto";var Tf,j$=h(()=>{"use strict";FS();Tf=class{usage={stopReason:null};iterations=0;toolCallCount=0;windDownReason=null;taskId=yte();startedAt=Date.now();elapsedMs(){return Date.now()-this.startedAt}withDuration(e){return{...e,durationMs:this.elapsedMs()}}terminalUsage(){return this.withDuration(this.usage)}addRoundUsage(e){this.usage=_a(this.usage,e),this.usage.contextWindowTokens=(e.inputTokens??0)+(e.outputTokens??0)+(e.cachedInputTokens??0)+(e.cacheCreationTokens??0)}}});function H$(t,e){if(!e)return;let n=t.messages.at(-1);!n||n.role!=="user"||(Array.isArray(n.content)?n.content.push({type:"text",text:e}):n.content=[{type:"text",text:n.content},{type:"text",text:e}],Wl(t.traceWriter,{jobId:t.subagentId??"",subagentId:t.subagentId??"",byteLength:Buffer.byteLength(e,"utf8")}))}var W$=h(()=>{"use strict";J()});async function*HS(t){let e=Sp(t.maxToolUseIterations),n=t.softDeadlineMs??0,r=new Tf,o=new bf,s=l=>({input:t,turn:r,retry:o,requestStartedAt:l}),i=wf(mf()),a=a$(),c=new ss(t.signal,t.traceWriter,"anthropic-direct");try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId};return}let l=yield*E$({input:t,turn:r,retry:o,ttfbTimeoutMs:i,stallTimeoutMs:a});if(l.kind==="terminated")return;if(l.kind==="retry-ttfb"){if((yield*BS("ttfb",s(l.requestStartedAt)))==="terminated")return;continue}if(l.kind==="overload-exhausted"){q(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"connection-phase",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:$S,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:st}),sessionId:t.ctx.sessionId};return}let{events:d,ttfb:u,stall:p,requestStartedAt:f}=l,m=yield*P$({events:d,input:t,turn:r,retry:o,ttfb:u,stall:p,stallTimeoutMs:a,requestStartedAt:f});if(m.kind==="terminated")return;if(m.kind==="retry"){if((yield*BS(m.reason,s(f)))==="terminated")return;continue}if(o.reset(),m.kind==="overload-exhausted"){q(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:$S,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:st}),sessionId:t.ctx.sessionId};return}if(m.kind==="translator-errored"){t.signal.aborted&&(yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId});return}let g=m.turnResult;if(g===null){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId};return}if(r.addRoundUsage(DS(g.usage,g.stopReason,t.model,t.fastMode?"fast":void 0)),t.onUsageProgress?.(r.usage),g.stopReason!=="tool_use"){yield*U$(g,t,r);return}if((yield*N$(g,t,r,e,n))==="terminated")return;H$(t,t.beforeNextRound?.())}}finally{c.finish(r.elapsedMs())}}var K$=h(()=>{"use strict";FS();J();gf();hf();ms();nc();Fs();y$();_$();M$();$$();B$();j$();zb();W$()});function bte(t,e){return t.authMode==="oauth"&&t.tokenRefresher!==void 0&&"status"in e&&e.status===401}async function*q$(t,e,n){let r=null;for await(let s of HS(e)){if(n())return;if(s.type==="error"&&bte(t,s.error)){r=s;break}yield s}if(!r)return;if(!await t.forceClientRefresh()){yield r;return}e.client=t.getClient(),e.headers=t.rotateHeaders(e),yield*HS(e)}var G$=h(()=>{"use strict";K$()});var Ef=h(()=>{"use strict"});async function*X$(t,e,n,r,o){let s=Ko(Xe()??"");if(yield{type:"paused",reason:"usage-limit",accountId:s,autoResume:t.autoResumeOnUsageLimit},q(e.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!1,autoResume:t.autoResumeOnUsageLimit}}),!t.autoResumeOnUsageLimit){t.markCredentialSnapshotStale(),yield o;return}let i=Date.now(),a=!1;for(;;){let c;if(t.getUsageLimitWait())c="aborted";else{let p=eM({signal:e.signal,retryAfterMs:6e4});t.setUsageLimitWait(p);try{c=await p}finally{t.setUsageLimitWait(null)}}if(c==="aborted")return;let d=s;if(c==="hot-swap"){let p=await t.forceClientRefresh();p&&(e.client=t.getClient(),d=p.accountId)}e.headers=t.rotateHeaders(e);let u=null;for await(let p of r(t,e,n)){if(!a&&p.type==="error"){let f=ga(p.error);if(f&&(f.kind==="oauth-limit"||f.kind==="oauth-limit-no-ts")){u=p;break}}a||(yield{type:"resumed",hotSwapped:c==="hot-swap",accountId:d},q(e.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-i,metadata:{source:"retry-layer",hotSwapped:c==="hot-swap"}}),a=!0),yield p}if(!u)return;if(Date.now()-i>72e5){yield u;return}}}async function*z$(t,e,n,r,o,s){if(s.getTime()-Date.now()>72e5){t.markCredentialSnapshotStale(),yield o;return}let i=Ko(Xe()??""),a=Date.now();if(yield{type:"paused",reason:"usage-limit",resetsAt:s,accountId:i,autoResume:t.autoResumeOnUsageLimit},q(e.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!0,autoResume:t.autoResumeOnUsageLimit,resetsAt:s.toISOString()}}),!t.autoResumeOnUsageLimit){t.markCredentialSnapshotStale(),yield o;return}let c,l=t.getUsageLimitWait();if(l)c=await l;else{let u=ZP({resetsAt:s,signal:e.signal});t.setUsageLimitWait(u);try{c=await u}finally{t.setUsageLimitWait(null)}}if(c==="aborted")return;let d=i;if(c==="hot-swap"){let u=await t.forceClientRefresh();u&&(e.client=t.getClient(),d=u.accountId)}e.headers=t.rotateHeaders(e),yield{type:"resumed",hotSwapped:c==="hot-swap",accountId:d},q(e.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-a,metadata:{source:"retry-layer",hotSwapped:c==="hot-swap"}}),yield*r(t,e,n)}var J$=h(()=>{"use strict";ha();CS();J();Ef()});async function*Q$(t,e,n,r){let o=null,s=null,i=!1,a=0;for(;;){let c,l=!1;for await(let p of r(t,e,n)){if(p.type==="error"){let f=ga(p.error);if(f&&f.kind==="oauth-limit"){s=f.resetsAt,o=p;break}if(f&&f.kind==="oauth-limit-no-ts"){i=!0,o=p;break}if(f&&f.kind==="rate-limit-transient"&&a<3){l=!0,c=f.retryAfterMs;break}}yield p}if(!l)break;if(a+=1,n()||e.signal.aborted)return;let u=Math.min(c??5e3,12e4)+Math.floor(Math.random()*1e3);if(q(e.traceWriter,{phase:"rate_limit",metadata:{reason:"retry-after",source:"retry-layer",attempt:a,waitMs:u}}),await We(u,e.signal),n()||e.signal.aborted)return;e.headers=t.rotateHeaders(e)}if(o){if(i){yield*X$(t,e,n,r,o);return}s&&(yield*z$(t,e,n,r,o,s))}}var Z$=h(()=>{"use strict";ha();Bn();J();Ef();J$()});async function*eU(t,e,n,r){let o=m$(t.surface),s=null,i=!1;for(;;){let a=null;for await(let l of r(t,e,n)){if(f$(l)){a=l;break}yield l}if(!a){i&&s!==null&&q(e.traceWriter,{phase:"overload_resume",durationMs:Date.now()-s,metadata:{source:"retry-layer",outcome:"recovered"}});return}if(n()||e.signal.aborted||o===0){yield a;return}s??=Date.now();let c=o-(Date.now()-s);if(c<=0){i&&q(e.traceWriter,{phase:"overload_resume",durationMs:Date.now()-s,metadata:{source:"retry-layer",outcome:"ceiling-reached"}}),yield a;return}if(i||(q(e.traceWriter,{phase:"overload_pause",metadata:{reason:"overloaded",source:"retry-layer",hasResetTimestamp:!1,ceilingMs:o,surface:t.surface??"unknown"}}),i=!0),await We(Math.min(p$(),c),e.signal),n()){yield a;return}if(e.signal.aborted)return;e.headers=t.rotateHeaders(e),yield{type:"stream.retry",sessionId:e.ctx.sessionId}}}var tU=h(()=>{"use strict";nc();Bn();J()});import{randomUUID as vte}from"node:crypto";var _f,nU=h(()=>{"use strict";xn();Ds();CS();G$();Z$();tU();Ef();_f=class{_client;_authMode;initSessionId;baseUrl;tokenRefresher;autoResumeOnUsageLimit;surface;refreshPromise=null;usageLimitWaitPromise=null;credentialSnapshotStale=!1;constructor(e){this._client=e.client,this._authMode=e.authMode,this.initSessionId=e.initSessionId,this.baseUrl=e.baseUrl,this.tokenRefresher=e.tokenRefresher,this.autoResumeOnUsageLimit=e.autoResumeOnUsageLimit,e.surface!==void 0&&(this.surface=e.surface)}get client(){return this._client}get authMode(){return this._authMode}rotateHeaders(e){return An(this._authMode,this.initSessionId,vte(),e.effort!==void 0,ff({...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{}}),e.fastMode===!0)}tierContext(){let e=this;return{get authMode(){return e._authMode},get surface(){return e.surface},get autoResumeOnUsageLimit(){return e.autoResumeOnUsageLimit},get tokenRefresher(){return e.tokenRefresher},getClient:()=>e._client,rotateHeaders:n=>e.rotateHeaders(n),forceClientRefresh:()=>e.forceClientRefresh(),getUsageLimitWait:()=>e.usageLimitWaitPromise,setUsageLimitWait:n=>{e.usageLimitWaitPromise=n},markCredentialSnapshotStale:()=>{e.credentialSnapshotStale=!0}}}async forceClientRefresh(){if(!this.tokenRefresher)return null;let e=Xe(),n=null;try{if(this.refreshPromise)n=await this.refreshPromise;else{this.refreshPromise=this.tokenRefresher();try{n=await this.refreshPromise??null}finally{this.refreshPromise=null}}}catch{return this.refreshPromise=null,null}if(!n)return null;this._client=n;let r=Xe();return{accountId:Ko(r??""),swapped:e!==r}}async*turnWithRetries(e,n){this.credentialSnapshotStale&&(await this.forceClientRefresh()&&(e.client=this._client,e.headers=this.rotateHeaders(e)),this.credentialSnapshotStale=!1);let r=this.tierContext();yield*eU(r,e,n,(o,s,i)=>Q$(o,s,i,q$))}}});function rU(){return Tte.map(t=>({...t}))}var Tte,oU=h(()=>{"use strict";Tte=[{value:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",description:"Balanced Claude \u2014 recommended default (1M context, 128k output)"},{value:"claude-sonnet-5",displayName:"Claude Sonnet 5",description:"Newer balanced Claude \u2014 adaptive thinking, new tokenizer"},{value:"claude-opus-5",displayName:"Claude Opus 5",description:"Highest-capability Claude for agentic coding"},{value:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}]});function Af(t){if(t.length===0)return;let e=t[t.length-1];if(!e||e.role!=="assistant"||typeof e.content=="string")return;let n=e.content,r=[];for(let s of n)s.type==="tool_use"&&typeof s.id=="string"&&r.push(s.id);if(r.length===0)return;let o={role:"user",content:r.map(s=>({type:"tool_result",tool_use_id:s,content:"Tool call interrupted before completing \u2014 no result recorded.",is_error:!0}))};t.push(o)}var KS=h(()=>{"use strict"});var xf=h(()=>{"use strict";Po()});async function*sU(t){if(t.state.autoCompactThreshold===void 0||t.state.closed)return;let e=t.state.lastUsage,n=sn(t.state.requestedModel);if(e===null||n<=0)return;let r=_e(e);if(bi(r,n,t.state.autoCompactThreshold))try{t.hookRegistry&&await t.hookRegistry.dispatch({event:"PreCompact",sessionId:t.initSessionId,trigger:"auto"}),(await t.compact()).compacted&&(t.state.lastUsage=null)}catch(o){if(!(o instanceof ee))throw o}}var iU=h(()=>{"use strict";Bt();xf();ie()});import{randomUUID as Ete}from"node:crypto";async function*aU(t){yield{type:"session.init",info:{sessionId:t.initSessionId,model:t.state.currentModel,permissionMode:t.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:t.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:t.retry.authMode,version:"anthropic-direct-v1"}};let n=t.promptStream[Symbol.asyncIterator]();try{for(;!t.state.closed;){let r=await Promise.race([n.next(),t.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=t.abort.begin();if(i.signal.aborted){t.abort.clear(i);return}Af(t.state.messages);{let u;try{Si(_e(t.state.lastUsage??{}),t.maxTokens,Tt(t.state.requestedModel??t.state.currentModel),t.state.requestedModel??t.state.currentModel)}catch(p){u=p instanceof Error?p:new Error(String(p))}if(u!==void 0){t.abort.clear(i),yield{type:"error",error:u};continue}}t.state.messages.push({role:"user",content:s.content});let a=t.composeSystem(),{decision:c,runInput:l}=w$({client:t.retry.client,messages:t.state.messages,system:a,tools:t.state.currentPermissionMode==="plan"?t.tools:t.tools?.filter(u=>u.name!==yt)??null,toolDispatcher:t.state.toolDispatcher,model:t.state.currentModel,maxTokens:t.maxTokens,signal:i.signal,authMode:t.retry.authMode,sessionId:t.initSessionId,requestId:Ete(),...t.fastModeController?{fastModeController:t.fastModeController}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{},onUsageProgress:u=>{t.state.lastUsage=u}}),d=!1;try{for await(let u of t.retry.turnWithRetries(l,()=>t.state.closed)){if(u.type==="turn.completed"){if(t.state.lastUsage=u.usage,t.abort.clear(i),d=!0,yield u,t.state.closed)return;continue}if(t.state.closed)return;u.type==="error"&&(d=!0),yield u}}catch(u){if(t.state.closed)return;if(i.signal.aborted){t.abort.clear(i),d||(yield t.makeInterruptedTurnEvent());continue}yield{type:"error",error:Sf(u,c?.effective===!0)};return}finally{t.abort.clear(i)}if(t.state.closed)return;if(i.signal.aborted){d||(yield t.makeInterruptedTurnEvent());continue}yield*sU(t)}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}var cU=h(()=>{"use strict";zr();Bt();KS();xf();jS();iU()});function lU(t){let e=t.lastUsage,n=Tt(t.requestedModel),r;if(e&&n>0){let i=_e(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=yi(e);return{tools:[],agents:[],isAutoCompactEnabled:t.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}function dU(t){return t?t.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}function uU(t){return{subscriptionType:t==="oauth"?"claude-subscription":"api-key"}}var pU=h(()=>{"use strict";Bt();xf()});var fU=h(()=>{"use strict";bw()});var mU=h(()=>{"use strict";hw()});function gU(t){let{state:e,systemPrefix:n,baseUrl:r}=t;e.userSystem&&(e.userSystem=Ju(e.userSystem));let o=[];n&&n.length>0&&o.push(...n),e.userSystem&&e.userSystem.length>0&&o.push({type:"text",text:e.userSystem});let s=gw(e.currentPermissionMode);s!==null&&o.push(s);let i=yw(e.currentPermissionMode);return i!==null&&o.push(i),o.length===0?null:ec({baseUrl:r})?QN(o,ao()):o}var hU=h(()=>{"use strict";Ds();fU();mU();Yb()});function yU(t,e){e===void 0||e.length===0||(t.requestedModel=e,t.currentModel=Ee(e)??e)}function bU(t){let{state:e,mode:n,onPermissionMode:r}=t;e.currentPermissionMode=n,e.toolDispatcher.setAllowAll?.(Et(n)),r?.(n)}function wU(t){let{state:e,cwd:n,cwdDependentsFactory:r}=t;if(e.toolDispatcher.setResolveBase?.(n),!r)return;let{userSystem:o,dispatcher:s}=r(n);e.userSystem=o,e.toolDispatcher=s}function SU(t){let{state:e,basePrompt:n,systemPromptRebuildFactory:r}=t;return r?(e.userSystem=r(n),!0):!1}var kU=h(()=>{"use strict";Mo();lt()});function vU(t){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:t}}var TU=h(()=>{"use strict"});function _te(t){if(t.role!=="user")return!1;let e=t.content;if(typeof e=="string")return!0;if(!Array.isArray(e))return!1;for(let n of e)if(n.type==="tool_result")return!1;return!0}function Ate(t){let n=[(t.role==="user"?"User":"Assistant")+":"];if(typeof t.content=="string")n.push(t.content);else if(Array.isArray(t.content))for(let r of t.content){let o=r.type;if(o==="text"&&"text"in r)n.push(r.text);else if(o==="tool_use"){let s=r.name??"unknown",i=RU(r.input);n.push(`[tool call: ${s} ${i}]`)}else if(o==="tool_result"){let s=r.content;n.push(`[tool result: ${IU(s)}]`)}else o==="image"?n.push("[image]"):o==="document"&&n.push("[document]")}return n.join(`
|
|
1417
1417
|
`)}function xte(t){let e=0;if(typeof t.content=="string")e+=t.content.length;else if(Array.isArray(t.content))for(let n of t.content){let r=n.type;r==="text"&&"text"in n?e+=n.text.length:r==="tool_use"?e+=RU(n.input).length:r==="tool_result"&&(e+=IU(n.content).length)}return e}function Rte(t){if(typeof t=="string")return eo(t);if(Array.isArray(t)){let e=0;for(let n of t)n.type==="text"&&"text"in n&&(e+=eo(n.text));return e}return 0}function Ite(t){if(typeof t=="string")return ds(t);if(Array.isArray(t)){for(let e of t)if(e.type==="text"&&"text"in e)return ds(e.text)}return!1}function qS(t,e){return rp(t,Cte,e??{})}function EU(t,e,n,r){return iw(t,e,Rf,n,r)}function _U(t,e,n){let r=aw(t,Rf);return{model:e,max_tokens:n,system:Ca,messages:[{role:"user",content:Oa(r)}],stream:!0}}function AU(t,e,n){return cw(t,e,n,Rf)}function xU(t,e,n){return lw(t,e,n,Rf)}function RU(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function IU(t){if(typeof t=="string")return t.length>320?t.slice(0,317)+"...":t;if(Array.isArray(t)){let e=[];for(let r of t)r.type==="text"&&"text"in r&&e.push(r.text);let n=e.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}var Rf,Cte,CU=h(()=>{"use strict";Da();Rf={isFreshUserTurn:_te,renderMessage:Ate,buildPreamble(t){return[{role:"user",content:Pa+`
|
|
1418
1418
|
|
|
1419
1419
|
`+t},{role:"assistant",content:Ma}]},countChars:xte};Cte={listToolResults(t){let e=[];for(let n of t){if(n.role!=="user"||!Array.isArray(n.content))continue;let r=n.content;for(let o of r){if(o.type!=="tool_result")continue;let s=o;e.push({byteLength:Rte(s.content),isPlaceholder:Ite(s.content),clear(i){s.content=i}})}}return e}}});import{randomUUID as Pte}from"node:crypto";async function MU(t){let{state:e,abort:n,retry:r,initSessionId:o,traceWriter:s}=t,i=e.messages.length;if(e.closed)return{compacted:!1,reason:"session-closed",messagesBefore:i,messagesAfter:i};if(!n.isIdle())return{compacted:!1,reason:"turn-in-flight",messagesBefore:i,messagesAfter:i};let a=Fte(),c=wi(_e(e.lastUsage??{}),sn(e.requestedModel)),l=EU(e.messages,a,c,Lte());if(l<0)return PU(e,i,"history-too-short");if(l===0)return PU(e,i,"nothing-to-summarize");let d=e.messages.slice(0,l),u=Nte(),p=_U(d,u,Dte),f=n.begin(),m;try{if(f.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let w=An(r.authMode,o,Pte()),v=r.client,_=await Promise.resolve(v.messages.create(p,{headers:w,signal:f.signal}));m=await $te(_)}catch(w){return f.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(w instanceof Error?w.message:String(w)),messagesBefore:i,messagesAfter:i}}finally{n.clear(f)}if(m.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=xU(e.messages,l,m),y=AU(e.messages,l,m);e.messages.splice(0,e.messages.length,...y);let b=e.messages.length;return Hl(s,{trigger:"manual",preCompactionMessages:d,summary:m,keptTailCount:i-l,keepLastNConfig:a,messagesBefore:i,messagesAfter:b,tokensSavedEstimate:g}),qS(e.messages,OU()),{compacted:!0,messagesBefore:i,messagesAfter:b,tokensSavedEstimate:g}}function Fte(){let t=k.AFK_COMPACT_KEEP_LAST_TURNS;if(t!==void 0&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return Mte}function Lte(){let t=k.AFK_COMPACT_SHRINK_FRACTION;if(t!==void 0&&t.length>0){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>0&&e<1)return e}return ls}function PU(t,e,n){let r=OU(),{blocksCleared:o,bytesReclaimed:s}=qS(t.messages,r);return o>0?{compacted:!1,reason:"microcompacted",messagesBefore:e,messagesAfter:t.messages.length,microcompaction:{blocksCleared:o,bytesReclaimed:s}}:{compacted:!1,reason:n,messagesBefore:e,messagesAfter:e}}function OU(){return us(k.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,k.AFK_MICROCOMPACT_KEEP_LAST)}function Nte(){let t=k.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?Ee(t)??t:Ote}async function $te(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var Mte,Ote,Dte,DU=h(()=>{"use strict";xn();CU();Da();Po();Bt();J();lt();F();Mte=2,Ote="claude-haiku-4-5-20251001",Dte=1024});function GS(t){if(typeof t=="string")return t;let e=[];for(let n of t)n.type==="text"&&typeof n.text=="string"&&e.push(n.text);return e.join(" ")}function LU(t){return t.role!=="user"?!1:GS(t.content).trim().length>0}function Ute(t){let e=t.replace(/\s+/g," ").trim();return e.length<=FU?e:e.slice(0,FU-1)+"\u2026"}function NU(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];r&&LU(r)&&e.push({turnIndex:n,preview:Ute(GS(r.content))})}return e.reverse()}function $U(t,e){let{state:n,abort:r}=t,o=n.messages.length;if(n.closed)return{rewound:!1,reason:"session-closed",messagesBefore:o,messagesAfter:o};if(!r.isIdle())return{rewound:!1,reason:"turn-in-flight",messagesBefore:o,messagesAfter:o};if(!Number.isInteger(e)||e<0||e>=o)return{rewound:!1,reason:"invalid-target",messagesBefore:o,messagesAfter:o};let s=n.messages[e];if(!s||!LU(s))return{rewound:!1,reason:"invalid-target",messagesBefore:o,messagesAfter:o};let i=GS(s.content);return n.messages.splice(e),Af(n.messages),{rewound:!0,reloadText:i,messagesBefore:o,messagesAfter:n.messages.length}}var FU,UU=h(()=>{"use strict";KS();FU=72});function BU(t){return MU(t)}function jU(t){return NU(t.messages)}function HU(t,e,n){return $U({state:t,abort:e},n)}var WU=h(()=>{"use strict";DU();UU()});import{randomUUID as Bte}from"node:crypto";var oc,XS=h(()=>{"use strict";Xb();YN();ow();nU();oU();cU();pU();hU();kU();TU();WU();oc=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;temperature;baseUrl;maxToolUseIterations;softDeadlineMs;traceWriter;subagentId;state;abort;retry;cwdDependentsFactory;systemPromptRebuildFactory;onPermissionMode;mcpManager;hookRegistry;throttleQueue;fastModeController;beforeNextRound;constructor(e){this.initSessionId=e.sessionId??Bte(),this.promptStream=e.promptStream,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.thinking=e.thinking,e.effort!==void 0&&(this.effort=e.effort),e.temperature!==void 0&&(this.temperature=e.temperature),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),e.maxToolUseIterations!==void 0&&(this.maxToolUseIterations=e.maxToolUseIterations),e.softDeadlineMs!==void 0&&(this.softDeadlineMs=e.softDeadlineMs),this.traceWriter=e.traceWriter,e.subagentId!==void 0&&(this.subagentId=e.subagentId),this.cwdDependentsFactory=e.cwdDependentsFactory,this.systemPromptRebuildFactory=e.systemPromptRebuildFactory,this.onPermissionMode=e.onPermissionMode,this.mcpManager=e.mcpManager,e.hookRegistry!==void 0&&(this.hookRegistry=e.hookRegistry),e.throttleQueue!==void 0&&(this.throttleQueue=e.throttleQueue),e.fastModeController!==void 0&&(this.fastModeController=e.fastModeController),e.beforeNextRound!==void 0&&(this.beforeNextRound=e.beforeNextRound),this.retry=new _f({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0,...e.surface!==void 0?{surface:e.surface}:{}}),this.state=VN({model:e.model,...e.requestedModel!==void 0?{requestedModel:e.requestedModel}:{},permissionMode:e.permissionMode??"default",userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,...e.initialMessages?{initialMessages:e.initialMessages}:{},...e.autoCompactThreshold!==void 0?{autoCompactThreshold:e.autoCompactThreshold}:{},...e.initialUsageInputTokens!==void 0?{initialUsageInputTokens:e.initialUsageInputTokens}:{}}),this.abort=new cs}turnDriverContext(){let e=this;return{get initSessionId(){return e.initSessionId},get promptStream(){return e.promptStream},get state(){return e.state},get abort(){return e.abort},get retry(){return e.retry},get maxTokens(){return e.maxTokens},get tools(){return e.tools},get thinking(){return e.thinking},get effort(){return e.effort},get temperature(){return e.temperature},get baseUrl(){return e.baseUrl},get maxToolUseIterations(){return e.maxToolUseIterations},get softDeadlineMs(){return e.softDeadlineMs},get traceWriter(){return e.traceWriter},get subagentId(){return e.subagentId},get mcpManager(){return e.mcpManager},get hookRegistry(){return e.hookRegistry},get throttleQueue(){return e.throttleQueue},get fastModeController(){return e.fastModeController},get beforeNextRound(){return e.beforeNextRound},composeSystem:()=>e.composeSystem(),makeInterruptedTurnEvent:()=>e.makeInterruptedTurnEvent(),compact:()=>e.compact()}}setBeforeNextRound(e){this.beforeNextRound=e}async*[Symbol.asyncIterator](){yield*aU(this.turnDriverContext())}composeSystem(){return gU({state:this.state,systemPrefix:this.systemPrefix,...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{}})}async interrupt(e="interrupted"){this.abort.requestAbort(e)}makeInterruptedTurnEvent(){return vU(this.initSessionId)}async setModel(e){yU(this.state,e)}async setPermissionMode(e){bU({state:this.state,mode:e,...this.onPermissionMode?{onPermissionMode:this.onPermissionMode}:{}})}setCwd(e){wU({state:this.state,cwd:e,...this.cwdDependentsFactory?{cwdDependentsFactory:this.cwdDependentsFactory}:{}})}setSystemPrompt(e){return SU({state:this.state,basePrompt:e,...this.systemPromptRebuildFactory?{systemPromptRebuildFactory:this.systemPromptRebuildFactory}:{}})}async supportedCommands(){return zu()}async supportedModels(){return rU()}async supportedAgents(){return[]}async getContextUsage(){return lU(this.state)}async mcpServerStatus(){return dU(this.mcpManager)}async accountInfo(){return uU(this.retry.authMode)}async reauth(){return this.retry.forceClientRefresh()}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){let e=await BU({state:this.state,abort:this.abort,retry:this.retry,initSessionId:this.initSessionId,...this.traceWriter?{traceWriter:this.traceWriter}:{}});return e.compacted&&(this.state.lastUsage=null),e}listRewindTargets(){return jU(this.state)}async rewindConversation(e){return HU(this.state,this.abort,e)}close(){this.state.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed()}}});function KU(t){return e=>{let n=t.getCurrentCwd();if(t.sharedReadRoots&&n!==void 0&&n!==e){let s=t.sharedReadRoots.indexOf(n);s!==-1?t.sharedReadRoots[s]=e:t.sharedReadRoots.includes(e)||t.sharedReadRoots.push(e)}if(t.sharedWriteRoots&&n!==void 0&&n!==e){let s=t.sharedWriteRoots.indexOf(n);s!==-1?t.sharedWriteRoots[s]=e:t.sharedWriteRoots.includes(e)||t.sharedWriteRoots.push(e)}t.setCurrentCwd(e),t.subagentExecutor?.setCwd(e),t.skillExecutor?.setCwd(e),t.composeExecutor?.setCwd(e);let r=Os(t.stableSystemPrefix,e,{surface:t.surface,sessionId:t.config.sessionId,depth:t.config.depth,maxDepth:t.config.maxDepth,workspace:t.runtimeStateSource.getWorkspace()}),o=t.buildDispatcher(t.getCurrentPermissionMode(),{cwd:e,readRoots:t.sharedReadRoots,writeRoots:t.sharedWriteRoots,...t.config.env!==void 0?{env:t.config.env}:{},sessionId:t.config.sessionId,parentSessionId:t.config.parentSessionId,traceWriter:t.config.traceWriter,runtimeStateSource:t.runtimeStateSource,hookRegistry:t.config.hookRegistry,planExitControls:t.config.planExitControls});return{userSystem:r,dispatcher:o}}}var qU=h(()=>{"use strict";pf()});function GU(t){return e=>{t.stableSystemPrefix.userSystem=e!==void 0&&e.length>0?e:null;let n=t.getCurrentCwd()??t.fallbackCwd;return Os(t.stableSystemPrefix,n,{surface:t.surface,sessionId:t.config.sessionId,depth:t.config.depth,maxDepth:t.config.maxDepth,workspace:t.runtimeStateSource.getWorkspace()})}}var XU=h(()=>{"use strict";pf()});function zU(t,e,n){let r=e.config,{client:o,authMode:s,localMode:i,model:a,maxTokens:c,cwd:l,systemPrefix:d,throttleQueue:u,tokenRefresher:p,queryDispatcher:f,runtimeStateSource:m,toolDefs:g,resolvedSessionId:y,stableSystemPrefix:b,toolSystemAppend:w}=n,v=y,_=bE(r.resumeHistory),A=r.resumeHistory?.at(-1)?.inputTokens,I=t.externalTools?void 0:KU({stableSystemPrefix:b,config:r,surface:t.surface,runtimeStateSource:m,getCurrentCwd:()=>t.getCurrentCwd(),setCurrentCwd:P=>{t.setCurrentCwd(P)},getCurrentPermissionMode:()=>t.getCurrentPermissionMode(),sharedReadRoots:t.getSharedReadRoots(),sharedWriteRoots:t.getSharedWriteRoots(),subagentExecutor:t.subagentExecutor,skillExecutor:t.skillExecutor,composeExecutor:t.composeExecutor,buildDispatcher:(P,H)=>t.buildDispatcher(P,H)}),C=t.externalTools?void 0:GU({stableSystemPrefix:b,config:r,surface:t.surface,runtimeStateSource:m,getCurrentCwd:()=>t.getCurrentCwd(),fallbackCwd:l}),T=Ml(r.effort,a),R=r.temperature!==void 0?yE(r.temperature):void 0,E=ki(r.autoCompact,typeof r.model=="string"&&r.model.length>0?r.model:a);return new oc({client:o,authMode:i?"api-key":s,promptStream:e.prompt,toolDispatcher:f,...v!==void 0?{sessionId:v}:{},..._!==void 0?{initialMessages:_}:{},...A!==void 0?{initialUsageInputTokens:A}:{},model:a,requestedModel:typeof r.model=="string"&&r.model.length>0?r.model:a,...r.permissionMode!==void 0?{permissionMode:r.permissionMode}:{},maxTokens:c,tools:g,userSystem:w,systemPrefix:d,tokenRefresher:p,...r.thinking!==void 0?{thinking:Pl(r.thinking,c,a)}:{},...T!==void 0?{effort:T}:{},...R!==void 0?{temperature:R}:{},...i?{baseUrl:r.baseUrl}:{},...r.traceWriter?{traceWriter:r.traceWriter}:{},...r.subagentId!==void 0?{subagentId:r.subagentId}:{},...r.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:r.autoResumeOnUsageLimit}:{},surface:t.declaredSurface,...r.maxToolUseIterations!==void 0?{maxToolUseIterations:r.maxToolUseIterations}:{},...r.softDeadlineMs!==void 0?{softDeadlineMs:r.softDeadlineMs}:{},...I!==void 0?{cwdDependentsFactory:I}:{},...C!==void 0?{systemPromptRebuildFactory:C}:{},onPermissionMode:P=>{t.setCurrentPermissionMode(P)},...t.mcpManager!==void 0?{mcpManager:t.mcpManager}:{},...E!==void 0?{autoCompactThreshold:E}:{},...r.hookRegistry!==void 0?{hookRegistry:r.hookRegistry}:{},...u!==void 0?{throttleQueue:u}:{},...t.fastModeController!==void 0?{fastModeController:t.fastModeController}:{}})}var JU=h(()=>{"use strict";XS();Ol();qU();XU()});var zS,VU,De,YU,QU=h(()=>{"use strict";dE();Ol();wE();qP();Su();Su();Nt();ku();B();hb();F();JP();IS();JU();Fe();IS();zS="anthropic-direct",VU=fi,De=class{name=zS;externalTools;memoryStore;workspaceStore;subscribeHandler;stateStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;composeExecutor;surface;declaredSurface;readOnlyMemory;readOnlyBash;mcpManager;customTools;fastModeController;grants=new Fl;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;_mintedSessionId=null;_spawnedPidRegistry=new Zo;constructor(e={}){if(this.memoryStore=e.memoryStore??new Ze,this.workspaceStore=e.workspaceStore,this.subscribeHandler=e.subscribeHandler,this.stateStore=e.stateStore??new jn(ho()),this.externalTools=e.tools,this.skillExecutor=e.skillExecutor,this.schemas=zP(e),this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.composeExecutor=e.composeExecutor,this.surface=e.surface??"cli",this.declaredSurface=e.surface,this.readOnlyMemory=e.readOnlyMemory===!0,this.readOnlyBash=e.readOnlyBash===!0,this.customTools=e.customTools??[],this.fastModeController=e.fastModeController,this.mcpManager=e.mcpManager,e.mcpManager){let n=e.mcpManager.onToolsRefreshed;e.mcpManager.onToolsRefreshed=r=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,n?.(r)}}e.clientFactory&&(this.providerFactory=e.clientFactory)}buildDispatcher(e,n){return KP({memoryStore:this.memoryStore,workspaceStore:this.workspaceStore,stateStore:this.stateStore,surface:this.surface,readOnlyMemory:this.readOnlyMemory,readOnlyBash:this.readOnlyBash,customTools:this.customTools,mcpManager:this.mcpManager,schemas:this.schemas,hookRegistry:this.hookRegistry,permissions:this.permissions,canUseTool:this.canUseTool,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,sessionGrantManager:this,getMcpToolsCache:()=>this._mcpToolsCache,setMcpToolsCache:r=>{this._mcpToolsCache=r},getMcpHandlersCache:()=>this._mcpHandlersCache,setMcpHandlersCache:r=>{this._mcpHandlersCache=r},...this.subscribeHandler!==void 0?{subscribeHandler:this.subscribeHandler}:{}},e,{...n,spawnedPidRegistry:this._spawnedPidRegistry})}setSubscribeHandler(e){this.subscribeHandler=e}close(){this.memoryStore.close(),this.workspaceStore?.close(),this.stateStore.close()}async complete(e){let n=e.apiKey&&e.apiKey.length>0?e.apiKey:k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${zS} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:e.model??VU,system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.signal&&(r.signal=e.signal);let o=this.providerFactory??wu();return o&&(r.clientFactory=o),lE(r)}addReadRoot(e,n="slash",r){this.grants.manager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grants.manager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grants.manager.revokeRoot(e,n,r)}getGrants(){return this.grants.manager.getGrants()}queryContext(){let e=this;return{get externalTools(){return e.externalTools},get providerFactory(){return e.providerFactory},get skillExecutor(){return e.skillExecutor},get subagentExecutor(){return e.subagentExecutor},get composeExecutor(){return e.composeExecutor},get canUseTool(){return e.canUseTool},get surface(){return e.surface},get declaredSurface(){return e.declaredSurface},get readOnlyMemory(){return e.readOnlyMemory},get workspaceStore(){return e.workspaceStore},get mcpManager(){return e.mcpManager},get fastModeController(){return e.fastModeController},getSharedReadRoots:()=>e.grants.readRoots,getSharedWriteRoots:()=>e.grants.writeRoots,getCurrentCwd:()=>e.grants.currentCwd,setCurrentCwd:n=>{e.grants.currentCwd=n},getCurrentPermissionMode:()=>e.grants.permissionMode,setCurrentPermissionMode:n=>{e.grants.permissionMode=n},getMintedSessionId:()=>e._mintedSessionId,setMintedSessionId:n=>{e._mintedSessionId=n},getPresenceSessionId:()=>e._presenceSessionId,setPresenceSessionId:n=>{e._presenceSessionId=n},ensureSharedRoots:n=>{e.grants.ensureInitialized(n)},buildDispatcher:(n,r)=>e.buildDispatcher(n,r)}}query(e){let n=this.queryContext(),r=JN(n,e,zS,VU);return zU(n,e,r)}},YU=new De});var ef=h(()=>{"use strict";QU();XS()});import{chmodSync as Hte,existsSync as Wte,mkdirSync as Kte,readFileSync as qte,unlinkSync as Gte,writeFileSync as Xte}from"node:fs";import{dirname as zte,join as Jte}from"node:path";function Ls(){return Jte(te(),"xai","auth.json")}function Vte(t){try{return qte(t,"utf-8")}catch{return null}}function Yte(t,e,n){Xte(t,e,{encoding:"utf-8",mode:n})}function Qte(t,e){Hte(t,e)}function Zte(t){Kte(t,{recursive:!0})}function ene(t){try{Gte(t)}catch{}}function tne(t){let e;try{e=JSON.parse(t)}catch{return null}if(typeof e!="object"||e===null)return null;let n=e,r=n.access_token,o=n.refresh_token,s=n.expires_at;if(typeof r!="string"||r.length===0||typeof o!="string"||o.length===0||typeof s!="number"||!Number.isFinite(s))return null;let i={access_token:r,refresh_token:o,expires_at:s};return typeof n.token_type=="string"&&(i.token_type=n.token_type),typeof n.scope=="string"&&(i.scope=n.scope),i}function Ns(t={}){let e=(t.authPath??Ls)(),r=(t.readFile??Vte)(e);return r===null?null:tne(r)}function JS(t,e={}){let n=(e.authPath??Ls)(),r=e.mkdir??Zte,o=e.writeFile??Yte,s=e.chmod??Qte;r(zte(n));let i={access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at};t.token_type!==void 0&&(i.token_type=t.token_type),t.scope!==void 0&&(i.scope=t.scope),o(n,`${JSON.stringify(i,null,2)}
|
|
1420
|
-
`,384),s(n,384)}function VS(t={}){let e=(t.authPath??Ls)(),n=t.exists??(o=>Wte(o)),r=t.unlink??ene;n(e)&&r(e)}function If(t){return t.length<=4?t:t.slice(-4)}var Cf=h(()=>{"use strict";B()});import{readFileSync as nne}from"node:fs";import{homedir as rne}from"node:os";import{join as one}from"node:path";function QS(t){let e=t?.trim();return e&&ine.test(e)?e:void 0}function ane(t,e){if(!t)return;let n=l=>l.split(".").map(Number),[r=0,o=0,s=0]=n(t),[i=0,a=0,c=0]=n(e);return r!==i?r>i?t:void 0:o!==a?o>a?t:void 0:s>=c?t:void 0}function cne(t={}){let e=t.readFile??(r=>nne(r,"utf-8")),n=t.homeDir??rne;try{let r=e(one(n(),".grok","version.json")),o=JSON.parse(r);if(typeof o!="object"||o===null)return;let s=o.version;return typeof s!="string"?void 0:QS(s)}catch{return}}function lne(t,e){let n=e.readEnv??(r=>k[r]);return QS(n(sne))??QS(t)??ane(cne(e),ZU)??ZU}function ZS(t){try{let e=new URL(t).hostname.toLowerCase();return e===YS||e.endsWith(`.${YS}`)}catch{return t.toLowerCase().includes(YS)}}function ek(t={},e={}){let n=lne(t.clientVersion,e),r=t.clientIdentifier?.trim()||"grok-shell";return{"X-XAI-Token-Auth":"xai-grok-cli","x-grok-client-version":n,"x-grok-client-identifier":r,"User-Agent":`agent-afk (grok-cli-compat/${n})`}}var YS,ZU,sne,ine,eB=h(()=>{"use strict";F();YS="cli-chat-proxy.grok.com",ZU="1.0.5",sne="AFK_XAI_GROK_CLIENT_VERSION",ine=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/});function dne(t){if(t==="AFK_XAI_BASE_URL")return k.AFK_XAI_BASE_URL;if(t==="AFK_XAI_OAUTH_BASE_URL")return k.AFK_XAI_OAUTH_BASE_URL}function Us(t,e={}){let n=e.readEnv??dne,r=e.baseUrlOverride?.trim();if(r){let c=tk(r),l=ZS(c);return{baseURL:c,defaultHeaders:l?ek({clientVersion:e.clientVersion},e.headerDeps):{},mode:t,proxyHeadersApplied:l}}if(t==="apikey"){let c=n("AFK_XAI_BASE_URL"),l=c&&c.trim()||sc;return{baseURL:tk(l),defaultHeaders:{},mode:t,proxyHeadersApplied:!1}}let o=n("AFK_XAI_OAUTH_BASE_URL"),s=tk(o&&o.trim()||$s),i=ZS(s),a=i?ek({clientVersion:e.clientVersion},e.headerDeps):{};return{baseURL:s,defaultHeaders:a,mode:t,proxyHeadersApplied:i}}function tk(t){return t.endsWith("/")?t.slice(0,-1):t}var sc,$s,ic=h(()=>{"use strict";F();eB();sc="https://api.x.ai/v1",$s="https://cli-chat-proxy.grok.com/v1"});function une(t){if(t==="XAI_API_KEY")return k.XAI_API_KEY}function pne(t,e){if(t&&t.length>0)return{key:t,source:"config"};let n=e("XAI_API_KEY");return n&&n.length>0?{key:n,source:"env"}:null}function fne(t){let e=Ns(t.store??{});return e?{bundle:e,last4:If(e.access_token)}:null}function St(t,e=void 0,n={}){let r=n.readEnv??une,o=pne(t,r),s=fne(n);return e==="oauth"?s?{apiKey:s.bundle.access_token,source:"xai-oauth",mode:"oauth",last4:s.last4,expiresAt:s.bundle.expires_at}:{apiKey:null,source:"no-usable-auth-forced-xai-oauth",mode:"oauth"}:e==="apikey"?o?{apiKey:o.key,source:o.source,mode:"apikey",last4:If(o.key),...o.source==="env"?{envVar:"XAI_API_KEY"}:{}}:{apiKey:null,source:"no-usable-auth-forced-xai-apikey",mode:"apikey"}:o&&s?{apiKey:null,source:"ambiguous-auth"}:o?{apiKey:o.key,source:o.source,mode:"apikey",last4:If(o.key),...o.source==="env"?{envVar:"XAI_API_KEY"}:{}}:s?{apiKey:s.bundle.access_token,source:"xai-oauth",mode:"oauth",last4:s.last4,expiresAt:s.bundle.expires_at}:{apiKey:null,source:"no-usable-auth"}}function mne(t,e){if(typeof t!="number")return"";let n=(e??(()=>Math.floor(Date.now()/1e3)))(),r=t-n;if(r<=0)return", EXPIRED \u2014 re-run `afk provider auth xai login`";let o=Math.floor(r/3600),s=Math.floor(r%3600/60);return`, expires in ${o>0?`${o}h `:""}${s}m`}function Bs(t,e={}){switch(t.source){case"config":return`using explicit AFK config xAI API key (\u2026${t.last4??"????"})`;case"env":return`using XAI_API_KEY env var (\u2026${t.last4??"????"})`;case"xai-oauth":{let n=mne(t.expiresAt,e.nowSeconds);return`using SuperGrok / SuperGrok Heavy / X Premium+ OAuth (\u2026${t.last4??"????"}${n})`}case"no-usable-auth-forced-xai-oauth":return"This model's slot/provider is `xai-oauth` but no SuperGrok OAuth tokens were found. Run `afk provider auth xai login` (device-code by default), or switch to `xai` with XAI_API_KEY.";case"no-usable-auth-forced-xai-apikey":return"This model's slot/provider is `xai` (API-key mode) but no XAI_API_KEY / config key was found. Set XAI_API_KEY, or use `xai-oauth` after `afk provider auth xai login`.";case"ambiguous-auth":return"Both XAI_API_KEY and SuperGrok OAuth tokens are present. Choose explicitly: `--provider xai` (API key \u2192 "+sc+") or `--provider xai-oauth` (subscription OAuth \u2192 "+$s+").";default:return"No xAI auth found. Set XAI_API_KEY for metered API access, or run `afk provider auth xai login` for SuperGrok / SuperGrok Heavy / X Premium+."}}function nk(t,e){let n=e.baseURL??(e.mode==="oauth"?$s:sc),r=(e.bodySnippet??"").slice(0,180);return t===402?`xAI returned HTTP 402 on ${n}`+(r?` (${r})`:"")+". This is usually a subscription/spend gate (e.g. personal-team-blocked), not a missing login. Check SuperGrok / SuperGrok Heavy / X Premium+ status, try the other endpoint via AFK_XAI_OAUTH_BASE_URL or AFK_XAI_BASE_URL, or use a metered XAI_API_KEY with `--provider xai`.":t===403?`xAI returned HTTP 403 on ${n}`+(r?` (${r})`:"")+`. After SuperGrok OAuth login this often means the account lacks OAuth API entitlement, the model requires SuperGrok Heavy, or traffic hit api.x.ai instead of the CLI chat proxy. Try AFK_XAI_OAUTH_BASE_URL=${$s} (default for xai-oauth), or fall back to XAI_API_KEY with \`--provider xai\`.`:`xAI returned HTTP ${t} on ${n}`+(r?`: ${r}`:"")}var co=h(()=>{"use strict";F();Cf();ic()});function Pf(t,e,n){if(e===!0)return"oauth";if(n===!0)return"apikey";if(t==="apikey"||t==="oauth")return t}function rk(t,e){return e!==void 0?e:Pf(t,void 0,void 0)}function ac(t,e){if(t==="xai-oauth")return"oauth";if(e)return"apikey"}var js=h(()=>{"use strict"});var ok,Mf,gne,yWe,hne,yne,Of,cc=h(()=>{"use strict";ok="https://auth.x.ai",Mf="b1a00492-073a-47ea-816f-4c329264a828",gne="openid profile email offline_access grok-cli:access api:access",yWe=`${gne} conversations:read conversations:write`,hne=56121,yne=`http://127.0.0.1:${hne}/callback`,Of=180});function kt(t){return typeof t=="string"&&t.length>0?t:void 0}async function Ff(t={}){let e=t.fetchFn??fetch,n=(t.issuer??ok).replace(/\/$/,""),r=`${n}/.well-known/openid-configuration`,o=await e(r,{method:"GET"});if(!o.ok)throw new Error(`xAI OIDC discovery failed: HTTP ${o.status} from ${r}`);let s=await o.json(),i=kt(s.authorization_endpoint),a=kt(s.token_endpoint);if(!i||!a)throw new Error("xAI OIDC discovery missing authorization_endpoint or token_endpoint");let c=new URL(n).origin,l=kt(s.issuer);if(l){let m;try{m=new URL(l).origin}catch{throw new Error("xAI OIDC discovery: body issuer origin does not match configured issuer")}if(m!==c)throw new Error("xAI OIDC discovery: body issuer origin does not match configured issuer")}let d=l??n;if(new URL(i).origin!==c)throw new Error("xAI OIDC discovery: authorization_endpoint origin does not match issuer");if(new URL(a).origin!==c)throw new Error("xAI OIDC discovery: token_endpoint origin does not match issuer");let u={issuer:d,authorization_endpoint:i,token_endpoint:a},p=kt(s.device_authorization_endpoint);if(p){if(new URL(p).origin!==c)throw new Error("xAI OIDC discovery: device_authorization_endpoint origin does not match issuer");u.device_authorization_endpoint=p}let f=kt(s.userinfo_endpoint);if(f){if(new URL(f).origin!==c)throw new Error("xAI OIDC discovery: userinfo_endpoint origin does not match issuer");u.userinfo_endpoint=f}return u}async function Lf(t={}){let n=(t.nowMs??(()=>Date.now()))();if(Df&&Df.expiresAt>n)return Df.result;let r=await Ff(t);return Df={result:r,expiresAt:n+bne},r}function lc(t,e,n){let r=kt(t.access_token);if(!r)return null;let o=kt(t.refresh_token)??n;if(!o)return null;let s=(e??(()=>Math.floor(Date.now()/1e3)))(),i=typeof t.expires_in=="number"?t.expires_in:3600,a=Math.min(Math.max(i,Of+60),86400),c={access_token:r,refresh_token:o,expires_at:s+a};return typeof t.token_type=="string"&&(c.token_type=t.token_type),typeof t.scope=="string"&&(c.scope=t.scope),c}var bne,Df,dc=h(()=>{"use strict";cc();bne=1440*60*1e3,Df=null});var tB=h(()=>{"use strict";cc();dc()});var nB=h(()=>{"use strict";cc();dc()});function xne(t){return t?.authPath?t.authPath():Ls()}async function rB(t,e={}){let n=await Lf(e),r=e.fetchFn??fetch,o=e.clientId??Mf,s=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:o}),i=await r(n.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:s.toString()}),a=await i.json().catch(()=>({}));if(!i.ok){let l=kt(a.error)??`http_${i.status}`,d=kt(a.error_description);throw new Error(`xAI token refresh failed: ${d?`${l}: ${d}`:l}`)}let c=lc(a,e.nowSeconds,t);if(!c)throw new Error("xAI refresh response missing access_token");return e.persist!==!1&&JS(c,e.store??{}),c}async function uc(t={}){let e=t.store??{},n=Ns(e);if(!n)return null;let r=(t.nowSeconds??(()=>Math.floor(Date.now()/1e3)))(),o=t.skewSeconds??Of;if(n.expires_at-o>r)return n;let s=xne(e),i=sk.get(s);if(i)try{return await i}catch{return Ns(e)}let a=(async()=>{try{return await rB(n.refresh_token,{...t,store:e,persist:!0})}catch(c){throw n.expires_at<=r&&VS(e),c}finally{sk.delete(s)}})();sk.set(s,a);try{return await a}catch{return n.expires_at>r?n:null}}var sk,Nf=h(()=>{"use strict";cc();Cf();dc();dc();tB();nB();sk=new Map});function $f(t){return typeof t!="number"?!1:t<=Math.floor(Date.now()/1e3)}function ik(t,e){let n=Jn(t);if(n!==402&&n!==403)return t instanceof Error?t:new Error(String(t));let r=t instanceof Error?t.message:typeof t=="string"?t:void 0,o=Us(e);return new Error(nk(n,{mode:e,baseURL:o.baseURL,...r!==void 0?{bodySnippet:r}:{}}))}function oB(t){return{async*[Symbol.asyncIterator](){yield{type:"error",error:new Error(t)}},async interrupt(){},async setModel(){},async setPermissionMode(){},async supportedCommands(){return[]},async supportedModels(){return[]},async supportedAgents(){return[]},async getContextUsage(){return{}},async mcpServerStatus(){return[]},async accountInfo(){return{}},async rewindFiles(){return{canRewind:!1,error:t}},async close(){}}}var ak=h(()=>{"use strict";co();ic();fs()});function sB(t,e){return t==="oauth"||t==="apikey"?t:e()}function iB(t){let{args:e,forceMode:n,authDeps:r,getLastMode:o,delegate:s}=t,i,a,c,l,d,u=async()=>{if(a)throw a;return i||c||(c=(async()=>{try{n!=="apikey"&&await uc({store:r.store});let p=St(e.config.apiKey,n,r);if(p.apiKey===null||!p.mode)throw new Error(Bs(p));if(p.mode==="oauth"&&$f(p.expiresAt))throw new Error("SuperGrok OAuth access token expired and refresh failed. Re-run `afk provider auth xai login`.");return i=s(e,p.apiKey,p.mode),l!==void 0&&i.setCwd?.(l),d!==void 0&&i.setSystemPrompt?.(d===null?void 0:d),i}catch(p){throw a=p instanceof Error?p:new Error(String(p)),a}finally{c=void 0}})(),c)};return{async*[Symbol.asyncIterator](){try{let p=await u();for await(let f of p)f.type==="error"?yield{type:"error",error:ik(f.error,sB(n,o))}:yield f}catch(p){let f=p instanceof Error?p:new Error(String(p));yield{type:"error",error:ik(f,sB(n,o))}}},async interrupt(p){await(i??await u().catch(()=>{}))?.interrupt(p)},async setModel(p){await(i??await u().catch(()=>{}))?.setModel(p)},async setPermissionMode(p){await(i??await u().catch(()=>{}))?.setPermissionMode(p)},setCwd(p){l=p,i?.setCwd?.(p)},setSystemPrompt(p){return d=p===void 0?null:p,i?.setSystemPrompt?.(p)??!1},async reauth(){return await(i??await u().catch(()=>{}))?.reauth?.()??null},async supportedCommands(){return await(i??await u().catch(()=>{}))?.supportedCommands()??[]},async supportedModels(){return await(i??await u().catch(()=>{}))?.supportedModels()??[]},async supportedAgents(){return await(i??await u().catch(()=>{}))?.supportedAgents()??[]},async getContextUsage(){return await(i??await u().catch(()=>{}))?.getContextUsage()??{}},async mcpServerStatus(){return await(i??await u().catch(()=>{}))?.mcpServerStatus()??[]},async accountInfo(){return await(i??await u().catch(()=>{}))?.accountInfo()??{}},async rewindFiles(p,f){let m=i??await u().catch(()=>{});return m?m.rewindFiles(p,f):{canRewind:!1,error:"xAI provider not initialized"}},async compact(){let p=i??await u().catch(()=>{});return p?.compact?p.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}},listRewindTargets(){return i?.listRewindTargets?.()??[]},async rewindConversation(p){let f=i??await u().catch(()=>{});return f?.rewindConversation?f.rewindConversation(p):{rewound:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}},async close(){await i?.close()}}}var aB=h(()=>{"use strict";co();Nf();ak()});var Rne,nr,pc=h(()=>{"use strict";gs();co();js();ic();Nf();aB();ak();js();co();ic();Cf();Nf();Yu();Rne="xai",nr=class{name=Rne;inner;authMode;authDeps;lastMode="apikey";lastResolvedMode;lastXaiBaseUrl;constructor(e={}){let{authMode:n,authDeps:r,...o}=e;this.authMode=n,this.authDeps=r??{},this.inner=new xe(o)}query(e){let n=Pf(this.authMode,e.config.forceXaiOAuth,e.config.forceXaiApiKey);return n==="oauth"||n===void 0?iB({args:e,forceMode:n,authDeps:this.authDeps,getLastMode:()=>this.lastMode,delegate:(r,o,s)=>this.delegateToInner(r,o,s)}):this.querySync(e,n)}querySync(e,n){let r=St(e.config.apiKey,n,this.authDeps);return r.apiKey===null||!r.mode?oB(Bs(r)):this.delegateToInner(e,r.apiKey,r.mode)}delegateToInner(e,n,r){this.rememberResolved(r,e.config.xaiBaseUrl);let o=Us(r,{readEnv:this.authDeps.readEnv?i=>this.authDeps.readEnv(i):void 0,...e.config.xaiBaseUrl!==void 0?{baseUrlOverride:e.config.xaiBaseUrl}:{}});this.inner.setEndpointDefaults({baseURL:o.baseURL,defaultHeaders:o.defaultHeaders});let s={...e.config,apiKey:n,openaiBaseUrl:o.baseURL,forceChatgptOAuth:!1,forceXaiOAuth:r==="oauth",forceXaiApiKey:r==="apikey"};return this.inner.query({...e,config:s})}rememberResolved(e,n){this.lastMode=e,this.lastResolvedMode=e,this.lastXaiBaseUrl=n}addReadRoot(e,n="slash",r){this.inner.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.inner.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.inner.revokeRoot(e,n,r)}getGrants(){return this.inner.getGrants()}close(){this.inner.close()}async complete(e){let n=rk(this.authMode,this.lastResolvedMode);(n==="oauth"||n===void 0)&&await uc({store:this.authDeps.store});let r=St(e.apiKey,n,this.authDeps);if(r.apiKey===null||!r.mode)throw new Error(Bs(r));if(r.mode==="oauth"&&$f(r.expiresAt))throw new Error("SuperGrok OAuth access token expired and refresh failed. Re-run `afk provider auth xai login`.");this.rememberResolved(r.mode,this.lastXaiBaseUrl);let o=Us(r.mode,{readEnv:this.authDeps.readEnv,...this.lastXaiBaseUrl!==void 0?{baseUrlOverride:this.lastXaiBaseUrl}:{}});return this.inner.setEndpointDefaults({baseURL:o.baseURL,defaultHeaders:o.defaultHeaders}),this.inner.complete({...e,apiKey:r.apiKey,baseUrl:o.baseURL})}}});function Cne(t){if(!t)return;let e=t.trim().toLowerCase();if(e){if(e==="anthropic"||e==="anthropic-direct")return"anthropic-direct";if(e==="openai"||e==="openai-compatible"||e==="openai-codex")return"openai-compatible";if(e==="xai")return"xai";if(e==="xai-oauth"||e==="xai_oauth")return"xai-oauth"}}function z(t,e){let n=e?.explicit??k.AFK_PROVIDER,r=e?.openaiBaseUrl??k.AFK_OPENAI_BASE_URL,o=Cne(n);if(o)return o;let s=gr(t,e?.slots);if(s.provider==="anthropic")return"anthropic-direct";if(s.provider==="openai"||s.provider==="chatgpt-oauth")return"openai-compatible";if(s.provider==="xai")return"xai";if(s.provider==="xai-oauth")return"xai-oauth";let i=s.id.trim().toLowerCase();return i&&(Ine.has(i)||i.startsWith("claude-")||i.startsWith("claude_")||i.startsWith("local-")||i.startsWith("local_"))?"anthropic-direct":i&&(i.startsWith("grok-")||i.startsWith("grok_")||i==="grok")?"xai":i&&(i.startsWith("gpt-")||i.startsWith("gpt_")||hr(i)||i.startsWith("codex-")||i.startsWith("codex_")||i==="codex"||i.startsWith("deepseek-")||i.startsWith("deepseek_")||i.startsWith("mistral-")||i.startsWith("mistral_")||i.startsWith("mixtral-")||i.startsWith("mixtral_")||i.startsWith("llama-")||i.startsWith("llama_")||i.startsWith("qwen-")||i.startsWith("qwen_")||i.includes("/"))||s.baseUrl&&s.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function U0(t,e,n){let r=z(t,e),o=n?.customTools,s=n?.canUseTool,i={...o!==void 0&&o.length>0?{customTools:o}:{},...s!==void 0?{canUseTool:s}:{}};switch(r){case"openai-compatible":case"openai-codex":return new xe(i);case"xai":case"xai-oauth":{let a=(e?.explicit??k.AFK_PROVIDER)?.trim().toLowerCase()??"",d=ac(r==="xai-oauth"||a==="xai-oauth"||a==="xai_oauth"?"xai-oauth":"xai",a==="xai"||a==="xai-oauth"||a==="xai_oauth"||r==="xai-oauth");return new nr({...i,...d!==void 0?{authMode:d}:{}})}default:return new De(i)}}var Ine,fe=h(()=>{"use strict";ef();gs();pc();js();lt();Fe();yr();F();ef();gs();pc();Ine=new Set([...Object.keys(mg),"auto"])});import{mkdir as Zre,readdir as jqe,readFile as eoe,rename as toe,rm as noe,stat as roe,unlink as dj,writeFile as vk}from"node:fs/promises";import{join as Qf}from"node:path";import{randomBytes as ooe}from"node:crypto";async function uj(t){await Zre(t,{recursive:!0,mode:448})}function Tk(t,e){return Qf(t,`${e}.json`)}function soe(t,e){return Qf(t,`${e}.lock`)}async function pj(t,e){let n=Qf(t,".."),r=Qf(n,`.tmp-${ooe(4).toString("hex")}.json`);try{await vk(r,JSON.stringify(e),{encoding:"utf-8",mode:384}),await toe(r,t)}catch(o){try{await noe(r,{force:!0})}catch{}throw o}}async function Ek(t,e=yo()){cr(t.taskId),await uj(e),await pj(Tk(e,t.taskId),t)}async function wc(t,e=yo()){cr(t);let n=Tk(e,t);try{let r=await eoe(n,"utf-8");return JSON.parse(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function _k(t,e,n){let r=soe(e,t);try{await vk(r,"",{flag:"wx",mode:384})}catch(o){if(o.code==="EEXIST"){let s;try{s=(await roe(r)).mtimeMs}catch{return null}if(Date.now()-s<=ioe)return null;try{await dj(r)}catch{}try{await vk(r,"",{flag:"wx",mode:384})}catch(i){if(i.code==="EEXIST")return null;throw i}}else throw o}try{return await n()}finally{try{await dj(r)}catch{}}}async function fj(t,e,n,r=yo()){return cr(t),await uj(r),await _k(t,r,async()=>{let s=await wc(t,r);if(s===null)throw new Error(`handoff-store: no record found for taskId ${t}`);if(s.status!=="pending")return{won:!1};let i={...s,status:"answered",answer:e,answeredAt:new Date().toISOString(),answerSource:n};return await pj(Tk(r,t),i),{won:!0}})??{won:!1}}var ioe,Ak=h(()=>{"use strict";B();ioe=3e4});var Gqe,aoe,mj=h(()=>{"use strict";Gqe=300*1e3,aoe=600*1e3});var gj=h(()=>{"use strict";B();F();mj()});function em(t,e){if(!Zf.test(t))throw new Error(`buildElicitationCallback: invalid id ${JSON.stringify(t)}`);if(!Number.isInteger(e)||e<0)throw new Error(`buildElicitationCallback: choiceIndex must be a non-negative integer, got ${e}`);let n=`${Sc}${e}:${t}`,r=Buffer.byteLength(n,"utf8");if(r>64)throw new Error(`buildElicitationCallback: payload ${r} bytes exceeds Telegram's 64-byte limit (id=${t})`);return n}function hj(t){if(!t||!t.startsWith(Sc)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(Sc.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1),s=parseInt(r,10);return!Number.isInteger(s)||s<0||String(s)!==r||!Zf.test(o)?null:{id:o,choiceIndex:s}}function yj(t){if(!Zf.test(t))throw new Error(`buildCustomElicitationCallback: invalid id ${JSON.stringify(t)}`);let e=`${kc}${t}`,n=Buffer.byteLength(e,"utf8");if(n>64)throw new Error(`buildCustomElicitationCallback: ${n} bytes exceeds 64-byte limit`);return e}function bj(t){if(!t||!t.startsWith(kc)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(kc.length);return Zf.test(e)?e:null}var Sc,Zf,kc,xk=h(()=>{"use strict";Sc="afk:e:",Zf=/^[a-zA-Z0-9_-]{1,48}$/;kc="afk:ec:"});function Tc(t,e){if(!wj.test(t))throw new Error(`buildHandoffCallback: invalid taskId ${JSON.stringify(t)}`);if(!Number.isInteger(e)||e<0)throw new Error(`buildHandoffCallback: choiceIndex must be non-negative integer, got ${e}`);let n=`${vc}${e}:${t}`,r=Buffer.byteLength(n,"utf8");if(r>64)throw new Error(`buildHandoffCallback: payload ${r} bytes exceeds Telegram's ${64}-byte limit`);return n}function Sj(t){if(!t||!t.startsWith(vc)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(vc.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1),s=parseInt(r,10);return!Number.isInteger(s)||s<0||String(s)!==r||!wj.test(o)?null:{taskId:o,choiceIndex:s}}var vc,wj,Ik=h(()=>{"use strict";xk();vc="afk:h:",wj=/^[A-Za-z0-9_-]{1,128}$/});async function Ck(t,e,n,r){let o=JSON.stringify(e);if(Buffer.byteLength(o,"utf-8")>kj)throw new Error(`[handoff-wiring] answer for task ${t} exceeds ${kj} bytes \u2014 rejected`);return(await fj(t,e,n,r)).won}var uGe,kj,vj=h(()=>{"use strict";Ak();gj();Dr();tm();Ik();uGe=1440*60*1e3,kj=64*1024});var Mk={};mo(Mk,{clearPendingTextHandoff:()=>Ej,matchReplyToHandoff:()=>doe,registerHandoffAnswerHandlers:()=>loe,sendHandoffQuestion:()=>Tj});import{Markup as Ec}from"telegraf";function Aj(t){return t.length<=_j?t:`${t.slice(0,_j)}...(truncated)`}function coe(t,e=64){if(Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.from(t,"utf8").subarray(0,e);return new TextDecoder("utf-8",{fatal:!1}).decode(n).replace(/\uFFFD$/,"")}async function Tj(t){let{bot:e,record:n,chatId:r,threadId:o,handoffsDir:s}=t,i=o?{message_thread_id:o}:{},a=n.question,c=a.type??"text",l=typeof a.message=="string"?a.message:"(question details unavailable)",d=typeof a.context=="string"?a.context:void 0,u=Array.isArray(a.choices)?a.choices:[],p=`\u{1F514} <b>Daemon task needs your answer</b>
|
|
1420
|
+
`,384),s(n,384)}function VS(t={}){let e=(t.authPath??Ls)(),n=t.exists??(o=>Wte(o)),r=t.unlink??ene;n(e)&&r(e)}function If(t){return t.length<=4?t:t.slice(-4)}var Cf=h(()=>{"use strict";B()});import{readFileSync as nne}from"node:fs";import{homedir as rne}from"node:os";import{join as one}from"node:path";function QS(t){let e=t?.trim();return e&&ine.test(e)?e:void 0}function ane(t,e){if(!t)return;let n=l=>l.split(".").map(Number),[r=0,o=0,s=0]=n(t),[i=0,a=0,c=0]=n(e);return r!==i?r>i?t:void 0:o!==a?o>a?t:void 0:s>=c?t:void 0}function cne(t={}){let e=t.readFile??(r=>nne(r,"utf-8")),n=t.homeDir??rne;try{let r=e(one(n(),".grok","version.json")),o=JSON.parse(r);if(typeof o!="object"||o===null)return;let s=o.version;return typeof s!="string"?void 0:QS(s)}catch{return}}function lne(t,e){let n=e.readEnv??(r=>k[r]);return QS(n(sne))??QS(t)??ane(cne(e),ZU)??ZU}function ZS(t){try{let e=new URL(t).hostname.toLowerCase();return e===YS||e.endsWith(`.${YS}`)}catch{return t.toLowerCase().includes(YS)}}function ek(t={},e={}){let n=lne(t.clientVersion,e),r=t.clientIdentifier?.trim()||"grok-shell";return{"X-XAI-Token-Auth":"xai-grok-cli","x-grok-client-version":n,"x-grok-client-identifier":r,"User-Agent":`agent-afk (grok-cli-compat/${n})`}}var YS,ZU,sne,ine,eB=h(()=>{"use strict";F();YS="cli-chat-proxy.grok.com",ZU="1.0.5",sne="AFK_XAI_GROK_CLIENT_VERSION",ine=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/});function dne(t){if(t==="AFK_XAI_BASE_URL")return k.AFK_XAI_BASE_URL;if(t==="AFK_XAI_OAUTH_BASE_URL")return k.AFK_XAI_OAUTH_BASE_URL}function Us(t,e={}){let n=e.readEnv??dne,r=e.baseUrlOverride?.trim();if(r){let c=tk(r),l=ZS(c);return{baseURL:c,defaultHeaders:l?ek({clientVersion:e.clientVersion},e.headerDeps):{},mode:t,proxyHeadersApplied:l}}if(t==="apikey"){let c=n("AFK_XAI_BASE_URL"),l=c&&c.trim()||sc;return{baseURL:tk(l),defaultHeaders:{},mode:t,proxyHeadersApplied:!1}}let o=n("AFK_XAI_OAUTH_BASE_URL"),s=tk(o&&o.trim()||$s),i=ZS(s),a=i?ek({clientVersion:e.clientVersion},e.headerDeps):{};return{baseURL:s,defaultHeaders:a,mode:t,proxyHeadersApplied:i}}function tk(t){return t.endsWith("/")?t.slice(0,-1):t}var sc,$s,ic=h(()=>{"use strict";F();eB();sc="https://api.x.ai/v1",$s="https://cli-chat-proxy.grok.com/v1"});function une(t){if(t==="XAI_API_KEY")return k.XAI_API_KEY}function pne(t,e){if(t&&t.length>0)return{key:t,source:"config"};let n=e("XAI_API_KEY");return n&&n.length>0?{key:n,source:"env"}:null}function fne(t){let e=Ns(t.store??{});return e?{bundle:e,last4:If(e.access_token)}:null}function St(t,e=void 0,n={}){let r=n.readEnv??une,o=pne(t,r),s=fne(n);return e==="oauth"?s?{apiKey:s.bundle.access_token,source:"xai-oauth",mode:"oauth",last4:s.last4,expiresAt:s.bundle.expires_at}:{apiKey:null,source:"no-usable-auth-forced-xai-oauth",mode:"oauth"}:e==="apikey"?o?{apiKey:o.key,source:o.source,mode:"apikey",last4:If(o.key),...o.source==="env"?{envVar:"XAI_API_KEY"}:{}}:{apiKey:null,source:"no-usable-auth-forced-xai-apikey",mode:"apikey"}:o&&s?{apiKey:null,source:"ambiguous-auth"}:o?{apiKey:o.key,source:o.source,mode:"apikey",last4:If(o.key),...o.source==="env"?{envVar:"XAI_API_KEY"}:{}}:s?{apiKey:s.bundle.access_token,source:"xai-oauth",mode:"oauth",last4:s.last4,expiresAt:s.bundle.expires_at}:{apiKey:null,source:"no-usable-auth"}}function mne(t,e){if(typeof t!="number")return"";let n=(e??(()=>Math.floor(Date.now()/1e3)))(),r=t-n;if(r<=0)return", EXPIRED \u2014 re-run `afk provider auth xai login`";let o=Math.floor(r/3600),s=Math.floor(r%3600/60);return`, expires in ${o>0?`${o}h `:""}${s}m`}function Bs(t,e={}){switch(t.source){case"config":return`using explicit AFK config xAI API key (\u2026${t.last4??"????"})`;case"env":return`using XAI_API_KEY env var (\u2026${t.last4??"????"})`;case"xai-oauth":{let n=mne(t.expiresAt,e.nowSeconds);return`using SuperGrok / SuperGrok Heavy / X Premium+ OAuth (\u2026${t.last4??"????"}${n})`}case"no-usable-auth-forced-xai-oauth":return"This model's slot/provider is `xai-oauth` but no SuperGrok OAuth tokens were found. Run `afk provider auth xai login` (device-code by default), or switch to `xai` with XAI_API_KEY.";case"no-usable-auth-forced-xai-apikey":return"This model's slot/provider is `xai` (API-key mode) but no XAI_API_KEY / config key was found. Set XAI_API_KEY, or use `xai-oauth` after `afk provider auth xai login`.";case"ambiguous-auth":return"Both XAI_API_KEY and SuperGrok OAuth tokens are present. Choose explicitly: `--provider xai` (API key \u2192 "+sc+") or `--provider xai-oauth` (subscription OAuth \u2192 "+$s+").";default:return"No xAI auth found. Set XAI_API_KEY for metered API access, or run `afk provider auth xai login` for SuperGrok / SuperGrok Heavy / X Premium+."}}function nk(t,e){let n=e.baseURL??(e.mode==="oauth"?$s:sc),r=(e.bodySnippet??"").slice(0,180);return t===402?`xAI returned HTTP 402 on ${n}`+(r?` (${r})`:"")+". This is usually a subscription/spend gate (e.g. personal-team-blocked), not a missing login. Check SuperGrok / SuperGrok Heavy / X Premium+ status, try the other endpoint via AFK_XAI_OAUTH_BASE_URL or AFK_XAI_BASE_URL, or use a metered XAI_API_KEY with `--provider xai`.":t===403?`xAI returned HTTP 403 on ${n}`+(r?` (${r})`:"")+`. After SuperGrok OAuth login this often means the account lacks OAuth API entitlement, the model requires SuperGrok Heavy, or traffic hit api.x.ai instead of the CLI chat proxy. Try AFK_XAI_OAUTH_BASE_URL=${$s} (default for xai-oauth), or fall back to XAI_API_KEY with \`--provider xai\`.`:`xAI returned HTTP ${t} on ${n}`+(r?`: ${r}`:"")}var co=h(()=>{"use strict";F();Cf();ic()});function Pf(t,e,n){if(e===!0)return"oauth";if(n===!0)return"apikey";if(t==="apikey"||t==="oauth")return t}function rk(t,e){return e!==void 0?e:Pf(t,void 0,void 0)}function ac(t,e){if(t==="xai-oauth")return"oauth";if(e)return"apikey"}var js=h(()=>{"use strict"});var ok,Mf,gne,bWe,hne,yne,Of,cc=h(()=>{"use strict";ok="https://auth.x.ai",Mf="b1a00492-073a-47ea-816f-4c329264a828",gne="openid profile email offline_access grok-cli:access api:access",bWe=`${gne} conversations:read conversations:write`,hne=56121,yne=`http://127.0.0.1:${hne}/callback`,Of=180});function kt(t){return typeof t=="string"&&t.length>0?t:void 0}async function Ff(t={}){let e=t.fetchFn??fetch,n=(t.issuer??ok).replace(/\/$/,""),r=`${n}/.well-known/openid-configuration`,o=await e(r,{method:"GET"});if(!o.ok)throw new Error(`xAI OIDC discovery failed: HTTP ${o.status} from ${r}`);let s=await o.json(),i=kt(s.authorization_endpoint),a=kt(s.token_endpoint);if(!i||!a)throw new Error("xAI OIDC discovery missing authorization_endpoint or token_endpoint");let c=new URL(n).origin,l=kt(s.issuer);if(l){let m;try{m=new URL(l).origin}catch{throw new Error("xAI OIDC discovery: body issuer origin does not match configured issuer")}if(m!==c)throw new Error("xAI OIDC discovery: body issuer origin does not match configured issuer")}let d=l??n;if(new URL(i).origin!==c)throw new Error("xAI OIDC discovery: authorization_endpoint origin does not match issuer");if(new URL(a).origin!==c)throw new Error("xAI OIDC discovery: token_endpoint origin does not match issuer");let u={issuer:d,authorization_endpoint:i,token_endpoint:a},p=kt(s.device_authorization_endpoint);if(p){if(new URL(p).origin!==c)throw new Error("xAI OIDC discovery: device_authorization_endpoint origin does not match issuer");u.device_authorization_endpoint=p}let f=kt(s.userinfo_endpoint);if(f){if(new URL(f).origin!==c)throw new Error("xAI OIDC discovery: userinfo_endpoint origin does not match issuer");u.userinfo_endpoint=f}return u}async function Lf(t={}){let n=(t.nowMs??(()=>Date.now()))();if(Df&&Df.expiresAt>n)return Df.result;let r=await Ff(t);return Df={result:r,expiresAt:n+bne},r}function lc(t,e,n){let r=kt(t.access_token);if(!r)return null;let o=kt(t.refresh_token)??n;if(!o)return null;let s=(e??(()=>Math.floor(Date.now()/1e3)))(),i=typeof t.expires_in=="number"?t.expires_in:3600,a=Math.min(Math.max(i,Of+60),86400),c={access_token:r,refresh_token:o,expires_at:s+a};return typeof t.token_type=="string"&&(c.token_type=t.token_type),typeof t.scope=="string"&&(c.scope=t.scope),c}var bne,Df,dc=h(()=>{"use strict";cc();bne=1440*60*1e3,Df=null});var tB=h(()=>{"use strict";cc();dc()});var nB=h(()=>{"use strict";cc();dc()});function xne(t){return t?.authPath?t.authPath():Ls()}async function rB(t,e={}){let n=await Lf(e),r=e.fetchFn??fetch,o=e.clientId??Mf,s=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:o}),i=await r(n.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:s.toString()}),a=await i.json().catch(()=>({}));if(!i.ok){let l=kt(a.error)??`http_${i.status}`,d=kt(a.error_description);throw new Error(`xAI token refresh failed: ${d?`${l}: ${d}`:l}`)}let c=lc(a,e.nowSeconds,t);if(!c)throw new Error("xAI refresh response missing access_token");return e.persist!==!1&&JS(c,e.store??{}),c}async function uc(t={}){let e=t.store??{},n=Ns(e);if(!n)return null;let r=(t.nowSeconds??(()=>Math.floor(Date.now()/1e3)))(),o=t.skewSeconds??Of;if(n.expires_at-o>r)return n;let s=xne(e),i=sk.get(s);if(i)try{return await i}catch{return Ns(e)}let a=(async()=>{try{return await rB(n.refresh_token,{...t,store:e,persist:!0})}catch(c){throw n.expires_at<=r&&VS(e),c}finally{sk.delete(s)}})();sk.set(s,a);try{return await a}catch{return n.expires_at>r?n:null}}var sk,Nf=h(()=>{"use strict";cc();Cf();dc();dc();tB();nB();sk=new Map});function $f(t){return typeof t!="number"?!1:t<=Math.floor(Date.now()/1e3)}function ik(t,e){let n=Jn(t);if(n!==402&&n!==403)return t instanceof Error?t:new Error(String(t));let r=t instanceof Error?t.message:typeof t=="string"?t:void 0,o=Us(e);return new Error(nk(n,{mode:e,baseURL:o.baseURL,...r!==void 0?{bodySnippet:r}:{}}))}function oB(t){return{async*[Symbol.asyncIterator](){yield{type:"error",error:new Error(t)}},async interrupt(){},async setModel(){},async setPermissionMode(){},async supportedCommands(){return[]},async supportedModels(){return[]},async supportedAgents(){return[]},async getContextUsage(){return{}},async mcpServerStatus(){return[]},async accountInfo(){return{}},async rewindFiles(){return{canRewind:!1,error:t}},async close(){}}}var ak=h(()=>{"use strict";co();ic();fs()});function sB(t,e){return t==="oauth"||t==="apikey"?t:e()}function iB(t){let{args:e,forceMode:n,authDeps:r,getLastMode:o,delegate:s}=t,i,a,c,l,d,u=async()=>{if(a)throw a;return i||c||(c=(async()=>{try{n!=="apikey"&&await uc({store:r.store});let p=St(e.config.apiKey,n,r);if(p.apiKey===null||!p.mode)throw new Error(Bs(p));if(p.mode==="oauth"&&$f(p.expiresAt))throw new Error("SuperGrok OAuth access token expired and refresh failed. Re-run `afk provider auth xai login`.");return i=s(e,p.apiKey,p.mode),l!==void 0&&i.setCwd?.(l),d!==void 0&&i.setSystemPrompt?.(d===null?void 0:d),i}catch(p){throw a=p instanceof Error?p:new Error(String(p)),a}finally{c=void 0}})(),c)};return{async*[Symbol.asyncIterator](){try{let p=await u();for await(let f of p)f.type==="error"?yield{type:"error",error:ik(f.error,sB(n,o))}:yield f}catch(p){let f=p instanceof Error?p:new Error(String(p));yield{type:"error",error:ik(f,sB(n,o))}}},async interrupt(p){await(i??await u().catch(()=>{}))?.interrupt(p)},async setModel(p){await(i??await u().catch(()=>{}))?.setModel(p)},async setPermissionMode(p){await(i??await u().catch(()=>{}))?.setPermissionMode(p)},setCwd(p){l=p,i?.setCwd?.(p)},setSystemPrompt(p){return d=p===void 0?null:p,i?.setSystemPrompt?.(p)??!1},async reauth(){return await(i??await u().catch(()=>{}))?.reauth?.()??null},async supportedCommands(){return await(i??await u().catch(()=>{}))?.supportedCommands()??[]},async supportedModels(){return await(i??await u().catch(()=>{}))?.supportedModels()??[]},async supportedAgents(){return await(i??await u().catch(()=>{}))?.supportedAgents()??[]},async getContextUsage(){return await(i??await u().catch(()=>{}))?.getContextUsage()??{}},async mcpServerStatus(){return await(i??await u().catch(()=>{}))?.mcpServerStatus()??[]},async accountInfo(){return await(i??await u().catch(()=>{}))?.accountInfo()??{}},async rewindFiles(p,f){let m=i??await u().catch(()=>{});return m?m.rewindFiles(p,f):{canRewind:!1,error:"xAI provider not initialized"}},async compact(){let p=i??await u().catch(()=>{});return p?.compact?p.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}},listRewindTargets(){return i?.listRewindTargets?.()??[]},async rewindConversation(p){let f=i??await u().catch(()=>{});return f?.rewindConversation?f.rewindConversation(p):{rewound:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}},async close(){await i?.close()}}}var aB=h(()=>{"use strict";co();Nf();ak()});var Rne,nr,pc=h(()=>{"use strict";gs();co();js();ic();Nf();aB();ak();js();co();ic();Cf();Nf();Yu();Rne="xai",nr=class{name=Rne;inner;authMode;authDeps;lastMode="apikey";lastResolvedMode;lastXaiBaseUrl;constructor(e={}){let{authMode:n,authDeps:r,...o}=e;this.authMode=n,this.authDeps=r??{},this.inner=new xe(o)}query(e){let n=Pf(this.authMode,e.config.forceXaiOAuth,e.config.forceXaiApiKey);return n==="oauth"||n===void 0?iB({args:e,forceMode:n,authDeps:this.authDeps,getLastMode:()=>this.lastMode,delegate:(r,o,s)=>this.delegateToInner(r,o,s)}):this.querySync(e,n)}querySync(e,n){let r=St(e.config.apiKey,n,this.authDeps);return r.apiKey===null||!r.mode?oB(Bs(r)):this.delegateToInner(e,r.apiKey,r.mode)}delegateToInner(e,n,r){this.rememberResolved(r,e.config.xaiBaseUrl);let o=Us(r,{readEnv:this.authDeps.readEnv?i=>this.authDeps.readEnv(i):void 0,...e.config.xaiBaseUrl!==void 0?{baseUrlOverride:e.config.xaiBaseUrl}:{}});this.inner.setEndpointDefaults({baseURL:o.baseURL,defaultHeaders:o.defaultHeaders});let s={...e.config,apiKey:n,openaiBaseUrl:o.baseURL,forceChatgptOAuth:!1,forceXaiOAuth:r==="oauth",forceXaiApiKey:r==="apikey"};return this.inner.query({...e,config:s})}rememberResolved(e,n){this.lastMode=e,this.lastResolvedMode=e,this.lastXaiBaseUrl=n}addReadRoot(e,n="slash",r){this.inner.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.inner.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.inner.revokeRoot(e,n,r)}getGrants(){return this.inner.getGrants()}close(){this.inner.close()}async complete(e){let n=rk(this.authMode,this.lastResolvedMode);(n==="oauth"||n===void 0)&&await uc({store:this.authDeps.store});let r=St(e.apiKey,n,this.authDeps);if(r.apiKey===null||!r.mode)throw new Error(Bs(r));if(r.mode==="oauth"&&$f(r.expiresAt))throw new Error("SuperGrok OAuth access token expired and refresh failed. Re-run `afk provider auth xai login`.");this.rememberResolved(r.mode,this.lastXaiBaseUrl);let o=Us(r.mode,{readEnv:this.authDeps.readEnv,...this.lastXaiBaseUrl!==void 0?{baseUrlOverride:this.lastXaiBaseUrl}:{}});return this.inner.setEndpointDefaults({baseURL:o.baseURL,defaultHeaders:o.defaultHeaders}),this.inner.complete({...e,apiKey:r.apiKey,baseUrl:o.baseURL})}}});function Cne(t){if(!t)return;let e=t.trim().toLowerCase();if(e){if(e==="anthropic"||e==="anthropic-direct")return"anthropic-direct";if(e==="openai"||e==="openai-compatible"||e==="openai-codex")return"openai-compatible";if(e==="xai")return"xai";if(e==="xai-oauth"||e==="xai_oauth")return"xai-oauth"}}function z(t,e){let n=e?.explicit??k.AFK_PROVIDER,r=e?.openaiBaseUrl??k.AFK_OPENAI_BASE_URL,o=Cne(n);if(o)return o;let s=gr(t,e?.slots);if(s.provider==="anthropic")return"anthropic-direct";if(s.provider==="openai"||s.provider==="chatgpt-oauth")return"openai-compatible";if(s.provider==="xai")return"xai";if(s.provider==="xai-oauth")return"xai-oauth";let i=s.id.trim().toLowerCase();return i&&(Ine.has(i)||i.startsWith("claude-")||i.startsWith("claude_")||i.startsWith("local-")||i.startsWith("local_"))?"anthropic-direct":i&&(i.startsWith("grok-")||i.startsWith("grok_")||i==="grok")?"xai":i&&(i.startsWith("gpt-")||i.startsWith("gpt_")||hr(i)||i.startsWith("codex-")||i.startsWith("codex_")||i==="codex"||i.startsWith("deepseek-")||i.startsWith("deepseek_")||i.startsWith("mistral-")||i.startsWith("mistral_")||i.startsWith("mixtral-")||i.startsWith("mixtral_")||i.startsWith("llama-")||i.startsWith("llama_")||i.startsWith("qwen-")||i.startsWith("qwen_")||i.includes("/"))||s.baseUrl&&s.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function U0(t,e,n){let r=z(t,e),o=n?.customTools,s=n?.canUseTool,i={...o!==void 0&&o.length>0?{customTools:o}:{},...s!==void 0?{canUseTool:s}:{}};switch(r){case"openai-compatible":case"openai-codex":return new xe(i);case"xai":case"xai-oauth":{let a=(e?.explicit??k.AFK_PROVIDER)?.trim().toLowerCase()??"",d=ac(r==="xai-oauth"||a==="xai-oauth"||a==="xai_oauth"?"xai-oauth":"xai",a==="xai"||a==="xai-oauth"||a==="xai_oauth"||r==="xai-oauth");return new nr({...i,...d!==void 0?{authMode:d}:{}})}default:return new De(i)}}var Ine,fe=h(()=>{"use strict";ef();gs();pc();js();lt();Fe();yr();F();ef();gs();pc();Ine=new Set([...Object.keys(mg),"auto"])});import{mkdir as Zre,readdir as Hqe,readFile as eoe,rename as toe,rm as noe,stat as roe,unlink as dj,writeFile as vk}from"node:fs/promises";import{join as Qf}from"node:path";import{randomBytes as ooe}from"node:crypto";async function uj(t){await Zre(t,{recursive:!0,mode:448})}function Tk(t,e){return Qf(t,`${e}.json`)}function soe(t,e){return Qf(t,`${e}.lock`)}async function pj(t,e){let n=Qf(t,".."),r=Qf(n,`.tmp-${ooe(4).toString("hex")}.json`);try{await vk(r,JSON.stringify(e),{encoding:"utf-8",mode:384}),await toe(r,t)}catch(o){try{await noe(r,{force:!0})}catch{}throw o}}async function Ek(t,e=yo()){cr(t.taskId),await uj(e),await pj(Tk(e,t.taskId),t)}async function wc(t,e=yo()){cr(t);let n=Tk(e,t);try{let r=await eoe(n,"utf-8");return JSON.parse(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function _k(t,e,n){let r=soe(e,t);try{await vk(r,"",{flag:"wx",mode:384})}catch(o){if(o.code==="EEXIST"){let s;try{s=(await roe(r)).mtimeMs}catch{return null}if(Date.now()-s<=ioe)return null;try{await dj(r)}catch{}try{await vk(r,"",{flag:"wx",mode:384})}catch(i){if(i.code==="EEXIST")return null;throw i}}else throw o}try{return await n()}finally{try{await dj(r)}catch{}}}async function fj(t,e,n,r=yo()){return cr(t),await uj(r),await _k(t,r,async()=>{let s=await wc(t,r);if(s===null)throw new Error(`handoff-store: no record found for taskId ${t}`);if(s.status!=="pending")return{won:!1};let i={...s,status:"answered",answer:e,answeredAt:new Date().toISOString(),answerSource:n};return await pj(Tk(r,t),i),{won:!0}})??{won:!1}}var ioe,Ak=h(()=>{"use strict";B();ioe=3e4});var Xqe,aoe,mj=h(()=>{"use strict";Xqe=300*1e3,aoe=600*1e3});var gj=h(()=>{"use strict";B();F();mj()});function em(t,e){if(!Zf.test(t))throw new Error(`buildElicitationCallback: invalid id ${JSON.stringify(t)}`);if(!Number.isInteger(e)||e<0)throw new Error(`buildElicitationCallback: choiceIndex must be a non-negative integer, got ${e}`);let n=`${Sc}${e}:${t}`,r=Buffer.byteLength(n,"utf8");if(r>64)throw new Error(`buildElicitationCallback: payload ${r} bytes exceeds Telegram's 64-byte limit (id=${t})`);return n}function hj(t){if(!t||!t.startsWith(Sc)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(Sc.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1),s=parseInt(r,10);return!Number.isInteger(s)||s<0||String(s)!==r||!Zf.test(o)?null:{id:o,choiceIndex:s}}function yj(t){if(!Zf.test(t))throw new Error(`buildCustomElicitationCallback: invalid id ${JSON.stringify(t)}`);let e=`${kc}${t}`,n=Buffer.byteLength(e,"utf8");if(n>64)throw new Error(`buildCustomElicitationCallback: ${n} bytes exceeds 64-byte limit`);return e}function bj(t){if(!t||!t.startsWith(kc)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(kc.length);return Zf.test(e)?e:null}var Sc,Zf,kc,xk=h(()=>{"use strict";Sc="afk:e:",Zf=/^[a-zA-Z0-9_-]{1,48}$/;kc="afk:ec:"});function Tc(t,e){if(!wj.test(t))throw new Error(`buildHandoffCallback: invalid taskId ${JSON.stringify(t)}`);if(!Number.isInteger(e)||e<0)throw new Error(`buildHandoffCallback: choiceIndex must be non-negative integer, got ${e}`);let n=`${vc}${e}:${t}`,r=Buffer.byteLength(n,"utf8");if(r>64)throw new Error(`buildHandoffCallback: payload ${r} bytes exceeds Telegram's ${64}-byte limit`);return n}function Sj(t){if(!t||!t.startsWith(vc)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(vc.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1),s=parseInt(r,10);return!Number.isInteger(s)||s<0||String(s)!==r||!wj.test(o)?null:{taskId:o,choiceIndex:s}}var vc,wj,Ik=h(()=>{"use strict";xk();vc="afk:h:",wj=/^[A-Za-z0-9_-]{1,128}$/});async function Ck(t,e,n,r){let o=JSON.stringify(e);if(Buffer.byteLength(o,"utf-8")>kj)throw new Error(`[handoff-wiring] answer for task ${t} exceeds ${kj} bytes \u2014 rejected`);return(await fj(t,e,n,r)).won}var pGe,kj,vj=h(()=>{"use strict";Ak();gj();Dr();tm();Ik();pGe=1440*60*1e3,kj=64*1024});var Mk={};mo(Mk,{clearPendingTextHandoff:()=>Ej,matchReplyToHandoff:()=>doe,registerHandoffAnswerHandlers:()=>loe,sendHandoffQuestion:()=>Tj});import{Markup as Ec}from"telegraf";function Aj(t){return t.length<=_j?t:`${t.slice(0,_j)}...(truncated)`}function coe(t,e=64){if(Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.from(t,"utf8").subarray(0,e);return new TextDecoder("utf-8",{fatal:!1}).decode(n).replace(/\uFFFD$/,"")}async function Tj(t){let{bot:e,record:n,chatId:r,threadId:o,handoffsDir:s}=t,i=o?{message_thread_id:o}:{},a=n.question,c=a.type??"text",l=typeof a.message=="string"?a.message:"(question details unavailable)",d=typeof a.context=="string"?a.context:void 0,u=Array.isArray(a.choices)?a.choices:[],p=`\u{1F514} <b>Daemon task needs your answer</b>
|
|
1421
1421
|
`;p+=`\u{1F4CB} <code>${ge(n.taskId)}</code>
|
|
1422
1422
|
|
|
1423
1423
|
`,d&&(p+=`<i>${ge(Aj(d))}</i>
|
|
@@ -1445,13 +1445,13 @@ ${r}
|
|
|
1445
1445
|
${o}`};if(s&&typeof s=="object"&&"type"in s&&s.type==="preset"){let i=s.append??"";return{...t,systemPrompt:{...s,append:`${i}
|
|
1446
1446
|
|
|
1447
1447
|
${o}`}}}return{...t,systemPrompt:o}}var Gm=new Map;function Xm(t,e){Gm.set(t,e)}function cl(t){return Gm.get(t)}function pT(t){Gm.delete(t)}Qm();function vT(t,e,n){wT(!0)&&Promise.resolve().then(async()=>{try{let r=yT({sessionId:t});for(let o of r.offers)await Promise.resolve(n(e,bT(o)))!==!1&&ST(o.manifest)}catch{}})}function ml(t){let e=t.toLowerCase().replace(/[`*_~]/g," ").replace(/[^\w\s-]/g," ").replace(/[\s_]+/g," ").trim();return e?e.split(" ").filter(Boolean).slice(0,6).join("-").slice(0,48).replace(/-+$/g,""):""}function TT(t){return{totalTurns:0,totalCostUsd:0,unpricedTurns:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:t,permissionMode:"default",thinkingUi:"live"}}function ET(t,e,n,r,o){let s=r?.totalCostUsd,i=s??0,a=r?.durationMs??0,c=Number(r?.usage?.input_tokens??0),l=Number(r?.usage?.output_tokens??0),d=c,u=l,p=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),f=r?.usage?.iterations;if(Array.isArray(f)&&f.length>0){let w=f[f.length-1];if(w&&typeof w=="object"){let v=w;d=Number(v.input_tokens??0),u=Number(v.output_tokens??0),p=Number(v.cache_read_input_tokens??0)+Number(v.cache_creation_input_tokens??0)}}t.totalTurns+=1,t.totalCostUsd+=i,s===void 0&&(t.unpricedTurns+=1),t.totalDurationMs+=a,t.totalTokens+=c+l,t.turnCosts.push(i);let m=Number(r?.usage?.context_window_tokens??NaN),g=Array.isArray(f)&&f.length>0,y=Number.isFinite(m)?m:g?d+u+p:void 0;if(t.turnTokens.push({input:d,output:u,cache:p,...y!==void 0?{footprint:y}:{}}),r?.sessionId&&!t.sessionId&&(t.sessionId=String(r.sessionId)),!t.name){let w=ml(e);w&&(t.name=w)}let b={user:e,assistant:n,timestamp:Date.now(),costUsd:i,durationMs:a,inputTokens:c,outputTokens:l,...o&&o.length>0?{toolEvents:o}:{}};return t.turns.push(b),b}import{readFileSync as uK,writeFileSync as pK,existsSync as hl,mkdirSync as fK,readdirSync as mK,statSync as gK,realpathSync as _T}from"fs";import{join as xT,basename as RT,resolve as AT,sep as hK,isAbsolute as yK}from"path";B();import{randomUUID as lK}from"node:crypto";var ai=class extends Error{constructor(e){super(e),this.name="SessionRegistryError"}},Zm=class{byId=new Map;byBinding=new Map;bySdk=new Map;now;constructor(e){this.now=e?.now??Date.now}create(e){let n=this.now(),r=e.id??lK();if(this.byId.has(r))throw new ai(`session handle already exists: ${r}`);let o={surface:e.surface,key:e.key,boundAt:n,lastActiveAt:n},s={id:r,surface:e.surface,model:e.model,createdAt:e.createdAt??n,lastActiveAt:n,status:"active",bindings:[o]};return e.name!==void 0&&(s.name=e.name),e.cwd!==void 0&&(s.cwd=e.cwd),e.sdkSessionId!==void 0&&(s.sdkSessionId=e.sdkSessionId),this.byId.set(r,s),this.pointBinding(this.bindingKey(o.surface,o.key),r),s.sdkSessionId!==void 0&&this.bySdk.set(s.sdkSessionId,r),this.clone(s)}load(e){if(this.byId.has(e.id))throw new ai(`session handle already exists: ${e.id}`);let n=this.clone(e);if(this.byId.set(n.id,n),n.status==="active")for(let r of n.bindings)this.pointBinding(this.bindingKey(r.surface,r.key),n.id);n.sdkSessionId!==void 0&&this.bySdk.set(n.sdkSessionId,n.id)}get(e){let n=this.byId.get(e);return n?this.clone(n):void 0}getBySdkSessionId(e){let n=this.bySdk.get(e);if(n===void 0)return;let r=this.byId.get(n);return r?this.clone(r):void 0}resolve(e,n){let r=this.byBinding.get(this.bindingKey(e,n));if(r===void 0)return;let o=this.byId.get(r);if(!(!o||o.status!=="active"))return this.clone(o)}bind(e,n){let r=this.require(e),o=this.now(),s=this.bindingKey(n.surface,n.key),i=r.bindings.find(a=>this.bindingKey(a.surface,a.key)===s);i?i.lastActiveAt=o:r.bindings.push({surface:n.surface,key:n.key,boundAt:o,lastActiveAt:o}),this.pointBinding(s,e),r.lastActiveAt=o}unbind(e,n){let r=this.bindingKey(e,n),o=this.byBinding.get(r);if(this.byBinding.delete(r),o===void 0)return;let s=this.byId.get(o);s&&(s.bindings=s.bindings.filter(i=>this.bindingKey(i.surface,i.key)!==r))}attachSdkSessionId(e,n){let r=this.require(e);r.sdkSessionId!==void 0&&r.sdkSessionId!==n&&this.bySdk.get(r.sdkSessionId)===e&&this.bySdk.delete(r.sdkSessionId),r.sdkSessionId=n,this.bySdk.set(n,e),r.lastActiveAt=this.now()}rename(e,n){let r=this.require(e);r.name=n,r.lastActiveAt=this.now()}touch(e){let n=this.require(e);n.lastActiveAt=this.now()}archive(e){let n=this.require(e);n.status="archived",n.lastActiveAt=this.now();for(let r of n.bindings){let o=this.bindingKey(r.surface,r.key);this.byBinding.get(o)===e&&this.byBinding.delete(o)}}list(e){let n=[];for(let r of this.byId.values())e?.surface!==void 0&&r.surface!==e.surface||e?.status!==void 0&&r.status!==e.status||n.push(this.clone(r));return n.sort((r,o)=>o.lastActiveAt-r.lastActiveAt),n}bindingKey(e,n){return`${e}\0${n}`}require(e){let n=this.byId.get(e);if(!n)throw new ai(`unknown session handle: ${e}`);return n}pointBinding(e,n){let r=this.byBinding.get(e);if(r!==void 0&&r!==n){let o=this.byId.get(r);o&&(o.bindings=o.bindings.filter(s=>this.bindingKey(s.surface,s.key)!==e))}this.byBinding.set(e,n)}clone(e){return{...e,bindings:e.bindings.map(n=>({...n}))}}};var gl=new Zm;function ci(){return Fv(),ce()}function bK(t){return xT(ci(),`${t}.json`)}function eg(t,{write:e=!1}={}){let n=t.includes("/")||t.includes("\\")||yK(t)?t:bK(t),r,o;if(!e&&hl(n)?(r=_T(n),o=_T(ci())):(r=AT(n),o=AT(ci())),!r.startsWith(o+hK)&&r!==o)throw new Error(`Session path escapes sessions directory: ${t}`);return r}function tg(t,e){let n=ci();hl(n)||fK(n,{recursive:!0});let r=e??t.sessionId??`session-${Date.now()}`,o={sessionId:t.sessionId,...t.name?{name:t.name}:{},...t.source?{source:t.source}:{},...t.actor?{actor:t.actor}:{},...t.telegramChatId!==void 0?{telegramChatId:t.telegramChatId}:{},...t.cwd?{cwd:t.cwd}:{},model:t.model,startedAt:t.sessionStartTime,savedAt:Date.now(),totalTurns:t.totalTurns,totalCostUsd:t.totalCostUsd,unpricedTurns:t.unpricedTurns,totalTokens:t.totalTokens,totalDurationMs:t.totalDurationMs,turns:t.turns},s=eg(r,{write:!0});return pK(s,JSON.stringify(o,null,2)),s}function $t(t){let e;try{e=eg(t)}catch(n){console.warn(`loadSession: rejected unsafe session id ${JSON.stringify(t)}: ${n.message}`);return}if(hl(e))try{let n=uK(e,"utf-8");return JSON.parse(n)}catch(n){console.warn(`loadSession: failed to read/parse ${e}: ${n.message}`);return}}function ng(t){let e;try{e=eg(t)}catch{return}let n=$t(e);if(n)return{path:e,id:RT(e,".json"),data:n};let r=Eo();for(let s of r){if(s.id!==t&&s.sessionId!==t&&s.name!==t)continue;let i=$t(s.path);if(i)return{path:s.path,id:s.id,data:i}}if(t.length>=3){let s=r.filter(i=>i.name!==void 0&&i.name.startsWith(t));if(s.length===1){let i=s[0];if(i){let a=$t(i.path);if(a)return{path:i.path,id:i.id,data:a}}}}}function Eo(){let t=ci();if(!hl(t))return[];let e=[];for(let n of mK(t)){if(!n.endsWith(".json"))continue;let r=xT(t,n);try{if(!gK(r).isFile())continue;let s=$t(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;e.push({path:r,id:RT(n,".json"),sessionId:s.sessionId,name:s.name,source:s.source,actor:s.actor,telegramChatId:s.telegramChatId,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd,cwd:s.cwd})}catch{}}return e.sort((n,r)=>r.savedAt-n.savedAt),e}function wK(t){let e=new Map,n=[];for(let r of t)r.toolUseId===void 0?n.push(r):e.set(r.toolUseId,r);return[...e.values(),...n]}function IT(t){return!t||t.length===0?"":`
|
|
1448
|
-
[Tools used: ${wK(t).map(r=>{let o=r.isError?"\u2717":"\u2713",s=r.input||r.inputRaw||"",i=s.length>80?s.slice(0,77)+"\u2026":s;return`${r.toolName}(${i})${o}`}).join(", ")}]`}function CT(t){return t?{resume:t.resumeId,sessionId:t.resumeId,...t.stored?{resumeHistory:t.stored.turns.map((e,n,r)=>{let o={user:e.user,assistant:(e.assistant??"")+IT(e.toolEvents)};return n===r.length-1&&e.inputTokens!==void 0&&(o.inputTokens=e.inputTokens),o})}:{}}:{}}function SK(t){if(t===null||typeof t!="object")return{};let e=t,n=e.message_thread_id,r=e.is_topic_message;return{...typeof n=="number"?{threadId:n}:{},...r===!0?{isTopic:!0}:{}}}function ae(t){let e=t.chat?.id;if(typeof e!="number")return;let n=t.message??t.editedMessage??t.callbackQuery?.message,{threadId:r,isTopic:o}=SK(n),s={chatId:e};return r!==void 0&&r!==0&&(s.threadId=r),o&&(s.isTopicMessage=!0),s}function PT(t){return t.threadId===void 0||t.threadId===0||t.threadId===1}function G(t){return PT(t)?String(t.chatId):`${t.chatId}:${t.threadId}`}function Tn(t){return PT(t)?{}:{message_thread_id:t.threadId}}function MT(t,e,n,r){let o=G(e),s=o,i=t.resolve("telegram",o);if(i){t.touch(i.id),n.sessionId&&t.attachSdkSessionId(i.id,n.sessionId);return}let a=t.get(s);if(a&&a.status==="active"){t.bind(s,{surface:"telegram",key:o}),n.sessionId&&t.attachSdkSessionId(s,n.sessionId);return}let c=a===void 0?s:void 0;t.create({surface:"telegram",key:o,model:n.model??r,id:c,sdkSessionId:n.sessionId})}function rg(t,e){t.archive(e)}function OT(t,e){let n;for(let o of t)o.chatId===e&&(!n||o.lastActivity>n.lastActivity)&&(n=o);if(!n)return;let r={chatId:n.chatId};return n.threadId!==void 0&&(r.threadId=n.threadId),r}function DT(t,e,n){let r=G(n);if(t.has(r))return;let o=e.get(r)?.sessionId;if(!o)return;let s=$t(o);if(!s||s.source!=="telegram"||s.telegramChatId!==n.chatId)return;let i={sessionId:s.sessionId,name:s.name,model:s.model,source:s.source,telegramChatId:s.telegramChatId,sessionStartTime:s.startedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd,unpricedTurns:s.unpricedTurns??0,totalTokens:s.totalTokens,totalDurationMs:s.totalDurationMs,turns:s.turns,turnCosts:[],turnTokens:[],permissionMode:"default"},a=e.get(r)?.cwd;a!==void 0&&(i.cwd=a),t.set(r,i)}import{promises as li}from"fs";import{join as FT}from"path";function tt(t){return typeof t=="number"?{chatId:t}:t}var yl=class{sessions=new Map;pendingSessions=new Map;sessionData=new Map;sessionStats=new Map;autosaveFailureLogged=new Set;pendingResume=new Map;options;constructor(e){this.options={dataDir:e.dataDir||"./data/telegram-sessions",defaultModel:e.defaultModel||"medium",apiKey:e.apiKey,settingSources:e.settingSources,thinking:e.thinking,effort:e.effort,botCwd:e.botCwd,createSession:e.createSession,registry:e.registry,onResumptionOffer:e.onResumptionOffer}}getSessionIfExists(e){return this.sessions.get(G(tt(e)))}async getSession(e){let n=tt(e),r=G(n),o=this.sessions.get(r);if(o)return this._touchActivity(r),o;let s=this.pendingSessions.get(r);if(s)try{return await s}finally{this._touchActivity(r)}let i=this.sessionData.get(r)??this._newData(n),a=(async()=>{let c={model:i.model,apiKey:this.options.apiKey,telegramChatId:n.chatId,...n.threadId!==void 0?{telegramThreadId:n.threadId}:{}};this.options.settingSources?.length&&(c.settingSources=this.options.settingSources),this.options.thinking!==void 0&&(c.thinking=this.options.thinking),this.options.effort!==void 0&&(c.effort=this.options.effort);let l=i.cwd??this.options.botCwd;l!==void 0&&l.length>0&&(c.cwd=l);let d=this.pendingResume.get(r);if(d!==void 0){let p=$t(d);Object.assign(c,CT({id:d,resumeId:p?.sessionId??d,stored:p}))}let u=await this.options.createSession(qm(Bm(c)));this.sessions.set(r,u),this.sessionData.set(r,i);try{this._ensureRegistryHandle(n,i)}catch{}return u.sessionId&&(Xm(u.sessionId,n),i.sessionId=u.sessionId),this.options.onResumptionOffer&&vT(u.sessionId??"",n,this.options.onResumptionOffer),d!==void 0&&this.pendingResume.delete(r),u})();this.pendingSessions.set(r,a);try{let c=await a;return this._touchActivity(r),c}finally{this.pendingSessions.delete(r)}}_newData(e){let n={chatId:e.chatId,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()};return e.threadId!==void 0&&(n.threadId=e.threadId),n}_touchActivity(e){let n=this.sessionData.get(e);n&&(n.lastActivity=new Date().toISOString())}_ensureRegistryHandle(e,n){MT(this.options.registry??gl,e,n,this.options.defaultModel)}recordTelegramTurn(e,n,r,o){let s=tt(e),i=G(s),a=this._getOrCreateStats(s),c=this.sessions.get(i);!a.sessionId&&c?.sessionId&&(a.sessionId=c.sessionId),ET(a,n,r,o),!a.sessionId&&c?.sessionId&&(a.sessionId=c.sessionId);let l=this.sessionData.get(i);if(l&&a.sessionId&&(l.sessionId=a.sessionId),a.sessionId&&Xm(a.sessionId,s),a.sessionId)try{tg(a)}catch(d){this.autosaveFailureLogged.has(i)||(this.autosaveFailureLogged.add(i),console.error(`[session-manager] autosave failed for chat ${s.chatId} \u2014 conversation may not be resumable:`,d))}}_hydrateStatsFromStore(e){DT(this.sessionStats,this.sessionData,e)}getSessionName(e){let n=tt(e);return this._hydrateStatsFromStore(n),this.sessionStats.get(G(n))?.name}setSessionName(e,n){let r=tt(e),o=G(r),s=this._getOrCreateStats(r);s.name=n;let i=this.sessions.get(o);if(!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId),s.totalTurns>0&&s.sessionId){let a=this.sessionData.get(o);return a&&(a.sessionId=s.sessionId),tg(s),{persisted:!0}}return{persisted:!1}}_getOrCreateStats(e){let n=G(e);this._hydrateStatsFromStore(e);let r=this.sessionStats.get(n);if(!r){r=TT(this.getModel(e)),r.source="telegram",r.telegramChatId=e.chatId;let o=this.getCwd(e);o&&(r.cwd=o),this.sessionStats.set(n,r)}return r}_resetStats(e){let n=this.sessionStats.get(e)?.sessionId??this.sessionData.get(e)?.sessionId;n&&pT(n),this.sessionStats.delete(e),this.autosaveFailureLogged.delete(e),this.pendingResume.delete(e);let r=this.sessionData.get(e);r&&delete r.sessionId}async resetSession(e){let n=tt(e),r=G(n);try{rg(this.options.registry??gl,r)}catch{}let o=this.sessions.get(r);o&&(await o.close(),this.sessions.delete(r)),this._resetStats(r);let s=this.sessionData.get(r);s&&(s.lastActivity=new Date().toISOString())}async switchModel(e,n){let r=tt(e),o=G(r);try{rg(this.options.registry??gl,o)}catch{}let s=this.sessions.get(o);s&&(await s.close(),this.sessions.delete(o)),this._resetStats(o);let i=this.sessionData.get(o);i?(i.model=n,i.lastActivity=new Date().toISOString()):(i=this._newData(r),i.model=n,this.sessionData.set(o,i));try{this._ensureRegistryHandle(r,i)}catch{}}getModel(e){return this.sessionData.get(G(tt(e)))?.model||this.options.defaultModel}async setCwd(e,n){let r=tt(e),o=G(r),s=this.sessions.get(o);s&&(await s.close(),this.sessions.delete(o)),this._resetStats(o);let i=this.sessionData.get(o);i?(i.cwd=n,i.lastActivity=new Date().toISOString()):(i=this._newData(r),i.cwd=n,this.sessionData.set(o,i))}getCwd(e){return this.sessionData.get(G(tt(e)))?.cwd??this.options.botCwd}listChatSessions(e){let n=tt(e),r=this.sessionData.get(G(n))?.sessionId;return Eo().filter(o=>o.source==="telegram"&&o.telegramChatId===n.chatId&&o.sessionId!==void 0).map(o=>{let s={sessionId:o.sessionId,model:o.model,turns:o.totalTurns,lastActive:o.savedAt,active:o.sessionId===r};return o.name!==void 0&&(s.name=o.name),s}).sort((o,s)=>s.lastActive-o.lastActive)}async switchToSession(e,n){let r=tt(e),o=G(r),s=this.pendingSessions.get(o);if(s!==void 0&&await s.catch(()=>{}),this.sessions.has(o)&&this.sessionData.get(o)?.sessionId===n)return{ok:!1,reason:"already-active"};let i=$t(n);if(!i||i.source!=="telegram"||i.telegramChatId!==r.chatId)return{ok:!1,reason:"not-found"};let a=this.sessions.get(o);a&&(await a.close().catch(l=>console.error("Error closing session on switch:",l)),this.sessions.delete(o)),this.sessionStats.delete(o),this.autosaveFailureLogged.delete(o);let c=this.sessionData.get(o);return c?(c.model=i.model,c.lastActivity=new Date().toISOString()):(c=this._newData(r),c.model=i.model,this.sessionData.set(o,c)),c.sessionId=n,i.cwd!==void 0?c.cwd=i.cwd:delete c.cwd,this.pendingResume.set(o,n),i.name!==void 0?{ok:!0,name:i.name}:{ok:!0}}async newSession(e){this.pendingResume.delete(G(tt(e))),await this.resetSession(e)}sidecarFileName(e){let n={chatId:e.chatId};return e.threadId!==void 0&&(n.threadId=e.threadId),`${G(n)}.json`}async loadSessions(){try{await li.mkdir(this.options.dataDir,{recursive:!0});let e=await li.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=FT(this.options.dataDir,n),o=await li.readFile(r,"utf-8"),s=JSON.parse(o),i={chatId:s.chatId};s.threadId!==void 0&&(i.threadId=s.threadId),this.sessionData.set(G(i),s);try{this._ensureRegistryHandle(i,s)}catch{}}}catch(e){e.code!=="ENOENT"&&console.error("Failed to load sessions:",e)}}async saveSessions(){try{await li.mkdir(this.options.dataDir,{recursive:!0});for(let e of this.sessionData.values()){let n=FT(this.options.dataDir,this.sidecarFileName(e));await li.writeFile(n,JSON.stringify(e,null,2))}}catch(e){console.error("Failed to save sessions:",e)}}_evictStaleSessionData(e=1440*60*1e3){let n=Date.now();for(let[r,o]of this.sessionData){if(this.sessions.has(r))continue;n-new Date(o.lastActivity).getTime()>e&&this.sessionData.delete(r)}}async closeAll(){this._evictStaleSessionData(),await this.saveSessions(),await Promise.all(Array.from(this.sessions.values()).map(e=>e.close().catch(n=>console.error("Error closing session:",n)))),this.sessions.clear()}getSessionCount(){return this.sessions.size}getChatCount(){return this.sessionData.size}getActiveThreadId(e){let n;for(let r of this.sessionData.values())r.chatId!==e||r.threadId===void 0||(n===void 0||r.lastActivity>n.lastActivity)&&(n=r);return n?.threadId}getBusySessionCount(){let e=0;for(let n of this.sessions.values())n.state!=="idle"&&n.state!=="closed"&&e++;return e}getActiveRouteForChat(e){return OT(this.sessionData.values(),e)}};Te();Te();async function ig(t){await t.reply($T())}Te();async function ag(t,e){let n=ae(t),r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(NT(r))}se();import{Markup as fB}from"telegraf";import{promises as One}from"fs";import{homedir as mB}from"os";import{isAbsolute as Dne,resolve as ck}from"path";async function ui(t,e){t.sendChatAction("typing").catch(()=>{});let n=setInterval(()=>{t.sendChatAction("typing").catch(()=>{})},4e3);try{return await e()}finally{clearInterval(n)}}Te();fe();Fe();be();xa();co();function Pne(t,e){try{if(!t||t.trim().toLowerCase()==="auto")return{available:!0,needs:"unknown"};let n=gr(t,e);if(n.id==="")return{available:!1,needs:"local",hint:"not configured (set AFK_MODEL_LOCAL / models.local)"};if(n.provider==="chatgpt-oauth"){let o=zn(void 0,{},!0),s=o.apiKey!=null,i=s?void 0:o.source==="chatgpt-oauth-expired"?"ChatGPT token expired \u2014 re-run `codex` to refresh":"needs ChatGPT sign-in (~/.codex/auth.json)";return{available:s,needs:"chatgpt-oauth",hint:i}}if(n.provider==="xai-oauth"){let o=St(void 0,"oauth").apiKey!=null;return{available:o,needs:"xai-oauth",hint:o?void 0:"needs SuperGrok OAuth (`afk provider auth xai login`)"}}if(n.provider==="xai"){let o=St(n.apiKey,"apikey").apiKey!=null;return{available:o,needs:"xai",hint:o?void 0:"needs XAI_API_KEY"}}if(n.apiKey)return{available:!0,needs:"unknown"};let r=z(t,e?{slots:e}:void 0);if(r==="anthropic-direct"){let o=!!zi();return{available:o,needs:"anthropic",hint:o?void 0:"needs Claude sign-in / ANTHROPIC_API_KEY"}}if(r==="openai-compatible"){if(n.baseUrl)return{available:!0,needs:"local"};let o=!!Td()||zn(void 0,{},!1).apiKey!=null;return{available:o,needs:"openai",hint:o?void 0:"needs OPENAI_API_KEY"}}if(r==="xai"||r==="xai-oauth"){let i=St(void 0,r==="xai-oauth"?"oauth":void 0).apiKey!=null;return{available:i,needs:r==="xai-oauth"?"xai-oauth":"xai",hint:i?void 0:"needs XAI_API_KEY or SuperGrok OAuth (`afk provider auth xai login`)"}}return{available:!0,needs:"unknown"}}catch{return{available:!0,needs:"unknown"}}}function cB(t,e){return Pne(t,e).available}Fe();var Mne=/^[A-Za-z0-9_@%+=:,./-]+$/;function lB(t){return Mne.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function dB(t,e){let n=["afk","interactive"];return typeof e=="string"&&e.length>0&&n.push("--model",lB(e)),n.push("--resume",lB(t)),n.join(" ")}fe();Fe();function uB(t){if(mr.includes(t)||Io(t)!==void 0)return!0;let e=z(t);if(e==="openai-compatible"||e==="xai"||e==="xai-oauth")return!0;let n=gr(t).id.trim().toLowerCase();return n.startsWith("claude-")||n.startsWith("claude_")}function pB(t){return uB(t)}async function lk(t,e,n,r){let o=ae(t);if(!o){await t.reply(X("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o.chatId),await t.reply(Sl())}catch(s){r("Clear error:",s),await t.reply(X(s))}}async function gB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}try{let o=await e.getSession(r),s=o.hookRegistry,i=await ui(t,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));i.compacted?await t.reply(kl({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await t.reply(vl(i.reason??"unknown"))}catch(o){o instanceof ee?await t.reply(`Compaction skipped: ${ge(o.reason??"blocked by hook")}`):(n("Compact error:",o),await t.reply(X(o)))}}async function dk(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let l=e.getModel(r),d=mr.map(u=>[fB.button.callback(cB(u)?u:`${u} \u2014 needs sign-in`,`afk:m:${u}`)]);await t.reply(`Current model: <b>${ge(l.toUpperCase())}</b>
|
|
1448
|
+
[Tools used: ${wK(t).map(r=>{let o=r.isError?"\u2717":"\u2713",s=r.input||r.inputRaw||"",i=s.length>80?s.slice(0,77)+"\u2026":s;return`${r.toolName}(${i})${o}`}).join(", ")}]`}function CT(t){return t?{resume:t.resumeId,sessionId:t.resumeId,...t.stored?{resumeHistory:t.stored.turns.map((e,n,r)=>{let o={user:e.user,assistant:(e.assistant??"")+IT(e.toolEvents)};return n===r.length-1&&e.inputTokens!==void 0&&(o.inputTokens=e.inputTokens),o})}:{}}:{}}function SK(t){if(t===null||typeof t!="object")return{};let e=t,n=e.message_thread_id,r=e.is_topic_message;return{...typeof n=="number"?{threadId:n}:{},...r===!0?{isTopic:!0}:{}}}function ae(t){let e=t.chat?.id;if(typeof e!="number")return;let n=t.message??t.editedMessage??t.callbackQuery?.message,{threadId:r,isTopic:o}=SK(n),s={chatId:e};return r!==void 0&&r!==0&&(s.threadId=r),o&&(s.isTopicMessage=!0),s}function PT(t){return t.threadId===void 0||t.threadId===0||t.threadId===1}function G(t){return PT(t)?String(t.chatId):`${t.chatId}:${t.threadId}`}function Tn(t){return PT(t)?{}:{message_thread_id:t.threadId}}function MT(t,e,n,r){let o=G(e),s=o,i=t.resolve("telegram",o);if(i){t.touch(i.id),n.sessionId&&t.attachSdkSessionId(i.id,n.sessionId);return}let a=t.get(s);if(a&&a.status==="active"){t.bind(s,{surface:"telegram",key:o}),n.sessionId&&t.attachSdkSessionId(s,n.sessionId);return}let c=a===void 0?s:void 0;t.create({surface:"telegram",key:o,model:n.model??r,id:c,sdkSessionId:n.sessionId})}function rg(t,e){t.archive(e)}function OT(t,e){let n;for(let o of t)o.chatId===e&&(!n||o.lastActivity>n.lastActivity)&&(n=o);if(!n)return;let r={chatId:n.chatId};return n.threadId!==void 0&&(r.threadId=n.threadId),r}function DT(t,e,n){let r=G(n);if(t.has(r))return;let o=e.get(r)?.sessionId;if(!o)return;let s=$t(o);if(!s||s.source!=="telegram"||s.telegramChatId!==n.chatId)return;let i={sessionId:s.sessionId,name:s.name,model:s.model,source:s.source,telegramChatId:s.telegramChatId,sessionStartTime:s.startedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd,unpricedTurns:s.unpricedTurns??0,totalTokens:s.totalTokens,totalDurationMs:s.totalDurationMs,turns:s.turns,turnCosts:[],turnTokens:[],permissionMode:"default"},a=e.get(r)?.cwd;a!==void 0&&(i.cwd=a),t.set(r,i)}import{promises as li}from"fs";import{join as FT}from"path";function tt(t){return typeof t=="number"?{chatId:t}:t}var yl=class{sessions=new Map;pendingSessions=new Map;sessionData=new Map;sessionStats=new Map;autosaveFailureLogged=new Set;pendingResume=new Map;options;constructor(e){this.options={dataDir:e.dataDir||"./data/telegram-sessions",defaultModel:e.defaultModel||"medium",apiKey:e.apiKey,settingSources:e.settingSources,thinking:e.thinking,effort:e.effort,botCwd:e.botCwd,createSession:e.createSession,registry:e.registry,onResumptionOffer:e.onResumptionOffer}}getSessionIfExists(e){return this.sessions.get(G(tt(e)))}async getSession(e){let n=tt(e),r=G(n),o=this.sessions.get(r);if(o)return this._touchActivity(r),o;let s=this.pendingSessions.get(r);if(s)try{return await s}finally{this._touchActivity(r)}let i=this.sessionData.get(r)??this._newData(n),a=(async()=>{let c={model:i.model,apiKey:this.options.apiKey,telegramChatId:n.chatId,...n.threadId!==void 0?{telegramThreadId:n.threadId}:{}};this.options.settingSources?.length&&(c.settingSources=this.options.settingSources),this.options.thinking!==void 0&&(c.thinking=this.options.thinking),this.options.effort!==void 0&&(c.effort=this.options.effort);let l=i.cwd??this.options.botCwd;l!==void 0&&l.length>0&&(c.cwd=l);let d=this.pendingResume.get(r);if(d!==void 0){let p=$t(d);Object.assign(c,CT({id:d,resumeId:p?.sessionId??d,stored:p}))}let u=await this.options.createSession(qm(Bm(c)));this.sessions.set(r,u),this.sessionData.set(r,i);try{this._ensureRegistryHandle(n,i)}catch{}return u.sessionId&&(Xm(u.sessionId,n),i.sessionId=u.sessionId),this.options.onResumptionOffer&&vT(u.sessionId??"",n,this.options.onResumptionOffer),d!==void 0&&this.pendingResume.delete(r),u})();this.pendingSessions.set(r,a);try{let c=await a;return this._touchActivity(r),c}finally{this.pendingSessions.delete(r)}}_newData(e){let n={chatId:e.chatId,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()};return e.threadId!==void 0&&(n.threadId=e.threadId),n}_touchActivity(e){let n=this.sessionData.get(e);n&&(n.lastActivity=new Date().toISOString())}_ensureRegistryHandle(e,n){MT(this.options.registry??gl,e,n,this.options.defaultModel)}recordTelegramTurn(e,n,r,o){let s=tt(e),i=G(s),a=this._getOrCreateStats(s),c=this.sessions.get(i);!a.sessionId&&c?.sessionId&&(a.sessionId=c.sessionId),ET(a,n,r,o),!a.sessionId&&c?.sessionId&&(a.sessionId=c.sessionId);let l=this.sessionData.get(i);if(l&&a.sessionId&&(l.sessionId=a.sessionId),a.sessionId&&Xm(a.sessionId,s),a.sessionId)try{tg(a)}catch(d){this.autosaveFailureLogged.has(i)||(this.autosaveFailureLogged.add(i),console.error(`[session-manager] autosave failed for chat ${s.chatId} \u2014 conversation may not be resumable:`,d))}}_hydrateStatsFromStore(e){DT(this.sessionStats,this.sessionData,e)}getSessionName(e){let n=tt(e);return this._hydrateStatsFromStore(n),this.sessionStats.get(G(n))?.name}setSessionName(e,n){let r=tt(e),o=G(r),s=this._getOrCreateStats(r);s.name=n;let i=this.sessions.get(o);if(!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId),s.totalTurns>0&&s.sessionId){let a=this.sessionData.get(o);return a&&(a.sessionId=s.sessionId),tg(s),{persisted:!0}}return{persisted:!1}}_getOrCreateStats(e){let n=G(e);this._hydrateStatsFromStore(e);let r=this.sessionStats.get(n);if(!r){r=TT(this.getModel(e)),r.source="telegram",r.telegramChatId=e.chatId;let o=this.getCwd(e);o&&(r.cwd=o),this.sessionStats.set(n,r)}return r}_resetStats(e){let n=this.sessionStats.get(e)?.sessionId??this.sessionData.get(e)?.sessionId;n&&pT(n),this.sessionStats.delete(e),this.autosaveFailureLogged.delete(e),this.pendingResume.delete(e);let r=this.sessionData.get(e);r&&delete r.sessionId}async resetSession(e){let n=tt(e),r=G(n);try{rg(this.options.registry??gl,r)}catch{}let o=this.sessions.get(r);o&&(await o.close(),this.sessions.delete(r)),this._resetStats(r);let s=this.sessionData.get(r);s&&(s.lastActivity=new Date().toISOString())}async switchModel(e,n){let r=tt(e),o=G(r);try{rg(this.options.registry??gl,o)}catch{}let s=this.sessions.get(o);s&&(await s.close(),this.sessions.delete(o)),this._resetStats(o);let i=this.sessionData.get(o);i?(i.model=n,i.lastActivity=new Date().toISOString()):(i=this._newData(r),i.model=n,this.sessionData.set(o,i));try{this._ensureRegistryHandle(r,i)}catch{}}getModel(e){return this.sessionData.get(G(tt(e)))?.model||this.options.defaultModel}async setCwd(e,n){let r=tt(e),o=G(r),s=this.sessions.get(o);s&&(await s.close(),this.sessions.delete(o)),this._resetStats(o);let i=this.sessionData.get(o);i?(i.cwd=n,i.lastActivity=new Date().toISOString()):(i=this._newData(r),i.cwd=n,this.sessionData.set(o,i))}getCwd(e){return this.sessionData.get(G(tt(e)))?.cwd??this.options.botCwd}listChatSessions(e){let n=tt(e),r=this.sessionData.get(G(n))?.sessionId;return Eo().filter(o=>o.source==="telegram"&&o.telegramChatId===n.chatId&&o.sessionId!==void 0).map(o=>{let s={sessionId:o.sessionId,model:o.model,turns:o.totalTurns,lastActive:o.savedAt,active:o.sessionId===r};return o.name!==void 0&&(s.name=o.name),s}).sort((o,s)=>s.lastActive-o.lastActive)}async switchToSession(e,n){let r=tt(e),o=G(r),s=this.pendingSessions.get(o);if(s!==void 0&&await s.catch(()=>{}),this.sessions.has(o)&&this.sessionData.get(o)?.sessionId===n)return{ok:!1,reason:"already-active"};let i=$t(n);if(!i||i.source!=="telegram"||i.telegramChatId!==r.chatId)return{ok:!1,reason:"not-found"};let a=this.sessions.get(o);a&&(await a.close().catch(l=>console.error("Error closing session on switch:",l)),this.sessions.delete(o)),this.sessionStats.delete(o),this.autosaveFailureLogged.delete(o);let c=this.sessionData.get(o);return c?(c.model=i.model,c.lastActivity=new Date().toISOString()):(c=this._newData(r),c.model=i.model,this.sessionData.set(o,c)),c.sessionId=n,i.cwd!==void 0?c.cwd=i.cwd:delete c.cwd,this.pendingResume.set(o,n),i.name!==void 0?{ok:!0,name:i.name}:{ok:!0}}async newSession(e){this.pendingResume.delete(G(tt(e))),await this.resetSession(e)}sidecarFileName(e){let n={chatId:e.chatId};return e.threadId!==void 0&&(n.threadId=e.threadId),`${G(n)}.json`}async loadSessions(){try{await li.mkdir(this.options.dataDir,{recursive:!0});let e=await li.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=FT(this.options.dataDir,n),o=await li.readFile(r,"utf-8"),s=JSON.parse(o),i={chatId:s.chatId};s.threadId!==void 0&&(i.threadId=s.threadId),this.sessionData.set(G(i),s);try{this._ensureRegistryHandle(i,s)}catch{}}}catch(e){e.code!=="ENOENT"&&console.error("Failed to load sessions:",e)}}async saveSessions(){try{await li.mkdir(this.options.dataDir,{recursive:!0});for(let e of this.sessionData.values()){let n=FT(this.options.dataDir,this.sidecarFileName(e));await li.writeFile(n,JSON.stringify(e,null,2))}}catch(e){console.error("Failed to save sessions:",e)}}_evictStaleSessionData(e=1440*60*1e3){let n=Date.now();for(let[r,o]of this.sessionData){if(this.sessions.has(r))continue;n-new Date(o.lastActivity).getTime()>e&&this.sessionData.delete(r)}}async closeAll(){this._evictStaleSessionData(),await this.saveSessions(),await Promise.all(Array.from(this.sessions.values()).map(e=>e.close().catch(n=>console.error("Error closing session:",n)))),this.sessions.clear()}getSessionCount(){return this.sessions.size}getChatCount(){return this.sessionData.size}getActiveThreadId(e){let n;for(let r of this.sessionData.values())r.chatId!==e||r.threadId===void 0||(n===void 0||r.lastActivity>n.lastActivity)&&(n=r);return n?.threadId}getBusySessionCount(){let e=0;for(let n of this.sessions.values())n.state!=="idle"&&n.state!=="closed"&&e++;return e}getActiveRouteForChat(e){return OT(this.sessionData.values(),e)}};Te();Te();async function ig(t){await t.reply($T())}Te();async function ag(t,e){let n=ae(t),r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(NT(r))}ie();import{Markup as fB}from"telegraf";import{promises as One}from"fs";import{homedir as mB}from"os";import{isAbsolute as Dne,resolve as ck}from"path";async function ui(t,e){t.sendChatAction("typing").catch(()=>{});let n=setInterval(()=>{t.sendChatAction("typing").catch(()=>{})},4e3);try{return await e()}finally{clearInterval(n)}}Te();fe();Fe();be();xa();co();function Pne(t,e){try{if(!t||t.trim().toLowerCase()==="auto")return{available:!0,needs:"unknown"};let n=gr(t,e);if(n.id==="")return{available:!1,needs:"local",hint:"not configured (set AFK_MODEL_LOCAL / models.local)"};if(n.provider==="chatgpt-oauth"){let o=zn(void 0,{},!0),s=o.apiKey!=null,i=s?void 0:o.source==="chatgpt-oauth-expired"?"ChatGPT token expired \u2014 re-run `codex` to refresh":"needs ChatGPT sign-in (~/.codex/auth.json)";return{available:s,needs:"chatgpt-oauth",hint:i}}if(n.provider==="xai-oauth"){let o=St(void 0,"oauth").apiKey!=null;return{available:o,needs:"xai-oauth",hint:o?void 0:"needs SuperGrok OAuth (`afk provider auth xai login`)"}}if(n.provider==="xai"){let o=St(n.apiKey,"apikey").apiKey!=null;return{available:o,needs:"xai",hint:o?void 0:"needs XAI_API_KEY"}}if(n.apiKey)return{available:!0,needs:"unknown"};let r=z(t,e?{slots:e}:void 0);if(r==="anthropic-direct"){let o=!!zi();return{available:o,needs:"anthropic",hint:o?void 0:"needs Claude sign-in / ANTHROPIC_API_KEY"}}if(r==="openai-compatible"){if(n.baseUrl)return{available:!0,needs:"local"};let o=!!Td()||zn(void 0,{},!1).apiKey!=null;return{available:o,needs:"openai",hint:o?void 0:"needs OPENAI_API_KEY"}}if(r==="xai"||r==="xai-oauth"){let i=St(void 0,r==="xai-oauth"?"oauth":void 0).apiKey!=null;return{available:i,needs:r==="xai-oauth"?"xai-oauth":"xai",hint:i?void 0:"needs XAI_API_KEY or SuperGrok OAuth (`afk provider auth xai login`)"}}return{available:!0,needs:"unknown"}}catch{return{available:!0,needs:"unknown"}}}function cB(t,e){return Pne(t,e).available}Fe();var Mne=/^[A-Za-z0-9_@%+=:,./-]+$/;function lB(t){return Mne.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function dB(t,e){let n=["afk","interactive"];return typeof e=="string"&&e.length>0&&n.push("--model",lB(e)),n.push("--resume",lB(t)),n.join(" ")}fe();Fe();function uB(t){if(mr.includes(t)||Io(t)!==void 0)return!0;let e=z(t);if(e==="openai-compatible"||e==="xai"||e==="xai-oauth")return!0;let n=gr(t).id.trim().toLowerCase();return n.startsWith("claude-")||n.startsWith("claude_")}function pB(t){return uB(t)}async function lk(t,e,n,r){let o=ae(t);if(!o){await t.reply(X("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o.chatId),await t.reply(Sl())}catch(s){r("Clear error:",s),await t.reply(X(s))}}async function gB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}try{let o=await e.getSession(r),s=o.hookRegistry,i=await ui(t,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));i.compacted?await t.reply(kl({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await t.reply(vl(i.reason??"unknown"))}catch(o){o instanceof ee?await t.reply(`Compaction skipped: ${ge(o.reason??"blocked by hook")}`):(n("Compact error:",o),await t.reply(X(o)))}}async function dk(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let l=e.getModel(r),d=mr.map(u=>[fB.button.callback(cB(u)?u:`${u} \u2014 needs sign-in`,`afk:m:${u}`)]);await t.reply(`Current model: <b>${ge(l.toUpperCase())}</b>
|
|
1449
1449
|
|
|
1450
1450
|
Switch to:`,{parse_mode:"HTML",reply_markup:fB.inlineKeyboard(d).reply_markup});return}let i=s[0];if(!i){await t.reply(X("Please specify a model: local, small, medium, large, opus, sonnet, haiku, or an org/model id"));return}let a=i.toLowerCase();if(!pB(a)){await t.reply(X(`Invalid model: ${i}
|
|
1451
|
-
Aliases: ${mr.join(", ")}, or a full model id`));return}let c=oE(a);if(c){await t.reply(X(c));return}try{await e.switchModel(r,a),await t.reply(wl(a))}catch(l){n("Model switch error:",l),await t.reply(X(l))}}function Fne(t,e){let n=t.trim();return n==="~"?mB():n.startsWith("~/")?ck(mB(),n.slice(2)):Dne(n)?ck(n):ck(e,n)}async function hB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).filter(l=>l.length>0);if(s.length===0){let l=e.getCwd(r);await t.reply(UT(l));return}let i=s[0];if(!i){await t.reply(X("Please specify a directory path"));return}let a=e.getCwd(r)??process.cwd(),c=Fne(i,a);try{if(!(await One.stat(c)).isDirectory()){await t.reply(X(`Not a directory: ${c}`));return}}catch(l){let d=l.code;d==="ENOENT"?await t.reply(og("ENOENT",c)):d==="EACCES"?await t.reply(og("EACCES",c)):(n("cwd stat error:",l),await t.reply(X(l)));return}try{await e.setCwd(r,c),await t.reply(BT(c))}catch(l){n("Cwd switch error:",l),await t.reply(X(l))}}async function yB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).join(" ").trim();if(!s){await t.reply(jT(e.getSessionName(r)));return}let i=ml(s);if(!i){await t.reply(HT());return}try{let{persisted:a}=e.setSessionName(r,i),c=a?dB(i,e.getModel(r)):void 0;await t.reply(WT(i,c))}catch(a){n("Name set error:",a),await t.reply(`\u{1F3F7}\uFE0F Named "${i}" but couldn't save it \u2014 it'll retry on your next message.`)}}import{Markup as bB}from"telegraf";Te();var Uf="afk:sw:",Lne=64;function Nne(t){let e=t.callbackQuery;return typeof e=="object"&&e!==null&&"data"in e?e.data:""}function wB(t,e){let n=t.getSessionIfExists(e);return n!==void 0&&n.state!=="idle"}async function SB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let o=e.listChatSessions(r);if(o.length===0){await t.reply(GT());return}let s=o.filter(i=>(Uf+i.sessionId).length<=Lne).map(i=>[bB.button.callback(`${i.active?"\u2705 ":""}${i.name??"(unnamed)"} \xB7 ${i.turns} turns`,`${Uf}${i.sessionId}`)]);await t.reply(qT(o),{parse_mode:"HTML",reply_markup:bB.inlineKeyboard(s).reply_markup})}async function kB(t,e,n,r){let o=ae(t);if(!o){await t.reply(X("Could not identify chat"));return}if(wB(e,o)){await t.reply(sg());return}try{await e.newSession(o),n.delete(o.chatId),await t.reply(zT())}catch(s){r("New session error:",s),await t.reply(X(s))}}async function vB(t,e,n){let r=ae(t),o=Nne(t),s=o.startsWith(Uf)?o.slice(Uf.length):"";if(!(!r||!s)){if(wB(e,r)){await t.reply(sg());return}try{let i=await e.switchToSession(r,s);if(!i.ok){await t.reply(i.reason==="already-active"?VT():JT());return}let a=XT(i.name!==void 0?{name:i.name}:{});await t.editMessageText(a,{parse_mode:"HTML"}).catch(()=>t.reply(a,{parse_mode:"HTML"}))}catch(i){n("Switch callback error:",i),await t.reply(X(i))}}}Te();var $ne="\u25D0 AFK mode ON \u2014 I'll work autonomously on reversible tasks and report here. High-risk / irreversible ops are REFUSED (not one-tap approvable) and surfaced as an Asking summary for you to handle deliberately. Send /afk off to stop.",Une="\u25CB AFK mode OFF \u2014 default permissions restored.";async function TB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let s=(t.message.text??"").split(/\s+/).slice(1).join(" ").trim().toLowerCase();try{let i=await e.getSession(r),a=i.getSessionMetadata().permissionMode==="autonomous",c=s==="on"?!0:s==="off"?!1:!a;if(c===a){await t.reply(c?"\u25D0 AFK mode is already ON.":"\u25CB AFK mode is already OFF.");return}await i.setPermissionMode(c?"autonomous":"default"),await t.reply(c?$ne:Une)}catch(i){n("AFK toggle error:",i),await t.reply(X("Could not toggle AFK mode"))}}qo();F();var Bne="https://api.anthropic.com/api/oauth/usage",jne="oauth-2025-04-20",Hne=1e4;async function EB(t){let e=t?.fetchImpl??fetch,n=t?.timeoutMs??Hne,r=t?.token??(k.CLAUDE_CODE_OAUTH_TOKEN||Xe());if(!r)return{kind:"unavailable",reason:"no-token",detail:"No Claude Code OAuth token found. Set CLAUDE_CODE_OAUTH_TOKEN or run `claude login` and try again."};let o;try{o=await e(Bne,{headers:{Authorization:`Bearer ${r}`,"anthropic-beta":jne},signal:AbortSignal.timeout(n)})}catch(u){return Wne(u)?{kind:"unavailable",reason:"timeout",detail:"Request to the usage endpoint timed out."}:{kind:"unavailable",reason:"network-error",detail:"Network error while contacting the usage endpoint."}}if(!o.ok)return{kind:"unavailable",reason:"http-error",detail:`Usage endpoint returned HTTP ${o.status}.`};let s;try{s=await o.json()}catch{return{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint returned a response that was not valid JSON."}}if(typeof s!="object"||s===null)return{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint returned an unexpected response shape."};let i=s,a=Bf(i.five_hour),c=Bf(i.seven_day),l=Bf(i.seven_day_sonnet),d=Bf(i.seven_day_opus);return!a&&!c&&!l&&!d?{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint response contained none of the known usage windows."}:{kind:"ok",...a!==void 0?{fiveHour:a}:{},...c!==void 0?{sevenDay:c}:{},...l!==void 0?{sevenDaySonnet:l}:{},...d!==void 0?{sevenDayOpus:d}:{}}}function Wne(t){return t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError")}var Kne=0,qne=4102444800;function Gne(t){if(typeof t=="string"){let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}if(typeof t=="number")return!Number.isFinite(t)||t<Kne||t>qne?void 0:new Date(t*1e3)}function Bf(t){if(typeof t!="object"||t===null)return;let e=t,n=e.utilization;if(typeof n!="number"||!Number.isFinite(n))return;let r=n>1?n/100:n,o=Math.min(1,Math.max(0,r)),s=Gne(e.resets_at);return{utilization:o,...s!==void 0?{resetsAt:s}:{}}}Te();async function _B(t,e){try{let n=await EB();await t.reply(LT(n))}catch(n){e("Usage command error:",n),await t.reply(X("Could not fetch usage"))}}import{execFile as dre,spawn as ure}from"node:child_process";import{promisify as pre}from"node:util";B();import{execFile as Xne}from"node:child_process";import{randomBytes as zne}from"node:crypto";import{promises as jf}from"node:fs";import{join as Hf}from"node:path";import{promisify as Jne}from"node:util";var
|
|
1451
|
+
Aliases: ${mr.join(", ")}, or a full model id`));return}let c=oE(a);if(c){await t.reply(X(c));return}try{await e.switchModel(r,a),await t.reply(wl(a))}catch(l){n("Model switch error:",l),await t.reply(X(l))}}function Fne(t,e){let n=t.trim();return n==="~"?mB():n.startsWith("~/")?ck(mB(),n.slice(2)):Dne(n)?ck(n):ck(e,n)}async function hB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).filter(l=>l.length>0);if(s.length===0){let l=e.getCwd(r);await t.reply(UT(l));return}let i=s[0];if(!i){await t.reply(X("Please specify a directory path"));return}let a=e.getCwd(r)??process.cwd(),c=Fne(i,a);try{if(!(await One.stat(c)).isDirectory()){await t.reply(X(`Not a directory: ${c}`));return}}catch(l){let d=l.code;d==="ENOENT"?await t.reply(og("ENOENT",c)):d==="EACCES"?await t.reply(og("EACCES",c)):(n("cwd stat error:",l),await t.reply(X(l)));return}try{await e.setCwd(r,c),await t.reply(BT(c))}catch(l){n("Cwd switch error:",l),await t.reply(X(l))}}async function yB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1).join(" ").trim();if(!s){await t.reply(jT(e.getSessionName(r)));return}let i=ml(s);if(!i){await t.reply(HT());return}try{let{persisted:a}=e.setSessionName(r,i),c=a?dB(i,e.getModel(r)):void 0;await t.reply(WT(i,c))}catch(a){n("Name set error:",a),await t.reply(`\u{1F3F7}\uFE0F Named "${i}" but couldn't save it \u2014 it'll retry on your next message.`)}}import{Markup as bB}from"telegraf";Te();var Uf="afk:sw:",Lne=64;function Nne(t){let e=t.callbackQuery;return typeof e=="object"&&e!==null&&"data"in e?e.data:""}function wB(t,e){let n=t.getSessionIfExists(e);return n!==void 0&&n.state!=="idle"}async function SB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let o=e.listChatSessions(r);if(o.length===0){await t.reply(GT());return}let s=o.filter(i=>(Uf+i.sessionId).length<=Lne).map(i=>[bB.button.callback(`${i.active?"\u2705 ":""}${i.name??"(unnamed)"} \xB7 ${i.turns} turns`,`${Uf}${i.sessionId}`)]);await t.reply(qT(o),{parse_mode:"HTML",reply_markup:bB.inlineKeyboard(s).reply_markup})}async function kB(t,e,n,r){let o=ae(t);if(!o){await t.reply(X("Could not identify chat"));return}if(wB(e,o)){await t.reply(sg());return}try{await e.newSession(o),n.delete(o.chatId),await t.reply(zT())}catch(s){r("New session error:",s),await t.reply(X(s))}}async function vB(t,e,n){let r=ae(t),o=Nne(t),s=o.startsWith(Uf)?o.slice(Uf.length):"";if(!(!r||!s)){if(wB(e,r)){await t.reply(sg());return}try{let i=await e.switchToSession(r,s);if(!i.ok){await t.reply(i.reason==="already-active"?VT():JT());return}let a=XT(i.name!==void 0?{name:i.name}:{});await t.editMessageText(a,{parse_mode:"HTML"}).catch(()=>t.reply(a,{parse_mode:"HTML"}))}catch(i){n("Switch callback error:",i),await t.reply(X(i))}}}Te();var $ne="\u25D0 AFK mode ON \u2014 I'll work autonomously on reversible tasks and report here. High-risk / irreversible ops are REFUSED (not one-tap approvable) and surfaced as an Asking summary for you to handle deliberately. Send /afk off to stop.",Une="\u25CB AFK mode OFF \u2014 default permissions restored.";async function TB(t,e,n){let r=ae(t);if(!r){await t.reply(X("Could not identify chat"));return}let s=(t.message.text??"").split(/\s+/).slice(1).join(" ").trim().toLowerCase();try{let i=await e.getSession(r),a=i.getSessionMetadata().permissionMode==="autonomous",c=s==="on"?!0:s==="off"?!1:!a;if(c===a){await t.reply(c?"\u25D0 AFK mode is already ON.":"\u25CB AFK mode is already OFF.");return}await i.setPermissionMode(c?"autonomous":"default"),await t.reply(c?$ne:Une)}catch(i){n("AFK toggle error:",i),await t.reply(X("Could not toggle AFK mode"))}}qo();F();var Bne="https://api.anthropic.com/api/oauth/usage",jne="oauth-2025-04-20",Hne=1e4;async function EB(t){let e=t?.fetchImpl??fetch,n=t?.timeoutMs??Hne,r=t?.token??(k.CLAUDE_CODE_OAUTH_TOKEN||Xe());if(!r)return{kind:"unavailable",reason:"no-token",detail:"No Claude Code OAuth token found. Set CLAUDE_CODE_OAUTH_TOKEN or run `claude login` and try again."};let o;try{o=await e(Bne,{headers:{Authorization:`Bearer ${r}`,"anthropic-beta":jne},signal:AbortSignal.timeout(n)})}catch(u){return Wne(u)?{kind:"unavailable",reason:"timeout",detail:"Request to the usage endpoint timed out."}:{kind:"unavailable",reason:"network-error",detail:"Network error while contacting the usage endpoint."}}if(!o.ok)return{kind:"unavailable",reason:"http-error",detail:`Usage endpoint returned HTTP ${o.status}.`};let s;try{s=await o.json()}catch{return{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint returned a response that was not valid JSON."}}if(typeof s!="object"||s===null)return{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint returned an unexpected response shape."};let i=s,a=Bf(i.five_hour),c=Bf(i.seven_day),l=Bf(i.seven_day_sonnet),d=Bf(i.seven_day_opus);return!a&&!c&&!l&&!d?{kind:"unavailable",reason:"malformed-response",detail:"Usage endpoint response contained none of the known usage windows."}:{kind:"ok",...a!==void 0?{fiveHour:a}:{},...c!==void 0?{sevenDay:c}:{},...l!==void 0?{sevenDaySonnet:l}:{},...d!==void 0?{sevenDayOpus:d}:{}}}function Wne(t){return t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError")}var Kne=0,qne=4102444800;function Gne(t){if(typeof t=="string"){let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}if(typeof t=="number")return!Number.isFinite(t)||t<Kne||t>qne?void 0:new Date(t*1e3)}function Bf(t){if(typeof t!="object"||t===null)return;let e=t,n=e.utilization;if(typeof n!="number"||!Number.isFinite(n))return;let r=n>1?n/100:n,o=Math.min(1,Math.max(0,r)),s=Gne(e.resets_at);return{utilization:o,...s!==void 0?{resetsAt:s}:{}}}Te();async function _B(t,e){try{let n=await EB();await t.reply(LT(n))}catch(n){e("Usage command error:",n),await t.reply(X("Could not fetch usage"))}}import{execFile as dre,spawn as ure}from"node:child_process";import{promisify as pre}from"node:util";B();import{execFile as Xne}from"node:child_process";import{randomBytes as zne}from"node:crypto";import{promises as jf}from"node:fs";import{join as Hf}from"node:path";import{promisify as Jne}from"node:util";var uKe=Jne(Xne);var rr=class extends Error{cause;code;constructor(e,n,r){super(e),this.name="WorktreeError",this.cause=n,this.code=r}};function Vne(t,e=40){return t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,e).replace(/-+$/g,"")||"task"}function Yne(){return zne(4).toString("hex").slice(0,4)}function Qne(t){let e=n=>String(n).padStart(2,"0");return`${t.getUTCFullYear()}${e(t.getUTCMonth()+1)}${e(t.getUTCDate())}T${e(t.getUTCHours())}${e(t.getUTCMinutes())}${e(t.getUTCSeconds())}`}function AB(t,e={}){let n=(e.now??(()=>new Date))(),r=(e.randomSuffix??Yne)();return`${Qne(n)}-${Vne(t,32)}-${r}`}function Zne(t){let e=t;return e.respawnedAt===void 0&&(e.respawnedAt=void 0),e.respawnedAs===void 0&&(e.respawnedAs=void 0),e.prUrl===void 0&&(e.prUrl=void 0),e.prCreatedAt===void 0&&(e.prCreatedAt=void 0),e}async function Hs(t){let e=Hf(Rv(t),"farm.json");try{let n=await jf.readFile(e,"utf8"),r=JSON.parse(n);if(r.schemaVersion!==1&&r.schemaVersion!==2&&r.schemaVersion!==3)throw new rr(`unsupported farm manifest schema: ${r.schemaVersion} (expected 1, 2, or 3)`,void 0,"unsupported-schema");return Zne(r)}catch(n){if(n.code==="ENOENT")return null;throw n instanceof rr?n:new rr(`failed to load farm manifest ${e}`,n,"invalid")}}async function xB(t,e){let n=await Hs(t);if(!n)throw new rr(`farm not found: ${t}`);return n.human_decision=e,n.decidedAt=new Date().toISOString(),n.schemaVersion=3,await jf.writeFile(Hf(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
|
|
1452
1452
|
`,"utf8"),n}async function RB(t,e){let n=await Hs(t);if(!n)throw new rr(`farm not found: ${t}`);return n.respawnedAt=new Date().toISOString(),n.respawnedAs=e,n.schemaVersion=3,await jf.writeFile(Hf(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
|
|
1453
1453
|
`,"utf8"),n}async function IB(t,e){let n=await Hs(t);if(!n)throw new rr(`farm not found: ${t}`);return n.prUrl=e,n.prCreatedAt=new Date().toISOString(),n.schemaVersion=3,await jf.writeFile(Hf(n.farmDir,"farm.json"),JSON.stringify(n,null,2)+`
|
|
1454
|
-
`,"utf8"),n}import{execFile as ere,spawn as
|
|
1454
|
+
`,"utf8"),n}import{execFile as ere,spawn as mKe}from"node:child_process";import{promisify as tre}from"node:util";var nre=tre(ere),rre=2e4,mc=class extends Error{kind;exitCode;stderr;constructor(e,n,r,o){super(e),this.name="GhError",this.kind=n,this.exitCode=r,this.stderr=o}},Wf=null,fc=null;function ore(t,e,n){return n===!0?"timeout":e==="ENOENT"?"not-found":/already exists/i.test(t)?"already-exists":/authentication|please log in|HTTP 40[13]|bad credentials|token|scope/i.test(t)?"unauthed":/ETIMEDOUT|ECONNRESET|ECONNREFUSED/i.test(t+(e??""))?"network":"unknown"}function CB(t,e){return nre(t,e,{timeout:rre,killSignal:"SIGTERM"}).then(n=>({stdout:n.stdout,stderr:n.stderr}))}async function PB(t={}){let e=(t._now??(()=>Date.now()))(),n=t.ttlMs??6e4,r=t.execFn??CB,o=t.log??(()=>{});return Wf&&Wf.expiresAt>e?(o("[gh] checkGhReady cache hit"),Wf.result):(o("[gh] checkGhReady cache miss \u2014 probing"),fc||(fc=(async()=>{try{await r("gh",["--version"])}catch(a){let c=a;return c.killed?{ok:!1,hint:"`gh` timed out \u2014 check connectivity"}:c.code==="ENOENT"?{ok:!1,hint:"`gh` CLI not found \u2014 install with: brew install gh"}:{ok:!1,hint:"`gh --version` failed unexpectedly \u2014 check gh installation"}}try{await r("gh",["auth","status"])}catch(a){let c=a;return c.killed||/ETIMEDOUT|ECONNRESET|ENOTFOUND/i.test(String(c.code??""))?{ok:!1,hint:"check network \u2014 cannot reach GitHub"}:{ok:!1,hint:"`gh` is not authenticated \u2014 run: gh auth login"}}let i={ok:!0};return n>0&&(Wf={result:i,expiresAt:e+n}),i})().finally(()=>{fc=null}),fc))}async function MB(t,e){let n=e??CB,r=["pr","create","--base",t.base,"--head",t.head,"--title",t.title,"--body",t.body];try{let{stdout:o}=await n("gh",r);return o.trim()}catch(o){let s=o,i=s.stderr??"",a=s.code,c=s.exitCode??1,l=ore(i,a,s.killed);throw new mc(`gh pr create failed (${l}): ${i.trim()}`,l,c,i)}}nl();function OB(t,e){let n;try{n=e?._store??new Ze}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}try{let r={type:"farm-decision",taskSlug:t.taskSlug,decision:t.decision,decidedAt:t.decidedAt,via:t.via};return{factId:n.storeFact({category:"decision",content:JSON.stringify(r),source_surface:"afk"})}}catch(r){return{skipped:!0,reason:r instanceof Error?r.message:String(r)}}}import{promises as sre}from"node:fs";import{join as ire}from"node:path";function LB(t){let e=t.filter(r=>r.score!==null),n=t.filter(r=>r.score===null).map(r=>r.index).sort((r,o)=>r-o);return e.sort((r,o)=>{let s=r.score,i=o.score,a=DB(s),c=DB(i);if(a!==c)return c-a;let l=FB(s.lint_ok),d=FB(i.lint_ok);return l!==d?d-l:s.loc_delta!==i.loc_delta?s.loc_delta-i.loc_delta:r.index-o.index}),[...e.map(r=>r.index),...n]}function DB(t){let e=t.pass+t.fail;return e===0?0:t.pass/e}function FB(t){return t===!0?2:t===!1?1:0}async function Kf(t,e={}){if(t.branches.length===0)throw new Error(`resolveWinnerBranch: farm ${t.taskSlug} has no branches`);let n=e.loadScore??are,r=await Promise.all(t.branches.map(async i=>({index:i.index,score:await n(t.farmDir,i.index)}))),o=LB(r),s=new Map(t.branches.map(i=>[i.index,i]));for(let i of o){let a=r.find(c=>c.index===i)?.score;if(a&&a.pass>0&&a.fail===0){let c=s.get(i);if(c)return{branch:c,source:"winner"}}}for(let i of o)if(r.find(c=>c.index===i)?.score){let c=s.get(i);if(c)return{branch:c,source:"top-scored"}}return{branch:t.branches[0],source:"fallback-first-branch"}}async function are(t,e){let n=ire(t,"scores",`branch-${e}.json`);try{let r=await sre.readFile(n,"utf8");return JSON.parse(r)}catch(r){return r.code==="ENOENT",null}}var qf="afk:f:";var cre=new Set(["p","d","r","x"]),lre=/^[a-z0-9T][a-z0-9T-]{0,62}$/;function NB(t){if(!t||!t.startsWith(qf)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(qf.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1);return!cre.has(r)||!lre.test(o)?null:{action:r,taskSlug:o}}var fre=pre(dre),uk=new Map;async function UB(t,e={}){let n=e.log??(()=>{}),r=mre(t),o=NB(r);if(!o){await me(t,"Unknown action",n);return}if(t.chat?.id===void 0){await me(t,"No chat context",n);return}let s=e.loadFarm??Hs,i;try{i=await s(o.taskSlug)}catch(a){n("[farm-callback] loadFarm failed:",a),await me(t,"Farm load failed",n);return}if(!i){await me(t,"Farm not found (already GC\u2019d?)",n);return}try{await gre(o.action,t,i,e,n)}catch(a){n("[farm-callback] dispatch error:",a),await me(t,"Internal error",n)}}function mre(t){return t.callbackQuery?.data}async function me(t,e,n){try{await t.answerCbQuery(e)}catch(r){n("[farm-callback] answerCbQuery failed:",r)}}async function gre(t,e,n,r,o){switch(t){case"x":return wre(e,n,r,o);case"d":return Sre(e,n,r,o);case"p":return $B(`p:${n.taskSlug}`,e,n,r,o,hre);case"r":return $B(`r:${n.taskSlug}`,e,n,r,o,bre)}}async function $B(t,e,n,r,o,s){let i=uk.get(t);if(i){o(`[farm-callback] ${t} \u2014 second tap, awaiting in-flight lock`);try{await i}catch{}let c=r.loadFarm??Hs,l;try{l=await c(n.taskSlug)}catch{await me(e,"Farm load failed",o);return}if(!l){await me(e,"Farm not found",o);return}return s(e,l,r,o)}let a=s(e,n,r,o);return uk.set(t,a),a.finally(()=>{uk.delete(t)}),a}async function hre(t,e,n,r){if(e.prUrl){await me(t,`PR already open: ${e.prUrl}`,r);return}await me(t,"Opening PR\u2026",r);let o=n.checkGhReady??PB,s;try{s=await o()}catch(g){r("[farm-callback] checkGhReady threw:",g);try{await t.reply("gh readiness check failed \u2014 see daemon logs")}catch{}return}if(!s.ok){try{await t.reply(s.hint)}catch{}return}let i=n.resolveWinnerBranch??Kf,a;try{a=await i(e)}catch(g){r("[farm-callback] resolveWinnerBranch failed:",g);try{await t.reply("Winner lookup failed")}catch{}return}let c=a.branch.branch,l=e.baseBranch??"main",d=`Auto PR: ${e.taskName}`,u=`Auto-generated by afk farm ${e.taskSlug} | winner: ${c} | created: ${new Date().toISOString()}`,p=n.createPr??MB,f;try{f=await p({base:l,head:c,title:d,body:u})}catch(g){if(g instanceof mc){let y={"not-found":"gh CLI not found \u2014 install with: brew install gh","already-exists":"PR already exists for this branch",unauthed:"gh is not authenticated \u2014 run: gh auth login",network:"Network error \u2014 check gh connectivity",timeout:"gh timed out \u2014 check connectivity",unknown:"gh pr create failed \u2014 see daemon logs"};try{await t.reply(y[g.kind])}catch{}return}r("[farm-callback] createPr failed:",g);try{await t.reply("gh pr create failed \u2014 see daemon logs")}catch{}return}let m=n.recordPrCreated??IB;try{await m(e.taskSlug,f)}catch(g){r("[farm-callback] recordPrCreated failed:",g)}try{await t.reply(`PR opened \u2713
|
|
1455
1455
|
\u{1F517} ${f}`)}catch(g){r("[farm-callback] reply failed:",g)}}function yre(t,e=()=>{}){e("[farm] spawning child afk process",{args:t});let n=ure("afk",t,{detached:!0,stdio:"ignore"});n.on("error",r=>{e("[farm] child spawn error",{args:t,err:r.message})}),n.on("exit",(r,o)=>{r!==0&&e("[farm] child exited with non-zero code",{args:t,code:r,signal:o})}),n.unref()}async function bre(t,e,n,r){if(e.respawnedAs){await me(t,`Already respawned as ${e.respawnedAs}`,r);return}if(e.branches.length===0){await me(t,"No branches remain \u2014 cannot respawn",r);return}await me(t,"Respawning\u2026",r);let o=n.resolveWinnerBranch??Kf,s;try{s=await o(e)}catch(u){r("[farm-callback] resolveWinnerBranch failed:",u);try{await t.reply("Winner lookup failed")}catch{}return}let i=s.branch,a=AB(e.taskName,{now:n._now,randomSuffix:n._randomSuffix}),c=e.branches.length;r("[farm] spawning child",{childSlug:a,baseRef:i.branch,branches:c});let l=n.spawnFarm??(u=>yre(u,r));try{l(["farm",e.taskName,"--branches",String(c),"--base-ref",i.branch,"--task-slug",a])}catch(u){r("[farm-callback] spawnFarm failed:",u);try{await t.reply("Respawn failed")}catch{}return}let d=n.recordRespawn??RB;try{await d(e.taskSlug,a)}catch(u){r("[farm-callback] recordRespawn failed:",u)}try{await t.reply(`Respawning as \`${a}\` from ${i.branch} \u2713
|
|
1456
1456
|
\u{1F504} Farm \`${e.taskSlug}\` respawned.
|
|
1457
1457
|
Child slug: \`${a}\`
|
|
@@ -1462,7 +1462,7 @@ Commits:
|
|
|
1462
1462
|
${l.stdout.trim()||"(none)"}
|
|
1463
1463
|
|
|
1464
1464
|
Stat:
|
|
1465
|
-
${d.stdout.trim()||"(no changes)"}`;await t.reply(u.slice(0,4e3))}catch(l){r("[farm-callback] diff failed:",l);try{await t.reply("Diff failed \u2014 see daemon logs.")}catch{}}}async function kre(t,e){let n=await fre("git",e,{cwd:t,maxBuffer:4194304});return{stdout:n.stdout,stderr:n.stderr}}Te();ha();import{TelegramError as vre}from"telegraf";function gc(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function hc(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}function Gf(t){return t instanceof vre}var lo=class extends Error{constructor(e){super(e),this.name="StreamTimeoutError"}};Qr();F();import
|
|
1465
|
+
${d.stdout.trim()||"(no changes)"}`;await t.reply(u.slice(0,4e3))}catch(l){r("[farm-callback] diff failed:",l);try{await t.reply("Diff failed \u2014 see daemon logs.")}catch{}}}async function kre(t,e){let n=await fre("git",e,{cwd:t,maxBuffer:4194304});return{stdout:n.stdout,stderr:n.stderr}}Te();ha();import{TelegramError as vre}from"telegraf";function gc(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function hc(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}function Gf(t){return t instanceof vre}var lo=class extends Error{constructor(e){super(e),this.name="StreamTimeoutError"}};Qr();F();import BKe from"string-width";var Tre=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,jKe=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function BB(t){return t.replace(Tre,"")}var Ere=/[\x00-\x1F\x7F-\x9F]/g;function Xf(t){return BB(t).replace(Ere," ").replace(/ {2,}/g," ").trim()}var pk=4,_re=[[["browser","web","fetch","scrape"],"Researching"],[["test","vitest","jest"],"Running tests"],[["bash","shell","exec","command"],"Running a command"]],Are=[[["search","grep","glob","find"],"Searching"],[["read","open","view","inspect"],"Reading files"],[["edit","write","patch","replace"],"Editing files"]];function zf(t){let e=Xf(t),n=new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean));for(let[o,s]of[..._re,...Are])if(o.some(i=>n.has(i)))return s;let r=e.replace(/[_-]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim();return r?`Using ${r}`:"Working"}function fk(t,e){let n=Xf(t??"").replace(/\s+/g," ").trim(),r=/^(working|processing|in progress|running)(?:\s*\([^)]*\))?$/i.test(n);return e&&(!n||r)?zf(e):n||(e?zf(e):"Working")}function mk(t){if(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(t))return"Sub-agent";let e=Xf(t).replace(/[_-]+/g," ").replace(/\s+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):"Sub-agent"}function gk(t,e){if(t<=0)return"";let n=e.slice(-pk),r=`\u{1F916} Sub-agents \xB7 ${t} ${t===1?"step":"steps"}`;return n.length>0?`
|
|
1466
1466
|
${r}
|
|
1467
1467
|
${n.join(`
|
|
1468
1468
|
`)}`:`
|
|
@@ -1500,7 +1500,7 @@ ${N}`,!0);continue}if(R.type==="chunk"&&R.chunk.type,R.type==="message"&&R.messa
|
|
|
1500
1500
|
|
|
1501
1501
|
\u{1F4A1} ${R.suggestion}`,await Se(c,t,s,y())),R.type==="notice"){let E=`
|
|
1502
1502
|
|
|
1503
|
-
_\u2139 ${R.text.replace(/[_*[\]()~`>#+\-=|{}.!]/g,"\\$&")}_`;c.accumulated+=E,await Se(c,t,s,y())}if(R.type==="paused"){await qB(R,w);continue}if(R.type==="resumed"){await GB(R,w);continue}if(R.type==="done"){await XB(R.metadata,w);break}R.type==="error"&&zB(R.error,w)}});let C=c.sentMessage;if(C&&!c.sawTerminalEvent){let T=i&&c.answerText.trim()?c.answerText:b();T.trim()&&await Vf(t,T)&&(await t.telegram.deleteMessage?.(s,C.message_id).catch(()=>{}),c.sentMessage=null)}else await JB(t,i,c.answerText,b(),C)}finally{(p.timedOut||!c.sawTerminalEvent)&&await Promise.resolve(e.interrupt?.()).catch(()=>{}),c.countdownInterval!==null&&(clearInterval(c.countdownInterval),c.countdownInterval=null),c.turnEnded=!0,g(),c.editInFlight=!1,p.apiRoundInFlight=!1,p.apiRoundSince=null,await Promise.resolve(_.return?.(void 0)).catch(()=>{})}}catch(v){throw r?.("Streaming error:",v),v}}async function Yf(t,e,n,r,o){if(!r.has(e))try{await Promise.race([n.waitForInitialization(),new Promise((a,c)=>setTimeout(()=>c(new Error("timeout")),5e3))]);let s=n.getSessionMetadata(),i=[{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"},{command:"cd",description:"Show or change session working directory"},{command:"name",description:"Show or set the session name"},{command:"usage",description:"Show Claude subscription usage"},{command:"sessions",description:"List and switch between sessions"},{command:"new",description:"Start a new session (keeps the current one)"}];if(s.slashCommands?.length)for(let a of s.slashCommands){let c=a.replace(/^\//,"");i.push({command:c,description:`SDK command: ${c}`})}if(s.skills?.length)for(let a of s.skills)i.push({command:a,description:`Run ${a} skill`});await t.telegram.setMyCommands(i,{scope:{type:"chat",chat_id:e}}),r.add(e),o(`Registered ${i.length} commands for chat ${e}`)}catch(s){o(`Could not register dynamic commands for chat ${e}:`,s)}}
|
|
1503
|
+
_\u2139 ${R.text.replace(/[_*[\]()~`>#+\-=|{}.!]/g,"\\$&")}_`;c.accumulated+=E,await Se(c,t,s,y())}if(R.type==="paused"){await qB(R,w);continue}if(R.type==="resumed"){await GB(R,w);continue}if(R.type==="done"){await XB(R.metadata,w);break}R.type==="error"&&zB(R.error,w)}});let C=c.sentMessage;if(C&&!c.sawTerminalEvent){let T=i&&c.answerText.trim()?c.answerText:b();T.trim()&&await Vf(t,T)&&(await t.telegram.deleteMessage?.(s,C.message_id).catch(()=>{}),c.sentMessage=null)}else await JB(t,i,c.answerText,b(),C)}finally{(p.timedOut||!c.sawTerminalEvent)&&await Promise.resolve(e.interrupt?.()).catch(()=>{}),c.countdownInterval!==null&&(clearInterval(c.countdownInterval),c.countdownInterval=null),c.turnEnded=!0,g(),c.editInFlight=!1,p.apiRoundInFlight=!1,p.apiRoundSince=null,await Promise.resolve(_.return?.(void 0)).catch(()=>{})}}catch(v){throw r?.("Streaming error:",v),v}}async function Yf(t,e,n,r,o){if(!r.has(e))try{await Promise.race([n.waitForInitialization(),new Promise((a,c)=>setTimeout(()=>c(new Error("timeout")),5e3))]);let s=n.getSessionMetadata(),i=[{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"},{command:"cd",description:"Show or change session working directory"},{command:"name",description:"Show or set the session name"},{command:"usage",description:"Show Claude subscription usage"},{command:"sessions",description:"List and switch between sessions"},{command:"new",description:"Start a new session (keeps the current one)"}];if(s.slashCommands?.length)for(let a of s.slashCommands){let c=a.replace(/^\//,"");i.push({command:c,description:`SDK command: ${c}`})}if(s.skills?.length)for(let a of s.skills)i.push({command:a,description:`Run ${a} skill`});await t.telegram.setMyCommands(i,{scope:{type:"chat",chat_id:e}}),r.add(e),o(`Registered ${i.length} commands for chat ${e}`)}catch(s){o(`Could not register dynamic commands for chat ${e}:`,s)}}ie();function ke(t){return[...[...t].map(r=>{if(r==="["||r==="]"||r==="@"||r==="("||r===")")return"";let o=r.codePointAt(0)??0;return o<32||o===127?" ":r}).join("").replace(/\s+/g," ").trim()].slice(0,64).join("")}function Ks(t,e){if(e!=="group"&&e!=="supergroup"||!t)return"";let n=ke([t.first_name??"",t.last_name??""].join(" ")),r=t.username?ke(t.username):"",o=typeof t.id=="number"&&Number.isFinite(t.id)?`id ${t.id}`:"",s=[n,r?`@${r}`:""].filter(Boolean).join(" "),i;if(s&&o)i=`${s} (${o})`;else if(s)i=s;else if(o)i=o;else return"";return`[from ${i}]: `}var oj=300;function kk(t){let n=[...t].map(o=>{if(o==="["||o==="]"||o==='"')return"";let s=o.codePointAt(0)??0;return s<32||s===127?" ":o}).join("").replace(/\s+/g," ").trim(),r=[...n];return r.length<=oj?n:r.slice(0,oj).join("")+"\u2026"}var sj="the assistant";function Hre(t,e){if(t&&typeof t.id=="number"&&Number.isFinite(t.id)&&e!==void 0&&t.id===e)return sj;if(!t)return"";let n=ke([t.first_name??"",t.last_name??""].join(" "));if(n&&n.toLowerCase()!==sj)return n;let r=t.username?ke(t.username):"";return r?`@${r}`:""}function yc(t){let{replyToMessage:e,quote:n,botId:r}=t,o=n?.text??"";if(!e&&o.length===0)return"";let s=Hre(e?.from,r),i=kk(o)||kk(e?.text??"")||kk(e?.caption??"");return i?s?`[in reply to ${s}: "${i}"] `:`[in reply to: "${i}"] `:e?s?`[in reply to ${s}'s message] `:"[in reply to an earlier message] ":""}function Wre(t){let{first_name:e="",last_name:n="",username:r}=t.sender_user,o=ke(`${e} ${n}`.trim()),s=r?ke(r):"";return[o,s?`@${s}`:""].filter(Boolean).join(" ")}function Kre(t){return ke(t.sender_user_name)}function qre(t){let e=t.sender_chat,n=ke(e.title??""),r=e.username?ke(e.username):"";return[n,r?`@${r}`:""].filter(Boolean).join(" ")}function Gre(t){let e=t.chat,n=ke(e.title??""),r=e.username?ke(e.username):"";return[n,r?`@${r}`:""].filter(Boolean).join(" ")}function Xre(t){let e=ke(`${t.first_name??""} ${t.last_name??""}`.trim()),n=t.username?ke(t.username):"";return[e,n?`@${n}`:""].filter(Boolean).join(" ")}function bc(t){let e="";if(t.forward_origin){let n=t.forward_origin;n.type==="user"?e=Wre(n):n.type==="hidden_user"?e=Kre(n):n.type==="chat"?e=qre(n):n.type==="channel"?e=Gre(n):console.warn(`[forward-provenance] unknown forward_origin.type "${n.type}" \u2014 Bot API may have added a new origin type`)}if(!e&&t.forward_from&&(e=Xre(t.forward_from)),!e&&t.forward_from_chat){let n=t.forward_from_chat,r=ke(n.title??""),o=n.username?ke(n.username):"";e=[r,o?`@${o}`:""].filter(Boolean).join(" ")}return!e&&t.forward_sender_name&&(e=ke(t.forward_sender_name)),e?`[forwarded from ${e}] `:""}Ga();var ij=5*1024*1024,zre=new Set(["txt","md","json","yaml","yml","xml","csv","log","py","js","ts","sh","toml","ini","cfg","conf","html","css","sql","rb","go","rs","java","c","cpp","h","jsx","tsx","kt","swift","r","pl","lua","php","bat","ps1"]),Jre="text/code files (.txt, .md, .py, .js, .ts, .json, .yaml, etc.) or PDF";function Vre(t){return t.replace(/\/bot[^/]+\//g,"/bot[REDACTED]/")}function Yre(t,e){let n=(t??"").toLowerCase().split(";")[0]?.trim()??"";if(n==="application/pdf")return"pdf";if(n.startsWith("text/"))return"text";let r=(e??"").split(".").pop()?.toLowerCase()??"";return zre.has(r)?"text":"unsupported"}async function Qre(t,e){let n=t.headers.get("content-length");if(n!=null){let a=Number(n);if(Number.isFinite(a)&&a>e)return{status:"too-large",bytesRead:a}}let r=t.body;if(!r)return{status:"missing-body"};let o=r.getReader(),s=[],i=0;try{for(;;){let{done:a,value:c}=await o.read();if(a)break;if(i+=c.byteLength,i>e)return await o.cancel().catch(()=>{}),{status:"too-large",bytesRead:i};s.push(Buffer.from(c))}}finally{o.releaseLock()}return{status:"ok",bytes:Buffer.concat(s,i)}}async function aj(t,e){let n=t.message,r=n?.document;if(!n||!r)return e("Document handling: missing message or document field"),null;let o=t.chat?.id,s=r.file_name,i=r.mime_type;if(r.file_size!=null&&r.file_size>ij)return e(`Document handling: oversized file (${r.file_size} bytes) for chat ${o??"(unknown)"}`),await t.reply("\u274C Document is too large (max 5 MB). Please send a smaller file."),null;let a=Yre(i,s);if(a==="unsupported")return e(`Document handling: unsupported type mime=${i??"(none)"} name=${s??"(none)"} for chat ${o??"(unknown)"}`),await t.reply(`\u274C Unsupported file type. Please send ${Jre}.`),null;let c;try{let m=await t.telegram.getFileLink(r.file_id),g=m instanceof URL?m:new URL(String(m));if(g.protocol!=="https:"||g.hostname!=="api.telegram.org"||g.port!==""&&g.port!=="443")return e(`Document handling: unexpected file URL (protocol=${g.protocol} hostname=${g.hostname}) for chat ${o??"(unknown)"}`),await t.reply("\u274C Couldn't download the document. Please try resending."),null;let y=await globalThis.fetch(g.href,{signal:AbortSignal.timeout(15e3),redirect:"error"});if(!y.ok)return e(`Document handling: fetch failed status=${y.status} for chat ${o??"(unknown)"}`),await t.reply("\u274C Couldn't download the document. Please try resending."),null;let b=await Qre(y,ij);if(b.status==="too-large")return e(`Document handling: downloaded file (${b.bytesRead} bytes) exceeds limit for chat ${o??"(unknown)"}`),await t.reply("\u274C Document is too large (max 5 MB). Please send a smaller file."),null;if(b.status==="missing-body")return e(`Document handling: fetch response had no body for chat ${o??"(unknown)"}`),await t.reply("\u274C Couldn't download the document. Please try resending."),null;c=b.bytes}catch(m){let g=m instanceof Error?m.message:String(m);return e("Document handling download error:",Vre(g)),await t.reply("\u274C Couldn't download the document. Please try resending."),null}let l=[],d=Ks(n.from,t.chat?.type),u=yc({replyToMessage:n.reply_to_message,botId:t.botInfo?.id}),p=bc(n),f=u+p+d;if(n.caption!=null){let m=[...n.caption].slice(0,1024).join("");l.push({type:"text",text:`${f}[User caption]: ${m}`})}else f&&l.push({type:"text",text:`${f}(document, no caption)`});if(a==="text"){let m=s??"document",g=c.toString("utf8");l.push({type:"text",text:`\u{1F4CE} Document: ${m}
|
|
1504
1504
|
|
|
1505
1505
|
${g}`})}else{let m=c.toString("base64");l.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:m}})}return l}function cj(t){return t.length<3?null:t.length>=4&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":null}async function lj(t,e){let n=t.headers.get("content-length");if(n!=null){let a=Number(n);if(Number.isFinite(a)&&a>e)return{status:"too-large",bytesRead:a}}let r=t.body;if(!r)return{status:"missing-body"};let o=r.getReader(),s=[],i=0;try{for(;;){let{done:a,value:c}=await o.read();if(a)break;if(i+=c.byteLength,i>e)return await o.cancel().catch(()=>{}),{status:"too-large",bytesRead:i};s.push(Buffer.from(c))}}finally{o.releaseLock()}return{status:"ok",bytes:Buffer.concat(s,i)}}function Ok(t,e,n,r,o){if(n!==void 0&&n===r)return!0;if(!e||e.length===0)return!1;let s=o?`@${o.toLowerCase()}`:void 0;for(let i of e){if(i.type==="text_mention"){if(i.user?.id===r)return!0;continue}if(i.type==="mention"&&s&&t!==void 0&&t.slice(i.offset,i.offset+i.length).toLowerCase()===s)return!0}return!1}var nm=class t{static MAX_QUEUE_DEPTH=5;sessionManager;messageQueues=new Map;registeredCommandChats;log;bot;claimedChats=new Map;reserveClaim(e){this.claimedChats.set(e,(this.claimedChats.get(e)??0)+1)}releaseClaim(e){let n=(this.claimedChats.get(e)??0)-1;n<=0?this.claimedChats.delete(e):this.claimedChats.set(e,n)}isClaimed(e){return(this.claimedChats.get(e)??0)>0}pendingElicitations=new Map;ledgerOriginatedPendingChats=new Set;tagOnlyChats;constructor(e,n,r,o,s=new Set){this.bot=e,this.sessionManager=n,this.registeredCommandChats=r,this.log=o,this.tagOnlyChats=s}async handlePhoto(e){let n=ae(e),r=n?.chatId,o=e.message,s=o?.photo;if(!n||!r||!s?.length){this.log(`Photo handling: missing chatId or photo array for chat ${r??"(unknown)"}`);return}if(this.tagOnlyChats.has(r)){let d=e.botInfo?.id;if(d===void 0){this.log(`[tag-only] Dropping photo in chat ${r}: bot identity unknown (botInfo missing)`);return}if(!Ok(o?.caption,o?.caption_entities,o?.reply_to_message?.from?.id,d,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed photo in chat ${r}`);return}}this.log(`\u{1F4F7} Photo from chat ID: ${r}`),await e.react?.("\u{1F440}").catch(()=>{});let i=s[s.length-1];if(!i){this.log(`Photo handling: empty photo array for chat ${r}`);return}let a=5*1024*1024;if(i.file_size!=null&&i.file_size>a){this.log(`Photo handling: oversized file (${i.file_size} bytes) rejected for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}let c=o?.caption,l=!1;try{l=this.isClaimed(G(n)),l||this.reserveClaim(G(n));let d=await this.sessionManager.getSession(n);if(Yf(this.bot,r,d,this.registeredCommandChats,this.log).catch(T=>this.log("Failed to register chat commands:",T)),(d.state!=="idle"||l)&&(this.messageQueues.get(G(n))?.length??0)>=t.MAX_QUEUE_DEPTH){await e.reply("\u23F3 Queue full. Please wait for your messages to be processed.");return}let u=await e.telegram.getFileLink(i.file_id),p=u instanceof URL?u:new URL(String(u));if(p.protocol!=="https:"||p.hostname!=="api.telegram.org"||p.port!==""&&p.port!=="443"){this.log(`Photo handling: unexpected file URL (protocol=${p.protocol} hostname=${p.hostname}) rejected for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let f=await globalThis.fetch(p.href,{signal:AbortSignal.timeout(15e3),redirect:"error"});if(!f.ok){this.log(`Photo handling: fetch failed with status ${f.status} for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let m=await lj(f,a);if(m.status==="too-large"){this.log(`Photo handling: downloaded file (${m.bytesRead} bytes) exceeds limit for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}if(m.status==="missing-body"){this.log(`Photo handling: fetch response had no body for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let g=m.bytes,y=["image/jpeg","image/png","image/gif","image/webp"],b=f.headers.get("content-type")??"",w=(b.split(";")[0]?.trim()??"").toLowerCase(),v;if(y.includes(w))v=w;else{let T=cj(g);if(T!==null)this.log(`Photo: sniffed ${T} (Content-Type was "${b}") for chat ${r}`),v=T;else{this.log(`Photo: unrecognised image format for chat ${r} (Content-Type: "${b}")`),await e.reply("\u274C Unsupported image format. Please send a JPEG, PNG, GIF, or WebP.");return}}let _=Ks(o?.from,e.chat?.type),x=yc({replyToMessage:o?.reply_to_message,quote:o?.quote,botId:e.botInfo?.id}),A=bc(o??{}),I=x+A+_,C=[];if(c!=null?C.push({type:"text",text:`${I}[User caption]: ${[...c].slice(0,1024).join("")}`}):I&&C.push({type:"text",text:`${I}(image, no caption)`}),await d.waitForInitialization(),d.sessionId===void 0)throw new Error("Telegram session initialized without a session id");if(await $F(C,d.sessionId,[{mediaType:v,bytes:g}]),d.state!=="idle"||l){let T=this.enqueuePhoto(n,e,C);T!==!1&&await e.reply(di(T));return}await this.processOne(n,e,C)}catch(d){let p=(d instanceof Error?d.message:String(d)).replace(/\/bot[^/]+\//g,"/bot[REDACTED]/");this.log("Photo handling error:",p),Gf(d)?await e.reply("\u274C Couldn't reach Telegram to fetch that image. Please try resending."):gc(d)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):hc(d)?await e.reply("\u274C Couldn't download the image. Please try resending."):await e.reply(bl())}finally{l||this.releaseClaim(G(n))}}async handleDocument(e){let n=ae(e);if(!n)return;let r=n.chatId;if(this.tagOnlyChats.has(r)){let i=e.botInfo?.id;if(i===void 0){this.log(`[tag-only] Dropping document in chat ${r}: bot identity unknown (botInfo missing)`);return}let a=e.message;if(!Ok(a?.caption,a?.caption_entities,a?.reply_to_message?.from?.id,i,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed document in chat ${r}`);return}}let o=G(n),s=!1;try{s=this.isClaimed(o),s||this.reserveClaim(o);let i=await this.sessionManager.getSession(n);if(Yf(this.bot,n.chatId,i,this.registeredCommandChats,this.log).catch(c=>this.log("Failed to register chat commands:",c)),(i.state!=="idle"||s)&&(this.messageQueues.get(o)?.length??0)>=t.MAX_QUEUE_DEPTH){await e.reply("\u23F3 Queue full. Please wait for your messages to be processed.");return}let a=await aj(e,this.log);if(a===null)return;if(i.state!=="idle"||s){let c=this.enqueueDocument(n,e,a);c!==!1&&await e.reply(di(c));return}await this.processOne(n,e,a)}catch(i){let a=i instanceof Error?i.message:String(i);this.log("Document handling error:",a.replace(/\/bot[^/]+\//g,"/bot[REDACTED]/")),await e.reply("\u274C An error occurred processing your document. Please try again.")}finally{s||this.releaseClaim(o)}}async handle(e){let n=ae(e),r=n?.chatId,o=e.message.text;if(!n||!r||!o)return;let s=G(n);if(this.log(`\u{1F4EC} Message from chat ID: ${r}`),o.startsWith("/"))return;let i=e.message,a=yc({replyToMessage:i.reply_to_message,quote:i.quote,botId:e.botInfo?.id}),c=bc(i),l=a+c+Ks(i.from,e.chat?.type)+o,d=Ks(i.from,e.chat?.type)+o;if(i.reply_to_message?.message_id!==void 0){let{matchReplyToHandoff:f}=await Promise.resolve().then(()=>(tm(),Mk));if(await f(this.bot,r,i.reply_to_message.message_id,o))return}let u=this.pendingElicitations.get(s);if(u){if(this.ledgerOriginatedPendingChats.has(s)){this.pendingElicitations.delete(s),this.ledgerOriginatedPendingChats.delete(s),u(d);return}let f=this.sessionManager.getSessionIfExists(n);if(f&&f.state!=="idle"){this.pendingElicitations.delete(s),u(d);return}this.log("[message] dropping stale pendingElicitation for route",s),this.pendingElicitations.delete(s)}if(this.tagOnlyChats.has(r)){let f=e.botInfo?.id;if(f===void 0){this.log(`[tag-only] Dropping message in chat ${r}: bot identity unknown (botInfo missing)`);return}let m=e.message;if(!Ok(m.text,m.entities,m.reply_to_message?.from?.id,f,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed message in chat ${r}`);return}}let p=!1;try{await e.react?.("\u{1F440}").catch(()=>{}),p=this.isClaimed(G(n)),p||this.reserveClaim(G(n));let f=await this.sessionManager.getSession(n);Yf(this.bot,r,f,this.registeredCommandChats,this.log).catch(g=>this.log("Failed to register chat commands:",g));let m=l;if(f.state!=="idle"||p){let g=this.enqueueMessage(n,e,m);g!==!1&&await e.reply(di(g));return}await this.processOne(n,e,m)}catch(f){this.log("Message handling error:",f),Gf(f)||(gc(f)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):hc(f)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(bl()))}finally{p||this.releaseClaim(G(n))}}async processClearDirect(e,n){this.reserveClaim(G(e));try{await this.sessionManager.resetSession(e),this.registeredCommandChats.delete(e.chatId),await n.reply(Sl())}catch(r){this.log("Clear error:",r),await n.reply(X(r))}finally{this.releaseClaim(G(e))}}async processCompactDirect(e,n){this.reserveClaim(G(e));let r=!1;try{let o=await this.sessionManager.getSession(e),s=o.hookRegistry,i=await ui(n,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));if(i.reason==="session-busy"){this.enqueueCompact(e,n),r=!0;return}i.reason==="microcompacted"&&i.microcompaction?await n.reply(KT(i.microcompaction)):i.compacted?await n.reply(kl({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await n.reply(vl(i.reason??"unknown"))}catch(o){o instanceof ee?await n.reply(`Compaction skipped: ${ge(o.reason??"blocked by hook")}`):(this.log("Compact error (queued):",o),await n.reply(X(o)))}finally{r||this.drainQueue(e).catch(o=>this.log("Drain error:",o)),this.releaseClaim(G(e))}}queueFor(e){let n=G(e),r=this.messageQueues.get(n);return r||(r=[],this.messageQueues.set(n,r)),r}enqueueMessage(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"message",ctx:n,text:r}),o.length)}enqueuePhoto(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"photo",ctx:n,content:r}),o.length)}enqueueDocument(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"document",ctx:n,content:r}),o.length)}enqueueClear(e,n){let r=this.queueFor(e);if(r.length>=t.MAX_QUEUE_DEPTH){n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{});return}r.push({type:"clear",ctx:n})}enqueueCompact(e,n){let r=this.queueFor(e);if(r.length>=t.MAX_QUEUE_DEPTH){n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{});return}r.push({type:"compact",ctx:n})}async processOne(e,n,r){this.reserveClaim(G(e));let o=!1;try{let s=await this.sessionManager.getSession(e),i=typeof r=="string"?r:r.map(a=>a.type==="text"?a.text:a.type==="document"?`[document: ${a.title??"file"}]`:"[image]").join(" ");await ui(n,()=>rj(n,s,r,this.log,{cleanFinal:!0,onComplete:(a,c)=>{this.sessionManager.recordTelegramTurn(e,i,a,c)}}))}catch(s){if(this.log("Message handling error:",s),(s?.message??"").includes("session is busy")){let a=typeof r=="string"?this.enqueueMessage(e,n,r):r.some(c=>c.type==="document")?this.enqueueDocument(e,n,r):this.enqueuePhoto(e,n,r);a!==!1&&await n.reply(di(a)),o=!0;return}s instanceof lo?await n.reply(`\u23F1\uFE0F ${s.message}`):Gf(s)||(gc(s)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):hc(s)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(bl()))}finally{o||this.drainQueue(e).catch(s=>this.log("Drain error:",s)),this.releaseClaim(G(e))}}async drainQueue(e){let n=G(e),r=this.messageQueues.get(n);if(!r?.length)return;let o=r.shift();r.length===0&&this.messageQueues.delete(n),o.type==="message"?await this.processOne(e,o.ctx,o.text):o.type==="photo"||o.type==="document"?await this.processOne(e,o.ctx,o.content):o.type==="compact"?await this.processCompactDirect(e,o.ctx):await this.processClearDirect(e,o.ctx)}};qi();import{Markup as _c}from"telegraf";xk();Te();Kr();import{randomBytes as poe}from"node:crypto";function foe(){return`elic-${poe(8).toString("hex")}`}var xj=-1;function moe(t,e=64){if(Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.from(t,"utf8").subarray(0,e);return new TextDecoder("utf-8",{fatal:!1}).decode(n).replace(/\uFFFD$/,"")}function rm(t,e,n,r){let o=()=>typeof n=="function"?n():typeof n=="number"?{chatId:n}:n,s=r?.ledgerOriginated??!1,i=new Map,a=new RegExp(`^${Pe(Sc)}\\d+:.+$`);e.action(a,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=hj(d);if(!u)return;let p=i.get(u.id);p&&l.chat?.id===p.chatId&&p.resolve(u.choiceIndex)});let c=new RegExp(`^${Pe(kc)}.+$`);return e.action(c,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=bj(d);if(!u)return;let p=i.get(u);p&&l.chat?.id===p.chatId&&p.resolve(xj)}),async(l,d)=>{if(d.signal.aborted)return{action:"decline"};let u=(d.sessionId!==void 0?cl(d.sessionId):void 0)??o(),p=u.chatId,f=G(u),m=Tn(u);function g(_){t.pendingElicitations.set(f,_),s&&t.ledgerOriginatedPendingChats.add(f)}function y(){t.pendingElicitations.delete(f),s&&t.ledgerOriginatedPendingChats.delete(f)}let b=l.type??"text",w=l.message,v=`\u{1F4AC} <b>Question from agent</b>
|
|
1506
1506
|
|
|
@@ -1524,11 +1524,11 @@ Enter a number${R}`}I&&(l.allowSkip?T+=`
|
|
|
1524
1524
|
<i>Type :cancel to cancel.</i>`),e.telegram.sendMessage(p,T,{parse_mode:"HTML",...m}).catch(()=>{x||(x=!0,d.signal.removeEventListener("abort",A),console.warn("[elicitation-handler] sendMessage failed; declining elicitation for route",f),y(),_({action:"decline"}))})})}}B();import{existsSync as goe,mkdirSync as hoe,readFileSync as yoe,renameSync as boe,writeFileSync as woe}from"fs";import{dirname as Soe,isAbsolute as koe}from"path";import{randomUUID as voe}from"node:crypto";var Dk={version:1,grants:[]},Rj="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function Fk(t=Date.now()){let e=t,n=new Array(10).fill("0");for(let o=9;o>=0;o--)n[o]=Rj[e%32],e=Math.floor(e/32);let r=new Array(16).fill("0");for(let o=0;o<16;o++)r[o]=Rj[Math.floor(Math.random()*32)];return n.join("")+r.join("")}function Cj(t=oi()){if(!goe(t))return Dk;try{let e=yoe(t,"utf8"),n=JSON.parse(e);return typeof n!="object"||n===null||!("version"in n)||n.version!==1||!("grants"in n)||!Array.isArray(n.grants)?Dk:{version:1,grants:n.grants.filter(Toe)}}catch(e){return console.warn(`[permissions] could not parse ${t} \u2014 treating as empty (persisted grants reset): `+(e instanceof Error?e.message:String(e))),Dk}}function Toe(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.path=="string"&&koe(e.path)&&(e.mode==="read"||e.mode==="write")&&(e.decision==="allow"||e.decision==="deny")&&typeof e.grantedAt=="string"&&(e.source==="elicit:repl"||e.source==="elicit:telegram"||e.source==="elicit:web"||e.source==="elicit:unknown"||e.source==="manual")}function Pj(t,e=oi()){let n=Cj(e),r={id:Fk(),grantedAt:t.grantedAt??new Date().toISOString(),path:t.path,mode:t.mode,decision:t.decision,source:t.source,...t.reason!==void 0?{reason:t.reason}:{},...t.expiresAt!==void 0?{expiresAt:t.expiresAt}:{}},o={version:1,grants:[...n.grants,r]};return Eoe(e,o),r}function Ij(t,e=oi()){let n=Cj(e),r=Date.now();return n.grants.filter(o=>o.decision==="allow").filter(o=>o.mode===t||t==="read"&&o.mode==="write").filter(o=>{if(o.expiresAt===void 0)return!0;let s=Date.parse(o.expiresAt);return Number.isFinite(s)?s>r:!0}).map(o=>o.path)}function qs(t,e=oi()){for(let n of Ij("read",e))t.addReadRoot(n,"tool");for(let n of Ij("write",e))t.addWriteRoot(n,"tool")}function Eoe(t,e){hoe(Soe(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${voe()}`;woe(n,JSON.stringify(e,null,2)+`
|
|
1525
1525
|
`,{encoding:"utf8",mode:384}),boe(n,t)}Kr();var xc="afk:pa:",_oe=64,Ac=new Map;function om(t,e,n=()=>{},r){let o=t;if(!o._elicitationRegistered){let s=new RegExp(`^${Pe(xc)}`);t.action(s,async i=>Aoe(i,n)),o._elicitationRegistered=!0}return async(s,i)=>{if(i.signal.aborted)return{action:"decline"};let a=i.sessionId!==void 0?cl(i.sessionId):void 0;return new Promise(c=>{let l=Fk(),d=xoe(s);Ac.set(l,{resolve:c,enumValues:d});let u=Roe(s),p=Ioe(l,d),f=Array.from(e).map(async m=>{try{let g=a??r?.(m);await t.telegram.sendMessage(m,u,{reply_markup:p,...g!==void 0?Tn(g):{}})}catch(g){n("[elicitation] sendMessage failed:",g)}});Promise.all(f),i.signal.addEventListener("abort",()=>{let m=Ac.get(l);m&&(Ac.delete(l),m.resolve({action:"decline"}))},{once:!0})})}}async function Aoe(t,e){let n=t.callbackQuery?.data;if(typeof n!="string"||!n.startsWith(xc)){await t.answerCbQuery("Unknown callback").catch(()=>{});return}let r=n.slice(xc.length),o=r.indexOf(":");if(o<=0||o===r.length-1){await t.answerCbQuery("Malformed callback").catch(()=>{});return}let s=r.slice(0,o),i=r.slice(o+1),a=Ac.get(s);if(!a){await t.answerCbQuery("This prompt is no longer active.").catch(()=>{});return}if(!a.enumValues.includes(i)){e("[elicitation] callback choice not in enum:",i,a.enumValues),await t.answerCbQuery("Unknown choice").catch(()=>{});return}Ac.delete(s),a.resolve({action:"accept",content:{choice:i}}),await t.answerCbQuery(`Recorded: ${i}`).catch(c=>{e("[elicitation] answerCbQuery failed:",c)})}function xoe(t){if(t.mode!=="form")return["accept","decline"];let e=t.requestedSchema;if(typeof e!="object"||e===null)return["accept","decline"];let n=e.properties;if(typeof n!="object"||n===null)return["accept","decline"];let r=Object.keys(n)[0];if(r===void 0)return["accept","decline"];let o=n[r];if(typeof o!="object"||o===null)return["accept","decline"];let s=o.enum;return Array.isArray(s)?s.map(String):["accept","decline"]}function Roe(t){let e=[];t.title&&e.push(t.title),e.push(t.message);let n=e.join(`
|
|
1526
1526
|
|
|
1527
|
-
`);return n.length>4e3?n.slice(0,3997)+"...":n}function Ioe(t,e){let n=xc.length+t.length+1,r=_oe-n,o=e.map(s=>{let i=s.length<=r?s:s.slice(0,r);return{text:Coe(i),callback_data:`${xc}${t}:${i}`}});return o.length===4?{inline_keyboard:[[o[0],o[1]],[o[2],o[3]]]}:{inline_keyboard:o.map(s=>[s])}}function Coe(t){switch(t){case"once":return"\u2705 Once";case"session":return"\u{1F501} Session";case"persist":return"\u{1F4BE} Always";case"deny":return"\u274C Deny";case"accept":return"\u2705 Accept";case"decline":return"\u274C Decline";default:return t.charAt(0).toUpperCase()+t.slice(1)}}function sm(t,e){return(n,r)=>n.type!==void 0?t(n,r):e(n,r)}$n();Xn();la();Ar();import*as im from"node:fs";B();import{createHmac as Poe,randomBytes as Moe,timingSafeEqual as
|
|
1527
|
+
`);return n.length>4e3?n.slice(0,3997)+"...":n}function Ioe(t,e){let n=xc.length+t.length+1,r=_oe-n,o=e.map(s=>{let i=s.length<=r?s:s.slice(0,r);return{text:Coe(i),callback_data:`${xc}${t}:${i}`}});return o.length===4?{inline_keyboard:[[o[0],o[1]],[o[2],o[3]]]}:{inline_keyboard:o.map(s=>[s])}}function Coe(t){switch(t){case"once":return"\u2705 Once";case"session":return"\u{1F501} Session";case"persist":return"\u{1F4BE} Always";case"deny":return"\u274C Deny";case"accept":return"\u2705 Accept";case"decline":return"\u274C Decline";default:return t.charAt(0).toUpperCase()+t.slice(1)}}function sm(t,e){return(n,r)=>n.type!==void 0?t(n,r):e(n,r)}$n();Xn();la();Ar();import*as im from"node:fs";B();import{createHmac as Poe,randomBytes as Moe,timingSafeEqual as n2e}from"node:crypto";var Mj="\0";function Ooe(t){return JSON.stringify(Lk(t))}function Lk(t){if(Array.isArray(t))return t.map(Lk);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=Lk(e[r]);return n}return t}function am(t){let e;try{e=Uv(t)}catch{return null}try{let n=im.readFileSync(e,"utf8").trim();return n.length>0?n:null}catch{return null}}function Oj(t,e){return Poe("sha256",t).update(e).digest("hex")}function Doe(t,e,n){return["elicitation_response",t,e,Ooe(n)].join(Mj)}function Dj(t,e,n,r){return Oj(t,Doe(e,n,r))}function Foe(t,e){return["abort_request",t,e].join(Mj)}function Fj(t,e,n){return Oj(t,Foe(e,n))}function Lj(){return Moe(8).toString("hex")}var Loe=1500,Nj=700,Nk=160,Noe=15*6e4,$oe=4;function Rc(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e)}\u2026`:n}function Uoe(t){switch(t.kind){case"meta":return`\u{1F4E1} Watching session ${t.sessionId}
|
|
1528
1528
|
model: ${t.model}${t.cwd?`
|
|
1529
1529
|
cwd: ${t.cwd}`:""}`;case"user":return`\u{1F464} ${Rc(t.text,Nj)}`;case"assistant":return`\u{1F916} ${Rc(t.text,Nj)}`;case"tool":return`\u{1F527} ${t.toolName}(${Rc(t.input,Nk)})`;case"tool_error":return`\u26A0\uFE0F tool failed: ${Rc(t.content,Nk)}`;case"done":{let e=[];return typeof t.durationMs=="number"&&e.push(`${(t.durationMs/1e3).toFixed(1)}s`),typeof t.costUsd=="number"&&e.push(`$${t.costUsd.toFixed(4)}`),`\u2705 turn done${e.length?` (${e.join(", ")})`:""}`}case"error":return`\u274C error: ${Rc(t.message,Nk)}`;case"paused":return`\u23F8\uFE0F paused on usage limit${t.resetsAt?` (resets ${t.resetsAt})`:""}`;case"resumed":return"\u25B6\uFE0F resumed";case"closed":return`\u{1F3C1} session closed${t.reason?` (${t.reason})`:""} \u2014 watch ended`;default:return null}}async function $j(t){let e=ng(t);return e?.data.sessionId&&await ca(e.data.sessionId)?e.data.sessionId:await ca(t)?t:null}async function Uj(){let t=[],n=(await Di()).filter(s=>s.surface!=="telegram");if(n.length>0){t.push("\u{1F7E2} Live sessions:");for(let s of n)t.push(` ${s.sessionId} (${s.surface}, ${s.cwd})`)}let r=Eo().filter(s=>s.source!=="telegram").slice(0,8),o=[];for(let s of r)s.sessionId&&await ca(s.sessionId)&&o.push(` ${s.name??s.id} (${s.model})`);return o.length>0&&(t.length>0&&t.push(""),t.push("\u{1F4BE} Recent sessions with activity logs:",...o)),t.length===0?"No watchable sessions found. Start one with `afk i` on your machine, then /watch <session-id-or-name>.":(t.push("","Watch one with /watch <session-id-or-name>."),t.join(`
|
|
1530
1530
|
`))}var cm=class{watches=new Map;log;bot;messageHandler;elicitHeartbeatMs;constructor(e=()=>{},n,r,o=Noe){this.log=e,this.bot=n,this.messageHandler=r,this.elicitHeartbeatMs=o}watching(e){return this.watches.get(e)?.sessionId}getWatched(e){return this.watches.get(e)?.sessionId}start(e,n,r,o=()=>({chatId:e})){this.stop(e);let s=new AbortController,i=this._run(e,n,r,o,s.signal).catch(a=>{this.log("watch loop error:",a)});this.watches.set(e,{sessionId:n,abort:s,finished:i})}stop(e){let n=this.watches.get(e);if(n)return this.watches.delete(e),n.abort.abort(),n.sessionId}async stopAll(){let e=[...this.watches.values()];this.watches.clear();for(let n of e)n.abort.abort();await Promise.allSettled(e.map(n=>n.finished))}async _run(e,n,r,o,s){let i=[],a=null,c=Promise.resolve(),l=this.bot!==void 0&&this.messageHandler!==void 0?sm(rm(this.messageHandler,this.bot,o,{ledgerOriginated:!0}),om(this.bot,new Set([e]),(...u)=>this.log("[elicitation]",...u),o)):void 0,d=()=>{if(a=null,i.length===0)return;let u=i.join(`
|
|
1531
|
-
`);i=[],c=c.then(()=>r(u)).catch(p=>this.log("watch send error:",p))};try{for await(let u of Hy(n,{signal:s})){if(u.kind==="elicitation"&&l!==void 0){a&&clearTimeout(a),d(),await c;let f=Date.now(),m=0,g=setInterval(()=>{if(m>=$oe){clearInterval(g);return}m+=1;let w=Math.round((Date.now()-f)/6e4);r(`\u23F3 Still waiting on your answer (${w}m elapsed) \u2014 no deadline, reply above whenever you're ready. (Send /unwatch to stop watching this session.)`).catch(()=>{})},this.elicitHeartbeatMs);g.unref?.();let y=await(async()=>{try{return await l(u.request,{signal:s})}finally{clearInterval(g)}})(),b=am(n);if(b!==null){let w=Dj(b,n,u.reqId,y);new Nn(n).record({kind:"elicitation_response",reqId:u.reqId,result:y,hmac:w})}else this.log("[watch] no session key for",n,"\u2014 skipping elicitation write-back");continue}let p=Uoe(u);if(p){if(i.push(p),u.kind==="closed"){d();break}a||(a=setTimeout(d,Loe),a.unref?.())}}a&&clearTimeout(a),d(),await c}finally{a&&clearTimeout(a);let u=this.watches.get(e);u&&u.sessionId===n&&u.abort.signal===s&&this.watches.delete(e)}}};Te();Te();async function Bj(t,e,n,r,o){let{chatId:s}=e,a=((t.message&&"text"in t.message?t.message.text:"")??"").split(/\s+/).slice(1).join(" ").trim();try{if(!a){await t.reply(await Uj());return}let c=await $j(a);if(!c){await t.reply(`No session ledger found for "${a}". Use /watch with no argument to list watchable sessions.`);return}let l=async d=>{for(let u of Ge(d))await t.telegram.sendMessage(s,u,r)};n.start(s,c,l),await t.reply(`\u{1F4E1} Watching ${c} \u2014 new activity will stream here. /unwatch to stop.`)}catch(c){o("Watch error:",c),await t.reply(X(c))}}Ar();la();Te();Kr();var lm=class t{bot;sessionManager;options;running=!1;registeredCommandChats=new Set;messageHandler;watchManager;autoSubscribeInterval=null;static AUTO_SUBSCRIBE_INTERVAL_MS=5e3;constructor(e){this.options=e,this.bot=new Boe(e.botToken,{handlerTimeout:1/0}),this.sessionManager=new yl({...e,onResumptionOffer:(n,r)=>this.bot.telegram.sendMessage(n.chatId,r,Tn(n)).then(()=>!0).catch(()=>!1)}),this.messageHandler=new nm(this.bot,this.sessionManager,this.registeredCommandChats,this.log.bind(this),e.tagOnlyChats??new Set),this.watchManager=new cm(this.log.bind(this),this.bot,this.messageHandler),this.setupHandlers()}setupHandlers(){this.bot.use(FA(this.options.allowedChatIds,this.log.bind(this))),this.bot.command("start",r=>ig(r)),this.bot.command("help",r=>ag(r,this.sessionManager)),this.bot.command("clear",async r=>{let o=ae(r);if(!o){await r.reply(X("Could not identify chat"));return}(await this.sessionManager.getSession(o)).state!=="idle"?(this.messageHandler.enqueueClear(o,r),await r.reply("Clear queued.")):await lk(r,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}),this.bot.command("compact",async r=>{let o=ae(r);if(!o){await r.reply(X("Could not identify chat"));return}if((await this.sessionManager.getSession(o)).state!=="idle")this.messageHandler.enqueueCompact(o,r),await r.reply("Compact queued.");else try{await gB(r,this.sessionManager,this.log.bind(this))}finally{this.messageHandler.drainQueue(o).catch(i=>this.log("Drain error:",i))}}),this.bot.command("model",r=>dk(r,this.sessionManager,this.log.bind(this))),this.bot.command(["cd","cwd"],r=>hB(r,this.sessionManager,this.log.bind(this))),this.bot.command("name",r=>yB(r,this.sessionManager,this.log.bind(this))),this.bot.command("afk",r=>TB(r,this.sessionManager,this.log.bind(this))),this.bot.command("usage",r=>_B(r,this.log.bind(this))),this.bot.command("sessions",r=>SB(r,this.sessionManager,this.log.bind(this))),this.bot.command("new",r=>kB(r,this.sessionManager,this.registeredCommandChats,this.log.bind(this))),this.bot.command("watch",async r=>{let o=ae(r);if(!o){await r.reply(X("Could not identify chat"));return}await Bj(r,o,this.watchManager,Tn(o),this.log.bind(this))}),this.bot.command("unwatch",async r=>{let o=r.chat?.id;if(!o){await r.reply(X("Could not identify chat"));return}let s=this.watchManager.stop(o);await r.reply(s?`Stopped watching ${s}.`:"Not watching anything.")}),this.bot.command("abort",async r=>{let o=r.chat?.id;if(!o){await r.reply(X("Could not identify chat"));return}let s=this.watchManager.getWatched(o);if(!s){await r.reply("Not watching any session. Use /watch <session-id> to watch a REPL session first, then /abort to stop it.");return}let i=am(s);if(i===null){await r.reply("Session key not found \u2014 the REPL may not have enabled AFK mode (/afk on). Cannot send a verified abort.");return}let a=Lj(),c=Fj(i,s,a);new Nn(s).record({kind:"abort_request",nonce:a,hmac:c}),await r.reply(`\u270B Abort sent to session ${s}.`)});let e=r=>{r.catch(o=>{let i=(o instanceof Error?o.message:String(o)).replace(/\/bot[^/]+\//g,"/bot[REDACTED]/");this.log("Detached update handler error:",i)})};this.bot.on("text",r=>e(this.messageHandler.handle(r))),this.bot.on("photo",r=>e(this.messageHandler.handlePhoto(r))),this.bot.on("document",r=>e(this.messageHandler.handleDocument(r))),this.bot.on(["voice","video","sticker","video_note","audio"],r=>{r.chat&&r.reply("I can process text, photo, and document messages. Voice and video support is not yet available.").catch(o=>this.log("Failed to send unsupported-type reply:",o))});let n=new RegExp(`^${Pe(qf)}`);this.bot.action(n,r=>UB(r,{log:this.log.bind(this)})),this.bot.action(/^afk:m:/,async r=>{if(await r.answerCbQuery().catch(()=>{}),r.chat?.id!==void 0&&!this.options.allowedChatIds.has(r.chat.id))return;let s=(typeof r.callbackQuery=="object"&&"data"in r.callbackQuery?r.callbackQuery.data:"").replace("afk:m:",""),i=ae(r);if(!(!i||!s)&&mr.includes(s))try{await this.sessionManager.switchModel(i,s);let a=wl(s);await r.editMessageText(a).catch(()=>r.reply(a))}catch(a){this.log("Model action error:",a)}}),this.bot.action(/^afk:sw:/,async r=>{await r.answerCbQuery().catch(()=>{}),!(r.chat?.id!==void 0&&!this.options.allowedChatIds.has(r.chat.id))&&await vB(r,this.sessionManager,this.log.bind(this))}),this.bot.catch((r,o)=>{this.log("Bot error:",r),o.chat&&o.reply(X("An unexpected error occurred. Please try again.")).catch(s=>this.log("Failed to send error message:",s))})}async start(){if(this.running)throw new Error("Bot is already running");this.log("Loading sessions..."),await this.sessionManager.loadSessions();let e=[...this.options.allowedChatIds];if(e.length>0){let n=e[0],r=rm(this.messageHandler,this.bot,n),o=om(this.bot,new Set(this.options.allowedChatIds),(...s)=>this.log("[elicitation]",...s));He.install(sm(r,o)),(await Promise.resolve().then(()=>(tm(),Mk))).registerHandoffAnswerHandlers(this.bot)}await qN(),this.log("Starting bot..."),await this.bot.launch(),this.log("Registering bot commands..."),await this.bot.telegram.setMyCommands([{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"},{command:"cd",description:"Show or change session working directory"},{command:"name",description:"Show or set the session name"},{command:"afk",description:"Toggle autonomous (AFK) mode for this chat"},{command:"usage",description:"Show Claude subscription usage"},{command:"watch",description:"Live-tail a CLI session from this chat"},{command:"unwatch",description:"Stop watching a session"}]),this.running=!0,this.log("Bot started successfully"),this.startAutoSubscribe()}async stop(){if(this.running){this.log("Stopping bot..."),this.running=!1,this.log("Stopping auto-subscribe loop..."),this.stopAutoSubscribe(),this.log("Uninstalling elicitation handler..."),He.uninstall(),this.log("Stopping session watches..."),await this.watchManager.stopAll(),this.log("Closing sessions..."),await this.sessionManager.closeAll(),this.log("Stopping bot polling...");try{this.bot.stop()}catch(e){this.log("Error stopping bot (may not have been started):",e)}this.log("Bot stopped")}}getStats(){return{running:this.running,activeSessions:this.sessionManager.getSessionCount(),totalChats:this.sessionManager.getChatCount()}}getBusySessionCount(){return this.sessionManager.getBusySessionCount()}async handleStart(e){return ig(e)}async handleHelp(e){return ag(e,this.sessionManager)}async handleClear(e){let n=ae(e);if(!n){await e.reply(X("Could not identify chat"));return}if((await this.sessionManager.getSession(n)).state!=="idle")this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.");else return lk(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}async handleMessage(e){return this.messageHandler.handle(e)}async handlePhoto(e){return this.messageHandler.handlePhoto(e)}async handleDocument(e){return this.messageHandler.handleDocument(e)}async handleModelSwitch(e){return dk(e,this.sessionManager,this.log.bind(this))}startAutoSubscribe(){if(this.autoSubscribeInterval!==null)return;let e=()=>{this.runAutoSubscribeTick().catch(n=>this.log("auto-subscribe tick error:",n))};this.autoSubscribeInterval=setInterval(e,t.AUTO_SUBSCRIBE_INTERVAL_MS),this.autoSubscribeInterval.unref?.(),e()}stopAutoSubscribe(){this.autoSubscribeInterval!==null&&(clearInterval(this.autoSubscribeInterval),this.autoSubscribeInterval=null)}async runAutoSubscribeTick(){let e=[...this.options.allowedChatIds];if(e.length===0)return;let n;try{n=await Di()}catch{return}let r=new Set(n.filter(o=>o.surface==="cli"&&o.afk===!0&&o.sessionId).map(o=>o.sessionId));for(let o of e){let s=this.watchManager.getWatched(o);s!==void 0&&!r.has(s)&&(this.watchManager.stop(o),this.log(`[auto-subscribe] stopped watch for ${s} (afk cleared)`));for(let i of r){if(this.watchManager.watching(o)===i)continue;let a=()=>this.sessionManager.getActiveRouteForChat(o)??{chatId:o},c=async l=>{for(let d of Ge(l))await this.bot.telegram.sendMessage(o,d,Tn(a()))};this.watchManager.start(o,i,c,a),this.log(`[auto-subscribe] started watch for ${i} on chat ${o}`);break}}}log(...e){this.options.verbose&&console.log("[TelegramBot]",...e)}};qi();My();B();F();import G2e from"chalk";import L from"chalk";var joe={brand:L.hex("#E67E4C"),mint:L.hex("#5FE3A1"),goblin:L.hex("#9CB04A"),user:L.cyan,caret:L.hex("#7AA2F7"),tool:L.hex("#DCDCAA"),chrome:L.hex("#B0B8C2"),syntaxString:L.italic.hex("#8AB07A"),toolArg:L.dim.white,thinking:L.italic.hex("#B5888F"),success:L.green,error:L.red,warning:L.yellow,plan:L.hex("#9F7CE0"),bypass:L.bold.hex("#FF6AC1"),meta:L.blackBright,info:L.hex("#5BA8FF"),fileRef:L.hex("#5B8FA8"),heading:L.bold.white,label:L.dim,dim:L.dim,bold:L.bold,italic:L.italic,diffAdd:L.green,diffRemove:L.red,diffHunk:L.blackBright},J2e={brand:L.hex("#C0562A"),mint:L.hex("#1B9E63"),goblin:L.hex("#6B7D2A"),user:L.hex("#0E7490"),caret:L.hex("#3B5BDB"),tool:L.hex("#7A6E00"),chrome:L.hex("#5A6470"),syntaxString:L.italic.hex("#3F7A3F"),toolArg:L.hex("#6B7280"),thinking:L.italic.hex("#8A5D64"),success:L.hex("#2E7D32"),error:L.hex("#C62828"),warning:L.hex("#B8860B"),plan:L.hex("#7048C0"),bypass:L.bold.hex("#D6297F"),meta:L.hex("#6B7280"),info:L.hex("#1D6FD6"),fileRef:L.hex("#2D5B7A"),heading:L.bold.hex("#1F2937"),label:L.dim,dim:L.dim,bold:L.bold,italic:L.italic,diffAdd:L.hex("#2E7D32"),diffRemove:L.hex("#C62828"),diffHunk:L.hex("#6B7280")},V2e={brand:L.hex("#FF9B5A"),mint:L.hex("#B4FCC3"),goblin:L.hex("#A5AC55"),user:L.hex("#42CBC8"),caret:L.hex("#9DBEFC"),tool:L.hex("#F7D179"),chrome:L.hex("#D3CDC5"),syntaxString:L.italic.hex("#96C182"),toolArg:L.dim.hex("#D3CDC5"),thinking:L.italic.hex("#C4929A"),success:L.hex("#8AE49E"),error:L.hex("#EF7F74"),warning:L.hex("#D7AA32"),plan:L.hex("#AE93DE"),bypass:L.bold.hex("#FFACE9"),meta:L.hex("#AAA19B"),info:L.hex("#739EF0"),fileRef:L.hex("#78ACB8"),heading:L.bold.hex("#F9F6F2"),label:L.dim,dim:L.dim,bold:L.bold,italic:L.italic,diffAdd:L.hex("#8AE49E"),diffRemove:L.hex("#EF7F74"),diffHunk:L.hex("#AAA19B")};var Hoe={...joe};var Woe="https://api.telegram.org";async function jj(t){try{let e=await fetch(`${Woe}/bot${t}/getMe`);if(!e.ok)return null;let n=await e.json();return!n.ok||!n.result?.id||!n.result?.first_name?null:{id:n.result.id,...n.result.username!==void 0?{username:n.result.username}:{},firstName:n.result.first_name}}catch{return null}}Nt();ku();fe();Xo();B();fe();be();F();Xo();function $k(){return`# Agent AFK
|
|
1531
|
+
`);i=[],c=c.then(()=>r(u)).catch(p=>this.log("watch send error:",p))};try{for await(let u of Hy(n,{signal:s})){if(u.kind==="elicitation"&&l!==void 0){a&&clearTimeout(a),d(),await c;let f=Date.now(),m=0,g=setInterval(()=>{if(m>=$oe){clearInterval(g);return}m+=1;let w=Math.round((Date.now()-f)/6e4);r(`\u23F3 Still waiting on your answer (${w}m elapsed) \u2014 no deadline, reply above whenever you're ready. (Send /unwatch to stop watching this session.)`).catch(()=>{})},this.elicitHeartbeatMs);g.unref?.();let y=await(async()=>{try{return await l(u.request,{signal:s})}finally{clearInterval(g)}})(),b=am(n);if(b!==null){let w=Dj(b,n,u.reqId,y);new Nn(n).record({kind:"elicitation_response",reqId:u.reqId,result:y,hmac:w})}else this.log("[watch] no session key for",n,"\u2014 skipping elicitation write-back");continue}let p=Uoe(u);if(p){if(i.push(p),u.kind==="closed"){d();break}a||(a=setTimeout(d,Loe),a.unref?.())}}a&&clearTimeout(a),d(),await c}finally{a&&clearTimeout(a);let u=this.watches.get(e);u&&u.sessionId===n&&u.abort.signal===s&&this.watches.delete(e)}}};Te();Te();async function Bj(t,e,n,r,o){let{chatId:s}=e,a=((t.message&&"text"in t.message?t.message.text:"")??"").split(/\s+/).slice(1).join(" ").trim();try{if(!a){await t.reply(await Uj());return}let c=await $j(a);if(!c){await t.reply(`No session ledger found for "${a}". Use /watch with no argument to list watchable sessions.`);return}let l=async d=>{for(let u of Ge(d))await t.telegram.sendMessage(s,u,r)};n.start(s,c,l),await t.reply(`\u{1F4E1} Watching ${c} \u2014 new activity will stream here. /unwatch to stop.`)}catch(c){o("Watch error:",c),await t.reply(X(c))}}Ar();la();Te();Kr();var lm=class t{bot;sessionManager;options;running=!1;registeredCommandChats=new Set;messageHandler;watchManager;autoSubscribeInterval=null;static AUTO_SUBSCRIBE_INTERVAL_MS=5e3;constructor(e){this.options=e,this.bot=new Boe(e.botToken,{handlerTimeout:1/0}),this.sessionManager=new yl({...e,onResumptionOffer:(n,r)=>this.bot.telegram.sendMessage(n.chatId,r,Tn(n)).then(()=>!0).catch(()=>!1)}),this.messageHandler=new nm(this.bot,this.sessionManager,this.registeredCommandChats,this.log.bind(this),e.tagOnlyChats??new Set),this.watchManager=new cm(this.log.bind(this),this.bot,this.messageHandler),this.setupHandlers()}setupHandlers(){this.bot.use(FA(this.options.allowedChatIds,this.log.bind(this))),this.bot.command("start",r=>ig(r)),this.bot.command("help",r=>ag(r,this.sessionManager)),this.bot.command("clear",async r=>{let o=ae(r);if(!o){await r.reply(X("Could not identify chat"));return}(await this.sessionManager.getSession(o)).state!=="idle"?(this.messageHandler.enqueueClear(o,r),await r.reply("Clear queued.")):await lk(r,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}),this.bot.command("compact",async r=>{let o=ae(r);if(!o){await r.reply(X("Could not identify chat"));return}if((await this.sessionManager.getSession(o)).state!=="idle")this.messageHandler.enqueueCompact(o,r),await r.reply("Compact queued.");else try{await gB(r,this.sessionManager,this.log.bind(this))}finally{this.messageHandler.drainQueue(o).catch(i=>this.log("Drain error:",i))}}),this.bot.command("model",r=>dk(r,this.sessionManager,this.log.bind(this))),this.bot.command(["cd","cwd"],r=>hB(r,this.sessionManager,this.log.bind(this))),this.bot.command("name",r=>yB(r,this.sessionManager,this.log.bind(this))),this.bot.command("afk",r=>TB(r,this.sessionManager,this.log.bind(this))),this.bot.command("usage",r=>_B(r,this.log.bind(this))),this.bot.command("sessions",r=>SB(r,this.sessionManager,this.log.bind(this))),this.bot.command("new",r=>kB(r,this.sessionManager,this.registeredCommandChats,this.log.bind(this))),this.bot.command("watch",async r=>{let o=ae(r);if(!o){await r.reply(X("Could not identify chat"));return}await Bj(r,o,this.watchManager,Tn(o),this.log.bind(this))}),this.bot.command("unwatch",async r=>{let o=r.chat?.id;if(!o){await r.reply(X("Could not identify chat"));return}let s=this.watchManager.stop(o);await r.reply(s?`Stopped watching ${s}.`:"Not watching anything.")}),this.bot.command("abort",async r=>{let o=r.chat?.id;if(!o){await r.reply(X("Could not identify chat"));return}let s=this.watchManager.getWatched(o);if(!s){await r.reply("Not watching any session. Use /watch <session-id> to watch a REPL session first, then /abort to stop it.");return}let i=am(s);if(i===null){await r.reply("Session key not found \u2014 the REPL may not have enabled AFK mode (/afk on). Cannot send a verified abort.");return}let a=Lj(),c=Fj(i,s,a);new Nn(s).record({kind:"abort_request",nonce:a,hmac:c}),await r.reply(`\u270B Abort sent to session ${s}.`)});let e=r=>{r.catch(o=>{let i=(o instanceof Error?o.message:String(o)).replace(/\/bot[^/]+\//g,"/bot[REDACTED]/");this.log("Detached update handler error:",i)})};this.bot.on("text",r=>e(this.messageHandler.handle(r))),this.bot.on("photo",r=>e(this.messageHandler.handlePhoto(r))),this.bot.on("document",r=>e(this.messageHandler.handleDocument(r))),this.bot.on(["voice","video","sticker","video_note","audio"],r=>{r.chat&&r.reply("I can process text, photo, and document messages. Voice and video support is not yet available.").catch(o=>this.log("Failed to send unsupported-type reply:",o))});let n=new RegExp(`^${Pe(qf)}`);this.bot.action(n,r=>UB(r,{log:this.log.bind(this)})),this.bot.action(/^afk:m:/,async r=>{if(await r.answerCbQuery().catch(()=>{}),r.chat?.id!==void 0&&!this.options.allowedChatIds.has(r.chat.id))return;let s=(typeof r.callbackQuery=="object"&&"data"in r.callbackQuery?r.callbackQuery.data:"").replace("afk:m:",""),i=ae(r);if(!(!i||!s)&&mr.includes(s))try{await this.sessionManager.switchModel(i,s);let a=wl(s);await r.editMessageText(a).catch(()=>r.reply(a))}catch(a){this.log("Model action error:",a)}}),this.bot.action(/^afk:sw:/,async r=>{await r.answerCbQuery().catch(()=>{}),!(r.chat?.id!==void 0&&!this.options.allowedChatIds.has(r.chat.id))&&await vB(r,this.sessionManager,this.log.bind(this))}),this.bot.catch((r,o)=>{this.log("Bot error:",r),o.chat&&o.reply(X("An unexpected error occurred. Please try again.")).catch(s=>this.log("Failed to send error message:",s))})}async start(){if(this.running)throw new Error("Bot is already running");this.log("Loading sessions..."),await this.sessionManager.loadSessions();let e=[...this.options.allowedChatIds];if(e.length>0){let n=e[0],r=rm(this.messageHandler,this.bot,n),o=om(this.bot,new Set(this.options.allowedChatIds),(...s)=>this.log("[elicitation]",...s));He.install(sm(r,o)),(await Promise.resolve().then(()=>(tm(),Mk))).registerHandoffAnswerHandlers(this.bot)}await qN(),this.log("Starting bot..."),await this.bot.launch(),this.log("Registering bot commands..."),await this.bot.telegram.setMyCommands([{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"},{command:"cd",description:"Show or change session working directory"},{command:"name",description:"Show or set the session name"},{command:"afk",description:"Toggle autonomous (AFK) mode for this chat"},{command:"usage",description:"Show Claude subscription usage"},{command:"watch",description:"Live-tail a CLI session from this chat"},{command:"unwatch",description:"Stop watching a session"}]),this.running=!0,this.log("Bot started successfully"),this.startAutoSubscribe()}async stop(){if(this.running){this.log("Stopping bot..."),this.running=!1,this.log("Stopping auto-subscribe loop..."),this.stopAutoSubscribe(),this.log("Uninstalling elicitation handler..."),He.uninstall(),this.log("Stopping session watches..."),await this.watchManager.stopAll(),this.log("Closing sessions..."),await this.sessionManager.closeAll(),this.log("Stopping bot polling...");try{this.bot.stop()}catch(e){this.log("Error stopping bot (may not have been started):",e)}this.log("Bot stopped")}}getStats(){return{running:this.running,activeSessions:this.sessionManager.getSessionCount(),totalChats:this.sessionManager.getChatCount()}}getBusySessionCount(){return this.sessionManager.getBusySessionCount()}async handleStart(e){return ig(e)}async handleHelp(e){return ag(e,this.sessionManager)}async handleClear(e){let n=ae(e);if(!n){await e.reply(X("Could not identify chat"));return}if((await this.sessionManager.getSession(n)).state!=="idle")this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.");else return lk(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}async handleMessage(e){return this.messageHandler.handle(e)}async handlePhoto(e){return this.messageHandler.handlePhoto(e)}async handleDocument(e){return this.messageHandler.handleDocument(e)}async handleModelSwitch(e){return dk(e,this.sessionManager,this.log.bind(this))}startAutoSubscribe(){if(this.autoSubscribeInterval!==null)return;let e=()=>{this.runAutoSubscribeTick().catch(n=>this.log("auto-subscribe tick error:",n))};this.autoSubscribeInterval=setInterval(e,t.AUTO_SUBSCRIBE_INTERVAL_MS),this.autoSubscribeInterval.unref?.(),e()}stopAutoSubscribe(){this.autoSubscribeInterval!==null&&(clearInterval(this.autoSubscribeInterval),this.autoSubscribeInterval=null)}async runAutoSubscribeTick(){let e=[...this.options.allowedChatIds];if(e.length===0)return;let n;try{n=await Di()}catch{return}let r=new Set(n.filter(o=>o.surface==="cli"&&o.afk===!0&&o.sessionId).map(o=>o.sessionId));for(let o of e){let s=this.watchManager.getWatched(o);s!==void 0&&!r.has(s)&&(this.watchManager.stop(o),this.log(`[auto-subscribe] stopped watch for ${s} (afk cleared)`));for(let i of r){if(this.watchManager.watching(o)===i)continue;let a=()=>this.sessionManager.getActiveRouteForChat(o)??{chatId:o},c=async l=>{for(let d of Ge(l))await this.bot.telegram.sendMessage(o,d,Tn(a()))};this.watchManager.start(o,i,c,a),this.log(`[auto-subscribe] started watch for ${i} on chat ${o}`);break}}}log(...e){this.options.verbose&&console.log("[TelegramBot]",...e)}};qi();My();B();F();import X2e from"chalk";import L from"chalk";var joe={brand:L.hex("#E67E4C"),mint:L.hex("#5FE3A1"),goblin:L.hex("#9CB04A"),user:L.cyan,caret:L.hex("#7AA2F7"),tool:L.hex("#DCDCAA"),chrome:L.hex("#B0B8C2"),syntaxString:L.italic.hex("#8AB07A"),toolArg:L.dim.white,thinking:L.italic.hex("#B5888F"),success:L.green,error:L.red,warning:L.yellow,plan:L.hex("#9F7CE0"),bypass:L.bold.hex("#FF6AC1"),meta:L.blackBright,info:L.hex("#5BA8FF"),fileRef:L.hex("#5B8FA8"),heading:L.bold.white,label:L.dim,dim:L.dim,bold:L.bold,italic:L.italic,diffAdd:L.green,diffRemove:L.red,diffHunk:L.blackBright},V2e={brand:L.hex("#C0562A"),mint:L.hex("#1B9E63"),goblin:L.hex("#6B7D2A"),user:L.hex("#0E7490"),caret:L.hex("#3B5BDB"),tool:L.hex("#7A6E00"),chrome:L.hex("#5A6470"),syntaxString:L.italic.hex("#3F7A3F"),toolArg:L.hex("#6B7280"),thinking:L.italic.hex("#8A5D64"),success:L.hex("#2E7D32"),error:L.hex("#C62828"),warning:L.hex("#B8860B"),plan:L.hex("#7048C0"),bypass:L.bold.hex("#D6297F"),meta:L.hex("#6B7280"),info:L.hex("#1D6FD6"),fileRef:L.hex("#2D5B7A"),heading:L.bold.hex("#1F2937"),label:L.dim,dim:L.dim,bold:L.bold,italic:L.italic,diffAdd:L.hex("#2E7D32"),diffRemove:L.hex("#C62828"),diffHunk:L.hex("#6B7280")},Y2e={brand:L.hex("#FF9B5A"),mint:L.hex("#B4FCC3"),goblin:L.hex("#A5AC55"),user:L.hex("#42CBC8"),caret:L.hex("#9DBEFC"),tool:L.hex("#F7D179"),chrome:L.hex("#D3CDC5"),syntaxString:L.italic.hex("#96C182"),toolArg:L.dim.hex("#D3CDC5"),thinking:L.italic.hex("#C4929A"),success:L.hex("#8AE49E"),error:L.hex("#EF7F74"),warning:L.hex("#D7AA32"),plan:L.hex("#AE93DE"),bypass:L.bold.hex("#FFACE9"),meta:L.hex("#AAA19B"),info:L.hex("#739EF0"),fileRef:L.hex("#78ACB8"),heading:L.bold.hex("#F9F6F2"),label:L.dim,dim:L.dim,bold:L.bold,italic:L.italic,diffAdd:L.hex("#8AE49E"),diffRemove:L.hex("#EF7F74"),diffHunk:L.hex("#AAA19B")};var Hoe={...joe};var Woe="https://api.telegram.org";async function jj(t){try{let e=await fetch(`${Woe}/bot${t}/getMe`);if(!e.ok)return null;let n=await e.json();return!n.ok||!n.result?.id||!n.result?.first_name?null:{id:n.result.id,...n.result.username!==void 0?{username:n.result.username}:{},firstName:n.result.first_name}}catch{return null}}Nt();ku();fe();Xo();B();fe();be();F();Xo();function $k(){return`# Agent AFK
|
|
1532
1532
|
|
|
1533
1533
|
## What this process is
|
|
1534
1534
|
|
|
@@ -1724,11 +1724,11 @@ The instructions below come from this operator's configuration (AFK.md, afk.conf
|
|
|
1724
1724
|
${Hj}
|
|
1725
1725
|
|
|
1726
1726
|
${r}`}fe();gs();pc();js();F();ut();Nt();Ue();zr();In();vi();function Wj(t,e){return re(t,e)}function Kj(t){let e=k.AFK_DEFAULT_SUBAGENT_MODEL;if(e&&e.length>0)return e;if(typeof t=="string"){let n=z(t);if(n==="openai-compatible"||n==="xai"||n==="xai-oauth")return t}return"medium"}function Koe(t){if(t===void 0)return;if(t==="max")return Number.POSITIVE_INFINITY;if(t===""||t==="NaN")throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Expected a positive integer or 'max'.`);if(!/^\d+$/.test(t))throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Expected a positive integer or 'max'.`);let e=Number(t);if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Must be a positive integer.`);return e}function qj(){return Koe(k.AFK_MAX_OUTPUT_TOKENS)}function qoe(t){if(t===void 0)return;let e=Number(t);if(!(!Number.isFinite(e)||e<=0))return Math.floor(e)}function Gj(){return qoe(k.AFK_MAX_TOOL_USE_ITERATIONS)}import{existsSync as Goe,readFileSync as Xoe}from"fs";var zoe=["TELEGRAM_BOT_TOKEN","AFK_TELEGRAM_ALLOWED_CHAT_IDS","TELEGRAM_VERBOSE","TELEGRAM_DATA_DIR"];function Joe(t){let e=new Map;if(!Goe(t))return e;try{let n=Xoe(t,"utf-8");for(let r of n.split(`
|
|
1727
|
-
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),e.set(i,a)}}catch{}return e}function Xj(t,e){if(t!=="TELEGRAM_BOT_TOKEN")return e;let n=e.indexOf(":");return n===-1?`${e.slice(0,4)}***`:`${e.slice(0,n+1)}***`}function zj(t,e=console.log){let n=Joe(t);for(let r of zoe){let o=n.get(r);if(o===void 0)continue;let s=process.env[r];s!==void 0&&s!==o&&e(`\u{1F527} ${r}: file value (${Xj(r,o)}) overrides shell value (${Xj(r,s)})`),process.env[r]=o}}F();xn();be();co();Xo();function Bk(t){return t==="openai-compatible"||t==="openai-codex"}function jk(t){return t==="xai"||t==="xai-oauth"}function Voe(){return St(void 0,"oauth").apiKey!=null}function Jj(t,e={}){let{openaiApiKey:n=k.OPENAI_API_KEY,codexApiKey:r=k.CODEX_API_KEY,loadAnthropicCredential:o=Go,loadXaiKey:s=Mh,hasXaiOAuth:i=Voe,detectMode:a=Ao}=e;if(Bk(t))return{kind:"openai",notices:[n||r?"\u{1F4DD} Using OPENAI_API_KEY / CODEX_API_KEY for OpenAI auth":"\u{1F4DD} Will attempt API key from ~/.codex/auth.json (run `afk provider auth diagnose` for details)"]};if(jk(t)){let d=t==="xai-oauth",u=s(),p=!!u&&u.length>0,f=i();if(d)return f?{kind:"xai",notices:["\u{1F4DD} Using SuperGrok / SuperGrok Heavy / X Premium+ OAuth for xAI"]}:{kind:"missing",errors:["\u274C SuperGrok OAuth required for xai-oauth models."," Run `afk provider auth xai login` (device-code), then restart the bot."]};if(!p&&!f)return{kind:"missing",errors:["\u274C Grok models require XAI_API_KEY or SuperGrok OAuth."," Set XAI_API_KEY, or run `afk provider auth xai login`."]};let m=[];return p&&m.push("\u{1F4DD} Using XAI_API_KEY for metered xAI auth"),f&&!p?m.push("\u{1F4DD} Using SuperGrok / SuperGrok Heavy / X Premium+ OAuth for xAI"):f&&p&&m.push("\u{1F4DD} Both XAI_API_KEY and SuperGrok OAuth present \u2014 use slot provider xai vs xai-oauth if ambiguous"),{kind:"xai",...p?{apiKey:u}:{},notices:m}}let c=o();if(!c||c.length===0)return{kind:"missing",errors:["\u274C Claude models require ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN."," Set one in your environment, run `afk login`, or sign in to Claude Code."]};let l=a(c)==="oauth"?"CLAUDE_CODE_OAUTH_TOKEN":"ANTHROPIC_API_KEY";return{kind:"anthropic",credential:c,envVar:l,notices:[l==="CLAUDE_CODE_OAUTH_TOKEN"?"\u{1F4DD} Using CLAUDE_CODE_OAUTH_TOKEN for Anthropic auth (OAuth, auto-refresh on 401)":"\u{1F4DD} Using ANTHROPIC_API_KEY for Anthropic auth"]}}function Vj(t,e,n={}){let r=n.log??console.log,o=n.error??console.error;if(t.kind==="missing"){for(let s of t.errors)o(s);return!1}t.kind==="anthropic"&&(process.env[t.envVar]=t.credential,e.apiKey=t.credential),t.kind==="xai"&&t.apiKey!==void 0&&t.apiKey.length>0&&(e.apiKey=t.apiKey);for(let s of t.notices)r(s);return!0}be();Xo();import{readFileSync as Yoe}from"fs";import{dirname as Qoe,join as Zoe}from"path";import{fileURLToPath as ese}from"url";var Ic="unknown",tse=["../package.json","../../package.json"];function dm(t=Qoe(ese(import.meta.url)),e=n=>Yoe(n,"utf8")){for(let n of tse)try{let r=JSON.parse(e(Zoe(t,n)));if(typeof r.version=="string"&&r.version.length>0)return r.version}catch{}return Ic}fe();lt();Eg();F();Bb();F();B();import{randomUUID as Cse}from"node:crypto";import{readFileSync as Pse,existsSync as Mse}from"node:fs";import{createHash as Ese}from"crypto";import{appendFileSync as _se}from"fs";import{mkdir as Ase,open as xse,writeFile as Rse}from"fs/promises";import{join as fH}from"path";import{z as S}from"zod";var Yj=["policy-refusal","timeout","budget","permission-denied","hook-block","abort","elicitation-declined","denial-breaker","repeat-failure","no-such-target"],Qj=new Set(["policy-refusal","permission-denied","hook-block","abort","elicitation-declined","no-such-target"]);import{z as po}from"zod";var Hk=po.object({transition:po.literal("cancelled"),jobId:po.string(),subagentId:po.string(),source:po.enum(["explicit","cascade"]),cancelledBy:po.literal("model").optional(),reason:po.string().optional()});var nse=S.object({phase:S.literal("started"),toolUseId:S.string(),name:S.string(),inputBytes:S.number().int().nonnegative(),argsFingerprint:S.string().regex(/^[0-9a-f]{64}$/).optional(),resourceFingerprint:S.string().regex(/^[0-9a-f]{64}$/).optional(),subagentId:S.string().optional()}),Zj=S.enum(Yj),rse=S.object({phase:S.literal("completed"),toolUseId:S.string(),name:S.string(),resultBytes:S.number().int().nonnegative(),isError:S.boolean(),truncated:S.boolean(),durationMs:S.number().nonnegative(),incomplete:S.boolean().optional(),incompleteReason:S.string().optional(),circuitBreaker:S.boolean().optional(),failureClass:Zj.optional(),batchIndex:S.number().int().positive().optional(),batchSize:S.number().int().positive().optional(),subagentId:S.string().optional()}),eH=S.discriminatedUnion("phase",[nse,rse]),ose=S.enum(["PreToolUse","PostToolUse","PostToolUseFailure","SessionStart","SessionEnd","SubagentStart","SubagentStop"]),tH=S.object({hookEvent:ose,decision:S.union([S.literal("block"),S.literal("approve")]).optional(),reason:S.string().optional(),blockedTool:S.string().optional(),subagentId:S.string().optional(),injectedContextBytes:S.number().int().nonnegative().optional(),durationMs:S.number().nonnegative().optional(),approvalOutcome:S.enum(["carve-out","approved","denied","unrecognised","timeout","decline","cancel","hard-block"]).optional()}),sse=S.object({transition:S.literal("started"),subagentId:S.string(),parentId:S.string(),model:S.string(),allowedTools:S.array(S.string()).readonly().optional(),systemPromptHash:S.string().optional(),promptHead:S.string().optional(),agentType:S.string().optional(),resolvedAgentType:S.string().optional()}),ise=S.object({transition:S.literal("succeeded"),subagentId:S.string(),durationMs:S.number().nonnegative(),turnCount:S.number().int().nonnegative(),totalCostUsd:S.number().nonnegative().optional(),outputBytes:S.number().int().nonnegative(),stopReason:S.string().optional()}),ase=S.object({transition:S.literal("failed"),subagentId:S.string(),errorClass:S.string(),errorMessage:S.string(),partialOutputBytes:S.number().int().nonnegative(),failureClass:Zj.optional()}),cse=S.object({transition:S.literal("cancelled"),subagentId:S.string(),source:S.enum(["cascade","explicit"]),timeout:S.boolean().optional()}),nH=S.discriminatedUnion("transition",[sse,ise,ase,cse]),lse=S.object({transition:S.literal("started"),jobId:S.string(),subagentId:S.string(),label:S.string(),model:S.string()}),dse=S.object({transition:S.literal("completed"),jobId:S.string(),subagentId:S.string(),durationMs:S.number().nonnegative(),outputBytes:S.number().int().nonnegative()}),use=S.object({transition:S.literal("failed"),jobId:S.string(),subagentId:S.string(),durationMs:S.number().nonnegative(),errorClass:S.string(),errorMessage:S.string()}),pse=S.object({transition:S.literal("joined"),jobId:S.string(),subagentId:S.string(),jobStatus:S.enum(["completed","failed","cancelled"])}),fse=S.object({transition:S.literal("delivered"),jobId:S.string(),subagentId:S.string(),jobStatus:S.enum(["completed","failed","cancelled"])}),rH=S.discriminatedUnion("transition",[lse,dse,use,Hk,pse,fse]),oH=S.object({kind:S.literal("monetary"),runningCostUsd:S.number().nonnegative(),maxBudgetUsd:S.number().nonnegative(),lastTurnCostUsd:S.number().nonnegative()}),mse=S.enum(["user_signal","cascade","timeout","budget","hook_block"]),sH=S.object({origin:mse,cascadedTo:S.array(S.string()).readonly(),reason:S.string().optional()}),iH=S.enum(["manual","token_threshold","turn_count"]),gse=S.object({path:S.string(),sizeBytes:S.number().int().nonnegative(),sha256:S.string().regex(/^[0-9a-f]{64}$/)}),hse=S.object({trigger:iH,preCompactionMessages:S.array(S.unknown()),summary:S.string(),keptTailCount:S.number().int().nonnegative(),keepLastNConfig:S.number().int().nonnegative(),messagesBefore:S.number().int().nonnegative(),messagesAfter:S.number().int().nonnegative(),tokensSavedEstimate:S.number().nonnegative().optional(),summarizationTokens:S.object({input:S.number().int().nonnegative(),output:S.number().int().nonnegative()}).optional()}),yse=S.object({trigger:iH,preCompactionMessagesRef:gse,summary:S.string(),keptTailCount:S.number().int().nonnegative(),keepLastNConfig:S.number().int().nonnegative(),messagesBefore:S.number().int().nonnegative(),messagesAfter:S.number().int().nonnegative(),tokensSavedEstimate:S.number().nonnegative().optional(),summarizationTokens:S.object({input:S.number().int().nonnegative(),output:S.number().int().nonnegative()}).optional()}),bse=S.enum(["model_end_turn","truncated","iteration_cap","abort","timeout","budget_exceeded","hook_blocked","max_turns_exceeded"]),aH=S.object({reason:bse,finalTurnCount:S.number().int().nonnegative(),finalCostUsd:S.number().nonnegative(),finalTokens:S.object({input:S.number().int().nonnegative().optional(),output:S.number().int().nonnegative().optional(),cacheRead:S.number().int().nonnegative().optional(),cacheCreation:S.number().int().nonnegative().optional()}),lastStopReason:S.string().optional(),guidance:S.string().optional()}),cH=S.object({source:S.string(),assertion:S.string(),evidence:S.array(S.string()).readonly(),confidence:S.number().min(0).max(1),dissent:S.string().optional()}),wse=S.enum(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),Sse=S.enum(["click","fill","press","select","hover","scroll_to","wait_for"]),kse=S.object({kind:S.enum(["semantic","element_id","selector"]),text:S.string().max(80).optional(),role:S.string().optional(),elementId:S.string().optional(),selectorHash:S.string().regex(/^[0-9a-f]{8}$/).optional()}),lH=S.object({jobId:S.string(),subagentId:S.string(),byteLength:S.number().int().nonnegative()}),dH=S.object({tool:wse,action:Sse.optional(),toolUseId:S.string(),backend:S.enum(["playwright","agent-browser"]).optional(),backendReason:S.string().optional(),target:kse.optional(),urlBefore:S.string().nullable(),urlAfter:S.string().nullable(),status:S.enum(["ok","error","ambiguous_target","blocked_by_policy"]),screenshotPath:S.string().optional(),observationSummary:S.string().max(500).optional(),error:S.object({reason:S.string(),recoverable:S.boolean()}).optional(),durationMs:S.number().nonnegative()}),vse=S.enum(["bootstrap_start","bootstrap_done","session_init_start","session_init_done","mcp_connect_start","mcp_connect_done","mcp_server_start","mcp_server_done","loop_start","loop_end","model_ttfb","interrupt_halt","rate_limit","ttfb_timeout","usage_limit_pause","usage_limit_resume","overload_pause","overload_resume","idle_watchdog_fired","pause_extension_granted","suspected_loop","compaction_disabled","boot_warning"]),uH=S.object({phase:vse,durationMs:S.number().nonnegative().optional(),metadata:S.record(S.string(),S.union([S.string(),S.number(),S.boolean()])).optional(),model:S.string().optional(),resolvedModel:S.string().optional(),origin:S.enum(["cli","telegram","daemon","web","unknown"]).optional(),actor:S.enum(["main","subagent"]).optional()}),Tse=S.object({status:S.enum(["succeeded","failed","cancelled"]),finalCostUsd:S.number().nonnegative(),finalTurnCount:S.number().int().nonnegative(),closedAt:S.string().datetime(),incomplete:S.boolean().optional(),subagentCount:S.number().int().nonnegative().optional(),subagentTokens:S.object({input:S.number().int().nonnegative().optional(),output:S.number().int().nonnegative().optional(),cacheRead:S.number().int().nonnegative().optional(),cacheCreation:S.number().int().nonnegative().optional()}).optional(),subagentCostUsd:S.number().nonnegative().optional()}),pH=S.discriminatedUnion("kind",[S.object({kind:S.literal("tool_call"),payload:eH}),S.object({kind:S.literal("hook_decision"),payload:tH}),S.object({kind:S.literal("subagent_lifecycle"),payload:nH}),S.object({kind:S.literal("background_agent"),payload:rH}),S.object({kind:S.literal("budget"),payload:oH}),S.object({kind:S.literal("abort"),payload:sH}),S.object({kind:S.literal("compaction"),payload:hse}),S.object({kind:S.literal("closure"),payload:aH}),S.object({kind:S.literal("claim"),payload:cH}),S.object({kind:S.literal("browser_event"),payload:dH}),S.object({kind:S.literal("queued_user_message"),payload:lH}),S.object({kind:S.literal("session_phase"),payload:uH})]),zXe=S.discriminatedUnion("kind",[S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("tool_call"),payload:eH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("hook_decision"),payload:tH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("subagent_lifecycle"),payload:nH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("background_agent"),payload:rH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("budget"),payload:oH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("abort"),payload:sH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("compaction"),payload:yse}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("closure"),payload:aH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("claim"),payload:cH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("browser_event"),payload:dH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("queued_user_message"),payload:lH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("session_phase"),payload:uH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("session_sealed"),payload:Tse})]);var um=new Set,mH=!1;function Ise(){mH||(mH=!0,process.on("exit",()=>{for(let t of um)t.sealOnProcessExit()}))}var pm=class{traceDir;tracePath;seq;sealed=!1;sealRecordPersisted=!1;fh=null;writeQueue=Promise.resolve();constructor(e){this.traceDir=e.traceDir,this.tracePath=fH(this.traceDir,"trace.jsonl"),this.seq=e.startSeq??0}getTracePath(){return this.tracePath}async write(e){if(this.sealed)throw new Error("NdjsonTraceWriter: trace is sealed; write() rejected");return pH.parse(e),this.enqueue(async()=>{await this.ensureOpen();let n=await this.materializePersistedEvent(e);await this.appendLine(n)})}async seal(e){this.sealed||(this.sealed=!0,await this.enqueue(async()=>{if(await this.ensureOpen(),this.sealRecordPersisted)return;let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:e};await this.appendLine(n),this.sealRecordPersisted=!0,this.fh&&await this.fh.sync()}),await this.closeHandle())}async close(){await this.enqueue(async()=>{}),await this.closeHandle()}enqueue(e){let n=this.writeQueue.then(e,e);return this.writeQueue=n.then(()=>{},()=>{}),n}async ensureOpen(){this.fh||(await Ase(this.traceDir,{recursive:!0}),this.fh=await xse(this.tracePath,"a"),um.add(this),Ise())}async closeHandle(){if(um.delete(this),!this.fh)return;let e=this.fh;this.fh=null,await e.close()}sealOnProcessExit(){if(this.sealRecordPersisted||this.seq===0)return;this.sealed=!0,um.delete(this);try{let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:{status:"failed",finalCostUsd:0,finalTurnCount:0,closedAt:new Date().toISOString(),incomplete:!0}};_se(this.tracePath,`${JSON.stringify(n)}
|
|
1727
|
+
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),e.set(i,a)}}catch{}return e}function Xj(t,e){if(t!=="TELEGRAM_BOT_TOKEN")return e;let n=e.indexOf(":");return n===-1?`${e.slice(0,4)}***`:`${e.slice(0,n+1)}***`}function zj(t,e=console.log){let n=Joe(t);for(let r of zoe){let o=n.get(r);if(o===void 0)continue;let s=process.env[r];s!==void 0&&s!==o&&e(`\u{1F527} ${r}: file value (${Xj(r,o)}) overrides shell value (${Xj(r,s)})`),process.env[r]=o}}F();xn();be();co();Xo();function Bk(t){return t==="openai-compatible"||t==="openai-codex"}function jk(t){return t==="xai"||t==="xai-oauth"}function Voe(){return St(void 0,"oauth").apiKey!=null}function Jj(t,e={}){let{openaiApiKey:n=k.OPENAI_API_KEY,codexApiKey:r=k.CODEX_API_KEY,loadAnthropicCredential:o=Go,loadXaiKey:s=Mh,hasXaiOAuth:i=Voe,detectMode:a=Ao}=e;if(Bk(t))return{kind:"openai",notices:[n||r?"\u{1F4DD} Using OPENAI_API_KEY / CODEX_API_KEY for OpenAI auth":"\u{1F4DD} Will attempt API key from ~/.codex/auth.json (run `afk provider auth diagnose` for details)"]};if(jk(t)){let d=t==="xai-oauth",u=s(),p=!!u&&u.length>0,f=i();if(d)return f?{kind:"xai",notices:["\u{1F4DD} Using SuperGrok / SuperGrok Heavy / X Premium+ OAuth for xAI"]}:{kind:"missing",errors:["\u274C SuperGrok OAuth required for xai-oauth models."," Run `afk provider auth xai login` (device-code), then restart the bot."]};if(!p&&!f)return{kind:"missing",errors:["\u274C Grok models require XAI_API_KEY or SuperGrok OAuth."," Set XAI_API_KEY, or run `afk provider auth xai login`."]};let m=[];return p&&m.push("\u{1F4DD} Using XAI_API_KEY for metered xAI auth"),f&&!p?m.push("\u{1F4DD} Using SuperGrok / SuperGrok Heavy / X Premium+ OAuth for xAI"):f&&p&&m.push("\u{1F4DD} Both XAI_API_KEY and SuperGrok OAuth present \u2014 use slot provider xai vs xai-oauth if ambiguous"),{kind:"xai",...p?{apiKey:u}:{},notices:m}}let c=o();if(!c||c.length===0)return{kind:"missing",errors:["\u274C Claude models require ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN."," Set one in your environment, run `afk login`, or sign in to Claude Code."]};let l=a(c)==="oauth"?"CLAUDE_CODE_OAUTH_TOKEN":"ANTHROPIC_API_KEY";return{kind:"anthropic",credential:c,envVar:l,notices:[l==="CLAUDE_CODE_OAUTH_TOKEN"?"\u{1F4DD} Using CLAUDE_CODE_OAUTH_TOKEN for Anthropic auth (OAuth, auto-refresh on 401)":"\u{1F4DD} Using ANTHROPIC_API_KEY for Anthropic auth"]}}function Vj(t,e,n={}){let r=n.log??console.log,o=n.error??console.error;if(t.kind==="missing"){for(let s of t.errors)o(s);return!1}t.kind==="anthropic"&&(process.env[t.envVar]=t.credential,e.apiKey=t.credential),t.kind==="xai"&&t.apiKey!==void 0&&t.apiKey.length>0&&(e.apiKey=t.apiKey);for(let s of t.notices)r(s);return!0}be();Xo();import{readFileSync as Yoe}from"fs";import{dirname as Qoe,join as Zoe}from"path";import{fileURLToPath as ese}from"url";var Ic="unknown",tse=["../package.json","../../package.json"];function dm(t=Qoe(ese(import.meta.url)),e=n=>Yoe(n,"utf8")){for(let n of tse)try{let r=JSON.parse(e(Zoe(t,n)));if(typeof r.version=="string"&&r.version.length>0)return r.version}catch{}return Ic}fe();lt();Eg();F();Bb();F();B();import{randomUUID as Cse}from"node:crypto";import{readFileSync as Pse,existsSync as Mse}from"node:fs";import{createHash as Ese}from"crypto";import{appendFileSync as _se}from"fs";import{mkdir as Ase,open as xse,writeFile as Rse}from"fs/promises";import{join as fH}from"path";import{z as S}from"zod";var Yj=["policy-refusal","timeout","budget","permission-denied","hook-block","abort","elicitation-declined","denial-breaker","repeat-failure","no-such-target"],Qj=new Set(["policy-refusal","permission-denied","hook-block","abort","elicitation-declined","no-such-target"]);import{z as po}from"zod";var Hk=po.object({transition:po.literal("cancelled"),jobId:po.string(),subagentId:po.string(),source:po.enum(["explicit","cascade"]),cancelledBy:po.literal("model").optional(),reason:po.string().optional()});var nse=S.object({phase:S.literal("started"),toolUseId:S.string(),name:S.string(),inputBytes:S.number().int().nonnegative(),argsFingerprint:S.string().regex(/^[0-9a-f]{64}$/).optional(),resourceFingerprint:S.string().regex(/^[0-9a-f]{64}$/).optional(),subagentId:S.string().optional()}),Zj=S.enum(Yj),rse=S.object({phase:S.literal("completed"),toolUseId:S.string(),name:S.string(),resultBytes:S.number().int().nonnegative(),isError:S.boolean(),truncated:S.boolean(),durationMs:S.number().nonnegative(),incomplete:S.boolean().optional(),incompleteReason:S.string().optional(),circuitBreaker:S.boolean().optional(),failureClass:Zj.optional(),batchIndex:S.number().int().positive().optional(),batchSize:S.number().int().positive().optional(),subagentId:S.string().optional()}),eH=S.discriminatedUnion("phase",[nse,rse]),ose=S.enum(["PreToolUse","PostToolUse","PostToolUseFailure","SessionStart","SessionEnd","SubagentStart","SubagentStop"]),tH=S.object({hookEvent:ose,decision:S.union([S.literal("block"),S.literal("approve")]).optional(),reason:S.string().optional(),blockedTool:S.string().optional(),subagentId:S.string().optional(),injectedContextBytes:S.number().int().nonnegative().optional(),durationMs:S.number().nonnegative().optional(),approvalOutcome:S.enum(["carve-out","approved","denied","unrecognised","timeout","decline","cancel","hard-block"]).optional()}),sse=S.object({transition:S.literal("started"),subagentId:S.string(),parentId:S.string(),model:S.string(),allowedTools:S.array(S.string()).readonly().optional(),systemPromptHash:S.string().optional(),promptHead:S.string().optional(),agentType:S.string().optional(),resolvedAgentType:S.string().optional()}),ise=S.object({transition:S.literal("succeeded"),subagentId:S.string(),durationMs:S.number().nonnegative(),turnCount:S.number().int().nonnegative(),totalCostUsd:S.number().nonnegative().optional(),outputBytes:S.number().int().nonnegative(),stopReason:S.string().optional()}),ase=S.object({transition:S.literal("failed"),subagentId:S.string(),errorClass:S.string(),errorMessage:S.string(),partialOutputBytes:S.number().int().nonnegative(),failureClass:Zj.optional()}),cse=S.object({transition:S.literal("cancelled"),subagentId:S.string(),source:S.enum(["cascade","explicit"]),timeout:S.boolean().optional()}),nH=S.discriminatedUnion("transition",[sse,ise,ase,cse]),lse=S.object({transition:S.literal("started"),jobId:S.string(),subagentId:S.string(),label:S.string(),model:S.string()}),dse=S.object({transition:S.literal("completed"),jobId:S.string(),subagentId:S.string(),durationMs:S.number().nonnegative(),outputBytes:S.number().int().nonnegative()}),use=S.object({transition:S.literal("failed"),jobId:S.string(),subagentId:S.string(),durationMs:S.number().nonnegative(),errorClass:S.string(),errorMessage:S.string()}),pse=S.object({transition:S.literal("joined"),jobId:S.string(),subagentId:S.string(),jobStatus:S.enum(["completed","failed","cancelled"])}),fse=S.object({transition:S.literal("delivered"),jobId:S.string(),subagentId:S.string(),jobStatus:S.enum(["completed","failed","cancelled"])}),rH=S.discriminatedUnion("transition",[lse,dse,use,Hk,pse,fse]),oH=S.object({kind:S.literal("monetary"),runningCostUsd:S.number().nonnegative(),maxBudgetUsd:S.number().nonnegative(),lastTurnCostUsd:S.number().nonnegative()}),mse=S.enum(["user_signal","cascade","timeout","budget","hook_block"]),sH=S.object({origin:mse,cascadedTo:S.array(S.string()).readonly(),reason:S.string().optional()}),iH=S.enum(["manual","token_threshold","turn_count"]),gse=S.object({path:S.string(),sizeBytes:S.number().int().nonnegative(),sha256:S.string().regex(/^[0-9a-f]{64}$/)}),hse=S.object({trigger:iH,preCompactionMessages:S.array(S.unknown()),summary:S.string(),keptTailCount:S.number().int().nonnegative(),keepLastNConfig:S.number().int().nonnegative(),messagesBefore:S.number().int().nonnegative(),messagesAfter:S.number().int().nonnegative(),tokensSavedEstimate:S.number().nonnegative().optional(),summarizationTokens:S.object({input:S.number().int().nonnegative(),output:S.number().int().nonnegative()}).optional()}),yse=S.object({trigger:iH,preCompactionMessagesRef:gse,summary:S.string(),keptTailCount:S.number().int().nonnegative(),keepLastNConfig:S.number().int().nonnegative(),messagesBefore:S.number().int().nonnegative(),messagesAfter:S.number().int().nonnegative(),tokensSavedEstimate:S.number().nonnegative().optional(),summarizationTokens:S.object({input:S.number().int().nonnegative(),output:S.number().int().nonnegative()}).optional()}),bse=S.enum(["model_end_turn","truncated","iteration_cap","abort","timeout","budget_exceeded","hook_blocked","max_turns_exceeded"]),aH=S.object({reason:bse,finalTurnCount:S.number().int().nonnegative(),finalCostUsd:S.number().nonnegative(),finalTokens:S.object({input:S.number().int().nonnegative().optional(),output:S.number().int().nonnegative().optional(),cacheRead:S.number().int().nonnegative().optional(),cacheCreation:S.number().int().nonnegative().optional()}),lastStopReason:S.string().optional(),guidance:S.string().optional()}),cH=S.object({source:S.string(),assertion:S.string(),evidence:S.array(S.string()).readonly(),confidence:S.number().min(0).max(1),dissent:S.string().optional()}),wse=S.enum(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),Sse=S.enum(["click","fill","press","select","hover","scroll_to","wait_for"]),kse=S.object({kind:S.enum(["semantic","element_id","selector"]),text:S.string().max(80).optional(),role:S.string().optional(),elementId:S.string().optional(),selectorHash:S.string().regex(/^[0-9a-f]{8}$/).optional()}),lH=S.object({jobId:S.string(),subagentId:S.string(),byteLength:S.number().int().nonnegative()}),dH=S.object({tool:wse,action:Sse.optional(),toolUseId:S.string(),backend:S.enum(["playwright","agent-browser"]).optional(),backendReason:S.string().optional(),target:kse.optional(),urlBefore:S.string().nullable(),urlAfter:S.string().nullable(),status:S.enum(["ok","error","ambiguous_target","blocked_by_policy"]),screenshotPath:S.string().optional(),observationSummary:S.string().max(500).optional(),error:S.object({reason:S.string(),recoverable:S.boolean()}).optional(),durationMs:S.number().nonnegative()}),vse=S.enum(["bootstrap_start","bootstrap_done","session_init_start","session_init_done","mcp_connect_start","mcp_connect_done","mcp_server_start","mcp_server_done","loop_start","loop_end","model_ttfb","interrupt_halt","rate_limit","ttfb_timeout","usage_limit_pause","usage_limit_resume","overload_pause","overload_resume","idle_watchdog_fired","pause_extension_granted","suspected_loop","compaction_disabled","boot_warning"]),uH=S.object({phase:vse,durationMs:S.number().nonnegative().optional(),metadata:S.record(S.string(),S.union([S.string(),S.number(),S.boolean()])).optional(),model:S.string().optional(),resolvedModel:S.string().optional(),origin:S.enum(["cli","telegram","daemon","web","unknown"]).optional(),actor:S.enum(["main","subagent"]).optional()}),Tse=S.object({status:S.enum(["succeeded","failed","cancelled"]),finalCostUsd:S.number().nonnegative(),finalTurnCount:S.number().int().nonnegative(),closedAt:S.string().datetime(),incomplete:S.boolean().optional(),subagentCount:S.number().int().nonnegative().optional(),subagentTokens:S.object({input:S.number().int().nonnegative().optional(),output:S.number().int().nonnegative().optional(),cacheRead:S.number().int().nonnegative().optional(),cacheCreation:S.number().int().nonnegative().optional()}).optional(),subagentCostUsd:S.number().nonnegative().optional()}),pH=S.discriminatedUnion("kind",[S.object({kind:S.literal("tool_call"),payload:eH}),S.object({kind:S.literal("hook_decision"),payload:tH}),S.object({kind:S.literal("subagent_lifecycle"),payload:nH}),S.object({kind:S.literal("background_agent"),payload:rH}),S.object({kind:S.literal("budget"),payload:oH}),S.object({kind:S.literal("abort"),payload:sH}),S.object({kind:S.literal("compaction"),payload:hse}),S.object({kind:S.literal("closure"),payload:aH}),S.object({kind:S.literal("claim"),payload:cH}),S.object({kind:S.literal("browser_event"),payload:dH}),S.object({kind:S.literal("queued_user_message"),payload:lH}),S.object({kind:S.literal("session_phase"),payload:uH})]),JXe=S.discriminatedUnion("kind",[S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("tool_call"),payload:eH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("hook_decision"),payload:tH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("subagent_lifecycle"),payload:nH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("background_agent"),payload:rH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("budget"),payload:oH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("abort"),payload:sH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("compaction"),payload:yse}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("closure"),payload:aH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("claim"),payload:cH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("browser_event"),payload:dH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("queued_user_message"),payload:lH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("session_phase"),payload:uH}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("session_sealed"),payload:Tse})]);var um=new Set,mH=!1;function Ise(){mH||(mH=!0,process.on("exit",()=>{for(let t of um)t.sealOnProcessExit()}))}var pm=class{traceDir;tracePath;seq;sealed=!1;sealRecordPersisted=!1;fh=null;writeQueue=Promise.resolve();constructor(e){this.traceDir=e.traceDir,this.tracePath=fH(this.traceDir,"trace.jsonl"),this.seq=e.startSeq??0}getTracePath(){return this.tracePath}async write(e){if(this.sealed)throw new Error("NdjsonTraceWriter: trace is sealed; write() rejected");return pH.parse(e),this.enqueue(async()=>{await this.ensureOpen();let n=await this.materializePersistedEvent(e);await this.appendLine(n)})}async seal(e){this.sealed||(this.sealed=!0,await this.enqueue(async()=>{if(await this.ensureOpen(),this.sealRecordPersisted)return;let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:e};await this.appendLine(n),this.sealRecordPersisted=!0,this.fh&&await this.fh.sync()}),await this.closeHandle())}async close(){await this.enqueue(async()=>{}),await this.closeHandle()}enqueue(e){let n=this.writeQueue.then(e,e);return this.writeQueue=n.then(()=>{},()=>{}),n}async ensureOpen(){this.fh||(await Ase(this.traceDir,{recursive:!0}),this.fh=await xse(this.tracePath,"a"),um.add(this),Ise())}async closeHandle(){if(um.delete(this),!this.fh)return;let e=this.fh;this.fh=null,await e.close()}sealOnProcessExit(){if(this.sealRecordPersisted||this.seq===0)return;this.sealed=!0,um.delete(this);try{let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:{status:"failed",finalCostUsd:0,finalTurnCount:0,closedAt:new Date().toISOString(),incomplete:!0}};_se(this.tracePath,`${JSON.stringify(n)}
|
|
1728
1728
|
`),this.sealRecordPersisted=!0}catch{}let e=this.fh;this.fh=null,e&&e.close().catch(()=>{})}async appendLine(e){if(!this.fh)throw new Error("NdjsonTraceWriter: file handle missing");await this.fh.appendFile(`${JSON.stringify(e)}
|
|
1729
1729
|
`)}async materializePersistedEvent(e){let n=new Date().toISOString(),r=this.seq++;if(e.kind==="compaction"){let o=await this.persistCompactionSidecar(e.payload,r,n);return{ts:n,seq:r,kind:"compaction",payload:o}}return{ts:n,seq:r,kind:e.kind,payload:e.payload}}async persistCompactionSidecar(e,n,r){let o=r.replace(/[:.]/g,"-"),s=fH(this.traceDir,`${String(n).padStart(6,"0")}-${o}-pre-compaction.json`),i=JSON.stringify(e.preCompactionMessages),a=Buffer.byteLength(i,"utf8"),c=Ese("sha256").update(i).digest("hex");await Rse(s,i,{encoding:"utf8",flag:"w"});let l={path:s,sizeBytes:a,sha256:c};return{trigger:e.trigger,preCompactionMessagesRef:l,summary:e.summary,keptTailCount:e.keptTailCount,keepLastNConfig:e.keepLastNConfig,messagesBefore:e.messagesBefore,messagesAfter:e.messagesAfter,...e.tokensSavedEstimate!==void 0?{tokensSavedEstimate:e.tokensSavedEstimate}:{},...e.summarizationTokens!==void 0?{summarizationTokens:e.summarizationTokens}:{}}}};function Ose(t){if(!Mse(t))return;let n=Pse(t,"utf8").split(`
|
|
1730
1730
|
`).filter(r=>r.trim().length>0);if(n.length!==0)try{let r=n[n.length-1]??"",s=JSON.parse(r).seq;return typeof s=="number"?s:void 0}catch{return}}function Wk(t={}){if(k.AFK_TRACE_DISABLED==="1")return null;let e=t.sessionLabel??Cse(),n=it(e),r=`${n}/trace.jsonl`,o=Ose(r),s=new pm({traceDir:n,...o!==void 0?{startSeq:o+1}:{}});return{writer:s,tracePath:s.getTracePath(),sessionLabel:e}}function gH(t=Wk){return t()?.writer??null}function Gs(t,e={}){let n="traceWriter"in e?e.traceWriter??null:(e.createTraceWriter??Wk)()?.writer??null,r=n?{traceWriter:n,...t,surface:"telegram"}:{...t,surface:"telegram"};return(e.newSession??((s,i)=>new Yr(s,i)))(r,t.traceWriter===void 0?n??void 0:void 0)}import{Client as CH}from"@modelcontextprotocol/sdk/client/index.js";import{CallToolResultSchema as Xse}from"@modelcontextprotocol/sdk/types.js";import{StreamableHTTPError as FH}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{UnauthorizedError as Jk}from"@modelcontextprotocol/sdk/client/auth.js";import{StdioClientTransport as Use}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Bse}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as jse}from"@modelcontextprotocol/sdk/client/sse.js";var Dse=[/^.+_API_KEY$/i,/^.+_TOKEN/i,/^.+_SECRET/i,/^.+_PASSWORD$/i,/^AWS_/i,/^GCP_/i,/^AZURE_/i,/^ANTHROPIC_/i,/^OPENAI_/i];function Fse(t){return Dse.some(e=>e.test(t))}var Lse=new Set(["NODE_OPTIONS","NODE_PATH","LD_PRELOAD","RUBYOPT"]),Nse=["DYLD_","PYTHON","PERL5"];function $se(t){if(Lse.has(t))return!0;for(let e of Nse)if(t.startsWith(e))return!0;return!1}function hH(t,e,n,r=[]){return e!=="project"?{allowed:!0}:Fse(t)?r.includes(t)?{allowed:!0}:{allowed:!1,warning:`[mcp:${n}] blocked secret expansion: \${${t}} matches a known-secret pattern and this is a project-local server. To opt in, add \`"allowSecretEnv": ["${t}"]\` to this server's entry in ~/.afk/config/mcp.json (not in the project .mcp.json \u2014 project files cannot self-authorize).`}:{allowed:!0}}function yH(t){let e=[];for(let n of Object.keys(t))$se(n)&&(delete t[n],e.push(n));return e}var bH=/\$(\$)?\{([A-Z_][A-Z0-9_]*)\}/gi;function fm(t,e=process.env){let n=[];return{value:t.replace(bH,(o,s,i)=>{if(s==="$")return`\${${i}}`;let a=e[i];return a===void 0||a===""?(n.push(i),""):a}),missing:n}}function Kk(t,e=process.env){if(t===void 0)return{value:{},missing:[]};let n={},r=new Set;for(let[o,s]of Object.entries(t)){let{value:i,missing:a}=fm(s,e);n[o]=i;for(let c of a)r.add(c)}return{value:n,missing:[...r]}}function wH(t,e,n=process.env,r=console.warn){let o=[],s=[];return{value:t.replace(bH,(a,c,l)=>{if(c==="$")return`\${${l}}`;let d=hH(l,e.layer,e.serverName,e.allowSecretEnv);if(!d.allowed)return d.warning&&r(d.warning),s.push(l),"";let u=n[l];return u===void 0||u===""?(o.push(l),""):u}),missing:o,blocked:s}}function SH(t,e,n=process.env,r=console.warn){if(t===void 0)return{value:{},missing:[],blocked:[]};let o={},s=new Set,i=new Set;for(let[a,c]of Object.entries(t)){let{value:l,missing:d,blocked:u}=wH(c,e,n,r);o[a]=l;for(let p of d)s.add(p);for(let p of u)i.add(p)}return{value:o,missing:[...s],blocked:[...i]}}function kH(t,e,n=process.env,r=console.warn){if(t===void 0)return{headers:{},missing:[],blocked:[]};let o={},s=new Set,i=new Set;for(let[a,c]of Object.entries(t)){let{value:l,missing:d,blocked:u}=wH(c,e,n,r);if(d.length>0)for(let p of d)s.add(p);else if(u.length===0)o[a]=l;else for(let p of u)i.add(p)}return{headers:o,missing:[...s],blocked:[...i]}}function Hse(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"||t==="0.0.0.0"}function Wse(){let t=["PATH","HOME","USER","USERNAME","LOGNAME","SHELL","TERM","TMPDIR","TEMP","TMP","LANG","LC_ALL","SYSTEMROOT","APPDATA","LOCALAPPDATA","PROGRAMDATA","PROGRAMFILES","NODE_PATH"],e={};for(let n of t){let r=process.env[n];typeof r=="string"&&(e[n]=r)}return e}function vH(t,e=process.env){if(t===void 0)return{headers:{},missing:[]};let n={},r=new Set;for(let[o,s]of Object.entries(t)){let{value:i,missing:a}=fm(s,e);if(a.length>0)for(let c of a)r.add(c);else n[o]=i}return{headers:n,missing:[...r]}}function mm(t,e,n,r="user-global",o=[]){let s=e.type??(e.command?"stdio":"streamable-http");if(s==="stdio"){if(typeof e.command!="string"||e.command.length===0)throw new Error(`McpTransport(${t}): stdio requires \`command\``);let i;if(r==="project"){let{value:l,missing:d,blocked:u}=SH(e.env,{layer:r,serverName:t,allowSecretEnv:o});d.length>0&&console.warn(`[mcp:${t}] missing env vars (passing as empty): ${d.join(", ")}`),u.length>0&&console.warn(`[mcp:${t}] ${u.length} secret expansion(s) blocked for project-local server`),i=l}else{let{value:l,missing:d}=Kk(e.env);d.length>0&&console.warn(`[mcp:${t}] missing env vars (passing as empty): ${d.join(", ")}`),i=l}let a=Wse();if(r==="project"){let l=yH(a);l.length>0&&console.warn(`[mcp:${t}] scrubbed dangerous inherited env vars for project-local server: ${l.join(", ")}`)}let c={command:e.command,...e.args?{args:e.args}:{},env:{...a,...i}};return{transport:new Use(c),isSSE:!1}}if(s==="streamable-http"||s==="sse"){if(typeof e.url!="string"||e.url.length===0)throw new Error(`McpTransport(${t}): ${s} requires \`url\``);let i=new URL(e.url);if(i.protocol!=="https:"&&!Hse(i.hostname))throw new Error(`McpTransport(${t}): refusing ${s} URL ${i.protocol}//${i.hostname} \u2014 credentials and tool I/O would transit in plaintext. Use https:, or point the URL at localhost / 127.0.0.1.`);let a,c;if(r==="project"){let{headers:d,missing:u,blocked:p}=kH(e.headers,{layer:r,serverName:t,allowSecretEnv:o});p.length>0&&console.warn(`[mcp:${t}] ${p.length} secret header expansion(s) blocked for project-local server`),a=d,c=u}else{let{headers:d,missing:u}=vH(e.headers);a=d,c=u}return c.length>0&&console.warn(`[mcp:${t}] missing header vars (passing as omitted): ${c.join(", ")}`),s==="sse"?(process.stderr.write(`[mcp:${t}] WARNING: SSE transport is deprecated. Upgrade your MCP server to use streamable-HTTP.
|
|
1731
|
-
`),{transport:new jse(i,{...Object.keys(a).length>0?{requestInit:{headers:a}}:{},...n?{authProvider:n}:{}}),isSSE:!0}):{transport:new Bse(i,{...Object.keys(a).length>0?{requestInit:{headers:a}}:{},...n?{authProvider:n}:{}}),isSSE:!1}}throw new Error(`McpTransport(${t}): unknown transport type "${String(s)}"`)}B();import{existsSync as qk,mkdirSync as xH,readFileSync as Gk,writeFileSync as Xk}from"node:fs";import{execFileSync as TH}from"node:child_process";import{randomUUID as Kse}from"node:crypto";import{homedir as EH,userInfo as _H}from"node:os";import{join as AH,dirname as RH}from"node:path";var
|
|
1731
|
+
`),{transport:new jse(i,{...Object.keys(a).length>0?{requestInit:{headers:a}}:{},...n?{authProvider:n}:{}}),isSSE:!0}):{transport:new Bse(i,{...Object.keys(a).length>0?{requestInit:{headers:a}}:{},...n?{authProvider:n}:{}}),isSSE:!1}}throw new Error(`McpTransport(${t}): unknown transport type "${String(s)}"`)}B();import{existsSync as qk,mkdirSync as xH,readFileSync as Gk,writeFileSync as Xk}from"node:fs";import{execFileSync as TH}from"node:child_process";import{randomUUID as Kse}from"node:crypto";import{homedir as EH,userInfo as _H}from"node:os";import{join as AH,dirname as RH}from"node:path";var Rze=600*1e3;function qse(){let t=process.platform==="darwin",e=process.platform==="linux";return{read(){if(t)try{return TH("security",["find-generic-password","-s","Claude Code-credentials","-a",_H().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0}catch{return}if(e){let n=AH(EH(),".claude",".credentials.json");if(!qk(n))return;try{return Gk(n,"utf-8")}catch{return}}},write(n){if(t)TH("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",_H().username,"-w",n],{stdio:["ignore","ignore","ignore"]});else if(e){let r=AH(EH(),".claude",".credentials.json");xH(RH(r),{recursive:!0}),Xk(r,n,{encoding:"utf-8",mode:384})}}}}function IH(t){let e=Jc();if(!qk(e))return;let n;try{n=JSON.parse(Gk(e,"utf-8"))}catch{return}t in n&&(delete n[t],Xk(e,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}))}function Gse(t,e){let n=Jc();xH(RH(n),{recursive:!0});let r={};if(qk(n))try{r=JSON.parse(Gk(n,"utf-8"))}catch{}let o=new URL(e),s=o.origin+o.pathname;r[t]={status:"oauth_pending",authorizationUrl:s,timestamp:Date.now()},Xk(n,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}var Cc=class{serverName;backend;constructor(e,n=qse()){this.serverName=e,this.backend=n}get redirectUrl(){return"http://localhost:3000/oauth/callback"}get clientMetadata(){return{redirect_uris:[this.redirectUrl],client_name:"agent-afk",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}clientInformation(){return this._readSlot().clientInfo}saveClientInformation(e){this._updateSlot(n=>({...n,clientInfo:e}))}tokens(){return this._readSlot().tokens}saveTokens(e){this._updateSlot(n=>({...n,tokens:e}));try{IH(this.serverName)}catch{}}saveCodeVerifier(e){this._updateSlot(n=>({...n,codeVerifier:e}))}codeVerifier(){let e=this._readSlot().codeVerifier;if(!e)throw new Error(`[mcp:${this.serverName}] no PKCE code verifier stored`);return e}state(){let e=this._readSlot().state;if(e)return e;let n=Kse();return this._updateSlot(r=>({...r,state:n})),n}saveDiscoveryState(e){this._updateSlot(n=>({...n,discoveryState:e}))}discoveryState(){return this._readSlot().discoveryState}invalidateCredentials(e){this._updateSlot(n=>{if(e==="all")return{};let r={...n};return e==="client"&&delete r.clientInfo,e==="tokens"&&delete r.tokens,e==="verifier"&&(delete r.codeVerifier,delete r.state),e==="discovery"&&delete r.discoveryState,r})}async redirectToAuthorization(e){let n=e.toString(),r=`\u{1F510} MCP server "${this.serverName}" requires authorization.
|
|
1732
1732
|
|
|
1733
1733
|
Open this URL to authorize:
|
|
1734
1734
|
${n}`;Gse(this.serverName,n);let o=!1;try{let{pushIfConfigured:s}=await Promise.resolve().then(()=>(Dr(),Px));o=await s(r)!==null}catch{}o||process.stderr.write(`[mcp:${this.serverName}] OAuth authorization required.
|
|
@@ -1776,7 +1776,7 @@ Single-pass sub-agent reports are prone to confident hallucination \u2014 polish
|
|
|
1776
1776
|
Skip when: the findings are purely exploratory, the sub-agent ran inside an already-verifying orchestrator, the user is about to dismiss the report, or the stakes are low (read-only Q&A).`,yie=fie.map(t=>new RegExp(`(?:^|-)${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:-|$)`,"i"));function bie(t){return t?yie.some(e=>e.test(t)):!1}function wie(t){return gie.some(e=>e.test(t))}function Sie(t){let e=0;for(let n of mie)n.test(t)&&e++;return e}function qH(){let t=!1,e=new Set;return n=>{if(n.event==="Stop")return t=!1,{};if(n.event!=="SubagentStop")return{};let r=n.lastMessage??"";return r.length<600?{}:bie(n.agentType)?{}:wie(r)?{}:Sie(r)<2?{}:t||e.has(n.subagentId)?{}:(t=!0,e.add(n.subagentId),{injectContext:hie})}}$n();Dr();var GH=300,kie="ask_question gate: no interactive operator is attached to this surface (no elicitation handler \u2014 daemon/scheduled/one-shot run), so the question cannot be answered now. The operator has been notified asynchronously. Do not re-ask or wait. Choose the most reasonable interpretation, state the assumption explicitly in your final report for async review, and proceed. If no safe assumption exists and the next action would be irreversible, end the turn with a Blocked terminal state naming exactly what the operator must supply.";function vie(t){Dn(t).catch(()=>{})}function XH(t={}){let e=t.hasHandler??(()=>He.hasHandler()),n=t.notify??vie;return function(o){if(o.event!=="PreToolUse")return{};if(o.toolName!=="ask_question")return{};if(e())return{};try{let i=(typeof o.input=="object"&&o.input!==null?String(o.input.question??""):"").trim(),a=i.length<=GH?i:`${i.slice(0,GH)}\u2026(truncated)`;n(`\u{1F514} AFK question (auto-gated; agent proceeds on a stated assumption):
|
|
1777
1777
|
`+(a!==""?a:"(question text unavailable)"))}catch{}return{decision:"block",reason:kie}}}var Zk=[{id:"rm-recursive-force",re:/\brm\s+-(?=[a-z]*r)(?=[a-z]*f)[a-z]+/i,tier:"observe"},{id:"rm-recursive-force-split",re:/\brm\s+-[a-z]*r[a-z]*\s+-[a-z]*f|\brm\s+-[a-z]*f[a-z]*\s+-[a-z]*r/i,tier:"observe"},{id:"rm-recursive-force-long",re:/\brm\s+[^|&;\n]*--recursive\b[^|&;\n]*--force\b|\brm\s+[^|&;\n]*--force\b[^|&;\n]*--recursive\b/i,tier:"observe"},{id:"rm-no-preserve-root",re:/\brm\b[^|&;\n]*--no-preserve-root\b/i,tier:"block",blockReason:"safe-destruct: blocked [rm-no-preserve-root] \u2014 explicit root-wipe flag, irrecoverable; remove the --no-preserve-root flag, or target a non-root path instead."},{id:"git-reset-hard",re:/\bgit\s+(?:(?:-{2}[\w-]+(?:=\S+)?|-[A-Za-z](?:\s+\S+)?)\s+)*reset\s+--hard\b/i,tier:"block",blockReason:'safe-destruct: blocked [git-reset-hard] \u2014 discards all uncommitted changes irrecoverably; commit or run "git stash" first. This hook cannot be self-bypassed: if the destruction is genuinely intended, stop and ask the operator to run it.'},{id:"git-clean-force",re:/\bgit\s+(?:(?:-{2}[\w-]+(?:=\S+)?|-[A-Za-z](?:\s+\S+)?)\s+)*clean\s+-[a-z]*f|\bgit\s+(?:(?:-{2}[\w-]+(?:=\S+)?|-[A-Za-z](?:\s+\S+)?)\s+)*clean\s+[^|&;\n]*--force\b/i,tier:"block",blockReason:'safe-destruct: blocked [git-clean-force] \u2014 deletes untracked files irrecoverably; use "git clean -n" (dry-run) to preview. This hook cannot be self-bypassed: if the destruction is genuinely intended, stop and ask the operator to run it.'},{id:"git-push-force",re:/\bgit\s+(?:(?:-{2}[\w-]+(?:=\S+)?|-[A-Za-z](?:\s+\S+)?)\s+)*push\b[^|&;\n]*--force(?!-)|\bgit\s+(?:(?:-{2}[\w-]+(?:=\S+)?|-[A-Za-z](?:\s+\S+)?)\s+)*push\b[^|&;\n]*(?<![\w-])-f\b/i,tier:"block",blockReason:'safe-destruct: blocked [git-push-force] \u2014 rewrites remote history, permanently destructive for all branch consumers; prefer "--force-with-lease" or coordinate with collaborators first.'},{id:"git-branch-force-delete",re:/\bgit\s+branch\s+[^|&;\n]*-D\b/,tier:"observe"},{id:"dd-to-device",re:/\bof=\/dev\/(?!null\b|zero\b|random\b|urandom\b|stdout\b|stderr\b|tty\b)\S/i,tier:"block",blockReason:"safe-destruct: blocked [dd-to-device] \u2014 writing directly to a block device is irrecoverable; verify the target path is a file, not a device node."},{id:"mkfs",re:/\bmkfs(\.\w+)?\b/i,tier:"block",blockReason:"safe-destruct: blocked [mkfs] \u2014 formats a filesystem, irrecoverably destroying all data on the target device; confirm the device path. This hook cannot be self-bypassed: if the destruction is genuinely intended, stop and ask the operator to run it."},{id:"redirect-to-block-device",re:/>\s*\/dev\/(sd|nvme|hd|disk|mmcblk|vd)\w*/i,tier:"block",blockReason:"safe-destruct: blocked [redirect-to-block-device] \u2014 shell redirect to a block device overwrites raw sectors irrecoverably; redirect to a file path instead."},{id:"find-delete",re:/\bfind\b[^|&;\n]*-delete\b|\bfind\b[^|&;\n]*-exec\s+rm\b/i,tier:"observe"},{id:"shred",re:/\bshred\b/i,tier:"block",blockReason:'safe-destruct: blocked [shred] \u2014 overwrites file data irrecoverably, bypassing the filesystem; use "rm" if secure deletion is not required. This hook cannot be self-bypassed: if the destruction is genuinely intended, stop and ask the operator to run it.'},{id:"sql-drop-truncate",re:/\b(drop\s+(table|database|schema|index)\b|truncate\s+table\b)/i,tier:"block",blockReason:"safe-destruct: blocked [sql-drop-truncate] \u2014 DDL destructor removes schema objects or all rows without a transaction rollback path; back up or use a migration with a down step. This hook cannot be self-bypassed: if the destruction is genuinely intended, stop and ask the operator to run it."},{id:"sql-delete-from",re:/\bdelete\s+from\b/i,tier:"observe"},{id:"curl-write-method",re:/\bcurl\b[^|;&]*\s(-X\s*|--request\s+)(POST|PUT|PATCH|DELETE)\b/i,tier:"observe"},{id:"curl-data-flag",re:/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)|\bwget\b[^|;&]*\s(--post-data\b|--post-file\b)/i,tier:"observe"},{id:"docker-destructive",re:/\bdocker\s+(system\s+prune|volume\s+(rm|prune)|image\s+prune|container\s+prune|network\s+prune)\b|\bdocker\b[^|&;\n]*\brmi?\s+[^|&;\n]*-f/i,tier:"observe"},{id:"kubectl-delete",re:/\bkubectl\s+delete\b/i,tier:"observe"},{id:"terraform-destroy",re:/\bterraform\s+destroy\b/i,tier:"block",blockReason:'safe-destruct: blocked [terraform-destroy] \u2014 tears down live external infrastructure irrecoverably (new apply creates new resources, not the same ones); run "terraform plan -destroy" to preview. This hook cannot be self-bypassed: if the destruction is genuinely intended, stop and ask the operator to run it.'},{id:"launchctl-service-register",re:/\blaunchctl\s+(?:(?:-{2}[\w-]+(?:=\S+)?|-[A-Za-z](?:\s+\S+)?)\s+)*(load|bootstrap|submit|start|kickstart|enable)(?:\s|$)/i,tier:"block",blockReason:"safe-destruct: blocked [launchctl-service-register] \u2014 installs a persistent launchd service that survives reboots and session boundaries; use `afk service install` via /service-setup instead. This hook cannot be self-bypassed: if the destruction is genuinely intended, stop and ask the operator to run it."},{id:"systemctl-service-enable",re:/\bsystemctl\s+(?:(?:-{2}[\w-]+(?:=\S+)?|-[A-Za-z](?:\s+\S+)?)\s+)*(enable|start|daemon-reload)(?:\s|$)/i,tier:"block",blockReason:"safe-destruct: blocked [systemctl-service-enable] \u2014 enables/starts a systemd unit that persists across sessions and reboots; use `afk service install` via /service-setup instead. This hook cannot be self-bypassed: if the destruction is genuinely intended, stop and ask the operator to run it."}];var Tie="safe-destruct observe-only: destructive-command attempt",Eie="This command was blocked by the safe-destruct hook because it matches an irrecoverable or externally-irreversible operation pattern. The block cannot be self-bypassed. If the destructive action is genuinely required, stop and ask the operator to run it manually, or use a safer alternative named in the block reason above.";function _ie(t){if(!t)return[];let e=[];for(let{id:n,re:r}of Zk)r.test(t)&&e.push(n);return e}function zH(){return function(e){if(e.event!=="PreToolUse")return{};if(e.toolName!=="bash")return{};let n=e.input,r=typeof n?.command=="string"?n.command:"";if(!r)return{};let o=_ie(r);if(o.length===0)return{};let s=new Map(Zk.map(i=>[i.id,i]));for(let i of o){let a=s.get(i);if(a?.tier==="block")return{decision:"block",reason:a.blockReason,injectContext:Eie}}return{decision:"approve",reason:`${Tie} [${o.join(", ")}]`}}}var ev=[{id:"npm-publish",re:/\bnpm\s+publish\b/i,tier:"block",blockReason:"release-boundary: blocked [npm-publish] \u2014 publishes a package to the npm registry, externally irreversible once consumed by dependents; verify changelog, version, and generated docs are current before publishing."},{id:"pnpm-publish",re:/\bpnpm\s+publish\b/i,tier:"block",blockReason:"release-boundary: blocked [pnpm-publish] \u2014 publishes a package to the npm registry, externally irreversible once consumed by dependents; verify changelog, version, and generated docs are current before publishing."},{id:"yarn-publish",re:/\byarn\s+(?:npm\s+)?publish\b/i,tier:"block",blockReason:"release-boundary: blocked [yarn-publish] \u2014 publishes a package to the npm registry, externally irreversible once consumed by dependents; verify changelog, version, and generated docs are current before publishing."},{id:"cargo-publish",re:/\bcargo\s+(?:--[\w-]+\s+)*publish\b/i,tier:"block",blockReason:"release-boundary: blocked [cargo-publish] \u2014 publishes a crate to crates.io, externally irreversible (crates.io does not allow un-publishing); verify Cargo.toml version and changelog."},{id:"pypi-twine-upload",re:/\btwine\s+upload\b/i,tier:"block",blockReason:"release-boundary: blocked [pypi-twine-upload] \u2014 uploads a package to PyPI, externally irreversible once consumed; verify setup.py/pyproject.toml version and changelog."},{id:"poetry-publish",re:/\bpoetry\s+publish\b/i,tier:"block",blockReason:"release-boundary: blocked [poetry-publish] \u2014 publishes a package to PyPI, externally irreversible once consumed; verify pyproject.toml version and changelog."},{id:"gem-push",re:/\bgem\s+push\b/i,tier:"block",blockReason:"release-boundary: blocked [gem-push] \u2014 pushes a gem to RubyGems, externally irreversible once consumed; verify gemspec version and changelog."},{id:"docker-push",re:/\bdocker\s+(?:image\s+)?push\b/i,tier:"block",blockReason:"release-boundary: blocked [docker-push] \u2014 pushes a container image to a registry, externally irreversible once pulled by consumers; verify image tag and contents."},{id:"gh-release-create",re:/\bgh\s+release\s+create\b/i,tier:"block",blockReason:"release-boundary: blocked [gh-release-create] \u2014 creates a GitHub release, externally visible and triggering downstream workflows; verify release notes and tag."},{id:"terraform-apply",re:/\bterraform\s+apply\b/i,tier:"block",blockReason:'release-boundary: blocked [terraform-apply] \u2014 applies infrastructure changes to live systems, externally irreversible (new apply creates different resources); run "terraform plan" to preview first.'},{id:"kubectl-apply",re:/\bkubectl\s+apply\b/i,tier:"block",blockReason:"release-boundary: blocked [kubectl-apply] \u2014 applies resources to a live Kubernetes cluster, externally irreversible for stateful workloads; verify manifests and target namespace."},{id:"git-push-mirror",re:/\bgit\s+push\b[^|&;\n]*--mirror\b/i,tier:"observe"},{id:"git-push-tags",re:/\bgit\s+push\b[^|&;\n]*--(?:tags|follow-tags)\b/i,tier:"observe"}];var JH="release-boundary observe-only: sync-boundary command",Aie="This command was blocked by the release-boundary hook because it crosses an externally-irreversible publish or deploy boundary. Once a package is published, a container pushed, a release cut, or infrastructure applied, the external state change cannot be undone by the agent. Verify that all living artifacts (changelog, version, generated docs, lock files) are up-to-date before proceeding, and ask the operator to confirm publication.";function xie(t){return/--dry-run\b/i.test(t)||/-refresh-only\b/i.test(t)}function Rie(t){let e=t.replace(/'[^']*'/g,"");return e=e.replace(/#[^\n]*/g,""),e}function Iie(t){if(!t)return[];let e=Rie(t),n=[];for(let{id:r,re:o}of ev)o.test(e)&&n.push(r);return n}function Cie(t){return ev.find(e=>e.id===t)}function VH(){return function(e){if(e.event!=="PreToolUse")return{};if(e.toolName!=="bash")return{};let n=e.input,r=typeof n?.command=="string"?n.command:"";if(!r)return{};let o=Iie(r);if(o.length===0)return{};if(xie(r))return{decision:"approve",reason:`${JH} [${o.join(", ")}] (dry-run: not blocked)`};for(let s of o){let i=Cie(s);if(i?.tier==="block")return{decision:"block",reason:i.blockReason,injectContext:Aie}}return{decision:"approve",reason:`${JH} [${o.join(", ")}]`}}}Nt();da();Dg();function YH(t){return function(n){if(n.event!=="PreToolUse")return{};if(n.parentSessionId)return{};if(t()!=="plan")return{};let{toolName:r}=n;if(su(r)==="write")return{decision:"block",reason:`plan mode: ${r} is refused. Use /plan off to exit plan mode.`};if(r==="worktree"){let o=typeof n.input=="object"&&n.input!==null?String(n.input.action??""):"";if(o!=="list")return{decision:"block",reason:`plan mode: worktree "${o}" is refused (mutates the worktree registry). Only action "list" is allowed in plan mode. Use /plan off to act.`}}if(r==="test_run"&&(typeof n.input=="object"&&n.input!==null?n.input.coverage===!0:!1))return{decision:"block",reason:"plan mode: test_run with coverage=true is refused \u2014 coverage writes artifact files to disk. Run without coverage, or use /plan off to act."};if(r==="bash"){let o=typeof n.input=="object"&&n.input!==null?String(n.input.command??""):"",s=Vl(o);if(s.mutating)return{decision:"block",reason:`plan mode: bash refused \u2014 command looks state-mutating (${s.reason??"mutation detected"}). Read-only investigation (git status/log/diff, ls, cat, grep, find) is allowed. Use /plan off to act.`}}return{}}}Vy();$n();J();Sa();Kb();import Ys from"path";Rr();import tv from"path";import{lstatSync as Pie}from"fs";import{spawnSync as Mie}from"child_process";var Oie=new Set(["node_modules","dist","build",".next","coverage",".cache","__pycache__",".turbo",".parcel-cache","out","target"]),Die=/[*?$`(){};|&<>'"\\\r\n]/;function Fie(t){return t==="--recursive"?!0:t.startsWith("--")?!1:/^-[A-Za-z]+$/.test(t)&&/[rR]/.test(t)}function Lie(t){if(!/^rm\b/.test(t)||Die.test(t))return null;let e=t.trim().split(/\s+/),n=[],r=!1,o=!1;for(let s of e.slice(1)){if(!o&&s==="--"){o=!0;continue}if(!o&&s.startsWith("-")){Fie(s)&&(r=!0);continue}n.push(s)}return n.length===0?null:{targets:n,recursive:r}}function Nie(t,e){try{return Pie(t).isDirectory()?Mie("git",["check-ignore","--quiet","--",t],{cwd:e,stdio:"ignore"}).status===0:!1}catch(n){return n.code==="ENOENT"}}function QH(t,e,n){let r=Lie(t);if(r===null||!r.recursive)return!1;let o=Be(n);for(let s of r.targets){if(s==="/"||s==="."||s===".."||s==="~"||s.startsWith("~/")||s==="$HOME"||s.startsWith("$HOME/")||s===".git"||s.startsWith(".git/"))return!1;let i=Be(tv.resolve(e,s));if(i===o||!i.startsWith(o+tv.sep)||!Oie.has(tv.basename(i))||!Nie(i,o))return!1}return!0}var $ie=3e5,ZH=300;function eW(t,e,n,r){let o=r?.approvalTimeoutMs??$ie,s=r?.promptForApproval??!0,i=r?.traceWriter,a=r?.sessionId,c=r?.route??((d,u)=>He.route(d,u));async function l(d,u,p,f){let m=Date.now(),g=Uie(d,u),y=new AbortController,b=()=>y.abort();p&&(p.aborted?y.abort():p.addEventListener("abort",b,{once:!0}));let w=Symbol("afk-approval-timeout"),v,_,x=new Promise(T=>{_=()=>{v||(v=setTimeout(()=>{y.abort(),T(w)},o),v.unref?.())}});function A(T,R){let E=Date.now()-m,P=T.decision==="block";return dt(i,{hookEvent:"PreToolUse",...P?{decision:"block"}:{},...P&&T.reason!==void 0?{reason:T.reason}:{},...P?{blockedTool:d}:{},durationMs:E,approvalOutcome:R}),T}let I;try{let T=f??a;I=await Promise.race([c(g,{signal:y.signal,onActive:_,...T!==void 0?{sessionId:T}:{}}),x])}finally{v&&clearTimeout(v),p&&p.removeEventListener("abort",b)}if(I===w)return A(Fc(d,`no approval arrived within ${Math.round(o/1e3)}s`),"timeout");if(I.action!=="accept")return A(Fc(d,I.action==="cancel"?"the operator cancelled the approval prompt":"no operator approval was available"),I.action==="cancel"?"cancel":"decline");let C=String(I.content?.choice??"").toLowerCase();return C==="approve"?A({},"approved"):C==="deny"?A(Fc(d,"the operator denied it"),"denied"):A(Fc(d,"the approval prompt returned an unrecognised choice"),"unrecognised")}return function(u,p){if(u.event!=="PreToolUse")return{};if(t()!=="autonomous")return{};let{toolName:f}=u,m=Date.now();if(f==="send_telegram")return{};let g=n?.()??e??process.cwd(),y=u.cwd,b=y??g,v=(y!==void 0?jie(y,g):void 0)??g,_=au(f,u.input,{cwd:b,workspaceRoot:v});if(_==="high"&&f==="bash"){let x=typeof u.input=="object"&&u.input!==null&&"command"in u.input?String(u.input.command??""):"";if(x&&QH(x,b,v))return dt(i,{hookEvent:"PreToolUse",blockedTool:f,durationMs:Date.now()-m,approvalOutcome:"carve-out"}),{}}if(_!=="high")return{};if(u.parentSessionId!==void 0||!s){let x=Fc(f,"AFK mode runs autonomously without a human watching");return dt(i,{hookEvent:"PreToolUse",decision:"block",...x.reason!==void 0?{reason:x.reason}:{},blockedTool:f,durationMs:Date.now()-m,approvalOutcome:"hard-block"}),x}return l(f,u.input,p,u.sessionId)}}function Uie(t,e){let n=Bie(e);return{serverName:"agent-afk",message:`AFK: \`${t}\` is high-risk / irreversible and AFK mode runs unattended. Approve this single call?`+(n?`
|
|
1778
1778
|
|
|
1779
|
-
Input: ${n}`:""),mode:"form",title:"AFK high-risk approval",requestedSchema:{type:"object",properties:{choice:{type:"string",title:"Approve this high-risk operation?",enum:["approve","deny"],description:"'approve' runs this single call. 'deny' refuses it (the model gets an error and should push an Asking summary or take a safe path)."}},required:["choice"]}}}function Bie(t){let e;try{e=typeof t=="string"?t:JSON.stringify(t)}catch{e=String(t)}return e?(e=Vr(e),e.length>ZH?`${e.slice(0,ZH)}\u2026 [truncated]`:e):""}function Fc(t,e){return{decision:"block",reason:`AFK mode: ${t} is refused \u2014 this op is high-risk or irreversible, and ${e}. Push an Asking summary to Telegram (send_telegram) and stop, or have the operator run /afk off and take over.`}}function jie(t,e){let n=Ys.resolve(t),r=Ys.resolve(e);if(n===r)return r;let o=Ys.relative(r,n);if(o!==""&&!o.startsWith("..")&&!Ys.isAbsolute(o))return os(n)??n;let s=os(r),i=os(n);if(s!==void 0&&i!==void 0&&Ys.dirname(s)===Ys.dirname(i))return i}fl();we();Zr();import{mkdirSync as Zie,rmSync as eae,writeFileSync as tae}from"fs";import{join as sv}from"path";se();ld();B();import{createHash as Hie}from"node:crypto";import{mkdirSync as Wie,existsSync as tW,unlinkSync as nW,readFileSync as Kie,writeFileSync as qie,renameSync as Gie}from"node:fs";import{join as rv,dirname as Xie}from"node:path";import{randomBytes as zie}from"node:crypto";function rW(){return rv(te(),"dag-checkpoints")}var Jie=/^[A-Za-z0-9_-]+$/;function ov(t){return!t||!Jie.test(t)||t.length>128?null:rv(rW(),`${t}.json`)}var nv=10*1024;function oW(t){let e=[...t.nodes.map(o=>o.id)].sort(),n=[...t.edges.map(o=>`${o.from}->${o.to}`)].sort(),r=JSON.stringify({nodes:e,edges:n});return Hie("sha256").update(r).digest("hex")}async function sW(t,e){Wie(rW(),{recursive:!0});let n=ov(t);if(n===null)throw new Error(`Invalid dagId: ${JSON.stringify(t)}`);let r=rv(Xie(n),`.tmp-${zie(4).toString("hex")}.json`);try{qie(r,JSON.stringify(e),"utf-8"),Gie(r,n)}catch(o){try{nW(r)}catch{}throw o}}async function iW(t,e){let n=ov(t);if(n===null||!tW(n))return null;let r;try{r=Kie(n,"utf-8")}catch{return null}let o;try{o=JSON.parse(r)}catch{return null}return o.dagHash!==e?null:o}async function aW(t){let e=ov(t);if(e!==null&&tW(e))try{nW(e)}catch{}}function cW(t){if(t===void 0)return"";let e=typeof t=="string"?t:JSON.stringify(t)??"";if(Buffer.byteLength(e,"utf8")<=nv)return e;let n=Buffer.from(e).subarray(0,nv).toString("utf8");for(;Buffer.byteLength(n,"utf8")>nv;)n=n.slice(0,-1);return n}function Vie(t){let e=new Set;for(let a of t.nodes){if(e.has(a.id))throw new Error(`Duplicate node ID: ${a.id}`);e.add(a.id)}let n=new Set;for(let a of t.edges){if(!e.has(a.from))throw new Error(`Edge references non-existent node: ${a.from}`);if(!e.has(a.to))throw new Error(`Edge references non-existent node: ${a.to}`);let c=`${a.from}->${a.to}`;if(n.has(c))throw new Error(`Duplicate edge: ${a.from} -> ${a.to}`);n.add(c)}let r=lW(t),o=new Map(r.inDegree),s=[];for(let[a,c]of o)c===0&&s.push(a);let i=0;for(;s.length>0;){let a=s.shift();i+=1;for(let c of r.downstream.get(a)??[]){let l=o.get(c)-1;o.set(c,l),l===0&&s.push(c)}}if(i!==e.size)throw new Error("Cycle detected in DAG")}function lW(t){let e=new Map,n=new Map,r=new Map;for(let o of t.nodes)e.set(o.id,new Set),n.set(o.id,new Set),r.set(o.id,0);for(let o of t.edges)e.get(o.from).add(o.to),n.get(o.to).add(o.from),r.set(o.to,r.get(o.to)+1);return{downstream:e,upstream:n,inDegree:r}}function Yie(t,e,n){let r=[t];for(;r.length>0;){let o=r.shift();for(let s of e.get(o)??[])n.has(s)||(n.add(s),r.push(s))}}async function dW(t,e,n={}){if(t.nodes.length===0)return{outputs:{},failed:[],skipped:[]};Vie(t);let{dagId:r,failFast:o=!0,nodeTimeoutMs:s,maxConcurrency:i=Ri()}=n,a=s!==void 0&&Number.isFinite(s)&&s>0,c=lW(t),l=new Map(t.nodes.map(w=>[w.id,w])),d={},u=[],p=new Set,f=new Set,m=new Map(c.inDegree),g=r!==void 0?oW(t):"";if(r!==void 0){let w=await iW(r,g);if(w!==null){for(let v of w.completedNodes){let _=w.nodeOutputs[v],x=_;if(_!==void 0)try{x=JSON.parse(_)}catch{x=_}d[v]=x,f.add(v),m.delete(v);for(let A of c.downstream.get(v)??[])m.set(A,m.get(A)-1)}for(let v of w.failedNodes){let _=w.nodeErrors?.[v]??"restored from checkpoint";u.push({id:v,error:new Error(_)}),f.add(v),m.delete(v)}for(let v of w.skippedNodes)p.add(v)}}let y=new AbortController,b=()=>{y.signal.aborted||y.abort(e.reason)};e.aborted?y.abort(e.reason):e.addEventListener("abort",b,{once:!0});try{for(;!y.signal.aborted;){let w=[];for(let[_,x]of m)x===0&&!f.has(_)&&!p.has(_)&&w.push(_);if(w.length===0)break;let v=await Lo(w,i,async _=>{let x=l.get(_),A=new AbortController,I=()=>{A.signal.aborted||A.abort(y.signal.reason)};y.signal.aborted?A.abort(y.signal.reason):y.signal.addEventListener("abort",I,{once:!0});let C;a&&!A.signal.aborted&&(C=setTimeout(()=>{A.signal.aborted||A.abort(new Ie(`DAG node "${_}" exceeded nodeTimeoutMs of ${s}ms`,s))},s));let T={};for(let R of c.upstream.get(_)??[])T[R]=d[R];try{let R=await x.run(T,A.signal);return{id:_,result:R}}finally{C!==void 0&&clearTimeout(C),y.signal.removeEventListener("abort",I)}});for(let _=0;_<v.length;_++){let x=v[_];if(x.status==="fulfilled"){let{id:A,result:I}=x.value;d[A]=I,f.add(A),m.delete(A);for(let C of c.downstream.get(A)??[])m.set(C,m.get(C)-1)}else{let A=x.reason instanceof Error?x.reason:new Error(String(x.reason)),I=w[_];u.push({id:I,error:A}),f.add(I),m.delete(I),Yie(I,c.downstream,p),o&&y.abort("fail-fast")}}if(r!==void 0&&!y.signal.aborted){let _={dagHash:g,completedNodes:Array.from(f).filter(x=>!u.some(A=>A.id===x)),nodeOutputs:Object.fromEntries(Object.entries(d).map(([x,A])=>[x,cW(A)])),failedNodes:u.map(x=>x.id),nodeErrors:Object.fromEntries(u.map(x=>[x.id,x.error.message])),skippedNodes:Array.from(p),timestamp:Date.now()};await sW(r,_).catch(()=>{})}}}finally{e.removeEventListener("abort",b)}return r!==void 0&&u.length===0&&await aW(r).catch(()=>{}),{outputs:d,failed:u,skipped:Array.from(p)}}Re();se();Wn();Rs();Yw();Ae();function Qie(t){let e=[];t.cwd!==void 0&&e.push({value:t.cwd,field:"cwd"});for(let n of t.readRoots??[])e.push({value:n,field:"readRoots"});for(let n of t.writeRoots??[])e.push({value:n,field:"writeRoots"});for(let{value:n,field:r}of e){let o=je(n);if(Qt(n)||Qt(o))throw new Error(`DAG node "${t.id}" ${r} "${n}" is too broad (filesystem root, home directory, or AFK directory)`);let s=oo(n)??oo(o);if(s!==void 0)throw new Error(`DAG node "${t.id}" ${r} "${n}" would un-gate credential root "${s}"`)}}async function uW(t){let{manager:e,parentSession:n,nodes:r,edges:o,failFast:s,nodeTimeoutMs:i}=t,a=n.abortSignal??new AbortController().signal,c=[i??0,za()].filter(u=>u>0),l=c.length>0?Nu(Math.min(...c)):0,d=r.map(u=>({id:u.id,async run(p,f){Qie(u);let m=await e.forkSubagent({parent:{sessionId:n.sessionId},config:{model:u.model??"sonnet",systemPrompt:u.systemPrompt,...u.canUseTool!==void 0?{canUseTool:u.canUseTool}:{},...u.cwd!==void 0?{cwd:u.cwd}:{},...u.readRoots!==void 0?{readRoots:u.readRoots}:{},...u.writeRoots!==void 0?{writeRoots:u.writeRoots}:{},...u.apiKey!==void 0?{apiKey:u.apiKey}:{},...u.maxToolUseIterations!==void 0?{maxToolUseIterations:u.maxToolUseIterations}:{},...u.provider!==void 0?{provider:u.provider}:{},...l!==0?{softDeadlineMs:l}:{}},idPrefix:u.idPrefix??`dag-${u.id}`,...u.outputSchema!==void 0?{outputSchema:u.outputSchema}:{},agentType:u.agentType??u.idPrefix??`dag-${u.id}`,...u.parentId!==void 0?{parentId:u.parentId}:{}}),g=()=>{m.cancel().catch(()=>{})};f.aborted?m.cancel().catch(()=>{}):f.addEventListener("abort",g,{once:!0});try{if(f.aborted)throw new DOMException("Aborted","AbortError");let y=u.promptBuilder(p),b=await m.runToResult(y);if(b.status!=="succeeded"){let v,_=f.reason;throw _ instanceof Ie?v=new Error(`Subagent ${u.id} aborted: ${_.message}`,b.error?{cause:b.error}:{}):v=b.error??new Error(`Subagent ${u.id} ${b.status}`),rF(v,{partialOutput:b.partialOutput,subagentId:b.id})}if(b.output!==void 0)return b.output;let w=b.message?.content;return typeof w=="string"?Es(w,b.stopReason):w}finally{f.removeEventListener("abort",g),await m.teardown().catch(()=>{})}}}));return dW({nodes:d,edges:o},a,{failFast:s,nodeTimeoutMs:i})}Jr();fe();be();Ua();Rt();ur();Qr();Ot();Ot();function pW(t,e,n){return e===void 0?{}:{provider:QF(t,e,n)}}_p();B();var fW=1e3,bm=36e5,mW=1,gW=1e3;function nae(t){if(typeof t!="object"||t===null)throw new Error("Compose tool input must be an object");let e=t,n=e.nodes;if(!Array.isArray(n)||n.length===0)throw new Error('Compose tool requires a non-empty "nodes" array');let r=20;if(n.length>r)throw new Error(`Compose tool supports at most ${r} nodes (got ${n.length}). Split into multiple compose calls for larger workloads.`);let o=[],s=new Set;for(let m of n){if(typeof m!="object"||m===null)throw new Error("Each node must be an object");let g=m,y=g.id;if(typeof y!="string"||y.trim().length===0)throw new Error('Each node must have a non-empty "id" string');if(!/^[A-Za-z0-9_-]+$/.test(y)){let v=y.replace(/[\x00-\x1f\x7f]/g,"?").slice(0,32);throw new Error(`Node id "${v}" must match /^[A-Za-z0-9_-]+$/ (alphanumeric, underscore, hyphen)`)}if(s.has(y))throw new Error(`Duplicate node ID: ${y}`);s.add(y);let b=g.prompt;if(typeof b!="string"||b.trim().length===0)throw new Error(`Node "${y}" must have a non-empty "prompt" string`);let w;if(g.model!==void 0){if(typeof g.model!="string")throw new Error(`Node "${y}" model must be a string`);w=g.model}o.push({id:y,prompt:b,model:w})}let i;if(e.edges!==void 0){if(!Array.isArray(e.edges))throw new Error('"edges" must be an array');i=[];for(let m of e.edges){if(typeof m!="object"||m===null)throw new Error("Each edge must be an object");let g=m;if(typeof g.from!="string"||typeof g.to!="string")throw new Error('Each edge must have "from" and "to" strings');if(!s.has(g.from))throw new Error(`Edge references non-existent node: ${g.from}`);if(!s.has(g.to))throw new Error(`Edge references non-existent node: ${g.to}`);i.push({from:g.from,to:g.to})}}let a;if(e.fail_fast!==void 0){if(typeof e.fail_fast!="boolean")throw new Error('"fail_fast" must be a boolean');a=e.fail_fast}let c=[],l;if(e.node_timeout_ms!==void 0){let m=e.node_timeout_ms;if(typeof m!="number"||!Number.isFinite(m)||m<=0)throw new Error('"node_timeout_ms" must be a positive finite number (milliseconds)');if(m<fW)throw new Error(`"node_timeout_ms" must be at least ${fW}ms (got ${m}). Sub-second timeouts are almost always a unit mistake.`);l=Math.min(bm,m),m>bm&&c.push(`node_timeout_ms clamped: requested ${m}ms exceeds the maximum ${bm}ms; using ${bm}ms.`)}let d="max_tool_rounds_per_node",u="max_tool_calls_per_node",p=e[d]!==void 0?d:u;e[d]!==void 0&&e[u]!==void 0?c.push(`both "${d}" and the deprecated "${u}" were supplied; using "${d}" and ignoring the deprecated key.`):e[u]!==void 0&&c.push(`"${u}" is deprecated \u2014 use "${d}". The unit is tool-use ROUNDS (a round with N parallel calls costs 1), and spending the budget now triggers a tools-stripped wind-down round instead of cancelling the node.`);let f;if(e[p]!==void 0){let m=e[p];if(typeof m!="number"||!Number.isFinite(m)||m<=0)throw new Error(`"${p}" must be a positive finite number`);if(!Number.isInteger(m))throw new Error(`"${p}" must be an integer (got ${m}). Tool-use rounds are discrete events; fractional budgets are not meaningful.`);if(m<mW)throw new Error(`"${p}" must be at least ${mW}`);if(m>gW)throw new Error(`"${p}" must be at most ${gW} (got ${m}). A larger budget no longer constrains useful work.`);f=m}return{parsed:{nodes:o,edges:i,fail_fast:a,node_timeout_ms:l,max_tool_rounds_per_node:f},warnings:c}}var Lc=8e3,hW=500,yW=4e3;function rae(t){if(t==null)return;let e=typeof t=="string"?t:JSON.stringify(t);if(e.length!==0)return e.length>yW?e.slice(0,yW)+`
|
|
1779
|
+
Input: ${n}`:""),mode:"form",title:"AFK high-risk approval",requestedSchema:{type:"object",properties:{choice:{type:"string",title:"Approve this high-risk operation?",enum:["approve","deny"],description:"'approve' runs this single call. 'deny' refuses it (the model gets an error and should push an Asking summary or take a safe path)."}},required:["choice"]}}}function Bie(t){let e;try{e=typeof t=="string"?t:JSON.stringify(t)}catch{e=String(t)}return e?(e=Vr(e),e.length>ZH?`${e.slice(0,ZH)}\u2026 [truncated]`:e):""}function Fc(t,e){return{decision:"block",reason:`AFK mode: ${t} is refused \u2014 this op is high-risk or irreversible, and ${e}. Push an Asking summary to Telegram (send_telegram) and stop, or have the operator run /afk off and take over.`}}function jie(t,e){let n=Ys.resolve(t),r=Ys.resolve(e);if(n===r)return r;let o=Ys.relative(r,n);if(o!==""&&!o.startsWith("..")&&!Ys.isAbsolute(o))return os(n)??n;let s=os(r),i=os(n);if(s!==void 0&&i!==void 0&&Ys.dirname(s)===Ys.dirname(i))return i}fl();we();Zr();import{mkdirSync as Zie,rmSync as eae,writeFileSync as tae}from"fs";import{join as sv}from"path";ie();ld();B();import{createHash as Hie}from"node:crypto";import{mkdirSync as Wie,existsSync as tW,unlinkSync as nW,readFileSync as Kie,writeFileSync as qie,renameSync as Gie}from"node:fs";import{join as rv,dirname as Xie}from"node:path";import{randomBytes as zie}from"node:crypto";function rW(){return rv(te(),"dag-checkpoints")}var Jie=/^[A-Za-z0-9_-]+$/;function ov(t){return!t||!Jie.test(t)||t.length>128?null:rv(rW(),`${t}.json`)}var nv=10*1024;function oW(t){let e=[...t.nodes.map(o=>o.id)].sort(),n=[...t.edges.map(o=>`${o.from}->${o.to}`)].sort(),r=JSON.stringify({nodes:e,edges:n});return Hie("sha256").update(r).digest("hex")}async function sW(t,e){Wie(rW(),{recursive:!0});let n=ov(t);if(n===null)throw new Error(`Invalid dagId: ${JSON.stringify(t)}`);let r=rv(Xie(n),`.tmp-${zie(4).toString("hex")}.json`);try{qie(r,JSON.stringify(e),"utf-8"),Gie(r,n)}catch(o){try{nW(r)}catch{}throw o}}async function iW(t,e){let n=ov(t);if(n===null||!tW(n))return null;let r;try{r=Kie(n,"utf-8")}catch{return null}let o;try{o=JSON.parse(r)}catch{return null}return o.dagHash!==e?null:o}async function aW(t){let e=ov(t);if(e!==null&&tW(e))try{nW(e)}catch{}}function cW(t){if(t===void 0)return"";let e=typeof t=="string"?t:JSON.stringify(t)??"";if(Buffer.byteLength(e,"utf8")<=nv)return e;let n=Buffer.from(e).subarray(0,nv).toString("utf8");for(;Buffer.byteLength(n,"utf8")>nv;)n=n.slice(0,-1);return n}function Vie(t){let e=new Set;for(let a of t.nodes){if(e.has(a.id))throw new Error(`Duplicate node ID: ${a.id}`);e.add(a.id)}let n=new Set;for(let a of t.edges){if(!e.has(a.from))throw new Error(`Edge references non-existent node: ${a.from}`);if(!e.has(a.to))throw new Error(`Edge references non-existent node: ${a.to}`);let c=`${a.from}->${a.to}`;if(n.has(c))throw new Error(`Duplicate edge: ${a.from} -> ${a.to}`);n.add(c)}let r=lW(t),o=new Map(r.inDegree),s=[];for(let[a,c]of o)c===0&&s.push(a);let i=0;for(;s.length>0;){let a=s.shift();i+=1;for(let c of r.downstream.get(a)??[]){let l=o.get(c)-1;o.set(c,l),l===0&&s.push(c)}}if(i!==e.size)throw new Error("Cycle detected in DAG")}function lW(t){let e=new Map,n=new Map,r=new Map;for(let o of t.nodes)e.set(o.id,new Set),n.set(o.id,new Set),r.set(o.id,0);for(let o of t.edges)e.get(o.from).add(o.to),n.get(o.to).add(o.from),r.set(o.to,r.get(o.to)+1);return{downstream:e,upstream:n,inDegree:r}}function Yie(t,e,n){let r=[t];for(;r.length>0;){let o=r.shift();for(let s of e.get(o)??[])n.has(s)||(n.add(s),r.push(s))}}async function dW(t,e,n={}){if(t.nodes.length===0)return{outputs:{},failed:[],skipped:[]};Vie(t);let{dagId:r,failFast:o=!0,nodeTimeoutMs:s,maxConcurrency:i=Ri()}=n,a=s!==void 0&&Number.isFinite(s)&&s>0,c=lW(t),l=new Map(t.nodes.map(w=>[w.id,w])),d={},u=[],p=new Set,f=new Set,m=new Map(c.inDegree),g=r!==void 0?oW(t):"";if(r!==void 0){let w=await iW(r,g);if(w!==null){for(let v of w.completedNodes){let _=w.nodeOutputs[v],x=_;if(_!==void 0)try{x=JSON.parse(_)}catch{x=_}d[v]=x,f.add(v),m.delete(v);for(let A of c.downstream.get(v)??[])m.set(A,m.get(A)-1)}for(let v of w.failedNodes){let _=w.nodeErrors?.[v]??"restored from checkpoint";u.push({id:v,error:new Error(_)}),f.add(v),m.delete(v)}for(let v of w.skippedNodes)p.add(v)}}let y=new AbortController,b=()=>{y.signal.aborted||y.abort(e.reason)};e.aborted?y.abort(e.reason):e.addEventListener("abort",b,{once:!0});try{for(;!y.signal.aborted;){let w=[];for(let[_,x]of m)x===0&&!f.has(_)&&!p.has(_)&&w.push(_);if(w.length===0)break;let v=await Lo(w,i,async _=>{let x=l.get(_),A=new AbortController,I=()=>{A.signal.aborted||A.abort(y.signal.reason)};y.signal.aborted?A.abort(y.signal.reason):y.signal.addEventListener("abort",I,{once:!0});let C;a&&!A.signal.aborted&&(C=setTimeout(()=>{A.signal.aborted||A.abort(new Ie(`DAG node "${_}" exceeded nodeTimeoutMs of ${s}ms`,s))},s));let T={};for(let R of c.upstream.get(_)??[])T[R]=d[R];try{let R=await x.run(T,A.signal);return{id:_,result:R}}finally{C!==void 0&&clearTimeout(C),y.signal.removeEventListener("abort",I)}});for(let _=0;_<v.length;_++){let x=v[_];if(x.status==="fulfilled"){let{id:A,result:I}=x.value;d[A]=I,f.add(A),m.delete(A);for(let C of c.downstream.get(A)??[])m.set(C,m.get(C)-1)}else{let A=x.reason instanceof Error?x.reason:new Error(String(x.reason)),I=w[_];u.push({id:I,error:A}),f.add(I),m.delete(I),Yie(I,c.downstream,p),o&&y.abort("fail-fast")}}if(r!==void 0&&!y.signal.aborted){let _={dagHash:g,completedNodes:Array.from(f).filter(x=>!u.some(A=>A.id===x)),nodeOutputs:Object.fromEntries(Object.entries(d).map(([x,A])=>[x,cW(A)])),failedNodes:u.map(x=>x.id),nodeErrors:Object.fromEntries(u.map(x=>[x.id,x.error.message])),skippedNodes:Array.from(p),timestamp:Date.now()};await sW(r,_).catch(()=>{})}}}finally{e.removeEventListener("abort",b)}return r!==void 0&&u.length===0&&await aW(r).catch(()=>{}),{outputs:d,failed:u,skipped:Array.from(p)}}Re();ie();Wn();Rs();Yw();Ae();function Qie(t){let e=[];t.cwd!==void 0&&e.push({value:t.cwd,field:"cwd"});for(let n of t.readRoots??[])e.push({value:n,field:"readRoots"});for(let n of t.writeRoots??[])e.push({value:n,field:"writeRoots"});for(let{value:n,field:r}of e){let o=je(n);if(Qt(n)||Qt(o))throw new Error(`DAG node "${t.id}" ${r} "${n}" is too broad (filesystem root, home directory, or AFK directory)`);let s=oo(n)??oo(o);if(s!==void 0)throw new Error(`DAG node "${t.id}" ${r} "${n}" would un-gate credential root "${s}"`)}}async function uW(t){let{manager:e,parentSession:n,nodes:r,edges:o,failFast:s,nodeTimeoutMs:i}=t,a=n.abortSignal??new AbortController().signal,c=[i??0,za()].filter(u=>u>0),l=c.length>0?Nu(Math.min(...c)):0,d=r.map(u=>({id:u.id,async run(p,f){Qie(u);let m=await e.forkSubagent({parent:{sessionId:n.sessionId},config:{model:u.model??"sonnet",systemPrompt:u.systemPrompt,...u.canUseTool!==void 0?{canUseTool:u.canUseTool}:{},...u.cwd!==void 0?{cwd:u.cwd}:{},...u.readRoots!==void 0?{readRoots:u.readRoots}:{},...u.writeRoots!==void 0?{writeRoots:u.writeRoots}:{},...u.apiKey!==void 0?{apiKey:u.apiKey}:{},...u.maxToolUseIterations!==void 0?{maxToolUseIterations:u.maxToolUseIterations}:{},...u.provider!==void 0?{provider:u.provider}:{},...l!==0?{softDeadlineMs:l}:{}},idPrefix:u.idPrefix??`dag-${u.id}`,...u.outputSchema!==void 0?{outputSchema:u.outputSchema}:{},agentType:u.agentType??u.idPrefix??`dag-${u.id}`,...u.parentId!==void 0?{parentId:u.parentId}:{}}),g=()=>{m.cancel().catch(()=>{})};f.aborted?m.cancel().catch(()=>{}):f.addEventListener("abort",g,{once:!0});try{if(f.aborted)throw new DOMException("Aborted","AbortError");let y=u.promptBuilder(p),b=await m.runToResult(y);if(b.status!=="succeeded"){let v,_=f.reason;throw _ instanceof Ie?v=new Error(`Subagent ${u.id} aborted: ${_.message}`,b.error?{cause:b.error}:{}):v=b.error??new Error(`Subagent ${u.id} ${b.status}`),rF(v,{partialOutput:b.partialOutput,subagentId:b.id})}if(b.output!==void 0)return b.output;let w=b.message?.content;return typeof w=="string"?Es(w,b.stopReason):w}finally{f.removeEventListener("abort",g),await m.teardown().catch(()=>{})}}}));return dW({nodes:d,edges:o},a,{failFast:s,nodeTimeoutMs:i})}Jr();fe();be();Ua();Rt();ur();Qr();Ot();Ot();function pW(t,e,n){return e===void 0?{}:{provider:QF(t,e,n)}}_p();B();var fW=1e3,bm=36e5,mW=1,gW=1e3;function nae(t){if(typeof t!="object"||t===null)throw new Error("Compose tool input must be an object");let e=t,n=e.nodes;if(!Array.isArray(n)||n.length===0)throw new Error('Compose tool requires a non-empty "nodes" array');let r=20;if(n.length>r)throw new Error(`Compose tool supports at most ${r} nodes (got ${n.length}). Split into multiple compose calls for larger workloads.`);let o=[],s=new Set;for(let m of n){if(typeof m!="object"||m===null)throw new Error("Each node must be an object");let g=m,y=g.id;if(typeof y!="string"||y.trim().length===0)throw new Error('Each node must have a non-empty "id" string');if(!/^[A-Za-z0-9_-]+$/.test(y)){let v=y.replace(/[\x00-\x1f\x7f]/g,"?").slice(0,32);throw new Error(`Node id "${v}" must match /^[A-Za-z0-9_-]+$/ (alphanumeric, underscore, hyphen)`)}if(s.has(y))throw new Error(`Duplicate node ID: ${y}`);s.add(y);let b=g.prompt;if(typeof b!="string"||b.trim().length===0)throw new Error(`Node "${y}" must have a non-empty "prompt" string`);let w;if(g.model!==void 0){if(typeof g.model!="string")throw new Error(`Node "${y}" model must be a string`);w=g.model}o.push({id:y,prompt:b,model:w})}let i;if(e.edges!==void 0){if(!Array.isArray(e.edges))throw new Error('"edges" must be an array');i=[];for(let m of e.edges){if(typeof m!="object"||m===null)throw new Error("Each edge must be an object");let g=m;if(typeof g.from!="string"||typeof g.to!="string")throw new Error('Each edge must have "from" and "to" strings');if(!s.has(g.from))throw new Error(`Edge references non-existent node: ${g.from}`);if(!s.has(g.to))throw new Error(`Edge references non-existent node: ${g.to}`);i.push({from:g.from,to:g.to})}}let a;if(e.fail_fast!==void 0){if(typeof e.fail_fast!="boolean")throw new Error('"fail_fast" must be a boolean');a=e.fail_fast}let c=[],l;if(e.node_timeout_ms!==void 0){let m=e.node_timeout_ms;if(typeof m!="number"||!Number.isFinite(m)||m<=0)throw new Error('"node_timeout_ms" must be a positive finite number (milliseconds)');if(m<fW)throw new Error(`"node_timeout_ms" must be at least ${fW}ms (got ${m}). Sub-second timeouts are almost always a unit mistake.`);l=Math.min(bm,m),m>bm&&c.push(`node_timeout_ms clamped: requested ${m}ms exceeds the maximum ${bm}ms; using ${bm}ms.`)}let d="max_tool_rounds_per_node",u="max_tool_calls_per_node",p=e[d]!==void 0?d:u;e[d]!==void 0&&e[u]!==void 0?c.push(`both "${d}" and the deprecated "${u}" were supplied; using "${d}" and ignoring the deprecated key.`):e[u]!==void 0&&c.push(`"${u}" is deprecated \u2014 use "${d}". The unit is tool-use ROUNDS (a round with N parallel calls costs 1), and spending the budget now triggers a tools-stripped wind-down round instead of cancelling the node.`);let f;if(e[p]!==void 0){let m=e[p];if(typeof m!="number"||!Number.isFinite(m)||m<=0)throw new Error(`"${p}" must be a positive finite number`);if(!Number.isInteger(m))throw new Error(`"${p}" must be an integer (got ${m}). Tool-use rounds are discrete events; fractional budgets are not meaningful.`);if(m<mW)throw new Error(`"${p}" must be at least ${mW}`);if(m>gW)throw new Error(`"${p}" must be at most ${gW} (got ${m}). A larger budget no longer constrains useful work.`);f=m}return{parsed:{nodes:o,edges:i,fail_fast:a,node_timeout_ms:l,max_tool_rounds_per_node:f},warnings:c}}var Lc=8e3,hW=500,yW=4e3;function rae(t){if(t==null)return;let e=typeof t=="string"?t:JSON.stringify(t);if(e.length!==0)return e.length>yW?e.slice(0,yW)+`
|
|
1780
1780
|
\u2026 (truncated)`:e}function oae(t,e,n,r){try{let o=sv(ce(),t,"compose",e);Zie(o,{recursive:!0});let s=sv(o,`${n}.txt`);return tae(s,r,"utf8"),s}catch{return}}function sae(t,e){let n=[],r=[];for(let[o,s]of Object.entries(t.outputs)){let i=typeof s=="string"?s:s!=null?JSON.stringify(s):"(no output)",a;if(i.length>Lc){let c=oae(e.sessionId,e.callId,o,i);r.push({nodeId:o,emittedChars:Lc,totalChars:i.length,...c!==void 0?{spillPath:c}:{}});let l=c!==void 0?`
|
|
1781
1781
|
\u2026 (truncated at ${Lc} / ${i.length} chars \u2014 full output at ${c})`:`
|
|
1782
1782
|
\u2026 (truncated at ${Lc} / ${i.length} chars)`;a=i.slice(0,Lc)+l}else a=i;n.push(`## ${o}
|