@anvia/core 1.1.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +226 -0
- package/dist/agent/agent-stream.js +7 -0
- package/dist/agent/agent-stream.js.map +1 -0
- package/dist/agent/agent-tool.js +24 -0
- package/dist/agent/agent-tool.js.map +1 -0
- package/dist/agent/agent.js +89 -0
- package/dist/agent/agent.js.map +1 -0
- package/dist/agent/errors.js +17 -0
- package/dist/agent/errors.js.map +1 -0
- package/dist/agent/ids.js +7 -0
- package/dist/agent/ids.js.map +1 -0
- package/dist/agent/index.d.ts +127 -9
- package/dist/agent/index.js +103 -21
- package/dist/agent/interactions/index.js +2 -2
- package/dist/agent/interactions.js +22 -0
- package/dist/agent/interactions.js.map +1 -0
- package/dist/agent/lifecycle.js +9 -0
- package/dist/agent/lifecycle.js.map +1 -0
- package/dist/agent/output-schema.js +10 -0
- package/dist/agent/output-schema.js.map +1 -0
- package/dist/agent/resolve-options.js +46 -0
- package/dist/agent/resolve-options.js.map +1 -0
- package/dist/agent/resolved-agent.js +92 -0
- package/dist/agent/resolved-agent.js.map +1 -0
- package/dist/agent/run-types.js +1 -0
- package/dist/agent/run-types.js.map +1 -0
- package/dist/agent/snapshot.js +17 -0
- package/dist/agent/snapshot.js.map +1 -0
- package/dist/agent/team/agent-team.js +98 -0
- package/dist/agent/team/agent-team.js.map +1 -0
- package/dist/agent/team/errors.js +9 -0
- package/dist/agent/team/errors.js.map +1 -0
- package/dist/agent/team/index.js +104 -0
- package/dist/agent/team/index.js.map +1 -0
- package/dist/agent/team/types.js +1 -0
- package/dist/agent/team/types.js.map +1 -0
- package/dist/agent/tool-catalog.js +37 -0
- package/dist/agent/tool-catalog.js.map +1 -0
- package/dist/agent/tool-state.js +11 -0
- package/dist/agent/tool-state.js.map +1 -0
- package/dist/agent/types.js +1 -0
- package/dist/agent/types.js.map +1 -0
- package/dist/agent/vector-context.js +10 -0
- package/dist/agent/vector-context.js.map +1 -0
- package/dist/{agent-DTmzs1Qr.d.ts → agent-C9VhENdj.d.ts} +2 -3
- package/dist/{chunk-2QZJTG2E.js → chunk-23GEYG2X.js} +11 -71
- package/dist/chunk-23GEYG2X.js.map +1 -0
- package/dist/{chunk-I3Q7XSBB.js → chunk-23LRXKQX.js} +6 -4
- package/dist/{chunk-I3Q7XSBB.js.map → chunk-23LRXKQX.js.map} +1 -1
- package/dist/{chunk-YK4WAAS4.js → chunk-2NLINXRF.js} +1 -1
- package/dist/{chunk-SPD4XVR7.js → chunk-2XSMGVBG.js} +1 -1
- package/dist/chunk-3J2CSVPR.js +1 -0
- package/dist/chunk-3J2CSVPR.js.map +1 -0
- package/dist/chunk-3P3YVJ7V.js +1 -0
- package/dist/chunk-3P3YVJ7V.js.map +1 -0
- package/dist/chunk-3TAQXJBC.js +107 -0
- package/dist/chunk-3TAQXJBC.js.map +1 -0
- package/dist/chunk-47NTHIVB.js +76 -0
- package/dist/chunk-47NTHIVB.js.map +1 -0
- package/dist/chunk-4AW2633B.js +9 -0
- package/dist/chunk-4AW2633B.js.map +1 -0
- package/dist/{chunk-3XQGVDU5.js → chunk-4C7AXYOM.js} +1 -1
- package/dist/{chunk-IZNOP6JG.js → chunk-4FIVU53H.js} +1 -1
- package/dist/chunk-4ITAV7YA.js +1 -0
- package/dist/chunk-4ITAV7YA.js.map +1 -0
- package/dist/{chunk-7JLAIN6E.js → chunk-4ONUNWGC.js} +2 -2
- package/dist/chunk-4UUIGAIX.js +1 -0
- package/dist/chunk-4UUIGAIX.js.map +1 -0
- package/dist/chunk-53TPAXYR.js +1 -0
- package/dist/chunk-53TPAXYR.js.map +1 -0
- package/dist/chunk-5AETKC4L.js +107 -0
- package/dist/chunk-5AETKC4L.js.map +1 -0
- package/dist/chunk-5I2NVRHC.js +146 -0
- package/dist/chunk-5I2NVRHC.js.map +1 -0
- package/dist/chunk-5IURMWFN.js +53 -0
- package/dist/chunk-5IURMWFN.js.map +1 -0
- package/dist/chunk-5M6GTA3T.js +1 -0
- package/dist/chunk-5M6GTA3T.js.map +1 -0
- package/dist/chunk-5N5W7CX7.js +18 -0
- package/dist/chunk-5N5W7CX7.js.map +1 -0
- package/dist/chunk-5P2YOQSA.js +355 -0
- package/dist/chunk-5P2YOQSA.js.map +1 -0
- package/dist/chunk-5S7T2URX.js +1 -0
- package/dist/chunk-5S7T2URX.js.map +1 -0
- package/dist/chunk-5V533R7F.js +19 -0
- package/dist/chunk-5V533R7F.js.map +1 -0
- package/dist/chunk-5WLIHNNJ.js +56 -0
- package/dist/chunk-5WLIHNNJ.js.map +1 -0
- package/dist/chunk-6BTJC3ES.js +37 -0
- package/dist/chunk-6BTJC3ES.js.map +1 -0
- package/dist/chunk-6N4ENZO4.js +24 -0
- package/dist/chunk-6N4ENZO4.js.map +1 -0
- package/dist/{chunk-4UQALF5Y.js → chunk-6RQYWZI3.js} +2 -36
- package/dist/chunk-6RQYWZI3.js.map +1 -0
- package/dist/chunk-6TAWRKFK.js +86 -0
- package/dist/chunk-6TAWRKFK.js.map +1 -0
- package/dist/chunk-7F53DOML.js +53 -0
- package/dist/chunk-7F53DOML.js.map +1 -0
- package/dist/chunk-7KAGWJ5M.js +112 -0
- package/dist/chunk-7KAGWJ5M.js.map +1 -0
- package/dist/chunk-7LBPRXZP.js +1 -0
- package/dist/chunk-7LBPRXZP.js.map +1 -0
- package/dist/chunk-A7BXVZXZ.js +25 -0
- package/dist/chunk-A7BXVZXZ.js.map +1 -0
- package/dist/chunk-B47EXUHL.js +67 -0
- package/dist/chunk-B47EXUHL.js.map +1 -0
- package/dist/chunk-B5JQDR33.js +14 -0
- package/dist/chunk-B5JQDR33.js.map +1 -0
- package/dist/chunk-B5YTCKUJ.js +158 -0
- package/dist/chunk-B5YTCKUJ.js.map +1 -0
- package/dist/chunk-BDDC72GF.js +189 -0
- package/dist/chunk-BDDC72GF.js.map +1 -0
- package/dist/chunk-BDKFFFVX.js +342 -0
- package/dist/chunk-BDKFFFVX.js.map +1 -0
- package/dist/{chunk-QGX73TSQ.js → chunk-BONQTXRQ.js} +3 -12
- package/dist/chunk-BONQTXRQ.js.map +1 -0
- package/dist/chunk-BUPC72Y2.js +1007 -0
- package/dist/chunk-BUPC72Y2.js.map +1 -0
- package/dist/chunk-CKKNO4XB.js +70 -0
- package/dist/chunk-CKKNO4XB.js.map +1 -0
- package/dist/chunk-CX7ZVTO5.js +22 -0
- package/dist/chunk-CX7ZVTO5.js.map +1 -0
- package/dist/chunk-DU4WA6LQ.js +1 -0
- package/dist/chunk-DU4WA6LQ.js.map +1 -0
- package/dist/chunk-EJR6VVB3.js +63 -0
- package/dist/chunk-EJR6VVB3.js.map +1 -0
- package/dist/chunk-EKZRAWBP.js +110 -0
- package/dist/chunk-EKZRAWBP.js.map +1 -0
- package/dist/chunk-ENZ2XX27.js +26 -0
- package/dist/chunk-ENZ2XX27.js.map +1 -0
- package/dist/chunk-EOAJBBII.js +1 -0
- package/dist/chunk-EOAJBBII.js.map +1 -0
- package/dist/chunk-ERN7P6Q4.js +1 -0
- package/dist/chunk-ERN7P6Q4.js.map +1 -0
- package/dist/chunk-ESOFEAYK.js +57 -0
- package/dist/chunk-ESOFEAYK.js.map +1 -0
- package/dist/chunk-ETYB5JO6.js +175 -0
- package/dist/chunk-ETYB5JO6.js.map +1 -0
- package/dist/chunk-EZR5AV3J.js +74 -0
- package/dist/chunk-EZR5AV3J.js.map +1 -0
- package/dist/chunk-F2OKLHGB.js +9 -0
- package/dist/chunk-F2OKLHGB.js.map +1 -0
- package/dist/chunk-F3E2RLC7.js +342 -0
- package/dist/chunk-F3E2RLC7.js.map +1 -0
- package/dist/chunk-FAPIZJS2.js +54 -0
- package/dist/chunk-FAPIZJS2.js.map +1 -0
- package/dist/chunk-GDJNOZ47.js +1 -0
- package/dist/chunk-GDJNOZ47.js.map +1 -0
- package/dist/chunk-GDY2Z2SZ.js +83 -0
- package/dist/chunk-GDY2Z2SZ.js.map +1 -0
- package/dist/chunk-GLMYZ6OA.js +20 -0
- package/dist/chunk-GLMYZ6OA.js.map +1 -0
- package/dist/{chunk-XEVOC433.js → chunk-GPVXCY5I.js} +2 -73
- package/dist/chunk-GPVXCY5I.js.map +1 -0
- package/dist/{chunk-KSKST3KP.js → chunk-H3H74RWJ.js} +1 -1
- package/dist/chunk-HAAGSIZH.js +89 -0
- package/dist/chunk-HAAGSIZH.js.map +1 -0
- package/dist/{chunk-K5L7R7XM.js → chunk-HHMLE3TZ.js} +6 -54
- package/dist/chunk-HHMLE3TZ.js.map +1 -0
- package/dist/{chunk-JLJMVRRE.js → chunk-HP34GRQX.js} +10 -83
- package/dist/chunk-HP34GRQX.js.map +1 -0
- package/dist/chunk-HTI343NP.js +1 -0
- package/dist/chunk-HTI343NP.js.map +1 -0
- package/dist/{chunk-T2C3CGDQ.js → chunk-HTI7DZJM.js} +6 -4
- package/dist/{chunk-T2C3CGDQ.js.map → chunk-HTI7DZJM.js.map} +1 -1
- package/dist/chunk-IDNL6IH4.js +294 -0
- package/dist/chunk-IDNL6IH4.js.map +1 -0
- package/dist/chunk-IV6YQTY2.js +47 -0
- package/dist/chunk-IV6YQTY2.js.map +1 -0
- package/dist/chunk-J4SINPUA.js +939 -0
- package/dist/chunk-J4SINPUA.js.map +1 -0
- package/dist/chunk-J6S6MT7O.js +32 -0
- package/dist/chunk-J6S6MT7O.js.map +1 -0
- package/dist/chunk-JB3RFK6K.js +168 -0
- package/dist/chunk-JB3RFK6K.js.map +1 -0
- package/dist/chunk-JBQNCUXA.js +34 -0
- package/dist/chunk-JBQNCUXA.js.map +1 -0
- package/dist/chunk-JMJFK3A4.js +1 -0
- package/dist/chunk-JMJFK3A4.js.map +1 -0
- package/dist/chunk-JMMZICU7.js +74 -0
- package/dist/chunk-JMMZICU7.js.map +1 -0
- package/dist/chunk-JOQ2T3QP.js +663 -0
- package/dist/chunk-JOQ2T3QP.js.map +1 -0
- package/dist/chunk-K4IBS7VB.js +55 -0
- package/dist/chunk-K4IBS7VB.js.map +1 -0
- package/dist/chunk-KBBQSP4M.js +16 -0
- package/dist/chunk-KBBQSP4M.js.map +1 -0
- package/dist/chunk-KFAVEL5F.js +68 -0
- package/dist/chunk-KFAVEL5F.js.map +1 -0
- package/dist/chunk-KITX3HDN.js +17 -0
- package/dist/chunk-KITX3HDN.js.map +1 -0
- package/dist/chunk-KO5NMTAM.js +1 -0
- package/dist/chunk-KO5NMTAM.js.map +1 -0
- package/dist/chunk-KY4VXIN2.js +118 -0
- package/dist/chunk-KY4VXIN2.js.map +1 -0
- package/dist/chunk-KZGSXJKU.js +29 -0
- package/dist/chunk-KZGSXJKU.js.map +1 -0
- package/dist/chunk-LAIATEUB.js +24 -0
- package/dist/chunk-LAIATEUB.js.map +1 -0
- package/dist/{chunk-OJBFDBLG.js → chunk-LBYJPMHC.js} +2 -2
- package/dist/chunk-LKIABZNR.js +49 -0
- package/dist/chunk-LKIABZNR.js.map +1 -0
- package/dist/chunk-LQJ4KHMY.js +23 -0
- package/dist/chunk-LQJ4KHMY.js.map +1 -0
- package/dist/chunk-MEN4AFDZ.js +1 -0
- package/dist/chunk-MEN4AFDZ.js.map +1 -0
- package/dist/chunk-MHOJJYDK.js +93 -0
- package/dist/chunk-MHOJJYDK.js.map +1 -0
- package/dist/chunk-MJCMKZFP.js +30 -0
- package/dist/chunk-MJCMKZFP.js.map +1 -0
- package/dist/chunk-MT3BLVYN.js +31 -0
- package/dist/chunk-MT3BLVYN.js.map +1 -0
- package/dist/chunk-NF6WBPFG.js +37 -0
- package/dist/chunk-NF6WBPFG.js.map +1 -0
- package/dist/chunk-NNEKBZSM.js +66 -0
- package/dist/chunk-NNEKBZSM.js.map +1 -0
- package/dist/chunk-NPJ2T3L5.js +19 -0
- package/dist/chunk-NPJ2T3L5.js.map +1 -0
- package/dist/chunk-NVALGVQG.js +150 -0
- package/dist/chunk-NVALGVQG.js.map +1 -0
- package/dist/chunk-OJF67RNM.js +1 -0
- package/dist/chunk-OJF67RNM.js.map +1 -0
- package/dist/chunk-PHLGGRHC.js +89 -0
- package/dist/chunk-PHLGGRHC.js.map +1 -0
- package/dist/chunk-PIMD4DYG.js +104 -0
- package/dist/chunk-PIMD4DYG.js.map +1 -0
- package/dist/chunk-PJNE75WC.js +1 -0
- package/dist/chunk-PJNE75WC.js.map +1 -0
- package/dist/{chunk-J6LVLV6P.js → chunk-PLDJCCVL.js} +1 -1
- package/dist/{chunk-3RWESPUG.js → chunk-POXHJF3H.js} +6 -51
- package/dist/chunk-POXHJF3H.js.map +1 -0
- package/dist/chunk-PPJ7SYQL.js +81 -0
- package/dist/chunk-PPJ7SYQL.js.map +1 -0
- package/dist/chunk-PT777EQ3.js +48 -0
- package/dist/chunk-PT777EQ3.js.map +1 -0
- package/dist/chunk-PYLPLFJZ.js +318 -0
- package/dist/chunk-PYLPLFJZ.js.map +1 -0
- package/dist/chunk-QEPBHHAP.js +41 -0
- package/dist/chunk-QEPBHHAP.js.map +1 -0
- package/dist/chunk-QHGYCYV6.js +91 -0
- package/dist/chunk-QHGYCYV6.js.map +1 -0
- package/dist/chunk-R6722CIU.js +28 -0
- package/dist/chunk-R6722CIU.js.map +1 -0
- package/dist/chunk-RA4YVN43.js +1 -0
- package/dist/chunk-RA4YVN43.js.map +1 -0
- package/dist/chunk-RT5LUEO3.js +2339 -0
- package/dist/chunk-RT5LUEO3.js.map +1 -0
- package/dist/chunk-RXKUIJ77.js +236 -0
- package/dist/chunk-RXKUIJ77.js.map +1 -0
- package/dist/chunk-SC4SUIEY.js +1 -0
- package/dist/chunk-SC4SUIEY.js.map +1 -0
- package/dist/chunk-SQAAVYJG.js +12 -0
- package/dist/chunk-SQAAVYJG.js.map +1 -0
- package/dist/chunk-SXE4J43E.js +59 -0
- package/dist/chunk-SXE4J43E.js.map +1 -0
- package/dist/{chunk-EFLT7XZD.js → chunk-SYULMZGL.js} +6 -4
- package/dist/{chunk-EFLT7XZD.js.map → chunk-SYULMZGL.js.map} +1 -1
- package/dist/chunk-T4KS577P.js +58 -0
- package/dist/chunk-T4KS577P.js.map +1 -0
- package/dist/chunk-TFIOU6UR.js +78 -0
- package/dist/chunk-TFIOU6UR.js.map +1 -0
- package/dist/chunk-TIZGADU4.js +375 -0
- package/dist/chunk-TIZGADU4.js.map +1 -0
- package/dist/chunk-TP3MCUXS.js +1 -0
- package/dist/chunk-TP3MCUXS.js.map +1 -0
- package/dist/chunk-TSPQD5HW.js +613 -0
- package/dist/chunk-TSPQD5HW.js.map +1 -0
- package/dist/{chunk-JTJU56ZV.js → chunk-UOGM62JL.js} +11 -7
- package/dist/{chunk-JTJU56ZV.js.map → chunk-UOGM62JL.js.map} +1 -1
- package/dist/chunk-USRKPEQN.js +55 -0
- package/dist/chunk-USRKPEQN.js.map +1 -0
- package/dist/chunk-UTAB3XQI.js +667 -0
- package/dist/chunk-UTAB3XQI.js.map +1 -0
- package/dist/chunk-V3FFZWF3.js +182 -0
- package/dist/chunk-V3FFZWF3.js.map +1 -0
- package/dist/chunk-V4OZ7ISA.js +9 -0
- package/dist/chunk-V4OZ7ISA.js.map +1 -0
- package/dist/chunk-VZ5ZZBNX.js +139 -0
- package/dist/chunk-VZ5ZZBNX.js.map +1 -0
- package/dist/{chunk-AHLKV6KP.js → chunk-WN6AVBO4.js} +1 -1
- package/dist/chunk-WXR5CWSC.js +1 -0
- package/dist/chunk-WXR5CWSC.js.map +1 -0
- package/dist/chunk-X6WS3XWL.js +36 -0
- package/dist/chunk-X6WS3XWL.js.map +1 -0
- package/dist/{chunk-Q5BCNYED.js → chunk-XJRNBTIV.js} +7 -4
- package/dist/chunk-XQV3XNVT.js +225 -0
- package/dist/chunk-XQV3XNVT.js.map +1 -0
- package/dist/chunk-XV3DH5GC.js +58 -0
- package/dist/chunk-XV3DH5GC.js.map +1 -0
- package/dist/chunk-YWRXOPHC.js +43 -0
- package/dist/chunk-YWRXOPHC.js.map +1 -0
- package/dist/chunk-YZVFIW5D.js +27 -0
- package/dist/chunk-YZVFIW5D.js.map +1 -0
- package/dist/chunk-ZHC5CD6J.js +33 -0
- package/dist/chunk-ZHC5CD6J.js.map +1 -0
- package/dist/chunk-ZPJFXRQZ.js +23 -0
- package/dist/chunk-ZPJFXRQZ.js.map +1 -0
- package/dist/chunk-ZPXOBQDS.js +57 -0
- package/dist/chunk-ZPXOBQDS.js.map +1 -0
- package/dist/chunk-ZUFS6R7L.js +155 -0
- package/dist/chunk-ZUFS6R7L.js.map +1 -0
- package/dist/chunk-ZXLCTQUX.js +62 -0
- package/dist/chunk-ZXLCTQUX.js.map +1 -0
- package/dist/chunk-ZYXMWEL4.js +59 -0
- package/dist/chunk-ZYXMWEL4.js.map +1 -0
- package/dist/completion/controls.js +11 -0
- package/dist/completion/controls.js.map +1 -0
- package/dist/completion/documents.js +9 -0
- package/dist/completion/documents.js.map +1 -0
- package/dist/completion/generate-completion.js +23 -0
- package/dist/completion/generate-completion.js.map +1 -0
- package/dist/completion/index.js +23 -12
- package/dist/completion/json.js +7 -0
- package/dist/completion/json.js.map +1 -0
- package/dist/completion/message-schema.js +18 -0
- package/dist/completion/message-schema.js.map +1 -0
- package/dist/completion/provider-output-error.js +12 -0
- package/dist/completion/provider-output-error.js.map +1 -0
- package/dist/completion/stream-accumulator.js +10 -0
- package/dist/completion/stream-accumulator.js.map +1 -0
- package/dist/completion/types.js +28 -0
- package/dist/completion/types.js.map +1 -0
- package/dist/documents/chunk-text.js +7 -0
- package/dist/documents/chunk-text.js.map +1 -0
- package/dist/documents/index.js +5 -2
- package/dist/documents/text-document.js +8 -0
- package/dist/documents/text-document.js.map +1 -0
- package/dist/embeddings/distance.js +17 -0
- package/dist/embeddings/distance.js.map +1 -0
- package/dist/embeddings/embed.js +18 -0
- package/dist/embeddings/embed.js.map +1 -0
- package/dist/embeddings/index.js +11 -6
- package/dist/embeddings/types.js +2 -0
- package/dist/embeddings/types.js.map +1 -0
- package/dist/evals/advanced-metrics.js +46 -0
- package/dist/evals/advanced-metrics.js.map +1 -0
- package/dist/evals/agent-target.js +10 -0
- package/dist/evals/agent-target.js.map +1 -0
- package/dist/evals/cli.js +40 -0
- package/dist/evals/cli.js.map +1 -0
- package/dist/evals/execution.js +15 -0
- package/dist/evals/execution.js.map +1 -0
- package/dist/evals/format.js +13 -0
- package/dist/evals/format.js.map +1 -0
- package/dist/evals/index.d.ts +4 -4
- package/dist/evals/index.js +87 -2660
- package/dist/evals/index.js.map +1 -1
- package/dist/evals/judge.js +27 -0
- package/dist/evals/judge.js.map +1 -0
- package/dist/evals/metric.js +7 -0
- package/dist/evals/metric.js.map +1 -0
- package/dist/evals/metrics.js +53 -0
- package/dist/evals/metrics.js.map +1 -0
- package/dist/evals/outcome.js +7 -0
- package/dist/evals/outcome.js.map +1 -0
- package/dist/evals/reporting.js +11 -0
- package/dist/evals/reporting.js.map +1 -0
- package/dist/evals/runner.js +29 -0
- package/dist/evals/runner.js.map +1 -0
- package/dist/evals/selectors.js +18 -0
- package/dist/evals/selectors.js.map +1 -0
- package/dist/evals/suite.js +11 -0
- package/dist/evals/suite.js.map +1 -0
- package/dist/evals/types.js +1 -0
- package/dist/evals/types.js.map +1 -0
- package/dist/extractor/extractor.js +23 -0
- package/dist/extractor/extractor.js.map +1 -0
- package/dist/extractor/index.js +16 -7
- package/dist/guardrails/actions.js +13 -0
- package/dist/guardrails/actions.js.map +1 -0
- package/dist/guardrails/index.d.ts +3 -4
- package/dist/guardrails/index.js +15 -7
- package/dist/guardrails/message.js +9 -0
- package/dist/guardrails/message.js.map +1 -0
- package/dist/guardrails/policy.js +17 -0
- package/dist/guardrails/policy.js.map +1 -0
- package/dist/guardrails/runtime.js +11 -0
- package/dist/guardrails/runtime.js.map +1 -0
- package/dist/guardrails/text.js +9 -0
- package/dist/guardrails/text.js.map +1 -0
- package/dist/guardrails/types.js +1 -0
- package/dist/guardrails/types.js.map +1 -0
- package/dist/hooks/control.js +17 -0
- package/dist/hooks/control.js.map +1 -0
- package/dist/hooks/index.js +19 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/types.js +2 -0
- package/dist/hooks/types.js.map +1 -0
- package/dist/image-generation/generate-image.js +11 -0
- package/dist/image-generation/generate-image.js.map +1 -0
- package/dist/image-generation/index.js +7 -4
- package/dist/image-generation/types.js +2 -0
- package/dist/image-generation/types.js.map +1 -0
- package/dist/index.d.ts +5 -7
- package/dist/index.js +163 -57
- package/dist/internal/abort.js +13 -0
- package/dist/internal/abort.js.map +1 -0
- package/dist/internal/agent-runtime/agent-run.js +81 -0
- package/dist/internal/agent-runtime/agent-run.js.map +1 -0
- package/dist/internal/agent-runtime/approval-request.js +1 -0
- package/dist/internal/agent-runtime/approval-request.js.map +1 -0
- package/dist/internal/agent-runtime/approval-requirement.js +9 -0
- package/dist/internal/agent-runtime/approval-requirement.js.map +1 -0
- package/dist/internal/agent-runtime/continuation-state.js +26 -0
- package/dist/internal/agent-runtime/continuation-state.js.map +1 -0
- package/dist/internal/agent-runtime/interaction-suspension.js +25 -0
- package/dist/internal/agent-runtime/interaction-suspension.js.map +1 -0
- package/dist/internal/agent-runtime/memory-scope.js +8 -0
- package/dist/internal/agent-runtime/memory-scope.js.map +1 -0
- package/dist/internal/agent-runtime/memory.js +24 -0
- package/dist/internal/agent-runtime/memory.js.map +1 -0
- package/dist/internal/agent-runtime/prepared-tool-call.js +19 -0
- package/dist/internal/agent-runtime/prepared-tool-call.js.map +1 -0
- package/dist/internal/agent-runtime/retrieval.js +35 -0
- package/dist/internal/agent-runtime/retrieval.js.map +1 -0
- package/dist/internal/agent-runtime/run-options.js +9 -0
- package/dist/internal/agent-runtime/run-options.js.map +1 -0
- package/dist/internal/agent-runtime/run-validation.js +9 -0
- package/dist/internal/agent-runtime/run-validation.js.map +1 -0
- package/dist/internal/agent-runtime/stream-events.js +11 -0
- package/dist/internal/agent-runtime/stream-events.js.map +1 -0
- package/dist/internal/agent-runtime/structured-output.js +13 -0
- package/dist/internal/agent-runtime/structured-output.js.map +1 -0
- package/dist/internal/agent-runtime/tool-execution.js +55 -0
- package/dist/internal/agent-runtime/tool-execution.js.map +1 -0
- package/dist/internal/agent.d.ts +5 -5
- package/dist/internal/agent.js +93 -57
- package/dist/internal/agent.js.map +1 -1
- package/dist/internal/async-queue.js +7 -0
- package/dist/internal/async-queue.js.map +1 -0
- package/dist/internal/completion-request.js +11 -0
- package/dist/internal/completion-request.js.map +1 -0
- package/dist/internal/concurrency.js +7 -0
- package/dist/internal/concurrency.js.map +1 -0
- package/dist/internal/json-object.js +8 -0
- package/dist/internal/json-object.js.map +1 -0
- package/dist/internal/rag-text.js +7 -0
- package/dist/internal/rag-text.js.map +1 -0
- package/dist/internal/record.js +7 -0
- package/dist/internal/record.js.map +1 -0
- package/dist/internal/team-runtime/coordination.js +12 -0
- package/dist/internal/team-runtime/coordination.js.map +1 -0
- package/dist/internal/team-runtime/member.js +26 -0
- package/dist/internal/team-runtime/member.js.map +1 -0
- package/dist/internal/team-runtime/policy.js +7 -0
- package/dist/internal/team-runtime/policy.js.map +1 -0
- package/dist/internal/team-runtime/run.js +95 -0
- package/dist/internal/team-runtime/run.js.map +1 -0
- package/dist/internal/team-runtime/stream.js +9 -0
- package/dist/internal/team-runtime/stream.js.map +1 -0
- package/dist/internal/team-runtime/tools.js +17 -0
- package/dist/internal/team-runtime/tools.js.map +1 -0
- package/dist/internal/type-utils.js +1 -0
- package/dist/internal/type-utils.js.map +1 -0
- package/dist/internal/vector-search-options.js +9 -0
- package/dist/internal/vector-search-options.js.map +1 -0
- package/dist/mcp/index.js +3 -1
- package/dist/mcp/tool.js +7 -0
- package/dist/mcp/tool.js.map +1 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/memory/assert.js +11 -0
- package/dist/memory/assert.js.map +1 -0
- package/dist/memory/compaction.js +26 -0
- package/dist/memory/compaction.js.map +1 -0
- package/dist/memory/errors.js +9 -0
- package/dist/memory/errors.js.map +1 -0
- package/dist/memory/index.js +23 -10
- package/dist/memory/options.js +10 -0
- package/dist/memory/options.js.map +1 -0
- package/dist/memory/scope-key.js +7 -0
- package/dist/memory/scope-key.js.map +1 -0
- package/dist/memory/types.js +2 -0
- package/dist/memory/types.js.map +1 -0
- package/dist/{types-CRda8x7p.d.ts → middleware-CWjnMbiH.d.ts} +64 -5
- package/dist/model-call-options.js +1 -0
- package/dist/model-call-options.js.map +1 -0
- package/dist/model-listing/errors.js +7 -0
- package/dist/model-listing/errors.js.map +1 -0
- package/dist/model-listing/index.js +4 -13
- package/dist/model-listing/index.js.map +1 -1
- package/dist/model-listing/types.js +2 -0
- package/dist/model-listing/types.js.map +1 -0
- package/dist/observability/group.js +30 -0
- package/dist/observability/group.js.map +1 -0
- package/dist/observability/index.d.ts +4 -6
- package/dist/observability/index.js +16 -8
- package/dist/observability/snapshot.js +7 -0
- package/dist/observability/snapshot.js.map +1 -0
- package/dist/observability/types.js +1 -0
- package/dist/observability/types.js.map +1 -0
- package/dist/pipeline/errors.js +9 -0
- package/dist/pipeline/errors.js.map +1 -0
- package/dist/pipeline/graph.js +21 -0
- package/dist/pipeline/graph.js.map +1 -0
- package/dist/pipeline/index.d.ts +4 -6
- package/dist/pipeline/index.js +27 -805
- package/dist/pipeline/index.js.map +1 -1
- package/dist/pipeline/observability.js +15 -0
- package/dist/pipeline/observability.js.map +1 -0
- package/dist/pipeline/pipeline.js +30 -0
- package/dist/pipeline/pipeline.js.map +1 -0
- package/dist/pipeline/runtime.js +17 -0
- package/dist/pipeline/runtime.js.map +1 -0
- package/dist/pipeline/types.js +1 -0
- package/dist/pipeline/types.js.map +1 -0
- package/dist/retry.js +20 -0
- package/dist/retry.js.map +1 -0
- package/dist/schema/index.js +1 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/schema/zod-schema.js +7 -0
- package/dist/schema/zod-schema.js.map +1 -0
- package/dist/skills/index.js +41 -12
- package/dist/skills/instructions.js +7 -0
- package/dist/skills/instructions.js.map +1 -0
- package/dist/skills/load.js +39 -0
- package/dist/skills/load.js.map +1 -0
- package/dist/skills/local.js +9 -0
- package/dist/skills/local.js.map +1 -0
- package/dist/skills/tools.js +37 -0
- package/dist/skills/tools.js.map +1 -0
- package/dist/skills/types.js +7 -0
- package/dist/skills/types.js.map +1 -0
- package/dist/speech-generation/generate-speech.js +11 -0
- package/dist/speech-generation/generate-speech.js.map +1 -0
- package/dist/speech-generation/index.js +7 -4
- package/dist/speech-generation/types.js +2 -0
- package/dist/speech-generation/types.js.map +1 -0
- package/dist/streaming/index.js +3 -37
- package/dist/streaming/index.js.map +1 -1
- package/dist/streaming/readable-stream.js +7 -0
- package/dist/streaming/readable-stream.js.map +1 -0
- package/dist/{text-CmjXxakS.d.ts → text-GbW4WYMg.d.ts} +1 -1
- package/dist/tool/create-tool.js +14 -0
- package/dist/tool/create-tool.js.map +1 -0
- package/dist/tool/dynamic-tools.js +35 -0
- package/dist/tool/dynamic-tools.js.map +1 -0
- package/dist/tool/errors.js +11 -0
- package/dist/tool/errors.js.map +1 -0
- package/dist/tool/index.d.ts +3 -2
- package/dist/tool/index.js +41 -15
- package/dist/tool/middleware.js +7 -0
- package/dist/tool/middleware.js.map +1 -0
- package/dist/tool/question-tool.js +17 -0
- package/dist/tool/question-tool.js.map +1 -0
- package/dist/tool/skill-tool-marker.js +9 -0
- package/dist/tool/skill-tool-marker.js.map +1 -0
- package/dist/tool/think-tool.js +15 -0
- package/dist/tool/think-tool.js.map +1 -0
- package/dist/tool/tool.js +17 -0
- package/dist/tool/tool.js.map +1 -0
- package/dist/transcription/index.js +7 -4
- package/dist/transcription/transcribe.js +11 -0
- package/dist/transcription/transcribe.js.map +1 -0
- package/dist/transcription/types.js +2 -0
- package/dist/transcription/types.js.map +1 -0
- package/dist/{types-h0EL6Xn0.d.ts → types-Bqw0AuFl.d.ts} +6 -2
- package/dist/vector-store/filter.js +9 -0
- package/dist/vector-store/filter.js.map +1 -0
- package/dist/vector-store/index.js +31 -11
- package/dist/vector-store/ingest.js +19 -0
- package/dist/vector-store/ingest.js.map +1 -0
- package/dist/vector-store/lsh.js +7 -0
- package/dist/vector-store/lsh.js.map +1 -0
- package/dist/vector-store/retrieve.js +15 -0
- package/dist/vector-store/retrieve.js.map +1 -0
- package/dist/vector-store/types.js +1 -0
- package/dist/vector-store/types.js.map +1 -0
- package/package.json +2 -2
- package/dist/chunk-2QZJTG2E.js.map +0 -1
- package/dist/chunk-3RWESPUG.js.map +0 -1
- package/dist/chunk-4UQALF5Y.js.map +0 -1
- package/dist/chunk-AZB6N7P4.js +0 -320
- package/dist/chunk-AZB6N7P4.js.map +0 -1
- package/dist/chunk-JLJMVRRE.js.map +0 -1
- package/dist/chunk-K5L7R7XM.js.map +0 -1
- package/dist/chunk-OI3LSMJG.js +0 -1545
- package/dist/chunk-OI3LSMJG.js.map +0 -1
- package/dist/chunk-QGX73TSQ.js.map +0 -1
- package/dist/chunk-XC3LVC4K.js +0 -753
- package/dist/chunk-XC3LVC4K.js.map +0 -1
- package/dist/chunk-XEVOC433.js.map +0 -1
- package/dist/chunk-XSV5C4R5.js +0 -400
- package/dist/chunk-XSV5C4R5.js.map +0 -1
- package/dist/chunk-XU54PLSD.js +0 -4786
- package/dist/chunk-XU54PLSD.js.map +0 -1
- package/dist/middleware-mY_lpjDp.d.ts +0 -59
- package/dist/type-utils-CtHVDRn_.d.ts +0 -6
- /package/dist/{chunk-YK4WAAS4.js.map → chunk-2NLINXRF.js.map} +0 -0
- /package/dist/{chunk-SPD4XVR7.js.map → chunk-2XSMGVBG.js.map} +0 -0
- /package/dist/{chunk-3XQGVDU5.js.map → chunk-4C7AXYOM.js.map} +0 -0
- /package/dist/{chunk-IZNOP6JG.js.map → chunk-4FIVU53H.js.map} +0 -0
- /package/dist/{chunk-7JLAIN6E.js.map → chunk-4ONUNWGC.js.map} +0 -0
- /package/dist/{chunk-KSKST3KP.js.map → chunk-H3H74RWJ.js.map} +0 -0
- /package/dist/{chunk-OJBFDBLG.js.map → chunk-LBYJPMHC.js.map} +0 -0
- /package/dist/{chunk-J6LVLV6P.js.map → chunk-PLDJCCVL.js.map} +0 -0
- /package/dist/{chunk-AHLKV6KP.js.map → chunk-WN6AVBO4.js.map} +0 -0
- /package/dist/{chunk-Q5BCNYED.js.map → chunk-XJRNBTIV.js.map} +0 -0
package/dist/chunk-XU54PLSD.js
DELETED
|
@@ -1,4786 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
assertAgentInteractionResponse,
|
|
3
|
-
parseAgentContinuation,
|
|
4
|
-
parseAgentInteractionResponse,
|
|
5
|
-
parseAgentQuestionPrompts
|
|
6
|
-
} from "./chunk-OJBFDBLG.js";
|
|
7
|
-
import {
|
|
8
|
-
isMcpTool
|
|
9
|
-
} from "./chunk-J6LVLV6P.js";
|
|
10
|
-
import {
|
|
11
|
-
MemoryCompactionConflictError,
|
|
12
|
-
MemoryCompactionError,
|
|
13
|
-
createMemoryCompactionSummary,
|
|
14
|
-
cumulativeCompactedMessageCount,
|
|
15
|
-
resolveMemoryOptions
|
|
16
|
-
} from "./chunk-JLJMVRRE.js";
|
|
17
|
-
import {
|
|
18
|
-
startAgentRunObservers
|
|
19
|
-
} from "./chunk-Q5BCNYED.js";
|
|
20
|
-
import {
|
|
21
|
-
isSkillTool
|
|
22
|
-
} from "./chunk-YK4WAAS4.js";
|
|
23
|
-
import {
|
|
24
|
-
isQuestionTool,
|
|
25
|
-
isToolIndex
|
|
26
|
-
} from "./chunk-2QZJTG2E.js";
|
|
27
|
-
import {
|
|
28
|
-
ToolNotFoundError,
|
|
29
|
-
ToolOutput,
|
|
30
|
-
assertFiniteMinScore,
|
|
31
|
-
assertPositiveSearchLimit,
|
|
32
|
-
assertToolApprovalRequirement,
|
|
33
|
-
createTool,
|
|
34
|
-
normalizeToolResultOutput,
|
|
35
|
-
parseToolArgs,
|
|
36
|
-
prepareToolCall,
|
|
37
|
-
prepareToolCallFromInput,
|
|
38
|
-
retrieveDocuments,
|
|
39
|
-
toolMayRequireApproval,
|
|
40
|
-
toolResultContentToText
|
|
41
|
-
} from "./chunk-XC3LVC4K.js";
|
|
42
|
-
import {
|
|
43
|
-
AgentRunBlockedError,
|
|
44
|
-
AgentRunCancelledError,
|
|
45
|
-
AgentStreamClosedError,
|
|
46
|
-
AgentStructuredOutputError,
|
|
47
|
-
AgentToolSuspensionError,
|
|
48
|
-
MaxTurnsError
|
|
49
|
-
} from "./chunk-AHLKV6KP.js";
|
|
50
|
-
import {
|
|
51
|
-
mapWithConcurrency
|
|
52
|
-
} from "./chunk-IZNOP6JG.js";
|
|
53
|
-
import {
|
|
54
|
-
mergeCompletionControlValues
|
|
55
|
-
} from "./chunk-4UQALF5Y.js";
|
|
56
|
-
import {
|
|
57
|
-
CompletionStreamAccumulator,
|
|
58
|
-
Usage,
|
|
59
|
-
assertCompletionControlsSupported,
|
|
60
|
-
assertCompletionRequestSupported,
|
|
61
|
-
assertCompletionResponseIntegrity,
|
|
62
|
-
createCompletionRequest,
|
|
63
|
-
getAssistantGenerationMetadata,
|
|
64
|
-
isProviderTool,
|
|
65
|
-
isStreamingCompletionModel,
|
|
66
|
-
textFromAssistantContent
|
|
67
|
-
} from "./chunk-OI3LSMJG.js";
|
|
68
|
-
import {
|
|
69
|
-
assertJsonObject
|
|
70
|
-
} from "./chunk-7JLAIN6E.js";
|
|
71
|
-
import {
|
|
72
|
-
parseMessage,
|
|
73
|
-
parseMessages,
|
|
74
|
-
toProviderJsonSchema
|
|
75
|
-
} from "./chunk-QGX73TSQ.js";
|
|
76
|
-
import {
|
|
77
|
-
isJsonValue
|
|
78
|
-
} from "./chunk-3XQGVDU5.js";
|
|
79
|
-
import {
|
|
80
|
-
abortError,
|
|
81
|
-
completionProviderOutputErrorUsage,
|
|
82
|
-
resolveRetryOptions,
|
|
83
|
-
retryDelayMs,
|
|
84
|
-
retryErrorAttributes,
|
|
85
|
-
retryOptionsForFailure,
|
|
86
|
-
throwIfAborted,
|
|
87
|
-
waitForRetry
|
|
88
|
-
} from "./chunk-3RWESPUG.js";
|
|
89
|
-
import {
|
|
90
|
-
appendGuardrailPolicies,
|
|
91
|
-
hasEnforcedOutputGuardrails,
|
|
92
|
-
runInputGuardrails,
|
|
93
|
-
runOutputGuardrails
|
|
94
|
-
} from "./chunk-AZB6N7P4.js";
|
|
95
|
-
|
|
96
|
-
// src/agent/tool-state.ts
|
|
97
|
-
var agentToolStates = /* @__PURE__ */ new WeakMap();
|
|
98
|
-
function registerAgentToolState(agent, publicState, toolsByName) {
|
|
99
|
-
agentToolStates.set(agent, { publicState, toolsByName });
|
|
100
|
-
}
|
|
101
|
-
function getAgentToolState(agent) {
|
|
102
|
-
return getStoredAgentToolState(agent).publicState;
|
|
103
|
-
}
|
|
104
|
-
function getRegisteredAgentTool(agent, toolName) {
|
|
105
|
-
return getStoredAgentToolState(agent).toolsByName.get(toolName);
|
|
106
|
-
}
|
|
107
|
-
function getStoredAgentToolState(agent) {
|
|
108
|
-
const state = agentToolStates.get(agent);
|
|
109
|
-
if (state === void 0) {
|
|
110
|
-
throw new TypeError("Agent tool state is unavailable.");
|
|
111
|
-
}
|
|
112
|
-
return state;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// src/hooks/control.ts
|
|
116
|
-
function createHook(hook) {
|
|
117
|
-
return hook;
|
|
118
|
-
}
|
|
119
|
-
function cancelRun(reason) {
|
|
120
|
-
return { type: "terminate", reason };
|
|
121
|
-
}
|
|
122
|
-
function skipTool(reason) {
|
|
123
|
-
return { type: "skip", reason };
|
|
124
|
-
}
|
|
125
|
-
function requestToolApproval(options = {}) {
|
|
126
|
-
const action = {
|
|
127
|
-
type: "approval_request"
|
|
128
|
-
};
|
|
129
|
-
if (options.reason !== void 0) {
|
|
130
|
-
action.reason = options.reason;
|
|
131
|
-
}
|
|
132
|
-
if (options.rejectMessage !== void 0) {
|
|
133
|
-
action.rejectMessage = options.rejectMessage;
|
|
134
|
-
}
|
|
135
|
-
return action;
|
|
136
|
-
}
|
|
137
|
-
var runControl = {
|
|
138
|
-
continue() {
|
|
139
|
-
return { type: "continue" };
|
|
140
|
-
},
|
|
141
|
-
cancel(reason) {
|
|
142
|
-
return cancelRun(reason);
|
|
143
|
-
}
|
|
144
|
-
};
|
|
145
|
-
var toolCallControl = {
|
|
146
|
-
run() {
|
|
147
|
-
return { type: "continue" };
|
|
148
|
-
},
|
|
149
|
-
skip(reason) {
|
|
150
|
-
return skipTool(reason);
|
|
151
|
-
},
|
|
152
|
-
cancel(reason) {
|
|
153
|
-
return { type: "terminate", reason };
|
|
154
|
-
},
|
|
155
|
-
requestApproval(options) {
|
|
156
|
-
return requestToolApproval(options);
|
|
157
|
-
}
|
|
158
|
-
};
|
|
159
|
-
|
|
160
|
-
// src/agent/vector-context.ts
|
|
161
|
-
function createVectorContext(options) {
|
|
162
|
-
const topK = assertPositiveSearchLimit(options.topK);
|
|
163
|
-
const minScore = assertFiniteMinScore(options.minScore);
|
|
164
|
-
let context = {
|
|
165
|
-
...options,
|
|
166
|
-
topK,
|
|
167
|
-
kind: "vector-context"
|
|
168
|
-
};
|
|
169
|
-
if (minScore !== void 0) {
|
|
170
|
-
context = { ...context, minScore };
|
|
171
|
-
}
|
|
172
|
-
return Object.freeze(context);
|
|
173
|
-
}
|
|
174
|
-
function isVectorContext(value) {
|
|
175
|
-
if (typeof value !== "object" || value === null) return false;
|
|
176
|
-
const candidate = value;
|
|
177
|
-
if (candidate.kind !== "vector-context" || typeof candidate.store?.search !== "function") {
|
|
178
|
-
return false;
|
|
179
|
-
}
|
|
180
|
-
return candidate.model !== void 0 || candidate.models?.dense !== void 0 && candidate.models.sparse !== void 0;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// src/internal/agent-runtime/run-options.ts
|
|
184
|
-
var internalAgentRunOptions = /* @__PURE__ */ Symbol("internalAgentRunOptions");
|
|
185
|
-
function withInternalAgentRunOptions(options, internal) {
|
|
186
|
-
return {
|
|
187
|
-
...options,
|
|
188
|
-
[internalAgentRunOptions]: internal
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
function getInternalAgentRunOptions(options) {
|
|
192
|
-
return options[internalAgentRunOptions];
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// src/agent/lifecycle.ts
|
|
196
|
-
function composeAgentLifecycle(first, second) {
|
|
197
|
-
if (first === void 0) return second;
|
|
198
|
-
if (second === void 0) return first;
|
|
199
|
-
return {
|
|
200
|
-
async onStart(event) {
|
|
201
|
-
await first.onStart?.(lifecycleSnapshot(event));
|
|
202
|
-
await second.onStart?.(lifecycleSnapshot(event));
|
|
203
|
-
},
|
|
204
|
-
async onStepFinish(event) {
|
|
205
|
-
await first.onStepFinish?.(lifecycleSnapshot(event));
|
|
206
|
-
await second.onStepFinish?.(lifecycleSnapshot(event));
|
|
207
|
-
},
|
|
208
|
-
async onToolStart(event) {
|
|
209
|
-
await first.onToolStart?.(lifecycleSnapshot(event));
|
|
210
|
-
await second.onToolStart?.(lifecycleSnapshot(event));
|
|
211
|
-
},
|
|
212
|
-
async onToolFinish(event) {
|
|
213
|
-
await first.onToolFinish?.(lifecycleSnapshot(event));
|
|
214
|
-
await second.onToolFinish?.(lifecycleSnapshot(event));
|
|
215
|
-
},
|
|
216
|
-
async onFinish(event) {
|
|
217
|
-
await first.onFinish?.(lifecycleSnapshot(event));
|
|
218
|
-
await second.onFinish?.(lifecycleSnapshot(event));
|
|
219
|
-
},
|
|
220
|
-
async onError(event) {
|
|
221
|
-
await first.onError?.(lifecycleSnapshot(event));
|
|
222
|
-
await second.onError?.(lifecycleSnapshot(event));
|
|
223
|
-
}
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
function lifecycleSnapshot(value) {
|
|
227
|
-
try {
|
|
228
|
-
return globalThis.structuredClone(value);
|
|
229
|
-
} catch {
|
|
230
|
-
return cloneLifecycleFallback(value, /* @__PURE__ */ new WeakMap());
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
function cloneLifecycleFallback(value, seen) {
|
|
234
|
-
if (typeof value !== "object" || value === null) {
|
|
235
|
-
return value;
|
|
236
|
-
}
|
|
237
|
-
const existing = seen.get(value);
|
|
238
|
-
if (existing !== void 0) {
|
|
239
|
-
return existing;
|
|
240
|
-
}
|
|
241
|
-
if (Array.isArray(value)) {
|
|
242
|
-
const clone2 = [];
|
|
243
|
-
seen.set(value, clone2);
|
|
244
|
-
clone2.push(...value.map((item) => cloneLifecycleFallback(item, seen)));
|
|
245
|
-
return clone2;
|
|
246
|
-
}
|
|
247
|
-
if (Object.getPrototypeOf(value) !== Object.prototype) {
|
|
248
|
-
return value;
|
|
249
|
-
}
|
|
250
|
-
const clone = {};
|
|
251
|
-
seen.set(value, clone);
|
|
252
|
-
for (const [key, item] of Object.entries(value)) {
|
|
253
|
-
clone[key] = cloneLifecycleFallback(item, seen);
|
|
254
|
-
}
|
|
255
|
-
return clone;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// src/agent/output-schema.ts
|
|
259
|
-
var providerOutputSchemas = /* @__PURE__ */ new WeakMap();
|
|
260
|
-
function registerAgentProviderOutputSchema(agent, schema) {
|
|
261
|
-
if (schema !== void 0) {
|
|
262
|
-
providerOutputSchemas.set(agent, toProviderJsonSchema(schema));
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
function getAgentProviderOutputSchema(agent) {
|
|
266
|
-
return providerOutputSchemas.get(agent);
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
// src/internal/async-queue.ts
|
|
270
|
-
function createAsyncQueue() {
|
|
271
|
-
const values = [];
|
|
272
|
-
const waiters = [];
|
|
273
|
-
let closed = false;
|
|
274
|
-
let error;
|
|
275
|
-
function flush() {
|
|
276
|
-
while (waiters.length > 0 && values.length > 0) {
|
|
277
|
-
const waiter = waiters.shift();
|
|
278
|
-
const value = values.shift();
|
|
279
|
-
if (waiter !== void 0) {
|
|
280
|
-
waiter.resolve({ value, done: false });
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
if (values.length > 0 || waiters.length === 0 || !closed) {
|
|
284
|
-
return;
|
|
285
|
-
}
|
|
286
|
-
while (waiters.length > 0) {
|
|
287
|
-
const waiter = waiters.shift();
|
|
288
|
-
if (waiter === void 0) {
|
|
289
|
-
continue;
|
|
290
|
-
}
|
|
291
|
-
if (error !== void 0) {
|
|
292
|
-
waiter.reject(error);
|
|
293
|
-
} else {
|
|
294
|
-
waiter.resolve({ value: void 0, done: true });
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
return {
|
|
299
|
-
enqueue(value) {
|
|
300
|
-
if (closed) {
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
values.push(value);
|
|
304
|
-
flush();
|
|
305
|
-
},
|
|
306
|
-
close() {
|
|
307
|
-
closed = true;
|
|
308
|
-
flush();
|
|
309
|
-
},
|
|
310
|
-
throw(thrown) {
|
|
311
|
-
closed = true;
|
|
312
|
-
error = thrown;
|
|
313
|
-
flush();
|
|
314
|
-
},
|
|
315
|
-
[Symbol.asyncIterator]() {
|
|
316
|
-
return {
|
|
317
|
-
next() {
|
|
318
|
-
if (values.length > 0) {
|
|
319
|
-
const value = values.shift();
|
|
320
|
-
return Promise.resolve({ value, done: false });
|
|
321
|
-
}
|
|
322
|
-
if (error !== void 0) {
|
|
323
|
-
return Promise.reject(error);
|
|
324
|
-
}
|
|
325
|
-
if (closed) {
|
|
326
|
-
return Promise.resolve({ value: void 0, done: true });
|
|
327
|
-
}
|
|
328
|
-
return new Promise((resolve, reject) => {
|
|
329
|
-
waiters.push({ resolve, reject });
|
|
330
|
-
});
|
|
331
|
-
}
|
|
332
|
-
};
|
|
333
|
-
}
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
// src/internal/rag-text.ts
|
|
338
|
-
function extractRagText(message) {
|
|
339
|
-
if (message.role === "user") {
|
|
340
|
-
if (typeof message.content === "string") {
|
|
341
|
-
return message.content;
|
|
342
|
-
}
|
|
343
|
-
return message.content.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n");
|
|
344
|
-
}
|
|
345
|
-
if (message.role === "tool") {
|
|
346
|
-
return message.content.flatMap((item) => {
|
|
347
|
-
if (item.type !== "tool-result") {
|
|
348
|
-
return [];
|
|
349
|
-
}
|
|
350
|
-
const output = item.output;
|
|
351
|
-
if (output.type === "text" || output.type === "error-text") {
|
|
352
|
-
return [output.value];
|
|
353
|
-
}
|
|
354
|
-
if (output.type === "content") {
|
|
355
|
-
return output.value.flatMap((part) => part.type === "text" ? [part.text] : []);
|
|
356
|
-
}
|
|
357
|
-
return [];
|
|
358
|
-
}).join("\n");
|
|
359
|
-
}
|
|
360
|
-
return void 0;
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
// src/internal/agent-runtime/continuation-state.ts
|
|
364
|
-
function serializeContinuationState(state) {
|
|
365
|
-
const value = structuredClone(state);
|
|
366
|
-
if (!isJsonValue(value) || Array.isArray(value) || value === null) {
|
|
367
|
-
throw new TypeError("Agent continuation state must be strict JSON.");
|
|
368
|
-
}
|
|
369
|
-
return value;
|
|
370
|
-
}
|
|
371
|
-
function parseContinuationState(value, interaction) {
|
|
372
|
-
requireOnlyKeys(value, [
|
|
373
|
-
"kind",
|
|
374
|
-
"history",
|
|
375
|
-
"messages",
|
|
376
|
-
"pending",
|
|
377
|
-
"remainingToolCalls",
|
|
378
|
-
"steering",
|
|
379
|
-
"memoryScope"
|
|
380
|
-
]);
|
|
381
|
-
if (value.kind !== "anvia.agent-continuation") {
|
|
382
|
-
throw new TypeError("Agent continuation has an unsupported internal state.");
|
|
383
|
-
}
|
|
384
|
-
const history = parseMessages(value.history);
|
|
385
|
-
const messages = parseMessages(value.messages);
|
|
386
|
-
const pending = parsePending(value.pending);
|
|
387
|
-
const remainingToolCalls = parseToolCalls(value.remainingToolCalls);
|
|
388
|
-
const steering = parseSteering(value.steering);
|
|
389
|
-
if (pending.toolCall.toolCallId !== interaction.toolCallId || pending.toolCall.toolName !== interaction.toolName || pending.toolCall.callId !== interaction.callId || pending.internalCallId !== interaction.internalCallId) {
|
|
390
|
-
throw new TypeError("Agent continuation interaction does not match its pending tool call.");
|
|
391
|
-
}
|
|
392
|
-
if (interaction.type === "tool-approval" && !jsonEqual(interaction.input, pending.input)) {
|
|
393
|
-
throw new TypeError("Agent continuation approval input does not match its pending tool input.");
|
|
394
|
-
}
|
|
395
|
-
if (interaction.type === "tool-question") {
|
|
396
|
-
const questions = object(pending.input) && "questions" in pending.input ? parseAgentQuestionPrompts(pending.input.questions) : void 0;
|
|
397
|
-
if (questions === void 0 || !jsonEqual(interaction.questions, questions)) {
|
|
398
|
-
throw new TypeError(
|
|
399
|
-
"Agent continuation questions do not match its pending question tool input."
|
|
400
|
-
);
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
const state = {
|
|
404
|
-
kind: "anvia.agent-continuation",
|
|
405
|
-
history,
|
|
406
|
-
messages,
|
|
407
|
-
pending,
|
|
408
|
-
remainingToolCalls,
|
|
409
|
-
steering
|
|
410
|
-
};
|
|
411
|
-
if (value.memoryScope !== void 0) {
|
|
412
|
-
state.memoryScope = parseOptionalJsonObject(value.memoryScope, "memoryScope");
|
|
413
|
-
}
|
|
414
|
-
return state;
|
|
415
|
-
}
|
|
416
|
-
function questionResult(answers) {
|
|
417
|
-
return { type: "json", value: { answers: structuredClone([...answers]) } };
|
|
418
|
-
}
|
|
419
|
-
function parsePending(value) {
|
|
420
|
-
if (!object(value)) throw new TypeError("Agent continuation pending state is invalid.");
|
|
421
|
-
const [toolCall] = parseToolCalls([value.toolCall]);
|
|
422
|
-
if (toolCall === void 0) throw new TypeError("Agent continuation pending tool is missing.");
|
|
423
|
-
if (typeof value.effectiveArgs !== "string" || typeof value.internalCallId !== "string") {
|
|
424
|
-
throw new TypeError("Agent continuation pending execution metadata is invalid.");
|
|
425
|
-
}
|
|
426
|
-
const pending = {
|
|
427
|
-
toolCall,
|
|
428
|
-
effectiveArgs: value.effectiveArgs,
|
|
429
|
-
input: parseJsonValue(value.input, "pending input"),
|
|
430
|
-
internalCallId: value.internalCallId
|
|
431
|
-
};
|
|
432
|
-
if (typeof value.rejectMessage === "string") {
|
|
433
|
-
pending.rejectMessage = value.rejectMessage;
|
|
434
|
-
}
|
|
435
|
-
return pending;
|
|
436
|
-
}
|
|
437
|
-
function parseJsonValue(value, name) {
|
|
438
|
-
if (!isJsonValue(value)) {
|
|
439
|
-
throw new TypeError(`Agent continuation ${name} is invalid.`);
|
|
440
|
-
}
|
|
441
|
-
return structuredClone(value);
|
|
442
|
-
}
|
|
443
|
-
function parseToolCalls(value) {
|
|
444
|
-
if (!Array.isArray(value)) throw new TypeError("Agent continuation tool calls must be an array.");
|
|
445
|
-
const message = parseMessages([{ role: "assistant", content: value }])[0];
|
|
446
|
-
if (message?.role !== "assistant" || typeof message.content === "string") {
|
|
447
|
-
throw new TypeError("Agent continuation tool calls are invalid.");
|
|
448
|
-
}
|
|
449
|
-
if (!message.content.every((part) => part.type === "tool-call")) {
|
|
450
|
-
throw new TypeError("Agent continuation contains a non-tool-call part.");
|
|
451
|
-
}
|
|
452
|
-
return message.content;
|
|
453
|
-
}
|
|
454
|
-
function parseSteering(value) {
|
|
455
|
-
if (!Array.isArray(value)) throw new TypeError("Agent continuation steering state is invalid.");
|
|
456
|
-
return value.map((item) => {
|
|
457
|
-
if (!object(item) || typeof item.id !== "string") {
|
|
458
|
-
throw new TypeError("Agent continuation steering entry is invalid.");
|
|
459
|
-
}
|
|
460
|
-
return { id: item.id, messages: parseMessages(item.messages) };
|
|
461
|
-
});
|
|
462
|
-
}
|
|
463
|
-
function parseOptionalJsonObject(value, name) {
|
|
464
|
-
if (value === void 0) return void 0;
|
|
465
|
-
if (!object(value) || !isJsonValue(value)) {
|
|
466
|
-
throw new TypeError(`Agent continuation ${name} is invalid.`);
|
|
467
|
-
}
|
|
468
|
-
return structuredClone(value);
|
|
469
|
-
}
|
|
470
|
-
function object(value) {
|
|
471
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
472
|
-
}
|
|
473
|
-
function requireOnlyKeys(value, allowed) {
|
|
474
|
-
const allowedKeys = new Set(allowed);
|
|
475
|
-
const unknown = Object.keys(value).find((key) => !allowedKeys.has(key));
|
|
476
|
-
if (unknown !== void 0) {
|
|
477
|
-
throw new TypeError(`Agent continuation state contains unknown key "${unknown}".`);
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
function jsonEqual(left, right) {
|
|
481
|
-
if (Object.is(left, right)) return true;
|
|
482
|
-
if (Array.isArray(left)) {
|
|
483
|
-
return Array.isArray(right) && left.length === right.length && left.every((value, index) => jsonEqual(value, right[index]));
|
|
484
|
-
}
|
|
485
|
-
if (object(left)) {
|
|
486
|
-
if (!object(right)) return false;
|
|
487
|
-
const keys = Object.keys(left);
|
|
488
|
-
return keys.length === Object.keys(right).length && keys.every((key) => key in right && jsonEqual(left[key], right[key]));
|
|
489
|
-
}
|
|
490
|
-
return false;
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
// src/internal/agent-runtime/interaction-suspension.ts
|
|
494
|
-
var AgentInteractionSignal = class extends Error {
|
|
495
|
-
constructor(interaction, rejectMessage) {
|
|
496
|
-
super("Agent execution requires a human interaction.");
|
|
497
|
-
this.interaction = interaction;
|
|
498
|
-
this.rejectMessage = rejectMessage;
|
|
499
|
-
this.name = "AgentInteractionSignal";
|
|
500
|
-
}
|
|
501
|
-
interaction;
|
|
502
|
-
rejectMessage;
|
|
503
|
-
};
|
|
504
|
-
var ToolExecutionSuspension = class extends Error {
|
|
505
|
-
constructor(interaction, pending) {
|
|
506
|
-
super("Tool execution suspended for human interaction.");
|
|
507
|
-
this.interaction = interaction;
|
|
508
|
-
this.pending = pending;
|
|
509
|
-
this.name = "ToolExecutionSuspension";
|
|
510
|
-
}
|
|
511
|
-
interaction;
|
|
512
|
-
pending;
|
|
513
|
-
completedResults = [];
|
|
514
|
-
remainingToolCalls = [];
|
|
515
|
-
};
|
|
516
|
-
function approvalInteraction(request) {
|
|
517
|
-
if (request.toolCallId === void 0) {
|
|
518
|
-
throw new TypeError("Tool approval requires a canonical toolCallId.");
|
|
519
|
-
}
|
|
520
|
-
if (!isJsonValue(request.args)) {
|
|
521
|
-
throw new TypeError("Tool approval input must be strict JSON.");
|
|
522
|
-
}
|
|
523
|
-
let interaction = {
|
|
524
|
-
type: "tool-approval",
|
|
525
|
-
id: request.id,
|
|
526
|
-
toolName: request.toolName,
|
|
527
|
-
toolCallId: request.toolCallId,
|
|
528
|
-
internalCallId: request.internalCallId,
|
|
529
|
-
input: request.args
|
|
530
|
-
};
|
|
531
|
-
if (request.callId !== void 0) interaction = { ...interaction, callId: request.callId };
|
|
532
|
-
if (request.reason !== void 0) interaction = { ...interaction, reason: request.reason };
|
|
533
|
-
return interaction;
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
// src/internal/agent-runtime/memory.ts
|
|
537
|
-
var AgentRunMemory = class {
|
|
538
|
-
constructor(agent, memoryScope, initialHistory) {
|
|
539
|
-
this.agent = agent;
|
|
540
|
-
this.memoryScope = memoryScope;
|
|
541
|
-
this.initialHistory = initialHistory;
|
|
542
|
-
}
|
|
543
|
-
agent;
|
|
544
|
-
memoryScope;
|
|
545
|
-
initialHistory;
|
|
546
|
-
memoryPolicy() {
|
|
547
|
-
return this.memory()?.savePolicy;
|
|
548
|
-
}
|
|
549
|
-
pendingTurnMessages(newMessages) {
|
|
550
|
-
return this.memoryPolicy() === "turn" ? [...newMessages] : [];
|
|
551
|
-
}
|
|
552
|
-
async prepareHistory(runId, incomingMessages, abortSignal) {
|
|
553
|
-
const memory = this.memory();
|
|
554
|
-
if (memory === void 0 || this.memoryScope === void 0) {
|
|
555
|
-
return {
|
|
556
|
-
history: this.initialHistory,
|
|
557
|
-
usage: Usage.empty()
|
|
558
|
-
};
|
|
559
|
-
}
|
|
560
|
-
const preparation = await this.prepareStoredHistory(
|
|
561
|
-
memory,
|
|
562
|
-
runId,
|
|
563
|
-
incomingMessages,
|
|
564
|
-
abortSignal
|
|
565
|
-
);
|
|
566
|
-
const memoryHistory = preparation.history;
|
|
567
|
-
const chatHistory = [...memoryHistory, ...this.initialHistory];
|
|
568
|
-
return {
|
|
569
|
-
...preparation,
|
|
570
|
-
history: chatHistory
|
|
571
|
-
};
|
|
572
|
-
}
|
|
573
|
-
async compact(runId, abortSignal) {
|
|
574
|
-
const memory = this.memory();
|
|
575
|
-
const scope = this.memoryScope;
|
|
576
|
-
if (memory === void 0 || scope === void 0) {
|
|
577
|
-
throw new TypeError("Manual memory compaction requires an Agent with configured memory.");
|
|
578
|
-
}
|
|
579
|
-
if (memory.compaction === void 0 || memory.store.compaction === void 0) {
|
|
580
|
-
throw new TypeError("Manual memory compaction requires a configured compaction policy.");
|
|
581
|
-
}
|
|
582
|
-
const preparation = await this.prepareStoredHistory(memory, runId, [], abortSignal, true);
|
|
583
|
-
if (preparation.compaction !== void 0) {
|
|
584
|
-
return { type: "compacted", ...preparation.compaction };
|
|
585
|
-
}
|
|
586
|
-
return {
|
|
587
|
-
type: "skipped",
|
|
588
|
-
reason: "nothing_to_compact",
|
|
589
|
-
originalMessageCount: preparation.history.length,
|
|
590
|
-
originalTokenCount: preparation.originalTokenCount ?? await countTokens(memory.compaction.tokenCounter, preparation.history)
|
|
591
|
-
};
|
|
592
|
-
}
|
|
593
|
-
async commitAcceptedInput(runId, messages) {
|
|
594
|
-
const memory = this.memory();
|
|
595
|
-
if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "message" || messages.length === 0) {
|
|
596
|
-
return;
|
|
597
|
-
}
|
|
598
|
-
await memory.store.append({
|
|
599
|
-
scope: this.memoryScope,
|
|
600
|
-
runId,
|
|
601
|
-
turn: 1,
|
|
602
|
-
messages
|
|
603
|
-
});
|
|
604
|
-
}
|
|
605
|
-
async commitMessages(runId, turn, messages, pendingTurnMessages) {
|
|
606
|
-
const memory = this.memory();
|
|
607
|
-
if (memory === void 0 || this.memoryScope === void 0 || messages.length === 0) {
|
|
608
|
-
return;
|
|
609
|
-
}
|
|
610
|
-
if (memory.savePolicy === "message") {
|
|
611
|
-
await memory.store.append({
|
|
612
|
-
scope: this.memoryScope,
|
|
613
|
-
runId,
|
|
614
|
-
turn,
|
|
615
|
-
messages
|
|
616
|
-
});
|
|
617
|
-
} else if (memory.savePolicy === "turn") {
|
|
618
|
-
pendingTurnMessages.push(...messages);
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
async commitCompletedTurn(runId, turn, pendingTurnMessages) {
|
|
622
|
-
const memory = this.memory();
|
|
623
|
-
if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "turn" || pendingTurnMessages.length === 0) {
|
|
624
|
-
return;
|
|
625
|
-
}
|
|
626
|
-
await memory.store.append({
|
|
627
|
-
scope: this.memoryScope,
|
|
628
|
-
runId,
|
|
629
|
-
turn,
|
|
630
|
-
messages: [...pendingTurnMessages]
|
|
631
|
-
});
|
|
632
|
-
pendingTurnMessages.length = 0;
|
|
633
|
-
}
|
|
634
|
-
async commitCompletedRun(runId, turn, newMessages, pendingTurnMessages) {
|
|
635
|
-
await this.commitCompletedTurn(runId, turn, pendingTurnMessages);
|
|
636
|
-
const memory = this.memory();
|
|
637
|
-
if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "run") {
|
|
638
|
-
return;
|
|
639
|
-
}
|
|
640
|
-
await memory.store.append({
|
|
641
|
-
scope: this.memoryScope,
|
|
642
|
-
runId,
|
|
643
|
-
turn,
|
|
644
|
-
messages: [...newMessages]
|
|
645
|
-
});
|
|
646
|
-
}
|
|
647
|
-
async recordError(runId, error, newMessages) {
|
|
648
|
-
const memory = this.memory();
|
|
649
|
-
if (memory === void 0 || this.memoryScope === void 0) {
|
|
650
|
-
return;
|
|
651
|
-
}
|
|
652
|
-
await memory.store.recordError?.({
|
|
653
|
-
scope: this.memoryScope,
|
|
654
|
-
runId,
|
|
655
|
-
error,
|
|
656
|
-
messages: [...newMessages]
|
|
657
|
-
});
|
|
658
|
-
}
|
|
659
|
-
memory() {
|
|
660
|
-
return this.memoryScope === void 0 ? void 0 : this.agent.memory;
|
|
661
|
-
}
|
|
662
|
-
async prepareStoredHistory(memory, runId, incomingMessages, abortSignal, force = false) {
|
|
663
|
-
const scope = this.memoryScope;
|
|
664
|
-
if (scope === void 0) {
|
|
665
|
-
return { history: [], usage: Usage.empty() };
|
|
666
|
-
}
|
|
667
|
-
const options = memory.compaction;
|
|
668
|
-
const capability = memory.store.compaction;
|
|
669
|
-
if (options === void 0 || capability === void 0) {
|
|
670
|
-
return {
|
|
671
|
-
history: await memory.store.load({ scope }),
|
|
672
|
-
usage: Usage.empty()
|
|
673
|
-
};
|
|
674
|
-
}
|
|
675
|
-
let usage = Usage.empty();
|
|
676
|
-
const maxAttempts = options.conflictRetries === false ? 1 : options.conflictRetries.maxAttempts;
|
|
677
|
-
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
678
|
-
throwIfAborted(abortSignal);
|
|
679
|
-
const snapshot = await capability.snapshot({ scope });
|
|
680
|
-
throwIfAborted(abortSignal);
|
|
681
|
-
const selection = await selectCompactionPrefix(
|
|
682
|
-
snapshot.messages,
|
|
683
|
-
incomingMessages,
|
|
684
|
-
options.trigger.afterTokens,
|
|
685
|
-
options.retention.recentTokens,
|
|
686
|
-
options.tokenCounter,
|
|
687
|
-
force
|
|
688
|
-
);
|
|
689
|
-
throwIfAborted(abortSignal);
|
|
690
|
-
const compactedMessageCount = selection.compactedMessageCount;
|
|
691
|
-
if (compactedMessageCount === 0) {
|
|
692
|
-
return {
|
|
693
|
-
history: snapshot.messages,
|
|
694
|
-
usage,
|
|
695
|
-
originalTokenCount: selection.originalTokenCount
|
|
696
|
-
};
|
|
697
|
-
}
|
|
698
|
-
const prefix = snapshot.messages.slice(0, compactedMessageCount);
|
|
699
|
-
let result;
|
|
700
|
-
try {
|
|
701
|
-
result = await options.compactor({
|
|
702
|
-
scope,
|
|
703
|
-
messages: prefix,
|
|
704
|
-
abortSignal
|
|
705
|
-
});
|
|
706
|
-
} catch (error) {
|
|
707
|
-
throw remappedCompactorError(error, usage);
|
|
708
|
-
}
|
|
709
|
-
if (result.usage !== void 0) {
|
|
710
|
-
usage = Usage.add(usage, result.usage);
|
|
711
|
-
}
|
|
712
|
-
if (typeof result?.summary !== "string") {
|
|
713
|
-
throw new MemoryCompactionError("Memory compactor must return a summary string.", {
|
|
714
|
-
usage
|
|
715
|
-
});
|
|
716
|
-
}
|
|
717
|
-
const summaryText = result.summary.trim();
|
|
718
|
-
if (summaryText.length === 0) {
|
|
719
|
-
throw new MemoryCompactionError("Memory compactor returned an empty summary.", {
|
|
720
|
-
usage
|
|
721
|
-
});
|
|
722
|
-
}
|
|
723
|
-
const summary = createMemoryCompactionSummary(
|
|
724
|
-
summaryText,
|
|
725
|
-
cumulativeCompactedMessageCount(prefix)
|
|
726
|
-
);
|
|
727
|
-
const retained = snapshot.messages.slice(compactedMessageCount);
|
|
728
|
-
let resultTokenCount;
|
|
729
|
-
try {
|
|
730
|
-
resultTokenCount = await countTokens(options.tokenCounter, [summary, ...retained]);
|
|
731
|
-
} catch (error) {
|
|
732
|
-
throw remappedCompactorError(error, usage);
|
|
733
|
-
}
|
|
734
|
-
throwIfAborted(abortSignal);
|
|
735
|
-
let replacement;
|
|
736
|
-
try {
|
|
737
|
-
replacement = await capability.replacePrefix({
|
|
738
|
-
scope,
|
|
739
|
-
revision: snapshot.revision,
|
|
740
|
-
messageCount: compactedMessageCount,
|
|
741
|
-
replacement: summary,
|
|
742
|
-
runId: `memory-compaction:${runId}:${attempt}`
|
|
743
|
-
});
|
|
744
|
-
} catch (error) {
|
|
745
|
-
throw new MemoryCompactionError("Memory compaction prefix replacement failed.", {
|
|
746
|
-
cause: error,
|
|
747
|
-
usage
|
|
748
|
-
});
|
|
749
|
-
}
|
|
750
|
-
if (replacement.status === "committed") {
|
|
751
|
-
return {
|
|
752
|
-
history: [summary, ...retained],
|
|
753
|
-
usage,
|
|
754
|
-
compaction: {
|
|
755
|
-
originalMessageCount: snapshot.messages.length,
|
|
756
|
-
compactedMessageCount,
|
|
757
|
-
retainedMessageCount: retained.length,
|
|
758
|
-
originalTokenCount: selection.originalTokenCount,
|
|
759
|
-
compactedTokenCount: selection.compactedTokenCount,
|
|
760
|
-
retainedTokenCount: selection.retainedTokenCount,
|
|
761
|
-
resultTokenCount,
|
|
762
|
-
attempts: attempt,
|
|
763
|
-
usage
|
|
764
|
-
}
|
|
765
|
-
};
|
|
766
|
-
}
|
|
767
|
-
throwIfAborted(abortSignal);
|
|
768
|
-
}
|
|
769
|
-
throw new MemoryCompactionConflictError(maxAttempts, usage);
|
|
770
|
-
}
|
|
771
|
-
};
|
|
772
|
-
async function selectCompactionPrefix(messages, incomingMessages, afterTokens, recentTokens, tokenCounter, force) {
|
|
773
|
-
const originalTokenCount = await countTokens(tokenCounter, messages);
|
|
774
|
-
const incomingTokenCount = incomingMessages.length === 0 ? 0 : await countTokens(tokenCounter, incomingMessages);
|
|
775
|
-
const none = {
|
|
776
|
-
compactedMessageCount: 0,
|
|
777
|
-
originalTokenCount,
|
|
778
|
-
compactedTokenCount: 0,
|
|
779
|
-
retainedTokenCount: originalTokenCount
|
|
780
|
-
};
|
|
781
|
-
if (!force && originalTokenCount + incomingTokenCount <= afterTokens) {
|
|
782
|
-
return none;
|
|
783
|
-
}
|
|
784
|
-
const userMessageIndexes = messages.flatMap(
|
|
785
|
-
(message, index) => message.role === "user" ? [index] : []
|
|
786
|
-
);
|
|
787
|
-
if (userMessageIndexes.length <= 1) {
|
|
788
|
-
return none;
|
|
789
|
-
}
|
|
790
|
-
const tailTokenCounts = /* @__PURE__ */ new Map();
|
|
791
|
-
const countTail = async (messageIndex) => {
|
|
792
|
-
const cached = tailTokenCounts.get(messageIndex);
|
|
793
|
-
if (cached !== void 0) return cached;
|
|
794
|
-
const count = await countTokens(tokenCounter, messages.slice(messageIndex));
|
|
795
|
-
tailTokenCounts.set(messageIndex, count);
|
|
796
|
-
return count;
|
|
797
|
-
};
|
|
798
|
-
let lower = 0;
|
|
799
|
-
let upper = userMessageIndexes.length - 1;
|
|
800
|
-
let retainedBoundary = upper;
|
|
801
|
-
while (lower <= upper) {
|
|
802
|
-
const middle = Math.floor((lower + upper) / 2);
|
|
803
|
-
const candidate = userMessageIndexes[middle] ?? 0;
|
|
804
|
-
if (await countTail(candidate) <= recentTokens) {
|
|
805
|
-
retainedBoundary = middle;
|
|
806
|
-
upper = middle - 1;
|
|
807
|
-
} else {
|
|
808
|
-
lower = middle + 1;
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
const compactedMessageCount = userMessageIndexes[retainedBoundary] ?? 0;
|
|
812
|
-
if (compactedMessageCount === 0) {
|
|
813
|
-
return none;
|
|
814
|
-
}
|
|
815
|
-
const compactedTokenCount = await countTokens(
|
|
816
|
-
tokenCounter,
|
|
817
|
-
messages.slice(0, compactedMessageCount)
|
|
818
|
-
);
|
|
819
|
-
const retainedTokenCount = tailTokenCounts.get(compactedMessageCount) ?? await countTokens(tokenCounter, messages.slice(compactedMessageCount));
|
|
820
|
-
return {
|
|
821
|
-
compactedMessageCount,
|
|
822
|
-
originalTokenCount,
|
|
823
|
-
compactedTokenCount,
|
|
824
|
-
retainedTokenCount
|
|
825
|
-
};
|
|
826
|
-
}
|
|
827
|
-
async function countTokens(tokenCounter, messages) {
|
|
828
|
-
let count;
|
|
829
|
-
try {
|
|
830
|
-
count = await tokenCounter(messages);
|
|
831
|
-
} catch (error) {
|
|
832
|
-
throw new MemoryCompactionError("Memory token counter failed.", { cause: error });
|
|
833
|
-
}
|
|
834
|
-
if (!Number.isSafeInteger(count) || count < 0) {
|
|
835
|
-
throw new MemoryCompactionError("Memory token counter must return a nonnegative safe integer.");
|
|
836
|
-
}
|
|
837
|
-
return count;
|
|
838
|
-
}
|
|
839
|
-
function remappedCompactorError(error, usage) {
|
|
840
|
-
if (error instanceof MemoryCompactionError) {
|
|
841
|
-
const mergedUsage = error.usage === void 0 ? usage : isEmptyUsage(usage) ? error.usage : Usage.add(usage, error.usage);
|
|
842
|
-
if (mergedUsage === error.usage || error.usage === void 0 && isEmptyUsage(usage)) {
|
|
843
|
-
return error;
|
|
844
|
-
}
|
|
845
|
-
return new MemoryCompactionError(error.message, {
|
|
846
|
-
cause: error,
|
|
847
|
-
usage: mergedUsage
|
|
848
|
-
});
|
|
849
|
-
}
|
|
850
|
-
return new MemoryCompactionError("Memory compactor failed.", {
|
|
851
|
-
cause: error,
|
|
852
|
-
usage
|
|
853
|
-
});
|
|
854
|
-
}
|
|
855
|
-
function isEmptyUsage(usage) {
|
|
856
|
-
return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.totalTokens === 0 && usage.cachedInputTokens === 0 && usage.cacheCreationInputTokens === 0;
|
|
857
|
-
}
|
|
858
|
-
|
|
859
|
-
// src/internal/agent-runtime/memory-scope.ts
|
|
860
|
-
function normalizeMemoryScope(scope, owner = "Agent") {
|
|
861
|
-
if (typeof scope !== "object" || scope === null || Array.isArray(scope)) {
|
|
862
|
-
throw new TypeError(`${owner} session must be an object.`);
|
|
863
|
-
}
|
|
864
|
-
if (typeof scope.sessionId !== "string" || scope.sessionId.trim().length === 0) {
|
|
865
|
-
throw new TypeError(`${owner} sessionId must be a non-empty string.`);
|
|
866
|
-
}
|
|
867
|
-
const normalized = {
|
|
868
|
-
sessionId: scope.sessionId.trim()
|
|
869
|
-
};
|
|
870
|
-
if (scope.userId !== void 0) normalized.userId = scope.userId;
|
|
871
|
-
if (scope.metadata !== void 0) normalized.metadata = scope.metadata;
|
|
872
|
-
return lifecycleSnapshot(normalized);
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
// src/internal/agent-runtime/retrieval.ts
|
|
876
|
-
async function fetchContextDocuments(agent, ragText, abortSignal) {
|
|
877
|
-
const documents = [];
|
|
878
|
-
for (const input of agent.context) {
|
|
879
|
-
if (!isVectorContext(input)) {
|
|
880
|
-
documents.push(input);
|
|
881
|
-
continue;
|
|
882
|
-
}
|
|
883
|
-
if (ragText === void 0 || ragText.length === 0) continue;
|
|
884
|
-
const request = {
|
|
885
|
-
query: ragText,
|
|
886
|
-
topK: input.topK,
|
|
887
|
-
minScore: input.minScore,
|
|
888
|
-
filter: input.filter,
|
|
889
|
-
retries: input.retries,
|
|
890
|
-
abortSignal
|
|
891
|
-
};
|
|
892
|
-
const results = "models" in input && input.models !== void 0 ? await retrieveDocuments({
|
|
893
|
-
...request,
|
|
894
|
-
store: input.store,
|
|
895
|
-
models: input.models,
|
|
896
|
-
fusion: input.fusion
|
|
897
|
-
}) : await retrieveDocuments({ ...request, store: input.store, model: input.model });
|
|
898
|
-
for (const result of results) {
|
|
899
|
-
const formatted = input.format?.(result);
|
|
900
|
-
if (formatted !== void 0) {
|
|
901
|
-
documents.push(formatted);
|
|
902
|
-
continue;
|
|
903
|
-
}
|
|
904
|
-
const metadata = formatMetadata(result.metadata);
|
|
905
|
-
const document = {
|
|
906
|
-
id: result.id,
|
|
907
|
-
text: typeof result.document === "string" ? result.document : JSON.stringify(result.document, null, 2)
|
|
908
|
-
};
|
|
909
|
-
if (metadata !== void 0) document.additionalProps = metadata;
|
|
910
|
-
documents.push(document);
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
return documents;
|
|
914
|
-
}
|
|
915
|
-
async function fetchToolDefinitions(agent, ragText, abortSignal) {
|
|
916
|
-
const state = getAgentToolState(agent);
|
|
917
|
-
const staticDefinitions = await Promise.all(
|
|
918
|
-
state.staticTools.map((tool) => tool.definition(ragText ?? ""))
|
|
919
|
-
);
|
|
920
|
-
if (ragText === void 0 || ragText.length === 0 || state.toolIndexes.length === 0) {
|
|
921
|
-
return staticDefinitions;
|
|
922
|
-
}
|
|
923
|
-
const definitions = [...staticDefinitions];
|
|
924
|
-
const names = new Set(staticDefinitions.map((definition) => definition.name));
|
|
925
|
-
for (const index of state.toolIndexes) {
|
|
926
|
-
const results = await index.search({ query: ragText, abortSignal });
|
|
927
|
-
for (const result of results) {
|
|
928
|
-
const toolName = result.document.toolName;
|
|
929
|
-
if (names.has(toolName)) continue;
|
|
930
|
-
const tool = index.tools.find((candidate) => candidate.name === toolName);
|
|
931
|
-
if (tool === void 0) continue;
|
|
932
|
-
names.add(toolName);
|
|
933
|
-
definitions.push(await tool.definition(ragText));
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
return definitions;
|
|
937
|
-
}
|
|
938
|
-
function formatMetadata(metadata) {
|
|
939
|
-
if (metadata === void 0) return void 0;
|
|
940
|
-
return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
// src/internal/agent-runtime/run-validation.ts
|
|
944
|
-
function assertNonnegativeSafeInteger(value, name) {
|
|
945
|
-
if (!Number.isSafeInteger(value) || value < 0) {
|
|
946
|
-
throw new TypeError(`${name} must be a nonnegative safe integer.`);
|
|
947
|
-
}
|
|
948
|
-
return value;
|
|
949
|
-
}
|
|
950
|
-
function assertPositiveSafeInteger(value, name) {
|
|
951
|
-
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
952
|
-
throw new TypeError(`${name} must be a positive safe integer.`);
|
|
953
|
-
}
|
|
954
|
-
return value;
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
// src/internal/agent-runtime/stream-events.ts
|
|
958
|
-
function addTurn(turn, event) {
|
|
959
|
-
if (event.type === "text_delta") {
|
|
960
|
-
return { type: "text_delta", turn, delta: event.delta };
|
|
961
|
-
}
|
|
962
|
-
if (event.type === "reasoning_delta") {
|
|
963
|
-
const mapped = { type: "reasoning_delta", turn, delta: event.delta };
|
|
964
|
-
if (event.id !== void 0) mapped.id = event.id;
|
|
965
|
-
if (event.contentType !== void 0) mapped.contentType = event.contentType;
|
|
966
|
-
if (event.signature !== void 0) mapped.signature = event.signature;
|
|
967
|
-
return mapped;
|
|
968
|
-
}
|
|
969
|
-
if (event.type === "source") {
|
|
970
|
-
return { type: "source", turn, source: event.source };
|
|
971
|
-
}
|
|
972
|
-
if (event.type === "provider_tool_call") {
|
|
973
|
-
return { type: "provider_tool_call", turn, toolCall: event.toolCall };
|
|
974
|
-
}
|
|
975
|
-
return { type: "tool_call", turn, toolCall: event.toolCall };
|
|
976
|
-
}
|
|
977
|
-
function addTurnToToolCallDelta(turn, event) {
|
|
978
|
-
const mapped = {
|
|
979
|
-
type: "tool_call_delta",
|
|
980
|
-
turn,
|
|
981
|
-
id: event.id
|
|
982
|
-
};
|
|
983
|
-
if (event.callId !== void 0) mapped.callId = event.callId;
|
|
984
|
-
if (event.name !== void 0) mapped.name = event.name;
|
|
985
|
-
if (event.argumentsDelta !== void 0) mapped.argumentsDelta = event.argumentsDelta;
|
|
986
|
-
if (event.argumentsMode !== void 0) mapped.argumentsMode = event.argumentsMode;
|
|
987
|
-
if (event.signature !== void 0) mapped.signature = event.signature;
|
|
988
|
-
return mapped;
|
|
989
|
-
}
|
|
990
|
-
function isGenerationDeltaEvent(type) {
|
|
991
|
-
return type === "text_delta" || type === "reasoning_delta" || type === "tool_call_delta" || type === "tool_call" || type === "source" || type === "provider_tool_call";
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
// src/internal/agent-runtime/structured-output.ts
|
|
995
|
-
var JSON_FENCE_START = "```json\n";
|
|
996
|
-
var JSON_FENCE_CRLF_START = "```json\r\n";
|
|
997
|
-
var UNLABELED_FENCE_START = "```\n";
|
|
998
|
-
var UNLABELED_FENCE_CRLF_START = "```\r\n";
|
|
999
|
-
var FENCE_END = "\n```";
|
|
1000
|
-
var STRUCTURED_OUTPUT_RETRY_PROMPT = "Your previous response was invalid structured output. Return only raw JSON that matches the supplied JSON schema. Do not use Markdown fences or include commentary.";
|
|
1001
|
-
var STRUCTURED_OUTPUT_TRUNCATED_RETRY_PROMPT = "Your previous response exceeded the provider output limit. Return substantially shorter raw JSON that matches the supplied JSON schema. Do not use Markdown fences or include commentary.";
|
|
1002
|
-
var STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH = 8192;
|
|
1003
|
-
var STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER = "\n...[output omitted]...\n";
|
|
1004
|
-
function structuredOutputRepairPreview(text) {
|
|
1005
|
-
if (text.length <= STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH) {
|
|
1006
|
-
return { text, includedOutputLength: text.length };
|
|
1007
|
-
}
|
|
1008
|
-
const availableLength = STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH - STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER.length;
|
|
1009
|
-
const headLength = Math.ceil(availableLength / 2);
|
|
1010
|
-
const tailLength = availableLength - headLength;
|
|
1011
|
-
return {
|
|
1012
|
-
text: `${text.slice(0, headLength)}${STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER}${text.slice(-tailLength)}`,
|
|
1013
|
-
includedOutputLength: headLength + tailLength
|
|
1014
|
-
};
|
|
1015
|
-
}
|
|
1016
|
-
function normalizeStructuredOutput(text) {
|
|
1017
|
-
const trimmed = text.trim();
|
|
1018
|
-
const opening = fenceOpening(trimmed);
|
|
1019
|
-
if (opening === void 0 || !trimmed.endsWith(FENCE_END)) {
|
|
1020
|
-
return { text: trimmed, format: "raw" };
|
|
1021
|
-
}
|
|
1022
|
-
const closingStart = trimmed.length - 3;
|
|
1023
|
-
const precedingNewline = closingStart - 1;
|
|
1024
|
-
const contentEnd = trimmed[precedingNewline - 1] === "\r" ? precedingNewline - 1 : precedingNewline;
|
|
1025
|
-
return {
|
|
1026
|
-
text: trimmed.slice(opening.length, contentEnd).trim(),
|
|
1027
|
-
format: opening.format
|
|
1028
|
-
};
|
|
1029
|
-
}
|
|
1030
|
-
function fenceOpening(text) {
|
|
1031
|
-
if (text.startsWith(JSON_FENCE_START)) {
|
|
1032
|
-
return { length: JSON_FENCE_START.length, format: "json-fence" };
|
|
1033
|
-
}
|
|
1034
|
-
if (text.startsWith(JSON_FENCE_CRLF_START)) {
|
|
1035
|
-
return { length: JSON_FENCE_CRLF_START.length, format: "json-fence" };
|
|
1036
|
-
}
|
|
1037
|
-
if (text.startsWith(UNLABELED_FENCE_START)) {
|
|
1038
|
-
return { length: UNLABELED_FENCE_START.length, format: "unlabeled-fence" };
|
|
1039
|
-
}
|
|
1040
|
-
if (text.startsWith(UNLABELED_FENCE_CRLF_START)) {
|
|
1041
|
-
return { length: UNLABELED_FENCE_CRLF_START.length, format: "unlabeled-fence" };
|
|
1042
|
-
}
|
|
1043
|
-
return void 0;
|
|
1044
|
-
}
|
|
1045
|
-
|
|
1046
|
-
// src/internal/agent-runtime/tool-execution.ts
|
|
1047
|
-
var ToolCallExecutor = class {
|
|
1048
|
-
constructor(agent, activeHook, approvalHandler, lifecycle, runContext, concurrency, requestMiddlewares, abortSignal, cancel) {
|
|
1049
|
-
this.agent = agent;
|
|
1050
|
-
this.activeHook = activeHook;
|
|
1051
|
-
this.approvalHandler = approvalHandler;
|
|
1052
|
-
this.lifecycle = lifecycle;
|
|
1053
|
-
this.runContext = runContext;
|
|
1054
|
-
this.concurrency = concurrency;
|
|
1055
|
-
this.requestMiddlewares = requestMiddlewares;
|
|
1056
|
-
this.abortSignal = abortSignal;
|
|
1057
|
-
this.cancel = cancel;
|
|
1058
|
-
}
|
|
1059
|
-
agent;
|
|
1060
|
-
activeHook;
|
|
1061
|
-
approvalHandler;
|
|
1062
|
-
lifecycle;
|
|
1063
|
-
runContext;
|
|
1064
|
-
concurrency;
|
|
1065
|
-
requestMiddlewares;
|
|
1066
|
-
abortSignal;
|
|
1067
|
-
cancel;
|
|
1068
|
-
async execute(toolCalls, onResult, onStreamEvent, observation) {
|
|
1069
|
-
assertCompletionResponseIntegrity({
|
|
1070
|
-
response: {
|
|
1071
|
-
choice: [...toolCalls],
|
|
1072
|
-
usage: Usage.empty(),
|
|
1073
|
-
rawResponse: void 0
|
|
1074
|
-
}
|
|
1075
|
-
});
|
|
1076
|
-
const executeOne = async (toolCall) => {
|
|
1077
|
-
throwIfAborted(this.abortSignal);
|
|
1078
|
-
const args = JSON.stringify(toolCall.input);
|
|
1079
|
-
const internalCallId = globalThis.crypto.randomUUID();
|
|
1080
|
-
const hookArgs = {
|
|
1081
|
-
toolName: toolCall.toolName,
|
|
1082
|
-
toolCallId: toolCall.toolCallId,
|
|
1083
|
-
internalCallId,
|
|
1084
|
-
args
|
|
1085
|
-
};
|
|
1086
|
-
if (toolCall.callId !== void 0) {
|
|
1087
|
-
hookArgs.callId = toolCall.callId;
|
|
1088
|
-
}
|
|
1089
|
-
const tool = this.agent.getTool(toolCall.toolName);
|
|
1090
|
-
const toolDefinition = observation?.toolDefinitions?.find(
|
|
1091
|
-
(definition) => definition.name === toolCall.toolName
|
|
1092
|
-
);
|
|
1093
|
-
const toolMetadata = toolTraceMetadata(tool);
|
|
1094
|
-
let toolStartArgs = {
|
|
1095
|
-
turn: observation?.turn ?? 0,
|
|
1096
|
-
toolCall,
|
|
1097
|
-
toolName: toolCall.toolName,
|
|
1098
|
-
internalCallId,
|
|
1099
|
-
args
|
|
1100
|
-
};
|
|
1101
|
-
if (toolCall.callId !== void 0) {
|
|
1102
|
-
toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };
|
|
1103
|
-
}
|
|
1104
|
-
if (toolDefinition !== void 0) toolStartArgs = { ...toolStartArgs, toolDefinition };
|
|
1105
|
-
if (toolMetadata !== void 0) toolStartArgs = { ...toolStartArgs, toolMetadata };
|
|
1106
|
-
const toolObservers = await observation?.runObservers.startTool(toolStartArgs);
|
|
1107
|
-
const toolObservation = new ToolObserverScope(toolObservers);
|
|
1108
|
-
let output;
|
|
1109
|
-
let skipped = false;
|
|
1110
|
-
let toolExecutionFailed = false;
|
|
1111
|
-
let effectiveArgs = args;
|
|
1112
|
-
try {
|
|
1113
|
-
const callAction = await this.activeHook?.onToolCall?.({
|
|
1114
|
-
...hookArgs,
|
|
1115
|
-
tool: toolCallControl
|
|
1116
|
-
});
|
|
1117
|
-
if (callAction?.type === "terminate") {
|
|
1118
|
-
throw this.cancel(callAction.reason);
|
|
1119
|
-
}
|
|
1120
|
-
if (callAction?.type === "skip") {
|
|
1121
|
-
output = { type: "text", value: callAction.reason };
|
|
1122
|
-
skipped = true;
|
|
1123
|
-
} else {
|
|
1124
|
-
try {
|
|
1125
|
-
effectiveArgs = await this.runToolInputMiddlewares({
|
|
1126
|
-
...hookArgs,
|
|
1127
|
-
turn: observation?.turn ?? 0,
|
|
1128
|
-
originalArgs: args
|
|
1129
|
-
});
|
|
1130
|
-
hookArgs.args = effectiveArgs;
|
|
1131
|
-
let prepared;
|
|
1132
|
-
try {
|
|
1133
|
-
prepared = this.prepareToolCall(tool, toolCall.toolName, effectiveArgs);
|
|
1134
|
-
} catch (error) {
|
|
1135
|
-
const outcome = await this.handleToolError(
|
|
1136
|
-
toolCall,
|
|
1137
|
-
hookArgs,
|
|
1138
|
-
effectiveArgs,
|
|
1139
|
-
error,
|
|
1140
|
-
toolObservation,
|
|
1141
|
-
observation
|
|
1142
|
-
);
|
|
1143
|
-
output = outcome.output;
|
|
1144
|
-
toolExecutionFailed = outcome.failed;
|
|
1145
|
-
}
|
|
1146
|
-
if (prepared !== void 0 && isQuestionTool(tool)) {
|
|
1147
|
-
try {
|
|
1148
|
-
const questions = parseAgentQuestionPrompts(
|
|
1149
|
-
prepared.input.questions
|
|
1150
|
-
);
|
|
1151
|
-
const interaction = {
|
|
1152
|
-
type: "tool-question",
|
|
1153
|
-
id: globalThis.crypto.randomUUID(),
|
|
1154
|
-
toolName: toolCall.toolName,
|
|
1155
|
-
toolCallId: toolCall.toolCallId,
|
|
1156
|
-
internalCallId,
|
|
1157
|
-
questions
|
|
1158
|
-
};
|
|
1159
|
-
if (toolCall.callId !== void 0) {
|
|
1160
|
-
Object.assign(interaction, { callId: toolCall.callId });
|
|
1161
|
-
}
|
|
1162
|
-
throw new AgentInteractionSignal(interaction);
|
|
1163
|
-
} catch (error) {
|
|
1164
|
-
if (error instanceof AgentInteractionSignal) throw error;
|
|
1165
|
-
const outcome = await this.handleToolError(
|
|
1166
|
-
toolCall,
|
|
1167
|
-
hookArgs,
|
|
1168
|
-
effectiveArgs,
|
|
1169
|
-
error,
|
|
1170
|
-
toolObservation,
|
|
1171
|
-
observation
|
|
1172
|
-
);
|
|
1173
|
-
output = outcome.output;
|
|
1174
|
-
toolExecutionFailed = outcome.failed;
|
|
1175
|
-
prepared = void 0;
|
|
1176
|
-
}
|
|
1177
|
-
}
|
|
1178
|
-
if (prepared !== void 0) {
|
|
1179
|
-
const approvalContext = createApprovalContext(
|
|
1180
|
-
prepared.input,
|
|
1181
|
-
hookArgs,
|
|
1182
|
-
this.agent,
|
|
1183
|
-
this.runContext
|
|
1184
|
-
);
|
|
1185
|
-
const approvalDecision = callAction?.type === "approval_request" ? await this.requestApproval(approvalContext, callAction, observation) : await this.evaluateToolApproval(tool, approvalContext, observation) ?? {
|
|
1186
|
-
approved: true
|
|
1187
|
-
};
|
|
1188
|
-
if (!approvalDecision.approved) {
|
|
1189
|
-
output = { type: "execution-denied", reason: approvalDecision.result };
|
|
1190
|
-
skipped = true;
|
|
1191
|
-
} else {
|
|
1192
|
-
const step = observation?.turn ?? 0;
|
|
1193
|
-
const lifecycleEvent = {
|
|
1194
|
-
runId: this.runContext.runId,
|
|
1195
|
-
step,
|
|
1196
|
-
toolName: toolCall.toolName,
|
|
1197
|
-
input: lifecycleSnapshot(prepared.input)
|
|
1198
|
-
};
|
|
1199
|
-
if (toolCall.callId !== void 0) {
|
|
1200
|
-
Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });
|
|
1201
|
-
}
|
|
1202
|
-
await this.lifecycle?.onToolStart?.(lifecycleEvent);
|
|
1203
|
-
const startedAt = Date.now();
|
|
1204
|
-
const outcome = await this.runApprovedToolCall(
|
|
1205
|
-
prepared,
|
|
1206
|
-
toolCall,
|
|
1207
|
-
hookArgs,
|
|
1208
|
-
effectiveArgs,
|
|
1209
|
-
toolObservation,
|
|
1210
|
-
observation,
|
|
1211
|
-
onStreamEvent
|
|
1212
|
-
);
|
|
1213
|
-
output = outcome.output;
|
|
1214
|
-
toolExecutionFailed = outcome.failed;
|
|
1215
|
-
const durationMs = Date.now() - startedAt;
|
|
1216
|
-
await this.lifecycle?.onToolFinish?.(
|
|
1217
|
-
outcome.failed ? {
|
|
1218
|
-
...lifecycleEvent,
|
|
1219
|
-
durationMs,
|
|
1220
|
-
success: false,
|
|
1221
|
-
error: lifecycleSnapshot(outcome.error)
|
|
1222
|
-
} : {
|
|
1223
|
-
...lifecycleEvent,
|
|
1224
|
-
durationMs,
|
|
1225
|
-
success: true,
|
|
1226
|
-
output: lifecycleSnapshot(output)
|
|
1227
|
-
}
|
|
1228
|
-
);
|
|
1229
|
-
}
|
|
1230
|
-
}
|
|
1231
|
-
} catch (error) {
|
|
1232
|
-
if (error instanceof AgentInteractionSignal) {
|
|
1233
|
-
await toolObservation.suspend({
|
|
1234
|
-
...toolStartArgs,
|
|
1235
|
-
interaction: error.interaction
|
|
1236
|
-
});
|
|
1237
|
-
throw error;
|
|
1238
|
-
}
|
|
1239
|
-
await toolObservation.error(
|
|
1240
|
-
toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
|
|
1241
|
-
);
|
|
1242
|
-
throw error;
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
if (output === void 0) {
|
|
1246
|
-
throw new Error(`Tool "${toolCall.toolName}" did not produce an execution result.`);
|
|
1247
|
-
}
|
|
1248
|
-
let result = toolOutputToText(output);
|
|
1249
|
-
let structuredResult = toolOutputToStructuredResult(output);
|
|
1250
|
-
if (!isSkillTool(tool)) {
|
|
1251
|
-
const middlewareReplacement = await this.runToolResultMiddlewares({
|
|
1252
|
-
...hookArgs,
|
|
1253
|
-
args: effectiveArgs,
|
|
1254
|
-
result,
|
|
1255
|
-
originalResult: result,
|
|
1256
|
-
structuredResult,
|
|
1257
|
-
originalStructuredResult: structuredResult,
|
|
1258
|
-
turn: observation?.turn ?? 0
|
|
1259
|
-
});
|
|
1260
|
-
if (middlewareReplacement !== void 0) {
|
|
1261
|
-
output = middlewareReplacement;
|
|
1262
|
-
result = toolOutputToText(middlewareReplacement);
|
|
1263
|
-
structuredResult = toolOutputToStructuredResult(middlewareReplacement);
|
|
1264
|
-
}
|
|
1265
|
-
}
|
|
1266
|
-
const resultAction = await this.activeHook?.onToolResult?.({
|
|
1267
|
-
...hookArgs,
|
|
1268
|
-
args: effectiveArgs,
|
|
1269
|
-
result,
|
|
1270
|
-
structuredResult,
|
|
1271
|
-
run: runControl
|
|
1272
|
-
});
|
|
1273
|
-
if (!toolExecutionFailed) {
|
|
1274
|
-
await toolObservation.end({
|
|
1275
|
-
turn: observation?.turn ?? 0,
|
|
1276
|
-
toolCall,
|
|
1277
|
-
toolName: toolCall.toolName,
|
|
1278
|
-
internalCallId,
|
|
1279
|
-
args: effectiveArgs,
|
|
1280
|
-
result,
|
|
1281
|
-
structuredResult,
|
|
1282
|
-
skipped,
|
|
1283
|
-
toolCallId: toolCall.callId
|
|
1284
|
-
});
|
|
1285
|
-
}
|
|
1286
|
-
if (resultAction?.type === "terminate") {
|
|
1287
|
-
throw this.cancel(resultAction.reason);
|
|
1288
|
-
}
|
|
1289
|
-
const resultPayload = {
|
|
1290
|
-
type: "tool_result",
|
|
1291
|
-
toolName: toolCall.toolName,
|
|
1292
|
-
toolCallId: toolCall.toolCallId,
|
|
1293
|
-
internalCallId,
|
|
1294
|
-
args: effectiveArgs,
|
|
1295
|
-
output,
|
|
1296
|
-
result,
|
|
1297
|
-
structuredResult
|
|
1298
|
-
};
|
|
1299
|
-
if (toolCall.callId !== void 0) resultPayload.callId = toolCall.callId;
|
|
1300
|
-
onResult?.(resultPayload);
|
|
1301
|
-
let resultPart = {
|
|
1302
|
-
type: "tool-result",
|
|
1303
|
-
toolCallId: toolCall.toolCallId,
|
|
1304
|
-
toolName: toolCall.toolName,
|
|
1305
|
-
output
|
|
1306
|
-
};
|
|
1307
|
-
if (toolCall.callId !== void 0) {
|
|
1308
|
-
resultPart = { ...resultPart, callId: toolCall.callId };
|
|
1309
|
-
}
|
|
1310
|
-
return resultPart;
|
|
1311
|
-
} catch (error) {
|
|
1312
|
-
if (error instanceof AgentInteractionSignal) {
|
|
1313
|
-
const pending = {
|
|
1314
|
-
toolCall,
|
|
1315
|
-
effectiveArgs,
|
|
1316
|
-
input: error.interaction.type === "tool-approval" ? error.interaction.input : parseToolArgs(effectiveArgs),
|
|
1317
|
-
internalCallId
|
|
1318
|
-
};
|
|
1319
|
-
if (error.rejectMessage !== void 0) pending.rejectMessage = error.rejectMessage;
|
|
1320
|
-
throw new ToolExecutionSuspension(error.interaction, pending);
|
|
1321
|
-
}
|
|
1322
|
-
await toolObservation.error(
|
|
1323
|
-
toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
|
|
1324
|
-
);
|
|
1325
|
-
throw error;
|
|
1326
|
-
}
|
|
1327
|
-
};
|
|
1328
|
-
if (this.concurrency === 1) {
|
|
1329
|
-
const results = [];
|
|
1330
|
-
for (const toolCall of toolCalls) {
|
|
1331
|
-
try {
|
|
1332
|
-
results.push(await executeOne(toolCall));
|
|
1333
|
-
} catch (error) {
|
|
1334
|
-
if (error instanceof ToolExecutionSuspension) {
|
|
1335
|
-
error.completedResults = [...results];
|
|
1336
|
-
error.remainingToolCalls = toolCalls.slice(results.length + 1);
|
|
1337
|
-
}
|
|
1338
|
-
throw error;
|
|
1339
|
-
}
|
|
1340
|
-
}
|
|
1341
|
-
return results;
|
|
1342
|
-
}
|
|
1343
|
-
return mapWithConcurrency(toolCalls, this.concurrency, executeOne);
|
|
1344
|
-
}
|
|
1345
|
-
async executeResumed(pending, onResult, onStreamEvent, observation) {
|
|
1346
|
-
throwIfAborted(this.abortSignal);
|
|
1347
|
-
const { toolCall, internalCallId, effectiveArgs } = pending;
|
|
1348
|
-
const tool = this.agent.getTool(toolCall.toolName);
|
|
1349
|
-
if (tool === void 0) {
|
|
1350
|
-
throw new Error(
|
|
1351
|
-
`Cannot resume tool interaction because tool "${toolCall.toolName}" is no longer registered.`
|
|
1352
|
-
);
|
|
1353
|
-
}
|
|
1354
|
-
if (isQuestionTool(tool)) {
|
|
1355
|
-
throw new TypeError("Question interactions are resolved from their submitted answers.");
|
|
1356
|
-
}
|
|
1357
|
-
const hookArgs = {
|
|
1358
|
-
toolName: toolCall.toolName,
|
|
1359
|
-
toolCallId: toolCall.toolCallId,
|
|
1360
|
-
internalCallId,
|
|
1361
|
-
args: effectiveArgs
|
|
1362
|
-
};
|
|
1363
|
-
if (toolCall.callId !== void 0) hookArgs.callId = toolCall.callId;
|
|
1364
|
-
const toolDefinition = observation?.toolDefinitions?.find(
|
|
1365
|
-
(definition) => definition.name === toolCall.toolName
|
|
1366
|
-
);
|
|
1367
|
-
const toolMetadata = toolTraceMetadata(tool);
|
|
1368
|
-
let toolStartArgs = {
|
|
1369
|
-
turn: observation?.turn ?? 0,
|
|
1370
|
-
toolCall,
|
|
1371
|
-
toolName: toolCall.toolName,
|
|
1372
|
-
internalCallId,
|
|
1373
|
-
args: effectiveArgs
|
|
1374
|
-
};
|
|
1375
|
-
if (toolCall.callId !== void 0) {
|
|
1376
|
-
toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };
|
|
1377
|
-
}
|
|
1378
|
-
if (toolDefinition !== void 0) toolStartArgs = { ...toolStartArgs, toolDefinition };
|
|
1379
|
-
if (toolMetadata !== void 0) toolStartArgs = { ...toolStartArgs, toolMetadata };
|
|
1380
|
-
const observers = await observation?.runObservers.startTool(toolStartArgs);
|
|
1381
|
-
const toolObservation = new ToolObserverScope(observers);
|
|
1382
|
-
let output;
|
|
1383
|
-
let failed = false;
|
|
1384
|
-
try {
|
|
1385
|
-
const prepared = prepareToolCallFromInput(tool, pending.input);
|
|
1386
|
-
const step = observation?.turn ?? 0;
|
|
1387
|
-
const lifecycleEvent = {
|
|
1388
|
-
runId: this.runContext.runId,
|
|
1389
|
-
step,
|
|
1390
|
-
toolName: toolCall.toolName,
|
|
1391
|
-
input: lifecycleSnapshot(prepared.input)
|
|
1392
|
-
};
|
|
1393
|
-
if (toolCall.callId !== void 0) {
|
|
1394
|
-
Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });
|
|
1395
|
-
}
|
|
1396
|
-
await this.lifecycle?.onToolStart?.(lifecycleEvent);
|
|
1397
|
-
const startedAt = Date.now();
|
|
1398
|
-
const outcome = await this.runApprovedToolCall(
|
|
1399
|
-
prepared,
|
|
1400
|
-
toolCall,
|
|
1401
|
-
hookArgs,
|
|
1402
|
-
effectiveArgs,
|
|
1403
|
-
toolObservation,
|
|
1404
|
-
observation,
|
|
1405
|
-
onStreamEvent
|
|
1406
|
-
);
|
|
1407
|
-
output = outcome.output;
|
|
1408
|
-
failed = outcome.failed;
|
|
1409
|
-
const durationMs = Date.now() - startedAt;
|
|
1410
|
-
await this.lifecycle?.onToolFinish?.(
|
|
1411
|
-
outcome.failed ? {
|
|
1412
|
-
...lifecycleEvent,
|
|
1413
|
-
durationMs,
|
|
1414
|
-
success: false,
|
|
1415
|
-
error: lifecycleSnapshot(outcome.error)
|
|
1416
|
-
} : {
|
|
1417
|
-
...lifecycleEvent,
|
|
1418
|
-
durationMs,
|
|
1419
|
-
success: true,
|
|
1420
|
-
output: lifecycleSnapshot(output)
|
|
1421
|
-
}
|
|
1422
|
-
);
|
|
1423
|
-
let result = toolOutputToText(output);
|
|
1424
|
-
let structuredResult = toolOutputToStructuredResult(output);
|
|
1425
|
-
if (!isSkillTool(tool)) {
|
|
1426
|
-
const replacement = await this.runToolResultMiddlewares({
|
|
1427
|
-
...hookArgs,
|
|
1428
|
-
args: effectiveArgs,
|
|
1429
|
-
result,
|
|
1430
|
-
originalResult: result,
|
|
1431
|
-
structuredResult,
|
|
1432
|
-
originalStructuredResult: structuredResult,
|
|
1433
|
-
turn: step
|
|
1434
|
-
});
|
|
1435
|
-
if (replacement !== void 0) {
|
|
1436
|
-
output = replacement;
|
|
1437
|
-
result = toolOutputToText(replacement);
|
|
1438
|
-
structuredResult = toolOutputToStructuredResult(replacement);
|
|
1439
|
-
}
|
|
1440
|
-
}
|
|
1441
|
-
const resultAction = await this.activeHook?.onToolResult?.({
|
|
1442
|
-
...hookArgs,
|
|
1443
|
-
result,
|
|
1444
|
-
structuredResult,
|
|
1445
|
-
run: runControl
|
|
1446
|
-
});
|
|
1447
|
-
if (!failed) {
|
|
1448
|
-
await toolObservation.end({
|
|
1449
|
-
turn: step,
|
|
1450
|
-
toolCall,
|
|
1451
|
-
toolName: toolCall.toolName,
|
|
1452
|
-
internalCallId,
|
|
1453
|
-
args: effectiveArgs,
|
|
1454
|
-
result,
|
|
1455
|
-
structuredResult,
|
|
1456
|
-
skipped: false,
|
|
1457
|
-
toolCallId: toolCall.callId
|
|
1458
|
-
});
|
|
1459
|
-
}
|
|
1460
|
-
if (resultAction?.type === "terminate") {
|
|
1461
|
-
throw this.cancel(resultAction.reason);
|
|
1462
|
-
}
|
|
1463
|
-
const resultPayload = {
|
|
1464
|
-
type: "tool_result",
|
|
1465
|
-
toolName: toolCall.toolName,
|
|
1466
|
-
toolCallId: toolCall.toolCallId,
|
|
1467
|
-
internalCallId,
|
|
1468
|
-
args: effectiveArgs,
|
|
1469
|
-
output,
|
|
1470
|
-
result,
|
|
1471
|
-
structuredResult
|
|
1472
|
-
};
|
|
1473
|
-
if (toolCall.callId !== void 0) resultPayload.callId = toolCall.callId;
|
|
1474
|
-
onResult?.(resultPayload);
|
|
1475
|
-
let resultPart = {
|
|
1476
|
-
type: "tool-result",
|
|
1477
|
-
toolName: toolCall.toolName,
|
|
1478
|
-
toolCallId: toolCall.toolCallId,
|
|
1479
|
-
output
|
|
1480
|
-
};
|
|
1481
|
-
if (toolCall.callId !== void 0) resultPart = { ...resultPart, callId: toolCall.callId };
|
|
1482
|
-
return resultPart;
|
|
1483
|
-
} catch (error) {
|
|
1484
|
-
await toolObservation.error(
|
|
1485
|
-
toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
|
|
1486
|
-
);
|
|
1487
|
-
throw error;
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
|
-
async resolveResumed(pending, initialOutput, onResult, observation) {
|
|
1491
|
-
throwIfAborted(this.abortSignal);
|
|
1492
|
-
const { toolCall, internalCallId, effectiveArgs } = pending;
|
|
1493
|
-
const tool = this.agent.getTool(toolCall.toolName);
|
|
1494
|
-
if (tool === void 0) {
|
|
1495
|
-
throw new Error(
|
|
1496
|
-
`Cannot resume tool interaction because tool "${toolCall.toolName}" is no longer registered.`
|
|
1497
|
-
);
|
|
1498
|
-
}
|
|
1499
|
-
const hookArgs = {
|
|
1500
|
-
toolName: toolCall.toolName,
|
|
1501
|
-
toolCallId: toolCall.toolCallId,
|
|
1502
|
-
internalCallId,
|
|
1503
|
-
args: effectiveArgs
|
|
1504
|
-
};
|
|
1505
|
-
if (toolCall.callId !== void 0) hookArgs.callId = toolCall.callId;
|
|
1506
|
-
const toolDefinition = observation?.toolDefinitions?.find(
|
|
1507
|
-
(definition) => definition.name === toolCall.toolName
|
|
1508
|
-
);
|
|
1509
|
-
const toolMetadata = toolTraceMetadata(tool);
|
|
1510
|
-
let toolStartArgs = {
|
|
1511
|
-
turn: observation?.turn ?? 0,
|
|
1512
|
-
toolCall,
|
|
1513
|
-
toolName: toolCall.toolName,
|
|
1514
|
-
internalCallId,
|
|
1515
|
-
args: effectiveArgs
|
|
1516
|
-
};
|
|
1517
|
-
if (toolCall.callId !== void 0) {
|
|
1518
|
-
toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };
|
|
1519
|
-
}
|
|
1520
|
-
if (toolDefinition !== void 0) toolStartArgs = { ...toolStartArgs, toolDefinition };
|
|
1521
|
-
if (toolMetadata !== void 0) toolStartArgs = { ...toolStartArgs, toolMetadata };
|
|
1522
|
-
const observers = await observation?.runObservers.startTool(toolStartArgs);
|
|
1523
|
-
const toolObservation = new ToolObserverScope(observers);
|
|
1524
|
-
try {
|
|
1525
|
-
let output = initialOutput;
|
|
1526
|
-
let result = toolOutputToText(output);
|
|
1527
|
-
let structuredResult = toolOutputToStructuredResult(output);
|
|
1528
|
-
if (!isSkillTool(tool)) {
|
|
1529
|
-
const replacement = await this.runToolResultMiddlewares({
|
|
1530
|
-
...hookArgs,
|
|
1531
|
-
args: effectiveArgs,
|
|
1532
|
-
result,
|
|
1533
|
-
originalResult: result,
|
|
1534
|
-
structuredResult,
|
|
1535
|
-
originalStructuredResult: structuredResult,
|
|
1536
|
-
turn: observation?.turn ?? 0
|
|
1537
|
-
});
|
|
1538
|
-
if (replacement !== void 0) {
|
|
1539
|
-
output = replacement;
|
|
1540
|
-
result = toolOutputToText(replacement);
|
|
1541
|
-
structuredResult = toolOutputToStructuredResult(replacement);
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
const resultAction = await this.activeHook?.onToolResult?.({
|
|
1545
|
-
...hookArgs,
|
|
1546
|
-
result,
|
|
1547
|
-
structuredResult,
|
|
1548
|
-
run: runControl
|
|
1549
|
-
});
|
|
1550
|
-
await toolObservation.end({
|
|
1551
|
-
turn: observation?.turn ?? 0,
|
|
1552
|
-
toolCall,
|
|
1553
|
-
toolName: toolCall.toolName,
|
|
1554
|
-
internalCallId,
|
|
1555
|
-
args: effectiveArgs,
|
|
1556
|
-
result,
|
|
1557
|
-
structuredResult,
|
|
1558
|
-
skipped: true,
|
|
1559
|
-
toolCallId: toolCall.callId
|
|
1560
|
-
});
|
|
1561
|
-
if (resultAction?.type === "terminate") {
|
|
1562
|
-
throw this.cancel(resultAction.reason);
|
|
1563
|
-
}
|
|
1564
|
-
const resultPayload = {
|
|
1565
|
-
type: "tool_result",
|
|
1566
|
-
toolName: toolCall.toolName,
|
|
1567
|
-
toolCallId: toolCall.toolCallId,
|
|
1568
|
-
internalCallId,
|
|
1569
|
-
args: effectiveArgs,
|
|
1570
|
-
output,
|
|
1571
|
-
result,
|
|
1572
|
-
structuredResult
|
|
1573
|
-
};
|
|
1574
|
-
if (toolCall.callId !== void 0) resultPayload.callId = toolCall.callId;
|
|
1575
|
-
onResult?.(resultPayload);
|
|
1576
|
-
let resultPart = {
|
|
1577
|
-
type: "tool-result",
|
|
1578
|
-
toolName: toolCall.toolName,
|
|
1579
|
-
toolCallId: toolCall.toolCallId,
|
|
1580
|
-
output
|
|
1581
|
-
};
|
|
1582
|
-
if (toolCall.callId !== void 0) resultPart = { ...resultPart, callId: toolCall.callId };
|
|
1583
|
-
return resultPart;
|
|
1584
|
-
} catch (error) {
|
|
1585
|
-
await toolObservation.error(
|
|
1586
|
-
toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
|
|
1587
|
-
);
|
|
1588
|
-
throw error;
|
|
1589
|
-
}
|
|
1590
|
-
}
|
|
1591
|
-
async runApprovedToolCall(prepared, toolCall, hookArgs, effectiveArgs, toolObservation, observation, onStreamEvent) {
|
|
1592
|
-
try {
|
|
1593
|
-
const toolContext = {
|
|
1594
|
-
abortSignal: this.abortSignal,
|
|
1595
|
-
emitStreamEvent: async (event) => {
|
|
1596
|
-
let streamEventArgs = {
|
|
1597
|
-
turn: observation?.turn ?? 0,
|
|
1598
|
-
toolCall,
|
|
1599
|
-
toolName: toolCall.toolName,
|
|
1600
|
-
internalCallId: hookArgs.internalCallId,
|
|
1601
|
-
args: effectiveArgs,
|
|
1602
|
-
event
|
|
1603
|
-
};
|
|
1604
|
-
if (toolCall.callId !== void 0) {
|
|
1605
|
-
streamEventArgs = { ...streamEventArgs, toolCallId: toolCall.callId };
|
|
1606
|
-
}
|
|
1607
|
-
await toolObservation.streamEvent(streamEventArgs);
|
|
1608
|
-
const payload = agentToolEventPayload(toolCall, hookArgs.internalCallId, event);
|
|
1609
|
-
if (payload !== void 0) {
|
|
1610
|
-
onStreamEvent?.(payload);
|
|
1611
|
-
}
|
|
1612
|
-
}
|
|
1613
|
-
};
|
|
1614
|
-
return {
|
|
1615
|
-
output: await prepared.call(toolContext),
|
|
1616
|
-
failed: false
|
|
1617
|
-
};
|
|
1618
|
-
} catch (error) {
|
|
1619
|
-
return this.handleToolError(
|
|
1620
|
-
toolCall,
|
|
1621
|
-
hookArgs,
|
|
1622
|
-
effectiveArgs,
|
|
1623
|
-
error,
|
|
1624
|
-
toolObservation,
|
|
1625
|
-
observation
|
|
1626
|
-
);
|
|
1627
|
-
}
|
|
1628
|
-
}
|
|
1629
|
-
prepareToolCall(tool, toolName, args) {
|
|
1630
|
-
if (tool !== void 0) {
|
|
1631
|
-
return prepareToolCall(tool, args);
|
|
1632
|
-
}
|
|
1633
|
-
const input = parseToolArgs(args);
|
|
1634
|
-
return {
|
|
1635
|
-
input,
|
|
1636
|
-
call: (context) => this.agent.callTool(toolName, args, context)
|
|
1637
|
-
};
|
|
1638
|
-
}
|
|
1639
|
-
async handleToolError(toolCall, hookArgs, args, error, toolObservation, observation) {
|
|
1640
|
-
const errorAction = await this.activeHook?.onToolError?.({
|
|
1641
|
-
...hookArgs,
|
|
1642
|
-
args,
|
|
1643
|
-
error,
|
|
1644
|
-
run: runControl
|
|
1645
|
-
});
|
|
1646
|
-
await toolObservation.error(
|
|
1647
|
-
toolErrorArgs(observation?.turn ?? 0, toolCall, hookArgs.internalCallId, args, error)
|
|
1648
|
-
);
|
|
1649
|
-
if (errorAction?.type === "terminate") {
|
|
1650
|
-
throw this.cancel(errorAction.reason);
|
|
1651
|
-
}
|
|
1652
|
-
return {
|
|
1653
|
-
output: {
|
|
1654
|
-
type: "error-text",
|
|
1655
|
-
value: error instanceof Error ? error.toString() : String(error)
|
|
1656
|
-
},
|
|
1657
|
-
failed: true,
|
|
1658
|
-
error
|
|
1659
|
-
};
|
|
1660
|
-
}
|
|
1661
|
-
async runToolResultMiddlewares(args) {
|
|
1662
|
-
let result = args.result;
|
|
1663
|
-
let structuredResult = args.structuredResult;
|
|
1664
|
-
let replaced = false;
|
|
1665
|
-
for (const middleware of this.activeMiddlewares()) {
|
|
1666
|
-
const outputReplacement = await middleware.onToolOutput?.({
|
|
1667
|
-
...args,
|
|
1668
|
-
result,
|
|
1669
|
-
structuredResult
|
|
1670
|
-
});
|
|
1671
|
-
if (outputReplacement !== void 0) {
|
|
1672
|
-
const normalized = normalizeToolOutputMiddlewareResult(outputReplacement);
|
|
1673
|
-
if (normalized.result !== void 0) {
|
|
1674
|
-
result = normalized.result;
|
|
1675
|
-
structuredResult = void 0;
|
|
1676
|
-
}
|
|
1677
|
-
if (normalized.structuredResult !== void 0) {
|
|
1678
|
-
structuredResult = normalized.structuredResult;
|
|
1679
|
-
result = toolResultContentToText(normalized.structuredResult);
|
|
1680
|
-
}
|
|
1681
|
-
replaced = true;
|
|
1682
|
-
}
|
|
1683
|
-
}
|
|
1684
|
-
return replaced ? structuredResult === void 0 ? { type: "text", value: result } : { type: "content", value: structuredResult } : void 0;
|
|
1685
|
-
}
|
|
1686
|
-
async runToolInputMiddlewares(args) {
|
|
1687
|
-
let current = args.args;
|
|
1688
|
-
for (const middleware of this.activeMiddlewares()) {
|
|
1689
|
-
const replacement = await middleware.onToolInput?.({
|
|
1690
|
-
...args,
|
|
1691
|
-
args: current
|
|
1692
|
-
});
|
|
1693
|
-
if (replacement?.args !== void 0) {
|
|
1694
|
-
if (typeof replacement.args === "string") {
|
|
1695
|
-
current = replacement.args;
|
|
1696
|
-
} else {
|
|
1697
|
-
if (!isJsonValue(replacement.args)) {
|
|
1698
|
-
throw new TypeError("Tool input middleware args must be a strict JSON value.");
|
|
1699
|
-
}
|
|
1700
|
-
current = JSON.stringify(replacement.args);
|
|
1701
|
-
}
|
|
1702
|
-
}
|
|
1703
|
-
}
|
|
1704
|
-
return current;
|
|
1705
|
-
}
|
|
1706
|
-
activeMiddlewares() {
|
|
1707
|
-
return [...this.agent.middlewares, ...this.requestMiddlewares];
|
|
1708
|
-
}
|
|
1709
|
-
async evaluateToolApproval(tool, context, observation) {
|
|
1710
|
-
const requirement = tool?.requiresApproval;
|
|
1711
|
-
if (requirement === void 0) return void 0;
|
|
1712
|
-
const resolved = typeof requirement === "function" ? await requirement(context.args, context) : requirement;
|
|
1713
|
-
assertToolApprovalRequirement(resolved, { allowFunction: false });
|
|
1714
|
-
if (resolved === false) return { approved: true };
|
|
1715
|
-
const reason = resolved === true ? void 0 : resolved.reason;
|
|
1716
|
-
return this.requestApproval(context, reason === void 0 ? {} : { reason }, observation);
|
|
1717
|
-
}
|
|
1718
|
-
async requestApproval(context, options, observation) {
|
|
1719
|
-
const request = {
|
|
1720
|
-
...context,
|
|
1721
|
-
id: globalThis.crypto.randomUUID()
|
|
1722
|
-
};
|
|
1723
|
-
if (options.reason !== void 0) {
|
|
1724
|
-
request.reason = options.reason;
|
|
1725
|
-
}
|
|
1726
|
-
if (options.rejectMessage !== void 0) {
|
|
1727
|
-
request.rejectMessage = options.rejectMessage;
|
|
1728
|
-
}
|
|
1729
|
-
await observation?.runObservers.event({
|
|
1730
|
-
name: "tool.approval_requested",
|
|
1731
|
-
attributes: approvalEventAttributes(request, observation.turn)
|
|
1732
|
-
});
|
|
1733
|
-
let decision;
|
|
1734
|
-
try {
|
|
1735
|
-
decision = await this.approvalHandler(request);
|
|
1736
|
-
} catch (error) {
|
|
1737
|
-
if (error instanceof AgentInteractionSignal) {
|
|
1738
|
-
throw error;
|
|
1739
|
-
}
|
|
1740
|
-
await observation?.runObservers.event({
|
|
1741
|
-
name: "tool.approval_failed",
|
|
1742
|
-
level: "ERROR",
|
|
1743
|
-
attributes: {
|
|
1744
|
-
...approvalEventAttributes(request, observation.turn),
|
|
1745
|
-
errorName: error instanceof Error ? error.name : typeof error
|
|
1746
|
-
}
|
|
1747
|
-
});
|
|
1748
|
-
throw error;
|
|
1749
|
-
}
|
|
1750
|
-
const attributes = {
|
|
1751
|
-
...approvalEventAttributes(request, observation?.turn ?? 0),
|
|
1752
|
-
approved: decision.approved
|
|
1753
|
-
};
|
|
1754
|
-
if (decision.reason !== void 0) attributes.decisionReason = decision.reason;
|
|
1755
|
-
await observation?.runObservers.event({
|
|
1756
|
-
name: "tool.approval_resolved",
|
|
1757
|
-
attributes
|
|
1758
|
-
});
|
|
1759
|
-
if (decision.approved) {
|
|
1760
|
-
return { approved: true };
|
|
1761
|
-
}
|
|
1762
|
-
return {
|
|
1763
|
-
approved: false,
|
|
1764
|
-
result: decision.reason ?? request.rejectMessage ?? "Tool approval was rejected."
|
|
1765
|
-
};
|
|
1766
|
-
}
|
|
1767
|
-
};
|
|
1768
|
-
function createApprovalContext(input, hookArgs, agent, run) {
|
|
1769
|
-
const approvalRun = {
|
|
1770
|
-
agentId: agent.id,
|
|
1771
|
-
runId: run.runId
|
|
1772
|
-
};
|
|
1773
|
-
if (run.sessionId !== void 0) {
|
|
1774
|
-
approvalRun.sessionId = run.sessionId;
|
|
1775
|
-
}
|
|
1776
|
-
if (run.metadata !== void 0) {
|
|
1777
|
-
approvalRun.metadata = run.metadata;
|
|
1778
|
-
}
|
|
1779
|
-
const context = {
|
|
1780
|
-
toolName: hookArgs.toolName,
|
|
1781
|
-
args: lifecycleSnapshot(input),
|
|
1782
|
-
rawArgs: hookArgs.args,
|
|
1783
|
-
toolCallId: hookArgs.toolCallId,
|
|
1784
|
-
internalCallId: hookArgs.internalCallId,
|
|
1785
|
-
run: approvalRun
|
|
1786
|
-
};
|
|
1787
|
-
if (hookArgs.callId !== void 0) {
|
|
1788
|
-
context.callId = hookArgs.callId;
|
|
1789
|
-
}
|
|
1790
|
-
return context;
|
|
1791
|
-
}
|
|
1792
|
-
function approvalEventAttributes(request, turn) {
|
|
1793
|
-
const attributes = {
|
|
1794
|
-
turn,
|
|
1795
|
-
approvalId: request.id,
|
|
1796
|
-
toolName: request.toolName,
|
|
1797
|
-
internalCallId: request.internalCallId
|
|
1798
|
-
};
|
|
1799
|
-
if (request.toolCallId !== void 0) attributes.toolCallId = request.toolCallId;
|
|
1800
|
-
if (request.reason !== void 0) attributes.reason = request.reason;
|
|
1801
|
-
return attributes;
|
|
1802
|
-
}
|
|
1803
|
-
function normalizeToolOutputMiddlewareResult(result) {
|
|
1804
|
-
if (typeof result === "string") {
|
|
1805
|
-
return { result };
|
|
1806
|
-
}
|
|
1807
|
-
if (typeof result !== "object" || result === null) {
|
|
1808
|
-
throw new TypeError("Tool output middleware must return text or structured content.");
|
|
1809
|
-
}
|
|
1810
|
-
const prototype = Object.getPrototypeOf(result);
|
|
1811
|
-
if (prototype !== Object.prototype && prototype !== null) {
|
|
1812
|
-
throw new TypeError("Tool output middleware must return text or structured content.");
|
|
1813
|
-
}
|
|
1814
|
-
const keys = Reflect.ownKeys(result);
|
|
1815
|
-
const hasResult = keys.includes("result");
|
|
1816
|
-
const hasStructuredResult = keys.includes("structuredResult");
|
|
1817
|
-
if (hasResult === hasStructuredResult || keys.some((key) => key !== "result" && key !== "structuredResult")) {
|
|
1818
|
-
throw new TypeError(
|
|
1819
|
-
"Tool output middleware must return exactly one of result or structuredResult."
|
|
1820
|
-
);
|
|
1821
|
-
}
|
|
1822
|
-
if (hasResult) {
|
|
1823
|
-
const descriptor2 = Object.getOwnPropertyDescriptor(result, "result");
|
|
1824
|
-
if (descriptor2 === void 0 || !("value" in descriptor2) || typeof descriptor2.value !== "string") {
|
|
1825
|
-
throw new TypeError("Tool output middleware result must be a string.");
|
|
1826
|
-
}
|
|
1827
|
-
return { result: descriptor2.value };
|
|
1828
|
-
}
|
|
1829
|
-
const descriptor = Object.getOwnPropertyDescriptor(result, "structuredResult");
|
|
1830
|
-
if (descriptor === void 0 || !("value" in descriptor)) {
|
|
1831
|
-
throw new TypeError("Tool output middleware structuredResult must be valid tool content.");
|
|
1832
|
-
}
|
|
1833
|
-
const normalized = normalizeToolResultOutput(ToolOutput.content(descriptor.value));
|
|
1834
|
-
if (normalized.type !== "content") {
|
|
1835
|
-
throw new TypeError("Tool output middleware structuredResult must be valid tool content.");
|
|
1836
|
-
}
|
|
1837
|
-
return { structuredResult: normalized.value };
|
|
1838
|
-
}
|
|
1839
|
-
function toolTraceMetadata(tool) {
|
|
1840
|
-
if (tool === void 0) {
|
|
1841
|
-
return void 0;
|
|
1842
|
-
}
|
|
1843
|
-
const result = {
|
|
1844
|
-
approvalRequired: toolMayRequireApproval(tool.requiresApproval)
|
|
1845
|
-
};
|
|
1846
|
-
if (isMcpTool(tool)) {
|
|
1847
|
-
result.mcpServerName = tool.mcp.serverName;
|
|
1848
|
-
result.mcpRemoteName = tool.mcp.remoteName;
|
|
1849
|
-
}
|
|
1850
|
-
return result;
|
|
1851
|
-
}
|
|
1852
|
-
function toolErrorArgs(turn, toolCall, internalCallId, args, error) {
|
|
1853
|
-
let observerArgs = {
|
|
1854
|
-
turn,
|
|
1855
|
-
toolCall,
|
|
1856
|
-
toolName: toolCall.toolName,
|
|
1857
|
-
internalCallId,
|
|
1858
|
-
args,
|
|
1859
|
-
error
|
|
1860
|
-
};
|
|
1861
|
-
if (toolCall.callId !== void 0) {
|
|
1862
|
-
observerArgs = { ...observerArgs, toolCallId: toolCall.callId };
|
|
1863
|
-
}
|
|
1864
|
-
return observerArgs;
|
|
1865
|
-
}
|
|
1866
|
-
var ToolObserverScope = class {
|
|
1867
|
-
constructor(observers) {
|
|
1868
|
-
this.observers = observers;
|
|
1869
|
-
}
|
|
1870
|
-
observers;
|
|
1871
|
-
terminal = false;
|
|
1872
|
-
streamEvent(args) {
|
|
1873
|
-
return this.observers?.streamEvent(args);
|
|
1874
|
-
}
|
|
1875
|
-
async end(args) {
|
|
1876
|
-
if (this.terminal) return;
|
|
1877
|
-
this.terminal = true;
|
|
1878
|
-
await this.observers?.end(args);
|
|
1879
|
-
}
|
|
1880
|
-
async suspend(args) {
|
|
1881
|
-
if (this.terminal) return;
|
|
1882
|
-
this.terminal = true;
|
|
1883
|
-
await this.observers?.suspend(args);
|
|
1884
|
-
}
|
|
1885
|
-
async error(args) {
|
|
1886
|
-
if (this.terminal) return;
|
|
1887
|
-
this.terminal = true;
|
|
1888
|
-
await this.observers?.error(args);
|
|
1889
|
-
}
|
|
1890
|
-
};
|
|
1891
|
-
function toolOutputToText(output) {
|
|
1892
|
-
switch (output.type) {
|
|
1893
|
-
case "text":
|
|
1894
|
-
case "error-text":
|
|
1895
|
-
return output.value;
|
|
1896
|
-
case "json":
|
|
1897
|
-
case "error-json":
|
|
1898
|
-
return JSON.stringify(output.value);
|
|
1899
|
-
case "content":
|
|
1900
|
-
return toolResultContentToText(output.value);
|
|
1901
|
-
case "execution-denied":
|
|
1902
|
-
return output.reason ?? "Tool execution was denied.";
|
|
1903
|
-
}
|
|
1904
|
-
}
|
|
1905
|
-
function toolOutputToStructuredResult(output) {
|
|
1906
|
-
return output.type === "content" ? output.value : void 0;
|
|
1907
|
-
}
|
|
1908
|
-
function agentToolEventPayload(toolCall, internalCallId, event) {
|
|
1909
|
-
if (typeof event.agentId !== "string" || event.agentId.length === 0) {
|
|
1910
|
-
return void 0;
|
|
1911
|
-
}
|
|
1912
|
-
const payload = {
|
|
1913
|
-
type: "agent_tool_event",
|
|
1914
|
-
toolName: toolCall.toolName,
|
|
1915
|
-
internalCallId,
|
|
1916
|
-
agentId: event.agentId,
|
|
1917
|
-
event: event.event
|
|
1918
|
-
};
|
|
1919
|
-
if (toolCall.callId !== void 0) {
|
|
1920
|
-
payload.toolCallId = toolCall.callId;
|
|
1921
|
-
}
|
|
1922
|
-
if (event.agentName !== void 0) {
|
|
1923
|
-
payload.agentName = event.agentName;
|
|
1924
|
-
}
|
|
1925
|
-
return payload;
|
|
1926
|
-
}
|
|
1927
|
-
|
|
1928
|
-
// src/internal/agent-runtime/agent-run.ts
|
|
1929
|
-
async function settleFailureCleanup(operations) {
|
|
1930
|
-
for (const operation of operations) {
|
|
1931
|
-
try {
|
|
1932
|
-
await operation();
|
|
1933
|
-
} catch {
|
|
1934
|
-
}
|
|
1935
|
-
}
|
|
1936
|
-
}
|
|
1937
|
-
var AgentRun = class _AgentRun {
|
|
1938
|
-
constructor(agent, promptMessage, initialHistory = [], options = {}) {
|
|
1939
|
-
this.agent = agent;
|
|
1940
|
-
this.promptMessage = promptMessage;
|
|
1941
|
-
this.chatHistory = initialHistory;
|
|
1942
|
-
this.maxTurnCount = assertNonnegativeSafeInteger(
|
|
1943
|
-
options.maxTurns ?? agent.defaultMaxTurns ?? 0,
|
|
1944
|
-
"maxTurns"
|
|
1945
|
-
);
|
|
1946
|
-
const internalOptions = getInternalAgentRunOptions(options);
|
|
1947
|
-
this.activeHook = internalOptions?.hook;
|
|
1948
|
-
this.onInternalFailure = internalOptions?.onFailure;
|
|
1949
|
-
this.onInternalMemoryCompaction = internalOptions?.onMemoryCompaction;
|
|
1950
|
-
this.requestedRunId = normalizeRequestedRunId(internalOptions?.runId);
|
|
1951
|
-
this.activeLifecycle = composeAgentLifecycle(agent.lifecycle, options.lifecycle);
|
|
1952
|
-
this.guardrailPolicies = options.guardrails === void 0 ? [...agent.guardrails] : appendGuardrailPolicies([...agent.guardrails], options.guardrails);
|
|
1953
|
-
const configuredConcurrency = assertPositiveSafeInteger(
|
|
1954
|
-
options.toolConcurrency ?? 1,
|
|
1955
|
-
"toolConcurrency"
|
|
1956
|
-
);
|
|
1957
|
-
this.concurrency = this.activeHook !== void 0 || agent.tools.some(
|
|
1958
|
-
(tool) => toolMayRequireApproval(tool.requiresApproval) || isQuestionTool(tool)
|
|
1959
|
-
) ? 1 : configuredConcurrency;
|
|
1960
|
-
this.traceOptions = options.trace;
|
|
1961
|
-
const retrySetting = options.retries === void 0 ? agent.retries : options.retries;
|
|
1962
|
-
this.completionRetryOptions = retrySetting === void 0 || retrySetting === false ? void 0 : resolveRetryOptions(retrySetting);
|
|
1963
|
-
this.requestMiddlewares = [...options.middlewares ?? []];
|
|
1964
|
-
this.controls = mergeCompletionControlValues(agent.controls, options.controls);
|
|
1965
|
-
this.memoryScope = options.memoryScope;
|
|
1966
|
-
this.memoryRecorder = new AgentRunMemory(agent, options.memoryScope, initialHistory);
|
|
1967
|
-
this.continuationState = options.continuationState;
|
|
1968
|
-
this.interactionResponse = options.interactionResponse;
|
|
1969
|
-
if (options.continuationState !== void 0) {
|
|
1970
|
-
this.steeringMessages.push(
|
|
1971
|
-
...options.continuationState.steering.map((entry) => ({
|
|
1972
|
-
id: entry.id,
|
|
1973
|
-
messages: [...entry.messages]
|
|
1974
|
-
}))
|
|
1975
|
-
);
|
|
1976
|
-
}
|
|
1977
|
-
this.resumedFrom = options.sourceRunId === void 0 || options.interactionId === void 0 ? void 0 : { runId: options.sourceRunId, interactionId: options.interactionId };
|
|
1978
|
-
this.linkExternalAbortSignal(options.abortSignal);
|
|
1979
|
-
}
|
|
1980
|
-
agent;
|
|
1981
|
-
promptMessage;
|
|
1982
|
-
chatHistory;
|
|
1983
|
-
maxTurnCount;
|
|
1984
|
-
activeHook;
|
|
1985
|
-
activeLifecycle;
|
|
1986
|
-
guardrailPolicies;
|
|
1987
|
-
guardrailDecisions = [];
|
|
1988
|
-
concurrency;
|
|
1989
|
-
traceOptions;
|
|
1990
|
-
completionRetryOptions;
|
|
1991
|
-
requestMiddlewares;
|
|
1992
|
-
controls;
|
|
1993
|
-
steeringMessages = [];
|
|
1994
|
-
runState = "idle";
|
|
1995
|
-
memoryRecorder;
|
|
1996
|
-
memoryScope;
|
|
1997
|
-
onInternalFailure;
|
|
1998
|
-
onInternalMemoryCompaction;
|
|
1999
|
-
memoryCompaction;
|
|
2000
|
-
requestedRunId;
|
|
2001
|
-
continuationState;
|
|
2002
|
-
interactionResponse;
|
|
2003
|
-
resumedFrom;
|
|
2004
|
-
currentMessages = [];
|
|
2005
|
-
cancellationError;
|
|
2006
|
-
activeGeneration;
|
|
2007
|
-
validatedStructuredOutput;
|
|
2008
|
-
failedCompletionUsage = Usage.empty();
|
|
2009
|
-
abortController = new AbortController();
|
|
2010
|
-
removeExternalAbortListener;
|
|
2011
|
-
static fromAgent(agent, options) {
|
|
2012
|
-
const normalized = normalizeAgentInput(agent.id, options);
|
|
2013
|
-
if (normalized.scope !== void 0 && agent.memory === void 0) {
|
|
2014
|
-
throw new TypeError(`Agent "${agent.id}" cannot use a session without a memory store.`);
|
|
2015
|
-
}
|
|
2016
|
-
return new _AgentRun(agent, normalized.prompt, normalized.history, {
|
|
2017
|
-
...options,
|
|
2018
|
-
memoryScope: normalized.scope,
|
|
2019
|
-
continuationState: normalized.continuationState,
|
|
2020
|
-
interactionResponse: normalized.interactionResponse,
|
|
2021
|
-
sourceRunId: normalized.sourceRunId,
|
|
2022
|
-
interactionId: normalized.interactionId
|
|
2023
|
-
});
|
|
2024
|
-
}
|
|
2025
|
-
steer(input) {
|
|
2026
|
-
if (this.isTerminal() || this.cancellationError !== void 0) {
|
|
2027
|
-
throw new AgentStreamClosedError();
|
|
2028
|
-
}
|
|
2029
|
-
const receipt = Object.freeze({
|
|
2030
|
-
id: globalThis.crypto.randomUUID(),
|
|
2031
|
-
status: "queued"
|
|
2032
|
-
});
|
|
2033
|
-
this.steeringMessages.push({ id: receipt.id, messages: normalizeSteeringInput(input) });
|
|
2034
|
-
return receipt;
|
|
2035
|
-
}
|
|
2036
|
-
cancel(reason) {
|
|
2037
|
-
if (this.isTerminal() || this.cancellationError !== void 0) {
|
|
2038
|
-
return this.cancellationError;
|
|
2039
|
-
}
|
|
2040
|
-
const messages = this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];
|
|
2041
|
-
const error = new AgentRunCancelledError([...this.chatHistory, ...messages], reason);
|
|
2042
|
-
this.setCancellationError(error);
|
|
2043
|
-
return error;
|
|
2044
|
-
}
|
|
2045
|
-
setCancellationError(error) {
|
|
2046
|
-
this.cancellationError = error;
|
|
2047
|
-
if (!this.abortController.signal.aborted) this.abortController.abort(error);
|
|
2048
|
-
}
|
|
2049
|
-
async generate() {
|
|
2050
|
-
this.startRun();
|
|
2051
|
-
const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();
|
|
2052
|
-
let usage = Usage.empty();
|
|
2053
|
-
let currentTurns = 0;
|
|
2054
|
-
let lastPrompt = this.promptMessage;
|
|
2055
|
-
let newMessages = [this.promptMessage];
|
|
2056
|
-
let runObservers;
|
|
2057
|
-
let pendingTurnMessages = [];
|
|
2058
|
-
try {
|
|
2059
|
-
this.throwIfCancelled();
|
|
2060
|
-
const memoryPreparation = this.continuationState === void 0 ? await this.memoryRecorder.prepareHistory(
|
|
2061
|
-
runId,
|
|
2062
|
-
newMessages,
|
|
2063
|
-
this.abortController.signal
|
|
2064
|
-
) : void 0;
|
|
2065
|
-
if (memoryPreparation !== void 0) {
|
|
2066
|
-
this.chatHistory = memoryPreparation.history;
|
|
2067
|
-
usage = Usage.add(usage, memoryPreparation.usage);
|
|
2068
|
-
this.memoryCompaction = memoryPreparation.compaction;
|
|
2069
|
-
await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);
|
|
2070
|
-
}
|
|
2071
|
-
runObservers = await this.startRunObservers(runId);
|
|
2072
|
-
if (memoryPreparation !== void 0) {
|
|
2073
|
-
await this.recordMemoryCompaction(memoryPreparation, runObservers);
|
|
2074
|
-
}
|
|
2075
|
-
this.throwIfCancelled();
|
|
2076
|
-
await this.activeLifecycle?.onStart?.({
|
|
2077
|
-
runId,
|
|
2078
|
-
input: lifecycleSnapshot(this.promptMessage),
|
|
2079
|
-
history: lifecycleSnapshot(this.chatHistory),
|
|
2080
|
-
maxTurns: this.maxTurnCount
|
|
2081
|
-
});
|
|
2082
|
-
if (this.continuationState === void 0) {
|
|
2083
|
-
const inputResult = await runInputGuardrails(this.guardrailPolicies, {
|
|
2084
|
-
prompt: this.promptMessage,
|
|
2085
|
-
history: this.chatHistory,
|
|
2086
|
-
inputText: textFromMessage(this.promptMessage),
|
|
2087
|
-
run: this.guardrailRunContext(runId)
|
|
2088
|
-
});
|
|
2089
|
-
for (const decision of inputResult.decisions) {
|
|
2090
|
-
await this.recordGuardrailDecision(decision, runObservers);
|
|
2091
|
-
}
|
|
2092
|
-
this.promptMessage = inputResult.prompt;
|
|
2093
|
-
if (inputResult.blocked) {
|
|
2094
|
-
const text = inputResult.message ?? "The request was blocked by a guardrail.";
|
|
2095
|
-
const result = {
|
|
2096
|
-
type: "blocked",
|
|
2097
|
-
stage: "input",
|
|
2098
|
-
...blockedOutcomeDetails(
|
|
2099
|
-
this.guardrailDecisions,
|
|
2100
|
-
"The request was blocked by a guardrail."
|
|
2101
|
-
),
|
|
2102
|
-
runId,
|
|
2103
|
-
text,
|
|
2104
|
-
usage,
|
|
2105
|
-
messages: [this.promptMessage, { role: "assistant", content: text }],
|
|
2106
|
-
trace: runObservers.trace,
|
|
2107
|
-
guardrails: [...this.guardrailDecisions],
|
|
2108
|
-
...this.memoryCompactionResult()
|
|
2109
|
-
};
|
|
2110
|
-
if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
|
|
2111
|
-
this.runState = "closing";
|
|
2112
|
-
await this.runLifecycleFinish(result);
|
|
2113
|
-
await runObservers.end(observerRunEnd(result));
|
|
2114
|
-
this.runState = "completed";
|
|
2115
|
-
this.disposeAbortLink();
|
|
2116
|
-
return result;
|
|
2117
|
-
}
|
|
2118
|
-
}
|
|
2119
|
-
newMessages = [this.promptMessage];
|
|
2120
|
-
await this.memoryRecorder.commitAcceptedInput(runId, newMessages);
|
|
2121
|
-
pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
|
|
2122
|
-
await this.runRunStartHook(newMessages);
|
|
2123
|
-
if (this.continuationState !== void 0) {
|
|
2124
|
-
const interactionAttributes = {};
|
|
2125
|
-
if (this.resumedFrom?.runId !== void 0) {
|
|
2126
|
-
interactionAttributes.sourceRunId = this.resumedFrom.runId;
|
|
2127
|
-
}
|
|
2128
|
-
if (this.resumedFrom?.interactionId !== void 0) {
|
|
2129
|
-
interactionAttributes.interactionId = this.resumedFrom.interactionId;
|
|
2130
|
-
}
|
|
2131
|
-
if (this.interactionResponse?.type !== void 0) {
|
|
2132
|
-
interactionAttributes.interactionType = this.interactionResponse.type;
|
|
2133
|
-
}
|
|
2134
|
-
await runObservers.event({
|
|
2135
|
-
name: "agent.interaction_response",
|
|
2136
|
-
attributes: interactionAttributes
|
|
2137
|
-
});
|
|
2138
|
-
try {
|
|
2139
|
-
const toolResults = await this.resolveContinuationTools(
|
|
2140
|
-
runId,
|
|
2141
|
-
newMessages,
|
|
2142
|
-
void 0,
|
|
2143
|
-
void 0,
|
|
2144
|
-
{
|
|
2145
|
-
turn: 1,
|
|
2146
|
-
runObservers
|
|
2147
|
-
}
|
|
2148
|
-
);
|
|
2149
|
-
const toolMessage = { role: "tool", content: toolResults };
|
|
2150
|
-
newMessages.push(toolMessage);
|
|
2151
|
-
await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);
|
|
2152
|
-
await this.drainSteeringMessages(runId, 1, newMessages, pendingTurnMessages);
|
|
2153
|
-
await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);
|
|
2154
|
-
} catch (error) {
|
|
2155
|
-
if (error instanceof ToolExecutionSuspension) {
|
|
2156
|
-
return this.finishSuspension({
|
|
2157
|
-
runId,
|
|
2158
|
-
turn: 1,
|
|
2159
|
-
usage,
|
|
2160
|
-
newMessages,
|
|
2161
|
-
pendingTurnMessages,
|
|
2162
|
-
runObservers,
|
|
2163
|
-
suspension: error,
|
|
2164
|
-
uncommittedMessages: []
|
|
2165
|
-
});
|
|
2166
|
-
}
|
|
2167
|
-
throw error;
|
|
2168
|
-
}
|
|
2169
|
-
}
|
|
2170
|
-
while (currentTurns <= this.maxTurnCount) {
|
|
2171
|
-
const prompt = newMessages.at(-1);
|
|
2172
|
-
if (prompt === void 0) {
|
|
2173
|
-
throw new Error("AgentRun requires at least one message");
|
|
2174
|
-
}
|
|
2175
|
-
lastPrompt = prompt;
|
|
2176
|
-
currentTurns += 1;
|
|
2177
|
-
const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];
|
|
2178
|
-
await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);
|
|
2179
|
-
await this.runCompletionCallHook(prompt, historyForRequest, newMessages);
|
|
2180
|
-
const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);
|
|
2181
|
-
let response;
|
|
2182
|
-
try {
|
|
2183
|
-
response = await this.runCompletion(request, currentTurns, runObservers);
|
|
2184
|
-
} catch (error) {
|
|
2185
|
-
await settleFailureCleanup([
|
|
2186
|
-
() => this.runCompletionErrorHook(prompt, error, newMessages)
|
|
2187
|
-
]);
|
|
2188
|
-
throw error;
|
|
2189
|
-
}
|
|
2190
|
-
response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
|
|
2191
|
-
try {
|
|
2192
|
-
assertCompletionResponseIntegrity({ response });
|
|
2193
|
-
} catch (error) {
|
|
2194
|
-
const providerOutputUsage = completionProviderOutputErrorUsage(error);
|
|
2195
|
-
if (providerOutputUsage !== void 0) usage = Usage.add(usage, providerOutputUsage);
|
|
2196
|
-
throw error;
|
|
2197
|
-
}
|
|
2198
|
-
usage = Usage.add(usage, response.usage);
|
|
2199
|
-
this.updateRunProgress(newMessages);
|
|
2200
|
-
await this.runCompletionResponseHook(prompt, response, newMessages);
|
|
2201
|
-
await this.runTurnEndHook(currentTurns, response, newMessages);
|
|
2202
|
-
await this.activeLifecycle?.onStepFinish?.({
|
|
2203
|
-
runId,
|
|
2204
|
-
step: currentTurns,
|
|
2205
|
-
response: lifecycleSnapshot(response),
|
|
2206
|
-
usage: lifecycleSnapshot(usage)
|
|
2207
|
-
});
|
|
2208
|
-
const toolCalls = response.choice.filter(
|
|
2209
|
-
(item) => item.type === "tool-call"
|
|
2210
|
-
);
|
|
2211
|
-
const assistantMessage = this.generatedAssistantMessage(response, request);
|
|
2212
|
-
newMessages.push(assistantMessage);
|
|
2213
|
-
if (toolCalls.length === 0) {
|
|
2214
|
-
if (this.steeringMessages.length > 0) {
|
|
2215
|
-
await this.memoryRecorder.commitMessages(
|
|
2216
|
-
runId,
|
|
2217
|
-
currentTurns,
|
|
2218
|
-
[assistantMessage],
|
|
2219
|
-
pendingTurnMessages
|
|
2220
|
-
);
|
|
2221
|
-
}
|
|
2222
|
-
const appliedSteering = await this.drainSteeringMessages(
|
|
2223
|
-
runId,
|
|
2224
|
-
currentTurns,
|
|
2225
|
-
newMessages,
|
|
2226
|
-
pendingTurnMessages,
|
|
2227
|
-
{ closeWhenEmpty: true }
|
|
2228
|
-
);
|
|
2229
|
-
if (appliedSteering.length > 0) {
|
|
2230
|
-
for (const receipt of appliedSteering) {
|
|
2231
|
-
await runObservers.event({
|
|
2232
|
-
name: "agent.steering_applied",
|
|
2233
|
-
attributes: { id: receipt.id, turn: currentTurns }
|
|
2234
|
-
});
|
|
2235
|
-
}
|
|
2236
|
-
await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
|
|
2237
|
-
continue;
|
|
2238
|
-
}
|
|
2239
|
-
const guardedOutput = await this.runOutputGuardrailsForResponse(
|
|
2240
|
-
runId,
|
|
2241
|
-
usage,
|
|
2242
|
-
response,
|
|
2243
|
-
newMessages,
|
|
2244
|
-
runObservers
|
|
2245
|
-
);
|
|
2246
|
-
response = guardedOutput.response;
|
|
2247
|
-
const finalAssistantMessage = this.generatedAssistantMessage(response, request);
|
|
2248
|
-
newMessages[newMessages.length - 1] = finalAssistantMessage;
|
|
2249
|
-
await this.memoryRecorder.commitMessages(
|
|
2250
|
-
runId,
|
|
2251
|
-
currentTurns,
|
|
2252
|
-
[finalAssistantMessage],
|
|
2253
|
-
pendingTurnMessages
|
|
2254
|
-
);
|
|
2255
|
-
const result = this.createTerminalResult(
|
|
2256
|
-
runId,
|
|
2257
|
-
guardedOutput.text,
|
|
2258
|
-
guardedOutput.blocked,
|
|
2259
|
-
usage,
|
|
2260
|
-
newMessages,
|
|
2261
|
-
runObservers
|
|
2262
|
-
);
|
|
2263
|
-
if (result.type === "response") {
|
|
2264
|
-
await this.runRunEndHook(result, newMessages);
|
|
2265
|
-
}
|
|
2266
|
-
await this.memoryRecorder.commitCompletedRun(
|
|
2267
|
-
runId,
|
|
2268
|
-
currentTurns,
|
|
2269
|
-
newMessages,
|
|
2270
|
-
pendingTurnMessages
|
|
2271
|
-
);
|
|
2272
|
-
await this.runLifecycleFinish(result);
|
|
2273
|
-
await runObservers.end(observerRunEnd(result));
|
|
2274
|
-
this.runState = "completed";
|
|
2275
|
-
this.disposeAbortLink();
|
|
2276
|
-
return result;
|
|
2277
|
-
}
|
|
2278
|
-
this.updateRunProgress(newMessages);
|
|
2279
|
-
let toolResults;
|
|
2280
|
-
try {
|
|
2281
|
-
toolResults = await this.executeToolCalls(
|
|
2282
|
-
runId,
|
|
2283
|
-
toolCalls,
|
|
2284
|
-
newMessages,
|
|
2285
|
-
void 0,
|
|
2286
|
-
void 0,
|
|
2287
|
-
{
|
|
2288
|
-
turn: currentTurns,
|
|
2289
|
-
runObservers,
|
|
2290
|
-
toolDefinitions: request.tools
|
|
2291
|
-
}
|
|
2292
|
-
);
|
|
2293
|
-
} catch (error) {
|
|
2294
|
-
if (error instanceof ToolExecutionSuspension) {
|
|
2295
|
-
return this.finishSuspension({
|
|
2296
|
-
runId,
|
|
2297
|
-
turn: currentTurns,
|
|
2298
|
-
usage,
|
|
2299
|
-
newMessages,
|
|
2300
|
-
pendingTurnMessages,
|
|
2301
|
-
runObservers,
|
|
2302
|
-
suspension: error,
|
|
2303
|
-
uncommittedMessages: [assistantMessage]
|
|
2304
|
-
});
|
|
2305
|
-
}
|
|
2306
|
-
throw error;
|
|
2307
|
-
}
|
|
2308
|
-
const toolMessage = { role: "tool", content: toolResults };
|
|
2309
|
-
newMessages.push(toolMessage);
|
|
2310
|
-
await this.memoryRecorder.commitMessages(
|
|
2311
|
-
runId,
|
|
2312
|
-
currentTurns,
|
|
2313
|
-
[assistantMessage, toolMessage],
|
|
2314
|
-
pendingTurnMessages
|
|
2315
|
-
);
|
|
2316
|
-
await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);
|
|
2317
|
-
await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
|
|
2318
|
-
}
|
|
2319
|
-
throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
|
|
2320
|
-
} catch (error) {
|
|
2321
|
-
if (error instanceof MemoryCompactionError && error.usage !== void 0) {
|
|
2322
|
-
usage = Usage.add(usage, error.usage);
|
|
2323
|
-
}
|
|
2324
|
-
const failedCompletionUsage = this.takeFailedCompletionUsage();
|
|
2325
|
-
if (error instanceof AgentStructuredOutputError) {
|
|
2326
|
-
usage = Usage.add(usage, error.usage);
|
|
2327
|
-
} else {
|
|
2328
|
-
usage = Usage.add(usage, failedCompletionUsage);
|
|
2329
|
-
}
|
|
2330
|
-
this.runState = "closing";
|
|
2331
|
-
const runError = this.normalizeRunError(error);
|
|
2332
|
-
const reportedError = await this.reportRunFailure(
|
|
2333
|
-
runError,
|
|
2334
|
-
runId,
|
|
2335
|
-
usage,
|
|
2336
|
-
newMessages,
|
|
2337
|
-
runObservers
|
|
2338
|
-
);
|
|
2339
|
-
this.runState = reportedError instanceof AgentRunCancelledError ? "cancelled" : "errored";
|
|
2340
|
-
this.disposeAbortLink();
|
|
2341
|
-
throw reportedError;
|
|
2342
|
-
}
|
|
2343
|
-
}
|
|
2344
|
-
async *events() {
|
|
2345
|
-
this.startRun();
|
|
2346
|
-
const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();
|
|
2347
|
-
let usage = Usage.empty();
|
|
2348
|
-
let currentTurns = 0;
|
|
2349
|
-
let lastPrompt = this.promptMessage;
|
|
2350
|
-
let newMessages = [this.promptMessage];
|
|
2351
|
-
const bufferOutputDeltas = hasEnforcedOutputGuardrails(this.guardrailPolicies);
|
|
2352
|
-
let runObservers;
|
|
2353
|
-
let pendingTurnMessages = [];
|
|
2354
|
-
try {
|
|
2355
|
-
this.throwIfCancelled();
|
|
2356
|
-
const memoryPreparation = this.continuationState === void 0 ? await this.memoryRecorder.prepareHistory(
|
|
2357
|
-
runId,
|
|
2358
|
-
newMessages,
|
|
2359
|
-
this.abortController.signal
|
|
2360
|
-
) : void 0;
|
|
2361
|
-
if (memoryPreparation !== void 0) {
|
|
2362
|
-
this.chatHistory = memoryPreparation.history;
|
|
2363
|
-
usage = Usage.add(usage, memoryPreparation.usage);
|
|
2364
|
-
this.memoryCompaction = memoryPreparation.compaction;
|
|
2365
|
-
await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);
|
|
2366
|
-
}
|
|
2367
|
-
runObservers = await this.startRunObservers(runId);
|
|
2368
|
-
if (memoryPreparation !== void 0) {
|
|
2369
|
-
await this.recordMemoryCompaction(memoryPreparation, runObservers);
|
|
2370
|
-
}
|
|
2371
|
-
if (memoryPreparation?.compaction !== void 0) {
|
|
2372
|
-
yield { type: "memory_compaction", ...memoryPreparation.compaction };
|
|
2373
|
-
}
|
|
2374
|
-
this.throwIfCancelled();
|
|
2375
|
-
await this.activeLifecycle?.onStart?.({
|
|
2376
|
-
runId,
|
|
2377
|
-
input: lifecycleSnapshot(this.promptMessage),
|
|
2378
|
-
history: lifecycleSnapshot(this.chatHistory),
|
|
2379
|
-
maxTurns: this.maxTurnCount
|
|
2380
|
-
});
|
|
2381
|
-
if (this.continuationState === void 0) {
|
|
2382
|
-
const inputResult = await runInputGuardrails(this.guardrailPolicies, {
|
|
2383
|
-
prompt: this.promptMessage,
|
|
2384
|
-
history: this.chatHistory,
|
|
2385
|
-
inputText: textFromMessage(this.promptMessage),
|
|
2386
|
-
run: this.guardrailRunContext(runId)
|
|
2387
|
-
});
|
|
2388
|
-
for (const decision of inputResult.decisions) {
|
|
2389
|
-
await this.recordGuardrailDecision(decision, runObservers);
|
|
2390
|
-
yield { type: "guardrail_decision", decision };
|
|
2391
|
-
}
|
|
2392
|
-
this.promptMessage = inputResult.prompt;
|
|
2393
|
-
if (inputResult.blocked) {
|
|
2394
|
-
const text = inputResult.message ?? "The request was blocked by a guardrail.";
|
|
2395
|
-
const result = {
|
|
2396
|
-
type: "blocked",
|
|
2397
|
-
stage: "input",
|
|
2398
|
-
...blockedOutcomeDetails(
|
|
2399
|
-
this.guardrailDecisions,
|
|
2400
|
-
"The request was blocked by a guardrail."
|
|
2401
|
-
),
|
|
2402
|
-
runId,
|
|
2403
|
-
text,
|
|
2404
|
-
usage,
|
|
2405
|
-
messages: [this.promptMessage, { role: "assistant", content: text }],
|
|
2406
|
-
trace: runObservers.trace,
|
|
2407
|
-
guardrails: [...this.guardrailDecisions],
|
|
2408
|
-
...this.memoryCompactionResult()
|
|
2409
|
-
};
|
|
2410
|
-
if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
|
|
2411
|
-
this.runState = "closing";
|
|
2412
|
-
await this.runLifecycleFinish(result);
|
|
2413
|
-
await runObservers.end(observerRunEnd(result));
|
|
2414
|
-
this.runState = "completed";
|
|
2415
|
-
this.disposeAbortLink();
|
|
2416
|
-
yield result;
|
|
2417
|
-
return;
|
|
2418
|
-
}
|
|
2419
|
-
}
|
|
2420
|
-
newMessages = [this.promptMessage];
|
|
2421
|
-
await this.memoryRecorder.commitAcceptedInput(runId, newMessages);
|
|
2422
|
-
pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
|
|
2423
|
-
await this.runRunStartHook(newMessages);
|
|
2424
|
-
if (this.continuationState !== void 0) {
|
|
2425
|
-
const responsePart = this.promptMessage.role === "tool" ? this.promptMessage.content[0] : void 0;
|
|
2426
|
-
if (responsePart === void 0 || responsePart.type === "tool-result") {
|
|
2427
|
-
throw new TypeError("Agent continuation response message is invalid.");
|
|
2428
|
-
}
|
|
2429
|
-
yield {
|
|
2430
|
-
type: "interaction_response",
|
|
2431
|
-
response: responsePart,
|
|
2432
|
-
sourceRunId: this.resumedFrom?.runId ?? this.continuationState.kind
|
|
2433
|
-
};
|
|
2434
|
-
try {
|
|
2435
|
-
const execution = this.executeContinuationToolStream(runId, newMessages, {
|
|
2436
|
-
turn: 1,
|
|
2437
|
-
runObservers
|
|
2438
|
-
});
|
|
2439
|
-
for await (const event of execution.events) {
|
|
2440
|
-
yield { turn: 1, ...event };
|
|
2441
|
-
}
|
|
2442
|
-
const toolResults = await execution.results;
|
|
2443
|
-
const toolMessage = { role: "tool", content: toolResults };
|
|
2444
|
-
newMessages.push(toolMessage);
|
|
2445
|
-
await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);
|
|
2446
|
-
for (const receipt of await this.drainSteeringMessages(
|
|
2447
|
-
runId,
|
|
2448
|
-
1,
|
|
2449
|
-
newMessages,
|
|
2450
|
-
pendingTurnMessages
|
|
2451
|
-
)) {
|
|
2452
|
-
yield { type: "steering_applied", id: receipt.id, turn: 1 };
|
|
2453
|
-
}
|
|
2454
|
-
await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);
|
|
2455
|
-
} catch (error) {
|
|
2456
|
-
if (error instanceof ToolExecutionSuspension) {
|
|
2457
|
-
const result = await this.finishSuspension({
|
|
2458
|
-
runId,
|
|
2459
|
-
turn: 1,
|
|
2460
|
-
usage,
|
|
2461
|
-
newMessages,
|
|
2462
|
-
pendingTurnMessages,
|
|
2463
|
-
runObservers,
|
|
2464
|
-
suspension: error,
|
|
2465
|
-
uncommittedMessages: []
|
|
2466
|
-
});
|
|
2467
|
-
yield result;
|
|
2468
|
-
return;
|
|
2469
|
-
}
|
|
2470
|
-
throw error;
|
|
2471
|
-
}
|
|
2472
|
-
}
|
|
2473
|
-
while (currentTurns <= this.maxTurnCount) {
|
|
2474
|
-
const prompt = newMessages.at(-1);
|
|
2475
|
-
if (prompt === void 0) {
|
|
2476
|
-
throw new Error("AgentRun requires at least one message");
|
|
2477
|
-
}
|
|
2478
|
-
lastPrompt = prompt;
|
|
2479
|
-
currentTurns += 1;
|
|
2480
|
-
const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];
|
|
2481
|
-
yield {
|
|
2482
|
-
type: "turn_start",
|
|
2483
|
-
turn: currentTurns,
|
|
2484
|
-
prompt,
|
|
2485
|
-
history: historyForRequest
|
|
2486
|
-
};
|
|
2487
|
-
await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);
|
|
2488
|
-
await this.runCompletionCallHook(prompt, historyForRequest, newMessages);
|
|
2489
|
-
const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);
|
|
2490
|
-
assertCompletionRequestSupported(this.agent.model, request, { streaming: true });
|
|
2491
|
-
const providerRequest = this.providerTraceRequest(request, { stream: true });
|
|
2492
|
-
const generationStartArgs = this.generationStartArgs(
|
|
2493
|
-
currentTurns,
|
|
2494
|
-
request,
|
|
2495
|
-
providerRequest
|
|
2496
|
-
);
|
|
2497
|
-
const generationObservers = await runObservers.startGeneration(generationStartArgs);
|
|
2498
|
-
this.activeGeneration = { turn: currentTurns, observers: generationObservers };
|
|
2499
|
-
const generationStartedAt = Date.now();
|
|
2500
|
-
yield {
|
|
2501
|
-
type: "generation_start",
|
|
2502
|
-
turn: currentTurns,
|
|
2503
|
-
request,
|
|
2504
|
-
modelInfo: generationStartArgs.modelInfo
|
|
2505
|
-
};
|
|
2506
|
-
const bufferResponseEvents = this.shouldBufferStreamResponseEvents() || this.agent.outputSchema !== void 0;
|
|
2507
|
-
const completionState = {
|
|
2508
|
-
response: void 0,
|
|
2509
|
-
firstDeltaMs: void 0,
|
|
2510
|
-
emittedToolCallIds: /* @__PURE__ */ new Set(),
|
|
2511
|
-
providerErrorUsage: Usage.empty()
|
|
2512
|
-
};
|
|
2513
|
-
let response;
|
|
2514
|
-
try {
|
|
2515
|
-
try {
|
|
2516
|
-
for await (const event of this.streamCompletion({
|
|
2517
|
-
request,
|
|
2518
|
-
turn: currentTurns,
|
|
2519
|
-
bufferResponseEvents,
|
|
2520
|
-
bufferOutputDeltas,
|
|
2521
|
-
generationStartedAt,
|
|
2522
|
-
generationObservers,
|
|
2523
|
-
runObservers,
|
|
2524
|
-
state: completionState
|
|
2525
|
-
})) {
|
|
2526
|
-
yield event;
|
|
2527
|
-
}
|
|
2528
|
-
} finally {
|
|
2529
|
-
usage = Usage.add(usage, completionState.providerErrorUsage);
|
|
2530
|
-
}
|
|
2531
|
-
if (completionState.response === void 0) {
|
|
2532
|
-
throw new Error("Streaming completion ended without a response.");
|
|
2533
|
-
}
|
|
2534
|
-
response = completionState.response;
|
|
2535
|
-
} catch (error) {
|
|
2536
|
-
await settleFailureCleanup([
|
|
2537
|
-
() => this.closeActiveGeneration(error),
|
|
2538
|
-
() => this.runCompletionErrorHook(prompt, error, newMessages)
|
|
2539
|
-
]);
|
|
2540
|
-
throw error;
|
|
2541
|
-
}
|
|
2542
|
-
const { firstDeltaMs, emittedToolCallIds } = completionState;
|
|
2543
|
-
let generationEndArgs = {
|
|
2544
|
-
turn: currentTurns,
|
|
2545
|
-
response
|
|
2546
|
-
};
|
|
2547
|
-
if (firstDeltaMs !== void 0) {
|
|
2548
|
-
generationEndArgs = { ...generationEndArgs, firstDeltaMs };
|
|
2549
|
-
}
|
|
2550
|
-
this.activeGeneration = void 0;
|
|
2551
|
-
await generationObservers.end(generationEndArgs);
|
|
2552
|
-
response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
|
|
2553
|
-
try {
|
|
2554
|
-
assertCompletionResponseIntegrity({ response });
|
|
2555
|
-
} catch (error) {
|
|
2556
|
-
const providerOutputUsage = completionProviderOutputErrorUsage(error);
|
|
2557
|
-
if (providerOutputUsage !== void 0) usage = Usage.add(usage, providerOutputUsage);
|
|
2558
|
-
throw error;
|
|
2559
|
-
}
|
|
2560
|
-
usage = Usage.add(usage, response.usage);
|
|
2561
|
-
this.updateRunProgress(newMessages);
|
|
2562
|
-
await this.runCompletionResponseHook(prompt, response, newMessages);
|
|
2563
|
-
await this.runTurnEndHook(currentTurns, response, newMessages);
|
|
2564
|
-
await this.activeLifecycle?.onStepFinish?.({
|
|
2565
|
-
runId,
|
|
2566
|
-
step: currentTurns,
|
|
2567
|
-
response: lifecycleSnapshot(response),
|
|
2568
|
-
usage: lifecycleSnapshot(usage)
|
|
2569
|
-
});
|
|
2570
|
-
const toolCalls = response.choice.filter(
|
|
2571
|
-
(item) => item.type === "tool-call"
|
|
2572
|
-
);
|
|
2573
|
-
const assistantMessage = this.generatedAssistantMessage(response, request);
|
|
2574
|
-
newMessages.push(assistantMessage);
|
|
2575
|
-
if (toolCalls.length === 0) {
|
|
2576
|
-
let emittedTurnEnd = false;
|
|
2577
|
-
if (!bufferOutputDeltas) {
|
|
2578
|
-
if (bufferResponseEvents) {
|
|
2579
|
-
for (const event of responseStreamEvents(currentTurns, response)) {
|
|
2580
|
-
yield event;
|
|
2581
|
-
}
|
|
2582
|
-
}
|
|
2583
|
-
yield {
|
|
2584
|
-
type: "turn_end",
|
|
2585
|
-
turn: currentTurns,
|
|
2586
|
-
response,
|
|
2587
|
-
firstDeltaMs
|
|
2588
|
-
};
|
|
2589
|
-
emittedTurnEnd = true;
|
|
2590
|
-
}
|
|
2591
|
-
if (this.steeringMessages.length > 0) {
|
|
2592
|
-
await this.memoryRecorder.commitMessages(
|
|
2593
|
-
runId,
|
|
2594
|
-
currentTurns,
|
|
2595
|
-
[assistantMessage],
|
|
2596
|
-
pendingTurnMessages
|
|
2597
|
-
);
|
|
2598
|
-
}
|
|
2599
|
-
const appliedSteering = await this.drainSteeringMessages(
|
|
2600
|
-
runId,
|
|
2601
|
-
currentTurns,
|
|
2602
|
-
newMessages,
|
|
2603
|
-
pendingTurnMessages,
|
|
2604
|
-
{ closeWhenEmpty: true }
|
|
2605
|
-
);
|
|
2606
|
-
for (const receipt of appliedSteering) {
|
|
2607
|
-
yield { type: "steering_applied", id: receipt.id, turn: currentTurns };
|
|
2608
|
-
}
|
|
2609
|
-
if (appliedSteering.length > 0) {
|
|
2610
|
-
await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
|
|
2611
|
-
continue;
|
|
2612
|
-
}
|
|
2613
|
-
for await (const event of this.completeStreamingRun({
|
|
2614
|
-
runId,
|
|
2615
|
-
turn: currentTurns,
|
|
2616
|
-
request,
|
|
2617
|
-
response,
|
|
2618
|
-
firstDeltaMs,
|
|
2619
|
-
usage,
|
|
2620
|
-
newMessages,
|
|
2621
|
-
pendingTurnMessages,
|
|
2622
|
-
runObservers,
|
|
2623
|
-
bufferResponseEvents,
|
|
2624
|
-
bufferOutputDeltas,
|
|
2625
|
-
emittedTurnEnd
|
|
2626
|
-
})) {
|
|
2627
|
-
yield event;
|
|
2628
|
-
}
|
|
2629
|
-
return;
|
|
2630
|
-
}
|
|
2631
|
-
if (bufferResponseEvents) {
|
|
2632
|
-
for (const event of responseStreamEvents(currentTurns, response)) {
|
|
2633
|
-
yield event;
|
|
2634
|
-
}
|
|
2635
|
-
} else {
|
|
2636
|
-
for (const toolCall of toolCalls) {
|
|
2637
|
-
if (!emittedToolCallIds.has(toolCall.toolCallId)) {
|
|
2638
|
-
yield { type: "tool_call", turn: currentTurns, toolCall };
|
|
2639
|
-
}
|
|
2640
|
-
}
|
|
2641
|
-
}
|
|
2642
|
-
this.updateRunProgress(newMessages);
|
|
2643
|
-
yield {
|
|
2644
|
-
type: "turn_end",
|
|
2645
|
-
turn: currentTurns,
|
|
2646
|
-
response,
|
|
2647
|
-
firstDeltaMs
|
|
2648
|
-
};
|
|
2649
|
-
let toolResults;
|
|
2650
|
-
try {
|
|
2651
|
-
const toolExecution = this.executeStreamingToolCalls(runId, toolCalls, newMessages, {
|
|
2652
|
-
turn: currentTurns,
|
|
2653
|
-
runObservers,
|
|
2654
|
-
toolDefinitions: request.tools
|
|
2655
|
-
});
|
|
2656
|
-
for await (const result of toolExecution.events) {
|
|
2657
|
-
yield { turn: currentTurns, ...result };
|
|
2658
|
-
}
|
|
2659
|
-
toolResults = await toolExecution.results;
|
|
2660
|
-
} catch (error) {
|
|
2661
|
-
if (error instanceof ToolExecutionSuspension) {
|
|
2662
|
-
const result = await this.finishSuspension({
|
|
2663
|
-
runId,
|
|
2664
|
-
turn: currentTurns,
|
|
2665
|
-
usage,
|
|
2666
|
-
newMessages,
|
|
2667
|
-
pendingTurnMessages,
|
|
2668
|
-
runObservers,
|
|
2669
|
-
suspension: error,
|
|
2670
|
-
uncommittedMessages: [assistantMessage]
|
|
2671
|
-
});
|
|
2672
|
-
yield result;
|
|
2673
|
-
return;
|
|
2674
|
-
}
|
|
2675
|
-
throw error;
|
|
2676
|
-
}
|
|
2677
|
-
const toolMessage = { role: "tool", content: toolResults };
|
|
2678
|
-
newMessages.push(toolMessage);
|
|
2679
|
-
await this.memoryRecorder.commitMessages(
|
|
2680
|
-
runId,
|
|
2681
|
-
currentTurns,
|
|
2682
|
-
[assistantMessage, toolMessage],
|
|
2683
|
-
pendingTurnMessages
|
|
2684
|
-
);
|
|
2685
|
-
for (const receipt of await this.drainSteeringMessages(
|
|
2686
|
-
runId,
|
|
2687
|
-
currentTurns,
|
|
2688
|
-
newMessages,
|
|
2689
|
-
pendingTurnMessages
|
|
2690
|
-
)) {
|
|
2691
|
-
yield { type: "steering_applied", id: receipt.id, turn: currentTurns };
|
|
2692
|
-
}
|
|
2693
|
-
await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
|
|
2694
|
-
}
|
|
2695
|
-
throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
|
|
2696
|
-
} catch (error) {
|
|
2697
|
-
if (error instanceof MemoryCompactionError && error.usage !== void 0) {
|
|
2698
|
-
usage = Usage.add(usage, error.usage);
|
|
2699
|
-
}
|
|
2700
|
-
if (error instanceof AgentStructuredOutputError) {
|
|
2701
|
-
usage = Usage.add(usage, error.usage);
|
|
2702
|
-
}
|
|
2703
|
-
this.runState = "closing";
|
|
2704
|
-
const runError = this.normalizeRunError(error);
|
|
2705
|
-
const reportedError = await this.reportRunFailure(
|
|
2706
|
-
runError,
|
|
2707
|
-
runId,
|
|
2708
|
-
usage,
|
|
2709
|
-
newMessages,
|
|
2710
|
-
runObservers
|
|
2711
|
-
);
|
|
2712
|
-
this.runState = reportedError instanceof AgentRunCancelledError ? "cancelled" : "errored";
|
|
2713
|
-
const finalUsage = usage;
|
|
2714
|
-
yield { type: "error", error: reportedError, usage: finalUsage };
|
|
2715
|
-
this.disposeAbortLink();
|
|
2716
|
-
return;
|
|
2717
|
-
} finally {
|
|
2718
|
-
if (this.runState === "running" || this.runState === "closing") {
|
|
2719
|
-
const cancellation = this.cancellationError ?? new AgentRunCancelledError([...this.chatHistory, ...newMessages], "Agent stream closed.");
|
|
2720
|
-
this.cancellationError = cancellation;
|
|
2721
|
-
await settleFailureCleanup([() => this.closeActiveGeneration(cancellation)]);
|
|
2722
|
-
await this.reportRunFailure(cancellation, runId, usage, newMessages, runObservers);
|
|
2723
|
-
this.runState = "cancelled";
|
|
2724
|
-
this.disposeAbortLink();
|
|
2725
|
-
}
|
|
2726
|
-
}
|
|
2727
|
-
}
|
|
2728
|
-
async runCompletion(request, turn, runObservers) {
|
|
2729
|
-
assertCompletionRequestSupported(this.agent.model, request);
|
|
2730
|
-
this.validatedStructuredOutput = void 0;
|
|
2731
|
-
this.failedCompletionUsage = Usage.empty();
|
|
2732
|
-
const providerRequest = this.providerTraceRequest(request);
|
|
2733
|
-
const generationObservers = await runObservers.startGeneration(
|
|
2734
|
-
this.generationStartArgs(turn, request, providerRequest)
|
|
2735
|
-
);
|
|
2736
|
-
let currentRequest = request;
|
|
2737
|
-
let failedAttemptUsage = Usage.empty();
|
|
2738
|
-
try {
|
|
2739
|
-
for (let attempt = 1; ; attempt += 1) {
|
|
2740
|
-
let response;
|
|
2741
|
-
try {
|
|
2742
|
-
this.throwIfCancelled();
|
|
2743
|
-
response = await this.agent.model.completion(currentRequest, this.modelCallOptions());
|
|
2744
|
-
assertCompletionResponseIntegrity({ response });
|
|
2745
|
-
} catch (error) {
|
|
2746
|
-
const attemptUsage = completionProviderOutputErrorUsage(error);
|
|
2747
|
-
if (attemptUsage !== void 0) {
|
|
2748
|
-
failedAttemptUsage = Usage.add(failedAttemptUsage, attemptUsage);
|
|
2749
|
-
this.failedCompletionUsage = failedAttemptUsage;
|
|
2750
|
-
}
|
|
2751
|
-
const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
|
|
2752
|
-
if (retryOptions === void 0) {
|
|
2753
|
-
throw error;
|
|
2754
|
-
}
|
|
2755
|
-
await this.scheduleCompletionRetry(
|
|
2756
|
-
error,
|
|
2757
|
-
attempt,
|
|
2758
|
-
turn,
|
|
2759
|
-
false,
|
|
2760
|
-
retryOptions,
|
|
2761
|
-
runObservers,
|
|
2762
|
-
providerOutputRetryEventAttributes(error, failedAttemptUsage)
|
|
2763
|
-
);
|
|
2764
|
-
continue;
|
|
2765
|
-
}
|
|
2766
|
-
const cumulativeUsage = Usage.add(failedAttemptUsage, response.usage);
|
|
2767
|
-
try {
|
|
2768
|
-
this.validateStructuredResponse(response, attempt, cumulativeUsage);
|
|
2769
|
-
} catch (error) {
|
|
2770
|
-
const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
|
|
2771
|
-
if (retryOptions === void 0) {
|
|
2772
|
-
throw error;
|
|
2773
|
-
}
|
|
2774
|
-
failedAttemptUsage = cumulativeUsage;
|
|
2775
|
-
this.failedCompletionUsage = failedAttemptUsage;
|
|
2776
|
-
const retryRequest = structuredOutputRetryRequest(request, response, error);
|
|
2777
|
-
currentRequest = retryRequest.request;
|
|
2778
|
-
await this.scheduleCompletionRetry(
|
|
2779
|
-
error,
|
|
2780
|
-
attempt,
|
|
2781
|
-
turn,
|
|
2782
|
-
false,
|
|
2783
|
-
retryOptions,
|
|
2784
|
-
runObservers,
|
|
2785
|
-
structuredOutputRetryEventAttributes(error, retryRequest)
|
|
2786
|
-
);
|
|
2787
|
-
continue;
|
|
2788
|
-
}
|
|
2789
|
-
const finalResponse = Usage.isEmpty(failedAttemptUsage) ? response : { ...response, usage: cumulativeUsage };
|
|
2790
|
-
await generationObservers.end({ turn, response: finalResponse });
|
|
2791
|
-
this.failedCompletionUsage = Usage.empty();
|
|
2792
|
-
return finalResponse;
|
|
2793
|
-
}
|
|
2794
|
-
} catch (error) {
|
|
2795
|
-
await settleFailureCleanup([() => generationObservers.error({ turn, error })]);
|
|
2796
|
-
throw error;
|
|
2797
|
-
}
|
|
2798
|
-
}
|
|
2799
|
-
async createTurnRequest(prompt, history, turn) {
|
|
2800
|
-
const ragText = extractRagText(prompt);
|
|
2801
|
-
const abortSignal = this.abortController.signal;
|
|
2802
|
-
const documents = await fetchContextDocuments(this.agent, ragText, abortSignal);
|
|
2803
|
-
const toolDefinitions = await fetchToolDefinitions(this.agent, ragText, abortSignal);
|
|
2804
|
-
const request = createCompletionRequest(providerMessages([...history, prompt]), {
|
|
2805
|
-
instructions: this.agent.instructions,
|
|
2806
|
-
documents,
|
|
2807
|
-
tools: [...toolDefinitions, ...getAgentToolState(this.agent).providerTools],
|
|
2808
|
-
temperature: this.agent.temperature,
|
|
2809
|
-
maxTokens: this.agent.maxTokens,
|
|
2810
|
-
providerOptions: this.agent.providerOptions,
|
|
2811
|
-
toolChoice: this.agent.toolChoice,
|
|
2812
|
-
controls: this.controls,
|
|
2813
|
-
outputSchema: getAgentProviderOutputSchema(this.agent)
|
|
2814
|
-
});
|
|
2815
|
-
return this.runCompletionRequestMiddlewares(request, turn);
|
|
2816
|
-
}
|
|
2817
|
-
async *streamCompletion(args) {
|
|
2818
|
-
const model = this.agent.model;
|
|
2819
|
-
if (!isStreamingCompletionModel(model)) {
|
|
2820
|
-
throw new TypeError("Streaming completion requires a streaming-capable model.");
|
|
2821
|
-
}
|
|
2822
|
-
this.validatedStructuredOutput = void 0;
|
|
2823
|
-
let currentRequest = args.request;
|
|
2824
|
-
for (let attempt = 1; ; attempt += 1) {
|
|
2825
|
-
const accumulator = new CompletionStreamAccumulator();
|
|
2826
|
-
let hasProviderProgress = false;
|
|
2827
|
-
let recordedErrorUsage = false;
|
|
2828
|
-
let attemptErrorUsage;
|
|
2829
|
-
try {
|
|
2830
|
-
this.throwIfCancelled();
|
|
2831
|
-
for await (const event of model.streamCompletion(currentRequest, this.modelCallOptions())) {
|
|
2832
|
-
if (event.type === "error") {
|
|
2833
|
-
const eventUsage = event.usage ?? completionProviderOutputErrorUsage(event.error);
|
|
2834
|
-
if (eventUsage !== void 0) {
|
|
2835
|
-
args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, eventUsage);
|
|
2836
|
-
recordedErrorUsage = true;
|
|
2837
|
-
attemptErrorUsage = eventUsage;
|
|
2838
|
-
}
|
|
2839
|
-
throw event.error;
|
|
2840
|
-
}
|
|
2841
|
-
const mapped = accumulator.accept(event);
|
|
2842
|
-
if (event.type === "final") break;
|
|
2843
|
-
if (event.type === "tool_call_delta" || mapped !== void 0) {
|
|
2844
|
-
hasProviderProgress = true;
|
|
2845
|
-
}
|
|
2846
|
-
if (args.state.firstDeltaMs === void 0 && isGenerationDeltaEvent(event.type)) {
|
|
2847
|
-
args.state.firstDeltaMs = Date.now() - args.generationStartedAt;
|
|
2848
|
-
}
|
|
2849
|
-
if (event.type === "tool_call_delta") {
|
|
2850
|
-
yield addTurnToToolCallDelta(args.turn, event);
|
|
2851
|
-
}
|
|
2852
|
-
if (mapped !== void 0) {
|
|
2853
|
-
await args.generationObservers.update?.({ turn: args.turn, delta: mapped });
|
|
2854
|
-
if (mapped.type === "tool_call") {
|
|
2855
|
-
args.state.emittedToolCallIds.add(mapped.toolCall.toolCallId);
|
|
2856
|
-
}
|
|
2857
|
-
const shouldBuffer = args.bufferResponseEvents || args.bufferOutputDeltas && (mapped.type === "text_delta" || mapped.type === "reasoning_delta");
|
|
2858
|
-
if (!shouldBuffer) {
|
|
2859
|
-
yield addTurn(args.turn, mapped);
|
|
2860
|
-
}
|
|
2861
|
-
}
|
|
2862
|
-
}
|
|
2863
|
-
const response = accumulator.response();
|
|
2864
|
-
assertCompletionResponseIntegrity({ response });
|
|
2865
|
-
const cumulativeStructuredUsage = Usage.add(args.state.providerErrorUsage, response.usage);
|
|
2866
|
-
try {
|
|
2867
|
-
this.validateStructuredResponse(response, attempt, cumulativeStructuredUsage);
|
|
2868
|
-
} catch (error) {
|
|
2869
|
-
const retryOptions = this.retryOptionsForFailure(error, attempt, args.turn, true);
|
|
2870
|
-
if (retryOptions === void 0) {
|
|
2871
|
-
if (error instanceof AgentStructuredOutputError) {
|
|
2872
|
-
args.state.providerErrorUsage = Usage.empty();
|
|
2873
|
-
}
|
|
2874
|
-
throw error;
|
|
2875
|
-
}
|
|
2876
|
-
args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, response.usage);
|
|
2877
|
-
args.state.firstDeltaMs = void 0;
|
|
2878
|
-
args.state.emittedToolCallIds.clear();
|
|
2879
|
-
const retryRequest = structuredOutputRetryRequest(args.request, response, error);
|
|
2880
|
-
currentRequest = retryRequest.request;
|
|
2881
|
-
await this.scheduleCompletionRetry(
|
|
2882
|
-
error,
|
|
2883
|
-
attempt,
|
|
2884
|
-
args.turn,
|
|
2885
|
-
true,
|
|
2886
|
-
retryOptions,
|
|
2887
|
-
args.runObservers,
|
|
2888
|
-
structuredOutputRetryEventAttributes(error, retryRequest)
|
|
2889
|
-
);
|
|
2890
|
-
continue;
|
|
2891
|
-
}
|
|
2892
|
-
args.state.response = Usage.isEmpty(args.state.providerErrorUsage) ? response : { ...response, usage: cumulativeStructuredUsage };
|
|
2893
|
-
args.state.providerErrorUsage = Usage.empty();
|
|
2894
|
-
return;
|
|
2895
|
-
} catch (error) {
|
|
2896
|
-
if (!recordedErrorUsage) {
|
|
2897
|
-
const attemptUsage = completionProviderOutputErrorUsage(error);
|
|
2898
|
-
if (attemptUsage !== void 0) {
|
|
2899
|
-
args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, attemptUsage);
|
|
2900
|
-
attemptErrorUsage = attemptUsage;
|
|
2901
|
-
}
|
|
2902
|
-
}
|
|
2903
|
-
const retryOptions = hasProviderProgress ? void 0 : this.retryOptionsForFailure(error, attempt, args.turn, true);
|
|
2904
|
-
if (retryOptions === void 0) {
|
|
2905
|
-
throw error;
|
|
2906
|
-
}
|
|
2907
|
-
await this.scheduleCompletionRetry(
|
|
2908
|
-
error,
|
|
2909
|
-
attempt,
|
|
2910
|
-
args.turn,
|
|
2911
|
-
true,
|
|
2912
|
-
retryOptions,
|
|
2913
|
-
args.runObservers,
|
|
2914
|
-
providerOutputRetryEventAttributes(
|
|
2915
|
-
error,
|
|
2916
|
-
args.state.providerErrorUsage,
|
|
2917
|
-
attemptErrorUsage
|
|
2918
|
-
)
|
|
2919
|
-
);
|
|
2920
|
-
}
|
|
2921
|
-
}
|
|
2922
|
-
}
|
|
2923
|
-
async *completeStreamingRun(args) {
|
|
2924
|
-
const guardedOutput = await this.runOutputGuardrailsForResponse(
|
|
2925
|
-
args.runId,
|
|
2926
|
-
args.usage,
|
|
2927
|
-
args.response,
|
|
2928
|
-
args.newMessages,
|
|
2929
|
-
args.runObservers
|
|
2930
|
-
);
|
|
2931
|
-
for (const decision of guardedOutput.decisions) {
|
|
2932
|
-
yield { type: "guardrail_decision", decision };
|
|
2933
|
-
}
|
|
2934
|
-
const response = guardedOutput.response;
|
|
2935
|
-
const assistantMessage = this.generatedAssistantMessage(response, args.request);
|
|
2936
|
-
args.newMessages[args.newMessages.length - 1] = assistantMessage;
|
|
2937
|
-
await this.memoryRecorder.commitMessages(
|
|
2938
|
-
args.runId,
|
|
2939
|
-
args.turn,
|
|
2940
|
-
[assistantMessage],
|
|
2941
|
-
args.pendingTurnMessages
|
|
2942
|
-
);
|
|
2943
|
-
if (!args.emittedTurnEnd && (args.bufferResponseEvents || args.bufferOutputDeltas)) {
|
|
2944
|
-
for (const event of responseStreamEvents(args.turn, response, args.bufferResponseEvents)) {
|
|
2945
|
-
yield event;
|
|
2946
|
-
}
|
|
2947
|
-
}
|
|
2948
|
-
if (!args.emittedTurnEnd) {
|
|
2949
|
-
yield {
|
|
2950
|
-
type: "turn_end",
|
|
2951
|
-
turn: args.turn,
|
|
2952
|
-
response,
|
|
2953
|
-
firstDeltaMs: args.firstDeltaMs
|
|
2954
|
-
};
|
|
2955
|
-
}
|
|
2956
|
-
const result = this.createTerminalResult(
|
|
2957
|
-
args.runId,
|
|
2958
|
-
guardedOutput.text,
|
|
2959
|
-
guardedOutput.blocked,
|
|
2960
|
-
args.usage,
|
|
2961
|
-
args.newMessages,
|
|
2962
|
-
args.runObservers
|
|
2963
|
-
);
|
|
2964
|
-
if (result.type === "response") {
|
|
2965
|
-
await this.runRunEndHook(result, args.newMessages);
|
|
2966
|
-
}
|
|
2967
|
-
await this.memoryRecorder.commitCompletedRun(
|
|
2968
|
-
args.runId,
|
|
2969
|
-
args.turn,
|
|
2970
|
-
args.newMessages,
|
|
2971
|
-
args.pendingTurnMessages
|
|
2972
|
-
);
|
|
2973
|
-
await this.runLifecycleFinish(result);
|
|
2974
|
-
await args.runObservers.end(observerRunEnd(result));
|
|
2975
|
-
this.runState = "completed";
|
|
2976
|
-
this.disposeAbortLink();
|
|
2977
|
-
yield result;
|
|
2978
|
-
}
|
|
2979
|
-
async finishSuspension(args) {
|
|
2980
|
-
const partialToolMessage = args.suspension.completedResults.length === 0 ? void 0 : { role: "tool", content: [...args.suspension.completedResults] };
|
|
2981
|
-
if (partialToolMessage !== void 0) {
|
|
2982
|
-
args.newMessages.push(partialToolMessage);
|
|
2983
|
-
args.uncommittedMessages.push(partialToolMessage);
|
|
2984
|
-
}
|
|
2985
|
-
await this.memoryRecorder.commitMessages(
|
|
2986
|
-
args.runId,
|
|
2987
|
-
args.turn,
|
|
2988
|
-
args.uncommittedMessages,
|
|
2989
|
-
args.pendingTurnMessages
|
|
2990
|
-
);
|
|
2991
|
-
await this.memoryRecorder.commitCompletedRun(
|
|
2992
|
-
args.runId,
|
|
2993
|
-
args.turn,
|
|
2994
|
-
args.newMessages,
|
|
2995
|
-
args.pendingTurnMessages
|
|
2996
|
-
);
|
|
2997
|
-
this.runState = "closing";
|
|
2998
|
-
const continuationState = {
|
|
2999
|
-
kind: "anvia.agent-continuation",
|
|
3000
|
-
history: [...this.chatHistory],
|
|
3001
|
-
messages: [...args.newMessages],
|
|
3002
|
-
pending: args.suspension.pending,
|
|
3003
|
-
remainingToolCalls: [...args.suspension.remainingToolCalls],
|
|
3004
|
-
steering: this.steeringMessages.map((entry) => ({
|
|
3005
|
-
id: entry.id,
|
|
3006
|
-
messages: [...entry.messages]
|
|
3007
|
-
}))
|
|
3008
|
-
};
|
|
3009
|
-
if (this.memoryScope !== void 0) continuationState.memoryScope = this.memoryScope;
|
|
3010
|
-
const continuation = parseAgentContinuation({
|
|
3011
|
-
version: 1,
|
|
3012
|
-
agentId: this.agent.id,
|
|
3013
|
-
sourceRunId: args.runId,
|
|
3014
|
-
interaction: args.suspension.interaction,
|
|
3015
|
-
state: serializeContinuationState(continuationState)
|
|
3016
|
-
});
|
|
3017
|
-
const result = {
|
|
3018
|
-
type: "interaction",
|
|
3019
|
-
runId: args.runId,
|
|
3020
|
-
text: latestAssistantText([...this.chatHistory, ...args.newMessages]),
|
|
3021
|
-
usage: args.usage,
|
|
3022
|
-
messages: [...args.newMessages],
|
|
3023
|
-
trace: args.runObservers.trace,
|
|
3024
|
-
guardrails: [...this.guardrailDecisions],
|
|
3025
|
-
interaction: continuation.interaction,
|
|
3026
|
-
continuation,
|
|
3027
|
-
...generationArtifacts([...this.chatHistory, ...args.newMessages]),
|
|
3028
|
-
...this.memoryCompactionResult()
|
|
3029
|
-
};
|
|
3030
|
-
if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
|
|
3031
|
-
await this.runLifecycleFinish(result);
|
|
3032
|
-
await args.runObservers.end(observerRunEnd(result));
|
|
3033
|
-
this.runState = "completed";
|
|
3034
|
-
this.currentMessages = [...args.newMessages];
|
|
3035
|
-
this.disposeAbortLink();
|
|
3036
|
-
return result;
|
|
3037
|
-
}
|
|
3038
|
-
generatedAssistantMessage(response, _request) {
|
|
3039
|
-
const generation = {
|
|
3040
|
-
provider: this.agent.model.provider,
|
|
3041
|
-
modelId: this.agent.model.modelId,
|
|
3042
|
-
usage: { ...response.usage }
|
|
3043
|
-
};
|
|
3044
|
-
if (response.finishReason !== void 0) generation.finishReason = response.finishReason;
|
|
3045
|
-
if (response.providerFinishReason !== void 0) {
|
|
3046
|
-
generation.providerFinishReason = response.providerFinishReason;
|
|
3047
|
-
}
|
|
3048
|
-
if (response.contextUsage !== void 0) generation.contextUsage = response.contextUsage;
|
|
3049
|
-
if (response.sources !== void 0) generation.sources = response.sources;
|
|
3050
|
-
if (response.providerToolCalls !== void 0) {
|
|
3051
|
-
generation.providerToolCalls = response.providerToolCalls;
|
|
3052
|
-
}
|
|
3053
|
-
const metadata = { anvia: { generation } };
|
|
3054
|
-
let message = {
|
|
3055
|
-
role: "assistant",
|
|
3056
|
-
content: response.choice,
|
|
3057
|
-
metadata
|
|
3058
|
-
};
|
|
3059
|
-
if (response.messageId !== void 0) message = { ...message, id: response.messageId };
|
|
3060
|
-
return message;
|
|
3061
|
-
}
|
|
3062
|
-
providerTraceRequest(request, options = {}) {
|
|
3063
|
-
try {
|
|
3064
|
-
return this.agent.model.traceRequest?.(request, options);
|
|
3065
|
-
} catch (error) {
|
|
3066
|
-
return {
|
|
3067
|
-
error: error instanceof Error ? error.message : String(error)
|
|
3068
|
-
};
|
|
3069
|
-
}
|
|
3070
|
-
}
|
|
3071
|
-
generationStartArgs(turn, request, providerRequest) {
|
|
3072
|
-
let args = {
|
|
3073
|
-
turn,
|
|
3074
|
-
request,
|
|
3075
|
-
modelInfo: {
|
|
3076
|
-
provider: this.agent.model.provider,
|
|
3077
|
-
modelId: this.agent.model.modelId,
|
|
3078
|
-
capabilities: this.agent.model.capabilities
|
|
3079
|
-
}
|
|
3080
|
-
};
|
|
3081
|
-
if (providerRequest !== void 0) args = { ...args, providerRequest };
|
|
3082
|
-
return args;
|
|
3083
|
-
}
|
|
3084
|
-
retryOptionsForFailure(error, attempt, turn, streaming) {
|
|
3085
|
-
if (this.abortController.signal.aborted) return void 0;
|
|
3086
|
-
return retryOptionsForFailure(this.completionRetryOptions, {
|
|
3087
|
-
error,
|
|
3088
|
-
attempt,
|
|
3089
|
-
turn,
|
|
3090
|
-
streaming
|
|
3091
|
-
});
|
|
3092
|
-
}
|
|
3093
|
-
async scheduleCompletionRetry(error, attempt, turn, streaming, options, runObservers, additionalAttributes) {
|
|
3094
|
-
const delayMs = retryDelayMs(options, attempt);
|
|
3095
|
-
const attributes = {
|
|
3096
|
-
turn,
|
|
3097
|
-
attempt,
|
|
3098
|
-
nextAttempt: attempt + 1,
|
|
3099
|
-
maxAttempts: options.maxAttempts,
|
|
3100
|
-
delayMs,
|
|
3101
|
-
streaming,
|
|
3102
|
-
...retryErrorAttributes(error)
|
|
3103
|
-
};
|
|
3104
|
-
if (additionalAttributes !== void 0) {
|
|
3105
|
-
Object.assign(attributes, additionalAttributes);
|
|
3106
|
-
}
|
|
3107
|
-
await runObservers.event({
|
|
3108
|
-
name: "completion.retry",
|
|
3109
|
-
level: "WARNING",
|
|
3110
|
-
attributes
|
|
3111
|
-
});
|
|
3112
|
-
await waitForRetry(delayMs, this.abortController.signal);
|
|
3113
|
-
}
|
|
3114
|
-
async executeToolCalls(runId, toolCalls, newMessages, onResult, onStreamEvent, observation) {
|
|
3115
|
-
const executor = this.createToolExecutor(runId, newMessages);
|
|
3116
|
-
return executor.execute(toolCalls, onResult, onStreamEvent, observation);
|
|
3117
|
-
}
|
|
3118
|
-
createToolExecutor(runId, newMessages) {
|
|
3119
|
-
return new ToolCallExecutor(
|
|
3120
|
-
this.agent,
|
|
3121
|
-
this.activeHook,
|
|
3122
|
-
async (request) => {
|
|
3123
|
-
throw new AgentInteractionSignal(approvalInteraction(request), request.rejectMessage);
|
|
3124
|
-
},
|
|
3125
|
-
this.activeLifecycle,
|
|
3126
|
-
{
|
|
3127
|
-
runId,
|
|
3128
|
-
sessionId: this.memoryScope?.sessionId,
|
|
3129
|
-
metadata: this.memoryScope?.metadata
|
|
3130
|
-
},
|
|
3131
|
-
this.concurrency,
|
|
3132
|
-
this.requestMiddlewares,
|
|
3133
|
-
this.abortController.signal,
|
|
3134
|
-
(reason) => this.cancelled(newMessages, reason)
|
|
3135
|
-
);
|
|
3136
|
-
}
|
|
3137
|
-
async resolveContinuationTools(runId, newMessages, onResult, onStreamEvent, observation) {
|
|
3138
|
-
const state = this.continuationState;
|
|
3139
|
-
const response = this.interactionResponse;
|
|
3140
|
-
if (state === void 0 || response === void 0) {
|
|
3141
|
-
return [];
|
|
3142
|
-
}
|
|
3143
|
-
const pending = state.pending;
|
|
3144
|
-
const interaction = this.resumedFrom;
|
|
3145
|
-
if (interaction === void 0) {
|
|
3146
|
-
throw new TypeError("Agent continuation is missing its source run linkage.");
|
|
3147
|
-
}
|
|
3148
|
-
const executor = this.createToolExecutor(runId, newMessages);
|
|
3149
|
-
const results = [];
|
|
3150
|
-
if (response.type === "tool-approval") {
|
|
3151
|
-
const attributes = {
|
|
3152
|
-
approvalId: interaction.interactionId,
|
|
3153
|
-
toolName: pending.toolCall.toolName,
|
|
3154
|
-
toolCallId: pending.toolCall.toolCallId,
|
|
3155
|
-
internalCallId: pending.internalCallId,
|
|
3156
|
-
approved: response.approved
|
|
3157
|
-
};
|
|
3158
|
-
if (response.reason !== void 0) attributes.decisionReason = response.reason;
|
|
3159
|
-
await observation.runObservers.event({
|
|
3160
|
-
name: "tool.approval_resolved",
|
|
3161
|
-
attributes
|
|
3162
|
-
});
|
|
3163
|
-
if (response.approved) {
|
|
3164
|
-
results.push(await executor.executeResumed(pending, onResult, onStreamEvent, observation));
|
|
3165
|
-
} else {
|
|
3166
|
-
const output = {
|
|
3167
|
-
type: "execution-denied",
|
|
3168
|
-
reason: response.reason ?? pending.rejectMessage ?? "Tool approval was rejected."
|
|
3169
|
-
};
|
|
3170
|
-
results.push(await executor.resolveResumed(pending, output, onResult, observation));
|
|
3171
|
-
}
|
|
3172
|
-
} else {
|
|
3173
|
-
const currentTool = this.agent.getTool(pending.toolCall.toolName);
|
|
3174
|
-
if (currentTool === void 0 || !isQuestionTool(currentTool)) {
|
|
3175
|
-
throw new TypeError(
|
|
3176
|
-
`Cannot resume question interaction because tool "${pending.toolCall.toolName}" is no longer registered as a question tool.`
|
|
3177
|
-
);
|
|
3178
|
-
}
|
|
3179
|
-
const output = questionResult(response.answers);
|
|
3180
|
-
results.push(await executor.resolveResumed(pending, output, onResult, observation));
|
|
3181
|
-
}
|
|
3182
|
-
try {
|
|
3183
|
-
results.push(
|
|
3184
|
-
...await executor.execute(state.remainingToolCalls, onResult, onStreamEvent, observation)
|
|
3185
|
-
);
|
|
3186
|
-
} catch (error) {
|
|
3187
|
-
if (error instanceof ToolExecutionSuspension) {
|
|
3188
|
-
error.completedResults = [...results, ...error.completedResults];
|
|
3189
|
-
}
|
|
3190
|
-
throw error;
|
|
3191
|
-
}
|
|
3192
|
-
return results;
|
|
3193
|
-
}
|
|
3194
|
-
executeStreamingToolCalls(runId, toolCalls, newMessages, observation) {
|
|
3195
|
-
const events = createAsyncQueue();
|
|
3196
|
-
const results = this.executeToolCalls(
|
|
3197
|
-
runId,
|
|
3198
|
-
toolCalls,
|
|
3199
|
-
newMessages,
|
|
3200
|
-
(result) => events.enqueue(result),
|
|
3201
|
-
(event) => events.enqueue(event),
|
|
3202
|
-
observation
|
|
3203
|
-
);
|
|
3204
|
-
results.then(
|
|
3205
|
-
() => events.close(),
|
|
3206
|
-
(error) => events.throw(error)
|
|
3207
|
-
);
|
|
3208
|
-
return { events, results };
|
|
3209
|
-
}
|
|
3210
|
-
executeContinuationToolStream(runId, newMessages, observation) {
|
|
3211
|
-
const events = createAsyncQueue();
|
|
3212
|
-
const results = this.resolveContinuationTools(
|
|
3213
|
-
runId,
|
|
3214
|
-
newMessages,
|
|
3215
|
-
(result) => events.enqueue(result),
|
|
3216
|
-
(event) => events.enqueue(event),
|
|
3217
|
-
observation
|
|
3218
|
-
);
|
|
3219
|
-
results.then(
|
|
3220
|
-
() => events.close(),
|
|
3221
|
-
(error) => events.throw(error)
|
|
3222
|
-
);
|
|
3223
|
-
return { events, results };
|
|
3224
|
-
}
|
|
3225
|
-
async closeActiveGeneration(error) {
|
|
3226
|
-
const active = this.activeGeneration;
|
|
3227
|
-
if (active === void 0) {
|
|
3228
|
-
return;
|
|
3229
|
-
}
|
|
3230
|
-
this.activeGeneration = void 0;
|
|
3231
|
-
await active.observers.error({ turn: active.turn, error });
|
|
3232
|
-
}
|
|
3233
|
-
updateRunProgress(messages) {
|
|
3234
|
-
this.currentMessages = [...messages];
|
|
3235
|
-
}
|
|
3236
|
-
async runLifecycleFinish(result) {
|
|
3237
|
-
const common = {
|
|
3238
|
-
runId: result.runId,
|
|
3239
|
-
text: result.text,
|
|
3240
|
-
usage: lifecycleSnapshot(result.usage),
|
|
3241
|
-
messages: lifecycleSnapshot(result.messages)
|
|
3242
|
-
};
|
|
3243
|
-
if (result.memoryCompaction !== void 0) {
|
|
3244
|
-
Object.assign(common, { memoryCompaction: lifecycleSnapshot(result.memoryCompaction) });
|
|
3245
|
-
}
|
|
3246
|
-
const event = result.type === "response" ? {
|
|
3247
|
-
...common,
|
|
3248
|
-
status: "completed",
|
|
3249
|
-
output: lifecycleSnapshot(result.output)
|
|
3250
|
-
} : result.type === "blocked" ? {
|
|
3251
|
-
...common,
|
|
3252
|
-
status: "blocked",
|
|
3253
|
-
stage: result.stage
|
|
3254
|
-
} : {
|
|
3255
|
-
...common,
|
|
3256
|
-
status: "suspended",
|
|
3257
|
-
interaction: lifecycleSnapshot(result.interaction)
|
|
3258
|
-
};
|
|
3259
|
-
await this.activeLifecycle?.onFinish?.(event);
|
|
3260
|
-
}
|
|
3261
|
-
async runLifecycleError(error, runId, usage, messages) {
|
|
3262
|
-
try {
|
|
3263
|
-
await this.activeLifecycle?.onError?.({
|
|
3264
|
-
runId,
|
|
3265
|
-
error: lifecycleSnapshot(error),
|
|
3266
|
-
usage: lifecycleSnapshot(usage),
|
|
3267
|
-
messages: lifecycleSnapshot([...this.chatHistory, ...messages])
|
|
3268
|
-
});
|
|
3269
|
-
return void 0;
|
|
3270
|
-
} catch (lifecycleError) {
|
|
3271
|
-
return lifecycleError;
|
|
3272
|
-
}
|
|
3273
|
-
}
|
|
3274
|
-
async reportRunFailure(error, runId, usage, messages, runObservers) {
|
|
3275
|
-
const reportedError = await this.resolveReportedRunError(error, runId, usage, messages);
|
|
3276
|
-
await settleFailureCleanup([
|
|
3277
|
-
() => this.onInternalFailure?.({
|
|
3278
|
-
error: reportedError,
|
|
3279
|
-
messages: lifecycleSnapshot(messages)
|
|
3280
|
-
}),
|
|
3281
|
-
() => runObservers?.error({
|
|
3282
|
-
status: reportedError instanceof AgentRunCancelledError ? "cancelled" : "failed",
|
|
3283
|
-
error: reportedError,
|
|
3284
|
-
usage,
|
|
3285
|
-
messages: [...messages]
|
|
3286
|
-
}),
|
|
3287
|
-
() => this.memoryRecorder.recordError(runId, reportedError, messages)
|
|
3288
|
-
]);
|
|
3289
|
-
return reportedError;
|
|
3290
|
-
}
|
|
3291
|
-
async resolveReportedRunError(error, runId, usage, messages) {
|
|
3292
|
-
try {
|
|
3293
|
-
await this.runRunErrorHook(error, usage, messages);
|
|
3294
|
-
} catch {
|
|
3295
|
-
}
|
|
3296
|
-
const reportedError = this.cancellationError ?? error;
|
|
3297
|
-
await this.runLifecycleError(reportedError, runId, usage, messages);
|
|
3298
|
-
return reportedError;
|
|
3299
|
-
}
|
|
3300
|
-
async runOutputGuardrailsForResponse(runId, usage, response, messages, runObservers) {
|
|
3301
|
-
const originalOutput = textFromAssistantContent(response.choice);
|
|
3302
|
-
const result = await runOutputGuardrails(this.guardrailPolicies, {
|
|
3303
|
-
outputText: originalOutput,
|
|
3304
|
-
messages: [...this.chatHistory, ...messages],
|
|
3305
|
-
usage,
|
|
3306
|
-
run: this.guardrailRunContext(runId)
|
|
3307
|
-
});
|
|
3308
|
-
for (const decision of result.decisions) {
|
|
3309
|
-
await this.recordGuardrailDecision(decision, runObservers);
|
|
3310
|
-
}
|
|
3311
|
-
const text = result.blocked ? result.message ?? "The response was blocked by a guardrail." : result.outputText;
|
|
3312
|
-
if (text === originalOutput) {
|
|
3313
|
-
return { text, blocked: result.blocked, response, decisions: result.decisions };
|
|
3314
|
-
}
|
|
3315
|
-
return {
|
|
3316
|
-
text,
|
|
3317
|
-
blocked: result.blocked,
|
|
3318
|
-
response: {
|
|
3319
|
-
...response,
|
|
3320
|
-
choice: [{ type: "text", text }]
|
|
3321
|
-
},
|
|
3322
|
-
decisions: result.decisions
|
|
3323
|
-
};
|
|
3324
|
-
}
|
|
3325
|
-
createTerminalResult(runId, text, blocked, usage, messages, runObservers) {
|
|
3326
|
-
const common = {
|
|
3327
|
-
runId,
|
|
3328
|
-
text,
|
|
3329
|
-
usage,
|
|
3330
|
-
messages: [...messages],
|
|
3331
|
-
trace: runObservers.trace,
|
|
3332
|
-
guardrails: [...this.guardrailDecisions],
|
|
3333
|
-
...generationArtifacts(messages),
|
|
3334
|
-
...this.memoryCompactionResult()
|
|
3335
|
-
};
|
|
3336
|
-
if (this.resumedFrom !== void 0) Object.assign(common, { resumedFrom: this.resumedFrom });
|
|
3337
|
-
if (blocked) {
|
|
3338
|
-
return {
|
|
3339
|
-
...common,
|
|
3340
|
-
type: "blocked",
|
|
3341
|
-
stage: "output",
|
|
3342
|
-
...blockedOutcomeDetails(
|
|
3343
|
-
this.guardrailDecisions,
|
|
3344
|
-
"The response was blocked by a guardrail."
|
|
3345
|
-
)
|
|
3346
|
-
};
|
|
3347
|
-
}
|
|
3348
|
-
return {
|
|
3349
|
-
...common,
|
|
3350
|
-
type: "response",
|
|
3351
|
-
output: this.parseOutput(text)
|
|
3352
|
-
};
|
|
3353
|
-
}
|
|
3354
|
-
validateStructuredResponse(response, attempt, usage) {
|
|
3355
|
-
if (this.agent.outputSchema === void 0) return;
|
|
3356
|
-
if (response.choice.some((item) => item.type === "tool-call")) return;
|
|
3357
|
-
const text = textFromAssistantContent(response.choice);
|
|
3358
|
-
const normalized = normalizeStructuredOutput(text);
|
|
3359
|
-
if (response.finishReason === "content-filter") {
|
|
3360
|
-
throw new AgentStructuredOutputError({
|
|
3361
|
-
phase: "content-filter",
|
|
3362
|
-
attempt,
|
|
3363
|
-
maxAttempts: this.completionRetryOptions?.maxAttempts ?? 1,
|
|
3364
|
-
outputLength: text.length,
|
|
3365
|
-
normalizedLength: normalized.text.length,
|
|
3366
|
-
outputFormat: normalized.format,
|
|
3367
|
-
attemptUsage: response.usage,
|
|
3368
|
-
usage,
|
|
3369
|
-
finishReason: response.finishReason,
|
|
3370
|
-
providerFinishReason: response.providerFinishReason
|
|
3371
|
-
});
|
|
3372
|
-
}
|
|
3373
|
-
if (response.finishReason === "length") {
|
|
3374
|
-
throw new AgentStructuredOutputError({
|
|
3375
|
-
phase: "truncated",
|
|
3376
|
-
attempt,
|
|
3377
|
-
maxAttempts: this.completionRetryOptions?.maxAttempts ?? 1,
|
|
3378
|
-
outputLength: text.length,
|
|
3379
|
-
normalizedLength: normalized.text.length,
|
|
3380
|
-
outputFormat: normalized.format,
|
|
3381
|
-
attemptUsage: response.usage,
|
|
3382
|
-
usage,
|
|
3383
|
-
finishReason: response.finishReason,
|
|
3384
|
-
providerFinishReason: response.providerFinishReason
|
|
3385
|
-
});
|
|
3386
|
-
}
|
|
3387
|
-
const output = this.parseOutput(text, attempt, usage, {
|
|
3388
|
-
useValidatedOutput: false,
|
|
3389
|
-
attemptUsage: response.usage,
|
|
3390
|
-
finishReason: response.finishReason,
|
|
3391
|
-
providerFinishReason: response.providerFinishReason
|
|
3392
|
-
});
|
|
3393
|
-
this.validatedStructuredOutput = { text, output };
|
|
3394
|
-
}
|
|
3395
|
-
takeFailedCompletionUsage() {
|
|
3396
|
-
const usage = this.failedCompletionUsage;
|
|
3397
|
-
this.failedCompletionUsage = Usage.empty();
|
|
3398
|
-
return usage;
|
|
3399
|
-
}
|
|
3400
|
-
parseOutput(text, attempt = 1, usage = Usage.empty(), options = {}) {
|
|
3401
|
-
const schema = this.agent.outputSchema;
|
|
3402
|
-
if (schema === void 0) return text;
|
|
3403
|
-
if (options.useValidatedOutput !== false && this.validatedStructuredOutput?.text === text) {
|
|
3404
|
-
return this.validatedStructuredOutput.output;
|
|
3405
|
-
}
|
|
3406
|
-
const normalized = normalizeStructuredOutput(text);
|
|
3407
|
-
const maxAttempts = this.completionRetryOptions?.maxAttempts ?? 1;
|
|
3408
|
-
let json;
|
|
3409
|
-
try {
|
|
3410
|
-
json = JSON.parse(normalized.text);
|
|
3411
|
-
if (!isJsonValue(json)) {
|
|
3412
|
-
throw new TypeError("Agent structured output is not a JSON value.");
|
|
3413
|
-
}
|
|
3414
|
-
} catch (error) {
|
|
3415
|
-
throw new AgentStructuredOutputError({
|
|
3416
|
-
phase: "parse",
|
|
3417
|
-
attempt,
|
|
3418
|
-
maxAttempts,
|
|
3419
|
-
outputLength: text.length,
|
|
3420
|
-
normalizedLength: normalized.text.length,
|
|
3421
|
-
outputFormat: normalized.format,
|
|
3422
|
-
attemptUsage: options.attemptUsage ?? usage,
|
|
3423
|
-
usage,
|
|
3424
|
-
finishReason: options.finishReason,
|
|
3425
|
-
providerFinishReason: options.providerFinishReason,
|
|
3426
|
-
cause: error
|
|
3427
|
-
});
|
|
3428
|
-
}
|
|
3429
|
-
try {
|
|
3430
|
-
return schema.parse(json);
|
|
3431
|
-
} catch (error) {
|
|
3432
|
-
throw new AgentStructuredOutputError({
|
|
3433
|
-
phase: "schema",
|
|
3434
|
-
attempt,
|
|
3435
|
-
maxAttempts,
|
|
3436
|
-
outputLength: text.length,
|
|
3437
|
-
normalizedLength: normalized.text.length,
|
|
3438
|
-
outputFormat: normalized.format,
|
|
3439
|
-
attemptUsage: options.attemptUsage ?? usage,
|
|
3440
|
-
usage,
|
|
3441
|
-
finishReason: options.finishReason,
|
|
3442
|
-
providerFinishReason: options.providerFinishReason,
|
|
3443
|
-
cause: error
|
|
3444
|
-
});
|
|
3445
|
-
}
|
|
3446
|
-
}
|
|
3447
|
-
memoryCompactionResult() {
|
|
3448
|
-
return this.memoryCompaction === void 0 ? {} : { memoryCompaction: lifecycleSnapshot(this.memoryCompaction) };
|
|
3449
|
-
}
|
|
3450
|
-
async recordGuardrailDecision(decision, runObservers) {
|
|
3451
|
-
this.guardrailDecisions.push(decision);
|
|
3452
|
-
await runObservers.event({
|
|
3453
|
-
name: "guardrail.decision",
|
|
3454
|
-
level: decision.action === "block" ? "WARNING" : "DEFAULT",
|
|
3455
|
-
attributes: guardrailDecisionAttributes(decision)
|
|
3456
|
-
});
|
|
3457
|
-
}
|
|
3458
|
-
async recordMemoryCompaction(preparation, runObservers) {
|
|
3459
|
-
const compaction = preparation.compaction;
|
|
3460
|
-
if (compaction === void 0) {
|
|
3461
|
-
return;
|
|
3462
|
-
}
|
|
3463
|
-
await runObservers.event({
|
|
3464
|
-
name: "memory.compaction",
|
|
3465
|
-
attributes: {
|
|
3466
|
-
originalMessageCount: compaction.originalMessageCount,
|
|
3467
|
-
compactedMessageCount: compaction.compactedMessageCount,
|
|
3468
|
-
retainedMessageCount: compaction.retainedMessageCount,
|
|
3469
|
-
originalTokenCount: compaction.originalTokenCount,
|
|
3470
|
-
compactedTokenCount: compaction.compactedTokenCount,
|
|
3471
|
-
retainedTokenCount: compaction.retainedTokenCount,
|
|
3472
|
-
resultTokenCount: compaction.resultTokenCount,
|
|
3473
|
-
attempts: compaction.attempts,
|
|
3474
|
-
inputTokens: compaction.usage.inputTokens,
|
|
3475
|
-
outputTokens: compaction.usage.outputTokens,
|
|
3476
|
-
totalTokens: compaction.usage.totalTokens
|
|
3477
|
-
}
|
|
3478
|
-
});
|
|
3479
|
-
}
|
|
3480
|
-
async notifyInternalMemoryCompaction(compaction) {
|
|
3481
|
-
if (compaction === void 0) {
|
|
3482
|
-
return;
|
|
3483
|
-
}
|
|
3484
|
-
await this.onInternalMemoryCompaction?.(lifecycleSnapshot(compaction));
|
|
3485
|
-
}
|
|
3486
|
-
guardrailRunContext(runId) {
|
|
3487
|
-
const context = {
|
|
3488
|
-
agentId: this.agent.id,
|
|
3489
|
-
runId
|
|
3490
|
-
};
|
|
3491
|
-
if (this.memoryScope !== void 0) {
|
|
3492
|
-
context.sessionId = this.memoryScope.sessionId;
|
|
3493
|
-
if (this.memoryScope.metadata !== void 0) {
|
|
3494
|
-
context.metadata = this.memoryScope.metadata;
|
|
3495
|
-
}
|
|
3496
|
-
}
|
|
3497
|
-
return context;
|
|
3498
|
-
}
|
|
3499
|
-
async startRunObservers(runId) {
|
|
3500
|
-
const observability = this.agent.observability;
|
|
3501
|
-
return startAgentRunObservers(
|
|
3502
|
-
observability?.observers ?? {},
|
|
3503
|
-
{
|
|
3504
|
-
runId,
|
|
3505
|
-
agentName: this.agent.name,
|
|
3506
|
-
agentDescription: this.agent.description,
|
|
3507
|
-
instructions: this.agent.instructions,
|
|
3508
|
-
trace: this.traceOptions,
|
|
3509
|
-
promptRef: this.traceOptions?.promptRef,
|
|
3510
|
-
prompt: this.promptMessage,
|
|
3511
|
-
history: this.chatHistory,
|
|
3512
|
-
maxTurns: this.maxTurnCount
|
|
3513
|
-
},
|
|
3514
|
-
{
|
|
3515
|
-
primaryTrace: observability?.primaryTrace,
|
|
3516
|
-
errorPolicy: observability?.errorPolicy ?? "ignore"
|
|
3517
|
-
}
|
|
3518
|
-
);
|
|
3519
|
-
}
|
|
3520
|
-
async runCompletionCallHook(prompt, history, newMessages) {
|
|
3521
|
-
const action = await this.activeHook?.onCompletionCall?.({
|
|
3522
|
-
prompt,
|
|
3523
|
-
history,
|
|
3524
|
-
run: runControl
|
|
3525
|
-
});
|
|
3526
|
-
if (action?.type === "terminate") {
|
|
3527
|
-
throw this.cancelled(newMessages, action.reason);
|
|
3528
|
-
}
|
|
3529
|
-
}
|
|
3530
|
-
async runRunStartHook(newMessages) {
|
|
3531
|
-
const action = await this.activeHook?.onRunStart?.({
|
|
3532
|
-
prompt: this.promptMessage,
|
|
3533
|
-
history: this.chatHistory,
|
|
3534
|
-
maxTurns: this.maxTurnCount,
|
|
3535
|
-
run: runControl
|
|
3536
|
-
});
|
|
3537
|
-
if (action?.type === "terminate") {
|
|
3538
|
-
throw this.cancelled(newMessages, action.reason);
|
|
3539
|
-
}
|
|
3540
|
-
}
|
|
3541
|
-
async runRunEndHook(result, newMessages) {
|
|
3542
|
-
const action = await this.activeHook?.onRunEnd?.({
|
|
3543
|
-
status: "completed",
|
|
3544
|
-
output: result.output,
|
|
3545
|
-
text: result.text,
|
|
3546
|
-
usage: result.usage,
|
|
3547
|
-
messages: result.messages,
|
|
3548
|
-
run: runControl
|
|
3549
|
-
});
|
|
3550
|
-
if (action?.type === "terminate") {
|
|
3551
|
-
throw this.cancelled(newMessages, action.reason);
|
|
3552
|
-
}
|
|
3553
|
-
}
|
|
3554
|
-
async runRunErrorHook(error, usage, newMessages) {
|
|
3555
|
-
const action = await this.activeHook?.onRunError?.({
|
|
3556
|
-
error,
|
|
3557
|
-
usage,
|
|
3558
|
-
messages: [...this.chatHistory, ...newMessages],
|
|
3559
|
-
run: runControl
|
|
3560
|
-
});
|
|
3561
|
-
if (action?.type === "terminate") {
|
|
3562
|
-
this.cancelled(newMessages, action.reason);
|
|
3563
|
-
}
|
|
3564
|
-
}
|
|
3565
|
-
async runTurnStartHook(turn, prompt, history, newMessages) {
|
|
3566
|
-
const action = await this.activeHook?.onTurnStart?.({
|
|
3567
|
-
turn,
|
|
3568
|
-
prompt,
|
|
3569
|
-
history,
|
|
3570
|
-
run: runControl
|
|
3571
|
-
});
|
|
3572
|
-
if (action?.type === "terminate") {
|
|
3573
|
-
throw this.cancelled(newMessages, action.reason);
|
|
3574
|
-
}
|
|
3575
|
-
}
|
|
3576
|
-
async runTurnEndHook(turn, response, newMessages) {
|
|
3577
|
-
const action = await this.activeHook?.onTurnEnd?.({
|
|
3578
|
-
turn,
|
|
3579
|
-
response,
|
|
3580
|
-
run: runControl
|
|
3581
|
-
});
|
|
3582
|
-
if (action?.type === "terminate") {
|
|
3583
|
-
throw this.cancelled(newMessages, action.reason);
|
|
3584
|
-
}
|
|
3585
|
-
}
|
|
3586
|
-
async runCompletionRequestMiddlewares(request, turn) {
|
|
3587
|
-
let current = request;
|
|
3588
|
-
for (const middleware of this.activeMiddlewares()) {
|
|
3589
|
-
const replacement = await middleware.onCompletionRequest?.({
|
|
3590
|
-
turn,
|
|
3591
|
-
request: current,
|
|
3592
|
-
originalRequest: request
|
|
3593
|
-
});
|
|
3594
|
-
if (replacement?.request !== void 0) {
|
|
3595
|
-
current = replacement.request;
|
|
3596
|
-
if (current.providerOptions !== void 0) {
|
|
3597
|
-
assertJsonObject(current.providerOptions, "providerOptions");
|
|
3598
|
-
}
|
|
3599
|
-
}
|
|
3600
|
-
}
|
|
3601
|
-
return current;
|
|
3602
|
-
}
|
|
3603
|
-
async runCompletionResponseMiddlewares(request, response, turn) {
|
|
3604
|
-
let current = response;
|
|
3605
|
-
for (const middleware of this.activeMiddlewares()) {
|
|
3606
|
-
const replacement = await middleware.onCompletionResponse?.({
|
|
3607
|
-
turn,
|
|
3608
|
-
request,
|
|
3609
|
-
response: current,
|
|
3610
|
-
originalResponse: response
|
|
3611
|
-
});
|
|
3612
|
-
if (replacement?.response !== void 0) {
|
|
3613
|
-
current = replacement.response;
|
|
3614
|
-
}
|
|
3615
|
-
}
|
|
3616
|
-
return current;
|
|
3617
|
-
}
|
|
3618
|
-
async runCompletionResponseHook(prompt, response, newMessages) {
|
|
3619
|
-
const action = await this.activeHook?.onCompletionResponse?.({
|
|
3620
|
-
prompt,
|
|
3621
|
-
response,
|
|
3622
|
-
run: runControl
|
|
3623
|
-
});
|
|
3624
|
-
if (action?.type === "terminate") {
|
|
3625
|
-
throw this.cancelled(newMessages, action.reason);
|
|
3626
|
-
}
|
|
3627
|
-
}
|
|
3628
|
-
async runCompletionErrorHook(prompt, error, newMessages) {
|
|
3629
|
-
const action = await this.activeHook?.onCompletionError?.({
|
|
3630
|
-
prompt,
|
|
3631
|
-
error,
|
|
3632
|
-
run: runControl
|
|
3633
|
-
});
|
|
3634
|
-
if (action?.type === "terminate") {
|
|
3635
|
-
throw this.cancelled(newMessages, action.reason);
|
|
3636
|
-
}
|
|
3637
|
-
}
|
|
3638
|
-
activeMiddlewares() {
|
|
3639
|
-
return [...this.agent.middlewares, ...this.requestMiddlewares];
|
|
3640
|
-
}
|
|
3641
|
-
shouldBufferStreamResponseEvents() {
|
|
3642
|
-
return this.activeHook?.onCompletionResponse !== void 0 || this.activeMiddlewares().some((middleware) => middleware.onCompletionResponse !== void 0);
|
|
3643
|
-
}
|
|
3644
|
-
async drainSteeringMessages(runId, turn, newMessages, pendingTurnMessages, options = {}) {
|
|
3645
|
-
const receipts = this.steeringMessages.splice(0);
|
|
3646
|
-
if (receipts.length === 0) {
|
|
3647
|
-
if (options.closeWhenEmpty === true) {
|
|
3648
|
-
this.runState = "closing";
|
|
3649
|
-
}
|
|
3650
|
-
return [];
|
|
3651
|
-
}
|
|
3652
|
-
const messages = receipts.flatMap((receipt) => receipt.messages);
|
|
3653
|
-
newMessages.push(...messages);
|
|
3654
|
-
await this.memoryRecorder.commitMessages(runId, turn, messages, pendingTurnMessages);
|
|
3655
|
-
return receipts;
|
|
3656
|
-
}
|
|
3657
|
-
startRun() {
|
|
3658
|
-
if (this.runState === "idle") {
|
|
3659
|
-
this.runState = "running";
|
|
3660
|
-
return;
|
|
3661
|
-
}
|
|
3662
|
-
if (this.runState === "running") {
|
|
3663
|
-
throw new Error("Agent stream is already running.");
|
|
3664
|
-
}
|
|
3665
|
-
throw new Error("Agent stream has already been consumed.");
|
|
3666
|
-
}
|
|
3667
|
-
isTerminal() {
|
|
3668
|
-
return this.runState !== "idle" && this.runState !== "running";
|
|
3669
|
-
}
|
|
3670
|
-
cancelled(newMessages, reason) {
|
|
3671
|
-
if (this.cancellationError !== void 0) return this.cancellationError;
|
|
3672
|
-
const error = new AgentRunCancelledError([...this.chatHistory, ...newMessages], reason);
|
|
3673
|
-
this.setCancellationError(error);
|
|
3674
|
-
return error;
|
|
3675
|
-
}
|
|
3676
|
-
linkExternalAbortSignal(signal) {
|
|
3677
|
-
if (signal === void 0) return;
|
|
3678
|
-
const cancelFromSignal = () => {
|
|
3679
|
-
if (this.cancellationError !== void 0 || this.isTerminal()) return;
|
|
3680
|
-
const cause = abortError(signal.reason);
|
|
3681
|
-
const reason = abortReason(signal.reason);
|
|
3682
|
-
const messages = this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];
|
|
3683
|
-
this.setCancellationError(
|
|
3684
|
-
new AgentRunCancelledError([...this.chatHistory, ...messages], reason, { cause })
|
|
3685
|
-
);
|
|
3686
|
-
};
|
|
3687
|
-
if (signal.aborted) {
|
|
3688
|
-
cancelFromSignal();
|
|
3689
|
-
return;
|
|
3690
|
-
}
|
|
3691
|
-
signal.addEventListener("abort", cancelFromSignal, { once: true });
|
|
3692
|
-
this.removeExternalAbortListener = () => signal.removeEventListener("abort", cancelFromSignal);
|
|
3693
|
-
}
|
|
3694
|
-
throwIfCancelled() {
|
|
3695
|
-
if (this.cancellationError !== void 0) throw this.cancellationError;
|
|
3696
|
-
throwIfAborted(this.abortController.signal);
|
|
3697
|
-
}
|
|
3698
|
-
normalizeRunError(error) {
|
|
3699
|
-
return this.abortController.signal.aborted && this.cancellationError !== void 0 ? this.cancellationError : error;
|
|
3700
|
-
}
|
|
3701
|
-
modelCallOptions() {
|
|
3702
|
-
return { abortSignal: this.abortController.signal };
|
|
3703
|
-
}
|
|
3704
|
-
disposeAbortLink() {
|
|
3705
|
-
this.removeExternalAbortListener?.();
|
|
3706
|
-
this.removeExternalAbortListener = void 0;
|
|
3707
|
-
}
|
|
3708
|
-
};
|
|
3709
|
-
function abortReason(reason) {
|
|
3710
|
-
if (typeof reason === "string" && reason.trim().length > 0) return reason;
|
|
3711
|
-
if (reason instanceof Error && reason.message.trim().length > 0) return reason.message;
|
|
3712
|
-
return "External abort signal.";
|
|
3713
|
-
}
|
|
3714
|
-
function normalizeAgentInput(agentId, input) {
|
|
3715
|
-
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
3716
|
-
throw new TypeError("Agent runs require one options object with prompt or messages.");
|
|
3717
|
-
}
|
|
3718
|
-
const hasContinuation = "continuation" in input && input.continuation !== void 0;
|
|
3719
|
-
const hasPrompt = "prompt" in input && input.prompt !== void 0;
|
|
3720
|
-
const hasMessages = "messages" in input && input.messages !== void 0;
|
|
3721
|
-
if (Number(hasContinuation) + Number(hasPrompt) + Number(hasMessages) !== 1) {
|
|
3722
|
-
throw new TypeError("Agent runs require exactly one of prompt, messages, or continuation.");
|
|
3723
|
-
}
|
|
3724
|
-
if (hasContinuation) {
|
|
3725
|
-
if (!("response" in input) || input.response === void 0) {
|
|
3726
|
-
throw new TypeError("Agent continuation runs require an interaction response.");
|
|
3727
|
-
}
|
|
3728
|
-
if ("session" in input && input.session !== void 0) {
|
|
3729
|
-
throw new TypeError("Agent continuations carry their memory scope and cannot use session.");
|
|
3730
|
-
}
|
|
3731
|
-
const continuation = parseAgentContinuation(input.continuation);
|
|
3732
|
-
if (continuation.agentId !== agentId) {
|
|
3733
|
-
throw new TypeError(
|
|
3734
|
-
`Agent continuation belongs to "${continuation.agentId}", not "${agentId}".`
|
|
3735
|
-
);
|
|
3736
|
-
}
|
|
3737
|
-
const response = parseAgentInteractionResponse(input.response);
|
|
3738
|
-
assertAgentInteractionResponse(continuation.interaction, response);
|
|
3739
|
-
const state = parseContinuationState(continuation.state, continuation.interaction);
|
|
3740
|
-
let responsePart;
|
|
3741
|
-
if (response.type === "tool-approval") {
|
|
3742
|
-
responsePart = {
|
|
3743
|
-
type: "tool-approval-response",
|
|
3744
|
-
interactionId: continuation.interaction.id,
|
|
3745
|
-
toolCallId: continuation.interaction.toolCallId,
|
|
3746
|
-
toolName: continuation.interaction.toolName,
|
|
3747
|
-
approved: response.approved
|
|
3748
|
-
};
|
|
3749
|
-
if (response.reason !== void 0)
|
|
3750
|
-
responsePart = { ...responsePart, reason: response.reason };
|
|
3751
|
-
} else {
|
|
3752
|
-
responsePart = {
|
|
3753
|
-
type: "tool-question-response",
|
|
3754
|
-
interactionId: continuation.interaction.id,
|
|
3755
|
-
toolCallId: continuation.interaction.toolCallId,
|
|
3756
|
-
toolName: continuation.interaction.toolName,
|
|
3757
|
-
answers: response.answers
|
|
3758
|
-
};
|
|
3759
|
-
}
|
|
3760
|
-
if (continuation.interaction.callId !== void 0) {
|
|
3761
|
-
responsePart = { ...responsePart, callId: continuation.interaction.callId };
|
|
3762
|
-
}
|
|
3763
|
-
const normalized = {
|
|
3764
|
-
prompt: parseMessage({ role: "tool", content: [responsePart] }),
|
|
3765
|
-
history: [...state.history, ...state.messages],
|
|
3766
|
-
continuationState: state,
|
|
3767
|
-
interactionResponse: response,
|
|
3768
|
-
sourceRunId: continuation.sourceRunId,
|
|
3769
|
-
interactionId: continuation.interaction.id
|
|
3770
|
-
};
|
|
3771
|
-
if (state.memoryScope !== void 0) {
|
|
3772
|
-
Object.assign(normalized, { scope: normalizeMemoryScope(state.memoryScope) });
|
|
3773
|
-
}
|
|
3774
|
-
return normalized;
|
|
3775
|
-
}
|
|
3776
|
-
if (hasPrompt) {
|
|
3777
|
-
const prompt = input.prompt;
|
|
3778
|
-
if (typeof prompt !== "string" && (typeof prompt !== "object" || prompt === null || prompt.role !== "user")) {
|
|
3779
|
-
throw new TypeError("Agent prompt must be text or a user message.");
|
|
3780
|
-
}
|
|
3781
|
-
const parsedPrompt = parseMessage(
|
|
3782
|
-
typeof prompt === "string" ? { role: "user", content: prompt } : prompt
|
|
3783
|
-
);
|
|
3784
|
-
if (parsedPrompt.role !== "user") {
|
|
3785
|
-
throw new TypeError("Agent prompt must be text or a user message.");
|
|
3786
|
-
}
|
|
3787
|
-
const normalized = {
|
|
3788
|
-
prompt: parsedPrompt,
|
|
3789
|
-
history: []
|
|
3790
|
-
};
|
|
3791
|
-
if (input.session !== void 0) {
|
|
3792
|
-
Object.assign(normalized, { scope: normalizeMemoryScope(input.session) });
|
|
3793
|
-
}
|
|
3794
|
-
return normalized;
|
|
3795
|
-
}
|
|
3796
|
-
if (input.session !== void 0) {
|
|
3797
|
-
throw new TypeError("Agent messages cannot be combined with a persisted session.");
|
|
3798
|
-
}
|
|
3799
|
-
const messages = input.messages;
|
|
3800
|
-
if (!Array.isArray(messages) || messages.length === 0) {
|
|
3801
|
-
throw new TypeError("Agent input transcript must contain at least one message.");
|
|
3802
|
-
}
|
|
3803
|
-
const parsedMessages = parseMessages(messages);
|
|
3804
|
-
const activePrompt = parsedMessages.at(-1);
|
|
3805
|
-
if (activePrompt === void 0) {
|
|
3806
|
-
throw new TypeError("Agent input transcript must contain at least one message.");
|
|
3807
|
-
}
|
|
3808
|
-
if (activePrompt.role !== "user") {
|
|
3809
|
-
throw new TypeError("Agent input transcript must end with a user message.");
|
|
3810
|
-
}
|
|
3811
|
-
return {
|
|
3812
|
-
prompt: activePrompt,
|
|
3813
|
-
history: parsedMessages.slice(0, -1)
|
|
3814
|
-
};
|
|
3815
|
-
}
|
|
3816
|
-
function normalizeSteeringInput(input) {
|
|
3817
|
-
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
3818
|
-
throw new TypeError("Agent steering requires one options object with prompt or messages.");
|
|
3819
|
-
}
|
|
3820
|
-
const hasPrompt = "prompt" in input && input.prompt !== void 0;
|
|
3821
|
-
const hasMessages = "messages" in input && input.messages !== void 0;
|
|
3822
|
-
if (hasPrompt === hasMessages) {
|
|
3823
|
-
throw new TypeError("Agent steering requires exactly one of prompt or messages.");
|
|
3824
|
-
}
|
|
3825
|
-
if (hasPrompt) {
|
|
3826
|
-
const prompt = input.prompt;
|
|
3827
|
-
if (typeof prompt !== "string" && (typeof prompt !== "object" || prompt === null || prompt.role !== "user")) {
|
|
3828
|
-
throw new TypeError("Agent steering prompt must be text or a user message.");
|
|
3829
|
-
}
|
|
3830
|
-
const parsedPrompt = parseMessage(
|
|
3831
|
-
typeof prompt === "string" ? { role: "user", content: prompt } : prompt
|
|
3832
|
-
);
|
|
3833
|
-
if (parsedPrompt.role !== "user") {
|
|
3834
|
-
throw new TypeError("Agent steering prompt must be text or a user message.");
|
|
3835
|
-
}
|
|
3836
|
-
return [parsedPrompt];
|
|
3837
|
-
}
|
|
3838
|
-
const messages = input.messages;
|
|
3839
|
-
if (!Array.isArray(messages) || messages.length === 0) {
|
|
3840
|
-
throw new TypeError("Agent steering messages must contain at least one user message.");
|
|
3841
|
-
}
|
|
3842
|
-
const parsedMessages = parseMessages(messages);
|
|
3843
|
-
if (parsedMessages.some((message) => message.role !== "user")) {
|
|
3844
|
-
throw new TypeError("Agent steering messages must all be user messages.");
|
|
3845
|
-
}
|
|
3846
|
-
return parsedMessages;
|
|
3847
|
-
}
|
|
3848
|
-
function normalizeRequestedRunId(runId) {
|
|
3849
|
-
if (runId === void 0) {
|
|
3850
|
-
return void 0;
|
|
3851
|
-
}
|
|
3852
|
-
if (typeof runId !== "string" || runId.trim().length === 0) {
|
|
3853
|
-
throw new TypeError("runId must be a non-empty string.");
|
|
3854
|
-
}
|
|
3855
|
-
return runId;
|
|
3856
|
-
}
|
|
3857
|
-
function responseStreamEvents(turn, response, includeProviderArtifacts = true) {
|
|
3858
|
-
const events = [];
|
|
3859
|
-
for (const item of response.choice) {
|
|
3860
|
-
if (item.type === "text") {
|
|
3861
|
-
if (item.text.length > 0) {
|
|
3862
|
-
events.push({ type: "text_delta", turn, delta: item.text });
|
|
3863
|
-
}
|
|
3864
|
-
continue;
|
|
3865
|
-
}
|
|
3866
|
-
if (item.type === "reasoning") {
|
|
3867
|
-
if (item.details === void 0) {
|
|
3868
|
-
if (item.text.length > 0) {
|
|
3869
|
-
events.push(reasoningDeltaEvent(turn, item.text, { id: item.id }));
|
|
3870
|
-
}
|
|
3871
|
-
continue;
|
|
3872
|
-
}
|
|
3873
|
-
for (const content of item.details) {
|
|
3874
|
-
const delta = content.type === "encrypted" || content.type === "redacted" ? content.data : content.text;
|
|
3875
|
-
events.push(
|
|
3876
|
-
reasoningDeltaEvent(turn, delta, {
|
|
3877
|
-
id: item.id,
|
|
3878
|
-
contentType: content.type,
|
|
3879
|
-
signature: content.type === "text" ? content.signature : void 0
|
|
3880
|
-
})
|
|
3881
|
-
);
|
|
3882
|
-
}
|
|
3883
|
-
continue;
|
|
3884
|
-
}
|
|
3885
|
-
if (item.type === "tool-call") {
|
|
3886
|
-
events.push({ type: "tool_call", turn, toolCall: item });
|
|
3887
|
-
}
|
|
3888
|
-
}
|
|
3889
|
-
if (includeProviderArtifacts) {
|
|
3890
|
-
for (const source of response.sources ?? []) {
|
|
3891
|
-
events.push({ type: "source", turn, source });
|
|
3892
|
-
}
|
|
3893
|
-
for (const toolCall of response.providerToolCalls ?? []) {
|
|
3894
|
-
events.push({ type: "provider_tool_call", turn, toolCall });
|
|
3895
|
-
}
|
|
3896
|
-
}
|
|
3897
|
-
return events;
|
|
3898
|
-
}
|
|
3899
|
-
function generationArtifacts(messages) {
|
|
3900
|
-
const sources = /* @__PURE__ */ new Map();
|
|
3901
|
-
const providerToolCalls = /* @__PURE__ */ new Map();
|
|
3902
|
-
let finishReason;
|
|
3903
|
-
let providerFinishReason;
|
|
3904
|
-
let contextUsage;
|
|
3905
|
-
for (const message of messages) {
|
|
3906
|
-
const metadata = getAssistantGenerationMetadata(message);
|
|
3907
|
-
if (metadata !== void 0) {
|
|
3908
|
-
finishReason = metadata.finishReason;
|
|
3909
|
-
providerFinishReason = metadata.providerFinishReason;
|
|
3910
|
-
contextUsage = metadata.contextUsage;
|
|
3911
|
-
}
|
|
3912
|
-
for (const source of metadata?.sources ?? []) {
|
|
3913
|
-
const key = `${source.url}\0${source.startIndex ?? ""}\0${source.endIndex ?? ""}`;
|
|
3914
|
-
sources.set(key, source);
|
|
3915
|
-
}
|
|
3916
|
-
for (const toolCall of metadata?.providerToolCalls ?? []) {
|
|
3917
|
-
providerToolCalls.set(toolCall.id, toolCall);
|
|
3918
|
-
}
|
|
3919
|
-
}
|
|
3920
|
-
const artifacts = {};
|
|
3921
|
-
if (sources.size > 0) artifacts.sources = [...sources.values()];
|
|
3922
|
-
if (providerToolCalls.size > 0) {
|
|
3923
|
-
artifacts.providerToolCalls = [...providerToolCalls.values()];
|
|
3924
|
-
}
|
|
3925
|
-
if (finishReason !== void 0) artifacts.finishReason = finishReason;
|
|
3926
|
-
if (providerFinishReason !== void 0) {
|
|
3927
|
-
artifacts.providerFinishReason = providerFinishReason;
|
|
3928
|
-
}
|
|
3929
|
-
if (contextUsage !== void 0) artifacts.contextUsage = contextUsage;
|
|
3930
|
-
return artifacts;
|
|
3931
|
-
}
|
|
3932
|
-
function reasoningDeltaEvent(turn, delta, details = {}) {
|
|
3933
|
-
const event = {
|
|
3934
|
-
type: "reasoning_delta",
|
|
3935
|
-
turn,
|
|
3936
|
-
delta
|
|
3937
|
-
};
|
|
3938
|
-
if (details.id !== void 0) {
|
|
3939
|
-
event.id = details.id;
|
|
3940
|
-
}
|
|
3941
|
-
if (details.contentType !== void 0) {
|
|
3942
|
-
event.contentType = details.contentType;
|
|
3943
|
-
}
|
|
3944
|
-
if (details.signature !== void 0) {
|
|
3945
|
-
event.signature = details.signature;
|
|
3946
|
-
}
|
|
3947
|
-
return event;
|
|
3948
|
-
}
|
|
3949
|
-
function textFromMessage(message) {
|
|
3950
|
-
if (message.role === "system") {
|
|
3951
|
-
return message.content;
|
|
3952
|
-
}
|
|
3953
|
-
if (typeof message.content === "string") {
|
|
3954
|
-
return message.content;
|
|
3955
|
-
}
|
|
3956
|
-
return message.content.flatMap((content) => {
|
|
3957
|
-
if (content.type === "text") {
|
|
3958
|
-
return [content.text];
|
|
3959
|
-
}
|
|
3960
|
-
if (content.type === "file" && content.data.type === "text") {
|
|
3961
|
-
return [content.data.text];
|
|
3962
|
-
}
|
|
3963
|
-
return [];
|
|
3964
|
-
}).join("\n");
|
|
3965
|
-
}
|
|
3966
|
-
function latestAssistantText(messages) {
|
|
3967
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
3968
|
-
const message = messages[index];
|
|
3969
|
-
if (message?.role === "assistant") {
|
|
3970
|
-
return typeof message.content === "string" ? message.content : textFromAssistantContent(message.content);
|
|
3971
|
-
}
|
|
3972
|
-
}
|
|
3973
|
-
return "";
|
|
3974
|
-
}
|
|
3975
|
-
function structuredOutputRetryRequest(request, response, error) {
|
|
3976
|
-
const truncated = error instanceof AgentStructuredOutputError && error.phase === "truncated";
|
|
3977
|
-
const correction = {
|
|
3978
|
-
role: "user",
|
|
3979
|
-
content: truncated ? STRUCTURED_OUTPUT_TRUNCATED_RETRY_PROMPT : STRUCTURED_OUTPUT_RETRY_PROMPT
|
|
3980
|
-
};
|
|
3981
|
-
if (truncated) {
|
|
3982
|
-
return {
|
|
3983
|
-
request: {
|
|
3984
|
-
...request,
|
|
3985
|
-
chatHistory: [...request.chatHistory, correction]
|
|
3986
|
-
},
|
|
3987
|
-
previousResponse: "omitted",
|
|
3988
|
-
includedOutputLength: 0
|
|
3989
|
-
};
|
|
3990
|
-
}
|
|
3991
|
-
const preview = structuredOutputRepairPreview(textFromAssistantContent(response.choice));
|
|
3992
|
-
if (preview.includedOutputLength === 0) {
|
|
3993
|
-
return {
|
|
3994
|
-
request: {
|
|
3995
|
-
...request,
|
|
3996
|
-
chatHistory: [...request.chatHistory, correction]
|
|
3997
|
-
},
|
|
3998
|
-
previousResponse: "omitted",
|
|
3999
|
-
includedOutputLength: 0
|
|
4000
|
-
};
|
|
4001
|
-
}
|
|
4002
|
-
const invalidResponse = {
|
|
4003
|
-
role: "assistant",
|
|
4004
|
-
content: [{ type: "text", text: preview.text }]
|
|
4005
|
-
};
|
|
4006
|
-
return {
|
|
4007
|
-
request: {
|
|
4008
|
-
...request,
|
|
4009
|
-
chatHistory: [...request.chatHistory, invalidResponse, correction]
|
|
4010
|
-
},
|
|
4011
|
-
previousResponse: "preview",
|
|
4012
|
-
includedOutputLength: preview.includedOutputLength
|
|
4013
|
-
};
|
|
4014
|
-
}
|
|
4015
|
-
function structuredOutputRetryEventAttributes(error, retryRequest) {
|
|
4016
|
-
const attributes = {
|
|
4017
|
-
previousResponse: retryRequest.previousResponse,
|
|
4018
|
-
includedOutputLength: retryRequest.includedOutputLength
|
|
4019
|
-
};
|
|
4020
|
-
if (!(error instanceof AgentStructuredOutputError)) return attributes;
|
|
4021
|
-
Object.assign(attributes, {
|
|
4022
|
-
failurePhase: error.phase,
|
|
4023
|
-
outputLength: error.outputLength,
|
|
4024
|
-
normalizedLength: error.normalizedLength,
|
|
4025
|
-
attemptUsage: usageEventValue(error.attemptUsage),
|
|
4026
|
-
cumulativeUsage: usageEventValue(error.usage)
|
|
4027
|
-
});
|
|
4028
|
-
if (error.finishReason !== void 0) attributes.finishReason = error.finishReason;
|
|
4029
|
-
if (error.providerFinishReason !== void 0) {
|
|
4030
|
-
attributes.providerFinishReason = error.providerFinishReason;
|
|
4031
|
-
}
|
|
4032
|
-
return attributes;
|
|
4033
|
-
}
|
|
4034
|
-
function providerOutputRetryEventAttributes(error, cumulativeUsage, attemptUsage) {
|
|
4035
|
-
const resolvedAttemptUsage = attemptUsage ?? completionProviderOutputErrorUsage(error);
|
|
4036
|
-
if (resolvedAttemptUsage === void 0) return void 0;
|
|
4037
|
-
return {
|
|
4038
|
-
attemptUsage: usageEventValue(resolvedAttemptUsage),
|
|
4039
|
-
cumulativeUsage: usageEventValue(cumulativeUsage)
|
|
4040
|
-
};
|
|
4041
|
-
}
|
|
4042
|
-
function usageEventValue(usage) {
|
|
4043
|
-
const value = {
|
|
4044
|
-
inputTokens: usage.inputTokens,
|
|
4045
|
-
outputTokens: usage.outputTokens,
|
|
4046
|
-
totalTokens: usage.totalTokens,
|
|
4047
|
-
cachedInputTokens: usage.cachedInputTokens,
|
|
4048
|
-
cacheCreationInputTokens: usage.cacheCreationInputTokens
|
|
4049
|
-
};
|
|
4050
|
-
if (usage.details !== void 0) value.details = { ...usage.details };
|
|
4051
|
-
return value;
|
|
4052
|
-
}
|
|
4053
|
-
function providerMessages(messages) {
|
|
4054
|
-
const providerMessages2 = [];
|
|
4055
|
-
for (const message of messages) {
|
|
4056
|
-
if (message.role !== "tool") {
|
|
4057
|
-
providerMessages2.push(message);
|
|
4058
|
-
continue;
|
|
4059
|
-
}
|
|
4060
|
-
const results = message.content.filter((part) => part.type === "tool-result");
|
|
4061
|
-
if (results.length > 0) {
|
|
4062
|
-
providerMessages2.push({ ...message, content: results });
|
|
4063
|
-
}
|
|
4064
|
-
}
|
|
4065
|
-
return providerMessages2;
|
|
4066
|
-
}
|
|
4067
|
-
function guardrailDecisionAttributes(decision) {
|
|
4068
|
-
const attributes = {
|
|
4069
|
-
policyId: decision.policyId,
|
|
4070
|
-
guardrailId: decision.guardrailId,
|
|
4071
|
-
boundary: decision.boundary,
|
|
4072
|
-
mode: decision.mode,
|
|
4073
|
-
action: decision.action,
|
|
4074
|
-
applied: decision.applied,
|
|
4075
|
-
latencyMs: decision.latencyMs
|
|
4076
|
-
};
|
|
4077
|
-
if (decision.reason !== void 0) {
|
|
4078
|
-
attributes.reason = decision.reason;
|
|
4079
|
-
}
|
|
4080
|
-
if (decision.message !== void 0) {
|
|
4081
|
-
attributes.message = decision.message;
|
|
4082
|
-
}
|
|
4083
|
-
return attributes;
|
|
4084
|
-
}
|
|
4085
|
-
function blockedOutcomeDetails(decisions, fallbackReason) {
|
|
4086
|
-
for (let index = decisions.length - 1; index >= 0; index -= 1) {
|
|
4087
|
-
const decision = decisions[index];
|
|
4088
|
-
if (decision?.applied !== true || decision.action !== "block") continue;
|
|
4089
|
-
return decision.message === void 0 ? { reason: decision.reason ?? fallbackReason } : { reason: decision.reason ?? fallbackReason, message: decision.message };
|
|
4090
|
-
}
|
|
4091
|
-
return { reason: fallbackReason };
|
|
4092
|
-
}
|
|
4093
|
-
function observerRunEnd(outcome) {
|
|
4094
|
-
const common = {
|
|
4095
|
-
runId: outcome.runId,
|
|
4096
|
-
text: outcome.text,
|
|
4097
|
-
usage: outcome.usage,
|
|
4098
|
-
messages: outcome.messages,
|
|
4099
|
-
sources: outcome.sources,
|
|
4100
|
-
providerToolCalls: outcome.providerToolCalls,
|
|
4101
|
-
resumedFrom: outcome.resumedFrom
|
|
4102
|
-
};
|
|
4103
|
-
switch (outcome.type) {
|
|
4104
|
-
case "response":
|
|
4105
|
-
return { ...common, status: "completed", output: outcome.output };
|
|
4106
|
-
case "blocked":
|
|
4107
|
-
return { ...common, status: "blocked", stage: outcome.stage };
|
|
4108
|
-
case "interaction":
|
|
4109
|
-
return { ...common, status: "suspended", interaction: outcome.interaction };
|
|
4110
|
-
}
|
|
4111
|
-
}
|
|
4112
|
-
|
|
4113
|
-
// src/agent/agent-stream.ts
|
|
4114
|
-
function createAgentStream(run) {
|
|
4115
|
-
return new DefaultAgentStream(run);
|
|
4116
|
-
}
|
|
4117
|
-
var DefaultAgentStream = class {
|
|
4118
|
-
constructor(run) {
|
|
4119
|
-
this.run = run;
|
|
4120
|
-
let resolveResult;
|
|
4121
|
-
let rejectResult;
|
|
4122
|
-
this.resultPromise = new Promise((resolve, reject) => {
|
|
4123
|
-
resolveResult = resolve;
|
|
4124
|
-
rejectResult = reject;
|
|
4125
|
-
});
|
|
4126
|
-
this.resolveResult = resolveResult;
|
|
4127
|
-
this.rejectResult = rejectResult;
|
|
4128
|
-
this.textPromise = this.resultPromise.then((result) => result.text);
|
|
4129
|
-
void this.resultPromise.catch(() => void 0);
|
|
4130
|
-
void this.textPromise.catch(() => void 0);
|
|
4131
|
-
}
|
|
4132
|
-
run;
|
|
4133
|
-
consuming = false;
|
|
4134
|
-
completed = false;
|
|
4135
|
-
settled = false;
|
|
4136
|
-
drainScheduled = false;
|
|
4137
|
-
resultPromise;
|
|
4138
|
-
textPromise;
|
|
4139
|
-
resolveResult;
|
|
4140
|
-
rejectResult;
|
|
4141
|
-
get events() {
|
|
4142
|
-
return this;
|
|
4143
|
-
}
|
|
4144
|
-
get textStream() {
|
|
4145
|
-
return {
|
|
4146
|
-
[Symbol.asyncIterator]: () => this.consumeText()
|
|
4147
|
-
};
|
|
4148
|
-
}
|
|
4149
|
-
get text() {
|
|
4150
|
-
this.scheduleDrain();
|
|
4151
|
-
return this.textPromise;
|
|
4152
|
-
}
|
|
4153
|
-
get result() {
|
|
4154
|
-
this.scheduleDrain();
|
|
4155
|
-
return this.resultPromise;
|
|
4156
|
-
}
|
|
4157
|
-
steer(input) {
|
|
4158
|
-
return this.run.steer(input);
|
|
4159
|
-
}
|
|
4160
|
-
cancel(reason = "Agent stream cancelled.") {
|
|
4161
|
-
this.run.cancel(reason);
|
|
4162
|
-
}
|
|
4163
|
-
[Symbol.asyncIterator]() {
|
|
4164
|
-
return this.consume()[Symbol.asyncIterator]();
|
|
4165
|
-
}
|
|
4166
|
-
async *consume() {
|
|
4167
|
-
if (this.completed) {
|
|
4168
|
-
throw new Error("Agent stream has already been consumed.");
|
|
4169
|
-
}
|
|
4170
|
-
if (this.consuming) {
|
|
4171
|
-
throw new Error("Agent stream is already running.");
|
|
4172
|
-
}
|
|
4173
|
-
this.consuming = true;
|
|
4174
|
-
try {
|
|
4175
|
-
for await (const event of this.run.events()) {
|
|
4176
|
-
if (isAgentOutcome(event)) {
|
|
4177
|
-
this.settled = true;
|
|
4178
|
-
this.resolveResult(event);
|
|
4179
|
-
} else if (event.type === "error") {
|
|
4180
|
-
this.settled = true;
|
|
4181
|
-
this.rejectResult(event.error);
|
|
4182
|
-
}
|
|
4183
|
-
yield event;
|
|
4184
|
-
}
|
|
4185
|
-
} finally {
|
|
4186
|
-
if (!this.completed) {
|
|
4187
|
-
const cancellation = this.run.cancel("Agent stream consumer closed the stream.");
|
|
4188
|
-
if (!this.settled && cancellation !== void 0) {
|
|
4189
|
-
this.settled = true;
|
|
4190
|
-
this.rejectResult(cancellation);
|
|
4191
|
-
}
|
|
4192
|
-
}
|
|
4193
|
-
this.consuming = false;
|
|
4194
|
-
this.completed = true;
|
|
4195
|
-
}
|
|
4196
|
-
}
|
|
4197
|
-
async *consumeText() {
|
|
4198
|
-
for await (const event of this.consume()) {
|
|
4199
|
-
if (event.type === "text_delta") yield event.delta;
|
|
4200
|
-
}
|
|
4201
|
-
}
|
|
4202
|
-
scheduleDrain() {
|
|
4203
|
-
if (this.completed || this.consuming || this.drainScheduled) return;
|
|
4204
|
-
this.drainScheduled = true;
|
|
4205
|
-
queueMicrotask(() => {
|
|
4206
|
-
this.drainScheduled = false;
|
|
4207
|
-
if (this.completed || this.consuming) return;
|
|
4208
|
-
void this.drain();
|
|
4209
|
-
});
|
|
4210
|
-
}
|
|
4211
|
-
async drain() {
|
|
4212
|
-
try {
|
|
4213
|
-
for await (const _event of this.consume()) {
|
|
4214
|
-
}
|
|
4215
|
-
} catch (error) {
|
|
4216
|
-
if (!this.settled) {
|
|
4217
|
-
this.settled = true;
|
|
4218
|
-
this.rejectResult(error);
|
|
4219
|
-
}
|
|
4220
|
-
}
|
|
4221
|
-
}
|
|
4222
|
-
};
|
|
4223
|
-
function isAgentOutcome(event) {
|
|
4224
|
-
return event.type === "response" || event.type === "interaction" || event.type === "blocked";
|
|
4225
|
-
}
|
|
4226
|
-
|
|
4227
|
-
// src/agent/agent-tool.ts
|
|
4228
|
-
import { z } from "zod";
|
|
4229
|
-
function createAgentTool(agent, options) {
|
|
4230
|
-
if (options.suspension !== "reject") {
|
|
4231
|
-
throw new TypeError('Agent.asTool() requires suspension: "reject".');
|
|
4232
|
-
}
|
|
4233
|
-
const description = options.description ?? agent.description ?? `Prompt the ${options.name} agent.`;
|
|
4234
|
-
return createTool({
|
|
4235
|
-
name: options.name,
|
|
4236
|
-
description,
|
|
4237
|
-
inputSchema: z.object({
|
|
4238
|
-
prompt: z.string().describe("The prompt to send to the agent.")
|
|
4239
|
-
}),
|
|
4240
|
-
execute: async ({ prompt }, context) => {
|
|
4241
|
-
if (options.stream === true && context.emitStreamEvent !== void 0 && agent.model.capabilities.streaming && isStreamingCompletionModel(agent.model)) {
|
|
4242
|
-
let completed = false;
|
|
4243
|
-
let output;
|
|
4244
|
-
const childStream = agent.stream({
|
|
4245
|
-
prompt,
|
|
4246
|
-
maxTurns: options.maxTurns,
|
|
4247
|
-
abortSignal: context.abortSignal
|
|
4248
|
-
});
|
|
4249
|
-
for await (const event of childStream) {
|
|
4250
|
-
const streamEvent = {
|
|
4251
|
-
agentId: agent.id,
|
|
4252
|
-
event
|
|
4253
|
-
};
|
|
4254
|
-
if (agent.name !== void 0) {
|
|
4255
|
-
streamEvent.agentName = agent.name;
|
|
4256
|
-
}
|
|
4257
|
-
await context.emitStreamEvent(streamEvent);
|
|
4258
|
-
if (event.type === "error") {
|
|
4259
|
-
throw event.error;
|
|
4260
|
-
}
|
|
4261
|
-
if (event.type === "interaction") {
|
|
4262
|
-
throw new AgentToolSuspensionError(event);
|
|
4263
|
-
}
|
|
4264
|
-
if (event.type === "blocked") {
|
|
4265
|
-
throw new AgentRunBlockedError(event);
|
|
4266
|
-
}
|
|
4267
|
-
if (event.type === "response") {
|
|
4268
|
-
output = event.output;
|
|
4269
|
-
completed = true;
|
|
4270
|
-
}
|
|
4271
|
-
}
|
|
4272
|
-
if (!completed) {
|
|
4273
|
-
throw new Error(`Agent tool "${options.name}" ended without a final result.`);
|
|
4274
|
-
}
|
|
4275
|
-
return output;
|
|
4276
|
-
}
|
|
4277
|
-
const response = await agent.generate({
|
|
4278
|
-
prompt,
|
|
4279
|
-
maxTurns: options.maxTurns,
|
|
4280
|
-
abortSignal: context.abortSignal
|
|
4281
|
-
});
|
|
4282
|
-
if (response.type === "interaction") {
|
|
4283
|
-
throw new AgentToolSuspensionError(response);
|
|
4284
|
-
}
|
|
4285
|
-
if (response.type === "blocked") {
|
|
4286
|
-
throw new AgentRunBlockedError(response);
|
|
4287
|
-
}
|
|
4288
|
-
return response.output;
|
|
4289
|
-
}
|
|
4290
|
-
});
|
|
4291
|
-
}
|
|
4292
|
-
|
|
4293
|
-
// src/agent/ids.ts
|
|
4294
|
-
function normalizeAgentId(id) {
|
|
4295
|
-
if (typeof id !== "string") {
|
|
4296
|
-
throw new TypeError("Agent id must be a string.");
|
|
4297
|
-
}
|
|
4298
|
-
const normalized = id.trim();
|
|
4299
|
-
if (normalized.length === 0) {
|
|
4300
|
-
throw new TypeError("Agent id must be a non-empty string.");
|
|
4301
|
-
}
|
|
4302
|
-
return normalized;
|
|
4303
|
-
}
|
|
4304
|
-
|
|
4305
|
-
// src/agent/resolve-options.ts
|
|
4306
|
-
var resolvedAgentOptions = /* @__PURE__ */ Symbol("resolvedAgentOptions");
|
|
4307
|
-
function resolveAgentOptions(options) {
|
|
4308
|
-
if (isInternalAgentOptions(options)) {
|
|
4309
|
-
return options;
|
|
4310
|
-
}
|
|
4311
|
-
const toolsByName = /* @__PURE__ */ new Map();
|
|
4312
|
-
const providerTools = [];
|
|
4313
|
-
const toolIndexes = [];
|
|
4314
|
-
for (const tool of options.tools ?? []) {
|
|
4315
|
-
if (isProviderTool(tool)) {
|
|
4316
|
-
providerTools.push(tool);
|
|
4317
|
-
} else if (isToolIndex(tool)) {
|
|
4318
|
-
toolIndexes.push(tool);
|
|
4319
|
-
} else if (tool.kind === "tool-index") {
|
|
4320
|
-
throw new TypeError("Invalid tool index: search, tools, and a numeric topK are required.");
|
|
4321
|
-
} else if (isMcpTool(tool)) {
|
|
4322
|
-
throw new TypeError(
|
|
4323
|
-
`MCP tool "${tool.name}" must be registered through Agent.mcpServers, not Agent.tools.`
|
|
4324
|
-
);
|
|
4325
|
-
} else {
|
|
4326
|
-
addUniqueTool(toolsByName, tool, "local tool");
|
|
4327
|
-
}
|
|
4328
|
-
}
|
|
4329
|
-
if (options.skills !== void 0) {
|
|
4330
|
-
for (const tool of options.skills.tools) {
|
|
4331
|
-
if (isMcpTool(tool)) {
|
|
4332
|
-
throw new TypeError(
|
|
4333
|
-
`MCP tool "${tool.name}" must be registered through Agent.mcpServers, not Agent.skills.`
|
|
4334
|
-
);
|
|
4335
|
-
}
|
|
4336
|
-
addUniqueTool(toolsByName, tool, "skill tool");
|
|
4337
|
-
}
|
|
4338
|
-
}
|
|
4339
|
-
const memory = resolveAgentMemory(options);
|
|
4340
|
-
const instructions = [options.instructions, options.skills?.instructions].filter((part) => part !== void 0 && part.length > 0).join("\n\n");
|
|
4341
|
-
return {
|
|
4342
|
-
id: options.id,
|
|
4343
|
-
name: options.name,
|
|
4344
|
-
description: options.description,
|
|
4345
|
-
model: options.model,
|
|
4346
|
-
instructions: instructions.length === 0 ? void 0 : instructions,
|
|
4347
|
-
context: [...options.context ?? []],
|
|
4348
|
-
temperature: options.temperature,
|
|
4349
|
-
maxTokens: options.maxTokens,
|
|
4350
|
-
providerOptions: options.providerOptions,
|
|
4351
|
-
controls: options.controls,
|
|
4352
|
-
retries: options.retries,
|
|
4353
|
-
tools: [...toolsByName.values()],
|
|
4354
|
-
mcpServers: [...options.mcpServers ?? []],
|
|
4355
|
-
providerTools,
|
|
4356
|
-
toolIndexes,
|
|
4357
|
-
toolChoice: options.toolChoice,
|
|
4358
|
-
defaultMaxTurns: options.maxTurns,
|
|
4359
|
-
lifecycle: options.lifecycle,
|
|
4360
|
-
outputSchema: options.outputSchema,
|
|
4361
|
-
observability: options.observability,
|
|
4362
|
-
guardrails: options.guardrails === void 0 ? [] : appendGuardrailPolicies([], options.guardrails),
|
|
4363
|
-
middlewares: [...options.middlewares ?? []],
|
|
4364
|
-
memory
|
|
4365
|
-
};
|
|
4366
|
-
}
|
|
4367
|
-
function markResolvedAgentOptions(options) {
|
|
4368
|
-
return {
|
|
4369
|
-
...options,
|
|
4370
|
-
[resolvedAgentOptions]: true
|
|
4371
|
-
};
|
|
4372
|
-
}
|
|
4373
|
-
function isInternalAgentOptions(options) {
|
|
4374
|
-
return options[resolvedAgentOptions] === true;
|
|
4375
|
-
}
|
|
4376
|
-
function resolveAgentMemory(options) {
|
|
4377
|
-
if (options.memory === void 0) {
|
|
4378
|
-
return void 0;
|
|
4379
|
-
}
|
|
4380
|
-
const { store, ...memoryOptions } = options.memory;
|
|
4381
|
-
const resolvedOptions = resolveMemoryOptions(memoryOptions);
|
|
4382
|
-
if (resolvedOptions.compaction !== void 0 && store.compaction === void 0) {
|
|
4383
|
-
throw new TypeError(
|
|
4384
|
-
"Memory compaction requires a store with the optional compaction capability."
|
|
4385
|
-
);
|
|
4386
|
-
}
|
|
4387
|
-
return { store, ...resolvedOptions };
|
|
4388
|
-
}
|
|
4389
|
-
function addUniqueTool(tools, tool, source) {
|
|
4390
|
-
if (tools.has(tool.name)) {
|
|
4391
|
-
throw new TypeError(`Duplicate ${source} name "${tool.name}".`);
|
|
4392
|
-
}
|
|
4393
|
-
tools.set(tool.name, tool);
|
|
4394
|
-
}
|
|
4395
|
-
|
|
4396
|
-
// src/agent/snapshot.ts
|
|
4397
|
-
function snapshotAgentContext(inputs) {
|
|
4398
|
-
const context = (inputs ?? []).map(snapshotContextInput);
|
|
4399
|
-
for (const input of context) {
|
|
4400
|
-
if (!isVectorContext(input)) continue;
|
|
4401
|
-
assertPositiveSearchLimit(input.topK);
|
|
4402
|
-
assertFiniteMinScore(input.minScore);
|
|
4403
|
-
}
|
|
4404
|
-
return Object.freeze(context);
|
|
4405
|
-
}
|
|
4406
|
-
function snapshotAgentObservability(observability) {
|
|
4407
|
-
if (observability === void 0) return void 0;
|
|
4408
|
-
const observers = {};
|
|
4409
|
-
for (const [name, observer] of Object.entries(observability.observers)) {
|
|
4410
|
-
if (name.trim().length === 0) {
|
|
4411
|
-
throw new TypeError("Agent observer names must not be empty.");
|
|
4412
|
-
}
|
|
4413
|
-
if (typeof observer !== "object" || observer === null || typeof observer.startRun !== "function") {
|
|
4414
|
-
throw new TypeError(`Agent observer "${name}" must implement startRun().`);
|
|
4415
|
-
}
|
|
4416
|
-
observers[name] = observer;
|
|
4417
|
-
}
|
|
4418
|
-
if (observability.primaryTrace !== void 0 && !(observability.primaryTrace in observers)) {
|
|
4419
|
-
throw new TypeError(
|
|
4420
|
-
`Agent primaryTrace "${observability.primaryTrace}" must name a configured observer.`
|
|
4421
|
-
);
|
|
4422
|
-
}
|
|
4423
|
-
const errorPolicy = observability.errorPolicy ?? "ignore";
|
|
4424
|
-
if (errorPolicy !== "ignore" && errorPolicy !== "throw") {
|
|
4425
|
-
throw new TypeError('Agent observability.errorPolicy must be "ignore" or "throw".');
|
|
4426
|
-
}
|
|
4427
|
-
let snapshot = {
|
|
4428
|
-
observers: Object.freeze(observers),
|
|
4429
|
-
errorPolicy
|
|
4430
|
-
};
|
|
4431
|
-
if (observability.primaryTrace !== void 0) {
|
|
4432
|
-
snapshot = { ...snapshot, primaryTrace: observability.primaryTrace };
|
|
4433
|
-
}
|
|
4434
|
-
return Object.freeze(snapshot);
|
|
4435
|
-
}
|
|
4436
|
-
function snapshotGuardrailPolicies(policies) {
|
|
4437
|
-
return Object.freeze((policies ?? []).map(snapshotGuardrailPolicy));
|
|
4438
|
-
}
|
|
4439
|
-
function snapshotAgentMemory(memory) {
|
|
4440
|
-
if (memory === void 0) {
|
|
4441
|
-
return void 0;
|
|
4442
|
-
}
|
|
4443
|
-
const compaction = memory.compaction === void 0 ? void 0 : Object.freeze({
|
|
4444
|
-
...memory.compaction,
|
|
4445
|
-
trigger: Object.freeze({ ...memory.compaction.trigger }),
|
|
4446
|
-
retention: Object.freeze({ ...memory.compaction.retention }),
|
|
4447
|
-
conflictRetries: memory.compaction.conflictRetries === false ? false : Object.freeze({ ...memory.compaction.conflictRetries })
|
|
4448
|
-
});
|
|
4449
|
-
let snapshot = {
|
|
4450
|
-
store: memory.store,
|
|
4451
|
-
savePolicy: memory.savePolicy
|
|
4452
|
-
};
|
|
4453
|
-
if (compaction !== void 0) {
|
|
4454
|
-
snapshot = { ...snapshot, compaction };
|
|
4455
|
-
}
|
|
4456
|
-
return Object.freeze(snapshot);
|
|
4457
|
-
}
|
|
4458
|
-
function cloneFrozenPlainData(value) {
|
|
4459
|
-
if (Array.isArray(value)) {
|
|
4460
|
-
return Object.freeze(value.map(cloneFrozenPlainData));
|
|
4461
|
-
}
|
|
4462
|
-
if (typeof value !== "object" || value === null) {
|
|
4463
|
-
return value;
|
|
4464
|
-
}
|
|
4465
|
-
const prototype = Object.getPrototypeOf(value);
|
|
4466
|
-
if (prototype !== Object.prototype && prototype !== null) {
|
|
4467
|
-
return value;
|
|
4468
|
-
}
|
|
4469
|
-
const clone = Object.fromEntries(
|
|
4470
|
-
Object.entries(value).map(([key, item]) => [key, cloneFrozenPlainData(item)])
|
|
4471
|
-
);
|
|
4472
|
-
return Object.freeze(clone);
|
|
4473
|
-
}
|
|
4474
|
-
function snapshotContextInput(input) {
|
|
4475
|
-
if (!isVectorContext(input)) {
|
|
4476
|
-
let document = {
|
|
4477
|
-
id: input.id,
|
|
4478
|
-
text: input.text
|
|
4479
|
-
};
|
|
4480
|
-
if (input.additionalProps !== void 0) {
|
|
4481
|
-
document = {
|
|
4482
|
-
...document,
|
|
4483
|
-
additionalProps: cloneFrozenPlainData(input.additionalProps)
|
|
4484
|
-
};
|
|
4485
|
-
}
|
|
4486
|
-
return Object.freeze(document);
|
|
4487
|
-
}
|
|
4488
|
-
const format = input.format;
|
|
4489
|
-
let shared = {
|
|
4490
|
-
kind: "vector-context",
|
|
4491
|
-
store: input.store,
|
|
4492
|
-
topK: input.topK
|
|
4493
|
-
};
|
|
4494
|
-
if (input.minScore !== void 0) {
|
|
4495
|
-
shared = { ...shared, minScore: input.minScore };
|
|
4496
|
-
}
|
|
4497
|
-
if (input.filter !== void 0) {
|
|
4498
|
-
shared = { ...shared, filter: cloneFrozenPlainData(input.filter) };
|
|
4499
|
-
}
|
|
4500
|
-
if (input.retries !== void 0) {
|
|
4501
|
-
shared = { ...shared, retries: cloneFrozenPlainData(input.retries) };
|
|
4502
|
-
}
|
|
4503
|
-
if (format !== void 0) {
|
|
4504
|
-
shared = {
|
|
4505
|
-
...shared,
|
|
4506
|
-
format: (result) => format.call(input, result)
|
|
4507
|
-
};
|
|
4508
|
-
}
|
|
4509
|
-
if (!("models" in input) || input.models === void 0) {
|
|
4510
|
-
return Object.freeze({ ...shared, store: input.store, model: input.model });
|
|
4511
|
-
}
|
|
4512
|
-
let context = {
|
|
4513
|
-
...shared,
|
|
4514
|
-
store: input.store,
|
|
4515
|
-
models: input.models
|
|
4516
|
-
};
|
|
4517
|
-
if (input.fusion !== void 0) {
|
|
4518
|
-
context = { ...context, fusion: input.fusion };
|
|
4519
|
-
}
|
|
4520
|
-
return Object.freeze(context);
|
|
4521
|
-
}
|
|
4522
|
-
function snapshotGuardrailPolicy(policy) {
|
|
4523
|
-
return Object.freeze({
|
|
4524
|
-
...policy,
|
|
4525
|
-
input: Object.freeze([...policy.input]),
|
|
4526
|
-
output: Object.freeze([...policy.output])
|
|
4527
|
-
});
|
|
4528
|
-
}
|
|
4529
|
-
|
|
4530
|
-
// src/agent/tool-catalog.ts
|
|
4531
|
-
function prepareAgentTools(options) {
|
|
4532
|
-
assertUniqueMcpServerNames(options.mcpServers ?? []);
|
|
4533
|
-
const mcpServers = Object.freeze((options.mcpServers ?? []).map(snapshotMcpServer));
|
|
4534
|
-
const configuredTools = [...options.tools ?? []];
|
|
4535
|
-
const staticTools = [...configuredTools, ...mcpServers.flatMap((server) => server.tools)];
|
|
4536
|
-
const toolIndexes = (options.toolIndexes ?? []).map(snapshotToolIndex);
|
|
4537
|
-
const providerTools = (options.providerTools ?? []).map(snapshotProviderTool);
|
|
4538
|
-
assertUniqueAgentToolNames({ staticTools, providerTools, toolIndexes });
|
|
4539
|
-
const toolsByName = new Map(staticTools.map((tool) => [tool.name, tool]));
|
|
4540
|
-
for (const index of toolIndexes) {
|
|
4541
|
-
for (const tool of index.tools) {
|
|
4542
|
-
toolsByName.set(tool.name, tool);
|
|
4543
|
-
}
|
|
4544
|
-
}
|
|
4545
|
-
const tools = Object.freeze([...toolsByName.values()]);
|
|
4546
|
-
const publicState = Object.freeze({
|
|
4547
|
-
configuredTools: Object.freeze(configuredTools),
|
|
4548
|
-
staticTools: Object.freeze(staticTools),
|
|
4549
|
-
providerTools: Object.freeze(providerTools),
|
|
4550
|
-
toolIndexes: Object.freeze(toolIndexes)
|
|
4551
|
-
});
|
|
4552
|
-
return { mcpServers, tools, publicState, toolsByName };
|
|
4553
|
-
}
|
|
4554
|
-
function assertUniqueAgentToolNames(options) {
|
|
4555
|
-
const owners = /* @__PURE__ */ new Map();
|
|
4556
|
-
for (const tool of options.staticTools) {
|
|
4557
|
-
registerToolOwner(owners, tool.name, isMcpTool(tool) ? "MCP tool" : "local or skill tool");
|
|
4558
|
-
}
|
|
4559
|
-
for (const tool of options.providerTools) {
|
|
4560
|
-
registerToolOwner(owners, tool.name, "provider tool");
|
|
4561
|
-
}
|
|
4562
|
-
for (const [indexPosition, index] of options.toolIndexes.entries()) {
|
|
4563
|
-
if (!isToolIndex(index)) {
|
|
4564
|
-
throw new TypeError("Invalid tool index: search, tools, and a numeric topK are required.");
|
|
4565
|
-
}
|
|
4566
|
-
assertPositiveSearchLimit(index.topK);
|
|
4567
|
-
assertFiniteMinScore(index.minScore);
|
|
4568
|
-
for (const tool of index.tools) {
|
|
4569
|
-
if (isMcpTool(tool)) {
|
|
4570
|
-
throw new TypeError(
|
|
4571
|
-
`MCP tool "${tool.name}" must be registered through Agent.mcpServers, not a tool index.`
|
|
4572
|
-
);
|
|
4573
|
-
}
|
|
4574
|
-
registerToolOwner(owners, tool.name, `tool index ${indexPosition + 1}`);
|
|
4575
|
-
}
|
|
4576
|
-
}
|
|
4577
|
-
}
|
|
4578
|
-
function registerToolOwner(owners, name, owner) {
|
|
4579
|
-
const existing = owners.get(name);
|
|
4580
|
-
if (existing !== void 0) {
|
|
4581
|
-
throw new TypeError(
|
|
4582
|
-
`Tool name collision for "${name}" between ${existing} and ${owner}. Tool names must be unique across every Agent tool source.`
|
|
4583
|
-
);
|
|
4584
|
-
}
|
|
4585
|
-
owners.set(name, owner);
|
|
4586
|
-
}
|
|
4587
|
-
function snapshotProviderTool(tool) {
|
|
4588
|
-
let snapshot = {
|
|
4589
|
-
...tool
|
|
4590
|
-
};
|
|
4591
|
-
if (tool.configuration !== void 0) {
|
|
4592
|
-
snapshot = { ...snapshot, configuration: cloneFrozenPlainData(tool.configuration) };
|
|
4593
|
-
}
|
|
4594
|
-
return Object.freeze(snapshot);
|
|
4595
|
-
}
|
|
4596
|
-
function snapshotMcpServer(server) {
|
|
4597
|
-
if (server.name.trim() === "") {
|
|
4598
|
-
throw new TypeError("MCP server name must not be empty.");
|
|
4599
|
-
}
|
|
4600
|
-
for (const tool of server.tools) {
|
|
4601
|
-
if (!isMcpTool(tool)) {
|
|
4602
|
-
throw new TypeError(`MCP server "${server.name}" contains an invalid MCP tool.`);
|
|
4603
|
-
}
|
|
4604
|
-
if (tool.mcp.serverName !== server.name) {
|
|
4605
|
-
throw new TypeError(
|
|
4606
|
-
`MCP tool "${tool.name}" belongs to server "${tool.mcp.serverName}", not "${server.name}".`
|
|
4607
|
-
);
|
|
4608
|
-
}
|
|
4609
|
-
}
|
|
4610
|
-
const tools = server.tools.map(snapshotMcpTool);
|
|
4611
|
-
let snapshot = {
|
|
4612
|
-
name: server.name,
|
|
4613
|
-
tools: Object.freeze(tools)
|
|
4614
|
-
};
|
|
4615
|
-
if (server.serverInfo !== void 0) {
|
|
4616
|
-
snapshot = { ...snapshot, serverInfo: cloneFrozenPlainData(server.serverInfo) };
|
|
4617
|
-
}
|
|
4618
|
-
if (server.capabilities !== void 0) {
|
|
4619
|
-
snapshot = { ...snapshot, capabilities: cloneFrozenPlainData(server.capabilities) };
|
|
4620
|
-
}
|
|
4621
|
-
if (server.instructions !== void 0) {
|
|
4622
|
-
snapshot = { ...snapshot, instructions: server.instructions };
|
|
4623
|
-
}
|
|
4624
|
-
return Object.freeze(snapshot);
|
|
4625
|
-
}
|
|
4626
|
-
function snapshotMcpTool(tool) {
|
|
4627
|
-
if (Object.isFrozen(tool) && Object.isFrozen(tool.mcp)) {
|
|
4628
|
-
return tool;
|
|
4629
|
-
}
|
|
4630
|
-
const parseInput = tool.parseInput;
|
|
4631
|
-
let snapshot = {
|
|
4632
|
-
name: tool.name,
|
|
4633
|
-
mcp: Object.freeze({ ...tool.mcp }),
|
|
4634
|
-
definition: (prompt) => tool.definition(prompt),
|
|
4635
|
-
call: (args, context) => tool.call(args, context)
|
|
4636
|
-
};
|
|
4637
|
-
if (tool.requiresApproval !== void 0) {
|
|
4638
|
-
snapshot = { ...snapshot, requiresApproval: tool.requiresApproval };
|
|
4639
|
-
}
|
|
4640
|
-
if (parseInput !== void 0) {
|
|
4641
|
-
snapshot = {
|
|
4642
|
-
...snapshot,
|
|
4643
|
-
parseInput: (args) => parseInput.call(tool, args)
|
|
4644
|
-
};
|
|
4645
|
-
}
|
|
4646
|
-
return Object.freeze(snapshot);
|
|
4647
|
-
}
|
|
4648
|
-
function assertUniqueMcpServerNames(servers) {
|
|
4649
|
-
const names = /* @__PURE__ */ new Set();
|
|
4650
|
-
for (const server of servers) {
|
|
4651
|
-
if (names.has(server.name)) {
|
|
4652
|
-
throw new TypeError(`Duplicate MCP server name "${server.name}".`);
|
|
4653
|
-
}
|
|
4654
|
-
names.add(server.name);
|
|
4655
|
-
}
|
|
4656
|
-
}
|
|
4657
|
-
function snapshotToolIndex(index) {
|
|
4658
|
-
const inspect = index.inspect;
|
|
4659
|
-
let snapshot = {
|
|
4660
|
-
kind: "tool-index",
|
|
4661
|
-
tools: Object.freeze([...index.tools]),
|
|
4662
|
-
topK: index.topK,
|
|
4663
|
-
search: (options) => index.search(options)
|
|
4664
|
-
};
|
|
4665
|
-
if (index.minScore !== void 0) {
|
|
4666
|
-
snapshot = { ...snapshot, minScore: index.minScore };
|
|
4667
|
-
}
|
|
4668
|
-
if (index.filter !== void 0) {
|
|
4669
|
-
snapshot = { ...snapshot, filter: cloneFrozenPlainData(index.filter) };
|
|
4670
|
-
}
|
|
4671
|
-
if (inspect !== void 0) {
|
|
4672
|
-
snapshot = {
|
|
4673
|
-
...snapshot,
|
|
4674
|
-
inspect: (request) => inspect.call(index, request)
|
|
4675
|
-
};
|
|
4676
|
-
}
|
|
4677
|
-
return Object.freeze(snapshot);
|
|
4678
|
-
}
|
|
4679
|
-
|
|
4680
|
-
// src/agent/agent.ts
|
|
4681
|
-
var DEFAULT_MAX_TURNS = 20;
|
|
4682
|
-
var Agent = class {
|
|
4683
|
-
id;
|
|
4684
|
-
name;
|
|
4685
|
-
description;
|
|
4686
|
-
model;
|
|
4687
|
-
instructions;
|
|
4688
|
-
context;
|
|
4689
|
-
temperature;
|
|
4690
|
-
maxTokens;
|
|
4691
|
-
providerOptions;
|
|
4692
|
-
controls;
|
|
4693
|
-
retries;
|
|
4694
|
-
mcpServers;
|
|
4695
|
-
tools;
|
|
4696
|
-
toolChoice;
|
|
4697
|
-
defaultMaxTurns;
|
|
4698
|
-
lifecycle;
|
|
4699
|
-
outputSchema;
|
|
4700
|
-
observability;
|
|
4701
|
-
guardrails;
|
|
4702
|
-
middlewares;
|
|
4703
|
-
memory;
|
|
4704
|
-
constructor(options) {
|
|
4705
|
-
const resolved = resolveAgentOptions(options);
|
|
4706
|
-
this.id = normalizeAgentId(resolved.id);
|
|
4707
|
-
this.name = resolved.name;
|
|
4708
|
-
this.description = resolved.description;
|
|
4709
|
-
this.model = resolved.model;
|
|
4710
|
-
this.instructions = resolved.instructions;
|
|
4711
|
-
this.context = snapshotAgentContext(resolved.context);
|
|
4712
|
-
this.temperature = resolved.temperature;
|
|
4713
|
-
this.maxTokens = resolved.maxTokens;
|
|
4714
|
-
if (resolved.providerOptions !== void 0) {
|
|
4715
|
-
assertJsonObject(resolved.providerOptions, "Agent providerOptions");
|
|
4716
|
-
}
|
|
4717
|
-
this.providerOptions = cloneFrozenPlainData(resolved.providerOptions);
|
|
4718
|
-
assertCompletionControlsSupported(this.model, resolved.controls);
|
|
4719
|
-
this.controls = cloneFrozenPlainData(resolved.controls);
|
|
4720
|
-
this.retries = cloneFrozenPlainData(resolved.retries);
|
|
4721
|
-
const preparedTools = prepareAgentTools(resolved);
|
|
4722
|
-
this.mcpServers = preparedTools.mcpServers;
|
|
4723
|
-
this.tools = preparedTools.tools;
|
|
4724
|
-
registerAgentToolState(this, preparedTools.publicState, preparedTools.toolsByName);
|
|
4725
|
-
this.toolChoice = cloneFrozenPlainData(resolved.toolChoice);
|
|
4726
|
-
this.defaultMaxTurns = assertNonnegativeSafeInteger(
|
|
4727
|
-
resolved.defaultMaxTurns ?? DEFAULT_MAX_TURNS,
|
|
4728
|
-
"maxTurns"
|
|
4729
|
-
);
|
|
4730
|
-
this.lifecycle = resolved.lifecycle;
|
|
4731
|
-
this.outputSchema = resolved.outputSchema;
|
|
4732
|
-
registerAgentProviderOutputSchema(this, resolved.outputSchema);
|
|
4733
|
-
this.observability = snapshotAgentObservability(resolved.observability);
|
|
4734
|
-
this.guardrails = snapshotGuardrailPolicies(resolved.guardrails);
|
|
4735
|
-
this.middlewares = Object.freeze([...resolved.middlewares ?? []]);
|
|
4736
|
-
this.memory = snapshotAgentMemory(resolved.memory);
|
|
4737
|
-
}
|
|
4738
|
-
generate(options) {
|
|
4739
|
-
return AgentRun.fromAgent(this, options).generate();
|
|
4740
|
-
}
|
|
4741
|
-
resume(continuation, response, settings = {}) {
|
|
4742
|
-
return this.generate({ continuation, response, ...settings });
|
|
4743
|
-
}
|
|
4744
|
-
stream(options) {
|
|
4745
|
-
const run = AgentRun.fromAgent(this, options);
|
|
4746
|
-
if (!this.model.capabilities.streaming || !isStreamingCompletionModel(this.model)) {
|
|
4747
|
-
throw new Error("This completion model does not support streaming");
|
|
4748
|
-
}
|
|
4749
|
-
return createAgentStream(run);
|
|
4750
|
-
}
|
|
4751
|
-
compactMemory(options) {
|
|
4752
|
-
if (typeof options !== "object" || options === null || Array.isArray(options)) {
|
|
4753
|
-
throw new TypeError("Manual memory compaction requires an options object.");
|
|
4754
|
-
}
|
|
4755
|
-
const scope = normalizeMemoryScope(options.session, "Manual memory compaction");
|
|
4756
|
-
const memory = new AgentRunMemory(this, scope, []);
|
|
4757
|
-
return memory.compact(
|
|
4758
|
-
`manual-memory-compaction:${globalThis.crypto.randomUUID()}`,
|
|
4759
|
-
options.abortSignal
|
|
4760
|
-
);
|
|
4761
|
-
}
|
|
4762
|
-
asTool(options) {
|
|
4763
|
-
return createAgentTool(this, options);
|
|
4764
|
-
}
|
|
4765
|
-
getTool(toolName) {
|
|
4766
|
-
return getRegisteredAgentTool(this, toolName);
|
|
4767
|
-
}
|
|
4768
|
-
async callTool(toolName, args, context) {
|
|
4769
|
-
const tool = this.getTool(toolName);
|
|
4770
|
-
if (tool === void 0) {
|
|
4771
|
-
throw new ToolNotFoundError(toolName);
|
|
4772
|
-
}
|
|
4773
|
-
return prepareToolCall(tool, args).call(context ?? {});
|
|
4774
|
-
}
|
|
4775
|
-
};
|
|
4776
|
-
|
|
4777
|
-
export {
|
|
4778
|
-
getAgentToolState,
|
|
4779
|
-
createHook,
|
|
4780
|
-
createVectorContext,
|
|
4781
|
-
isVectorContext,
|
|
4782
|
-
withInternalAgentRunOptions,
|
|
4783
|
-
markResolvedAgentOptions,
|
|
4784
|
-
Agent
|
|
4785
|
-
};
|
|
4786
|
-
//# sourceMappingURL=chunk-XU54PLSD.js.map
|