evalution 1.0.4 → 1.0.6
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/LICENSING.md +30 -6
- package/README.md +1 -0
- package/dist/check-BTg6THHB.d.ts +1925 -0
- package/dist/checks/index.d.ts +71 -0
- package/dist/checks/index.js +2 -0
- package/dist/checks-Cq97JU-h.js +309 -0
- package/dist/cli/index.js +5328 -348
- package/dist/client/assets/DatasetView-BcYR5beY.css +1 -0
- package/dist/client/assets/DatasetView-CyX0mCj8.js +15 -0
- package/dist/client/assets/EvalRunView-5IZp_6Ob.js +2 -0
- package/dist/client/assets/EvalView-DBTK6rCe.js +1 -0
- package/dist/client/assets/abap-BdImnpbu.js +1 -0
- package/dist/client/assets/actionscript-3-CoDkCxhg.js +1 -0
- package/dist/client/assets/ada-bCR0ucgS.js +1 -0
- package/dist/client/assets/andromeeda-C4gqWexZ.js +1 -0
- package/dist/client/assets/angular-html-CU67Zn6k.js +1 -0
- package/dist/client/assets/angular-ts-BwZT4LLn.js +1 -0
- package/dist/client/assets/apache-Pmp26Uib.js +1 -0
- package/dist/client/assets/apex-D8_7TLub.js +1 -0
- package/dist/client/assets/apl-dKokRX4l.js +1 -0
- package/dist/client/assets/applescript-Co6uUVPk.js +1 -0
- package/dist/client/assets/ara-BRHolxvo.js +1 -0
- package/dist/client/assets/asciidoc-Ve4PFQV2.js +1 -0
- package/dist/client/assets/asm-D_Q5rh1f.js +1 -0
- package/dist/client/assets/astro-CbQHKStN.js +1 -0
- package/dist/client/assets/aurora-x-D-2ljcwZ.js +1 -0
- package/dist/client/assets/awk-DMzUqQB5.js +1 -0
- package/dist/client/assets/ayu-dark-DYE7WIF3.js +1 -0
- package/dist/client/assets/ayu-light-BA47KaF1.js +1 -0
- package/dist/client/assets/ayu-mirage-32ctXXKs.js +1 -0
- package/dist/client/assets/ballerina-BFfxhgS-.js +1 -0
- package/dist/client/assets/bat-BkioyH1T.js +1 -0
- package/dist/client/assets/beancount-k_qm7-4y.js +1 -0
- package/dist/client/assets/berry-uYugtg8r.js +1 -0
- package/dist/client/assets/bibtex-CHM0blh-.js +1 -0
- package/dist/client/assets/bicep-Bmn6On1c.js +1 -0
- package/dist/client/assets/bird2-DPOp833l.js +1 -0
- package/dist/client/assets/blade-D4QpJJKB.js +1 -0
- package/dist/client/assets/bsl-BO_Y6i37.js +1 -0
- package/dist/client/assets/c-BIGW1oBm.js +1 -0
- package/dist/client/assets/c3-eo99z4R2.js +1 -0
- package/dist/client/assets/cadence-Bv_4Rxtq.js +1 -0
- package/dist/client/assets/cairo-KRGpt6FW.js +1 -0
- package/dist/client/assets/catppuccin-frappe-DFWUc33u.js +1 -0
- package/dist/client/assets/catppuccin-latte-C9dUb6Cb.js +1 -0
- package/dist/client/assets/catppuccin-macchiato-DQyhUUbL.js +1 -0
- package/dist/client/assets/catppuccin-mocha-D87Tk5Gz.js +1 -0
- package/dist/client/assets/clarity-D53aC0YG.js +1 -0
- package/dist/client/assets/clojure-P80f7IUj.js +1 -0
- package/dist/client/assets/cmake-D1j8_8rp.js +1 -0
- package/dist/client/assets/cobol-nwyudZeR.js +1 -0
- package/dist/client/assets/codeowners-Bp6g37R7.js +1 -0
- package/dist/client/assets/codeql-DsOJ9woJ.js +1 -0
- package/dist/client/assets/coffee-Ch7k5sss.js +1 -0
- package/dist/client/assets/common-lisp-Cg-RD9OK.js +1 -0
- package/dist/client/assets/coq-DkFqJrB1.js +1 -0
- package/dist/client/assets/cpp-CofmeUqb.js +1 -0
- package/dist/client/assets/crystal-tKQVLTB8.js +1 -0
- package/dist/client/assets/csharp-COcwbKMJ.js +1 -0
- package/dist/client/assets/css-DPfMkruS.js +1 -0
- package/dist/client/assets/csv-fuZLfV_i.js +1 -0
- package/dist/client/assets/cue-D82EKSYY.js +1 -0
- package/dist/client/assets/cypher-COkxafJQ.js +1 -0
- package/dist/client/assets/d-85-TOEBH.js +1 -0
- package/dist/client/assets/dark-plus-C3mMm8J8.js +1 -0
- package/dist/client/assets/dart-CF10PKvl.js +1 -0
- package/dist/client/assets/data-grid-overlay-editor-CBtkQufd.js +1 -0
- package/dist/client/assets/dax-CEL-wOlO.js +1 -0
- package/dist/client/assets/desktop-BmXAJ9_W.js +1 -0
- package/dist/client/assets/diff-D97Zzqfu.js +1 -0
- package/dist/client/assets/docker-BcOcwvcX.js +1 -0
- package/dist/client/assets/dotenv-Da5cRb03.js +1 -0
- package/dist/client/assets/dracula-BzJJZx-M.js +1 -0
- package/dist/client/assets/dracula-soft-BXkSAIEj.js +1 -0
- package/dist/client/assets/dream-maker-BtqSS_iP.js +1 -0
- package/dist/client/assets/edge-BkV0erSs.js +1 -0
- package/dist/client/assets/elixir-CDX3lj18.js +1 -0
- package/dist/client/assets/elm-DbKCFpqz.js +1 -0
- package/dist/client/assets/emacs-lisp-C9XAeP06.js +1 -0
- package/dist/client/assets/erb-B12qg9BL.js +1 -0
- package/dist/client/assets/erlang-DsQrWhSR.js +1 -0
- package/dist/client/assets/everforest-dark-BgDCqdQA.js +1 -0
- package/dist/client/assets/everforest-light-C8M2exoo.js +1 -0
- package/dist/client/assets/fennel-BYunw83y.js +1 -0
- package/dist/client/assets/fish-BvzEVeQv.js +1 -0
- package/dist/client/assets/fluent-C4IJs8-o.js +1 -0
- package/dist/client/assets/fortran-fixed-form-CkoXwp7k.js +1 -0
- package/dist/client/assets/fortran-free-form-BxgE0vQu.js +1 -0
- package/dist/client/assets/fsharp-CXgrBDvD.js +1 -0
- package/dist/client/assets/gdresource-BOOCDP_w.js +1 -0
- package/dist/client/assets/gdscript-C5YyOfLZ.js +1 -0
- package/dist/client/assets/gdshader-DkwncUOv.js +1 -0
- package/dist/client/assets/genie-D0YGMca9.js +1 -0
- package/dist/client/assets/gherkin-DyxjwDmM.js +1 -0
- package/dist/client/assets/git-commit-F4YmCXRG.js +1 -0
- package/dist/client/assets/git-rebase-r7XF79zn.js +1 -0
- package/dist/client/assets/github-dark-DHJKELXO.js +1 -0
- package/dist/client/assets/github-dark-default-Cuk6v7N8.js +1 -0
- package/dist/client/assets/github-dark-dimmed-DH5Ifo-i.js +1 -0
- package/dist/client/assets/github-dark-high-contrast-E3gJ1_iC.js +1 -0
- package/dist/client/assets/github-light-DAi9KRSo.js +1 -0
- package/dist/client/assets/github-light-default-D7oLnXFd.js +1 -0
- package/dist/client/assets/github-light-high-contrast-BfjtVDDH.js +1 -0
- package/dist/client/assets/gleam-BspZqrRM.js +1 -0
- package/dist/client/assets/glimmer-js-Rg0-pVw9.js +1 -0
- package/dist/client/assets/glimmer-ts-U6CK756n.js +1 -0
- package/dist/client/assets/glsl-DplSGwfg.js +1 -0
- package/dist/client/assets/gn-n2N0HUVH.js +1 -0
- package/dist/client/assets/gnuplot-DdkO51Og.js +1 -0
- package/dist/client/assets/go-CxLEBnE3.js +1 -0
- package/dist/client/assets/graphql-ChdNCCLP.js +1 -0
- package/dist/client/assets/groovy-gcz8RCvz.js +1 -0
- package/dist/client/assets/gruvbox-dark-hard-CFHQjOhq.js +1 -0
- package/dist/client/assets/gruvbox-dark-medium-GsRaNv29.js +1 -0
- package/dist/client/assets/gruvbox-dark-soft-CVdnzihN.js +1 -0
- package/dist/client/assets/gruvbox-light-hard-CH1njM8p.js +1 -0
- package/dist/client/assets/gruvbox-light-medium-DRw_LuNl.js +1 -0
- package/dist/client/assets/gruvbox-light-soft-hJgmCMqR.js +1 -0
- package/dist/client/assets/hack-CaT9iCJl.js +1 -0
- package/dist/client/assets/haml-B8DHNrY2.js +1 -0
- package/dist/client/assets/handlebars-BL8al0AC.js +1 -0
- package/dist/client/assets/haskell-Df6bDoY_.js +1 -0
- package/dist/client/assets/haxe-CzTSHFRz.js +1 -0
- package/dist/client/assets/hcl-BWvSN4gD.js +1 -0
- package/dist/client/assets/highlighted-body-KPVGNVTW-DyudWmoO.js +1 -0
- package/dist/client/assets/hjson-D5-asLiD.js +1 -0
- package/dist/client/assets/hlsl-D3lLCCz7.js +1 -0
- package/dist/client/assets/horizon-BUw7H-hv.js +1 -0
- package/dist/client/assets/horizon-bright-Cn-bp-IR.js +1 -0
- package/dist/client/assets/houston-DnULxvSX.js +1 -0
- package/dist/client/assets/html-GMplVEZG.js +1 -0
- package/dist/client/assets/html-derivative-BFtXZ54Q.js +1 -0
- package/dist/client/assets/http-jrhK8wxY.js +1 -0
- package/dist/client/assets/hurl-irOxFIW8.js +1 -0
- package/dist/client/assets/hxml-Bvhsp5Yf.js +1 -0
- package/dist/client/assets/hy-DFXneXwc.js +1 -0
- package/dist/client/assets/imba-DGztddWO.js +1 -0
- package/dist/client/assets/index-B7OFMd2c.css +32 -0
- package/dist/client/assets/index-aypgoZcG.js +701 -0
- package/dist/client/assets/ini-BEwlwnbL.js +1 -0
- package/dist/client/assets/java-CylS5w8V.js +1 -0
- package/dist/client/assets/javascript-wDzz0qaB.js +1 -0
- package/dist/client/assets/jinja-4LBKfQ-Z.js +1 -0
- package/dist/client/assets/jison-wvAkD_A8.js +1 -0
- package/dist/client/assets/json-Cp-IABpG.js +1 -0
- package/dist/client/assets/json5-C9tS-k6U.js +1 -0
- package/dist/client/assets/jsonc-Des-eS-w.js +1 -0
- package/dist/client/assets/jsonl-DcaNXYhu.js +1 -0
- package/dist/client/assets/jsonnet-DFQXde-d.js +1 -0
- package/dist/client/assets/jssm-C2t-YnRu.js +1 -0
- package/dist/client/assets/jsx-g9-lgVsj.js +1 -0
- package/dist/client/assets/julia-CxzCAyBv.js +1 -0
- package/dist/client/assets/just-Cw27pwNe.js +1 -0
- package/dist/client/assets/kanagawa-dragon-CkXjmgJE.js +1 -0
- package/dist/client/assets/kanagawa-lotus-CfQXZHmo.js +1 -0
- package/dist/client/assets/kanagawa-wave-DWedfzmr.js +1 -0
- package/dist/client/assets/kdl-DV7GczEv.js +1 -0
- package/dist/client/assets/kotlin-BdnUsdx6.js +1 -0
- package/dist/client/assets/kusto-DZf3V79B.js +1 -0
- package/dist/client/assets/laserwave-DUszq2jm.js +1 -0
- package/dist/client/assets/latex-CWtU0Tv5.js +1 -0
- package/dist/client/assets/lean-BZvkOJ9d.js +1 -0
- package/dist/client/assets/less-B1dDrJ26.js +1 -0
- package/dist/client/assets/light-plus-B7mTdjB0.js +1 -0
- package/dist/client/assets/liquid-DYVedYrR.js +1 -0
- package/dist/client/assets/llvm-DjAJT7YJ.js +1 -0
- package/dist/client/assets/log-2UxHyX5q.js +1 -0
- package/dist/client/assets/logo-BtOb2qkB.js +1 -0
- package/dist/client/assets/lua-BaeVxFsk.js +1 -0
- package/dist/client/assets/luau-C-HG3fhB.js +1 -0
- package/dist/client/assets/make-CHLpvVh8.js +1 -0
- package/dist/client/assets/markdown-Cvjx9yec.js +1 -0
- package/dist/client/assets/marko-CnJfTvn9.js +1 -0
- package/dist/client/assets/material-theme-D5KoaKCx.js +1 -0
- package/dist/client/assets/material-theme-darker-BfHTSMKl.js +1 -0
- package/dist/client/assets/material-theme-lighter-B0m2ddpp.js +1 -0
- package/dist/client/assets/material-theme-ocean-CyktbL80.js +1 -0
- package/dist/client/assets/material-theme-palenight-Csfq5Kiy.js +1 -0
- package/dist/client/assets/matlab-D7o27uSR.js +1 -0
- package/dist/client/assets/mdc-BMNejdWA.js +1 -0
- package/dist/client/assets/mdx-Cmh6b_Ma.js +1 -0
- package/dist/client/assets/mermaid-mWjccvbQ.js +1 -0
- package/dist/client/assets/min-dark-CafNBF8u.js +1 -0
- package/dist/client/assets/min-light-CTRr51gU.js +1 -0
- package/dist/client/assets/mipsasm-CKIfxQSi.js +1 -0
- package/dist/client/assets/mojo-rZm6bMo-.js +1 -0
- package/dist/client/assets/monokai-D4h5O-jR.js +1 -0
- package/dist/client/assets/moonbit-_H4v1dQx.js +1 -0
- package/dist/client/assets/move-IF9eRakj.js +1 -0
- package/dist/client/assets/narrat-DRg8JJMk.js +1 -0
- package/dist/client/assets/nextflow-Zz6hmt5N.js +1 -0
- package/dist/client/assets/nextflow-groovy-BeH2EWoN.js +1 -0
- package/dist/client/assets/nginx-BpAMiNFr.js +1 -0
- package/dist/client/assets/night-owl-C39BiMTA.js +1 -0
- package/dist/client/assets/night-owl-light-CMTm3GFP.js +1 -0
- package/dist/client/assets/nim-CVrawwO9.js +1 -0
- package/dist/client/assets/nix-CwoSXNpI.js +1 -0
- package/dist/client/assets/nord-Ddv68eIx.js +1 -0
- package/dist/client/assets/number-overlay-editor-CXHiTLsp.js +9 -0
- package/dist/client/assets/nushell-Cz2AlsmD.js +1 -0
- package/dist/client/assets/objective-c-DXmwc3jG.js +1 -0
- package/dist/client/assets/objective-cpp-CLxacb5B.js +1 -0
- package/dist/client/assets/ocaml-C0hk2d4L.js +1 -0
- package/dist/client/assets/odin-BBf5iR-q.js +1 -0
- package/dist/client/assets/one-dark-pro-DVMEJ2y_.js +1 -0
- package/dist/client/assets/one-light-C3Wv6jpd.js +1 -0
- package/dist/client/assets/openscad-C4EeE6gA.js +1 -0
- package/dist/client/assets/pascal-D93ZcfNL.js +1 -0
- package/dist/client/assets/perl-C0TMdlhV.js +1 -0
- package/dist/client/assets/php-Dhbhpdrm.js +1 -0
- package/dist/client/assets/pkl-u5AG7uiY.js +1 -0
- package/dist/client/assets/plastic-3e1v2bzS.js +1 -0
- package/dist/client/assets/plsql-ChMvpjG-.js +1 -0
- package/dist/client/assets/po-BTJTHyun.js +1 -0
- package/dist/client/assets/poimandres-CS3Unz2-.js +1 -0
- package/dist/client/assets/polar-C0HS_06l.js +1 -0
- package/dist/client/assets/postcss-CXtECtnM.js +1 -0
- package/dist/client/assets/powerquery-CEu0bR-o.js +1 -0
- package/dist/client/assets/powershell-Dpen1YoG.js +1 -0
- package/dist/client/assets/prisma-Dd19v3D-.js +1 -0
- package/dist/client/assets/prolog-CbFg5uaA.js +1 -0
- package/dist/client/assets/proto-C7zT0LnQ.js +1 -0
- package/dist/client/assets/pug-CGlum2m_.js +1 -0
- package/dist/client/assets/puppet-BMWR74SV.js +1 -0
- package/dist/client/assets/purescript-CklMAg4u.js +1 -0
- package/dist/client/assets/python-B6aJPvgy.js +1 -0
- package/dist/client/assets/qml-3beO22l8.js +1 -0
- package/dist/client/assets/qmldir-C8lEn-DE.js +1 -0
- package/dist/client/assets/qss-IeuSbFQv.js +1 -0
- package/dist/client/assets/r-Dspwwk_N.js +1 -0
- package/dist/client/assets/racket-BqYA7rlc.js +1 -0
- package/dist/client/assets/raku-DXvB9xmW.js +1 -0
- package/dist/client/assets/razor-Uh8Bk_45.js +1 -0
- package/dist/client/assets/red-bN70gL4F.js +1 -0
- package/dist/client/assets/reg-C-SQnVFl.js +1 -0
- package/dist/client/assets/regexp-CDVJQ6XC.js +1 -0
- package/dist/client/assets/rel-C3B-1QV4.js +1 -0
- package/dist/client/assets/riscv-BM1_JUlF.js +1 -0
- package/dist/client/assets/ron-D8l8udqQ.js +1 -0
- package/dist/client/assets/rose-pine-dawn-DHQR4-dF.js +1 -0
- package/dist/client/assets/rose-pine-moon-D4_iv3hh.js +1 -0
- package/dist/client/assets/rose-pine-qdsjHGoJ.js +1 -0
- package/dist/client/assets/rosmsg-BJDFO7_C.js +1 -0
- package/dist/client/assets/rst-BrH8l1NY.js +1 -0
- package/dist/client/assets/ruby-Dw2BHqvy.js +1 -0
- package/dist/client/assets/rust-B1yitclQ.js +1 -0
- package/dist/client/assets/sas-cz2c8ADy.js +1 -0
- package/dist/client/assets/sass-Cj5Yp3dK.js +1 -0
- package/dist/client/assets/scala-C151Ov-r.js +1 -0
- package/dist/client/assets/scheme-C98Dy4si.js +1 -0
- package/dist/client/assets/scss-OYdSNvt2.js +1 -0
- package/dist/client/assets/sdbl-DVxCFoDh.js +1 -0
- package/dist/client/assets/shaderlab-Dg9Lc6iA.js +1 -0
- package/dist/client/assets/shellscript-Yzrsuije.js +1 -0
- package/dist/client/assets/shellsession-BADoaaVG.js +1 -0
- package/dist/client/assets/slack-dark-BthQWCQV.js +1 -0
- package/dist/client/assets/slack-ochin-DqwNpetd.js +1 -0
- package/dist/client/assets/smalltalk-BERRCDM3.js +1 -0
- package/dist/client/assets/snazzy-light-Bw305WKR.js +1 -0
- package/dist/client/assets/solarized-dark-DXbdFlpD.js +1 -0
- package/dist/client/assets/solarized-light-L9t79GZl.js +1 -0
- package/dist/client/assets/solidity-rGO070M0.js +1 -0
- package/dist/client/assets/soy-Brmx7dQM.js +1 -0
- package/dist/client/assets/sparql-rVzFXLq3.js +1 -0
- package/dist/client/assets/splunk-BtCnVYZw.js +1 -0
- package/dist/client/assets/sql-BLtJtn59.js +1 -0
- package/dist/client/assets/ssh-config-_ykCGR6B.js +1 -0
- package/dist/client/assets/stata-BH5u7GGu.js +1 -0
- package/dist/client/assets/stylus-BEDo0Tqx.js +1 -0
- package/dist/client/assets/surrealql-Bq5Q-fJD.js +1 -0
- package/dist/client/assets/svelte-C_ipcX3V.js +1 -0
- package/dist/client/assets/swift-D82vCrfD.js +1 -0
- package/dist/client/assets/synthwave-84-CbfX1IO0.js +1 -0
- package/dist/client/assets/system-verilog-CnnmHF94.js +1 -0
- package/dist/client/assets/systemd-4A_iFExJ.js +1 -0
- package/dist/client/assets/talonscript-CkByrt1z.js +1 -0
- package/dist/client/assets/tasl-QIJgUcNo.js +1 -0
- package/dist/client/assets/tcl-dwOrl1Do.js +1 -0
- package/dist/client/assets/templ-P3uqSqPl.js +1 -0
- package/dist/client/assets/terraform-BETggiCN.js +1 -0
- package/dist/client/assets/tex-idrVyKtj.js +1 -0
- package/dist/client/assets/tokyo-night-hegEt444.js +1 -0
- package/dist/client/assets/toml-vGWfd6FD.js +1 -0
- package/dist/client/assets/ts-tags-zn1MmPIZ.js +1 -0
- package/dist/client/assets/tsv-B_m7g4N7.js +1 -0
- package/dist/client/assets/tsx-COt5Ahok.js +1 -0
- package/dist/client/assets/turtle-BsS91CYL.js +1 -0
- package/dist/client/assets/twig-DNn4PbVi.js +1 -0
- package/dist/client/assets/typescript-BPQ3VLAy.js +1 -0
- package/dist/client/assets/typespec-BGHnOYBU.js +1 -0
- package/dist/client/assets/typst-DHCkPAjA.js +1 -0
- package/dist/client/assets/v-BcVCzyr7.js +1 -0
- package/dist/client/assets/vala-CsfeWuGM.js +1 -0
- package/dist/client/assets/vb-D17OF-Vu.js +1 -0
- package/dist/client/assets/verilog-BQ8w6xss.js +1 -0
- package/dist/client/assets/vesper-DU1UobuO.js +1 -0
- package/dist/client/assets/vhdl-CeAyd5Ju.js +1 -0
- package/dist/client/assets/viml-CJc9bBzg.js +1 -0
- package/dist/client/assets/vitesse-black-Bkuqu6BP.js +1 -0
- package/dist/client/assets/vitesse-dark-D0r3Knsf.js +1 -0
- package/dist/client/assets/vitesse-light-CVO1_9PV.js +1 -0
- package/dist/client/assets/vue-DN_0RTcg.js +1 -0
- package/dist/client/assets/vue-html-AaS7Mt5G.js +1 -0
- package/dist/client/assets/vue-vine-CQOfvN7w.js +1 -0
- package/dist/client/assets/vyper-CDx5xZoG.js +1 -0
- package/dist/client/assets/wasm-CG6Dc4jp.js +1 -0
- package/dist/client/assets/wasm-MzD3tlZU.js +1 -0
- package/dist/client/assets/wenyan-BV7otONQ.js +1 -0
- package/dist/client/assets/wgsl-Dx-B1_4e.js +1 -0
- package/dist/client/assets/wikitext-BhOHFoWU.js +1 -0
- package/dist/client/assets/wit-5i3qLPDT.js +1 -0
- package/dist/client/assets/wolfram-lXgVvXCa.js +1 -0
- package/dist/client/assets/xml-sdJ4AIDG.js +1 -0
- package/dist/client/assets/xsl-CtQFsRM5.js +1 -0
- package/dist/client/assets/yaml-Buea-lGh.js +1 -0
- package/dist/client/assets/zenscript-DVFEvuxE.js +1 -0
- package/dist/client/assets/zig-VOosw3JB.js +1 -0
- package/dist/client/index.html +2 -2
- package/dist/dataset-types-CSjbM_Vz.d.ts +564 -0
- package/dist/index.d.ts +3806 -894
- package/dist/index.js +3653 -578
- package/dist/instance-names-pVQxJbtw.js +12 -0
- package/dist/otlp-trace-ingestor-V8_bbpUG.js +12376 -0
- package/dist/runtime-DCNx7dHI.js +302 -0
- package/dist/trace-Dn6Pfcc5.d.ts +200 -0
- package/dist/views/datasets/index.d.ts +68 -0
- package/dist/views/datasets/index.js +237 -0
- package/dist/views/index.d.ts +98 -0
- package/dist/views/index.js +156 -0
- package/dist/views/react/index.d.ts +55 -0
- package/dist/views/react/index.js +246 -0
- package/package.json +78 -14
- package/dist/client/assets/index-C4XXh0na.js +0 -144
- package/dist/client/assets/index-CHPZsnKo.css +0 -32
- package/dist/vercel-ai-sdk-B8ivuOzP.js +0 -853
package/dist/index.js
CHANGED
|
@@ -1,156 +1,1610 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
1
|
+
import { A as SqlQueryError, At as TypeSafeTelemetry, B as EvalRunRefusedError, Bt as findPackageDts, C as promptIdOf, Ct as OTelTraceIngestor, D as EvalNotFoundError, Dt as shortId, E as normalizeOtlpRequest, Ft as PLAYGROUND_ENVIRONMENT, Gt as PROMPT_NAME_ATTRIBUTE, Ht as missingPackageMessage, It as SERVICE_NAME_ATTRIBUTE, Jt as PROMPT_VERSION_ATTRIBUTE, Kt as PROMPT_PROVIDER_ID_ATTRIBUTE, L as DatasetNotFoundError, Lt as isCheckSpan, Mt as PLAYGROUND_RESOURCE, Nt as CHECK_ATTRIBUTE, O as DEFAULT_MAX_QUERY_ROWS, Ot as TypeSafeSDK, Pt as DEPLOYMENT_ENVIRONMENT_ATTRIBUTE, Qt as mergePromptIdentity, R as DatasetValidationError, Rt as spanMessages, S as VariationConflictError, St as setupGlobalOTelPipeline, T as decodeOtlpProtobuf, Ut as PROMPT_ID_ATTRIBUTE, V as EvalRunner, Vt as isMissingPackage, Wt as PROMPT_INPUTS_ATTRIBUTE, Xt as createTracerForPrompt, Yt as SPAN_KIND_ATTRIBUTE, Zt as getPromptSpanAttributes, _ as assertSqliteFile, _t as isResource, a as BaseTraceProvider, at as resolveExecutionInputs, b as rollupSpans, bt as VercelAISDK, c as LocalEvalProvider, ct as findInputCycle, d as runEvalMigrations, dt as namedBindings, f as LocalDirectoryDatasetProvider, ft as DEFAULT_PLAYGROUND_IGNORE_PATTERNS, g as runMigrations, gt as isValidInstanceName, h as MIGRATIONS_TABLE, ht as resourceParameterNames, i as mergeSpans, it as resolveExecutionInput, jt as BaseTraceIngestor, k as DEFAULT_QUERY_TIMEOUT_MS, kt as PROMPT_IDENTITY, l as openLocalEvalProvider, lt as inputReferenceProblems, m as runDatasetMigrations, mt as ResourceRegistry, n as LocalDatabaseTraceProvider, nn as isVariationLoaderHookRegistered, ot as stampReceipts, p as TursoDatasetProvider, pt as DEFAULT_PLAYGROUND_INCLUDE_PATTERNS, qt as PROMPT_VARIATION_ATTRIBUTE, r as TursoTraceProvider, rn as registerVariationLoaderHook, rt as matchSourcesToSlots, s as TRACE_QUERY_SCHEMA, st as collectInputSlots, t as OtlpTraceIngestor, tn as LocalFileProvider, u as TursoEvalProvider, v as createLocalTursoClient, vt as isStandardSchema, w as toPromptRef, wt as isEditable, xt as VercelAISDKTelemetry, y as mkdirSelfIgnoring, yt as resource, z as DEFAULT_EVAL_CONCURRENCY, zt as assertUpdateStyle } from "./otlp-trace-ingestor-V8_bbpUG.js";
|
|
2
|
+
import { _ as isCheck, g as check, n as builtinCheck, r as builtinCheckInfos } from "./checks-Cq97JU-h.js";
|
|
3
|
+
import "node:module";
|
|
4
|
+
import path, { dirname } from "node:path";
|
|
5
|
+
import { access, realpath } from "node:fs/promises";
|
|
6
|
+
import { minimatch } from "minimatch";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
5
8
|
import fs$1 from "node:fs";
|
|
6
|
-
import { addProperty, extractPropertiesFromDeclaration, extractPropertiesFromObjectLiteral, extractPropertiesFromParameters, findTypeDeclaration, removeProperty, updateProperty, valueToSourceText } from "ts-proppy";
|
|
9
|
+
import { addProperty, buildPropTypeFromType, extractPropertiesFromDeclaration, extractPropertiesFromObjectLiteral, extractPropertiesFromParameters, findTypeDeclaration, isOpaqueType, removeProperty, resolveBindings, updateProperty, valueToSourceText } from "ts-proppy";
|
|
7
10
|
import ts from "typescript";
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { drizzle } from "drizzle-orm/tursodatabase-sync";
|
|
13
|
+
import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
|
|
14
|
+
import { integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
15
|
+
//#region \0rolldown/runtime.js
|
|
16
|
+
var __defProp = Object.defineProperty;
|
|
17
|
+
var __exportAll = (all, no_symbols) => {
|
|
18
|
+
let target = {};
|
|
19
|
+
for (var name in all) __defProp(target, name, {
|
|
20
|
+
get: all[name],
|
|
21
|
+
enumerable: true
|
|
22
|
+
});
|
|
23
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
24
|
+
return target;
|
|
25
|
+
};
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/file-provider-memory.ts
|
|
12
28
|
/**
|
|
13
|
-
*
|
|
29
|
+
* An in-memory {@link FileProvider} backed by a `Map<string, string>`.
|
|
14
30
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
31
|
+
* Intended for unit tests and non-local environments (e.g. a browser or
|
|
32
|
+
* service-worker bundle) — all file I/O stays in-process with no disk access.
|
|
33
|
+
* It depends only on `node:path` and `minimatch`, so it carries no Node-only
|
|
34
|
+
* runtime dependencies (no `node:fs`, `chokidar`, etc.). Calling
|
|
35
|
+
* {@link writeFile} triggers any active {@link watch} callbacks synchronously,
|
|
36
|
+
* making it easy to test reactive code paths.
|
|
18
37
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* const provider = new MemoryFileProvider({
|
|
41
|
+
* '/virtual/prompt.ts': 'export function myPrompt() { ... }',
|
|
42
|
+
* });
|
|
43
|
+
* const content = await provider.readFile('/virtual/prompt.ts');
|
|
44
|
+
* ```
|
|
21
45
|
*/
|
|
22
|
-
var
|
|
46
|
+
var MemoryFileProvider = class {
|
|
47
|
+
files;
|
|
48
|
+
watchers = /* @__PURE__ */ new Set();
|
|
49
|
+
/**
|
|
50
|
+
* @param files - Initial file contents keyed by absolute path.
|
|
51
|
+
*/
|
|
52
|
+
constructor(files = {}) {
|
|
53
|
+
this.files = new Map(Object.entries(files));
|
|
54
|
+
}
|
|
23
55
|
async readFile(filePath) {
|
|
24
|
-
|
|
56
|
+
const content = this.files.get(filePath);
|
|
57
|
+
if (content === void 0) throw new Error(`File not found: ${filePath}`);
|
|
58
|
+
return content;
|
|
25
59
|
}
|
|
26
60
|
async writeFile(filePath, content) {
|
|
27
|
-
|
|
28
|
-
|
|
61
|
+
const isNew = !this.files.has(filePath);
|
|
62
|
+
this.files.set(filePath, content);
|
|
63
|
+
this.notifyWatchers(isNew ? "add" : "change", filePath);
|
|
29
64
|
}
|
|
30
65
|
async deleteFile(filePath) {
|
|
31
|
-
|
|
66
|
+
this.files.delete(filePath);
|
|
67
|
+
this.notifyWatchers("remove", filePath);
|
|
32
68
|
}
|
|
33
69
|
async import(filePath) {
|
|
34
|
-
|
|
70
|
+
const content = this.files.get(filePath);
|
|
71
|
+
if (content === void 0) throw new Error(`File not found: ${filePath}`);
|
|
72
|
+
return import(`data:text/javascript;charset=utf-8,${encodeURIComponent(content)}`);
|
|
73
|
+
}
|
|
74
|
+
async importSource(_filePath, source) {
|
|
75
|
+
return import(`data:text/javascript;charset=utf-8,${encodeURIComponent(source)}`);
|
|
35
76
|
}
|
|
36
77
|
async *glob(pattern, options = {}) {
|
|
37
|
-
const { cwd, ignore = [], absolute = false } = options;
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
const relativePath =
|
|
41
|
-
if (
|
|
42
|
-
|
|
78
|
+
const { cwd = process.cwd(), ignore = [], absolute = false } = options;
|
|
79
|
+
for (const filePath of this.files.keys()) {
|
|
80
|
+
if (!filePath.startsWith(cwd + path.sep)) continue;
|
|
81
|
+
const relativePath = path.relative(cwd, filePath).replace(/\\/g, "/");
|
|
82
|
+
if (!minimatch(relativePath, pattern)) continue;
|
|
83
|
+
if (ignore.some((p) => minimatch(relativePath, p, { dot: true }))) continue;
|
|
84
|
+
yield absolute ? filePath : relativePath;
|
|
43
85
|
}
|
|
44
86
|
}
|
|
45
87
|
watch(patterns, options, callback) {
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
88
|
+
const watcher = {
|
|
89
|
+
patterns,
|
|
90
|
+
cwd: options.cwd ?? process.cwd(),
|
|
91
|
+
ignored: options.ignored ?? [],
|
|
92
|
+
callback
|
|
93
|
+
};
|
|
94
|
+
this.watchers.add(watcher);
|
|
95
|
+
return () => {
|
|
96
|
+
this.watchers.delete(watcher);
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
notifyWatchers(eventType, filePath) {
|
|
100
|
+
for (const watcher of this.watchers) {
|
|
101
|
+
const { cwd, patterns, ignored, callback } = watcher;
|
|
102
|
+
if (!filePath.startsWith(cwd + path.sep)) continue;
|
|
103
|
+
const relativePath = path.relative(cwd, filePath).replace(/\\/g, "/");
|
|
104
|
+
if (!patterns.some((p) => minimatch(relativePath, p))) continue;
|
|
105
|
+
if (ignored.some((p) => minimatch(relativePath, p, { dot: true }))) continue;
|
|
106
|
+
callback(eventType, relativePath);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/file-provider-overlay.ts
|
|
112
|
+
/**
|
|
113
|
+
* A {@link FileProvider} that lays in-memory content over another one: for
|
|
114
|
+
* an overlaid path, `readFile`, `writeFile` and `import` hit the overlay;
|
|
115
|
+
* everything else passes through.
|
|
116
|
+
*
|
|
117
|
+
* This is how a prompt variation is materialized without touching disk: its
|
|
118
|
+
* base content is overlaid at the prompt's **real** path, and the ordinary
|
|
119
|
+
* edit pipeline applies the variation's updates to it there — so parsing sees
|
|
120
|
+
* the patched text, and imports from it resolve as the real file's would.
|
|
121
|
+
* See `specs/prompt-versions-and-variations.md` §H.
|
|
122
|
+
*/
|
|
123
|
+
var OverlayFileProvider = class {
|
|
124
|
+
overlay = /* @__PURE__ */ new Map();
|
|
125
|
+
/** The provider everything not overlaid passes through to. */
|
|
126
|
+
inner;
|
|
127
|
+
/** @param inner - The provider everything not overlaid passes through to. */
|
|
128
|
+
constructor(inner) {
|
|
129
|
+
this.inner = inner;
|
|
130
|
+
}
|
|
131
|
+
/** Lays `content` over `filePath`. */
|
|
132
|
+
set(filePath, content) {
|
|
133
|
+
this.overlay.set(filePath, content);
|
|
134
|
+
}
|
|
135
|
+
/** The overlaid content at `filePath`, if any. */
|
|
136
|
+
get(filePath) {
|
|
137
|
+
return this.overlay.get(filePath);
|
|
138
|
+
}
|
|
139
|
+
/** Removes every overlay, so everything passes through again. */
|
|
140
|
+
clear() {
|
|
141
|
+
this.overlay.clear();
|
|
142
|
+
}
|
|
143
|
+
async readFile(filePath) {
|
|
144
|
+
return this.overlay.get(filePath) ?? this.inner.readFile(filePath);
|
|
145
|
+
}
|
|
146
|
+
async writeFile(filePath, content) {
|
|
147
|
+
if (this.overlay.has(filePath)) this.overlay.set(filePath, content);
|
|
148
|
+
else await this.inner.writeFile(filePath, content);
|
|
149
|
+
}
|
|
150
|
+
async deleteFile(filePath) {
|
|
151
|
+
if (this.overlay.has(filePath)) this.overlay.delete(filePath);
|
|
152
|
+
else await this.inner.deleteFile(filePath);
|
|
153
|
+
}
|
|
154
|
+
async import(filePath, options) {
|
|
155
|
+
const content = this.overlay.get(filePath);
|
|
156
|
+
if (content === void 0) return this.inner.import(filePath, options);
|
|
157
|
+
return this.importSource(filePath, content);
|
|
158
|
+
}
|
|
159
|
+
async importSource(filePath, source) {
|
|
160
|
+
if (!this.inner.importSource) throw new Error("This file provider can't import a module from memory, so prompt variations can't be run with it.");
|
|
161
|
+
return this.inner.importSource(filePath, source);
|
|
162
|
+
}
|
|
163
|
+
glob(pattern, options) {
|
|
164
|
+
return this.inner.glob(pattern, options);
|
|
165
|
+
}
|
|
166
|
+
watch(patterns, options, callback) {
|
|
167
|
+
return this.inner.watch(patterns, options, callback);
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
//#endregion
|
|
171
|
+
//#region src/prompt/variations/canonical-updates.ts
|
|
172
|
+
/** Prefix of a per-parameter field name, e.g. `modelParameters.temperature`. */
|
|
173
|
+
const MODEL_PARAMETER_PREFIX = "modelParameters.";
|
|
174
|
+
/**
|
|
175
|
+
* The fields a set of updates sets, as `[field, value]` pairs: `model`,
|
|
176
|
+
* `system`, `messages`, `state`, `questions`, and one
|
|
177
|
+
* `modelParameters.<name>` per model parameter. `null` means "remove".
|
|
178
|
+
*/
|
|
179
|
+
function updateFields(updates) {
|
|
180
|
+
const fields = [];
|
|
181
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
182
|
+
if (key === "style" || value === void 0) continue;
|
|
183
|
+
if (key === "modelParameters") {
|
|
184
|
+
for (const [name, param] of Object.entries(value ?? {})) if (param !== void 0) fields.push([`${MODEL_PARAMETER_PREFIX}${name}`, param]);
|
|
185
|
+
} else fields.push([key, value]);
|
|
186
|
+
}
|
|
187
|
+
return fields;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* The value `prompt` currently has for `field` (see {@link updateFields}), or
|
|
191
|
+
* `undefined` when it has none.
|
|
192
|
+
*/
|
|
193
|
+
function promptFieldValue(prompt, field) {
|
|
194
|
+
if (field.startsWith(MODEL_PARAMETER_PREFIX)) {
|
|
195
|
+
const name = field.slice(16);
|
|
196
|
+
return prompt.modelParameters.find((p) => p.def.name === name)?.value;
|
|
197
|
+
}
|
|
198
|
+
switch (field) {
|
|
199
|
+
case "model": return prompt.model;
|
|
200
|
+
case "system": return prompt.style === "chat" ? prompt.system : void 0;
|
|
201
|
+
case "messages": return prompt.style === "chat" ? prompt.messages : void 0;
|
|
202
|
+
case "state": return prompt.style === "questions" ? prompt.state.value : void 0;
|
|
203
|
+
case "questions": return prompt.style === "questions" ? prompt.questions.value : void 0;
|
|
204
|
+
default: return;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* `prompt`'s values for the fields `updates` sets — what applying them
|
|
209
|
+
* overwrites. A missing prompt has no values: every field is `null`.
|
|
210
|
+
*/
|
|
211
|
+
function fieldValuesOf(prompt, updates) {
|
|
212
|
+
return Object.fromEntries(updateFields(updates).map(([field]) => [field, (prompt && promptFieldValue(prompt, field)) ?? null]));
|
|
213
|
+
}
|
|
214
|
+
/** `values`' entries for the fields `updates` sets — `null` for one it lacks. */
|
|
215
|
+
function pickFieldValues(values, updates) {
|
|
216
|
+
return Object.fromEntries(updateFields(updates).map(([field]) => [field, values[field] ?? null]));
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Whether `prompt` still has every value in `values` — so a variation that
|
|
220
|
+
* recorded overwriting them applies to it unchanged.
|
|
221
|
+
*/
|
|
222
|
+
function hasFieldValues(prompt, values) {
|
|
223
|
+
return Object.entries(values).every(([field, value]) => sameValue(value, promptFieldValue(prompt, field)));
|
|
224
|
+
}
|
|
225
|
+
/** A copy of `updates` with `field` set to `value`. */
|
|
226
|
+
function withField(updates, field, value) {
|
|
227
|
+
if (field.startsWith(MODEL_PARAMETER_PREFIX)) {
|
|
228
|
+
const name = field.slice(16);
|
|
229
|
+
return {
|
|
230
|
+
...updates,
|
|
231
|
+
modelParameters: {
|
|
232
|
+
...updates.modelParameters,
|
|
233
|
+
[name]: value
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
...updates,
|
|
239
|
+
[field]: value
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Updates that set every field to `prompt`'s value — `null` for one it
|
|
244
|
+
* doesn't have — so applying them anywhere reproduces `prompt`'s fields.
|
|
245
|
+
* Canonicalize against the target to keep only what differs.
|
|
246
|
+
*/
|
|
247
|
+
function fieldUpdatesOf(prompt) {
|
|
248
|
+
const modelParameters = Object.fromEntries(prompt.modelParameters.map((p) => [p.def.name, p.value ?? null]));
|
|
249
|
+
const common = {
|
|
250
|
+
model: prompt.model ?? null,
|
|
251
|
+
...Object.keys(modelParameters).length > 0 && { modelParameters }
|
|
252
|
+
};
|
|
253
|
+
return prompt.style === "chat" ? {
|
|
254
|
+
style: "chat",
|
|
255
|
+
...common,
|
|
256
|
+
system: prompt.system ?? null,
|
|
257
|
+
messages: prompt.messages.length > 0 ? prompt.messages : null
|
|
258
|
+
} : {
|
|
259
|
+
style: "questions",
|
|
260
|
+
...common,
|
|
261
|
+
state: prompt.state.value ?? null,
|
|
262
|
+
questions: prompt.questions.value ?? null
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/** Whether `updates` set nothing at all. */
|
|
266
|
+
function isEmptyUpdates(updates) {
|
|
267
|
+
return updateFields(updates).length === 0;
|
|
268
|
+
}
|
|
269
|
+
/** Updates that set nothing, in `style`. */
|
|
270
|
+
function emptyUpdates(style) {
|
|
271
|
+
return { style };
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Folds successive edits into one: later fields win, `modelParameters` merges
|
|
275
|
+
* per key, and `null` (remove) is kept as a value. The result takes the last
|
|
276
|
+
* set's style; sets of another style than the last are dropped, since their
|
|
277
|
+
* fields don't mean anything in it.
|
|
278
|
+
*/
|
|
279
|
+
function mergeUpdates(...sets) {
|
|
280
|
+
const present = sets.filter((s) => !!s);
|
|
281
|
+
const style = present.at(-1)?.style ?? "chat";
|
|
282
|
+
let merged = emptyUpdates(style);
|
|
283
|
+
for (const set of present) {
|
|
284
|
+
if (set.style !== style) continue;
|
|
285
|
+
for (const [field, value] of updateFields(set)) merged = withField(merged, field, value);
|
|
286
|
+
}
|
|
287
|
+
return merged;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* `value` in the form two values are compared in: display-only details
|
|
291
|
+
* (`displayValue`, and the import candidates a catalog value carries) are
|
|
292
|
+
* dropped, a template with no interpolation is the plain string it spells,
|
|
293
|
+
* and an empty message list is no message list.
|
|
294
|
+
*/
|
|
295
|
+
function comparable(value) {
|
|
296
|
+
if (value === null || value === void 0) return void 0;
|
|
297
|
+
if (Array.isArray(value)) return value.length === 0 ? void 0 : value.map(comparableNode);
|
|
298
|
+
return comparableNode(value);
|
|
299
|
+
}
|
|
300
|
+
function comparableNode(value) {
|
|
301
|
+
if (Array.isArray(value)) return value.map(comparableNode);
|
|
302
|
+
if (!value || typeof value !== "object") return value;
|
|
303
|
+
const node = value;
|
|
304
|
+
if (typeof node.kind === "string") {
|
|
305
|
+
if (node.kind === "template" && Array.isArray(node.value)) {
|
|
306
|
+
const segments = mergeTemplateSegments(node.value);
|
|
307
|
+
if (segments.every((s) => typeof s === "string")) return {
|
|
308
|
+
kind: "primitive",
|
|
309
|
+
value: segments.join("")
|
|
310
|
+
};
|
|
311
|
+
return {
|
|
312
|
+
kind: "template",
|
|
313
|
+
value: segments.map(comparableNode)
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
const { displayValue: _, ...rest } = node;
|
|
317
|
+
if (node.kind === "functionCall") delete rest.binding;
|
|
318
|
+
return mapValues(rest);
|
|
319
|
+
}
|
|
320
|
+
return mapValues(node);
|
|
321
|
+
}
|
|
322
|
+
function mapValues(node) {
|
|
323
|
+
return Object.fromEntries(Object.entries(node).filter(([, v]) => v !== void 0).map(([k, v]) => [k, comparableNode(v)]));
|
|
324
|
+
}
|
|
325
|
+
/** Adjacent literal segments joined, empty ones dropped. */
|
|
326
|
+
function mergeTemplateSegments(segments) {
|
|
327
|
+
const out = [];
|
|
328
|
+
for (const segment of segments) {
|
|
329
|
+
if (typeof segment === "string") {
|
|
330
|
+
if (segment === "") continue;
|
|
331
|
+
if (typeof out.at(-1) === "string") {
|
|
332
|
+
out[out.length - 1] = out.at(-1) + segment;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
out.push(segment);
|
|
337
|
+
}
|
|
338
|
+
return out;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Whether two field values mean the same thing. `null` (remove) and
|
|
342
|
+
* `undefined` (absent) are the same.
|
|
343
|
+
*/
|
|
344
|
+
function sameValue(a, b) {
|
|
345
|
+
return stableStringify(comparable(a)) === stableStringify(comparable(b));
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* JSON with object keys sorted and `undefined` properties dropped, so equal
|
|
349
|
+
* values always produce equal bytes.
|
|
350
|
+
*/
|
|
351
|
+
function stableStringify(value) {
|
|
352
|
+
if (value === void 0) return "undefined";
|
|
353
|
+
return JSON.stringify(sortKeys(value));
|
|
354
|
+
}
|
|
355
|
+
function sortKeys(value) {
|
|
356
|
+
if (Array.isArray(value)) return value.map(sortKeys);
|
|
357
|
+
if (!value || typeof value !== "object") return value;
|
|
358
|
+
return Object.fromEntries(Object.keys(value).sort().filter((k) => value[k] !== void 0).map((k) => [k, sortKeys(value[k])]));
|
|
359
|
+
}
|
|
360
|
+
/** `value` without any `displayValue`: it is re-derived from source on every parse. */
|
|
361
|
+
function withoutDisplayValues(value) {
|
|
362
|
+
if (Array.isArray(value)) return value.map(withoutDisplayValues);
|
|
363
|
+
if (!value || typeof value !== "object") return value;
|
|
364
|
+
const node = value;
|
|
365
|
+
return Object.fromEntries(Object.entries(node).filter(([k, v]) => v !== void 0 && !(k === "displayValue" && "kind" in node)).map(([k, v]) => [k, withoutDisplayValues(v)]));
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* `updates` without the fields `values` already has — what
|
|
369
|
+
* {@link canonicalizeUpdates} does against a prompt, done against the field
|
|
370
|
+
* values a variation recorded instead.
|
|
371
|
+
*/
|
|
372
|
+
function withoutUnchanged(values, updates) {
|
|
373
|
+
let result = emptyUpdates(updates.style);
|
|
374
|
+
for (const [field, value] of updateFields(updates)) {
|
|
375
|
+
if (sameValue(values[field], value)) continue;
|
|
376
|
+
result = withField(result, field, withoutDisplayValues(value));
|
|
377
|
+
}
|
|
378
|
+
return result;
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* The one spelling of `updates` against `base`:
|
|
382
|
+
*
|
|
383
|
+
* - **Minimized against the base.** A field equal to the base's value is
|
|
384
|
+
* dropped, so edit-then-undo leaves nothing.
|
|
385
|
+
* - **Stripped of display-only detail** (`displayValue`), which the next
|
|
386
|
+
* parse re-derives anyway.
|
|
387
|
+
*
|
|
388
|
+
* Serialize the result with {@link serializeUpdates} for sorted keys and no
|
|
389
|
+
* insignificant whitespace. Updates of another style than `base`'s are
|
|
390
|
+
* returned unminimized: none of their fields line up with the base's.
|
|
391
|
+
*/
|
|
392
|
+
function canonicalizeUpdates(base, updates) {
|
|
393
|
+
let result = emptyUpdates(updates.style);
|
|
394
|
+
for (const [field, value] of updateFields(updates)) {
|
|
395
|
+
if (base.style === updates.style && sameValue(promptFieldValue(base, field), value)) continue;
|
|
396
|
+
result = withField(result, field, withoutDisplayValues(value));
|
|
397
|
+
}
|
|
398
|
+
return result;
|
|
399
|
+
}
|
|
400
|
+
/** The canonical bytes of a variation's base values — stored and deduped on beside its updates. */
|
|
401
|
+
function serializeFieldValues(values) {
|
|
402
|
+
return stableStringify(withoutDisplayValues(values));
|
|
403
|
+
}
|
|
404
|
+
/** The canonical bytes of `updates` — what a variation row stores and dedupes on. */
|
|
405
|
+
function serializeUpdates(updates) {
|
|
406
|
+
return stableStringify(updates);
|
|
407
|
+
}
|
|
408
|
+
//#endregion
|
|
409
|
+
//#region src/prompt/variations/rebase.ts
|
|
410
|
+
/** The pseudo-field a conflict names when the prompt itself is gone. */
|
|
411
|
+
const PROMPT_FIELD = "prompt";
|
|
412
|
+
/**
|
|
413
|
+
* Re-expresses a variation's `updates` against `target`. Each field the
|
|
414
|
+
* updates set compares three values — the base's being the one the variation
|
|
415
|
+
* recorded overwriting (`baseValues`), so no copy of the base is needed:
|
|
416
|
+
*
|
|
417
|
+
* | `T[f]` vs `B[f]` | `T[f]` vs `V[f]` | result |
|
|
418
|
+
* | --- | --- | --- |
|
|
419
|
+
* | equal | — | take `V[f]` (only the variation changed it) |
|
|
420
|
+
* | differs | equal | drop `f` (both made the same change) |
|
|
421
|
+
* | differs | differs | conflict |
|
|
422
|
+
*
|
|
423
|
+
* A `target` of `undefined` — the prompt doesn't exist there — conflicts on
|
|
424
|
+
* the pseudo-field {@link PROMPT_FIELD}, as does one whose style changed.
|
|
425
|
+
*/
|
|
426
|
+
function rebaseUpdates({ promptId, baseValues, updates }, target) {
|
|
427
|
+
if (!target || target.style !== updates.style) return {
|
|
428
|
+
ok: false,
|
|
429
|
+
updates: emptyUpdates(updates.style),
|
|
430
|
+
conflicts: [{
|
|
431
|
+
field: PROMPT_FIELD,
|
|
432
|
+
base: promptId,
|
|
433
|
+
target: target ? `${target.id} (${target.style})` : null,
|
|
434
|
+
variation: promptId
|
|
435
|
+
}]
|
|
436
|
+
};
|
|
437
|
+
let kept = emptyUpdates(updates.style);
|
|
438
|
+
const conflicts = [];
|
|
439
|
+
for (const [field, value] of updateFields(updates)) {
|
|
440
|
+
const b = baseValues[field];
|
|
441
|
+
const t = promptFieldValue(target, field);
|
|
442
|
+
if (sameValue(t, b)) kept = withField(kept, field, value);
|
|
443
|
+
else if (!sameValue(t, value)) conflicts.push({
|
|
444
|
+
field,
|
|
445
|
+
base: b,
|
|
446
|
+
target: t,
|
|
447
|
+
variation: value
|
|
58
448
|
});
|
|
59
|
-
|
|
60
|
-
|
|
449
|
+
}
|
|
450
|
+
const merged = canonicalizeUpdates(target, kept);
|
|
451
|
+
return conflicts.length > 0 ? {
|
|
452
|
+
ok: false,
|
|
453
|
+
updates: merged,
|
|
454
|
+
conflicts
|
|
455
|
+
} : {
|
|
456
|
+
ok: true,
|
|
457
|
+
updates: merged
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Brings `incoming` into `existing`, both already against `target`: fields
|
|
462
|
+
* only one side sets go through, and a field both set differently conflicts,
|
|
463
|
+
* with the existing side as the conflict's `target`.
|
|
464
|
+
*/
|
|
465
|
+
function mergeIntoWip(target, existing, incoming) {
|
|
466
|
+
const existingFields = new Map(updateFields(existing));
|
|
467
|
+
let merged = existing;
|
|
468
|
+
const conflicts = [];
|
|
469
|
+
for (const [field, value] of updateFields(incoming)) {
|
|
470
|
+
if (!existingFields.has(field)) {
|
|
471
|
+
merged = withField(merged, field, value);
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
const mine = existingFields.get(field);
|
|
475
|
+
if (sameValue(mine, value)) continue;
|
|
476
|
+
conflicts.push({
|
|
477
|
+
field,
|
|
478
|
+
base: promptFieldValue(target, field),
|
|
479
|
+
target: mine,
|
|
480
|
+
variation: value
|
|
61
481
|
});
|
|
62
|
-
|
|
63
|
-
|
|
482
|
+
}
|
|
483
|
+
const updates = canonicalizeUpdates(target, merged);
|
|
484
|
+
return conflicts.length > 0 ? {
|
|
485
|
+
ok: false,
|
|
486
|
+
updates,
|
|
487
|
+
conflicts
|
|
488
|
+
} : {
|
|
489
|
+
ok: true,
|
|
490
|
+
updates
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Settles `pending` with a choice per conflicted field, producing the updates
|
|
495
|
+
* the WIP holds from then on, against `pending.targetValues`. Keeping the
|
|
496
|
+
* working tree's value on a rebase conflict leaves nothing to apply, which
|
|
497
|
+
* the canonicalization drops.
|
|
498
|
+
*
|
|
499
|
+
* @throws When a conflicted field has no choice, or the conflict is on the
|
|
500
|
+
* prompt itself, which no choice resolves.
|
|
501
|
+
*/
|
|
502
|
+
function resolveConflicts(pending, choices) {
|
|
503
|
+
let updates = pending.updates;
|
|
504
|
+
for (const conflict of pending.conflicts) {
|
|
505
|
+
if (conflict.field === "prompt") throw new Error("The prompt no longer exists at the target; discard these edits instead");
|
|
506
|
+
const choice = choices[conflict.field];
|
|
507
|
+
if (choice !== "target" && choice !== "variation") throw new Error(`No choice given for conflicted field '${conflict.field}'`);
|
|
508
|
+
updates = withField(updates, conflict.field, choice === "target" ? conflict.target : conflict.variation);
|
|
509
|
+
}
|
|
510
|
+
return withoutUnchanged(pending.targetValues, updates);
|
|
511
|
+
}
|
|
512
|
+
//#endregion
|
|
513
|
+
//#region src/prompt/file/file-variations.ts
|
|
514
|
+
/** How many parsed versions and materialized variations are kept. */
|
|
515
|
+
const MATERIALIZED_CACHE_SIZE = 64;
|
|
516
|
+
/** Normalize fields only: see {@link FileVariationsHost.normalizeWith}. */
|
|
517
|
+
const FIELDS = { resolveTypes: false };
|
|
518
|
+
/** Labels for the two sides of a conflict an external edit caused. */
|
|
519
|
+
const REBASE_LABELS = {
|
|
520
|
+
target: "working tree",
|
|
521
|
+
variation: "unsaved edits"
|
|
522
|
+
};
|
|
523
|
+
/** A simple bounded map: the oldest entry goes when it's full. */
|
|
524
|
+
var BoundedCache = class {
|
|
525
|
+
map = /* @__PURE__ */ new Map();
|
|
526
|
+
size;
|
|
527
|
+
constructor(size) {
|
|
528
|
+
this.size = size;
|
|
529
|
+
}
|
|
530
|
+
get(key) {
|
|
531
|
+
return this.map.get(key);
|
|
532
|
+
}
|
|
533
|
+
set(key, value) {
|
|
534
|
+
this.map.delete(key);
|
|
535
|
+
this.map.set(key, value);
|
|
536
|
+
if (this.map.size > this.size) this.map.delete(this.map.keys().next().value);
|
|
537
|
+
return value;
|
|
538
|
+
}
|
|
539
|
+
delete(key) {
|
|
540
|
+
this.map.delete(key);
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
/** The public face of a stored variation. */
|
|
544
|
+
function toInfo(v) {
|
|
545
|
+
const { globalId: _, baseValues: _values, ...info } = v;
|
|
546
|
+
return info;
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Versions and variations for a {@link FilePromptProvider}: it reads commits
|
|
550
|
+
* through a {@link VersioningAdapter}, keeps variations in a
|
|
551
|
+
* {@link VariationStore}, and materializes them — parsing and running a
|
|
552
|
+
* variation's patched source — through an {@link OverlayFileProvider}, so
|
|
553
|
+
* nothing but an explicit save ever writes a prompt file.
|
|
554
|
+
*
|
|
555
|
+
* A variation applies to the working tree as it is: the values it recorded
|
|
556
|
+
* overwriting are the base of the three-way merge that carries it across
|
|
557
|
+
* changes made there, so uncommitted changes need no version of their own.
|
|
558
|
+
*
|
|
559
|
+
* See `specs/prompt-versions-and-variations.md` §C–§H.
|
|
560
|
+
*/
|
|
561
|
+
var FileVariations = class {
|
|
562
|
+
/** A file's content at a version. Versions are immutable, so this never goes stale. */
|
|
563
|
+
contents = new BoundedCache(MATERIALIZED_CACHE_SIZE * 4);
|
|
564
|
+
/** Prompts parsed at versions that aren't head. */
|
|
565
|
+
versionPrompts = new BoundedCache(MATERIALIZED_CACHE_SIZE);
|
|
566
|
+
/** Materialized variations, keyed by id and last change. */
|
|
567
|
+
materialized = new BoundedCache(MATERIALIZED_CACHE_SIZE);
|
|
568
|
+
/** Head prompts with their types resolved, by id, with the content they were read from. */
|
|
569
|
+
headTypesCache = /* @__PURE__ */ new Map();
|
|
570
|
+
/** Head prompts' fields alone, by id, with the content they were read from. */
|
|
571
|
+
headFieldsCache = /* @__PURE__ */ new Map();
|
|
572
|
+
/** The one overlay every materialization goes through, one at a time. */
|
|
573
|
+
overlay;
|
|
574
|
+
overlayFileType;
|
|
575
|
+
overlayLock = Promise.resolve();
|
|
576
|
+
/** Tail of the WIP mutation chain per prompt, as `FilePromptProvider.mutateFile`. */
|
|
577
|
+
wipLocks = /* @__PURE__ */ new Map();
|
|
578
|
+
host;
|
|
579
|
+
/** How versions are named; without it (no git), there are no versions. */
|
|
580
|
+
versioning;
|
|
581
|
+
/** Where variations are kept; without one, there are versions but no variations. */
|
|
582
|
+
store;
|
|
583
|
+
constructor(host, versioning, store) {
|
|
584
|
+
this.host = host;
|
|
585
|
+
this.versioning = versioning;
|
|
586
|
+
this.store = store;
|
|
587
|
+
}
|
|
588
|
+
relativePath(filePath) {
|
|
589
|
+
return path.relative(this.host.rootDir, filePath).split(path.sep).join("/");
|
|
590
|
+
}
|
|
591
|
+
relativePathOf(promptId) {
|
|
592
|
+
return this.relativePath(this.host.parsePromptId(promptId)[0]);
|
|
593
|
+
}
|
|
594
|
+
/** `filePath`'s content at `version`, or `undefined` if it didn't exist there. */
|
|
595
|
+
contentAt(version, filePath) {
|
|
596
|
+
if (!this.versioning) return Promise.resolve(void 0);
|
|
597
|
+
const rel = this.relativePath(filePath);
|
|
598
|
+
const key = `${version}\0${rel}`;
|
|
599
|
+
const cached = this.contents.get(key);
|
|
600
|
+
if (cached) return cached;
|
|
601
|
+
const read = this.versioning.readFile(version, rel);
|
|
602
|
+
read.catch(() => this.contents.delete(key));
|
|
603
|
+
return this.contents.set(key, read);
|
|
604
|
+
}
|
|
605
|
+
async diskContent(filePath) {
|
|
606
|
+
return this.host.fileProvider.readFile(filePath).catch(() => void 0);
|
|
607
|
+
}
|
|
608
|
+
/** Whether `filePath` at `version` is what's on disk now. */
|
|
609
|
+
async isHeadContent(version, filePath) {
|
|
610
|
+
const [atVersion, onDisk] = await Promise.all([this.contentAt(version, filePath), this.diskContent(filePath)]);
|
|
611
|
+
return atVersion !== void 0 && atVersion === onDisk;
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* The commit a variation made against the working tree now is based on:
|
|
615
|
+
* the one checked out, when the prompt's file has nothing uncommitted — so
|
|
616
|
+
* that the commit plus the variation reproduces what was seen. Otherwise,
|
|
617
|
+
* none.
|
|
618
|
+
*/
|
|
619
|
+
async baseFor(filePath, head) {
|
|
620
|
+
head ??= await this.versioning?.head();
|
|
621
|
+
const commit = head?.commit?.id;
|
|
622
|
+
if (!commit) return void 0;
|
|
623
|
+
return head.clean || await this.isHeadContent(commit, filePath) ? commit : void 0;
|
|
624
|
+
}
|
|
625
|
+
/** Forgets memoized state that something on disk may have changed. */
|
|
626
|
+
invalidate() {
|
|
627
|
+
this.headTypesCache.clear();
|
|
628
|
+
}
|
|
629
|
+
requireVersioning() {
|
|
630
|
+
if (!this.versioning) throw new Error("Prompt versions are unavailable");
|
|
631
|
+
return this.versioning;
|
|
632
|
+
}
|
|
633
|
+
requireStore() {
|
|
634
|
+
if (!this.store) throw new Error("This prompt provider has no variation store");
|
|
635
|
+
return this.store;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Runs `use` with the overlay holding `content` at `filePath`, one at a
|
|
639
|
+
* time: the overlay is shared, so two materializations must not interleave.
|
|
640
|
+
*/
|
|
641
|
+
withOverlay(filePath, content, use) {
|
|
642
|
+
const run = async () => {
|
|
643
|
+
if (!this.overlay) {
|
|
644
|
+
if (!this.host.fileType.withFileProvider) throw new Error("This prompt file type can't show or run variations: it has no `withFileProvider`");
|
|
645
|
+
this.overlay = new OverlayFileProvider(this.host.fileProvider);
|
|
646
|
+
this.overlayFileType = this.host.fileType.withFileProvider(this.overlay);
|
|
647
|
+
}
|
|
648
|
+
this.overlay.set(filePath, content);
|
|
649
|
+
try {
|
|
650
|
+
return await use(this.overlayFileType, this.overlay);
|
|
651
|
+
} finally {
|
|
652
|
+
this.overlay.clear();
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
const result = this.overlayLock.then(run, run);
|
|
656
|
+
this.overlayLock = result.catch(() => {});
|
|
657
|
+
return result;
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* The prompt `promptId` as it was at `version`, unannotated, or `undefined`
|
|
661
|
+
* when it didn't exist there. Parsed through the overlay unless the file is
|
|
662
|
+
* unchanged since, in which case head's own parse is it.
|
|
663
|
+
*
|
|
664
|
+
* Fields only — no execute parameters or input sources: merging needs only
|
|
665
|
+
* the fields, and an old version can't run, so resolving its types (most
|
|
666
|
+
* of what a read costs) would buy nothing.
|
|
667
|
+
*/
|
|
668
|
+
async promptAtVersion(version, promptId) {
|
|
669
|
+
const [filePath, name] = this.host.parsePromptId(promptId);
|
|
670
|
+
const content = await this.contentAt(version, filePath);
|
|
671
|
+
if (content === void 0) return void 0;
|
|
672
|
+
if (content === await this.diskContent(filePath)) return this.headFields(promptId);
|
|
673
|
+
const key = `${version}\0${promptId}`;
|
|
674
|
+
const cached = this.versionPrompts.get(key);
|
|
675
|
+
if (cached) return cached;
|
|
676
|
+
const parsed = this.withOverlay(filePath, content, async (fileType) => (await this.host.normalizeWith(fileType, [filePath], FIELDS)).find((p) => p.name === name));
|
|
677
|
+
parsed.catch(() => this.versionPrompts.delete(key));
|
|
678
|
+
return this.versionPrompts.set(key, parsed);
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* A variation's source — its base commit's content, or the working tree's
|
|
682
|
+
* when it has none, with its updates applied through the ordinary edit
|
|
683
|
+
* pipeline — and the prompt it parses to, fields only. See
|
|
684
|
+
* {@link withHeadTypes} for the rest.
|
|
685
|
+
*/
|
|
686
|
+
async materialize(v) {
|
|
687
|
+
const [filePath, name] = this.host.parsePromptId(v.promptId);
|
|
688
|
+
const content = v.base !== void 0 ? await this.contentAt(v.base, filePath) : await this.diskContent(filePath);
|
|
689
|
+
if (content === void 0) throw new Error(`Can't read ${this.relativePath(filePath)}` + (v.base !== void 0 ? ` at version ${v.base}` : ""));
|
|
690
|
+
const key = `${v.id}\0${v.updatedAt}\0${v.base ?? createHash("sha1").update(content).digest("hex")}`;
|
|
691
|
+
const cached = this.materialized.get(key);
|
|
692
|
+
if (cached) return cached;
|
|
693
|
+
const result = this.withOverlay(filePath, content, async (fileType, overlay) => {
|
|
694
|
+
if (!isEmptyUpdates(v.updates)) await this.host.applyUpdates(fileType, filePath, name, v.promptId, v.updates);
|
|
695
|
+
const prompt = (await this.host.normalizeWith(fileType, [filePath], FIELDS)).find((p) => p.name === name);
|
|
696
|
+
if (!prompt) throw new Error("Prompt not found");
|
|
697
|
+
return {
|
|
698
|
+
source: overlay.get(filePath) ?? content,
|
|
699
|
+
prompt
|
|
700
|
+
};
|
|
64
701
|
});
|
|
65
|
-
|
|
66
|
-
|
|
702
|
+
result.catch(() => this.materialized.delete(key));
|
|
703
|
+
return this.materialized.set(key, result);
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Loads a variation's config for running: imports its patched source as
|
|
707
|
+
* though it were the real file, so its imports resolve against head's code.
|
|
708
|
+
*/
|
|
709
|
+
async loadConfig(v, params) {
|
|
710
|
+
const { source } = await this.materialize(v);
|
|
711
|
+
const [filePath, name] = this.host.parsePromptId(v.promptId);
|
|
712
|
+
return this.withOverlay(filePath, source, (fileType) => fileType.loadConfig(filePath, name, params));
|
|
713
|
+
}
|
|
714
|
+
/** Adds what the client needs to know about head to a head prompt. */
|
|
715
|
+
annotateHead(prompt, wip) {
|
|
716
|
+
return {
|
|
717
|
+
...prompt,
|
|
718
|
+
ref: { promptId: prompt.id },
|
|
719
|
+
atHead: true,
|
|
720
|
+
...wip && {
|
|
721
|
+
dirty: true,
|
|
722
|
+
wipId: wip.id
|
|
723
|
+
}
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
/** Annotates every head prompt with whether it has unsaved edits. */
|
|
727
|
+
async annotateAll(prompts) {
|
|
728
|
+
const wips = new Map((await this.store?.listHeadWips() ?? []).map((w) => [w.promptId, w]));
|
|
729
|
+
return prompts.map((p) => this.annotateHead(p, wips.get(p.id)));
|
|
730
|
+
}
|
|
731
|
+
/** The head prompt, annotated, with any unsaved edits rebased first. */
|
|
732
|
+
async headPrompt(promptId) {
|
|
733
|
+
const wip = await this.withWipLock(promptId, () => this.currentHeadWip(promptId));
|
|
734
|
+
const prompt = await this.headTypes(promptId);
|
|
735
|
+
return prompt ? this.annotateHead(prompt, wip) : null;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* The head prompt, fully normalized — its types resolved — and kept until
|
|
739
|
+
* its file or a playground module changes, so the variations on head can
|
|
740
|
+
* borrow its types instead of resolving their own (see
|
|
741
|
+
* {@link withHeadTypes}).
|
|
742
|
+
*/
|
|
743
|
+
async headTypes(promptId) {
|
|
744
|
+
const [filePath, name] = this.host.parsePromptId(promptId);
|
|
745
|
+
const content = await this.diskContent(filePath);
|
|
746
|
+
const cached = this.headTypesCache.get(promptId);
|
|
747
|
+
if (cached && cached.content === content) return cached.prompt;
|
|
748
|
+
const prompt = (await this.host.normalizeWith(this.host.fileType, [filePath]).catch(() => [])).find((p) => p.name === name);
|
|
749
|
+
if (prompt && content !== void 0) this.headTypesCache.set(promptId, {
|
|
750
|
+
content,
|
|
751
|
+
prompt
|
|
67
752
|
});
|
|
68
|
-
return
|
|
69
|
-
|
|
753
|
+
return prompt;
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* The head prompt's fields, parsed without resolving types and kept until
|
|
757
|
+
* its file changes — what unsaved edits are merged against.
|
|
758
|
+
*/
|
|
759
|
+
async headFields(promptId) {
|
|
760
|
+
const [filePath, name] = this.host.parsePromptId(promptId);
|
|
761
|
+
const content = await this.diskContent(filePath);
|
|
762
|
+
if (content === void 0) return void 0;
|
|
763
|
+
const typed = this.headTypesCache.get(promptId);
|
|
764
|
+
if (typed?.content === content) return typed.prompt;
|
|
765
|
+
const cached = this.headFieldsCache.get(promptId);
|
|
766
|
+
if (cached?.content === content) return cached.prompt;
|
|
767
|
+
const prompt = (await this.host.normalizeWith(this.host.fileType, [filePath], FIELDS).catch(() => [])).find((p) => p.name === name);
|
|
768
|
+
this.headFieldsCache.set(promptId, {
|
|
769
|
+
content,
|
|
770
|
+
prompt
|
|
771
|
+
});
|
|
772
|
+
return prompt;
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* `prompt` — a variation on head, parsed fields-only — with head's resolved
|
|
776
|
+
* types: its execute parameters, input sources and layout. A variation
|
|
777
|
+
* changes only fields (model, system, messages, parameters), none of which
|
|
778
|
+
* those are derived from, so head's answers are its answers — without the
|
|
779
|
+
* program build that re-deriving them would cost on every edit.
|
|
780
|
+
*/
|
|
781
|
+
async withHeadTypes(prompt) {
|
|
782
|
+
const head = await this.headTypes(prompt.id);
|
|
783
|
+
if (!head) return prompt;
|
|
784
|
+
const { executeParameters, inputSources, inputLayout } = head;
|
|
785
|
+
return {
|
|
786
|
+
...prompt,
|
|
787
|
+
...executeParameters && { executeParameters },
|
|
788
|
+
...inputSources && { inputSources },
|
|
789
|
+
...inputLayout && { inputLayout }
|
|
70
790
|
};
|
|
71
791
|
}
|
|
792
|
+
/** The prompt `ref` names. */
|
|
793
|
+
async getPrompt(ref) {
|
|
794
|
+
const r = toPromptRef(ref);
|
|
795
|
+
if (r.variation !== void 0) return this.variationPrompt(r.variation);
|
|
796
|
+
if (r.version !== void 0) return this.versionPrompt(r.promptId, r.version);
|
|
797
|
+
return this.headPrompt(r.promptId);
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* The prompt at `version`. When that's what's on disk now, it's head — so
|
|
801
|
+
* opening a trace just run lands somewhere editable.
|
|
802
|
+
*/
|
|
803
|
+
async versionPrompt(promptId, version) {
|
|
804
|
+
const [filePath] = this.host.parsePromptId(promptId);
|
|
805
|
+
if (await this.isHeadContent(version, filePath)) return this.headPrompt(promptId);
|
|
806
|
+
const [prompt, info, wip] = await Promise.all([
|
|
807
|
+
this.promptAtVersion(version, promptId).catch(() => void 0),
|
|
808
|
+
this.versioning?.get(version),
|
|
809
|
+
this.store?.getHeadWip(promptId)
|
|
810
|
+
]);
|
|
811
|
+
if (!prompt) return null;
|
|
812
|
+
return {
|
|
813
|
+
...prompt,
|
|
814
|
+
ref: {
|
|
815
|
+
promptId,
|
|
816
|
+
version
|
|
817
|
+
},
|
|
818
|
+
...info && { version: info },
|
|
819
|
+
atHead: false,
|
|
820
|
+
...wip && {
|
|
821
|
+
dirty: true,
|
|
822
|
+
wipId: wip.id
|
|
823
|
+
}
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
async variationPrompt(id) {
|
|
827
|
+
let v = await this.store?.get(id);
|
|
828
|
+
if (!v) return null;
|
|
829
|
+
if (v.wip && v.onHead) {
|
|
830
|
+
const promptId = v.promptId;
|
|
831
|
+
const current = await this.withWipLock(promptId, () => this.currentHeadWip(promptId));
|
|
832
|
+
if (current?.id !== id) return this.headPrompt(promptId);
|
|
833
|
+
v = current;
|
|
834
|
+
}
|
|
835
|
+
const [filePath] = this.host.parsePromptId(v.promptId);
|
|
836
|
+
const [{ prompt }, info, atHead, wip] = await Promise.all([
|
|
837
|
+
this.materialize(v),
|
|
838
|
+
v.base !== void 0 ? this.versioning?.get(v.base) : void 0,
|
|
839
|
+
v.base === void 0 || this.isHeadContent(v.base, filePath),
|
|
840
|
+
v.wip && v.onHead ? Promise.resolve(v) : this.store?.getHeadWip(v.promptId)
|
|
841
|
+
]);
|
|
842
|
+
return {
|
|
843
|
+
...atHead ? await this.withHeadTypes(prompt) : prompt,
|
|
844
|
+
ref: {
|
|
845
|
+
promptId: v.promptId,
|
|
846
|
+
variation: id
|
|
847
|
+
},
|
|
848
|
+
...info && { version: info },
|
|
849
|
+
variation: toInfo(v),
|
|
850
|
+
atHead,
|
|
851
|
+
...wip && {
|
|
852
|
+
dirty: true,
|
|
853
|
+
wipId: wip.id
|
|
854
|
+
}
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Runs `fn` once every earlier WIP mutation of `promptId` has settled, so
|
|
859
|
+
* rapid edits, a save and an external-edit rebase never interleave.
|
|
860
|
+
*/
|
|
861
|
+
withWipLock(promptId, fn) {
|
|
862
|
+
const result = (this.wipLocks.get(promptId) ?? Promise.resolve()).then(fn, fn);
|
|
863
|
+
const settled = result.then(() => {}, () => {});
|
|
864
|
+
this.wipLocks.set(promptId, settled);
|
|
865
|
+
settled.then(() => {
|
|
866
|
+
if (this.wipLocks.get(promptId) === settled) this.wipLocks.delete(promptId);
|
|
867
|
+
});
|
|
868
|
+
return result;
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Runs `fn` on variation `id` under its prompt's WIP lock, with the
|
|
872
|
+
* variation as it stands once the lock is held — so acting on it never
|
|
873
|
+
* undoes a mutation queued ahead, like an edit still landing when a save
|
|
874
|
+
* arrives.
|
|
875
|
+
*
|
|
876
|
+
* @param wip - Require a WIP: a frozen variation, or none, is an error.
|
|
877
|
+
*/
|
|
878
|
+
async withVariation(id, fn, { wip = false } = {}) {
|
|
879
|
+
const store = this.requireStore();
|
|
880
|
+
const read = async () => {
|
|
881
|
+
const v = await store.get(id);
|
|
882
|
+
if (!v || wip && !v.wip) throw new Error(`No ${wip ? "WIP " : ""}variation ${id}`);
|
|
883
|
+
return v;
|
|
884
|
+
};
|
|
885
|
+
const { promptId } = await read();
|
|
886
|
+
return this.withWipLock(promptId, async () => fn(await read()));
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* The prompt's head WIP, rebased onto the working tree first if a field it
|
|
890
|
+
* sets changed there since — whether the watcher saw the change or it
|
|
891
|
+
* happened while the server was down. A clean rebase is silent; a
|
|
892
|
+
* conflicted one leaves the WIP with pending conflicts. Call with the WIP
|
|
893
|
+
* lock held.
|
|
894
|
+
*/
|
|
895
|
+
async currentHeadWip(promptId) {
|
|
896
|
+
const wip = await this.store?.getHeadWip(promptId);
|
|
897
|
+
if (!wip) return void 0;
|
|
898
|
+
const [filePath] = this.host.parsePromptId(promptId);
|
|
899
|
+
if (await this.diskContent(filePath) === void 0) return wip;
|
|
900
|
+
const head = await this.headFields(promptId);
|
|
901
|
+
const settledOn = wip.pending?.targetValues ?? wip.baseValues;
|
|
902
|
+
if (head ? head.style === wip.updates.style && hasFieldValues(head, settledOn) : !!wip.pending) return wip;
|
|
903
|
+
const outcome = rebaseUpdates(wip, head);
|
|
904
|
+
const store = this.requireStore();
|
|
905
|
+
if (outcome.ok) {
|
|
906
|
+
if (isEmptyUpdates(outcome.updates)) {
|
|
907
|
+
await store.deleteWip(wip.id);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
return store.updateWip(wip.id, {
|
|
911
|
+
updates: outcome.updates,
|
|
912
|
+
baseValues: fieldValuesOf(head, outcome.updates),
|
|
913
|
+
pending: null
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
return store.updateWip(wip.id, { pending: {
|
|
917
|
+
targetValues: fieldValuesOf(head, wip.updates),
|
|
918
|
+
updates: outcome.updates,
|
|
919
|
+
conflicts: outcome.conflicts,
|
|
920
|
+
labels: REBASE_LABELS
|
|
921
|
+
} });
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* The id of `v`'s prompt at head: its own while its file still exists,
|
|
925
|
+
* else whatever its `prompts()` id has now — a file move.
|
|
926
|
+
*/
|
|
927
|
+
async headPromptId(v) {
|
|
928
|
+
const [filePath] = this.host.parsePromptId(v.promptId);
|
|
929
|
+
if (!v.globalId || await this.diskContent(filePath) !== void 0) return v.promptId;
|
|
930
|
+
return (await this.host.parseAll()).find((p) => p.globalId === v.globalId)?.id ?? v.promptId;
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Re-expresses `v` against `target` — a version, or the working tree when
|
|
934
|
+
* omitted (§F) — finding the prompt there by its id, then (on the working
|
|
935
|
+
* tree) by its `prompts()` id, so a rename doesn't lose it. Also returns
|
|
936
|
+
* the prompt found, which the result's updates apply to.
|
|
937
|
+
*/
|
|
938
|
+
async rebaseOnto(v, target, targetPromptId) {
|
|
939
|
+
const promptId = targetPromptId ?? v.promptId;
|
|
940
|
+
let found = target === void 0 ? await this.headFields(promptId) : await this.promptAtVersion(target, promptId).catch(() => void 0);
|
|
941
|
+
if (!found && v.globalId && target === void 0) found = (await this.host.parseAll()).find((p) => p.globalId === v.globalId);
|
|
942
|
+
return {
|
|
943
|
+
...rebaseUpdates(v, found),
|
|
944
|
+
promptId: found?.id ?? v.promptId,
|
|
945
|
+
onto: found
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
/** Updates a prompt at `ref` — see `FilePromptProvider.updatePromptProperties`. */
|
|
949
|
+
async update(ref, updates) {
|
|
950
|
+
const store = this.requireStore();
|
|
951
|
+
const r = toPromptRef(ref);
|
|
952
|
+
const source = r.variation !== void 0 ? await store.get(r.variation) : void 0;
|
|
953
|
+
if (r.variation !== void 0 && !source) throw new Error(`No variation ${r.variation}`);
|
|
954
|
+
if (source && !source.wip) throw new Error("A saved variation can't be edited. Open it on the working tree to edit it.");
|
|
955
|
+
const promptId = source?.promptId ?? r.promptId;
|
|
956
|
+
const [filePath] = this.host.parsePromptId(promptId);
|
|
957
|
+
const landed = await this.withWipLock(promptId, async () => {
|
|
958
|
+
let version;
|
|
959
|
+
let existing;
|
|
960
|
+
const current = source?.wip ? await store.get(source.id) : void 0;
|
|
961
|
+
if (current && !current.onHead) {
|
|
962
|
+
existing = current;
|
|
963
|
+
version = current.base;
|
|
964
|
+
} else if (current) existing = await this.currentHeadWip(promptId);
|
|
965
|
+
else {
|
|
966
|
+
const asked = source ? source.onHead ? void 0 : source.base : r.version;
|
|
967
|
+
if (asked !== void 0 && !await this.isHeadContent(asked, filePath)) {
|
|
968
|
+
version = asked;
|
|
969
|
+
existing = await store.getWip(promptId, asked);
|
|
970
|
+
} else existing = await this.currentHeadWip(promptId);
|
|
971
|
+
}
|
|
972
|
+
if (existing?.pending) throw new VariationConflictError(existing.pending.conflicts);
|
|
973
|
+
const basePrompt = version === void 0 ? await this.headFields(promptId) : await this.promptAtVersion(version, promptId);
|
|
974
|
+
if (!basePrompt) throw new Error("Prompt not found");
|
|
975
|
+
const canonical = canonicalizeUpdates(basePrompt, mergeUpdates(existing?.updates, updates));
|
|
976
|
+
if (isEmptyUpdates(canonical)) {
|
|
977
|
+
if (existing) await store.deleteWip(existing.id);
|
|
978
|
+
return version === void 0 ? { promptId } : {
|
|
979
|
+
promptId,
|
|
980
|
+
version
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
const baseValues = fieldValuesOf(basePrompt, canonical);
|
|
984
|
+
return {
|
|
985
|
+
promptId,
|
|
986
|
+
variation: (existing ? await store.updateWip(existing.id, {
|
|
987
|
+
updates: canonical,
|
|
988
|
+
baseValues
|
|
989
|
+
}) : await store.putWip({
|
|
990
|
+
promptId,
|
|
991
|
+
...basePrompt.globalId && { globalId: basePrompt.globalId },
|
|
992
|
+
...version !== void 0 && { base: version },
|
|
993
|
+
updates: canonical,
|
|
994
|
+
baseValues,
|
|
995
|
+
onHead: version === void 0
|
|
996
|
+
})).id
|
|
997
|
+
};
|
|
998
|
+
});
|
|
999
|
+
this.host.emit({
|
|
1000
|
+
type: "change",
|
|
1001
|
+
promptId,
|
|
1002
|
+
ref: landed
|
|
1003
|
+
});
|
|
1004
|
+
const prompt = await this.getPrompt(landed);
|
|
1005
|
+
if (!prompt) throw new Error("Prompt not found");
|
|
1006
|
+
return {
|
|
1007
|
+
prompt,
|
|
1008
|
+
ref: landed
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* What running `ref` runs: the working tree — with the commit checked out,
|
|
1013
|
+
* which the run records as its version when nothing is uncommitted — and
|
|
1014
|
+
* the variation applied to it, if any: carried onto the working tree and
|
|
1015
|
+
* frozen, so every trace points at an immutable variation, and running
|
|
1016
|
+
* unchanged edits twice reuses one.
|
|
1017
|
+
*
|
|
1018
|
+
* @throws {@link VariationConflictError} when the variation can't be applied
|
|
1019
|
+
* to the working tree without choosing between two changes.
|
|
1020
|
+
*/
|
|
1021
|
+
async prepareRun(ref) {
|
|
1022
|
+
const [filePath] = this.host.parsePromptId(ref.promptId);
|
|
1023
|
+
const head = await this.versioning?.head();
|
|
1024
|
+
if (ref.variation === void 0) {
|
|
1025
|
+
if (ref.version !== void 0 && !await this.isHeadContent(ref.version, filePath)) throw new Error("Running is only available on the working tree. Open this version on the working tree to run it.");
|
|
1026
|
+
return { head };
|
|
1027
|
+
}
|
|
1028
|
+
const store = this.requireStore();
|
|
1029
|
+
const v = await store.get(ref.variation);
|
|
1030
|
+
if (!v) throw new Error(`No variation ${ref.variation}`);
|
|
1031
|
+
if (v.pending) throw new VariationConflictError(v.pending.conflicts);
|
|
1032
|
+
const outcome = await this.rebaseOnto(v, void 0, await this.headPromptId(v));
|
|
1033
|
+
if (!outcome.ok) throw new VariationConflictError(outcome.conflicts);
|
|
1034
|
+
if (isEmptyUpdates(outcome.updates)) return { head };
|
|
1035
|
+
const [runPath] = this.host.parsePromptId(outcome.promptId);
|
|
1036
|
+
const base = await this.baseFor(runPath, head);
|
|
1037
|
+
return {
|
|
1038
|
+
head,
|
|
1039
|
+
variation: await store.intern({
|
|
1040
|
+
promptId: outcome.promptId,
|
|
1041
|
+
globalId: v.globalId,
|
|
1042
|
+
...base !== void 0 && { base },
|
|
1043
|
+
updates: outcome.updates,
|
|
1044
|
+
baseValues: fieldValuesOf(outcome.onto, outcome.updates)
|
|
1045
|
+
})
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
/** The prompt a prepared run will run — for recording its parameters. */
|
|
1049
|
+
async preparedPrompt(variation) {
|
|
1050
|
+
return this.withHeadTypes((await this.materialize(variation)).prompt);
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Called when prompt files changed on disk: rebases their head WIPs (see
|
|
1054
|
+
* {@link currentHeadWip}) and tells watchers about any WIP that moved.
|
|
1055
|
+
*/
|
|
1056
|
+
async onPromptsChanged(promptIds) {
|
|
1057
|
+
this.invalidate();
|
|
1058
|
+
if (!this.store) return;
|
|
1059
|
+
for (const promptId of promptIds) {
|
|
1060
|
+
const before = await this.store.getHeadWip(promptId);
|
|
1061
|
+
if (!before) continue;
|
|
1062
|
+
const after = await this.withWipLock(promptId, () => this.currentHeadWip(promptId));
|
|
1063
|
+
if (after?.updatedAt !== before.updatedAt) this.host.emit({
|
|
1064
|
+
type: "change",
|
|
1065
|
+
promptId,
|
|
1066
|
+
ref: after ? {
|
|
1067
|
+
promptId,
|
|
1068
|
+
variation: after.id
|
|
1069
|
+
} : { promptId }
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Moves a prompt's head WIP along with a rename: rebased onto the renamed
|
|
1075
|
+
* prompt at head, under its new id.
|
|
1076
|
+
*/
|
|
1077
|
+
async onPromptRenamed(oldId, newId) {
|
|
1078
|
+
const store = this.store;
|
|
1079
|
+
if (!store) return;
|
|
1080
|
+
this.invalidate();
|
|
1081
|
+
await this.withWipLock(oldId, async () => {
|
|
1082
|
+
const wip = await store.getHeadWip(oldId);
|
|
1083
|
+
if (!wip) return;
|
|
1084
|
+
const outcome = await this.rebaseOnto(wip, void 0, newId);
|
|
1085
|
+
await store.deleteWip(wip.id);
|
|
1086
|
+
if (outcome.ok && isEmptyUpdates(outcome.updates)) return;
|
|
1087
|
+
const moved = await store.putWip({
|
|
1088
|
+
promptId: newId,
|
|
1089
|
+
...wip.globalId && { globalId: wip.globalId },
|
|
1090
|
+
updates: outcome.ok ? outcome.updates : wip.updates,
|
|
1091
|
+
baseValues: outcome.ok ? fieldValuesOf(outcome.onto, outcome.updates) : wip.baseValues,
|
|
1092
|
+
onHead: true
|
|
1093
|
+
});
|
|
1094
|
+
if (!outcome.ok) await store.updateWip(moved.id, { pending: {
|
|
1095
|
+
targetValues: fieldValuesOf(outcome.onto, wip.updates),
|
|
1096
|
+
updates: outcome.updates,
|
|
1097
|
+
conflicts: outcome.conflicts,
|
|
1098
|
+
labels: REBASE_LABELS
|
|
1099
|
+
} });
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Brings a variation into the prompt's head WIP (§G): rebases it onto the
|
|
1104
|
+
* working tree, then merges it into the WIP field by field.
|
|
1105
|
+
*
|
|
1106
|
+
* Changes nothing when a field conflicts, unless `options` says how to
|
|
1107
|
+
* settle it: the conflicts come back, labelled, for the caller to choose —
|
|
1108
|
+
* throw the unsaved edits away (`replace`), pick a side per field
|
|
1109
|
+
* (`choices`), or leave everything as it was.
|
|
1110
|
+
*
|
|
1111
|
+
* @param build - The variation to bring.
|
|
1112
|
+
*/
|
|
1113
|
+
openOnHeadFrom(promptId, { label, originName }, build, { choices, replace } = {}) {
|
|
1114
|
+
const store = this.requireStore();
|
|
1115
|
+
const settles = (conflicts) => !!choices && conflicts.every((c) => choices[c.field]);
|
|
1116
|
+
return this.withWipLock(promptId, async () => {
|
|
1117
|
+
let wip = await this.currentHeadWip(promptId);
|
|
1118
|
+
if (wip && replace) {
|
|
1119
|
+
await store.deleteWip(wip.id);
|
|
1120
|
+
wip = void 0;
|
|
1121
|
+
}
|
|
1122
|
+
if (wip?.pending) return {
|
|
1123
|
+
ok: false,
|
|
1124
|
+
conflicts: wip.pending.conflicts,
|
|
1125
|
+
labels: wip.pending.labels,
|
|
1126
|
+
promptId
|
|
1127
|
+
};
|
|
1128
|
+
const x = await build();
|
|
1129
|
+
const rebased = await this.rebaseOnto(x, void 0, promptId);
|
|
1130
|
+
const head = rebased.onto;
|
|
1131
|
+
let incoming = rebased.updates;
|
|
1132
|
+
if (!rebased.ok) {
|
|
1133
|
+
const labels = {
|
|
1134
|
+
target: "working tree",
|
|
1135
|
+
variation: label
|
|
1136
|
+
};
|
|
1137
|
+
if (!settles(rebased.conflicts)) return {
|
|
1138
|
+
ok: false,
|
|
1139
|
+
conflicts: rebased.conflicts,
|
|
1140
|
+
labels,
|
|
1141
|
+
promptId: rebased.promptId
|
|
1142
|
+
};
|
|
1143
|
+
incoming = resolveConflicts({
|
|
1144
|
+
targetValues: fieldValuesOf(head, x.updates),
|
|
1145
|
+
updates: rebased.updates,
|
|
1146
|
+
conflicts: rebased.conflicts,
|
|
1147
|
+
labels
|
|
1148
|
+
}, choices);
|
|
1149
|
+
}
|
|
1150
|
+
if (!wip) {
|
|
1151
|
+
const { base: _, ...unbased } = x;
|
|
1152
|
+
if (isEmptyUpdates(incoming)) return {
|
|
1153
|
+
ok: true,
|
|
1154
|
+
variation: toInfo({
|
|
1155
|
+
...unbased,
|
|
1156
|
+
updates: incoming
|
|
1157
|
+
}),
|
|
1158
|
+
promptId: rebased.promptId
|
|
1159
|
+
};
|
|
1160
|
+
return {
|
|
1161
|
+
ok: true,
|
|
1162
|
+
variation: toInfo(await store.putWip({
|
|
1163
|
+
promptId: rebased.promptId,
|
|
1164
|
+
...x.globalId && { globalId: x.globalId },
|
|
1165
|
+
updates: incoming,
|
|
1166
|
+
baseValues: fieldValuesOf(head, incoming),
|
|
1167
|
+
onHead: true,
|
|
1168
|
+
...originName && { originName }
|
|
1169
|
+
})),
|
|
1170
|
+
promptId: rebased.promptId
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
if (!head) throw new Error("Prompt not found");
|
|
1174
|
+
const merged = mergeIntoWip(head, wip.updates, incoming);
|
|
1175
|
+
let updates = merged.updates;
|
|
1176
|
+
if (!merged.ok) {
|
|
1177
|
+
const labels = {
|
|
1178
|
+
target: "unsaved edits",
|
|
1179
|
+
variation: label
|
|
1180
|
+
};
|
|
1181
|
+
if (!settles(merged.conflicts)) return {
|
|
1182
|
+
ok: false,
|
|
1183
|
+
conflicts: merged.conflicts,
|
|
1184
|
+
labels,
|
|
1185
|
+
promptId: wip.promptId
|
|
1186
|
+
};
|
|
1187
|
+
updates = resolveConflicts({
|
|
1188
|
+
targetValues: fieldValuesOf(head, mergeUpdates(wip.updates, incoming)),
|
|
1189
|
+
updates: merged.updates,
|
|
1190
|
+
conflicts: merged.conflicts,
|
|
1191
|
+
labels
|
|
1192
|
+
}, choices);
|
|
1193
|
+
}
|
|
1194
|
+
if (isEmptyUpdates(updates)) {
|
|
1195
|
+
await store.deleteWip(wip.id);
|
|
1196
|
+
return {
|
|
1197
|
+
ok: true,
|
|
1198
|
+
variation: toInfo({
|
|
1199
|
+
...wip,
|
|
1200
|
+
updates
|
|
1201
|
+
}),
|
|
1202
|
+
promptId: wip.promptId
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
return {
|
|
1206
|
+
ok: true,
|
|
1207
|
+
variation: toInfo(await store.updateWip(wip.id, {
|
|
1208
|
+
updates,
|
|
1209
|
+
baseValues: fieldValuesOf(head, updates)
|
|
1210
|
+
})),
|
|
1211
|
+
promptId: wip.promptId
|
|
1212
|
+
};
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* The versions that changed `promptId`'s file, newest first, back to where
|
|
1217
|
+
* the prompt was created or renamed: before that, its file holds no prompt
|
|
1218
|
+
* by this name — or someone else's — and there's nothing to open. A version
|
|
1219
|
+
* that can't be read is skipped, not the end: older ones may still open.
|
|
1220
|
+
*/
|
|
1221
|
+
async promptHistory(promptId, { limit, before } = {}) {
|
|
1222
|
+
const all = await this.requireVersioning().history(this.relativePathOf(promptId), before !== void 0 ? { before } : {});
|
|
1223
|
+
const history = [];
|
|
1224
|
+
for (const version of all) {
|
|
1225
|
+
if (limit !== void 0 && history.length >= limit) break;
|
|
1226
|
+
let prompt;
|
|
1227
|
+
try {
|
|
1228
|
+
prompt = await this.promptAtVersion(version.id, promptId);
|
|
1229
|
+
} catch {
|
|
1230
|
+
continue;
|
|
1231
|
+
}
|
|
1232
|
+
if (!prompt) break;
|
|
1233
|
+
history.push(version);
|
|
1234
|
+
}
|
|
1235
|
+
return history;
|
|
1236
|
+
}
|
|
1237
|
+
/** {@link PromptVersions} over this provider's versioning adapter. */
|
|
1238
|
+
versions = {
|
|
1239
|
+
head: () => this.requireVersioning().head(),
|
|
1240
|
+
history: (promptId, options) => this.promptHistory(promptId, options),
|
|
1241
|
+
get: (id) => this.requireVersioning().get(id)
|
|
1242
|
+
};
|
|
1243
|
+
/** {@link PromptVariations} over this provider's variation store. */
|
|
1244
|
+
variations = {
|
|
1245
|
+
get: async (id) => {
|
|
1246
|
+
const v = await this.requireStore().get(id);
|
|
1247
|
+
return v && toInfo(v);
|
|
1248
|
+
},
|
|
1249
|
+
list: async (promptId) => (await this.requireStore().list(promptId)).map(toInfo),
|
|
1250
|
+
name: async (id, name) => {
|
|
1251
|
+
const store = this.requireStore();
|
|
1252
|
+
if (!name.trim()) throw new Error("A variation's name can't be empty");
|
|
1253
|
+
return this.withVariation(id, async (v) => {
|
|
1254
|
+
if (v.pending) throw new VariationConflictError(v.pending.conflicts);
|
|
1255
|
+
let frozen = v;
|
|
1256
|
+
if (v.wip) {
|
|
1257
|
+
const base = v.onHead ? await this.baseFor(this.host.parsePromptId(v.promptId)[0]) : v.base;
|
|
1258
|
+
frozen = await store.intern({
|
|
1259
|
+
promptId: v.promptId,
|
|
1260
|
+
globalId: v.globalId,
|
|
1261
|
+
...base !== void 0 && { base },
|
|
1262
|
+
updates: v.updates,
|
|
1263
|
+
baseValues: v.baseValues
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
await store.name(frozen.id, frozen.promptId, name.trim());
|
|
1267
|
+
if (v.wip && v.originName) await store.updateWip(v.id, { originName: null });
|
|
1268
|
+
this.host.emit({
|
|
1269
|
+
type: "change",
|
|
1270
|
+
promptId: v.promptId
|
|
1271
|
+
});
|
|
1272
|
+
return toInfo(await store.get(frozen.id));
|
|
1273
|
+
});
|
|
1274
|
+
},
|
|
1275
|
+
unname: async (promptId, name) => {
|
|
1276
|
+
await this.requireStore().unname(promptId, name);
|
|
1277
|
+
this.host.emit({
|
|
1278
|
+
type: "change",
|
|
1279
|
+
promptId
|
|
1280
|
+
});
|
|
1281
|
+
},
|
|
1282
|
+
rename: async (promptId, from, to) => {
|
|
1283
|
+
const store = this.requireStore();
|
|
1284
|
+
const name = to.trim();
|
|
1285
|
+
if (!name) throw new Error("A variation's name can't be empty");
|
|
1286
|
+
const id = await store.rename(promptId, from, name);
|
|
1287
|
+
this.host.emit({
|
|
1288
|
+
type: "change",
|
|
1289
|
+
promptId
|
|
1290
|
+
});
|
|
1291
|
+
return toInfo(await store.get(id));
|
|
1292
|
+
},
|
|
1293
|
+
rebase: async (id, onto) => {
|
|
1294
|
+
const store = this.requireStore();
|
|
1295
|
+
const v = await store.get(id);
|
|
1296
|
+
if (!v) throw new Error(`No variation ${id}`);
|
|
1297
|
+
const outcome = await this.rebaseOnto(v, onto, onto === void 0 ? await this.headPromptId(v) : void 0);
|
|
1298
|
+
if (!outcome.ok) return {
|
|
1299
|
+
ok: false,
|
|
1300
|
+
conflicts: outcome.conflicts
|
|
1301
|
+
};
|
|
1302
|
+
const base = onto ?? await this.baseFor(this.host.parsePromptId(outcome.promptId)[0]);
|
|
1303
|
+
return {
|
|
1304
|
+
ok: true,
|
|
1305
|
+
variation: toInfo(await store.intern({
|
|
1306
|
+
promptId: outcome.promptId,
|
|
1307
|
+
globalId: v.globalId,
|
|
1308
|
+
...base !== void 0 && { base },
|
|
1309
|
+
updates: outcome.updates,
|
|
1310
|
+
baseValues: fieldValuesOf(outcome.onto, outcome.updates)
|
|
1311
|
+
}))
|
|
1312
|
+
};
|
|
1313
|
+
},
|
|
1314
|
+
openOnHead: async (id, options) => {
|
|
1315
|
+
const x = await this.requireStore().get(id);
|
|
1316
|
+
if (!x) throw new Error(`No variation ${id}`);
|
|
1317
|
+
if (x.pending) return {
|
|
1318
|
+
ok: false,
|
|
1319
|
+
conflicts: x.pending.conflicts
|
|
1320
|
+
};
|
|
1321
|
+
const label = x.names[0] ?? x.originName ?? "variation";
|
|
1322
|
+
const { promptId, ...outcome } = await this.openOnHeadFrom(await this.headPromptId(x), {
|
|
1323
|
+
label,
|
|
1324
|
+
originName: x.names[0]
|
|
1325
|
+
}, async () => x, options);
|
|
1326
|
+
this.host.emit({
|
|
1327
|
+
type: "change",
|
|
1328
|
+
promptId
|
|
1329
|
+
});
|
|
1330
|
+
return outcome;
|
|
1331
|
+
},
|
|
1332
|
+
openVersionOnHead: async (promptId, version, options) => {
|
|
1333
|
+
const old = await this.promptAtVersion(version, promptId);
|
|
1334
|
+
if (!old) throw new Error(`${promptId} doesn't exist at ${version}`);
|
|
1335
|
+
const { promptId: landedOn, ...outcome } = await this.openOnHeadFrom(promptId, { label: shortId(version) }, async () => {
|
|
1336
|
+
const updates = fieldUpdatesOf(old);
|
|
1337
|
+
return {
|
|
1338
|
+
id: "",
|
|
1339
|
+
promptId,
|
|
1340
|
+
...old.globalId && { globalId: old.globalId },
|
|
1341
|
+
base: version,
|
|
1342
|
+
updates,
|
|
1343
|
+
baseValues: fieldValuesOf(await this.headFields(promptId), updates),
|
|
1344
|
+
wip: false,
|
|
1345
|
+
names: [],
|
|
1346
|
+
createdAt: Date.now(),
|
|
1347
|
+
updatedAt: Date.now()
|
|
1348
|
+
};
|
|
1349
|
+
}, options);
|
|
1350
|
+
this.host.emit({
|
|
1351
|
+
type: "change",
|
|
1352
|
+
promptId: landedOn
|
|
1353
|
+
});
|
|
1354
|
+
return outcome;
|
|
1355
|
+
},
|
|
1356
|
+
save: async (wipId) => {
|
|
1357
|
+
const store = this.requireStore();
|
|
1358
|
+
const { promptId, ...outcome } = await this.withVariation(wipId, async (v) => {
|
|
1359
|
+
if (v.pending) return {
|
|
1360
|
+
ok: false,
|
|
1361
|
+
conflicts: v.pending.conflicts,
|
|
1362
|
+
promptId: v.promptId
|
|
1363
|
+
};
|
|
1364
|
+
const outcome = await this.rebaseOnto(v, void 0, await this.headPromptId(v));
|
|
1365
|
+
if (!outcome.ok) return {
|
|
1366
|
+
ok: false,
|
|
1367
|
+
conflicts: outcome.conflicts,
|
|
1368
|
+
promptId: v.promptId
|
|
1369
|
+
};
|
|
1370
|
+
const { promptId, updates } = outcome;
|
|
1371
|
+
const [filePath, name] = this.host.parsePromptId(promptId);
|
|
1372
|
+
if (!isEmptyUpdates(updates)) await this.host.mutateFile(filePath, () => this.host.applyUpdates(this.host.fileType, filePath, name, promptId, updates));
|
|
1373
|
+
await store.deleteWip(v.id);
|
|
1374
|
+
this.invalidate();
|
|
1375
|
+
return {
|
|
1376
|
+
ok: true,
|
|
1377
|
+
variation: toInfo({
|
|
1378
|
+
...v,
|
|
1379
|
+
updates
|
|
1380
|
+
}),
|
|
1381
|
+
promptId
|
|
1382
|
+
};
|
|
1383
|
+
}, { wip: true });
|
|
1384
|
+
this.host.emit({
|
|
1385
|
+
type: "change",
|
|
1386
|
+
promptId
|
|
1387
|
+
});
|
|
1388
|
+
return outcome;
|
|
1389
|
+
},
|
|
1390
|
+
discard: async (id) => {
|
|
1391
|
+
const store = this.requireStore();
|
|
1392
|
+
const promptId = await this.withVariation(id, async (v) => {
|
|
1393
|
+
if (!v.wip) throw new Error("Only unsaved edits can be discarded");
|
|
1394
|
+
await store.deleteWip(id);
|
|
1395
|
+
return v.promptId;
|
|
1396
|
+
});
|
|
1397
|
+
this.host.emit({
|
|
1398
|
+
type: "change",
|
|
1399
|
+
promptId
|
|
1400
|
+
});
|
|
1401
|
+
},
|
|
1402
|
+
resolve: async (id, choices) => {
|
|
1403
|
+
const store = this.requireStore();
|
|
1404
|
+
const { promptId, ...result } = await this.withVariation(id, async (current) => {
|
|
1405
|
+
const { promptId, pending } = current;
|
|
1406
|
+
if (!pending) return {
|
|
1407
|
+
ok: true,
|
|
1408
|
+
variation: toInfo(current),
|
|
1409
|
+
promptId
|
|
1410
|
+
};
|
|
1411
|
+
const updates = resolveConflicts(pending, choices);
|
|
1412
|
+
if (isEmptyUpdates(updates)) {
|
|
1413
|
+
await store.deleteWip(id);
|
|
1414
|
+
return {
|
|
1415
|
+
ok: true,
|
|
1416
|
+
variation: toInfo({
|
|
1417
|
+
...current,
|
|
1418
|
+
updates
|
|
1419
|
+
}),
|
|
1420
|
+
promptId
|
|
1421
|
+
};
|
|
1422
|
+
}
|
|
1423
|
+
return {
|
|
1424
|
+
ok: true,
|
|
1425
|
+
variation: toInfo(await store.updateWip(id, {
|
|
1426
|
+
updates,
|
|
1427
|
+
baseValues: pickFieldValues(pending.targetValues, updates),
|
|
1428
|
+
pending: null
|
|
1429
|
+
})),
|
|
1430
|
+
promptId
|
|
1431
|
+
};
|
|
1432
|
+
}, { wip: true });
|
|
1433
|
+
this.host.emit({
|
|
1434
|
+
type: "change",
|
|
1435
|
+
promptId,
|
|
1436
|
+
ref: {
|
|
1437
|
+
promptId,
|
|
1438
|
+
variation: id
|
|
1439
|
+
}
|
|
1440
|
+
});
|
|
1441
|
+
return result;
|
|
1442
|
+
}
|
|
1443
|
+
};
|
|
1444
|
+
};
|
|
1445
|
+
//#endregion
|
|
1446
|
+
//#region src/prompt/file/ts/prompt-program.ts
|
|
1447
|
+
const FALLBACK_OPTIONS = {
|
|
1448
|
+
target: ts.ScriptTarget.ESNext,
|
|
1449
|
+
module: ts.ModuleKind.ESNext,
|
|
1450
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
1451
|
+
allowJs: true,
|
|
1452
|
+
skipLibCheck: true,
|
|
1453
|
+
noEmit: true
|
|
72
1454
|
};
|
|
1455
|
+
/** Parsed declaration files that are stable for the lifetime of the process. */
|
|
1456
|
+
const immutableSourceFiles = /* @__PURE__ */ new Map();
|
|
1457
|
+
const TS_LIB_DIR = path.dirname(ts.getDefaultLibFilePath({}));
|
|
1458
|
+
/** Whether `fileName` names a file that will not change while we run. */
|
|
1459
|
+
function isImmutable(fileName) {
|
|
1460
|
+
return fileName.startsWith(TS_LIB_DIR) || fileName.includes("/node_modules/");
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Load the compiler options from the nearest `tsconfig.json` at or above
|
|
1464
|
+
* `fromPath`, so imports that rely on the project's `paths` aliases and
|
|
1465
|
+
* `moduleResolution` settings resolve the way they do for the user's own build.
|
|
1466
|
+
*/
|
|
1467
|
+
function compilerOptionsFor(fromPath) {
|
|
1468
|
+
const configPath = ts.findConfigFile(path.dirname(fromPath), ts.sys.fileExists);
|
|
1469
|
+
if (!configPath) return FALLBACK_OPTIONS;
|
|
1470
|
+
const { config, error } = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
1471
|
+
if (error) return FALLBACK_OPTIONS;
|
|
1472
|
+
return {
|
|
1473
|
+
...ts.parseJsonConfigFileContent(config, ts.sys, path.dirname(configPath)).options,
|
|
1474
|
+
noEmit: true,
|
|
1475
|
+
skipLibCheck: true
|
|
1476
|
+
};
|
|
1477
|
+
}
|
|
1478
|
+
/**
|
|
1479
|
+
* Build a {@link PromptProgram} over `sources`, a map of absolute file path to
|
|
1480
|
+
* that file's current content.
|
|
1481
|
+
*
|
|
1482
|
+
* `sources` is an overlay: those files are used as given (so unsaved edits are
|
|
1483
|
+
* seen), while everything they import is read from disk. Imports therefore
|
|
1484
|
+
* resolve only for files that exist on the real filesystem — with an in-memory
|
|
1485
|
+
* {@link FileProvider} the prompt files themselves still parse, but their
|
|
1486
|
+
* cross-file types stay unresolved and extraction falls back to the syntax
|
|
1487
|
+
* tree.
|
|
1488
|
+
*
|
|
1489
|
+
* @param sources - Prompt files to root the program at, keyed by absolute path.
|
|
1490
|
+
* @param previous - The program from a prior build. Passing it lets TypeScript
|
|
1491
|
+
* reuse source files that have not changed, which keeps re-parsing on watch
|
|
1492
|
+
* events far cheaper than building from scratch.
|
|
1493
|
+
*/
|
|
1494
|
+
function createPromptProgram(sources, previous) {
|
|
1495
|
+
const rootNames = [...sources.keys()];
|
|
1496
|
+
if (rootNames.length === 0) return void 0;
|
|
1497
|
+
const options = compilerOptionsFor(rootNames[0]);
|
|
1498
|
+
const host = ts.createCompilerHost(options, true);
|
|
1499
|
+
const { getSourceFile, readFile, fileExists } = host;
|
|
1500
|
+
host.getSourceFile = (fileName, languageVersion, onError, shouldCreate) => {
|
|
1501
|
+
const overlaid = sources.get(fileName);
|
|
1502
|
+
if (overlaid !== void 0) return ts.createSourceFile(fileName, overlaid, languageVersion, true);
|
|
1503
|
+
const cached = immutableSourceFiles.get(fileName);
|
|
1504
|
+
if (cached) return cached;
|
|
1505
|
+
const parsed = getSourceFile.call(host, fileName, languageVersion, onError, shouldCreate);
|
|
1506
|
+
if (parsed && isImmutable(fileName)) immutableSourceFiles.set(fileName, parsed);
|
|
1507
|
+
return parsed;
|
|
1508
|
+
};
|
|
1509
|
+
host.readFile = (fileName) => sources.get(fileName) ?? readFile.call(host, fileName);
|
|
1510
|
+
host.fileExists = (fileName) => sources.has(fileName) || fileExists.call(host, fileName);
|
|
1511
|
+
const program = ts.createProgram({
|
|
1512
|
+
rootNames,
|
|
1513
|
+
options,
|
|
1514
|
+
host,
|
|
1515
|
+
oldProgram: previous
|
|
1516
|
+
});
|
|
1517
|
+
return {
|
|
1518
|
+
program,
|
|
1519
|
+
typeChecker: program.getTypeChecker(),
|
|
1520
|
+
getSourceFile: (filePath) => program.getSourceFile(filePath)
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
73
1523
|
//#endregion
|
|
74
|
-
//#region src/file-
|
|
1524
|
+
//#region src/prompt/file/ts/slot-matching.ts
|
|
1525
|
+
/** How many properties one slot tree may contribute, as a runaway guard. */
|
|
1526
|
+
const MAX_SLOTS = 500;
|
|
75
1527
|
/**
|
|
76
|
-
*
|
|
1528
|
+
* Type flags a slot never gains anything from being walked past.
|
|
77
1529
|
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
1530
|
+
* The `*Like` flags matter: they also cover a branded primitive spelled as a
|
|
1531
|
+
* template literal (`` `tsk_${string}` ``, the shape the AI SDK infers ids
|
|
1532
|
+
* as) — which otherwise carries the whole `String` interface, so without this
|
|
1533
|
+
* a single branded-id leaf expands into ~50 method slots (`.charAt`,
|
|
1534
|
+
* `.slice`, …) and can burn through {@link MAX_SLOTS} before a sibling
|
|
1535
|
+
* member's own fields are ever reached. Mirrors the constant `ts-proppy`'s
|
|
1536
|
+
* `PropType` extraction is built from, for the same reason `isOpaqueType`
|
|
1537
|
+
* below is: `collectInputSlots` (over `PropDefinition`s built by that same
|
|
1538
|
+
* extraction) never produces a path past a primitive either, and the two
|
|
1539
|
+
* walks have to agree.
|
|
1540
|
+
*/
|
|
1541
|
+
const PRIMITIVE_FLAGS = ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.BigIntLike | ts.TypeFlags.ESSymbolLike | ts.TypeFlags.VoidLike | ts.TypeFlags.Null | ts.TypeFlags.Never | ts.TypeFlags.Any | ts.TypeFlags.Unknown;
|
|
1542
|
+
/**
|
|
1543
|
+
* Collect every slot reachable from `roots`, as dotted path → type.
|
|
84
1544
|
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
1545
|
+
* Mirrors `collectInputSlots`'s walk over `PropDefinition`s: parameters, plus
|
|
1546
|
+
* the object properties nested inside them, to the same {@link MAX_SLOT_DEPTH}
|
|
1547
|
+
* — the two must agree, or this side would offer a source at a path the other
|
|
1548
|
+
* never produces. That agreement is also why this stops at exactly the types
|
|
1549
|
+
* `collectInputSlots` treats as leaves: a primitive (including a branded one,
|
|
1550
|
+
* see {@link PRIMITIVE_FLAGS}), a function, or a type `isOpaqueType` calls
|
|
1551
|
+
* unconstructible (a class-instance handle, an all-method interface) — the
|
|
1552
|
+
* same {@link isOpaqueType} the `PropDefinition` side uses to decide `kind:
|
|
1553
|
+
* 'opaque'` rather than `'object'`. Arrays and unions are not descended into
|
|
1554
|
+
* either: neither has a path that stays meaningful once the value changes
|
|
1555
|
+
* shape, so a saved selection could not name one reliably.
|
|
92
1556
|
*/
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
return
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
this.notifyWatchers(isNew ? "add" : "change", filePath);
|
|
111
|
-
}
|
|
112
|
-
async deleteFile(filePath) {
|
|
113
|
-
this.files.delete(filePath);
|
|
114
|
-
this.notifyWatchers("remove", filePath);
|
|
115
|
-
}
|
|
116
|
-
async import(filePath) {
|
|
117
|
-
const content = this.files.get(filePath);
|
|
118
|
-
if (content === void 0) throw new Error(`File not found: ${filePath}`);
|
|
119
|
-
return import(`data:text/javascript;charset=utf-8,${encodeURIComponent(content)}`);
|
|
120
|
-
}
|
|
121
|
-
async *glob(pattern, options = {}) {
|
|
122
|
-
const { cwd = process.cwd(), ignore = [], absolute = false } = options;
|
|
123
|
-
for (const filePath of this.files.keys()) {
|
|
124
|
-
if (!filePath.startsWith(cwd + path.sep)) continue;
|
|
125
|
-
const relativePath = path.relative(cwd, filePath).replace(/\\/g, "/");
|
|
126
|
-
if (!minimatch(relativePath, pattern)) continue;
|
|
127
|
-
if (ignore.some((p) => minimatch(relativePath, p))) continue;
|
|
128
|
-
yield absolute ? filePath : relativePath;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
watch(patterns, options, callback) {
|
|
132
|
-
const watcher = {
|
|
133
|
-
patterns,
|
|
134
|
-
cwd: options.cwd ?? process.cwd(),
|
|
135
|
-
ignored: options.ignored ?? [],
|
|
136
|
-
callback
|
|
137
|
-
};
|
|
138
|
-
this.watchers.add(watcher);
|
|
139
|
-
return () => {
|
|
140
|
-
this.watchers.delete(watcher);
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
notifyWatchers(eventType, filePath) {
|
|
144
|
-
for (const watcher of this.watchers) {
|
|
145
|
-
const { cwd, patterns, ignored, callback } = watcher;
|
|
146
|
-
if (!filePath.startsWith(cwd + path.sep)) continue;
|
|
147
|
-
const relativePath = path.relative(cwd, filePath).replace(/\\/g, "/");
|
|
148
|
-
if (!patterns.some((p) => minimatch(relativePath, p))) continue;
|
|
149
|
-
if (ignored.some((p) => minimatch(relativePath, p))) continue;
|
|
150
|
-
callback(eventType, relativePath);
|
|
1557
|
+
function collectSlotTypes(roots, typeChecker, location) {
|
|
1558
|
+
const slots = /* @__PURE__ */ new Map();
|
|
1559
|
+
const walk = (prefix, type, depth) => {
|
|
1560
|
+
if (slots.size >= MAX_SLOTS) return;
|
|
1561
|
+
slots.set(prefix, type);
|
|
1562
|
+
if (depth + 1 >= 4) return;
|
|
1563
|
+
if (type.isUnion() || typeChecker.isArrayType(type)) return;
|
|
1564
|
+
if (typeChecker.isTupleType(type)) return;
|
|
1565
|
+
if (type.flags & PRIMITIVE_FLAGS) return;
|
|
1566
|
+
if (type.isIntersection() && type.types.some((t) => t.flags & PRIMITIVE_FLAGS)) return;
|
|
1567
|
+
if (type.getCallSignatures().length > 0) return;
|
|
1568
|
+
const properties = typeChecker.getPropertiesOfType(type);
|
|
1569
|
+
if (isOpaqueType(type, typeChecker, location, properties)) return;
|
|
1570
|
+
for (const property of properties) {
|
|
1571
|
+
const declaration = property.valueDeclaration ?? property.declarations?.[0];
|
|
1572
|
+
const propertyType = typeChecker.getTypeOfSymbolAtLocation(property, declaration ?? location);
|
|
1573
|
+
walk(`${prefix}.${property.getName()}`, propertyType, depth + 1);
|
|
151
1574
|
}
|
|
1575
|
+
};
|
|
1576
|
+
for (const [name, type] of roots) walk(name, type, 0);
|
|
1577
|
+
return slots;
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* Match each source type against each slot by **assignability**.
|
|
1581
|
+
*
|
|
1582
|
+
* Not by comparing `typeToString` spellings, which is the obvious alternative
|
|
1583
|
+
* and is wrong in both directions that matter: `TaskId` and
|
|
1584
|
+
* `` `tsk_${string}` `` are one type written two ways, and the AI SDK's own
|
|
1585
|
+
* inference produces the template-literal spelling where a prompt's signature
|
|
1586
|
+
* uses the alias. Under identity a source would silently fail to be offered on
|
|
1587
|
+
* a slot it fits perfectly, and an author's only recourse would be to pin a
|
|
1588
|
+
* type argument until the two strings happened to agree.
|
|
1589
|
+
*
|
|
1590
|
+
* N×M by construction, but each test is a relation check over types the
|
|
1591
|
+
* checker has already resolved, not another resolution.
|
|
1592
|
+
*
|
|
1593
|
+
* @param slots - Slot path → the slot's type, from {@link collectSlotTypes}.
|
|
1594
|
+
* @param sources - Source key → the type that source supplies.
|
|
1595
|
+
* @param typeChecker - Checker both sets of types were resolved in.
|
|
1596
|
+
* @returns Slot path → keys of the sources that fit it.
|
|
1597
|
+
*/
|
|
1598
|
+
function matchByAssignability(slots, sources, typeChecker) {
|
|
1599
|
+
const matches = {};
|
|
1600
|
+
for (const [path, slotType] of slots) for (const [key, sourceType] of sources) {
|
|
1601
|
+
if (!typeChecker.isTypeAssignableTo(sourceType, slotType)) continue;
|
|
1602
|
+
const existing = matches[path];
|
|
1603
|
+
if (existing) existing.push(key);
|
|
1604
|
+
else matches[path] = [key];
|
|
152
1605
|
}
|
|
153
|
-
|
|
1606
|
+
return matches;
|
|
1607
|
+
}
|
|
154
1608
|
//#endregion
|
|
155
1609
|
//#region src/prompt/file/ts/ts-prompt-file-type.ts
|
|
156
1610
|
/**
|
|
@@ -180,7 +1634,8 @@ var MemoryFileProvider = class {
|
|
|
180
1634
|
function isValidIdentifier(name) {
|
|
181
1635
|
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
182
1636
|
}
|
|
183
|
-
var TSPromptFileType = class {
|
|
1637
|
+
var TSPromptFileType = class TSPromptFileType {
|
|
1638
|
+
language = "typescript";
|
|
184
1639
|
defaultIncludePatterns = ["**/*.prompt.ts", "**/*.promp.ts"];
|
|
185
1640
|
defaultFileExtension = ".prompt.ts";
|
|
186
1641
|
newPromptSkeleton(promptsId, name, importPath) {
|
|
@@ -195,19 +1650,205 @@ export default prompts(
|
|
|
195
1650
|
}));`;
|
|
196
1651
|
}
|
|
197
1652
|
fileProvider;
|
|
1653
|
+
/** Kept between parses so TypeScript can reuse unchanged source files. */
|
|
1654
|
+
previousProgram;
|
|
1655
|
+
/**
|
|
1656
|
+
* Project probe results, keyed by root and probes, with the fingerprint of
|
|
1657
|
+
* the modules they were computed against.
|
|
1658
|
+
*/
|
|
1659
|
+
projectCache = /* @__PURE__ */ new Map();
|
|
198
1660
|
constructor(fileProvider = new LocalFileProvider()) {
|
|
199
1661
|
this.fileProvider = fileProvider;
|
|
200
1662
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
1663
|
+
withFileProvider(fileProvider) {
|
|
1664
|
+
const copy = new TSPromptFileType(fileProvider);
|
|
1665
|
+
copy.defaultIncludePatterns = this.defaultIncludePatterns;
|
|
1666
|
+
copy.defaultFileExtension = this.defaultFileExtension;
|
|
1667
|
+
return copy;
|
|
1668
|
+
}
|
|
1669
|
+
async parsePrompts(files, rootDir = "", { companionFiles = [] } = {}) {
|
|
1670
|
+
const sources = await this.readAll(files);
|
|
1671
|
+
const companions = await this.readAll(companionFiles.filter((f) => !sources.has(f)));
|
|
1672
|
+
const program = this.buildProgram(new Map([...sources, ...companions]));
|
|
1673
|
+
return [...sources].flatMap(([filePath, sourceCode]) => this.parseFileContent(filePath, sourceCode, rootDir, program?.getSourceFile(filePath), program?.typeChecker));
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Evaluates probes and slot matches by injecting each expression into the
|
|
1677
|
+
* file it concerns as a type alias and asking the checker what it resolves
|
|
1678
|
+
* to.
|
|
1679
|
+
*
|
|
1680
|
+
* Everything rides in **one** program build. A build brings a fresh checker
|
|
1681
|
+
* that re-derives every type the files depend on — for a config that infers
|
|
1682
|
+
* tool types, hundreds of milliseconds — while an extra alias in an existing
|
|
1683
|
+
* build is nearly free.
|
|
1684
|
+
*/
|
|
1685
|
+
async resolveTypes({ probes = [], slotMatches = [], project }) {
|
|
1686
|
+
const result = {
|
|
1687
|
+
probes: probes.map(() => void 0),
|
|
1688
|
+
slotMatches: slotMatches.map(() => ({}))
|
|
1689
|
+
};
|
|
1690
|
+
let projectProbes = [];
|
|
1691
|
+
let cacheKey;
|
|
1692
|
+
let fingerprint;
|
|
1693
|
+
if (project && project.probes.length > 0) {
|
|
1694
|
+
cacheKey = `${project.rootDir}\0${JSON.stringify(project.probes)}`;
|
|
1695
|
+
fingerprint = moduleFingerprint(project.rootDir, project.probes);
|
|
1696
|
+
const cached = this.projectCache.get(cacheKey);
|
|
1697
|
+
if (cached && cached.fingerprint === fingerprint) result.project = { ...cached.results };
|
|
1698
|
+
else {
|
|
1699
|
+
projectProbes = project.probes;
|
|
1700
|
+
result.project = Object.fromEntries(project.probes.map((p) => [p.name, void 0]));
|
|
1701
|
+
}
|
|
1702
|
+
} else if (project) result.project = {};
|
|
1703
|
+
if (probes.length === 0 && slotMatches.length === 0 && projectProbes.length === 0) return result;
|
|
1704
|
+
const projectFile = project ? path.join(project.rootDir, PROJECT_PROBE_MODULE) : "";
|
|
1705
|
+
let projectBuilt = false;
|
|
1706
|
+
await this.withInjectedTypes([
|
|
1707
|
+
...probes.map((req) => ({
|
|
1708
|
+
filePath: req.filePath,
|
|
1709
|
+
promptName: req.promptName,
|
|
1710
|
+
expressions: probeExpressions(req.probe)
|
|
1711
|
+
})),
|
|
1712
|
+
...slotMatches.map((req) => ({
|
|
1713
|
+
filePath: req.filePath,
|
|
1714
|
+
promptName: req.promptName,
|
|
1715
|
+
expressions: slotMatchExpressions(req)
|
|
1716
|
+
})),
|
|
1717
|
+
...projectProbes.map((probe) => ({
|
|
1718
|
+
filePath: projectFile,
|
|
1719
|
+
promptName: "",
|
|
1720
|
+
expressions: probeExpressions(probe),
|
|
1721
|
+
virtual: true
|
|
1722
|
+
}))
|
|
1723
|
+
], (index, resolve, program, sourceFile) => {
|
|
1724
|
+
if (index < probes.length) result.probes[index] = evaluateProbe(probes[index].probe, resolve, program, sourceFile);
|
|
1725
|
+
else if (index < probes.length + slotMatches.length) {
|
|
1726
|
+
const i = index - probes.length;
|
|
1727
|
+
result.slotMatches[i] = matchSlots(slotMatches[i], resolve, program, sourceFile);
|
|
1728
|
+
} else {
|
|
1729
|
+
projectBuilt = true;
|
|
1730
|
+
const probe = projectProbes[index - probes.length - slotMatches.length];
|
|
1731
|
+
result.project[probe.name] = evaluateProbe(probe, resolve, program, sourceFile);
|
|
1732
|
+
}
|
|
1733
|
+
});
|
|
1734
|
+
if (projectBuilt && cacheKey && fingerprint) this.projectCache.set(cacheKey, {
|
|
1735
|
+
fingerprint,
|
|
1736
|
+
results: { ...result.project }
|
|
1737
|
+
});
|
|
1738
|
+
return result;
|
|
1739
|
+
}
|
|
1740
|
+
async resolveTypeProbes(requests) {
|
|
1741
|
+
return (await this.resolveTypes({ probes: requests })).probes;
|
|
1742
|
+
}
|
|
1743
|
+
async resolveSlotMatches(requests) {
|
|
1744
|
+
return (await this.resolveTypes({ slotMatches: requests })).slotMatches;
|
|
1745
|
+
}
|
|
1746
|
+
/**
|
|
1747
|
+
* Evaluate named type expressions in the scope of the prompt files they
|
|
1748
|
+
* concern, in a single program build.
|
|
1749
|
+
*
|
|
1750
|
+
* Each expression becomes a `type` alias appended to its own prompt file, so
|
|
1751
|
+
* it is evaluated where the file's own imports and declarations are visible,
|
|
1752
|
+
* and `$config` is substituted for a way to name what that prompt returns.
|
|
1753
|
+
* `visit` is then called once per request with a `resolve(name)` that hands
|
|
1754
|
+
* back the type each alias landed on.
|
|
1755
|
+
*
|
|
1756
|
+
* Batching is the whole point: one build serves every request, however many
|
|
1757
|
+
* aliases they contribute between them.
|
|
1758
|
+
*/
|
|
1759
|
+
async withInjectedTypes(requests, visit) {
|
|
1760
|
+
const alias = (index, name) => `__evalution_t${index}_${name}`;
|
|
1761
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
1762
|
+
requests.forEach((req, index) => {
|
|
1763
|
+
const list = byFile.get(req.filePath);
|
|
1764
|
+
if (list) list.push(index);
|
|
1765
|
+
else byFile.set(req.filePath, [index]);
|
|
1766
|
+
});
|
|
1767
|
+
const sources = /* @__PURE__ */ new Map();
|
|
1768
|
+
for (const [filePath, indices] of byFile) {
|
|
1769
|
+
let sourceCode;
|
|
1770
|
+
if (requests[indices[0]].virtual) sourceCode = "export {};\n";
|
|
1771
|
+
else try {
|
|
1772
|
+
sourceCode = await this.fileProvider.readFile(filePath);
|
|
1773
|
+
} catch {
|
|
1774
|
+
continue;
|
|
1775
|
+
}
|
|
1776
|
+
const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.ESNext, true);
|
|
1777
|
+
const lines = [];
|
|
1778
|
+
for (const index of indices) {
|
|
1779
|
+
const request = requests[index];
|
|
1780
|
+
const config = this.configTypeExpression(sourceFile, filePath, request.promptName);
|
|
1781
|
+
for (const [name, expression] of Object.entries(request.expressions)) {
|
|
1782
|
+
const substituted = config ? expression.replaceAll("$config", config) : expression;
|
|
1783
|
+
const rhs = !config && expression.includes("$config") ? "never" : substituted;
|
|
1784
|
+
lines.push(`type ${alias(index, name)} = ${rhs}`);
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
if (lines.length > 0) sources.set(filePath, `${sourceCode}\n${lines.join("\n")}\n`);
|
|
1788
|
+
}
|
|
1789
|
+
const program = this.buildProgram(sources);
|
|
1790
|
+
if (!program) return;
|
|
1791
|
+
for (const [filePath, indices] of byFile) {
|
|
1792
|
+
const sourceFile = program.getSourceFile(filePath);
|
|
1793
|
+
if (!sourceFile) continue;
|
|
1794
|
+
for (const index of indices) visit(index, (name) => resolveTypeAlias(sourceFile, alias(index, name), program.typeChecker), program, sourceFile);
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* A type expression naming what the prompt named `promptName` returns, to
|
|
1799
|
+
* substitute for a probe's `$config` token.
|
|
1800
|
+
*
|
|
1801
|
+
* Which shape a prompt file uses is this file type's knowledge: an exported
|
|
1802
|
+
* function declaration can be named directly, while a prompt defined through
|
|
1803
|
+
* the `prompts()` helper lives inside an anonymous default export and has to
|
|
1804
|
+
* be reached by importing the module back into itself.
|
|
1805
|
+
*/
|
|
1806
|
+
configTypeExpression(sourceFile, filePath, promptName) {
|
|
1807
|
+
let shape;
|
|
1808
|
+
const visit = (node) => {
|
|
1809
|
+
if (shape) return;
|
|
1810
|
+
if (ts.isFunctionDeclaration(node) && node.name?.text === promptName && node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
|
|
1811
|
+
shape = "function";
|
|
1812
|
+
return;
|
|
1813
|
+
}
|
|
1814
|
+
if (ts.isExportAssignment(node)) {
|
|
1815
|
+
if (findPromptsHelperCall(node.expression)?.object.properties.some((p) => getPropertyName(p) === promptName)) {
|
|
1816
|
+
shape = "helper";
|
|
1817
|
+
return;
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
ts.forEachChild(node, visit);
|
|
1821
|
+
};
|
|
1822
|
+
visit(sourceFile);
|
|
1823
|
+
if (shape === "function") return `ReturnType<typeof ${promptName}>`;
|
|
1824
|
+
if (shape === "helper") {
|
|
1825
|
+
const self = `./${path.basename(filePath).replace(/\.ts$/, ".js")}`;
|
|
1826
|
+
return `ReturnType<ReturnType<typeof import(${JSON.stringify(self)}).default>[${JSON.stringify(promptName)}]>`;
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
async readAll(files) {
|
|
1830
|
+
return new Map(await Promise.all(files.map(async (filePath) => [filePath, await this.fileProvider.readFile(filePath)])));
|
|
1831
|
+
}
|
|
1832
|
+
/**
|
|
1833
|
+
* Build a program over `sources`, reusing the previous one's unchanged
|
|
1834
|
+
* source files.
|
|
1835
|
+
*
|
|
1836
|
+
* Type resolution is best-effort: a project whose tsconfig or imports fail
|
|
1837
|
+
* to load still parses, just without checker-backed types.
|
|
1838
|
+
*/
|
|
1839
|
+
buildProgram(sources) {
|
|
1840
|
+
try {
|
|
1841
|
+
const program = createPromptProgram(sources, this.previousProgram);
|
|
1842
|
+
this.previousProgram = program?.program;
|
|
1843
|
+
return program;
|
|
1844
|
+
} catch {
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
206
1847
|
}
|
|
207
1848
|
async updateProperty(filePath, propDef, value, promptId) {
|
|
208
1849
|
if (!propDef.valueSpan) throw new Error(`Property '${propDef.name}' is missing valueSpan`);
|
|
209
1850
|
let sourceCode = await this.fileProvider.readFile(filePath);
|
|
210
|
-
const adjusted =
|
|
1851
|
+
const adjusted = resolveBindings(sourceCode, value, filePath);
|
|
211
1852
|
sourceCode = adjusted.sourceCode;
|
|
212
1853
|
const resolvedValue = adjusted.value;
|
|
213
1854
|
const functionName = promptId?.slice(promptId.lastIndexOf("#") + 1);
|
|
@@ -229,7 +1870,7 @@ export default prompts(
|
|
|
229
1870
|
}
|
|
230
1871
|
async addProperty(filePath, promptName, propertyName, value) {
|
|
231
1872
|
let sourceCode = await this.fileProvider.readFile(filePath);
|
|
232
|
-
const adjusted =
|
|
1873
|
+
const adjusted = resolveBindings(sourceCode, value, filePath);
|
|
233
1874
|
sourceCode = adjusted.sourceCode;
|
|
234
1875
|
const resolvedValue = adjusted.value;
|
|
235
1876
|
const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.Latest, true);
|
|
@@ -274,7 +1915,7 @@ export default prompts(
|
|
|
274
1915
|
await this.fileProvider.writeFile(filePath, newSource);
|
|
275
1916
|
}
|
|
276
1917
|
async loadConfig(filePath, promptName, params) {
|
|
277
|
-
const module = await this.fileProvider.import(filePath);
|
|
1918
|
+
const module = await this.fileProvider.import(filePath, { fresh: true });
|
|
278
1919
|
let fn = module[promptName];
|
|
279
1920
|
if (typeof fn !== "function" && typeof module.default === "function") {
|
|
280
1921
|
const obj = module.default();
|
|
@@ -285,19 +1926,20 @@ export default prompts(
|
|
|
285
1926
|
if (!config || typeof config !== "object") throw new Error(`'${promptName}' did not return a valid config object`);
|
|
286
1927
|
return config;
|
|
287
1928
|
}
|
|
288
|
-
parseFileContent(filePath, sourceCode, rootDir) {
|
|
289
|
-
const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.ESNext, true);
|
|
1929
|
+
parseFileContent(filePath, sourceCode, rootDir, programSourceFile, typeChecker) {
|
|
1930
|
+
const sourceFile = programSourceFile ?? ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.ESNext, true);
|
|
1931
|
+
const checker = programSourceFile ? typeChecker : void 0;
|
|
290
1932
|
const prompts = [];
|
|
291
1933
|
const visitNode = (node) => {
|
|
292
1934
|
if (ts.isFunctionDeclaration(node) && node.name) {
|
|
293
1935
|
if (node.modifiers?.some((mod) => mod.kind === ts.SyntaxKind.ExportKeyword)) {
|
|
294
|
-
const prompt = this.parseFunctionDeclaration(node, sourceFile, filePath, rootDir);
|
|
1936
|
+
const prompt = this.parseFunctionDeclaration(node, sourceFile, filePath, rootDir, checker);
|
|
295
1937
|
if (prompt) prompts.push(prompt);
|
|
296
1938
|
}
|
|
297
1939
|
} else if (ts.isExportAssignment(node)) {
|
|
298
1940
|
const helper = findPromptsHelperCall(node.expression);
|
|
299
1941
|
if (helper) for (const prop of helper.object.properties) {
|
|
300
|
-
const parsed = this.parseHelperProperty(prop, sourceFile, filePath, rootDir, helper.moduleId);
|
|
1942
|
+
const parsed = this.parseHelperProperty(prop, sourceFile, filePath, rootDir, helper.moduleId, checker);
|
|
301
1943
|
if (parsed) prompts.push(parsed);
|
|
302
1944
|
}
|
|
303
1945
|
}
|
|
@@ -306,14 +1948,14 @@ export default prompts(
|
|
|
306
1948
|
visitNode(sourceFile);
|
|
307
1949
|
return prompts;
|
|
308
1950
|
}
|
|
309
|
-
parseHelperProperty(prop, sourceFile, filePath, rootDir, moduleId) {
|
|
1951
|
+
parseHelperProperty(prop, sourceFile, filePath, rootDir, moduleId, typeChecker) {
|
|
310
1952
|
const name = getPropertyName(prop);
|
|
311
1953
|
if (!name) return null;
|
|
312
1954
|
const fn = getPropertyFunction(prop);
|
|
313
1955
|
if (!fn) return null;
|
|
314
1956
|
const returnObject = findReturnObjectInFunctionLike(fn);
|
|
315
1957
|
if (!returnObject) return null;
|
|
316
|
-
const functionParameters = extractPropertiesFromParameters(fn.parameters, sourceFile).definitions;
|
|
1958
|
+
const functionParameters = extractPropertiesFromParameters(fn.parameters, sourceFile, typeChecker).definitions;
|
|
317
1959
|
const relativeFilePath = rootDir ? path.relative(rootDir, filePath) : filePath;
|
|
318
1960
|
const extractedProps = extractPropertiesFromObjectLiteral(returnObject, void 0, sourceFile);
|
|
319
1961
|
const treePath = relativeFilePath.split("/").filter(Boolean);
|
|
@@ -327,10 +1969,10 @@ export default prompts(
|
|
|
327
1969
|
treePath
|
|
328
1970
|
};
|
|
329
1971
|
}
|
|
330
|
-
parseFunctionDeclaration(node, sourceFile, filePath, rootDir) {
|
|
1972
|
+
parseFunctionDeclaration(node, sourceFile, filePath, rootDir, typeChecker) {
|
|
331
1973
|
if (!node.name) return null;
|
|
332
1974
|
const functionName = node.name.text;
|
|
333
|
-
const functionParameters = extractPropertiesFromParameters(node.parameters, sourceFile).definitions;
|
|
1975
|
+
const functionParameters = extractPropertiesFromParameters(node.parameters, sourceFile, typeChecker).definitions;
|
|
334
1976
|
const returnObject = this.findReturnObjectInFunction(node);
|
|
335
1977
|
if (!returnObject) return null;
|
|
336
1978
|
const relativeFilePath = rootDir ? path.relative(rootDir, filePath) : filePath;
|
|
@@ -386,6 +2028,197 @@ export default prompts(
|
|
|
386
2028
|
return returnObj;
|
|
387
2029
|
}
|
|
388
2030
|
};
|
|
2031
|
+
/** Make an arbitrary key safe to embed in a TypeScript identifier. */
|
|
2032
|
+
function sourceAlias(key) {
|
|
2033
|
+
return `src_${aliasSafe(key)}`;
|
|
2034
|
+
}
|
|
2035
|
+
function slotAlias(name) {
|
|
2036
|
+
return `slot_${aliasSafe(name)}`;
|
|
2037
|
+
}
|
|
2038
|
+
/** The aliases a slot match needs injected: one per source, one per extra root. */
|
|
2039
|
+
function slotMatchExpressions(request) {
|
|
2040
|
+
return {
|
|
2041
|
+
...Object.fromEntries(request.sources.map((src) => [sourceAlias(src.key), src.expression])),
|
|
2042
|
+
...Object.fromEntries(Object.entries(request.extraSlots ?? {}).map(([name, expression]) => [slotAlias(name), expression]))
|
|
2043
|
+
};
|
|
2044
|
+
}
|
|
2045
|
+
/** The name of the virtual module project probes are evaluated in. */
|
|
2046
|
+
const PROJECT_PROBE_MODULE = "__evalution_project_probes__.ts";
|
|
2047
|
+
/** The alias for a `factories` probe's `produces` type, checked before its modules. */
|
|
2048
|
+
const PRODUCES_ALIAS = "produces";
|
|
2049
|
+
/** The alias for a `factories` probe's `i`th module. */
|
|
2050
|
+
function factoryAlias(i) {
|
|
2051
|
+
return `factories_${i}`;
|
|
2052
|
+
}
|
|
2053
|
+
/**
|
|
2054
|
+
* The aliases a probe needs injected. A `factories` probe gets one per module,
|
|
2055
|
+
* so a module that isn't installed only empties its own alias.
|
|
2056
|
+
*
|
|
2057
|
+
* Each alias is a mapped type over the module's exports keeping those whose
|
|
2058
|
+
* call (or, with a `member`, whose method's call) produces the probe's type,
|
|
2059
|
+
* mapped to that callable. The `0 extends 1 & X` guards drop `any` — an
|
|
2060
|
+
* uninstalled module types as `any`, and so would a call returning it.
|
|
2061
|
+
*/
|
|
2062
|
+
function probeExpressions(probe) {
|
|
2063
|
+
if (probe.kind === "type") return { probe: probe.expression };
|
|
2064
|
+
const member = probe.member && JSON.stringify(probe.member);
|
|
2065
|
+
return Object.fromEntries([[PRODUCES_ALIAS, probe.produces], ...probe.modules.map((module, i) => {
|
|
2066
|
+
const m = `typeof import(${JSON.stringify(module)})`;
|
|
2067
|
+
const callable = member ? `${m}[K] extends { readonly ${member}: infer F } ? F : never` : `${m}[K]`;
|
|
2068
|
+
return [factoryAlias(i), `0 extends 1 & ${m} ? never : { [K in keyof ${m} as (${callable}) extends (...args: any) => infer R ? 0 extends 1 & R ? never : [R] extends [${probe.produces}] ? K : never : never]: ${callable} }`];
|
|
2069
|
+
})]);
|
|
2070
|
+
}
|
|
2071
|
+
/**
|
|
2072
|
+
* A fingerprint of the installed packages `probes` read, so cached results can
|
|
2073
|
+
* be kept exactly as long as nothing was installed, removed or upgraded: each
|
|
2074
|
+
* package's manifest path and modification time, as found walking up from
|
|
2075
|
+
* `rootDir`.
|
|
2076
|
+
*/
|
|
2077
|
+
function moduleFingerprint(rootDir, probes) {
|
|
2078
|
+
const specifiers = /* @__PURE__ */ new Set();
|
|
2079
|
+
const addImports = (text) => {
|
|
2080
|
+
for (const m of text.matchAll(/import\(\s*["']([^"']+)["']\s*\)/g)) specifiers.add(m[1]);
|
|
2081
|
+
};
|
|
2082
|
+
for (const probe of probes) if (probe.kind === "type") addImports(probe.expression);
|
|
2083
|
+
else {
|
|
2084
|
+
for (const module of probe.modules) specifiers.add(module);
|
|
2085
|
+
addImports(probe.produces);
|
|
2086
|
+
}
|
|
2087
|
+
const parts = [];
|
|
2088
|
+
for (const specifier of [...specifiers].sort()) {
|
|
2089
|
+
if (specifier.startsWith(".")) continue;
|
|
2090
|
+
const segments = specifier.split("/");
|
|
2091
|
+
const pkg = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
|
|
2092
|
+
let found = "missing";
|
|
2093
|
+
for (let dir = rootDir;; dir = path.dirname(dir)) {
|
|
2094
|
+
const manifest = path.join(dir, "node_modules", pkg, "package.json");
|
|
2095
|
+
if (ts.sys.fileExists(manifest)) {
|
|
2096
|
+
found = `${manifest}@${ts.sys.getModifiedTime?.(manifest)?.getTime() ?? 0}`;
|
|
2097
|
+
break;
|
|
2098
|
+
}
|
|
2099
|
+
if (path.dirname(dir) === dir) break;
|
|
2100
|
+
}
|
|
2101
|
+
parts.push(`${pkg}=${found}`);
|
|
2102
|
+
}
|
|
2103
|
+
return parts.join(";");
|
|
2104
|
+
}
|
|
2105
|
+
/** What a probe's injected aliases resolved to, reported three-valued. */
|
|
2106
|
+
function evaluateProbe(probe, resolve, program, sourceFile) {
|
|
2107
|
+
if (probe.kind === "factories") return evaluateFactories(probe, resolve, program, sourceFile);
|
|
2108
|
+
const type = resolve("probe");
|
|
2109
|
+
if (!type || type.flags & ts.TypeFlags.Any) return void 0;
|
|
2110
|
+
if (type.flags & ts.TypeFlags.Never) return null;
|
|
2111
|
+
const built = buildPropTypeFromType(type, program.typeChecker, sourceFile);
|
|
2112
|
+
const def = {
|
|
2113
|
+
name: probe.name,
|
|
2114
|
+
type: probe.syntax ? {
|
|
2115
|
+
...built,
|
|
2116
|
+
syntax: probe.syntax
|
|
2117
|
+
} : built,
|
|
2118
|
+
optional: false
|
|
2119
|
+
};
|
|
2120
|
+
if (probe.description) def.description = probe.description;
|
|
2121
|
+
return def;
|
|
2122
|
+
}
|
|
2123
|
+
/**
|
|
2124
|
+
* The factories a `factories` probe's aliases found: each surviving export
|
|
2125
|
+
* (or its `member`), described as a `function`-kind definition bound to an
|
|
2126
|
+
* import of the export from its module. `undefined` when no alias resolved at all (nothing was evaluated).
|
|
2127
|
+
*/
|
|
2128
|
+
function evaluateFactories(probe, resolve, { typeChecker }, sourceFile) {
|
|
2129
|
+
const produces = resolve(PRODUCES_ALIAS);
|
|
2130
|
+
if (!produces || produces.flags & ts.TypeFlags.Any) return void 0;
|
|
2131
|
+
const factories = [];
|
|
2132
|
+
let evaluated = false;
|
|
2133
|
+
probe.modules.forEach((from, i) => {
|
|
2134
|
+
const type = resolve(factoryAlias(i));
|
|
2135
|
+
if (!type) return;
|
|
2136
|
+
evaluated = true;
|
|
2137
|
+
if (type.flags & (ts.TypeFlags.Never | ts.TypeFlags.Any)) return;
|
|
2138
|
+
for (const symbol of typeChecker.getPropertiesOfType(type)) {
|
|
2139
|
+
const built = buildPropTypeFromType(typeChecker.getTypeOfSymbolAtLocation(symbol, sourceFile), typeChecker, sourceFile);
|
|
2140
|
+
if (built.kind !== "function") continue;
|
|
2141
|
+
const def = {
|
|
2142
|
+
name: probe.member ? `${symbol.name}.${probe.member}` : symbol.name,
|
|
2143
|
+
type: built,
|
|
2144
|
+
optional: false
|
|
2145
|
+
};
|
|
2146
|
+
const description = probe.member ? "" : ts.displayPartsToString(symbol.getDocumentationComment(typeChecker)).trim();
|
|
2147
|
+
if (description) def.description = description;
|
|
2148
|
+
factories.push({
|
|
2149
|
+
def,
|
|
2150
|
+
binding: {
|
|
2151
|
+
kind: "import",
|
|
2152
|
+
spec: {
|
|
2153
|
+
name: symbol.name,
|
|
2154
|
+
from
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
});
|
|
2158
|
+
}
|
|
2159
|
+
});
|
|
2160
|
+
return evaluated ? factories : void 0;
|
|
2161
|
+
}
|
|
2162
|
+
/** Which of a request's sources fit which of its slots, by assignability. */
|
|
2163
|
+
function matchSlots(request, resolve, program, sourceFile) {
|
|
2164
|
+
const { typeChecker } = program;
|
|
2165
|
+
const roots = /* @__PURE__ */ new Map();
|
|
2166
|
+
const fn = findPromptFunctionLike(sourceFile, request.promptName);
|
|
2167
|
+
for (const parameter of fn?.parameters ?? []) {
|
|
2168
|
+
if (!ts.isIdentifier(parameter.name)) continue;
|
|
2169
|
+
roots.set(parameter.name.text, typeChecker.getTypeAtLocation(parameter));
|
|
2170
|
+
}
|
|
2171
|
+
for (const name of Object.keys(request.extraSlots ?? {})) {
|
|
2172
|
+
const type = resolve(slotAlias(name));
|
|
2173
|
+
if (type && !(type.flags & ts.TypeFlags.Never)) roots.set(name, type);
|
|
2174
|
+
}
|
|
2175
|
+
const sourceTypes = /* @__PURE__ */ new Map();
|
|
2176
|
+
for (const src of request.sources) {
|
|
2177
|
+
const type = resolve(sourceAlias(src.key));
|
|
2178
|
+
if (!type || type.flags & (ts.TypeFlags.Never | ts.TypeFlags.Any)) continue;
|
|
2179
|
+
sourceTypes.set(src.key, type);
|
|
2180
|
+
}
|
|
2181
|
+
if (sourceTypes.size === 0) return {};
|
|
2182
|
+
return matchByAssignability(collectSlotTypes(roots, typeChecker, sourceFile), sourceTypes, typeChecker);
|
|
2183
|
+
}
|
|
2184
|
+
function aliasSafe(key) {
|
|
2185
|
+
return key.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
2186
|
+
}
|
|
2187
|
+
/**
|
|
2188
|
+
* The function-like node a prompt is defined by, in either shape this file
|
|
2189
|
+
* type recognises — a top-level exported declaration, or a property of the
|
|
2190
|
+
* object a `prompts()` helper's factory returns.
|
|
2191
|
+
*/
|
|
2192
|
+
function findPromptFunctionLike(sourceFile, promptName) {
|
|
2193
|
+
let found;
|
|
2194
|
+
const visit = (node) => {
|
|
2195
|
+
if (found) return;
|
|
2196
|
+
if (ts.isFunctionDeclaration(node) && node.name?.text === promptName) {
|
|
2197
|
+
found = node;
|
|
2198
|
+
return;
|
|
2199
|
+
}
|
|
2200
|
+
if (ts.isExportAssignment(node)) {
|
|
2201
|
+
const helper = findPromptsHelperCall(node.expression);
|
|
2202
|
+
for (const prop of helper?.object.properties ?? []) if (getPropertyName(prop) === promptName) {
|
|
2203
|
+
found = getPropertyFunction(prop) ?? void 0;
|
|
2204
|
+
return;
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
ts.forEachChild(node, visit);
|
|
2208
|
+
};
|
|
2209
|
+
visit(sourceFile);
|
|
2210
|
+
return found;
|
|
2211
|
+
}
|
|
2212
|
+
/**
|
|
2213
|
+
* Resolve the type an injected probe alias stands for.
|
|
2214
|
+
*
|
|
2215
|
+
* Reads the alias's *declared* type rather than the symbol's, so a probe that
|
|
2216
|
+
* resolves to a mapped or conditional type is evaluated rather than handed
|
|
2217
|
+
* back as the alias name.
|
|
2218
|
+
*/
|
|
2219
|
+
function resolveTypeAlias(sourceFile, aliasName, typeChecker) {
|
|
2220
|
+
for (const stmt of sourceFile.statements) if (ts.isTypeAliasDeclaration(stmt) && stmt.name.text === aliasName) return typeChecker.getTypeFromTypeNode(stmt.type);
|
|
2221
|
+
}
|
|
389
2222
|
/**
|
|
390
2223
|
* If `expr` is a call like `prompts({ id }, factory)` whose factory immediately
|
|
391
2224
|
* returns an object literal, return that object literal together with the module
|
|
@@ -423,138 +2256,6 @@ function getPropertyFunction(prop) {
|
|
|
423
2256
|
}
|
|
424
2257
|
return null;
|
|
425
2258
|
}
|
|
426
|
-
/**
|
|
427
|
-
* Resolve binding-array candidates against the file's structure.
|
|
428
|
-
*
|
|
429
|
-
* For each `functionCall` in `value`, walk its `binding` candidates in order
|
|
430
|
-
* and pick the first one that matches the source:
|
|
431
|
-
* - `parameter` candidates match when the file contains the named
|
|
432
|
-
* `enclosingCall` (e.g. `prompts(({...}) => ...)`) whose first parameter is
|
|
433
|
-
* a destructured object. The callee is added to that destructure (if not
|
|
434
|
-
* already present) and the value's `binding` is stripped — the new
|
|
435
|
-
* functionCall reads its callee from the closure parameter, not a top-level
|
|
436
|
-
* import.
|
|
437
|
-
* - `import` candidates always match. They collapse the binding to that
|
|
438
|
-
* single import so ts-proppy's emitter adds the corresponding top-level
|
|
439
|
-
* import.
|
|
440
|
-
*
|
|
441
|
-
* Returns the (possibly) adjusted source code along with a plain
|
|
442
|
-
* {@link PropValue} ready for ts-proppy.
|
|
443
|
-
*/
|
|
444
|
-
function resolveBindingsAndAugment(sourceCode, value) {
|
|
445
|
-
const sourceFile = ts.createSourceFile("helper-adjust.ts", sourceCode, ts.ScriptTarget.Latest, true);
|
|
446
|
-
const destructureAdditions = /* @__PURE__ */ new Map();
|
|
447
|
-
const resolveCandidate = (_fc, candidates) => {
|
|
448
|
-
for (const c of candidates) if (c.kind === "parameter") {
|
|
449
|
-
const dest = findEnclosingCallDestructure(sourceFile, c.enclosingCall);
|
|
450
|
-
if (dest) return { viaDestructure: dest };
|
|
451
|
-
} else if (c.kind === "import") return { binding: c };
|
|
452
|
-
return {};
|
|
453
|
-
};
|
|
454
|
-
const adjusted = mapFunctionCalls(value, (fc) => {
|
|
455
|
-
if (!fc.binding) return fc;
|
|
456
|
-
const result = resolveCandidate(fc, Array.isArray(fc.binding) ? fc.binding : [fc.binding]);
|
|
457
|
-
if (result.viaDestructure) {
|
|
458
|
-
const set = destructureAdditions.get(result.viaDestructure) ?? /* @__PURE__ */ new Set();
|
|
459
|
-
set.add(fc.callee);
|
|
460
|
-
destructureAdditions.set(result.viaDestructure, set);
|
|
461
|
-
const { binding: _drop, ...rest } = fc;
|
|
462
|
-
return rest;
|
|
463
|
-
}
|
|
464
|
-
if (result.binding) return {
|
|
465
|
-
...fc,
|
|
466
|
-
binding: result.binding
|
|
467
|
-
};
|
|
468
|
-
const { binding: _none, ...rest } = fc;
|
|
469
|
-
return rest;
|
|
470
|
-
});
|
|
471
|
-
const augmentations = [...destructureAdditions.entries()].map(([dest, names]) => {
|
|
472
|
-
const existing = /* @__PURE__ */ new Set();
|
|
473
|
-
for (const el of dest.elements) if (ts.isIdentifier(el.name)) existing.add(el.name.text);
|
|
474
|
-
return {
|
|
475
|
-
dest,
|
|
476
|
-
toAdd: [...names].filter((n) => !existing.has(n))
|
|
477
|
-
};
|
|
478
|
-
}).filter((a) => a.toAdd.length > 0).sort((a, b) => b.dest.getEnd() - a.dest.getEnd());
|
|
479
|
-
let nextSource = sourceCode;
|
|
480
|
-
for (const { dest, toAdd } of augmentations) {
|
|
481
|
-
let closeOffset = dest.getEnd() - 1;
|
|
482
|
-
while (nextSource[closeOffset - 1] === " ") closeOffset--;
|
|
483
|
-
const isEmpty = dest.elements.length === 0;
|
|
484
|
-
const insertion = (isEmpty ? " " : ", ") + toAdd.join(", ") + (isEmpty ? " " : "");
|
|
485
|
-
nextSource = nextSource.slice(0, closeOffset) + insertion + nextSource.slice(closeOffset);
|
|
486
|
-
}
|
|
487
|
-
return {
|
|
488
|
-
sourceCode: nextSource,
|
|
489
|
-
value: adjusted
|
|
490
|
-
};
|
|
491
|
-
}
|
|
492
|
-
/**
|
|
493
|
-
* Find the destructured first parameter of a call matching `enclosingCall` at
|
|
494
|
-
* the top level of `sourceFile`. Returns null when no such call exists or when
|
|
495
|
-
* its first parameter is not an object binding pattern.
|
|
496
|
-
*
|
|
497
|
-
* When `enclosingCall.import` is provided, the callee identifier must resolve
|
|
498
|
-
* to a named import matching that spec.
|
|
499
|
-
*/
|
|
500
|
-
function findEnclosingCallDestructure(sourceFile, enclosingCall) {
|
|
501
|
-
if (!enclosingCall) return null;
|
|
502
|
-
if (!(enclosingCall.import ? sourceFileHasNamedImport(sourceFile, enclosingCall.import.name, enclosingCall.import.from) : true)) return null;
|
|
503
|
-
let found = null;
|
|
504
|
-
const visit = (node) => {
|
|
505
|
-
if (found) return;
|
|
506
|
-
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === enclosingCall.callee) {
|
|
507
|
-
const factory = node.arguments.find((arg) => ts.isArrowFunction(arg) || ts.isFunctionExpression(arg));
|
|
508
|
-
if (factory) {
|
|
509
|
-
const param = factory.parameters[0];
|
|
510
|
-
if (param?.name && ts.isObjectBindingPattern(param.name)) {
|
|
511
|
-
found = param.name;
|
|
512
|
-
return;
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
ts.forEachChild(node, visit);
|
|
517
|
-
};
|
|
518
|
-
visit(sourceFile);
|
|
519
|
-
return found;
|
|
520
|
-
}
|
|
521
|
-
function sourceFileHasNamedImport(sourceFile, name, from) {
|
|
522
|
-
for (const stmt of sourceFile.statements) {
|
|
523
|
-
if (!ts.isImportDeclaration(stmt)) continue;
|
|
524
|
-
if (!ts.isStringLiteral(stmt.moduleSpecifier)) continue;
|
|
525
|
-
if (stmt.moduleSpecifier.text !== from) continue;
|
|
526
|
-
const clause = stmt.importClause;
|
|
527
|
-
if (!clause?.namedBindings || !ts.isNamedImports(clause.namedBindings)) continue;
|
|
528
|
-
for (const el of clause.namedBindings.elements) if (el.name.text === name) return true;
|
|
529
|
-
}
|
|
530
|
-
return false;
|
|
531
|
-
}
|
|
532
|
-
/** Walk a ModelPropValue tree, transforming each functionCall via `fn`. */
|
|
533
|
-
function mapFunctionCalls(value, fn) {
|
|
534
|
-
switch (value.kind) {
|
|
535
|
-
case "functionCall": {
|
|
536
|
-
const mappedArgs = value.args.map((a) => mapFunctionCalls(a, fn));
|
|
537
|
-
return fn({
|
|
538
|
-
...value,
|
|
539
|
-
args: mappedArgs
|
|
540
|
-
});
|
|
541
|
-
}
|
|
542
|
-
case "object": {
|
|
543
|
-
const properties = {};
|
|
544
|
-
for (const [k, v] of Object.entries(value.properties)) properties[k] = mapFunctionCalls(v, fn);
|
|
545
|
-
return {
|
|
546
|
-
...value,
|
|
547
|
-
properties
|
|
548
|
-
};
|
|
549
|
-
}
|
|
550
|
-
case "array":
|
|
551
|
-
case "tuple": return {
|
|
552
|
-
...value,
|
|
553
|
-
elements: value.elements.map((el) => mapFunctionCalls(el, fn))
|
|
554
|
-
};
|
|
555
|
-
default: return value;
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
2259
|
function findReturnObjectInFunctionLike(fn) {
|
|
559
2260
|
if (ts.isArrowFunction(fn) && !ts.isBlock(fn.body)) {
|
|
560
2261
|
const body = ts.isParenthesizedExpression(fn.body) ? fn.body.expression : fn.body;
|
|
@@ -569,17 +2270,147 @@ function findReturnObjectInFunctionLike(fn) {
|
|
|
569
2270
|
}
|
|
570
2271
|
ts.forEachChild(n, visit);
|
|
571
2272
|
};
|
|
572
|
-
if (fn.body) visit(fn.body);
|
|
573
|
-
return result;
|
|
2273
|
+
if (fn.body) visit(fn.body);
|
|
2274
|
+
return result;
|
|
2275
|
+
}
|
|
2276
|
+
//#endregion
|
|
2277
|
+
//#region src/prompt/file/file-prompt-provider.ts
|
|
2278
|
+
/** Directories never scanned unless an include pattern names them. */
|
|
2279
|
+
const DEFAULT_IGNORED_DIRS = [
|
|
2280
|
+
"node_modules",
|
|
2281
|
+
"dist",
|
|
2282
|
+
".git"
|
|
2283
|
+
];
|
|
2284
|
+
/**
|
|
2285
|
+
* The ignore patterns to scan `includePatterns` with: the user's own
|
|
2286
|
+
* `ignorePatterns` plus a `**\/<dir>/**` pattern for each default ignored
|
|
2287
|
+
* directory — except those an include pattern names as a path segment (e.g.
|
|
2288
|
+
* `dist/**\/*.prompt.ts`), so opting a directory back in is explicit.
|
|
2289
|
+
*/
|
|
2290
|
+
function withDefaultIgnores(includePatterns, ignorePatterns) {
|
|
2291
|
+
return [...DEFAULT_IGNORED_DIRS.filter((dir) => !includePatterns.some((p) => p.split("/").includes(dir))).map((dir) => `**/${dir}/**`), ...ignorePatterns];
|
|
2292
|
+
}
|
|
2293
|
+
let defaultIDCounter = 0;
|
|
2294
|
+
/**
|
|
2295
|
+
* A TypeScript type expression naming what a source produces, for the file
|
|
2296
|
+
* type to evaluate in the scope of `promptFilePath`.
|
|
2297
|
+
*
|
|
2298
|
+
* The type is read back off the resource's own declaration rather than
|
|
2299
|
+
* declared separately: it is where the type came from in the first place, so
|
|
2300
|
+
* there is nothing to keep in sync, nothing to go stale under a rename, and
|
|
2301
|
+
* nothing a checker could not verify. A dynamic resource's type comes off
|
|
2302
|
+
* `create()`'s return (`Awaited` covers the common async `create`); a static
|
|
2303
|
+
* `value` resource has no `create` to read, so its `value` property is read
|
|
2304
|
+
* directly. Which one applies is known from the scan (see
|
|
2305
|
+
* {@link RegisteredSource.resource}), and has to be — the two definitions are
|
|
2306
|
+
* a union, so indexing the wrong property wouldn't type-check. A value source
|
|
2307
|
+
* appends its own key(s) as further indexed access, which is what makes
|
|
2308
|
+
* `taskA.id` type-check as `TaskId` rather than as the whole seeded object.
|
|
2309
|
+
*/
|
|
2310
|
+
function resourceTypeExpression(promptFilePath, source) {
|
|
2311
|
+
const resource = source.resource;
|
|
2312
|
+
let specifier = path.relative(path.dirname(promptFilePath), resource.modulePath).replace(/\\/g, "/").replace(/\.ts$/, ".js");
|
|
2313
|
+
if (!specifier.startsWith(".")) specifier = `./${specifier}`;
|
|
2314
|
+
const exported = `${`typeof import(${JSON.stringify(specifier)})`}[${JSON.stringify(resource.key)}]`;
|
|
2315
|
+
let expression = "value" in resource.resource ? `${exported}["value"]` : `Awaited<ReturnType<${exported}["create"]>>["value"]`;
|
|
2316
|
+
for (const key of source.outputPath) expression = `${expression}[${JSON.stringify(key)}]`;
|
|
2317
|
+
return expression;
|
|
2318
|
+
}
|
|
2319
|
+
/**
|
|
2320
|
+
* A type expression naming what `paramName` — a schema-valued entry of
|
|
2321
|
+
* `resource`'s own `inputs` — validates to, for the file type to evaluate in
|
|
2322
|
+
* the scope of the resource's *own* module.
|
|
2323
|
+
*
|
|
2324
|
+
* A resource's arguments are prompt-independent, so unlike
|
|
2325
|
+
* {@link resourceTypeExpression} this is evaluated once per (resource,
|
|
2326
|
+
* parameter) rather than once per (prompt, source): the injected alias lands
|
|
2327
|
+
* in the resource's own file, self-referencing its own export, so it needs
|
|
2328
|
+
* no import at all. `~standard.types` is Standard Schema's phantom
|
|
2329
|
+
* (type-only, never populated at run time) property carrying the schema's
|
|
2330
|
+
* inferred input/output types — reading `["output"]` off it is what turns a
|
|
2331
|
+
* `z.string()` into the type `string` without this file knowing anything
|
|
2332
|
+
* about zod, or any other validator, at all. See
|
|
2333
|
+
* `specs/resource-arguments.md` §H.
|
|
2334
|
+
*/
|
|
2335
|
+
function resourceParameterTypeExpression(resource, paramName) {
|
|
2336
|
+
return `${`NonNullable<typeof ${resource.key}["inputs"]>`}[${JSON.stringify(paramName)}] extends { "~standard": { types?: { output: infer O } } } ? O : never`;
|
|
2337
|
+
}
|
|
2338
|
+
/**
|
|
2339
|
+
* Whether `candidate` depends on `target`, directly or transitively, through
|
|
2340
|
+
* *code-wired* `inputs` (dependencies, never arguments — those aren't static).
|
|
2341
|
+
*
|
|
2342
|
+
* Used to keep a resource off its own argument's source list, and off the
|
|
2343
|
+
* list of any resource that would transitively create it — offering it there
|
|
2344
|
+
* would let a user assemble in the picker exactly the cycle
|
|
2345
|
+
* `ResourceRegistry`'s runtime check exists to reject, just with a worse
|
|
2346
|
+
* error. See `specs/resource-arguments.md` §H.
|
|
2347
|
+
*/
|
|
2348
|
+
function dependsOn(candidate, target, byResource, seen = /* @__PURE__ */ new Set()) {
|
|
2349
|
+
if (candidate === target) return true;
|
|
2350
|
+
if (seen.has(candidate)) return false;
|
|
2351
|
+
seen.add(candidate);
|
|
2352
|
+
const inputs = "inputs" in candidate.resource ? candidate.resource.inputs ?? {} : {};
|
|
2353
|
+
for (const value of Object.values(inputs)) {
|
|
2354
|
+
if (!isResource(value)) continue;
|
|
2355
|
+
const registered = byResource.get(value);
|
|
2356
|
+
if (registered && dependsOn(registered, target, byResource, seen)) return true;
|
|
2357
|
+
}
|
|
2358
|
+
return false;
|
|
2359
|
+
}
|
|
2360
|
+
/**
|
|
2361
|
+
* A resource argument reported with the right name but no resolved type —
|
|
2362
|
+
* the checker-less degradation `specs/resource-arguments.md` §B and §G both
|
|
2363
|
+
* call for. Unlike an opaque *value* source, an argument is always plain
|
|
2364
|
+
* data by construction (it's validated by a schema, never a live handle), so
|
|
2365
|
+
* this deliberately isn't `kind: 'opaque'` — that would tell `SourceRow` the
|
|
2366
|
+
* slot has no editor at all. A generic string editor is offered instead, and
|
|
2367
|
+
* `ResourceRegistry`'s own validation (which needs no checker at all) catches
|
|
2368
|
+
* a value the real type would have rejected.
|
|
2369
|
+
*/
|
|
2370
|
+
function unresolvedParameter(name) {
|
|
2371
|
+
return {
|
|
2372
|
+
name,
|
|
2373
|
+
type: {
|
|
2374
|
+
kind: "primitive",
|
|
2375
|
+
syntax: "unknown",
|
|
2376
|
+
base: "string"
|
|
2377
|
+
},
|
|
2378
|
+
optional: false
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2381
|
+
/** Whether a probe resolved to a definition (rather than factories, or nothing). */
|
|
2382
|
+
function isDefinition(result) {
|
|
2383
|
+
return !!result && !Array.isArray(result);
|
|
2384
|
+
}
|
|
2385
|
+
/**
|
|
2386
|
+
* A file type's slot-match answer (slot path → source uris) turned around into
|
|
2387
|
+
* source uri → the slot paths it fits, or `undefined` when there is none.
|
|
2388
|
+
*/
|
|
2389
|
+
function invertSlotMatches(byPath) {
|
|
2390
|
+
if (!byPath || Object.keys(byPath).length === 0) return void 0;
|
|
2391
|
+
const byUri = /* @__PURE__ */ new Map();
|
|
2392
|
+
for (const [slotPath, uris] of Object.entries(byPath)) for (const uri of uris) {
|
|
2393
|
+
const set = byUri.get(uri);
|
|
2394
|
+
if (set) set.add(slotPath);
|
|
2395
|
+
else byUri.set(uri, /* @__PURE__ */ new Set([slotPath]));
|
|
2396
|
+
}
|
|
2397
|
+
return byUri;
|
|
2398
|
+
}
|
|
2399
|
+
/**
|
|
2400
|
+
* `registered` as {@link InputSource}s for `matchSourcesToSlots`, carrying the
|
|
2401
|
+
* checker's type matches (see {@link invertSlotMatches}) where it has any.
|
|
2402
|
+
*/
|
|
2403
|
+
function toInputSources(registered, byType) {
|
|
2404
|
+
return registered.map((r) => {
|
|
2405
|
+
const fits = byType?.get(r.uri);
|
|
2406
|
+
return {
|
|
2407
|
+
uri: r.uri,
|
|
2408
|
+
key: r.key,
|
|
2409
|
+
for: r.for,
|
|
2410
|
+
fitsType: fits ? (_type, path) => fits.has(path) : void 0
|
|
2411
|
+
};
|
|
2412
|
+
});
|
|
574
2413
|
}
|
|
575
|
-
//#endregion
|
|
576
|
-
//#region src/prompt/file/file-prompt-provider.ts
|
|
577
|
-
const DEFAULT_IGNORE_PATTERNS = [
|
|
578
|
-
"**/node_modules/**",
|
|
579
|
-
"**/dist/**",
|
|
580
|
-
"**/.git/**"
|
|
581
|
-
];
|
|
582
|
-
let defaultIDCounter = 0;
|
|
583
2414
|
/**
|
|
584
2415
|
* A {@link PromptProvider} that discovers and serves prompts from
|
|
585
2416
|
* files on the local file system (or any {@link FileProvider}).
|
|
@@ -606,29 +2437,524 @@ var FilePromptProvider = class {
|
|
|
606
2437
|
fileProvider;
|
|
607
2438
|
includePatterns;
|
|
608
2439
|
ignorePatterns;
|
|
2440
|
+
playgroundIncludePatterns;
|
|
2441
|
+
playgroundIgnorePatterns;
|
|
609
2442
|
sdkAdapter;
|
|
610
|
-
|
|
2443
|
+
resources;
|
|
2444
|
+
/** Tail of the in-flight mutation chain per file (see {@link mutateFile}). */
|
|
2445
|
+
fileMutations = /* @__PURE__ */ new Map();
|
|
2446
|
+
/** Explicit adapters, `false` for off, `undefined` for the default. */
|
|
2447
|
+
versioningOption;
|
|
2448
|
+
variationStoreOption;
|
|
2449
|
+
/** Whether the defaults apply: files are on the real disk. */
|
|
2450
|
+
useDefaultVersioning;
|
|
2451
|
+
/** Versions and variations, set up on first use. */
|
|
2452
|
+
variationsReady;
|
|
2453
|
+
/** Everyone {@link watch}ing, for changes that aren't file events. */
|
|
2454
|
+
listeners = /* @__PURE__ */ new Set();
|
|
2455
|
+
/**
|
|
2456
|
+
* Versions of this provider's prompts: git commits. Absent when versioning
|
|
2457
|
+
* is turned off; a method rejects when the default turns out to be
|
|
2458
|
+
* unavailable (outside a repository).
|
|
2459
|
+
*/
|
|
2460
|
+
versions;
|
|
2461
|
+
/**
|
|
2462
|
+
* Variations of this provider's prompts: unsaved edits, and named
|
|
2463
|
+
* alternatives. Absent when turned off; a method rejects when the default
|
|
2464
|
+
* store turns out to be unavailable.
|
|
2465
|
+
*/
|
|
2466
|
+
variations;
|
|
2467
|
+
constructor({ id = "fs" + (defaultIDCounter++ ? defaultIDCounter : ""), rootDir = process.cwd(), fileProvider, fileType, includePatterns, ignorePatterns = [], playgroundIncludePatterns = DEFAULT_PLAYGROUND_INCLUDE_PATTERNS, sdk, versioning, variationStore }) {
|
|
2468
|
+
this.useDefaultVersioning = !fileProvider;
|
|
2469
|
+
fileProvider ??= new LocalFileProvider();
|
|
2470
|
+
this.versioningOption = versioning;
|
|
2471
|
+
this.variationStoreOption = variationStore;
|
|
611
2472
|
fileType ??= new TSPromptFileType(fileProvider);
|
|
612
2473
|
this.id = id;
|
|
613
2474
|
this.rootDir = rootDir;
|
|
614
2475
|
this.fileProvider = fileProvider;
|
|
615
2476
|
this.fileType = fileType;
|
|
616
2477
|
this.includePatterns = includePatterns ?? fileType.defaultIncludePatterns;
|
|
617
|
-
this.ignorePatterns = ignorePatterns;
|
|
2478
|
+
this.ignorePatterns = withDefaultIgnores(this.includePatterns, ignorePatterns);
|
|
2479
|
+
this.playgroundIncludePatterns = playgroundIncludePatterns;
|
|
2480
|
+
this.playgroundIgnorePatterns = withDefaultIgnores(playgroundIncludePatterns, [...DEFAULT_PLAYGROUND_IGNORE_PATTERNS, ...ignorePatterns]);
|
|
618
2481
|
this.sdkAdapter = sdk;
|
|
2482
|
+
this.resources = new ResourceRegistry({
|
|
2483
|
+
fileProvider,
|
|
2484
|
+
rootDir,
|
|
2485
|
+
includePatterns: playgroundIncludePatterns,
|
|
2486
|
+
ignorePatterns: this.playgroundIgnorePatterns
|
|
2487
|
+
});
|
|
2488
|
+
this.versions = this.versioningPossible ? this.deferredVersions() : void 0;
|
|
2489
|
+
this.variations = this.storePossible ? this.deferredVariations() : void 0;
|
|
619
2490
|
}
|
|
620
2491
|
async getAllPrompts() {
|
|
621
2492
|
await this.ensureFiles();
|
|
622
|
-
|
|
2493
|
+
const prompts = await this.normalizeAll(this.files);
|
|
2494
|
+
const variations = await this.fileVariations();
|
|
2495
|
+
return variations ? variations.annotateAll(prompts) : prompts;
|
|
623
2496
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
2497
|
+
/** The absolute path of the file `prompt` is defined in. */
|
|
2498
|
+
getSourcePath(prompt) {
|
|
2499
|
+
const relative = prompt.metadata?.relativeFilePath;
|
|
2500
|
+
return relative ? path.join(this.rootDir, relative) : void 0;
|
|
627
2501
|
}
|
|
628
|
-
async
|
|
629
|
-
const
|
|
630
|
-
if (
|
|
2502
|
+
async getPrompt(ref) {
|
|
2503
|
+
const variations = await this.fileVariations();
|
|
2504
|
+
if (variations) return variations.getPrompt(ref);
|
|
2505
|
+
const r = toPromptRef(ref);
|
|
2506
|
+
if (r.version !== void 0 || r.variation !== void 0) return null;
|
|
2507
|
+
return this.headPrompt(r.promptId);
|
|
2508
|
+
}
|
|
2509
|
+
/** The prompt as it is on disk, unannotated. */
|
|
2510
|
+
async headPrompt(id) {
|
|
2511
|
+
const [filePath, name] = this.parsePromptId(id);
|
|
2512
|
+
return (await this.normalizeAll([filePath]).catch(() => [])).find((p) => p.name === name) ?? null;
|
|
2513
|
+
}
|
|
2514
|
+
/**
|
|
2515
|
+
* Whether versions can be set up at all: off when turned off, and when a
|
|
2516
|
+
* custom file provider left nothing to default to.
|
|
2517
|
+
*/
|
|
2518
|
+
get versioningPossible() {
|
|
2519
|
+
if (this.versioningOption === false) return false;
|
|
2520
|
+
return !!this.versioningOption || this.useDefaultVersioning;
|
|
2521
|
+
}
|
|
2522
|
+
/** Whether variations can be set up at all, as {@link versioningPossible}. */
|
|
2523
|
+
get storePossible() {
|
|
2524
|
+
return this.variationStoreOption === void 0 ? this.useDefaultVersioning : !!this.variationStoreOption;
|
|
2525
|
+
}
|
|
2526
|
+
/**
|
|
2527
|
+
* This provider's versions and variations, set up on first use — which is
|
|
2528
|
+
* where the defaults are decided, since finding a repository takes a `git`
|
|
2529
|
+
* call. `undefined` when there are none.
|
|
2530
|
+
*/
|
|
2531
|
+
fileVariations() {
|
|
2532
|
+
if (!this.versioningPossible && !this.storePossible) return Promise.resolve(void 0);
|
|
2533
|
+
this.variationsReady ??= this.setUpVariations().catch((err) => {
|
|
2534
|
+
console.warn("⚠️ prompt versions are unavailable:", err?.message ?? err);
|
|
2535
|
+
});
|
|
2536
|
+
return this.variationsReady;
|
|
2537
|
+
}
|
|
2538
|
+
async setUpVariations() {
|
|
2539
|
+
let store = this.variationStoreOption || void 0;
|
|
2540
|
+
if (!store && this.variationStoreOption === void 0 && this.useDefaultVersioning) {
|
|
2541
|
+
const { LocalVariationStore } = await Promise.resolve().then(() => local_variation_store_exports);
|
|
2542
|
+
store = new LocalVariationStore(path.join(this.rootDir, ".evalution", "variations", "variations.db"));
|
|
2543
|
+
}
|
|
2544
|
+
let versioning = this.versioningOption || void 0;
|
|
2545
|
+
if (!versioning && this.versioningOption === void 0 && this.useDefaultVersioning) {
|
|
2546
|
+
const { GitVersioning } = await Promise.resolve().then(() => git_versioning_exports);
|
|
2547
|
+
versioning = await GitVersioning.detect(this.rootDir);
|
|
2548
|
+
}
|
|
2549
|
+
if (!versioning && !store) return void 0;
|
|
2550
|
+
return new FileVariations({
|
|
2551
|
+
rootDir: this.rootDir,
|
|
2552
|
+
fileProvider: this.fileProvider,
|
|
2553
|
+
fileType: this.fileType,
|
|
2554
|
+
parsePromptId: (id) => this.parsePromptId(id),
|
|
2555
|
+
parseAll: async () => {
|
|
2556
|
+
await this.ensureFiles();
|
|
2557
|
+
return this.normalizeAll(this.files);
|
|
2558
|
+
},
|
|
2559
|
+
normalizeWith: (fileType, files, options) => this.normalizeAll(files, fileType, options),
|
|
2560
|
+
applyUpdates: (fileType, filePath, promptName, promptId, updates) => this.applyUpdates(fileType, filePath, promptName, promptId, updates),
|
|
2561
|
+
mutateFile: (filePath, mutate) => this.mutateFile(filePath, mutate),
|
|
2562
|
+
emit: (event) => this.emit(event)
|
|
2563
|
+
}, versioning, store);
|
|
2564
|
+
}
|
|
2565
|
+
emit(event) {
|
|
2566
|
+
for (const listener of this.listeners) listener(event);
|
|
2567
|
+
}
|
|
2568
|
+
/** {@link versions}, forwarding to {@link fileVariations} once it's set up. */
|
|
2569
|
+
deferredVersions() {
|
|
2570
|
+
const ready = async () => {
|
|
2571
|
+
const variations = await this.fileVariations();
|
|
2572
|
+
if (!variations?.versioning) throw new Error("Prompt versions are unavailable");
|
|
2573
|
+
return variations.versions;
|
|
2574
|
+
};
|
|
2575
|
+
return {
|
|
2576
|
+
head: async () => (await ready()).head(),
|
|
2577
|
+
history: async (promptId, options) => (await ready()).history(promptId, options),
|
|
2578
|
+
get: async (id) => (await ready()).get(id)
|
|
2579
|
+
};
|
|
2580
|
+
}
|
|
2581
|
+
/** {@link variations}, forwarding to {@link fileVariations} once it's set up. */
|
|
2582
|
+
deferredVariations() {
|
|
2583
|
+
const ready = async () => {
|
|
2584
|
+
const variations = await this.fileVariations();
|
|
2585
|
+
if (!variations?.store) throw new Error("Prompt variations are unavailable");
|
|
2586
|
+
return variations.variations;
|
|
2587
|
+
};
|
|
2588
|
+
return {
|
|
2589
|
+
get: async (id) => (await ready()).get(id),
|
|
2590
|
+
list: async (promptId) => (await ready()).list(promptId),
|
|
2591
|
+
name: async (id, name) => (await ready()).name(id, name),
|
|
2592
|
+
unname: async (promptId, name) => (await ready()).unname(promptId, name),
|
|
2593
|
+
rename: async (promptId, from, to) => (await ready()).rename(promptId, from, to),
|
|
2594
|
+
rebase: async (id, onto) => (await ready()).rebase(id, onto),
|
|
2595
|
+
openOnHead: async (id, options) => (await ready()).openOnHead(id, options),
|
|
2596
|
+
openVersionOnHead: async (promptId, version, options) => (await ready()).openVersionOnHead(promptId, version, options),
|
|
2597
|
+
save: async (id) => (await ready()).save(id),
|
|
2598
|
+
discard: async (id) => (await ready()).discard(id),
|
|
2599
|
+
resolve: async (id, choices) => (await ready()).resolve(id, choices)
|
|
2600
|
+
};
|
|
2601
|
+
}
|
|
2602
|
+
/**
|
|
2603
|
+
* Parse `files` and normalize every prompt in them.
|
|
2604
|
+
*
|
|
2605
|
+
* Two TypeScript program builds, however many prompts and resources: one to
|
|
2606
|
+
* parse, and one that answers every type question normalization asks —
|
|
2607
|
+
* execute parameter probes, which resources fit each prompt's slots, and the
|
|
2608
|
+
* types and slots of resources' own arguments. Each build brings a fresh
|
|
2609
|
+
* checker that re-derives every type the files depend on, so a question
|
|
2610
|
+
* asked in a build of its own costs far more than the same question batched.
|
|
2611
|
+
*/
|
|
2612
|
+
async normalizeAll(files, fileType = this.fileType, { resolveTypes = true } = {}) {
|
|
2613
|
+
const playgroundFiles = await this.resources.modulePaths();
|
|
2614
|
+
const parsed = await fileType.parsePrompts(files, this.rootDir, { companionFiles: playgroundFiles });
|
|
2615
|
+
if (!resolveTypes) {
|
|
2616
|
+
const project = await this.resolveProjectProbes();
|
|
2617
|
+
return parsed.map((p) => ({
|
|
2618
|
+
...this.sdkAdapter.normalizePrompt(p, void 0, project),
|
|
2619
|
+
metadata: p.metadata
|
|
2620
|
+
}));
|
|
2621
|
+
}
|
|
2622
|
+
const probes = this.promptProbes(parsed);
|
|
2623
|
+
const scope = await this.resourceScope(parsed);
|
|
2624
|
+
const executeRequests = this.promptProbeRequests(parsed, probes);
|
|
2625
|
+
const parameterRequests = scope ? this.resourceParameterRequests(scope.withParams) : [];
|
|
2626
|
+
const promptSlotRequests = scope ? this.promptSlotRequests(parsed, scope.inScope, probes) : [];
|
|
2627
|
+
const resourceSlotRequests = scope ? this.resourceSlotRequests(scope.withParams) : [];
|
|
2628
|
+
const resolved = await this.resolveTypes([...executeRequests, ...parameterRequests], [...promptSlotRequests, ...resourceSlotRequests], this.projectProbes(), fileType);
|
|
2629
|
+
const project = this.projectResults(resolved.project);
|
|
2630
|
+
const executeParameters = this.assemblePromptProbes(probes, resolved.probes?.slice(0, executeRequests.length));
|
|
2631
|
+
const inputSources = scope ? this.assembleInputSources(parsed, scope, executeParameters, {
|
|
2632
|
+
typeMatches: this.assembleTypeMatches(parsed, resolved.slotMatches?.slice(0, promptSlotRequests.length)),
|
|
2633
|
+
resourceParameters: this.assembleResourceParameters(scope.withParams, resolved.probes?.slice(executeRequests.length)),
|
|
2634
|
+
resourceSlotMatches: resolved.slotMatches?.slice(promptSlotRequests.length)
|
|
2635
|
+
}) : parsed.map(() => void 0);
|
|
2636
|
+
return parsed.map((p, i) => {
|
|
2637
|
+
return {
|
|
2638
|
+
...this.sdkAdapter.normalizePrompt(p, executeParameters[i], project),
|
|
2639
|
+
metadata: p.metadata,
|
|
2640
|
+
...inputSources[i] ? { inputSources: inputSources[i] } : {}
|
|
2641
|
+
};
|
|
2642
|
+
});
|
|
2643
|
+
}
|
|
2644
|
+
/**
|
|
2645
|
+
* Put every type question to the file type at once, so they share one
|
|
2646
|
+
* program build. A list comes back `undefined` when the file type cannot
|
|
2647
|
+
* answer that kind of question at all, which callers degrade from rather
|
|
2648
|
+
* than reading as "no answer".
|
|
2649
|
+
*/
|
|
2650
|
+
async resolveTypes(probes, slotMatches, project, fileType = this.fileType) {
|
|
2651
|
+
if (fileType.resolveTypes) return fileType.resolveTypes({
|
|
2652
|
+
probes,
|
|
2653
|
+
slotMatches,
|
|
2654
|
+
...project?.length && { project: {
|
|
2655
|
+
rootDir: this.rootDir,
|
|
2656
|
+
probes: project
|
|
2657
|
+
} }
|
|
2658
|
+
});
|
|
2659
|
+
return {
|
|
2660
|
+
probes: fileType.resolveTypeProbes ? await fileType.resolveTypeProbes(probes) : void 0,
|
|
2661
|
+
slotMatches: fileType.resolveSlotMatches ? await fileType.resolveSlotMatches(slotMatches) : void 0
|
|
2662
|
+
};
|
|
2663
|
+
}
|
|
2664
|
+
/**
|
|
2665
|
+
* What the SDK wants to know about the project as a whole — the installed
|
|
2666
|
+
* SDK's own types — asked in the file type's language.
|
|
2667
|
+
*/
|
|
2668
|
+
projectProbes() {
|
|
2669
|
+
return this.sdkAdapter.getProjectProbes?.(this.fileType.language) ?? [];
|
|
2670
|
+
}
|
|
2671
|
+
/**
|
|
2672
|
+
* The project probes' results, with an `undefined` ("could not evaluate")
|
|
2673
|
+
* for every probe the file type didn't answer, so an adapter always sees
|
|
2674
|
+
* each probe it asked for.
|
|
2675
|
+
*/
|
|
2676
|
+
projectResults(resolved) {
|
|
2677
|
+
return Object.fromEntries(this.projectProbes().map((p) => [p.name, resolved?.[p.name]]));
|
|
2678
|
+
}
|
|
2679
|
+
/**
|
|
2680
|
+
* Resolve just the project probes — for adapter methods that need them
|
|
2681
|
+
* outside a normalization pass, like the model definition. Cheap after the
|
|
2682
|
+
* first call: the file type caches them.
|
|
2683
|
+
*/
|
|
2684
|
+
async resolveProjectProbes() {
|
|
2685
|
+
const probes = this.projectProbes();
|
|
2686
|
+
if (probes.length === 0) return {};
|
|
2687
|
+
const resolved = await this.resolveTypes([], [], probes);
|
|
2688
|
+
return this.projectResults(resolved.project);
|
|
2689
|
+
}
|
|
2690
|
+
/**
|
|
2691
|
+
* What the SDK says it wants to know about each prompt — chiefly what it
|
|
2692
|
+
* needs at run time — one list per prompt.
|
|
2693
|
+
*
|
|
2694
|
+
* The file type declares the language and the adapter is asked *in* it, so
|
|
2695
|
+
* an adapter that cannot write the expression says so by returning nothing
|
|
2696
|
+
* rather than emitting a variant per language and hoping.
|
|
2697
|
+
*/
|
|
2698
|
+
promptProbes(parsed) {
|
|
2699
|
+
const getProbes = this.sdkAdapter.getPromptProbes;
|
|
2700
|
+
if (!getProbes) return parsed.map(() => []);
|
|
2701
|
+
const language = this.fileType.language;
|
|
2702
|
+
return parsed.map((p) => getProbes.call(this.sdkAdapter, p, language));
|
|
2703
|
+
}
|
|
2704
|
+
/**
|
|
2705
|
+
* Ask the file type to answer what the SDK asked about each prompt —
|
|
2706
|
+
* the second half of the §E negotiation, with this provider as the only
|
|
2707
|
+
* place the two meet. Flattened across prompts, in order.
|
|
2708
|
+
*
|
|
2709
|
+
* A probe is written defensively enough not to need the parse result to
|
|
2710
|
+
* decide whether to ask, which is what makes batching them possible.
|
|
2711
|
+
*/
|
|
2712
|
+
promptProbeRequests(parsed, perPrompt) {
|
|
2713
|
+
return parsed.flatMap((prompt, i) => perPrompt[i].map((probe) => ({
|
|
2714
|
+
probe,
|
|
2715
|
+
filePath: this.absolutePathOf(prompt),
|
|
2716
|
+
promptName: prompt.name
|
|
2717
|
+
})));
|
|
2718
|
+
}
|
|
2719
|
+
/**
|
|
2720
|
+
* Split the answers to {@link promptProbeRequests} back into one list per
|
|
2721
|
+
* prompt.
|
|
2722
|
+
*
|
|
2723
|
+
* Without a resolver the adapter still hears about its own probes — as a
|
|
2724
|
+
* row of `undefined`s, which it reads as "declared but unresolved" rather
|
|
2725
|
+
* than as "no requirement". Degrading to silence here is exactly the bug
|
|
2726
|
+
* this machinery exists to prevent.
|
|
2727
|
+
*/
|
|
2728
|
+
assemblePromptProbes(perPrompt, resolved) {
|
|
2729
|
+
let cursor = 0;
|
|
2730
|
+
return perPrompt.map((probes) => {
|
|
2731
|
+
if (probes.length === 0) return void 0;
|
|
2732
|
+
const start = cursor;
|
|
2733
|
+
cursor += probes.length;
|
|
2734
|
+
return resolved ? resolved.slice(start, cursor) : probes.map(() => void 0);
|
|
2735
|
+
});
|
|
2736
|
+
}
|
|
2737
|
+
/**
|
|
2738
|
+
* The resources each prompt can draw on, or `undefined` when there are no
|
|
2739
|
+
* playground resources (nor modules that failed to load) at all.
|
|
2740
|
+
*/
|
|
2741
|
+
async resourceScope(parsed) {
|
|
2742
|
+
const all = await this.resources.all();
|
|
2743
|
+
const moduleErrors = await this.resources.errors();
|
|
2744
|
+
if (all.length === 0 && moduleErrors.length === 0) return void 0;
|
|
2745
|
+
const inScope = await Promise.all(parsed.map((p) => this.resources.inScopeFor(this.absolutePathOf(p))));
|
|
2746
|
+
const byResource = new Map(all.map((r) => [r.resource, r]));
|
|
2747
|
+
const withParams = [];
|
|
2748
|
+
for (const resource of all) {
|
|
2749
|
+
const names = resourceParameterNames(resource.resource);
|
|
2750
|
+
if (names.length === 0) continue;
|
|
2751
|
+
const candidates = (await this.resources.inScopeFor(resource.modulePath)).filter((s) => !dependsOn(s.resource, resource, byResource));
|
|
2752
|
+
withParams.push({
|
|
2753
|
+
resource,
|
|
2754
|
+
names,
|
|
2755
|
+
candidates
|
|
2756
|
+
});
|
|
2757
|
+
}
|
|
2758
|
+
return {
|
|
2759
|
+
moduleErrors,
|
|
2760
|
+
inScope,
|
|
2761
|
+
withParams
|
|
2762
|
+
};
|
|
2763
|
+
}
|
|
2764
|
+
/**
|
|
2765
|
+
* Work out which resources can fill which of each prompt's input slots.
|
|
2766
|
+
*
|
|
2767
|
+
* Three strategies, first match wins (see `matchSourcesToSlots`). The type
|
|
2768
|
+
* strategy's answers come from the file type, which is where a checker
|
|
2769
|
+
* lives; explicit and name matching are decided here, since neither needs
|
|
2770
|
+
* one.
|
|
2771
|
+
*/
|
|
2772
|
+
assembleInputSources(parsed, scope, executeParameters, { typeMatches, resourceParameters, resourceSlotMatches }) {
|
|
2773
|
+
const resourceSlots = this.assembleResourceSlots(scope.withParams, resourceParameters, resourceSlotMatches);
|
|
2774
|
+
return parsed.map((prompt, i) => {
|
|
2775
|
+
const available = scope.inScope[i];
|
|
2776
|
+
const sources = toInputSources(available, typeMatches[i]);
|
|
2777
|
+
const functionSlots = matchSourcesToSlots(collectInputSlots(prompt.functionParameters), sources, prompt.name);
|
|
2778
|
+
const executeSlots = matchSourcesToSlots(collectInputSlots((executeParameters[i] ?? []).filter(isDefinition)), sources, prompt.name);
|
|
2779
|
+
const describedResources = this.resources.describe(available).map((info) => {
|
|
2780
|
+
const parameters = resourceParameters.get(info.uri);
|
|
2781
|
+
return parameters ? {
|
|
2782
|
+
...info,
|
|
2783
|
+
parameters
|
|
2784
|
+
} : info;
|
|
2785
|
+
});
|
|
2786
|
+
const promptResourceSlots = {};
|
|
2787
|
+
for (const r of available) {
|
|
2788
|
+
if (r.outputPath.length > 0) continue;
|
|
2789
|
+
const slots = resourceSlots.get(r.uri);
|
|
2790
|
+
if (slots && Object.keys(slots).length > 0) promptResourceSlots[r.uri] = slots;
|
|
2791
|
+
}
|
|
2792
|
+
return {
|
|
2793
|
+
resources: [...describedResources, ...scope.moduleErrors.map((e) => ({
|
|
2794
|
+
uri: path.relative(this.rootDir, e.modulePath),
|
|
2795
|
+
label: path.basename(e.modulePath),
|
|
2796
|
+
scope: "run",
|
|
2797
|
+
error: e.message
|
|
2798
|
+
}))],
|
|
2799
|
+
functionSlots,
|
|
2800
|
+
executeSlots,
|
|
2801
|
+
...Object.keys(promptResourceSlots).length > 0 ? { resourceSlots: promptResourceSlots } : {}
|
|
2802
|
+
};
|
|
2803
|
+
});
|
|
2804
|
+
}
|
|
2805
|
+
/**
|
|
2806
|
+
* One probe per declared resource argument, flattened across resources in
|
|
2807
|
+
* order.
|
|
2808
|
+
*
|
|
2809
|
+
* Asked once across every resource rather than once per prompt: a
|
|
2810
|
+
* resource's arguments don't depend on which prompt is looking at it. See
|
|
2811
|
+
* `specs/resource-arguments.md` §H.
|
|
2812
|
+
*/
|
|
2813
|
+
resourceParameterRequests(withParams) {
|
|
2814
|
+
return withParams.flatMap(({ resource, names }) => names.map((name) => ({
|
|
2815
|
+
probe: {
|
|
2816
|
+
kind: "type",
|
|
2817
|
+
name,
|
|
2818
|
+
expression: resourceParameterTypeExpression(resource, name)
|
|
2819
|
+
},
|
|
2820
|
+
filePath: resource.modulePath,
|
|
2821
|
+
promptName: resource.key
|
|
2822
|
+
})));
|
|
2823
|
+
}
|
|
2824
|
+
/**
|
|
2825
|
+
* The names and — where a checker is available — resolved types of every
|
|
2826
|
+
* discovered resource's declared arguments, keyed by the resource's `uri`.
|
|
2827
|
+
*
|
|
2828
|
+
* Without a checker, the schema-valued keys are still enumerable at
|
|
2829
|
+
* runtime — `resourceParameterNames` doesn't need one — so a resource with
|
|
2830
|
+
* arguments still reports their names, each with an unresolved type and a
|
|
2831
|
+
* plain string editor (see `unresolvedParameter`) rather than being absent. That degradation, and the resolved case
|
|
2832
|
+
* both, are what let `ResourceInfo.parameters` (§G) exist at all.
|
|
2833
|
+
*/
|
|
2834
|
+
assembleResourceParameters(withParams, resolved) {
|
|
2835
|
+
let cursor = 0;
|
|
2836
|
+
return new Map(withParams.map(({ resource, names }) => {
|
|
2837
|
+
const start = cursor;
|
|
2838
|
+
cursor += names.length;
|
|
2839
|
+
return [resource.uri, names.map((name, j) => {
|
|
2840
|
+
const result = resolved?.[start + j];
|
|
2841
|
+
return isDefinition(result) ? result : unresolvedParameter(name);
|
|
2842
|
+
})];
|
|
2843
|
+
}));
|
|
2844
|
+
}
|
|
2845
|
+
/**
|
|
2846
|
+
* The §D.2 type strategy: hand the file type a type expression per resource
|
|
2847
|
+
* and let its checker decide assignability. Empty when no prompt has a
|
|
2848
|
+
* source in scope, so there is nothing to ask.
|
|
2849
|
+
*
|
|
2850
|
+
* The expression reads the resource's produced type back off its own
|
|
2851
|
+
* `create()`, which is where the type came from — so there is no type string
|
|
2852
|
+
* on a resource to go stale under a rename, and no second mechanism to read.
|
|
2853
|
+
*/
|
|
2854
|
+
promptSlotRequests(parsed, inScope, probes) {
|
|
2855
|
+
const requests = parsed.map((prompt, i) => {
|
|
2856
|
+
const filePath = this.absolutePathOf(prompt);
|
|
2857
|
+
return {
|
|
2858
|
+
filePath,
|
|
2859
|
+
promptName: prompt.name,
|
|
2860
|
+
extraSlots: Object.fromEntries(probes[i].flatMap((probe) => probe.kind === "type" ? [[probe.name, probe.expression]] : [])),
|
|
2861
|
+
sources: inScope[i].map((r) => ({
|
|
2862
|
+
key: r.uri,
|
|
2863
|
+
expression: resourceTypeExpression(filePath, r)
|
|
2864
|
+
}))
|
|
2865
|
+
};
|
|
2866
|
+
});
|
|
2867
|
+
return requests.every((r) => r.sources.length === 0) ? [] : requests;
|
|
2868
|
+
}
|
|
2869
|
+
/**
|
|
2870
|
+
* Turn each prompt's answer to {@link promptSlotRequests} (slot path →
|
|
2871
|
+
* source uris) around into source uri → the slot paths it fits.
|
|
2872
|
+
*/
|
|
2873
|
+
assembleTypeMatches(parsed, matched) {
|
|
2874
|
+
return parsed.map((_, i) => invertSlotMatches(matched?.[i]));
|
|
2875
|
+
}
|
|
2876
|
+
/**
|
|
2877
|
+
* Which sources can fill which of each resource's own argument slots — the
|
|
2878
|
+
* §H "resourceSlots" half of matching, asked once across every resource
|
|
2879
|
+
* (arguments are prompt-independent) against each one's candidates.
|
|
2880
|
+
*/
|
|
2881
|
+
resourceSlotRequests(withParams) {
|
|
2882
|
+
return withParams.map(({ resource, names, candidates }) => ({
|
|
2883
|
+
filePath: resource.modulePath,
|
|
2884
|
+
promptName: resource.key,
|
|
2885
|
+
sources: candidates.map((s) => ({
|
|
2886
|
+
key: s.uri,
|
|
2887
|
+
expression: resourceTypeExpression(resource.modulePath, s)
|
|
2888
|
+
})),
|
|
2889
|
+
extraSlots: Object.fromEntries(names.map((name) => [name, resourceParameterTypeExpression(resource, name)]))
|
|
2890
|
+
}));
|
|
2891
|
+
}
|
|
2892
|
+
/**
|
|
2893
|
+
* Which sources can fill which of each resource's own argument slots, keyed
|
|
2894
|
+
* by the resource's `uri` — by the same three strategies a prompt's own
|
|
2895
|
+
* slots use (see {@link assembleInputSources}), with the file type's answers
|
|
2896
|
+
* to {@link resourceSlotRequests} as the type strategy.
|
|
2897
|
+
*/
|
|
2898
|
+
assembleResourceSlots(withParams, parameters, matched) {
|
|
2899
|
+
return new Map(withParams.map(({ resource, candidates }, i) => [resource.uri, matchSourcesToSlots(collectInputSlots(parameters.get(resource.uri) ?? []), toInputSources(candidates, invertSlotMatches(matched?.[i])), resource.key)]));
|
|
2900
|
+
}
|
|
2901
|
+
absolutePathOf(prompt) {
|
|
2902
|
+
return path.join(this.rootDir, prompt.metadata.relativeFilePath);
|
|
2903
|
+
}
|
|
2904
|
+
/**
|
|
2905
|
+
* Runs `mutate` once every earlier mutation of `filePath` has settled.
|
|
2906
|
+
*
|
|
2907
|
+
* Every edit is a read-modify-write of the whole file — parse it, splice the
|
|
2908
|
+
* new value into the spans that parse reported, write it back. Two that
|
|
2909
|
+
* overlap (the editor saves faster than a save completes) leave the second
|
|
2910
|
+
* reading a file the first is in the middle of writing: a write truncates
|
|
2911
|
+
* before it fills, so that read can land on an empty or partial file, whose
|
|
2912
|
+
* parse finds no prompt of that name and reports "Prompt not found". Editing
|
|
2913
|
+
* one file at a time is enough to keep each edit's read and write adjacent;
|
|
2914
|
+
* edits to different files still run concurrently.
|
|
2915
|
+
*/
|
|
2916
|
+
mutateFile(filePath, mutate) {
|
|
2917
|
+
const result = (this.fileMutations.get(filePath) ?? Promise.resolve()).then(mutate, mutate);
|
|
2918
|
+
const settled = result.then(() => {}, () => {});
|
|
2919
|
+
this.fileMutations.set(filePath, settled);
|
|
2920
|
+
settled.then(() => {
|
|
2921
|
+
if (this.fileMutations.get(filePath) === settled) this.fileMutations.delete(filePath);
|
|
2922
|
+
});
|
|
2923
|
+
return result;
|
|
2924
|
+
}
|
|
2925
|
+
/**
|
|
2926
|
+
* Applies `updates` to the prompt `ref` names.
|
|
2927
|
+
*
|
|
2928
|
+
* With variations, this never writes the file: the edit lands in the
|
|
2929
|
+
* work-in-progress variation for `ref`'s base — created on the first edit,
|
|
2930
|
+
* deleted once edits cancel out — and the returned ref names it. Writing the
|
|
2931
|
+
* file is {@link PromptVariations.save}. A saved variation is read-only;
|
|
2932
|
+
* open it on the working tree to edit it. Without variations, the file is
|
|
2933
|
+
* written as the edit arrives.
|
|
2934
|
+
*/
|
|
2935
|
+
async updatePromptProperties(ref, updates) {
|
|
2936
|
+
const variations = await this.fileVariations();
|
|
2937
|
+
if (variations?.store) return variations.update(ref, updates);
|
|
2938
|
+
const r = toPromptRef(ref);
|
|
2939
|
+
if (r.version !== void 0 || r.variation !== void 0) throw new Error("This provider has no variations to edit");
|
|
2940
|
+
const promptId = r.promptId;
|
|
631
2941
|
const [filePath, promptName] = this.parsePromptId(promptId);
|
|
2942
|
+
return {
|
|
2943
|
+
prompt: await this.mutateFile(filePath, async () => {
|
|
2944
|
+
await this.applyUpdates(this.fileType, filePath, promptName, promptId, updates);
|
|
2945
|
+
return await this.getPrompt(promptId);
|
|
2946
|
+
}),
|
|
2947
|
+
ref: { promptId }
|
|
2948
|
+
};
|
|
2949
|
+
}
|
|
2950
|
+
/**
|
|
2951
|
+
* Writes `updates` into a prompt's source through `fileType` — the one
|
|
2952
|
+
* implementation of "apply updates to source", used to save to disk and to
|
|
2953
|
+
* materialize a variation in an overlay alike.
|
|
2954
|
+
*/
|
|
2955
|
+
async applyUpdates(fileType, filePath, promptName, promptId, updates) {
|
|
2956
|
+
const parsed = (await fileType.parsePrompts([filePath], this.rootDir).catch(() => [])).find((p) => p.name === promptName);
|
|
2957
|
+
if (!parsed) throw new Error("Prompt not found");
|
|
632
2958
|
const { definitions, values } = parsed.extractedProps;
|
|
633
2959
|
const rawUpdates = this.sdkAdapter.denormalizeUpdates(updates, values);
|
|
634
2960
|
for (const [propertyName, value] of Object.entries(rawUpdates)) {
|
|
@@ -636,48 +2962,188 @@ var FilePromptProvider = class {
|
|
|
636
2962
|
const currentValue = values?.[propertyName];
|
|
637
2963
|
if (value === null) {
|
|
638
2964
|
if (!propDef) throw new Error(`Property '${propertyName}' not found`);
|
|
639
|
-
await
|
|
640
|
-
} else if (!propDef) await
|
|
2965
|
+
await fileType.removeProperty(filePath, propDef);
|
|
2966
|
+
} else if (!propDef) await fileType.addProperty(filePath, promptName, propertyName, value);
|
|
641
2967
|
else {
|
|
642
2968
|
if (currentValue && !isEditable(currentValue)) throw new Error(`Property '${propertyName}' is not editable`);
|
|
643
2969
|
if (!propDef.valueSpan) throw new Error(`Property '${propertyName}' is missing source metadata`);
|
|
644
|
-
await
|
|
2970
|
+
await fileType.updateProperty(filePath, propDef, value, promptId);
|
|
645
2971
|
}
|
|
646
2972
|
}
|
|
647
|
-
return await this.getPrompt(promptId);
|
|
648
2973
|
}
|
|
649
|
-
async
|
|
650
|
-
|
|
651
|
-
|
|
2974
|
+
async getModelDefinition(style) {
|
|
2975
|
+
return this.sdkAdapter.getModelDefinition(await this.resolveProjectProbes(), style);
|
|
2976
|
+
}
|
|
2977
|
+
getModelParameters() {
|
|
2978
|
+
return this.sdkAdapter.getModelParameters(this.rootDir);
|
|
2979
|
+
}
|
|
2980
|
+
async resolveInputs(_ref, inputs, context) {
|
|
2981
|
+
const lease = this.resources.lease();
|
|
2982
|
+
const resolveMore = async (more) => Object.fromEntries(await Promise.all(Object.entries(more).map(async ([name, input]) => [name, await resolveExecutionInput(input, lease, context)])));
|
|
652
2983
|
try {
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
2984
|
+
const { functionParams, executeValues } = await resolveExecutionInputs(inputs, lease, context);
|
|
2985
|
+
return {
|
|
2986
|
+
functionParams,
|
|
2987
|
+
executeValues,
|
|
2988
|
+
receipts: lease.receipts(),
|
|
2989
|
+
resolveMore,
|
|
2990
|
+
prepareCheck: async (uri, args) => {
|
|
2991
|
+
const target = builtinCheck(uri) ?? (await this.resources.checks()).find((c) => c.uri === uri)?.check;
|
|
2992
|
+
if (!target) throw new Error(`Check '${uri}' not found`);
|
|
2993
|
+
const resolved = await lease.resolveDeclared(target.inputs, uri, () => resolveMore(args));
|
|
2994
|
+
return {
|
|
2995
|
+
run: (run) => target.run(resolved, run),
|
|
2996
|
+
timeoutMs: target.timeoutMs,
|
|
2997
|
+
runsOnError: target.runsOnError
|
|
2998
|
+
};
|
|
2999
|
+
},
|
|
3000
|
+
release: () => lease.release()
|
|
3001
|
+
};
|
|
3002
|
+
} catch (err) {
|
|
3003
|
+
await lease.release();
|
|
3004
|
+
throw err;
|
|
656
3005
|
}
|
|
657
|
-
return prompts.find((p) => p.name === name) || null;
|
|
658
3006
|
}
|
|
659
|
-
|
|
3007
|
+
/**
|
|
3008
|
+
* The built-in checks, plus every `check()` exported from a playground
|
|
3009
|
+
* module, with each one's schema inputs probed for their types the same
|
|
3010
|
+
* way a resource's arguments are (`specs/evals.md` §B.4). A module that
|
|
3011
|
+
* failed to load is listed with its error rather than hidden.
|
|
3012
|
+
*/
|
|
3013
|
+
async listChecks() {
|
|
3014
|
+
const registered = await this.resources.checks();
|
|
3015
|
+
const moduleErrors = await this.resources.errors();
|
|
3016
|
+
const broken = [];
|
|
3017
|
+
const withNames = registered.flatMap((c) => {
|
|
3018
|
+
try {
|
|
3019
|
+
return [{
|
|
3020
|
+
registered: c,
|
|
3021
|
+
names: resourceParameterNames(c.check)
|
|
3022
|
+
}];
|
|
3023
|
+
} catch (err) {
|
|
3024
|
+
broken.push({
|
|
3025
|
+
uri: c.uri,
|
|
3026
|
+
label: c.check.label ?? c.key,
|
|
3027
|
+
parameters: [],
|
|
3028
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3029
|
+
});
|
|
3030
|
+
return [];
|
|
3031
|
+
}
|
|
3032
|
+
});
|
|
3033
|
+
const requests = withNames.flatMap(({ registered: c, names }) => names.map((name) => ({
|
|
3034
|
+
probe: {
|
|
3035
|
+
kind: "type",
|
|
3036
|
+
name,
|
|
3037
|
+
expression: resourceParameterTypeExpression(c, name)
|
|
3038
|
+
},
|
|
3039
|
+
filePath: c.modulePath,
|
|
3040
|
+
promptName: c.key
|
|
3041
|
+
})));
|
|
3042
|
+
const resolved = requests.length > 0 ? await this.resolveTypes(requests, []) : {};
|
|
3043
|
+
let cursor = 0;
|
|
3044
|
+
const user = withNames.map(({ registered: c, names }) => {
|
|
3045
|
+
const start = cursor;
|
|
3046
|
+
cursor += names.length;
|
|
3047
|
+
return {
|
|
3048
|
+
uri: c.uri,
|
|
3049
|
+
label: c.check.label ?? c.key,
|
|
3050
|
+
...c.check.group && { group: c.check.group },
|
|
3051
|
+
...c.check.description && { description: c.check.description },
|
|
3052
|
+
...c.check.runsOnError && { runsOnError: true },
|
|
3053
|
+
parameters: names.map((name, j) => {
|
|
3054
|
+
const result = resolved.probes?.[start + j];
|
|
3055
|
+
return isDefinition(result) ? result : unresolvedParameter(name);
|
|
3056
|
+
})
|
|
3057
|
+
};
|
|
3058
|
+
});
|
|
3059
|
+
return [
|
|
3060
|
+
...builtinCheckInfos(),
|
|
3061
|
+
...user,
|
|
3062
|
+
...broken,
|
|
3063
|
+
...moduleErrors.map((e) => ({
|
|
3064
|
+
uri: path.relative(this.rootDir, e.modulePath),
|
|
3065
|
+
label: path.basename(e.modulePath),
|
|
3066
|
+
parameters: [],
|
|
3067
|
+
error: e.message
|
|
3068
|
+
}))
|
|
3069
|
+
];
|
|
3070
|
+
}
|
|
3071
|
+
/**
|
|
3072
|
+
* Runs the prompt `ref` names, on the working tree: a variation is carried
|
|
3073
|
+
* onto it first if made elsewhere. The commit checked out is recorded on
|
|
3074
|
+
* the trace as the version — when nothing is uncommitted, so the version
|
|
3075
|
+
* is what ran — along with the variation, and both are returned.
|
|
3076
|
+
*/
|
|
3077
|
+
async execute(ref, params, { traceId, rootSpanId, executeValues, inputs, onSettled } = {}) {
|
|
3078
|
+
const r = toPromptRef(ref);
|
|
3079
|
+
const variations = await this.fileVariations();
|
|
3080
|
+
if (!variations && (r.version !== void 0 || r.variation !== void 0)) throw new Error("This provider has no versions or variations to run");
|
|
3081
|
+
const prepared = variations ? await variations.prepareRun(r) : void 0;
|
|
3082
|
+
const variation = prepared?.variation;
|
|
3083
|
+
const promptId = variation?.promptId ?? r.promptId;
|
|
3084
|
+
const [filePath, promptName] = this.parsePromptId(promptId);
|
|
3085
|
+
const config = variation ? await variations.loadConfig(variation, params) : await this.fileType.loadConfig(filePath, promptName, params);
|
|
3086
|
+
const snapshot = await this.parameterSnapshot(promptId, variation);
|
|
3087
|
+
const version = prepared?.head?.clean ? prepared.head.commit?.id : void 0;
|
|
3088
|
+
const identity = {
|
|
3089
|
+
id: promptId,
|
|
3090
|
+
name: promptName,
|
|
3091
|
+
functionInputs: inputs?.functionInputs ? [...inputs.functionInputs] : void 0,
|
|
3092
|
+
executeInputs: inputs?.executeInputs,
|
|
3093
|
+
resources: inputs?.resources,
|
|
3094
|
+
parameterDefinitions: snapshot?.functionParameters,
|
|
3095
|
+
executeParameterDefinitions: snapshot?.executeParameters,
|
|
3096
|
+
version,
|
|
3097
|
+
variation: variation?.id
|
|
3098
|
+
};
|
|
3099
|
+
const handle = await this.sdkAdapter.executeConfig(config, {
|
|
3100
|
+
traceId,
|
|
3101
|
+
rootSpanId,
|
|
3102
|
+
executeValues,
|
|
3103
|
+
identity
|
|
3104
|
+
});
|
|
3105
|
+
if (onSettled) if (handle) handle.done.then(onSettled, onSettled);
|
|
3106
|
+
else onSettled();
|
|
660
3107
|
return {
|
|
661
|
-
...
|
|
662
|
-
|
|
3108
|
+
...version && { version },
|
|
3109
|
+
...variation && { variation: variation.id }
|
|
663
3110
|
};
|
|
664
3111
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
3112
|
+
/**
|
|
3113
|
+
* The prompt's parameter definitions as they stand right now, recorded
|
|
3114
|
+
* beside a run's inputs.
|
|
3115
|
+
*
|
|
3116
|
+
* Redundant whenever the run's recorded version can be read back, but a run
|
|
3117
|
+
* on a dirty working tree records no version, and the recorded signature
|
|
3118
|
+
* costs little. Replay then compares two known signatures instead
|
|
3119
|
+
* of inferring a match.
|
|
3120
|
+
*
|
|
3121
|
+
* Both halves are recorded: the execute parameters are only known after
|
|
3122
|
+
* normalization (their shapes come from type probes), and without them a
|
|
3123
|
+
* trace's `executeInputs` would have names but no types.
|
|
3124
|
+
*/
|
|
3125
|
+
async parameterSnapshot(promptId, variation) {
|
|
3126
|
+
try {
|
|
3127
|
+
const prompt = variation ? await (await this.fileVariations())?.preparedPrompt(variation) : await this.headPrompt(promptId);
|
|
3128
|
+
return prompt ? {
|
|
3129
|
+
functionParameters: prompt.functionParameters,
|
|
3130
|
+
executeParameters: prompt.executeParameters
|
|
3131
|
+
} : void 0;
|
|
3132
|
+
} catch {
|
|
3133
|
+
return;
|
|
3134
|
+
}
|
|
670
3135
|
}
|
|
671
|
-
async
|
|
672
|
-
|
|
673
|
-
const config = await this.fileType.loadConfig(filePath, promptName, params);
|
|
674
|
-
await this.sdkAdapter.executeConfig(config);
|
|
3136
|
+
async setupTraceIngestion() {
|
|
3137
|
+
return this.sdkAdapter.setupTraceIngestion?.();
|
|
675
3138
|
}
|
|
676
3139
|
async renamePrompt(promptId, newName) {
|
|
677
3140
|
const [filePath, oldName] = this.parsePromptId(promptId);
|
|
678
|
-
await this.
|
|
679
|
-
|
|
680
|
-
|
|
3141
|
+
const renamed = await this.mutateFile(filePath, async () => {
|
|
3142
|
+
await this.fileType.renamePrompt(filePath, oldName, newName);
|
|
3143
|
+
return `${path.relative(this.rootDir, filePath)}#${newName}`;
|
|
3144
|
+
});
|
|
3145
|
+
await (await this.fileVariations())?.onPromptRenamed(promptId, renamed);
|
|
3146
|
+
const prompt = await this.getPrompt(renamed);
|
|
681
3147
|
if (!prompt) throw new Error("Failed to find renamed prompt");
|
|
682
3148
|
return prompt;
|
|
683
3149
|
}
|
|
@@ -739,20 +3205,39 @@ var FilePromptProvider = class {
|
|
|
739
3205
|
] };
|
|
740
3206
|
}
|
|
741
3207
|
watch(callback) {
|
|
742
|
-
|
|
3208
|
+
this.listeners.add(callback);
|
|
3209
|
+
const unwatchPlayground = this.fileProvider.watch(this.playgroundIncludePatterns, {
|
|
3210
|
+
cwd: this.rootDir,
|
|
3211
|
+
ignored: this.playgroundIgnorePatterns
|
|
3212
|
+
}, async () => {
|
|
3213
|
+
(await this.fileVariations())?.invalidate();
|
|
3214
|
+
await this.resources.invalidate();
|
|
3215
|
+
try {
|
|
3216
|
+
for (const prompt of await this.getAllPrompts()) callback({
|
|
3217
|
+
type: "change",
|
|
3218
|
+
promptId: prompt.id
|
|
3219
|
+
});
|
|
3220
|
+
} catch (err) {
|
|
3221
|
+
console.warn("failed to refresh prompts after a playground change:", err);
|
|
3222
|
+
}
|
|
3223
|
+
});
|
|
3224
|
+
const unwatchPrompts = this.fileProvider.watch(this.includePatterns, {
|
|
743
3225
|
cwd: this.rootDir,
|
|
744
3226
|
ignored: this.ignorePatterns
|
|
745
3227
|
}, async (eventType, filePath) => {
|
|
746
3228
|
const absolutePath = this.resolveFilePath(filePath);
|
|
747
3229
|
if (eventType === "change" || eventType === "add") {
|
|
748
3230
|
if (this.files && !this.files.includes(absolutePath)) this.files.push(absolutePath);
|
|
749
|
-
|
|
3231
|
+
const prompts = await this.fileType.parsePrompts([absolutePath], this.rootDir);
|
|
3232
|
+
prompts.forEach((prompt) => {
|
|
750
3233
|
callback({
|
|
751
3234
|
type: eventType === "change" ? "change" : "add",
|
|
752
3235
|
promptId: prompt.id
|
|
753
3236
|
});
|
|
754
3237
|
});
|
|
3238
|
+
await (await this.fileVariations())?.onPromptsChanged(prompts.map((p) => p.id)).catch((err) => console.warn("failed to rebase unsaved edits:", err));
|
|
755
3239
|
} else {
|
|
3240
|
+
(await this.fileVariations())?.invalidate();
|
|
756
3241
|
if (this.files) this.files = this.files.filter((f) => f !== absolutePath);
|
|
757
3242
|
callback({
|
|
758
3243
|
type: "remove",
|
|
@@ -760,46 +3245,582 @@ var FilePromptProvider = class {
|
|
|
760
3245
|
});
|
|
761
3246
|
}
|
|
762
3247
|
});
|
|
3248
|
+
return () => {
|
|
3249
|
+
this.listeners.delete(callback);
|
|
3250
|
+
unwatchPlayground();
|
|
3251
|
+
unwatchPrompts();
|
|
3252
|
+
};
|
|
3253
|
+
}
|
|
3254
|
+
async ensureFiles() {
|
|
3255
|
+
if (!this.files) this.files = await Array.fromAsync(this.findPromptFiles());
|
|
3256
|
+
}
|
|
3257
|
+
async *findPromptFiles() {
|
|
3258
|
+
const uniqueFiles = /* @__PURE__ */ new Set();
|
|
3259
|
+
for (const pattern of this.includePatterns) {
|
|
3260
|
+
const iter = this.fileProvider.glob(pattern, {
|
|
3261
|
+
cwd: this.rootDir,
|
|
3262
|
+
absolute: true,
|
|
3263
|
+
ignore: this.ignorePatterns
|
|
3264
|
+
});
|
|
3265
|
+
for await (const file of iter) if (!uniqueFiles.has(file)) {
|
|
3266
|
+
uniqueFiles.add(file);
|
|
3267
|
+
yield file;
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
}
|
|
3271
|
+
parsePromptId(id) {
|
|
3272
|
+
const hashIdx = id.lastIndexOf("#");
|
|
3273
|
+
if (hashIdx < 0) throw new Error(`Invalid prompt ID format: ${id}`);
|
|
3274
|
+
const relativePath = id.slice(0, hashIdx);
|
|
3275
|
+
const functionName = id.slice(hashIdx + 1);
|
|
3276
|
+
return [path.isAbsolute(relativePath) ? relativePath : path.join(this.rootDir, relativePath), functionName];
|
|
3277
|
+
}
|
|
3278
|
+
async listDirectories() {
|
|
3279
|
+
const dirs = /* @__PURE__ */ new Set(["."]);
|
|
3280
|
+
const iter = this.fileProvider.glob("**/", {
|
|
3281
|
+
cwd: this.rootDir,
|
|
3282
|
+
ignore: this.ignorePatterns
|
|
3283
|
+
});
|
|
3284
|
+
for await (const dir of iter) {
|
|
3285
|
+
const clean = dir.replace(/\/$/, "");
|
|
3286
|
+
if (clean) dirs.add(clean);
|
|
3287
|
+
}
|
|
3288
|
+
return Array.from(dirs).sort();
|
|
3289
|
+
}
|
|
3290
|
+
resolveFilePath(relativePath) {
|
|
3291
|
+
if (relativePath.startsWith("/")) return relativePath;
|
|
3292
|
+
return `${this.rootDir}/${relativePath}`;
|
|
3293
|
+
}
|
|
3294
|
+
};
|
|
3295
|
+
//#endregion
|
|
3296
|
+
//#region src/prompt/variations/db/migrations/bundled.ts
|
|
3297
|
+
/** Every migration under `src/prompt/variations/db/migrations/`, in apply order. */
|
|
3298
|
+
const bundledMigrations = [{
|
|
3299
|
+
"name": "20260929123404_concerned_switch",
|
|
3300
|
+
"hash": "9998d655c263eab83809e3c85bc935f57a4b15435638681103ad953387f63c83",
|
|
3301
|
+
"folderMillis": 1790685244e3,
|
|
3302
|
+
"bps": true,
|
|
3303
|
+
"sql": [
|
|
3304
|
+
"-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nCREATE TABLE `variation_names` (\n `prompt_id` text NOT NULL,\n `name` text NOT NULL,\n `variation_id` text NOT NULL,\n `created_at` real NOT NULL,\n CONSTRAINT `variation_names_pk` PRIMARY KEY(`prompt_id`, `name`),\n CONSTRAINT `fk_variation_names_variation_id_variations_id_fk` FOREIGN KEY (`variation_id`) REFERENCES `variations`(`id`)\n);\n",
|
|
3305
|
+
"\nCREATE TABLE `variations` (\n `id` text PRIMARY KEY,\n `prompt_id` text NOT NULL,\n `global_id` text,\n `base_version` text DEFAULT '' NOT NULL,\n `updates` text NOT NULL,\n `base_values` text NOT NULL,\n `wip` integer DEFAULT 0 NOT NULL,\n `on_head` integer DEFAULT 0 NOT NULL,\n `origin_name` text,\n `pending` text,\n `created_at` real NOT NULL,\n `updated_at` real NOT NULL\n);\n",
|
|
3306
|
+
"\nCREATE UNIQUE INDEX `uq_variations_frozen` ON `variations` (`prompt_id`,`base_version`,`updates`,`base_values`) WHERE \"variations\".\"wip\" = 0;",
|
|
3307
|
+
"\nCREATE UNIQUE INDEX `uq_variations_wip` ON `variations` (`prompt_id`,`base_version`) WHERE \"variations\".\"wip\" = 1 and \"variations\".\"on_head\" = 0;",
|
|
3308
|
+
"\nCREATE UNIQUE INDEX `uq_variations_head_wip` ON `variations` (`prompt_id`) WHERE \"variations\".\"wip\" = 1 and \"variations\".\"on_head\" = 1;"
|
|
3309
|
+
]
|
|
3310
|
+
}];
|
|
3311
|
+
//#endregion
|
|
3312
|
+
//#region src/prompt/variations/db/migrate.ts
|
|
3313
|
+
/**
|
|
3314
|
+
* Applies the variation store's bundled migrations — the twin of
|
|
3315
|
+
* `src/trace/db/migrate.ts`, sharing its fs-free runner and ledger table.
|
|
3316
|
+
*/
|
|
3317
|
+
/**
|
|
3318
|
+
* Applies every variation-store migration that hasn't already run.
|
|
3319
|
+
* Idempotent. Call before constructing a {@link TursoVariationStore} over the
|
|
3320
|
+
* same client.
|
|
3321
|
+
*/
|
|
3322
|
+
async function runVariationMigrations(db) {
|
|
3323
|
+
await runMigrations(db, bundledMigrations);
|
|
3324
|
+
}
|
|
3325
|
+
//#endregion
|
|
3326
|
+
//#region src/prompt/variations/db/schema.ts
|
|
3327
|
+
/**
|
|
3328
|
+
* Drizzle sqlite-core schema backing {@link TursoVariationStore}. See
|
|
3329
|
+
* `specs/prompt-versions-and-variations.md` §E. fs-free by construction, like
|
|
3330
|
+
* the trace and dataset schemas.
|
|
3331
|
+
*/
|
|
3332
|
+
/**
|
|
3333
|
+
* Every variation, frozen or WIP. A frozen row is unique by (prompt, base,
|
|
3334
|
+
* canonical updates, the values they overwrite); there is at most one WIP per
|
|
3335
|
+
* (prompt, old version), and at most one head WIP per prompt.
|
|
3336
|
+
*/
|
|
3337
|
+
const variations = sqliteTable("variations", {
|
|
3338
|
+
/** `var_` + a short random id. */
|
|
3339
|
+
id: text("id").primaryKey(),
|
|
3340
|
+
/** The prompt's provider-scoped id, as of the base. */
|
|
3341
|
+
promptId: text("prompt_id").notNull(),
|
|
3342
|
+
/** The prompt's `prompts()` id, when it has one. */
|
|
3343
|
+
globalId: text("global_id"),
|
|
3344
|
+
/**
|
|
3345
|
+
* The commit the variation was made against, or `''` for none — so it
|
|
3346
|
+
* takes part in the unique indexes, which a NULL wouldn't.
|
|
3347
|
+
*/
|
|
3348
|
+
baseVersion: text("base_version").notNull().default(""),
|
|
3349
|
+
/** Canonical JSON `NormalizedPromptUpdates` — see `serializeUpdates`. */
|
|
3350
|
+
updates: text("updates").notNull(),
|
|
3351
|
+
/** Canonical JSON `FieldValues`: what the updates overwrite. */
|
|
3352
|
+
baseValues: text("base_values").notNull(),
|
|
3353
|
+
wip: integer("wip").notNull().default(0),
|
|
3354
|
+
/** For a WIP: whether it holds the unsaved edits to head. */
|
|
3355
|
+
onHead: integer("on_head").notNull().default(0),
|
|
3356
|
+
/** For a WIP opened from a named variation: that name. */
|
|
3357
|
+
originName: text("origin_name"),
|
|
3358
|
+
/** For a WIP: JSON `PendingConflicts` awaiting resolution. */
|
|
3359
|
+
pending: text("pending"),
|
|
3360
|
+
/** Creation timestamp (ms). */
|
|
3361
|
+
createdAt: real("created_at").notNull(),
|
|
3362
|
+
/** Last-change timestamp (ms). */
|
|
3363
|
+
updatedAt: real("updated_at").notNull()
|
|
3364
|
+
}, (t) => [
|
|
3365
|
+
uniqueIndex("uq_variations_frozen").on(t.promptId, t.baseVersion, t.updates, t.baseValues).where(sql`${t.wip} = 0`),
|
|
3366
|
+
uniqueIndex("uq_variations_wip").on(t.promptId, t.baseVersion).where(sql`${t.wip} = 1 and ${t.onHead} = 0`),
|
|
3367
|
+
uniqueIndex("uq_variations_head_wip").on(t.promptId).where(sql`${t.wip} = 1 and ${t.onHead} = 1`)
|
|
3368
|
+
]);
|
|
3369
|
+
/** Names point at variations; a variation doesn't carry its names. */
|
|
3370
|
+
const variationNames = sqliteTable("variation_names", {
|
|
3371
|
+
promptId: text("prompt_id").notNull(),
|
|
3372
|
+
name: text("name").notNull(),
|
|
3373
|
+
variationId: text("variation_id").notNull().references(() => variations.id),
|
|
3374
|
+
/** Creation timestamp (ms). */
|
|
3375
|
+
createdAt: real("created_at").notNull()
|
|
3376
|
+
}, (t) => [primaryKey({ columns: [t.promptId, t.name] })]);
|
|
3377
|
+
//#endregion
|
|
3378
|
+
//#region src/prompt/variations/turso-variation-store.ts
|
|
3379
|
+
const BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
3380
|
+
/** `var_` + 16 base-62 characters. */
|
|
3381
|
+
function mintVariationId() {
|
|
3382
|
+
const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
|
|
3383
|
+
let id = "var_";
|
|
3384
|
+
for (const b of bytes) id += BASE62[b % 62];
|
|
3385
|
+
return id;
|
|
3386
|
+
}
|
|
3387
|
+
/**
|
|
3388
|
+
* `VariationStore` over a Turso/libSQL database via
|
|
3389
|
+
* `drizzle-orm/tursodatabase-sync`. Migrations are *not* run here: call
|
|
3390
|
+
* `runVariationMigrations` against the same client first.
|
|
3391
|
+
*/
|
|
3392
|
+
var TursoVariationStore = class {
|
|
3393
|
+
db;
|
|
3394
|
+
/** Tail of the serialized-write chain — as `TursoTraceProvider.serializeWrite`. */
|
|
3395
|
+
writes = Promise.resolve();
|
|
3396
|
+
constructor({ client }) {
|
|
3397
|
+
this.db = drizzle({ client });
|
|
3398
|
+
}
|
|
3399
|
+
/**
|
|
3400
|
+
* Runs an operation to completion before the next one starts: the client is
|
|
3401
|
+
* a single connection, and overlapping transactions on it fail outright —
|
|
3402
|
+
* as does a read that lands in the middle of one ("statement has been
|
|
3403
|
+
* finalized"). Reads go through here too; this store is small and quiet.
|
|
3404
|
+
*/
|
|
3405
|
+
serialize(write) {
|
|
3406
|
+
const next = this.writes.then(write, write);
|
|
3407
|
+
this.writes = next.catch(() => {});
|
|
3408
|
+
return next;
|
|
3409
|
+
}
|
|
3410
|
+
/** Rows as {@link StoredVariation}s, with their names attached. */
|
|
3411
|
+
async hydrate(rows) {
|
|
3412
|
+
if (rows.length === 0) return [];
|
|
3413
|
+
const names = await this.db.select().from(variationNames).where(inArray(variationNames.variationId, rows.map((r) => r.id))).orderBy(asc(variationNames.createdAt));
|
|
3414
|
+
return rows.map((row) => ({
|
|
3415
|
+
id: row.id,
|
|
3416
|
+
promptId: row.promptId,
|
|
3417
|
+
...row.globalId && { globalId: row.globalId },
|
|
3418
|
+
...row.baseVersion && { base: row.baseVersion },
|
|
3419
|
+
updates: JSON.parse(row.updates),
|
|
3420
|
+
baseValues: JSON.parse(row.baseValues),
|
|
3421
|
+
wip: row.wip === 1,
|
|
3422
|
+
...row.wip === 1 && { onHead: row.onHead === 1 },
|
|
3423
|
+
names: names.filter((n) => n.variationId === row.id).map((n) => n.name),
|
|
3424
|
+
...row.originName && { originName: row.originName },
|
|
3425
|
+
...row.pending && { pending: JSON.parse(row.pending) },
|
|
3426
|
+
createdAt: row.createdAt,
|
|
3427
|
+
updatedAt: row.updatedAt
|
|
3428
|
+
}));
|
|
3429
|
+
}
|
|
3430
|
+
async one(rows) {
|
|
3431
|
+
return (await this.hydrate(rows.slice(0, 1)))[0];
|
|
3432
|
+
}
|
|
3433
|
+
/** The row with this id — for use inside an operation already serialized. */
|
|
3434
|
+
async readById(id) {
|
|
3435
|
+
return this.one(await this.db.select().from(variations).where(eq(variations.id, id)));
|
|
3436
|
+
}
|
|
3437
|
+
get(id) {
|
|
3438
|
+
return this.serialize(() => this.readById(id));
|
|
3439
|
+
}
|
|
3440
|
+
intern(v) {
|
|
3441
|
+
const updates = serializeUpdates(v.updates);
|
|
3442
|
+
const baseValues = serializeFieldValues(v.baseValues);
|
|
3443
|
+
const baseVersion = v.base ?? "";
|
|
3444
|
+
return this.serialize(async () => {
|
|
3445
|
+
const now = Date.now();
|
|
3446
|
+
await this.db.insert(variations).values({
|
|
3447
|
+
id: mintVariationId(),
|
|
3448
|
+
promptId: v.promptId,
|
|
3449
|
+
globalId: v.globalId ?? null,
|
|
3450
|
+
baseVersion,
|
|
3451
|
+
updates,
|
|
3452
|
+
baseValues,
|
|
3453
|
+
wip: 0,
|
|
3454
|
+
createdAt: now,
|
|
3455
|
+
updatedAt: now
|
|
3456
|
+
}).onConflictDoNothing();
|
|
3457
|
+
const found = await this.one(await this.db.select().from(variations).where(and(eq(variations.wip, 0), eq(variations.promptId, v.promptId), eq(variations.baseVersion, baseVersion), eq(variations.updates, updates), eq(variations.baseValues, baseValues))));
|
|
3458
|
+
if (!found) throw new Error("Interned variation vanished");
|
|
3459
|
+
return found;
|
|
3460
|
+
});
|
|
3461
|
+
}
|
|
3462
|
+
getWip(promptId, base) {
|
|
3463
|
+
return this.serialize(async () => {
|
|
3464
|
+
return this.one(await this.db.select().from(variations).where(and(eq(variations.wip, 1), eq(variations.onHead, 0), eq(variations.promptId, promptId), eq(variations.baseVersion, base))));
|
|
3465
|
+
});
|
|
3466
|
+
}
|
|
3467
|
+
getHeadWip(promptId) {
|
|
3468
|
+
return this.serialize(async () => {
|
|
3469
|
+
return this.one(await this.db.select().from(variations).where(and(eq(variations.wip, 1), eq(variations.onHead, 1), eq(variations.promptId, promptId))));
|
|
3470
|
+
});
|
|
3471
|
+
}
|
|
3472
|
+
listHeadWips() {
|
|
3473
|
+
return this.serialize(async () => {
|
|
3474
|
+
return this.hydrate(await this.db.select().from(variations).where(and(eq(variations.wip, 1), eq(variations.onHead, 1))));
|
|
3475
|
+
});
|
|
3476
|
+
}
|
|
3477
|
+
putWip(v) {
|
|
3478
|
+
return this.serialize(async () => {
|
|
3479
|
+
const now = Date.now();
|
|
3480
|
+
const id = mintVariationId();
|
|
3481
|
+
await this.db.transaction(async (tx) => {
|
|
3482
|
+
await tx.delete(variations).where(and(eq(variations.wip, 1), eq(variations.promptId, v.promptId), v.onHead ? eq(variations.onHead, 1) : and(eq(variations.onHead, 0), eq(variations.baseVersion, v.base ?? ""))));
|
|
3483
|
+
await tx.insert(variations).values({
|
|
3484
|
+
id,
|
|
3485
|
+
promptId: v.promptId,
|
|
3486
|
+
globalId: v.globalId ?? null,
|
|
3487
|
+
baseVersion: v.base ?? "",
|
|
3488
|
+
updates: serializeUpdates(v.updates),
|
|
3489
|
+
baseValues: serializeFieldValues(v.baseValues),
|
|
3490
|
+
wip: 1,
|
|
3491
|
+
onHead: v.onHead ? 1 : 0,
|
|
3492
|
+
originName: v.originName ?? null,
|
|
3493
|
+
createdAt: now,
|
|
3494
|
+
updatedAt: now
|
|
3495
|
+
});
|
|
3496
|
+
});
|
|
3497
|
+
return await this.readById(id);
|
|
3498
|
+
});
|
|
3499
|
+
}
|
|
3500
|
+
updateWip(id, changes) {
|
|
3501
|
+
return this.serialize(async () => {
|
|
3502
|
+
const set = { updatedAt: Date.now() };
|
|
3503
|
+
if (changes.updates !== void 0) set.updates = serializeUpdates(changes.updates);
|
|
3504
|
+
if (changes.baseValues !== void 0) set.baseValues = serializeFieldValues(changes.baseValues);
|
|
3505
|
+
if (changes.pending !== void 0) set.pending = changes.pending && JSON.stringify(changes.pending);
|
|
3506
|
+
if (changes.originName !== void 0) set.originName = changes.originName;
|
|
3507
|
+
await this.db.update(variations).set(set).where(and(eq(variations.id, id), eq(variations.wip, 1)));
|
|
3508
|
+
const updated = await this.readById(id);
|
|
3509
|
+
if (!updated?.wip) throw new Error(`No WIP variation ${id}`);
|
|
3510
|
+
return updated;
|
|
3511
|
+
});
|
|
3512
|
+
}
|
|
3513
|
+
deleteWip(id) {
|
|
3514
|
+
return this.serialize(async () => {
|
|
3515
|
+
await this.db.delete(variations).where(and(eq(variations.id, id), eq(variations.wip, 1)));
|
|
3516
|
+
});
|
|
763
3517
|
}
|
|
764
|
-
|
|
765
|
-
|
|
3518
|
+
list(promptId) {
|
|
3519
|
+
return this.serialize(async () => {
|
|
3520
|
+
const named = this.db.select({ id: variationNames.variationId }).from(variationNames).where(eq(variationNames.promptId, promptId));
|
|
3521
|
+
return this.hydrate(await this.db.select().from(variations).where(or(and(eq(variations.wip, 1), eq(variations.promptId, promptId)), inArray(variations.id, named))).orderBy(desc(variations.updatedAt)));
|
|
3522
|
+
});
|
|
766
3523
|
}
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
3524
|
+
name(id, promptId, name) {
|
|
3525
|
+
return this.serialize(async () => {
|
|
3526
|
+
await this.db.insert(variationNames).values({
|
|
3527
|
+
promptId,
|
|
3528
|
+
name,
|
|
3529
|
+
variationId: id,
|
|
3530
|
+
createdAt: Date.now()
|
|
3531
|
+
}).onConflictDoUpdate({
|
|
3532
|
+
target: [variationNames.promptId, variationNames.name],
|
|
3533
|
+
set: {
|
|
3534
|
+
variationId: id,
|
|
3535
|
+
createdAt: Date.now()
|
|
3536
|
+
}
|
|
774
3537
|
});
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
3538
|
+
});
|
|
3539
|
+
}
|
|
3540
|
+
unname(promptId, name) {
|
|
3541
|
+
return this.serialize(async () => {
|
|
3542
|
+
await this.db.delete(variationNames).where(and(eq(variationNames.promptId, promptId), eq(variationNames.name, name)));
|
|
3543
|
+
});
|
|
3544
|
+
}
|
|
3545
|
+
rename(promptId, from, to) {
|
|
3546
|
+
return this.serialize(async () => {
|
|
3547
|
+
const named = (name) => and(eq(variationNames.promptId, promptId), eq(variationNames.name, name));
|
|
3548
|
+
const idNamed = async (name) => {
|
|
3549
|
+
const [row] = await this.db.select({ id: variationNames.variationId }).from(variationNames).where(named(name));
|
|
3550
|
+
return row?.id;
|
|
3551
|
+
};
|
|
3552
|
+
const id = await idNamed(from);
|
|
3553
|
+
if (!id) throw new Error(`No variation named "${from}"`);
|
|
3554
|
+
if (from === to) return id;
|
|
3555
|
+
if (await idNamed(to)) throw new Error(`A variation named "${to}" already exists`);
|
|
3556
|
+
await this.db.update(variationNames).set({ name: to }).where(named(from));
|
|
3557
|
+
return id;
|
|
3558
|
+
});
|
|
3559
|
+
}
|
|
3560
|
+
};
|
|
3561
|
+
//#endregion
|
|
3562
|
+
//#region src/prompt/variations/local-variation-store.ts
|
|
3563
|
+
/**
|
|
3564
|
+
* Node-side (fs-allowed) bootstrap for the local {@link TursoVariationStore}
|
|
3565
|
+
* — the one place a real path gets involved, as `local-turso-client.ts` is
|
|
3566
|
+
* for traces.
|
|
3567
|
+
*/
|
|
3568
|
+
var local_variation_store_exports = /* @__PURE__ */ __exportAll({
|
|
3569
|
+
LocalVariationStore: () => LocalVariationStore,
|
|
3570
|
+
openLocalVariationStore: () => openLocalVariationStore
|
|
3571
|
+
});
|
|
3572
|
+
/**
|
|
3573
|
+
* Opens (creating if needed) the variation database at `path` — by default
|
|
3574
|
+
* `.evalution/variations/variations.db` — in a directory that ignores itself,
|
|
3575
|
+
* so variations stay out of git without anyone editing their `.gitignore`.
|
|
3576
|
+
*/
|
|
3577
|
+
async function openLocalVariationStore(path) {
|
|
3578
|
+
await mkdirSelfIgnoring(dirname(path));
|
|
3579
|
+
await assertSqliteFile(path);
|
|
3580
|
+
const client = await createLocalTursoClient({ path });
|
|
3581
|
+
await runVariationMigrations(drizzle({ client }));
|
|
3582
|
+
return new TursoVariationStore({ client });
|
|
3583
|
+
}
|
|
3584
|
+
/**
|
|
3585
|
+
* The default variation store: a {@link TursoVariationStore} at `path` that
|
|
3586
|
+
* isn't created until something is written. Until then every read answers
|
|
3587
|
+
* "nothing" — so browsing prompts never leaves a database behind, just as
|
|
3588
|
+
* the trace store writes nothing until the first trace.
|
|
3589
|
+
*/
|
|
3590
|
+
var LocalVariationStore = class {
|
|
3591
|
+
path;
|
|
3592
|
+
opened;
|
|
3593
|
+
/** @param path - The database file; created, with its directory, on first write. */
|
|
3594
|
+
constructor(path) {
|
|
3595
|
+
this.path = path;
|
|
3596
|
+
}
|
|
3597
|
+
/** Whether a failure to open has been reported, so it's reported once. */
|
|
3598
|
+
warned = false;
|
|
3599
|
+
/** The store, creating it if needed. Set synchronously, so concurrent first writes share one open. */
|
|
3600
|
+
open() {
|
|
3601
|
+
this.opened ??= openLocalVariationStore(this.path).catch((err) => {
|
|
3602
|
+
throw new Error(/lock/i.test(String(err?.message)) ? `The variation store at ${this.path} is in use by another evalution process; unsaved edits are unavailable in this one.` : `Couldn't open the variation store at ${this.path}: ${err?.message ?? err}`);
|
|
3603
|
+
});
|
|
3604
|
+
this.opened.catch(() => {
|
|
3605
|
+
this.opened = void 0;
|
|
3606
|
+
});
|
|
3607
|
+
return this.opened;
|
|
3608
|
+
}
|
|
3609
|
+
/**
|
|
3610
|
+
* The store if it exists yet, without creating it. A store that won't open
|
|
3611
|
+
* — locked by another evalution process on the same project, say — reads
|
|
3612
|
+
* as empty, with a warning, rather than failing every prompt read (and
|
|
3613
|
+
* with them, startup).
|
|
3614
|
+
*/
|
|
3615
|
+
async existing() {
|
|
3616
|
+
if (!(!!this.opened || await access(this.path).then(() => true, () => false))) return void 0;
|
|
3617
|
+
try {
|
|
3618
|
+
return await this.open();
|
|
3619
|
+
} catch (err) {
|
|
3620
|
+
if (!this.warned) {
|
|
3621
|
+
this.warned = true;
|
|
3622
|
+
console.warn(`⚠️ ${err?.message ?? err}`);
|
|
778
3623
|
}
|
|
3624
|
+
return;
|
|
779
3625
|
}
|
|
780
3626
|
}
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
if (hashIdx < 0) throw new Error(`Invalid prompt ID format: ${id}`);
|
|
784
|
-
const relativePath = id.slice(0, hashIdx);
|
|
785
|
-
const functionName = id.slice(hashIdx + 1);
|
|
786
|
-
return [path.isAbsolute(relativePath) ? relativePath : path.join(this.rootDir, relativePath), functionName];
|
|
3627
|
+
async get(id) {
|
|
3628
|
+
return (await this.existing())?.get(id);
|
|
787
3629
|
}
|
|
788
|
-
async
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
3630
|
+
async intern(v) {
|
|
3631
|
+
return (await this.open()).intern(v);
|
|
3632
|
+
}
|
|
3633
|
+
async getWip(promptId, base) {
|
|
3634
|
+
return (await this.existing())?.getWip(promptId, base);
|
|
3635
|
+
}
|
|
3636
|
+
async getHeadWip(promptId) {
|
|
3637
|
+
return (await this.existing())?.getHeadWip(promptId);
|
|
3638
|
+
}
|
|
3639
|
+
async listHeadWips() {
|
|
3640
|
+
return await (await this.existing())?.listHeadWips() ?? [];
|
|
3641
|
+
}
|
|
3642
|
+
async putWip(v) {
|
|
3643
|
+
return (await this.open()).putWip(v);
|
|
3644
|
+
}
|
|
3645
|
+
async updateWip(id, changes) {
|
|
3646
|
+
return (await this.open()).updateWip(id, changes);
|
|
3647
|
+
}
|
|
3648
|
+
async deleteWip(id) {
|
|
3649
|
+
await (await this.existing())?.deleteWip(id);
|
|
3650
|
+
}
|
|
3651
|
+
async list(promptId) {
|
|
3652
|
+
return await (await this.existing())?.list(promptId) ?? [];
|
|
3653
|
+
}
|
|
3654
|
+
async name(id, promptId, name) {
|
|
3655
|
+
await (await this.open()).name(id, promptId, name);
|
|
3656
|
+
}
|
|
3657
|
+
async unname(promptId, name) {
|
|
3658
|
+
await (await this.existing())?.unname(promptId, name);
|
|
3659
|
+
}
|
|
3660
|
+
async rename(promptId, from, to) {
|
|
3661
|
+
return (await this.open()).rename(promptId, from, to);
|
|
3662
|
+
}
|
|
3663
|
+
};
|
|
3664
|
+
//#endregion
|
|
3665
|
+
//#region src/prompt/versioning/git-versioning.ts
|
|
3666
|
+
var git_versioning_exports = /* @__PURE__ */ __exportAll({ GitVersioning: () => GitVersioning });
|
|
3667
|
+
/** Commits `git log` is asked for when listing a file's history. */
|
|
3668
|
+
const MAX_HISTORY_COMMITS = 1e3;
|
|
3669
|
+
/**
|
|
3670
|
+
* A commit id (or abbreviation). Every id reaching git is checked against
|
|
3671
|
+
* this, so nothing a client sends can be read as an option.
|
|
3672
|
+
*/
|
|
3673
|
+
const OBJECT_ID = /^[0-9a-f]{4,64}$/;
|
|
3674
|
+
/** Thrown when git exits non-zero where that isn't an expected answer. */
|
|
3675
|
+
var GitError = class extends Error {
|
|
3676
|
+
constructor(args, result) {
|
|
3677
|
+
super(`git ${args.join(" ")} failed (${result.code}): ${result.stderr.trim()}`);
|
|
3678
|
+
}
|
|
3679
|
+
};
|
|
3680
|
+
/** Runs git and collects its output. Rejects only if git can't be started. */
|
|
3681
|
+
function runGit(cwd, args) {
|
|
3682
|
+
return new Promise((resolve, reject) => {
|
|
3683
|
+
const child = spawn("git", args, {
|
|
3684
|
+
cwd,
|
|
3685
|
+
env: {
|
|
3686
|
+
...process.env,
|
|
3687
|
+
GIT_OPTIONAL_LOCKS: "0"
|
|
3688
|
+
},
|
|
3689
|
+
stdio: [
|
|
3690
|
+
"pipe",
|
|
3691
|
+
"pipe",
|
|
3692
|
+
"pipe"
|
|
3693
|
+
]
|
|
793
3694
|
});
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
3695
|
+
const stdout = [];
|
|
3696
|
+
const stderr = [];
|
|
3697
|
+
child.stdout.on("data", (chunk) => stdout.push(chunk));
|
|
3698
|
+
child.stderr.on("data", (chunk) => stderr.push(chunk));
|
|
3699
|
+
child.on("error", reject);
|
|
3700
|
+
child.on("close", (code) => resolve({
|
|
3701
|
+
code: code ?? 1,
|
|
3702
|
+
stdout: Buffer.concat(stdout).toString("utf8"),
|
|
3703
|
+
stderr: Buffer.concat(stderr).toString("utf8")
|
|
3704
|
+
}));
|
|
3705
|
+
child.stdin.end();
|
|
3706
|
+
});
|
|
3707
|
+
}
|
|
3708
|
+
/** `git log` format for {@link parseLogEntry}: fields NUL-separated, records RS-terminated. */
|
|
3709
|
+
const LOG_FORMAT = "--format=%H%x00%an%x00%ct%x00%s%x1e";
|
|
3710
|
+
function parseLog(stdout) {
|
|
3711
|
+
return stdout.split("").map((record) => record.trim()).filter(Boolean).map((record) => {
|
|
3712
|
+
const [id, author, time, message] = record.split("\0");
|
|
3713
|
+
return {
|
|
3714
|
+
id,
|
|
3715
|
+
message,
|
|
3716
|
+
author,
|
|
3717
|
+
time: Number(time) * 1e3
|
|
3718
|
+
};
|
|
3719
|
+
});
|
|
3720
|
+
}
|
|
3721
|
+
/**
|
|
3722
|
+
* A {@link VersioningAdapter} for a git repository: a version is a commit.
|
|
3723
|
+
* Uncommitted changes are never recorded — a run on a dirty working tree
|
|
3724
|
+
* simply has no version.
|
|
3725
|
+
*
|
|
3726
|
+
* Shells out to `git`; there is no library dependency. See
|
|
3727
|
+
* `specs/prompt-versions-and-variations.md` §C.
|
|
3728
|
+
*/
|
|
3729
|
+
var GitVersioning = class GitVersioning {
|
|
3730
|
+
id = "git";
|
|
3731
|
+
repoDir;
|
|
3732
|
+
rootDir;
|
|
3733
|
+
constructor({ repoDir, rootDir }) {
|
|
3734
|
+
this.repoDir = repoDir;
|
|
3735
|
+
this.rootDir = rootDir;
|
|
3736
|
+
}
|
|
3737
|
+
/**
|
|
3738
|
+
* Builds a `GitVersioning` for the repository containing `rootDir`, or
|
|
3739
|
+
* returns `undefined` when there is none — or no `git` binary to run, which
|
|
3740
|
+
* is reported once, here, as "versioning unavailable" rather than failing
|
|
3741
|
+
* later.
|
|
3742
|
+
*/
|
|
3743
|
+
static async detect(rootDir) {
|
|
3744
|
+
let result;
|
|
3745
|
+
try {
|
|
3746
|
+
result = await runGit(rootDir, ["rev-parse", "--show-toplevel"]);
|
|
3747
|
+
} catch (err) {
|
|
3748
|
+
console.warn(`⚠️ git versioning unavailable (${err?.code === "ENOENT" ? "no git binary found" : err?.message}); prompts will have no versions.`);
|
|
3749
|
+
return;
|
|
797
3750
|
}
|
|
798
|
-
|
|
3751
|
+
if (result.code !== 0) return void 0;
|
|
3752
|
+
return new GitVersioning({
|
|
3753
|
+
repoDir: result.stdout.trim(),
|
|
3754
|
+
rootDir: await realpath(rootDir)
|
|
3755
|
+
});
|
|
799
3756
|
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
return
|
|
3757
|
+
async head() {
|
|
3758
|
+
const [commit, status] = await Promise.all([this.resolve("HEAD"), this.git(["status", "--porcelain"])]);
|
|
3759
|
+
return {
|
|
3760
|
+
...commit && { commit: await this.info(commit) },
|
|
3761
|
+
clean: status.trim() === ""
|
|
3762
|
+
};
|
|
3763
|
+
}
|
|
3764
|
+
async readFile(version, relativePath) {
|
|
3765
|
+
if (!OBJECT_ID.test(version)) return void 0;
|
|
3766
|
+
const result = await runGit(this.repoDir, [
|
|
3767
|
+
"cat-file",
|
|
3768
|
+
"blob",
|
|
3769
|
+
`${version}:${this.repoPath(relativePath)}`
|
|
3770
|
+
]);
|
|
3771
|
+
return result.code === 0 ? result.stdout : void 0;
|
|
3772
|
+
}
|
|
3773
|
+
async get(id) {
|
|
3774
|
+
if (!OBJECT_ID.test(id)) return void 0;
|
|
3775
|
+
const result = await runGit(this.repoDir, [
|
|
3776
|
+
"log",
|
|
3777
|
+
"--no-walk",
|
|
3778
|
+
LOG_FORMAT,
|
|
3779
|
+
`${id}^{commit}`,
|
|
3780
|
+
"--"
|
|
3781
|
+
]);
|
|
3782
|
+
if (result.code !== 0) return void 0;
|
|
3783
|
+
return parseLog(result.stdout)[0];
|
|
3784
|
+
}
|
|
3785
|
+
async history(relativePath, { limit, before } = {}) {
|
|
3786
|
+
if (!await this.resolve("HEAD")) return [];
|
|
3787
|
+
let commits = parseLog(await this.git([
|
|
3788
|
+
"log",
|
|
3789
|
+
LOG_FORMAT,
|
|
3790
|
+
`-n${MAX_HISTORY_COMMITS}`,
|
|
3791
|
+
"HEAD",
|
|
3792
|
+
"--",
|
|
3793
|
+
this.repoPath(relativePath)
|
|
3794
|
+
]));
|
|
3795
|
+
if (before) {
|
|
3796
|
+
const index = commits.findIndex((v) => v.id === before);
|
|
3797
|
+
if (index >= 0) commits = commits.slice(index + 1);
|
|
3798
|
+
}
|
|
3799
|
+
return limit !== void 0 ? commits.slice(0, limit) : commits;
|
|
3800
|
+
}
|
|
3801
|
+
async info(commit) {
|
|
3802
|
+
const info = await this.get(commit);
|
|
3803
|
+
if (!info) throw new Error(`git commit ${commit} vanished`);
|
|
3804
|
+
return info;
|
|
3805
|
+
}
|
|
3806
|
+
/** The object `rev` names, or `undefined` if it names nothing (an unborn `HEAD`). */
|
|
3807
|
+
async resolve(rev) {
|
|
3808
|
+
const result = await runGit(this.repoDir, [
|
|
3809
|
+
"rev-parse",
|
|
3810
|
+
"-q",
|
|
3811
|
+
"--verify",
|
|
3812
|
+
rev
|
|
3813
|
+
]);
|
|
3814
|
+
return result.code === 0 ? result.stdout.trim() : void 0;
|
|
3815
|
+
}
|
|
3816
|
+
/** `relativePath` (relative to {@link rootDir}) relative to the repository, in git's spelling. */
|
|
3817
|
+
repoPath(relativePath) {
|
|
3818
|
+
return path.relative(this.repoDir, path.resolve(this.rootDir, relativePath)).split(path.sep).join("/");
|
|
3819
|
+
}
|
|
3820
|
+
async git(args) {
|
|
3821
|
+
const result = await runGit(this.repoDir, args);
|
|
3822
|
+
if (result.code !== 0) throw new GitError(args, result);
|
|
3823
|
+
return result.stdout;
|
|
803
3824
|
}
|
|
804
3825
|
};
|
|
805
3826
|
//#endregion
|
|
@@ -809,6 +3830,7 @@ const AGENT_KEY = "agent";
|
|
|
809
3830
|
const SYSTEM_KEY = "system_instruction";
|
|
810
3831
|
const INPUT_KEY = "input";
|
|
811
3832
|
const GENERATION_CONFIG_KEY = "generation_config";
|
|
3833
|
+
const AGENT_CONFIG_KEY = "agent_config";
|
|
812
3834
|
const FALLBACK_GENERATION_CONFIG_PARAMS = [
|
|
813
3835
|
{
|
|
814
3836
|
name: "temperature",
|
|
@@ -852,9 +3874,13 @@ const FALLBACK_GENERATION_CONFIG_PARAMS = [
|
|
|
852
3874
|
type: {
|
|
853
3875
|
kind: "array",
|
|
854
3876
|
syntax: "string[]",
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
3877
|
+
element: {
|
|
3878
|
+
name: "",
|
|
3879
|
+
type: {
|
|
3880
|
+
kind: "primitive",
|
|
3881
|
+
syntax: "string"
|
|
3882
|
+
},
|
|
3883
|
+
optional: false
|
|
858
3884
|
}
|
|
859
3885
|
},
|
|
860
3886
|
optional: true
|
|
@@ -910,188 +3936,172 @@ const FALLBACK_GENERATION_CONFIG_PARAMS = [
|
|
|
910
3936
|
}
|
|
911
3937
|
];
|
|
912
3938
|
/**
|
|
3939
|
+
* The models `interactions.create` accepts — a subset of the full Gemini
|
|
3940
|
+
* lineup. See https://ai.google.dev/gemini-api/docs/interactions
|
|
3941
|
+
*/
|
|
3942
|
+
const CURATED_MODELS = [
|
|
3943
|
+
{
|
|
3944
|
+
label: "Gemini 3.8 Flash",
|
|
3945
|
+
id: "gemini-3.8-flash"
|
|
3946
|
+
},
|
|
3947
|
+
{
|
|
3948
|
+
label: "Gemini 3.7 Flash",
|
|
3949
|
+
id: "gemini-3.7-flash"
|
|
3950
|
+
},
|
|
3951
|
+
{
|
|
3952
|
+
label: "Gemini 3.6 Flash",
|
|
3953
|
+
id: "gemini-3.6-flash"
|
|
3954
|
+
},
|
|
3955
|
+
{
|
|
3956
|
+
label: "Gemini 3.5 Flash",
|
|
3957
|
+
id: "gemini-3.5-flash"
|
|
3958
|
+
},
|
|
3959
|
+
{
|
|
3960
|
+
label: "Gemini 3.5 Flash-Lite",
|
|
3961
|
+
id: "gemini-3.5-flash-lite"
|
|
3962
|
+
},
|
|
3963
|
+
{
|
|
3964
|
+
label: "Gemini 3.1 Pro Preview",
|
|
3965
|
+
id: "gemini-3.1-pro-preview"
|
|
3966
|
+
},
|
|
3967
|
+
{
|
|
3968
|
+
label: "Gemini 3.1 Flash-Lite",
|
|
3969
|
+
id: "gemini-3.1-flash-lite"
|
|
3970
|
+
},
|
|
3971
|
+
{
|
|
3972
|
+
label: "Gemini 3 Flash Preview",
|
|
3973
|
+
id: "gemini-3-flash-preview"
|
|
3974
|
+
},
|
|
3975
|
+
{
|
|
3976
|
+
label: "Gemini 2.5 Pro",
|
|
3977
|
+
id: "gemini-2.5-pro"
|
|
3978
|
+
},
|
|
3979
|
+
{
|
|
3980
|
+
label: "Gemini 2.5 Flash",
|
|
3981
|
+
id: "gemini-2.5-flash"
|
|
3982
|
+
},
|
|
3983
|
+
{
|
|
3984
|
+
label: "Gemini 2.5 Flash-Lite",
|
|
3985
|
+
id: "gemini-2.5-flash-lite"
|
|
3986
|
+
}
|
|
3987
|
+
];
|
|
3988
|
+
/** The agents `interactions.create` accepts. */
|
|
3989
|
+
const CURATED_AGENTS = [
|
|
3990
|
+
{
|
|
3991
|
+
label: "Deep Research Preview",
|
|
3992
|
+
id: "deep-research-preview-04-2026"
|
|
3993
|
+
},
|
|
3994
|
+
{
|
|
3995
|
+
label: "Deep Research Max Preview",
|
|
3996
|
+
id: "deep-research-max-preview-04-2026"
|
|
3997
|
+
},
|
|
3998
|
+
{
|
|
3999
|
+
label: "Antigravity Preview",
|
|
4000
|
+
id: "antigravity-preview-09-2026"
|
|
4001
|
+
}
|
|
4002
|
+
];
|
|
4003
|
+
/** Each variant's own settings, which are invalid under the other. */
|
|
4004
|
+
const VARIANT_CONFIG_KEY = {
|
|
4005
|
+
model: GENERATION_CONFIG_KEY,
|
|
4006
|
+
agent: AGENT_CONFIG_KEY
|
|
4007
|
+
};
|
|
4008
|
+
const STRING = {
|
|
4009
|
+
kind: "primitive",
|
|
4010
|
+
syntax: "string",
|
|
4011
|
+
base: "string"
|
|
4012
|
+
};
|
|
4013
|
+
/** One variant's fragment of the config, `{ model: … }` or `{ agent: … }`. */
|
|
4014
|
+
function variantType(key, idType = STRING) {
|
|
4015
|
+
return {
|
|
4016
|
+
kind: "object",
|
|
4017
|
+
syntax: `{ ${key}: ${key === MODEL_KEY ? "Model" : "AgentOption"} }`,
|
|
4018
|
+
properties: [{
|
|
4019
|
+
name: key,
|
|
4020
|
+
type: idType,
|
|
4021
|
+
optional: false
|
|
4022
|
+
}]
|
|
4023
|
+
};
|
|
4024
|
+
}
|
|
4025
|
+
/** The model slot's type when it couldn't be resolved. */
|
|
4026
|
+
const FALLBACK_MODEL_TYPE = {
|
|
4027
|
+
kind: "union",
|
|
4028
|
+
syntax: "{ model: Model } | { agent: AgentOption }",
|
|
4029
|
+
types: [variantType(MODEL_KEY), variantType(AGENT_KEY)]
|
|
4030
|
+
};
|
|
4031
|
+
/** Probe name for the model slot's type, as reported in project results. */
|
|
4032
|
+
const MODEL_PROBE = "model";
|
|
4033
|
+
/**
|
|
4034
|
+
* The model slot as a union of two config fragments: each variant's own ID
|
|
4035
|
+
* key, read off the SDK's own request types.
|
|
4036
|
+
*/
|
|
4037
|
+
const MODEL_PROJECT_PROBES = [{
|
|
4038
|
+
kind: "type",
|
|
4039
|
+
name: MODEL_PROBE,
|
|
4040
|
+
expression: "Pick<import(\"@google/genai\").Interactions.CreateModelInteraction, \"model\"> | Pick<import(\"@google/genai\").Interactions.CreateAgentInteraction, \"agent\">",
|
|
4041
|
+
syntax: "{ model: Model } | { agent: AgentOption }"
|
|
4042
|
+
}];
|
|
4043
|
+
/** The variant member of a resolved model type, by the key it carries. */
|
|
4044
|
+
function memberFor(type, key) {
|
|
4045
|
+
return (type.kind === "union" ? type.types : [type]).find((m) => m.kind === "object" && m.properties.some((p) => p.name === key)) ?? variantType(key);
|
|
4046
|
+
}
|
|
4047
|
+
function fragment(key, id) {
|
|
4048
|
+
return {
|
|
4049
|
+
kind: "object",
|
|
4050
|
+
properties: { [key]: {
|
|
4051
|
+
kind: "primitive",
|
|
4052
|
+
value: id
|
|
4053
|
+
} },
|
|
4054
|
+
displayValue: id
|
|
4055
|
+
};
|
|
4056
|
+
}
|
|
4057
|
+
/** Which variant a model fragment is, if it is one. */
|
|
4058
|
+
function variantOf(value) {
|
|
4059
|
+
if (value?.kind !== "object") return void 0;
|
|
4060
|
+
if (MODEL_KEY in value.properties) return MODEL_KEY;
|
|
4061
|
+
if (AGENT_KEY in value.properties) return AGENT_KEY;
|
|
4062
|
+
}
|
|
4063
|
+
/**
|
|
913
4064
|
* {@link SDKAdapter} implementation for the Google GenAI
|
|
914
4065
|
* [Interactions API](https://ai.google.dev/gemini-api/docs/interactions)
|
|
915
4066
|
* (`@google/genai` package). Currently experimental and untested.
|
|
916
4067
|
*/
|
|
917
4068
|
var GeminiInteractionsSDK = class {
|
|
918
4069
|
promptsHelperImport = "FIXME";
|
|
919
|
-
|
|
920
|
-
return
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
properties: {
|
|
948
|
-
key: {
|
|
949
|
-
kind: "primitive",
|
|
950
|
-
value: "agent"
|
|
951
|
-
},
|
|
952
|
-
value: {
|
|
953
|
-
kind: "primitive",
|
|
954
|
-
value: "$input"
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
} } },
|
|
959
|
-
models: [
|
|
960
|
-
{
|
|
961
|
-
id: "gemini-3.1-pro-preview",
|
|
962
|
-
label: "Gemini 3.1 Pro Preview",
|
|
963
|
-
values: { model: {
|
|
964
|
-
kind: "object",
|
|
965
|
-
properties: {
|
|
966
|
-
key: {
|
|
967
|
-
kind: "primitive",
|
|
968
|
-
value: "model"
|
|
969
|
-
},
|
|
970
|
-
value: {
|
|
971
|
-
kind: "primitive",
|
|
972
|
-
value: "gemini-3.1-pro-preview"
|
|
973
|
-
}
|
|
974
|
-
},
|
|
975
|
-
displayValue: "gemini-3.1-pro-preview"
|
|
976
|
-
} },
|
|
977
|
-
group: "Google"
|
|
978
|
-
},
|
|
979
|
-
{
|
|
980
|
-
id: "gemini-3-flash-preview",
|
|
981
|
-
label: "Gemini 3 Flash Preview",
|
|
982
|
-
values: { model: {
|
|
983
|
-
kind: "object",
|
|
984
|
-
properties: {
|
|
985
|
-
key: {
|
|
986
|
-
kind: "primitive",
|
|
987
|
-
value: "model"
|
|
988
|
-
},
|
|
989
|
-
value: {
|
|
990
|
-
kind: "primitive",
|
|
991
|
-
value: "gemini-3-flash-preview"
|
|
992
|
-
}
|
|
993
|
-
},
|
|
994
|
-
displayValue: "gemini-3-flash-preview"
|
|
995
|
-
} },
|
|
996
|
-
group: "Google"
|
|
997
|
-
},
|
|
998
|
-
{
|
|
999
|
-
id: "gemini-3.1-flash-lite-preview",
|
|
1000
|
-
label: "Gemini 3.1 Flash-Lite Preview",
|
|
1001
|
-
values: { model: {
|
|
1002
|
-
kind: "object",
|
|
1003
|
-
properties: {
|
|
1004
|
-
key: {
|
|
1005
|
-
kind: "primitive",
|
|
1006
|
-
value: "model"
|
|
1007
|
-
},
|
|
1008
|
-
value: {
|
|
1009
|
-
kind: "primitive",
|
|
1010
|
-
value: "gemini-3.1-flash-lite-preview"
|
|
1011
|
-
}
|
|
1012
|
-
},
|
|
1013
|
-
displayValue: "gemini-3.1-flash-lite-preview"
|
|
1014
|
-
} },
|
|
1015
|
-
group: "Google"
|
|
1016
|
-
},
|
|
1017
|
-
{
|
|
1018
|
-
id: "gemini-2.5-pro",
|
|
1019
|
-
label: "Gemini 2.5 Pro",
|
|
1020
|
-
values: { model: {
|
|
1021
|
-
kind: "object",
|
|
1022
|
-
properties: {
|
|
1023
|
-
key: {
|
|
1024
|
-
kind: "primitive",
|
|
1025
|
-
value: "model"
|
|
1026
|
-
},
|
|
1027
|
-
value: {
|
|
1028
|
-
kind: "primitive",
|
|
1029
|
-
value: "gemini-2.5-pro"
|
|
1030
|
-
}
|
|
1031
|
-
},
|
|
1032
|
-
displayValue: "gemini-2.5-pro"
|
|
1033
|
-
} },
|
|
1034
|
-
group: "Google"
|
|
1035
|
-
},
|
|
1036
|
-
{
|
|
1037
|
-
id: "gemini-2.5-flash",
|
|
1038
|
-
label: "Gemini 2.5 Flash",
|
|
1039
|
-
values: { model: {
|
|
1040
|
-
kind: "object",
|
|
1041
|
-
properties: {
|
|
1042
|
-
key: {
|
|
1043
|
-
kind: "primitive",
|
|
1044
|
-
value: "model"
|
|
1045
|
-
},
|
|
1046
|
-
value: {
|
|
1047
|
-
kind: "primitive",
|
|
1048
|
-
value: "gemini-2.5-flash"
|
|
1049
|
-
}
|
|
1050
|
-
},
|
|
1051
|
-
displayValue: "gemini-2.5-flash"
|
|
1052
|
-
} },
|
|
1053
|
-
group: "Google"
|
|
1054
|
-
},
|
|
1055
|
-
{
|
|
1056
|
-
id: "gemini-2.5-flash-lite",
|
|
1057
|
-
label: "Gemini 2.5 Flash-lite",
|
|
1058
|
-
values: { model: {
|
|
1059
|
-
kind: "object",
|
|
1060
|
-
properties: {
|
|
1061
|
-
key: {
|
|
1062
|
-
kind: "primitive",
|
|
1063
|
-
value: "model"
|
|
1064
|
-
},
|
|
1065
|
-
value: {
|
|
1066
|
-
kind: "primitive",
|
|
1067
|
-
value: "gemini-2.5-flash-lite"
|
|
1068
|
-
}
|
|
1069
|
-
},
|
|
1070
|
-
displayValue: "gemini-2.5-flash-lite"
|
|
1071
|
-
} },
|
|
1072
|
-
group: "Google"
|
|
1073
|
-
},
|
|
1074
|
-
{
|
|
1075
|
-
id: "deep-research-pro-preview-12-2025",
|
|
1076
|
-
label: "Deep Research Preview",
|
|
1077
|
-
values: { agent: {
|
|
1078
|
-
kind: "object",
|
|
1079
|
-
properties: {
|
|
1080
|
-
key: {
|
|
1081
|
-
kind: "primitive",
|
|
1082
|
-
value: "agent"
|
|
1083
|
-
},
|
|
1084
|
-
value: {
|
|
1085
|
-
kind: "primitive",
|
|
1086
|
-
value: "deep-research-pro-preview-12-2025"
|
|
1087
|
-
}
|
|
1088
|
-
},
|
|
1089
|
-
displayValue: "deep-research-pro-preview-12-2025"
|
|
1090
|
-
} },
|
|
1091
|
-
group: "Google"
|
|
1092
|
-
}
|
|
1093
|
-
]
|
|
4070
|
+
getProjectProbes(language) {
|
|
4071
|
+
return language === "typescript" ? MODEL_PROJECT_PROBES : [];
|
|
4072
|
+
}
|
|
4073
|
+
/**
|
|
4074
|
+
* One model row whose value is an honest config fragment —
|
|
4075
|
+
* `{ model: "gemini-3.5-flash" }` or `{ agent: "deep-research-…" }` —
|
|
4076
|
+
* because `interactions.create` takes one or the other, never both. The
|
|
4077
|
+
* **Models** and **Agents** catalogs each narrow their free-form entry to
|
|
4078
|
+
* their own variant.
|
|
4079
|
+
*/
|
|
4080
|
+
async getModelDefinition(project) {
|
|
4081
|
+
const resolved = project[MODEL_PROBE];
|
|
4082
|
+
const type = resolved && !Array.isArray(resolved) ? resolved.type : FALLBACK_MODEL_TYPE;
|
|
4083
|
+
const catalog = (key, label, ids) => ({
|
|
4084
|
+
label,
|
|
4085
|
+
groups: [{
|
|
4086
|
+
label: "Google",
|
|
4087
|
+
icon: "Google",
|
|
4088
|
+
presets: ids.map(({ label, id }) => ({
|
|
4089
|
+
label,
|
|
4090
|
+
value: fragment(key, id)
|
|
4091
|
+
}))
|
|
4092
|
+
}],
|
|
4093
|
+
literal: {
|
|
4094
|
+
name: "model",
|
|
4095
|
+
type: memberFor(type, key),
|
|
4096
|
+
optional: false
|
|
4097
|
+
}
|
|
1094
4098
|
});
|
|
4099
|
+
return {
|
|
4100
|
+
name: "model",
|
|
4101
|
+
type,
|
|
4102
|
+
optional: false,
|
|
4103
|
+
catalogs: [catalog(MODEL_KEY, "Models", CURATED_MODELS), catalog(AGENT_KEY, "Agents", CURATED_AGENTS)]
|
|
4104
|
+
};
|
|
1095
4105
|
}
|
|
1096
4106
|
getModelParameters(rootDir) {
|
|
1097
4107
|
try {
|
|
@@ -1106,6 +4116,13 @@ var GeminiInteractionsSDK = class {
|
|
|
1106
4116
|
return FALLBACK_GENERATION_CONFIG_PARAMS;
|
|
1107
4117
|
}
|
|
1108
4118
|
async executeConfig(config) {
|
|
4119
|
+
let GoogleGenAI;
|
|
4120
|
+
try {
|
|
4121
|
+
({GoogleGenAI} = await import("@google/genai"));
|
|
4122
|
+
} catch (err) {
|
|
4123
|
+
if (!isMissingPackage(err, "@google/genai")) throw err;
|
|
4124
|
+
throw new Error(missingPackageMessage("@google/genai"), { cause: err });
|
|
4125
|
+
}
|
|
1109
4126
|
await new GoogleGenAI({}).interactions.create({
|
|
1110
4127
|
...config,
|
|
1111
4128
|
store: false
|
|
@@ -1117,47 +4134,23 @@ var GeminiInteractionsSDK = class {
|
|
|
1117
4134
|
const inputValue = values?.[INPUT_KEY];
|
|
1118
4135
|
const modelValue = values?.[MODEL_KEY];
|
|
1119
4136
|
const agentValue = values?.[AGENT_KEY];
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
} else if (agentValue) {
|
|
1136
|
-
model = {
|
|
1137
|
-
kind: "object",
|
|
1138
|
-
properties: {
|
|
1139
|
-
key: {
|
|
1140
|
-
kind: "primitive",
|
|
1141
|
-
value: "agent"
|
|
1142
|
-
},
|
|
1143
|
-
value: agentValue
|
|
1144
|
-
},
|
|
1145
|
-
displayValue: valueToSourceText(agentValue)
|
|
1146
|
-
};
|
|
1147
|
-
modelEditable = isEditable(agentValue);
|
|
1148
|
-
}
|
|
1149
|
-
const genConfigDef = definitions.find((d) => d.name === GENERATION_CONFIG_KEY);
|
|
1150
|
-
const genConfigValue = values?.[GENERATION_CONFIG_KEY];
|
|
1151
|
-
const genConfigProps = genConfigValue?.kind === "object" ? genConfigValue.properties : {};
|
|
1152
|
-
const modelParameters = (genConfigDef?.type.kind === "object" ? genConfigDef.type.properties : []).map((def) => {
|
|
1153
|
-
const value = genConfigProps[def.name];
|
|
1154
|
-
return {
|
|
1155
|
-
def,
|
|
1156
|
-
value,
|
|
1157
|
-
editable: value ? isEditable(value) : true
|
|
1158
|
-
};
|
|
1159
|
-
});
|
|
4137
|
+
const variant = !modelValue && agentValue ? AGENT_KEY : MODEL_KEY;
|
|
4138
|
+
const idValue = variant === MODEL_KEY ? modelValue : agentValue;
|
|
4139
|
+
const model = idValue && {
|
|
4140
|
+
kind: "object",
|
|
4141
|
+
properties: { [variant]: idValue },
|
|
4142
|
+
displayValue: idValue.kind === "primitive" ? String(idValue.value) : valueToSourceText(idValue)
|
|
4143
|
+
};
|
|
4144
|
+
const configKey = VARIANT_CONFIG_KEY[variant];
|
|
4145
|
+
const configDef = definitions.find((d) => d.name === configKey);
|
|
4146
|
+
const configValue = values?.[configKey];
|
|
4147
|
+
const configProps = configValue?.kind === "object" ? configValue.properties : {};
|
|
4148
|
+
const modelParameters = (configDef?.type.kind === "object" ? configDef.type.properties : []).map((def) => ({
|
|
4149
|
+
def,
|
|
4150
|
+
value: configProps[def.name]
|
|
4151
|
+
}));
|
|
1160
4152
|
return {
|
|
4153
|
+
style: "chat",
|
|
1161
4154
|
id: prompt.id,
|
|
1162
4155
|
providerId: prompt.providerId,
|
|
1163
4156
|
name: prompt.name,
|
|
@@ -1165,36 +4158,48 @@ var GeminiInteractionsSDK = class {
|
|
|
1165
4158
|
metadata: prompt.metadata,
|
|
1166
4159
|
treePath: prompt.treePath,
|
|
1167
4160
|
model,
|
|
1168
|
-
modelEditable,
|
|
4161
|
+
modelEditable: true,
|
|
1169
4162
|
system: systemValue,
|
|
1170
|
-
systemEditable:
|
|
4163
|
+
systemEditable: true,
|
|
1171
4164
|
messages: extractMessages(inputValue),
|
|
1172
|
-
messagesEditable:
|
|
4165
|
+
messagesEditable: true,
|
|
1173
4166
|
modelParameters
|
|
1174
4167
|
};
|
|
1175
4168
|
}
|
|
1176
4169
|
denormalizeUpdates(updates, currentValues) {
|
|
4170
|
+
assertUpdateStyle(updates, "chat");
|
|
1177
4171
|
const out = {};
|
|
4172
|
+
const remove = (key) => {
|
|
4173
|
+
if (currentValues && key in currentValues) out[key] = null;
|
|
4174
|
+
};
|
|
4175
|
+
const currentVariant = currentValues && MODEL_KEY in currentValues ? MODEL_KEY : currentValues && AGENT_KEY in currentValues ? AGENT_KEY : void 0;
|
|
4176
|
+
let variant = currentVariant ?? MODEL_KEY;
|
|
1178
4177
|
if ("model" in updates) {
|
|
1179
|
-
|
|
1180
|
-
if (
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
4178
|
+
const next = variantOf(updates.model);
|
|
4179
|
+
if (!next) {
|
|
4180
|
+
remove(MODEL_KEY);
|
|
4181
|
+
remove(AGENT_KEY);
|
|
4182
|
+
} else if (updates.model?.kind === "object") {
|
|
4183
|
+
const other = next === MODEL_KEY ? AGENT_KEY : MODEL_KEY;
|
|
4184
|
+
out[next] = updates.model.properties[next];
|
|
4185
|
+
remove(other);
|
|
4186
|
+
if (currentVariant && currentVariant !== next) remove(VARIANT_CONFIG_KEY[other]);
|
|
4187
|
+
variant = next;
|
|
1185
4188
|
}
|
|
1186
4189
|
}
|
|
1187
4190
|
if ("system" in updates) out[SYSTEM_KEY] = updates.system ?? null;
|
|
1188
4191
|
if ("messages" in updates) out[INPUT_KEY] = updates.messages == null ? null : messagesToValue(updates.messages);
|
|
1189
4192
|
if (updates.modelParameters) {
|
|
1190
|
-
const
|
|
4193
|
+
const configKey = VARIANT_CONFIG_KEY[variant];
|
|
4194
|
+
const current = variant === currentVariant ? currentValues?.[configKey] : void 0;
|
|
1191
4195
|
const merged = current?.kind === "object" ? { ...current.properties } : {};
|
|
1192
4196
|
for (const [name, value] of Object.entries(updates.modelParameters)) if (value === null) delete merged[name];
|
|
1193
4197
|
else merged[name] = value;
|
|
1194
|
-
|
|
4198
|
+
if (Object.keys(merged).length > 0) out[configKey] = {
|
|
1195
4199
|
kind: "object",
|
|
1196
4200
|
properties: merged
|
|
1197
|
-
}
|
|
4201
|
+
};
|
|
4202
|
+
else remove(configKey);
|
|
1198
4203
|
}
|
|
1199
4204
|
return out;
|
|
1200
4205
|
}
|
|
@@ -1288,4 +4293,74 @@ function extractMessages(value) {
|
|
|
1288
4293
|
return results;
|
|
1289
4294
|
}
|
|
1290
4295
|
//#endregion
|
|
1291
|
-
|
|
4296
|
+
//#region src/trace/memory-trace-provider.ts
|
|
4297
|
+
/**
|
|
4298
|
+
* In-memory {@link TraceProvider}, populated by one or more
|
|
4299
|
+
* {@link TraceIngestor}s, each connected via `ingestor.addSink(provider)`.
|
|
4300
|
+
*/
|
|
4301
|
+
var MemoryTraceProvider = class extends BaseTraceProvider {
|
|
4302
|
+
traces = /* @__PURE__ */ new Map();
|
|
4303
|
+
spansByTrace = /* @__PURE__ */ new Map();
|
|
4304
|
+
constructor({ id = "memory", displayName = "In-Memory Traces", description = "Stores traces in memory for the current process." } = {}) {
|
|
4305
|
+
super({
|
|
4306
|
+
id,
|
|
4307
|
+
displayName,
|
|
4308
|
+
description
|
|
4309
|
+
});
|
|
4310
|
+
}
|
|
4311
|
+
async getAllTraces() {
|
|
4312
|
+
const summaries = Array.from(this.traces.values()).map((t) => {
|
|
4313
|
+
const spans = this.spansByTrace.get(t.id) ?? [];
|
|
4314
|
+
return {
|
|
4315
|
+
id: t.id,
|
|
4316
|
+
providerId: this.id,
|
|
4317
|
+
name: t.name,
|
|
4318
|
+
startTime: t.startTime,
|
|
4319
|
+
endTime: t.endTime,
|
|
4320
|
+
status: t.status,
|
|
4321
|
+
spanCount: spans.length,
|
|
4322
|
+
...rollupSpans(spans),
|
|
4323
|
+
annotationCounts: {
|
|
4324
|
+
issue: 0,
|
|
4325
|
+
good: 0,
|
|
4326
|
+
note: 0
|
|
4327
|
+
}
|
|
4328
|
+
};
|
|
4329
|
+
});
|
|
4330
|
+
summaries.sort((a, b) => b.startTime - a.startTime);
|
|
4331
|
+
return summaries;
|
|
4332
|
+
}
|
|
4333
|
+
async hasTrace(traceId) {
|
|
4334
|
+
return this.traces.has(traceId);
|
|
4335
|
+
}
|
|
4336
|
+
async getTraceWithoutSpans(traceId) {
|
|
4337
|
+
return this.traces.get(traceId);
|
|
4338
|
+
}
|
|
4339
|
+
async getTraceSpans(traceId) {
|
|
4340
|
+
return this.spansByTrace.get(traceId) ?? [];
|
|
4341
|
+
}
|
|
4342
|
+
async addOrUpdateTrace(trace) {
|
|
4343
|
+
this.traces.set(trace.id, trace);
|
|
4344
|
+
}
|
|
4345
|
+
async removeTrace(traceId) {
|
|
4346
|
+
this.traces.delete(traceId);
|
|
4347
|
+
this.spansByTrace.delete(traceId);
|
|
4348
|
+
}
|
|
4349
|
+
async addOrUpdateSpan(span) {
|
|
4350
|
+
let list = this.spansByTrace.get(span.traceId);
|
|
4351
|
+
if (!list) {
|
|
4352
|
+
list = [];
|
|
4353
|
+
this.spansByTrace.set(span.traceId, list);
|
|
4354
|
+
}
|
|
4355
|
+
const idx = list.findIndex((s) => s.id === span.id);
|
|
4356
|
+
if (idx >= 0) {
|
|
4357
|
+
const merged = mergeSpans(list[idx], span);
|
|
4358
|
+
list[idx] = merged;
|
|
4359
|
+
return merged;
|
|
4360
|
+
}
|
|
4361
|
+
list.push(span);
|
|
4362
|
+
return span;
|
|
4363
|
+
}
|
|
4364
|
+
};
|
|
4365
|
+
//#endregion
|
|
4366
|
+
export { BaseTraceIngestor, BaseTraceProvider, CHECK_ATTRIBUTE, DEFAULT_EVAL_CONCURRENCY, DEFAULT_MAX_QUERY_ROWS, DEFAULT_PLAYGROUND_IGNORE_PATTERNS, DEFAULT_PLAYGROUND_INCLUDE_PATTERNS, DEFAULT_QUERY_TIMEOUT_MS, DEPLOYMENT_ENVIRONMENT_ATTRIBUTE, DatasetNotFoundError, DatasetValidationError, EvalNotFoundError, EvalRunRefusedError, EvalRunner, FilePromptProvider, GeminiInteractionsSDK, GitVersioning, LocalDatabaseTraceProvider, LocalDirectoryDatasetProvider, LocalEvalProvider, LocalFileProvider, LocalVariationStore, MIGRATIONS_TABLE, MemoryFileProvider, MemoryTraceProvider, OTelTraceIngestor, OtlpTraceIngestor, OverlayFileProvider, PLAYGROUND_ENVIRONMENT, PLAYGROUND_RESOURCE, PROMPT_FIELD, PROMPT_IDENTITY, PROMPT_ID_ATTRIBUTE, PROMPT_INPUTS_ATTRIBUTE, PROMPT_NAME_ATTRIBUTE, PROMPT_PROVIDER_ID_ATTRIBUTE, PROMPT_VARIATION_ATTRIBUTE, PROMPT_VERSION_ATTRIBUTE, ResourceRegistry, SERVICE_NAME_ATTRIBUTE, SPAN_KIND_ATTRIBUTE, SqlQueryError, TRACE_QUERY_SCHEMA, TSPromptFileType, TursoDatasetProvider, TursoEvalProvider, TursoTraceProvider, TursoVariationStore, TypeSafeSDK, TypeSafeTelemetry, VariationConflictError, VercelAISDK, VercelAISDKTelemetry, assertUpdateStyle, canonicalizeUpdates, check, collectInputSlots, createLocalTursoClient, createTracerForPrompt, decodeOtlpProtobuf, fieldValuesOf, findInputCycle, getPromptSpanAttributes, inputReferenceProblems, isCheck, isCheckSpan, isResource, isStandardSchema, isValidInstanceName, isVariationLoaderHookRegistered, matchSourcesToSlots, mergeIntoWip, mergePromptIdentity, mergeSpans, mergeUpdates, namedBindings, normalizeOtlpRequest, openLocalEvalProvider, openLocalVariationStore, promptIdOf, rebaseUpdates, registerVariationLoaderHook, resolveConflicts, resolveExecutionInput, resolveExecutionInputs, resource, resourceParameterNames, runDatasetMigrations, runEvalMigrations, runMigrations, runVariationMigrations, serializeUpdates, setupGlobalOTelPipeline, spanMessages, stampReceipts, toPromptRef };
|