@cloudflare/think 0.9.1 → 0.11.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/README.md +10 -17
- package/dist/{chat-sdk-Bb93yaZh.js → chat-sdk-D6cUghsQ.js} +33 -8
- package/dist/chat-sdk-D6cUghsQ.js.map +1 -0
- package/dist/cli/index.js +718 -55
- package/dist/cli/index.js.map +1 -1
- package/dist/{codegen-CuPdJRpV.js → codegen-DlA2QQuU.js} +6 -38
- package/dist/codegen-DlA2QQuU.js.map +1 -0
- package/dist/{config-D512sQYg.d.ts → config-CD7hqncK.d.ts} +5 -5
- package/dist/extensions/index.js +1 -1
- package/dist/framework/index.d.ts +17 -62
- package/dist/framework/index.js +3 -57
- package/dist/{think-CwxWGsX1.d.ts → index-D_S5mETO.d.ts} +1643 -688
- package/dist/{manager-BPndMP_6.js → manager-CSk5htym.js} +7 -7
- package/dist/{manager-BPndMP_6.js.map → manager-CSk5htym.js.map} +1 -1
- package/dist/{manifest-CpB-xngB.d.ts → manifest-DK5HuGga.d.ts} +16 -18
- package/dist/messengers/index.d.ts +59 -55
- package/dist/messengers/index.js +2 -2
- package/dist/messengers/telegram.d.ts +4 -4
- package/dist/messengers/telegram.js +1 -1
- package/dist/react.d.ts +79 -0
- package/dist/react.js +28 -0
- package/dist/react.js.map +1 -0
- package/dist/server-entry.d.ts +1 -1
- package/dist/server-entry.js +1 -1
- package/dist/server-entry.js.map +1 -1
- package/dist/studio/assets/abap-CLvhMVsD.js +1 -0
- package/dist/studio/assets/actionscript-3--17pq3dv.js +1 -0
- package/dist/studio/assets/ada-C5qYipkI.js +1 -0
- package/dist/studio/assets/andromeeda-vGVdxbeo.js +1 -0
- package/dist/studio/assets/angular-html-D27LthTc.js +1 -0
- package/dist/studio/assets/angular-ts-DtNL2gQ7.js +1 -0
- package/dist/studio/assets/apache-U0d_L8uA.js +1 -0
- package/dist/studio/assets/apex-CGTLDQj6.js +1 -0
- package/dist/studio/assets/apl-BgEcDqM0.js +1 -0
- package/dist/studio/assets/applescript-CCn79oCD.js +1 -0
- package/dist/studio/assets/ara-4CJ0cIlV.js +1 -0
- package/dist/studio/assets/asciidoc-DE70LPWp.js +1 -0
- package/dist/studio/assets/asm-Cmm7eHzH.js +1 -0
- package/dist/studio/assets/astro-CstbRF9e.js +1 -0
- package/dist/studio/assets/aurora-x-CDeNXAV0.js +1 -0
- package/dist/studio/assets/awk-BWXHIvNe.js +1 -0
- package/dist/studio/assets/ayu-dark-DluEY0Gj.js +1 -0
- package/dist/studio/assets/ayu-light-C3h-C4tm.js +1 -0
- package/dist/studio/assets/ayu-mirage-Bqwy1Gya.js +1 -0
- package/dist/studio/assets/ballerina-B7ZEbQpA.js +1 -0
- package/dist/studio/assets/bat-Bo4NYOV-.js +1 -0
- package/dist/studio/assets/beancount-D-usSTwE.js +1 -0
- package/dist/studio/assets/berry-DKpUyyne.js +1 -0
- package/dist/studio/assets/bibtex-Ci_nEsc7.js +1 -0
- package/dist/studio/assets/bicep-CUHmPFLl.js +1 -0
- package/dist/studio/assets/bird2-C2hNVINV.js +1 -0
- package/dist/studio/assets/blade-CLG-7epG.js +1 -0
- package/dist/studio/assets/bsl-BkkzgIyY.js +1 -0
- package/dist/studio/assets/c-CssQqwxO.js +1 -0
- package/dist/studio/assets/c3-CnJL0r0V.js +1 -0
- package/dist/studio/assets/cadence-CQ2zXKGN.js +1 -0
- package/dist/studio/assets/cairo-DLTphjLi.js +1 -0
- package/dist/studio/assets/catppuccin-frappe-3VR1Za6u.js +1 -0
- package/dist/studio/assets/catppuccin-latte-DwIHMF0Q.js +1 -0
- package/dist/studio/assets/catppuccin-macchiato-DYnBP6_5.js +1 -0
- package/dist/studio/assets/catppuccin-mocha-DYhrFGRu.js +1 -0
- package/dist/studio/assets/clarity-SemFz856.js +1 -0
- package/dist/studio/assets/clojure-DqKBuwfJ.js +1 -0
- package/dist/studio/assets/cmake-Bj61d0ZC.js +1 -0
- package/dist/studio/assets/cobol-CjmzHCjg.js +1 -0
- package/dist/studio/assets/codeowners-C8r90Shi.js +1 -0
- package/dist/studio/assets/codeql-oeQT6MSM.js +1 -0
- package/dist/studio/assets/coffee-B_rqYPkp.js +1 -0
- package/dist/studio/assets/common-lisp-Cv5bFMCO.js +1 -0
- package/dist/studio/assets/coq-BrsZFFmf.js +1 -0
- package/dist/studio/assets/cpp-5YyZJlb7.js +1 -0
- package/dist/studio/assets/crystal-D7uKze0i.js +1 -0
- package/dist/studio/assets/csharp-Ct8U2NOr.js +1 -0
- package/dist/studio/assets/css-k9oPgg7G.js +1 -0
- package/dist/studio/assets/csv-Dx-8-gkx.js +1 -0
- package/dist/studio/assets/cue-CE9AQfxI.js +1 -0
- package/dist/studio/assets/cypher-ClKdZ_lG.js +1 -0
- package/dist/studio/assets/d-qD-0Kul2.js +1 -0
- package/dist/studio/assets/dark-plus-Cs2F2srj.js +1 -0
- package/dist/studio/assets/dart-DkHntEIa.js +1 -0
- package/dist/studio/assets/dax-BkyTk9wS.js +1 -0
- package/dist/studio/assets/desktop-Dlh5hvp9.js +1 -0
- package/dist/studio/assets/diff-woXpYk--.js +1 -0
- package/dist/studio/assets/docker-IyjqRm3v.js +1 -0
- package/dist/studio/assets/dotenv-_5a1GRtc.js +1 -0
- package/dist/studio/assets/dracula-BHWKrbxM.js +1 -0
- package/dist/studio/assets/dracula-soft-5eyTD99u.js +1 -0
- package/dist/studio/assets/dream-maker-DW3nJb8Q.js +1 -0
- package/dist/studio/assets/edge-CGgsSt0x.js +1 -0
- package/dist/studio/assets/elixir-BX_d5Evo.js +1 -0
- package/dist/studio/assets/elm-DENxDm5e.js +1 -0
- package/dist/studio/assets/emacs-lisp-C9PiwqqW.js +1 -0
- package/dist/studio/assets/erb-DvYOup03.js +1 -0
- package/dist/studio/assets/erlang-Cphh6RMH.js +1 -0
- package/dist/studio/assets/everforest-dark-sB-x3p7T.js +1 -0
- package/dist/studio/assets/everforest-light-Df2xbC6M.js +1 -0
- package/dist/studio/assets/fennel-DQxkIbk2.js +1 -0
- package/dist/studio/assets/fish-BJitypiv.js +1 -0
- package/dist/studio/assets/fluent-C03EYrpw.js +1 -0
- package/dist/studio/assets/fortran-fixed-form-DEKoE2YW.js +1 -0
- package/dist/studio/assets/fortran-free-form-CYNrtFtB.js +1 -0
- package/dist/studio/assets/fsharp-D13ZGOAj.js +1 -0
- package/dist/studio/assets/gdresource-C0sCabJj.js +1 -0
- package/dist/studio/assets/gdscript-Cp2uCuqX.js +1 -0
- package/dist/studio/assets/gdshader-CBce3t8t.js +1 -0
- package/dist/studio/assets/genie-CV2tkWYe.js +1 -0
- package/dist/studio/assets/gherkin-DExj1W_8.js +1 -0
- package/dist/studio/assets/git-commit-BSykSTBG.js +1 -0
- package/dist/studio/assets/git-rebase-BsAdTS5A.js +1 -0
- package/dist/studio/assets/github-dark-C-LZuMrd.js +1 -0
- package/dist/studio/assets/github-dark-default-DXG-b-1a.js +1 -0
- package/dist/studio/assets/github-dark-dimmed-Bx1FflLF.js +1 -0
- package/dist/studio/assets/github-dark-high-contrast-B_tTalzw.js +1 -0
- package/dist/studio/assets/github-light-EUqPIrTm.js +1 -0
- package/dist/studio/assets/github-light-default-BXViO-2h.js +1 -0
- package/dist/studio/assets/github-light-high-contrast-B68TUdTA.js +1 -0
- package/dist/studio/assets/gleam-CSRkHgEL.js +1 -0
- package/dist/studio/assets/glimmer-js-e0h98Z67.js +1 -0
- package/dist/studio/assets/glimmer-ts-C9s5Kv8m.js +1 -0
- package/dist/studio/assets/glsl-CCiyeTRs.js +1 -0
- package/dist/studio/assets/gn-ilITqXS6.js +1 -0
- package/dist/studio/assets/gnuplot-7GGW24-e.js +1 -0
- package/dist/studio/assets/go-BJwz_mda.js +1 -0
- package/dist/studio/assets/graphql-BRtHwsqk.js +1 -0
- package/dist/studio/assets/groovy-CacY0gHj.js +1 -0
- package/dist/studio/assets/gruvbox-dark-hard-C820rvS2.js +1 -0
- package/dist/studio/assets/gruvbox-dark-medium-BPjhmG05.js +1 -0
- package/dist/studio/assets/gruvbox-dark-soft-MrdJrrXF.js +1 -0
- package/dist/studio/assets/gruvbox-light-hard-BC_s9l72.js +1 -0
- package/dist/studio/assets/gruvbox-light-medium-BAWPOn9u.js +1 -0
- package/dist/studio/assets/gruvbox-light-soft-BSMLrYjP.js +1 -0
- package/dist/studio/assets/hack-Dnt0QXHh.js +1 -0
- package/dist/studio/assets/haml-EXGmzuB1.js +1 -0
- package/dist/studio/assets/handlebars-CzyBIDJE.js +1 -0
- package/dist/studio/assets/haskell-D8IpX4py.js +1 -0
- package/dist/studio/assets/haxe-OTjmBuCE.js +1 -0
- package/dist/studio/assets/hcl-Dh228itO.js +1 -0
- package/dist/studio/assets/highlighted-body-OFNGDK62-CQUFKLNu.js +1 -0
- package/dist/studio/assets/hjson-CxZEssPk.js +1 -0
- package/dist/studio/assets/hlsl-Cvrh5tZx.js +1 -0
- package/dist/studio/assets/horizon-CE9ld1lL.js +1 -0
- package/dist/studio/assets/horizon-bright-Br1oVSNq.js +1 -0
- package/dist/studio/assets/houston-CsvMBhTu.js +1 -0
- package/dist/studio/assets/html-BAT8b_VM.js +1 -0
- package/dist/studio/assets/html-derivative-7tkS-r6F.js +1 -0
- package/dist/studio/assets/http-Cgka02Qq.js +1 -0
- package/dist/studio/assets/hurl-Cbkh8WEw.js +1 -0
- package/dist/studio/assets/hxml-B0Qn7Nwc.js +1 -0
- package/dist/studio/assets/hy-CZbG8q4J.js +1 -0
- package/dist/studio/assets/imba-DsUTQ-LC.js +1 -0
- package/dist/studio/assets/index-D6n8vpkp.js +390 -0
- package/dist/studio/assets/index-DkGWw6ES.css +2 -0
- package/dist/studio/assets/ini-B5eOa1yu.js +1 -0
- package/dist/studio/assets/java-DrRKiUno.js +1 -0
- package/dist/studio/assets/javascript-9LAnHOxD.js +1 -0
- package/dist/studio/assets/jinja-CqRt4prs.js +1 -0
- package/dist/studio/assets/jison-BX-IOQpJ.js +1 -0
- package/dist/studio/assets/json-dOrE-En8.js +1 -0
- package/dist/studio/assets/json5-BR5RXkoi.js +1 -0
- package/dist/studio/assets/jsonc-CYpm1nAK.js +1 -0
- package/dist/studio/assets/jsonl-CmCQp5Yx.js +1 -0
- package/dist/studio/assets/jsonnet-CJTPZ8u_.js +1 -0
- package/dist/studio/assets/jssm-DXw9l8Rf.js +1 -0
- package/dist/studio/assets/jsx-BSTPfqWX.js +1 -0
- package/dist/studio/assets/julia-Dvz-BPmf.js +1 -0
- package/dist/studio/assets/just-BHQm0Atq.js +1 -0
- package/dist/studio/assets/kanagawa-dragon-CXtmUGW6.js +1 -0
- package/dist/studio/assets/kanagawa-lotus-BN08jTvb.js +1 -0
- package/dist/studio/assets/kanagawa-wave-CTweb8Dz.js +1 -0
- package/dist/studio/assets/kdl-CsD5j6eV.js +1 -0
- package/dist/studio/assets/kotlin-DhhofPvG.js +1 -0
- package/dist/studio/assets/kusto-BUv0MjJC.js +1 -0
- package/dist/studio/assets/laserwave-C_8bwKvT.js +1 -0
- package/dist/studio/assets/latex-CxdhxuXv.js +1 -0
- package/dist/studio/assets/lean-CewbzKMR.js +1 -0
- package/dist/studio/assets/less-DVTAwKKz.js +1 -0
- package/dist/studio/assets/light-plus-DVQuIRkW.js +1 -0
- package/dist/studio/assets/liquid-D-hM-Q_F.js +1 -0
- package/dist/studio/assets/llvm-Cm23YOpf.js +1 -0
- package/dist/studio/assets/log-BNLmms1o.js +1 -0
- package/dist/studio/assets/logo-Cluzi2Zq.js +1 -0
- package/dist/studio/assets/lua-5qtqjLHq.js +1 -0
- package/dist/studio/assets/luau-CNKltnaQ.js +1 -0
- package/dist/studio/assets/make-Dixweg8N.js +1 -0
- package/dist/studio/assets/markdown-BYOwaDjH.js +1 -0
- package/dist/studio/assets/marko-5FJaM2co.js +1 -0
- package/dist/studio/assets/material-theme-Bm3Qr25_.js +1 -0
- package/dist/studio/assets/material-theme-darker-2IIEA8gg.js +1 -0
- package/dist/studio/assets/material-theme-lighter-uhdI0v04.js +1 -0
- package/dist/studio/assets/material-theme-ocean-CHQ94UKr.js +1 -0
- package/dist/studio/assets/material-theme-palenight-B5W6OYN7.js +1 -0
- package/dist/studio/assets/matlab-D7qyCx1q.js +1 -0
- package/dist/studio/assets/mdc-BhYW7lCG.js +1 -0
- package/dist/studio/assets/mdx-DQZ5AkYe.js +1 -0
- package/dist/studio/assets/mermaid-Bk4SNUv9.js +1 -0
- package/dist/studio/assets/mermaid-GHXKKRXX-CWM2EB-u.js +1 -0
- package/dist/studio/assets/min-dark-BSWPekZh.js +1 -0
- package/dist/studio/assets/min-light-DDpmG2fV.js +1 -0
- package/dist/studio/assets/mipsasm-BMqwQI7S.js +1 -0
- package/dist/studio/assets/mojo-BgCJLMeH.js +1 -0
- package/dist/studio/assets/monokai-CdkpiU2Y.js +1 -0
- package/dist/studio/assets/moonbit-CaWjb8XO.js +1 -0
- package/dist/studio/assets/move-B1IS1UjX.js +1 -0
- package/dist/studio/assets/narrat-_X_XdTYD.js +1 -0
- package/dist/studio/assets/nextflow-Bbiyy34d.js +1 -0
- package/dist/studio/assets/nextflow-groovy-Dc_ddanL.js +1 -0
- package/dist/studio/assets/nginx-rtAXrRye.js +1 -0
- package/dist/studio/assets/night-owl-DhmEMT88.js +1 -0
- package/dist/studio/assets/night-owl-light-eJ-hLW7d.js +1 -0
- package/dist/studio/assets/nim-DQSmaN9U.js +1 -0
- package/dist/studio/assets/nix-IvuFDN5E.js +1 -0
- package/dist/studio/assets/nord-Cb4Vim4T.js +1 -0
- package/dist/studio/assets/nushell-DcLAeLz5.js +1 -0
- package/dist/studio/assets/objective-c-D1A_Heim.js +1 -0
- package/dist/studio/assets/objective-cpp-BsSzOQcm.js +1 -0
- package/dist/studio/assets/ocaml-O90oeIOV.js +1 -0
- package/dist/studio/assets/odin-B1RWQWA5.js +1 -0
- package/dist/studio/assets/one-dark-pro-CLwyXe_n.js +1 -0
- package/dist/studio/assets/one-light-D7Lr4KcI.js +1 -0
- package/dist/studio/assets/openscad-BUDT5pXO.js +1 -0
- package/dist/studio/assets/pascal-4ZHwLPI5.js +1 -0
- package/dist/studio/assets/perl-B54AdcaE.js +1 -0
- package/dist/studio/assets/php-DpvTxCny.js +1 -0
- package/dist/studio/assets/pkl-ot-7Btpt.js +1 -0
- package/dist/studio/assets/plastic-DQwYfKfQ.js +1 -0
- package/dist/studio/assets/plsql-DGHpHOYJ.js +1 -0
- package/dist/studio/assets/po-BiJDBrnU.js +1 -0
- package/dist/studio/assets/poimandres-DRFjx7u4.js +1 -0
- package/dist/studio/assets/polar-C7UOKdEL.js +1 -0
- package/dist/studio/assets/postcss-BXeXVLqQ.js +1 -0
- package/dist/studio/assets/powerquery-DNMTfnFr.js +1 -0
- package/dist/studio/assets/powershell-DshXNtvi.js +1 -0
- package/dist/studio/assets/prisma-BsRQq5mF.js +1 -0
- package/dist/studio/assets/prolog-iXnhIJG7.js +1 -0
- package/dist/studio/assets/proto-DB4EqR-F.js +1 -0
- package/dist/studio/assets/pug-Cyffw0Ho.js +1 -0
- package/dist/studio/assets/puppet-CDv2pdJW.js +1 -0
- package/dist/studio/assets/purescript-9MfHhQsQ.js +1 -0
- package/dist/studio/assets/python-gzcpVVnB.js +1 -0
- package/dist/studio/assets/qml-CxRetSkO.js +1 -0
- package/dist/studio/assets/qmldir-DCQb3MpD.js +1 -0
- package/dist/studio/assets/qss-Fe1Jh2GI.js +1 -0
- package/dist/studio/assets/r-CXWRxrXc.js +1 -0
- package/dist/studio/assets/racket-DcIDlBhZ.js +1 -0
- package/dist/studio/assets/raku-B3gFvitq.js +1 -0
- package/dist/studio/assets/razor-BJzI-zc9.js +1 -0
- package/dist/studio/assets/red-CJ3rzSJv.js +1 -0
- package/dist/studio/assets/reg-CRGYupPL.js +1 -0
- package/dist/studio/assets/regexp-dqxdfrnE.js +1 -0
- package/dist/studio/assets/rel-BtDbiS_P.js +1 -0
- package/dist/studio/assets/riscv-Ckw8ddFX.js +1 -0
- package/dist/studio/assets/ron-VUp2lXgN.js +1 -0
- package/dist/studio/assets/rose-pine-BthvhNj6.js +1 -0
- package/dist/studio/assets/rose-pine-dawn-Dg85fqjY.js +1 -0
- package/dist/studio/assets/rose-pine-moon-hon4tzzS.js +1 -0
- package/dist/studio/assets/rosmsg-CAekHB0j.js +1 -0
- package/dist/studio/assets/rst-BW7eKYj4.js +1 -0
- package/dist/studio/assets/ruby-D5Npyj8-.js +1 -0
- package/dist/studio/assets/rust-Cfkwpbl8.js +1 -0
- package/dist/studio/assets/sas-DZLppjul.js +1 -0
- package/dist/studio/assets/sass-DXrisJhu.js +1 -0
- package/dist/studio/assets/scala-DKOlJaKm.js +1 -0
- package/dist/studio/assets/scheme-DQCgrYNe.js +1 -0
- package/dist/studio/assets/scss-CbqoxyAe.js +1 -0
- package/dist/studio/assets/sdbl-bTVj8UrX.js +1 -0
- package/dist/studio/assets/shaderlab-TOUzSsQk.js +1 -0
- package/dist/studio/assets/shellscript-CFHqBeXu.js +1 -0
- package/dist/studio/assets/shellsession-CbZDA4Bf.js +1 -0
- package/dist/studio/assets/slack-dark-DnToyrRv.js +1 -0
- package/dist/studio/assets/slack-ochin-B2OO5cIa.js +1 -0
- package/dist/studio/assets/smalltalk-B16xEiuN.js +1 -0
- package/dist/studio/assets/snazzy-light-4G7pJPwS.js +1 -0
- package/dist/studio/assets/solarized-dark-DV17i1UV.js +1 -0
- package/dist/studio/assets/solarized-light-DSh2HLQt.js +1 -0
- package/dist/studio/assets/solidity-CKzVLygQ.js +1 -0
- package/dist/studio/assets/soy-PImjtV58.js +1 -0
- package/dist/studio/assets/sparql-D_iOobhT.js +1 -0
- package/dist/studio/assets/splunk-BC2Px7Mm.js +1 -0
- package/dist/studio/assets/sql-DhGo8urW.js +1 -0
- package/dist/studio/assets/ssh-config-BgfXC-Er.js +1 -0
- package/dist/studio/assets/stata-CjHWbU2v.js +1 -0
- package/dist/studio/assets/stylus-B6D30XZt.js +1 -0
- package/dist/studio/assets/surrealql-o8Qr4t56.js +1 -0
- package/dist/studio/assets/svelte-DlSIyEV1.js +1 -0
- package/dist/studio/assets/swift-DonLKvLd.js +1 -0
- package/dist/studio/assets/synthwave-84-nFMaYfgc.js +1 -0
- package/dist/studio/assets/system-verilog-DJ5XKQeo.js +1 -0
- package/dist/studio/assets/systemd-BxMlprV5.js +1 -0
- package/dist/studio/assets/talonscript-CohzipZa.js +1 -0
- package/dist/studio/assets/tasl-DMoTqEGO.js +1 -0
- package/dist/studio/assets/tcl-CZd0xW_V.js +1 -0
- package/dist/studio/assets/templ-qizfwU1w.js +1 -0
- package/dist/studio/assets/terraform-DswuEJGm.js +1 -0
- package/dist/studio/assets/tex-Ca7T661H.js +1 -0
- package/dist/studio/assets/tokyo-night-oM2G3aXe.js +1 -0
- package/dist/studio/assets/toml-CcmNWLt0.js +1 -0
- package/dist/studio/assets/ts-tags-DUmjLkgl.js +1 -0
- package/dist/studio/assets/tsv-sltzmVWM.js +1 -0
- package/dist/studio/assets/tsx-CfwgIqHW.js +1 -0
- package/dist/studio/assets/turtle-ByJddavk.js +1 -0
- package/dist/studio/assets/twig-D7NAYUBY.js +1 -0
- package/dist/studio/assets/typescript-Bbz9oX-P.js +1 -0
- package/dist/studio/assets/typespec-B88KGewJ.js +1 -0
- package/dist/studio/assets/typst-DI99ib-x.js +1 -0
- package/dist/studio/assets/v-DETTlOr0.js +1 -0
- package/dist/studio/assets/vala-zf12oZj6.js +1 -0
- package/dist/studio/assets/vb-Djn5o6TS.js +1 -0
- package/dist/studio/assets/verilog-CiiDBU1e.js +1 -0
- package/dist/studio/assets/vesper-D5bVUKB1.js +1 -0
- package/dist/studio/assets/vhdl-BroJfC0k.js +1 -0
- package/dist/studio/assets/viml-DvXPmvsu.js +1 -0
- package/dist/studio/assets/vitesse-black-fwtXNY1n.js +1 -0
- package/dist/studio/assets/vitesse-dark-BZCL-v6S.js +1 -0
- package/dist/studio/assets/vitesse-light-VbXTXTou.js +1 -0
- package/dist/studio/assets/vue-html-CcxTb_Jn.js +1 -0
- package/dist/studio/assets/vue-vYpz06zQ.js +1 -0
- package/dist/studio/assets/vue-vine-DW4RqCKF.js +1 -0
- package/dist/studio/assets/vyper-CgoNMtux.js +1 -0
- package/dist/studio/assets/wasm-BnjxR4X6.js +1 -0
- package/dist/studio/assets/wasm-ByWQv1Qj.js +1 -0
- package/dist/studio/assets/wenyan-C8pVoKbM.js +1 -0
- package/dist/studio/assets/wgsl-BsKzXJz4.js +1 -0
- package/dist/studio/assets/wikitext-ClFFjSW2.js +1 -0
- package/dist/studio/assets/wit-DdvCle-K.js +1 -0
- package/dist/studio/assets/wolfram-DLL8P-h_.js +1 -0
- package/dist/studio/assets/xml-R4LZ_u4f.js +1 -0
- package/dist/studio/assets/xsl-CS-xzp3L.js +1 -0
- package/dist/studio/assets/yaml-CqDWbYXd.js +1 -0
- package/dist/studio/assets/zenscript-BnlCZFoB.js +1 -0
- package/dist/studio/assets/zig-CMLA9XwU.js +1 -0
- package/dist/studio/index.html +23 -0
- package/dist/think.d.ts +2 -2
- package/dist/think.js +8292 -2
- package/dist/think.js.map +1 -0
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.js +2 -2
- package/dist/tools/workspace.js.map +1 -1
- package/dist/{types-codegen-B6c5KpYH.js → types-codegen-C-9yeFao.js} +9 -33
- package/dist/types-codegen-C-9yeFao.js.map +1 -0
- package/dist/vite.d.ts +12 -5
- package/dist/vite.js +73 -1
- package/dist/vite.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/actions.md +297 -0
- package/docs/channels.md +185 -0
- package/docs/client-tools.md +233 -0
- package/docs/getting-started.md +314 -0
- package/docs/index.md +1272 -0
- package/docs/lifecycle-hooks.md +839 -0
- package/docs/messengers.md +197 -0
- package/docs/programmatic-submissions.md +206 -0
- package/docs/sub-agents.md +520 -0
- package/docs/tools.md +582 -0
- package/docs/workflows.md +217 -0
- package/package.json +57 -10
- package/dist/chat-sdk-Bb93yaZh.js.map +0 -1
- package/dist/codegen-CuPdJRpV.js.map +0 -1
- package/dist/framework/index.js.map +0 -1
- package/dist/think-2nHHEcY3.js +0 -6446
- package/dist/think-2nHHEcY3.js.map +0 -1
- package/dist/types-codegen-B6c5KpYH.js.map +0 -1
|
@@ -0,0 +1,839 @@
|
|
|
1
|
+
# Lifecycle Hooks
|
|
2
|
+
|
|
3
|
+
Think owns the `streamText` call and provides hooks at each stage of the chat turn. Hooks fire on every turn regardless of entry path — WebSocket chat, sub-agent `chat()`, `saveMessages()`, durable `submitMessages()` execution, `continueLastTurn()`, and auto-continuation after tool results.
|
|
4
|
+
|
|
5
|
+
## Hook Summary
|
|
6
|
+
|
|
7
|
+
| Hook | When it fires | Return | Async |
|
|
8
|
+
| -------------------------------- | ----------------------------------------------------------- | --------------------------------- | ----- |
|
|
9
|
+
| `configureSession(session)` | Once during `onStart` | `Session` | yes |
|
|
10
|
+
| `beforeTurn(ctx)` | Before `streamText` | `TurnConfig` or void | yes |
|
|
11
|
+
| `beforeStep(ctx)` | Before each model step | `StepConfig` or void | yes |
|
|
12
|
+
| `beforeToolCall(ctx)` | When model calls a tool | `ToolCallDecision` or void | yes |
|
|
13
|
+
| `afterToolCall(ctx)` | After tool execution | void | yes |
|
|
14
|
+
| `onStepFinish(ctx)` | After each step completes | void | yes |
|
|
15
|
+
| `onChunk(ctx)` | Per streaming chunk | void | yes |
|
|
16
|
+
| `onChatResponse(result)` | After turn completes and message is persisted | void | yes |
|
|
17
|
+
| `onChatError(error, ctx?)` | On error during a turn | error to propagate | no |
|
|
18
|
+
| `classifyChatError(error, ctx?)` | On a turn error, when `contextOverflow.reactive` is enabled | `ChatErrorClassification` or void | no |
|
|
19
|
+
|
|
20
|
+
## Execution Order
|
|
21
|
+
|
|
22
|
+
For a turn with two tool calls:
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
configureSession() ← once at startup, not per-turn
|
|
26
|
+
│
|
|
27
|
+
beforeTurn() ← inspect assembled context, override model/tools/prompt
|
|
28
|
+
│
|
|
29
|
+
┌── streamText ───────────────────────────────────┐
|
|
30
|
+
│ beforeStep() │
|
|
31
|
+
│ │ │
|
|
32
|
+
│ onChunk() onChunk() onChunk() ... │
|
|
33
|
+
│ │ │
|
|
34
|
+
│ beforeToolCall() → tool executes │
|
|
35
|
+
│ afterToolCall() │
|
|
36
|
+
│ │ │
|
|
37
|
+
│ onStepFinish() │
|
|
38
|
+
│ │ │
|
|
39
|
+
│ beforeStep() │
|
|
40
|
+
│ │ │
|
|
41
|
+
│ onChunk() onChunk() ... │
|
|
42
|
+
│ │ │
|
|
43
|
+
│ beforeToolCall() → tool executes │
|
|
44
|
+
│ afterToolCall() │
|
|
45
|
+
│ │ │
|
|
46
|
+
│ onStepFinish() │
|
|
47
|
+
└─────────────────────────────────────────────────┘
|
|
48
|
+
│
|
|
49
|
+
onChatResponse() ← message persisted, turn lock released
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## configureSession
|
|
55
|
+
|
|
56
|
+
Called once during Durable Object initialization (`onStart`). Configure the Session with context blocks, compaction, search, and skills.
|
|
57
|
+
|
|
58
|
+
```typescript
|
|
59
|
+
configureSession(session: Session): Session | Promise<Session>
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
import { Think, Session } from "@cloudflare/think";
|
|
64
|
+
import { createCompactFunction } from "agents/experimental/memory/utils/compaction-helpers";
|
|
65
|
+
import { generateText } from "ai";
|
|
66
|
+
|
|
67
|
+
export class MyAgent extends Think<Env> {
|
|
68
|
+
getModel() {
|
|
69
|
+
/* ... */
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
configureSession(session: Session) {
|
|
73
|
+
return session
|
|
74
|
+
.withContext("soul", {
|
|
75
|
+
provider: { get: async () => "You are a helpful coding assistant." }
|
|
76
|
+
})
|
|
77
|
+
.withContext("memory", {
|
|
78
|
+
description: "Learned facts about the user.",
|
|
79
|
+
maxTokens: 1100
|
|
80
|
+
})
|
|
81
|
+
.onCompaction(
|
|
82
|
+
createCompactFunction({
|
|
83
|
+
summarize: (prompt) =>
|
|
84
|
+
generateText({ model: this.getModel(), prompt }).then((r) => r.text)
|
|
85
|
+
})
|
|
86
|
+
)
|
|
87
|
+
.compactAfter(100_000)
|
|
88
|
+
.withCachedPrompt();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
When `configureSession` adds context blocks, Think builds the system prompt from those blocks instead of using `getSystemPrompt()`. See the [Sessions documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for the full API.
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## beforeTurn
|
|
98
|
+
|
|
99
|
+
Called before `streamText`. Receives the fully assembled context — system prompt, converted messages, merged tools, and model. Return a `TurnConfig` to override any part, or void to accept defaults.
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
beforeTurn(ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### TurnContext
|
|
106
|
+
|
|
107
|
+
| Field | Type | Description |
|
|
108
|
+
| -------------- | ------------------------- | ------------------------------------------------------------------------ |
|
|
109
|
+
| `system` | `string` | Assembled system prompt (from context blocks or `getSystemPrompt()`) |
|
|
110
|
+
| `messages` | `ModelMessage[]` | Assembled model messages (truncated) |
|
|
111
|
+
| `tools` | `ToolSet` | Merged tool set (workspace + getTools + session + MCP + client + caller) |
|
|
112
|
+
| `model` | `LanguageModel` | The model from `getModel()` |
|
|
113
|
+
| `continuation` | `boolean` | Whether this is a continuation turn (auto-continue after tool result) |
|
|
114
|
+
| `body` | `Record<string, unknown>` | Custom body fields from the client request |
|
|
115
|
+
|
|
116
|
+
### TurnConfig
|
|
117
|
+
|
|
118
|
+
All fields are optional. Return only what you want to change.
|
|
119
|
+
|
|
120
|
+
| Field | Type | Description |
|
|
121
|
+
| -------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
122
|
+
| `model` | `LanguageModel` | Override the model for this turn |
|
|
123
|
+
| `system` | `string` | Override the system prompt |
|
|
124
|
+
| `messages` | `ModelMessage[]` | Override the assembled messages |
|
|
125
|
+
| `tools` | `ToolSet` | Extra tools to merge (additive) |
|
|
126
|
+
| `activeTools` | `string[]` | Limit which tools the model can call |
|
|
127
|
+
| `toolChoice` | `ToolChoice` | Force a specific tool call |
|
|
128
|
+
| `maxSteps` | `number` | Override `maxSteps` for this turn |
|
|
129
|
+
| `stopWhen` | `StopCondition \| StopCondition[]` | Additional early-exit conditions |
|
|
130
|
+
| `sendReasoning` | `boolean` | Send reasoning chunks for this turn |
|
|
131
|
+
| `maxOutputTokens` | `number` | Maximum tokens to generate |
|
|
132
|
+
| `temperature` | `number` | Sampling temperature |
|
|
133
|
+
| `topP` | `number` | Nucleus sampling value |
|
|
134
|
+
| `topK` | `number` | Top-K sampling value |
|
|
135
|
+
| `presencePenalty` | `number` | Presence penalty |
|
|
136
|
+
| `frequencyPenalty` | `number` | Frequency penalty |
|
|
137
|
+
| `stopSequences` | `string[]` | Stop generation sequences |
|
|
138
|
+
| `seed` | `number` | Sampling seed when supported |
|
|
139
|
+
| `maxRetries` | `number` | Maximum retries for this turn |
|
|
140
|
+
| `timeout` | `TimeoutConfiguration` | Timeout for this turn |
|
|
141
|
+
| `chatStreamStallTimeoutMs` | `number` | Override the stream-stall watchdog for this turn (`0` disables it); auto-resets after the turn. Useful for a turn with a known-slow tool — see [Think configuration](./index.md). |
|
|
142
|
+
| `headers` | `Record<string, string>` | Additional provider request headers |
|
|
143
|
+
| `providerOptions` | `Record<string, unknown>` | Provider-specific options |
|
|
144
|
+
| `experimental_transform` | `StreamTextTransform \| StreamTextTransform[]` | AI SDK stream transform(s) for this turn — inspect or rewrite stream parts (for example, emit `source` parts derived from tool results). Applied in order. |
|
|
145
|
+
|
|
146
|
+
### Examples
|
|
147
|
+
|
|
148
|
+
Switch to a cheaper model for continuation turns:
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
beforeTurn(ctx: TurnContext) {
|
|
152
|
+
if (ctx.continuation) {
|
|
153
|
+
return { model: this.cheapModel };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Restrict which tools the model can call:
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
beforeTurn(ctx: TurnContext) {
|
|
162
|
+
return { activeTools: ["read", "write", "getWeather"] };
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Add per-turn context from the client body:
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
beforeTurn(ctx: TurnContext) {
|
|
170
|
+
if (ctx.body?.selectedFile) {
|
|
171
|
+
return {
|
|
172
|
+
system: ctx.system + `\n\nUser is editing: ${ctx.body.selectedFile}`
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Override `maxSteps` based on conversation length:
|
|
179
|
+
|
|
180
|
+
```typescript
|
|
181
|
+
beforeTurn(ctx: TurnContext) {
|
|
182
|
+
if (ctx.messages.length > 100) {
|
|
183
|
+
return { maxSteps: 3 };
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Stop early when a designated tool is called while retaining Think's `maxSteps` safety bound:
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
import { hasToolCall } from "ai";
|
|
192
|
+
|
|
193
|
+
beforeTurn() {
|
|
194
|
+
return { stopWhen: hasToolCall("finalAnswer") };
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`stopWhen` is additive: Think sends both `stepCountIs(maxSteps)` and your condition(s) to the AI SDK, so the loop ends when either one matches. Stop conditions are functions, so they can be returned from a Think subclass's `beforeTurn`, but not from sandboxed extension `beforeTurn` hooks over RPC.
|
|
199
|
+
|
|
200
|
+
Prune older tool calls from the model context with the AI SDK's [`pruneMessages`](https://ai-sdk.dev/):
|
|
201
|
+
|
|
202
|
+
```typescript
|
|
203
|
+
import { pruneMessages } from "ai";
|
|
204
|
+
|
|
205
|
+
beforeTurn(ctx: TurnContext) {
|
|
206
|
+
return {
|
|
207
|
+
messages: pruneMessages({
|
|
208
|
+
messages: ctx.messages,
|
|
209
|
+
toolCalls: "before-last-2-messages"
|
|
210
|
+
})
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Scope pruning per-tool with the array form so client-side tool results survive across turns:
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
import { pruneMessages } from "ai";
|
|
219
|
+
|
|
220
|
+
beforeTurn(ctx: TurnContext) {
|
|
221
|
+
return {
|
|
222
|
+
messages: pruneMessages({
|
|
223
|
+
messages: ctx.messages,
|
|
224
|
+
toolCalls: [
|
|
225
|
+
{ type: "before-last-2-messages", tools: ["read_file", "search"] }
|
|
226
|
+
]
|
|
227
|
+
})
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Hide reasoning for internal continuation turns:
|
|
233
|
+
|
|
234
|
+
```typescript
|
|
235
|
+
beforeTurn(ctx: TurnContext) {
|
|
236
|
+
if (ctx.continuation) {
|
|
237
|
+
return { sendReasoning: false };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Disable retries and apply a streaming timeout for a recovery turn:
|
|
243
|
+
|
|
244
|
+
```typescript
|
|
245
|
+
beforeTurn(ctx: TurnContext) {
|
|
246
|
+
if (ctx.body?.recovering) {
|
|
247
|
+
return {
|
|
248
|
+
maxRetries: 0,
|
|
249
|
+
timeout: { totalMs: 30_000, chunkMs: 5_000 }
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
Force structured output for a turn (Vercel AI SDK `Output.object`). Combine with `activeTools: []` because some providers (e.g. `workers-ai-provider`) strip tools when `responseFormat: "json"` is active:
|
|
256
|
+
|
|
257
|
+
```typescript
|
|
258
|
+
import { Output } from "ai";
|
|
259
|
+
import { z } from "zod";
|
|
260
|
+
|
|
261
|
+
const ResultSchema = z.object({ severity: z.enum(["low", "high"]) });
|
|
262
|
+
|
|
263
|
+
beforeTurn(ctx: TurnContext) {
|
|
264
|
+
// Gate however your agent decides "this is the structured-answer turn":
|
|
265
|
+
// a body flag set by the caller, an internal phase enum, or a separate
|
|
266
|
+
// sub-agent invocation. `ctx.continuation === true` means "this turn
|
|
267
|
+
// was triggered by Think's auto-continuation after tool results", which
|
|
268
|
+
// is *not* the same as "terminal turn" — don't conflate them.
|
|
269
|
+
if (ctx.body?.mode === "structured-answer") {
|
|
270
|
+
return {
|
|
271
|
+
output: Output.object({ schema: ResultSchema }),
|
|
272
|
+
activeTools: []
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
> `output` is a turn-level setting only. The AI SDK's `prepareStep` does not accept an `output` override, so `beforeStep` cannot toggle structured output on a single step. If you need per-step structured output, run a separate turn (or a sub-agent call) with `output` set in `beforeTurn`.
|
|
279
|
+
|
|
280
|
+
---
|
|
281
|
+
|
|
282
|
+
## beforeStep
|
|
283
|
+
|
|
284
|
+
Called before each AI SDK step in the agentic loop. Think forwards this hook to `streamText` as `prepareStep`, so it receives the AI SDK's full prepare-step context and can return per-step overrides. Use `beforeTurn` for turn-wide assembly and `beforeStep` when the decision depends on the step number or previous step results.
|
|
285
|
+
|
|
286
|
+
```typescript
|
|
287
|
+
beforeStep(ctx: PrepareStepContext): StepConfig | void | Promise<StepConfig | void>
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
`beforeStep` fires _between_ steps in the agentic loop: after the previous step's `onStepFinish` and before the next model call. For a tool-call → answer flow that means the order is:
|
|
291
|
+
|
|
292
|
+
```
|
|
293
|
+
beforeStep(ctx, stepNumber=0) ← ctx.steps = []
|
|
294
|
+
→ model emits tool-call → beforeToolCall → execute → afterToolCall
|
|
295
|
+
onStepFinish(step 0)
|
|
296
|
+
beforeStep(ctx, stepNumber=1) ← ctx.steps = [step 0]
|
|
297
|
+
→ model emits final text
|
|
298
|
+
onStepFinish(step 1)
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
### PrepareStepContext
|
|
302
|
+
|
|
303
|
+
`PrepareStepContext<TOOLS>` is the parameter of the AI SDK's `PrepareStepFunction<TOOLS>`.
|
|
304
|
+
|
|
305
|
+
| Field | Type | Description |
|
|
306
|
+
| ---------------------- | -------------------------- | ---------------------------------------------- |
|
|
307
|
+
| `steps` | `Array<StepResult<TOOLS>>` | Steps that have already completed |
|
|
308
|
+
| `stepNumber` | `number` | Zero-based number of the step about to run |
|
|
309
|
+
| `model` | `LanguageModel` | Model currently selected for this step |
|
|
310
|
+
| `messages` | `ModelMessage[]` | Messages that will be sent to the model |
|
|
311
|
+
| `experimental_context` | `unknown` | AI SDK experimental context for tool execution |
|
|
312
|
+
|
|
313
|
+
### StepConfig
|
|
314
|
+
|
|
315
|
+
`StepConfig<TOOLS>` is the AI SDK's `PrepareStepResult<TOOLS>`. Return only the fields to override for the current step.
|
|
316
|
+
|
|
317
|
+
| Field | Type | Description |
|
|
318
|
+
| ---------------------- | ------------------------------------------------------ | ----------------------------------------------------------- |
|
|
319
|
+
| `model` | `LanguageModel` | Override the model for this step |
|
|
320
|
+
| `toolChoice` | `ToolChoice<TOOLS>` | Force or disable tool calling for this step |
|
|
321
|
+
| `activeTools` | `Array<keyof TOOLS>` | Limit which tools are available for this step |
|
|
322
|
+
| `system` | `string \| SystemModelMessage \| SystemModelMessage[]` | Override the system message for this step |
|
|
323
|
+
| `messages` | `ModelMessage[]` | Override the full message list for this step |
|
|
324
|
+
| `experimental_context` | `unknown` | Override context passed to tool execution from this step on |
|
|
325
|
+
| `providerOptions` | `ProviderOptions` | Provider-specific options for this step |
|
|
326
|
+
|
|
327
|
+
### Examples
|
|
328
|
+
|
|
329
|
+
Force a search tool on the first step:
|
|
330
|
+
|
|
331
|
+
```typescript
|
|
332
|
+
beforeStep(ctx: PrepareStepContext<typeof tools>): StepConfig<typeof tools> | void {
|
|
333
|
+
if (ctx.stepNumber === 0) {
|
|
334
|
+
return {
|
|
335
|
+
activeTools: ["search"],
|
|
336
|
+
toolChoice: { type: "tool", toolName: "search" }
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
Switch to a cheaper model after tool results are available (assumes a `fastSummaryModel` field on your subclass):
|
|
343
|
+
|
|
344
|
+
```typescript
|
|
345
|
+
beforeStep(ctx: PrepareStepContext): StepConfig | void {
|
|
346
|
+
if (ctx.steps.some((step) => step.toolResults.length > 0)) {
|
|
347
|
+
return { model: this.fastSummaryModel };
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
Trim tool-heavy messages on later steps:
|
|
353
|
+
|
|
354
|
+
```typescript
|
|
355
|
+
beforeStep(ctx: PrepareStepContext): StepConfig | void {
|
|
356
|
+
if (ctx.stepNumber < 2) return;
|
|
357
|
+
return {
|
|
358
|
+
messages: ctx.messages.slice(-8)
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
### Limitations
|
|
364
|
+
|
|
365
|
+
The following are AI SDK boundary constraints surfaced through `beforeStep`, not Think-imposed limits:
|
|
366
|
+
|
|
367
|
+
- **No `abortSignal` in the context.** If `beforeStep` does remote work (e.g. fetches a model from a registry), it cannot be cancelled by turn-level abort. Keep the hook fast and synchronous when possible.
|
|
368
|
+
- **`output` cannot be overridden per step.** `PrepareStepResult` doesn't include `output`. Set structured output at the turn level via `TurnConfig.output` (returned from `beforeTurn`).
|
|
369
|
+
- **`maxSteps` cannot be overridden per step.** Set it at the turn level via `TurnConfig.maxSteps`.
|
|
370
|
+
- **`experimental_context` is typed `unknown`.** Narrow it yourself.
|
|
371
|
+
- **Subclass-only.** `beforeStep` is not dispatched to extensions — the prepareStep event surface includes a live `LanguageModel` instance which is not JSON-safe to snapshot.
|
|
372
|
+
|
|
373
|
+
---
|
|
374
|
+
|
|
375
|
+
## beforeToolCall
|
|
376
|
+
|
|
377
|
+
Called **before** the tool's `execute` function runs. Think wraps every server-side tool's `execute` so it can consult this hook and act on the returned `ToolCallDecision`. Only fires for tools with `execute` — client tools are handled on the client.
|
|
378
|
+
|
|
379
|
+
```typescript
|
|
380
|
+
beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void | Promise<ToolCallDecision | void>
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
### ToolCallDecision
|
|
384
|
+
|
|
385
|
+
| Return value | Effect |
|
|
386
|
+
| ------------------------------------------ | ---------------------------------------------------------------------------------- |
|
|
387
|
+
| `void` / `undefined` | Run the original `execute` with the original `input` |
|
|
388
|
+
| `{ action: "allow" }` | Same as `void` |
|
|
389
|
+
| `{ action: "allow", input }` | Run the original `execute` with the substituted `input` |
|
|
390
|
+
| `{ action: "block", reason? }` | Skip `execute`; the model sees `reason` (or a default string) as the tool's output |
|
|
391
|
+
| `{ action: "substitute", output, input? }` | Skip `execute`; the model sees `output` as the tool's output |
|
|
392
|
+
|
|
393
|
+
`afterToolCall` always fires after the decision resolves. For `block` and `substitute`, the substituted value flows through `afterToolCall` as `success: true, output: ...` (the model's perspective: it received a string back).
|
|
394
|
+
|
|
395
|
+
> Note: when `allow` substitutes the input, `afterToolCall.input` still reflects what the **model** emitted (the AI SDK records the original tool-call chunk), while `output` reflects the result of executing with the substituted input. If you need to see the substituted input in `afterToolCall`, capture it in `beforeToolCall` and stash it on the agent.
|
|
396
|
+
|
|
397
|
+
### ToolCallContext
|
|
398
|
+
|
|
399
|
+
`ToolCallContext<TOOLS>` spreads the AI SDK's `TypedToolCall<TOOLS>` at the top level (so `ctx.toolName` and `ctx.input` work without unwrapping) and adds the per-call event extras from `OnToolCallStartEvent`.
|
|
400
|
+
|
|
401
|
+
| Field | Type | Description |
|
|
402
|
+
| ------------------ | ----------------------------- | --------------------------------------------------------------------------- |
|
|
403
|
+
| `type` | `"tool-call"` | Discriminator |
|
|
404
|
+
| `toolCallId` | `string` | Unique id for this tool call |
|
|
405
|
+
| `toolName` | `string` | Name of the tool being called |
|
|
406
|
+
| `input` | typed when `TOOLS` is passed | Arguments the model provided (formerly `args`; renamed to match AI SDK) |
|
|
407
|
+
| `dynamic?` | `boolean` | `true` for runtime-registered tools, `false`/absent for statically declared |
|
|
408
|
+
| `providerMetadata` | `ProviderMetadata?` | Provider-specific metadata for this call |
|
|
409
|
+
| `stepNumber` | `number \| undefined` | Index of the current step where this tool call occurs |
|
|
410
|
+
| `messages` | `ReadonlyArray<ModelMessage>` | Conversation messages visible at tool execution time |
|
|
411
|
+
| `abortSignal` | `AbortSignal \| undefined` | Aborts if the turn is cancelled |
|
|
412
|
+
|
|
413
|
+
Pass an explicit `TOOLS` generic to get full input typing:
|
|
414
|
+
|
|
415
|
+
```typescript
|
|
416
|
+
import type { ToolCallContext } from "@cloudflare/think";
|
|
417
|
+
|
|
418
|
+
const tools = { search: tool({ inputSchema: z.object({ query: z.string() }), ... }) };
|
|
419
|
+
|
|
420
|
+
beforeToolCall(ctx: ToolCallContext<typeof tools>) {
|
|
421
|
+
if (ctx.toolName === "search") {
|
|
422
|
+
ctx.input.query; // typed as string
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
### Examples
|
|
428
|
+
|
|
429
|
+
Log all tool calls:
|
|
430
|
+
|
|
431
|
+
```typescript
|
|
432
|
+
beforeToolCall(ctx: ToolCallContext) {
|
|
433
|
+
console.log(`Tool called: ${ctx.toolName}`, ctx.input);
|
|
434
|
+
}
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
Block a tool when the agent is in a restricted mode:
|
|
438
|
+
|
|
439
|
+
```typescript
|
|
440
|
+
beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
|
|
441
|
+
if (this.isReadOnlyMode && ctx.toolName === "delete") {
|
|
442
|
+
return {
|
|
443
|
+
action: "block",
|
|
444
|
+
reason: "delete is disabled in read-only mode"
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
Substitute a cached result without running `execute`:
|
|
451
|
+
|
|
452
|
+
```typescript
|
|
453
|
+
async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {
|
|
454
|
+
if (ctx.toolName === "weather") {
|
|
455
|
+
const cached = await this.cache.get(`weather:${JSON.stringify(ctx.input)}`);
|
|
456
|
+
if (cached) return { action: "substitute", output: cached };
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
Sanitize the model's input before execution (e.g. clamp a `limit`):
|
|
462
|
+
|
|
463
|
+
```typescript
|
|
464
|
+
beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
|
|
465
|
+
if (ctx.toolName === "search") {
|
|
466
|
+
const input = ctx.input as { query: string; limit?: number };
|
|
467
|
+
return {
|
|
468
|
+
action: "allow",
|
|
469
|
+
input: { ...input, limit: Math.min(input.limit ?? 10, 50) }
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
### Notes & limitations
|
|
476
|
+
|
|
477
|
+
- **Substituted input is not re-validated.** The AI SDK validates the model's emitted input against the tool's `inputSchema` _before_ `execute` runs. When `beforeToolCall` returns `{ action: "allow", input: ... }`, that substituted input is passed straight through to `execute` without going through the schema again. If you substitute, ensure the shape stays valid for the tool you're calling.
|
|
478
|
+
- **`stepNumber` is `undefined` in `ToolCallContext`.** The AI SDK's `ToolExecutionOptions` doesn't expose the current step index. The same field _is_ populated on `ToolCallResultContext` (sourced from `experimental_onToolCallFinish`).
|
|
479
|
+
- **Throwing from `beforeToolCall`** propagates as a tool error — the AI SDK records it in the same way it would record an `execute` failure, and `afterToolCall` fires with `success: false, error: ...`.
|
|
480
|
+
- **Streaming tools (AsyncIterable returns).** The AI SDK supports tools whose `execute` returns `AsyncIterable<output>` to emit preliminary results before a final value. This works regardless of whether the iterator is returned directly (`function execute(...) { return makeIter(); }`, `async function* execute(...) { … }`) or wrapped in a Promise (`async function execute(...) { return makeIter(); }`). Because Think's wrapper must `await beforeToolCall` first, preliminary chunks are collapsed — only the final yielded value reaches the model. If you need true preliminary streaming, override `getTools()` to provide such tools and avoid using `beforeToolCall` for them.
|
|
481
|
+
- **Hook order:** `beforeToolCall` (subclass) → extension `beforeToolCall` dispatch → original `execute` (or `block`/`substitute` short-circuit) → AI SDK records the outcome → `afterToolCall` (subclass) → extension `afterToolCall` dispatch.
|
|
482
|
+
|
|
483
|
+
---
|
|
484
|
+
|
|
485
|
+
## afterToolCall
|
|
486
|
+
|
|
487
|
+
Called after a tool's outcome is known — for real executions, for `block` (carries the `reason` as `output`), and for `substitute` (carries the substituted `output`). The discriminated `success`/`output`/`error` reflects what the model actually sees: thrown errors from the original `execute` become `success: false`; everything else (including blocked / substituted calls) is `success: true`.
|
|
488
|
+
|
|
489
|
+
```typescript
|
|
490
|
+
afterToolCall(ctx: ToolCallResultContext): void | Promise<void>
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
### ToolCallResultContext
|
|
494
|
+
|
|
495
|
+
`ToolCallResultContext<TOOLS>` is backed by the AI SDK's `OnToolCallFinishEvent<TOOLS>` (the parameter of `experimental_onToolCallFinish`). It spreads the originating `TypedToolCall<TOOLS>` at the top level, plus the per-call event extras and a discriminated outcome:
|
|
496
|
+
|
|
497
|
+
| Field | Type | Description |
|
|
498
|
+
| ------------ | ------------------------------------- | ---------------------------------------------------- |
|
|
499
|
+
| `type` | `"tool-call"` | Discriminator (carried over from the call) |
|
|
500
|
+
| `toolCallId` | `string` | Unique id matching the originating `ToolCallContext` |
|
|
501
|
+
| `toolName` | `string` | Name of the tool that was called |
|
|
502
|
+
| `input` | typed when `TOOLS` is passed | Arguments the tool was called with |
|
|
503
|
+
| `dynamic?` | `boolean` | `true` for runtime-registered tools |
|
|
504
|
+
| `stepNumber` | `number \| undefined` | Index of the current step |
|
|
505
|
+
| `messages` | `ReadonlyArray<ModelMessage>` | Conversation messages visible at tool execution time |
|
|
506
|
+
| `durationMs` | `number` | Wall-clock execution time of `execute` |
|
|
507
|
+
| `success` | `boolean` | Discriminator: `true` on success, `false` on failure |
|
|
508
|
+
| `output` | `unknown` (when `success` is `true`) | Whatever the tool's `execute` returned |
|
|
509
|
+
| `error` | `unknown` (when `success` is `false`) | Whatever was thrown from `execute` |
|
|
510
|
+
|
|
511
|
+
### Example
|
|
512
|
+
|
|
513
|
+
Track tool usage and surface failures:
|
|
514
|
+
|
|
515
|
+
```typescript
|
|
516
|
+
afterToolCall(ctx: ToolCallResultContext) {
|
|
517
|
+
if (ctx.success) {
|
|
518
|
+
this.env.ANALYTICS.writeDataPoint({
|
|
519
|
+
blobs: [ctx.toolName, "ok"],
|
|
520
|
+
doubles: [ctx.durationMs, JSON.stringify(ctx.output).length]
|
|
521
|
+
});
|
|
522
|
+
} else {
|
|
523
|
+
this.env.ANALYTICS.writeDataPoint({
|
|
524
|
+
blobs: [ctx.toolName, "error", String(ctx.error)],
|
|
525
|
+
doubles: [ctx.durationMs]
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
---
|
|
532
|
+
|
|
533
|
+
## onStepFinish
|
|
534
|
+
|
|
535
|
+
Called after each step completes in the agentic loop. A step is one `streamText` iteration — the model generates text, optionally calls tools, and the step ends.
|
|
536
|
+
|
|
537
|
+
```typescript
|
|
538
|
+
onStepFinish(ctx: StepContext): void | Promise<void>
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
### StepContext
|
|
542
|
+
|
|
543
|
+
`StepContext<TOOLS>` is a re-export of the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`). The full step record is forwarded — nothing is dropped or renamed. Highlights:
|
|
544
|
+
|
|
545
|
+
| Field | Type | Description |
|
|
546
|
+
| ------------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
547
|
+
| `stepNumber` | `number` | Zero-based index of this step |
|
|
548
|
+
| `text` | `string` | Text generated in this step |
|
|
549
|
+
| `reasoning` | `Array<ReasoningPart>` | Reasoning parts emitted by the model |
|
|
550
|
+
| `reasoningText` | `string \| undefined` | Concatenated reasoning text |
|
|
551
|
+
| `files` | `Array<GeneratedFile>` | Files generated during the step |
|
|
552
|
+
| `sources` | `Array<Source>` | Citations / sources used |
|
|
553
|
+
| `toolCalls` | `Array<TypedToolCall<TOOLS>>` | Typed tool calls (same shape as `ToolCallContext`) |
|
|
554
|
+
| `toolResults` | `Array<TypedToolResult<TOOLS>>` | Typed tool results (same shape as `ToolCallResultContext`) |
|
|
555
|
+
| `finishReason` | `FinishReason` | Unified finish reason from the model |
|
|
556
|
+
| `rawFinishReason` | `string \| undefined` | Raw provider finish reason |
|
|
557
|
+
| `usage` | `LanguageModelUsage` | `inputTokens`, `outputTokens`, `totalTokens`, `reasoningTokens`, `cachedInputTokens` |
|
|
558
|
+
| `warnings` | `CallWarning[] \| undefined` | Warnings from the provider |
|
|
559
|
+
| `request` | `LanguageModelRequestMetadata` | Raw request metadata |
|
|
560
|
+
| `response` | `LanguageModelResponseMetadata & { messages, body? }` | Raw response metadata + assistant/tool messages |
|
|
561
|
+
| `providerMetadata` | `ProviderMetadata \| undefined` | Provider-specific metadata (e.g. Anthropic cache accounting) |
|
|
562
|
+
|
|
563
|
+
### Examples
|
|
564
|
+
|
|
565
|
+
Log step-level usage with cache accounting:
|
|
566
|
+
|
|
567
|
+
```typescript
|
|
568
|
+
onStepFinish(ctx: StepContext) {
|
|
569
|
+
console.log(
|
|
570
|
+
`Step ${ctx.stepNumber} (${ctx.finishReason}): ` +
|
|
571
|
+
`${ctx.usage.inputTokens}in/${ctx.usage.outputTokens}out, ` +
|
|
572
|
+
`${ctx.usage.cachedInputTokens ?? 0} cached`
|
|
573
|
+
);
|
|
574
|
+
}
|
|
575
|
+
```
|
|
576
|
+
|
|
577
|
+
Capture reasoning text and citations:
|
|
578
|
+
|
|
579
|
+
```typescript
|
|
580
|
+
onStepFinish(ctx: StepContext) {
|
|
581
|
+
if (ctx.reasoningText) {
|
|
582
|
+
this.env.LOGS.writeDataPoint({ blobs: ["reasoning", ctx.reasoningText] });
|
|
583
|
+
}
|
|
584
|
+
for (const source of ctx.sources) {
|
|
585
|
+
this.env.LOGS.writeDataPoint({ blobs: ["source", source.url ?? ""] });
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
Read provider-specific cache tokens (Anthropic):
|
|
591
|
+
|
|
592
|
+
```typescript
|
|
593
|
+
onStepFinish(ctx: StepContext) {
|
|
594
|
+
const anthropic = ctx.providerMetadata?.anthropic as
|
|
595
|
+
| { cacheCreationInputTokens?: number; cacheReadInputTokens?: number }
|
|
596
|
+
| undefined;
|
|
597
|
+
if (anthropic) {
|
|
598
|
+
console.log(
|
|
599
|
+
`cache: ${anthropic.cacheCreationInputTokens ?? 0} created, ` +
|
|
600
|
+
`${anthropic.cacheReadInputTokens ?? 0} read`
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
---
|
|
607
|
+
|
|
608
|
+
## onChunk
|
|
609
|
+
|
|
610
|
+
Called for each streaming chunk. High-frequency — fires per token. Override for streaming analytics, progress indicators, or token counting. Observational only.
|
|
611
|
+
|
|
612
|
+
```typescript
|
|
613
|
+
onChunk(ctx: ChunkContext): void | Promise<void>
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
### ChunkContext
|
|
617
|
+
|
|
618
|
+
`ChunkContext<TOOLS>` is the parameter type of the AI SDK's `StreamTextOnChunkCallback<TOOLS>`. The `chunk` field is a discriminated union of `TextStreamPart` variants — narrow on `chunk.type` for typed access:
|
|
619
|
+
|
|
620
|
+
| Field | Type | Description |
|
|
621
|
+
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
|
|
622
|
+
| `chunk` | `Extract<TextStreamPart<TOOLS>, { type: "text-delta" \| "reasoning-delta" \| "source" \| "tool-call" \| "tool-input-start" \| "tool-input-delta" \| "tool-result" \| "raw" }>` | The current chunk from the AI SDK stream |
|
|
623
|
+
|
|
624
|
+
Example — count text-delta tokens and forward reasoning to a logger:
|
|
625
|
+
|
|
626
|
+
```typescript
|
|
627
|
+
onChunk(ctx: ChunkContext) {
|
|
628
|
+
switch (ctx.chunk.type) {
|
|
629
|
+
case "text-delta":
|
|
630
|
+
this.tokensStreamed += ctx.chunk.text.length;
|
|
631
|
+
break;
|
|
632
|
+
case "reasoning-delta":
|
|
633
|
+
console.log("[reasoning]", ctx.chunk.text);
|
|
634
|
+
break;
|
|
635
|
+
case "tool-call":
|
|
636
|
+
console.log(`[tool] ${ctx.chunk.toolName}`, ctx.chunk.input);
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
```
|
|
641
|
+
|
|
642
|
+
---
|
|
643
|
+
|
|
644
|
+
## onChatResponse
|
|
645
|
+
|
|
646
|
+
Called after a chat turn completes and the assistant message has been persisted. The turn lock is released before this hook runs, so it is safe to call `saveMessages` or other methods from inside.
|
|
647
|
+
|
|
648
|
+
Fires for all turn completion paths that persist an assistant message: WebSocket, sub-agent RPC, `saveMessages()`, durable `submitMessages()` execution, `continueLastTurn()`, and auto-continuation.
|
|
649
|
+
|
|
650
|
+
```typescript
|
|
651
|
+
onChatResponse(result: ChatResponseResult): void | Promise<void>
|
|
652
|
+
```
|
|
653
|
+
|
|
654
|
+
### ChatResponseResult
|
|
655
|
+
|
|
656
|
+
| Field | Type | Description |
|
|
657
|
+
| -------------- | ------------------------------------- | ------------------------------------------ |
|
|
658
|
+
| `message` | `UIMessage` | The persisted assistant message |
|
|
659
|
+
| `requestId` | `string` | Unique ID for this turn |
|
|
660
|
+
| `continuation` | `boolean` | Whether this was a continuation turn |
|
|
661
|
+
| `status` | `"completed" \| "error" \| "aborted"` | How the turn ended |
|
|
662
|
+
| `error` | `string?` | Error message (when `status` is `"error"`) |
|
|
663
|
+
|
|
664
|
+
### Examples
|
|
665
|
+
|
|
666
|
+
Log turn completion:
|
|
667
|
+
|
|
668
|
+
```typescript
|
|
669
|
+
onChatResponse(result: ChatResponseResult) {
|
|
670
|
+
if (result.status === "completed") {
|
|
671
|
+
console.log(
|
|
672
|
+
`Turn ${result.requestId} completed: ${result.message.parts.length} parts`
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
```
|
|
677
|
+
|
|
678
|
+
Chain a follow-up turn:
|
|
679
|
+
|
|
680
|
+
```typescript
|
|
681
|
+
async onChatResponse(result: ChatResponseResult) {
|
|
682
|
+
if (result.status === "completed" && this.shouldFollowUp(result.message)) {
|
|
683
|
+
await this.saveMessages([{
|
|
684
|
+
id: crypto.randomUUID(),
|
|
685
|
+
role: "user",
|
|
686
|
+
parts: [{ type: "text", text: "Now summarize what you found." }]
|
|
687
|
+
}]);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
```
|
|
691
|
+
|
|
692
|
+
Distinguish abort from error:
|
|
693
|
+
|
|
694
|
+
```typescript
|
|
695
|
+
async onChatResponse(result: ChatResponseResult) {
|
|
696
|
+
if (result.status === "aborted") {
|
|
697
|
+
// Cancelled via chat-request-cancel or saveMessages({ signal })
|
|
698
|
+
// — partial chunks are persisted, the message is the partial
|
|
699
|
+
// assistant transcript at the moment of abort.
|
|
700
|
+
this.logAbortMetric(result.requestId);
|
|
701
|
+
} else if (result.status === "error") {
|
|
702
|
+
// Inference threw — `result.error` carries the error message.
|
|
703
|
+
console.error(`Turn ${result.requestId} errored: ${result.error}`);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
---
|
|
709
|
+
|
|
710
|
+
## onChatError
|
|
711
|
+
|
|
712
|
+
Called when an error occurs during a chat turn. Return the error to propagate it, or return a different error. The optional context describes where the failure happened and whether user messages were already persisted.
|
|
713
|
+
|
|
714
|
+
```typescript
|
|
715
|
+
onChatError(error: unknown, ctx?: ChatErrorContext): unknown
|
|
716
|
+
```
|
|
717
|
+
|
|
718
|
+
The partial assistant message (if any) is persisted before this hook fires.
|
|
719
|
+
|
|
720
|
+
`ChatErrorContext` includes:
|
|
721
|
+
|
|
722
|
+
| Field | Type | Description |
|
|
723
|
+
| ------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
724
|
+
| `requestId` | `string \| undefined` | Chat request ID, when available |
|
|
725
|
+
| `stage` | `"parse" \| "persist" \| "turn" \| "stream" \| "recovery" \| "transcript"` | Failure stage |
|
|
726
|
+
| `messagesPersisted` | `boolean` | Whether incoming user messages were already stored |
|
|
727
|
+
| `classification` | `ChatErrorClassification \| undefined` | Set to `"context_overflow"` on the terminal `onChatError` when a context overflow could not be recovered (see [`classifyChatError`](#classifychaterror)); `undefined` otherwise |
|
|
728
|
+
|
|
729
|
+
Think also emits `chat:request:failed` on the `agents:chat` observability channel with the same stage and persistence information.
|
|
730
|
+
|
|
731
|
+
### Example
|
|
732
|
+
|
|
733
|
+
Log and transform errors:
|
|
734
|
+
|
|
735
|
+
```typescript
|
|
736
|
+
onChatError(error: unknown, ctx?: ChatErrorContext) {
|
|
737
|
+
console.error("Chat turn failed:", ctx?.stage, error);
|
|
738
|
+
if (ctx?.classification === "context_overflow") {
|
|
739
|
+
return new Error("This conversation is too long to continue. Please start a new one.");
|
|
740
|
+
}
|
|
741
|
+
return new Error("Something went wrong. Please try again.");
|
|
742
|
+
}
|
|
743
|
+
```
|
|
744
|
+
|
|
745
|
+
---
|
|
746
|
+
|
|
747
|
+
## classifyChatError
|
|
748
|
+
|
|
749
|
+
Called when an error occurs during a turn, **before** `onChatError`. Maps a raw provider error into a provider-agnostic category so Think can react without baking provider-specific strings into the framework — the same split as the `tokenCounter` you pass to `compactAfter()`. The app owns the mapping because it knows which provider and model it talks to.
|
|
750
|
+
|
|
751
|
+
```typescript
|
|
752
|
+
classifyChatError(error: unknown, ctx?: ChatErrorContext): ChatErrorClassification | void
|
|
753
|
+
```
|
|
754
|
+
|
|
755
|
+
`ChatErrorClassification` is `"context_overflow" | "rate_limit" | "transient" | "fatal" | "unknown"`. Today this hook drives **only** context-overflow recovery: Think calls it when a turn errors **and** `contextOverflow.reactive` is enabled (if reactive is off, it is not called). Returning `"context_overflow"` runs the compact-and-retry backstop (see [Context-window overflow recovery](./index.md#context-window-overflow-recovery)); if recovery cannot save the turn, that classification is surfaced on the terminal `onChatError` call via `ChatErrorContext.classification`. The other categories are reserved for future use — returning one today is a no-op (the turn terminalizes as usual) and is not forwarded to `onChatError`. Returning `void` (the default) keeps the existing terminal behavior.
|
|
756
|
+
|
|
757
|
+
The argument may be an `Error`, an AI SDK `APICallError` (with `statusCode`/`responseBody`), or — for in-stream provider errors that surface as a stream error part rather than a throw — the error message string. Narrow accordingly. (Think confirms provider context-overflow errors always surface as in-stream error parts, never thrown exceptions out of `streamText`, so this hook sees them whether you read the `Error` or the string form.)
|
|
758
|
+
|
|
759
|
+
The second argument is a [`ChatErrorContext`](#onchaterror): when consulted for overflow recovery it is `{ stage: "stream", requestId }`, so a classifier can correlate the error with the in-flight turn — for example to call [`cancelChat(requestId)`](./index.md) and bail out of recovery.
|
|
760
|
+
|
|
761
|
+
### Example
|
|
762
|
+
|
|
763
|
+
For the common case, assign the bundled `defaultContextOverflowClassifier`, which matches the context-overflow errors of Anthropic, OpenAI, Google, Bedrock, and others:
|
|
764
|
+
|
|
765
|
+
```typescript
|
|
766
|
+
import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
|
|
767
|
+
|
|
768
|
+
export class MyAgent extends Think<Env> {
|
|
769
|
+
override classifyChatError = defaultContextOverflowClassifier;
|
|
770
|
+
}
|
|
771
|
+
```
|
|
772
|
+
|
|
773
|
+
Or write your own, optionally delegating to the bundled classifier:
|
|
774
|
+
|
|
775
|
+
```typescript
|
|
776
|
+
import type { ChatErrorClassification } from "@cloudflare/think";
|
|
777
|
+
import { defaultContextOverflowClassifier } from "@cloudflare/think";
|
|
778
|
+
|
|
779
|
+
classifyChatError(error: unknown): ChatErrorClassification | void {
|
|
780
|
+
if (error instanceof Error && /rate.?limit/i.test(error.message)) {
|
|
781
|
+
return "rate_limit";
|
|
782
|
+
}
|
|
783
|
+
return defaultContextOverflowClassifier(error);
|
|
784
|
+
}
|
|
785
|
+
```
|
|
786
|
+
|
|
787
|
+
---
|
|
788
|
+
|
|
789
|
+
## Extension hook subscriptions
|
|
790
|
+
|
|
791
|
+
Extensions can subscribe to `beforeTurn`, `beforeToolCall`, `afterToolCall`, `onStepFinish`, and `onChunk` via their manifest's `hooks` array. Think dispatches to extension-side handlers in load order, after the subclass hook has run, with a JSON-safe snapshot of the event. `beforeStep` is available to subclasses only and is not dispatched to extensions (it runs on the AI SDK's `prepareStep` boundary, where snapshotting non-serializable inputs like `LanguageModel` instances is not meaningful).
|
|
792
|
+
|
|
793
|
+
```js
|
|
794
|
+
// extension source
|
|
795
|
+
({
|
|
796
|
+
tools: {
|
|
797
|
+
/* ... */
|
|
798
|
+
},
|
|
799
|
+
hooks: {
|
|
800
|
+
beforeTurn: async (snapshot, host) => {
|
|
801
|
+
/* may return TurnConfig */
|
|
802
|
+
},
|
|
803
|
+
beforeToolCall: async (snapshot, host) => {
|
|
804
|
+
/* observation */
|
|
805
|
+
},
|
|
806
|
+
afterToolCall: async (snapshot, host) => {
|
|
807
|
+
/* observation */
|
|
808
|
+
},
|
|
809
|
+
onStepFinish: async (snapshot, host) => {
|
|
810
|
+
/* observation */
|
|
811
|
+
},
|
|
812
|
+
onChunk: async (snapshot, host) => {
|
|
813
|
+
/* observation; high-frequency */
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
});
|
|
817
|
+
```
|
|
818
|
+
|
|
819
|
+
The handler receives `(snapshot, host)` — symmetric with tool `execute`. `host` is the bridge (`HostBridgeLoopback`) when the extension was loaded with permissions that require it; otherwise `null`.
|
|
820
|
+
|
|
821
|
+
### Snapshot shapes
|
|
822
|
+
|
|
823
|
+
Snapshots are intentionally narrower than the subclass `Context` types — class instances, `AbortSignal`s, and other non-JSON-clonable values can't cross the Workers RPC boundary.
|
|
824
|
+
|
|
825
|
+
| Hook | Snapshot fields |
|
|
826
|
+
| ---------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
827
|
+
| `beforeTurn` | `{ system, toolNames, messageCount, continuation, body?, modelId }` — see `TurnContextSnapshot` |
|
|
828
|
+
| `beforeToolCall` | `{ toolName, toolCallId, input, stepNumber, dynamic? }` |
|
|
829
|
+
| `afterToolCall` | `{ toolName, toolCallId, input, stepNumber, durationMs, success, output? \| error?, dynamic? }` |
|
|
830
|
+
| `onStepFinish` | `{ stepNumber, finishReason, text, reasoningText, toolCallCount, toolResultCount, usage, providerMetadata }` |
|
|
831
|
+
| `onChunk` | `{ type, text?, toolName?, toolCallId? }` — minimal because this fires per token |
|
|
832
|
+
|
|
833
|
+
### Return values
|
|
834
|
+
|
|
835
|
+
Only `beforeTurn` honors return values (it merges scalar `TurnConfig` fields back into the turn). The other extension hooks are observation-only — return values are discarded. Errors thrown from extension hooks are caught and logged; they do not abort the turn.
|
|
836
|
+
|
|
837
|
+
### Performance note
|
|
838
|
+
|
|
839
|
+
`onChunk` fires per streaming token. Subscribing in an extension means an RPC round trip per chunk. Use sparingly — prefer aggregating in `onStepFinish` instead unless you specifically need per-token reactivity.
|