@agimon-ai/po-cloudflare 0.0.2-alpha.2 → 0.0.2-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/abort-signals-Bkmp_euQ.js +34 -0
- package/dist/anthropic-messages-CkYm8M3V.js +14317 -0
- package/dist/{approval-BMXqnTYd.js → approval-Eu7UgGL-.js} +1 -1
- package/dist/assets/assets/{CodeEditorView-BnyZHaYM.js → CodeEditorView-rEfljuRK.js} +2 -2
- package/dist/assets/assets/{abnfDiagram-WEYOIA3C-muME0eCj.js → abnfDiagram-WEYOIA3C-J6Iu5p17.js} +2 -2
- package/dist/assets/assets/{architecture-WOLXFQ4H-DMnhK1WH.js → architecture-WOLXFQ4H-DKj_xMR1.js} +1 -1
- package/dist/assets/assets/{architectureDiagram-ZHVYKT53-DKn7XGP7.js → architectureDiagram-ZHVYKT53--D1MzuBo.js} +2 -2
- package/dist/assets/assets/{blockDiagram-RJAE7QA3-DtDctXZg.js → blockDiagram-RJAE7QA3-CrWO0t-Q.js} +2 -2
- package/dist/assets/assets/{c4Diagram-XDPPPE54-23pGLJeP.js → c4Diagram-XDPPPE54-CBMOJREz.js} +2 -2
- package/dist/assets/assets/channel-CNegK3Rr.js +2 -0
- package/dist/assets/assets/{chunk-2E7WHVMD-BZ2nGNPa.js → chunk-2E7WHVMD-CR9NMk46.js} +2 -2
- package/dist/assets/assets/{chunk-4EMNKR2T-Dui1SYFi.js → chunk-4EMNKR2T-B4D0falO.js} +2 -2
- package/dist/assets/assets/{chunk-55XCU76K-CUB92Evl.js → chunk-55XCU76K-CKrttFen.js} +2 -2
- package/dist/assets/assets/{chunk-7S6XSTFO-CVayPHfE.js → chunk-7S6XSTFO-BPNrdjSb.js} +2 -2
- package/dist/assets/assets/{chunk-AQDTSKZB---wakYqY.js → chunk-AQDTSKZB-Ddx2gPU_.js} +2 -2
- package/dist/assets/assets/{chunk-DSNLSHJZ-DfbdohUR.js → chunk-DSNLSHJZ-iQg3RbZ_.js} +2 -2
- package/dist/assets/assets/{chunk-HAGFOTED-Dr4KRh-b.js → chunk-HAGFOTED-CGlDRwnk.js} +2 -2
- package/dist/assets/assets/{chunk-HNE4Q36P-D06cR91Z.js → chunk-HNE4Q36P-CN7VMEsn.js} +2 -2
- package/dist/assets/assets/{chunk-NQOKRVIF-Ca4gLeDb.js → chunk-NQOKRVIF-DQKmIS4j.js} +2 -2
- package/dist/assets/assets/{chunk-UHW7PFBP-DmL638jN.js → chunk-UHW7PFBP-BKSG_d1a.js} +2 -2
- package/dist/assets/assets/{chunk-VQ5W62QI-pkxSW5Zj.js → chunk-VQ5W62QI-AbFHiDOg.js} +2 -2
- package/dist/assets/assets/{chunk-WQQL4CDK-Dcc8hV4U.js → chunk-WQQL4CDK-C5a4DmCb.js} +2 -2
- package/dist/assets/assets/chunk-XXDRQBXY-BbVKQGnw.js +2 -0
- package/dist/assets/assets/{chunk-YZO67HFG-B_HKcFrw.js → chunk-YZO67HFG-UbKezTdY.js} +2 -2
- package/dist/assets/assets/{chunk-ZAUX2LTX-DAzZUysS.js → chunk-ZAUX2LTX-BShGGpRc.js} +2 -2
- package/dist/assets/assets/{chunk-ZCHMQSOR-DAVgjymL.js → chunk-ZCHMQSOR-BmV-PDP0.js} +2 -2
- package/dist/assets/assets/{classDiagram-v2-4MYWR3UA-Fsw8TGPu.js → classDiagram-v2-4MYWR3UA-DB-cfBNq.js} +2 -2
- package/dist/assets/assets/{cose-bilkent-JH36ORCC-CgUbISYV.js → cose-bilkent-JH36ORCC-Dprqh48h.js} +2 -2
- package/dist/assets/assets/{cynefin-EF2NZ3EQ-D1LxAU2x.js → cynefin-EF2NZ3EQ-Bz4CND4n.js} +1 -1
- package/dist/assets/assets/{cynefinDiagram-WF24UDRP-D54I1jil.js → cynefinDiagram-WF24UDRP-Cv0Tq-0q.js} +2 -2
- package/dist/assets/assets/{dagre-NK4GIZVX-DC7zL16U.js → dagre-NK4GIZVX-H4d8oeNm.js} +2 -2
- package/dist/assets/assets/{diagram-CBK3MWTC-DB0ptUdz.js → diagram-CBK3MWTC-D75OthTM.js} +2 -2
- package/dist/assets/assets/{diagram-I5XIIV2D-CozSftPJ.js → diagram-I5XIIV2D-CB_W2jXU.js} +2 -2
- package/dist/assets/assets/{diagram-ODIL2UCW-g3WOEWDS.js → diagram-ODIL2UCW-DPO0lYZ-.js} +2 -2
- package/dist/assets/assets/{diagram-PFBEJUXE-CFxGeOYi.js → diagram-PFBEJUXE-DJ9olXAC.js} +2 -2
- package/dist/assets/assets/{diagram-RJA3I4VV-BQBsLche.js → diagram-RJA3I4VV-DL3974PI.js} +2 -2
- package/dist/assets/assets/{diagram-TYUNFSNR-DrjpW2yq.js → diagram-TYUNFSNR-ZuYESp4p.js} +2 -2
- package/dist/assets/assets/{dist-B3JXhDWV.js → dist-BnkGKHOV.js} +2 -2
- package/dist/assets/assets/{dist-1-mhYUBH.js → dist-C8iSs-hT.js} +2 -2
- package/dist/assets/assets/{dist-XIZum9n5.js → dist-CXqaT1wB.js} +2 -2
- package/dist/assets/assets/{dist-gfbb4ygy.js → dist-CdrEbsAL.js} +2 -2
- package/dist/assets/assets/{dist-h6SOnP8-.js → dist-CeotBqYt.js} +2 -2
- package/dist/assets/assets/{dist-DvgCCshF.js → dist-D2iSi_lg.js} +2 -2
- package/dist/assets/assets/{dist-DjL8d1jZ.js → dist-DvCNYjgK.js} +2 -2
- package/dist/assets/assets/{dist-BabjcJ3j.js → dist-G3vL_xw7.js} +2 -2
- package/dist/assets/assets/{dist-Izr2SB3q.js → dist-zXhaMKmO.js} +2 -2
- package/dist/assets/assets/{ebnfDiagram-V4P3TTPT-BZS_aAve.js → ebnfDiagram-V4P3TTPT-DNfHKEsm.js} +2 -2
- package/dist/assets/assets/{elk-QONTBCTQ-B2ksVmMA.js → elk-QONTBCTQ-C0FX9D60.js} +2 -2
- package/dist/assets/assets/{erDiagram-KYQIGQAA-7P6zF-Z-.js → erDiagram-KYQIGQAA-BI1O9lW0.js} +2 -2
- package/dist/assets/assets/{eventmodeling-K75KTNOO-RoGQoRq-.js → eventmodeling-K75KTNOO-BmWt-aOv.js} +1 -1
- package/dist/assets/assets/flowDiagram-IUGLLWBU-DQj3H5a6.js +1 -0
- package/dist/assets/assets/{ganttDiagram-R7GPNTJY-CTOlRy7M.js → ganttDiagram-R7GPNTJY-pM7PmQ6B.js} +2 -2
- package/dist/assets/assets/{gitGraph-VSP46ZUC-CPqytIt0.js → gitGraph-VSP46ZUC-D0QXMQxv.js} +1 -1
- package/dist/assets/assets/{gitGraphDiagram-PDYL7XHY-BffLxuxg.js → gitGraphDiagram-PDYL7XHY-BsMltgt3.js} +2 -2
- package/dist/assets/assets/index-BTHzc8EN.js +155 -0
- package/dist/assets/assets/{info-OHQRW6UA-BI8RK0Ow.js → info-OHQRW6UA-Dp5Eu5PX.js} +1 -1
- package/dist/assets/assets/{infoDiagram-MVDRKAX5-DUIst1FB.js → infoDiagram-MVDRKAX5-TgXRfZiq.js} +2 -2
- package/dist/assets/assets/{ishikawaDiagram-HPEHV2GE-CA17Eho5.js → ishikawaDiagram-HPEHV2GE-Qzrmih4p.js} +2 -2
- package/dist/assets/assets/{journeyDiagram-BOSHW7O7-CNri5Ap9.js → journeyDiagram-BOSHW7O7-BksI3QOT.js} +2 -2
- package/dist/assets/assets/{kanban-definition-FNSA4HC5-DnXna7jO.js → kanban-definition-FNSA4HC5-l_IuN5_k.js} +2 -2
- package/dist/assets/assets/{line-BsXJZn93.js → line-BDKssGoM.js} +2 -2
- package/dist/assets/assets/{linear-BHYaD5T0.js → linear-C9vmtzBC.js} +2 -2
- package/dist/assets/assets/{mermaid-parser.core-B64Eo-8a.js → mermaid-parser.core-O1yFX7K_.js} +4 -4
- package/dist/assets/assets/{mermaid.core-Zw9qmTzg.js → mermaid.core-CIq57361.js} +5 -5
- package/dist/assets/assets/{mindmap-definition-6OY57UG3-E5qz4KNc.js → mindmap-definition-6OY57UG3-BkVuZ010.js} +2 -2
- package/dist/assets/assets/{packet-JDAUHWVQ-DgfizTr3.js → packet-JDAUHWVQ-PPNcSWeV.js} +1 -1
- package/dist/assets/assets/{pegDiagram-ECIUJNBX-D0WK_agM.js → pegDiagram-ECIUJNBX-ClwrHXhM.js} +2 -2
- package/dist/assets/assets/{pie-XZMESJXO-PJR1sXD4.js → pie-XZMESJXO-BAE4Cy9j.js} +1 -1
- package/dist/assets/assets/{pieDiagram-GNMPY74T-CPuU-NTs.js → pieDiagram-GNMPY74T-CvQ62Knb.js} +2 -2
- package/dist/assets/assets/{quadrantDiagram-D57K4MC3-5C9yjM1b.js → quadrantDiagram-D57K4MC3-CzAyT5ZB.js} +2 -2
- package/dist/assets/assets/{radar-ABXABTNO-BspdXgl0.js → radar-ABXABTNO-CoEe8B7b.js} +1 -1
- package/dist/assets/assets/{railroad-I3PHUGI6-Ct0a6hLD.js → railroad-I3PHUGI6-BbK5J8H5.js} +1 -1
- package/dist/assets/assets/{railroad-abnf-LNEFI6M7-fduYB4SA.js → railroad-abnf-LNEFI6M7-DlGngfop.js} +1 -1
- package/dist/assets/assets/{railroad-ebnf-DWYD2UWJ-CTQa8Sww.js → railroad-ebnf-DWYD2UWJ-BRk4ifMx.js} +1 -1
- package/dist/assets/assets/{railroad-peg-JR7BVNR7-DatoH3GJ.js → railroad-peg-JR7BVNR7-Rz-3vbj2.js} +1 -1
- package/dist/assets/assets/{railroadDiagram-Y72NRBL7-C8sWN8l2.js → railroadDiagram-Y72NRBL7-DQISBRHH.js} +2 -2
- package/dist/assets/assets/{requirementDiagram-EQYSW5RA-CqRz4RcT.js → requirementDiagram-EQYSW5RA-DcK4FnTB.js} +2 -2
- package/dist/assets/assets/{sankeyDiagram-SY24JHO5-bdiuKKlX.js → sankeyDiagram-SY24JHO5-N2EXBOYb.js} +2 -2
- package/dist/assets/assets/{sequenceDiagram-BLEHNHQU-Zy-8I0Hy.js → sequenceDiagram-BLEHNHQU-CMJ2EqC_.js} +2 -2
- package/dist/assets/assets/{src-gihY33R9.js → src-Df9VBjd7.js} +2 -2
- package/dist/assets/assets/{stateDiagram-v2-A6IESKWZ-DXQERPvz.js → stateDiagram-v2-A6IESKWZ-D6Cxm8wj.js} +2 -2
- package/dist/assets/assets/{swimlanes-B3ENRKFQ-1gjZQElg.js → swimlanes-B3ENRKFQ-BybuzSPd.js} +2 -2
- package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-CXJkO6sc.js +9 -0
- package/dist/assets/assets/{timeline-definition-JXYKGLGB-CTeYEw-9.js → timeline-definition-JXYKGLGB-BzjkWUdz.js} +2 -2
- package/dist/assets/assets/{treeView-D4JQ5SDB-DD-EsLLT.js → treeView-D4JQ5SDB-DIDWwDtU.js} +1 -1
- package/dist/assets/assets/{treemap-SAJKECNS-BLdFeS5J.js → treemap-SAJKECNS-SWP4JszI.js} +1 -1
- package/dist/assets/assets/{usecaseDiagram-WPOLBNNX-C1GikSSP.js → usecaseDiagram-WPOLBNNX-ZfCxSJdE.js} +2 -2
- package/dist/assets/assets/{vennDiagram-Q3Y3IDCW-B1FoA3g8.js → vennDiagram-Q3Y3IDCW-o44wkgGH.js} +2 -2
- package/dist/assets/assets/{wardley-7MLQ67FV-BrHb5Bjf.js → wardley-7MLQ67FV-0zKRsI4Z.js} +1 -1
- package/dist/assets/assets/{wardleyDiagram-IVAIDKWA-CmPLD1X4.js → wardleyDiagram-IVAIDKWA-CyBVyB40.js} +2 -2
- package/dist/assets/assets/{webpack-BYWDFj_R.js → webpack-C4nkEwJD.js} +2 -2
- package/dist/assets/assets/{xychartDiagram-4URNHDU4-DR5pfEjl.js → xychartDiagram-4URNHDU4-BMvRihYC.js} +2 -2
- package/dist/assets/bundle-asset-policy.json +1 -1
- package/dist/assets/index.html +1 -1
- package/dist/assets/plugins/assets/base-B5jpmLBl.css +2 -0
- package/dist/assets/plugins/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
- package/dist/assets/plugins/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
- package/dist/assets/plugins/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
- package/dist/assets/plugins/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
- package/dist/assets/plugins/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
- package/dist/assets/plugins/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
- package/dist/assets/plugins/assets/jetbrains-mono-cyrillic-ext-wght-normal-EocZY2iu.woff2 +0 -0
- package/dist/assets/plugins/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/assets/plugins/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/assets/plugins/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/assets/plugins/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/assets/plugins/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/assets/plugins/chunks/po-web-runtime-D4qQFtJO.js +1 -0
- package/dist/assets/plugins/compositions.json +1 -0
- package/dist/assets/plugins/slots/approval.09e72f36-Cck_K9ex.js +2 -0
- package/dist/assets/plugins/slots/artifacts.50b639bb-BZM7uEbe.js +1 -0
- package/dist/assets/plugins/slots/builtin-tools.75108f21-EWWGTveL.js +7 -0
- package/dist/assets/plugins/slots/codemode.c58fb583-CgfTL6kt.js +9 -0
- package/dist/assets/plugins/slots/domain.753f9f92-BU0ilfwM.js +1 -0
- package/dist/assets/plugins/slots/mcp.82cc1ff5-BaCD2xZB.js +109 -0
- package/dist/assets/plugins/slots/profile.ab16dcec-Cu6ev2uW.js +1 -0
- package/dist/assets/plugins/slots/skill.62a0a1b3-Bz20F1eA.js +4 -0
- package/dist/{atomicJson-BJfPFSYF.js → atomicJson-DwSqByUJ.js} +3 -3
- package/dist/azure-openai-config-DHMgdIa-.js +55 -0
- package/dist/azure-openai-responses-CTgRdQ4m.js +183 -0
- package/dist/backgroundWork-bE3pc-R9.js +25 -0
- package/dist/classifier-shared-jXm-plIK.js +106 -0
- package/dist/cloudflare-workers-ai-system-one-B0wH6HU5.js +52 -0
- package/dist/{codemode-DbPu0yJN.js → codemode-yHAHBZO-.js} +1 -1
- package/dist/diagnostics-DPTP-yrt.js +131 -0
- package/dist/dist-Dvx5mlIR.js +50 -0
- package/dist/{domains-BNjGTOPj.js → domains-dHfk2U8X.js} +4 -4
- package/dist/env-api-keys-CAnjjnsR.js +32 -0
- package/dist/error-body-DQZRsyL5.js +102 -0
- package/dist/{exports-BNZz2DNU.js → exports-CrJqsTU6.js} +8 -8
- package/dist/{extensionFile-CXOa5G4C.js → extensionFile-CY4EFNHQ.js} +1 -1
- package/dist/github-copilot-headers-DpQQAh-s.js +22 -0
- package/dist/google-generative-ai-BTTOo5RQ.js +328 -0
- package/dist/google-shared-S7bqOccz.js +19588 -0
- package/dist/google-vertex-BcMU_DMb.js +374 -0
- package/dist/{harnessStore-BT706Ly6.js → harnessStore-CRtlTdbI.js} +4 -4
- package/dist/harnessStore-DZ4lDIq6.js +1 -0
- package/dist/hash-B3RRpLS2.js +16 -0
- package/dist/headers-BEuxFxDI.js +17 -0
- package/dist/{hubChannel-BHQyzcOo.js → hubChannel-Cj1iF847.js} +1 -1
- package/dist/identity-BIeAyilV.js +165 -0
- package/dist/{layeredConfig-DPQAnlXD.js → layeredConfig-BqIwPJ-I.js} +3 -3
- package/dist/majorModes-AYZvnOpU.js +1 -0
- package/dist/{majorModes-DbCfLZH3.js → majorModes-C-OD4PBc.js} +4 -4
- package/dist/mistral-conversations-DN8VSERk.js +689 -0
- package/dist/models-D6d73jcW.js +1511 -0
- package/dist/node-DytJOfYf.js +23 -0
- package/dist/node-UuMT2C3q.js +2479 -0
- package/dist/openai-bt3ZRBZv.js +17357 -0
- package/dist/openai-codex-responses-cL36x0ml.js +1210 -0
- package/dist/openai-completions-BWsTNYyT.js +984 -0
- package/dist/openai-decisions-Dfn_KgQd.js +142 -0
- package/dist/openai-prompt-cache-Bc6qNWt0.js +8 -0
- package/dist/openai-responses-aa0LoyCJ.js +281 -0
- package/dist/openai-responses-shared-H-jH5SlM.js +661 -0
- package/dist/openrouter-cost-D99Qqcs6.js +30 -0
- package/dist/openrouter-images-BpwVpALC.js +124 -0
- package/dist/pi-messages-BHAIkYBj.js +312 -0
- package/dist/{platform-B4AAgwJ0.js → platform-CNhm9zLi.js} +1 -1
- package/dist/{platformFiles-C_bXo4Ig.js → platformFiles-3rzOh9cg.js} +1 -1
- package/dist/provider-env-DgfpjgTa.js +38 -0
- package/dist/provider-retry-ChD-K2Gv.js +79 -0
- package/dist/{remoteMcp-CMqZldeA.js → remoteMcp-Ci8crSU9.js} +1 -1
- package/dist/sanitize-unicode-Dl4ROF7y.js +26 -0
- package/dist/{server-BZh1ZXz_.js → server-B2xd7WTP.js} +4 -4
- package/dist/{server-DJAanjoI.js → server-BPvd3Ya5.js} +6 -6
- package/dist/{server-D4W7EdJY.js → server-BccTx_r6.js} +11 -10
- package/dist/{server-BZaPPoQp.js → server-Bf3_VTkt.js} +9 -9
- package/dist/{server-tvgQ99rv.js → server-BmAziQml.js} +4 -4
- package/dist/{server-r358hzQg.js → server-BvV-GqDO.js} +3 -3
- package/dist/{server-BAAL9-NA.js → server-C1ijZQp4.js} +2 -2
- package/dist/{server-BE6VqEiA.js → server-CUvohcAm.js} +4 -4
- package/dist/{server-D8ndq0wL.js → server-CYQHzqaQ.js} +2 -2
- package/dist/{server-Dt4y1rZD.js → server-De_PIOty.js} +5 -5
- package/dist/{server-A-_GFpPr.js → server-DrZBZ17y.js} +7 -7
- package/dist/{server-Dpgh8PDh.js → server-DwWTQg1J.js} +4 -4
- package/dist/{server-D75MWDhB.js → server-xiuzwJ1C.js} +2 -2
- package/dist/{server-D3PQk1Gt.js → server-y9pjeHJM.js} +3 -3
- package/dist/{serverPlugin-BOI6c6s5.js → serverPlugin-H4T49sac.js} +4 -50
- package/dist/{sessionConfig-rBQgzXlT.js → sessionConfig-2a4LWInR.js} +8 -8
- package/dist/simple-options-DWrW31_K.js +156 -0
- package/dist/streaming-json-t4rzNHEp.js +858 -0
- package/dist/system-one-shared-DLVLdzYL.js +132 -0
- package/dist/transform-messages-CjTSwW9q.js +356 -0
- package/dist/typesafe-system-one-DBVcjcUQ.js +37 -0
- package/dist/uuid-mkNGilLv.js +31 -0
- package/dist/worker.js +56113 -21793
- package/package.json +22 -22
- package/dist/assets/assets/channel-CMrEzemr.js +0 -2
- package/dist/assets/assets/chunk-XXDRQBXY-CFf0S6bN.js +0 -2
- package/dist/assets/assets/flowDiagram-IUGLLWBU-BhGbWVf0.js +0 -1
- package/dist/assets/assets/index-Bx_K4Joy.js +0 -155
- package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-q91tR8ri.js +0 -9
- package/dist/backgroundWork-CeFrbRnj.js +0 -43
- package/dist/harnessStore-BiH9vSuD.js +0 -1
- package/dist/majorModes-BvWNqoHt.js +0 -1
- package/dist/server-36iuA3MI.js +0 -343
|
@@ -0,0 +1,1511 @@
|
|
|
1
|
+
import { i as NOOP_TELEMETRY_METRICS, n as defineTelemetrySchema, r as NOOP_TELEMETRY_CONTEXT, t as createTypedSpanStarter } from "./dist-Dvx5mlIR.js";
|
|
2
|
+
import { c as ownedSlice, i as mergeClientIdentity, o as contentText, r as getOpenCodeSessionHeaders, s as getSystemMessageText } from "./identity-BIeAyilV.js";
|
|
3
|
+
import { i as AssistantMessageEventStream, r as formatThrownValue } from "./diagnostics-DPTP-yrt.js";
|
|
4
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-telemetry@1.5.0/node_modules/@earendil-works/pi-telemetry/dist/metrics.js
|
|
5
|
+
/** Bind instrument names, kinds, metadata, and exact measurement attributes to one or more schemas. */
|
|
6
|
+
function createTypedMetrics(metrics, schemas) {
|
|
7
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
8
|
+
for (const schema of schemas) for (const [name, definition] of Object.entries(schema.metrics ?? {})) definitions.set(name, definition);
|
|
9
|
+
return {
|
|
10
|
+
counter: (name) => metrics.counter(name, definitions.get(name)),
|
|
11
|
+
upDownCounter: (name) => metrics.upDownCounter(name, definitions.get(name)),
|
|
12
|
+
histogram: (name) => metrics.histogram(name, definitions.get(name))
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/utils/transcript.js
|
|
17
|
+
/**
|
|
18
|
+
* Build the leading system message for a prompt and tool set. Returns undefined when
|
|
19
|
+
* both are empty, so an empty transcript stays empty.
|
|
20
|
+
*/
|
|
21
|
+
function createInitialSystemMessage(systemPrompt, tools) {
|
|
22
|
+
const hasSystemPrompt = systemPrompt !== void 0 && systemPrompt.length > 0;
|
|
23
|
+
const hasTools = tools !== void 0 && tools.length > 0;
|
|
24
|
+
if (!hasSystemPrompt && !hasTools) return void 0;
|
|
25
|
+
return {
|
|
26
|
+
role: "system",
|
|
27
|
+
content: systemPrompt ?? "",
|
|
28
|
+
...hasTools ? { toolsAdded: tools } : {},
|
|
29
|
+
timestamp: 0
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Fold `Context.systemPrompt` and `Context.tools` into a leading system message.
|
|
34
|
+
* This is the only entry point that produces a {@link TranscriptContext}; every
|
|
35
|
+
* provider-facing function expects the result.
|
|
36
|
+
*/
|
|
37
|
+
function normalizeContext(context) {
|
|
38
|
+
const initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);
|
|
39
|
+
return { messages: initialMessage ? [initialMessage, ...context.messages] : context.messages };
|
|
40
|
+
}
|
|
41
|
+
function isSystemMessage(message) {
|
|
42
|
+
return message.role === "system";
|
|
43
|
+
}
|
|
44
|
+
/** Return the leading system message, if the transcript starts with one. */
|
|
45
|
+
function getInitialSystemMessage(messages) {
|
|
46
|
+
const first = messages[0];
|
|
47
|
+
return first && isSystemMessage(first) ? first : void 0;
|
|
48
|
+
}
|
|
49
|
+
/** Drop the leading system message for APIs that carry the prompt outside the message list. */
|
|
50
|
+
function withoutInitialSystemMessage(messages) {
|
|
51
|
+
return getInitialSystemMessage(messages) ? messages.slice(1) : messages;
|
|
52
|
+
}
|
|
53
|
+
/** Resolve the tools available after applying every transcript delta in order. */
|
|
54
|
+
function getCurrentTools(messages) {
|
|
55
|
+
const tools = /* @__PURE__ */ new Map();
|
|
56
|
+
for (const message of messages) {
|
|
57
|
+
if (!isSystemMessage(message)) continue;
|
|
58
|
+
for (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);
|
|
59
|
+
for (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);
|
|
60
|
+
}
|
|
61
|
+
return [...tools.values()];
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Replay every system message into one leading system message holding the current
|
|
65
|
+
* prompt and tools. Later `content` is appended to the base prompt, `sections` are
|
|
66
|
+
* patched by name, and tools are resolved with {@link getCurrentTools}.
|
|
67
|
+
*/
|
|
68
|
+
function getCurrentSystemMessage(messages) {
|
|
69
|
+
const content = [];
|
|
70
|
+
const sections = /* @__PURE__ */ new Map();
|
|
71
|
+
let timestamp;
|
|
72
|
+
for (const message of messages) {
|
|
73
|
+
if (!isSystemMessage(message)) continue;
|
|
74
|
+
timestamp ??= message.timestamp;
|
|
75
|
+
const text = contentText(message.content);
|
|
76
|
+
if (text.length > 0) content.push(text);
|
|
77
|
+
for (const [name, value] of Object.entries(message.sections ?? {})) if (value === null) sections.delete(name);
|
|
78
|
+
else sections.set(name, value);
|
|
79
|
+
}
|
|
80
|
+
const tools = getCurrentTools(messages);
|
|
81
|
+
if (timestamp === void 0 && tools.length === 0) return void 0;
|
|
82
|
+
return {
|
|
83
|
+
role: "system",
|
|
84
|
+
content: content.join("\n\n"),
|
|
85
|
+
...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {},
|
|
86
|
+
...tools.length > 0 ? { toolsAdded: tools } : {},
|
|
87
|
+
timestamp: timestamp ?? 0
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** Render the current system prompt text after replaying every system message. */
|
|
91
|
+
function getCurrentSystemPrompt(messages) {
|
|
92
|
+
const message = getCurrentSystemMessage(messages);
|
|
93
|
+
return message ? getSystemMessageText(message) : "";
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Rebuild the transcript for APIs without mid-conversation system messages: the replayed
|
|
97
|
+
* system message leads, and every later system message is dropped.
|
|
98
|
+
*/
|
|
99
|
+
function collapseSystemMessages(context) {
|
|
100
|
+
const head = getCurrentSystemMessage(context.messages);
|
|
101
|
+
const messages = context.messages.filter((message) => message.role !== "system");
|
|
102
|
+
return { messages: head ? [head, ...messages] : messages };
|
|
103
|
+
}
|
|
104
|
+
/** Keep later system messages in place when the model accepts them; otherwise collapse them. */
|
|
105
|
+
function resolveTranscript(context, supportsMidConvoSystemMessages) {
|
|
106
|
+
return supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);
|
|
107
|
+
}
|
|
108
|
+
/** Strip executable and display-only fields from a tool before transcript comparison or persistence. */
|
|
109
|
+
function toToolDeclaration(tool) {
|
|
110
|
+
return {
|
|
111
|
+
name: tool.name,
|
|
112
|
+
description: tool.description,
|
|
113
|
+
parameters: JSON.parse(JSON.stringify(tool.parameters)),
|
|
114
|
+
...tool.constrainedSampling === void 0 ? {} : { constrainedSampling: tool.constrainedSampling }
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Whether two tools declare the same interface to the model.
|
|
119
|
+
*
|
|
120
|
+
* Both sides go through {@link toToolDeclaration} first: its JSON round-trip drops the
|
|
121
|
+
* schema metadata keys (TypeBox's non-enumerable kind marks) and `undefined` fields that a structural comparison would see, and
|
|
122
|
+
* builds both objects with the same key order, so comparing the serialized declarations
|
|
123
|
+
* is exact. This avoids a deep-equal dependency in a browser-safe package.
|
|
124
|
+
*/
|
|
125
|
+
function declarationsEqual(left, right) {
|
|
126
|
+
return JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));
|
|
127
|
+
}
|
|
128
|
+
/** Every definition referenced by transcript tool state, in first-declaration order. */
|
|
129
|
+
function getDeclaredTools(messages) {
|
|
130
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
131
|
+
for (const message of messages) {
|
|
132
|
+
if (!isSystemMessage(message)) continue;
|
|
133
|
+
for (const tool of message.toolsAdded ?? []) definitions.set(tool.name, tool);
|
|
134
|
+
}
|
|
135
|
+
return [...definitions.values()];
|
|
136
|
+
}
|
|
137
|
+
/** Index of the last system message with a removal or same-name redeclaration, or -1. */
|
|
138
|
+
function findLastNonAdditiveToolChange(systemMessages) {
|
|
139
|
+
const declared = /* @__PURE__ */ new Set();
|
|
140
|
+
let last = -1;
|
|
141
|
+
for (let index = 0; index < systemMessages.length; index++) {
|
|
142
|
+
const message = systemMessages[index];
|
|
143
|
+
if ((message.toolsRemoved?.length ?? 0) > 0) last = index;
|
|
144
|
+
for (const tool of message.toolsAdded ?? []) {
|
|
145
|
+
if (declared.has(tool.name)) last = index;
|
|
146
|
+
declared.add(tool.name);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return last;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Split tool declarations between the top-level request field and in-place changes.
|
|
153
|
+
*
|
|
154
|
+
* With `"changes"`, the top-level list stays empty and every system message, including the
|
|
155
|
+
* leading one, declares its tools in place: an in-place declaration can replace an earlier
|
|
156
|
+
* in-place one, but not a top-level one. With `"additions"`, a removal or redefinition cannot be
|
|
157
|
+
* expressed in place, so the top-level list becomes the tool state after the last such change;
|
|
158
|
+
* later additions stay anchored, and the cached prefix is invalidated once per removal instead
|
|
159
|
+
* of on every later addition. With `"none"`, the top-level list is the current tool set.
|
|
160
|
+
*/
|
|
161
|
+
function resolveTranscriptTools(messages, support) {
|
|
162
|
+
const systemMessages = messages.filter(isSystemMessage);
|
|
163
|
+
if (support === "none") return {
|
|
164
|
+
requestTools: getCurrentTools(systemMessages),
|
|
165
|
+
foldedSystemMessages: systemMessages.length
|
|
166
|
+
};
|
|
167
|
+
if (support === "changes") return {
|
|
168
|
+
requestTools: [],
|
|
169
|
+
foldedSystemMessages: 0
|
|
170
|
+
};
|
|
171
|
+
const folded = Math.max(getInitialSystemMessage(messages) ? 1 : 0, findLastNonAdditiveToolChange(systemMessages) + 1);
|
|
172
|
+
return {
|
|
173
|
+
requestTools: getCurrentTools(systemMessages.slice(0, folded)),
|
|
174
|
+
foldedSystemMessages: folded
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
//#endregion
|
|
178
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/api/lazy.js
|
|
179
|
+
function createSetupErrorMessage(model, error, timestamp) {
|
|
180
|
+
return {
|
|
181
|
+
role: "assistant",
|
|
182
|
+
content: [],
|
|
183
|
+
api: model.api,
|
|
184
|
+
provider: model.provider,
|
|
185
|
+
model: model.id,
|
|
186
|
+
usage: {
|
|
187
|
+
input: 0,
|
|
188
|
+
output: 0,
|
|
189
|
+
cacheRead: 0,
|
|
190
|
+
cacheWrite: 0,
|
|
191
|
+
totalTokens: 0,
|
|
192
|
+
cost: {
|
|
193
|
+
input: 0,
|
|
194
|
+
output: 0,
|
|
195
|
+
cacheRead: 0,
|
|
196
|
+
cacheWrite: 0,
|
|
197
|
+
total: 0
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
stopReason: "error",
|
|
201
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
202
|
+
timestamp
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
function hasResult(source) {
|
|
206
|
+
return typeof source.result === "function";
|
|
207
|
+
}
|
|
208
|
+
async function forwardStream(target, source, observer, observeResult) {
|
|
209
|
+
let result;
|
|
210
|
+
for await (const event of source) {
|
|
211
|
+
target.push(event);
|
|
212
|
+
observer?.onEvent?.(event);
|
|
213
|
+
if (event.type === "done") result = event.message;
|
|
214
|
+
else if (event.type === "error") result = event.error;
|
|
215
|
+
}
|
|
216
|
+
if (hasResult(source)) result = await source.result();
|
|
217
|
+
target.end(result);
|
|
218
|
+
observeResult(result);
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Returns a stream synchronously while running async setup (auth resolution,
|
|
222
|
+
* lazy module loading) behind it. Setup failures terminate the stream with an
|
|
223
|
+
* error event.
|
|
224
|
+
*/
|
|
225
|
+
function lazyStream(model, setup, observer) {
|
|
226
|
+
const startedAt = Date.now();
|
|
227
|
+
const outer = new AssistantMessageEventStream();
|
|
228
|
+
let observedResult = false;
|
|
229
|
+
const observeResult = (result) => {
|
|
230
|
+
if (observedResult) return;
|
|
231
|
+
observedResult = true;
|
|
232
|
+
observer?.onResult?.(result);
|
|
233
|
+
};
|
|
234
|
+
setup().then((inner) => forwardStream(outer, inner, observer, observeResult)).catch((error) => {
|
|
235
|
+
const message = createSetupErrorMessage(model, error, startedAt);
|
|
236
|
+
const event = {
|
|
237
|
+
type: "error",
|
|
238
|
+
reason: "error",
|
|
239
|
+
error: message
|
|
240
|
+
};
|
|
241
|
+
outer.push(event);
|
|
242
|
+
observer?.onEvent?.(event);
|
|
243
|
+
outer.end(message);
|
|
244
|
+
observeResult(message);
|
|
245
|
+
});
|
|
246
|
+
return outer;
|
|
247
|
+
}
|
|
248
|
+
function lazyApi(load, capabilities) {
|
|
249
|
+
const api = {
|
|
250
|
+
stream: (model, context, options) => lazyStream(model, async () => (await load()).stream(model, context, options)),
|
|
251
|
+
streamSimple: (model, context, options) => lazyStream(model, async () => (await load()).streamSimple(model, context, options))
|
|
252
|
+
};
|
|
253
|
+
if (capabilities?.fetchDeferred) api.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
|
|
254
|
+
const implementation = await load();
|
|
255
|
+
if (!implementation.fetchDeferred) throw new Error("API does not support deferred responses");
|
|
256
|
+
return implementation.fetchDeferred(model, handle, options);
|
|
257
|
+
});
|
|
258
|
+
if (capabilities?.cancelDeferred) api.cancelDeferred = async (model, handle, options) => {
|
|
259
|
+
const implementation = await load();
|
|
260
|
+
if (!implementation.cancelDeferred) throw new Error("API cannot cancel deferred responses");
|
|
261
|
+
await implementation.cancelDeferred(model, handle, options);
|
|
262
|
+
};
|
|
263
|
+
return api;
|
|
264
|
+
}
|
|
265
|
+
//#endregion
|
|
266
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/auth/context.js
|
|
267
|
+
var __rewriteRelativeImportExtension = function(path, preserveJsx) {
|
|
268
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
|
|
269
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
|
|
270
|
+
});
|
|
271
|
+
return path;
|
|
272
|
+
};
|
|
273
|
+
const importNodeModule = (specifier) => import(__rewriteRelativeImportExtension(specifier));
|
|
274
|
+
function getProcessEnv() {
|
|
275
|
+
return globalThis.process?.env;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Default auth context: env vars from `process.env` (undefined in browsers),
|
|
279
|
+
* file existence via node:fs (always false in browsers).
|
|
280
|
+
*/
|
|
281
|
+
function defaultProviderAuthContext() {
|
|
282
|
+
return {
|
|
283
|
+
async env(name) {
|
|
284
|
+
const value = getProcessEnv()?.[name];
|
|
285
|
+
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
286
|
+
},
|
|
287
|
+
async fileExists(path) {
|
|
288
|
+
try {
|
|
289
|
+
const fs = await importNodeModule("node:fs/promises");
|
|
290
|
+
let resolved = path;
|
|
291
|
+
if (resolved.startsWith("~")) resolved = (await importNodeModule("node:os")).homedir() + resolved.slice(1);
|
|
292
|
+
await fs.access(resolved);
|
|
293
|
+
return true;
|
|
294
|
+
} catch {
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
//#endregion
|
|
301
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/utils/abort.js
|
|
302
|
+
function abortReason(signal) {
|
|
303
|
+
if (signal.reason !== void 0) return signal.reason;
|
|
304
|
+
const error = /* @__PURE__ */ new Error("The operation was aborted");
|
|
305
|
+
error.name = "AbortError";
|
|
306
|
+
return error;
|
|
307
|
+
}
|
|
308
|
+
/** Create an operation-local signal for public APIs whose signal is optional. */
|
|
309
|
+
function operationSignal(signal) {
|
|
310
|
+
return signal ?? new AbortController().signal;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Stop waiting for an operation when its signal aborts while continuing to
|
|
314
|
+
* observe the abandoned promise so a later rejection is always handled.
|
|
315
|
+
*/
|
|
316
|
+
function raceWithAbortSignal(operation, signal) {
|
|
317
|
+
if (signal.aborted) {
|
|
318
|
+
operation.catch(() => {});
|
|
319
|
+
return Promise.reject(abortReason(signal));
|
|
320
|
+
}
|
|
321
|
+
return new Promise((resolve, reject) => {
|
|
322
|
+
let settled = false;
|
|
323
|
+
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
324
|
+
const onAbort = () => {
|
|
325
|
+
if (settled) return;
|
|
326
|
+
settled = true;
|
|
327
|
+
cleanup();
|
|
328
|
+
reject(abortReason(signal));
|
|
329
|
+
};
|
|
330
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
331
|
+
operation.then((value) => {
|
|
332
|
+
if (settled) return;
|
|
333
|
+
settled = true;
|
|
334
|
+
cleanup();
|
|
335
|
+
resolve(value);
|
|
336
|
+
}, (error) => {
|
|
337
|
+
if (settled) return;
|
|
338
|
+
settled = true;
|
|
339
|
+
cleanup();
|
|
340
|
+
reject(error);
|
|
341
|
+
});
|
|
342
|
+
if (signal.aborted) onAbort();
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
//#endregion
|
|
346
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js
|
|
347
|
+
/**
|
|
348
|
+
* Default in-memory credential store. Apps inject persistent stores.
|
|
349
|
+
* Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.
|
|
350
|
+
* Writes are serialized per provider through a promise chain.
|
|
351
|
+
*/
|
|
352
|
+
var InMemoryCredentialStore = class {
|
|
353
|
+
credentials = /* @__PURE__ */ new Map();
|
|
354
|
+
chains = /* @__PURE__ */ new Map();
|
|
355
|
+
/** Serialize tasks per provider id without releasing the chain before active work settles. */
|
|
356
|
+
enqueue(providerId, task, options) {
|
|
357
|
+
const signal = operationSignal(options?.signal);
|
|
358
|
+
const previous = this.chains.get(providerId) ?? Promise.resolve();
|
|
359
|
+
const queued = (async () => {
|
|
360
|
+
await previous.catch(() => {});
|
|
361
|
+
signal.throwIfAborted();
|
|
362
|
+
return task();
|
|
363
|
+
})();
|
|
364
|
+
const tail = queued.catch(() => {});
|
|
365
|
+
this.chains.set(providerId, tail);
|
|
366
|
+
tail.then(() => {
|
|
367
|
+
if (this.chains.get(providerId) === tail) this.chains.delete(providerId);
|
|
368
|
+
});
|
|
369
|
+
return raceWithAbortSignal(queued, signal);
|
|
370
|
+
}
|
|
371
|
+
async read(providerId, options) {
|
|
372
|
+
options?.signal?.throwIfAborted();
|
|
373
|
+
return this.credentials.get(providerId);
|
|
374
|
+
}
|
|
375
|
+
async list(options) {
|
|
376
|
+
options?.signal?.throwIfAborted();
|
|
377
|
+
return [...this.credentials].map(([providerId, credential]) => ({
|
|
378
|
+
providerId,
|
|
379
|
+
type: credential.type
|
|
380
|
+
}));
|
|
381
|
+
}
|
|
382
|
+
modify(providerId, fn, options) {
|
|
383
|
+
return this.enqueue(providerId, async () => {
|
|
384
|
+
const current = this.credentials.get(providerId);
|
|
385
|
+
const next = await fn(current);
|
|
386
|
+
options?.signal?.throwIfAborted();
|
|
387
|
+
if (next !== void 0) this.credentials.set(providerId, next);
|
|
388
|
+
return next ?? current;
|
|
389
|
+
}, options);
|
|
390
|
+
}
|
|
391
|
+
delete(providerId, options) {
|
|
392
|
+
return this.enqueue(providerId, async () => {
|
|
393
|
+
this.credentials.delete(providerId);
|
|
394
|
+
}, options);
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
//#endregion
|
|
398
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/utils/models-error.js
|
|
399
|
+
var ModelsError = class extends Error {
|
|
400
|
+
code;
|
|
401
|
+
constructor(code, message, options) {
|
|
402
|
+
super(withCauseDetail(message, options?.cause), options);
|
|
403
|
+
this.name = "ModelsError";
|
|
404
|
+
this.code = code;
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
/** Callers surface `error.message` only, so keep the underlying reason in it. */
|
|
408
|
+
function withCauseDetail(message, cause) {
|
|
409
|
+
if (cause === void 0 || cause === null) return message;
|
|
410
|
+
const detail = formatThrownValue(cause).trim();
|
|
411
|
+
if (!detail || message.includes(detail)) return message;
|
|
412
|
+
return `${message}: ${detail}`;
|
|
413
|
+
}
|
|
414
|
+
//#endregion
|
|
415
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js
|
|
416
|
+
/**
|
|
417
|
+
* Auth resolution shared by all operations in a `Models` collection.
|
|
418
|
+
* A stored credential owns the provider: ambient/env is consulted only when
|
|
419
|
+
* nothing is stored. No silent env fallback after a failed refresh or for a
|
|
420
|
+
* credential type without a matching handler.
|
|
421
|
+
*/
|
|
422
|
+
function resolveProviderAuth(provider, credentials, authContext, overrides) {
|
|
423
|
+
const signal = operationSignal(overrides?.signal);
|
|
424
|
+
return raceWithAbortSignal(resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal), signal);
|
|
425
|
+
}
|
|
426
|
+
async function resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal) {
|
|
427
|
+
signal.throwIfAborted();
|
|
428
|
+
const requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;
|
|
429
|
+
if (overrides?.apiKey !== void 0 && provider.auth.apiKey) return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, {
|
|
430
|
+
type: "api_key",
|
|
431
|
+
key: overrides.apiKey,
|
|
432
|
+
env: overrides.env
|
|
433
|
+
}, signal);
|
|
434
|
+
const stored = await readCredential(credentials, provider.id, signal);
|
|
435
|
+
if (stored) {
|
|
436
|
+
if (stored.type === "oauth" && provider.auth.oauth) return resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored, signal, overrides?.minOAuthValidityMs);
|
|
437
|
+
if (stored.type === "api_key" && provider.auth.apiKey) {
|
|
438
|
+
const credential = overrides?.env ? {
|
|
439
|
+
...stored,
|
|
440
|
+
env: {
|
|
441
|
+
...stored.env,
|
|
442
|
+
...overrides.env
|
|
443
|
+
}
|
|
444
|
+
} : stored;
|
|
445
|
+
return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);
|
|
446
|
+
}
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
return provider.auth.apiKey ? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, void 0, signal) : void 0;
|
|
450
|
+
}
|
|
451
|
+
function overlayEnvAuthContext(base, env) {
|
|
452
|
+
return {
|
|
453
|
+
env: async (name) => env[name] || await base.env(name),
|
|
454
|
+
fileExists: (path) => base.fileExists(path)
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
const DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 3e5;
|
|
458
|
+
const DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15e3;
|
|
459
|
+
/**
|
|
460
|
+
* Refresh a stored OAuth credential under the credential-store lock and persist
|
|
461
|
+
* the result before the lock is released. `needsRefresh` is re-checked under
|
|
462
|
+
* the lock, so concurrent callers and processes refresh only once.
|
|
463
|
+
*
|
|
464
|
+
* `signal` cancels only the wait for the lock. Once a refresh starts, the
|
|
465
|
+
* provider may already have rotated the refresh token, so the refresh and its
|
|
466
|
+
* persistence ignore `signal` and are bounded only by a timeout. Otherwise a
|
|
467
|
+
* cancelled caller could discard the only valid refresh token. Callers that
|
|
468
|
+
* must return promptly on cancellation race this promise with their signal.
|
|
469
|
+
*
|
|
470
|
+
* Resolves with the stored OAuth credential after the operation, or undefined
|
|
471
|
+
* when the provider no longer has an OAuth credential.
|
|
472
|
+
*/
|
|
473
|
+
async function refreshStoredOAuthCredential(credentials, providerId, oauth, needsRefresh, signal) {
|
|
474
|
+
let post;
|
|
475
|
+
const lockWait = new AbortController();
|
|
476
|
+
const cancelLockWait = () => lockWait.abort(signal.reason);
|
|
477
|
+
signal.addEventListener("abort", cancelLockWait, { once: true });
|
|
478
|
+
if (signal.aborted) cancelLockWait();
|
|
479
|
+
try {
|
|
480
|
+
post = await credentials.modify(providerId, async (current) => {
|
|
481
|
+
signal.removeEventListener("abort", cancelLockWait);
|
|
482
|
+
signal.throwIfAborted();
|
|
483
|
+
if (current?.type !== "oauth") return void 0;
|
|
484
|
+
if (!needsRefresh(current)) return void 0;
|
|
485
|
+
try {
|
|
486
|
+
return await oauth.refresh(current, AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS));
|
|
487
|
+
} catch (error) {
|
|
488
|
+
throw new ModelsError("oauth", `OAuth refresh failed for ${providerId}`, { cause: error });
|
|
489
|
+
}
|
|
490
|
+
}, { signal: lockWait.signal });
|
|
491
|
+
} catch (error) {
|
|
492
|
+
if (error instanceof ModelsError) throw error;
|
|
493
|
+
signal.throwIfAborted();
|
|
494
|
+
throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
|
|
495
|
+
} finally {
|
|
496
|
+
signal.removeEventListener("abort", cancelLockWait);
|
|
497
|
+
}
|
|
498
|
+
return post?.type === "oauth" ? post : void 0;
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* OAuth resolution with double-checked locking: tokens with less than five
|
|
502
|
+
* minutes remaining are refreshed through `refreshStoredOAuthCredential`.
|
|
503
|
+
*/
|
|
504
|
+
async function resolveStoredOAuth(credentials, providerId, oauth, stored, signal, minOAuthValidityMs) {
|
|
505
|
+
const minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);
|
|
506
|
+
const expiresSoon = (credential) => Date.now() + minimumValidityMs >= credential.expires;
|
|
507
|
+
let credential = stored;
|
|
508
|
+
if (expiresSoon(credential)) {
|
|
509
|
+
const post = await refreshStoredOAuthCredential(credentials, providerId, oauth, expiresSoon, signal);
|
|
510
|
+
if (!post) return void 0;
|
|
511
|
+
credential = post;
|
|
512
|
+
if (minOAuthValidityMs !== void 0 && expiresSoon(credential)) throw new ModelsError("oauth", `OAuth refresh returned a token that expires too soon for ${providerId}`);
|
|
513
|
+
}
|
|
514
|
+
try {
|
|
515
|
+
return {
|
|
516
|
+
auth: await oauth.toAuth(credential),
|
|
517
|
+
source: "OAuth"
|
|
518
|
+
};
|
|
519
|
+
} catch (error) {
|
|
520
|
+
throw new ModelsError("oauth", `OAuth auth derivation failed for ${providerId}`, { cause: error });
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
async function resolveApiKey(authContext, apiKey, providerId, credential, signal) {
|
|
524
|
+
try {
|
|
525
|
+
return await apiKey.resolve({
|
|
526
|
+
ctx: authContext,
|
|
527
|
+
credential,
|
|
528
|
+
signal
|
|
529
|
+
});
|
|
530
|
+
} catch (error) {
|
|
531
|
+
throw new ModelsError("auth", `API key auth failed for provider ${providerId}`, { cause: error });
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
async function readCredential(credentials, providerId, signal) {
|
|
535
|
+
try {
|
|
536
|
+
return await credentials.read(providerId, { signal });
|
|
537
|
+
} catch (error) {
|
|
538
|
+
throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
//#endregion
|
|
542
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/models-store.js
|
|
543
|
+
var InMemoryModelsStore = class {
|
|
544
|
+
entries = /* @__PURE__ */ new Map();
|
|
545
|
+
async read(providerId, options) {
|
|
546
|
+
options?.signal?.throwIfAborted();
|
|
547
|
+
const entry = this.entries.get(providerId);
|
|
548
|
+
return entry ? structuredClone(entry) : void 0;
|
|
549
|
+
}
|
|
550
|
+
async write(providerId, entry, options) {
|
|
551
|
+
options?.signal?.throwIfAborted();
|
|
552
|
+
this.entries.set(providerId, structuredClone(entry));
|
|
553
|
+
}
|
|
554
|
+
async delete(providerId, options) {
|
|
555
|
+
options?.signal?.throwIfAborted();
|
|
556
|
+
this.entries.delete(providerId);
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
//#endregion
|
|
560
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/telemetry.js
|
|
561
|
+
const provider = {
|
|
562
|
+
type: "string",
|
|
563
|
+
description: "Provider identifier.",
|
|
564
|
+
required: true
|
|
565
|
+
};
|
|
566
|
+
const model = {
|
|
567
|
+
type: "string",
|
|
568
|
+
description: "Requested model identifier.",
|
|
569
|
+
required: true
|
|
570
|
+
};
|
|
571
|
+
const stop = {
|
|
572
|
+
type: "string",
|
|
573
|
+
description: "Normalized stop reason.",
|
|
574
|
+
values: [
|
|
575
|
+
"pending",
|
|
576
|
+
"stop",
|
|
577
|
+
"length",
|
|
578
|
+
"toolUse",
|
|
579
|
+
"error",
|
|
580
|
+
"aborted",
|
|
581
|
+
"deferred"
|
|
582
|
+
]
|
|
583
|
+
};
|
|
584
|
+
const request = {
|
|
585
|
+
description: "One logical model request, including authentication and provider setup.",
|
|
586
|
+
parents: { kind: "any" },
|
|
587
|
+
startAttributes: {
|
|
588
|
+
provider,
|
|
589
|
+
api: {
|
|
590
|
+
type: "string",
|
|
591
|
+
description: "API identifier.",
|
|
592
|
+
required: true
|
|
593
|
+
},
|
|
594
|
+
model,
|
|
595
|
+
reasoning: {
|
|
596
|
+
type: "string",
|
|
597
|
+
description: "Scalar requested reasoning level.",
|
|
598
|
+
required: false
|
|
599
|
+
}
|
|
600
|
+
},
|
|
601
|
+
endAttributes: {
|
|
602
|
+
stop,
|
|
603
|
+
"usage.input": {
|
|
604
|
+
type: "number",
|
|
605
|
+
description: "Uncached input tokens."
|
|
606
|
+
},
|
|
607
|
+
"usage.output": {
|
|
608
|
+
type: "number",
|
|
609
|
+
description: "Output tokens."
|
|
610
|
+
},
|
|
611
|
+
"usage.cache_read": {
|
|
612
|
+
type: "number",
|
|
613
|
+
description: "Cache-read tokens."
|
|
614
|
+
},
|
|
615
|
+
"usage.cache_write": {
|
|
616
|
+
type: "number",
|
|
617
|
+
description: "Cache-write tokens."
|
|
618
|
+
},
|
|
619
|
+
"cost.total": {
|
|
620
|
+
type: "number",
|
|
621
|
+
description: "Total request cost in USD."
|
|
622
|
+
},
|
|
623
|
+
"response.id": {
|
|
624
|
+
type: "string",
|
|
625
|
+
description: "Provider response identifier.",
|
|
626
|
+
cardinality: "high"
|
|
627
|
+
}
|
|
628
|
+
},
|
|
629
|
+
events: {
|
|
630
|
+
"pi.ai.first_chunk": {
|
|
631
|
+
description: "First normalized stream event delivered.",
|
|
632
|
+
attributes: {}
|
|
633
|
+
},
|
|
634
|
+
"pi.ai.block": {
|
|
635
|
+
description: "A completed content block; content is never recorded.",
|
|
636
|
+
attributes: {
|
|
637
|
+
type: {
|
|
638
|
+
type: "string",
|
|
639
|
+
description: "Block kind.",
|
|
640
|
+
values: [
|
|
641
|
+
"text",
|
|
642
|
+
"thinking",
|
|
643
|
+
"tool_call"
|
|
644
|
+
],
|
|
645
|
+
required: true
|
|
646
|
+
},
|
|
647
|
+
index: {
|
|
648
|
+
type: "number",
|
|
649
|
+
description: "Content block index.",
|
|
650
|
+
required: true
|
|
651
|
+
},
|
|
652
|
+
chars: {
|
|
653
|
+
type: "number",
|
|
654
|
+
description: "UTF-16 character count.",
|
|
655
|
+
required: true
|
|
656
|
+
},
|
|
657
|
+
tool: {
|
|
658
|
+
type: "string",
|
|
659
|
+
description: "Tool name, for tool-call blocks only.",
|
|
660
|
+
required: false
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
},
|
|
665
|
+
status: {
|
|
666
|
+
default: "ok",
|
|
667
|
+
errorWhen: "Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok."
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
/** Pi-owned request metadata, bounded error status, events, and low-cardinality metrics. */
|
|
671
|
+
const AI_TELEMETRY_SCHEMA = defineTelemetrySchema({
|
|
672
|
+
version: 1,
|
|
673
|
+
spans: {
|
|
674
|
+
"pi.ai.request": request,
|
|
675
|
+
"pi.ai.poll": {
|
|
676
|
+
...request,
|
|
677
|
+
description: "One deferred-response poll, not the deferred request's lifetime."
|
|
678
|
+
}
|
|
679
|
+
},
|
|
680
|
+
metrics: {
|
|
681
|
+
"pi.ai.request.duration": {
|
|
682
|
+
kind: "histogram",
|
|
683
|
+
description: "Logical request or poll duration.",
|
|
684
|
+
unit: "ms",
|
|
685
|
+
attributes: {
|
|
686
|
+
provider,
|
|
687
|
+
model,
|
|
688
|
+
stop: {
|
|
689
|
+
...stop,
|
|
690
|
+
required: true
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
},
|
|
694
|
+
"pi.ai.first_chunk.duration": {
|
|
695
|
+
kind: "histogram",
|
|
696
|
+
description: "Time to the first normalized stream event.",
|
|
697
|
+
unit: "ms",
|
|
698
|
+
attributes: {
|
|
699
|
+
provider,
|
|
700
|
+
model
|
|
701
|
+
}
|
|
702
|
+
},
|
|
703
|
+
"pi.ai.tokens": {
|
|
704
|
+
kind: "counter",
|
|
705
|
+
description: "Reported model token usage; pending and deferred polls are excluded.",
|
|
706
|
+
unit: "token",
|
|
707
|
+
attributes: {
|
|
708
|
+
provider,
|
|
709
|
+
model,
|
|
710
|
+
kind: {
|
|
711
|
+
type: "string",
|
|
712
|
+
description: "Token usage category.",
|
|
713
|
+
values: [
|
|
714
|
+
"input",
|
|
715
|
+
"output",
|
|
716
|
+
"cache_read",
|
|
717
|
+
"cache_write"
|
|
718
|
+
],
|
|
719
|
+
required: true
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
},
|
|
723
|
+
"pi.ai.cost": {
|
|
724
|
+
kind: "counter",
|
|
725
|
+
description: "Reported model cost; pending and deferred polls are excluded.",
|
|
726
|
+
unit: "USD",
|
|
727
|
+
attributes: {
|
|
728
|
+
provider,
|
|
729
|
+
model
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
function createInstruments(adapter) {
|
|
735
|
+
const metrics = createTypedMetrics(adapter, [AI_TELEMETRY_SCHEMA]);
|
|
736
|
+
return {
|
|
737
|
+
requestDuration: metrics.histogram("pi.ai.request.duration"),
|
|
738
|
+
firstChunkDuration: metrics.histogram("pi.ai.first_chunk.duration"),
|
|
739
|
+
tokens: metrics.counter("pi.ai.tokens"),
|
|
740
|
+
cost: metrics.counter("pi.ai.cost")
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
const instrumentCache = /* @__PURE__ */ new WeakMap();
|
|
744
|
+
function observeModelRequest(requestedModel, options, poll) {
|
|
745
|
+
const started = performance.now();
|
|
746
|
+
const attributes = {
|
|
747
|
+
provider: requestedModel.provider,
|
|
748
|
+
model: requestedModel.id
|
|
749
|
+
};
|
|
750
|
+
const adapter = options?.telemetry?.metrics ?? NOOP_TELEMETRY_METRICS;
|
|
751
|
+
let instruments = instrumentCache.get(adapter);
|
|
752
|
+
if (!instruments) {
|
|
753
|
+
instruments = createInstruments(adapter);
|
|
754
|
+
instrumentCache.set(adapter, instruments);
|
|
755
|
+
}
|
|
756
|
+
const { requestDuration, firstChunkDuration, tokens, cost } = instruments;
|
|
757
|
+
let span;
|
|
758
|
+
let finish;
|
|
759
|
+
let first = true;
|
|
760
|
+
const toolChars = /* @__PURE__ */ new Map();
|
|
761
|
+
const finished = new Promise((resolve) => {
|
|
762
|
+
finish = resolve;
|
|
763
|
+
});
|
|
764
|
+
const run = (activeSpan) => {
|
|
765
|
+
span = activeSpan;
|
|
766
|
+
return finished;
|
|
767
|
+
};
|
|
768
|
+
const startAttributes = {
|
|
769
|
+
...attributes,
|
|
770
|
+
api: requestedModel.api,
|
|
771
|
+
...typeof options?.reasoning === "string" ? { reasoning: options.reasoning } : {}
|
|
772
|
+
};
|
|
773
|
+
const start = createTypedSpanStarter(options?.telemetry ?? NOOP_TELEMETRY_CONTEXT, [AI_TELEMETRY_SCHEMA]);
|
|
774
|
+
if (poll) start("pi.ai.poll", startAttributes, run);
|
|
775
|
+
else start("pi.ai.request", startAttributes, run);
|
|
776
|
+
return {
|
|
777
|
+
onEvent(event) {
|
|
778
|
+
if (first) {
|
|
779
|
+
first = false;
|
|
780
|
+
span.addEvent("pi.ai.first_chunk");
|
|
781
|
+
firstChunkDuration.record(performance.now() - started, attributes, span);
|
|
782
|
+
}
|
|
783
|
+
if (event.type === "toolcall_delta") toolChars.set(event.contentIndex, (toolChars.get(event.contentIndex) ?? 0) + event.delta.length);
|
|
784
|
+
else if (event.type === "text_end" || event.type === "thinking_end") span.addEvent("pi.ai.block", {
|
|
785
|
+
type: event.type === "text_end" ? "text" : "thinking",
|
|
786
|
+
index: event.contentIndex,
|
|
787
|
+
chars: event.content.length
|
|
788
|
+
});
|
|
789
|
+
else if (event.type === "toolcall_end") {
|
|
790
|
+
const chars = toolChars.get(event.contentIndex) ?? 0;
|
|
791
|
+
toolChars.delete(event.contentIndex);
|
|
792
|
+
span.addEvent("pi.ai.block", {
|
|
793
|
+
type: "tool_call",
|
|
794
|
+
index: event.contentIndex,
|
|
795
|
+
chars,
|
|
796
|
+
tool: event.toolCall.name
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
},
|
|
800
|
+
onResult(message) {
|
|
801
|
+
if (message) {
|
|
802
|
+
span.setAttributes({
|
|
803
|
+
stop: message.stopReason,
|
|
804
|
+
"usage.input": message.usage.input,
|
|
805
|
+
"usage.output": message.usage.output,
|
|
806
|
+
"usage.cache_read": message.usage.cacheRead,
|
|
807
|
+
"usage.cache_write": message.usage.cacheWrite,
|
|
808
|
+
"cost.total": message.usage.cost.total,
|
|
809
|
+
"response.id": message.responseId
|
|
810
|
+
});
|
|
811
|
+
if (message.stopReason === "error") span.setStatus({
|
|
812
|
+
status: "error",
|
|
813
|
+
error: {
|
|
814
|
+
name: "provider_error",
|
|
815
|
+
message: ownedSlice(message.errorMessage ?? "", 0, 500)
|
|
816
|
+
}
|
|
817
|
+
});
|
|
818
|
+
requestDuration.record(performance.now() - started, {
|
|
819
|
+
...attributes,
|
|
820
|
+
stop: message.stopReason
|
|
821
|
+
}, span);
|
|
822
|
+
if (!poll || message.stopReason !== "pending" && message.stopReason !== "deferred") {
|
|
823
|
+
tokens.add(message.usage.input, {
|
|
824
|
+
...attributes,
|
|
825
|
+
kind: "input"
|
|
826
|
+
});
|
|
827
|
+
tokens.add(message.usage.output, {
|
|
828
|
+
...attributes,
|
|
829
|
+
kind: "output"
|
|
830
|
+
});
|
|
831
|
+
tokens.add(message.usage.cacheRead, {
|
|
832
|
+
...attributes,
|
|
833
|
+
kind: "cache_read"
|
|
834
|
+
});
|
|
835
|
+
tokens.add(message.usage.cacheWrite, {
|
|
836
|
+
...attributes,
|
|
837
|
+
kind: "cache_write"
|
|
838
|
+
});
|
|
839
|
+
cost.add(message.usage.cost.total, attributes);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
finish();
|
|
843
|
+
}
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
//#endregion
|
|
847
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/utils/model-operations.js
|
|
848
|
+
/** The type of a model. Models without `type` are chat models. */
|
|
849
|
+
function getModelType(model) {
|
|
850
|
+
return model.type ?? "chat";
|
|
851
|
+
}
|
|
852
|
+
/** Runtime-checked model type narrowing, including legacy chat models without `type`. */
|
|
853
|
+
function isModelType(model, type) {
|
|
854
|
+
return getModelType(model) === type;
|
|
855
|
+
}
|
|
856
|
+
function assertChatModel(model) {
|
|
857
|
+
if (!isModelType(model, "chat")) throw new ModelsError("provider", `Model ${model.provider}/${model.id} is not a chat model`);
|
|
858
|
+
}
|
|
859
|
+
function assertImageModel(model) {
|
|
860
|
+
if (!isModelType(model, "image")) throw new ModelsError("provider", `Model ${model.provider}/${model.id} is not an image model`);
|
|
861
|
+
}
|
|
862
|
+
function assertClassifierModel(model) {
|
|
863
|
+
if (!isModelType(model, "classifier")) throw new ModelsError("provider", `Model ${model.provider}/${model.id} is not a classifier model`);
|
|
864
|
+
}
|
|
865
|
+
/** Rejects classifier images for models whose catalog entry does not accept image input. */
|
|
866
|
+
function assertClassifierInputSupported(model, context) {
|
|
867
|
+
if (context.images?.length && !model.input.includes("image")) throw new ModelsError("provider", `Model ${model.provider}/${model.id} does not accept image input`);
|
|
868
|
+
}
|
|
869
|
+
function imageErrorResult(model, error, aborted = false) {
|
|
870
|
+
return {
|
|
871
|
+
api: model.api,
|
|
872
|
+
provider: model.provider,
|
|
873
|
+
model: model.id,
|
|
874
|
+
output: [],
|
|
875
|
+
stopReason: aborted ? "aborted" : "error",
|
|
876
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
877
|
+
timestamp: Date.now()
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
function classifierErrorResult(model, error, aborted = false) {
|
|
881
|
+
return {
|
|
882
|
+
api: model.api,
|
|
883
|
+
provider: model.provider,
|
|
884
|
+
model: model.id,
|
|
885
|
+
answers: {},
|
|
886
|
+
stopReason: aborted ? "aborted" : "error",
|
|
887
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
888
|
+
timestamp: Date.now()
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
//#endregion
|
|
892
|
+
//#region ../../../node_modules/.pnpm/@earendil-works+pi-ai@1.5.0_@aws-sdk+credential-provider-node@3.972.86_@modelcontextpro_cbd356c737d8e30c7d704b4728fb9233/node_modules/@earendil-works/pi-ai/dist/models.js
|
|
893
|
+
const KNOWN_MODEL_TYPES = {
|
|
894
|
+
chat: true,
|
|
895
|
+
image: true,
|
|
896
|
+
classifier: true
|
|
897
|
+
};
|
|
898
|
+
/** Models from stores and remote sources may have types that only newer versions know. */
|
|
899
|
+
function hasKnownModelType(model) {
|
|
900
|
+
return Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model));
|
|
901
|
+
}
|
|
902
|
+
/** Drops stored models whose type this version does not know. */
|
|
903
|
+
function withKnownModelTypes(entry) {
|
|
904
|
+
return {
|
|
905
|
+
...entry,
|
|
906
|
+
models: entry.models.filter(hasKnownModelType)
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
function mergeHeaders(base, override) {
|
|
910
|
+
if (!base && !override) return void 0;
|
|
911
|
+
const merged = { ...base };
|
|
912
|
+
for (const [name, value] of Object.entries(override ?? {})) {
|
|
913
|
+
const lowerName = name.toLowerCase();
|
|
914
|
+
for (const existingName of Object.keys(merged)) if (existingName.toLowerCase() === lowerName) delete merged[existingName];
|
|
915
|
+
merged[name] = value;
|
|
916
|
+
}
|
|
917
|
+
return merged;
|
|
918
|
+
}
|
|
919
|
+
var ModelsImpl = class {
|
|
920
|
+
providers = /* @__PURE__ */ new Map();
|
|
921
|
+
credentials;
|
|
922
|
+
modelsStore;
|
|
923
|
+
authContext;
|
|
924
|
+
identity;
|
|
925
|
+
refreshGenerations = /* @__PURE__ */ new Map();
|
|
926
|
+
refreshControllers = /* @__PURE__ */ new Map();
|
|
927
|
+
publicationChains = /* @__PURE__ */ new Map();
|
|
928
|
+
constructor(options) {
|
|
929
|
+
this.credentials = options?.credentials ?? new InMemoryCredentialStore();
|
|
930
|
+
this.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();
|
|
931
|
+
this.authContext = options?.authContext ?? defaultProviderAuthContext();
|
|
932
|
+
this.identity = options?.identity;
|
|
933
|
+
}
|
|
934
|
+
setProvider(provider) {
|
|
935
|
+
this.supersedeProviderRefresh(provider.id);
|
|
936
|
+
this.providers.set(provider.id, provider);
|
|
937
|
+
}
|
|
938
|
+
deleteProvider(id) {
|
|
939
|
+
this.supersedeProviderRefresh(id);
|
|
940
|
+
this.providers.delete(id);
|
|
941
|
+
}
|
|
942
|
+
clearProviders() {
|
|
943
|
+
for (const id of /* @__PURE__ */ new Set([...this.providers.keys(), ...this.refreshControllers.keys()])) this.supersedeProviderRefresh(id);
|
|
944
|
+
this.providers.clear();
|
|
945
|
+
}
|
|
946
|
+
getProviders() {
|
|
947
|
+
return Array.from(this.providers.values());
|
|
948
|
+
}
|
|
949
|
+
getProvider(id) {
|
|
950
|
+
return this.providers.get(id);
|
|
951
|
+
}
|
|
952
|
+
getModels(provider) {
|
|
953
|
+
if (provider !== void 0) {
|
|
954
|
+
const entry = this.providers.get(provider);
|
|
955
|
+
if (!entry) return [];
|
|
956
|
+
try {
|
|
957
|
+
return entry.getModels();
|
|
958
|
+
} catch {
|
|
959
|
+
return [];
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
const models = [];
|
|
963
|
+
for (const entry of this.providers.values()) try {
|
|
964
|
+
models.push(...entry.getModels());
|
|
965
|
+
} catch {}
|
|
966
|
+
return models;
|
|
967
|
+
}
|
|
968
|
+
getAllModels(provider) {
|
|
969
|
+
if (provider !== void 0) {
|
|
970
|
+
const entry = this.providers.get(provider);
|
|
971
|
+
if (!entry) return [];
|
|
972
|
+
try {
|
|
973
|
+
return entry.getAllModels?.() ?? entry.getModels();
|
|
974
|
+
} catch {
|
|
975
|
+
return [];
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
const models = [];
|
|
979
|
+
for (const entry of this.providers.values()) try {
|
|
980
|
+
models.push(...entry.getAllModels?.() ?? entry.getModels());
|
|
981
|
+
} catch {}
|
|
982
|
+
return models;
|
|
983
|
+
}
|
|
984
|
+
getModelsOfType(type, provider) {
|
|
985
|
+
return this.getAllModels(provider).filter((model) => isModelType(model, type));
|
|
986
|
+
}
|
|
987
|
+
getModel(provider, id) {
|
|
988
|
+
return this.getModels(provider).find((model) => model.id === id);
|
|
989
|
+
}
|
|
990
|
+
getModelOfType(type, provider, id) {
|
|
991
|
+
return this.getModelsOfType(type, provider).find((model) => model.id === id);
|
|
992
|
+
}
|
|
993
|
+
supersedeProviderRefresh(providerId) {
|
|
994
|
+
const generation = (this.refreshGenerations.get(providerId) ?? 0) + 1;
|
|
995
|
+
this.refreshGenerations.set(providerId, generation);
|
|
996
|
+
const previous = this.refreshControllers.get(providerId);
|
|
997
|
+
if (previous) {
|
|
998
|
+
this.refreshControllers.delete(providerId);
|
|
999
|
+
previous.abort();
|
|
1000
|
+
}
|
|
1001
|
+
return generation;
|
|
1002
|
+
}
|
|
1003
|
+
beginProviderRefresh(providerId) {
|
|
1004
|
+
const generation = this.supersedeProviderRefresh(providerId);
|
|
1005
|
+
const controller = new AbortController();
|
|
1006
|
+
this.refreshControllers.set(providerId, controller);
|
|
1007
|
+
return {
|
|
1008
|
+
generation,
|
|
1009
|
+
controller
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
publishProviderModels(providerId, generation, signal, publication) {
|
|
1013
|
+
const previous = this.publicationChains.get(providerId) ?? Promise.resolve();
|
|
1014
|
+
const queued = (async () => {
|
|
1015
|
+
await previous.catch(() => {});
|
|
1016
|
+
if (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;
|
|
1017
|
+
if (publication.persist === null) await this.modelsStore.delete(providerId, { signal });
|
|
1018
|
+
else if (publication.persist !== void 0) await this.modelsStore.write(providerId, structuredClone(publication.persist), { signal });
|
|
1019
|
+
if (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;
|
|
1020
|
+
publication.update?.();
|
|
1021
|
+
return true;
|
|
1022
|
+
})();
|
|
1023
|
+
const tail = queued.catch(() => {});
|
|
1024
|
+
this.publicationChains.set(providerId, tail);
|
|
1025
|
+
tail.then(() => {
|
|
1026
|
+
if (this.publicationChains.get(providerId) === tail) this.publicationChains.delete(providerId);
|
|
1027
|
+
});
|
|
1028
|
+
return raceWithAbortSignal(queued, signal);
|
|
1029
|
+
}
|
|
1030
|
+
async runProviderRefreshPhase(provider, credential, allowNetwork, force, generation, signal) {
|
|
1031
|
+
const stored = await this.modelsStore.read(provider.id, { signal });
|
|
1032
|
+
await provider.refreshModels({
|
|
1033
|
+
credential,
|
|
1034
|
+
stored: stored ? withKnownModelTypes(structuredClone(stored)) : void 0,
|
|
1035
|
+
publish: (publication) => this.publishProviderModels(provider.id, generation, signal, publication),
|
|
1036
|
+
allowNetwork,
|
|
1037
|
+
force: allowNetwork ? force : void 0,
|
|
1038
|
+
signal,
|
|
1039
|
+
baseUrl: provider.baseUrl
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
async refresh(options = {}) {
|
|
1043
|
+
const allowNetwork = options.allowNetwork ?? true;
|
|
1044
|
+
const callerSignal = operationSignal(options.signal);
|
|
1045
|
+
const errors = /* @__PURE__ */ new Map();
|
|
1046
|
+
if (callerSignal.aborted) return {
|
|
1047
|
+
aborted: true,
|
|
1048
|
+
errors
|
|
1049
|
+
};
|
|
1050
|
+
const selected = options.providers ? new Set(options.providers) : void 0;
|
|
1051
|
+
const refreshable = Array.from(this.providers.values()).filter((provider) => provider.refreshModels !== void 0 && (!selected || selected.has(provider.id)));
|
|
1052
|
+
const refresh = Promise.all(refreshable.map(async (provider) => {
|
|
1053
|
+
const { generation, controller } = this.beginProviderRefresh(provider.id);
|
|
1054
|
+
const signal = AbortSignal.any([callerSignal, controller.signal]);
|
|
1055
|
+
const operation = (async () => {
|
|
1056
|
+
let storedCredential;
|
|
1057
|
+
let credentialError;
|
|
1058
|
+
try {
|
|
1059
|
+
storedCredential = await this.readCredential(provider.id, signal);
|
|
1060
|
+
} catch (error) {
|
|
1061
|
+
credentialError = error;
|
|
1062
|
+
}
|
|
1063
|
+
await this.runProviderRefreshPhase(provider, storedCredential, false, void 0, generation, signal);
|
|
1064
|
+
if (credentialError !== void 0) throw credentialError;
|
|
1065
|
+
if (!allowNetwork || signal.aborted) return;
|
|
1066
|
+
const credential = await this.resolveRefreshCredential(provider, storedCredential, signal);
|
|
1067
|
+
if (!credential) return;
|
|
1068
|
+
await this.runProviderRefreshPhase(provider, credential, true, options.force, generation, signal);
|
|
1069
|
+
})();
|
|
1070
|
+
try {
|
|
1071
|
+
await raceWithAbortSignal(operation, signal);
|
|
1072
|
+
} catch (error) {
|
|
1073
|
+
if (!signal.aborted) errors.set(provider.id, error instanceof Error ? error : new ModelsError("model_source", `Model refresh failed for ${provider.id}`, { cause: error }));
|
|
1074
|
+
} finally {
|
|
1075
|
+
if (this.refreshControllers.get(provider.id) === controller) this.refreshControllers.delete(provider.id);
|
|
1076
|
+
}
|
|
1077
|
+
}));
|
|
1078
|
+
try {
|
|
1079
|
+
await raceWithAbortSignal(refresh, callerSignal);
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
if (!callerSignal.aborted) throw error;
|
|
1082
|
+
}
|
|
1083
|
+
return {
|
|
1084
|
+
aborted: callerSignal.aborted,
|
|
1085
|
+
errors: new Map(errors)
|
|
1086
|
+
};
|
|
1087
|
+
}
|
|
1088
|
+
async resolveRefreshCredential(provider, stored, signal) {
|
|
1089
|
+
if (stored?.type === "oauth") {
|
|
1090
|
+
const oauth = provider.auth.oauth;
|
|
1091
|
+
if (!oauth) return void 0;
|
|
1092
|
+
if (Date.now() < stored.expires) return stored;
|
|
1093
|
+
if (signal.aborted) return void 0;
|
|
1094
|
+
return refreshStoredOAuthCredential(this.credentials, provider.id, oauth, (current) => Date.now() >= current.expires, signal);
|
|
1095
|
+
}
|
|
1096
|
+
const apiKey = provider.auth.apiKey;
|
|
1097
|
+
if (!apiKey) return void 0;
|
|
1098
|
+
const credential = stored?.type === "api_key" ? stored : void 0;
|
|
1099
|
+
const result = await apiKey.resolve({
|
|
1100
|
+
ctx: this.authContext,
|
|
1101
|
+
credential,
|
|
1102
|
+
signal
|
|
1103
|
+
});
|
|
1104
|
+
if (!result) return void 0;
|
|
1105
|
+
return {
|
|
1106
|
+
type: "api_key",
|
|
1107
|
+
key: result.auth.apiKey,
|
|
1108
|
+
env: result.env
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
async readCredential(providerId, signal) {
|
|
1112
|
+
try {
|
|
1113
|
+
return await this.credentials.read(providerId, { signal });
|
|
1114
|
+
} catch (error) {
|
|
1115
|
+
throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
async checkProviderAuth(provider, credential, signal) {
|
|
1119
|
+
if (credential?.type === "oauth") return provider.auth.oauth ? {
|
|
1120
|
+
source: "OAuth",
|
|
1121
|
+
type: "oauth"
|
|
1122
|
+
} : void 0;
|
|
1123
|
+
const apiKey = provider.auth.apiKey;
|
|
1124
|
+
if (!apiKey) return void 0;
|
|
1125
|
+
if (apiKey.check) try {
|
|
1126
|
+
return await apiKey.check({
|
|
1127
|
+
ctx: this.authContext,
|
|
1128
|
+
credential: credential?.type === "api_key" ? credential : void 0,
|
|
1129
|
+
signal
|
|
1130
|
+
});
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
throw new ModelsError("auth", `API key auth check failed for provider ${provider.id}`, { cause: error });
|
|
1133
|
+
}
|
|
1134
|
+
const resolution = await resolveProviderAuth(provider, this.credentials, this.authContext, { signal });
|
|
1135
|
+
return resolution ? {
|
|
1136
|
+
source: resolution.source,
|
|
1137
|
+
type: "api_key"
|
|
1138
|
+
} : void 0;
|
|
1139
|
+
}
|
|
1140
|
+
checkAuth(providerId, options) {
|
|
1141
|
+
const signal = operationSignal(options?.signal);
|
|
1142
|
+
return raceWithAbortSignal((async () => {
|
|
1143
|
+
signal.throwIfAborted();
|
|
1144
|
+
const provider = this.providers.get(providerId);
|
|
1145
|
+
if (!provider) return void 0;
|
|
1146
|
+
return this.checkProviderAuth(provider, await this.readCredential(providerId, signal), signal);
|
|
1147
|
+
})(), signal);
|
|
1148
|
+
}
|
|
1149
|
+
async getAuthenticatedProviders(providerId, signal) {
|
|
1150
|
+
signal.throwIfAborted();
|
|
1151
|
+
const providers = providerId ? [this.providers.get(providerId)].filter((entry) => entry !== void 0) : this.getProviders();
|
|
1152
|
+
return (await Promise.all(providers.map(async (provider) => {
|
|
1153
|
+
const credential = await this.readCredential(provider.id, signal);
|
|
1154
|
+
return {
|
|
1155
|
+
provider,
|
|
1156
|
+
credential,
|
|
1157
|
+
auth: await this.checkProviderAuth(provider, credential, signal)
|
|
1158
|
+
};
|
|
1159
|
+
}))).filter((entry) => entry.auth !== void 0);
|
|
1160
|
+
}
|
|
1161
|
+
getAvailable(providerId, options) {
|
|
1162
|
+
const signal = operationSignal(options?.signal);
|
|
1163
|
+
return raceWithAbortSignal((async () => {
|
|
1164
|
+
return (await this.getAuthenticatedProviders(providerId, signal)).flatMap(({ provider, credential }) => {
|
|
1165
|
+
const models = provider.getModels();
|
|
1166
|
+
return provider.filterModels?.(models, credential) ?? models;
|
|
1167
|
+
});
|
|
1168
|
+
})(), signal);
|
|
1169
|
+
}
|
|
1170
|
+
async getAvailableOfType(type, providerId, options) {
|
|
1171
|
+
return (await this.getAllAvailable(providerId, options)).filter((model) => isModelType(model, type));
|
|
1172
|
+
}
|
|
1173
|
+
getAllAvailable(providerId, options) {
|
|
1174
|
+
const signal = operationSignal(options?.signal);
|
|
1175
|
+
return raceWithAbortSignal((async () => {
|
|
1176
|
+
return (await this.getAuthenticatedProviders(providerId, signal)).flatMap(({ provider, credential }) => {
|
|
1177
|
+
const models = provider.getAllModels?.() ?? provider.getModels();
|
|
1178
|
+
if (provider.filterAllModels) return provider.filterAllModels(models, credential);
|
|
1179
|
+
if (!provider.filterModels) return models;
|
|
1180
|
+
const availableChatIds = new Set(provider.filterModels(provider.getModels(), credential).map((model) => model.id));
|
|
1181
|
+
return models.filter((model) => !isModelType(model, "chat") || availableChatIds.has(model.id));
|
|
1182
|
+
});
|
|
1183
|
+
})(), signal);
|
|
1184
|
+
}
|
|
1185
|
+
async getAuth(providerOrModel, overrides) {
|
|
1186
|
+
const signal = operationSignal(overrides?.signal);
|
|
1187
|
+
const providerId = typeof providerOrModel === "string" ? providerOrModel : providerOrModel.provider;
|
|
1188
|
+
const provider = this.providers.get(providerId);
|
|
1189
|
+
if (!provider) return void 0;
|
|
1190
|
+
const result = await resolveProviderAuth(provider, this.credentials, this.authContext, {
|
|
1191
|
+
...overrides,
|
|
1192
|
+
signal
|
|
1193
|
+
});
|
|
1194
|
+
if (!result || typeof providerOrModel === "string" || !providerOrModel.headers) return result;
|
|
1195
|
+
return {
|
|
1196
|
+
...result,
|
|
1197
|
+
auth: {
|
|
1198
|
+
...result.auth,
|
|
1199
|
+
headers: mergeHeaders(result.auth.headers, providerOrModel.headers)
|
|
1200
|
+
}
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
async login(providerId, type, interaction, options) {
|
|
1204
|
+
const signal = operationSignal(interaction.signal);
|
|
1205
|
+
signal.throwIfAborted();
|
|
1206
|
+
const provider = this.providers.get(providerId);
|
|
1207
|
+
if (!provider) throw new ModelsError("provider", `Unknown provider: ${providerId}`);
|
|
1208
|
+
const method = type === "oauth" ? provider.auth.oauth : provider.auth.apiKey;
|
|
1209
|
+
if (!method?.login) throw new ModelsError("auth", `${provider.name} does not support ${type} login`);
|
|
1210
|
+
const credential = await raceWithAbortSignal(method.login({
|
|
1211
|
+
...interaction,
|
|
1212
|
+
signal
|
|
1213
|
+
}, options), signal);
|
|
1214
|
+
let mutationStarted = false;
|
|
1215
|
+
let markMutationStarted;
|
|
1216
|
+
const started = new Promise((resolve) => {
|
|
1217
|
+
markMutationStarted = resolve;
|
|
1218
|
+
});
|
|
1219
|
+
const mutation = this.credentials.modify(providerId, async () => {
|
|
1220
|
+
mutationStarted = true;
|
|
1221
|
+
markMutationStarted?.();
|
|
1222
|
+
return credential;
|
|
1223
|
+
}, { signal });
|
|
1224
|
+
mutation.catch(() => {});
|
|
1225
|
+
try {
|
|
1226
|
+
await new Promise((resolve, reject) => {
|
|
1227
|
+
const onAbort = () => {
|
|
1228
|
+
if (!mutationStarted) reject(signal.reason);
|
|
1229
|
+
};
|
|
1230
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1231
|
+
Promise.race([started, mutation]).then(() => {
|
|
1232
|
+
signal.removeEventListener("abort", onAbort);
|
|
1233
|
+
resolve();
|
|
1234
|
+
}, (error) => {
|
|
1235
|
+
signal.removeEventListener("abort", onAbort);
|
|
1236
|
+
reject(error);
|
|
1237
|
+
});
|
|
1238
|
+
if (signal.aborted) onAbort();
|
|
1239
|
+
});
|
|
1240
|
+
await mutation;
|
|
1241
|
+
} catch (error) {
|
|
1242
|
+
signal.throwIfAborted();
|
|
1243
|
+
throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
|
|
1244
|
+
}
|
|
1245
|
+
return credential;
|
|
1246
|
+
}
|
|
1247
|
+
async logout(providerId, options) {
|
|
1248
|
+
const signal = operationSignal(options?.signal);
|
|
1249
|
+
signal.throwIfAborted();
|
|
1250
|
+
try {
|
|
1251
|
+
await this.credentials.delete(providerId, { signal });
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
signal.throwIfAborted();
|
|
1254
|
+
throw new ModelsError("auth", `Credential store delete failed for ${providerId}`, { cause: error });
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
requireProvider(model) {
|
|
1258
|
+
const provider = this.providers.get(model.provider);
|
|
1259
|
+
if (!provider) throw new ModelsError("provider", `Unknown provider: ${model.provider}`);
|
|
1260
|
+
return provider;
|
|
1261
|
+
}
|
|
1262
|
+
requireChatProvider(model) {
|
|
1263
|
+
assertChatModel(model);
|
|
1264
|
+
return this.requireProvider(model);
|
|
1265
|
+
}
|
|
1266
|
+
async applyAuth(model, options) {
|
|
1267
|
+
this.requireProvider(model);
|
|
1268
|
+
const resolution = await this.getAuth(model, {
|
|
1269
|
+
apiKey: options?.apiKey,
|
|
1270
|
+
env: options?.env,
|
|
1271
|
+
signal: options?.signal
|
|
1272
|
+
});
|
|
1273
|
+
if (!resolution) throw new ModelsError("auth", `Provider is not configured: ${model.provider}`);
|
|
1274
|
+
const auth = resolution.auth;
|
|
1275
|
+
const apiKey = options?.apiKey ?? auth.apiKey;
|
|
1276
|
+
const requestModel = auth.baseUrl ? {
|
|
1277
|
+
...model,
|
|
1278
|
+
baseUrl: auth.baseUrl
|
|
1279
|
+
} : model;
|
|
1280
|
+
const sessionId = options && "sessionId" in options && typeof options.sessionId === "string" ? options.sessionId : void 0;
|
|
1281
|
+
let headers = mergeHeaders(mergeHeaders(getOpenCodeSessionHeaders(requestModel, sessionId), auth.headers), options?.headers);
|
|
1282
|
+
if (options?.transformHeaders) headers = await options.transformHeaders(headers ?? {});
|
|
1283
|
+
const env = resolution.env || options?.env ? {
|
|
1284
|
+
...resolution.env ?? {},
|
|
1285
|
+
...options?.env ?? {}
|
|
1286
|
+
} : void 0;
|
|
1287
|
+
const identity = mergeClientIdentity(this.identity, options?.identity);
|
|
1288
|
+
const { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};
|
|
1289
|
+
return {
|
|
1290
|
+
requestModel,
|
|
1291
|
+
requestOptions: {
|
|
1292
|
+
...providerOptions,
|
|
1293
|
+
apiKey,
|
|
1294
|
+
headers,
|
|
1295
|
+
env,
|
|
1296
|
+
...identity === void 0 ? {} : { identity }
|
|
1297
|
+
}
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
stream(model, context, options) {
|
|
1301
|
+
const transcript = normalizeContext(context);
|
|
1302
|
+
return lazyStream(model, async () => {
|
|
1303
|
+
const provider = this.requireChatProvider(model);
|
|
1304
|
+
const { requestModel, requestOptions } = await this.applyAuth(model, options);
|
|
1305
|
+
return provider.stream(requestModel, transcript, requestOptions);
|
|
1306
|
+
}, observeModelRequest(model, options, false));
|
|
1307
|
+
}
|
|
1308
|
+
async complete(model, context, options) {
|
|
1309
|
+
return this.stream(model, context, options).result();
|
|
1310
|
+
}
|
|
1311
|
+
streamSimple(model, context, options) {
|
|
1312
|
+
const transcript = normalizeContext(context);
|
|
1313
|
+
return lazyStream(model, async () => {
|
|
1314
|
+
const provider = this.requireChatProvider(model);
|
|
1315
|
+
const { requestModel, requestOptions } = await this.applyAuth(model, options);
|
|
1316
|
+
return provider.streamSimple(requestModel, transcript, requestOptions);
|
|
1317
|
+
}, observeModelRequest(model, options, false));
|
|
1318
|
+
}
|
|
1319
|
+
async completeSimple(model, context, options) {
|
|
1320
|
+
return this.streamSimple(model, context, options).result();
|
|
1321
|
+
}
|
|
1322
|
+
streamDeferred(model, handle, options) {
|
|
1323
|
+
return lazyStream(model, async () => {
|
|
1324
|
+
const provider = this.requireChatProvider(model);
|
|
1325
|
+
if (!provider.fetchDeferred) throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
|
|
1326
|
+
const { requestModel, requestOptions } = await this.applyAuth(model, options);
|
|
1327
|
+
return provider.fetchDeferred(requestModel, handle, requestOptions);
|
|
1328
|
+
}, observeModelRequest(model, options, true));
|
|
1329
|
+
}
|
|
1330
|
+
async fetchDeferred(model, handle, options) {
|
|
1331
|
+
return this.streamDeferred(model, handle, options).result();
|
|
1332
|
+
}
|
|
1333
|
+
async cancelDeferred(model, handle, options) {
|
|
1334
|
+
const provider = this.requireChatProvider(model);
|
|
1335
|
+
if (!provider.cancelDeferred) throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
|
|
1336
|
+
const { requestModel, requestOptions } = await this.applyAuth(model, options);
|
|
1337
|
+
await provider.cancelDeferred(requestModel, handle, requestOptions);
|
|
1338
|
+
}
|
|
1339
|
+
async generateImages(model, context, options) {
|
|
1340
|
+
try {
|
|
1341
|
+
assertImageModel(model);
|
|
1342
|
+
const provider = this.requireProvider(model);
|
|
1343
|
+
if (!provider.generateImages) throw new ModelsError("provider", `Provider ${model.provider} does not support image generation`);
|
|
1344
|
+
const { requestModel, requestOptions } = await this.applyAuth(model, options);
|
|
1345
|
+
return await provider.generateImages(requestModel, context, requestOptions);
|
|
1346
|
+
} catch (error) {
|
|
1347
|
+
return imageErrorResult(model, error, options?.signal?.aborted);
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
async classify(model, context, options) {
|
|
1351
|
+
try {
|
|
1352
|
+
assertClassifierModel(model);
|
|
1353
|
+
assertClassifierInputSupported(model, context);
|
|
1354
|
+
const provider = this.requireProvider(model);
|
|
1355
|
+
if (!provider.classify) throw new ModelsError("provider", `Provider ${model.provider} does not support classification`);
|
|
1356
|
+
const { requestModel, requestOptions } = await this.applyAuth(model, options);
|
|
1357
|
+
return await provider.classify(requestModel, context, requestOptions);
|
|
1358
|
+
} catch (error) {
|
|
1359
|
+
return classifierErrorResult(model, error, options?.signal?.aborted);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
};
|
|
1363
|
+
function createModels(options) {
|
|
1364
|
+
return new ModelsImpl(options);
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1367
|
+
* Builds a provider from parts. Built-in provider factories and models.json
|
|
1368
|
+
* custom providers both go through this. A single `api` streams all chat
|
|
1369
|
+
* models; an `api` map dispatches on `model.api`, and a model whose api has
|
|
1370
|
+
* no entry produces a stream error. One-shot operation maps dispatch on
|
|
1371
|
+
* `model.api` the same way. At least one concrete implementation across
|
|
1372
|
+
* `api`/`images`/`classifiers` is required; empty maps are rejected.
|
|
1373
|
+
*/
|
|
1374
|
+
function createProvider(input) {
|
|
1375
|
+
const single = input.api && typeof input.api.stream === "function" ? input.api : void 0;
|
|
1376
|
+
const byApi = single || !input.api ? void 0 : input.api;
|
|
1377
|
+
const images = input.images;
|
|
1378
|
+
const classifiers = input.classifiers;
|
|
1379
|
+
const streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== void 0);
|
|
1380
|
+
const imageImplementations = Object.values(images ?? {}).filter((entry) => entry !== void 0);
|
|
1381
|
+
const classifierImplementations = Object.values(classifiers ?? {}).filter((entry) => entry !== void 0);
|
|
1382
|
+
if (streams.length === 0 && imageImplementations.length === 0 && classifierImplementations.length === 0) throw new Error(`Provider ${input.id}: at least one of "api", "images", or "classifiers" is required.`);
|
|
1383
|
+
const baselineModels = input.models;
|
|
1384
|
+
let dynamicModels = [];
|
|
1385
|
+
const fetchModels = input.fetchModels;
|
|
1386
|
+
const currentModels = () => {
|
|
1387
|
+
const merged = [...baselineModels];
|
|
1388
|
+
for (const model of dynamicModels) {
|
|
1389
|
+
const index = merged.findIndex((entry) => getModelType(entry) === getModelType(model) && entry.id === model.id);
|
|
1390
|
+
if (index >= 0) merged[index] = model;
|
|
1391
|
+
else merged.push(model);
|
|
1392
|
+
}
|
|
1393
|
+
return merged;
|
|
1394
|
+
};
|
|
1395
|
+
const apiFor = (model) => single ?? byApi?.[model.api];
|
|
1396
|
+
const dispatch = (model, run) => {
|
|
1397
|
+
const streams = apiFor(model);
|
|
1398
|
+
if (!streams) return lazyStream(model, async () => {
|
|
1399
|
+
throw new ModelsError("stream", `Provider ${input.id} has no API implementation for "${model.api}"`);
|
|
1400
|
+
});
|
|
1401
|
+
return run(streams);
|
|
1402
|
+
};
|
|
1403
|
+
const provider = {
|
|
1404
|
+
id: input.id,
|
|
1405
|
+
name: input.name ?? input.id,
|
|
1406
|
+
baseUrl: input.baseUrl,
|
|
1407
|
+
headers: input.headers,
|
|
1408
|
+
auth: input.auth,
|
|
1409
|
+
getModels: () => currentModels().filter((model) => isModelType(model, "chat")),
|
|
1410
|
+
getAllModels: currentModels,
|
|
1411
|
+
refreshModels: fetchModels ? async (context) => {
|
|
1412
|
+
if (context.stored) {
|
|
1413
|
+
const restored = context.stored.models.filter((model) => model.provider === input.id).map((model) => model);
|
|
1414
|
+
if (!await context.publish({ update: () => {
|
|
1415
|
+
dynamicModels = restored;
|
|
1416
|
+
} })) return;
|
|
1417
|
+
}
|
|
1418
|
+
if (!context.allowNetwork || context.signal.aborted) return;
|
|
1419
|
+
const fetched = await fetchModels(context);
|
|
1420
|
+
if (context.signal.aborted) return;
|
|
1421
|
+
const refreshed = fetched.filter(hasKnownModelType);
|
|
1422
|
+
await context.publish({
|
|
1423
|
+
persist: {
|
|
1424
|
+
models: refreshed,
|
|
1425
|
+
checkedAt: Date.now()
|
|
1426
|
+
},
|
|
1427
|
+
update: () => {
|
|
1428
|
+
dynamicModels = refreshed;
|
|
1429
|
+
}
|
|
1430
|
+
});
|
|
1431
|
+
} : void 0,
|
|
1432
|
+
filterModels: input.filterModels,
|
|
1433
|
+
filterAllModels: input.filterAllModels,
|
|
1434
|
+
stream: (model, context, options) => dispatch(model, (streams) => streams.stream(model, context, options)),
|
|
1435
|
+
streamSimple: (model, context, options) => dispatch(model, (streams) => streams.streamSimple(model, context, options))
|
|
1436
|
+
};
|
|
1437
|
+
if (streams.some((entry) => entry.fetchDeferred !== void 0)) provider.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
|
|
1438
|
+
const implementation = apiFor(model);
|
|
1439
|
+
if (!implementation?.fetchDeferred) throw new ModelsError("provider", `Provider ${input.id} does not support deferred responses for "${model.api}"`);
|
|
1440
|
+
return implementation.fetchDeferred(model, handle, options);
|
|
1441
|
+
});
|
|
1442
|
+
if (streams.some((entry) => entry.cancelDeferred !== void 0)) provider.cancelDeferred = async (model, handle, options) => {
|
|
1443
|
+
const implementation = apiFor(model);
|
|
1444
|
+
if (!implementation?.cancelDeferred) throw new ModelsError("provider", `Provider ${input.id} cannot cancel deferred responses for "${model.api}"`);
|
|
1445
|
+
await implementation.cancelDeferred(model, handle, options);
|
|
1446
|
+
};
|
|
1447
|
+
if (images && imageImplementations.length > 0) provider.generateImages = async (model, context, options) => {
|
|
1448
|
+
const implementation = images[model.api];
|
|
1449
|
+
if (!implementation) return imageErrorResult(model, new ModelsError("provider", `Provider ${input.id} has no image generation implementation for "${model.api}"`));
|
|
1450
|
+
return implementation.generateImages(model, context, options);
|
|
1451
|
+
};
|
|
1452
|
+
if (classifiers && classifierImplementations.length > 0) provider.classify = async (model, context, options) => {
|
|
1453
|
+
const implementation = classifiers[model.api];
|
|
1454
|
+
if (!implementation) return classifierErrorResult(model, new ModelsError("provider", `Provider ${input.id} has no classifier implementation for "${model.api}"`));
|
|
1455
|
+
return implementation.classify(model, context, options);
|
|
1456
|
+
};
|
|
1457
|
+
return provider;
|
|
1458
|
+
}
|
|
1459
|
+
function calculateCost(model, usage) {
|
|
1460
|
+
const inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
1461
|
+
let rates = model.cost;
|
|
1462
|
+
let matchedThreshold = -1;
|
|
1463
|
+
for (const tier of model.cost.tiers ?? []) if (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {
|
|
1464
|
+
rates = tier;
|
|
1465
|
+
matchedThreshold = tier.inputTokensAbove;
|
|
1466
|
+
}
|
|
1467
|
+
const longWrite = usage.cacheWrite1h ?? 0;
|
|
1468
|
+
const shortWrite = usage.cacheWrite - longWrite;
|
|
1469
|
+
usage.cost.input = rates.input / 1e6 * usage.input;
|
|
1470
|
+
usage.cost.output = rates.output / 1e6 * usage.output;
|
|
1471
|
+
usage.cost.cacheRead = rates.cacheRead / 1e6 * usage.cacheRead;
|
|
1472
|
+
usage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1e6;
|
|
1473
|
+
usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
1474
|
+
usage.cost.totalFromProvider = false;
|
|
1475
|
+
return usage.cost;
|
|
1476
|
+
}
|
|
1477
|
+
const EXTENDED_THINKING_LEVELS = [
|
|
1478
|
+
"off",
|
|
1479
|
+
"minimal",
|
|
1480
|
+
"low",
|
|
1481
|
+
"medium",
|
|
1482
|
+
"high",
|
|
1483
|
+
"xhigh",
|
|
1484
|
+
"max"
|
|
1485
|
+
];
|
|
1486
|
+
function getSupportedThinkingLevels(model) {
|
|
1487
|
+
if (!model.reasoning) return ["off"];
|
|
1488
|
+
return EXTENDED_THINKING_LEVELS.filter((level) => {
|
|
1489
|
+
const mapped = model.thinkingLevelMap?.[level];
|
|
1490
|
+
if (mapped === null) return false;
|
|
1491
|
+
if (level === "xhigh" || level === "max") return mapped !== void 0;
|
|
1492
|
+
return true;
|
|
1493
|
+
});
|
|
1494
|
+
}
|
|
1495
|
+
function clampThinkingLevel(model, level) {
|
|
1496
|
+
const availableLevels = getSupportedThinkingLevels(model);
|
|
1497
|
+
if (availableLevels.includes(level)) return level;
|
|
1498
|
+
const requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);
|
|
1499
|
+
if (requestedIndex === -1) return availableLevels[0] ?? "off";
|
|
1500
|
+
for (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i++) {
|
|
1501
|
+
const candidate = EXTENDED_THINKING_LEVELS[i];
|
|
1502
|
+
if (availableLevels.includes(candidate)) return candidate;
|
|
1503
|
+
}
|
|
1504
|
+
for (let i = requestedIndex - 1; i >= 0; i--) {
|
|
1505
|
+
const candidate = EXTENDED_THINKING_LEVELS[i];
|
|
1506
|
+
if (availableLevels.includes(candidate)) return candidate;
|
|
1507
|
+
}
|
|
1508
|
+
return availableLevels[0] ?? "off";
|
|
1509
|
+
}
|
|
1510
|
+
//#endregion
|
|
1511
|
+
export { createTypedMetrics as S, normalizeContext as _, getSupportedThinkingLevels as a, toToolDeclaration as b, ModelsError as c, collapseSystemMessages as d, declarationsEqual as f, getInitialSystemMessage as g, getDeclaredTools as h, createProvider as i, lazyApi as l, getCurrentTools as m, clampThinkingLevel as n, getModelType as o, getCurrentSystemPrompt as p, createModels as r, isModelType as s, calculateCost as t, lazyStream as u, resolveTranscript as v, withoutInitialSystemMessage as x, resolveTranscriptTools as y };
|