@sixb/core 0.1.25 → 0.1.26
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 +35 -35
- package/dist/agents/attachment-keys.d.ts +25 -0
- package/dist/agents/attachment-keys.d.ts.map +1 -0
- package/dist/agents/cancel.d.ts +12 -0
- package/dist/agents/cancel.d.ts.map +1 -1
- package/dist/agents/children.d.ts.map +1 -1
- package/dist/agents/dispatch.d.ts +1 -9
- package/dist/agents/dispatch.d.ts.map +1 -1
- package/dist/agents/execution.d.ts +5 -0
- package/dist/agents/execution.d.ts.map +1 -1
- package/dist/agents/index.d.ts +31 -6
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +154 -66
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/model-loop.d.ts +3 -5
- package/dist/agents/model-loop.d.ts.map +1 -1
- package/dist/agents/model-routing.d.ts +4 -1
- package/dist/agents/model-routing.d.ts.map +1 -1
- package/dist/agents/request.d.ts +9 -1
- package/dist/agents/request.d.ts.map +1 -1
- package/dist/agents/run-after-finish.d.ts +11 -0
- package/dist/agents/run-after-finish.d.ts.map +1 -0
- package/dist/agents/run-artifacts.d.ts +56 -0
- package/dist/agents/run-artifacts.d.ts.map +1 -0
- package/dist/agents/run-events.d.ts +49 -0
- package/dist/agents/run-events.d.ts.map +1 -0
- package/dist/agents/run-fence.d.ts +38 -0
- package/dist/agents/run-fence.d.ts.map +1 -0
- package/dist/agents/run-liveness.d.ts +36 -0
- package/dist/agents/run-liveness.d.ts.map +1 -0
- package/dist/agents/run-plan.d.ts +110 -0
- package/dist/agents/run-plan.d.ts.map +1 -0
- package/dist/agents/run-session-children.d.ts +89 -0
- package/dist/agents/run-session-children.d.ts.map +1 -0
- package/dist/agents/run-session-http.d.ts +37 -0
- package/dist/agents/run-session-http.d.ts.map +1 -0
- package/dist/agents/run-session-serve.d.ts +24 -0
- package/dist/agents/run-session-serve.d.ts.map +1 -0
- package/dist/agents/run-session-wire.d.ts +31 -0
- package/dist/agents/run-session-wire.d.ts.map +1 -0
- package/dist/agents/run-session.d.ts +239 -0
- package/dist/agents/run-session.d.ts.map +1 -0
- package/dist/agents/run-token.d.ts +40 -0
- package/dist/agents/run-token.d.ts.map +1 -0
- package/dist/agents/run-tools.d.ts +68 -0
- package/dist/agents/run-tools.d.ts.map +1 -0
- package/dist/agents/run-turn.d.ts +59 -0
- package/dist/agents/run-turn.d.ts.map +1 -0
- package/dist/agents/streams/index.js +1 -1
- package/dist/agents/streams/internal.d.ts +1 -1
- package/dist/agents/streams/internal.d.ts.map +1 -1
- package/dist/agents/streams/internal.js +2 -4
- package/dist/agents/streams/internal.js.map +1 -1
- package/dist/agents/streams/protocol.d.ts +1 -96
- package/dist/agents/streams/protocol.d.ts.map +1 -1
- package/dist/agents/subagent-runs.d.ts +7 -1
- package/dist/agents/subagent-runs.d.ts.map +1 -1
- package/dist/agents/tool-files.d.ts +34 -0
- package/dist/agents/tool-files.d.ts.map +1 -0
- package/dist/agents/workflow-node-session.d.ts +99 -0
- package/dist/agents/workflow-node-session.d.ts.map +1 -0
- package/dist/artifacts/frames/index.js +1 -1
- package/dist/artifacts/frames/index.js.map +1 -1
- package/dist/artifacts/index.js.map +1 -1
- package/dist/artifacts/publish/index.d.ts +1 -1
- package/dist/artifacts/publish/index.d.ts.map +1 -1
- package/dist/artifacts/publish/index.js +19 -19
- package/dist/auth/index.js +8 -8
- package/dist/authorization/index.js +4 -4
- package/dist/bootstrap/index.js +45 -43
- package/dist/bootstrap/index.js.map +2 -2
- package/dist/{chunk-2fn60nvs.js → chunk-06sg8s4z.js} +2 -2
- package/dist/{chunk-2fn60nvs.js.map → chunk-06sg8s4z.js.map} +1 -1
- package/dist/chunk-07kkp2e1.js.map +1 -1
- package/dist/{chunk-9ntbsnke.js → chunk-0bc3w0zq.js} +7 -7
- package/dist/{chunk-9ntbsnke.js.map → chunk-0bc3w0zq.js.map} +2 -2
- package/dist/{chunk-d2m879s4.js → chunk-0kk2wt0h.js} +27 -27
- package/dist/chunk-0kk2wt0h.js.map +12 -0
- package/dist/chunk-16a9dmfy.js.map +1 -1
- package/dist/chunk-18sk89cg.js.map +2 -2
- package/dist/{chunk-3qms4nax.js → chunk-1vg43g9q.js} +20 -20
- package/dist/{chunk-3qms4nax.js.map → chunk-1vg43g9q.js.map} +4 -4
- package/dist/{chunk-hqsp2sx4.js → chunk-1xvqgg88.js} +31 -33
- package/dist/{chunk-hqsp2sx4.js.map → chunk-1xvqgg88.js.map} +6 -6
- package/dist/chunk-2adz0h75.js.map +1 -1
- package/dist/{chunk-fm62y49k.js → chunk-2pk5hjj9.js} +5 -3
- package/dist/{chunk-fm62y49k.js.map → chunk-2pk5hjj9.js.map} +5 -5
- package/dist/{chunk-vrf90dkv.js → chunk-2vjnyz1s.js} +1 -1
- package/dist/{chunk-vrf90dkv.js.map → chunk-2vjnyz1s.js.map} +1 -1
- package/dist/{chunk-4f3ydv7t.js → chunk-315qye3g.js} +1 -1
- package/dist/{chunk-4f3ydv7t.js.map → chunk-315qye3g.js.map} +1 -1
- package/dist/{chunk-rap5w0x0.js → chunk-31khg3g0.js} +1 -1
- package/dist/{chunk-rap5w0x0.js.map → chunk-31khg3g0.js.map} +1 -1
- package/dist/chunk-45ngkxkp.js.map +1 -1
- package/dist/chunk-48jezz3j.js.map +1 -1
- package/dist/{chunk-vr3j63jq.js → chunk-4jq2bg8t.js} +78 -78
- package/dist/{chunk-vr3j63jq.js.map → chunk-4jq2bg8t.js.map} +4 -4
- package/dist/chunk-4ymrcdbm.js.map +1 -1
- package/dist/chunk-58geavnf.js.map +1 -1
- package/dist/{chunk-6y0mkhex.js → chunk-59kf345w.js} +2 -2
- package/dist/{chunk-6y0mkhex.js.map → chunk-59kf345w.js.map} +1 -1
- package/dist/{chunk-3p93tb91.js → chunk-6qn7nmd3.js} +102 -102
- package/dist/{chunk-3p93tb91.js.map → chunk-6qn7nmd3.js.map} +4 -4
- package/dist/chunk-73j0v4qv.js +355 -0
- package/dist/chunk-73j0v4qv.js.map +13 -0
- package/dist/{chunk-2gjj5dx3.js → chunk-78ymxrn0.js} +1 -1
- package/dist/{chunk-6bkbyer5.js → chunk-7ex2p3zp.js} +3 -3
- package/dist/{chunk-6bkbyer5.js.map → chunk-7ex2p3zp.js.map} +1 -1
- package/dist/{chunk-5tfev0fv.js → chunk-7hf6tkgs.js} +167 -167
- package/dist/{chunk-5tfev0fv.js.map → chunk-7hf6tkgs.js.map} +4 -4
- package/dist/{chunk-8z4726jz.js → chunk-7wn5z7mq.js} +10 -10
- package/dist/{chunk-8z4726jz.js.map → chunk-7wn5z7mq.js.map} +2 -2
- package/dist/{chunk-6n69k945.js → chunk-8mb7mt8n.js} +2 -2
- package/dist/chunk-8ncg20rd.js.map +1 -1
- package/dist/{chunk-68wghpdf.js → chunk-8v5a54qz.js} +50 -11
- package/dist/{chunk-68wghpdf.js.map → chunk-8v5a54qz.js.map} +3 -3
- package/dist/{chunk-gqm0b7vd.js → chunk-8v6xzwgr.js} +92 -76
- package/dist/{chunk-gqm0b7vd.js.map → chunk-8v6xzwgr.js.map} +6 -6
- package/dist/{chunk-m36fw8ft.js → chunk-8wsjr52f.js} +1 -1
- package/dist/{chunk-vd1rk42q.js → chunk-8xnz9vvp.js} +4 -4
- package/dist/{chunk-vd1rk42q.js.map → chunk-8xnz9vvp.js.map} +1 -1
- package/dist/chunk-9mab3dvg.js.map +1 -1
- package/dist/chunk-9tc8dxmn.js.map +1 -1
- package/dist/chunk-9x8dybsb.js.map +2 -2
- package/dist/chunk-a3faa34j.js.map +1 -1
- package/dist/{chunk-62a63pr6.js → chunk-axb4ss9a.js} +7 -7
- package/dist/{chunk-62a63pr6.js.map → chunk-axb4ss9a.js.map} +2 -2
- package/dist/{chunk-z3ryd53f.js → chunk-b6ghvap7.js} +35 -11
- package/dist/{chunk-z3ryd53f.js.map → chunk-b6ghvap7.js.map} +3 -3
- package/dist/{chunk-sqfvnvqj.js → chunk-c14ap3s9.js} +2 -2
- package/dist/{chunk-sqfvnvqj.js.map → chunk-c14ap3s9.js.map} +1 -1
- package/dist/{chunk-661ezhks.js → chunk-cbcgs9f7.js} +87 -8
- package/dist/chunk-cbcgs9f7.js.map +11 -0
- package/dist/chunk-cwdzcv37.js.map +1 -1
- package/dist/{chunk-bab05bhg.js → chunk-dgtd0836.js} +1 -1
- package/dist/{chunk-1j6j0rht.js → chunk-e24fvw8g.js} +1 -1
- package/dist/{chunk-1j6j0rht.js.map → chunk-e24fvw8g.js.map} +1 -1
- package/dist/chunk-e5wf5vz0.js.map +1 -1
- package/dist/chunk-eptrvnby.js.map +1 -1
- package/dist/chunk-ey1nk510.js.map +1 -1
- package/dist/{chunk-j936th07.js → chunk-fakrpfy3.js} +58 -58
- package/dist/{chunk-j936th07.js.map → chunk-fakrpfy3.js.map} +5 -5
- package/dist/chunk-fb3feg1e.js.map +1 -1
- package/dist/chunk-ff5xkv0p.js.map +1 -1
- package/dist/chunk-fntqb7qy.js.map +1 -1
- package/dist/{chunk-7ny9mjgm.js → chunk-ft3w5ahs.js} +1 -1
- package/dist/chunk-g663fahq.js.map +1 -1
- package/dist/{chunk-cdk3egjj.js → chunk-h1na2cxc.js} +1 -1
- package/dist/{chunk-cdk3egjj.js.map → chunk-h1na2cxc.js.map} +1 -1
- package/dist/chunk-hn2r7z41.js.map +1 -1
- package/dist/{chunk-24bqx0dx.js → chunk-hn76sanm.js} +1 -1
- package/dist/{chunk-24bqx0dx.js.map → chunk-hn76sanm.js.map} +1 -1
- package/dist/chunk-jmfet9r4.js.map +1 -1
- package/dist/{chunk-bnr4a734.js → chunk-jn3ysaf2.js} +24 -22
- package/dist/{chunk-bnr4a734.js.map → chunk-jn3ysaf2.js.map} +5 -5
- package/dist/{chunk-4y26vs3v.js → chunk-jspskey0.js} +16 -3
- package/dist/chunk-jspskey0.js.map +10 -0
- package/dist/{chunk-r6szek0x.js → chunk-jt3r6thp.js} +2 -135
- package/dist/chunk-jt3r6thp.js.map +10 -0
- package/dist/chunk-kfee1h52.js.map +1 -1
- package/dist/{chunk-qx00vjrj.js → chunk-kwfhd1g0.js} +23 -23
- package/dist/{chunk-qx00vjrj.js.map → chunk-kwfhd1g0.js.map} +4 -4
- package/dist/chunk-m427qgq0.js.map +1 -1
- package/dist/chunk-mbsbxarb.js.map +1 -1
- package/dist/{chunk-et017krg.js → chunk-mdxmt0n3.js} +8657 -8704
- package/dist/{chunk-et017krg.js.map → chunk-mdxmt0n3.js.map} +37 -37
- package/dist/chunk-mmagke4x.js.map +1 -1
- package/dist/{chunk-2x19q6k6.js → chunk-mqx25wwh.js} +319 -154
- package/dist/chunk-mqx25wwh.js.map +18 -0
- package/dist/chunk-mzx71snp.js.map +1 -1
- package/dist/chunk-n8q5j6y5.js.map +1 -1
- package/dist/chunk-npcr0228.js.map +1 -1
- package/dist/{chunk-m2nevja0.js → chunk-phm3c7b9.js} +1 -1
- package/dist/{chunk-m2nevja0.js.map → chunk-phm3c7b9.js.map} +1 -1
- package/dist/chunk-qf954wje.js.map +1 -1
- package/dist/{chunk-65pyhyas.js → chunk-qgvbxfqv.js} +6 -8
- package/dist/{chunk-65pyhyas.js.map → chunk-qgvbxfqv.js.map} +2 -2
- package/dist/{chunk-hk38wahh.js → chunk-qst145py.js} +4 -4
- package/dist/{chunk-hk38wahh.js.map → chunk-qst145py.js.map} +1 -1
- package/dist/{chunk-c844dkwd.js → chunk-qtzftvxa.js} +4 -5
- package/dist/{chunk-c844dkwd.js.map → chunk-qtzftvxa.js.map} +2 -2
- package/dist/chunk-ratkv4zc.js +3 -0
- package/dist/chunk-ratkv4zc.js.map +9 -0
- package/dist/{chunk-nzapm6p0.js → chunk-s3we74h8.js} +1 -2
- package/dist/chunk-s3we74h8.js.map +12 -0
- package/dist/{chunk-0xmt5p5y.js → chunk-t3brw0wd.js} +1 -2
- package/dist/{chunk-0xmt5p5y.js.map → chunk-t3brw0wd.js.map} +2 -2
- package/dist/chunk-t5608tkq.js.map +1 -1
- package/dist/chunk-tdxfsg1c.js.map +1 -1
- package/dist/{chunk-1t6k1avb.js → chunk-tnhqtfea.js} +1 -1
- package/dist/chunk-vhbw5sqm.js.map +1 -1
- package/dist/{chunk-rp9wwk7b.js → chunk-vx4e4zv4.js} +30 -30
- package/dist/{chunk-rp9wwk7b.js.map → chunk-vx4e4zv4.js.map} +4 -4
- package/dist/chunk-waqk73p1.js.map +1 -1
- package/dist/chunk-x0v3jd47.js.map +1 -1
- package/dist/{chunk-yecwnwpq.js → chunk-xm8qgbqm.js} +58 -29
- package/dist/{chunk-yecwnwpq.js.map → chunk-xm8qgbqm.js.map} +7 -7
- package/dist/{chunk-97wr6p2g.js → chunk-y7j6x4h0.js} +8 -8
- package/dist/{chunk-97wr6p2g.js.map → chunk-y7j6x4h0.js.map} +4 -4
- package/dist/{chunk-xe0732g0.js → chunk-yavhtnac.js} +12 -8
- package/dist/{chunk-xe0732g0.js.map → chunk-yavhtnac.js.map} +4 -4
- package/dist/chunk-yd00vzqr.js +3394 -0
- package/dist/chunk-yd00vzqr.js.map +37 -0
- package/dist/{chunk-n9w3n38q.js → chunk-ye5c8016.js} +54 -8
- package/dist/chunk-ye5c8016.js.map +23 -0
- package/dist/chunk-yw9pyg66.js.map +1 -1
- package/dist/{chunk-nydf3dbe.js → chunk-z9mg7wya.js} +37 -20
- package/dist/chunk-z9mg7wya.js.map +13 -0
- package/dist/chunk-zbc929zg.js.map +1 -1
- package/dist/chunk-zhh1jd89.js +290 -0
- package/dist/chunk-zhh1jd89.js.map +10 -0
- package/dist/connectors/connections/authorizations.d.ts +2 -2
- package/dist/connectors/connections/authorizations.d.ts.map +1 -1
- package/dist/connectors/connections/service.d.ts.map +1 -1
- package/dist/connectors/connections/tokens.d.ts +2 -2
- package/dist/connectors/connections/tokens.d.ts.map +1 -1
- package/dist/connectors/connections/validation.d.ts +5 -0
- package/dist/connectors/connections/validation.d.ts.map +1 -1
- package/dist/connectors/types.d.ts +9 -2
- package/dist/connectors/types.d.ts.map +1 -1
- package/dist/datasets/write.js +3 -3
- package/dist/deploy/internal.js +2 -5
- package/dist/deploy/internal.js.map +3 -3
- package/dist/deploy/types.d.ts +0 -2
- package/dist/deploy/types.d.ts.map +1 -1
- package/dist/execution/agent.d.ts +2 -2
- package/dist/execution/agent.d.ts.map +1 -1
- package/dist/execution/agent.js +38 -38
- package/dist/execution/agent.js.map +1 -1
- package/dist/execution/primitive.js +35 -35
- package/dist/execution/request.js +37 -37
- package/dist/execution/request.js.map +2 -2
- package/dist/http/api-routes.d.ts +12 -11
- package/dist/http/api-routes.d.ts.map +1 -1
- package/dist/http/index.js +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +53 -51
- package/dist/index.js.map +1 -1
- package/dist/lake-storage/index.js +3 -3
- package/dist/logging/internal.js +1 -1
- package/dist/materializer/index.js +17 -17
- package/dist/models/execution/errors.d.ts +5 -0
- package/dist/models/execution/errors.d.ts.map +1 -1
- package/dist/models/execution/index.d.ts +2 -1
- package/dist/models/execution/index.d.ts.map +1 -1
- package/dist/models/execution/index.js +55 -50
- package/dist/models/execution/index.js.map +1 -1
- package/dist/models/execution/model-call-recorder.d.ts +7 -2
- package/dist/models/execution/model-call-recorder.d.ts.map +1 -1
- package/dist/models/execution.d.ts.map +1 -1
- package/dist/models/language-call.d.ts +51 -0
- package/dist/models/language-call.d.ts.map +1 -0
- package/dist/objects/index.js +35 -35
- package/dist/objects/query/index.js +17 -17
- package/dist/ontology/docs-markdown.d.ts.map +1 -1
- package/dist/ontology/index.d.ts +1 -1
- package/dist/ontology/index.d.ts.map +1 -1
- package/dist/ontology/index.js +4 -4
- package/dist/ontology/internal.js +8 -275
- package/dist/ontology/internal.js.map +3 -4
- package/dist/ontology/user-ref.d.ts +21 -3
- package/dist/ontology/user-ref.d.ts.map +1 -1
- package/dist/pipelines/index.js +19 -19
- package/dist/projections/builders.d.ts +13 -2
- package/dist/projections/builders.d.ts.map +1 -1
- package/dist/projections/index.d.ts +1 -1
- package/dist/projections/index.d.ts.map +1 -1
- package/dist/projections/internal.js +17 -17
- package/dist/projections/types.d.ts +7 -0
- package/dist/projections/types.d.ts.map +1 -1
- package/dist/projections/validation.d.ts +2 -0
- package/dist/projections/validation.d.ts.map +1 -1
- package/dist/query.js +2 -2
- package/dist/queues/in-memory.d.ts +0 -1
- package/dist/queues/in-memory.d.ts.map +1 -1
- package/dist/queues/index.d.ts +1 -1
- package/dist/queues/index.d.ts.map +1 -1
- package/dist/queues/index.js +1 -1
- package/dist/queues/types.d.ts +0 -8
- package/dist/queues/types.d.ts.map +1 -1
- package/dist/runtime/internal.js +23 -23
- package/dist/runtime/internal.js.map +1 -1
- package/dist/sandboxes/configuration.d.ts +4 -6
- package/dist/sandboxes/configuration.d.ts.map +1 -1
- package/dist/sandboxes/environment.d.ts.map +1 -1
- package/dist/sandboxes/exec.d.ts +5 -3
- package/dist/sandboxes/exec.d.ts.map +1 -1
- package/dist/sandboxes/guest-credentials.d.ts +61 -0
- package/dist/sandboxes/guest-credentials.d.ts.map +1 -0
- package/dist/sandboxes/index.d.ts +2 -0
- package/dist/sandboxes/index.d.ts.map +1 -1
- package/dist/sandboxes/index.js +23 -9
- package/dist/sandboxes/index.js.map +1 -1
- package/dist/sandboxes/sandbox.d.ts +18 -4
- package/dist/sandboxes/sandbox.d.ts.map +1 -1
- package/dist/security/internal.js +1 -1
- package/dist/security/internal.js.map +1 -1
- package/dist/shares/internal.js +17 -17
- package/dist/shares/internal.js.map +1 -1
- package/dist/storage/agents/in-memory.d.ts +3 -1
- package/dist/storage/agents/in-memory.d.ts.map +1 -1
- package/dist/storage/agents/index.d.ts +1 -1
- package/dist/storage/agents/index.d.ts.map +1 -1
- package/dist/storage/agents/provider.d.ts +6 -0
- package/dist/storage/agents/provider.d.ts.map +1 -1
- package/dist/storage/agents/provider.js +8 -2
- package/dist/storage/agents/provider.js.map +1 -1
- package/dist/storage/agents/types.d.ts +63 -7
- package/dist/storage/agents/types.d.ts.map +1 -1
- package/dist/storage/ai-cost/provider.js +2 -2
- package/dist/storage/connector-connections/provider.js.map +1 -1
- package/dist/storage/file-upload-sessions/provider.js +9 -9
- package/dist/storage/index.d.ts +1 -1
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/index.js +15 -15
- package/dist/storage/ontology/provider.js +1 -1
- package/dist/storage/share-grants/provider.js +3 -3
- package/dist/storage/types.d.ts +1 -1
- package/dist/storage/types.d.ts.map +1 -1
- package/dist/storage/workflow-runs/provider.js +9 -9
- package/dist/syncs/index.js +20 -20
- package/dist/testing/agent-storage-contract.d.ts.map +1 -1
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +677 -352
- package/dist/testing/index.js.map +9 -7
- package/dist/testing/queues-contract.d.ts.map +1 -1
- package/dist/testing/sandbox-credentials-contract.d.ts +27 -0
- package/dist/testing/sandbox-credentials-contract.d.ts.map +1 -0
- package/dist/testing/sandboxes-contract.d.ts.map +1 -1
- package/dist/testing/users.d.ts +20 -0
- package/dist/testing/users.d.ts.map +1 -0
- package/dist/users/execution.d.ts +6 -2
- package/dist/users/execution.d.ts.map +1 -1
- package/dist/users/index.d.ts +1 -1
- package/dist/users/index.d.ts.map +1 -1
- package/dist/webhooks/internal.js +17 -17
- package/dist/webhooks/internal.js.map +1 -1
- package/dist/workers/index.js.map +1 -1
- package/dist/workflows/index.js +41 -39
- package/dist/workflows/index.js.map +1 -1
- package/package.json +1 -1
- package/src/agents/README.md +136 -0
- package/src/agents/attachment-keys.ts +83 -0
- package/src/agents/cancel.ts +16 -1
- package/src/agents/children.ts +5 -3
- package/src/agents/dispatch.ts +6 -58
- package/src/agents/execution.ts +18 -0
- package/src/agents/index.ts +127 -21
- package/src/agents/model-loop.ts +23 -73
- package/src/agents/model-routing.ts +7 -2
- package/src/agents/request.ts +69 -20
- package/src/agents/run-after-finish.ts +133 -0
- package/src/agents/run-artifacts.ts +257 -0
- package/src/agents/run-events.ts +302 -0
- package/src/agents/run-fence.ts +71 -0
- package/src/agents/run-liveness.ts +122 -0
- package/src/agents/run-plan.ts +316 -0
- package/src/agents/run-session-children.ts +303 -0
- package/src/agents/run-session-http.ts +397 -0
- package/src/agents/run-session-serve.ts +479 -0
- package/src/agents/run-session-wire.ts +189 -0
- package/src/agents/run-session.ts +802 -0
- package/src/agents/run-token.ts +124 -0
- package/src/agents/run-tools.ts +180 -0
- package/src/agents/run-turn.ts +265 -0
- package/src/agents/streams/internal.ts +0 -1
- package/src/agents/streams/protocol.ts +0 -292
- package/src/agents/subagent-runs.ts +19 -1
- package/src/agents/tool-files.ts +225 -0
- package/src/agents/workflow-node-session.ts +387 -0
- package/src/artifacts/publish/index.ts +1 -0
- package/src/connectors/connections/authorizations.ts +3 -2
- package/src/connectors/connections/service.ts +5 -1
- package/src/connectors/connections/tokens.ts +41 -5
- package/src/connectors/connections/validation.ts +21 -0
- package/src/connectors/types.ts +12 -2
- package/src/deploy/types.ts +0 -2
- package/src/deploy/validation.ts +1 -4
- package/src/execution/agent.ts +2 -2
- package/src/execution/authorized-object-reader.ts +28 -1
- package/src/http/api-routes.ts +114 -27
- package/src/index.ts +3 -1
- package/src/models/execution/README.md +15 -1
- package/src/models/execution/errors.ts +14 -0
- package/src/models/execution/index.ts +2 -1
- package/src/models/execution/model-call-recorder.ts +12 -10
- package/src/models/execution.ts +9 -11
- package/src/models/language-call.ts +247 -0
- package/src/ontology/docs-markdown.ts +14 -0
- package/src/ontology/index.ts +1 -1
- package/src/ontology/user-ref.ts +40 -6
- package/src/projections/builders.ts +48 -4
- package/src/projections/index.ts +1 -0
- package/src/projections/registry.ts +1 -0
- package/src/projections/revision.ts +10 -0
- package/src/projections/types.ts +8 -0
- package/src/projections/validation.ts +52 -6
- package/src/queues/in-memory.ts +0 -5
- package/src/queues/index.ts +0 -2
- package/src/queues/types.ts +0 -13
- package/src/runtime/host.ts +1 -1
- package/src/sandboxes/README.md +17 -6
- package/src/sandboxes/configuration.ts +7 -9
- package/src/sandboxes/environment.ts +1 -0
- package/src/sandboxes/exec.ts +17 -9
- package/src/sandboxes/guest-credentials.ts +262 -0
- package/src/sandboxes/index.ts +14 -0
- package/src/sandboxes/sandbox.ts +19 -4
- package/src/storage/agents/in-memory.ts +53 -0
- package/src/storage/agents/index.ts +2 -0
- package/src/storage/agents/provider.ts +56 -11
- package/src/storage/agents/types.ts +59 -7
- package/src/storage/index.ts +2 -0
- package/src/storage/types.ts +1 -0
- package/src/testing/agent-storage-contract.ts +175 -2
- package/src/testing/ai-model-call-groups-contract.ts +0 -1
- package/src/testing/index.ts +5 -0
- package/src/testing/queues-contract.ts +0 -16
- package/src/testing/sandbox-credentials-contract.ts +284 -0
- package/src/testing/sandboxes-contract.ts +21 -0
- package/src/testing/users.ts +39 -0
- package/src/users/execution.ts +33 -7
- package/src/users/index.ts +7 -1
- package/dist/agents/api-gateway.d.ts +0 -26
- package/dist/agents/api-gateway.d.ts.map +0 -1
- package/dist/chunk-2x19q6k6.js.map +0 -17
- package/dist/chunk-4y26vs3v.js.map +0 -10
- package/dist/chunk-661ezhks.js.map +0 -11
- package/dist/chunk-d2m879s4.js.map +0 -12
- package/dist/chunk-n9w3n38q.js.map +0 -23
- package/dist/chunk-nydf3dbe.js.map +0 -13
- package/dist/chunk-nzapm6p0.js.map +0 -12
- package/dist/chunk-r6szek0x.js.map +0 -10
- package/dist/chunk-vabga7fk.js +0 -176
- package/dist/chunk-vabga7fk.js.map +0 -12
- package/dist/chunk-vpgwq5nf.js +0 -810
- package/dist/chunk-vpgwq5nf.js.map +0 -21
- package/src/agents/api-gateway.ts +0 -68
- /package/dist/{chunk-2gjj5dx3.js.map → chunk-78ymxrn0.js.map} +0 -0
- /package/dist/{chunk-6n69k945.js.map → chunk-8mb7mt8n.js.map} +0 -0
- /package/dist/{chunk-m36fw8ft.js.map → chunk-8wsjr52f.js.map} +0 -0
- /package/dist/{chunk-bab05bhg.js.map → chunk-dgtd0836.js.map} +0 -0
- /package/dist/{chunk-7ny9mjgm.js.map → chunk-ft3w5ahs.js.map} +0 -0
- /package/dist/{chunk-1t6k1avb.js.map → chunk-tnhqtfea.js.map} +0 -0
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/storage/agents/provider.ts", "../src/agents/ids.ts", "../src/agents/types.ts", "../src/storage/agents/errors.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import { isDeepStrictEqual } from \"node:util\"\nimport { createAgentMessageId, createCopiedAgentContextCheckpointId } from \"../../agents/ids\"\nimport { AGENT_REASONING_LEVELS } from \"../../agents/types\"\nimport type { Principal, UserPrincipal } from \"../../auth\"\nimport { isFileRef } from \"../../blob-storage/validation\"\nimport { isJsonObject, isPlainRecord } from \"../../json\"\nimport { isLanguageModelTier, LANGUAGE_MODEL_TIERS } from \"../../models/catalog\"\nimport { isModelReasoning } from \"../../models/language-model\"\nimport type { ExecutionRecord, ExecutionStorage } from \"../executions\"\nimport { findAgentRunExecution } from \"../executions/run-link\"\nimport { AgentStorageError } from \"./errors\"\nimport type {\n AddAgentThreadParticipantsInput,\n AgentApprovalCall,\n AgentApprovalMode,\n AgentApprovalRecord,\n AgentApprovalStatus,\n AgentContextCheckpointRecord,\n AgentMemoryChange,\n AgentMessageRecord,\n AgentRunRecord,\n AgentThreadParticipantRecord,\n AgentThreadRecord,\n AgentThreadSandboxParams,\n AgentThreadSandboxState,\n ConversationAgentRunSpec,\n CreateAgentContextCheckpointInput,\n CreateSubagentRunInput,\n FinishAgentRunInput,\n ForkAgentThreadInput,\n ListAgentApprovalsInput,\n RequestAgentApprovalInput,\n SaveAgentMemoryInput,\n StopAgentApprovalsInput,\n SubagentRunFile,\n SubagentRunRecord,\n SubagentRunResult,\n TransitionAgentThreadSandboxInput,\n} from \"./types\"\nimport {\n AGENT_APPROVAL_MODES,\n AGENT_HOLDING_APPROVAL_MODES,\n AGENT_MEMORY_HISTORY_DAYS,\n} from \"./types\"\n\nconst SANDBOX_NAME_PATTERN = /^[a-zA-Z0-9-]{1,80}$/\n\n/**\n * Shared state machine. Providers must lock the run, then thread, around this decision/write.\n *\n * A conversation has a workspace once its sandbox is configured. A sub-agent's thread may keep a\n * blank one while the sub-agent pauses, fenced by the thread's active run as a turn's is. Its\n * next run starts a fresh one where a conversation's would need an explicit recreation.\n */\nexport function transitionAgentThreadSandbox(\n thread: AgentThreadRecord | null,\n run: AgentRunRecord | null,\n input: TransitionAgentThreadSandboxInput\n): AgentThreadSandboxState {\n const fail = (message: string): never => {\n throw new AgentStorageError(\"invalid_state\", `[Sixb] Sandbox ${message}`)\n }\n if (!thread || (!thread.sandboxParams && thread.kind !== \"subagent\")) {\n return fail(\"is not configured on this thread.\")\n }\n if (!SANDBOX_NAME_PATTERN.test(input.name)) return fail(\"name is invalid.\")\n const state = thread.sandboxState\n if (input.action === \"recreate\") {\n if (thread.activeRunId !== null) return fail(\"cannot be recreated during an active run.\")\n if (!state || state.name !== input.expectedSandboxName || input.name === state.name)\n return fail(\"changed; reload before recreating.\")\n if (![\"busy\", \"blocked\", \"unavailable\"].includes(state.status)) {\n return fail(\"does not require recovery.\")\n }\n return {\n name: input.name,\n status: \"new\",\n initialized: false,\n resetAt: new Date().toISOString(),\n }\n }\n if (\n !run ||\n run.threadId !== thread.id ||\n run.status !== \"running\" ||\n thread.activeRunId !== run.id ||\n run.id !== input.runId ||\n run.execution?.token !== input.executionToken ||\n run.execution.queueLeaseExpiresAt.getTime() <= Date.now()\n ) {\n throw new AgentStorageError(\"execution_lost\", \"[Sixb] Sandbox execution ownership was lost.\")\n }\n if (input.action === \"acquire\") {\n if (state && state.status !== \"new\" && state.status !== \"ready\") {\n if (thread.kind === \"subagent\" && state.name !== input.name) {\n return startSubagentWorkspaceAgain(input)\n }\n return fail(\"requires recovery; previous operations may still be in flight.\")\n }\n if (state && state.name !== input.name) return fail(\"name changed.\")\n if (!/^[a-f0-9]{64}$/.test(input.sourceFingerprint))\n return fail(\"source fingerprint is invalid.\")\n if (state?.sourceFingerprint && state.sourceFingerprint !== input.sourceFingerprint) {\n return fail(\"source identity changed; the existing checkout was not opened.\")\n }\n return {\n name: input.name,\n status: \"busy\",\n initialized: state?.initialized ?? false,\n ...(state?.resetAt ? { resetAt: state.resetAt } : {}),\n sourceFingerprint: input.sourceFingerprint,\n owner: { runId: input.runId, executionToken: input.executionToken },\n }\n }\n if (\n state?.status !== \"busy\" ||\n state.name !== input.name ||\n state.owner?.runId !== input.runId ||\n state.owner.executionToken !== input.executionToken\n ) {\n return fail(\"is not owned by this execution.\")\n }\n if (input.action === \"replace\") {\n if (\n !state.initialized ||\n input.nextName === state.name ||\n !SANDBOX_NAME_PATTERN.test(input.nextName)\n ) {\n return fail(\"replacement requires initialized state and a fresh valid name.\")\n }\n // Only the owning worker may report confirmed loss; retain its fence across replacement.\n return {\n ...state,\n name: input.nextName,\n initialized: false,\n resetAt: new Date().toISOString(),\n }\n }\n if (input.status === \"ready\" && !input.initialized) return fail(\"initialization is incomplete.\")\n return {\n name: state.name,\n status: input.status,\n initialized: input.initialized,\n sourceFingerprint: state.sourceFingerprint,\n ...(state.resetAt ? { resetAt: state.resetAt } : {}),\n }\n}\n\n/**\n * A sub-agent's thread whose workspace an ended run left destroyed, unsaved or in doubt: the run\n * that continues it starts from a fresh one, under a new name, and is told its files were reset.\n * Nobody can recreate a sub-agent's workspace, and the thread's single active run is this one, so\n * whatever the old name still holds is never opened again.\n */\nfunction startSubagentWorkspaceAgain(\n input: Extract<TransitionAgentThreadSandboxInput, { readonly action: \"acquire\" }>\n): AgentThreadSandboxState {\n if (!/^[a-f0-9]{64}$/.test(input.sourceFingerprint)) {\n throw new AgentStorageError(\"invalid_state\", \"[Sixb] Sandbox source fingerprint is invalid.\")\n }\n return {\n name: input.name,\n status: \"busy\",\n initialized: false,\n resetAt: new Date().toISOString(),\n sourceFingerprint: input.sourceFingerprint,\n owner: { runId: input.runId, executionToken: input.executionToken },\n }\n}\n\n/** Snapshot application parameters independently of worker-owned sandbox state. */\nexport function snapshotAgentThreadSandboxParams(value: unknown): AgentThreadSandboxParams {\n if (!isPlainRecord(value) || !isJsonObject(value)) {\n throw new AgentStorageError(\n \"invalid_input\",\n \"[Sixb] Thread sandbox must contain only JSON params.\"\n )\n }\n return structuredClone(value)\n}\n\n/**\n * The users an add actually adds: those not already taking part. Providers call it under the\n * thread's lock with the participants they read there, so the cap holds across concurrent adds.\n * Who may be added is the caller's decision; this enforces only the cap.\n */\nexport function participantsToAdd(\n input: AddAgentThreadParticipantsInput,\n existing: readonly AgentThreadParticipantRecord[],\n prefix = \"Sixb\"\n): readonly UserPrincipal[] {\n const taken = new Set(existing.map((participant) => participant.principal.id))\n const added = input.principals.filter((principal) => !taken.has(principal.id))\n\n if (existing.length + added.length > input.maxParticipants) {\n throw new AgentStorageError(\n \"participant_limit\",\n `[${prefix}] Agent thread '${input.threadId}' can have at most ${input.maxParticipants} participants.`\n )\n }\n\n return added\n}\n\n/**\n * Participants oldest first, then by user id and thread id compared as UTF-8 bytes: the order\n * PostgreSQL's \"C\" collation and SQLite's binary one give, so every provider lists them alike.\n */\nexport function compareAgentThreadParticipants(\n left: AgentThreadParticipantRecord,\n right: AgentThreadParticipantRecord\n): number {\n return (\n left.addedAt.getTime() - right.addedAt.getTime() ||\n Buffer.compare(Buffer.from(left.principal.id), Buffer.from(right.principal.id)) ||\n Buffer.compare(Buffer.from(left.threadId), Buffer.from(right.threadId))\n )\n}\n\nconst ARTIFACT_ID_TOKEN = /art_[0-9a-z]{10}/g\n\n/**\n * Text with each artifact id the copies map replaced by its copy's: a copied message's parts, as\n * JSON, or a summary. Ids are fixed-length tokens, so one never matches inside another.\n */\nexport function remapArtifactIds(\n text: string,\n copies: Readonly<Record<string, string>> | undefined\n): string {\n if (!copies || Object.keys(copies).length === 0) return text\n return text.replace(ARTIFACT_ID_TOKEN, (id) => copies[id] ?? id)\n}\n\n/** What a fork reads from its source thread, inside the provider's transaction. */\nexport interface AgentThreadForkSource {\n /** The active run's trigger message, when a turn is running. */\n readonly triggerMessageId?: string\n /**\n * Every message of the source, ordered by ascending `seq`. `counted: false` marks one the thread\n * does not count ({@link countsAsThreadMessage}); a provider reads it from the parts it copies.\n */\n readonly messages: readonly (Pick<AgentMessageRecord, \"id\" | \"seq\"> & {\n readonly counted?: boolean\n })[]\n /** Every checkpoint of the source, latest first, in `getLatest` order. */\n readonly checkpoints: readonly AgentContextCheckpointRecord[]\n}\n\n/** The rows a provider writes for a fork. */\nexport interface AgentThreadForkPlan {\n readonly thread: AgentThreadRecord\n /** The source messages to copy, in `seq` order, with the id of each copy. */\n readonly messages: readonly { readonly sourceId: string; readonly id: string }[]\n readonly checkpoint?: AgentContextCheckpointRecord\n}\n\n/**\n * Decide what a fork copies. While a turn is running, the fork copies what came before its trigger\n * message, so the copy never has a gap; otherwise it copies everything. Copies keep their `seq`,\n * so the latest checkpoint whose observed head was copied projects unchanged.\n *\n * The plan mints the ids of the copies: which messages are copied is only known here, under the\n * provider's lock, so the caller cannot supply them.\n */\n/**\n * Whether a message counts in its thread's `messageCount`, which reads as what the conversation\n * shows. The message Sixb writes to resume a paused turn carries only how its calls ended, which the\n * chat shows on their cards: it is not counted.\n */\nexport function countsAsThreadMessage(message: Pick<AgentMessageRecord, \"parts\">): boolean {\n return !(\n message.parts.length > 0 && message.parts.every((part) => part.type === \"approval-outcome\")\n )\n}\n\nexport function planAgentThreadFork(\n input: ForkAgentThreadInput,\n source: AgentThreadForkSource,\n prefix = \"Sixb\"\n): AgentThreadForkPlan {\n const createdAt = new Date(input.createdAt ?? new Date())\n const sandboxState = forkedSandboxState(input, createdAt, prefix)\n\n const trigger = source.messages.find((message) => message.id === source.triggerMessageId)\n const copied =\n trigger === undefined\n ? source.messages\n : source.messages.filter((message) => message.seq < trigger.seq)\n const lastCopiedSeq = copied.at(-1)?.seq ?? 0\n\n const checkpoint = source.checkpoints.find(\n (candidate) => candidate.observedHeadSeq <= lastCopiedSeq\n )\n\n const thread: AgentThreadRecord = {\n id: input.id,\n projectId: input.projectId,\n kind: \"conversation\",\n ownerPrincipal: structuredClone(input.ownerPrincipal),\n ...(input.title === undefined ? {} : { title: input.title }),\n ...(input.sandboxParams === undefined\n ? {}\n : { sandboxParams: snapshotAgentThreadSandboxParams(input.sandboxParams) }),\n ...(sandboxState === undefined ? {} : { sandboxState }),\n status: \"active\",\n activeRunId: null,\n // No `lastMessageAt` until the fork's first new message: threads sort by it, else by their\n // creation, so a fork of an old conversation sorts with what its owner just did.\n messageCount: copied.filter((message) => message.counted !== false).length,\n createdAt,\n updatedAt: createdAt,\n }\n\n return {\n thread,\n messages: copied.map((message) => ({ sourceId: message.id, id: createAgentMessageId() })),\n ...(checkpoint === undefined\n ? {}\n : {\n checkpoint: {\n ...copyCheckpoint(checkpoint, input.id),\n summary: remapArtifactIds(checkpoint.summary, input.artifactCopies),\n },\n }),\n }\n}\n\n/**\n * The copy starts the fork's chain: its predecessors stay in the source. Its `createdByRunId`\n * still names the source run, under a foreign key that restricts deletion: deleting runs or\n * threads later must account for the forks that copied their checkpoints.\n */\nfunction copyCheckpoint(\n checkpoint: AgentContextCheckpointRecord,\n threadId: string\n): AgentContextCheckpointRecord {\n const { previousCheckpointId: _previous, ...copied } = structuredClone(checkpoint)\n return { ...copied, id: createCopiedAgentContextCheckpointId(), threadId }\n}\n\n/** A fresh sandbox, reset at the fork, so the Agent knows earlier local files are not there. */\nfunction forkedSandboxState(\n input: ForkAgentThreadInput,\n createdAt: Date,\n prefix: string\n): AgentThreadSandboxState | undefined {\n if ((input.sandboxParams === undefined) !== (input.sandboxName === undefined)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] A forked thread needs a sandbox name exactly when it has sandbox params.`\n )\n }\n\n if (input.sandboxName === undefined) return undefined\n\n if (!SANDBOX_NAME_PATTERN.test(input.sandboxName)) {\n throw new AgentStorageError(\"invalid_input\", `[${prefix}] Sandbox name is invalid.`)\n }\n\n return {\n name: input.sandboxName,\n status: \"new\",\n initialized: false,\n resetAt: createdAt.toISOString(),\n }\n}\n\n/** Validate the provider-neutral model selection captured for a conversational turn. */\nexport function assertConversationAgentRunSpec(\n spec: ConversationAgentRunSpec,\n prefix = \"Sixb\"\n): void {\n if (!isRecord(spec) || !isRecord(spec.model)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run spec must contain a model reference.`\n )\n }\n for (const [name, value] of [\n [\"model.provider\", spec.model.provider],\n [\"model.modelId\", spec.model.modelId],\n ] as const) {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run '${name}' must not be empty.`\n )\n }\n }\n if (spec.reasoning !== undefined && !isModelReasoning(spec.reasoning)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent reasoning must be one of: ${AGENT_REASONING_LEVELS.join(\", \")}, or a nonnegative budgetTokens object.`\n )\n }\n\n if (spec.tier !== undefined && !isLanguageModelTier(spec.tier)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run 'tier' must be one of: ${LANGUAGE_MODEL_TIERS.join(\", \")}.`\n )\n }\n if (spec.tierProbabilities !== undefined && !isTierProbabilities(spec.tierProbabilities)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run 'tierProbabilities' must give each tier a probability.`\n )\n }\n\n for (const [name, value] of [\n [\"timeZone\", spec.timeZone],\n [\"locale\", spec.locale],\n ] as const) {\n if (value !== undefined && (typeof value !== \"string\" || value.trim().length === 0)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run '${name}' must be a non-empty string.`\n )\n }\n }\n assertApprovalModeField(spec.approvalMode, \"Conversational Agent run\", prefix)\n}\n\nexport function isAgentApprovalMode(value: unknown): value is AgentApprovalMode {\n return (AGENT_APPROVAL_MODES as readonly unknown[]).includes(value)\n}\n\n/** Validate a mode a store is asked to keep, before it writes anything. */\nexport function assertAgentApprovalModeInput(\n mode: unknown,\n prefix = \"Sixb\"\n): asserts mode is AgentApprovalMode {\n if (!isAgentApprovalMode(mode)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent approval mode must be one of: ${AGENT_APPROVAL_MODES.join(\", \")}.`\n )\n }\n}\n\nfunction assertApprovalModeField(value: unknown, owner: string, prefix: string): void {\n if (value !== undefined && !isAgentApprovalMode(value)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] ${owner} 'approvalMode' must be one of: ${AGENT_APPROVAL_MODES.join(\", \")}.`\n )\n }\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction isTierProbabilities(value: unknown): boolean {\n if (!isRecord(value) || Object.keys(value).length !== LANGUAGE_MODEL_TIERS.length) return false\n\n return LANGUAGE_MODEL_TIERS.every((tier) => {\n const probability = value[tier]\n return typeof probability === \"number\" && probability >= 0 && probability <= 1\n })\n}\n\n/** Validate the semantic link between a conversational Agent run and its immutable execution. */\nexport async function assertAgentRunExecution(input: {\n readonly executions: ExecutionStorage\n readonly projectId: string\n readonly executionId: string\n readonly runId: string\n}): Promise<ExecutionRecord> {\n const execution = await findAgentRunExecution({\n executions: input.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.runId,\n authority: { type: \"inherited\" },\n })\n if (!execution) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[Sixb] Execution '${input.executionId}' does not authorize Agent run '${input.runId}'.`\n )\n }\n return execution\n}\n\n/** Validate the provider-neutral payload of an idempotent child admission. */\nexport function assertCreateSubagentRunInput(input: CreateSubagentRunInput, prefix = \"Sixb\"): void {\n for (const [name, value] of [\n [\"id\", input.id],\n [\"projectId\", input.projectId],\n [\"executionId\", input.executionId],\n [\"parentRunId\", input.parentRunId],\n [\"parentExecutionToken\", input.parentExecutionToken],\n [\"spawnKey\", input.spawnKey],\n [\"model.provider\", input.spec.model.provider],\n [\"model.modelId\", input.spec.model.modelId],\n [\"task\", input.spec.task],\n [\"thread.id\", input.thread.id],\n [\"trigger.id\", input.trigger.id],\n ] as const) {\n if (value.trim().length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run '${name}' must not be empty.`\n )\n }\n }\n if (input.spawnKey.length > 128) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent spawn key must not exceed 128 characters.`\n )\n }\n for (const [name, value] of [\n [\"maxActiveChildren\", input.maxActiveChildren],\n [\"spec.maxSteps\", input.spec.maxSteps],\n ] as const) {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run '${name}' must be a positive safe integer.`\n )\n }\n }\n if (new Set(input.spec.toolNames).size !== input.spec.toolNames.length) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run tool names must be unique.`\n )\n }\n if (input.spec.reasoning !== undefined && !isModelReasoning(input.spec.reasoning)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent reasoning must be one of: ${AGENT_REASONING_LEVELS.join(\", \")}, or a nonnegative budgetTokens object.`\n )\n }\n assertApprovalModeField(input.spec.approvalMode, \"Subagent run\", prefix)\n\n assertSubagentRunFiles(input.spec.files, \"spec.files\", prefix)\n\n if (input.spec.toolNames.some((name) => !name.trim())) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run tool names must not be empty.`\n )\n }\n if (!Array.isArray(input.trigger.parts) || input.trigger.parts.length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run trigger must have at least one part.`\n )\n }\n if (input.createdAt && !Number.isFinite(input.createdAt.getTime())) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run createdAt must be a valid date.`\n )\n }\n}\n\n/** Exact semantic match required when a durable spawn key is replayed. */\nexport function subagentRunMatchesCreateInput(\n run: AgentRunRecord,\n input: CreateSubagentRunInput\n): run is SubagentRunRecord {\n return (\n run.kind === \"subagent\" &&\n run.id === input.id &&\n run.projectId === input.projectId &&\n run.executionId === input.executionId &&\n run.parentRunId === input.parentRunId &&\n run.spawnKey === input.spawnKey &&\n run.threadId === input.thread.id &&\n isDeepStrictEqual(run.spec, input.spec)\n )\n}\n\n/** Refuse what only a conversation does on a sub-agent's thread. */\nexport function assertConversationThreadRow(\n thread: Pick<AgentThreadRecord, \"id\" | \"kind\">,\n /** What is refused, completing \"only a conversation …\". */\n operation: string,\n prefix = \"Sixb\"\n): void {\n if (thread.kind === \"conversation\") return\n throw new AgentStorageError(\n \"thread_not_conversation\",\n `[${prefix}] Agent thread '${thread.id}' is a sub-agent's: only a conversation ${operation}.`\n )\n}\n\n/**\n * The thread a child's first run creates. Its conversation's owner owns it, and its run is active\n * in it from the start: the trigger is its first and only message.\n */\nexport function newSubagentThreadRecord(\n input: CreateSubagentRunInput,\n conversation: { readonly id: string; readonly ownerPrincipal: Principal },\n createdAt: Date\n): AgentThreadRecord {\n return {\n id: input.thread.id,\n projectId: input.projectId,\n kind: \"subagent\",\n parent: { threadId: conversation.id, spawnedBy: input.parentRunId, key: input.spawnKey },\n ownerPrincipal: structuredClone(conversation.ownerPrincipal),\n status: \"active\",\n activeRunId: input.id,\n lastMessageAt: createdAt,\n messageCount: 1,\n createdAt,\n updatedAt: createdAt,\n }\n}\n\n/**\n * A later run of a child goes into its thread: the same child of the same conversation, and only\n * once the thread's previous run has ended, as in a conversation.\n */\nexport function assertSubagentThreadTakesRun(\n thread: AgentThreadRecord | null,\n input: CreateSubagentRunInput,\n conversationId: string,\n prefix = \"Sixb\"\n): asserts thread is AgentThreadRecord {\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[${prefix}] Agent thread '${input.thread.id}' not found for project '${input.projectId}'.`\n )\n }\n if (\n thread.kind !== \"subagent\" ||\n thread.parent?.threadId !== conversationId ||\n thread.parent.key !== input.spawnKey\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent thread '${thread.id}' is not the thread of child '${input.spawnKey}' of this conversation.`\n )\n }\n if (thread.activeRunId !== null) {\n throw new AgentStorageError(\n \"active_run_exists\",\n `[${prefix}] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`\n )\n }\n}\n\n/**\n * Validate what a finish keeps: a child's result once it succeeded. A child that paused, on its\n * held calls or on a question, may not have answered yet, so its text may be empty. A conversation\n * turn keeps none, and has no parent to wait for.\n */\nexport function assertAgentRunFinishPayload(\n kind: AgentRunRecord[\"kind\"],\n input: FinishAgentRunInput,\n runId: string,\n prefix = \"Sixb\"\n): void {\n if (kind === \"conversation\") {\n if (input.status === \"succeeded\" && input.result !== undefined) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run '${runId}' cannot persist a subagent result.`\n )\n }\n if (input.finishReason === \"awaiting_answer\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run '${runId}' has no parent to wait for: only a subagent finishes awaiting_answer.`\n )\n }\n return\n }\n\n if (input.status === \"succeeded\") {\n const paused =\n input.finishReason === \"awaiting_approval\" || input.finishReason === \"awaiting_answer\"\n assertSubagentRunResult(input.result, runId, prefix, paused)\n }\n}\n\n/**\n * Validate the small durable result returned by a successful child. A child that paused on its held\n * calls may not have answered yet, so its text may be empty.\n */\nexport function assertSubagentRunResult(\n result: SubagentRunResult | undefined,\n runId: string,\n prefix = \"Sixb\",\n paused = false\n): asserts result is SubagentRunResult {\n if (typeof result?.text !== \"string\" || (!paused && result.text.trim().length === 0)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Succeeded subagent run '${runId}' requires text.`\n )\n }\n assertSubagentRunFiles(result.files, \"result.files\", prefix)\n if (\n result.filesError !== undefined &&\n (typeof result.filesError !== \"string\" || !result.filesError.trim() || result.files?.length)\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run '${runId}' result.filesError must say why it returned no files.`\n )\n }\n}\n\n/** Each file a parent and its child exchange: a safe relative path, once, and a valid FileRef. */\nfunction assertSubagentRunFiles(\n files: readonly SubagentRunFile[] | undefined,\n field: string,\n prefix: string\n): void {\n if (files === undefined) return\n\n if (!Array.isArray(files)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run ${field} must be a list.`\n )\n }\n\n const paths = new Set<string>()\n for (const file of files) {\n const segments: readonly string[] = typeof file?.path === \"string\" ? file.path.split(\"/\") : []\n const safe =\n segments.length > 0 &&\n !file.path.includes(\"\\0\") &&\n segments.every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\")\n if (!safe || paths.has(file.path) || !isFileRef(file.fileRef)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run ${field} must hold unique relative paths, each with a valid FileRef.`\n )\n }\n paths.add(file.path)\n }\n}\n\n/** Validate provider-independent checkpoint fields before entering a storage critical section. */\nexport function assertCreateAgentContextCheckpointInput(\n input: CreateAgentContextCheckpointInput,\n prefix = \"Sixb\"\n): void {\n for (const [name, value] of [\n [\"id\", input.id],\n [\"projectId\", input.projectId],\n [\"threadId\", input.threadId],\n [\"createdByRunId\", input.createdByRunId],\n [\"executionToken\", input.executionToken],\n [\"summary\", input.summary],\n [\"summaryModelId\", input.summaryModelId],\n ] as const) {\n if (value.trim().length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint '${name}' must not be empty.`\n )\n }\n }\n\n if (input.summaryFormatVersion !== 1) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint summary format version must be 1.`\n )\n }\n if (input.reason !== \"threshold\" && input.reason !== \"overflow\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint reason must be 'threshold' or 'overflow'.`\n )\n }\n if (\n input.expectedPreviousCheckpointId !== null &&\n input.expectedPreviousCheckpointId.trim().length === 0\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint expected previous id must not be empty.`\n )\n }\n if (input.createdAt && !Number.isFinite(input.createdAt.getTime())) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint createdAt must be a valid date.`\n )\n }\n\n for (const [name, value, minimum] of [\n [\"expectedHeadSeq\", input.expectedHeadSeq, 1],\n [\"summarizedThroughSeq\", input.summarizedThroughSeq, 1],\n [\"observedHeadSeq\", input.observedHeadSeq, 1],\n [\"estimatedInputTokensBefore\", input.estimatedInputTokensBefore, 0],\n [\"estimatedInputTokensAfter\", input.estimatedInputTokensAfter, 0],\n ] as const) {\n if (!Number.isSafeInteger(value) || value < minimum) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint '${name}' must be a safe integer greater than or equal to ${minimum}.`\n )\n }\n }\n\n if (input.observedHeadSeq !== input.expectedHeadSeq) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint observed head must equal its expected message head.`\n )\n }\n if (input.summarizedThroughSeq >= input.observedHeadSeq) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint must retain the triggering head message.`\n )\n }\n}\n\n/** Assert that the current delivery still owns the active conversational run. */\nexport function assertAgentContextCheckpointAuthority(input: {\n readonly create: CreateAgentContextCheckpointInput\n readonly run: AgentRunRecord | null\n readonly thread: AgentThreadRecord | null\n readonly prefix?: string\n}): asserts input is typeof input & {\n readonly run: AgentRunRecord\n readonly thread: AgentThreadRecord\n} {\n const { create, run, thread } = input\n const prefix = input.prefix ?? \"Sixb\"\n if (!run) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[${prefix}] Agent run '${create.createdByRunId}' not found for project '${create.projectId}'.`\n )\n }\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[${prefix}] Agent thread '${create.threadId}' not found for project '${create.projectId}'.`\n )\n }\n if (run.kind !== \"conversation\" || run.threadId !== create.threadId) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent run '${run.id}' does not belong to thread '${create.threadId}'.`\n )\n }\n if (run.status !== \"running\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent run '${run.id}' is not running (status '${run.status}').`\n )\n }\n if (!run.execution || run.execution.token !== create.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[${prefix}] Execution token is no longer current on agent run '${run.id}'.`\n )\n }\n if (thread.activeRunId !== run.id) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent run '${run.id}' no longer owns thread '${thread.id}'.`\n )\n }\n}\n\n/** Assert both compare-and-swap anchors and the retained-turn boundary. */\nexport function assertAgentContextCheckpointAnchors(input: {\n readonly create: CreateAgentContextCheckpointInput\n readonly latest: AgentContextCheckpointRecord | null\n readonly headSeq: number\n readonly firstRetained: AgentMessageRecord | null\n readonly prefix?: string\n}): void {\n const { create, latest, headSeq, firstRetained } = input\n const prefix = input.prefix ?? \"Sixb\"\n if (headSeq !== create.expectedHeadSeq) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent thread '${create.threadId}' message head changed from ${create.expectedHeadSeq} to ${headSeq}.`\n )\n }\n\n const latestId = latest?.id ?? null\n if (latestId !== create.expectedPreviousCheckpointId) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent thread '${create.threadId}' checkpoint head changed.`\n )\n }\n if (latest && create.summarizedThroughSeq <= latest.summarizedThroughSeq) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint boundary must advance beyond sequence ${latest.summarizedThroughSeq}.`\n )\n }\n if (!firstRetained || firstRetained.seq !== create.summarizedThroughSeq + 1) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent context checkpoint boundary does not align with stored thread messages.`\n )\n }\n if (firstRetained.role !== \"user\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint must retain a complete turn beginning with a user message.`\n )\n }\n}\n\n/** Validate the mutable anchors again before returning an idempotently created checkpoint. */\nexport function assertAgentContextCheckpointReplayState(input: {\n readonly create: CreateAgentContextCheckpointInput\n readonly existing: AgentContextCheckpointRecord\n readonly latest: AgentContextCheckpointRecord | null\n readonly headSeq: number\n readonly prefix?: string\n}): void {\n const prefix = input.prefix ?? \"Sixb\"\n if (input.headSeq !== input.create.expectedHeadSeq) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent thread '${input.create.threadId}' message head changed from ${input.create.expectedHeadSeq} to ${input.headSeq}.`\n )\n }\n if (input.latest?.id !== input.existing.id) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent thread '${input.create.threadId}' checkpoint head changed after '${input.existing.id}'.`\n )\n }\n}\n\n/** Compare the durable semantic payload; delivery token and generated timestamp are not content. */\nexport function agentContextCheckpointMatchesCreateInput(\n record: AgentContextCheckpointRecord,\n input: CreateAgentContextCheckpointInput\n): boolean {\n return (\n record.id === input.id &&\n record.projectId === input.projectId &&\n record.threadId === input.threadId &&\n record.createdByRunId === input.createdByRunId &&\n (record.previousCheckpointId ?? null) === input.expectedPreviousCheckpointId &&\n record.reason === input.reason &&\n record.summary === input.summary &&\n record.summaryFormatVersion === input.summaryFormatVersion &&\n record.summarizedThroughSeq === input.summarizedThroughSeq &&\n record.observedHeadSeq === input.observedHeadSeq &&\n record.estimatedInputTokensBefore === input.estimatedInputTokensBefore &&\n record.estimatedInputTokensAfter === input.estimatedInputTokensAfter &&\n record.summaryModelId === input.summaryModelId\n )\n}\n\n/** Validate the fields of a save that storage relies on, before entering its transaction. */\nexport function assertSaveAgentMemoryInput(input: SaveAgentMemoryInput, prefix = \"Sixb\"): void {\n const fail = (message: string): never => {\n throw new AgentStorageError(\"invalid_input\", `[${prefix}] Agent memory ${message}`)\n }\n if (input.projectId.trim().length === 0) fail(\"project id must not be empty.\")\n if (input.repoId.trim().length === 0) fail(\"repo id must not be empty.\")\n if (!Number.isSafeInteger(input.baseRevision) || input.baseRevision < 0) {\n fail(\"base revision must be a non-negative integer.\")\n }\n if (input.message.trim().length === 0) fail(\"save message must not be empty.\")\n if (input.changes.length === 0) fail(\"save must change at least one file.\")\n const paths = new Set<string>()\n for (const change of input.changes) {\n if (change.path.length === 0) fail(\"paths must not be empty.\")\n if (paths.has(change.path)) fail(`save changes '${change.path}' more than once.`)\n paths.add(change.path)\n }\n if (input.createdAt && !Number.isFinite(input.createdAt.getTime())) {\n fail(\"save time must be a valid date.\")\n }\n}\n\n/** A path's highest-revision version; `contents: null` when that revision deleted it. */\nexport interface LatestAgentMemoryFile {\n readonly revision: number\n readonly contents: string | null\n}\n\n/**\n * The changes of a save that would overwrite another save's work, as their files are now: every\n * change when the repo is behind the base revision (it was deleted since), otherwise each change\n * whose path was written after the base revision. Ordered by path.\n */\nexport function agentMemoryConflicts(\n input: SaveAgentMemoryInput,\n head: number,\n latest: ReadonlyMap<string, LatestAgentMemoryFile>\n): AgentMemoryChange[] {\n return input.changes\n .filter(\n (change) =>\n input.baseRevision > head || (latest.get(change.path)?.revision ?? 0) > input.baseRevision\n )\n .map((change) => ({ path: change.path, contents: latest.get(change.path)?.contents ?? null }))\n .sort((left, right) => compareAgentMemoryPaths(left.path, right.path))\n}\n\n/** Code-unit order, as SQLite and Postgres (with `COLLATE \"C\"`) compare paths. */\nexport function compareAgentMemoryPaths(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\n/** File versions written before this time leave the history once a newer version exists. */\nexport function agentMemoryHistoryCutoff(savedAt: Date): Date {\n return new Date(savedAt.getTime() - AGENT_MEMORY_HISTORY_DAYS * 24 * 60 * 60 * 1000)\n}\n\n// ── approvals ─────────────────────────────────────────────────────────────────────────────────\n\n/** An approval that still answers for its call key: a settled one asks again. */\nexport const LIVE_AGENT_APPROVAL_STATUSES = [\n \"pending\",\n \"approved\",\n \"denied\",\n] as const satisfies readonly AgentApprovalStatus[]\n\n/**\n * Whether an approval keeps its run paused: still waiting, or decided and not reported to the model\n * yet. A run finishes `awaiting_approval` only while it holds one.\n */\nexport function agentApprovalHoldsRun(approval: AgentApprovalRecord, runId: string): boolean {\n return (\n (approval.runId === runId || approval.callerRunId === runId) &&\n (LIVE_AGENT_APPROVAL_STATUSES as readonly string[]).includes(approval.status) &&\n approval.reportedInMessageId === undefined\n )\n}\n\n/** Refuse a paused finish that holds no call, or a paused finish that did not succeed. */\nexport function assertAwaitingApprovalFinish(input: {\n readonly runId: string\n readonly status: string\n readonly holdsApproval: boolean\n readonly prefix?: string\n}): void {\n const prefix = input.prefix ?? \"Sixb\"\n if (input.status !== \"succeeded\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent run '${input.runId}' can only pause for approval when it succeeds.`\n )\n }\n if (!input.holdsApproval) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent run '${input.runId}' holds no call waiting for approval, so it cannot finish awaiting one.`\n )\n }\n}\n\n/**\n * Whether a run can have approvals: its mode holds some calls. A turn from before approval modes,\n * or in `auto`, holds none, and neither do its children, which copy its mode.\n */\nexport function agentRunMayHoldCalls(run: AgentRunRecord): boolean {\n return (AGENT_HOLDING_APPROVAL_MODES as readonly unknown[]).includes(run.spec?.approvalMode)\n}\n\n/** Whether a stop request reaches this approval. */\nexport function agentApprovalStops(\n approval: AgentApprovalRecord,\n input: StopAgentApprovalsInput\n): boolean {\n return (\n approval.projectId === input.projectId &&\n approval.threadId === input.threadId &&\n approval.reportedInMessageId === undefined &&\n (input.runId === undefined || approval.runId === input.runId) &&\n (input.requestedBy === undefined ||\n (approval.requestedBy.type === input.requestedBy.type &&\n approval.requestedBy.id === input.requestedBy.id))\n )\n}\n\n/** Whether a repair pass has work on this approval; providers run the same filter in SQL. */\nexport function agentApprovalRepairable(\n approval: AgentApprovalRecord,\n claimableBefore: Date\n): boolean {\n const unfinished =\n approval.status === \"approved\" &&\n approval.outcome === undefined &&\n (approval.executionClaimedAt ?? approval.decidedAt ?? new Date(0)) <= claimableBefore\n const resumable =\n (approval.status === \"approved\" || approval.status === \"denied\") &&\n approval.reportedInMessageId === undefined &&\n approval.turnStoppedAt === undefined\n return unfinished || resumable\n}\n\n/** Whether an approved call without an outcome can be claimed now. */\nexport function agentApprovalClaimable(approval: AgentApprovalRecord, staleBefore: Date): boolean {\n return (\n approval.status === \"approved\" &&\n approval.outcome === undefined &&\n (approval.executionClaimedAt ?? approval.decidedAt ?? new Date(0)) <= staleBefore\n )\n}\n\n/** The run id the call names: unique among a thread's live approvals. */\nexport function agentApprovalCallKey(call: AgentApprovalCall): string {\n return call.kind === \"action\" ? call.actionRunId : call.workflowRunId\n}\n\nexport function assertRequestAgentApprovalInput(\n input: RequestAgentApprovalInput,\n prefix = \"Sixb\"\n): void {\n for (const [name, value] of [\n [\"id\", input.id],\n [\"projectId\", input.projectId],\n [\"runId\", input.runId],\n [\"callerRunId\", input.callerRunId],\n [\"executionToken\", input.executionToken],\n [\"call key\", agentApprovalCallKey(input.call)],\n ] as const) {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent approval '${name}' must not be empty.`\n )\n }\n }\n if (!(AGENT_HOLDING_APPROVAL_MODES as readonly unknown[]).includes(input.mode)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent approval mode must be one of: ${AGENT_HOLDING_APPROVAL_MODES.join(\", \")}.`\n )\n }\n}\n\n/**\n * Fence a held call: the caller run is running with the request's token, and is the turn or one of\n * its children. Returns the turn's thread.\n */\nexport function assertAgentApprovalCaller(input: {\n readonly request: RequestAgentApprovalInput\n readonly turn: AgentRunRecord | null\n readonly caller: AgentRunRecord | null\n readonly prefix?: string\n}): string {\n const { request, turn, caller } = input\n const prefix = input.prefix ?? \"Sixb\"\n if (!turn || !caller) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[${prefix}] Agent run '${turn ? request.callerRunId : request.runId}' not found for project '${request.projectId}'.`\n )\n }\n if (turn.kind !== \"conversation\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent approval run '${turn.id}' must be a conversation turn.`\n )\n }\n if (caller.id !== turn.id && !(caller.kind === \"subagent\" && caller.parentRunId === turn.id)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent run '${caller.id}' does not belong to turn '${turn.id}'.`\n )\n }\n if (caller.status !== \"running\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent run '${caller.id}' is not running (status '${caller.status}').`\n )\n }\n if (!caller.execution || caller.execution.token !== request.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[${prefix}] Execution token is no longer current on agent run '${caller.id}'.`\n )\n }\n return turn.threadId\n}\n\n/** The approval a request creates, before any provider writes it. */\nexport function newAgentApprovalRecord(\n input: RequestAgentApprovalInput,\n threadId: string\n): AgentApprovalRecord {\n return {\n id: input.id,\n projectId: input.projectId,\n threadId,\n runId: input.runId,\n callerRunId: input.callerRunId,\n requestedBy: structuredClone(input.requestedBy),\n mode: input.mode,\n callKey: agentApprovalCallKey(input.call),\n call: structuredClone(input.call),\n status: \"pending\",\n createdAt: new Date(input.createdAt ?? new Date()),\n expiresAt: new Date(input.expiresAt),\n }\n}\n\n/** Whether an approval matches a list filter; providers run the same filter in SQL. */\nexport function agentApprovalMatches(\n approval: AgentApprovalRecord,\n input: ListAgentApprovalsInput\n): boolean {\n return (\n approval.projectId === input.projectId &&\n (input.threadId === undefined || approval.threadId === input.threadId) &&\n (input.runId === undefined || approval.runId === input.runId) &&\n (input.requestedBy === undefined ||\n (approval.requestedBy.type === input.requestedBy.type &&\n approval.requestedBy.id === input.requestedBy.id)) &&\n (input.statuses === undefined || input.statuses.includes(approval.status)) &&\n (input.reported === undefined ||\n (approval.reportedInMessageId !== undefined) === input.reported)\n )\n}\n",
|
|
6
|
-
"import { createHash, randomUUID } from \"node:crypto\"\n\n/**\n * Id helpers for agent persistence. Threads, the run id, and the user (trigger) message are minted\n * by the trigger; the queued run is persisted with the user message, and the assistant message id\n * is minted when the turn finalizes. Prefixes make ids self-describing in logs.\n */\n\nexport function createAgentThreadId(): string {\n return `agt_thr_${randomUUID()}`\n}\n\n/** A fresh provider name, scoped to one project's thread; never a filesystem revision. */\nexport function createAgentThreadSandboxName(projectId: string, threadId: string): string {\n const digest = createHash(\"sha256\")\n .update(JSON.stringify([projectId, threadId, randomUUID()]))\n .digest(\"hex\")\n return `sixb-sb-${digest}`\n}\n\nexport function createAgentRunId(): string {\n return `agt_run_${randomUUID()}`\n}\n\n/** One stable child identity per parent-selected spawn key. */\nexport function createSubagentRunId(parentRunId: string, spawnKey: string): string {\n return `agt_run_child_${spawnDigest(parentRunId, spawnKey)}`\n}\n\n/**\n * The thread a child works in, named after the turn that spawned it and its key. It shares its\n * first run's digest: migration `subagent-threads` names the threads of earlier children so.\n */\nexport function createSubagentThreadId(spawningRunId: string, spawnKey: string): string {\n return `agt_thr_child_${spawnDigest(spawningRunId, spawnKey)}`\n}\n\nfunction spawnDigest(runId: string, spawnKey: string): string {\n return createHash(\"sha256\").update(runId).update(\"\\0\").update(spawnKey).digest(\"hex\")\n}\n\n/** Stable execution identity paired with a deterministic child run. */\nexport function createSubagentExecutionId(runId: string): string {\n return `exec_${runId}`\n}\n\nexport function createAgentMessageId(): string {\n return `agt_msg_${randomUUID()}`\n}\n\n/** One deterministic context-checkpoint identity per conversational run. */\nexport function agentContextCheckpointId(runId: string): string {\n return `agt_ctx_${runId}`\n}\n\n/** A checkpoint copied into a fork; the source's checkpoint keeps its run-derived id. */\nexport function createCopiedAgentContextCheckpointId(): string {\n return `agt_ctx_copy_${randomUUID()}`\n}\n\n/** A queue delivery's fencing token for writes to an `agent_runs` record. */\nexport function createAgentRunExecutionToken(): string {\n return `agt_exec_${randomUUID()}`\n}\n",
|
|
7
|
-
"import type { ActionsRuntime } from \"../actions/execution\"\nimport type { BlobBody, FileRef, OpenedFileRef } from \"../blob-storage\"\nimport type { ConnectorRuntime } from \"../connectors\"\nimport type { JsonPrimitive, JsonValue, ReadonlyJsonValue } from \"../json\"\nimport type { Logger } from \"../logging\"\nimport { type LanguageModelRef, MODEL_REASONING_LEVELS, type ModelReasoning } from \"../models\"\nimport type { ModelsRuntime } from \"../models/generation-types\"\nimport type { InferSchema } from \"../ontology/inference\"\nimport type { Schema } from \"../ontology/types\"\nimport type { ObjectReader } from \"../runtime/types\"\nimport type { UsersRuntime } from \"../users\"\n\nexport type {\n AgentContextEntryInput,\n AgentContextInput,\n AgentContextOrigin,\n AgentContextPart,\n} from \"./context/entries\"\n\n/** Public capability reference used by security grants such as `can.run(agent)`. */\nexport interface AgentReference {\n readonly kind: \"agent\"\n readonly usage: AgentUsageReference\n readonly threads: AgentThreadsReference\n readonly memory: AgentMemoryReference\n}\n\n/** Project-wide AI accounting and limit capability, independent of permission to run the Agent. */\nexport interface AgentUsageReference {\n readonly kind: \"aiUsage\"\n}\n\n/** Every user's conversations with the Agent, as `can.observe(agent.threads)` reads them. */\nexport interface AgentThreadsReference {\n readonly kind: \"agentThreads\"\n}\n\n/** The project's shared Agent memory, which every conversation reads. */\nexport interface AgentMemoryReference {\n readonly kind: \"agentMemory\"\n}\n\n/** Public metadata for the project's conversational Agent. */\nexport interface AgentDescriptor {\n readonly name: string\n readonly model: LanguageModelRef\n}\n\nexport type AgentReasoning = ModelReasoning\n\nexport const AGENT_REASONING_LEVELS = MODEL_REASONING_LEVELS\n\ntype Simplify<T> = { [K in keyof T]: T[K] } & {}\ntype JsonifyAgentToolInput<T> = unknown extends T\n ? ReadonlyJsonValue\n : T extends Date\n ? string\n : T extends readonly (infer TItem)[]\n ? readonly JsonifyAgentToolInput<TItem>[]\n : T extends JsonPrimitive\n ? T\n : T extends object\n ? { readonly [K in keyof T]: JsonifyAgentToolInput<T[K]> }\n : never\n\n/** A model-facing object shape expressed with Sixb's schema DSL. */\nexport type AgentToolInputSchema = Readonly<Record<string, Schema>>\n\n/** Infer the handler input represented by an agent tool schema. */\nexport type InferAgentToolInputSchema<TInput extends AgentToolInputSchema> =\n string extends keyof TInput\n ? Readonly<Record<string, unknown>>\n : Simplify<{\n readonly [K in keyof TInput]: JsonifyAgentToolInput<InferSchema<TInput[K]>>\n }>\n\n/** Identifies the conversational, workflow, or child Agent execution that invoked a tool. */\nexport type AgentToolRunInfo =\n | {\n readonly kind: \"conversation\"\n readonly id: string\n readonly threadId: string\n }\n | {\n readonly kind: \"subagent\"\n readonly id: string\n readonly parentRunId: string\n }\n | {\n readonly kind: \"workflow\"\n readonly id: string\n readonly workflowId: string\n readonly stepId: string\n }\n\n/** Input accepted by the run-scoped file publisher exposed to agent tools. */\nexport interface AgentToolFilePutInput {\n readonly body: BlobBody\n readonly fileName: string\n readonly mediaType?: string\n}\n\n/** A file a tool stored durably, and the path of its copy inside the current run sandbox. */\nexport interface AgentToolFile {\n readonly fileRef: FileRef\n readonly sandboxPath: string\n}\n\n/** The narrow file-writing surface available to an agent tool call. */\nexport interface AgentToolFiles {\n put(input: AgentToolFilePutInput): Promise<AgentToolFile>\n}\n\n/**\n * The files attached to the run that invoked a tool: the messages of a chat's thread, or the input\n * files of a workflow AI task. A child Agent has none.\n */\nexport interface AgentToolAttachments {\n /**\n * Open an attachment by the `key` the Agent sees in `$SIXB_ATTACHMENTS`. Returns null when its\n * stored file is gone, and throws an `AgentToolPublicError` for a key that is not one of this\n * run's attachments.\n */\n open(key: string): Promise<OpenedFileRef | null>\n}\n\nexport type AgentToolTextContent = {\n readonly type: \"text\"\n readonly text: string\n}\n\nexport type AgentToolFileContent = {\n readonly type: \"file\"\n readonly fileRef: FileRef\n}\n\n/** Durable model-facing content returned by a file-aware tool. */\nexport type AgentToolContent = AgentToolTextContent | AgentToolFileContent\n\n/**\n * A file-aware tool result. The tag distinguishes this envelope from an ordinary JSON result while\n * keeping the whole value safe to persist in the durable tool-call trace.\n */\nexport type AgentToolResult = {\n readonly kind: \"agentToolResult\"\n readonly content: readonly AgentToolContent[]\n}\n\n/**\n * The run's domain SDK as an agent tool sees it. Unlike workflow steps and actions, it acts as the\n * run's requester: the signed-in user in a chat, that same user in a child Agent, and the step's\n * groups in a workflow AI task.\n *\n * A structural view of the public `Sixb` SDK, like `WorkflowRuntimeFacade`: the handler receives the\n * run's bound SDK, and this type guides it to what a tool should do. It reads objects and changes\n * them by requesting actions, which validate and record the change. Authority comes from the run,\n * not from this view.\n */\nexport interface AgentToolRuntimeFacade extends ObjectReader {\n readonly actions: ActionsRuntime\n readonly models: ModelsRuntime\n readonly connector: ConnectorRuntime\n readonly users: UsersRuntime\n}\n\n/** The narrow, run-scoped surface passed to an agent tool handler. */\nexport interface AgentToolRunContext<\n TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,\n> {\n readonly input: TInput\n readonly toolCallId: string\n readonly signal: AbortSignal\n readonly run: AgentToolRunInfo\n readonly sixb: AgentToolRuntimeFacade\n readonly logger: Logger\n readonly files: AgentToolFiles\n readonly attachments: AgentToolAttachments\n}\n\n/** Agent tool handlers may return only values safe to persist in agent messages. */\nexport type AgentToolHandlerResult<\n TOutput extends ReadonlyJsonValue | AgentToolResult = ReadonlyJsonValue | AgentToolResult,\n> = TOutput | Promise<TOutput>\n\nexport type AgentToolHandler<\n TInput extends Readonly<Record<string, unknown>>,\n TOutput extends ReadonlyJsonValue | AgentToolResult = ReadonlyJsonValue | AgentToolResult,\n> = (context: AgentToolRunContext<TInput>) => AgentToolHandlerResult<TOutput>\n\n/**\n * Runtime definitions are stored heterogeneously. Keep variance erasure at this\n * boundary only; authoring through `run()` remains strictly contravariant.\n */\ntype StoredAgentToolHandler<TInput extends Readonly<Record<string, unknown>>> = {\n bivarianceHack(context: AgentToolRunContext<TInput>): JsonValue | Promise<JsonValue>\n}[\"bivarianceHack\"]\n\ndeclare const agentToolOutputValueType: unique symbol\n\n/** A reusable, inert model tool definition selected explicitly by an agent. */\nexport interface AgentToolDefinition<\n TName extends string = string,\n TInput extends AgentToolInputSchema = AgentToolInputSchema,\n TOutput extends ReadonlyJsonValue | AgentToolResult = ReadonlyJsonValue | AgentToolResult,\n> {\n readonly kind: \"agentTool\"\n readonly name: TName\n readonly description: string\n readonly input: TInput\n readonly handler: StoredAgentToolHandler<InferAgentToolInputSchema<TInput>>\n readonly [agentToolOutputValueType]?: TOutput\n}\n\n/** Infer the input received by a tool definition's handler. */\nexport type InferAgentToolInput<TTool extends AgentToolDefinition> = InferAgentToolInputSchema<\n TTool[\"input\"]\n>\n\n/**\n * Infer the output a chat receives from a tool: its handler's return value, saved on the message\n * and streamed live as is. A file-aware tool's output is its `AgentToolResult` envelope.\n */\nexport type InferAgentToolOutput<TTool extends AgentToolDefinition> =\n TTool extends AgentToolDefinition<string, AgentToolInputSchema, infer TOutput> ? TOutput : never\n\nexport interface AgentToolRunBuilder<TName extends string, TInput extends AgentToolInputSchema> {\n run<TOutput extends ReadonlyJsonValue | AgentToolResult>(\n handler: AgentToolHandler<InferAgentToolInputSchema<TInput>, TOutput>\n ): AgentToolDefinition<TName, TInput, TOutput>\n}\n\nexport interface AgentToolInputBuilder<TName extends string> {\n input<const TInput extends AgentToolInputSchema>(\n input: TInput\n ): AgentToolRunBuilder<TName, TInput>\n}\n\nexport interface AgentToolDescriptionBuilder<TName extends string> {\n description(description: string): AgentToolInputBuilder<TName>\n}\n",
|
|
8
|
-
"export type AgentStorageErrorCode =\n | \"thread_not_found\"\n /** A conversation's operation on a sub-agent's thread: a turn, a fork, a participant. */\n | \"thread_not_conversation\"\n | \"active_run_exists\"\n | \"active_child_limit\"\n | \"run_not_found\"\n | \"invalid_input\"\n | \"invalid_state\"\n | \"execution_lost\"\n | \"duplicate_id\"\n | \"participant_limit\"\n\n/**\n * Error for agent-storage invariants and invalid state transitions (single-flight, execution\n * ownership, run lifecycle, message append). Callers branch on `code` rather than message text.\n */\nexport class AgentStorageError extends Error {\n readonly name = \"AgentStorageError\"\n\n constructor(\n readonly code: AgentStorageErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n"
|
|
9
|
-
],
|
|
10
|
-
"mappings": ";;;;;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AM,IAAI;AAAA,IAChC,QAAQ;AAAA,IACR,WAAW,IAAI,KAAK,MAAM,aAAa,IAAI,IAAM;AAAA,IACjD,WAAW,IAAI,KAAK,MAAM,SAAS;AAAA,EACrC;AAAA;AAIK,SAAS,qBAAoB,CAClC,UACA,OACS;AAAA,EACT,OACE,SAAS,cAAc,MAAM,cAC5B,MAAM,aAAa,aAAa,SAAS,aAAa,MAAM,cAC5D,MAAM,UAAU,aAAa,SAAS,UAAU,MAAM,WACtD,MAAM,gBAAgB,aACpB,SAAS,YAAY,SAAS,MAAM,YAAY,QAC/C,SAAS,YAAY,OAAO,MAAM,YAAY,QACjD,MAAM,aAAa,aAAa,MAAM,SAAS,SAAS,SAAS,MAAM,OACvE,MAAM,aAAa,aACjB,SAAS,wBAAwB,cAAe,MAAM;AAAA;",
|
|
11
|
-
"debugId": "B924D384F542DD1B64756E2164756E21",
|
|
12
|
-
"names": []
|
|
13
|
-
}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/queues/errors.ts", "../src/queues/in-memory.ts", "../src/queues/indexed-heap.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"/**\n * Error for queue invariants and invalid queue operations.\n */\nexport class QueueError extends Error {\n readonly name = \"QueueError\"\n}\n",
|
|
6
|
-
"import { randomUUID } from \"node:crypto\"\nimport type { SixbErrorCode } from \"../errors/types\"\nimport { QueueError } from \"./errors\"\nimport { IndexedHeap } from \"./indexed-heap\"\nimport type {\n AgentQueueJob,\n AgentQueueJobFailureCode,\n ClaimedQueueJob,\n NewQueueJob,\n PipelineQueueJobFailureCode,\n PipelineRunRequestedQueueJob,\n ProjectionQueueJobFailureCode,\n ProjectionRunRequestedQueueJob,\n Queue,\n QueueJob,\n QueueJobFailure,\n Queues,\n SubagentQueueJob,\n SyncQueueJobFailureCode,\n SyncRunRequestedQueueJob,\n VectorIndexingQueueJob,\n WorkflowQueueJob,\n WorkflowQueueJobFailureCode,\n} from \"./types\"\n\ntype QueueRecordState = \"queued\" | \"completed\" | \"failed\"\n\ninterface QueueRecord<TQueueJob extends QueueJob = QueueJob> {\n readonly sequence: number\n readonly queueId: string\n job: TQueueJob\n availableAtMs: number\n readonly createdAtMs: number\n leaseExpiryMs: number | null\n // A leased job stays \"queued\" until a worker completes or fails it.\n state: QueueRecordState\n failure: QueueJobFailure | null\n leaseId: string | null\n claimedAt: string | null\n leaseExpiresAt: string | null\n}\n\nfunction assertNonEmpty(value: string, fieldName: string): void {\n if (value.trim().length === 0) {\n throw new QueueError(`[Sixb] Queue ${fieldName} must not be empty`)\n }\n}\n\nfunction parseTimestamp(value: string, fieldName: string): number {\n const timestamp = Date.parse(value)\n\n if (Number.isNaN(timestamp)) {\n throw new QueueError(`[Sixb] Queue ${fieldName} must be a valid timestamp`)\n }\n\n return timestamp\n}\n\nfunction assertPositiveNumber(value: number, fieldName: string): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw new QueueError(`[Sixb] Queue ${fieldName} must be greater than 0`)\n }\n}\n\nfunction clearLease(record: QueueRecord): void {\n record.leaseId = null\n record.claimedAt = null\n record.leaseExpiresAt = null\n record.leaseExpiryMs = null\n}\n\n// Best-effort ordering is part of the contract; this keeps the in-memory provider deterministic.\nfunction compareQueueRecords(left: QueueRecord, right: QueueRecord): number {\n const availableDifference = left.availableAtMs - right.availableAtMs\n if (availableDifference !== 0) return availableDifference\n const createdDifference = left.createdAtMs - right.createdAtMs\n if (createdDifference !== 0) return createdDifference\n\n return left.sequence - right.sequence\n}\n\nfunction createQueueJob<TQueueJob extends QueueJob>(\n projectId: string,\n newJob: NewQueueJob<TQueueJob>\n): TQueueJob {\n const createdAt = new Date().toISOString()\n const availableAt = newJob.availableAt ?? createdAt\n parseTimestamp(availableAt, \"availableAt\")\n\n return {\n id: newJob.id ?? randomUUID(),\n projectId,\n createdAt,\n availableAt,\n attempt: 0,\n metadata: newJob.metadata ? structuredClone(newJob.metadata) : undefined,\n type: newJob.type,\n payload: structuredClone(newJob.payload),\n } as TQueueJob\n}\n\nfunction leaseExpiresAtMs(record: QueueRecord): number | null {\n return record.leaseExpiryMs\n}\n\nfunction eligibleAt(record: QueueRecord): number {\n return Math.max(record.availableAtMs, record.leaseExpiryMs ?? -Infinity)\n}\n\n// Largest delay `setTimeout` accepts; a waiting claim that wakes early just waits again.\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\n\ninterface QueueLane {\n // Terminal records remain here for caller-id deduplication, never in the delivery indexes.\n readonly records: Map<string, QueueRecord>\n readonly ready: IndexedHeap<QueueRecord>\n readonly waiting: IndexedHeap<QueueRecord>\n /** Wakes claims waiting on this lane. */\n readonly waiters: Set<() => void>\n}\n\nfunction toClaimedQueueJob<TQueueJob extends QueueJob>(\n record: QueueRecord<TQueueJob>\n): ClaimedQueueJob<TQueueJob> {\n if (!record.leaseId || !record.claimedAt || !record.leaseExpiresAt) {\n throw new QueueError(`[Sixb] Queue job '${record.job.id}' is not currently leased`)\n }\n\n return {\n leaseId: record.leaseId,\n claimedAt: record.claimedAt,\n leaseExpiresAt: record.leaseExpiresAt,\n job: structuredClone(record.job),\n }\n}\n\nclass InMemoryQueueStore {\n private readonly projects = new Map<string, Map<string, QueueLane>>()\n private nextSequence = 1\n\n add<TQueueJob extends QueueJob>(projectId: string, queueId: string, job: TQueueJob): void {\n const lane = this.lane(projectId, queueId)\n const record: QueueRecord = {\n sequence: this.nextSequence++,\n queueId,\n job,\n availableAtMs: parseTimestamp(job.availableAt, \"job.availableAt\"),\n createdAtMs: parseTimestamp(job.createdAt, \"job.createdAt\"),\n leaseExpiryMs: null,\n state: \"queued\",\n failure: null,\n leaseId: null,\n claimedAt: null,\n leaseExpiresAt: null,\n }\n lane.records.set(job.id, record)\n this.schedule(projectId, record, Date.now())\n }\n\n find<TQueueJob extends QueueJob>(\n projectId: string,\n queueId: string,\n jobId: string\n ): QueueRecord<TQueueJob> | null {\n return (this.projects.get(projectId)?.get(queueId)?.records.get(jobId) ??\n null) as QueueRecord<TQueueJob> | null\n }\n\n schedule(projectId: string, record: QueueRecord, now: number): void {\n const lane = this.lane(projectId, record.queueId)\n if (record.state !== \"queued\") {\n lane.ready.delete(record)\n lane.waiting.delete(record)\n } else if (eligibleAt(record) <= now) {\n lane.waiting.delete(record)\n lane.ready.set(record)\n } else {\n lane.ready.delete(record)\n lane.waiting.set(record)\n }\n // Any change can make a job claimable or move the next due time; waiters look again.\n for (const wake of lane.waiters) wake()\n }\n\n /** Resolves when the lane changes, its next delayed job or lease comes due, or `signal` aborts. */\n waitForWork(projectId: string, queueId: string, signal: AbortSignal): Promise<void> {\n const lane = this.lane(projectId, queueId)\n const next = lane.waiting.peek()\n const dueInMs = next ? eligibleAt(next) - Date.now() : MAX_TIMER_DELAY_MS\n return new Promise((resolve) => {\n // Always armed: like a blocking read on a socket, a waiting claim keeps its process alive.\n const timer = setTimeout(wake, Math.min(dueInMs, MAX_TIMER_DELAY_MS))\n function wake(): void {\n clearTimeout(timer)\n lane.waiters.delete(wake)\n signal.removeEventListener(\"abort\", wake)\n resolve()\n }\n lane.waiters.add(wake)\n signal.addEventListener(\"abort\", wake, { once: true })\n })\n }\n\n takeReady<TQueueJob extends QueueJob>(\n projectId: string,\n queueId: string,\n now: number,\n limit: number\n ): QueueRecord<TQueueJob>[] {\n const lane = this.projects.get(projectId)?.get(queueId)\n if (!lane) return []\n // Wake delayed jobs and expired leases, then order all ready jobs by the original contract.\n // A lease expiry controls eligibility, not the priority of a redelivered job.\n while (lane.waiting.peek() && eligibleAt(lane.waiting.peek()!) <= now) {\n lane.ready.set(lane.waiting.pop()!)\n }\n const selected: QueueRecord[] = []\n while (selected.length < limit) {\n const record = lane.ready.peek()\n if (!record || record.availableAtMs > now) break\n lane.ready.pop()\n // A backwards wall-clock adjustment can make a previously expired lease live again.\n if (eligibleAt(record) > now) lane.waiting.set(record)\n else selected.push(record)\n }\n return selected as QueueRecord<TQueueJob>[]\n }\n\n private lane(projectId: string, queueId: string): QueueLane {\n let queues = this.projects.get(projectId)\n if (!queues) {\n queues = new Map()\n this.projects.set(projectId, queues)\n }\n let lane = queues.get(queueId)\n if (!lane) {\n lane = {\n records: new Map(),\n ready: new IndexedHeap(compareQueueRecords),\n waiting: new IndexedHeap(\n (left, right) => eligibleAt(left) - eligibleAt(right) || left.sequence - right.sequence\n ),\n waiters: new Set(),\n }\n queues.set(queueId, lane)\n }\n return lane\n }\n}\n\nclass InMemoryQueue<TQueueJob extends QueueJob, TFailureCode extends SixbErrorCode>\n implements Queue<TQueueJob, TFailureCode>\n{\n constructor(\n private readonly store: InMemoryQueueStore,\n private readonly queueId: string\n ) {\n assertNonEmpty(queueId, \"queueId\")\n }\n\n async enqueue(params: {\n projectId: string\n jobs: readonly NewQueueJob<TQueueJob>[]\n }): Promise<readonly TQueueJob[]> {\n assertNonEmpty(params.projectId, \"projectId\")\n\n if (params.jobs.length === 0) {\n return []\n }\n\n const createdJobs = params.jobs.map((job) => {\n if (job.id !== undefined) assertNonEmpty(job.id, \"job.id\")\n const existing = job.id\n ? this.store.find<TQueueJob>(params.projectId, this.queueId, job.id)\n : null\n if (existing) return existing.job\n\n const created = createQueueJob(params.projectId, job)\n this.store.add(params.projectId, this.queueId, created)\n return created\n })\n\n return createdJobs.map((job) => structuredClone(job))\n }\n\n async claim(params: {\n projectId: string\n workerId: string\n limit?: number\n leaseMs?: number\n signal?: AbortSignal\n }): Promise<readonly ClaimedQueueJob<TQueueJob>[]> {\n assertNonEmpty(params.projectId, \"projectId\")\n assertNonEmpty(params.workerId, \"workerId\")\n\n const limit = Math.trunc(params.limit ?? 1)\n if (!(limit > 0)) {\n return []\n }\n\n const leaseMs = params.leaseMs ?? 30_000\n assertPositiveNumber(leaseMs, \"leaseMs\")\n\n for (;;) {\n if (params.signal?.aborted) return []\n const now = Date.now()\n const claimedAt = new Date(now).toISOString()\n // Validate before removing candidates, and cache the same millisecond precision we return.\n const leaseExpiry = new Date(now + leaseMs)\n const leaseExpiresAt = leaseExpiry.toISOString()\n const claimable = this.store.takeReady<TQueueJob>(params.projectId, this.queueId, now, limit)\n if (claimable.length === 0 && params.signal) {\n await this.store.waitForWork(params.projectId, this.queueId, params.signal)\n continue\n }\n\n return claimable.map((record) => {\n // Attempts count claims so redelivery after lease expiry or retry is visible to workers.\n record.job = {\n ...record.job,\n attempt: record.job.attempt + 1,\n }\n record.leaseId = randomUUID()\n record.claimedAt = claimedAt\n record.leaseExpiresAt = leaseExpiresAt\n record.leaseExpiryMs = leaseExpiry.getTime()\n this.store.schedule(params.projectId, record, now)\n\n return toClaimedQueueJob(record)\n })\n }\n }\n\n async complete(params: { projectId: string; jobId: string; leaseId: string }): Promise<void> {\n const record = this.requireActiveLease(params)\n record.state = \"completed\"\n clearLease(record)\n this.store.schedule(params.projectId, record, Date.now())\n }\n\n async retry(params: {\n projectId: string\n jobId: string\n leaseId: string\n availableAt?: string\n }): Promise<void> {\n const record = this.requireActiveLease(params)\n const availableAt = params.availableAt ?? new Date().toISOString()\n const availableAtMs = parseTimestamp(availableAt, \"availableAt\")\n\n record.availableAtMs = availableAtMs\n record.job = {\n ...record.job,\n availableAt,\n }\n clearLease(record)\n this.store.schedule(params.projectId, record, Date.now())\n }\n\n async fail(params: {\n projectId: string\n jobId: string\n leaseId: string\n failure: QueueJobFailure<TFailureCode>\n }): Promise<void> {\n const record = this.requireActiveLease(params)\n record.state = \"failed\"\n record.failure = structuredClone(params.failure)\n clearLease(record)\n this.store.schedule(params.projectId, record, Date.now())\n }\n\n async renewLease(params: {\n projectId: string\n jobId: string\n leaseId: string\n leaseMs: number\n }): Promise<ClaimedQueueJob<TQueueJob> | null> {\n assertPositiveNumber(params.leaseMs, \"leaseMs\")\n\n const record = this.store.find<TQueueJob>(params.projectId, this.queueId, params.jobId)\n if (!record || record.state !== \"queued\") {\n return null\n }\n\n const now = Date.now()\n const expiresAt = leaseExpiresAtMs(record)\n if (record.leaseId !== params.leaseId || expiresAt === null) {\n return null\n }\n\n if (expiresAt <= now) {\n return null\n }\n\n const leaseExpiry = new Date(now + params.leaseMs)\n record.leaseExpiresAt = leaseExpiry.toISOString()\n record.leaseExpiryMs = leaseExpiry.getTime()\n this.store.schedule(params.projectId, record, now)\n return toClaimedQueueJob(record)\n }\n\n private requireActiveLease(params: {\n projectId: string\n jobId: string\n leaseId: string\n }): QueueRecord<TQueueJob> {\n assertNonEmpty(params.projectId, \"projectId\")\n assertNonEmpty(params.jobId, \"jobId\")\n assertNonEmpty(params.leaseId, \"leaseId\")\n\n const record = this.store.find<TQueueJob>(params.projectId, this.queueId, params.jobId)\n\n if (!record) {\n throw new QueueError(`[Sixb] Unknown queue job '${params.jobId}'`)\n }\n\n if (record.state !== \"queued\") {\n throw new QueueError(`[Sixb] Queue job '${params.jobId}' is no longer active`)\n }\n\n if (record.leaseId !== params.leaseId || !record.leaseExpiresAt) {\n throw new QueueError(`[Sixb] Lease mismatch for queue job '${params.jobId}'`)\n }\n\n const expiresAt = leaseExpiresAtMs(record)\n if (expiresAt === null || expiresAt <= Date.now()) {\n throw new QueueError(`[Sixb] Lease for queue job '${params.jobId}' has expired`)\n }\n\n return record\n }\n}\n\nexport class InMemoryQueues implements Queues {\n readonly scope = \"process\" as const\n private readonly store = new InMemoryQueueStore()\n\n readonly vectorIndexing = new InMemoryQueue<\n VectorIndexingQueueJob,\n \"internal.unexpected\" | \"runtime.cancelled\"\n >(this.store, \"vector.indexing\")\n readonly syncRuns = new InMemoryQueue<SyncRunRequestedQueueJob, SyncQueueJobFailureCode>(\n this.store,\n \"sync.runs\"\n )\n readonly pipelines = new InMemoryQueue<PipelineRunRequestedQueueJob, PipelineQueueJobFailureCode>(\n this.store,\n \"pipeline.runs\"\n )\n readonly projections = new InMemoryQueue<\n ProjectionRunRequestedQueueJob,\n ProjectionQueueJobFailureCode\n >(this.store, \"projection.runs\")\n readonly workflows = new InMemoryQueue<WorkflowQueueJob, WorkflowQueueJobFailureCode>(\n this.store,\n \"workflow.runs\"\n )\n readonly agents = new InMemoryQueue<AgentQueueJob, AgentQueueJobFailureCode>(\n this.store,\n \"agent.runs\"\n )\n readonly agentChildren = new InMemoryQueue<SubagentQueueJob, AgentQueueJobFailureCode>(\n this.store,\n \"agent.children\"\n )\n\n /** Nothing to reach: the store is a field of this object. */\n health(): Promise<void> {\n return Promise.resolve()\n }\n}\n",
|
|
7
|
-
"/** Internal mutable priority index. Updating or removing an entry never leaves stale copies. */\nexport class IndexedHeap<T> {\n private readonly items: T[] = []\n private readonly positions = new Map<T, number>()\n\n constructor(private readonly compare: (left: T, right: T) => number) {}\n\n peek(): T | undefined {\n return this.items[0]\n }\n\n pop(): T | undefined {\n const first = this.peek()\n if (first !== undefined) this.delete(first)\n return first\n }\n\n set(item: T): void {\n const index = this.positions.get(item)\n if (index === undefined) {\n this.positions.set(item, this.items.length)\n this.items.push(item)\n this.up(this.items.length - 1)\n } else {\n this.down(this.up(index))\n }\n }\n\n delete(item: T): void {\n const index = this.positions.get(item)\n if (index === undefined) return\n const last = this.items.pop()!\n this.positions.delete(item)\n if (index === this.items.length) return\n this.items[index] = last\n this.positions.set(last, index)\n this.down(this.up(index))\n }\n\n private up(start: number): number {\n let index = start\n while (index > 0) {\n const parent = Math.floor((index - 1) / 2)\n if (this.compare(this.items[parent]!, this.items[index]!) <= 0) break\n this.swap(parent, index)\n index = parent\n }\n return index\n }\n\n private down(start: number): void {\n let index = start\n while (index * 2 + 1 < this.items.length) {\n const left = index * 2 + 1\n const right = left + 1\n const child =\n right < this.items.length && this.compare(this.items[right]!, this.items[left]!) < 0\n ? right\n : left\n if (this.compare(this.items[index]!, this.items[child]!) <= 0) break\n this.swap(index, child)\n index = child\n }\n }\n\n private swap(left: number, right: number): void {\n const a = this.items[left]!\n const b = this.items[right]!\n this.items[left] = b\n this.items[right] = a\n this.positions.set(a, right)\n this.positions.set(b, left)\n }\n}\n"
|
|
8
|
-
],
|
|
9
|
-
"mappings": ";;AAGO,MAAM,oBAAmB,MAAM;AAAA,EAC3B,OAAO;AAClB;;ACLA;;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;AAEO,MAAM,gBAAiC;AAAA,EACnC,QAAQ;AAAA,EACA,QAAQ,IAAI;AAAA,EAEpB,iBAAiB,IAAI,cAG5B,KAAK,OAAO,iBAAiB;AAAA,EACtB,WAAW,IAAI,cACtB,KAAK,OACL,WACF;AAAA,EACS,YAAY,IAAI,cACvB,KAAK,OACL,eACF;AAAA,EACS,cAAc,IAAI,cAGzB,KAAK,OAAO,iBAAiB;AAAA,EACtB,YAAY,IAAI,cACvB,KAAK,OACL,eACF;AAAA,EACS,SAAS,IAAI,cACpB,KAAK,OACL,YACF;AAAA,EACS,gBAAgB,IAAI,cAC3B,KAAK,OACL,gBACF;AAAA,EAGA,MAAM,GAAkB;AAAA,IACtB,OAAO,QAAQ,QAAQ;AAAA;AAE3B;",
|
|
10
|
-
"debugId": "685F22E5A6A17CC964756E2164756E21",
|
|
11
|
-
"names": []
|
|
12
|
-
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/agents/streams/protocol.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import type { Broker, BrokerStreamDefinition } from \"../../broker\"\nimport { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport { isPlainRecord, type JsonValue } from \"../../json\"\nimport { isModelUiChunk, type ModelUiChunk } from \"../../models/events\"\nimport {\n AGENT_APPROVAL_STATUSES,\n AGENT_RUN_FAILURE_CODES,\n type AgentApprovalRecord,\n type AgentApprovalStatus,\n type AgentContextCheckpointReason,\n type AgentRunFailureCode,\n type AgentRunRecord,\n type ConversationAgentRunRecord,\n type SubagentRunRecord,\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\n/**\n * A held call of a thread's turn changed: it was held, decided, ran, or was set aside. Clients read\n * the thread's approvals again.\n */\nexport interface AgentApprovalActivityEvent {\n readonly schemaVersion: typeof AGENT_ACTIVITY_STREAM_SCHEMA_VERSION\n readonly type: \"agent.approval.activity\"\n readonly projectId: string\n readonly approvalId: string\n readonly threadId: string\n /** The conversation turn the call belongs to. */\n readonly runId: string\n readonly status: AgentApprovalStatus\n /** Whether the approved call ran and has its outcome. */\n readonly hasOutcome: boolean\n readonly occurredAt: string\n}\n\n/** Everything the project's activity feed carries. */\nexport type AgentActivityEvent = AgentRunActivityEvent | AgentApprovalActivityEvent\n\nexport function agentApprovalActivityEvent(\n approval: AgentApprovalRecord,\n occurredAt: Date = new Date()\n): AgentApprovalActivityEvent {\n return {\n schemaVersion: AGENT_ACTIVITY_STREAM_SCHEMA_VERSION,\n type: \"agent.approval.activity\",\n projectId: approval.projectId,\n approvalId: approval.id,\n threadId: approval.threadId,\n runId: approval.runId,\n status: approval.status,\n hasOutcome: approval.outcome !== undefined,\n occurredAt: occurredAt.toISOString(),\n }\n}\n\nexport function isAgentApprovalActivityEvent(value: unknown): value is AgentApprovalActivityEvent {\n return (\n isPlainRecord(value) &&\n value.schemaVersion === AGENT_ACTIVITY_STREAM_SCHEMA_VERSION &&\n value.type === \"agent.approval.activity\" &&\n typeof value.projectId === \"string\" &&\n typeof value.approvalId === \"string\" &&\n typeof value.threadId === \"string\" &&\n typeof value.runId === \"string\" &&\n (AGENT_APPROVAL_STATUSES as readonly unknown[]).includes(value.status) &&\n typeof value.hasOutcome === \"boolean\" &&\n typeof value.occurredAt === \"string\"\n )\n}\n\nexport function isAgentActivityEvent(value: unknown): value is AgentActivityEvent {\n return isAgentRunActivityEvent(value) || isAgentApprovalActivityEvent(value)\n}\n\n/** Announce held calls that changed, in one append. Each change is announced once. */\nexport async function publishAgentApprovalActivity(\n broker: Broker,\n approvals: readonly AgentApprovalRecord[]\n): Promise<void> {\n const first = approvals[0]\n if (!first) return\n\n await broker.ensureStream({\n projectId: first.projectId,\n stream: agentActivityStreamDefinition(),\n })\n await broker.append({\n projectId: first.projectId,\n streamId: AGENT_ACTIVITY_STREAM_ID,\n records: approvals.map((approval) => {\n const event = agentApprovalActivityEvent(approval)\n return {\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.approvalId}:${event.status}${event.hasOutcome ? \":outcome\" : \"\"}`,\n }\n }),\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// ── Inbox streams (mail between a turn and its sub-agents) ──────────────────────────────────────\n//\n// A sub-agent's thread has an inbox its runs read at each step boundary: its parent steering it,\n// and the parent's reply to its question. Every run of the child reads the same one. A turn has\n// one too, where its children ask it. Its durable record is the sender's tool call and the\n// reader's thread, which keeps each `mail` part where it was read, or the tool result. An answer\n// the parent could only give in a later turn starts the run that continues the child, never through\n// these streams. A thread's inbox outlives the turn only so that a child paused on a held call,\n// which a later turn continues once the user decides, can still be given what it did not read: it\n// keeps mail as long as an approval waits, and a day more.\n//\n// A turn's inbox also hears when each of its children finishes, so one subscription per turn wakes\n// its waits for questions and for children alike.\n\nexport type AgentThreadInboxStreamId = `agents.threads.${string}.inbox`\nexport type AgentRunInboxStreamId = `agents.runs.${string}.inbox`\n\nexport function agentThreadInboxStreamId(threadId: string): AgentThreadInboxStreamId {\n return `agents.threads.${threadId}.inbox`\n}\n\nexport function agentRunInboxStreamId(runId: string): AgentRunInboxStreamId {\n return `agents.runs.${runId}.inbox`\n}\n\nconst AGENT_MAIL_RECORD = \"agent.mail\"\n\nconst AGENT_INBOX_RETENTION = {\n // An approval waits at most 7 days (`AGENT_APPROVAL_TTL_MS`).\n maxAgeMs: 8 * 24 * 60 * 60 * 1000,\n maxRecords: 1_000,\n} as const\n\n/** Whose inbox: a sub-agent's thread, or a turn its children ask. */\nexport type AgentInbox = { readonly threadId: string } | { readonly runId: string }\n\nfunction inboxStreamDefinition(inbox: AgentInbox): BrokerStreamDefinition {\n return { id: inboxStreamId(inbox), retention: AGENT_INBOX_RETENTION }\n}\n\nfunction inboxStreamId(inbox: AgentInbox): AgentThreadInboxStreamId | AgentRunInboxStreamId {\n return \"threadId\" in inbox\n ? agentThreadInboxStreamId(inbox.threadId)\n : agentRunInboxStreamId(inbox.runId)\n}\n\n/**\n * The kinds of mail this version writes and understands:\n *\n * - `message`: the parent steers its child;\n * - `question`: the child asks its parent, and waits;\n * - `answer`: the parent's reply to a question, `inReplyTo`;\n * - `deferred`: the parent's turn ended without one, so the child pauses on its question.\n */\nexport const AGENT_MAIL_KINDS = [\"message\", \"question\", \"answer\", \"deferred\"] as const\nexport type AgentMailKind = (typeof AGENT_MAIL_KINDS)[number]\n\n/**\n * One message between a turn and its sub-agent: to the child's thread, or, a question, from the\n * child's thread to the turn.\n */\nexport type AgentMail = {\n /** Unique per message: a sender writing it again, or the broker redelivering it, is the same. */\n readonly id: string\n readonly fromRunId: string\n readonly kind: AgentMailKind\n /** The question an `answer` or `deferred` replies to. */\n readonly inReplyTo?: string\n /** What the reader's model reads, whatever the kind: a reader that does not know it reads this. */\n readonly text: string\n readonly sentAt: string\n} & (\n | { readonly toThreadId: string }\n | {\n readonly toRunId: string\n /** The sub-agent's thread that asks. */\n readonly fromThreadId: string\n }\n)\n\n/**\n * Mail as a reader finds it. Its kind may be one a newer sender writes: the reader delivers its\n * text as a message rather than skipping it, so no reader's cursor passes mail it never delivered.\n */\nexport type ReceivedAgentMail = Omit<AgentMail, \"kind\"> & { readonly kind: string }\n\nexport function isKnownAgentMailKind(kind: string): kind is AgentMailKind {\n return (AGENT_MAIL_KINDS as readonly string[]).includes(kind)\n}\n\nfunction isReceivedAgentMail(value: unknown): value is ReceivedAgentMail {\n return (\n isPlainRecord(value) &&\n typeof value.id === \"string\" &&\n typeof value.fromRunId === \"string\" &&\n (typeof value.toThreadId === \"string\" ||\n (typeof value.toRunId === \"string\" && typeof value.fromThreadId === \"string\")) &&\n typeof value.kind === \"string\" &&\n value.kind.length > 0 &&\n (value.inReplyTo === undefined || typeof value.inReplyTo === \"string\") &&\n typeof value.text === \"string\" &&\n typeof value.sentAt === \"string\"\n )\n}\n\n/** Whether mail is addressed to this inbox. */\nfunction isFor(mail: ReceivedAgentMail, inbox: AgentInbox): boolean {\n return \"threadId\" in inbox\n ? \"toThreadId\" in mail && mail.toThreadId === inbox.threadId\n : \"toRunId\" in mail && mail.toRunId === inbox.runId\n}\n\nfunction recipientOf(mail: AgentMail): AgentInbox {\n return \"toThreadId\" in mail ? { threadId: mail.toThreadId } : { runId: mail.toRunId }\n}\n\n/** Write a message to its recipient's inbox. Idempotent by its id where the broker dedupes. */\nexport async function publishAgentMail(\n broker: Broker,\n params: { readonly projectId: string; readonly mail: AgentMail }\n): Promise<void> {\n const { projectId, mail } = params\n const inbox = recipientOf(mail)\n await broker.ensureStream({ projectId, stream: inboxStreamDefinition(inbox) })\n await broker.append({\n projectId,\n streamId: inboxStreamId(inbox),\n records: [\n {\n name: AGENT_MAIL_RECORD,\n key: \"threadId\" in inbox ? inbox.threadId : inbox.runId,\n // The mail is composed only of validated JSON primitives.\n payload: mail as unknown as JsonValue,\n idempotencyKey: mail.id,\n },\n ],\n })\n}\n\n/**\n * Call `onMail` with each page of mail to an inbox as it arrives, from its start. It is a wake: a\n * broker may deliver a record again, so the reader keeps each mail once by its id. Returns the\n * unsubscribe handle.\n */\nexport function subscribeAgentMail(\n broker: Broker,\n params: { readonly projectId: string; readonly inbox: AgentInbox },\n onMail: (mail: readonly ReceivedAgentMail[]) => void\n): Promise<() => void> {\n return subscribeAgentInbox(broker, params, { mail: onMail })\n}\n\n/**\n * Hear an inbox from its start: its mail, and, for a turn's with `childFinished`, the ids of its\n * children as each finishes. Both are wakes: a broker may deliver a record again, and a finish says\n * only that the child's run is worth reading. Returns the unsubscribe handle.\n */\nexport async function subscribeAgentInbox(\n broker: Broker,\n params: { readonly projectId: string; readonly inbox: AgentInbox },\n on: {\n readonly mail: (mail: readonly ReceivedAgentMail[]) => void\n readonly childFinished?: (runIds: readonly string[]) => void\n }\n): Promise<() => void> {\n const { inbox } = params\n await broker.ensureStream({\n projectId: params.projectId,\n stream: inboxStreamDefinition(inbox),\n })\n return broker.subscribe(\n {\n projectId: params.projectId,\n streamId: inboxStreamId(inbox),\n from: \"earliest\",\n names: on.childFinished\n ? [AGENT_MAIL_RECORD, AGENT_CHILD_FINISHED_RECORD]\n : [AGENT_MAIL_RECORD],\n },\n (records) => {\n const mail: ReceivedAgentMail[] = []\n const finished: string[] = []\n for (const { name, payload } of records) {\n if (name === AGENT_MAIL_RECORD) {\n if (isReceivedAgentMail(payload) && isFor(payload, inbox)) mail.push(payload)\n } else if (\n \"runId\" in inbox &&\n isAgentChildFinished(payload) &&\n payload.parentRunId === inbox.runId\n ) {\n finished.push(payload.runId)\n }\n }\n\n if (mail.length > 0) on.mail(mail)\n if (finished.length > 0) on.childFinished?.(finished)\n }\n )\n}\n\nconst AGENT_CHILD_FINISHED_RECORD = \"agent.child.finished\"\n\n/** A child stopped being at work: it ended, or paused on a held call or on its question. */\ninterface AgentChildFinished {\n readonly runId: string\n readonly parentRunId: string\n readonly status: \"succeeded\" | \"failed\" | \"cancelled\"\n}\n\nfunction isAgentChildFinished(value: unknown): value is AgentChildFinished {\n return (\n isPlainRecord(value) &&\n typeof value.runId === \"string\" &&\n typeof value.parentRunId === \"string\" &&\n isTerminalAgentRunStatus(value.status)\n )\n}\n\n/**\n * Tell the turn a child works under, on the turn's inbox, that the child finished. Its run stream\n * says so too, but that stream belongs to the transcript sink, which a worker may replace, and\n * hearing it would take one subscription per child, each carrying every chunk the child streams.\n * This record is the platform's, and one subscription per turn hears every child.\n */\nexport async function publishAgentChildFinished(\n broker: Broker,\n run: SubagentRunRecord\n): Promise<void> {\n if (run.status === \"queued\" || run.status === \"running\") return\n\n const finished: AgentChildFinished = {\n runId: run.id,\n parentRunId: run.parentRunId,\n status: run.status,\n }\n const inbox = { runId: run.parentRunId }\n await broker.ensureStream({ projectId: run.projectId, stream: inboxStreamDefinition(inbox) })\n await broker.append({\n projectId: run.projectId,\n streamId: inboxStreamId(inbox),\n records: [\n {\n name: AGENT_CHILD_FINISHED_RECORD,\n key: run.parentRunId,\n // The record is composed only of validated JSON primitives.\n payload: finished as unknown as JsonValue,\n idempotencyKey: `${run.id}:${run.attempt}:finished:${run.status}`,\n },\n ],\n })\n}\n\n/**\n * Read an inbox's mail after `afterCursor`, or from the start, every page of it. Carry the returned\n * cursor to the next read. A record that is not mail at all (no envelope, no text) cannot be\n * delivered: it is reported and passed, never silently.\n */\nexport async function readAgentMail(\n broker: Broker,\n params: { readonly projectId: string; readonly inbox: AgentInbox; readonly afterCursor?: string }\n): Promise<{ readonly mail: readonly ReceivedAgentMail[]; readonly cursor?: string }> {\n const mail: ReceivedAgentMail[] = []\n const streamId = inboxStreamId(params.inbox)\n let cursor = params.afterCursor\n\n for (;;) {\n const page = await broker.read({\n projectId: params.projectId,\n streamId,\n names: [AGENT_MAIL_RECORD],\n ...(cursor === undefined ? {} : { afterCursor: cursor }),\n })\n for (const record of page.records) {\n if (!isReceivedAgentMail(record.payload)) {\n console.error(\n `[Sixb] Agent inbox '${streamId}' record '${record.cursor}' is not mail; it is skipped.`\n )\n continue\n }\n if (isFor(record.payload, params.inbox)) mail.push(record.payload)\n }\n\n const previous = cursor\n cursor = page.cursor ?? cursor\n if (!page.hasMore || cursor === previous) break\n }\n\n return { mail, ...(cursor === undefined ? {} : { cursor }) }\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: ModelUiChunk\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 // A chunk type this reader does not know fails here, so a newer producer's chunk is skipped.\n return Number.isInteger(value.chunkIndex) && isModelUiChunk(value.chunk)\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 else await publishAgentChildFinished(broker, run)\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";;;;;;;;;;;;;;;;AAiBO,IAAM,mCAAkC;AACxC,IAAM,sCAAqC;AAAA,EAChD,UAAU,IAAI,KAAK,KAAK;AAAA,EACxB,YAAY;AACd;AAEO,IAAM,wCAAuC;AAC7C,IAAM,4BAA2B;AACjC,IAAM,2CAA0C;AAAA,EACrD,UAAU,KAAK,KAAK,KAAK;AAAA,EACzB,YAAY;AACd;AAaO,SAAS,8BAA6B,GAA2B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iB,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,8BAA6B,KAAK;AAAA,MACpD;AAAA,IACF;AAAA,EACF,CAAC;AAAA,EACD,IAAI,IAAI,SAAS;AAAA,IAAgB,MAAM,yBAAwB,QAAQ,GAAG;AAAA,EACrE;AAAA,UAAM,2BAA0B,QAAQ,GAAG;AAAA;",
|
|
8
|
-
"debugId": "8695CFFE3CAE404964756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|
package/dist/chunk-vabga7fk.js
DELETED
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import {
|
|
3
|
-
SandboxError2,
|
|
4
|
-
staticSandboxRecipe2,
|
|
5
|
-
captureEnvironment
|
|
6
|
-
} from "./chunk-d2m879s4.js";
|
|
7
|
-
|
|
8
|
-
// src/sandboxes/config.ts
|
|
9
|
-
function sandboxConfig2(options) {
|
|
10
|
-
if (options.auth !== undefined && typeof options.auth?.authorize !== "function") {
|
|
11
|
-
throw new SandboxError2("[Sixb] sandboxes.auth requires an authorize function.");
|
|
12
|
-
}
|
|
13
|
-
const authorize = options.auth?.authorize.bind(options.auth);
|
|
14
|
-
if (options.params !== undefined && options.resolve === undefined) {
|
|
15
|
-
throw new SandboxError2("[Sixb] Sandbox params require a resolve function.");
|
|
16
|
-
}
|
|
17
|
-
if (options.resolve !== undefined && typeof options.resolve !== "function") {
|
|
18
|
-
throw new SandboxError2("[Sixb] Sandbox resolve must be a function.");
|
|
19
|
-
}
|
|
20
|
-
if (options.resolve !== undefined && (options.source !== undefined || options.setup !== undefined)) {
|
|
21
|
-
throw new SandboxError2("[Sixb] Use either static source/setup or resolve, not both.");
|
|
22
|
-
}
|
|
23
|
-
const environment = staticSandboxRecipe2(options);
|
|
24
|
-
return Object.freeze({
|
|
25
|
-
...authorize ? { auth: Object.freeze({ authorize }) } : {},
|
|
26
|
-
...environment,
|
|
27
|
-
...options.params === undefined ? {} : { params: structuredClone(options.params) },
|
|
28
|
-
...options.resolve === undefined ? {} : { resolve: options.resolve }
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
// src/sandboxes/environment.ts
|
|
32
|
-
import { posix } from "path";
|
|
33
|
-
function sandboxCreationEnvironment2(configuration, options) {
|
|
34
|
-
if (options.environment === undefined && configuration.resolve !== undefined) {
|
|
35
|
-
throw new SandboxError2("[Sixb] Dynamic sandbox configuration requires an execution-resolved environment.");
|
|
36
|
-
}
|
|
37
|
-
const environment = captureEnvironment(options.environment !== undefined ? options.environment : {
|
|
38
|
-
...configuration.source === undefined ? {} : { source: configuration.source },
|
|
39
|
-
...configuration.setup === undefined ? {} : { setup: configuration.setup }
|
|
40
|
-
});
|
|
41
|
-
if (environment.env !== undefined || environment.network !== undefined) {
|
|
42
|
-
throw new SandboxError2("[Sixb] Pass env and network as sandbox session options, not environment.");
|
|
43
|
-
}
|
|
44
|
-
if (environment.source) {
|
|
45
|
-
if ((configuration.auth !== undefined || environment.source.access === "write") && !options.requestCredentials?.length) {
|
|
46
|
-
throw new SandboxError2("[Sixb] Sandbox source authentication requires execution-prepared request credentials.");
|
|
47
|
-
}
|
|
48
|
-
const network = options.network ?? configuration.network ?? { mode: "none" };
|
|
49
|
-
const origin = new URL(environment.source.url).origin;
|
|
50
|
-
if (network.mode === "none" || network.mode === "restricted" && !network.allow.some((target) => target.origin === origin)) {
|
|
51
|
-
throw new SandboxError2("[Sixb] Sandbox network policy denies the source origin.");
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
options.signal?.throwIfAborted();
|
|
55
|
-
return environment;
|
|
56
|
-
}
|
|
57
|
-
function sandboxProjectDirectory2(session, hasSource) {
|
|
58
|
-
if (!hasSource)
|
|
59
|
-
return session;
|
|
60
|
-
const workingDirectory = posix.join(session.workingDirectory, "repository");
|
|
61
|
-
return {
|
|
62
|
-
id: session.id,
|
|
63
|
-
provider: session.provider,
|
|
64
|
-
get status() {
|
|
65
|
-
return session.status;
|
|
66
|
-
},
|
|
67
|
-
workingDirectory,
|
|
68
|
-
...session.setRequestCredentials ? { setRequestCredentials: session.setRequestCredentials.bind(session) } : {},
|
|
69
|
-
runCommand: (command, args, options) => session.runCommand(command, args, { ...options, cwd: options?.cwd ?? workingDirectory }),
|
|
70
|
-
writeFiles: (files) => session.writeFiles(files.map((file) => ({
|
|
71
|
-
...file,
|
|
72
|
-
path: posix.isAbsolute(file.path) ? file.path : posix.join(workingDirectory, file.path)
|
|
73
|
-
}))),
|
|
74
|
-
stop: () => session.stop(),
|
|
75
|
-
destroy: () => session.destroy()
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
async function initializeSandboxEnvironment2(session, environment, signal) {
|
|
79
|
-
environment = captureEnvironment(environment);
|
|
80
|
-
const run = async (sandbox, command, args) => {
|
|
81
|
-
signal?.throwIfAborted();
|
|
82
|
-
const result = await sandbox.runCommand(command, args, { timeout: 120000, signal });
|
|
83
|
-
if (result.exitCode !== 0 || result.timedOut) {
|
|
84
|
-
throw new SandboxError2("[Sixb] Sandbox environment initialization failed.");
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
signal?.throwIfAborted();
|
|
88
|
-
const sandbox = sandboxProjectDirectory2(session, environment.source !== undefined);
|
|
89
|
-
if (environment.source) {
|
|
90
|
-
await run(session, "git", ["clone", "--", environment.source.url, "repository"]);
|
|
91
|
-
if (environment.source.revision) {
|
|
92
|
-
await run(sandbox, "git", ["checkout", environment.source.revision, "--"]);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
for (const command of environment.setup ?? [])
|
|
96
|
-
await run(sandbox, "bash", ["-lc", command]);
|
|
97
|
-
return sandbox;
|
|
98
|
-
}
|
|
99
|
-
// src/sandboxes/exec.ts
|
|
100
|
-
var DEFAULT_KILL_EXIT_CODE = 137;
|
|
101
|
-
async function exec2(options) {
|
|
102
|
-
const start = Date.now();
|
|
103
|
-
const [head, ...rest] = options.argv;
|
|
104
|
-
if (!head) {
|
|
105
|
-
return {
|
|
106
|
-
exitCode: 1,
|
|
107
|
-
stdout: "",
|
|
108
|
-
stderr: "[Sandbox] empty argv",
|
|
109
|
-
durationMs: 0
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
let proc;
|
|
113
|
-
try {
|
|
114
|
-
proc = Bun.spawn([head, ...rest], {
|
|
115
|
-
cwd: options.cwd,
|
|
116
|
-
env: options.env,
|
|
117
|
-
stdin: "ignore",
|
|
118
|
-
stdout: "pipe",
|
|
119
|
-
stderr: "pipe"
|
|
120
|
-
});
|
|
121
|
-
} catch (error) {
|
|
122
|
-
return {
|
|
123
|
-
exitCode: 127,
|
|
124
|
-
stdout: "",
|
|
125
|
-
stderr: error instanceof Error ? error.message : String(error),
|
|
126
|
-
durationMs: Date.now() - start
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
let timedOut = false;
|
|
130
|
-
let killed = false;
|
|
131
|
-
const timer = options.timeoutMs !== undefined && options.timeoutMs > 0 ? setTimeout(() => {
|
|
132
|
-
timedOut = true;
|
|
133
|
-
killed = true;
|
|
134
|
-
proc.kill("SIGKILL");
|
|
135
|
-
}, options.timeoutMs) : undefined;
|
|
136
|
-
const onAbort = () => {
|
|
137
|
-
if (!killed) {
|
|
138
|
-
killed = true;
|
|
139
|
-
proc.kill("SIGKILL");
|
|
140
|
-
}
|
|
141
|
-
};
|
|
142
|
-
options.signal?.addEventListener("abort", onAbort);
|
|
143
|
-
if (options.signal?.aborted) {
|
|
144
|
-
onAbort();
|
|
145
|
-
}
|
|
146
|
-
let stdout = "";
|
|
147
|
-
let stderr = "";
|
|
148
|
-
let exitCode = 0;
|
|
149
|
-
try {
|
|
150
|
-
const [stdoutText, stderrText, code] = await Promise.all([
|
|
151
|
-
new Response(proc.stdout).text(),
|
|
152
|
-
new Response(proc.stderr).text(),
|
|
153
|
-
proc.exited
|
|
154
|
-
]);
|
|
155
|
-
stdout = stdoutText;
|
|
156
|
-
stderr = stderrText;
|
|
157
|
-
exitCode = typeof code === "number" ? code : DEFAULT_KILL_EXIT_CODE;
|
|
158
|
-
} finally {
|
|
159
|
-
if (timer !== undefined)
|
|
160
|
-
clearTimeout(timer);
|
|
161
|
-
options.signal?.removeEventListener("abort", onAbort);
|
|
162
|
-
}
|
|
163
|
-
if (killed && exitCode === 0) {
|
|
164
|
-
exitCode = DEFAULT_KILL_EXIT_CODE;
|
|
165
|
-
}
|
|
166
|
-
return {
|
|
167
|
-
exitCode,
|
|
168
|
-
stdout,
|
|
169
|
-
stderr,
|
|
170
|
-
durationMs: Date.now() - start,
|
|
171
|
-
...timedOut ? { timedOut: true } : {}
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
export { sandboxConfig2, sandboxCreationEnvironment2, sandboxProjectDirectory2, initializeSandboxEnvironment2, exec2 };
|
|
175
|
-
|
|
176
|
-
//# debugId=00B8A2DFA48E731B64756E2164756E21
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/sandboxes/config.ts", "../src/sandboxes/environment.ts", "../src/sandboxes/exec.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import type { ParamsConfig } from \"../shared/params/types\"\nimport { type SandboxConfig, staticSandboxRecipe } from \"./configuration\"\nimport { SandboxError } from \"./errors\"\n\n/** Extract only the common recipe; provider credentials and infrastructure stay on the factory. */\nexport function sandboxConfig<TParams extends ParamsConfig>(\n options: SandboxConfig<TParams>\n): SandboxConfig<TParams> {\n if (options.auth !== undefined && typeof options.auth?.authorize !== \"function\") {\n throw new SandboxError(\"[Sixb] sandboxes.auth requires an authorize function.\")\n }\n const authorize = options.auth?.authorize.bind(options.auth)\n if (options.params !== undefined && options.resolve === undefined) {\n throw new SandboxError(\"[Sixb] Sandbox params require a resolve function.\")\n }\n if (options.resolve !== undefined && typeof options.resolve !== \"function\") {\n throw new SandboxError(\"[Sixb] Sandbox resolve must be a function.\")\n }\n if (\n options.resolve !== undefined &&\n (options.source !== undefined || options.setup !== undefined)\n ) {\n throw new SandboxError(\"[Sixb] Use either static source/setup or resolve, not both.\")\n }\n const environment = staticSandboxRecipe(options)\n return Object.freeze({\n ...(authorize ? { auth: Object.freeze({ authorize }) } : {}),\n ...environment,\n ...(options.params === undefined ? {} : { params: structuredClone(options.params) }),\n ...(options.resolve === undefined ? {} : { resolve: options.resolve }),\n })\n}\n",
|
|
6
|
-
"import { posix } from \"node:path\"\nimport type { ParamsConfig } from \"../shared/params/types\"\nimport type { SandboxConfig } from \"./configuration\"\nimport { captureEnvironment, type SandboxEnvironment } from \"./configuration\"\nimport { SandboxError } from \"./errors\"\nimport type { CreateSandboxOptions, Sandbox } from \"./sandbox\"\n\n/** Select and validate before provisioning. Only the execution runtime may resolve a recipe. */\nexport function sandboxCreationEnvironment<TParams extends ParamsConfig>(\n configuration: SandboxConfig<TParams>,\n options: CreateSandboxOptions\n): Pick<SandboxEnvironment, \"source\" | \"setup\"> {\n if (options.environment === undefined && configuration.resolve !== undefined) {\n throw new SandboxError(\n \"[Sixb] Dynamic sandbox configuration requires an execution-resolved environment.\"\n )\n }\n const environment = captureEnvironment(\n options.environment !== undefined\n ? options.environment\n : {\n ...(configuration.source === undefined ? {} : { source: configuration.source }),\n ...(configuration.setup === undefined ? {} : { setup: configuration.setup }),\n }\n )\n if (environment.env !== undefined || environment.network !== undefined) {\n throw new SandboxError(\n \"[Sixb] Pass env and network as sandbox session options, not environment.\"\n )\n }\n if (environment.source) {\n if (\n (configuration.auth !== undefined || environment.source.access === \"write\") &&\n !options.requestCredentials?.length\n ) {\n throw new SandboxError(\n \"[Sixb] Sandbox source authentication requires execution-prepared request credentials.\"\n )\n }\n const network = options.network ?? configuration.network ?? { mode: \"none\" }\n const origin = new URL(environment.source.url).origin\n if (\n network.mode === \"none\" ||\n (network.mode === \"restricted\" && !network.allow.some((target) => target.origin === origin))\n ) {\n throw new SandboxError(\"[Sixb] Sandbox network policy denies the source origin.\")\n }\n }\n options.signal?.throwIfAborted()\n return environment\n}\n\n/** Select the same project directory on creation and resume without touching saved files. */\nexport function sandboxProjectDirectory(session: Sandbox, hasSource: boolean): Sandbox {\n if (!hasSource) return session\n const workingDirectory = posix.join(session.workingDirectory, \"repository\")\n return {\n id: session.id,\n provider: session.provider,\n get status() {\n return session.status\n },\n workingDirectory,\n ...(session.setRequestCredentials\n ? { setRequestCredentials: session.setRequestCredentials.bind(session) }\n : {}),\n runCommand: (command, args, options) =>\n session.runCommand(command, args, { ...options, cwd: options?.cwd ?? workingDirectory }),\n writeFiles: (files) =>\n session.writeFiles(\n files.map((file) => ({\n ...file,\n path: posix.isAbsolute(file.path) ? file.path : posix.join(workingDirectory, file.path),\n }))\n ),\n stop: () => session.stop(),\n destroy: () => session.destroy(),\n }\n}\n\n/** Provider-side initialization, after the session network/credentials have been applied.\n * Call only on fresh creation. The caller owns cleanup if any command fails.\n */\nexport async function initializeSandboxEnvironment(\n session: Sandbox,\n environment: Pick<SandboxEnvironment, \"source\" | \"setup\">,\n signal?: AbortSignal\n): Promise<Sandbox> {\n environment = captureEnvironment(environment)\n const run = async (sandbox: Sandbox, command: string, args: readonly string[]) => {\n signal?.throwIfAborted()\n const result = await sandbox.runCommand(command, args, { timeout: 120_000, signal })\n if (result.exitCode !== 0 || result.timedOut) {\n throw new SandboxError(\"[Sixb] Sandbox environment initialization failed.\")\n }\n }\n signal?.throwIfAborted()\n const sandbox = sandboxProjectDirectory(session, environment.source !== undefined)\n if (environment.source) {\n await run(session, \"git\", [\"clone\", \"--\", environment.source.url, \"repository\"])\n if (environment.source.revision) {\n await run(sandbox, \"git\", [\"checkout\", environment.source.revision, \"--\"])\n }\n }\n for (const command of environment.setup ?? []) await run(sandbox, \"bash\", [\"-lc\", command])\n return sandbox\n}\n",
|
|
7
|
-
"import type { CommandResult } from \"./sandbox\"\n\nexport interface ExecOptions {\n readonly argv: readonly string[]\n readonly cwd: string\n readonly env: Readonly<Record<string, string>>\n readonly timeoutMs?: number\n readonly signal?: AbortSignal\n}\n\nconst DEFAULT_KILL_EXIT_CODE = 137\n\n/**\n * Spawn a child process and gather its {@link CommandResult}. Wraps Bun.spawn with timeout and\n * AbortSignal handling, and never throws. Command-agnostic: the wrapper makes no assumptions about\n * what it spawns, so sandbox providers share it. On timeout/abort it SIGKILLs the spawned process;\n * any provider whose spawned process merely fronts a longer-lived resource (e.g. a VM) is\n * responsible for reaping that resource in its own stop()/destroy().\n */\nexport async function exec(options: ExecOptions): Promise<CommandResult> {\n const start = Date.now()\n\n const [head, ...rest] = options.argv\n if (!head) {\n return {\n exitCode: 1,\n stdout: \"\",\n stderr: \"[Sandbox] empty argv\",\n durationMs: 0,\n }\n }\n\n let proc: ReturnType<typeof Bun.spawn>\n try {\n proc = Bun.spawn([head, ...rest], {\n cwd: options.cwd,\n env: options.env,\n stdin: \"ignore\",\n stdout: \"pipe\",\n stderr: \"pipe\",\n })\n } catch (error) {\n return {\n exitCode: 127,\n stdout: \"\",\n stderr: error instanceof Error ? error.message : String(error),\n durationMs: Date.now() - start,\n }\n }\n\n let timedOut = false\n let killed = false\n\n const timer =\n options.timeoutMs !== undefined && options.timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true\n killed = true\n proc.kill(\"SIGKILL\")\n }, options.timeoutMs)\n : undefined\n\n const onAbort = (): void => {\n if (!killed) {\n killed = true\n proc.kill(\"SIGKILL\")\n }\n }\n options.signal?.addEventListener(\"abort\", onAbort)\n if (options.signal?.aborted) {\n onAbort()\n }\n\n let stdout = \"\"\n let stderr = \"\"\n let exitCode = 0\n try {\n const [stdoutText, stderrText, code] = await Promise.all([\n new Response(proc.stdout as ReadableStream<Uint8Array>).text(),\n new Response(proc.stderr as ReadableStream<Uint8Array>).text(),\n proc.exited,\n ])\n stdout = stdoutText\n stderr = stderrText\n exitCode = typeof code === \"number\" ? code : DEFAULT_KILL_EXIT_CODE\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n options.signal?.removeEventListener(\"abort\", onAbort)\n }\n\n if (killed && exitCode === 0) {\n exitCode = DEFAULT_KILL_EXIT_CODE\n }\n\n return {\n exitCode,\n stdout,\n stderr,\n durationMs: Date.now() - start,\n ...(timedOut ? { timedOut: true } : {}),\n }\n}\n"
|
|
8
|
-
],
|
|
9
|
-
"mappings": ";;;;;;;;AAKO,SAAS,cAA2C,CACzD,SACwB;AAAA,EACxB,IAAI,QAAQ,SAAS,aAAa,OAAO,QAAQ,MAAM,cAAc,YAAY;AAAA,IAC/E,MAAM,IAAI,cAAa,uDAAuD;AAAA,EAChF;AAAA,EACA,MAAM,YAAY,QAAQ,MAAM,UAAU,KAAK,QAAQ,IAAI;AAAA,EAC3D,IAAI,QAAQ,WAAW,aAAa,QAAQ,YAAY,WAAW;AAAA,IACjE,MAAM,IAAI,cAAa,mDAAmD;AAAA,EAC5E;AAAA,EACA,IAAI,QAAQ,YAAY,aAAa,OAAO,QAAQ,YAAY,YAAY;AAAA,IAC1E,MAAM,IAAI,cAAa,4CAA4C;AAAA,EACrE;AAAA,EACA,IACE,QAAQ,YAAY,cACnB,QAAQ,WAAW,aAAa,QAAQ,UAAU,YACnD;AAAA,IACA,MAAM,IAAI,cAAa,6DAA6D;AAAA,EACtF;AAAA,EACA,MAAM,cAAc,qBAAoB,OAAO;AAAA,EAC/C,OAAO,OAAO,OAAO;AAAA,OACf,YAAY,EAAE,MAAM,OAAO,OAAO,EAAE,UAAU,CAAC,EAAE,IAAI,CAAC;AAAA,OACvD;AAAA,OACC,QAAQ,WAAW,YAAY,CAAC,IAAI,EAAE,QAAQ,gBAAgB,QAAQ,MAAM,EAAE;AAAA,OAC9E,QAAQ,YAAY,YAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;AAAA,EACtE,CAAC;AAAA;;AC9BH;AAQO,SAAS,2BAAwD,CACtE,eACA,SAC8C;AAAA,EAC9C,IAAI,QAAQ,gBA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