@theokit/sdk 4.23.0 → 4.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/a2a/index.cjs +10 -171
- package/dist/a2a/index.cjs.map +1 -1
- package/dist/a2a/index.js +3 -170
- package/dist/a2a/index.js.map +1 -1
- package/dist/agent-factory-registry-UU46BUMU.cjs +16 -0
- package/dist/agent-factory-registry-UU46BUMU.cjs.map +1 -0
- package/dist/agent-factory-registry-ZVTABLEY.js +3 -0
- package/dist/agent-factory-registry-ZVTABLEY.js.map +1 -0
- package/dist/auth/index.cjs +63 -343
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.js +6 -318
- package/dist/auth/index.js.map +1 -1
- package/dist/batch-2FSD2UNL.cjs +244 -0
- package/dist/batch-2FSD2UNL.cjs.map +1 -0
- package/dist/batch-MR2HKYMS.js +241 -0
- package/dist/batch-MR2HKYMS.js.map +1 -0
- package/dist/chunk-2HRYBRD7.cjs +31 -0
- package/dist/chunk-2HRYBRD7.cjs.map +1 -0
- package/dist/chunk-2MF3IE2D.cjs +2863 -0
- package/dist/chunk-2MF3IE2D.cjs.map +1 -0
- package/dist/chunk-2ONFGMBV.js +6 -0
- package/dist/chunk-2ONFGMBV.js.map +1 -0
- package/dist/chunk-2SFBB54R.js +23 -0
- package/dist/chunk-2SFBB54R.js.map +1 -0
- package/dist/chunk-2XLKLVVR.js +18 -0
- package/dist/chunk-2XLKLVVR.js.map +1 -0
- package/dist/chunk-4HKMQEPX.js +458 -0
- package/dist/chunk-4HKMQEPX.js.map +1 -0
- package/dist/chunk-4SXHEZIV.cjs +240 -0
- package/dist/chunk-4SXHEZIV.cjs.map +1 -0
- package/dist/chunk-4VPXM6UU.js +10 -0
- package/dist/chunk-4VPXM6UU.js.map +1 -0
- package/dist/chunk-4WL52CXU.cjs +148 -0
- package/dist/chunk-4WL52CXU.cjs.map +1 -0
- package/dist/chunk-5NBUH3NO.js +39 -0
- package/dist/chunk-5NBUH3NO.js.map +1 -0
- package/dist/chunk-5PZMMF4H.js +43 -0
- package/dist/chunk-5PZMMF4H.js.map +1 -0
- package/dist/chunk-6CLRANZA.js +289 -0
- package/dist/chunk-6CLRANZA.js.map +1 -0
- package/dist/chunk-6JSIEDKL.cjs +121 -0
- package/dist/chunk-6JSIEDKL.cjs.map +1 -0
- package/dist/chunk-6M4ODB2V.cjs +145 -0
- package/dist/chunk-6M4ODB2V.cjs.map +1 -0
- package/dist/chunk-6X6ID4MO.js +20 -0
- package/dist/chunk-6X6ID4MO.js.map +1 -0
- package/dist/chunk-77FOZCOT.js +165 -0
- package/dist/chunk-77FOZCOT.js.map +1 -0
- package/dist/chunk-7AD3ZTZL.js +25 -0
- package/dist/chunk-7AD3ZTZL.js.map +1 -0
- package/dist/chunk-7GFX45DD.js +57 -0
- package/dist/chunk-7GFX45DD.js.map +1 -0
- package/dist/chunk-7RMWOMDB.cjs +460 -0
- package/dist/chunk-7RMWOMDB.cjs.map +1 -0
- package/dist/chunk-7S7KKUO6.cjs +45 -0
- package/dist/chunk-7S7KKUO6.cjs.map +1 -0
- package/dist/chunk-7W7ZWMLQ.js +99 -0
- package/dist/chunk-7W7ZWMLQ.js.map +1 -0
- package/dist/chunk-A44COQJJ.cjs +353 -0
- package/dist/chunk-A44COQJJ.cjs.map +1 -0
- package/dist/chunk-AKSBP7OO.js +185 -0
- package/dist/chunk-AKSBP7OO.js.map +1 -0
- package/dist/chunk-ANIZEWTU.cjs +196 -0
- package/dist/chunk-ANIZEWTU.cjs.map +1 -0
- package/dist/chunk-BEURCLDV.cjs +139 -0
- package/dist/chunk-BEURCLDV.cjs.map +1 -0
- package/dist/chunk-BFWPZMG7.js +379 -0
- package/dist/chunk-BFWPZMG7.js.map +1 -0
- package/dist/chunk-BUUUWQMB.cjs +34 -0
- package/dist/chunk-BUUUWQMB.cjs.map +1 -0
- package/dist/chunk-BV2MWEMV.cjs +26 -0
- package/dist/chunk-BV2MWEMV.cjs.map +1 -0
- package/dist/chunk-BWT67BI4.cjs +268 -0
- package/dist/chunk-BWT67BI4.cjs.map +1 -0
- package/dist/chunk-BXV2QUIC.js +191 -0
- package/dist/chunk-BXV2QUIC.js.map +1 -0
- package/dist/chunk-C6Y6CWYD.cjs +44 -0
- package/dist/chunk-C6Y6CWYD.cjs.map +1 -0
- package/dist/chunk-C7PICHRF.cjs +68 -0
- package/dist/chunk-C7PICHRF.cjs.map +1 -0
- package/dist/chunk-CAH3G4IS.js +13 -0
- package/dist/chunk-CAH3G4IS.js.map +1 -0
- package/dist/chunk-CJ6YJ2L3.cjs +10590 -0
- package/dist/chunk-CJ6YJ2L3.cjs.map +1 -0
- package/dist/chunk-D42XHI4O.cjs +565 -0
- package/dist/chunk-D42XHI4O.cjs.map +1 -0
- package/dist/chunk-DGRZNMTU.js +104 -0
- package/dist/chunk-DGRZNMTU.js.map +1 -0
- package/dist/chunk-DUK5WMKJ.js +71 -0
- package/dist/chunk-DUK5WMKJ.js.map +1 -0
- package/dist/chunk-EEZ7CFMM.js +14 -0
- package/dist/chunk-EEZ7CFMM.js.map +1 -0
- package/dist/chunk-EPYZOCOL.cjs +82 -0
- package/dist/chunk-EPYZOCOL.cjs.map +1 -0
- package/dist/chunk-EVADEGM7.cjs +168 -0
- package/dist/chunk-EVADEGM7.cjs.map +1 -0
- package/dist/chunk-F3XVLFLM.js +10573 -0
- package/dist/chunk-F3XVLFLM.js.map +1 -0
- package/dist/chunk-FD2UT76F.js +3 -0
- package/dist/chunk-FD2UT76F.js.map +1 -0
- package/dist/chunk-FV3YEMQ7.js +179 -0
- package/dist/chunk-FV3YEMQ7.js.map +1 -0
- package/dist/chunk-G2F67XUR.cjs +184 -0
- package/dist/chunk-G2F67XUR.cjs.map +1 -0
- package/dist/chunk-G6GO6BXD.js +994 -0
- package/dist/chunk-G6GO6BXD.js.map +1 -0
- package/dist/chunk-GIW4L6HY.cjs +27 -0
- package/dist/chunk-GIW4L6HY.cjs.map +1 -0
- package/dist/chunk-GJAGKFTR.js +74 -0
- package/dist/chunk-GJAGKFTR.js.map +1 -0
- package/dist/chunk-HFPGOTVF.cjs +324 -0
- package/dist/chunk-HFPGOTVF.cjs.map +1 -0
- package/dist/chunk-HRA3CPGG.js +486 -0
- package/dist/chunk-HRA3CPGG.js.map +1 -0
- package/dist/chunk-HZQEDNF6.js +66 -0
- package/dist/chunk-HZQEDNF6.js.map +1 -0
- package/dist/chunk-IT3PWBW4.cjs +19 -0
- package/dist/chunk-IT3PWBW4.cjs.map +1 -0
- package/dist/chunk-JD74LN7R.cjs +171 -0
- package/dist/chunk-JD74LN7R.cjs.map +1 -0
- package/dist/chunk-JTFYYKDT.js +135 -0
- package/dist/chunk-JTFYYKDT.js.map +1 -0
- package/dist/chunk-K2BQQ445.js +30 -0
- package/dist/chunk-K2BQQ445.js.map +1 -0
- package/dist/chunk-KAP4GJHO.js +546 -0
- package/dist/chunk-KAP4GJHO.js.map +1 -0
- package/dist/chunk-KIO7QFIV.cjs +223 -0
- package/dist/chunk-KIO7QFIV.cjs.map +1 -0
- package/dist/chunk-KSKU6JY6.cjs +71 -0
- package/dist/chunk-KSKU6JY6.cjs.map +1 -0
- package/dist/chunk-LSLPF6OI.cjs +192 -0
- package/dist/chunk-LSLPF6OI.cjs.map +1 -0
- package/dist/chunk-LU7VALW5.js +312 -0
- package/dist/chunk-LU7VALW5.js.map +1 -0
- package/dist/chunk-LUSXDZPV.cjs +296 -0
- package/dist/chunk-LUSXDZPV.cjs.map +1 -0
- package/dist/chunk-M72RJVPC.js +69 -0
- package/dist/chunk-M72RJVPC.js.map +1 -0
- package/dist/chunk-MQLCZ4HJ.cjs +1010 -0
- package/dist/chunk-MQLCZ4HJ.cjs.map +1 -0
- package/dist/chunk-MUUQ2WFJ.cjs +4 -0
- package/dist/chunk-MUUQ2WFJ.cjs.map +1 -0
- package/dist/chunk-MZ5ZRORA.cjs +496 -0
- package/dist/chunk-MZ5ZRORA.cjs.map +1 -0
- package/dist/chunk-N24XBYNX.cjs +140 -0
- package/dist/chunk-N24XBYNX.cjs.map +1 -0
- package/dist/chunk-NINIJCHU.cjs +23 -0
- package/dist/chunk-NINIJCHU.cjs.map +1 -0
- package/dist/chunk-NRSH7RJY.js +2841 -0
- package/dist/chunk-NRSH7RJY.js.map +1 -0
- package/dist/chunk-OIYQBUW4.cjs +111 -0
- package/dist/chunk-OIYQBUW4.cjs.map +1 -0
- package/dist/chunk-PNVDQL5Y.cjs +15 -0
- package/dist/chunk-PNVDQL5Y.cjs.map +1 -0
- package/dist/chunk-POQT2OIF.js +214 -0
- package/dist/chunk-POQT2OIF.js.map +1 -0
- package/dist/chunk-QUTUJ6P6.cjs +76 -0
- package/dist/chunk-QUTUJ6P6.cjs.map +1 -0
- package/dist/chunk-S2BBRVQX.js +68 -0
- package/dist/chunk-S2BBRVQX.js.map +1 -0
- package/dist/chunk-S5RCBTSF.js +145 -0
- package/dist/chunk-S5RCBTSF.js.map +1 -0
- package/dist/chunk-S7OEXQMI.cjs +136 -0
- package/dist/chunk-S7OEXQMI.cjs.map +1 -0
- package/dist/chunk-SKWVAQAY.js +129 -0
- package/dist/chunk-SKWVAQAY.js.map +1 -0
- package/dist/chunk-SQLZ7ONU.js +152 -0
- package/dist/chunk-SQLZ7ONU.js.map +1 -0
- package/dist/chunk-TIZ4TS5V.cjs +72 -0
- package/dist/chunk-TIZ4TS5V.cjs.map +1 -0
- package/dist/chunk-TQKCU7CL.js +142 -0
- package/dist/chunk-TQKCU7CL.js.map +1 -0
- package/dist/chunk-U54XCYG3.js +116 -0
- package/dist/chunk-U54XCYG3.js.map +1 -0
- package/dist/chunk-U6QGZHPN.js +29 -0
- package/dist/chunk-U6QGZHPN.js.map +1 -0
- package/dist/chunk-UCFONJBG.js +79 -0
- package/dist/chunk-UCFONJBG.js.map +1 -0
- package/dist/chunk-UJ7IQJAG.js +141 -0
- package/dist/chunk-UJ7IQJAG.js.map +1 -0
- package/dist/chunk-UVNG67DG.js +253 -0
- package/dist/chunk-UVNG67DG.js.map +1 -0
- package/dist/chunk-V4XRLPEF.js +25 -0
- package/dist/chunk-V4XRLPEF.js.map +1 -0
- package/dist/chunk-VJ26EKGJ.cjs +28 -0
- package/dist/chunk-VJ26EKGJ.cjs.map +1 -0
- package/dist/chunk-VK7MAV65.cjs +90 -0
- package/dist/chunk-VK7MAV65.cjs.map +1 -0
- package/dist/chunk-VYCKUKPA.cjs +106 -0
- package/dist/chunk-VYCKUKPA.cjs.map +1 -0
- package/dist/chunk-VYHJZVL5.cjs +29 -0
- package/dist/chunk-VYHJZVL5.cjs.map +1 -0
- package/dist/chunk-WA3FO4R7.js +155 -0
- package/dist/chunk-WA3FO4R7.js.map +1 -0
- package/dist/chunk-WJVHMTKB.cjs +12 -0
- package/dist/chunk-WJVHMTKB.cjs.map +1 -0
- package/dist/chunk-WLKFWQSJ.js +333 -0
- package/dist/chunk-WLKFWQSJ.js.map +1 -0
- package/dist/chunk-WPZTYOUX.cjs +59 -0
- package/dist/chunk-WPZTYOUX.cjs.map +1 -0
- package/dist/chunk-X2FR4OIT.js +27 -0
- package/dist/chunk-X2FR4OIT.js.map +1 -0
- package/dist/chunk-XIG2IE3L.js +134 -0
- package/dist/chunk-XIG2IE3L.js.map +1 -0
- package/dist/chunk-YLQQX5W2.cjs +20 -0
- package/dist/chunk-YLQQX5W2.cjs.map +1 -0
- package/dist/chunk-YPEPCZHF.cjs +147 -0
- package/dist/chunk-YPEPCZHF.cjs.map +1 -0
- package/dist/chunk-YPQF26X7.cjs +8 -0
- package/dist/chunk-YPQF26X7.cjs.map +1 -0
- package/dist/chunk-YU6KON2I.cjs +160 -0
- package/dist/chunk-YU6KON2I.cjs.map +1 -0
- package/dist/chunk-Z2OC3UIW.cjs +388 -0
- package/dist/chunk-Z2OC3UIW.cjs.map +1 -0
- package/dist/chunk-ZZWTY3RX.js +230 -0
- package/dist/chunk-ZZWTY3RX.js.map +1 -0
- package/dist/compact-session-OO2GD76G.js +17 -0
- package/dist/compact-session-OO2GD76G.js.map +1 -0
- package/dist/compact-session-OO7NVWPB.cjs +54 -0
- package/dist/compact-session-OO7NVWPB.cjs.map +1 -0
- package/dist/compaction.cjs +54 -303
- package/dist/compaction.cjs.map +1 -1
- package/dist/compaction.js +3 -292
- package/dist/compaction.js.map +1 -1
- package/dist/concurrency.cjs +9 -81
- package/dist/concurrency.cjs.map +1 -1
- package/dist/concurrency.js +5 -80
- package/dist/concurrency.js.map +1 -1
- package/dist/context-GWANQLX4.js +5 -0
- package/dist/context-GWANQLX4.js.map +1 -0
- package/dist/context-KNWVTZSY.cjs +22 -0
- package/dist/context-KNWVTZSY.cjs.map +1 -0
- package/dist/cron.cjs +44 -20675
- package/dist/cron.cjs.map +1 -1
- package/dist/cron.js +38 -20675
- package/dist/cron.js.map +1 -1
- package/dist/errors.cjs +78 -470
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.js +2 -455
- package/dist/errors.js.map +1 -1
- package/dist/eval.cjs +72 -20410
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +59 -20401
- package/dist/eval.js.map +1 -1
- package/dist/executor-ORJS5GV2.js +981 -0
- package/dist/executor-ORJS5GV2.js.map +1 -0
- package/dist/executor-Y4MKPIUD.cjs +985 -0
- package/dist/executor-Y4MKPIUD.cjs.map +1 -0
- package/dist/filesystem/index.cjs +7 -112
- package/dist/filesystem/index.cjs.map +1 -1
- package/dist/filesystem/index.js +4 -109
- package/dist/filesystem/index.js.map +1 -1
- package/dist/fork-agent-RSV4E3EA.js +61 -0
- package/dist/fork-agent-RSV4E3EA.js.map +1 -0
- package/dist/fork-agent-Y2IK2RYU.cjs +64 -0
- package/dist/fork-agent-Y2IK2RYU.cjs.map +1 -0
- package/dist/fs-session-store-KAUQYSGI.cjs +17 -0
- package/dist/fs-session-store-KAUQYSGI.cjs.map +1 -0
- package/dist/fs-session-store-ZKB5NN37.js +8 -0
- package/dist/fs-session-store-ZKB5NN37.js.map +1 -0
- package/dist/generate-object-H3RNAM6S.cjs +20 -0
- package/dist/generate-object-H3RNAM6S.cjs.map +1 -0
- package/dist/generate-object-YJPDV5BS.js +7 -0
- package/dist/generate-object-YJPDV5BS.js.map +1 -0
- package/dist/index-manager-CB6I7XFQ.cjs +19 -0
- package/dist/index-manager-CB6I7XFQ.cjs.map +1 -0
- package/dist/index-manager-L27Q3QAC.js +10 -0
- package/dist/index-manager-L27Q3QAC.js.map +1 -0
- package/dist/index.cjs +371 -22887
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +92 -22712
- package/dist/index.js.map +1 -1
- package/dist/inject-session-6MJUSGZP.cjs +27 -0
- package/dist/inject-session-6MJUSGZP.cjs.map +1 -0
- package/dist/inject-session-KOFHS5K3.js +25 -0
- package/dist/inject-session-KOFHS5K3.js.map +1 -0
- package/dist/internal/auth/credential-store.d.ts +20 -3
- package/dist/internal/persistence/index.cjs +93 -508
- package/dist/internal/persistence/index.cjs.map +1 -1
- package/dist/internal/persistence/index.js +11 -489
- package/dist/internal/persistence/index.js.map +1 -1
- package/dist/internal/security/index.cjs +44 -361
- package/dist/internal/security/index.cjs.map +1 -1
- package/dist/internal/security/index.js +4 -355
- package/dist/internal/security/index.js.map +1 -1
- package/dist/judge-call-7CF7D334.cjs +95 -0
- package/dist/judge-call-7CF7D334.cjs.map +1 -0
- package/dist/judge-call-VIMNK5TA.js +92 -0
- package/dist/judge-call-VIMNK5TA.js.map +1 -0
- package/dist/models.cjs +24 -913
- package/dist/models.cjs.map +1 -1
- package/dist/models.js +11 -901
- package/dist/models.js.map +1 -1
- package/dist/oauth-transaction-store-7CKHPQRN.cjs +32 -0
- package/dist/oauth-transaction-store-7CKHPQRN.cjs.map +1 -0
- package/dist/oauth-transaction-store-W74I6EFD.js +3 -0
- package/dist/oauth-transaction-store-W74I6EFD.js.map +1 -0
- package/dist/path-safety.cjs +31 -200
- package/dist/path-safety.cjs.map +1 -1
- package/dist/path-safety.js +3 -197
- package/dist/path-safety.js.map +1 -1
- package/dist/persistence.cjs +73 -393
- package/dist/persistence.cjs.map +1 -1
- package/dist/persistence.js +9 -381
- package/dist/persistence.js.map +1 -1
- package/dist/project.cjs +8 -112
- package/dist/project.cjs.map +1 -1
- package/dist/project.js +6 -110
- package/dist/project.js.map +1 -1
- package/dist/registry-34IWWDQQ.js +9 -0
- package/dist/registry-34IWWDQQ.js.map +1 -0
- package/dist/registry-APYDISL6.cjs +46 -0
- package/dist/registry-APYDISL6.cjs.map +1 -0
- package/dist/retry.cjs +7 -87
- package/dist/retry.cjs.map +1 -1
- package/dist/retry.js +3 -90
- package/dist/retry.js.map +1 -1
- package/dist/run-to-completion-J73I6IY4.cjs +48 -0
- package/dist/run-to-completion-J73I6IY4.cjs.map +1 -0
- package/dist/run-to-completion-JDPIUKSH.js +3 -0
- package/dist/run-to-completion-JDPIUKSH.js.map +1 -0
- package/dist/run-until-2PX4QBHZ.js +168 -0
- package/dist/run-until-2PX4QBHZ.js.map +1 -0
- package/dist/run-until-DB3LVGZS.cjs +171 -0
- package/dist/run-until-DB3LVGZS.cjs.map +1 -0
- package/dist/sandbox/index.cjs +35 -337
- package/dist/sandbox/index.cjs.map +1 -1
- package/dist/sandbox/index.js +7 -323
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sanitize/index.cjs +5 -112
- package/dist/sanitize/index.cjs.map +1 -1
- package/dist/sanitize/index.js +1 -114
- package/dist/sanitize/index.js.map +1 -1
- package/dist/server/auth/index.cjs +35 -175
- package/dist/server/auth/index.cjs.map +1 -1
- package/dist/server/auth/index.js +7 -161
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/errors-envelope.cjs +17 -328
- package/dist/server/errors-envelope.cjs.map +1 -1
- package/dist/server/errors-envelope.js +4 -317
- package/dist/server/errors-envelope.js.map +1 -1
- package/dist/session-transcript-LPNZR3YS.cjs +46 -0
- package/dist/session-transcript-LPNZR3YS.cjs.map +1 -0
- package/dist/session-transcript-T7LGJUGW.js +5 -0
- package/dist/session-transcript-T7LGJUGW.js.map +1 -0
- package/dist/skills.cjs +12 -280
- package/dist/skills.cjs.map +1 -1
- package/dist/skills.js +4 -282
- package/dist/skills.js.map +1 -1
- package/dist/stream-object-QEQJJDTI.cjs +20 -0
- package/dist/stream-object-QEQJJDTI.cjs.map +1 -0
- package/dist/stream-object-WUQSSRY2.js +7 -0
- package/dist/stream-object-WUQSSRY2.js.map +1 -0
- package/dist/stream-to-completion-DFJ5T3BK.js +30 -0
- package/dist/stream-to-completion-DFJ5T3BK.js.map +1 -0
- package/dist/stream-to-completion-H2MHISSK.cjs +32 -0
- package/dist/stream-to-completion-H2MHISSK.cjs.map +1 -0
- package/dist/subagents.cjs +2 -8
- package/dist/subagents.cjs.map +1 -1
- package/dist/subagents.js +1 -7
- package/dist/subagents.js.map +1 -1
- package/dist/subscription/index.cjs +4 -17
- package/dist/subscription/index.cjs.map +1 -1
- package/dist/subscription/index.js +3 -16
- package/dist/subscription/index.js.map +1 -1
- package/dist/task-store.cjs +16 -258
- package/dist/task-store.cjs.map +1 -1
- package/dist/task-store.js +4 -259
- package/dist/task-store.js.map +1 -1
- package/dist/workflow.cjs +71 -2797
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.js +8 -2812
- package/dist/workflow.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from 'fs';
|
|
2
|
+
import { readdir } from 'fs/promises';
|
|
3
|
+
import { isAbsolute, resolve, join, dirname } from 'path';
|
|
4
|
+
|
|
5
|
+
// src/internal/runtime/context/context-discovery.ts
|
|
6
|
+
var DEFAULT_DISCOVERY_SPECS = [
|
|
7
|
+
{
|
|
8
|
+
id: "AGENTS.md",
|
|
9
|
+
pattern: "AGENTS.md",
|
|
10
|
+
scope: "git-root-walk",
|
|
11
|
+
parser: "plain-markdown",
|
|
12
|
+
followImports: false,
|
|
13
|
+
priority: 10
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
id: "GEMINI.md",
|
|
17
|
+
pattern: "GEMINI.md",
|
|
18
|
+
scope: "git-root-walk",
|
|
19
|
+
parser: "plain-markdown",
|
|
20
|
+
followImports: true,
|
|
21
|
+
priority: 20
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
id: "CLAUDE.md",
|
|
25
|
+
pattern: "CLAUDE.md",
|
|
26
|
+
scope: "git-root-walk",
|
|
27
|
+
parser: "plain-markdown",
|
|
28
|
+
followImports: true,
|
|
29
|
+
priority: 30
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
id: "cursor-rules",
|
|
33
|
+
pattern: ".cursor/rules/*.mdc",
|
|
34
|
+
scope: "globbed",
|
|
35
|
+
parser: "mdc",
|
|
36
|
+
followImports: false,
|
|
37
|
+
priority: 40
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
id: "theokit-rules",
|
|
41
|
+
pattern: ".theokit/rules/*.md",
|
|
42
|
+
scope: "globbed",
|
|
43
|
+
parser: "rules-frontmatter",
|
|
44
|
+
followImports: false,
|
|
45
|
+
priority: 45
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
id: "theokit-context",
|
|
49
|
+
pattern: ".theokit/context/*.md",
|
|
50
|
+
scope: "globbed",
|
|
51
|
+
parser: "frontmatter-zod",
|
|
52
|
+
followImports: false,
|
|
53
|
+
priority: 50
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
id: "THEO.md",
|
|
57
|
+
pattern: ".theokit/THEO.md",
|
|
58
|
+
scope: "cwd-only",
|
|
59
|
+
parser: "plain-markdown",
|
|
60
|
+
followImports: false,
|
|
61
|
+
priority: 60
|
|
62
|
+
}
|
|
63
|
+
];
|
|
64
|
+
var SAFE_FILENAME = /^[a-zA-Z0-9_.\-/*]+$/;
|
|
65
|
+
var TRAVERSAL_RE = /(^|\/)\.\.(\/|$)/;
|
|
66
|
+
function isSafePattern(pattern) {
|
|
67
|
+
if (typeof pattern !== "string" || pattern.length === 0) return false;
|
|
68
|
+
if (TRAVERSAL_RE.test(pattern)) return false;
|
|
69
|
+
if (isAbsolute(pattern)) return false;
|
|
70
|
+
return SAFE_FILENAME.test(pattern);
|
|
71
|
+
}
|
|
72
|
+
function findGitRoot(cwd) {
|
|
73
|
+
if (typeof cwd !== "string" || cwd.length === 0) return void 0;
|
|
74
|
+
let current = resolve(cwd);
|
|
75
|
+
for (let i = 0; i < 64; i += 1) {
|
|
76
|
+
if (existsSync(join(current, ".git"))) return current;
|
|
77
|
+
const parent = dirname(current);
|
|
78
|
+
if (parent === current) return void 0;
|
|
79
|
+
current = parent;
|
|
80
|
+
}
|
|
81
|
+
return void 0;
|
|
82
|
+
}
|
|
83
|
+
function walkUpForFile(cwd, filename, stopDir) {
|
|
84
|
+
if (!isSafePattern(filename)) {
|
|
85
|
+
return [];
|
|
86
|
+
}
|
|
87
|
+
const start = resolve(cwd);
|
|
88
|
+
const stop = stopDir !== void 0 ? resolve(stopDir) : void 0;
|
|
89
|
+
const found = [];
|
|
90
|
+
const seenReal = /* @__PURE__ */ new Set();
|
|
91
|
+
let current = start;
|
|
92
|
+
for (let i = 0; i < 64; i += 1) {
|
|
93
|
+
const candidate = join(current, filename);
|
|
94
|
+
if (existsSync(candidate)) {
|
|
95
|
+
let real;
|
|
96
|
+
try {
|
|
97
|
+
real = realpathSync(candidate);
|
|
98
|
+
} catch {
|
|
99
|
+
real = candidate;
|
|
100
|
+
}
|
|
101
|
+
if (!seenReal.has(real)) {
|
|
102
|
+
seenReal.add(real);
|
|
103
|
+
found.push(real);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (stop !== void 0 && current === stop) break;
|
|
107
|
+
const parent = dirname(current);
|
|
108
|
+
if (parent === current) break;
|
|
109
|
+
current = parent;
|
|
110
|
+
}
|
|
111
|
+
return found;
|
|
112
|
+
}
|
|
113
|
+
async function walkUpForGlob(cwd, pattern) {
|
|
114
|
+
if (!isSafePattern(pattern)) return [];
|
|
115
|
+
const lastSlash = pattern.lastIndexOf("/");
|
|
116
|
+
if (lastSlash < 0) {
|
|
117
|
+
const candidate = join(cwd, pattern);
|
|
118
|
+
return existsSync(candidate) ? [resolve(candidate)] : [];
|
|
119
|
+
}
|
|
120
|
+
const dirPart = pattern.slice(0, lastSlash);
|
|
121
|
+
const filePart = pattern.slice(lastSlash + 1);
|
|
122
|
+
const dir = join(cwd, dirPart);
|
|
123
|
+
if (!existsSync(dir)) return [];
|
|
124
|
+
const fileRe = filePartToRegex(filePart);
|
|
125
|
+
let entries;
|
|
126
|
+
try {
|
|
127
|
+
entries = await readdir(dir);
|
|
128
|
+
} catch {
|
|
129
|
+
return [];
|
|
130
|
+
}
|
|
131
|
+
const matched = entries.filter((e) => fileRe.test(e)).sort();
|
|
132
|
+
return matched.map((e) => resolve(join(dir, e)));
|
|
133
|
+
}
|
|
134
|
+
function filePartToRegex(filePart) {
|
|
135
|
+
const escaped = filePart.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
|
|
136
|
+
return new RegExp(`^${escaped}$`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export { DEFAULT_DISCOVERY_SPECS, findGitRoot, isSafePattern, walkUpForFile, walkUpForGlob };
|
|
140
|
+
//# sourceMappingURL=chunk-UJ7IQJAG.js.map
|
|
141
|
+
//# sourceMappingURL=chunk-UJ7IQJAG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/context/context-discovery.ts"],"names":[],"mappings":";;;;;AAsDO,IAAM,uBAAA,GAAwD;AAAA,EACnE;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,EAAS,WAAA;AAAA,IACT,KAAA,EAAO,eAAA;AAAA,IACP,MAAA,EAAQ,gBAAA;AAAA,IACR,aAAA,EAAe,KAAA;AAAA,IACf,QAAA,EAAU;AAAA,GACZ;AAAA,EACA;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,EAAS,WAAA;AAAA,IACT,KAAA,EAAO,eAAA;AAAA,IACP,MAAA,EAAQ,gBAAA;AAA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AAC,UAAA,CAAW,GAAG,CAAA,SAAU,EAAC;AAE9B,EAAA,MAAM,MAAA,GAAS,gBAAgB,QAAQ,CAAA;AACvC,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,QAAQ,GAAG,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACA,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,KAAM,OAAO,IAAA,CAAK,CAAC,CAAC,CAAA,CAAE,IAAA,EAAK;AAC3D,EAAA,OAAO,OAAA,CAAQ,IAAI,CAAC,CAAA,KAAM,QAAQ,IAAA,CAAK,GAAA,EAAK,CAAC,CAAC,CAAC,CAAA;AACjD;AAEA,SAAS,gBAAgB,QAAA,EAA0B;AACjD,EAAA,MAAM,OAAA,GAAU,SAAS,OAAA,CAAQ,mBAAA,EAAqB,MAAM,CAAA,CAAE,OAAA,CAAQ,OAAO,IAAI,CAAA;AACjF,EAAA,OAAO,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,OAAO,CAAA,CAAA,CAAG,CAAA;AAClC","file":"chunk-UJ7IQJAG.js","sourcesContent":["/**\n * Context file discovery (T1.1, ADRs D150 / D151).\n *\n * Discovers context files via three scopes:\n * - `cwd-only` — single dir, single path lookup\n * - `git-root-walk` — walk cwd → git-root, collect every directory's match\n * (nearest-first ordering)\n * - `globbed` — glob pattern relative to cwd (e.g. `.cursor/rules/*.mdc`)\n *\n * Pure `existsSync` checks — **no `.gitignore` parsing** (EC-A, KISS) and\n * **no invented `.theokitignore`** (EC-B). Paths normalized via\n * `realpath` to dedup symlink chains pointing to the same physical file\n * (EC-F). Git worktrees work transparently because `.git` exists as a\n * file in that case (EC-N).\n *\n * @internal\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\n\n/** Single filename (\"AGENTS.md\") or relative glob (\".cursor/rules/*.mdc\"). */\nexport type DiscoveryScope = \"cwd-only\" | \"git-root-walk\" | \"globbed\";\n\n/** Parser to apply once file is read. */\nexport type DiscoveryParser = \"plain-markdown\" | \"mdc\" | \"frontmatter-zod\" | \"rules-frontmatter\";\n\n/**\n * Specification for one discoverable context source. The default registry\n * `DEFAULT_DISCOVERY_SPECS` covers the 2026 industry-standard set.\n *\n * @internal\n */\nexport interface DiscoverySpec {\n /** Stable identifier — used as `<source name=\"\">` and telemetry key. */\n readonly id: string;\n /** Priority for merge (lower = earlier in prompt). */\n readonly priority: number;\n /** Filename (cwd-only/git-root-walk) or glob (globbed). */\n readonly pattern: string;\n readonly scope: DiscoveryScope;\n readonly parser: DiscoveryParser;\n /** Whether to follow `@path` import directives (CLAUDE.md / GEMINI.md). */\n readonly followImports: boolean;\n}\n\n/**\n * 2026 industry-standard context file registry. Sorted by priority\n * ascending — earlier in prompt = more general, last-writer-wins on\n * conflict (D152 concat-by-priority).\n *\n * @internal\n */\nexport const DEFAULT_DISCOVERY_SPECS: ReadonlyArray<DiscoverySpec> = [\n {\n id: \"AGENTS.md\",\n pattern: \"AGENTS.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 10,\n },\n {\n id: \"GEMINI.md\",\n pattern: \"GEMINI.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 20,\n },\n {\n id: \"CLAUDE.md\",\n pattern: \"CLAUDE.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 30,\n },\n {\n id: \"cursor-rules\",\n pattern: \".cursor/rules/*.mdc\",\n scope: \"globbed\",\n parser: \"mdc\",\n followImports: false,\n priority: 40,\n },\n {\n id: \"theokit-rules\",\n pattern: \".theokit/rules/*.md\",\n scope: \"globbed\",\n parser: \"rules-frontmatter\",\n followImports: false,\n priority: 45,\n },\n {\n id: \"theokit-context\",\n pattern: \".theokit/context/*.md\",\n scope: \"globbed\",\n parser: \"frontmatter-zod\",\n followImports: false,\n priority: 50,\n },\n {\n id: \"THEO.md\",\n pattern: \".theokit/THEO.md\",\n scope: \"cwd-only\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 60,\n },\n];\n\nconst SAFE_FILENAME = /^[a-zA-Z0-9_.\\-/*]+$/;\nconst TRAVERSAL_RE = /(^|\\/)\\.\\.(\\/|$)/;\n\n/**\n * Reject patterns that contain path traversal (`..`) or non-allowed\n * characters (D81 parity, EC-4).\n *\n * @internal\n */\nexport function isSafePattern(pattern: string): boolean {\n if (typeof pattern !== \"string\" || pattern.length === 0) return false;\n if (TRAVERSAL_RE.test(pattern)) return false;\n if (isAbsolute(pattern)) return false;\n return SAFE_FILENAME.test(pattern);\n}\n\n/**\n * Walk upward from `cwd` looking for the closest directory containing\n * a `.git` entry (file OR directory — worktrees use a `.git` FILE,\n * EC-N). Returns the absolute path of that directory, or `undefined`\n * when no git root exists at or above `cwd`.\n *\n * @internal\n */\nexport function findGitRoot(cwd: string): string | undefined {\n if (typeof cwd !== \"string\" || cwd.length === 0) return undefined;\n let current = resolve(cwd);\n // Guard against infinite loops on weird filesystems.\n for (let i = 0; i < 64; i += 1) {\n if (existsSync(join(current, \".git\"))) return current;\n const parent = dirname(current);\n if (parent === current) return undefined;\n current = parent;\n }\n return undefined;\n}\n\n/**\n * Walk `cwd` upward to `stopDir` (inclusive) collecting every existing\n * occurrence of `filename`. Returns absolute, realpath-deduped paths in\n * nearest-first order (innermost dir first).\n *\n * No `.gitignore` parsing (EC-A). Realpath collapses symlink chains\n * pointing to the same physical file (EC-F). Filesystem races (file\n * deleted mid-walk) are skipped silently (EC-5).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: walk-up loop combines validation + realpath dedup + FS-race handling + stopDir guard in a single bounded loop; splitting fragments the dedup invariant.\nexport function walkUpForFile(\n cwd: string,\n filename: string,\n stopDir: string | undefined,\n): string[] {\n if (!isSafePattern(filename)) {\n return [];\n }\n const start = resolve(cwd);\n const stop = stopDir !== undefined ? resolve(stopDir) : undefined;\n const found: string[] = [];\n const seenReal = new Set<string>();\n let current = start;\n // 64-level depth cap.\n for (let i = 0; i < 64; i += 1) {\n const candidate = join(current, filename);\n if (existsSync(candidate)) {\n let real: string;\n try {\n real = realpathSync(candidate);\n } catch {\n // FS race (deleted mid-walk) — skip.\n real = candidate;\n }\n if (!seenReal.has(real)) {\n seenReal.add(real);\n found.push(real);\n }\n }\n if (stop !== undefined && current === stop) break;\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return found;\n}\n\n/**\n * Glob-style discovery scoped to a single directory under cwd (e.g.\n * `.cursor/rules/*.mdc`). Flat — does NOT recurse into subdirectories\n * (EC-R: nested directories deferred to v2). Returns absolute,\n * lex-sorted paths.\n *\n * @internal\n */\nexport async function walkUpForGlob(cwd: string, pattern: string): Promise<string[]> {\n if (!isSafePattern(pattern)) return [];\n const lastSlash = pattern.lastIndexOf(\"/\");\n if (lastSlash < 0) {\n // Single filename — treat as cwd-only single match.\n const candidate = join(cwd, pattern);\n return existsSync(candidate) ? [resolve(candidate)] : [];\n }\n const dirPart = pattern.slice(0, lastSlash);\n const filePart = pattern.slice(lastSlash + 1);\n const dir = join(cwd, dirPart);\n if (!existsSync(dir)) return [];\n // Build a regex from the file part — supports only `*` wildcard.\n const fileRe = filePartToRegex(filePart);\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n const matched = entries.filter((e) => fileRe.test(e)).sort();\n return matched.map((e) => resolve(join(dir, e)));\n}\n\nfunction filePartToRegex(filePart: string): RegExp {\n const escaped = filePart.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\");\n return new RegExp(`^${escaped}$`);\n}\n"]}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { atomicWriteText } from './chunk-S2BBRVQX.js';
|
|
2
|
+
import { mkdir, readFile, readdir } from 'fs/promises';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
|
|
5
|
+
// src/types/workflow.ts
|
|
6
|
+
var WorkflowDuplicateStepIdError = class extends Error {
|
|
7
|
+
constructor(stepId) {
|
|
8
|
+
super(`Duplicate step id "${stepId}" in workflow.`);
|
|
9
|
+
this.stepId = stepId;
|
|
10
|
+
}
|
|
11
|
+
stepId;
|
|
12
|
+
name = "WorkflowDuplicateStepIdError";
|
|
13
|
+
};
|
|
14
|
+
var WorkflowInputError = class extends Error {
|
|
15
|
+
constructor(workflowName, detail) {
|
|
16
|
+
super(`Workflow "${workflowName}" input failed schema validation: ${detail}`);
|
|
17
|
+
this.workflowName = workflowName;
|
|
18
|
+
this.detail = detail;
|
|
19
|
+
}
|
|
20
|
+
workflowName;
|
|
21
|
+
detail;
|
|
22
|
+
name = "WorkflowInputError";
|
|
23
|
+
};
|
|
24
|
+
var WorkflowOutputError = class extends Error {
|
|
25
|
+
constructor(workflowName, detail) {
|
|
26
|
+
super(`Workflow "${workflowName}" output failed schema validation: ${detail}`);
|
|
27
|
+
this.workflowName = workflowName;
|
|
28
|
+
this.detail = detail;
|
|
29
|
+
}
|
|
30
|
+
workflowName;
|
|
31
|
+
detail;
|
|
32
|
+
name = "WorkflowOutputError";
|
|
33
|
+
};
|
|
34
|
+
var WorkflowStateError = class extends Error {
|
|
35
|
+
constructor(workflowName, detail) {
|
|
36
|
+
super(`Workflow "${workflowName}" state failed schema validation: ${detail}`);
|
|
37
|
+
this.workflowName = workflowName;
|
|
38
|
+
this.detail = detail;
|
|
39
|
+
}
|
|
40
|
+
workflowName;
|
|
41
|
+
detail;
|
|
42
|
+
name = "WorkflowStateError";
|
|
43
|
+
};
|
|
44
|
+
var WorkflowNestedError = class extends Error {
|
|
45
|
+
constructor(stepId, childName, childStatus, childError) {
|
|
46
|
+
super(
|
|
47
|
+
`Nested workflow "${childName}" (step "${stepId}") ended with status "${childStatus}"${childStatus === "suspended" ? " \u2014 nested suspend/resume is not supported in v1 (use a top-level suspend)" : ""}${childError ? `: ${childError.name}: ${childError.message}` : ""}`,
|
|
48
|
+
// Reconstruct a synthetic Error from the serialized child-error shape so
|
|
49
|
+
// debuggers surface the nested cause chain — the original Error instance is
|
|
50
|
+
// lost at the WorkflowRun serialization boundary, so this is the best
|
|
51
|
+
// achievable without changing the run protocol.
|
|
52
|
+
childError ? { cause: Object.assign(new Error(childError.message), { name: childError.name }) } : void 0
|
|
53
|
+
);
|
|
54
|
+
this.stepId = stepId;
|
|
55
|
+
this.childName = childName;
|
|
56
|
+
this.childStatus = childStatus;
|
|
57
|
+
this.childError = childError;
|
|
58
|
+
}
|
|
59
|
+
stepId;
|
|
60
|
+
childName;
|
|
61
|
+
childStatus;
|
|
62
|
+
childError;
|
|
63
|
+
name = "WorkflowNestedError";
|
|
64
|
+
};
|
|
65
|
+
var WorkflowAlreadyRunningError = class extends Error {
|
|
66
|
+
constructor(workflowName, runId) {
|
|
67
|
+
super(`Workflow "${workflowName}" run "${runId}" already in-flight.`);
|
|
68
|
+
this.workflowName = workflowName;
|
|
69
|
+
this.runId = runId;
|
|
70
|
+
}
|
|
71
|
+
workflowName;
|
|
72
|
+
runId;
|
|
73
|
+
name = "WorkflowAlreadyRunningError";
|
|
74
|
+
};
|
|
75
|
+
var WorkflowSnapshotNotFoundError = class extends Error {
|
|
76
|
+
constructor(runId) {
|
|
77
|
+
super(`No snapshot found for runId "${runId}". Configure persistence to enable resume.`);
|
|
78
|
+
this.runId = runId;
|
|
79
|
+
}
|
|
80
|
+
runId;
|
|
81
|
+
name = "WorkflowSnapshotNotFoundError";
|
|
82
|
+
};
|
|
83
|
+
var WorkflowMaxIterationsExceededError = class extends Error {
|
|
84
|
+
constructor(stepId, maxIterations) {
|
|
85
|
+
super(`Step "${stepId}" exceeded max iterations (${maxIterations}).`);
|
|
86
|
+
this.stepId = stepId;
|
|
87
|
+
this.maxIterations = maxIterations;
|
|
88
|
+
}
|
|
89
|
+
stepId;
|
|
90
|
+
maxIterations;
|
|
91
|
+
name = "WorkflowMaxIterationsExceededError";
|
|
92
|
+
};
|
|
93
|
+
var WorkflowNotSerializableError = class extends Error {
|
|
94
|
+
constructor(stepId, underlying) {
|
|
95
|
+
super(
|
|
96
|
+
`Workflow snapshot at step "${stepId}" failed to serialize as JSON: ${underlying.message}. Persisted snapshots support only JSON-serializable values (no BigInt, no circular refs, no class instances with cycles).`
|
|
97
|
+
);
|
|
98
|
+
this.stepId = stepId;
|
|
99
|
+
this.underlying = underlying;
|
|
100
|
+
}
|
|
101
|
+
stepId;
|
|
102
|
+
underlying;
|
|
103
|
+
name = "WorkflowNotSerializableError";
|
|
104
|
+
};
|
|
105
|
+
var WorkflowResumeStepNotFoundError = class extends Error {
|
|
106
|
+
constructor(stepId, workflowName) {
|
|
107
|
+
super(
|
|
108
|
+
`Cannot resume: step "${stepId}" not found in workflow "${workflowName}". The Workflow definition diverged from the snapshot.`
|
|
109
|
+
);
|
|
110
|
+
this.stepId = stepId;
|
|
111
|
+
this.workflowName = workflowName;
|
|
112
|
+
}
|
|
113
|
+
stepId;
|
|
114
|
+
workflowName;
|
|
115
|
+
name = "WorkflowResumeStepNotFoundError";
|
|
116
|
+
};
|
|
117
|
+
var WorkflowParallelError = class extends AggregateError {
|
|
118
|
+
constructor(errors, stepId) {
|
|
119
|
+
super(errors, `${errors.length} branch(es) failed in parallel step "${stepId}".`);
|
|
120
|
+
this.stepId = stepId;
|
|
121
|
+
}
|
|
122
|
+
stepId;
|
|
123
|
+
name = "WorkflowParallelError";
|
|
124
|
+
};
|
|
125
|
+
var WorkflowCompensateNotImplementedError = class extends Error {
|
|
126
|
+
constructor(stepId) {
|
|
127
|
+
super(
|
|
128
|
+
`Step "${stepId}" defines compensate, but saga engine is deferred to v1.2. Remove compensate or implement rollback manually.`
|
|
129
|
+
);
|
|
130
|
+
this.stepId = stepId;
|
|
131
|
+
}
|
|
132
|
+
stepId;
|
|
133
|
+
name = "WorkflowCompensateNotImplementedError";
|
|
134
|
+
};
|
|
135
|
+
var InMemoryWorkflowSnapshotStore = class {
|
|
136
|
+
map = /* @__PURE__ */ new Map();
|
|
137
|
+
async save(snapshot) {
|
|
138
|
+
try {
|
|
139
|
+
JSON.stringify(snapshot);
|
|
140
|
+
} catch (err) {
|
|
141
|
+
throw new WorkflowNotSerializableError(
|
|
142
|
+
snapshot.currentStepId,
|
|
143
|
+
err instanceof Error ? err : new Error(String(err))
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
this.map.set(snapshot.runId, snapshot);
|
|
147
|
+
}
|
|
148
|
+
async load(runId) {
|
|
149
|
+
return this.map.get(runId);
|
|
150
|
+
}
|
|
151
|
+
async delete(runId) {
|
|
152
|
+
this.map.delete(runId);
|
|
153
|
+
}
|
|
154
|
+
async list(workflowName) {
|
|
155
|
+
return [...this.map.values()].filter((s) => workflowName === void 0 || s.workflowName === workflowName).map((s) => ({
|
|
156
|
+
runId: s.runId,
|
|
157
|
+
workflowName: s.workflowName,
|
|
158
|
+
suspendedAt: s.suspendedAt
|
|
159
|
+
}));
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
var JsonFileWorkflowSnapshotStore = class {
|
|
163
|
+
constructor(dir) {
|
|
164
|
+
this.dir = dir;
|
|
165
|
+
}
|
|
166
|
+
dir;
|
|
167
|
+
filePath(runId) {
|
|
168
|
+
return join(this.dir, `${runId}.json`);
|
|
169
|
+
}
|
|
170
|
+
async save(snapshot) {
|
|
171
|
+
let serialized;
|
|
172
|
+
try {
|
|
173
|
+
serialized = JSON.stringify(snapshot);
|
|
174
|
+
} catch (err) {
|
|
175
|
+
throw new WorkflowNotSerializableError(
|
|
176
|
+
snapshot.currentStepId,
|
|
177
|
+
err instanceof Error ? err : new Error(String(err))
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
await mkdir(this.dir, { recursive: true });
|
|
181
|
+
await atomicWriteText(this.filePath(snapshot.runId), serialized);
|
|
182
|
+
}
|
|
183
|
+
async load(runId) {
|
|
184
|
+
try {
|
|
185
|
+
const raw = await readFile(this.filePath(runId), "utf8");
|
|
186
|
+
return JSON.parse(raw);
|
|
187
|
+
} catch (err) {
|
|
188
|
+
if (err.code === "ENOENT") return void 0;
|
|
189
|
+
throw err;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async delete(runId) {
|
|
193
|
+
try {
|
|
194
|
+
await (await import('fs/promises')).unlink(this.filePath(runId));
|
|
195
|
+
} catch (err) {
|
|
196
|
+
if (err.code !== "ENOENT") throw err;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
async readEntriesOrEmpty() {
|
|
200
|
+
try {
|
|
201
|
+
return await readdir(this.dir);
|
|
202
|
+
} catch (err) {
|
|
203
|
+
if (err.code === "ENOENT") return [];
|
|
204
|
+
throw err;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
async readSnapshotSafe(file) {
|
|
208
|
+
try {
|
|
209
|
+
const raw = await readFile(join(this.dir, file), "utf8");
|
|
210
|
+
return JSON.parse(raw);
|
|
211
|
+
} catch {
|
|
212
|
+
return void 0;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async list(workflowName) {
|
|
216
|
+
const entries = await this.readEntriesOrEmpty();
|
|
217
|
+
const results = [];
|
|
218
|
+
for (const file of entries) {
|
|
219
|
+
if (!file.endsWith(".json")) continue;
|
|
220
|
+
const snap = await this.readSnapshotSafe(file);
|
|
221
|
+
if (snap === void 0) continue;
|
|
222
|
+
if (workflowName !== void 0 && snap.workflowName !== workflowName) continue;
|
|
223
|
+
results.push({
|
|
224
|
+
runId: snap.runId,
|
|
225
|
+
workflowName: snap.workflowName,
|
|
226
|
+
suspendedAt: snap.suspendedAt
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
return results;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
var memoryStore = new InMemoryWorkflowSnapshotStore();
|
|
233
|
+
var jsonStores = /* @__PURE__ */ new Map();
|
|
234
|
+
function getSnapshotStoreFor(options) {
|
|
235
|
+
if (options.persistence?.backend === "json") {
|
|
236
|
+
const dir = options.persistence.dir;
|
|
237
|
+
let store = jsonStores.get(dir);
|
|
238
|
+
if (store === void 0) {
|
|
239
|
+
store = new JsonFileWorkflowSnapshotStore(dir);
|
|
240
|
+
jsonStores.set(dir, store);
|
|
241
|
+
}
|
|
242
|
+
return store;
|
|
243
|
+
}
|
|
244
|
+
return memoryStore;
|
|
245
|
+
}
|
|
246
|
+
function __resetSnapshotStoresForTests() {
|
|
247
|
+
jsonStores.clear();
|
|
248
|
+
memoryStore.map.clear();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export { WorkflowAlreadyRunningError, WorkflowCompensateNotImplementedError, WorkflowDuplicateStepIdError, WorkflowInputError, WorkflowMaxIterationsExceededError, WorkflowNestedError, WorkflowNotSerializableError, WorkflowOutputError, WorkflowParallelError, WorkflowResumeStepNotFoundError, WorkflowSnapshotNotFoundError, WorkflowStateError, __resetSnapshotStoresForTests, getSnapshotStoreFor };
|
|
252
|
+
//# sourceMappingURL=chunk-UVNG67DG.js.map
|
|
253
|
+
//# sourceMappingURL=chunk-UVNG67DG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types/workflow.ts","../src/internal/workflow/snapshot-store.ts"],"names":[],"mappings":";;;;;AA2RO,IAAM,4BAAA,GAAN,cAA2C,KAAA,CAAM;AAAA,EAEtD,YAA4B,MAAA,EAAgB;AAC1C,IAAA,KAAA,CAAM,CAAA,mBAAA,EAAsB,MAAM,CAAA,cAAA,CAAgB,CAAA;AADxB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAE5B;AAAA,EAF4B,MAAA;AAAA,EADV,IAAA,GAAO,8BAAA;AAI3B;AAMO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAE5C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,EAAa,YAAY,CAAA,kCAAA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AAA,KAAiB,MAAA,IAAa,IAAA,CAAK,YAAA,KAAiB,YAAA,EAAc;AACtE,MAAA,OAAA,CAAQ,IAAA,CAAK;AAAA,QACX,OAAO,IAAA,CAAK,KAAA;AAAA,QACZ,cAAc,IAAA,CAAK,YAAA;AAAA,QACnB,aAAa,IAAA,CAAK;AAAA,OACnB,CAAA;AAAA,IACH;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AACF,CAAA;AAIA,IAAM,WAAA,GAAc,IAAI,6BAAA,EAA8B;AACtD,IAAM,UAAA,uBAAiB,GAAA,EAA2C;AAE3D,SAAS,oBAAoB,OAAA,EAAiD;AACnF,EAAA,IAAI,OAAA,CAAQ,WAAA,EAAa,OAAA,KAAY,MAAA,EAAQ;AAC3C,IAAA,MAAM,GAAA,GAAM,QAAQ,WAAA,CAAY,GAAA;AAChC,IAAA,IAAI,KAAA,GAAQ,UAAA,CAAW,GAAA,CAAI,GAAG,CAAA;AAC9B,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,KAAA,GAAQ,IAAI,8BAA8B,GAAG,CAAA;AAC7C,MAAA,UAAA,CAAW,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,IAC3B;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,WAAA;AACT;AAGO,SAAS,6BAAA,GAAsC;AACpD,EAAA,UAAA,CAAW,KAAA,EAAM;AAGjB,EAAC,WAAA,CAAoB,IAAI,KAAA,EAAM;AACjC","file":"chunk-UVNG67DG.js","sourcesContent":["/**\n * Public type contract for `Workflow.create / .run / .resume` (Adoption\n * Roadmap #5; ADRs D230-D248).\n *\n * Step types form a discriminated union by `kind`. Helper factory functions\n * (`fn()`, `agentStep()`) live in `workflow.ts` and hide the discriminator\n * from end users.\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\n\nimport type { SDKAgent } from \"./agent.js\";\nimport type { MessageOrigin } from \"./run.js\";\n\n/* ─── Step discriminated union (D232) ─── */\n\nexport type Step =\n | FnStep\n | AgentStep\n | ParallelStep\n | BranchStep\n | ForeachStep\n | DowhileStep\n | SleepStep\n | SuspendStep;\n\n/** A pure function step. */\nexport interface FnStep {\n readonly kind: \"fn\";\n readonly id: string;\n readonly fn: (input: unknown, ctx: StepContext) => Promise<unknown> | unknown;\n readonly inputSchema?: ZodType;\n readonly outputSchema?: ZodType;\n readonly retry?: RetryPolicy;\n /** D238 — slot reserved; runtime throws if engine not yet implemented. */\n readonly compensate?: (input: unknown, output: unknown, error: Error) => Promise<void> | void;\n}\n\n/** An agent.send-driven step. */\nexport interface AgentStep {\n readonly kind: \"agent\";\n readonly id: string;\n readonly agent: SDKAgent;\n readonly promptTemplate: string | ((input: unknown) => string);\n readonly retry?: RetryPolicy;\n /**\n * SE3 — provenance stamped onto this step's `agent.send()` (forwarded to\n * `RunResult.origin`). Squad sets `{ kind: \"peer\", from: \"agent-<i-1>\" }` on\n * every step after the first so a peer-driven turn is attributable.\n */\n readonly origin?: MessageOrigin;\n}\n\n/** N concurrent branches, each its own mini-step-list. */\nexport interface ParallelStep {\n readonly kind: \"parallel\";\n readonly id: string;\n readonly branches: ReadonlyArray<ReadonlyArray<Step>>;\n readonly concurrency?: number;\n readonly errorPolicy?: \"fail-fast\" | \"collect\";\n}\n\n/** First-match-wins predicates + optional fallback. */\nexport interface BranchStep {\n readonly kind: \"branch\";\n readonly id: string;\n readonly predicates: ReadonlyArray<\n readonly [(input: unknown) => boolean | Promise<boolean>, ReadonlyArray<Step>]\n >;\n readonly fallback?: ReadonlyArray<Step>;\n}\n\n/** Map a step over an upstream array output. */\nexport interface ForeachStep {\n readonly kind: \"foreach\";\n readonly id: string;\n /** ID of an upstream top-level step whose output is iterable. */\n readonly iterableFrom: string;\n readonly step: Step;\n readonly concurrency?: number;\n}\n\n/** Loop a step until condFn returns false. */\nexport interface DowhileStep {\n readonly kind: \"dowhile\";\n readonly id: string;\n readonly step: Step;\n readonly condFn: (output: unknown, iteration: number) => boolean | Promise<boolean>;\n readonly maxIterations?: number;\n}\n\n/** Pause for a fixed duration. */\nexport interface SleepStep {\n readonly kind: \"sleep\";\n readonly id: string;\n readonly durationMs: number;\n}\n\n/** Standalone explicit suspend point. */\nexport interface SuspendStep {\n readonly kind: \"suspend\";\n readonly id: string;\n readonly payloadSchema?: ZodType;\n}\n\n/* ─── Supporting types ─── */\n\n/** D237 — retry policy applied per fn/agent step. */\nexport interface RetryPolicy {\n /** Total attempts (MIN 1, MAX 20). `1` = no retry. */\n readonly maxAttempts: number;\n readonly initialBackoffMs?: number;\n readonly backoffCoefficient?: number;\n readonly maximumBackoffMs?: number;\n readonly nonRetryableErrors?: ReadonlyArray<string>;\n}\n\n/** D247 — context handed to every step.fn. */\nexport interface StepContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly log: {\n debug: (msg: string, attrs?: Record<string, unknown>) => void;\n info: (msg: string, attrs?: Record<string, unknown>) => void;\n warn: (msg: string, attrs?: Record<string, unknown>) => void;\n };\n /** Pause the workflow; resume via `Workflow.resume({...})`. */\n readonly suspend: (payload?: unknown) => Promise<never>;\n /**\n * SE29 — the workflow's shared state (from `WorkflowOptions.initialState`,\n * mutated by {@link setState}), visible to every subsequent step in the run.\n * `undefined` when no `initialState`/`setState` has run. Persisted across\n * suspend/resume.\n */\n readonly state: unknown;\n /**\n * SE29 — update the shared state for subsequent steps. Validated against\n * `WorkflowOptions.stateSchema` when set (a mismatch throws\n * {@link WorkflowStateError}, which fails the step/run — Rule 8).\n */\n readonly setState: (next: unknown) => void;\n}\n\n/* ─── Result types ─── */\n\nexport interface StepResult {\n readonly stepId: string;\n readonly kind: Step[\"kind\"];\n readonly status: \"completed\" | \"failed\" | \"skipped\" | \"suspended\";\n readonly attempts: number;\n readonly durationMs: number;\n readonly output?: unknown;\n readonly error?: { name: string; message: string };\n}\n\nexport interface WorkflowRun<TOutput = unknown> {\n readonly id: string;\n readonly name: string;\n readonly status: \"running\" | \"completed\" | \"failed\" | \"suspended\" | \"cancelled\";\n readonly output?: TOutput;\n readonly error?: { name: string; message: string };\n readonly startedAt: number;\n readonly endedAt?: number;\n readonly stepResults: ReadonlyArray<StepResult>;\n}\n\nexport interface WorkflowSnapshot {\n /** v1 = pre-SE29 (no `state`); v2 = SE29 (carries `state`). Resume reads both. */\n readonly _schemaVersion: 1 | 2;\n readonly runId: string;\n readonly workflowName: string;\n readonly currentStepId: string;\n readonly suspendedPayload?: unknown;\n readonly stepResults: ReadonlyArray<StepResult>;\n readonly accumulatedInput: unknown;\n /** SE29 — shared state captured at suspend (v2). Absent on a v1 snapshot. */\n readonly state?: unknown;\n readonly suspendedAt: number;\n}\n\n/* ─── SE28 — streaming ─── */\n\n/**\n * SE28 — a step-level workflow event emitted by `Workflow.stream()` as top-level\n * steps run. Coarse-grained (one event per top-level step; nested\n * parallel/branch/foreach emit as their single wrapping step), distinct from the\n * token-delta agent stream. Discriminate on `type`.\n *\n * @public\n */\nexport type WorkflowEvent =\n | { readonly type: \"step_started\"; readonly stepId: string }\n | { readonly type: \"step_completed\"; readonly stepId: string; readonly output: unknown }\n | {\n readonly type: \"step_failed\";\n readonly stepId: string;\n readonly error: { readonly name: string; readonly message: string };\n }\n | { readonly type: \"workflow_suspended\"; readonly stepId: string }\n | { readonly type: \"workflow_completed\" };\n\n/**\n * SE28 — the async iterator returned by `Workflow.stream()`. Yields\n * {@link WorkflowEvent}s in execution order; `result` resolves to the same\n * terminal {@link WorkflowRun} the `run()` path returns (the authoritative\n * outcome — the stream ends when the run terminates).\n *\n * @public\n */\nexport type WorkflowStream<TOutput = unknown> = AsyncIterableIterator<WorkflowEvent> & {\n readonly result: Promise<WorkflowRun<TOutput>>;\n};\n\n/* ─── Options ─── */\n\nexport interface WorkflowPersistenceOptions {\n readonly backend: \"memory\" | \"json\";\n /** Required for `backend: \"json\"`. */\n readonly dir?: string;\n}\n\nexport interface WorkflowOptions {\n readonly name: string;\n readonly persistence?: WorkflowPersistenceOptions;\n /**\n * SE27 — Zod schema for the WHOLE workflow's input. When set, `run(input)`\n * validates `input` BEFORE step 1; a mismatch yields `status: \"failed\"` with a\n * typed {@link WorkflowInputError} in `error` (fail-fast, no step runs, no\n * silent coerce). Absent ⇒ no whole-workflow input validation (unchanged).\n */\n readonly inputSchema?: ZodType;\n /**\n * SE27 — Zod schema for the workflow's final output. When set, the terminal\n * `completed` output is validated before `WorkflowRun.output` is populated; a\n * mismatch yields `status: \"failed\"` with a typed {@link WorkflowOutputError}.\n * Only validated on the `completed` path (suspended/failed runs skip it).\n */\n readonly outputSchema?: ZodType;\n /**\n * SE29 — Zod schema for the workflow's shared state (see `StepContext.state` /\n * `setState`). When set, `initialState` and every `setState(next)` are\n * validated against it (a mismatch throws {@link WorkflowStateError}). When\n * `initialState` is absent, `state` starts as `undefined` and validation fires\n * on the first `setState` call.\n */\n readonly stateSchema?: ZodType;\n /**\n * SE29 — the initial shared state, seeded onto `StepContext.state` before\n * step 1. Validated against `stateSchema` when both are set. Persisted across\n * suspend/resume.\n */\n readonly initialState?: unknown;\n /** Internal — minted at `.commit()`. Not user-facing. */\n readonly workflowId?: string;\n}\n\nexport interface WorkflowRunOptions {\n readonly signal?: AbortSignal;\n /** Override run ID for deterministic resume (advanced; default = mintRunId). */\n readonly runId?: string;\n /**\n * Opt-in Task wrapping (ADRs D363, D374). Registers the workflow run\n * as a `Task` (kind=\"workflow\") with a `wf-` namespaced id (D368,\n * EC-5). The task transitions terminal when `Workflow.run` resolves.\n *\n * Auto-id: `wf-{runId}`.\n *\n * @public\n */\n readonly task?: true | { id?: string; meta?: Record<string, unknown> };\n}\n\nexport interface WorkflowResumeOptions<TI = unknown> {\n readonly runId: string;\n readonly workflow: { run: (input: TI, opts?: WorkflowRunOptions) => Promise<WorkflowRun> };\n readonly payload?: unknown;\n readonly signal?: AbortSignal;\n}\n\n/* ─── Error classes ─── */\n\nexport class WorkflowDuplicateStepIdError extends Error {\n override readonly name = \"WorkflowDuplicateStepIdError\";\n constructor(public readonly stepId: string) {\n super(`Duplicate step id \"${stepId}\" in workflow.`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `inputSchema` rejected `run(input)` (before step 1).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowInputError extends Error {\n override readonly name = \"WorkflowInputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" input failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `outputSchema` rejected the final output (on `completed`).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowOutputError extends Error {\n override readonly name = \"WorkflowOutputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" output failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE29 — `WorkflowOptions.stateSchema` rejected an `initialState` or a\n * `setState(next)` call. `detail` is a pre-formatted issues summary.\n */\nexport class WorkflowStateError extends Error {\n override readonly name = \"WorkflowStateError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" state failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE30 — a nested workflow (via `workflowStep`) did not `complete`. A nested\n * `suspended` is NOT resumable in v1 (resume continues AFTER the step, so the\n * child would be skipped) — restructure with a top-level suspend. A nested\n * `failed`/`cancelled` fails the parent step with the child's error attached.\n */\nexport class WorkflowNestedError extends Error {\n override readonly name = \"WorkflowNestedError\";\n constructor(\n public readonly stepId: string,\n public readonly childName: string,\n public readonly childStatus: Exclude<WorkflowRun[\"status\"], \"completed\">,\n public readonly childError?: { name: string; message: string },\n ) {\n super(\n `Nested workflow \"${childName}\" (step \"${stepId}\") ended with status \"${childStatus}\"${\n childStatus === \"suspended\"\n ? \" — nested suspend/resume is not supported in v1 (use a top-level suspend)\"\n : \"\"\n }${childError ? `: ${childError.name}: ${childError.message}` : \"\"}`,\n // Reconstruct a synthetic Error from the serialized child-error shape so\n // debuggers surface the nested cause chain — the original Error instance is\n // lost at the WorkflowRun serialization boundary, so this is the best\n // achievable without changing the run protocol.\n childError\n ? { cause: Object.assign(new Error(childError.message), { name: childError.name }) }\n : undefined,\n );\n }\n}\n\nexport class WorkflowAlreadyRunningError extends Error {\n override readonly name = \"WorkflowAlreadyRunningError\";\n constructor(\n public readonly workflowName: string,\n public readonly runId: string,\n ) {\n super(`Workflow \"${workflowName}\" run \"${runId}\" already in-flight.`);\n }\n}\n\nexport class WorkflowSnapshotNotFoundError extends Error {\n override readonly name = \"WorkflowSnapshotNotFoundError\";\n constructor(public readonly runId: string) {\n super(`No snapshot found for runId \"${runId}\". Configure persistence to enable resume.`);\n }\n}\n\nexport class WorkflowMaxIterationsExceededError extends Error {\n override readonly name = \"WorkflowMaxIterationsExceededError\";\n constructor(\n public readonly stepId: string,\n public readonly maxIterations: number,\n ) {\n super(`Step \"${stepId}\" exceeded max iterations (${maxIterations}).`);\n }\n}\n\n/** EC-4 absorbed — JSON.stringify failed on snapshot payload. */\nexport class WorkflowNotSerializableError extends Error {\n override readonly name = \"WorkflowNotSerializableError\";\n constructor(\n public readonly stepId: string,\n public readonly underlying: Error,\n ) {\n super(\n `Workflow snapshot at step \"${stepId}\" failed to serialize as JSON: ${underlying.message}. ` +\n `Persisted snapshots support only JSON-serializable values (no BigInt, no circular refs, no class instances with cycles).`,\n );\n }\n}\n\n/** EC-8 absorbed — `currentStepId` from snapshot not found in resumed workflow. */\nexport class WorkflowResumeStepNotFoundError extends Error {\n override readonly name = \"WorkflowResumeStepNotFoundError\";\n constructor(\n public readonly stepId: string,\n public readonly workflowName: string,\n ) {\n super(\n `Cannot resume: step \"${stepId}\" not found in workflow \"${workflowName}\". ` +\n `The Workflow definition diverged from the snapshot.`,\n );\n }\n}\n\n/** Aggregate failure from parallel branches. */\nexport class WorkflowParallelError extends AggregateError {\n override readonly name = \"WorkflowParallelError\";\n constructor(\n errors: ReadonlyArray<Error>,\n public readonly stepId: string,\n ) {\n super(errors, `${errors.length} branch(es) failed in parallel step \"${stepId}\".`);\n }\n}\n\n/** D238 — saga engine not yet implemented. */\nexport class WorkflowCompensateNotImplementedError extends Error {\n override readonly name = \"WorkflowCompensateNotImplementedError\";\n constructor(public readonly stepId: string) {\n super(\n `Step \"${stepId}\" defines compensate, but saga engine is deferred to v1.2. ` +\n `Remove compensate or implement rollback manually.`,\n );\n }\n}\n","/**\n * Snapshot store interface + InMemory and JsonFile backends (ADR D235).\n *\n * EC-4 absorbed: serialization happens here. `JSON.stringify` failure raises\n * `WorkflowNotSerializableError` instead of letting the underlying `TypeError`\n * leak.\n *\n * @internal\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n WorkflowNotSerializableError,\n type WorkflowOptions,\n type WorkflowSnapshot,\n} from \"../../types/workflow.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nexport interface WorkflowSnapshotStore {\n save(snapshot: WorkflowSnapshot): Promise<void>;\n load(runId: string): Promise<WorkflowSnapshot | undefined>;\n delete(runId: string): Promise<void>;\n list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>>;\n}\n\n/* ─── InMemory backend (default) ─── */\n\nclass InMemoryWorkflowSnapshotStore implements WorkflowSnapshotStore {\n private readonly map = new Map<string, WorkflowSnapshot>();\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n // Verify serializability even in-memory so behavior is consistent with json backend.\n try {\n JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n this.map.set(snapshot.runId, snapshot);\n }\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n return this.map.get(runId);\n }\n async delete(runId: string): Promise<void> {\n this.map.delete(runId);\n }\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n return [...this.map.values()]\n .filter((s) => workflowName === undefined || s.workflowName === workflowName)\n .map((s) => ({\n runId: s.runId,\n workflowName: s.workflowName,\n suspendedAt: s.suspendedAt,\n }));\n }\n}\n\n/* ─── Json file backend (opt-in) ─── */\n\nclass JsonFileWorkflowSnapshotStore implements WorkflowSnapshotStore {\n constructor(private readonly dir: string) {}\n\n private filePath(runId: string): string {\n return join(this.dir, `${runId}.json`);\n }\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n let serialized: string;\n try {\n serialized = JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n await mkdir(this.dir, { recursive: true });\n await atomicWriteText(this.filePath(snapshot.runId), serialized);\n }\n\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(this.filePath(runId), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw err;\n }\n }\n\n async delete(runId: string): Promise<void> {\n try {\n await (await import(\"node:fs/promises\")).unlink(this.filePath(runId));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n }\n\n private async readEntriesOrEmpty(): Promise<string[]> {\n try {\n return await readdir(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n }\n\n private async readSnapshotSafe(file: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(join(this.dir, file), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch {\n return undefined;\n }\n }\n\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n const entries = await this.readEntriesOrEmpty();\n const results: Array<{ runId: string; workflowName: string; suspendedAt: number }> = [];\n for (const file of entries) {\n if (!file.endsWith(\".json\")) continue;\n const snap = await this.readSnapshotSafe(file);\n if (snap === undefined) continue;\n if (workflowName !== undefined && snap.workflowName !== workflowName) continue;\n results.push({\n runId: snap.runId,\n workflowName: snap.workflowName,\n suspendedAt: snap.suspendedAt,\n });\n }\n return results;\n }\n}\n\n/* ─── Resolver: per-Workflow store cache ─── */\n\nconst memoryStore = new InMemoryWorkflowSnapshotStore();\nconst jsonStores = new Map<string, JsonFileWorkflowSnapshotStore>();\n\nexport function getSnapshotStoreFor(options: WorkflowOptions): WorkflowSnapshotStore {\n if (options.persistence?.backend === \"json\") {\n const dir = options.persistence.dir as string; // schema enforces dir is set\n let store = jsonStores.get(dir);\n if (store === undefined) {\n store = new JsonFileWorkflowSnapshotStore(dir);\n jsonStores.set(dir, store);\n }\n return store;\n }\n return memoryStore;\n}\n\n/** Test seam — clear in-memory store between tests. */\nexport function __resetSnapshotStoresForTests(): void {\n jsonStores.clear();\n // memoryStore has private map; reset via assignment.\n // biome-ignore lint/suspicious/noExplicitAny: test-only seam\n (memoryStore as any).map.clear();\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createSemaphore } from './chunk-5PZMMF4H.js';
|
|
2
|
+
|
|
3
|
+
// src/internal/runtime/concurrency/map-with-concurrency.ts
|
|
4
|
+
var NEVER_ABORT = new AbortController().signal;
|
|
5
|
+
async function mapWithConcurrency(items, concurrency, fn, options) {
|
|
6
|
+
const semaphore = createSemaphore(concurrency);
|
|
7
|
+
const signal = options?.signal ?? NEVER_ABORT;
|
|
8
|
+
return Promise.all(
|
|
9
|
+
items.map(async (item, index) => {
|
|
10
|
+
const release = await semaphore.acquire();
|
|
11
|
+
try {
|
|
12
|
+
if (signal.aborted) {
|
|
13
|
+
throw signal.reason instanceof Error ? signal.reason : new Error("mapWithConcurrency: aborted");
|
|
14
|
+
}
|
|
15
|
+
return await fn(item, index, signal);
|
|
16
|
+
} finally {
|
|
17
|
+
release();
|
|
18
|
+
}
|
|
19
|
+
})
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export { mapWithConcurrency };
|
|
24
|
+
//# sourceMappingURL=chunk-V4XRLPEF.js.map
|
|
25
|
+
//# sourceMappingURL=chunk-V4XRLPEF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/concurrency/map-with-concurrency.ts"],"names":[],"mappings":";;;AAcA,IAAM,WAAA,GAA2B,IAAI,eAAA,EAAgB,CAAE,MAAA;AAgBvD,eAAsB,kBAAA,CACpB,KAAA,EACA,WAAA,EACA,EAAA,EACA,OAAA,EACc;AACd,EAAA,MAAM,SAAA,GAAY,gBAAgB,WAAW,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,SAAS,MAAA,IAAU,WAAA;AAClC,EAAA,OAAO,OAAA,CAAQ,GAAA;AAAA,IACb,KAAA,CAAM,GAAA,CAAI,OAAO,IAAA,EAAM,KAAA,KAAU;AAC/B,MAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,OAAA,EAAQ;AACxC,MAAA,IAAI;AACF,QAAA,IAAI,OAAO,OAAA,EAAS;AAClB,UAAA,MAAM,OAAO,MAAA,YAAkB,KAAA,GAC3B,OAAO,MAAA,GACP,IAAI,MAAM,6BAA6B,CAAA;AAAA,QAC7C;AACA,QAAA,OAAO,MAAM,EAAA,CAAG,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAAA,MACrC,CAAA,SAAE;AACA,QAAA,OAAA,EAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,GACH;AACF","file":"chunk-V4XRLPEF.js","sourcesContent":["/**\n * Ordered, bounded-concurrency parallel map (plan m0-foundation-expose-primitives, M0-2).\n *\n * Runs `fn` over `items` with at most `concurrency` invocations in flight at\n * once, preserving input order in the result array. Fail-fast: rejects with the\n * first error a task throws (matching the in-house `boundedParallel`/`runBatches`\n * clones this consolidates). Backed by the in-house {@link createSemaphore}\n * (ADR D135 — no `p-limit`/`p-map` dependency).\n *\n * @internal — public via `@theokit/sdk/concurrency`\n */\n\nimport { createSemaphore } from \"./async-semaphore.js\";\n\nconst NEVER_ABORT: AbortSignal = new AbortController().signal;\n\n/**\n * Map `fn` over `items` with bounded concurrency, preserving order.\n *\n * @param items - inputs to process\n * @param concurrency - max in-flight invocations (positive integer; validated)\n * @param fn - async mapper; receives the item, its index, and an abort signal\n * @param options.signal - optional abort signal; once aborted, no new `fn`\n * invocation is started (in-flight ones are not force-cancelled)\n * @returns results in the same order as `items`\n * @throws ConfigurationError when `concurrency` is not a positive integer\n *\n * @example\n * await mapWithConcurrency([1, 2, 3], 2, async (n) => n * 2); // [2, 4, 6]\n */\nexport async function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n concurrency: number,\n fn: (item: T, index: number, signal: AbortSignal) => Promise<R>,\n options?: { signal?: AbortSignal },\n): Promise<R[]> {\n const semaphore = createSemaphore(concurrency);\n const signal = options?.signal ?? NEVER_ABORT;\n return Promise.all(\n items.map(async (item, index) => {\n const release = await semaphore.acquire();\n try {\n if (signal.aborted) {\n throw signal.reason instanceof Error\n ? signal.reason\n : new Error(\"mapWithConcurrency: aborted\");\n }\n return await fn(item, index, signal);\n } finally {\n release();\n }\n }),\n );\n}\n"]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var async_hooks = require('async_hooks');
|
|
4
|
+
|
|
5
|
+
// src/internal/runtime/concurrency/async-local-storage.ts
|
|
6
|
+
var toolWhitelistStore = new async_hooks.AsyncLocalStorage();
|
|
7
|
+
async function withToolWhitelist(whitelist, fn) {
|
|
8
|
+
return toolWhitelistStore.run(whitelist, fn);
|
|
9
|
+
}
|
|
10
|
+
function currentToolWhitelist() {
|
|
11
|
+
return toolWhitelistStore.getStore();
|
|
12
|
+
}
|
|
13
|
+
function checkToolWhitelist(toolName) {
|
|
14
|
+
const whitelist = currentToolWhitelist();
|
|
15
|
+
if (whitelist === void 0) return { allowed: true };
|
|
16
|
+
if (!whitelist.has(toolName)) {
|
|
17
|
+
return {
|
|
18
|
+
allowed: false,
|
|
19
|
+
reason: `Tool "${toolName}" not available in this fork context`
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
return { allowed: true };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
exports.checkToolWhitelist = checkToolWhitelist;
|
|
26
|
+
exports.withToolWhitelist = withToolWhitelist;
|
|
27
|
+
//# sourceMappingURL=chunk-VJ26EKGJ.cjs.map
|
|
28
|
+
//# sourceMappingURL=chunk-VJ26EKGJ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/concurrency/async-local-storage.ts"],"names":["AsyncLocalStorage"],"mappings":";;;;;AAsBA,IAAM,kBAAA,GAAqB,IAAIA,6BAAA,EAA+B;AAQ9D,eAAsB,iBAAA,CACpB,WACA,EAAA,EACY;AACZ,EAAA,OAAO,kBAAA,CAAmB,GAAA,CAAI,SAAA,EAAW,EAAE,CAAA;AAC7C;AAQO,SAAS,oBAAA,GAAgD;AAC9D,EAAA,OAAO,mBAAmB,QAAA,EAAS;AACrC;AAoBO,SAAS,mBAAmB,QAAA,EAAyC;AAC1E,EAAA,MAAM,YAAY,oBAAA,EAAqB;AACvC,EAAA,IAAI,SAAA,KAAc,MAAA,EAAW,OAAO,EAAE,SAAS,IAAA,EAAK;AACpD,EAAA,IAAI,CAAC,SAAA,CAAU,GAAA,CAAI,QAAQ,CAAA,EAAG;AAC5B,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,KAAA;AAAA,MACT,MAAA,EAAQ,SAAS,QAAQ,CAAA,oCAAA;AAAA,KAC3B;AAAA,EACF;AACA,EAAA,OAAO,EAAE,SAAS,IAAA,EAAK;AACzB","file":"chunk-VJ26EKGJ.cjs","sourcesContent":["/**\n * Per-fork tool whitelist via `AsyncLocalStorage` (ADR D111).\n *\n * Forked agents (background review, curator, judge) need a tool subset\n * distinct from the parent's. A global mutable `let _whitelist` would\n * corrupt state when two forks run in parallel. `AsyncLocalStorage`\n * propagates the whitelist through the async chain so each fork sees its\n * own — no cross-fork bleed.\n *\n * Outside a `withToolWhitelist(...)` scope, `currentToolWhitelist()`\n * returns `undefined` and `checkToolWhitelist` allows every tool — the\n * parent agent is unaffected.\n *\n * Wire site: `internal/agent-loop/tool-dispatch.ts:dispatchSingleCall`\n * calls `checkToolWhitelist` after the repair middleware and before\n * `tools.find`.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst toolWhitelistStore = new AsyncLocalStorage<Set<string>>();\n\n/**\n * Run `fn` with `whitelist` as the active tool filter. Nested calls\n * shadow the outer set; the outer is restored on return (EC-F).\n *\n * @internal\n */\nexport async function withToolWhitelist<T>(\n whitelist: Set<string>,\n fn: () => Promise<T>,\n): Promise<T> {\n return toolWhitelistStore.run(whitelist, fn);\n}\n\n/**\n * Active tool whitelist for the current async context, or `undefined`\n * when not inside a `withToolWhitelist(...)` scope.\n *\n * @internal\n */\nexport function currentToolWhitelist(): Set<string> | undefined {\n return toolWhitelistStore.getStore();\n}\n\n/**\n * Decision returned by {@link checkToolWhitelist}.\n *\n * @internal\n */\nexport interface ToolWhitelistDecision {\n allowed: boolean;\n /** Populated only when `allowed === false`. */\n reason?: string;\n}\n\n/**\n * Check whether `toolName` is allowed in the current fork context.\n * Returns `{ allowed: true }` when no fork is active — preserves the\n * parent agent's full tool surface.\n *\n * @internal\n */\nexport function checkToolWhitelist(toolName: string): ToolWhitelistDecision {\n const whitelist = currentToolWhitelist();\n if (whitelist === undefined) return { allowed: true };\n if (!whitelist.has(toolName)) {\n return {\n allowed: false,\n reason: `Tool \"${toolName}\" not available in this fork context`,\n };\n }\n return { allowed: true };\n}\n"]}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/internal/runtime/lifecycle/run-to-completion.ts
|
|
4
|
+
var DEFAULT_MAX_ROUNDS = 5;
|
|
5
|
+
var DEFAULT_CONTINUATION_PROMPT = "Continue from where you left off and finish the task. If it is already complete, give the final answer.";
|
|
6
|
+
function isEmptyRound(result) {
|
|
7
|
+
return (result.result ?? "").trim() === "";
|
|
8
|
+
}
|
|
9
|
+
function classifyRound(result, round, maxRounds, emptyStreak) {
|
|
10
|
+
if (result.stoppedByDoomLoop === true) return "no_progress";
|
|
11
|
+
if (result.stoppedAtIterationLimit !== true) return "done";
|
|
12
|
+
if (isEmptyRound(result) && emptyStreak >= 1) return "no_progress";
|
|
13
|
+
if (round >= maxRounds) return "step_limit";
|
|
14
|
+
return "continue";
|
|
15
|
+
}
|
|
16
|
+
function addUsage(acc, u) {
|
|
17
|
+
if (u === void 0) return acc;
|
|
18
|
+
const inputTokens = (acc?.inputTokens ?? 0) + u.inputTokens;
|
|
19
|
+
const outputTokens = (acc?.outputTokens ?? 0) + u.outputTokens;
|
|
20
|
+
const sumOpt = (a, b) => a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
|
|
21
|
+
return {
|
|
22
|
+
inputTokens,
|
|
23
|
+
outputTokens,
|
|
24
|
+
totalTokens: inputTokens + outputTokens,
|
|
25
|
+
cacheReadTokens: sumOpt(acc?.cacheReadTokens, u.cacheReadTokens),
|
|
26
|
+
cacheWriteTokens: sumOpt(acc?.cacheWriteTokens, u.cacheWriteTokens),
|
|
27
|
+
reasoningTokens: sumOpt(acc?.reasoningTokens, u.reasoningTokens)
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function buildResult(terminal, rounds, lastResult, usage) {
|
|
31
|
+
return { terminal, rounds, lastResult, ...usage !== void 0 ? { usage } : {} };
|
|
32
|
+
}
|
|
33
|
+
async function continuationTail(round, lastResult, usage, onTruncated, signal) {
|
|
34
|
+
await onTruncated?.({ round });
|
|
35
|
+
return signal?.aborted === true ? buildResult("step_limit", round, lastResult, usage) : void 0;
|
|
36
|
+
}
|
|
37
|
+
function resolveContinuation(options) {
|
|
38
|
+
return {
|
|
39
|
+
maxRounds: options?.maxRounds ?? DEFAULT_MAX_ROUNDS,
|
|
40
|
+
continuationPrompt: options?.continuationPrompt ?? DEFAULT_CONTINUATION_PROMPT,
|
|
41
|
+
onTruncated: options?.onTruncated,
|
|
42
|
+
signal: options?.signal,
|
|
43
|
+
sendOptions: options?.sendOptions,
|
|
44
|
+
state: { usage: void 0, emptyStreak: 0 }
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function promptForRound(round, message, continuationPrompt) {
|
|
48
|
+
return round === 0 ? message : continuationPrompt;
|
|
49
|
+
}
|
|
50
|
+
async function stepRound(agent, prompt, sendOptions, round, maxRounds, state) {
|
|
51
|
+
const roundOptions = round === 0 ? sendOptions : { ...sendOptions ?? {}, origin: { kind: "auto-continuation" } };
|
|
52
|
+
const run = await agent.send(prompt, roundOptions);
|
|
53
|
+
const result = await run.wait();
|
|
54
|
+
const usage = addUsage(state.usage, result.usage);
|
|
55
|
+
const decision = classifyRound(result, round, maxRounds, state.emptyStreak);
|
|
56
|
+
if (decision !== "continue") return { terminal: buildResult(decision, round, result, usage) };
|
|
57
|
+
const emptyStreak = isEmptyRound(result) ? state.emptyStreak + 1 : 0;
|
|
58
|
+
return { next: { usage, emptyStreak }, lastResult: result };
|
|
59
|
+
}
|
|
60
|
+
async function runToCompletionImpl(agent, message, options) {
|
|
61
|
+
const cfg = resolveContinuation(options);
|
|
62
|
+
let state = cfg.state;
|
|
63
|
+
for (let round = 0; ; round += 1) {
|
|
64
|
+
const prompt = promptForRound(round, message, cfg.continuationPrompt);
|
|
65
|
+
const outcome = await stepRound(agent, prompt, cfg.sendOptions, round, cfg.maxRounds, state);
|
|
66
|
+
if ("terminal" in outcome) return outcome.terminal;
|
|
67
|
+
state = outcome.next;
|
|
68
|
+
const aborted = await continuationTail(
|
|
69
|
+
round,
|
|
70
|
+
outcome.lastResult,
|
|
71
|
+
state.usage,
|
|
72
|
+
cfg.onTruncated,
|
|
73
|
+
cfg.signal
|
|
74
|
+
);
|
|
75
|
+
if (aborted !== void 0) return aborted;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
exports.DEFAULT_CONTINUATION_PROMPT = DEFAULT_CONTINUATION_PROMPT;
|
|
80
|
+
exports.DEFAULT_MAX_ROUNDS = DEFAULT_MAX_ROUNDS;
|
|
81
|
+
exports.addUsage = addUsage;
|
|
82
|
+
exports.buildResult = buildResult;
|
|
83
|
+
exports.classifyRound = classifyRound;
|
|
84
|
+
exports.continuationTail = continuationTail;
|
|
85
|
+
exports.isEmptyRound = isEmptyRound;
|
|
86
|
+
exports.promptForRound = promptForRound;
|
|
87
|
+
exports.resolveContinuation = resolveContinuation;
|
|
88
|
+
exports.runToCompletionImpl = runToCompletionImpl;
|
|
89
|
+
//# sourceMappingURL=chunk-VK7MAV65.cjs.map
|
|
90
|
+
//# sourceMappingURL=chunk-VK7MAV65.cjs.map
|