@sixb/core 0.1.8 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/index.js +77 -89
- package/dist/actions/index.js.map +1 -1
- package/dist/actions/run-dispatch.d.ts.map +1 -1
- package/dist/actions/types/context.d.ts +2 -0
- package/dist/actions/types/context.d.ts.map +1 -1
- package/dist/actions/validation.d.ts +1 -1
- package/dist/actions/validation.d.ts.map +1 -1
- package/dist/actions/worker.js +33 -37
- package/dist/actions/worker.js.map +2 -2
- package/dist/agents/adapters.d.ts +3 -3
- package/dist/agents/{context.d.ts → context/entries.d.ts} +3 -3
- package/dist/agents/context/entries.d.ts.map +1 -0
- package/dist/agents/context/index.d.ts +4 -0
- package/dist/agents/context/index.d.ts.map +1 -0
- package/dist/agents/context/index.js +19 -0
- package/dist/agents/{streams.js.map → context/index.js.map} +1 -1
- package/dist/agents/context-model.d.ts +1 -1
- package/dist/agents/context-model.d.ts.map +1 -1
- package/dist/agents/context-resolution.d.ts +1 -1
- package/dist/agents/context-resolution.d.ts.map +1 -1
- package/dist/agents/index.d.ts +4 -4
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +192 -204
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/message.d.ts +1 -1
- package/dist/agents/message.d.ts.map +1 -1
- package/dist/agents/model-loop.d.ts +2 -0
- package/dist/agents/model-loop.d.ts.map +1 -1
- package/dist/agents/request.d.ts +1 -1
- package/dist/agents/request.d.ts.map +1 -1
- package/dist/agents/streams/index.d.ts +4 -0
- package/dist/agents/streams/index.d.ts.map +1 -0
- package/dist/agents/streams/index.js +20 -0
- package/dist/{chunk-y64skrwp.js.map → agents/streams/index.js.map} +1 -1
- package/dist/agents/streams/internal.d.ts +3 -0
- package/dist/agents/streams/internal.d.ts.map +1 -0
- package/dist/agents/streams/internal.js +40 -0
- package/dist/agents/{context.js.map → streams/internal.js.map} +1 -1
- package/dist/agents/{streams.d.ts → streams/protocol.d.ts} +5 -5
- package/dist/agents/streams/protocol.d.ts.map +1 -0
- package/dist/agents/types.d.ts +1 -1
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/validation.d.ts.map +1 -1
- package/dist/auth/index.d.ts +0 -1
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +96 -108
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/strategy.js +8 -9
- package/dist/auth/strategy.js.map +1 -1
- package/dist/authorization/index.js +51 -56
- package/dist/authorization/index.js.map +1 -1
- package/dist/blob-storage/browser.js +15 -17
- package/dist/blob-storage/browser.js.map +1 -1
- package/dist/blob-storage/index.js +36 -38
- package/dist/blob-storage/index.js.map +1 -1
- package/dist/bootstrap/discovery.d.ts +14 -1
- package/dist/bootstrap/discovery.d.ts.map +1 -1
- package/dist/bootstrap/index.d.ts +2 -2
- package/dist/bootstrap/index.d.ts.map +1 -1
- package/dist/bootstrap/index.js +79 -88
- package/dist/bootstrap/index.js.map +1 -1
- package/dist/broker/index.js +8 -10
- package/dist/broker/index.js.map +1 -1
- package/dist/{chunk-k34z5rvh.js → chunk-0rdrecsb.js} +18 -18
- package/dist/{chunk-k34z5rvh.js.map → chunk-0rdrecsb.js.map} +2 -2
- package/dist/{chunk-q0k9nc5a.js → chunk-0w35wavj.js} +98 -98
- package/dist/{chunk-q0k9nc5a.js.map → chunk-0w35wavj.js.map} +2 -2
- package/dist/chunk-0y39rgsb.js +43 -0
- package/dist/{chunk-c15dr03f.js.map → chunk-0y39rgsb.js.map} +2 -2
- package/dist/{chunk-k522z7v6.js → chunk-17kfctj6.js} +16 -11
- package/dist/chunk-17kfctj6.js.map +10 -0
- package/dist/{chunk-aa2pen2v.js → chunk-1enhpacz.js} +188 -175
- package/dist/{chunk-aa2pen2v.js.map → chunk-1enhpacz.js.map} +2 -2
- package/dist/{chunk-5gd7tpv6.js → chunk-2c4j899j.js} +4 -4
- package/dist/{chunk-5gd7tpv6.js.map → chunk-2c4j899j.js.map} +2 -2
- package/dist/{chunk-fvt9rjsa.js → chunk-38zv5rkr.js} +4 -4
- package/dist/{chunk-fvt9rjsa.js.map → chunk-38zv5rkr.js.map} +1 -1
- package/dist/{chunk-w3e09qqk.js → chunk-39tqv9hz.js} +24 -24
- package/dist/{chunk-w3e09qqk.js.map → chunk-39tqv9hz.js.map} +2 -2
- package/dist/{chunk-04b07a9q.js → chunk-3bh94gbw.js} +13 -13
- package/dist/{chunk-04b07a9q.js.map → chunk-3bh94gbw.js.map} +2 -2
- package/dist/{chunk-8m5ejdpn.js → chunk-3f7veca0.js} +4 -4
- package/dist/{chunk-8m5ejdpn.js.map → chunk-3f7veca0.js.map} +2 -2
- package/dist/chunk-3frsnm7x.js +32 -0
- package/dist/chunk-3frsnm7x.js.map +11 -0
- package/dist/{chunk-n2w475r0.js → chunk-3tgwrcyh.js} +81 -81
- package/dist/{chunk-n2w475r0.js.map → chunk-3tgwrcyh.js.map} +2 -2
- package/dist/{chunk-mwsxn98e.js → chunk-52hbv0ak.js} +170 -170
- package/dist/{chunk-mwsxn98e.js.map → chunk-52hbv0ak.js.map} +4 -4
- package/dist/{chunk-nf4r78r4.js → chunk-5a4a52tq.js} +4 -4
- package/dist/{chunk-nf4r78r4.js.map → chunk-5a4a52tq.js.map} +2 -2
- package/dist/{chunk-rte5sm3z.js → chunk-5hz0fnca.js} +23 -23
- package/dist/{chunk-rte5sm3z.js.map → chunk-5hz0fnca.js.map} +2 -2
- package/dist/chunk-653vwrzr.js +39 -0
- package/dist/chunk-653vwrzr.js.map +10 -0
- package/dist/{chunk-qw9gvjv5.js → chunk-72w2pxk7.js} +13 -13
- package/dist/{chunk-qw9gvjv5.js.map → chunk-72w2pxk7.js.map} +2 -2
- package/dist/chunk-7apz6hg4.js +50 -0
- package/dist/{chunk-jq43kdvk.js.map → chunk-7apz6hg4.js.map} +2 -2
- package/dist/chunk-7bs40fe1.js +218 -0
- package/dist/{chunk-p1rzczbt.js.map → chunk-7bs40fe1.js.map} +3 -3
- package/dist/chunk-7zgecwy1.js +113 -0
- package/dist/chunk-7zgecwy1.js.map +10 -0
- package/dist/{chunk-pc7ys28c.js → chunk-860dwwy0.js} +29 -29
- package/dist/{chunk-pc7ys28c.js.map → chunk-860dwwy0.js.map} +2 -2
- package/dist/chunk-8vj0rjgs.js +165 -0
- package/dist/chunk-8vj0rjgs.js.map +15 -0
- package/dist/{chunk-7y0f6rf1.js → chunk-92vk7gta.js} +58 -58
- package/dist/chunk-92vk7gta.js.map +10 -0
- package/dist/{chunk-rafagrwr.js → chunk-93csa55g.js} +45 -17
- package/dist/chunk-93csa55g.js.map +11 -0
- package/dist/{chunk-d8qkxt2v.js → chunk-98cw09sw.js} +7 -7
- package/dist/chunk-98cw09sw.js.map +10 -0
- package/dist/{chunk-n4khvw9n.js → chunk-9qsh3p5y.js} +17 -17
- package/dist/{chunk-n4khvw9n.js.map → chunk-9qsh3p5y.js.map} +2 -2
- package/dist/{chunk-4a849fr1.js → chunk-9tc8dxmn.js} +1 -1
- package/dist/{chunk-9nbmsvn5.js → chunk-9vx5e9g1.js} +9 -9
- package/dist/{chunk-9nbmsvn5.js.map → chunk-9vx5e9g1.js.map} +2 -2
- package/dist/{chunk-f26bck4t.js → chunk-an5tt9y0.js} +353 -353
- package/dist/{chunk-f26bck4t.js.map → chunk-an5tt9y0.js.map} +2 -2
- package/dist/{chunk-2dw777qw.js → chunk-ap0g1g74.js} +37 -82
- package/dist/{chunk-2dw777qw.js.map → chunk-ap0g1g74.js.map} +3 -4
- package/dist/{chunk-v4en4jc2.js → chunk-awbhdqyc.js} +7 -7
- package/dist/{chunk-v4en4jc2.js.map → chunk-awbhdqyc.js.map} +2 -2
- package/dist/{chunk-ka3a2ft3.js → chunk-b19g04jk.js} +12 -12
- package/dist/{chunk-ka3a2ft3.js.map → chunk-b19g04jk.js.map} +2 -2
- package/dist/{chunk-nx7k8tpr.js → chunk-br3k6qbf.js} +23 -23
- package/dist/{chunk-nx7k8tpr.js.map → chunk-br3k6qbf.js.map} +2 -2
- package/dist/{chunk-dbc80ad7.js → chunk-c5rkjrgp.js} +28 -28
- package/dist/{chunk-dbc80ad7.js.map → chunk-c5rkjrgp.js.map} +2 -2
- package/dist/{chunk-dktq02ne.js → chunk-cqr3acm1.js} +4 -4
- package/dist/{chunk-dktq02ne.js.map → chunk-cqr3acm1.js.map} +2 -2
- package/dist/chunk-d62kjtbg.js +7 -0
- package/dist/{chunk-zcnhxkvd.js.map → chunk-d62kjtbg.js.map} +2 -2
- package/dist/{chunk-74drx9gd.js → chunk-dfm066qg.js} +10 -10
- package/dist/{chunk-74drx9gd.js.map → chunk-dfm066qg.js.map} +2 -2
- package/dist/{chunk-5e3pq99w.js → chunk-dmn70ztd.js} +30 -30
- package/dist/chunk-dmn70ztd.js.map +11 -0
- package/dist/{chunk-p1x242ad.js → chunk-dz5h08xv.js} +175 -175
- package/dist/{chunk-p1x242ad.js.map → chunk-dz5h08xv.js.map} +2 -2
- package/dist/{chunk-p2vqaxkc.js → chunk-e0d1rzef.js} +27 -22
- package/dist/{chunk-p2vqaxkc.js.map → chunk-e0d1rzef.js.map} +3 -3
- package/dist/{chunk-5sz8ta9r.js → chunk-e1c18xjx.js} +52 -52
- package/dist/{chunk-5sz8ta9r.js.map → chunk-e1c18xjx.js.map} +2 -2
- package/dist/{chunk-wtf06et8.js → chunk-emyyk7dx.js} +55 -55
- package/dist/{chunk-wtf06et8.js.map → chunk-emyyk7dx.js.map} +2 -2
- package/dist/{chunk-19jp6g9d.js → chunk-f0rwz2vh.js} +54 -33
- package/dist/chunk-f0rwz2vh.js.map +11 -0
- package/dist/{chunk-2xns679x.js → chunk-f4w3yp4f.js} +171 -36
- package/dist/chunk-f4w3yp4f.js.map +12 -0
- package/dist/{chunk-979ww6b3.js → chunk-fb3feg1e.js} +29 -29
- package/dist/{chunk-979ww6b3.js.map → chunk-fb3feg1e.js.map} +2 -2
- package/dist/{chunk-4sm0aznx.js → chunk-g00bfdq6.js} +254 -256
- package/dist/{chunk-4sm0aznx.js.map → chunk-g00bfdq6.js.map} +3 -3
- package/dist/{chunk-p03r0h5s.js → chunk-g53f0e4j.js} +76 -202
- package/dist/chunk-g53f0e4j.js.map +15 -0
- package/dist/chunk-g6cke204.js +124 -0
- package/dist/chunk-g6cke204.js.map +10 -0
- package/dist/{chunk-51fjndv0.js → chunk-gfdh9kqa.js} +4 -4
- package/dist/{chunk-51fjndv0.js.map → chunk-gfdh9kqa.js.map} +2 -2
- package/dist/chunk-h1gfhhbh.js +602 -0
- package/dist/chunk-h1gfhhbh.js.map +18 -0
- package/dist/chunk-h3v76ams.js +32 -0
- package/dist/{chunk-08m3b6w8.js.map → chunk-h3v76ams.js.map} +2 -2
- package/dist/{chunk-xajtptbw.js → chunk-hpr1r6av.js} +1367 -418
- package/dist/chunk-hpr1r6av.js.map +44 -0
- package/dist/{chunk-jecn6t54.js → chunk-jgwb25gc.js} +74 -74
- package/dist/{chunk-jecn6t54.js.map → chunk-jgwb25gc.js.map} +2 -2
- package/dist/{chunk-w9tg6yyb.js → chunk-jjy0fhrn.js} +36 -36
- package/dist/{chunk-w9tg6yyb.js.map → chunk-jjy0fhrn.js.map} +2 -2
- package/dist/{chunk-wdage1eb.js → chunk-jmfet9r4.js} +6 -6
- package/dist/{chunk-wdage1eb.js.map → chunk-jmfet9r4.js.map} +2 -2
- package/dist/{chunk-ajnan18g.js → chunk-k3cqkkn2.js} +58 -55
- package/dist/chunk-k3cqkkn2.js.map +12 -0
- package/dist/{chunk-s5y30bc9.js → chunk-kxwa347f.js} +51 -49
- package/dist/{chunk-s5y30bc9.js.map → chunk-kxwa347f.js.map} +4 -4
- package/dist/{chunk-2ab72m2h.js → chunk-m2ca93my.js} +3 -3
- package/dist/{chunk-2ab72m2h.js.map → chunk-m2ca93my.js.map} +2 -2
- package/dist/{chunk-3z1qec12.js → chunk-m3z3x9v0.js} +107 -64
- package/dist/{chunk-3z1qec12.js.map → chunk-m3z3x9v0.js.map} +3 -3
- package/dist/{chunk-sbzzr4kx.js → chunk-mjbk2djy.js} +1061 -1195
- package/dist/{chunk-sbzzr4kx.js.map → chunk-mjbk2djy.js.map} +9 -15
- package/dist/{chunk-4jjp5k14.js → chunk-mmagke4x.js} +6 -6
- package/dist/{chunk-4jjp5k14.js.map → chunk-mmagke4x.js.map} +2 -2
- package/dist/{chunk-359jm1jw.js → chunk-mrp7k0pw.js} +20 -20
- package/dist/{chunk-359jm1jw.js.map → chunk-mrp7k0pw.js.map} +2 -2
- package/dist/{chunk-h0k55pc7.js → chunk-ms2tmn1k.js} +139 -139
- package/dist/{chunk-h0k55pc7.js.map → chunk-ms2tmn1k.js.map} +2 -2
- package/dist/{chunk-rv2hkwwa.js → chunk-ppytyr6w.js} +156 -179
- package/dist/{chunk-rv2hkwwa.js.map → chunk-ppytyr6w.js.map} +3 -5
- package/dist/{chunk-trxxmgnf.js → chunk-pqajwytd.js} +10 -10
- package/dist/{chunk-trxxmgnf.js.map → chunk-pqajwytd.js.map} +3 -3
- package/dist/{chunk-nn0tekr1.js → chunk-pr2h4bv4.js} +33 -33
- package/dist/{chunk-nn0tekr1.js.map → chunk-pr2h4bv4.js.map} +2 -2
- package/dist/{chunk-xwnf87e1.js → chunk-q5gz3g2j.js} +64 -64
- package/dist/{chunk-xwnf87e1.js.map → chunk-q5gz3g2j.js.map} +2 -2
- package/dist/{chunk-5ntny1qx.js → chunk-qf954wje.js} +6 -6
- package/dist/{chunk-5ntny1qx.js.map → chunk-qf954wje.js.map} +2 -2
- package/dist/{chunk-mth82m8t.js → chunk-qhcpj9wc.js} +77 -77
- package/dist/{chunk-mth82m8t.js.map → chunk-qhcpj9wc.js.map} +2 -2
- package/dist/{chunk-tpnd31c1.js → chunk-r29fxdhn.js} +12 -12
- package/dist/{chunk-tpnd31c1.js.map → chunk-r29fxdhn.js.map} +2 -2
- package/dist/{chunk-b49dgvsj.js → chunk-r2y23egw.js} +3 -3
- package/dist/{chunk-b49dgvsj.js.map → chunk-r2y23egw.js.map} +2 -2
- package/dist/{chunk-3xep5cjx.js → chunk-r4tfx1sf.js} +104 -86
- package/dist/chunk-r4tfx1sf.js.map +15 -0
- package/dist/{chunk-4rh2m6zg.js → chunk-rb1xx120.js} +13 -13
- package/dist/{chunk-4rh2m6zg.js.map → chunk-rb1xx120.js.map} +2 -2
- package/dist/chunk-s3csryxe.js +152 -0
- package/dist/chunk-s3csryxe.js.map +11 -0
- package/dist/chunk-s670k14v.js +60 -0
- package/dist/{chunk-407j3msh.js.map → chunk-s670k14v.js.map} +2 -2
- package/dist/chunk-skz0hst3.js +788 -0
- package/dist/chunk-skz0hst3.js.map +19 -0
- package/dist/{chunk-r8jrnexe.js → chunk-v4jbb3rs.js} +4 -4
- package/dist/{chunk-r8jrnexe.js.map → chunk-v4jbb3rs.js.map} +2 -2
- package/dist/{chunk-v1xppd0y.js → chunk-vf691g1r.js} +60 -60
- package/dist/{chunk-v1xppd0y.js.map → chunk-vf691g1r.js.map} +2 -2
- package/dist/{chunk-w1tvjszy.js → chunk-vsj3mdfj.js} +8 -8
- package/dist/{chunk-w1tvjszy.js.map → chunk-vsj3mdfj.js.map} +2 -2
- package/dist/{chunk-9dzba0f2.js → chunk-wjasrj67.js} +8 -8
- package/dist/{chunk-9dzba0f2.js.map → chunk-wjasrj67.js.map} +2 -2
- package/dist/{chunk-1evzqhks.js → chunk-wr8qp979.js} +6 -6
- package/dist/{chunk-1evzqhks.js.map → chunk-wr8qp979.js.map} +2 -2
- package/dist/{chunk-n6jxh8sw.js → chunk-wy0qdqfm.js} +18 -18
- package/dist/{chunk-n6jxh8sw.js.map → chunk-wy0qdqfm.js.map} +2 -2
- package/dist/{chunk-8tsf6dmc.js → chunk-x57ycxq0.js} +204 -204
- package/dist/{chunk-8tsf6dmc.js.map → chunk-x57ycxq0.js.map} +2 -2
- package/dist/{chunk-z4ccwbkz.js → chunk-x9v4cx1d.js} +1 -1
- package/dist/{chunk-gbejpkex.js → chunk-xfbydgzy.js} +26 -26
- package/dist/{chunk-gbejpkex.js.map → chunk-xfbydgzy.js.map} +2 -2
- package/dist/{chunk-gzasd5b6.js → chunk-xyr8kppc.js} +22 -22
- package/dist/{chunk-gzasd5b6.js.map → chunk-xyr8kppc.js.map} +2 -2
- package/dist/{chunk-h5vqbfmd.js → chunk-ypbtykv6.js} +117 -117
- package/dist/{chunk-h5vqbfmd.js.map → chunk-ypbtykv6.js.map} +3 -3
- package/dist/{chunk-ry24jbr1.js → chunk-yv79ncbv.js} +10 -10
- package/dist/{chunk-ry24jbr1.js.map → chunk-yv79ncbv.js.map} +2 -2
- package/dist/{chunk-yp8ee62z.js → chunk-z30bv4ga.js} +35 -35
- package/dist/{chunk-yp8ee62z.js.map → chunk-z30bv4ga.js.map} +2 -2
- package/dist/{chunk-8ydjhh27.js → chunk-z3y411fq.js} +11 -7
- package/dist/{chunk-8ydjhh27.js.map → chunk-z3y411fq.js.map} +3 -3
- package/dist/{chunk-9t8f5xfx.js → chunk-z5rnrmz1.js} +10 -10
- package/dist/{chunk-9t8f5xfx.js.map → chunk-z5rnrmz1.js.map} +2 -2
- package/dist/{chunk-96swp2wd.js → chunk-z667z3sg.js} +3 -3
- package/dist/{chunk-96swp2wd.js.map → chunk-z667z3sg.js.map} +2 -2
- package/dist/{chunk-4yqmp43v.js → chunk-z8fx5cgb.js} +12 -12
- package/dist/{chunk-4yqmp43v.js.map → chunk-z8fx5cgb.js.map} +2 -2
- package/dist/{chunk-xhy826cz.js → chunk-zcnq6105.js} +7 -7
- package/dist/{chunk-xhy826cz.js.map → chunk-zcnq6105.js.map} +2 -2
- package/dist/{chunk-yt8wphsx.js → chunk-zvx7h87b.js} +3 -3
- package/dist/{chunk-yt8wphsx.js.map → chunk-zvx7h87b.js.map} +2 -2
- package/dist/connectors/connections/internal.js +9 -10
- package/dist/connectors/connections/internal.js.map +1 -1
- package/dist/datasets/write.js +8 -12
- package/dist/datasets/write.js.map +1 -1
- package/dist/edits/index.js +7 -8
- package/dist/edits/index.js.map +1 -1
- package/dist/error-reporting/internal.js +22 -24
- package/dist/error-reporting/internal.js.map +1 -1
- package/dist/errors/internal.d.ts +1 -1
- package/dist/errors/internal.d.ts.map +1 -1
- package/dist/errors/internal.js +22 -24
- package/dist/errors/internal.js.map +1 -1
- package/dist/errors/redaction.d.ts +8 -0
- package/dist/errors/redaction.d.ts.map +1 -0
- package/dist/errors/types.d.ts +4 -0
- package/dist/errors/types.d.ts.map +1 -1
- package/dist/events/index.js +60 -63
- package/dist/events/index.js.map +1 -1
- package/dist/events/scope.js +4 -5
- package/dist/events/scope.js.map +1 -1
- package/dist/events/selectors/index.js +9 -10
- package/dist/events/selectors/index.js.map +1 -1
- package/dist/execution/agent.d.ts +3 -3
- package/dist/execution/agent.d.ts.map +1 -1
- package/dist/execution/agent.js +70 -82
- package/dist/execution/agent.js.map +1 -1
- package/dist/execution/durable.d.ts +1 -0
- package/dist/execution/durable.d.ts.map +1 -1
- package/dist/execution/primitive.d.ts +2 -0
- package/dist/execution/primitive.d.ts.map +1 -1
- package/dist/execution/primitive.js +63 -71
- package/dist/execution/primitive.js.map +3 -3
- package/dist/execution/request.d.ts +1 -0
- package/dist/execution/request.d.ts.map +1 -1
- package/dist/execution/request.js +65 -75
- package/dist/execution/request.js.map +3 -3
- package/dist/http/index.js +10 -11
- package/dist/http/index.js.map +1 -1
- package/dist/index.d.ts +14 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +455 -477
- package/dist/index.js.map +1 -1
- package/dist/lake-storage/index.js +38 -42
- package/dist/lake-storage/index.js.map +1 -1
- package/dist/logging/index.d.ts +3 -4
- package/dist/logging/index.d.ts.map +1 -1
- package/dist/logging/index.js +18 -40
- package/dist/logging/index.js.map +1 -1
- package/dist/logging/internal.d.ts +5 -0
- package/dist/logging/internal.d.ts.map +1 -0
- package/dist/logging/internal.js +43 -0
- package/dist/logging/internal.js.map +9 -0
- package/dist/materialization/index.js +46 -49
- package/dist/materialization/index.js.map +1 -1
- package/dist/materializer/index.js +137 -145
- package/dist/materializer/index.js.map +1 -1
- package/dist/models/errors.d.ts +4 -0
- package/dist/models/errors.d.ts.map +1 -1
- package/dist/models/execution/binding.d.ts +9 -0
- package/dist/models/execution/binding.d.ts.map +1 -0
- package/dist/models/execution/errors.d.ts +9 -0
- package/dist/models/execution/errors.d.ts.map +1 -0
- package/dist/models/execution/index.d.ts +11 -0
- package/dist/models/execution/index.d.ts.map +1 -0
- package/dist/models/execution/index.js +55 -0
- package/dist/models/execution/index.js.map +9 -0
- package/dist/models/execution/model-call-accounting.d.ts +17 -0
- package/dist/models/execution/model-call-accounting.d.ts.map +1 -0
- package/dist/models/execution/model-call-admission.d.ts +47 -0
- package/dist/models/execution/model-call-admission.d.ts.map +1 -0
- package/dist/models/execution/model-call-limits.d.ts +15 -0
- package/dist/models/execution/model-call-limits.d.ts.map +1 -0
- package/dist/models/execution/model-call-recorder.d.ts +40 -0
- package/dist/models/execution/model-call-recorder.d.ts.map +1 -0
- package/dist/models/execution/model-call-recovery.d.ts +12 -0
- package/dist/models/execution/model-call-recovery.d.ts.map +1 -0
- package/dist/models/execution/recovery-queue.d.ts +5 -0
- package/dist/models/execution/recovery-queue.d.ts.map +1 -0
- package/dist/models/execution/types.d.ts +44 -0
- package/dist/models/execution/types.d.ts.map +1 -0
- package/dist/models/execution/usage.d.ts +5 -0
- package/dist/models/execution/usage.d.ts.map +1 -0
- package/dist/models/execution.d.ts +6 -0
- package/dist/models/execution.d.ts.map +1 -0
- package/dist/models/generation-types.d.ts +40 -0
- package/dist/models/generation-types.d.ts.map +1 -0
- package/dist/models/index.d.ts +1 -0
- package/dist/models/index.d.ts.map +1 -1
- package/dist/models/index.js +42 -43
- package/dist/models/index.js.map +1 -1
- package/dist/models/language-model.d.ts +3 -0
- package/dist/models/language-model.d.ts.map +1 -1
- package/dist/models/output.d.ts +5 -0
- package/dist/models/output.d.ts.map +1 -0
- package/dist/models/resolve.d.ts +4 -0
- package/dist/models/resolve.d.ts.map +1 -0
- package/dist/objects/execution.d.ts.map +1 -1
- package/dist/objects/index.js +75 -87
- package/dist/objects/index.js.map +1 -1
- package/dist/objects/query/index.js +67 -76
- package/dist/objects/query/index.js.map +1 -1
- package/dist/ontology/index.d.ts +1 -2
- package/dist/ontology/index.d.ts.map +1 -1
- package/dist/ontology/index.js +62 -113
- package/dist/ontology/index.js.map +1 -1
- package/dist/ontology/internal.d.ts +7 -0
- package/dist/ontology/internal.d.ts.map +1 -1
- package/dist/ontology/internal.js +65 -116
- package/dist/ontology/internal.js.map +3 -4
- package/dist/pipelines/index.js +57 -66
- package/dist/pipelines/index.js.map +1 -1
- package/dist/projections/internal.js +58 -67
- package/dist/projections/internal.js.map +1 -1
- package/dist/query.d.ts +0 -1
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +11 -15
- package/dist/query.js.map +1 -1
- package/dist/queues/index.d.ts +2 -1
- package/dist/queues/index.d.ts.map +1 -1
- package/dist/queues/index.js +6 -7
- package/dist/queues/index.js.map +1 -1
- package/dist/queues/types.d.ts +3 -20
- package/dist/queues/types.d.ts.map +1 -1
- package/dist/rules/internal.js +4 -5
- package/dist/rules/internal.js.map +1 -1
- package/dist/runtime/create.d.ts +2 -1
- package/dist/runtime/create.d.ts.map +1 -1
- package/dist/runtime/host.d.ts +2 -1
- package/dist/runtime/host.d.ts.map +1 -1
- package/dist/runtime/internal.js +13 -14
- package/dist/runtime/internal.js.map +1 -1
- package/dist/runtime/sixb.d.ts +2 -0
- package/dist/runtime/sixb.d.ts.map +1 -1
- package/dist/sandboxes/errors.d.ts +4 -0
- package/dist/sandboxes/errors.d.ts.map +1 -1
- package/dist/sandboxes/index.d.ts +2 -2
- package/dist/sandboxes/index.d.ts.map +1 -1
- package/dist/sandboxes/index.js +14 -13
- package/dist/sandboxes/index.js.map +1 -1
- package/dist/sandboxes/sandbox.d.ts +35 -7
- package/dist/sandboxes/sandbox.d.ts.map +1 -1
- package/dist/scheduler/index.js +9 -10
- package/dist/scheduler/index.js.map +1 -1
- package/dist/schedules/index.js +31 -33
- package/dist/schedules/index.js.map +1 -1
- package/dist/shares/internal.js +46 -54
- package/dist/shares/internal.js.map +2 -2
- package/dist/storage/action-runs/failure.js +7 -9
- package/dist/storage/action-runs/failure.js.map +1 -1
- package/dist/storage/action-runs/provider.js +4 -8
- package/dist/storage/action-runs/provider.js.map +1 -1
- package/dist/storage/agents/in-memory.d.ts.map +1 -1
- package/dist/storage/agents/provider.js +26 -30
- package/dist/storage/agents/provider.js.map +1 -1
- package/dist/storage/agents/types.d.ts +0 -3
- package/dist/storage/agents/types.d.ts.map +1 -1
- package/dist/storage/ai-cost/attribution.d.ts +4 -0
- package/dist/storage/ai-cost/attribution.d.ts.map +1 -0
- package/dist/storage/ai-cost/groups.d.ts +3 -0
- package/dist/storage/ai-cost/groups.d.ts.map +1 -1
- package/dist/storage/ai-cost/provider.d.ts +1 -0
- package/dist/storage/ai-cost/provider.d.ts.map +1 -1
- package/dist/storage/ai-cost/provider.js +30 -143
- package/dist/storage/ai-cost/provider.js.map +3 -4
- package/dist/storage/ai-cost/types.d.ts +15 -0
- package/dist/storage/ai-cost/types.d.ts.map +1 -1
- package/dist/storage/ai-limits/enforcement.js +14 -16
- package/dist/storage/ai-limits/enforcement.js.map +1 -1
- package/dist/storage/ai-limits/provider.js +56 -57
- package/dist/storage/ai-limits/provider.js.map +1 -1
- package/dist/storage/auth/in-memory.d.ts +1 -1
- package/dist/storage/auth/in-memory.d.ts.map +1 -1
- package/dist/storage/connector-connections/provider.js +34 -36
- package/dist/storage/connector-connections/provider.js.map +2 -2
- package/dist/storage/executions/in-memory.d.ts.map +1 -1
- package/dist/storage/executions/provider.d.ts +2 -1
- package/dist/storage/executions/provider.d.ts.map +1 -1
- package/dist/storage/executions/provider.js +14 -11
- package/dist/storage/executions/provider.js.map +3 -3
- package/dist/storage/executions/types.d.ts +6 -2
- package/dist/storage/executions/types.d.ts.map +1 -1
- package/dist/storage/executions/validation.d.ts +2 -0
- package/dist/storage/executions/validation.d.ts.map +1 -1
- package/dist/storage/in-memory/index.d.ts.map +1 -1
- package/dist/storage/index.d.ts +6 -7
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/index.js +221 -256
- package/dist/storage/index.js.map +1 -1
- package/dist/storage/internal.d.ts +10 -0
- package/dist/storage/internal.d.ts.map +1 -0
- package/dist/storage/internal.js +47 -0
- package/dist/storage/internal.js.map +9 -0
- package/dist/storage/ontology/provider.js +105 -109
- package/dist/storage/ontology/provider.js.map +1 -1
- package/dist/storage/operation-scope.js +18 -19
- package/dist/storage/operation-scope.js.map +1 -1
- package/dist/storage/pipeline-runs/provider.js +4 -6
- package/dist/storage/pipeline-runs/provider.js.map +1 -1
- package/dist/storage/projection-runs/provider.js +66 -70
- package/dist/storage/projection-runs/provider.js.map +1 -1
- package/dist/storage/share-grants/provider.js +17 -19
- package/dist/storage/share-grants/provider.js.map +1 -1
- package/dist/storage/share-sessions/provider.js +14 -15
- package/dist/storage/share-sessions/provider.js.map +1 -1
- package/dist/storage/sync-runs/provider.js +4 -6
- package/dist/storage/sync-runs/provider.js.map +1 -1
- package/dist/storage/webhook-runs/provider.js +4 -6
- package/dist/storage/webhook-runs/provider.js.map +1 -1
- package/dist/storage/workflow-runs/in-memory.d.ts.map +1 -1
- package/dist/storage/workflow-runs/provider.js +13 -21
- package/dist/storage/workflow-runs/provider.js.map +1 -1
- package/dist/storage/workflow-runs/types.d.ts +0 -3
- package/dist/storage/workflow-runs/types.d.ts.map +1 -1
- package/dist/syncs/index.js +55 -65
- package/dist/syncs/index.js.map +1 -1
- package/dist/testing/action-execution.d.ts +4 -1
- package/dist/testing/action-execution.d.ts.map +1 -1
- package/dist/testing/agent-execution.d.ts +1 -0
- package/dist/testing/agent-execution.d.ts.map +1 -1
- package/dist/testing/agent-storage-contract.d.ts.map +1 -1
- package/dist/testing/ai-model-call-groups-contract.d.ts.map +1 -1
- package/dist/testing/execution-storage-contract.d.ts.map +1 -1
- package/dist/testing/execution.d.ts +1 -0
- package/dist/testing/execution.d.ts.map +1 -1
- package/dist/testing/index.js +911 -799
- package/dist/testing/index.js.map +9 -9
- package/dist/testing/workflow-execution.d.ts +1 -0
- package/dist/testing/workflow-execution.d.ts.map +1 -1
- package/dist/webhooks/internal.js +51 -59
- package/dist/webhooks/internal.js.map +2 -2
- package/dist/workers/index.js +11 -13
- package/dist/workers/index.js.map +2 -2
- package/dist/workflows/failure.d.ts +2 -0
- package/dist/workflows/failure.d.ts.map +1 -1
- package/dist/workflows/index.js +135 -147
- package/dist/workflows/index.js.map +1 -1
- package/dist/workflows/request.d.ts.map +1 -1
- package/dist/workflows/run-dispatch.d.ts +0 -1
- package/dist/workflows/run-dispatch.d.ts.map +1 -1
- package/dist/workflows/types.d.ts +2 -0
- package/dist/workflows/types.d.ts.map +1 -1
- package/package.json +48 -30
- package/src/actions/run-dispatch.ts +2 -6
- package/src/actions/types/context.ts +2 -0
- package/src/actions/validation.ts +2 -1
- package/src/agents/adapters.ts +4 -9
- package/src/agents/{context.ts → context/entries.ts} +4 -4
- package/src/agents/context/index.ts +15 -0
- package/src/agents/context-model.ts +1 -1
- package/src/agents/context-resolution.ts +1 -1
- package/src/agents/index.ts +4 -4
- package/src/agents/message.ts +1 -1
- package/src/agents/model-loop.ts +8 -0
- package/src/agents/request.ts +11 -26
- package/src/agents/streams/index.ts +18 -0
- package/src/agents/streams/internal.ts +19 -0
- package/src/agents/{streams.ts → streams/protocol.ts} +5 -5
- package/src/agents/types.ts +1 -1
- package/src/agents/validation.ts +3 -7
- package/src/auth/index.ts +0 -1
- package/src/bootstrap/discovery.ts +81 -24
- package/src/bootstrap/index.ts +8 -1
- package/src/errors/internal.ts +90 -10
- package/src/errors/redaction.ts +98 -0
- package/src/errors/types.ts +4 -0
- package/src/execution/agent.ts +5 -3
- package/src/execution/durable.ts +11 -1
- package/src/execution/primitive.ts +5 -1
- package/src/execution/request.ts +3 -0
- package/src/index.ts +20 -18
- package/src/logging/index.ts +2 -33
- package/src/logging/internal.ts +43 -0
- package/src/models/errors.ts +12 -0
- package/src/models/execution/binding.ts +29 -0
- package/src/models/execution/errors.ts +18 -0
- package/src/models/execution/index.ts +26 -0
- package/src/models/execution/model-call-accounting.ts +211 -0
- package/src/models/execution/model-call-admission.ts +127 -0
- package/src/models/execution/model-call-limits.ts +135 -0
- package/src/models/execution/model-call-recorder.ts +235 -0
- package/src/models/execution/model-call-recovery.ts +125 -0
- package/src/models/execution/recovery-queue.ts +31 -0
- package/src/models/execution/types.ts +58 -0
- package/src/models/execution/usage.ts +23 -0
- package/src/models/execution.ts +207 -0
- package/src/models/generation-types.ts +50 -0
- package/src/models/index.ts +8 -0
- package/src/models/language-model.ts +3 -0
- package/src/models/output.ts +45 -0
- package/src/models/resolve.ts +27 -0
- package/src/objects/execution.ts +1 -1
- package/src/ontology/index.ts +1 -2
- package/src/ontology/internal.ts +35 -0
- package/src/projections/run-dispatch.ts +1 -0
- package/src/query.ts +0 -1
- package/src/queues/index.ts +4 -2
- package/src/queues/types.ts +6 -25
- package/src/runtime/create.ts +2 -1
- package/src/runtime/host.ts +2 -1
- package/src/runtime/sixb.ts +4 -0
- package/src/sandboxes/errors.ts +5 -0
- package/src/sandboxes/index.ts +3 -0
- package/src/sandboxes/sandbox.ts +35 -7
- package/src/storage/agents/in-memory.ts +0 -3
- package/src/storage/agents/types.ts +0 -3
- package/src/storage/ai-cost/analytics.ts +1 -1
- package/src/storage/ai-cost/attribution.ts +15 -0
- package/src/storage/ai-cost/groups.ts +5 -1
- package/src/storage/ai-cost/provider.ts +1 -0
- package/src/storage/ai-cost/types.ts +7 -0
- package/src/storage/auth/in-memory.ts +1 -1
- package/src/storage/executions/in-memory.ts +4 -9
- package/src/storage/executions/provider.ts +4 -0
- package/src/storage/executions/types.ts +6 -2
- package/src/storage/executions/validation.ts +32 -0
- package/src/storage/in-memory/index.ts +16 -1
- package/src/storage/index.ts +3 -29
- package/src/storage/internal.ts +20 -0
- package/src/storage/workflow-runs/in-memory.ts +0 -2
- package/src/storage/workflow-runs/types.ts +0 -3
- package/src/testing/action-execution.ts +9 -2
- package/src/testing/agent-execution.ts +3 -0
- package/src/testing/agent-storage-contract.ts +0 -5
- package/src/testing/ai-model-call-groups-contract.ts +74 -2
- package/src/testing/execution-storage-contract.ts +59 -1
- package/src/testing/execution.ts +6 -0
- package/src/testing/workflow-execution.ts +4 -0
- package/src/workflows/failure.ts +62 -1
- package/src/workflows/request.ts +0 -9
- package/src/workflows/run-dispatch.ts +0 -3
- package/src/workflows/types.ts +2 -0
- package/src/workflows/validation.ts +1 -1
- package/dist/agents/context.d.ts.map +0 -1
- package/dist/agents/context.js +0 -23
- package/dist/agents/streams.d.ts.map +0 -1
- package/dist/agents/streams.js +0 -55
- package/dist/chunk-08m3b6w8.js +0 -32
- package/dist/chunk-19jp6g9d.js.map +0 -11
- package/dist/chunk-2xns679x.js.map +0 -11
- package/dist/chunk-3xep5cjx.js.map +0 -15
- package/dist/chunk-407j3msh.js +0 -60
- package/dist/chunk-4qfkag59.js +0 -1568
- package/dist/chunk-4qfkag59.js.map +0 -20
- package/dist/chunk-5e3pq99w.js.map +0 -11
- package/dist/chunk-7y0f6rf1.js.map +0 -10
- package/dist/chunk-ajnan18g.js.map +0 -12
- package/dist/chunk-c15dr03f.js +0 -43
- package/dist/chunk-d8qkxt2v.js.map +0 -10
- package/dist/chunk-jq43kdvk.js +0 -50
- package/dist/chunk-k522z7v6.js.map +0 -10
- package/dist/chunk-p03r0h5s.js.map +0 -16
- package/dist/chunk-p1rzczbt.js +0 -218
- package/dist/chunk-rafagrwr.js.map +0 -11
- package/dist/chunk-xajtptbw.js.map +0 -40
- package/dist/chunk-y64skrwp.js +0 -19
- package/dist/chunk-zcnhxkvd.js +0 -7
- package/dist/logging/types.js +0 -27
- package/dist/logging/types.js.map +0 -9
- /package/dist/{chunk-zqqz8052.js → chunk-7n30ybym.js} +0 -0
- /package/dist/{chunk-zqqz8052.js.map → chunk-7n30ybym.js.map} +0 -0
- /package/dist/{chunk-4a849fr1.js.map → chunk-9tc8dxmn.js.map} +0 -0
- /package/dist/{chunk-j1sbhm7p.js → chunk-ey1nk510.js} +0 -0
- /package/dist/{chunk-j1sbhm7p.js.map → chunk-ey1nk510.js.map} +0 -0
- /package/dist/{chunk-z4ccwbkz.js.map → chunk-x9v4cx1d.js.map} +0 -0
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/agents/context-model.ts", "../src/agents/tool-result.ts", "../src/agents/adapters.ts", "../src/agents/api-gateway.ts", "../src/agents/validation.ts", "../src/agents/tool-definition.ts", "../src/agents/builders.ts", "../src/agents/context-compaction.ts", "../src/agents/model-loop.ts", "../src/agents/reference.ts", "../src/agents/thread-context-projection.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import { stableJsonStringify } from \"../json\"\nimport type { AgentContextPart } from \"./context\"\n\n/** Project persisted context into one deterministic, escaped data block for the model. */\nexport function serializeAgentContextForModel(\n parts: readonly AgentContextPart[]\n): string | undefined {\n if (parts.length === 0) return undefined\n\n const lines = [\"<sixb_user_context>\"]\n for (const part of parts) {\n if (part.context.kind === \"object\") {\n lines.push(\n \" <object_context>\",\n ` <object_type_id>${escapeXml(part.context.ref.objectTypeId)}</object_type_id>`,\n ` <primary_id>${escapeXml(part.context.ref.primaryId)}</primary_id>`,\n \" </object_context>\"\n )\n continue\n }\n\n lines.push(\n \" <app_state_context>\",\n ` <id>${escapeXml(part.context.id)}</id>`,\n ` <description>${escapeXml(part.context.description)}</description>`,\n ` <value format=\"json\">${escapeXml(stableJsonStringify(part.context.value))}</value>`,\n \" </app_state_context>\"\n )\n }\n lines.push(\"</sixb_user_context>\")\n return lines.join(\"\\n\")\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\")\n}\n",
|
|
6
|
-
"import { isFileRef } from \"../blob-storage/validation\"\nimport { isPlainRecord } from \"../json\"\nimport type { AgentToolResult } from \"./types\"\n\n/** Narrow a durable JSON tool output to Sixb's file-aware result envelope. */\nexport function isAgentToolResult(value: unknown): value is AgentToolResult {\n return (\n isPlainRecord(value) &&\n value.kind === \"agentToolResult\" &&\n getInvalidAgentToolResultReason(value) === undefined\n )\n}\n\n/** Return a precise path when a tagged result does not satisfy the public rich-result contract. */\nexport function getInvalidAgentToolResultReason(value: unknown): string | undefined {\n if (!isPlainRecord(value) || value.kind !== \"agentToolResult\") {\n return undefined\n }\n\n if (!Array.isArray(value.content)) {\n return \"result.content must be an array\"\n }\n const unsupportedKey = Object.keys(value).find((key) => key !== \"kind\" && key !== \"content\")\n if (unsupportedKey) {\n return `result.${unsupportedKey} is not supported`\n }\n if (value.content.length === 0) {\n return \"result.content must contain at least one content part\"\n }\n\n for (let index = 0; index < value.content.length; index += 1) {\n const part = value.content[index]\n const path = `result.content[${index}]`\n if (!isPlainRecord(part)) {\n return `${path} must be a text or file content part`\n }\n if (part.type === \"text\") {\n if (typeof part.text !== \"string\") {\n return `${path}.text must be a string`\n }\n const unsupportedKey = Object.keys(part).find((key) => key !== \"type\" && key !== \"text\")\n if (unsupportedKey) {\n return `${path}.${unsupportedKey} is not supported`\n }\n continue\n }\n if (part.type === \"file\") {\n if (!isFileRef(part.fileRef)) {\n return `${path}.fileRef must be a valid FileRef`\n }\n const unsupportedKey = Object.keys(part).find((key) => key !== \"type\" && key !== \"fileRef\")\n if (unsupportedKey) {\n return `${path}.${unsupportedKey} is not supported`\n }\n continue\n }\n return `${path}.type must be 'text' or 'file'`\n }\n\n return undefined\n}\n",
|
|
7
|
-
"import type { JsonValue } from \"../json\"\nimport type {\n ModelAssistantPart,\n ModelFilePart,\n ModelMessage,\n ModelTextPart,\n ModelToolCallPart,\n ModelToolOutput,\n ModelToolResultPart,\n ProviderData,\n} from \"../models\"\nimport { serializeAgentContextForModel } from \"./context-model\"\nimport type {\n AgentFilePart,\n AgentMessage,\n AgentMessagePart,\n AgentTextPart,\n AgentToolCallPart,\n} from \"./message\"\nimport { isAgentToolResult } from \"./tool-result\"\nimport type { AgentToolFileContent } from \"./types\"\n\nexport interface AgentFileDataResolverInput<TMessage extends AgentMessage = AgentMessage> {\n readonly message: TMessage\n readonly part: AgentFilePart\n readonly partIndex: number\n}\n\nexport interface AgentFileDataProjection {\n readonly data: URL\n readonly mediaType?: string\n readonly filename?: string\n}\n\nexport interface AgentToolResultFileResolverInput<TMessage extends AgentMessage = AgentMessage> {\n readonly message: TMessage\n readonly part: AgentToolCallPart\n readonly partIndex: number\n readonly contentPart: AgentToolFileContent\n readonly contentIndex: number\n}\n\nexport interface ToModelMessagesOptions<TMessage extends AgentMessage = AgentMessage> {\n /**\n * Convert a stored file reference into model-readable data. When omitted, file parts are skipped\n * rather than leaking blob ids or passing an unsupported Sixb-only shape to model providers.\n */\n readonly fileData?:\n | ((input: AgentFileDataResolverInput<TMessage>) => URL | AgentFileDataProjection | undefined)\n | undefined\n /**\n * Convert a stored file reference into model-readable text context. This is appended before any\n * file data part so metadata, truncation notes, and sandbox/API access hints stay visible even for\n * models that cannot consume inline files.\n */\n readonly fileText?: (input: AgentFileDataResolverInput<TMessage>) => string | undefined\n /** Add current metadata, sandbox paths, and projection notes for a tool-result file. */\n readonly toolResultFileText?: (\n input: AgentToolResultFileResolverInput<TMessage>\n ) => string | undefined\n}\n\n/**\n * Project durable messages into Sixb model messages. Assistant parts are grouped\n * into blocks at each `step-start`; each block yields one `assistant` message plus, for any\n * non-provider-executed tool calls, one `tool` message. Provider-executed tool results stay inline\n * in the assistant message. Without a tool registry, a string output maps to `text` and anything\n * else to `json`; this is the documented fidelity scope (a tool's custom `toModelOutput` is not\n * reproduced).\n */\nexport function toModelMessages<TMessage extends AgentMessage>(\n messages: readonly TMessage[],\n options: ToModelMessagesOptions<TMessage> = {}\n): ModelMessage[] {\n const result: ModelMessage[] = []\n for (const message of messages) {\n switch (message.role) {\n case \"system\":\n result.push(systemModelMessage(message))\n break\n case \"user\":\n result.push(userModelMessage(message, options))\n break\n case \"assistant\":\n appendAssistantModelMessages(result, message, options)\n break\n }\n }\n return result\n}\n\nfunction systemModelMessage(message: AgentMessage): ModelMessage {\n const textParts = message.parts.filter((part) => part.type === \"text\")\n const providerData = mergeProviderMetadata(textParts)\n return {\n role: \"system\",\n content: textParts.map((part) => part.text).join(\"\"),\n ...(providerData === undefined ? {} : { providerData }),\n }\n}\n\nfunction mergeProviderMetadata(parts: readonly AgentTextPart[]): ProviderData | undefined {\n let merged: Record<string, JsonValue> | undefined\n for (const part of parts) {\n const meta = part.providerMetadata\n if (meta !== undefined && typeof meta === \"object\" && meta !== null && !Array.isArray(meta)) {\n merged = { ...(merged ?? {}), ...meta }\n }\n }\n return merged\n}\n\nfunction userModelMessage<TMessage extends AgentMessage>(\n message: TMessage,\n options: ToModelMessagesOptions<TMessage>\n): ModelMessage {\n const content: (ModelTextPart | ModelFilePart)[] = []\n const serializedContext = serializeAgentContextForModel(\n message.parts.filter((part) => part.type === \"context\")\n )\n if (serializedContext) {\n content.push({ type: \"text\", text: `${serializedContext}\\n\\n` })\n }\n message.parts.forEach((part, partIndex) => {\n if (part.type === \"text\") {\n content.push({\n type: \"text\",\n text: part.text,\n ...(part.providerMetadata === undefined ? {} : { providerData: part.providerMetadata }),\n })\n return\n }\n if (part.type === \"file\") {\n const fileContext = options.fileText?.({ message, part, partIndex })\n if (fileContext) {\n content.push({ type: \"text\", text: fileContext })\n }\n const resolved = options.fileData?.({ message, part, partIndex })\n if (resolved) {\n const projection = resolved instanceof URL ? { data: resolved } : resolved\n content.push({\n type: \"file\",\n data: projection.data,\n mediaType: projection.mediaType ?? part.fileRef.mediaType ?? \"application/octet-stream\",\n ...(projection.filename !== undefined\n ? { filename: projection.filename }\n : part.fileRef.fileName === undefined\n ? {}\n : { filename: part.fileRef.fileName }),\n ...(part.providerMetadata === undefined ? {} : { providerData: part.providerMetadata }),\n })\n }\n }\n })\n return { role: \"user\", content }\n}\n\nfunction appendAssistantModelMessages<TMessage extends AgentMessage>(\n result: ModelMessage[],\n message: TMessage,\n options: ToModelMessagesOptions<TMessage>\n): void {\n let block: Array<{ readonly part: AgentMessagePart; readonly partIndex: number }> = []\n const flush = (): void => {\n if (block.length === 0) {\n return\n }\n const current = block\n block = []\n\n const content: ModelAssistantPart[] = []\n const toolResults: ModelToolResultPart[] = []\n for (const { part, partIndex } of current) {\n if (part.type === \"text\" || part.type === \"reasoning\") {\n content.push({\n type: part.type,\n text: part.text,\n ...(part.providerMetadata === undefined ? {} : { providerData: part.providerMetadata }),\n })\n } else if (part.type === \"file\") {\n const fileContext = options.fileText?.({ message, part, partIndex })\n if (fileContext) {\n content.push({ type: \"text\", text: fileContext })\n }\n } else if (part.type === \"tool-call\") {\n content.push(toolCallModelPart(part))\n if (part.providerExecuted === true) {\n content.push(toolResultModelPart(message, part, partIndex, \"json\", options))\n } else {\n toolResults.push(toolResultModelPart(message, part, partIndex, \"text\", options))\n }\n } else if (part.type === \"provider-state\") {\n content.push({\n type: \"provider-state\",\n providerId: part.providerId,\n data: part.data,\n })\n }\n }\n result.push({ role: \"assistant\", content })\n\n if (toolResults.length > 0) {\n result.push({ role: \"tool\", content: toolResults })\n }\n }\n\n message.parts.forEach((part, partIndex) => {\n if (part.type === \"step-start\") {\n flush()\n } else {\n block.push({ part, partIndex })\n }\n })\n flush()\n}\n\nfunction toolCallModelPart(part: AgentToolCallPart): ModelToolCallPart {\n return {\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n ...(part.providerExecuted === undefined ? {} : { providerExecuted: part.providerExecuted }),\n ...(part.providerMetadata === undefined ? {} : { providerData: part.providerMetadata }),\n }\n}\n\nfunction toolResultModelPart<TMessage extends AgentMessage>(\n message: TMessage,\n part: AgentToolCallPart,\n partIndex: number,\n errorMode: \"text\" | \"json\",\n options: ToModelMessagesOptions<TMessage>\n): ModelToolResultPart {\n // Stored providerMetadata belongs to the call, not this synthesized result. Replaying it here\n // can replace the result with the provider's original tool-call block.\n return {\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: toolResultOutput(message, part, partIndex, errorMode, options),\n }\n}\n\nfunction toolResultOutput<TMessage extends AgentMessage>(\n message: TMessage,\n part: AgentToolCallPart,\n partIndex: number,\n errorMode: \"text\" | \"json\",\n options: ToModelMessagesOptions<TMessage>\n): ModelToolOutput {\n if (part.state === \"output-error\") {\n return errorMode === \"json\"\n ? { type: \"error-json\", value: part.errorText }\n : { type: \"error-text\", value: part.errorText }\n }\n if (isAgentToolResult(part.output)) {\n const value: string[] = []\n part.output.content.forEach((contentPart, contentIndex) => {\n if (contentPart.type === \"text\") {\n value.push(contentPart.text)\n return\n }\n\n const fileContext = options.toolResultFileText?.({\n message,\n part,\n partIndex,\n contentPart,\n contentIndex,\n })\n value.push(fileContext ?? toolResultFileFallbackText(contentPart))\n })\n return { type: \"text\", value: value.join(\"\\n\") }\n }\n return typeof part.output === \"string\"\n ? { type: \"text\", value: part.output }\n : { type: \"json\", value: part.output }\n}\n\nfunction toolResultFileFallbackText(part: AgentToolFileContent): string {\n const attributes = [\n part.fileRef.fileName ? `name=${JSON.stringify(part.fileRef.fileName)}` : undefined,\n part.fileRef.mediaType ? `mediaType=${JSON.stringify(part.fileRef.mediaType)}` : undefined,\n `sizeBytes=${part.fileRef.sizeBytes}`,\n ].filter((value): value is string => value !== undefined)\n return `[Tool-created file: ${attributes.join(\" \")}. Contents are not available inline.]`\n}\n",
|
|
8
|
-
"import { createHmac, timingSafeEqual } from \"node:crypto\"\nimport { SIXB_API_ROUTES } from \"../http/api-routes\"\nimport { matchesPathPattern, normalizeRoutePath } from \"../http/route-pattern\"\n\nexport const AGENT_API_GATEWAY_PREFIX = \"/__sixb/agent-api\"\n\nconst AGENT_API_GATEWAY_CAPABILITY_PREFIX = \"sixb_agw_v1_\"\n\nexport interface AgentApiGatewayCapabilityInput {\n readonly projectId: string\n readonly runId: string\n readonly executionToken: string\n}\n\nexport interface AgentApiRoute {\n readonly method: string\n readonly path: string\n}\n\n/**\n * The routes the agent API gateway may proxy — the `agentApi` projection of the canonical\n * {@link SIXB_API_ROUTES} table, so this list can never drift from (nor exceed) the bearer boundary.\n */\nexport const AGENT_API_ROUTES: readonly AgentApiRoute[] = SIXB_API_ROUTES.filter(\n (route) => route.agentApi\n).map((route) => ({ method: route.method, path: route.path }))\n\nexport function createAgentApiGatewayCapability(input: AgentApiGatewayCapabilityInput): string {\n return `${AGENT_API_GATEWAY_CAPABILITY_PREFIX}${capabilityDigest(input)}`\n}\n\nexport function isValidAgentApiGatewayCapability(\n input: AgentApiGatewayCapabilityInput & { readonly capability: string }\n): boolean {\n const expected = createAgentApiGatewayCapability(input)\n const actual = input.capability\n const expectedBuffer = Buffer.from(expected)\n const actualBuffer = Buffer.from(actual)\n return (\n expectedBuffer.byteLength === actualBuffer.byteLength &&\n timingSafeEqual(expectedBuffer, actualBuffer)\n )\n}\n\nexport function isAllowedAgentApiRequest(method: string, pathname: string): boolean {\n const normalizedMethod = method.toUpperCase()\n const normalizedPath = normalizeRoutePath(pathname)\n return AGENT_API_ROUTES.some(\n (route) => route.method === normalizedMethod && matchesPathPattern(normalizedPath, route.path)\n )\n}\n\nfunction capabilityDigest(input: AgentApiGatewayCapabilityInput): string {\n return createHmac(\"sha256\", input.executionToken)\n .update(`agent-api-gateway:${input.projectId}:${input.runId}`)\n .digest(\"base64url\")\n}\n",
|
|
9
|
-
"import { getInvalidJsonValueReason, isPlainRecord, type JsonValue } from \"../json\"\nimport {\n normalizeSchemaValue,\n type ObjectSchema,\n OntologyValidationError,\n type ValueType,\n validateSchemaValue,\n} from \"../ontology\"\nimport { AgentDefinitionError } from \"./errors\"\nimport type { AgentToolDefinition, AgentToolInputSchema } from \"./types\"\n\nconst AGENT_TOOL_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/\nconst AGENT_TOOL_PRIMITIVE_SCHEMAS = new Set([\n \"string\",\n \"integer\",\n \"double\",\n \"decimal\",\n \"boolean\",\n \"date\",\n \"timestamp\",\n \"uuid\",\n \"fileRef\",\n])\n\nexport const AGENT_RESERVED_TOOL_NAMES = [\n \"bash\",\n \"read\",\n \"view_file\",\n \"spawn_agent\",\n \"wait_agent\",\n] as const\n\nexport function isAgentToolDefinition(value: unknown): value is AgentToolDefinition {\n return (\n isRecord(value) &&\n value.kind === \"agentTool\" &&\n typeof value.name === \"string\" &&\n typeof value.description === \"string\" &&\n isPlainRecord(value.input) &&\n typeof value.handler === \"function\"\n )\n}\n\nexport function assertValidAgentToolName(name: unknown): asserts name is string {\n if (typeof name !== \"string\" || !AGENT_TOOL_NAME_PATTERN.test(name)) {\n throw new AgentDefinitionError(\n \"[Sixb] Agent tool name must be 1-64 characters, start with a letter or underscore, and contain only letters, numbers, underscores, or hyphens.\"\n )\n }\n if ((AGENT_RESERVED_TOOL_NAMES as readonly string[]).includes(name)) {\n throw new AgentDefinitionError(`[Sixb] Agent tool name '${name}' is reserved by the framework.`)\n }\n}\n\nexport function assertValidAgentToolDescription(name: string, description: unknown): void {\n if (typeof description !== \"string\" || !description.trim()) {\n throw new AgentDefinitionError(`[Sixb] Agent tool '${name}' description must not be empty.`)\n }\n}\n\nexport function assertValidAgentToolInput(name: string, input: unknown): void {\n if (!isPlainRecord(input)) {\n throw new AgentDefinitionError(`[Sixb] Agent tool '${name}' input must be a schema object.`)\n }\n\n for (const [field, schema] of Object.entries(input)) {\n if (!field.trim()) {\n throw new AgentDefinitionError(\n `[Sixb] Agent tool '${name}' input field names must not be empty.`\n )\n }\n assertValidAgentToolSchema(name, schema, `input.${field}`, new Set())\n }\n}\n\nexport function validateAndSnapshotAgentToolInput<TInput extends AgentToolInputSchema>(\n toolName: string,\n input: TInput\n): TInput {\n assertValidAgentToolInput(toolName, input)\n try {\n return deepFreeze(structuredClone(input))\n } catch {\n throw new AgentDefinitionError(\n `[Sixb] Agent tool '${toolName}' input must be safely snapshot-compatible.`\n )\n }\n}\n\n/** Validate model input against a tool schema, normalize it to JSON, and lock the snapshot. */\nexport function validateAndNormalizeAgentToolInput(\n toolName: string,\n shape: AgentToolInputSchema,\n value: unknown,\n valueTypesById: ReadonlyMap<string, ValueType>\n): Record<string, JsonValue> {\n const label = `Agent tool '${toolName}' input`\n if (!isPlainRecord(value)) {\n throw new OntologyValidationError(`[Sixb] ${label} must be a JSON object.`)\n }\n\n const reason = getInvalidJsonValueReason(value, label)\n if (reason) {\n throw new OntologyValidationError(`[Sixb] ${label} must be JSON-compatible; ${reason}.`)\n }\n\n const schema: ObjectSchema = {\n type: \"object\",\n properties: Object.fromEntries(\n Object.entries(shape).map(([field, fieldSchema]) => [\n field,\n { schema: fieldSchema, required: true },\n ])\n ),\n }\n validateSchemaValue(schema, value, label, valueTypesById)\n return deepFreeze(\n normalizeSchemaValue(schema, value, label, valueTypesById) as Record<string, JsonValue>\n )\n}\n\nfunction assertValidAgentToolSchema(\n toolName: string,\n schema: unknown,\n path: string,\n visiting: Set<object>\n): void {\n if (typeof schema === \"string\") {\n if (AGENT_TOOL_PRIMITIVE_SCHEMAS.has(schema)) {\n return\n }\n throw invalidAgentToolSchema(toolName, path)\n }\n if (!isPlainRecord(schema) || typeof schema.type !== \"string\" || visiting.has(schema)) {\n throw invalidAgentToolSchema(toolName, path)\n }\n\n visiting.add(schema)\n switch (schema.type) {\n case \"enum\": {\n const values = schema.values\n const validValues = isValidAgentToolEnumValues(values, schema.valueType)\n if (!validValues || new Set(values).size !== values.length) {\n throw invalidAgentToolSchema(toolName, path)\n }\n break\n }\n case \"array\":\n assertValidAgentToolSchema(toolName, schema.items, `${path}.items`, visiting)\n break\n case \"map\":\n if (schema.keySchema !== \"string\") {\n throw invalidAgentToolSchema(toolName, path)\n }\n assertValidAgentToolSchema(toolName, schema.valueSchema, `${path}.valueSchema`, visiting)\n break\n case \"object\": {\n if (!isPlainRecord(schema.properties)) {\n throw invalidAgentToolSchema(toolName, path)\n }\n for (const [fieldId, field] of Object.entries(schema.properties)) {\n if (!fieldId.trim() || !isPlainRecord(field) || !(\"schema\" in field)) {\n throw invalidAgentToolSchema(toolName, `${path}.properties.${fieldId}`)\n }\n if (\n (field.required !== undefined && typeof field.required !== \"boolean\") ||\n (field.nullable !== undefined && typeof field.nullable !== \"boolean\") ||\n (field.description !== undefined &&\n (typeof field.description !== \"string\" || !field.description.trim()))\n ) {\n throw invalidAgentToolSchema(toolName, `${path}.properties.${fieldId}`)\n }\n assertValidAgentToolSchema(\n toolName,\n field.schema,\n `${path}.properties.${fieldId}.schema`,\n visiting\n )\n }\n break\n }\n case \"valueTypeRef\":\n if (typeof schema.valueTypeId !== \"string\" || !schema.valueTypeId.trim()) {\n throw invalidAgentToolSchema(toolName, path)\n }\n if (schema._resolved !== undefined) {\n assertValidAgentToolSchema(toolName, schema._resolved, `${path}._resolved`, visiting)\n }\n break\n default:\n throw invalidAgentToolSchema(toolName, path)\n }\n visiting.delete(schema)\n}\n\nfunction invalidAgentToolSchema(toolName: string, path: string): AgentDefinitionError {\n return new AgentDefinitionError(\n `[Sixb] Agent tool '${toolName}' ${path} must be a valid Sixb schema.`\n )\n}\n\nexport function assertValidProjectAgentToolDefinitions(\n tools: readonly AgentToolDefinition[]\n): void {\n const seen = new Set<string>()\n for (let index = 0; index < tools.length; index += 1) {\n const tool = tools[index]\n if (!Object.hasOwn(tools, index) || !isAgentToolDefinition(tool)) {\n throw new AgentDefinitionError(\n \"[Sixb] Project tools must contain only agent tool definitions.\"\n )\n }\n\n assertValidAgentToolName(tool.name)\n assertValidAgentToolDescription(tool.name, tool.description)\n assertValidAgentToolInput(tool.name, tool.input)\n if (seen.has(tool.name)) {\n throw new AgentDefinitionError(\n `[Sixb] Project tools contain duplicate tool name '${tool.name}'.`\n )\n }\n seen.add(tool.name)\n }\n}\n\nfunction isValidAgentToolEnumValues(values: unknown, valueType: unknown): values is unknown[] {\n if (!Array.isArray(values) || values.length === 0) {\n return false\n }\n\n for (let index = 0; index < values.length; index += 1) {\n if (!Object.hasOwn(values, index)) {\n return false\n }\n const value = values[index]\n if (\n valueType === \"string\"\n ? typeof value !== \"string\"\n : valueType !== \"integer\" || typeof value !== \"number\" || !Number.isInteger(value)\n ) {\n return false\n }\n }\n return true\n}\n\nfunction deepFreeze<T>(value: T, seen: Set<object> = new Set()): T {\n if (value === null || typeof value !== \"object\" || seen.has(value)) {\n return value\n }\n\n seen.add(value)\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key)\n if (descriptor && \"value\" in descriptor) {\n deepFreeze(descriptor.value, seen)\n }\n }\n return Object.freeze(value)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n",
|
|
10
|
-
"import {\n cloneJsonValue,\n getInvalidJsonValueReason,\n type JsonValue,\n type ReadonlyJsonValue,\n} from \"../json\"\nimport { AgentDefinitionError, AgentToolResultValidationError } from \"./errors\"\nimport { getInvalidAgentToolResultReason } from \"./tool-result\"\nimport type {\n AgentToolDefinition,\n AgentToolHandler,\n AgentToolInputSchema,\n InferAgentToolInputSchema,\n} from \"./types\"\nimport {\n assertValidAgentToolDescription,\n assertValidAgentToolName,\n assertValidProjectAgentToolDefinitions,\n validateAndSnapshotAgentToolInput,\n} from \"./validation\"\n\nconst EMPTY_AGENT_TOOLS: readonly AgentToolDefinition[] = Object.freeze([])\nconst normalizedAgentTools = new WeakSet<AgentToolDefinition>()\n\nexport function createAgentToolDefinition<\n const TName extends string,\n const TInput extends AgentToolInputSchema,\n>(definition: {\n readonly name: TName\n readonly description: string\n readonly input: TInput\n readonly handler: AgentToolHandler<InferAgentToolInputSchema<TInput>>\n}): AgentToolDefinition<TName, TInput> {\n assertValidAgentToolName(definition.name)\n assertValidAgentToolDescription(definition.name, definition.description)\n if (typeof definition.handler !== \"function\") {\n throw new AgentDefinitionError(\n `[Sixb] Agent tool '${definition.name}' handler must be a function.`\n )\n }\n\n const input = validateAndSnapshotAgentToolInput(definition.name, definition.input)\n const tool: AgentToolDefinition<TName, TInput> = {\n kind: \"agentTool\",\n name: definition.name,\n description: definition.description,\n input,\n handler: async (context) => {\n const result = await definition.handler(context)\n let snapshot: JsonValue\n try {\n // AgentToolResult is intentionally expressed with FileRef instead of a duplicate JSON-only\n // shape. Runtime validation below proves that the complete envelope crosses the same JSON\n // boundary as legacy results.\n snapshot = cloneJsonValue(result as ReadonlyJsonValue, \"result\")\n } catch (cause) {\n throw new AgentToolResultValidationError(\n definition.name,\n getInvalidJsonValueReason(result, \"result\") ?? \"result could not be cloned safely\",\n { cause }\n )\n }\n const richResultReason = getInvalidAgentToolResultReason(snapshot)\n if (richResultReason) {\n throw new AgentToolResultValidationError(definition.name, richResultReason)\n }\n return snapshot\n },\n }\n\n normalizedAgentTools.add(tool)\n return Object.freeze(tool)\n}\n\nexport function toolsFromProjectConfig(\n tools: readonly AgentToolDefinition[] | undefined\n): readonly AgentToolDefinition[] {\n if (tools === undefined) {\n return EMPTY_AGENT_TOOLS\n }\n if (!Array.isArray(tools)) {\n throw new AgentDefinitionError(\n \"[Sixb] Project tools must be an array of agent tool definitions.\"\n )\n }\n\n assertValidProjectAgentToolDefinitions(tools)\n return normalizeAgentToolDefinitions(tools)\n}\n\nfunction normalizeAgentToolDefinitions(\n tools: readonly AgentToolDefinition[]\n): readonly AgentToolDefinition[] {\n const normalized: AgentToolDefinition[] = []\n for (const tool of tools) {\n normalized.push(normalizeAgentToolDefinition(tool))\n }\n return Object.freeze(normalized)\n}\n\nfunction normalizeAgentToolDefinition(tool: AgentToolDefinition): AgentToolDefinition {\n if (normalizedAgentTools.has(tool)) {\n return tool\n }\n\n return createAgentToolDefinition({\n name: tool.name,\n description: tool.description,\n input: tool.input,\n handler: (context) => tool.handler(context),\n })\n}\n",
|
|
11
|
-
"import { createAgentToolDefinition } from \"./tool-definition\"\nimport type {\n AgentToolDefinition,\n AgentToolDescriptionBuilder,\n AgentToolHandler,\n AgentToolInputBuilder,\n AgentToolInputSchema,\n AgentToolRunBuilder,\n InferAgentToolInputSchema,\n} from \"./types\"\nimport {\n assertValidAgentToolDescription,\n assertValidAgentToolInput,\n assertValidAgentToolName,\n} from \"./validation\"\n\n/**\n * Define a reusable tool registered through `createSixb({ tools })`.\n *\n * The returned definition is inert. The agent worker supplies its run-scoped\n * context and executes the handler only when a run calls the tool.\n */\nexport function defineAgentTool<const TName extends string>(\n name: TName\n): AgentToolDescriptionBuilder<TName> {\n assertValidAgentToolName(name)\n\n return {\n description(description: string): AgentToolInputBuilder<TName> {\n assertValidAgentToolDescription(name, description)\n\n return {\n input<const TInput extends AgentToolInputSchema>(\n input: TInput\n ): AgentToolRunBuilder<TName, TInput> {\n assertValidAgentToolInput(name, input)\n\n return {\n run(\n handler: AgentToolHandler<InferAgentToolInputSchema<TInput>>\n ): AgentToolDefinition<TName, TInput> {\n return createAgentToolDefinition({ name, description, input, handler })\n },\n }\n },\n }\n },\n }\n}\n",
|
|
12
|
-
"import { stableJsonStringify } from \"../json\"\nimport type { AgentMessageRecord } from \"../storage/agents/types\"\nimport type { AgentMessage, AgentMessagePart } from \"./message\"\n\nexport const AGENT_CONTEXT_ESTIMATOR_VERSION = 1 as const\n\nconst CHARS_PER_TOKEN = 4\nconst REQUEST_OVERHEAD_TOKENS = 8\nconst MESSAGE_OVERHEAD_TOKENS = 8\nconst TOOL_OVERHEAD_TOKENS = 16\nconst STEP_OVERHEAD_TOKENS = 2\nconst IMAGE_ALLOWANCE_TOKENS = 1_200\nconst FILE_TEXT_INLINE_MAX_BYTES = 50 * 1024\nconst FILE_TEXT_INLINE_TOTAL_MAX_BYTES = 200 * 1024\nconst TOOL_RESULT_SUMMARY_MAX_CHARS = 2_000\n\nexport interface AgentContextEstimateTool {\n readonly name: string\n readonly description: string\n /** Deterministic JSON-schema serialization sent for this tool. */\n readonly inputSchema: string\n}\n\nexport interface EstimateAgentContextRequestTokensInput {\n readonly systemPrompt: string\n readonly tools: readonly AgentContextEstimateTool[]\n readonly messages: readonly AgentMessage[]\n}\n\nexport interface AgentContextTokenEstimate {\n readonly tokens: number\n readonly estimatorVersion: typeof AGENT_CONTEXT_ESTIMATOR_VERSION\n}\n\nexport interface AgentContextCompactionBoundary {\n readonly messagesToSummarize: readonly AgentMessageRecord[]\n readonly retainedMessages: readonly AgentMessageRecord[]\n readonly summarizedThroughSeq: number\n}\n\n/** Compaction begins only once the estimated request crosses the reserved input budget. */\nexport function shouldCompactAgentContext(input: {\n readonly estimatedInputTokens: number\n readonly inputBudgetTokens: number\n}): boolean {\n return input.estimatedInputTokens > input.inputBudgetTokens\n}\n\n/** Estimate the provider request shape with one stable, conservative character heuristic. */\nexport function estimateAgentContextRequestTokens(\n input: EstimateAgentContextRequestTokensInput\n): AgentContextTokenEstimate {\n const toolTokens = input.tools.reduce(\n (total, tool) =>\n total +\n TOOL_OVERHEAD_TOKENS +\n textTokens(tool.name) +\n textTokens(tool.description) +\n textTokens(tool.inputSchema),\n 0\n )\n return {\n tokens:\n REQUEST_OVERHEAD_TOKENS +\n textTokens(input.systemPrompt) +\n toolTokens +\n estimateAgentContextMessagesTokens(input.messages).tokens,\n estimatorVersion: AGENT_CONTEXT_ESTIMATOR_VERSION,\n }\n}\n\n/** Estimate message-only growth after a provider-usage anchor. */\nexport function estimateAgentContextMessagesTokens(\n messages: readonly AgentMessage[]\n): AgentContextTokenEstimate {\n const attachments = { textBytesRemaining: FILE_TEXT_INLINE_TOTAL_MAX_BYTES }\n let tokens = 0\n for (const message of messages) {\n tokens += estimateMessageTokens(message, attachments)\n }\n return { tokens, estimatorVersion: AGENT_CONTEXT_ESTIMATOR_VERSION }\n}\n\n/** Select the safe user boundary whose retained tail is closest to the configured recent budget. */\nexport function selectAgentContextCompactionBoundary(input: {\n readonly messages: readonly AgentMessageRecord[]\n readonly keepRecentTokens: number\n}): AgentContextCompactionBoundary | null {\n if (input.messages.length < 2) return null\n\n let retainedTokens = 0\n let boundaryIndex: number | null = null\n let closestDistance = Number.POSITIVE_INFINITY\n for (let index = input.messages.length - 1; index > 0; index -= 1) {\n retainedTokens += estimateAgentContextMessagesTokens([input.messages[index]!]).tokens\n if (input.messages[index]?.role !== \"user\") continue\n\n const distance = Math.abs(input.keepRecentTokens - retainedTokens)\n if (distance <= closestDistance) {\n boundaryIndex = index\n closestDistance = distance\n }\n if (retainedTokens >= input.keepRecentTokens) break\n }\n\n if (boundaryIndex === null) return null\n\n const summarizedThroughSeq = input.messages[boundaryIndex - 1]?.seq\n if (summarizedThroughSeq === undefined) return null\n return {\n messagesToSummarize: input.messages.slice(0, boundaryIndex),\n retainedMessages: input.messages.slice(boundaryIndex),\n summarizedThroughSeq,\n }\n}\n\n/** Serialize durable conversation content as escaped quoted data for the summary model. */\nexport function serializeAgentMessagesForSummary(messages: readonly AgentMessageRecord[]): string {\n const lines = [\"<sixb_conversation_history>\"]\n for (const message of messages) {\n lines.push(\n ` <message id=\"${escapeXml(message.id)}\" seq=\"${message.seq}\" role=\"${message.role}\">`\n )\n message.parts.forEach((part, partIndex) => {\n lines.push(...serializeSummaryPart(message, part, partIndex))\n })\n lines.push(\" </message>\")\n }\n lines.push(\"</sixb_conversation_history>\")\n return lines.join(\"\\n\")\n}\n\nfunction estimateMessageTokens(\n message: AgentMessage,\n attachments: { textBytesRemaining: number }\n): number {\n let tokens = MESSAGE_OVERHEAD_TOKENS\n for (const part of message.parts) {\n switch (part.type) {\n case \"text\":\n case \"reasoning\":\n tokens += textTokens(part.text)\n break\n case \"step-start\":\n tokens += STEP_OVERHEAD_TOKENS\n break\n case \"context\":\n tokens += textTokens(stableJsonStringify(part.context))\n break\n case \"provider-state\":\n tokens += textTokens(stableJsonStringify(part.data))\n break\n case \"tool-call\":\n tokens +=\n TOOL_OVERHEAD_TOKENS +\n textTokens(part.toolName) +\n textTokens(stableJsonStringify(part.input)) +\n (part.state === \"output-available\"\n ? textTokens(stableJsonStringify(part.output))\n : textTokens(part.errorText))\n break\n case \"file\": {\n const file = part.fileRef\n tokens += textTokens(\n [file.blobId, file.digest, file.fileName, file.mediaType, file.logicalPath]\n .filter((value): value is string => value !== undefined)\n .join(\" \")\n )\n if (message.role !== \"assistant\") {\n if (looksLikeImage(file.mediaType, file.fileName)) {\n tokens += IMAGE_ALLOWANCE_TOKENS\n } else {\n const inlineBytes = Math.min(\n file.sizeBytes,\n FILE_TEXT_INLINE_MAX_BYTES,\n attachments.textBytesRemaining\n )\n attachments.textBytesRemaining -= inlineBytes\n tokens += Math.ceil(inlineBytes / CHARS_PER_TOKEN)\n }\n }\n break\n }\n }\n }\n return tokens\n}\n\nfunction serializeSummaryPart(\n message: AgentMessageRecord,\n part: AgentMessagePart,\n partIndex: number\n): string[] {\n const indent = \" \"\n switch (part.type) {\n case \"text\":\n return [`${indent}<text>${escapeXml(part.text)}</text>`]\n case \"reasoning\":\n case \"provider-state\":\n case \"step-start\":\n return []\n case \"context\":\n return part.context.kind === \"object\"\n ? [\n `${indent}<object_context origin=\"${part.origin}\" object_type_id=\"${escapeXml(part.context.ref.objectTypeId)}\" primary_id=\"${escapeXml(part.context.ref.primaryId)}\" />`,\n ]\n : [\n `${indent}<app_context origin=\"${part.origin}\" id=\"${escapeXml(part.context.id)}\" label=\"${escapeXml(part.context.label)}\">`,\n `${indent} <description>${escapeXml(part.context.description)}</description>`,\n `${indent} <value format=\"json\">${escapeXml(stableJsonStringify(part.context.value))}</value>`,\n `${indent}</app_context>`,\n ]\n case \"file\": {\n const file = part.fileRef\n const attributes = [\n `message_id=\"${escapeXml(message.id)}\"`,\n `part_index=\"${partIndex}\"`,\n `blob_id=\"${escapeXml(file.blobId)}\"`,\n `digest=\"${escapeXml(file.digest)}\"`,\n `size_bytes=\"${file.sizeBytes}\"`,\n ...(file.fileName === undefined ? [] : [`file_name=\"${escapeXml(file.fileName)}\"`]),\n ...(file.mediaType === undefined ? [] : [`media_type=\"${escapeXml(file.mediaType)}\"`]),\n ...(file.logicalPath === undefined\n ? []\n : [`logical_path=\"${escapeXml(file.logicalPath)}\"`]),\n ]\n return [`${indent}<file ${attributes.join(\" \")} />`]\n }\n case \"tool-call\": {\n const output =\n part.state === \"output-available\"\n ? truncateToolResult(stableJsonStringify(part.output))\n : truncateToolResult(part.errorText)\n return [\n `${indent}<tool_call id=\"${escapeXml(part.toolCallId)}\" name=\"${escapeXml(part.toolName)}\" state=\"${part.state}\">`,\n `${indent} <input format=\"json\">${escapeXml(stableJsonStringify(part.input))}</input>`,\n `${indent} <result>${escapeXml(output)}</result>`,\n `${indent}</tool_call>`,\n ]\n }\n }\n}\n\nfunction truncateToolResult(value: string): string {\n if (value.length <= TOOL_RESULT_SUMMARY_MAX_CHARS) return value\n return `${value.slice(0, TOOL_RESULT_SUMMARY_MAX_CHARS)}\\n[truncated ${value.length - TOOL_RESULT_SUMMARY_MAX_CHARS} characters]`\n}\n\nfunction looksLikeImage(mediaType: string | undefined, fileName: string | undefined): boolean {\n if (mediaType?.toLowerCase().startsWith(\"image/\")) return true\n return /\\.(?:avif|gif|jpe?g|png|webp)$/i.test(fileName ?? \"\")\n}\n\nfunction textTokens(value: string): number {\n return Math.ceil(new TextEncoder().encode(value).byteLength / CHARS_PER_TOKEN)\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\")\n}\n",
|
|
13
|
-
"import { randomUUID } from \"node:crypto\"\nimport {\n assertJsonObject,\n assertJsonValue,\n isJsonValue,\n isPlainRecord,\n type JsonValue,\n} from \"../json\"\nimport { ModelProviderError, ModelStreamError, StructuredOutputError } from \"../models/errors\"\nimport type {\n LanguageModelStreamEvent,\n ModelCallEndEvent,\n ModelFinishReason,\n ModelStep,\n ModelUiChunk,\n ModelUsage,\n} from \"../models/events\"\nimport type {\n LanguageModel,\n ModelReasoning,\n ModelToolSpecification,\n} from \"../models/language-model\"\nimport type {\n ModelAssistantPart,\n ModelMessage,\n ModelProviderStatePart,\n ModelTextPart,\n ModelToolCallPart,\n ModelToolOutput,\n ModelToolResultPart,\n ProviderData,\n} from \"../models/messages\"\nimport {\n estimateModelCall,\n type ModelCallCost,\n type ModelReportedCost,\n rateModelCall,\n} from \"../models/pricing\"\nimport type { ModelOutput, ModelTool } from \"../models/tools\"\n\nconst MAX_PROVIDER_DATA_BYTES = 256 * 1024\n\ninterface ModelLoopOptions {\n readonly model: LanguageModel\n readonly messages: readonly ModelMessage[]\n readonly tools?: readonly ModelTool[]\n readonly reasoning?: ModelReasoning\n readonly maxOutputTokens?: number\n readonly caching?: \"auto\" | \"off\"\n readonly maxSteps: number\n readonly signal: AbortSignal\n /** Reserve the final provider call for a tool-free synthesis response. */\n readonly finalStepInstruction?: string\n readonly prepareStep?: (\n input: PrepareModelStepInput\n ) => PrepareModelStepResult | undefined | Promise<PrepareModelStepResult | undefined>\n readonly onEvent?: (event: ModelUiChunk) => void | Promise<void>\n readonly onModelCallEnd?: (event: ModelCallEndEvent) => void | Promise<void>\n readonly onStepEnd?: (step: ModelStep) => void | Promise<void>\n readonly generateCallId?: () => string\n}\n\n/** Non-text output requires a validator; unvalidated text can only inhabit types accepting string. */\nexport type RunModelLoopInput<TOutput = string> = ModelLoopOptions &\n (\n | { readonly output: ModelOutput<TOutput> }\n | (string extends TOutput ? { readonly output?: undefined } : never)\n )\n\nexport interface PrepareModelStepInput {\n readonly stepIndex: number\n readonly messages: readonly ModelMessage[]\n readonly model: LanguageModel\n readonly signal: AbortSignal\n}\n\nexport interface PrepareModelStepResult {\n /** Replacement history retained for this request and subsequent steps. */\n readonly messages?: readonly ModelMessage[]\n}\n\nexport type ModelLoopResult<TOutput = string> =\n | {\n readonly status: \"completed\"\n readonly output: TOutput\n readonly steps: readonly ModelStep[]\n readonly finishReason: ModelFinishReason\n }\n | {\n readonly status: \"aborted\"\n readonly steps: readonly ModelStep[]\n readonly partialContent: readonly ModelAssistantPart[]\n }\n\ninterface CompletedResponse {\n readonly providerIds?: import(\"../models/events\").ModelProviderIds\n readonly content: readonly ModelAssistantPart[]\n readonly toolCalls: readonly ParsedToolCall[]\n readonly finishReason: ModelFinishReason\n readonly rawFinishReason?: string\n readonly usage: ModelUsage\n readonly responseId?: string\n readonly responseModelId?: string\n readonly projectionError?: Error\n readonly reportedCost?: ModelReportedCost\n readonly route?: import(\"../models/events\").ModelRoute\n}\n\ninterface ParsedToolCall {\n readonly part: ModelToolCallPart\n readonly inputError?: Error\n}\n\n/**\n * Run a provider-neutral, streaming model/tool loop.\n *\n * One step is exactly one provider call. Lifecycle and stream callbacks are awaited so the caller\n * controls backpressure and can fail closed before another billable call starts.\n * Completed steps and partial content contain validated JSON payloads and normalized provider\n * metadata. Trace adapters may project these results directly; storage owns write validation.\n */\nexport function runModelLoop<TOutput = string>(\n input: RunModelLoopInput<TOutput>\n): Promise<ModelLoopResult<TOutput>>\nexport async function runModelLoop(\n input: RunModelLoopInput<unknown>\n): Promise<ModelLoopResult<unknown>> {\n assertLoopInput(input)\n const tools = indexTools(input.tools ?? [])\n const toolSpecifications = [...tools.values()].map<ModelToolSpecification>((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n }))\n let messages: readonly ModelMessage[] = [...input.messages]\n const steps: ModelStep[] = []\n const generateCallId = input.generateCallId ?? (() => `model_call_${randomUUID()}`)\n const callIds = new Set<string>()\n\n for (let stepIndex = 0; stepIndex < input.maxSteps; stepIndex += 1) {\n if (input.signal.aborted) {\n return { status: \"aborted\", steps, partialContent: [] }\n }\n await input.onEvent?.({ type: \"start-step\" })\n\n let requestMessages: readonly ModelMessage[]\n try {\n const prepared = await input.prepareStep?.({\n stepIndex,\n messages,\n model: input.model,\n signal: input.signal,\n })\n requestMessages = prepared?.messages ?? messages\n } catch (error) {\n if (!input.signal.aborted && !isAbortError(error)) throw error\n return { status: \"aborted\", steps, partialContent: [] }\n }\n if (input.signal.aborted) {\n return { status: \"aborted\", steps, partialContent: [] }\n }\n let requestTools: readonly ModelToolSpecification[] = toolSpecifications\n if (input.finalStepInstruction !== undefined && stepIndex === input.maxSteps - 1) {\n requestMessages = [\n ...requestMessages,\n { role: \"user\", content: [{ type: \"text\", text: input.finalStepInstruction }] },\n ]\n requestTools = []\n }\n\n const callId = generateCallId()\n if (!callId || callIds.has(callId)) {\n throw new ModelStreamError(`[SixbModels] Model call IDs must be nonempty and unique.`)\n }\n callIds.add(callId)\n const accumulator = new StreamAccumulator(input.onEvent)\n let accepted = false\n let cost: ModelCallCost = { status: \"unpriceable\", reason: \"missing-usage\" }\n let terminalStreamError: { readonly error: unknown } | undefined\n try {\n const stream = await input.model.stream({\n callId,\n messages: requestMessages,\n tools: requestTools,\n ...(input.reasoning === undefined ? {} : { reasoning: input.reasoning }),\n ...(input.maxOutputTokens === undefined ? {} : { maxOutputTokens: input.maxOutputTokens }),\n ...(input.caching === undefined ? {} : { caching: input.caching }),\n ...(input.output === undefined\n ? {}\n : {\n responseFormat: {\n type: \"json\" as const,\n name: input.output.name,\n ...(input.output.description === undefined\n ? {}\n : { description: input.output.description }),\n schema: input.output.schema,\n },\n }),\n signal: input.signal,\n })\n accepted = true\n for await (const event of stream.events) {\n await accumulator.accept(event)\n }\n } catch (error) {\n const aborted = input.signal.aborted || isAbortError(error)\n if (accumulator.isFinished()) {\n if (!aborted) terminalStreamError = { error }\n } else if (!aborted) {\n throw error\n } else {\n return {\n status: \"aborted\",\n steps,\n partialContent: accumulator.partialContent(),\n }\n }\n } finally {\n // Once a stream is accepted, cancellation or protocol failure cannot erase the call.\n // Only a finish event establishes final meters; interrupted calls remain explicitly unknown.\n if (accepted) {\n const facts = accumulator.accounting()\n const estimate = accumulator.isFinished() ? estimateModelCall(input.model, facts) : cost\n cost = facts.reportedCost\n ? rateModelCall({ usage: facts.usage, reported: facts.reportedCost })\n : estimate\n await input.onModelCallEnd?.({\n callId,\n providerId: input.model.providerId,\n modelId: input.model.modelId,\n responseId: facts.responseId ?? `${callId}:response`,\n providerIds: facts.providerIds,\n responseModelId: facts.responseModelId,\n usage: facts.usage,\n cost,\n ...(facts.reportedCost === undefined ? {} : { estimate }),\n ...(input.reasoning === undefined ? {} : { requestedReasoning: input.reasoning }),\n ...(facts.route === undefined ? {} : { route: facts.route }),\n })\n }\n }\n\n if (input.signal.aborted && !accumulator.isFinished()) {\n return { status: \"aborted\", steps, partialContent: accumulator.partialContent() }\n }\n const response = accumulator.complete()\n const responseId = response.responseId ?? `${callId}:response`\n if (terminalStreamError) throw terminalStreamError.error\n if (response.projectionError) throw response.projectionError\n if (input.signal.aborted) {\n return { status: \"aborted\", steps, partialContent: response.content }\n }\n\n const localCalls = response.toolCalls.filter((call) => call.part.providerExecuted !== true)\n if (response.finishReason === \"pause\" && localCalls.length === 0) {\n const step = modelStep(response, responseId, response.content, cost)\n steps.push(step)\n await input.onStepEnd?.(step)\n messages = [...requestMessages, { role: \"assistant\", content: response.content }]\n if (stepIndex + 1 === input.maxSteps) {\n throw new ModelStreamError(\n \"[SixbModels] Model reached the step limit while a provider continuation was pending.\"\n )\n }\n continue\n }\n if (localCalls.length === 0) {\n const step = modelStep(response, responseId, response.content, cost)\n steps.push(step)\n await input.onStepEnd?.(step)\n if (input.output) {\n const text = responseText(response)\n if (response.finishReason !== \"stop\") {\n throw new StructuredOutputError(\n `[SixbModels] Structured output did not complete successfully (${response.finishReason}).`,\n structuredOutputErrorContext(input, response, responseId, cost, text)\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw new StructuredOutputError(\"[SixbModels] Model did not produce valid JSON output.\", {\n cause: error,\n ...structuredOutputErrorContext(input, response, responseId, cost, text),\n })\n }\n try {\n return {\n status: \"completed\",\n output: input.output.validate(raw),\n steps,\n finishReason: response.finishReason,\n }\n } catch (error) {\n throw new StructuredOutputError(\"[SixbModels] Structured output validation failed.\", {\n cause: error,\n ...structuredOutputErrorContext(input, response, responseId, cost, text),\n })\n }\n }\n const output = responseText(response)\n return { status: \"completed\", output, steps, finishReason: response.finishReason }\n }\n\n const toolResults = await Promise.all(\n localCalls.map((call) => executeToolCall(call, tools, callId, input.signal, input.onEvent))\n )\n const step = modelStep(response, responseId, [...response.content, ...toolResults], cost)\n steps.push(step)\n await input.onStepEnd?.(step)\n\n if (input.signal.aborted) {\n return {\n status: \"aborted\",\n steps,\n partialContent: [],\n }\n }\n\n const assistantContent = response.content.filter(\n (part) => part.type !== \"tool-result\" || part.providerExecuted === true\n )\n messages = [\n ...requestMessages,\n { role: \"assistant\", content: assistantContent },\n { role: \"tool\", content: toolResults },\n ]\n\n if (stepIndex + 1 === input.maxSteps) {\n if (input.output) {\n throw new StructuredOutputError(\n \"[SixbModels] Model reached the step limit without structured output.\",\n structuredOutputErrorContext(input, response, responseId, cost, responseText(response))\n )\n }\n const output = responseText(response)\n return { status: \"completed\", output, steps, finishReason: response.finishReason }\n }\n }\n\n throw new ModelStreamError(\"[SixbModels] Model loop exited without a terminal result.\")\n}\n\nfunction assertLoopInput(input: RunModelLoopInput<unknown>): void {\n if (\n input.maxOutputTokens !== undefined &&\n (!Number.isSafeInteger(input.maxOutputTokens) || input.maxOutputTokens <= 0)\n ) {\n throw new TypeError(\"[SixbModels] maxOutputTokens must be a positive safe integer.\")\n }\n if (!Number.isInteger(input.maxSteps) || input.maxSteps <= 0) {\n throw new TypeError(\"[SixbModels] maxSteps must be a positive integer.\")\n }\n if (!input.model.providerId.trim() || !input.model.modelId.trim()) {\n throw new TypeError(\"[SixbModels] Model providerId and modelId must not be empty.\")\n }\n if (\n input.model.definition.providerId !== input.model.providerId ||\n input.model.definition.modelId !== input.model.modelId\n ) {\n throw new TypeError(\n `[SixbModels] Model definition for '${input.model.providerId}/${input.model.modelId}' has a different identity.`\n )\n }\n if (input.output) {\n if (!input.output.name.trim()) {\n throw new TypeError(\"[SixbModels] Structured output names must not be empty.\")\n }\n assertJsonObject(input.output.schema, \"structured output schema\")\n }\n}\n\nfunction indexTools(tools: readonly ModelTool[]): ReadonlyMap<string, ModelTool> {\n const result = new Map<string, ModelTool>()\n for (const tool of tools) {\n if (!tool.name.trim()) throw new TypeError(\"[SixbModels] Tool names must not be empty.\")\n if (result.has(tool.name)) {\n throw new TypeError(`[SixbModels] Duplicate tool name '${tool.name}'.`)\n }\n assertJsonObject(tool.inputSchema, `tool '${tool.name}' input schema`)\n result.set(tool.name, tool)\n }\n return result\n}\n\nfunction responseText(response: CompletedResponse): string {\n return response.content\n .filter((part): part is ModelTextPart => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\")\n}\n\nfunction structuredOutputErrorContext(\n input: RunModelLoopInput<unknown>,\n response: CompletedResponse,\n responseId: string,\n cost: ModelCallCost,\n text: string\n) {\n return {\n text,\n providerId: input.model.providerId,\n modelId: input.model.modelId,\n responseId,\n ...(response.responseModelId === undefined\n ? {}\n : { responseModelId: response.responseModelId }),\n finishReason: response.finishReason,\n usage: response.usage,\n cost,\n }\n}\n\nfunction modelStep(\n response: CompletedResponse,\n responseId: string,\n content: readonly ModelAssistantPart[],\n cost: import(\"../models/pricing\").ModelCallCost\n): ModelStep {\n return {\n content,\n finishReason: response.finishReason,\n ...(response.rawFinishReason === undefined\n ? {}\n : { rawFinishReason: response.rawFinishReason }),\n usage: response.usage,\n responseId,\n ...(response.responseModelId === undefined\n ? {}\n : { responseModelId: response.responseModelId }),\n cost,\n ...(response.route === undefined ? {} : { route: response.route }),\n }\n}\n\nasync function executeToolCall(\n call: ParsedToolCall,\n tools: ReadonlyMap<string, ModelTool>,\n callId: string,\n signal: AbortSignal,\n onEvent: RunModelLoopInput[\"onEvent\"]\n): Promise<ModelToolResultPart> {\n const { part } = call\n if (call.inputError) {\n const errorText = `Tool input is not valid JSON: ${call.inputError.message}`\n await onEvent?.({\n type: \"tool-input-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n errorText,\n })\n return toolErrorResult(part, errorText)\n }\n\n const tool = tools.get(part.toolName)\n if (!tool) {\n const errorText = `Tool '${part.toolName}' is not available.`\n await onEvent?.({\n type: \"tool-output-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n errorText,\n })\n return toolErrorResult(part, errorText)\n }\n\n let parsed: unknown\n try {\n parsed = tool.parseInput(part.input)\n } catch (error) {\n const errorText = error instanceof Error ? error.message : \"Tool input validation failed.\"\n await onEvent?.({\n type: \"tool-input-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n errorText,\n })\n return toolErrorResult(part, errorText)\n }\n\n await onEvent?.({\n type: \"tool-input-available\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n })\n let output: JsonValue\n let modelOutput: ModelToolOutput\n try {\n const context = { signal, callId, toolCallId: part.toolCallId }\n output = await tool.execute(parsed, context)\n assertJsonValue(output, `tool '${part.toolName}' output`)\n modelOutput = tool.toModelOutput\n ? await tool.toModelOutput(output, context)\n : modelToolOutput(output)\n validateModelToolOutput(modelOutput, part.toolName)\n } catch (error) {\n const errorText = tool.errorText(error)\n await onEvent?.({\n type: \"tool-output-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n errorText,\n })\n return toolErrorResult(part, errorText)\n }\n // Publication failures belong to the caller, not the tool's recoverable error channel.\n await onEvent?.({\n type: \"tool-output-available\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n })\n return {\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: modelOutput,\n ...(modelOutputMatchesOriginal(modelOutput, output) ? {} : { originalOutput: output }),\n }\n}\n\nfunction validateModelToolOutput(output: ModelToolOutput, toolName: string): void {\n if (output.type === \"text\" || output.type === \"error-text\") {\n if (typeof output.value !== \"string\") {\n throw new TypeError(`[SixbModels] Tool '${toolName}' model output must contain text.`)\n }\n return\n }\n if (output.type !== \"json\" && output.type !== \"error-json\") {\n throw new TypeError(\n `[SixbModels] Tool '${toolName}' returned an unsupported model output type.`\n )\n }\n assertJsonValue(output.value, `tool '${toolName}' model output`)\n}\n\nfunction modelOutputMatchesOriginal(output: ModelToolOutput, original: JsonValue): boolean {\n if (output.type === \"text\") return typeof original === \"string\" && output.value === original\n if (output.type === \"json\") return output.value === original\n return false\n}\n\nfunction modelToolOutput(value: JsonValue): ModelToolOutput {\n return typeof value === \"string\" ? { type: \"text\", value } : { type: \"json\", value }\n}\n\nfunction toolErrorResult(part: ModelToolCallPart, errorText: string): ModelToolResultPart {\n if (typeof errorText !== \"string\") {\n throw new TypeError(`[SixbModels] Tool '${part.toolName}' error text must be a string.`)\n }\n return {\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: { type: \"error-text\", value: errorText },\n }\n}\n\ntype MutableTextPart = {\n type: \"text\"\n text: string\n providerData?: ProviderData\n complete: boolean\n}\ntype MutableReasoningPart = {\n type: \"reasoning\"\n text: string\n providerData?: ProviderData\n complete: boolean\n}\ntype MutableToolCall = {\n type: \"tool-call\"\n toolCallId: string\n toolName: string\n inputText: string\n providerData?: ProviderData\n providerExecuted?: boolean\n dynamic?: boolean\n complete: boolean\n}\ntype MutablePart =\n | MutableTextPart\n | MutableReasoningPart\n | MutableToolCall\n | ModelToolResultPart\n | ModelProviderStatePart\n\nclass StreamAccumulator {\n private readonly parts: MutablePart[] = []\n private readonly spans = new Map<string, MutableTextPart | MutableReasoningPart>()\n private readonly toolCalls = new Map<string, MutableToolCall>()\n private started = false\n private finished = false\n private finishReason: ModelFinishReason | undefined\n private rawFinishReason: string | undefined\n private usage: ModelUsage = {}\n private responseId: string | undefined\n private providerIds: import(\"../models/events\").ModelProviderIds | undefined\n private responseModelId: string | undefined\n private projectionError: Error | undefined\n private reportedCost: ModelReportedCost | undefined\n private route: import(\"../models/events\").ModelRoute | undefined\n\n constructor(private readonly onEvent: RunModelLoopInput[\"onEvent\"]) {}\n\n isFinished(): boolean {\n return this.finished\n }\n\n async accept(event: LanguageModelStreamEvent): Promise<void> {\n if (this.finished) {\n throw new ModelStreamError(`[SixbModels] Received '${event.type}' after stream finish.`)\n }\n switch (event.type) {\n case \"stream-start\":\n if (this.started) throw new ModelStreamError(\"[SixbModels] Duplicate stream-start event.\")\n this.started = true\n return\n case \"response-metadata\":\n this.requireStarted(event.type)\n this.responseId = event.id ?? this.responseId\n if (event.providerIds) this.providerIds = { ...this.providerIds, ...event.providerIds }\n this.responseModelId = event.modelId ?? this.responseModelId\n return\n case \"text-start\":\n await this.startText(event)\n return\n case \"text-delta\":\n await this.appendText(event, \"text\")\n return\n case \"text-end\":\n await this.endText(event, \"text\")\n return\n case \"reasoning-start\":\n await this.startReasoning(event)\n return\n case \"reasoning-delta\":\n await this.appendText(event, \"reasoning\")\n return\n case \"reasoning-end\":\n await this.endText(event, \"reasoning\")\n return\n case \"tool-input-start\":\n await this.startTool(event)\n return\n case \"tool-input-delta\":\n await this.appendTool(event)\n return\n case \"tool-input-end\":\n this.endTool(event)\n return\n case \"tool-call\":\n await this.completeTool(event)\n return\n case \"tool-result\":\n this.addProviderToolResult(event)\n return\n case \"provider-state\":\n if (typeof event.providerId !== \"string\" || event.providerId.length === 0) {\n this.captureProjectionError(\n new ModelStreamError(\"[SixbModels] Provider state requires a nonempty provider ID.\")\n )\n return\n }\n if (this.captureProviderState(event.data)) {\n this.parts.push({\n type: \"provider-state\",\n providerId: event.providerId,\n data: event.data,\n })\n }\n return\n case \"finish\":\n this.requireStarted(event.type)\n validateUsage(event.usage)\n this.captureProviderData(event.providerData)\n this.finished = true\n this.finishReason = event.finishReason\n this.rawFinishReason = event.rawFinishReason\n this.usage = event.usage\n this.reportedCost = event.reportedCost\n this.route = event.route\n return\n case \"error\":\n throw event.error instanceof Error\n ? event.error\n : new ModelProviderError(\"[SixbModels] Provider stream failed.\", \"unknown\", \"unknown\", {\n cause: event.error,\n })\n }\n }\n\n complete(): CompletedResponse {\n if (!this.started) throw new ModelStreamError(\"[SixbModels] Stream did not start.\")\n if (!this.finished || !this.finishReason) {\n throw new ModelStreamError(\"[SixbModels] Stream ended without a finish event.\")\n }\n for (const part of this.parts) {\n if (\"complete\" in part && !part.complete) {\n throw new ModelStreamError(\n `[SixbModels] Stream finished with incomplete ${part.type} content.`\n )\n }\n }\n const parsed = this.parseParts(false)\n return {\n content: parsed.content,\n toolCalls: parsed.toolCalls,\n finishReason: this.finishReason,\n ...(this.rawFinishReason === undefined ? {} : { rawFinishReason: this.rawFinishReason }),\n ...this.accounting(),\n ...(this.projectionError === undefined ? {} : { projectionError: this.projectionError }),\n }\n }\n\n accounting() {\n return {\n usage: this.usage,\n ...(this.responseId === undefined ? {} : { responseId: this.responseId }),\n ...(this.providerIds === undefined ? {} : { providerIds: this.providerIds }),\n ...(this.responseModelId === undefined ? {} : { responseModelId: this.responseModelId }),\n ...(this.reportedCost === undefined ? {} : { reportedCost: this.reportedCost }),\n ...(this.route === undefined ? {} : { route: this.route }),\n }\n }\n\n partialContent(): readonly ModelAssistantPart[] {\n return this.parseParts(true).content\n }\n\n private parseParts(partial: boolean): {\n readonly content: ModelAssistantPart[]\n readonly toolCalls: ParsedToolCall[]\n } {\n const content: ModelAssistantPart[] = []\n const toolCalls: ParsedToolCall[] = []\n for (const part of this.parts) {\n if (part.type === \"text\") {\n if ((!partial || part.text.length > 0) && (part.complete || partial)) {\n content.push({\n type: \"text\",\n text: part.text,\n ...(part.providerData === undefined ? {} : { providerData: part.providerData }),\n })\n }\n } else if (part.type === \"reasoning\") {\n if (part.complete) {\n content.push({\n type: \"reasoning\",\n text: part.text,\n ...(part.providerData === undefined ? {} : { providerData: part.providerData }),\n })\n }\n } else if (part.type === \"tool-call\") {\n if (!part.complete) continue\n let value: JsonValue = null\n let inputError: Error | undefined\n try {\n const parsed: unknown = JSON.parse(part.inputText)\n if (!isJsonValue(parsed)) throw new TypeError(\"input is not a JSON value\")\n value = parsed\n } catch (error) {\n inputError = error instanceof Error ? error : new Error(String(error))\n }\n const call: ModelToolCallPart = {\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: value,\n ...(part.providerData === undefined ? {} : { providerData: part.providerData }),\n ...(part.providerExecuted === undefined\n ? {}\n : { providerExecuted: part.providerExecuted }),\n ...(part.dynamic === undefined ? {} : { dynamic: part.dynamic }),\n }\n content.push(call)\n toolCalls.push({ part: call, ...(inputError === undefined ? {} : { inputError }) })\n } else {\n content.push(part)\n }\n }\n return { content, toolCalls }\n }\n\n private async startText(\n event: Extract<LanguageModelStreamEvent, { type: \"text-start\" }>\n ): Promise<void> {\n this.requireStarted(event.type)\n this.assertNewSpan(event.id)\n const providerData = this.captureProviderData(event.providerData)\n const part: MutableTextPart = {\n type: \"text\",\n text: \"\",\n complete: false,\n ...(providerData === undefined ? {} : { providerData }),\n }\n this.spans.set(event.id, part)\n this.parts.push(part)\n await this.onEvent?.({ type: \"text-start\", id: event.id })\n }\n\n private async startReasoning(\n event: Extract<LanguageModelStreamEvent, { type: \"reasoning-start\" }>\n ): Promise<void> {\n this.requireStarted(event.type)\n this.assertNewSpan(event.id)\n const providerData = this.captureProviderData(event.providerData)\n const part: MutableReasoningPart = {\n type: \"reasoning\",\n text: \"\",\n complete: false,\n ...(providerData === undefined ? {} : { providerData }),\n }\n this.spans.set(event.id, part)\n this.parts.push(part)\n await this.onEvent?.({ type: \"reasoning-start\", id: event.id })\n }\n\n private async appendText(\n event: Extract<LanguageModelStreamEvent, { type: \"text-delta\" | \"reasoning-delta\" }>,\n expected: \"text\" | \"reasoning\"\n ): Promise<void> {\n const part = this.spans.get(event.id)\n if (!part || part.type !== expected || part.complete) {\n throw new ModelStreamError(\n `[SixbModels] ${event.type} references unopened ${expected} span '${event.id}'.`\n )\n }\n part.text += event.delta\n await this.onEvent?.({ type: event.type, id: event.id, delta: event.delta })\n }\n\n private async endText(\n event: Extract<LanguageModelStreamEvent, { type: \"text-end\" | \"reasoning-end\" }>,\n expected: \"text\" | \"reasoning\"\n ): Promise<void> {\n const part = this.spans.get(event.id)\n if (!part || part.type !== expected || part.complete) {\n throw new ModelStreamError(\n `[SixbModels] ${event.type} references unopened ${expected} span '${event.id}'.`\n )\n }\n part.providerData = mergeProviderData(\n part.providerData,\n this.captureProviderData(event.providerData)\n )\n part.complete = true\n this.spans.delete(event.id)\n await this.onEvent?.({ type: event.type, id: event.id })\n }\n\n private async startTool(\n event: Extract<LanguageModelStreamEvent, { type: \"tool-input-start\" }>\n ): Promise<void> {\n this.requireStarted(event.type)\n if (\n typeof event.id !== \"string\" ||\n !event.id ||\n typeof event.toolName !== \"string\" ||\n !event.toolName\n ) {\n throw new ModelStreamError(\"[SixbModels] Tool calls require nonempty IDs and names.\")\n }\n if (this.toolCalls.has(event.id)) {\n throw new ModelStreamError(`[SixbModels] Duplicate tool call ID '${event.id}'.`)\n }\n const providerData = this.captureProviderData(event.providerData)\n const part: MutableToolCall = {\n type: \"tool-call\",\n toolCallId: event.id,\n toolName: event.toolName,\n inputText: \"\",\n complete: false,\n ...(providerData === undefined ? {} : { providerData }),\n ...(event.providerExecuted === undefined ? {} : { providerExecuted: event.providerExecuted }),\n ...(event.dynamic === undefined ? {} : { dynamic: event.dynamic }),\n }\n this.toolCalls.set(event.id, part)\n this.parts.push(part)\n await this.onEvent?.({\n type: \"tool-input-start\",\n toolCallId: event.id,\n toolName: event.toolName,\n })\n }\n\n private async appendTool(\n event: Extract<LanguageModelStreamEvent, { type: \"tool-input-delta\" }>\n ): Promise<void> {\n const part = this.toolCalls.get(event.id)\n if (!part || part.complete) {\n throw new ModelStreamError(\n `[SixbModels] tool-input-delta references unopened tool call '${event.id}'.`\n )\n }\n part.inputText += event.delta\n await this.onEvent?.({\n type: \"tool-input-delta\",\n toolCallId: event.id,\n toolName: part.toolName,\n inputTextDelta: event.delta,\n })\n }\n\n private endTool(event: Extract<LanguageModelStreamEvent, { type: \"tool-input-end\" }>): void {\n const part = this.toolCalls.get(event.id)\n if (!part || part.complete) {\n throw new ModelStreamError(\n `[SixbModels] tool-input-end references unopened tool call '${event.id}'.`\n )\n }\n part.providerData = mergeProviderData(\n part.providerData,\n this.captureProviderData(event.providerData)\n )\n part.complete = true\n }\n\n private async completeTool(\n event: Extract<LanguageModelStreamEvent, { type: \"tool-call\" }>\n ): Promise<void> {\n await this.startTool({\n type: \"tool-input-start\",\n id: event.toolCallId,\n toolName: event.toolName,\n ...(event.providerData === undefined ? {} : { providerData: event.providerData }),\n ...(event.providerExecuted === undefined ? {} : { providerExecuted: event.providerExecuted }),\n ...(event.dynamic === undefined ? {} : { dynamic: event.dynamic }),\n })\n const part = this.toolCalls.get(event.toolCallId)\n if (!part) throw new ModelStreamError(\"[SixbModels] Failed to index completed tool call.\")\n part.inputText = event.input\n part.complete = true\n }\n\n private addProviderToolResult(\n event: Extract<LanguageModelStreamEvent, { type: \"tool-result\" }>\n ): void {\n if (!this.captureJsonValue(event.output, \"provider tool result\")) return\n const providerData = this.captureProviderData(event.providerData)\n this.parts.push({\n type: \"tool-result\",\n toolCallId: event.toolCallId,\n toolName: event.toolName,\n output: event.isError\n ? { type: \"error-json\", value: event.output }\n : modelToolOutput(event.output),\n providerExecuted: event.providerExecuted ?? true,\n ...(event.dynamic === undefined ? {} : { dynamic: event.dynamic }),\n ...(providerData === undefined ? {} : { providerData }),\n })\n }\n\n private captureProviderData(data: ProviderData | undefined): ProviderData | undefined {\n if (data === undefined) return undefined\n try {\n return normalizeProviderData(data)\n } catch (error) {\n this.captureProjectionError(error)\n return undefined\n }\n }\n\n private captureProviderState(value: unknown): value is JsonValue {\n if (!this.captureJsonValue(value, \"provider state\")) return false\n if (JSON.stringify(value).length > MAX_PROVIDER_DATA_BYTES) {\n this.captureProjectionError(\n new ModelStreamError(\n `[SixbModels] Provider state exceeds the ${MAX_PROVIDER_DATA_BYTES}-byte response limit.`\n )\n )\n return false\n }\n return true\n }\n\n private captureJsonValue(value: unknown, label: string): value is JsonValue {\n try {\n assertJsonValue(value, label)\n return true\n } catch (error) {\n this.captureProjectionError(error)\n return false\n }\n }\n\n private captureProjectionError(error: unknown): void {\n this.projectionError ??= error instanceof Error ? error : new Error(String(error))\n }\n\n private requireStarted(type: string): void {\n if (!this.started) {\n throw new ModelStreamError(`[SixbModels] Received '${type}' before stream-start.`)\n }\n }\n\n private assertNewSpan(id: string): void {\n if (!id) throw new ModelStreamError(\"[SixbModels] Content span IDs must not be empty.\")\n if (this.spans.has(id)) {\n throw new ModelStreamError(`[SixbModels] Duplicate open content span '${id}'.`)\n }\n }\n}\n\nfunction validateUsage(usage: ModelUsage): void {\n for (const [key, value] of Object.entries(usage)) {\n if (key === \"raw\") {\n if (value !== undefined) assertJsonValue(value, \"raw model usage\")\n continue\n }\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {\n throw new ModelStreamError(`[SixbModels] Usage field '${key}' must be a nonnegative integer.`)\n }\n }\n}\n\nfunction normalizeProviderData(value: ProviderData): ProviderData {\n const data = omitUndefinedObjectProperties(value)\n assertJsonValue(data, \"provider data\")\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n throw new TypeError(\"[SixbModels] provider data must be a JSON object.\")\n }\n if (JSON.stringify(data).length > MAX_PROVIDER_DATA_BYTES) {\n throw new ModelStreamError(\n `[SixbModels] Provider data exceeds the ${MAX_PROVIDER_DATA_BYTES}-byte response limit.`\n )\n }\n return data\n}\n\n/** Normalize absent metadata fields at ingestion, leaving non-JSON values for validation. */\nfunction omitUndefinedObjectProperties(value: unknown, seen = new Set<object>()): unknown {\n if (typeof value !== \"object\" || value === null || seen.has(value)) return value\n seen.add(value)\n try {\n if (Array.isArray(value)) {\n return value.map((entry) => omitUndefinedObjectProperties(entry, seen))\n }\n if (!isPlainRecord(value)) return value\n return Object.fromEntries(\n Reflect.ownKeys(value)\n .filter((key) => Object.prototype.propertyIsEnumerable.call(value, key))\n .map((key) => [key, Reflect.get(value, key)] as const)\n .filter(([, entry]) => entry !== undefined)\n .map(([key, entry]) => [key, omitUndefinedObjectProperties(entry, seen)])\n )\n } finally {\n seen.delete(value)\n }\n}\n\nfunction mergeProviderData(\n first: ProviderData | undefined,\n second: ProviderData | undefined\n): ProviderData | undefined {\n if (first === undefined) return second\n if (second === undefined) return first\n return { ...first, ...second }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (\n (error instanceof DOMException && error.name === \"AbortError\") ||\n (error instanceof Error && error.name === \"AbortError\")\n )\n}\n",
|
|
14
|
-
"import type { AgentReference } from \"./types\"\n\n/** Project Agent capability used in security grants such as `can.run(agent)`. */\nexport const agent: AgentReference = Object.freeze({\n kind: \"agent\",\n usage: Object.freeze({ kind: \"aiUsage\" }),\n})\n",
|
|
15
|
-
"import type { AgentContextCheckpointRecord, AgentMessageRecord } from \"../storage/agents/types\"\nimport type { AgentMessage } from \"./message\"\n\n/** A model-only message. Persisted tail messages carry `id`; the synthetic summary does not. */\nexport interface AgentThreadModelContextMessage extends AgentMessage {\n readonly id?: string\n}\n\nexport interface ProjectAgentThreadModelContextInput {\n readonly checkpoint: AgentContextCheckpointRecord | null\n /** Complete retained tail, ordered by ascending per-thread sequence. */\n readonly messages: readonly AgentMessageRecord[]\n}\n\n/**\n * Build the bounded, model-only view of a durable thread.\n *\n * The function is deliberately pure: storage chooses the latest checkpoint and reads its retained\n * tail; this function validates that projection and prepends one synthetic user-role summary.\n */\nexport function projectAgentThreadModelContext(\n input: ProjectAgentThreadModelContextInput\n): readonly AgentThreadModelContextMessage[] {\n const { checkpoint, messages } = input\n if (!checkpoint) return messages\n\n assertConsistentCheckpointProjection(checkpoint, messages)\n return [\n {\n role: \"user\",\n parts: [{ type: \"text\", text: serializeThreadSummary(checkpoint.summary) }],\n },\n ...messages,\n ]\n}\n\nfunction assertConsistentCheckpointProjection(\n checkpoint: AgentContextCheckpointRecord,\n messages: readonly AgentMessageRecord[]\n): void {\n if (checkpoint.summaryFormatVersion !== 1 || checkpoint.summary.trim().length === 0) {\n throw projectionError(checkpoint, \"has an invalid summary\")\n }\n if (checkpoint.summarizedThroughSeq >= checkpoint.observedHeadSeq) {\n throw projectionError(checkpoint, \"does not retain its observed head\")\n }\n if (messages.length === 0) {\n throw projectionError(checkpoint, \"has no retained messages\")\n }\n\n let expectedSeq = checkpoint.summarizedThroughSeq + 1\n for (const message of messages) {\n if (message.projectId !== checkpoint.projectId || message.threadId !== checkpoint.threadId) {\n throw projectionError(checkpoint, \"contains a message from another thread\")\n }\n if (message.seq !== expectedSeq) {\n throw projectionError(checkpoint, `has a sequence gap before message '${message.id}'`)\n }\n expectedSeq += 1\n }\n\n if (messages[0]?.role !== \"user\") {\n throw projectionError(checkpoint, \"does not begin at a user turn boundary\")\n }\n if ((messages.at(-1)?.seq ?? 0) < checkpoint.observedHeadSeq) {\n throw projectionError(checkpoint, \"ends before the checkpoint's observed head\")\n }\n}\n\nfunction serializeThreadSummary(summary: string): string {\n return [\n \"The earlier conversation was compacted into this continuation summary.\",\n \"\",\n \"<sixb_thread_summary>\",\n escapeXml(summary),\n \"</sixb_thread_summary>\",\n ].join(\"\\n\")\n}\n\nfunction projectionError(checkpoint: AgentContextCheckpointRecord, detail: string): Error {\n return new Error(\n `[Sixb] Agent context checkpoint '${checkpoint.id}' for thread '${checkpoint.threadId}' ${detail}.`\n )\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\")\n}\n"
|
|
16
|
-
],
|
|
17
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,SAAS,6BAA6B,CAC3C,OACoB;AAAA,EACpB,IAAI,MAAM,WAAW;AAAA,IAAG;AAAA,EAExB,MAAM,QAAQ,CAAC,qBAAqB;AAAA,EACpC,WAAW,QAAQ,OAAO;AAAA,IACxB,IAAI,KAAK,QAAQ,SAAS,UAAU;AAAA,MAClC,MAAM,KACJ,sBACA,uBAAuB,UAAU,KAAK,QAAQ,IAAI,YAAY,sBAC9D,mBAAmB,UAAU,KAAK,QAAQ,IAAI,SAAS,kBACvD,qBACF;AAAA,MACA;AAAA,IACF;AAAA,IAEA,MAAM,KACJ,yBACA,WAAW,UAAU,KAAK,QAAQ,EAAE,UACpC,oBAAoB,UAAU,KAAK,QAAQ,WAAW,mBACtD,4BAA4B,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B;AAAA,EACxF,OAAO,IAAI,MACT,oCAAoC,WAAW,mBAAmB,WAAW,aAAa,SAC5F;AAAA;AAGF,SAAS,UAAS,CAAC,OAAuB;AAAA,EACxC,OAAO,MACJ,WAAW,KAAK,OAAO,EACvB,WAAW,KAAK,MAAM,EACtB,WAAW,KAAK,MAAM,EACtB,WAAW,KAAK,QAAQ,EACxB,WAAW,KAAK,QAAQ;AAAA;",
|
|
18
|
-
"debugId": "5E06D21E695131D964756E2164756E21",
|
|
19
|
-
"names": []
|
|
20
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/agents/errors.ts", "../src/agents/context.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"/**\n * Base error for the agents module. Specific subclasses extend this so callers\n * can catch any agent-scoped failure with a single `instanceof AgentDefinitionError` check.\n */\nexport class AgentDefinitionError extends Error {\n readonly name: string = \"AgentDefinitionError\"\n}\n\n/**\n * An agent-tool failure whose message is intentionally safe to expose to the model and persist in\n * the durable trace. Tool authors must keep the message free of credentials and internal details;\n * unknown errors remain masked by the worker.\n */\nexport class AgentToolPublicError extends Error {\n readonly name: string = \"AgentToolPublicError\"\n}\n\n/** Raised when an agent tool result cannot cross the durable message boundary. */\nexport class AgentToolResultValidationError extends Error {\n readonly name = \"AgentToolResultValidationError\"\n\n constructor(\n readonly toolName: string,\n readonly reason: string,\n options?: ErrorOptions\n ) {\n super(`[Sixb] Agent tool '${toolName}' returned an invalid result; ${reason}.`, options)\n }\n}\n\nexport type AgentRequestErrorCode =\n | \"agent_selector_removed\"\n | \"agent_not_found\"\n | \"model_not_found\"\n | \"invalid_model_selection\"\n | \"run_not_found\"\n | \"run_not_retryable\"\n | \"thread_not_found\"\n | \"active_run_exists\"\n | \"authority_not_inheritable\"\n | \"invalid_context\"\n | \"storage_unavailable\"\n\n/**\n * Raised by {@link requestAgentRun} (the trigger). Callers branch on `code` rather than message text\n * — e.g. the HTTP layer maps `active_run_exists` to 409 and `agent_not_found` to 404.\n */\nexport class AgentRequestError extends Error {\n readonly name = \"AgentRequestError\"\n\n constructor(\n readonly code: AgentRequestErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n",
|
|
6
|
-
"import type { JsonValue } from \"../json\"\nimport { cloneJsonValue, getInvalidJsonValueReason, stableJsonStringify } from \"../json\"\nimport type { ObjectRef } from \"../ontology/refs\"\nimport { AgentRequestError } from \"./errors\"\n\nexport type AgentContextInput =\n | { readonly kind: \"object\"; readonly ref: ObjectRef }\n | {\n readonly kind: \"app-state\"\n readonly id: string\n readonly label: string\n readonly description: string\n readonly value: JsonValue\n }\n\nexport type AgentContextOrigin = \"ambient\" | \"explicit\"\n\nexport interface AgentContextEntryInput {\n readonly context: AgentContextInput\n readonly origin: AgentContextOrigin\n}\n\n/** Durable user-message part. Origin is display provenance, never an authorization grant. */\nexport interface AgentContextPart extends AgentContextEntryInput {\n readonly type: \"context\"\n}\n\nexport const MAX_AGENT_CONTEXT_ENTRIES = 12\nexport const MAX_AGENT_APP_STATE_ENTRY_BYTES = 16 * 1024\nexport const MAX_AGENT_APP_STATE_TOTAL_BYTES = 64 * 1024\n\n/** Typed constructors for context values shared by custom apps and agent clients. */\nexport const agentContext = {\n object<const TObjectTypeId extends string>(\n objectType: { readonly id: TObjectTypeId },\n primaryId: string\n ) {\n return {\n kind: \"object\" as const,\n ref: { objectTypeId: objectType.id, primaryId },\n }\n },\n\n appState<const TValue extends JsonValue>(\n id: string,\n input: {\n readonly label: string\n readonly description: string\n readonly value: TValue\n }\n ) {\n return { kind: \"app-state\" as const, id, ...input }\n },\n}\n\n/** Stable identity shared by core deduplication and context-aware clients. */\nexport function agentContextIdentity(context: AgentContextInput): string {\n return context.kind === \"object\"\n ? `object:${encodeURIComponent(context.ref.objectTypeId)}:${encodeURIComponent(context.ref.primaryId)}`\n : `app-state:${encodeURIComponent(context.id)}`\n}\n\n/** Stable semantic key for client-side comparisons. */\nexport function agentContextFingerprint(context: AgentContextInput): string {\n return stableJsonStringify(context)\n}\n\n/**\n * Validate transport-independent context rules and clone mutable app state before it can become\n * durable. Object existence and visibility are resolved separately because they require a runtime.\n */\nexport function normalizeAgentContextEntries(\n input: readonly AgentContextEntryInput[] | undefined\n): readonly AgentContextEntryInput[] {\n if (input === undefined) return []\n if (!Array.isArray(input)) invalidContext(\"context must be an array\")\n if (input.length > MAX_AGENT_CONTEXT_ENTRIES) {\n invalidContext(`context cannot contain more than ${MAX_AGENT_CONTEXT_ENTRIES} entries`)\n }\n\n const entries: AgentContextEntryInput[] = []\n const byIdentity = new Map<string, string>()\n let totalAppStateBytes = 0\n\n for (const [index, rawEntry] of input.entries()) {\n const entry = normalizeEntry(rawEntry, index)\n const identity = agentContextIdentity(entry.context)\n const serialized = stableJsonStringify(entry)\n const existing = byIdentity.get(identity)\n\n if (existing !== undefined) {\n if (existing === serialized) continue\n invalidContext(`context contains conflicting entries for '${identity}'`)\n }\n\n if (entry.context.kind === \"app-state\") {\n const bytes = utf8ByteLength(serialized)\n if (bytes > MAX_AGENT_APP_STATE_ENTRY_BYTES) {\n invalidContext(\n `context entry '${identity}' exceeds the ${MAX_AGENT_APP_STATE_ENTRY_BYTES}-byte limit`\n )\n }\n totalAppStateBytes += bytes\n if (totalAppStateBytes > MAX_AGENT_APP_STATE_TOTAL_BYTES) {\n invalidContext(\n `app-state context exceeds the ${MAX_AGENT_APP_STATE_TOTAL_BYTES}-byte message limit`\n )\n }\n }\n\n byIdentity.set(identity, serialized)\n entries.push(entry)\n }\n\n return entries\n}\n\nfunction normalizeEntry(rawEntry: unknown, index: number): AgentContextEntryInput {\n if (!isRecord(rawEntry)) invalidContext(`context[${index}] must be an object`)\n if (rawEntry.origin !== \"ambient\" && rawEntry.origin !== \"explicit\") {\n invalidContext(`context[${index}].origin must be 'ambient' or 'explicit'`)\n }\n if (!isRecord(rawEntry.context)) invalidContext(`context[${index}].context must be an object`)\n\n const context = rawEntry.context\n if (context.kind === \"object\") {\n if (!isRecord(context.ref)) invalidContext(`context[${index}].context.ref must be an object`)\n const objectTypeId = requireNonEmptyString(\n context.ref.objectTypeId,\n `context[${index}].context.ref.objectTypeId`\n )\n const primaryId = requireNonEmptyString(\n context.ref.primaryId,\n `context[${index}].context.ref.primaryId`\n )\n return {\n context: { kind: \"object\", ref: { objectTypeId, primaryId } },\n origin: rawEntry.origin,\n }\n }\n\n if (context.kind === \"app-state\") {\n const id = requireNonEmptyString(context.id, `context[${index}].context.id`)\n const label = requireNonEmptyString(context.label, `context[${index}].context.label`)\n const description = requireNonEmptyString(\n context.description,\n `context[${index}].context.description`\n )\n const reason = getInvalidJsonValueReason(context.value, `context[${index}].context.value`)\n if (reason) {\n invalidContext(`context[${index}].context.value must be a JSON value; ${reason}`)\n }\n return {\n context: {\n kind: \"app-state\",\n id,\n label,\n description,\n value: cloneJsonValue(context.value as JsonValue),\n },\n origin: rawEntry.origin,\n }\n }\n\n invalidContext(`context[${index}].context.kind must be 'object' or 'app-state'`)\n}\n\nfunction requireNonEmptyString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n invalidContext(`${label} must be a non-empty string`)\n }\n return value\n}\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).byteLength\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction invalidContext(message: string): never {\n throw new AgentRequestError(\"invalid_context\", `[Sixb] Invalid agent context: ${message}.`)\n}\n"
|
|
7
|
-
],
|
|
8
|
-
"mappings": ";;;;;;;;AAIO,MAAM,6BAA6B,MAAM;AAAA,EACrC,OAAe;AAC1B;AAAA;AAOO,MAAM,6BAA6B,MAAM;AAAA,EACrC,OAAe;AAC1B;AAAA;AAGO,MAAM,uCAAuC,MAAM;AAAA,EAI7C;AAAA,EACA;AAAA,EAJF,OAAO;AAAA,EAEhB,WAAW,CACA,UACA,QACT,SACA;AAAA,IACA,MAAM,sBA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
"version": 3,
|
|
3
|
-
"sources": ["../src/agents/streams.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import type { Broker, BrokerStreamDefinition } from \"../broker\"\nimport { parseSixbFailure } from \"../errors/internal\"\nimport type { SixbFailure } from \"../errors/types\"\nimport { isJsonValue, isPlainRecord, type JsonValue } from \"../json\"\nimport {\n AGENT_RUN_FAILURE_CODES,\n type AgentContextCheckpointReason,\n type AgentRunFailureCode,\n type AgentRunRecord,\n type ConversationAgentRunRecord,\n} from \"../storage/agents/types\"\n\nexport const AGENT_RUN_STREAM_SCHEMA_VERSION = 1 as const\nexport const DEFAULT_AGENT_RUN_STREAM_RETENTION = {\n maxAgeMs: 2 * 60 * 60 * 1000, // 2 hours\n maxRecords: 5_000,\n} as const\n\nexport const AGENT_ACTIVITY_STREAM_SCHEMA_VERSION = 1 as const\nexport const AGENT_ACTIVITY_STREAM_ID = \"agents.activity\" as const\nexport const DEFAULT_AGENT_ACTIVITY_STREAM_RETENTION = {\n maxAgeMs: 24 * 60 * 60 * 1000, // 24 hours\n maxRecords: 10_000,\n} as const\n\nexport interface AgentRunActivityEvent {\n readonly schemaVersion: typeof AGENT_ACTIVITY_STREAM_SCHEMA_VERSION\n readonly type: \"agent.run.activity\"\n readonly projectId: string\n readonly runId: string\n readonly threadId: string\n readonly status: AgentRunRecord[\"status\"]\n readonly attempt: number\n readonly occurredAt: string\n}\n\nexport function agentActivityStreamDefinition(): BrokerStreamDefinition {\n return {\n id: AGENT_ACTIVITY_STREAM_ID,\n retention: DEFAULT_AGENT_ACTIVITY_STREAM_RETENTION,\n }\n}\n\nexport function agentRunActivityEvent(\n run: ConversationAgentRunRecord,\n occurredAt: Date = new Date()\n): AgentRunActivityEvent {\n return {\n schemaVersion: AGENT_ACTIVITY_STREAM_SCHEMA_VERSION,\n type: \"agent.run.activity\",\n projectId: run.projectId,\n runId: run.id,\n threadId: run.threadId,\n status: run.status,\n attempt: run.attempt,\n occurredAt: occurredAt.toISOString(),\n }\n}\n\nexport function isAgentRunActivityEvent(value: unknown): value is AgentRunActivityEvent {\n return (\n isPlainRecord(value) &&\n value.schemaVersion === AGENT_ACTIVITY_STREAM_SCHEMA_VERSION &&\n value.type === \"agent.run.activity\" &&\n typeof value.projectId === \"string\" &&\n typeof value.runId === \"string\" &&\n typeof value.threadId === \"string\" &&\n isAgentRunStatus(value.status) &&\n typeof value.attempt === \"number\" &&\n Number.isFinite(value.attempt) &&\n typeof value.occurredAt === \"string\"\n )\n}\n\nexport async function publishAgentRunActivity(\n broker: Broker,\n run: ConversationAgentRunRecord\n): Promise<void> {\n const event = agentRunActivityEvent(run)\n await broker.ensureStream({\n projectId: run.projectId,\n stream: agentActivityStreamDefinition(),\n })\n await broker.append({\n projectId: run.projectId,\n streamId: AGENT_ACTIVITY_STREAM_ID,\n records: [\n {\n name: event.type,\n key: event.threadId,\n // The event is composed only of validated JSON primitives.\n payload: event as unknown as JsonValue,\n idempotencyKey: `${event.runId}:${event.attempt}:${event.status}`,\n },\n ],\n })\n}\n\nexport type AgentRunStreamId = `agents.runs.${string}`\n\nexport function agentRunStreamId(runId: string): AgentRunStreamId {\n return `agents.runs.${runId}`\n}\n\nexport function agentRunStreamDefinition(runId: string): BrokerStreamDefinition {\n return {\n id: agentRunStreamId(runId),\n retention: DEFAULT_AGENT_RUN_STREAM_RETENTION,\n }\n}\n\ntype AgentRunStreamEventBase = {\n readonly schemaVersion: typeof AGENT_RUN_STREAM_SCHEMA_VERSION\n readonly projectId: string\n readonly runId: string\n readonly attempt: number\n readonly occurredAt: string\n} & (\n | {\n readonly threadId: string\n readonly parentRunId?: never\n }\n | {\n readonly parentRunId: string\n readonly threadId?: never\n }\n)\n\n// ── Control stream (worker-inbound) ─────────────────────────────────────────────────────────────\n//\n// A per-run channel the API layer publishes to and the worker subscribes to — the reverse direction\n// of the event stream above. It carries only a cancel signal, and is addressed by `runId` (not a run\n// record), so a cancel works even before the worker has reserved the run. Kept separate from the\n// event stream so control records never reach the browser client.\n\nexport type AgentRunControlStreamId = `agents.runs.${string}.control`\n\nexport function agentRunControlStreamId(runId: string): AgentRunControlStreamId {\n return `agents.runs.${runId}.control`\n}\n\n/** The only control record: a request to stop the run. */\nexport const AGENT_RUN_CANCEL_RECORD = \"agent.run.cancel\"\n\n// A cancel only needs to outlive the queue wait plus one turn, so retention is short and tiny.\nconst AGENT_RUN_CONTROL_RETENTION = { maxAgeMs: 30 * 60 * 1000, maxRecords: 16 } as const\n\nexport function agentRunControlStreamDefinition(runId: string): BrokerStreamDefinition {\n return { id: agentRunControlStreamId(runId), retention: AGENT_RUN_CONTROL_RETENTION }\n}\n\n/**\n * Signal a run to stop. Publishing is addressed by `runId`, so it works whether the run is queued,\n * reserved, or being drained — the worker picks the record up when it subscribes.\n */\nexport async function publishAgentRunCancel(\n broker: Broker,\n params: { readonly projectId: string; readonly runId: string }\n): Promise<void> {\n await broker.ensureStream({\n projectId: params.projectId,\n stream: agentRunControlStreamDefinition(params.runId),\n })\n await broker.append({\n projectId: params.projectId,\n streamId: agentRunControlStreamId(params.runId),\n records: [\n {\n name: AGENT_RUN_CANCEL_RECORD,\n key: params.runId,\n payload: { runId: params.runId },\n idempotencyKey: `${params.runId}:cancel`,\n },\n ],\n })\n}\n\n/**\n * Watch a run's control stream and invoke `onCancel` when a cancel arrives. Reads from `earliest` so\n * a cancel published before the worker subscribed (a run stopped while still queued) is still seen.\n * Returns the unsubscribe handle.\n */\nexport async function subscribeAgentRunCancel(\n broker: Broker,\n params: { readonly projectId: string; readonly runId: string },\n onCancel: () => void\n): Promise<() => void> {\n await broker.ensureStream({\n projectId: params.projectId,\n stream: agentRunControlStreamDefinition(params.runId),\n })\n return broker.subscribe(\n {\n projectId: params.projectId,\n streamId: agentRunControlStreamId(params.runId),\n from: \"earliest\",\n names: [AGENT_RUN_CANCEL_RECORD],\n },\n () => onCancel()\n )\n}\n\n/** Exact portable failure exposed by a terminal Agent run stream event. */\nexport type AgentRunFailure = SixbFailure<AgentRunFailureCode>\n\nexport const AGENT_COMPACTION_FAILURE_CODES = [\n \"context_limit_exceeded\",\n \"summary_failed\",\n \"checkpoint_failed\",\n] as const\nexport type AgentCompactionFailureCode = (typeof AGENT_COMPACTION_FAILURE_CODES)[number]\n\nexport type AgentRunStreamEvent =\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.run.started\"\n readonly modelId?: string\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.compaction.started\"\n readonly reason: AgentContextCheckpointReason\n readonly estimatedInputTokensBefore: number\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.compaction.completed\"\n readonly reason: AgentContextCheckpointReason\n readonly checkpointId: string\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.compaction.failed\"\n readonly reason: AgentContextCheckpointReason\n readonly errorCode: AgentCompactionFailureCode\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.ui.chunk\"\n readonly chunkIndex: number\n readonly chunk: JsonValue\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.message.finalized\"\n readonly messageId: string\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.run.finished\"\n readonly status: \"succeeded\" | \"failed\" | \"cancelled\"\n readonly finishReason?: string\n readonly error?: AgentRunFailure\n })\n\nexport type AgentRunFinishedEvent = Extract<AgentRunStreamEvent, { type: \"agent.run.finished\" }>\n\n// ── Record construction ──────────────────────────────────────────────────────────────────────────\n//\n// The wire format of run stream records — event shape, record name/key, and the idempotency-key\n// vocabulary — is owned here so every producer (the worker's stream sink, the server's queued\n// cancellation) shares one definition and cannot drift.\n\n/** Build the terminal stream event for a finished run. Throws if the run is not terminal. */\nexport function agentRunFinishedEvent(\n run: AgentRunRecord,\n occurredAt: Date = new Date()\n): AgentRunFinishedEvent {\n if (run.status === \"queued\" || run.status === \"running\") {\n throw new Error(\n `[Sixb] Agent run '${run.id}' is not terminal (status '${run.status}'), so it has no finished event.`\n )\n }\n return {\n ...agentRunStreamEventBase(run, occurredAt),\n type: \"agent.run.finished\",\n status: run.status,\n ...(run.finishReason === undefined ? {} : { finishReason: run.finishReason }),\n ...(run.error === undefined ? {} : { error: run.error }),\n }\n}\n\n/** Shared lineage for stream records emitted by conversational and headless runs. */\nexport function agentRunStreamEventBase(\n run: AgentRunRecord,\n occurredAt: Date = new Date()\n): AgentRunStreamEventBase {\n const common = {\n schemaVersion: AGENT_RUN_STREAM_SCHEMA_VERSION,\n projectId: run.projectId,\n runId: run.id,\n attempt: run.attempt,\n occurredAt: occurredAt.toISOString(),\n }\n return run.kind === \"conversation\"\n ? { ...common, threadId: run.threadId }\n : { ...common, parentRunId: run.parentRunId }\n}\n\n/** Validate an Agent stream payload using the same contract its producers use. */\nexport function isAgentRunStreamEvent(value: unknown): value is AgentRunStreamEvent {\n if (\n !isPlainRecord(value) ||\n value.schemaVersion !== AGENT_RUN_STREAM_SCHEMA_VERSION ||\n typeof value.projectId !== \"string\" ||\n typeof value.runId !== \"string\" ||\n typeof value.attempt !== \"number\" ||\n !Number.isFinite(value.attempt) ||\n typeof value.occurredAt !== \"string\" ||\n typeof value.type !== \"string\"\n ) {\n return false\n }\n const hasConversationLineage =\n typeof value.threadId === \"string\" && value.parentRunId === undefined\n const hasSubagentLineage = typeof value.parentRunId === \"string\" && value.threadId === undefined\n if (!hasConversationLineage && !hasSubagentLineage) return false\n\n switch (value.type) {\n case \"agent.run.started\":\n return value.modelId === undefined || typeof value.modelId === \"string\"\n case \"agent.compaction.started\":\n return (\n isAgentContextCheckpointReason(value.reason) &&\n isTokenEstimate(value.estimatedInputTokensBefore)\n )\n case \"agent.compaction.completed\":\n return (\n isAgentContextCheckpointReason(value.reason) &&\n typeof value.checkpointId === \"string\" &&\n isTokenEstimate(value.estimatedInputTokensBefore) &&\n isTokenEstimate(value.estimatedInputTokensAfter)\n )\n case \"agent.compaction.failed\":\n return (\n isAgentContextCheckpointReason(value.reason) &&\n AGENT_COMPACTION_FAILURE_CODES.includes(value.errorCode as AgentCompactionFailureCode)\n )\n case \"agent.ui.chunk\":\n return (\n Number.isInteger(value.chunkIndex) &&\n Object.hasOwn(value, \"chunk\") &&\n isJsonValue(value.chunk)\n )\n case \"agent.message.finalized\":\n return typeof value.messageId === \"string\"\n case \"agent.run.finished\":\n return (\n isTerminalAgentRunStatus(value.status) &&\n (value.finishReason === undefined || typeof value.finishReason === \"string\") &&\n (value.error === undefined || isAgentRunFailure(value.error))\n )\n default:\n return false\n }\n}\n\nfunction isAgentContextCheckpointReason(value: unknown): value is AgentContextCheckpointReason {\n return value === \"threshold\" || value === \"overflow\"\n}\n\nfunction isTokenEstimate(value: unknown): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0\n}\n\nfunction isTerminalAgentRunStatus(value: unknown): value is \"succeeded\" | \"failed\" | \"cancelled\" {\n return value === \"succeeded\" || value === \"failed\" || value === \"cancelled\"\n}\n\nfunction isAgentRunStatus(value: unknown): value is AgentRunRecord[\"status\"] {\n return value === \"queued\" || value === \"running\" || isTerminalAgentRunStatus(value)\n}\n\nfunction isAgentRunFailure(value: unknown): value is AgentRunFailure {\n if (!isPlainRecord(value)) return false\n try {\n parseSixbFailure(value, AGENT_RUN_FAILURE_CODES)\n return true\n } catch {\n return false\n }\n}\n\n/** Single owner of the idempotency-key vocabulary for agent run stream records. */\nexport function agentRunStreamIdempotencyKey(event: AgentRunStreamEvent): string {\n switch (event.type) {\n case \"agent.run.started\":\n return `${event.runId}:${event.attempt}:started`\n case \"agent.compaction.started\":\n return `${event.runId}:${event.attempt}:compaction:${event.reason}:started`\n case \"agent.compaction.completed\":\n return `${event.runId}:${event.attempt}:compaction:${event.checkpointId}:completed`\n case \"agent.compaction.failed\":\n return `${event.runId}:${event.attempt}:compaction:${event.reason}:failed:${event.errorCode}`\n case \"agent.ui.chunk\":\n return `${event.runId}:${event.attempt}:chunk:${event.chunkIndex}`\n case \"agent.message.finalized\":\n return `${event.runId}:${event.attempt}:message:${event.messageId}:finalized`\n case \"agent.run.finished\":\n return `${event.runId}:${event.attempt}:finished:${event.status}`\n }\n}\n\n/**\n * Ensure the run's stream and append its terminal record — mirrors {@link publishAgentRunCancel}.\n * Used where a terminal transition happens outside the worker (e.g. cancelling a queued run).\n */\nexport async function publishAgentRunFinished(broker: Broker, run: AgentRunRecord): Promise<void> {\n const event = agentRunFinishedEvent(run)\n await broker.ensureStream({\n projectId: run.projectId,\n stream: agentRunStreamDefinition(run.id),\n })\n await broker.append({\n projectId: run.projectId,\n streamId: agentRunStreamId(run.id),\n records: [\n {\n name: event.type,\n key: event.runId,\n // The event is built from JSON primitives only, so the round-trip is a safe narrowing.\n payload: JSON.parse(JSON.stringify(event)) as JsonValue,\n idempotencyKey: agentRunStreamIdempotencyKey(event),\n },\n ],\n })\n if (run.kind === \"conversation\") await publishAgentRunActivity(broker, run)\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";;;;;;;;;;;;;AAYO,IAAM,kCAAkC;AACxC,IAAM,qCAAqC;AAAA,EAChD,UAAU,IAAI,KAAK,KAAK;AAAA,EACxB,YAAY;AACd;AAEO,IAAM,uCAAuC;AAC7C,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;AAAA,EACrD,UAAU,KAAK,KAAK,KAAK;AAAA,EACzB,YAAY;AACd;AAaO,SAAS,6BAA6B,GAA2B;AAAA,EACtE,OAAO;AAAA,IACL,IAAI;AAAA,IACJ,WAAW;AAAA,EACb;AAAA;AAGK,SAAS,qBAAqB,CACnC,KACA,aAAmB,IAAI,MACA;AAAA,EACvB,OAAO;AAAA,IACL,eAAe;AAAA,IACf,MAAM;AAAA,IACN,WAAW,IAAI;AAAA,IACf,OAAO,IAAI;AAAA,IACX,UAAU,IAAI;AAAA,IACd,QAAQ,IAAI;AAAA,IACZ,SAAS,IAAI;AAAA,IACb,YAAY,WAAW,YAAY;AAAA,EACrC;AAAA;AAGK,SAAS,uBAAuB,CAAC,OAAgD;AAAA,EACtF,OACE,cAAc,KAAK,KACnB,MAA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M,SAAS,MAAM,oBAAoB,MAAM;AAAA;AAAA;AAQ/D,eAAsB,uBAAuB,CAAC,QAAgB,KAAoC;AAAA,EAChG,MAAM,QAAQ,sBAAsB,GAAG;AAAA,EACvC,MAAM,OAAO,aAAa;AAAA,IACxB,WAAW,IAAI;AAAA,IACf,QAAQ,yBAAyB,IAAI,EAAE;AAAA,EACzC,CAAC;AAAA,EACD,MAAM,OAAO,OAAO;AAAA,IAClB,WAAW,IAAI;AAAA,IACf,UAAU,iBAAiB,IAAI,EAAE;AAAA,IACjC,SAAS;AAAA,MACP;AAAA,QACE,MAAM,MAAM;AAAA,QACZ,KAAK,MAAM;AAAA,QAEX,SAAS,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAAA,QACzC,gBAAgB,6BAA6B,KAAK;AAAA,MACpD;AAAA,IACF;AAAA,EACF,CAAC;AAAA,EACD,IAAI,IAAI,SAAS;AAAA,IAAgB,MAAM,wBAAwB,QAAQ,GAAG;AAAA;",
|
|
8
|
-
"debugId": "01E889A4551AE38464756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/projections/capability.ts", "../src/projections/run-dispatch.ts", "../src/projections/run-id.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import type { ProjectionRegistry } from \"./registry\"\nimport type { ProjectionDispatchDescriptor } from \"./types\"\n\nconst projectionRegistryKey: unique symbol = Symbol(\"sixb.projectionRegistry\")\n\ninterface ProjectionRegistryOwner {\n readonly [projectionRegistryKey]?: ProjectionRegistry\n}\n\nexport function registerProjectionRegistry(owner: object, registry: ProjectionRegistry): void {\n const registered = (owner as ProjectionRegistryOwner)[projectionRegistryKey]\n if (registered && registered !== registry) {\n throw new Error(\"[Sixb] Projection registry is already registered for this owner.\")\n }\n Object.defineProperty(owner, projectionRegistryKey, {\n configurable: false,\n enumerable: false,\n value: registry,\n writable: false,\n })\n}\n\nexport function getProjectionRegistry(owner: object): ProjectionRegistry {\n const registry = (owner as ProjectionRegistryOwner)[projectionRegistryKey]\n if (registry) return registry\n throw new Error(\"[Sixb] Projection registry is not registered for this runtime.\")\n}\n\nexport function getProjectionDispatchDescriptors(\n owner: object\n): readonly ProjectionDispatchDescriptor[] {\n return getProjectionRegistry(owner).getDispatchDescriptors()\n}\n\nexport function shareProjectionRegistry(source: object, target: object): void {\n registerProjectionRegistry(target, getProjectionRegistry(source))\n}\n",
|
|
6
|
-
"import { randomUUID } from \"node:crypto\"\nimport { reportRunFailure } from \"../error-reporting/capability\"\nimport { createSixbError, toSixbFailure } from \"../errors/internal\"\nimport type { SixbFailure } from \"../errors/types\"\nimport type { RunDispatcher } from \"../execution/dispatch\"\nimport { createPrimitiveExecutionRecord } from \"../execution/durable\"\nimport type { DatasetProducer, LakeStorage } from \"../lake-storage\"\nimport type { Queues } from \"../queues\"\nimport type { SixbDefinitions } from \"../runtime/definitions\"\nimport type { ExecutionRecord, ProjectionRunRecord, Storage } from \"../storage\"\nimport { ProjectionRunError } from \"../storage\"\nimport { findPrimitiveRunExecution } from \"../storage/executions/run-link\"\nimport {\n assertProjectionRunDurableExecution,\n assertProjectionRunIdentityMatches,\n} from \"../storage/projection-runs/provider\"\nimport { getProjectionRegistry } from \"./capability\"\nimport { ProjectionValidationError } from \"./errors\"\nimport { createProjectionRunId } from \"./run-id\"\nimport {\n PROJECTION_RUN_FAILURE_CODES,\n type ProjectionDefinition,\n type ProjectionRunFailureCode,\n} from \"./types\"\n\n/** Target maximum mapped points per telemetry commit; a single-property projection reads 500 rows. */\nexport const PROJECTION_TELEMETRY_BATCH_SIZE = 500\n\nexport interface ProjectionRunDispatchInput {\n readonly projectionId: string\n readonly datasetVersion: {\n readonly datasetId: string\n readonly versionId: string\n readonly createdAt: string\n }\n readonly metadata?: Readonly<Record<string, string>>\n}\n\nexport interface ProjectionRunDispatchResult {\n readonly projectionId: string\n readonly runId: string\n readonly queuedAt: string\n readonly jobId?: string\n readonly created: boolean\n}\n\nexport type ProjectionRunDispatchPort = RunDispatcher<\n ProjectionRunDispatchInput,\n ProjectionRunDispatchResult\n>\n\nexport interface ProjectionRunDispatcherDependencies {\n readonly id: string\n readonly definitions: Pick<SixbDefinitions, \"projections\">\n readonly lakeStorage: Pick<LakeStorage, \"getVersion\">\n readonly storage: Storage\n readonly queues: Pick<Queues, \"projections\">\n}\n\ntype PersistedProjectionRun =\n | { readonly publish: false; readonly run: ProjectionRunRecord }\n | {\n readonly publish: true\n readonly run: ProjectionRunRecord\n readonly queuedAt: Date\n readonly created: boolean\n }\n\n/** Core-owned durable dispatch boundary for immutable dataset-version materialization. */\nexport class ProjectionRunDispatcher implements ProjectionRunDispatchPort {\n constructor(private readonly dependencies: ProjectionRunDispatcherDependencies) {}\n\n async dispatch(input: ProjectionRunDispatchInput): Promise<ProjectionRunDispatchResult> {\n assertDispatchInput(input)\n const registry = getProjectionRegistry(this.dependencies)\n const descriptor = registry.resolveDispatch(input.projectionId)\n if (descriptor.datasetId !== input.datasetVersion.datasetId) {\n throw new ProjectionValidationError(\n `[Sixb] Projection '${input.projectionId}' consumes dataset '${descriptor.datasetId}', not '${input.datasetVersion.datasetId}'.`\n )\n }\n const projection = this.dependencies.definitions.projections.getById(input.projectionId)\n if (!projection) {\n throw new ProjectionValidationError(`[Sixb] Unknown projection '${input.projectionId}'.`)\n }\n const version = await this.dependencies.lakeStorage.getVersion(\n input.datasetVersion.datasetId,\n input.datasetVersion.versionId\n )\n if (!version || version.createdAt.toISOString() !== input.datasetVersion.createdAt) {\n throw new ProjectionValidationError(\n `[Sixb] Dataset '${input.datasetVersion.datasetId}' version '${input.datasetVersion.versionId}' does not match its immutable metadata.`\n )\n }\n if (version.mode === \"schema\") {\n throw new ProjectionValidationError(\n `[Sixb] Projection '${input.projectionId}' cannot materialize a schema-only dataset version.`\n )\n }\n\n const { datasetId: _datasetId, ...semanticIdentity } = descriptor\n const identity = {\n ...semanticIdentity,\n datasetVersion: structuredClone(input.datasetVersion),\n }\n const runId = createProjectionRunId(this.dependencies.id, identity)\n const projectionRuns = requireProjectionRunStorage(this.dependencies.storage)\n const existing = await projectionRuns.getById({ projectId: this.dependencies.id, id: runId })\n const persisted = existing\n ? await reuseProjectionRun(this.dependencies, existing, identity)\n : await persistProjectionRun({\n dependencies: this.dependencies,\n runId,\n identity,\n projection,\n producerExecution: await resolveProducerExecution(\n this.dependencies.storage,\n this.dependencies.id,\n version.producer\n ),\n })\n\n if (!persisted.publish) return existingResult(persisted.run)\n return publishProjectionRun(this.dependencies, input.metadata, persisted)\n }\n}\n\nasync function persistProjectionRun(input: {\n readonly dependencies: ProjectionRunDispatcherDependencies\n readonly runId: string\n readonly identity: ProjectionRunRecord[\"identity\"]\n readonly projection: ProjectionDefinition\n readonly producerExecution: ExecutionRecord | null\n}): Promise<PersistedProjectionRun> {\n const execution = createPrimitiveExecutionRecord({\n id: `exec_${randomUUID()}`,\n primitive: { kind: \"projection\", id: input.identity.projectionId, runId: input.runId },\n origin: {\n type: \"automatic\",\n projectId: input.dependencies.id,\n source: {\n type: \"datasetVersion\",\n datasetId: input.identity.datasetVersion.datasetId,\n versionId: input.identity.datasetVersion.versionId,\n },\n correlationId: input.producerExecution?.correlationId ?? input.runId,\n ...(input.producerExecution?.requestedBy === undefined\n ? {}\n : { requestedBy: input.producerExecution.requestedBy }),\n },\n })\n const queuedAt = new Date()\n\n try {\n return await input.dependencies.storage.transaction(\n async (tx): Promise<PersistedProjectionRun> => {\n const projectionRuns = requireProjectionRunStorage(tx)\n const raced = await projectionRuns.getById({\n projectId: input.dependencies.id,\n id: input.runId,\n })\n if (raced) {\n await assertExistingRun(tx, raced, input.identity)\n return { publish: false, run: raced }\n }\n await tx.executions.create(execution)\n const run = await queueProjectionRun(projectionRuns, {\n id: input.runId,\n projectId: input.dependencies.id,\n executionId: execution.id,\n identity: input.identity,\n projection: input.projection,\n queuedAt,\n })\n return { publish: true, run, queuedAt, created: true }\n },\n { isolation: \"serializable\" }\n )\n } catch (error) {\n if (!(error instanceof ProjectionRunError)) throw error\n const raced = await requireProjectionRunStorage(input.dependencies.storage).getById({\n projectId: input.dependencies.id,\n id: input.runId,\n })\n if (!raced) throw error\n await assertExistingRun(input.dependencies.storage, raced, input.identity)\n return { publish: false, run: raced }\n }\n}\n\nasync function reuseProjectionRun(\n dependencies: ProjectionRunDispatcherDependencies,\n existing: ProjectionRunRecord,\n identity: ProjectionRunRecord[\"identity\"]\n): Promise<PersistedProjectionRun> {\n await assertExistingRun(dependencies.storage, existing, identity)\n if (\n existing.status !== \"failed\" ||\n existing.error?.code !== \"queue.enqueue_failed\" ||\n !existing.error.retryable\n ) {\n return { publish: false, run: existing }\n }\n const queuedAt = new Date()\n const projectionRuns = requireProjectionRunStorage(dependencies.storage)\n try {\n const run = await requeueProjectionRun(projectionRuns, existing, queuedAt)\n return { publish: true, run, queuedAt, created: false }\n } catch (error) {\n if (!(error instanceof ProjectionRunError)) throw error\n const raced = await projectionRuns.getById({ projectId: existing.projectId, id: existing.id })\n if (\n !raced ||\n (raced.status === \"failed\" &&\n raced.error?.code === \"queue.enqueue_failed\" &&\n raced.error.retryable)\n ) {\n throw error\n }\n await assertExistingRun(dependencies.storage, raced, identity)\n return { publish: false, run: raced }\n }\n}\n\nasync function publishProjectionRun(\n dependencies: ProjectionRunDispatcherDependencies,\n metadata: Readonly<Record<string, string>> | undefined,\n persisted: Extract<PersistedProjectionRun, { readonly publish: true }>\n): Promise<ProjectionRunDispatchResult> {\n try {\n const [job] = await dependencies.queues.projections.enqueue({\n projectId: dependencies.id,\n jobs: [\n {\n id: persisted.run.id,\n type: \"projection.run.requested\",\n payload: { runId: persisted.run.id },\n ...(metadata === undefined ? {} : { metadata }),\n },\n ],\n })\n return {\n projectionId: persisted.run.identity.projectionId,\n runId: persisted.run.id,\n queuedAt: persisted.queuedAt.toISOString(),\n ...(job?.id ? { jobId: job.id } : {}),\n created: persisted.created,\n }\n } catch (error) {\n const failedAt = new Date()\n const failure = toEnqueueFailure(error, persisted.run, failedAt)\n const failed = await requireProjectionRunStorage(dependencies.storage).failEnqueue({\n projectId: dependencies.id,\n id: persisted.run.id,\n finishedAt: failedAt,\n error: failure,\n })\n reportRunFailure(dependencies, error, {\n projectId: dependencies.id,\n runKind: \"projection\",\n run: {\n runId: failed.id,\n projectionId: failed.identity.projectionId,\n projectionKind: failed.identity.projectionKind,\n },\n failure,\n })\n throw error\n }\n}\n\nasync function assertExistingRun(\n storage: Storage,\n run: ProjectionRunRecord,\n identity: ProjectionRunRecord[\"identity\"]\n): Promise<void> {\n assertProjectionRunIdentityMatches(run, identity)\n await assertProjectionRunDurableExecution({\n executions: storage.executions,\n projectId: run.projectId,\n executionId: run.executionId,\n runId: run.id,\n projectionId: run.identity.projectionId,\n datasetId: run.identity.datasetVersion.datasetId,\n datasetVersionId: run.identity.datasetVersion.versionId,\n })\n}\n\nasync function resolveProducerExecution(\n storage: Storage,\n projectId: string,\n producer: DatasetProducer | undefined\n): Promise<ExecutionRecord | null> {\n if (producer?.kind === \"ingest\") {\n return producer.id ? storage.executions.getById({ projectId, id: producer.id }) : null\n }\n if (!producer?.runId) return null\n if (producer.kind === \"sync\") {\n const run = await storage.syncRuns?.getById({ projectId, id: producer.runId })\n if (!run) return null\n assertProducerId(producer, run.syncId)\n return requireProducerExecution({\n executions: storage.executions,\n projectId,\n executionId: run.executionId,\n primitive: { kind: \"sync\", id: run.syncId, runId: run.id },\n })\n }\n\n const run = await storage.pipelineRuns?.getById({ projectId, id: producer.runId })\n if (!run) return null\n assertProducerId(producer, run.pipelineId)\n return requireProducerExecution({\n executions: storage.executions,\n projectId,\n executionId: run.executionId,\n primitive: { kind: \"pipeline\", id: run.pipelineId, runId: run.id },\n })\n}\n\nasync function requireProducerExecution(input: {\n readonly executions: Storage[\"executions\"]\n readonly projectId: string\n readonly executionId: string\n readonly primitive:\n | { readonly kind: \"sync\"; readonly id: string; readonly runId: string }\n | { readonly kind: \"pipeline\"; readonly id: string; readonly runId: string }\n}): Promise<ExecutionRecord> {\n const execution = await findPrimitiveRunExecution({\n executions: input.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n primitive: input.primitive,\n sourceTypes: [\"execution\", \"schedule\", \"event\"],\n })\n if (execution) return execution\n throw new ProjectionValidationError(\n `[Sixb] Dataset producer run '${input.primitive.runId}' references an invalid execution.`\n )\n}\n\nfunction assertProducerId(producer: DatasetProducer, runOwnerId: string): void {\n if (producer.id === undefined || producer.id === runOwnerId) return\n throw new ProjectionValidationError(\n `[Sixb] Dataset producer '${producer.kind}:${producer.id}' does not match run '${producer.runId}'.`\n )\n}\n\nfunction requireProjectionRunStorage(storage: Storage): NonNullable<Storage[\"projectionRuns\"]> {\n if (storage.projectionRuns) return storage.projectionRuns\n throw new ProjectionValidationError(\"[Sixb] Projection run storage is not configured.\")\n}\n\nfunction queueProjectionRun(\n storage: NonNullable<Storage[\"projectionRuns\"]>,\n input: {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly identity: ProjectionRunRecord[\"identity\"]\n readonly projection: ProjectionDefinition\n readonly queuedAt: Date\n }\n): Promise<ProjectionRunRecord> {\n const common = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n queuedAt: input.queuedAt,\n }\n switch (input.projection._tag) {\n case \"ObjectProjectionDefinition\":\n if (input.identity.projectionKind !== \"object\") {\n throw invalidProjectionDefinition(input.id)\n }\n return storage.queue({\n ...common,\n identity: input.identity,\n target: { objectTypeId: input.projection.objectTypeId },\n })\n case \"LinkProjectionDefinition\":\n if (input.identity.projectionKind !== \"link\") {\n throw invalidProjectionDefinition(input.id)\n }\n return storage.queue({\n ...common,\n identity: input.identity,\n target: {\n sourceObjectTypeId: input.projection.sourceObjectTypeId,\n targetObjectTypeId: input.projection.targetObjectTypeId,\n },\n })\n case \"TelemetryProjectionDefinition\":\n if (input.identity.projectionKind !== \"telemetry\") {\n throw invalidProjectionDefinition(input.id)\n }\n return storage.queue({\n ...common,\n identity: input.identity,\n target: { objectTypeId: input.projection.objectTypeId },\n fixedBatchSize: telemetryProjectionBatchRowCount(input.projection),\n })\n }\n}\n\nfunction telemetryProjectionBatchRowCount(\n projection: Extract<ProjectionDefinition, { readonly _tag: \"TelemetryProjectionDefinition\" }>\n): number {\n const mappedPropertyCount = Object.keys(projection.properties).length\n if (mappedPropertyCount === 0) throw invalidProjectionDefinition(projection.id)\n return Math.max(1, Math.floor(PROJECTION_TELEMETRY_BATCH_SIZE / mappedPropertyCount))\n}\n\nfunction requeueProjectionRun(\n storage: NonNullable<Storage[\"projectionRuns\"]>,\n run: ProjectionRunRecord,\n queuedAt: Date\n): Promise<ProjectionRunRecord> {\n const common = {\n id: run.id,\n projectId: run.projectId,\n executionId: run.executionId,\n queuedAt,\n }\n switch (run.identity.projectionKind) {\n case \"object\": {\n if (!(\"objectTypeId\" in run.target)) throw invalidProjectionDefinition(run.id)\n return storage.queue({ ...common, identity: run.identity, target: run.target })\n }\n case \"link\": {\n if (!(\"sourceObjectTypeId\" in run.target)) throw invalidProjectionDefinition(run.id)\n return storage.queue({ ...common, identity: run.identity, target: run.target })\n }\n case \"telemetry\": {\n if (!(\"objectTypeId\" in run.target) || !run.telemetryCheckpoint) {\n throw invalidProjectionDefinition(run.id)\n }\n return storage.queue({\n ...common,\n identity: run.identity,\n target: run.target,\n fixedBatchSize: run.telemetryCheckpoint.fixedBatchSize,\n })\n }\n }\n}\n\nfunction invalidProjectionDefinition(runId: string): ProjectionValidationError {\n return new ProjectionValidationError(\n `[Sixb] Projection run '${runId}' has inconsistent definition metadata.`\n )\n}\n\nfunction existingResult(run: ProjectionRunRecord): ProjectionRunDispatchResult {\n return {\n projectionId: run.identity.projectionId,\n runId: run.id,\n queuedAt: run.queuedAt.toISOString(),\n created: false,\n }\n}\n\nfunction assertDispatchInput(input: ProjectionRunDispatchInput): void {\n for (const [field, value] of [\n [\"projectionId\", input.projectionId],\n [\"datasetId\", input.datasetVersion.datasetId],\n [\"versionId\", input.datasetVersion.versionId],\n ] as const) {\n if (!value.trim())\n throw new ProjectionValidationError(`[Sixb] Projection ${field} is required.`)\n }\n const timestamp = Date.parse(input.datasetVersion.createdAt)\n if (\n !Number.isFinite(timestamp) ||\n new Date(timestamp).toISOString() !== input.datasetVersion.createdAt\n ) {\n throw new ProjectionValidationError(\"[Sixb] Projection dataset version timestamp is invalid.\")\n }\n}\n\nfunction toEnqueueFailure(\n error: unknown,\n run: ProjectionRunRecord,\n at: Date\n): SixbFailure<ProjectionRunFailureCode> {\n const enqueueError = createSixbError(\n \"queue.enqueue_failed\",\n `[Sixb] Could not enqueue Projection run '${run.id}'.`,\n {\n cause: error,\n details: {\n projectionId: run.identity.projectionId,\n projectionKind: run.identity.projectionKind,\n runId: run.id,\n phase: \"enqueue\",\n },\n }\n )\n return toSixbFailure(enqueueError, { allowedCodes: PROJECTION_RUN_FAILURE_CODES, at })\n}\n",
|
|
7
|
-
"import { sha256Canonical } from \"../materialization/identity\"\nimport type { ProjectionMaterializationIdentity } from \"../materialization/model\"\n\nexport function createProjectionRunId(\n projectId: string,\n identity: ProjectionMaterializationIdentity\n): string {\n return sha256Canonical({\n projectId,\n projectionId: identity.projectionId,\n projectionKind: identity.projectionKind,\n protocol: identity.protocol,\n datasetId: identity.datasetVersion.datasetId,\n versionId: identity.datasetVersion.versionId,\n createdAt: identity.datasetVersion.createdAt,\n ontologyRevision: identity.ontologyRevision,\n projectionRevision: identity.projectionRevision,\n ownershipHash: identity.ownershipHash,\n })\n}\n"
|
|
8
|
-
],
|
|
9
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAM,wBAAuC,OAAO,yBAAyB;AAMtE,SAAS,0BAA0B,CAAC,OAAe,UAAoC;AAAA,EAC5F,MAAM,aAAc,MAAkC;AAAA,EACtD,IAAI,cAAc,eAAe,UAAU;AAAA,IACzC,MAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAAA,EACA,OAAO,eAAe,OAAO,uBAAuB;AAAA,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MAC7B,OAAO,IAAI;AAAA,MACX,OAAO;AAAA,IACT;AAAA,EACF,CACF;AAAA,EACA,OAAO,cAAc,cAAc,EAAE,cAAc,8BAA8B,GAAG,CAAC;AAAA;",
|
|
10
|
-
"debugId": "C0C0C7AA378374DA64756E2164756E21",
|
|
11
|
-
"names": []
|
|
12
|
-
}
|
package/dist/chunk-c15dr03f.js
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import {
|
|
3
|
-
aiLimitSubjectKey
|
|
4
|
-
} from "./chunk-jecn6t54.js";
|
|
5
|
-
import {
|
|
6
|
-
createSixbError
|
|
7
|
-
} from "./chunk-2xns679x.js";
|
|
8
|
-
|
|
9
|
-
// src/storage/ai-limits/enforcement.ts
|
|
10
|
-
function aiLimitSubjectsFromAttribution(requestedBy, requesterGroupIds) {
|
|
11
|
-
const subjects = [
|
|
12
|
-
{ type: "project" },
|
|
13
|
-
...requesterGroupIds.map((id) => ({ type: "group", id }))
|
|
14
|
-
];
|
|
15
|
-
if (requestedBy)
|
|
16
|
-
subjects.push(requestedBy);
|
|
17
|
-
const byKey = new Map(subjects.map((subject) => [aiLimitSubjectKey(subject), subject]));
|
|
18
|
-
return [...byKey.values()].sort((left, right) => aiLimitSubjectKey(left).localeCompare(aiLimitSubjectKey(right)));
|
|
19
|
-
}
|
|
20
|
-
function applicableAiLimitPolicyStatuses(statuses, subjects) {
|
|
21
|
-
const keys = new Set(subjects.map(aiLimitSubjectKey));
|
|
22
|
-
return statuses.filter((status) => keys.has(aiLimitSubjectKey(status.policy.subject)));
|
|
23
|
-
}
|
|
24
|
-
function applicableAiLimitPolicies(policies, subjects) {
|
|
25
|
-
const keys = new Set(subjects.map(aiLimitSubjectKey));
|
|
26
|
-
return policies.filter((policy) => keys.has(aiLimitSubjectKey(policy.subject)));
|
|
27
|
-
}
|
|
28
|
-
function aiUsageLimitExceededError(resetAt) {
|
|
29
|
-
return createSixbError("ai.usage_limit_exceeded", "[Sixb] An applicable AI usage limit has no capacity for this model call.", { details: aiLimitFailureDetails({ resetAt }) });
|
|
30
|
-
}
|
|
31
|
-
function aiUsageLimitUnavailableError(reasons) {
|
|
32
|
-
return createSixbError("ai.usage_limit_unavailable", "[Sixb] An applicable AI usage limit could not be evaluated safely.", { details: aiLimitFailureDetails({ reasons }) });
|
|
33
|
-
}
|
|
34
|
-
function aiLimitFailureDetails(input) {
|
|
35
|
-
return {
|
|
36
|
-
...input.resetAt === undefined ? {} : { resetAt: input.resetAt.toISOString() },
|
|
37
|
-
...input.reasons === undefined ? {} : { reasons: [...input.reasons] }
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export { aiLimitSubjectsFromAttribution, applicableAiLimitPolicyStatuses, applicableAiLimitPolicies, aiUsageLimitExceededError, aiUsageLimitUnavailableError };
|
|
42
|
-
|
|
43
|
-
//# debugId=264BFFFD79C6CA2964756E2164756E21
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/storage/agents/types.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import type { AgentMessage, AgentMessagePart, AgentMessageRole } from \"../../agents/message\"\nimport type { AgentReasoningLevel } from \"../../agents/types\"\nimport type { Principal } from \"../../auth\"\nimport type { FileRef } from \"../../blob-storage\"\nimport type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { JsonValue } from \"../../json\"\nimport type { LanguageModelRef } from \"../../models\"\n\n// ── agent_threads — one conversation with an agent ──────────────────────────────────────────────\n\nexport type AgentThreadStatus = \"active\" | \"archived\"\n\nexport interface AgentThreadRecord {\n readonly id: string\n readonly projectId: string\n /** Who owns/opened the thread. Reuses the canonical auth principal (gains `agent` later for free). */\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly status: AgentThreadStatus\n /** Single-flight anchor: the id of the one run currently allowed to write, or `null` when idle. */\n readonly activeRunId: string | null\n readonly lastMessageAt?: Date\n readonly messageCount: number\n readonly createdAt: Date\n readonly updatedAt: Date\n}\n\nexport interface CreateAgentThreadInput {\n readonly id: string\n readonly projectId: string\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly status?: AgentThreadStatus\n readonly createdAt?: Date\n readonly updatedAt?: Date\n}\n\nexport interface ListAgentThreadsInput {\n readonly projectId: string\n readonly statuses?: readonly AgentThreadStatus[]\n readonly ownerPrincipal?: Principal\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentThreadsResult {\n readonly threads: readonly AgentThreadRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_runs — one loop execution (the worker job; attribution + fencing) ───────────────────\n\n/** Lifecycle shared by every durable agent execution, conversational or workflow-owned. */\nexport type AgentExecutionStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\"\n\nexport type AgentRunStatus = AgentExecutionStatus\nexport type AgentRunKind = \"conversation\" | \"subagent\"\n\n/** Error codes an agent execution can persist and expose through its public contract. */\nexport const AGENT_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"agent.execution_failed\",\n \"ai.usage_limit_exceeded\",\n \"ai.usage_limit_unavailable\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type AgentRunFailureCode = (typeof AGENT_RUN_FAILURE_CODES)[number]\n\n/**\n * Why a run ended — Sixb's provider-independent vocabulary. It includes model-loop reasons plus\n * platform-level endings such as `timeout`, so reads remain typed and exhaustive. `other` and\n * `unknown` preserve terminal state when a provider adds a new reason.\n */\nexport const AGENT_RUN_FINISH_REASONS = [\n \"stop\",\n \"length\",\n \"content-filter\",\n \"tool-calls\",\n \"timeout\",\n \"error\",\n \"other\",\n \"unknown\",\n] as const\n\nexport type AgentRunFinishReason = (typeof AGENT_RUN_FINISH_REASONS)[number]\n\n/**\n * Coerce an external finish-reason string — a DB column or an SDK value — to {@link\n * AgentRunFinishReason}. An unrecognised value becomes `\"unknown\"` rather than being dropped.\n */\nexport function coerceAgentRunFinishReason(\n value: string | null | undefined\n): AgentRunFinishReason | undefined {\n if (value === null || value === undefined) {\n return undefined\n }\n return (AGENT_RUN_FINISH_REASONS as readonly string[]).includes(value)\n ? (value as AgentRunFinishReason)\n : \"unknown\"\n}\n\n/** Stable, user-facing diagnostics emitted by the platform while executing a run. */\nexport const AGENT_RUN_DIAGNOSTIC_CODES = [\n \"output_file_limit_exceeded\",\n \"output_file_too_large\",\n \"output_budget_exhausted\",\n \"output_collection_failed\",\n \"output_file_changed\",\n \"output_storage_failed\",\n] as const\n\n/**\n * Closed on purpose, and the wire is closed with it.\n *\n * Sixb writes these codes and the generated client is what reads them, so an open union would only\n * be honest if the HTTP schema were open too — and that costs the OpenAPI enum, the client's\n * autocompletion, and Atlas's exhaustive `switch`. Sixb owns both ends, so a new code is a minor\n * version bump: cheap here, and a broken `switch` is better than a 500 from `z.enum`.\n */\nexport type AgentRunDiagnosticCode = (typeof AGENT_RUN_DIAGNOSTIC_CODES)[number]\nexport type AgentRunDiagnosticSeverity = \"warning\" | \"error\"\n\nexport interface AgentRunDiagnostic {\n readonly code: AgentRunDiagnosticCode\n readonly severity: AgentRunDiagnosticSeverity\n readonly scope: \"output\"\n /** Relative path inside the run's published output directory, when one file is involved. */\n readonly path?: string\n /** Sanitized, stable copy suitable for display to an end user. */\n readonly message: string\n}\n\n/**\n * Authorization state for the current queue delivery.\n *\n * `queueLeaseExpiresAt` is a persisted projection of `ClaimedQueueJob.leaseExpiresAt`, not an\n * independently managed run lease. It may only be extended from a successful queue lease renewal.\n */\nexport interface AgentRunExecution {\n readonly token: string\n readonly queueLeaseExpiresAt: Date\n}\n\ninterface AgentRunRecordBase {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n /** Durable group memberships snapshotted when the run was admitted. */\n readonly requesterGroupIds: readonly string[]\n readonly status: AgentRunStatus\n readonly modelId?: string\n /** Why the run ended (our own SDK-independent enum). */\n readonly finishReason?: AgentRunFinishReason\n /** Platform diagnostics are transcript annotations, never agent-authored message content. */\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n /** Portable failure snapshot when the run did not succeed. */\n readonly error?: SixbFailure<AgentRunFailureCode>\n /** Execution attempts: `0` while queued, `1` on first start, incremented on redelivery. */\n readonly attempt: number\n readonly execution?: AgentRunExecution\n readonly createdAt: Date\n readonly startedAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface ConversationAgentRunRecord extends AgentRunRecordBase {\n readonly kind: \"conversation\"\n readonly threadId: string\n readonly triggerMessageId: string\n /** Immutable model selection captured at admission. Absent only on runs predating this field. */\n readonly spec?: ConversationAgentRunSpec\n}\n\n/** Immutable, serialisable model selection for one conversational turn. */\nexport interface ConversationAgentRunSpec {\n readonly model: LanguageModelRef\n readonly reasoning?: AgentReasoningLevel\n}\n\n/** Immutable, serialisable child configuration captured before dispatch. */\nexport interface SubagentRunSpec {\n readonly model: LanguageModelRef\n readonly reasoning?: AgentReasoningLevel\n /** Focused task supplied by the parent Agent. */\n readonly task: string\n /** Project tools available when the child was admitted. Runtime tools are injected separately. */\n readonly toolNames: readonly string[]\n readonly maxSteps: number\n}\n\n/** Durable child output returned to its parent by `wait_agent`. */\nexport interface SubagentRunResult {\n readonly text?: string\n readonly files?: readonly FileRef[]\n}\n\nexport interface SubagentRunRecord extends AgentRunRecordBase {\n readonly kind: \"subagent\"\n readonly parentRunId: string\n /** Stable parent-selected key that makes repeated tool execution idempotent. */\n readonly spawnKey: string\n readonly spec: SubagentRunSpec\n readonly result?: SubagentRunResult\n}\n\nexport type AgentRunRecord = ConversationAgentRunRecord | SubagentRunRecord\n\nexport interface CreateAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly threadId: string\n readonly triggerMessageId: string\n readonly spec: ConversationAgentRunSpec\n readonly requesterGroupIds: readonly string[]\n readonly createdAt?: Date\n}\n\nexport interface CreateSubagentRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly parentRunId: string\n /** Current parent delivery token. New children are admitted only while that delivery owns it. */\n readonly parentExecutionToken: string\n readonly spawnKey: string\n readonly spec: SubagentRunSpec\n /** Internal safety bound enforced atomically across worker processes. */\n readonly maxActiveChildren: number\n readonly createdAt?: Date\n}\n\nexport interface StartAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly modelId?: string\n readonly execution: AgentRunExecution\n readonly startedAt?: Date\n}\n\nexport interface FinishQueuedAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n}\n\nexport interface ReclaimAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly execution: AgentRunExecution\n}\n\nexport interface ConfirmAgentRunExecutionOwnershipInput {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n /** Exact expiration returned by the queue claim or its latest successful renewal. */\n readonly queueLeaseExpiresAt: Date\n}\n\nexport type FinishAgentRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly status: \"succeeded\"\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n readonly result?: SubagentRunResult\n readonly completedAt?: Date\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly status: \"failed\" | \"cancelled\"\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n }\n\nexport interface ListAgentRunsInput {\n readonly projectId: string\n readonly kinds?: readonly AgentRunKind[]\n readonly threadId?: string\n readonly parentRunId?: string\n readonly statuses?: readonly AgentRunStatus[]\n /** Effective start time; runs that never started use `createdAt`. */\n readonly startedAfter?: Date\n /** Effective start time; runs that never started use `createdAt`. */\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentRunsResult {\n readonly runs: readonly AgentRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_messages — one message (assistant messages inserted only once finalized) ─────────────\n\nexport type { AgentMessageRole }\n\nexport interface AgentMessageRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /** The run that produced this message; `null` for user-authored messages. */\n readonly runId: string | null\n readonly role: AgentMessageRole\n /** Principal that authored this persisted message: caller for user messages, agent identity later for assistant messages. */\n readonly authorPrincipal?: Principal\n /** Monotonic per thread, assigned by the store. */\n readonly seq: number\n /** Structured message content — text / reasoning / step boundaries / tool calls. */\n readonly parts: readonly AgentMessagePart[]\n /** Message-level metadata (mirrors `UIMessage.metadata`). */\n readonly metadata?: JsonValue\n /** Versions the `parts` shape so it can be migrated; stamped from `AGENT_MESSAGE_CONTENT_VERSION`. */\n readonly contentVersion: number\n readonly createdAt: Date\n readonly completedAt?: Date\n}\n\n/** Append a message: a {@link AgentMessage} (role + parts + metadata) plus its storage identity. */\nexport interface AppendAgentMessageInput extends AgentMessage {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly runId: string | null\n readonly authorPrincipal?: Principal\n readonly createdAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface DeleteAgentMessagesByRunInput {\n readonly projectId: string\n readonly threadId: string\n readonly runId: string\n}\n\nexport interface ListAgentMessagesInput {\n readonly projectId: string\n readonly threadId: string\n /** Return only messages whose per-thread sequence is greater than this retained boundary. */\n readonly afterSeq?: number\n readonly roles?: readonly AgentMessageRole[]\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentMessagesResult {\n readonly messages: readonly AgentMessageRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_context_checkpoints — append-only model-context boundaries ──────────────────────────\n\nexport type AgentContextCheckpointReason = \"threshold\" | \"overflow\"\n\n/**\n * A durable summary boundary used only when projecting a thread into model context.\n *\n * Checkpoints never replace or mutate transcript messages. Normal thread reads remain authoritative\n * and complete; the worker reads the latest checkpoint and only the retained message tail.\n */\nexport interface AgentContextCheckpointRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly createdByRunId: string\n readonly previousCheckpointId?: string\n readonly reason: AgentContextCheckpointReason\n readonly summary: string\n readonly summaryFormatVersion: 1\n readonly summarizedThroughSeq: number\n readonly observedHeadSeq: number\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n readonly summaryModelId: string\n readonly createdAt: Date\n}\n\nexport interface CreateAgentContextCheckpointInput {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly createdByRunId: string\n /** Compare-and-swap anchor. `null` means the thread must not have a prior checkpoint. */\n readonly expectedPreviousCheckpointId: string | null\n /** Compare-and-swap anchor for the complete transcript observed by the summarizer. */\n readonly expectedHeadSeq: number\n /** Current delivery token for `createdByRunId`; stale redeliveries must not write. */\n readonly executionToken: string\n readonly reason: AgentContextCheckpointReason\n readonly summary: string\n readonly summaryFormatVersion: 1\n readonly summarizedThroughSeq: number\n readonly observedHeadSeq: number\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n readonly summaryModelId: string\n readonly createdAt?: Date\n}\n\n// ── Store ───────────────────────────────────────────────────────────────────────────────────────\n\nexport interface AgentThreadStore {\n create(input: CreateAgentThreadInput): Promise<AgentThreadRecord>\n getById(params: { projectId: string; id: string }): Promise<AgentThreadRecord | null>\n list(input: ListAgentThreadsInput): Promise<ListAgentThreadsResult>\n}\n\nexport interface AgentRunStore {\n /** Persist a queued run and atomically claim the thread's single-flight slot. */\n create(input: CreateAgentRunInput): Promise<ConversationAgentRunRecord>\n /** Persist or replay one idempotent child run while atomically enforcing parent fan-out. */\n createSubagent(input: CreateSubagentRunInput): Promise<SubagentRunRecord>\n /** Transition a queued run to running and install the first delivery's execution token. */\n start(input: StartAgentRunInput): Promise<AgentRunRecord>\n /** Finish a queued run before execution and release the thread's single-flight slot. */\n finishQueued(input: FinishQueuedAgentRunInput): Promise<AgentRunRecord>\n /** Rotate the execution token for a redelivered running job (`attempt++`). */\n reclaim(input: ReclaimAgentRunInput): Promise<AgentRunRecord>\n /**\n * Project the queue's latest confirmed ownership expiration onto the current execution.\n * Implementations must fence by token and must never move the expiration backwards.\n */\n confirmExecutionOwnership(input: ConfirmAgentRunExecutionOwnershipInput): Promise<AgentRunRecord>\n /** Finalize a run and release the thread's `activeRunId`. */\n finish(input: FinishAgentRunInput): Promise<AgentRunRecord>\n getById(params: { projectId: string; id: string }): Promise<AgentRunRecord | null>\n getByIds(params: {\n projectId: string\n ids: readonly string[]\n }): Promise<readonly AgentRunRecord[]>\n list(input: ListAgentRunsInput): Promise<ListAgentRunsResult>\n}\n\nexport interface AgentMessageStore {\n /** Insert a message (its `parts` are the canonical content) and bump thread stats. */\n append(input: AppendAgentMessageInput): Promise<AgentMessageRecord>\n /** Delete every message produced by one run and repair the thread's message stats. */\n deleteByRunId(input: DeleteAgentMessagesByRunInput): Promise<number>\n getById(params: { projectId: string; id: string }): Promise<AgentMessageRecord | null>\n list(input: ListAgentMessagesInput): Promise<ListAgentMessagesResult>\n}\n\nexport interface AgentContextCheckpointStore {\n /**\n * Append one checkpoint after atomically validating run ownership and both transcript anchors.\n * Repeating the same payload for the same creating run is idempotent.\n */\n create(input: CreateAgentContextCheckpointInput): Promise<AgentContextCheckpointRecord>\n /** Return checkpoints created by the requested runs, in first-occurrence input order. */\n getByRunIds(input: {\n readonly projectId: string\n readonly runIds: readonly string[]\n }): Promise<readonly AgentContextCheckpointRecord[]>\n getLatest(input: {\n readonly projectId: string\n readonly threadId: string\n }): Promise<AgentContextCheckpointRecord | null>\n}\n\nexport interface AgentStorage {\n readonly threads: AgentThreadStore\n readonly runs: AgentRunStore\n readonly messages: AgentMessageStore\n readonly checkpoints: AgentContextCheckpointStore\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";;AA6DO,IAAM,0BAA0B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AASO,IAAM,2BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,SAAS,0BAA0B,CACxC,OACkC;AAAA,EAClC,IAAI,UAAU,QAAQ,UAAU,WAAW;AAAA,IACzC;AAAA,EACF;AAAA,EACA,OAAQ,yBAA+C,SAAS,KAAK,IAChE,QACD;AAAA;AAIC,IAAM,6BAA6B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
|
|
8
|
-
"debugId": "4012BA3E8FE1A2E864756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|