@theokit/sdk 4.24.0 → 4.26.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 -367
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.js +6 -342
- 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-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-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-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-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-KDNBTPY2.js +458 -0
- package/dist/chunk-KDNBTPY2.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-PSJN532Q.js +10573 -0
- package/dist/chunk-PSJN532Q.js.map +1 -0
- package/dist/chunk-QUTUJ6P6.cjs +76 -0
- package/dist/chunk-QUTUJ6P6.cjs.map +1 -0
- package/dist/chunk-R43CNCES.cjs +460 -0
- package/dist/chunk-R43CNCES.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-ZUBIEQJF.cjs +10590 -0
- package/dist/chunk-ZUBIEQJF.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-x3muPNgg.d.cts → cron-D0JKR-yX.d.cts} +2 -1
- package/dist/{cron-B_NkE_VM.d.ts → cron-DivRaEmN.d.ts} +2 -1
- package/dist/cron.cjs +44 -20676
- package/dist/cron.cjs.map +1 -1
- package/dist/cron.d.cts +1 -1
- package/dist/cron.d.ts +1 -1
- package/dist/cron.js +38 -20676
- package/dist/cron.js.map +1 -1
- package/dist/errors.cjs +78 -470
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +3 -424
- package/dist/errors.js +2 -455
- package/dist/errors.js.map +1 -1
- package/dist/eval.cjs +72 -20411
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +59 -20402
- 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 -22888
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -21
- package/dist/index.d.ts +16 -21
- package/dist/index.js +92 -22713
- 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/judge/judge-call.d.ts +32 -19
- 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-CEQ3FYYD.js +126 -0
- package/dist/judge-call-CEQ3FYYD.js.map +1 -0
- package/dist/judge-call-QG4WZ7F3.cjs +130 -0
- package/dist/judge-call-QG4WZ7F3.cjs.map +1 -0
- package/dist/models.cjs +24 -919
- package/dist/models.cjs.map +1 -1
- package/dist/models.js +11 -907
- 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-PNO3QQLI.cjs +180 -0
- package/dist/run-until-PNO3QQLI.cjs.map +1 -0
- package/dist/run-until-XLHEHRQM.js +177 -0
- package/dist/run-until-XLHEHRQM.js.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/types/goal-events.d.ts +2 -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 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/config/workspace-dir.ts","../src/internal/runtime/context/yaml-frontmatter.ts","../src/internal/runtime/skills/skill-frontmatter.ts","../src/internal/runtime/skills/discover-skills.ts","../src/internal/runtime/system-prompt/escape.ts","../src/internal/runtime/skills/skills-block.ts"],"names":["readdir","ConfigurationError","safePathJoin","assert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CAAA;AACtC","file":"chunk-LSLPF6OI.cjs","sourcesContent":["import { readdir } from \"node:fs/promises\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\n\n/**\n * Entry returned by `readWorkspaceDir`. Mirrors the subset of\n * `fs.Dirent` the file-based loaders use.\n */\nexport interface WorkspaceDirEntry {\n name: string;\n isDirectory(): boolean;\n isFile(): boolean;\n}\n\n/**\n * Read a workspace subdirectory and return its entries. When the directory\n * does not exist (`ENOENT`), returns an empty array — the file-based loaders\n * (skills, plugins, agents) treat a missing directory as \"no entries\"\n * rather than an error.\n *\n * Any other I/O failure is wrapped as `ConfigurationError` so callers can\n * surface a stable error code.\n *\n * @internal\n */\nexport async function readWorkspaceDir(\n root: string,\n errorCode: string,\n describe: string,\n): Promise<WorkspaceDirEntry[]> {\n try {\n return (await readdir(root, { withFileTypes: true })) as WorkspaceDirEntry[];\n } catch (cause) {\n const err = cause as NodeJS.ErrnoException;\n if (err.code === \"ENOENT\") return [];\n throw new ConfigurationError(`Failed to read ${describe}: ${root}`, {\n code: errorCode,\n cause,\n });\n }\n}\n","/**\n * Tiny YAML-frontmatter parser shared by the file-based loaders (skills,\n * subagents, hooks, context, plugins). Supports four scalar shapes:\n *\n * key: bar → \"bar\" (string)\n * key: 42 → 42 (number)\n * key: true → true (boolean)\n * key: [a, b, c] → [\"a\",\"b\",\"c\"](string[])\n * key: → undefined (caller's Zod default kicks in)\n *\n * Limitations (intentional — keep parser tiny, no dep):\n * - No nested objects (use flat keys like `providerId` not `provider.id`).\n * - No quoted strings — `match: \"1\"` becomes the literal 3-char string `\"1\"`.\n * - List values cannot contain a literal comma inside an element; the\n * `tags: [a,b, c]` splitter is greedy on `,`. Use multi-line lists or\n * reword if you need this.\n *\n * @internal\n */\n\nexport type FrontmatterValue = string | number | boolean | string[];\n\nexport function parseSimpleYaml(text: string): Record<string, FrontmatterValue | undefined> {\n const fields: Record<string, FrontmatterValue | undefined> = {};\n for (const line of text.split(/\\r?\\n/)) {\n const colonIndex = line.indexOf(\":\");\n if (colonIndex === -1) continue;\n const key = line.slice(0, colonIndex).trim();\n if (key.length === 0) continue;\n const raw = line.slice(colonIndex + 1).trim();\n fields[key] = coerce(raw);\n }\n return fields;\n}\n\nfunction coerce(raw: string): FrontmatterValue | undefined {\n // EC-3: empty value → undefined so Zod `.optional().default(...)` applies.\n if (raw.length === 0) return undefined;\n if (raw.startsWith(\"[\") && raw.endsWith(\"]\")) {\n return raw\n .slice(1, -1)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n if (raw === \"true\" || raw === \"false\") return raw === \"true\";\n const n = Number(raw);\n if (Number.isFinite(n) && raw === String(n)) return n;\n return raw;\n}\n","import { ConfigurationError } from \"../../../errors.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\n\ntype StringFields = Record<string, string | undefined>;\n\n/** Narrow a FrontmatterValue to string; non-strings + undefined → undefined. */\nfunction asString(v: FrontmatterValue | undefined): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\n/** Coerce parser output to legacy string-only shape (skill schema is all-string). */\nfunction toStringFields(raw: Record<string, FrontmatterValue | undefined>): StringFields {\n const out: StringFields = {};\n for (const [k, v] of Object.entries(raw)) out[k] = asString(v);\n return out;\n}\n\n/**\n * Strict skill frontmatter schema (ADR D10).\n *\n * Required: `name`, `description`.\n * Optional: `category`, `dependencies` (comma-separated string in the\n * simple-YAML dialect — parsed to `string[]`).\n *\n * Unknown fields are ignored (forward-compat). Malformed YAML or missing\n * required fields surface as `ConfigurationError` with one of the typed\n * codes below.\n *\n * @internal\n */\nexport interface SkillFrontmatter {\n name: string;\n description: string;\n category?: string;\n dependencies?: string[];\n}\n\n/**\n * Parse a SKILL.md file body into validated frontmatter.\n *\n * @throws ConfigurationError(code: \"missing_frontmatter\") — no `---` block at file head.\n * @throws ConfigurationError(code: \"schema_invalid\") — YAML malformed OR required field missing.\n *\n * @internal\n */\nexport function parseSkillFrontmatter(raw: string, fallbackName: string): SkillFrontmatter {\n const fields = extractAndParseFrontmatter(raw, fallbackName);\n const name = resolveName(fields, fallbackName);\n ensureRequiredFields(fields, name);\n return buildFrontmatter(fields, name);\n}\n\n/**\n * SE20 — return a SKILL.md's BODY (everything after the frontmatter block), trimmed.\n * When there is no frontmatter block, the whole file is the body. Reuses the same\n * frontmatter regex as {@link parseSkillFrontmatter} (DRY).\n */\nexport function stripSkillFrontmatter(raw: string): string {\n const match = /^---\\s*\\n[\\s\\S]*?\\n---\\s*\\n/.exec(raw);\n return (match === null ? raw : raw.slice(match[0].length)).trim();\n}\n\nfunction extractAndParseFrontmatter(raw: string, fallbackName: string): StringFields {\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(`Skill ${fallbackName} is missing frontmatter`, {\n code: \"missing_frontmatter\",\n });\n }\n const frontmatter = match[1] ?? \"\";\n // EC-5: guard against syntactically invalid frontmatter so the loader\n // surfaces schema_invalid rather than crashing.\n try {\n return toStringFields(parseSimpleYaml(frontmatter));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new ConfigurationError(\n `Skill ${fallbackName} has malformed YAML frontmatter: ${detail}`,\n { code: \"schema_invalid\", cause },\n );\n }\n}\n\nfunction resolveName(fields: StringFields, fallbackName: string): string {\n if (hasContent(fields.name)) return fields.name;\n if (hasContent(fallbackName)) return fallbackName;\n throw new ConfigurationError(\"Skill at unknown path is missing required field: name\", {\n code: \"schema_invalid\",\n });\n}\n\nfunction ensureRequiredFields(fields: StringFields, name: string): void {\n if (!hasContent(fields.description)) {\n throw new ConfigurationError(`Skill ${name} is missing required field: description`, {\n code: \"schema_invalid\",\n });\n }\n}\n\nfunction buildFrontmatter(fields: StringFields, name: string): SkillFrontmatter {\n const description = fields.description;\n if (description === undefined) {\n // ensureRequiredFields already threw; this is unreachable but satisfies TS\n throw new ConfigurationError(`Skill ${name} missing description`, { code: \"schema_invalid\" });\n }\n const result: SkillFrontmatter = { name, description };\n if (hasContent(fields.category)) result.category = fields.category;\n const deps = parseDependencies(fields.dependencies);\n if (deps !== undefined) result.dependencies = deps;\n return result;\n}\n\nfunction parseDependencies(raw: string | undefined): string[] | undefined {\n if (!hasContent(raw)) return undefined;\n const deps = (raw as string)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n return deps.length > 0 ? deps : undefined;\n}\n\nfunction hasContent(value: string | undefined): value is string {\n return value !== undefined && value.trim().length > 0;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { assertNoSymlinkEscape, safePathJoin } from \"../../security/path-guard.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { parseSkillFrontmatter } from \"./skill-frontmatter.js\";\n\n/**\n * A discovered skill's metadata. The skill BODY is never included — only the\n * strict frontmatter fields plus the resolved `source` path.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport interface Skill {\n name: string;\n description: string;\n /** Absolute path to the discovered `SKILL.md`. */\n source: string;\n category?: string;\n dependencies?: string[];\n}\n\n/**\n * Information passed to `onInvalidSkill` when a `SKILL.md` is present but its\n * frontmatter is malformed (missing required field or invalid YAML).\n *\n * @public\n */\nexport interface InvalidSkillInfo {\n /** The skill directory name (used as the fallback skill name). */\n name: string;\n /** Absolute path to the offending `SKILL.md`. */\n source: string;\n /** Typed reason: `missing_frontmatter` or `schema_invalid`. */\n code: string;\n message: string;\n}\n\n/**\n * Options for {@link discoverSkills}.\n *\n * @public\n */\nexport interface DiscoverSkillsOptions {\n /**\n * Called once per directory that contains a `SKILL.md` with malformed\n * frontmatter. The skill is excluded from the result; discovery continues\n * (strict-frontmatter ADR / EC-5). A directory WITHOUT a `SKILL.md` is NOT a\n * malformed skill and does not trigger this callback.\n *\n * Default: no-op (a library primitive must not write to the consumer's\n * stderr by default).\n */\n onInvalidSkill?: (info: InvalidSkillInfo) => void;\n}\n\n/**\n * Discover `SKILL.md` skills under an arbitrary directory.\n *\n * For each immediate subdirectory `<dir>/<name>/` containing a `SKILL.md`, the\n * file's strict YAML frontmatter is parsed (`name`/`description` required;\n * `category`/`dependencies` optional). Malformed skills are skipped (optionally\n * reported via {@link DiscoverSkillsOptions.onInvalidSkill}); a subdirectory\n * whose realpath escapes `dir` (via symlink) is skipped (symlink-escape guard,\n * reusing `@theokit/sdk/path-safety`).\n *\n * NEVER throws: a missing, unreadable, or non-directory `dir` yields `[]`.\n *\n * Discovery order follows the filesystem `readdir` order (OS-dependent). Sort\n * the result before {@link buildSkillsBlock} if a stable block order matters.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport async function discoverSkills(\n dir: string,\n options?: DiscoverSkillsOptions,\n): Promise<Skill[]> {\n let entries: Awaited<ReturnType<typeof readWorkspaceDir>>;\n try {\n entries = await readWorkspaceDir(dir, \"skills_read_error\", \"skills directory\");\n } catch {\n // never-throw contract: unreadable / not-a-directory → no skills (EC-1)\n return [];\n }\n\n const skills: Skill[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n let skillDir: string;\n try {\n skillDir = safePathJoin(dir, entry.name);\n assertNoSymlinkEscape(skillDir, dir);\n } catch {\n continue;\n }\n const skillPath = join(skillDir, \"SKILL.md\");\n let raw: string;\n try {\n raw = await readFile(skillPath, \"utf8\");\n } catch {\n // no SKILL.md in this subdir → not a skill, not an error (EC-2)\n continue;\n }\n const skill = tryParseSkill(raw, entry.name, skillPath, options);\n if (skill !== undefined) skills.push(skill);\n }\n return skills;\n}\n\nfunction tryParseSkill(\n raw: string,\n fallbackName: string,\n source: string,\n options: DiscoverSkillsOptions | undefined,\n): Skill | undefined {\n try {\n const frontmatter = parseSkillFrontmatter(raw, fallbackName);\n const skill: Skill = {\n name: frontmatter.name,\n description: frontmatter.description,\n source,\n };\n if (frontmatter.category !== undefined) skill.category = frontmatter.category;\n if (frontmatter.dependencies !== undefined) skill.dependencies = frontmatter.dependencies;\n return skill;\n } catch (cause) {\n if (cause instanceof ConfigurationError) {\n options?.onInvalidSkill?.({\n name: fallbackName,\n source,\n code: cause.code ?? \"unknown\",\n message: cause.message,\n });\n return undefined;\n }\n throw cause;\n }\n}\n","/**\n * Block-body XML escape (ADR D9 — prompt-injection defence).\n *\n * Order matters: `&` MUST be escaped first so subsequent `<`/`>` replacements\n * do not double-encode the `&` characters they introduce.\n *\n * @internal\n */\nexport const escapeBlockBody = (s: string): string =>\n s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n","import { escapeBlockBody } from \"../system-prompt/escape.js\";\n\n/**\n * Render the `<skills>` system-prompt block from a skill list.\n *\n * Input is the structural subset `{ name, description }` — the skill BODY is\n * NOT in the type, so it cannot leak into the prompt. Both fields are passed\n * through `escapeBlockBody` to neutralise prompt-injection vectors hidden in\n * user-controlled SKILL.md frontmatter (injection-escape ADR).\n *\n * Returns `undefined` for an empty list so the caller can omit the block.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport function buildSkillsBlock(\n skills: ReadonlyArray<{ name: string; description: string }>,\n): string | undefined {\n if (skills.length === 0) return undefined;\n const lines = skills.map(\n (skill) => ` - ${escapeBlockBody(skill.name)}: ${escapeBlockBody(skill.description)}`,\n );\n return `<skills>\\n${lines.join(\"\\n\")}\\n</skills>`;\n}\n"]}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { AuthCallbackError } from './chunk-5NBUH3NO.js';
|
|
2
|
+
import { AuthenticationError } from './chunk-WLKFWQSJ.js';
|
|
3
|
+
import { randomBytes } from 'crypto';
|
|
4
|
+
import { readFileSync, mkdirSync, chmodSync, openSync, writeFileSync, fsyncSync, closeSync, renameSync, unlinkSync, statSync } from 'fs';
|
|
5
|
+
import { join } from 'path';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
|
|
8
|
+
function credentialHome(config, env = {}) {
|
|
9
|
+
const override = config.homeEnvVar !== void 0 ? env[config.homeEnvVar]?.trim() : void 0;
|
|
10
|
+
return override !== void 0 && override.length > 0 ? override : join(config.home, config.dirName);
|
|
11
|
+
}
|
|
12
|
+
function authFilePath(config, env = {}) {
|
|
13
|
+
return join(credentialHome(config, env), config.fileName);
|
|
14
|
+
}
|
|
15
|
+
var CredentialError = class extends AuthenticationError {
|
|
16
|
+
// Field, not an assignment in the constructor: `AuthenticationError.name` is `override readonly`
|
|
17
|
+
// (`errors.ts:174`), so `this.name = …` does not compile. Caught by `tsc`, not by vitest — the
|
|
18
|
+
// suite was green with the broken assignment because the transpiler strips the type.
|
|
19
|
+
name = "CredentialError";
|
|
20
|
+
};
|
|
21
|
+
var apiFileSchema = z.object({
|
|
22
|
+
type: z.literal("api").optional(),
|
|
23
|
+
provider: z.string().min(1).optional(),
|
|
24
|
+
api_key: z.string()
|
|
25
|
+
}).strict();
|
|
26
|
+
var oauthFileSchema = z.object({
|
|
27
|
+
type: z.literal("oauth"),
|
|
28
|
+
provider: z.string().min(1),
|
|
29
|
+
access: z.string().min(1),
|
|
30
|
+
refresh: z.string().min(1),
|
|
31
|
+
expires: z.number(),
|
|
32
|
+
account_id: z.string().optional()
|
|
33
|
+
}).strict();
|
|
34
|
+
var fileSchema = z.union([oauthFileSchema, apiFileSchema]);
|
|
35
|
+
function assertSecureModes(dirPath, path) {
|
|
36
|
+
const dirMode = statSync(dirPath).mode & 511;
|
|
37
|
+
if ((dirMode & 18) !== 0) {
|
|
38
|
+
throw new CredentialError(
|
|
39
|
+
`${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file inside it can be replaced. Fix it with: chmod 700 ${dirPath}`
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
const mode = statSync(path).mode & 511;
|
|
43
|
+
if ((mode & 63) !== 0) {
|
|
44
|
+
throw new CredentialError(
|
|
45
|
+
`${path} is readable by other users (mode ${mode.toString(8)}). A credential file must not be. Fix it with: chmod 600 ${path}`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function describeUnionError(parsed, err, path) {
|
|
50
|
+
const looksOAuth = typeof parsed === "object" && parsed !== null && parsed.type === "oauth";
|
|
51
|
+
const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);
|
|
52
|
+
let issue;
|
|
53
|
+
if (!specific.success) {
|
|
54
|
+
issue = specific.error.issues[0];
|
|
55
|
+
} else if (err instanceof z.ZodError) {
|
|
56
|
+
issue = err.issues[0];
|
|
57
|
+
}
|
|
58
|
+
return new CredentialError(
|
|
59
|
+
`${path}: ${issue?.message ?? String(err)} [${issue?.path.join(".") || "root"}]`
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
function parseStoredFile(raw, path) {
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
parsed = JSON.parse(raw);
|
|
66
|
+
} catch {
|
|
67
|
+
throw new CredentialError(
|
|
68
|
+
`${path} is not valid JSON. Expected: {"provider": "<name>", "api_key": "..."}`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return fileSchema.parse(parsed);
|
|
73
|
+
} catch (err) {
|
|
74
|
+
throw describeUnionError(parsed, err, path);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function readAuthFile(config, env = {}) {
|
|
78
|
+
const path = authFilePath(config, env);
|
|
79
|
+
let raw;
|
|
80
|
+
try {
|
|
81
|
+
raw = readFileSync(path, "utf8");
|
|
82
|
+
} catch (err) {
|
|
83
|
+
if (err.code === "ENOENT") return void 0;
|
|
84
|
+
throw new CredentialError(`cannot read ${path}: ${err.message}`);
|
|
85
|
+
}
|
|
86
|
+
assertSecureModes(credentialHome(config, env), path);
|
|
87
|
+
return parseStoredFile(raw, path);
|
|
88
|
+
}
|
|
89
|
+
function readStoredOAuth(config, env = {}) {
|
|
90
|
+
const stored = readAuthFile(config, env);
|
|
91
|
+
return stored !== void 0 && stored.type === "oauth" ? stored : void 0;
|
|
92
|
+
}
|
|
93
|
+
function isOAuthWrite(c) {
|
|
94
|
+
return "type" in c && c.type === "oauth";
|
|
95
|
+
}
|
|
96
|
+
function buildStorePayload(cred) {
|
|
97
|
+
if (isOAuthWrite(cred)) {
|
|
98
|
+
if (cred.access.length === 0 || cred.refresh.length === 0) {
|
|
99
|
+
throw new CredentialError(
|
|
100
|
+
"refusing to write an oauth credential with an empty access/refresh token"
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
type: "oauth",
|
|
105
|
+
provider: cred.provider,
|
|
106
|
+
access: cred.access,
|
|
107
|
+
refresh: cred.refresh,
|
|
108
|
+
expires: cred.expires,
|
|
109
|
+
...cred.account_id !== void 0 ? { account_id: cred.account_id } : {}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
if (typeof cred.apiKey !== "string" || cred.apiKey.length === 0) {
|
|
113
|
+
throw new CredentialError("refusing to write an empty API key");
|
|
114
|
+
}
|
|
115
|
+
return { provider: cred.provider, api_key: cred.apiKey };
|
|
116
|
+
}
|
|
117
|
+
function writeCredential(cred, config, env = {}) {
|
|
118
|
+
const payload = buildStorePayload(cred);
|
|
119
|
+
const dir = credentialHome(config, env);
|
|
120
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
121
|
+
chmodSync(dir, 448);
|
|
122
|
+
const path = authFilePath(config, env);
|
|
123
|
+
const tmp = `${path}.tmp-${randomBytes(8).toString("hex")}`;
|
|
124
|
+
try {
|
|
125
|
+
const fd = openSync(tmp, "wx", 384);
|
|
126
|
+
try {
|
|
127
|
+
writeFileSync(fd, `${JSON.stringify(payload, null, 2)}
|
|
128
|
+
`);
|
|
129
|
+
fsyncSync(fd);
|
|
130
|
+
} finally {
|
|
131
|
+
closeSync(fd);
|
|
132
|
+
}
|
|
133
|
+
chmodSync(tmp, 384);
|
|
134
|
+
renameSync(tmp, path);
|
|
135
|
+
} catch (err) {
|
|
136
|
+
try {
|
|
137
|
+
unlinkSync(tmp);
|
|
138
|
+
} catch {
|
|
139
|
+
}
|
|
140
|
+
throw new CredentialError(`cannot write ${path}: ${err.message}`);
|
|
141
|
+
}
|
|
142
|
+
return path;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// src/internal/auth/oauth-engine.ts
|
|
146
|
+
var REFRESH_SKEW_MS = 6e4;
|
|
147
|
+
function parseTokenResponse(body, now) {
|
|
148
|
+
const b = body;
|
|
149
|
+
if (typeof b.access_token !== "string" || b.access_token.length === 0) {
|
|
150
|
+
throw new AuthCallbackError(
|
|
151
|
+
"oauth_token_exchange_failed",
|
|
152
|
+
"token response had no access_token"
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
if (typeof b.refresh_token !== "string" || b.refresh_token.length === 0) {
|
|
156
|
+
throw new AuthCallbackError(
|
|
157
|
+
"oauth_token_exchange_failed",
|
|
158
|
+
"token response had no refresh_token"
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
const expiresIn = typeof b.expires_in === "number" ? b.expires_in : 3600;
|
|
162
|
+
return {
|
|
163
|
+
access: b.access_token,
|
|
164
|
+
refresh: b.refresh_token,
|
|
165
|
+
expires: now + expiresIn * 1e3,
|
|
166
|
+
...typeof b.account_id === "string" ? { accountId: b.account_id } : {}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
async function postGrant(config, form, deps) {
|
|
170
|
+
let res;
|
|
171
|
+
try {
|
|
172
|
+
res = await deps.fetch(config.tokenEndpoint, {
|
|
173
|
+
method: "POST",
|
|
174
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
175
|
+
body: new URLSearchParams(form).toString()
|
|
176
|
+
});
|
|
177
|
+
} catch (err) {
|
|
178
|
+
throw new AuthCallbackError(
|
|
179
|
+
"oauth_token_exchange_failed",
|
|
180
|
+
`token endpoint request failed: ${err.message}`
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
if (!res.ok) {
|
|
184
|
+
throw new AuthCallbackError(
|
|
185
|
+
"oauth_token_exchange_failed",
|
|
186
|
+
`token endpoint returned HTTP ${res.status}`
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
let json;
|
|
190
|
+
try {
|
|
191
|
+
json = await res.json();
|
|
192
|
+
} catch {
|
|
193
|
+
throw new AuthCallbackError("oauth_token_exchange_failed", "token response was not valid JSON");
|
|
194
|
+
}
|
|
195
|
+
return parseTokenResponse(json, deps.now());
|
|
196
|
+
}
|
|
197
|
+
function exchangeCode(config, input, deps) {
|
|
198
|
+
return postGrant(
|
|
199
|
+
config,
|
|
200
|
+
{
|
|
201
|
+
grant_type: "authorization_code",
|
|
202
|
+
code: input.code,
|
|
203
|
+
redirect_uri: config.redirectUri,
|
|
204
|
+
client_id: config.clientId,
|
|
205
|
+
code_verifier: input.verifier
|
|
206
|
+
},
|
|
207
|
+
deps
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
function refreshOAuthTokens(config, refresh, deps) {
|
|
211
|
+
return postGrant(
|
|
212
|
+
config,
|
|
213
|
+
{ grant_type: "refresh_token", refresh_token: refresh, client_id: config.clientId },
|
|
214
|
+
deps
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
function persistOAuthTokens(provider, tokens, store, env = {}) {
|
|
218
|
+
return writeCredential(
|
|
219
|
+
{
|
|
220
|
+
type: "oauth",
|
|
221
|
+
provider,
|
|
222
|
+
access: tokens.access,
|
|
223
|
+
refresh: tokens.refresh,
|
|
224
|
+
expires: tokens.expires,
|
|
225
|
+
...tokens.accountId !== void 0 ? { account_id: tokens.accountId } : {}
|
|
226
|
+
},
|
|
227
|
+
store,
|
|
228
|
+
env
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
var inFlightRefresh = /* @__PURE__ */ new Map();
|
|
232
|
+
async function ensureFreshCredential(resolved, opts, deps) {
|
|
233
|
+
if (resolved.kind !== "oauth") return resolved;
|
|
234
|
+
const now = deps.now();
|
|
235
|
+
if (resolved.expiresAt !== void 0 && resolved.expiresAt > now + REFRESH_SKEW_MS) {
|
|
236
|
+
return resolved;
|
|
237
|
+
}
|
|
238
|
+
const env = opts.env ?? {};
|
|
239
|
+
const path = authFilePath(opts.store, env);
|
|
240
|
+
let refresh = inFlightRefresh.get(path);
|
|
241
|
+
if (refresh === void 0) {
|
|
242
|
+
refresh = (async () => {
|
|
243
|
+
const stored = readStoredOAuth(opts.store, env);
|
|
244
|
+
if (stored === void 0) {
|
|
245
|
+
throw new AuthCallbackError(
|
|
246
|
+
"oauth_token_exchange_failed",
|
|
247
|
+
"no stored oauth credential to refresh"
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
const fresh2 = await refreshOAuthTokens(opts.config, stored.refresh, deps);
|
|
251
|
+
const merged = {
|
|
252
|
+
...fresh2,
|
|
253
|
+
accountId: fresh2.accountId ?? stored.account_id
|
|
254
|
+
};
|
|
255
|
+
persistOAuthTokens(resolved.provider, merged, opts.store, env);
|
|
256
|
+
return merged;
|
|
257
|
+
})();
|
|
258
|
+
inFlightRefresh.set(path, refresh);
|
|
259
|
+
refresh.finally(() => inFlightRefresh.delete(path)).catch(() => {
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
const fresh = await refresh;
|
|
263
|
+
return {
|
|
264
|
+
kind: "oauth",
|
|
265
|
+
provider: resolved.provider,
|
|
266
|
+
apiKey: fresh.access,
|
|
267
|
+
source: resolved.source,
|
|
268
|
+
inferred: false,
|
|
269
|
+
expiresAt: fresh.expires
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// src/internal/auth/resolve-credential.ts
|
|
274
|
+
async function resolveOAuth(stored, path, opts, env) {
|
|
275
|
+
if (stored.provider !== opts.provider) return void 0;
|
|
276
|
+
const base = {
|
|
277
|
+
kind: "oauth",
|
|
278
|
+
provider: opts.provider,
|
|
279
|
+
apiKey: stored.access,
|
|
280
|
+
source: path,
|
|
281
|
+
inferred: false,
|
|
282
|
+
expiresAt: stored.expires
|
|
283
|
+
};
|
|
284
|
+
if (opts.oauth === void 0) return base;
|
|
285
|
+
const deps = {
|
|
286
|
+
fetch: opts.deps?.fetch ?? fetch,
|
|
287
|
+
now: opts.deps?.now ?? (() => Date.now())
|
|
288
|
+
};
|
|
289
|
+
return ensureFreshCredential(base, { config: opts.oauth, store: opts.store, env }, deps);
|
|
290
|
+
}
|
|
291
|
+
async function resolveCredential(opts) {
|
|
292
|
+
const env = opts.env ?? {};
|
|
293
|
+
const stored = readAuthFile(opts.store, env);
|
|
294
|
+
if (stored === void 0) return void 0;
|
|
295
|
+
const path = authFilePath(opts.store, env);
|
|
296
|
+
if (stored.type === "oauth") {
|
|
297
|
+
return resolveOAuth(stored, path, opts, env);
|
|
298
|
+
}
|
|
299
|
+
if (stored.api_key.length === 0) return void 0;
|
|
300
|
+
if (stored.provider !== opts.provider) return void 0;
|
|
301
|
+
return {
|
|
302
|
+
kind: "api",
|
|
303
|
+
provider: opts.provider,
|
|
304
|
+
apiKey: stored.api_key,
|
|
305
|
+
source: path,
|
|
306
|
+
inferred: false
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export { CredentialError, authFilePath, credentialHome, ensureFreshCredential, exchangeCode, persistOAuthTokens, readAuthFile, readStoredOAuth, refreshOAuthTokens, resolveCredential, writeCredential };
|
|
311
|
+
//# sourceMappingURL=chunk-LU7VALW5.js.map
|
|
312
|
+
//# sourceMappingURL=chunk-LU7VALW5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/auth/credential-store.ts","../src/internal/auth/oauth-engine.ts","../src/internal/auth/resolve-credential.ts"],"names":["fresh"],"mappings":";;;;;;;AAwCO,SAAS,cAAA,CACd,MAAA,EACA,GAAA,GAA0C,EAAC,EACnC;AACR,EAAA,MAAM,QAAA,GAAW,OAAO,UAAA,KAAe,MAAA,GAAY,IAAI,MAAA,CAAO,UAAU,CAAA,EAAG,IAAA,EAAK,GAAI,MAAA;AACpF,EAAA,OAAO,QAAA,KAAa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AAA;AACzF;AAEA,eAAsB,kBACpB,IAAA,EACyC;AACzC,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,IAAO,EAAC;AACzB,EAAA,MAAM,MAAA,GAAS,YAAA,CAAa,IAAA,CAAK,KAAA,EAAO,GAAG,CAAA;AAC3C,EAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AAEjC,EAAA,MAAM,IAAA,GAAO,YAAA,CAAa,IAAA,CAAK,KAAA,EAAO,GAAG,CAAA;AAEzC,EAAA,IAAI,MAAA,CAAO,SAAS,OAAA,EAAS;AAC3B,IAAA,OAAO,YAAA,CAAa,MAAA,EAAQ,IAAA,EAAM,IAAA,EAAM,GAAG,CAAA;AAAA,EAC7C;AAOA,EAAA,IAAI,MAAA,CAAO,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG,OAAO,MAAA;AACxC,EAAA,IAAI,MAAA,CAAO,QAAA,KAAa,IAAA,CAAK,QAAA,EAAU,OAAO,MAAA;AAC9C,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,KAAA;AAAA,IACN,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,QAAQ,MAAA,CAAO,OAAA;AAAA,IACf,MAAA,EAAQ,IAAA;AAAA,IACR,QAAA,EAAU;AAAA,GACZ;AACF","file":"chunk-LU7VALW5.js","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { AuthenticationError } from \"../../errors.js\";\n\n/**\n * M42 — the SDK credential store. Promoted DOWN from agent-builder's hardened `agents/lib/credentials.ts`\n * (M37), generalized from a closed `openrouter|anthropic|openai` union to an open `provider: string` and\n * driven by a caller-supplied {@link CredentialStoreConfig} (no hardcoded `.agent-builder`/`auth.json` /\n * `AGENT_BUILDER_HOME`). The security-critical file mechanics are ported VERBATIM (ADR D3 of the M42 plan):\n * atomic O_EXCL + rename + fsync write, 0700/0600 mode gates, `env` is always a PARAMETER (never an ambient\n * `process.env` read). Contract SHAPE adapted from OpenCode's provider `auth.loader` (MIT © 2025 opencode).\n *\n * The env-precedence + key-prefix-inference + declared-provider rungs of the agent-builder resolver are\n * APP POLICY and deliberately stay UP in the consumer; this module owns only the on-disk store + the\n * `api|oauth` discriminated union. See {@link resolveCredential} (SDK) for the store-read + refresh path.\n *\n * @internal\n */\nimport type {\n CredentialStoreConfig,\n StoredCredential,\n StoredOAuthCredential,\n} from \"./auth-types.js\";\n\n/** The store directory, honoring an optional `homeEnvVar` override. */\nexport function credentialHome(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const override = config.homeEnvVar !== undefined ? env[config.homeEnvVar]?.trim() : undefined;\n return override !== undefined && override.length > 0\n ? override\n : join(config.home, config.dirName);\n}\n\n/** The credential file path inside the (possibly overridden) store directory. */\nexport function authFilePath(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n return join(credentialHome(config, env), config.fileName);\n}\n\n/**\n * A credential problem the caller can act on. Never carries the key value.\n *\n * M78 — this used to extend bare `Error`, which quietly disabled classification for the entire auth\n * path: `isTransientError` is `err instanceof TheokitAgentError && err.isRetryable === true`\n * (`errors.ts:443`), so a credential failure could never be judged transient OR permanent. The\n * predicate was not \"forgotten\" downstream — it was unusable there by construction.\n *\n * Extending `AuthenticationError` is ADDITIVE: the class still exists, still reports\n * `name: \"CredentialError\"`, and every existing `instanceof CredentialError` stays true. It only\n * gains ancestors. `AuthenticationError` pins `isRetryable: false`, so gaining the ability to be\n * classified does NOT turn a revoked credential into a retry loop.\n *\n * The single reference does the same thing with one root type: Codex routes every domain failure\n * through `CodexErr` with `is_retryable()` as a method (`protocol/src/error.rs:176`), rather than\n * parallel classes extending the language's `Error`.\n */\nexport class CredentialError extends AuthenticationError {\n // Field, not an assignment in the constructor: `AuthenticationError.name` is `override readonly`\n // (`errors.ts:174`), so `this.name = …` does not compile. Caught by `tsc`, not by vitest — the\n // suite was green with the broken assignment because the transpiler strips the type.\n override readonly name: string = \"CredentialError\";\n}\n\n/**\n * The on-disk store — a discriminated union on `type` (OpenCode `Info` shape). A legacy file with NO\n * `type` (or `type: 'api'`) is the API-key variant — read unchanged, no migration. The `oauth` variant\n * carries the token pair + expiry.\n */\nconst apiFileSchema = z\n .object({\n type: z.literal(\"api\").optional(),\n provider: z.string().min(1).optional(),\n api_key: z.string(),\n })\n .strict();\n\nconst oauthFileSchema = z\n .object({\n type: z.literal(\"oauth\"),\n provider: z.string().min(1),\n access: z.string().min(1),\n refresh: z.string().min(1),\n expires: z.number(),\n account_id: z.string().optional(),\n })\n .strict();\n\n// oauth first (it requires `type: 'oauth'`); a legacy `{provider?, api_key}` falls through to api.\nconst fileSchema = z.union([oauthFileSchema, apiFileSchema]);\n\n/**\n * Read the credential file. Absent ⇒ `undefined` (the normal case). Present-but-wrong is a typed error\n * naming the file: a malformed credential store must not surface as a raw parse crash. Enforces the\n * 0700 dir / 0600 file mode gates (ported verbatim — a writable dir lets an attacker swap the file for a\n * symlink to their own account).\n */\n/**\n * The 0700-dir / 0600-file mode gates (ported verbatim). The DIRECTORY matters as much as the file:\n * `mkdirSync(mode)` applies only at creation, so a pre-existing store dir keeps whatever mode it had, and a\n * writable dir lets an attacker replace the credential file with a symlink to their own 0600 file — the\n * agent then runs on THEIR account.\n */\nfunction assertSecureModes(dirPath: string, path: string): void {\n const dirMode = statSync(dirPath).mode & 0o777;\n if ((dirMode & 0o022) !== 0) {\n throw new CredentialError(\n `${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file ` +\n `inside it can be replaced. Fix it with: chmod 700 ${dirPath}`,\n );\n }\n const mode = statSync(path).mode & 0o777;\n if ((mode & 0o077) !== 0) {\n throw new CredentialError(\n `${path} is readable by other users (mode ${mode.toString(8)}). ` +\n `A credential file must not be. Fix it with: chmod 600 ${path}`,\n );\n }\n}\n\n/**\n * A `z.union` reports a generic \"Invalid input\" at the root, hiding WHAT is wrong. Pick the sub-schema the\n * file was CLEARLY aiming at (by its `type` discriminant) and surface that schema's specific issue.\n */\nfunction describeUnionError(parsed: unknown, err: unknown, path: string): CredentialError {\n const looksOAuth =\n typeof parsed === \"object\" &&\n parsed !== null &&\n (parsed as { type?: unknown }).type === \"oauth\";\n const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);\n let issue: z.ZodIssue | undefined;\n if (!specific.success) {\n issue = specific.error.issues[0];\n } else if (err instanceof z.ZodError) {\n issue = err.issues[0];\n }\n return new CredentialError(\n `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(\".\") || \"root\"}]`,\n );\n}\n\n/** Parse the raw file into the store union, surfacing the SPECIFIC sub-schema issue (not a generic union error). */\nfunction parseStoredFile(raw: string, path: string): StoredCredential {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // The parser's message embeds a snippet of the INPUT — up to the raw key when a user pastes the bare\n // key instead of JSON. The position is not actionable anyway, so the expected shape is more useful.\n throw new CredentialError(\n `${path} is not valid JSON. Expected: {\"provider\": \"<name>\", \"api_key\": \"...\"}`,\n );\n }\n try {\n return fileSchema.parse(parsed);\n } catch (err) {\n throw describeUnionError(parsed, err, path);\n }\n}\n\nexport function readAuthFile(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredCredential | undefined {\n const path = authFilePath(config, env);\n\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new CredentialError(`cannot read ${path}: ${(err as Error).message}`);\n }\n\n assertSecureModes(credentialHome(config, env), path);\n return parseStoredFile(raw, path);\n}\n\n/**\n * Read the stored OAuth credential (with its refresh token), or `undefined` when the store is absent or\n * holds an api credential. The oauth engine needs the refresh token, which the resolved bearer does not\n * carry. Enforces the same 0600/0700 gates as every other read.\n */\nexport function readStoredOAuth(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredOAuthCredential | undefined {\n const stored = readAuthFile(config, env);\n return stored !== undefined && stored.type === \"oauth\" ? stored : undefined;\n}\n\n/** Narrows a writable credential to the oauth variant. */\nfunction isOAuthWrite(\n c: { provider: string; apiKey: string } | StoredOAuthCredential,\n): c is StoredOAuthCredential {\n return \"type\" in c && c.type === \"oauth\";\n}\n\n/**\n * Persist a credential atomically at mode `0600`. Ported VERBATIM (ADR D3): write to a random-named temp\n * file in the same directory with `wx` (O_EXCL), fsync, close, chmod, then `rename` (atomic on POSIX) —\n * so a crash mid-write leaves whatever was there untouched, and a pre-planted symlink cannot capture the\n * key. The api variant persists the unchanged `{provider, api_key}` (back-compat, no `type` key); the\n * oauth variant persists `{type:'oauth', provider, access, refresh, expires, account_id?}`.\n */\n/** Build the on-disk JSON payload for the credential variant, validating non-empty tokens. */\nfunction buildStorePayload(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n): Record<string, unknown> {\n if (isOAuthWrite(cred)) {\n if (cred.access.length === 0 || cred.refresh.length === 0) {\n throw new CredentialError(\n \"refusing to write an oauth credential with an empty access/refresh token\",\n );\n }\n return {\n type: \"oauth\",\n provider: cred.provider,\n access: cred.access,\n refresh: cred.refresh,\n expires: cred.expires,\n ...(cred.account_id !== undefined ? { account_id: cred.account_id } : {}),\n };\n }\n if (typeof cred.apiKey !== \"string\" || cred.apiKey.length === 0) {\n throw new CredentialError(\"refusing to write an empty API key\");\n }\n return { provider: cred.provider, api_key: cred.apiKey };\n}\n\nexport function writeCredential(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const payload = buildStorePayload(cred);\n\n const dir = credentialHome(config, env);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700); // unconditional: mkdirSync's mode applies only at creation\n\n const path = authFilePath(config, env);\n // RANDOM name + `wx` (O_EXCL): a predictable temp name with a plain write follows a pre-planted SYMLINK,\n // landing the key in an attacker's file while reporting success. O_EXCL refuses any pre-existing file or\n // link; the random suffix also removes the pid collision two containers sharing a bind-mounted home make.\n const tmp = `${path}.tmp-${randomBytes(8).toString(\"hex\")}`;\n try {\n const fd = openSync(tmp, \"wx\", 0o600);\n try {\n writeFileSync(fd, `${JSON.stringify(payload, null, 2)}\\n`);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n chmodSync(tmp, 0o600); // explicit: the mode argument is subject to umask\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // the temp file may not exist; its absence is not a failure of the write\n }\n throw new CredentialError(`cannot write ${path}: ${(err as Error).message}`);\n }\n return path;\n}\n","/**\n * M42 — the SDK OAuth engine. Promoted DOWN from agent-builder's hardened `agents/lib/oauth.ts` +\n * `oauth-device.ts` (M37), generalized to `provider: string` + a caller-supplied {@link CredentialStoreConfig}\n * (no hardcoded client IDs — the caller declares its provider's endpoints). Ported VERBATIM (ADR D3): the\n * refresh coalescing lock, the no-token-in-error discipline, and the RFC 8628 device grant.\n *\n * Reuses the SDK's typed error taxonomy (`AuthCallbackError` from `server/auth`) for exchange/refresh\n * failures. All network I/O + clock + sleep are INJECTED so the flow is deterministic.\n *\n * ─── ADAPTED FROM OpenCode (MIT License, Copyright (c) 2025 opencode — https://github.com/sst/opencode) ───\n * - the device-grant poll loop (device_code → authorization_pending / slow_down) is adapted from\n * `packages/opencode/src/plugin/github-copilot/copilot.ts`;\n * - the JWT-claim / account-id extraction + the OpenAI two-step headless flow are adapted from\n * `packages/opencode/src/plugin/openai/codex.ts`.\n * The MIT license permits this reuse with attribution; this notice + the NOTICE file are that attribution.\n *\n * @internal\n */\nimport { AuthCallbackError } from \"../../server/auth/errors.js\";\n\nimport type {\n CredentialStoreConfig,\n HttpDeps,\n OAuthProviderConfig,\n OAuthTokens,\n ResolvedCredential,\n} from \"./auth-types.js\";\nimport { authFilePath, readStoredOAuth, writeCredential } from \"./credential-store.js\";\n\n/** Refresh a token this many ms BEFORE it actually expires (avoid a last-second, mid-request expiry). */\nconst REFRESH_SKEW_MS = 60_000;\n\n/** Parse an OAuth token endpoint response into our token triple. Throws a typed error on a bad shape. */\nfunction parseTokenResponse(body: unknown, now: number): OAuthTokens {\n const b = body as {\n access_token?: unknown;\n refresh_token?: unknown;\n expires_in?: unknown;\n account_id?: unknown;\n };\n if (typeof b.access_token !== \"string\" || b.access_token.length === 0) {\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n \"token response had no access_token\",\n );\n }\n if (typeof b.refresh_token !== \"string\" || b.refresh_token.length === 0) {\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n \"token response had no refresh_token\",\n );\n }\n const expiresIn = typeof b.expires_in === \"number\" ? b.expires_in : 3600;\n return {\n access: b.access_token,\n refresh: b.refresh_token,\n expires: now + expiresIn * 1000,\n ...(typeof b.account_id === \"string\" ? { accountId: b.account_id } : {}),\n };\n}\n\n/** POST a form-encoded grant to the token endpoint; return the parsed JSON or throw a typed error. */\nasync function postGrant(\n config: OAuthProviderConfig,\n form: Record<string, string>,\n deps: HttpDeps,\n): Promise<OAuthTokens> {\n let res: Response;\n try {\n res = await deps.fetch(config.tokenEndpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\", accept: \"application/json\" },\n body: new URLSearchParams(form).toString(),\n });\n } catch (err) {\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n `token endpoint request failed: ${(err as Error).message}`,\n );\n }\n if (!res.ok) {\n // The body may carry an OAuth `error` code, but never echo it verbatim — it can contain a token in\n // some providers' error payloads. Report the status only.\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n `token endpoint returned HTTP ${res.status}`,\n );\n }\n let json: unknown;\n try {\n json = await res.json();\n } catch {\n // Do NOT echo the parser message — on a 200 non-JSON body it embeds a snippet of the response, which\n // in a token context can contain access/refresh material.\n throw new AuthCallbackError(\"oauth_token_exchange_failed\", \"token response was not valid JSON\");\n }\n return parseTokenResponse(json, deps.now());\n}\n\n/** Exchange an authorization `code` (+ PKCE verifier) for the token pair. */\nexport function exchangeCode(\n config: OAuthProviderConfig,\n input: { code: string; verifier: string },\n deps: HttpDeps,\n): Promise<OAuthTokens> {\n return postGrant(\n config,\n {\n grant_type: \"authorization_code\",\n code: input.code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n code_verifier: input.verifier,\n },\n deps,\n );\n}\n\n/** Swap a refresh token for a fresh access (and possibly rotated refresh) token. */\nexport function refreshOAuthTokens(\n config: OAuthProviderConfig,\n refresh: string,\n deps: HttpDeps,\n): Promise<OAuthTokens> {\n return postGrant(\n config,\n { grant_type: \"refresh_token\", refresh_token: refresh, client_id: config.clientId },\n deps,\n );\n}\n\n/** Persist a token triple to the store's oauth variant through the hardened 0600 writer. */\nexport function persistOAuthTokens(\n provider: string,\n tokens: OAuthTokens,\n store: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n return writeCredential(\n {\n type: \"oauth\",\n provider,\n access: tokens.access,\n refresh: tokens.refresh,\n expires: tokens.expires,\n ...(tokens.accountId !== undefined ? { account_id: tokens.accountId } : {}),\n },\n store,\n env,\n );\n}\n\n/**\n * In-flight refreshes, keyed by the auth-file path. Refresh tokens ROTATE (single-use) on many providers,\n * so two concurrent turns must NOT both POST the same refresh token — the second would present an\n * already-consumed token and fail. This coalesces concurrent refreshes of the same store onto one promise.\n * Process-local — the single-credential store is per-user; a cross-process lock would be over-engineering.\n */\nconst inFlightRefresh = new Map<string, Promise<OAuthTokens>>();\n\n/**\n * Return a credential guaranteed fresh enough to use. An `api` credential passes through untouched. An\n * `oauth` credential still valid (beyond the skew window) passes through; an expired one is refreshed,\n * re-persisted 0600, and returned with the new access token. Concurrent refreshes of the same store are\n * coalesced (single-use refresh tokens); the rejected promise is evicted so a failure is not cached-poison.\n */\nexport async function ensureFreshCredential(\n resolved: ResolvedCredential,\n opts: {\n config: OAuthProviderConfig;\n store: CredentialStoreConfig;\n env?: Record<string, string | undefined>;\n },\n deps: HttpDeps,\n): Promise<ResolvedCredential> {\n if (resolved.kind !== \"oauth\") return resolved;\n\n const now = deps.now();\n if (resolved.expiresAt !== undefined && resolved.expiresAt > now + REFRESH_SKEW_MS) {\n return resolved; // still valid — no network, no rewrite\n }\n\n const env = opts.env ?? {};\n const path = authFilePath(opts.store, env);\n let refresh = inFlightRefresh.get(path);\n if (refresh === undefined) {\n refresh = (async (): Promise<OAuthTokens> => {\n const stored = readStoredOAuth(opts.store, env);\n if (stored === undefined) {\n // The resolved credential said oauth but the store no longer holds it — do not fabricate; surface it.\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n \"no stored oauth credential to refresh\",\n );\n }\n const fresh = await refreshOAuthTokens(opts.config, stored.refresh, deps);\n // M43 D4 fix #1 — the OAuth refresh response returns JWTs, not a top-level `account_id`, so\n // `parseTokenResponse` leaves `fresh.accountId` undefined. Prefer a freshly-derived id, else PRESERVE\n // the stored one (account_id is stable) — otherwise the Codex `ChatGPT-Account-Id` header empties after\n // the first refresh and the backend 401/403s.\n const merged: OAuthTokens = {\n ...fresh,\n accountId: fresh.accountId ?? stored.account_id,\n };\n persistOAuthTokens(resolved.provider, merged, opts.store, env);\n return merged;\n })();\n inFlightRefresh.set(path, refresh);\n refresh.finally(() => inFlightRefresh.delete(path)).catch(() => {});\n }\n\n const fresh = await refresh;\n return {\n kind: \"oauth\",\n provider: resolved.provider,\n apiKey: fresh.access,\n source: resolved.source,\n inferred: false,\n expiresAt: fresh.expires,\n };\n}\n","/**\n * M42 — `resolveCredential`: the public composition entrypoint over the credential store + oauth engine.\n * Given a provider name + a {@link CredentialStoreConfig} (and, for oauth, an {@link OAuthProviderConfig}),\n * read the store and return a FRESH `ResolvedCredential` — an api credential passes through by identity; an\n * oauth credential is transparently refreshed when its access token is within the skew window. Returns\n * `undefined` when the store holds no credential for `provider` (the caller then falls back to env / apiKeys).\n *\n * Mirrors agent-builder's `resolveFreshCredential` composition (store read → oauth → ensureFreshCredential),\n * defaulting `fetch`/`now` to globals. This is the async surface an oauth provider's M41 `transform.fetch`\n * calls at stream time, so a mid-turn token expiry refreshes without rebuilding the agent.\n *\n * @internal (re-exported from the package barrel as public)\n */\nimport type {\n CredentialStoreConfig,\n HttpDeps,\n OAuthProviderConfig,\n ResolvedCredential,\n} from \"./auth-types.js\";\nimport { authFilePath, readAuthFile } from \"./credential-store.js\";\nimport { ensureFreshCredential } from \"./oauth-engine.js\";\n\nexport interface ResolveCredentialOptions {\n /** The provider whose stored credential to resolve. */\n provider: string;\n /** Where the credential store lives. */\n store: CredentialStoreConfig;\n /** Env for the store's optional `homeEnvVar` override. Never an ambient read. */\n env?: Record<string, string | undefined>;\n /** Required to refresh an oauth credential; omit for an api-only store. */\n oauth?: OAuthProviderConfig;\n /** Injected HTTP + clock for deterministic tests; default globals. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * Resolve a fresh credential for `provider` from the store, or `undefined` if the store holds none for it.\n * oauth credentials are auto-refreshed when `opts.oauth` is supplied; api credentials pass through.\n */\n/** Resolve (and, when a config is supplied, refresh) the oauth variant for the requested provider. */\nasync function resolveOAuth(\n stored: { provider: string; access: string; expires: number },\n path: string,\n opts: ResolveCredentialOptions,\n env: Record<string, string | undefined>,\n): Promise<ResolvedCredential | undefined> {\n if (stored.provider !== opts.provider) return undefined;\n const base: ResolvedCredential = {\n kind: \"oauth\",\n provider: opts.provider,\n apiKey: stored.access,\n source: path,\n inferred: false,\n expiresAt: stored.expires,\n };\n if (opts.oauth === undefined) return base; // no config to refresh with — return the stored access token\n const deps: HttpDeps = {\n fetch: opts.deps?.fetch ?? fetch,\n now: opts.deps?.now ?? (() => Date.now()),\n };\n return ensureFreshCredential(base, { config: opts.oauth, store: opts.store, env }, deps);\n}\n\nexport async function resolveCredential(\n opts: ResolveCredentialOptions,\n): Promise<ResolvedCredential | undefined> {\n const env = opts.env ?? {};\n const stored = readAuthFile(opts.store, env);\n if (stored === undefined) return undefined;\n\n const path = authFilePath(opts.store, env);\n\n if (stored.type === \"oauth\") {\n return resolveOAuth(stored, path, opts, env);\n }\n\n // api variant: require the stored `provider` to MATCH the requested provider (M42 review MEDIUM-2).\n // The generic SDK cannot infer a provider from a key prefix (that was agent-builder app policy), so a\n // provider-less or mismatched stored key is NOT attributed to the requested provider — otherwise a legacy\n // `{api_key:\"sk-ant-…\"}` file could be POSTed to the wrong vendor's endpoint (cross-vendor key exposure).\n // Fail-closed, mirroring OpenCode, whose credential resolution never attributes a key across providers.\n if (stored.api_key.length === 0) return undefined;\n if (stored.provider !== opts.provider) return undefined;\n return {\n kind: \"api\",\n provider: opts.provider,\n apiKey: stored.api_key,\n source: path,\n inferred: false,\n };\n}\n"]}
|