theokit 0.75.0 → 0.76.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -1
- package/dist/{actions-virtual-module-MIQPBAZW.js → actions-virtual-module-34PJIOI6.js} +11 -9
- package/dist/actions-virtual-module-34PJIOI6.js.map +1 -0
- package/dist/{actions-virtual-module-QEI6QPK4.js → actions-virtual-module-HS4W7HQU.js} +6 -5
- package/dist/{actions-virtual-module-QEI6QPK4.js.map → actions-virtual-module-HS4W7HQU.js.map} +1 -1
- package/dist/adapters/agent-mount.js +9 -7
- package/dist/{agent-IIF6JUWX.js → agent-HCK5RHH7.js} +4 -3
- package/dist/{app-typed-client-CHSITA46.js → app-typed-client-BWITJLJA.js} +6 -5
- package/dist/{app-typed-client-CHSITA46.js.map → app-typed-client-BWITJLJA.js.map} +1 -1
- package/dist/{app-typed-client-XQJXF646.js → app-typed-client-FR4M4VND.js} +11 -9
- package/dist/app-typed-client-FR4M4VND.js.map +1 -0
- package/dist/{aws-lambda-K5Y6XS5V.js → aws-lambda-XT7ZDJ6B.js} +3 -3
- package/dist/{build-QIO4VAW2.js → build-Y3CWTWP6.js} +25 -93
- package/dist/build-Y3CWTWP6.js.map +1 -0
- package/dist/{bun-VPXMWFBA.js → bun-PJLDELDT.js} +5 -5
- package/dist/{chunk-D7STTNQN.js → chunk-2FZYZHZM.js} +3 -3
- package/dist/{chunk-RKRFJRJ3.js → chunk-2SGNODVJ.js} +31 -17
- package/dist/chunk-2SGNODVJ.js.map +1 -0
- package/dist/chunk-2SQ7YAU3.js +85 -0
- package/dist/chunk-2SQ7YAU3.js.map +1 -0
- package/dist/{chunk-SYIQV4UH.js → chunk-33DGAR6Q.js} +2 -2
- package/dist/{chunk-CLSYYO5F.js → chunk-3HRANFEN.js} +2 -2
- package/dist/{chunk-EW5IG7GA.js → chunk-42TYMRBG.js} +1 -1
- package/dist/{chunk-EW5IG7GA.js.map → chunk-42TYMRBG.js.map} +1 -1
- package/dist/{chunk-BINRCILF.js → chunk-4JRXZTVQ.js} +4 -13
- package/dist/chunk-4JRXZTVQ.js.map +1 -0
- package/dist/{chunk-ICXXHV4V.js → chunk-54BIQFP4.js} +4 -13
- package/dist/chunk-54BIQFP4.js.map +1 -0
- package/dist/{chunk-NX3P5MLH.js → chunk-C2BRSL4W.js} +50 -6
- package/dist/chunk-C2BRSL4W.js.map +1 -0
- package/dist/{chunk-6RVWPEKK.js → chunk-C5FBN5LO.js} +88 -24
- package/dist/chunk-C5FBN5LO.js.map +1 -0
- package/dist/{chunk-NLHAYGQQ.js → chunk-G3DDIEYE.js} +4 -2
- package/dist/chunk-G3DDIEYE.js.map +1 -0
- package/dist/{chunk-R4AMIBZL.js → chunk-GLD7UXOG.js} +5 -5
- package/dist/chunk-GLD7UXOG.js.map +1 -0
- package/dist/{chunk-3MKRDJQ2.js → chunk-I27DTFV4.js} +273 -75
- package/dist/chunk-I27DTFV4.js.map +1 -0
- package/dist/chunk-ISTKIQNY.js +67 -0
- package/dist/chunk-ISTKIQNY.js.map +1 -0
- package/dist/chunk-IXXZBZF7.js +70 -0
- package/dist/chunk-IXXZBZF7.js.map +1 -0
- package/dist/{chunk-PVNMLZ5G.js → chunk-JO462JZM.js} +2 -2
- package/dist/chunk-KKLXKR2B.js +469 -0
- package/dist/chunk-KKLXKR2B.js.map +1 -0
- package/dist/{chunk-RY6D4EXL.js → chunk-LCP5FT55.js} +25 -4
- package/dist/{chunk-RY6D4EXL.js.map → chunk-LCP5FT55.js.map} +1 -1
- package/dist/{chunk-D2R5SJEL.js → chunk-MAJZ2L3A.js} +2 -2
- package/dist/{chunk-D2R5SJEL.js.map → chunk-MAJZ2L3A.js.map} +1 -1
- package/dist/chunk-NF7LXSXZ.js +19 -0
- package/dist/chunk-NF7LXSXZ.js.map +1 -0
- package/dist/{chunk-VPK7ABMB.js → chunk-NWUZMJN2.js} +3 -3
- package/dist/{chunk-EVKNHQWG.js → chunk-OO3PHTRT.js} +45 -4
- package/dist/chunk-OO3PHTRT.js.map +1 -0
- package/dist/{chunk-2Z7TANA4.js → chunk-PVI6HM6E.js} +3 -3
- package/dist/{chunk-4X43VTST.js → chunk-TODO6J42.js} +1 -1
- package/dist/chunk-TODO6J42.js.map +1 -0
- package/dist/{chunk-ZDCCILMP.js → chunk-TQTEKNOL.js} +2 -69
- package/dist/chunk-TQTEKNOL.js.map +1 -0
- package/dist/{chunk-MX63AWEK.js → chunk-VXDTQO3S.js} +22 -6
- package/dist/{chunk-MX63AWEK.js.map → chunk-VXDTQO3S.js.map} +1 -1
- package/dist/{chunk-OZB2TKGJ.js → chunk-W2I6L4IJ.js} +2 -2
- package/dist/{chunk-2BMJQMTH.js → chunk-XDLFOATW.js} +5 -5
- package/dist/{chunk-RQKMY3JW.js → chunk-XI4FALFZ.js} +3 -3
- package/dist/chunk-XI4FALFZ.js.map +1 -0
- package/dist/{chunk-47VNWTL4.js → chunk-XXHR7X35.js} +9 -5
- package/dist/chunk-XXHR7X35.js.map +1 -0
- package/dist/{chunk-2FHNJ7LI.js → chunk-Z76QQR7I.js} +2 -2
- package/dist/chunk-ZICY2CD7.js +16 -0
- package/dist/chunk-ZICY2CD7.js.map +1 -0
- package/dist/{chunk-I5PDEWZZ.js → chunk-ZQJORKBM.js} +9 -3
- package/dist/chunk-ZQJORKBM.js.map +1 -0
- package/dist/cli/index.js +21 -15
- package/dist/cli/index.js.map +1 -1
- package/dist/{cloudflare-PRTTYWRD.js → cloudflare-F7KLBOU4.js} +7 -7
- package/dist/{cloudflare-PRTTYWRD.js.map → cloudflare-F7KLBOU4.js.map} +1 -1
- package/dist/{config-support-HUZ4DXR7.js → config-support-2TER2BYD.js} +28 -21
- package/dist/config-support-2TER2BYD.js.map +1 -0
- package/dist/cron-lock-C3YpKDz2.d.ts +33 -0
- package/dist/db-ZWDKD57T.js +86 -0
- package/dist/db-ZWDKD57T.js.map +1 -0
- package/dist/{deno-deploy-M5V3PYWU.js → deno-deploy-LJ5JQQVR.js} +5 -5
- package/dist/{dev-J2XZIENF.js → dev-R6U3JOYM.js} +60 -11
- package/dist/dev-R6U3JOYM.js.map +1 -0
- package/dist/{dev-emit-AXTJK56H.js → dev-emit-BR6ERY63.js} +9 -5
- package/dist/dev-emit-BR6ERY63.js.map +1 -0
- package/dist/{dev-emit-XAPVJBM4.js → dev-emit-GFGLZZOH.js} +2 -2
- package/dist/{engine-singleton-X4R7AZBJ.js → engine-singleton-BQ5QOMTC.js} +15 -9
- package/dist/{engine-singleton-X4R7AZBJ.js.map → engine-singleton-BQ5QOMTC.js.map} +1 -1
- package/dist/{generate-RW3NO3NR.js → generate-2VAWEL7X.js} +205 -65
- package/dist/generate-2VAWEL7X.js.map +1 -0
- package/dist/{index-CmkWlIDO.d.ts → index-DfsJ3Qhk.d.ts} +1 -1
- package/dist/index.d.ts +12 -3
- package/dist/index.js +12 -10
- package/dist/index.js.map +1 -1
- package/dist/{info-6NAUW5XY.js → info-IPMW56PI.js} +4 -4
- package/dist/{internal-api-R7TTYMCY.js → internal-api-6RAOYIET.js} +6 -5
- package/dist/{internal-api-A5HA7TYF.js → internal-api-LJOFLJSS.js} +13 -10
- package/dist/job-backend-WvUs5rO1.d.ts +119 -0
- package/dist/{load-config-CLFWJOXN.js → load-config-USRR4GXP.js} +4 -4
- package/dist/{mcp-MWTG3LRA.js → mcp-FBXEX45H.js} +5 -4
- package/dist/{mcp-MWTG3LRA.js.map → mcp-FBXEX45H.js.map} +1 -1
- package/dist/{netlify-NI4HYDKN.js → netlify-ZPQNREFH.js} +2 -2
- package/dist/{node-LORYECWI.js → node-3EV3CVWB.js} +2 -2
- package/dist/{observability-bootstrap-DOWRMADT.js → observability-bootstrap-DMJ7R6WA.js} +3 -3
- package/dist/{openapi-RVFUXXCR.js → openapi-CA3E3LZH.js} +5 -5
- package/dist/{preview-ML4CFUD6.js → preview-AX2TMD26.js} +3 -3
- package/dist/registry-3D2KR7UE.js +34 -0
- package/dist/{routes-SMNSI2ZX.js → routes-BJ7GGRCV.js} +4 -4
- package/dist/{schema-DJH3IOVR.js → schema-FBM2UH72.js} +3 -3
- package/dist/{schemas-2R2J64ZH.js → schemas-BUR6PWSA.js} +2 -2
- package/dist/server/agent/index.d.ts +1 -1
- package/dist/server/agent/index.js +2 -1
- package/dist/server/cost/index.d.ts +2 -2
- package/dist/server/cost/index.js +1 -1
- package/dist/server/cost/sqlite/index.d.ts +2 -2
- package/dist/server/cost/sqlite/index.js +1 -1
- package/dist/server/cron/index.d.ts +20 -7
- package/dist/server/cron/index.js +5 -2
- package/dist/server/http/index.d.ts +2 -2
- package/dist/server/http/index.js +9 -7
- package/dist/server/index.d.ts +8 -7
- package/dist/server/index.js +42 -27
- package/dist/server/index.js.map +1 -1
- package/dist/server/jobs/index.d.ts +85 -44
- package/dist/server/jobs/index.js +8 -2
- package/dist/server/observability/index.js +8 -7
- package/dist/server/storage/index.d.ts +2 -2
- package/dist/server/storage/index.js +4 -1
- package/dist/server/webhook/index.d.ts +4 -5
- package/dist/server/webhook/index.js +1 -1
- package/dist/{server-boundary-ZT6HN7ON.js → server-boundary-EKIGYL7B.js} +6 -5
- package/dist/{server-boundary-ZT6HN7ON.js.map → server-boundary-EKIGYL7B.js.map} +1 -1
- package/dist/{server-boundary-HYLYGFZY.js → server-boundary-WSGVQAXP.js} +11 -9
- package/dist/server-boundary-WSGVQAXP.js.map +1 -0
- package/dist/{start-L5TGWGLU.js → start-4FY3TLM7.js} +118 -185
- package/dist/start-4FY3TLM7.js.map +1 -0
- package/dist/{static-O2RZ5NLR.js → static-VNN4HYRN.js} +2 -2
- package/dist/{storage-manager-BtG38jYl.d.ts → storage-manager-Clu2RBpH.d.ts} +15 -3
- package/dist/{storage-manager-3O5PDO6O.js → storage-manager-O3APCXYX.js} +46 -5
- package/dist/storage-manager-O3APCXYX.js.map +1 -0
- package/dist/{storage-types-CFGPFIdB.d.ts → storage-types-ndO0ZZqH.d.ts} +2 -2
- package/dist/{theo-cloud-B4R7GCWK.js → theo-cloud-243SPOIA.js} +2 -2
- package/dist/{vercel-INHLOCSZ.js → vercel-EXKSZ2OQ.js} +5 -5
- package/dist/vite-plugin/index.js +12 -10
- package/dist/{vite-plugin-OJND2LU5.js → vite-plugin-LE42ZIGV.js} +10 -9
- package/dist/{whatsapp-D_Fnl1LX.d.ts → whatsapp-4W2eK2ij.d.ts} +1 -1
- package/package.json +5 -5
- package/dist/actions-virtual-module-MIQPBAZW.js.map +0 -1
- package/dist/app-typed-client-XQJXF646.js.map +0 -1
- package/dist/build-QIO4VAW2.js.map +0 -1
- package/dist/chunk-3MKRDJQ2.js.map +0 -1
- package/dist/chunk-47VNWTL4.js.map +0 -1
- package/dist/chunk-4X43VTST.js.map +0 -1
- package/dist/chunk-6RVWPEKK.js.map +0 -1
- package/dist/chunk-BINRCILF.js.map +0 -1
- package/dist/chunk-EVKNHQWG.js.map +0 -1
- package/dist/chunk-I5PDEWZZ.js.map +0 -1
- package/dist/chunk-ICXXHV4V.js.map +0 -1
- package/dist/chunk-IDEZ7FU2.js +0 -18
- package/dist/chunk-IDEZ7FU2.js.map +0 -1
- package/dist/chunk-NLHAYGQQ.js.map +0 -1
- package/dist/chunk-NX3P5MLH.js.map +0 -1
- package/dist/chunk-R4AMIBZL.js.map +0 -1
- package/dist/chunk-RKRFJRJ3.js.map +0 -1
- package/dist/chunk-RQKMY3JW.js.map +0 -1
- package/dist/chunk-YCF3N4JS.js +0 -26
- package/dist/chunk-YCF3N4JS.js.map +0 -1
- package/dist/chunk-ZDCCILMP.js.map +0 -1
- package/dist/config-support-HUZ4DXR7.js.map +0 -1
- package/dist/db-IVVCQE5Z.js +0 -76
- package/dist/db-IVVCQE5Z.js.map +0 -1
- package/dist/dev-J2XZIENF.js.map +0 -1
- package/dist/dev-emit-AXTJK56H.js.map +0 -1
- package/dist/generate-RW3NO3NR.js.map +0 -1
- package/dist/job-backend-CgC8Xf33.d.ts +0 -68
- package/dist/registry-SUE4HJXL.js +0 -34
- package/dist/server-boundary-HYLYGFZY.js.map +0 -1
- package/dist/start-L5TGWGLU.js.map +0 -1
- package/dist/storage-manager-3O5PDO6O.js.map +0 -1
- /package/dist/{agent-IIF6JUWX.js.map → agent-HCK5RHH7.js.map} +0 -0
- /package/dist/{aws-lambda-K5Y6XS5V.js.map → aws-lambda-XT7ZDJ6B.js.map} +0 -0
- /package/dist/{bun-VPXMWFBA.js.map → bun-PJLDELDT.js.map} +0 -0
- /package/dist/{chunk-D7STTNQN.js.map → chunk-2FZYZHZM.js.map} +0 -0
- /package/dist/{chunk-SYIQV4UH.js.map → chunk-33DGAR6Q.js.map} +0 -0
- /package/dist/{chunk-CLSYYO5F.js.map → chunk-3HRANFEN.js.map} +0 -0
- /package/dist/{chunk-PVNMLZ5G.js.map → chunk-JO462JZM.js.map} +0 -0
- /package/dist/{chunk-VPK7ABMB.js.map → chunk-NWUZMJN2.js.map} +0 -0
- /package/dist/{chunk-2Z7TANA4.js.map → chunk-PVI6HM6E.js.map} +0 -0
- /package/dist/{chunk-OZB2TKGJ.js.map → chunk-W2I6L4IJ.js.map} +0 -0
- /package/dist/{chunk-2BMJQMTH.js.map → chunk-XDLFOATW.js.map} +0 -0
- /package/dist/{chunk-2FHNJ7LI.js.map → chunk-Z76QQR7I.js.map} +0 -0
- /package/dist/{deno-deploy-M5V3PYWU.js.map → deno-deploy-LJ5JQQVR.js.map} +0 -0
- /package/dist/{dev-emit-XAPVJBM4.js.map → dev-emit-GFGLZZOH.js.map} +0 -0
- /package/dist/{info-6NAUW5XY.js.map → info-IPMW56PI.js.map} +0 -0
- /package/dist/{internal-api-R7TTYMCY.js.map → internal-api-6RAOYIET.js.map} +0 -0
- /package/dist/{internal-api-A5HA7TYF.js.map → internal-api-LJOFLJSS.js.map} +0 -0
- /package/dist/{load-config-CLFWJOXN.js.map → load-config-USRR4GXP.js.map} +0 -0
- /package/dist/{netlify-NI4HYDKN.js.map → netlify-ZPQNREFH.js.map} +0 -0
- /package/dist/{node-LORYECWI.js.map → node-3EV3CVWB.js.map} +0 -0
- /package/dist/{observability-bootstrap-DOWRMADT.js.map → observability-bootstrap-DMJ7R6WA.js.map} +0 -0
- /package/dist/{openapi-RVFUXXCR.js.map → openapi-CA3E3LZH.js.map} +0 -0
- /package/dist/{preview-ML4CFUD6.js.map → preview-AX2TMD26.js.map} +0 -0
- /package/dist/{registry-SUE4HJXL.js.map → registry-3D2KR7UE.js.map} +0 -0
- /package/dist/{routes-SMNSI2ZX.js.map → routes-BJ7GGRCV.js.map} +0 -0
- /package/dist/{schema-DJH3IOVR.js.map → schema-FBM2UH72.js.map} +0 -0
- /package/dist/{schemas-2R2J64ZH.js.map → schemas-BUR6PWSA.js.map} +0 -0
- /package/dist/{static-O2RZ5NLR.js.map → static-VNN4HYRN.js.map} +0 -0
- /package/dist/{theo-cloud-B4R7GCWK.js.map → theo-cloud-243SPOIA.js.map} +0 -0
- /package/dist/{vercel-INHLOCSZ.js.map → vercel-EXKSZ2OQ.js.map} +0 -0
- /package/dist/{vite-plugin-OJND2LU5.js.map → vite-plugin-LE42ZIGV.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vite-plugin/index.ts","../src/vite-plugin/config-hook.ts","../src/config/load-config.ts","../src/config/errors.ts","../src/config/schema.ts","../src/core/contracts/theo-ui-theme.ts","../src/config/resolve-plugin-specifiers.ts","../src/vite-plugin/theoui-detect.ts","../src/vite-plugin/config-resolve.ts","../src/vite-plugin/configure-server-hook.ts","../src/devtools/server-side/route-manifest.ts","../src/router/scan.ts","../src/router/types.ts","../src/vite-plugin/action-middleware.ts","../src/vite-plugin/agent-middleware.ts","../src/server/agent/approve-agent.ts","../src/server/http/plugin-lifecycle.ts","../src/vite-plugin/api-middleware.ts","../src/vite-plugin/ssr-dev-middleware.ts","../src/core/contracts/find-root-div.ts","../src/vite-plugin/hoist-head-tags.ts","../src/vite-plugin/ws-upgrade.ts","../src/vite-plugin/integrate-studio.ts","../src/vite-plugin/integrate-ui.ts","../src/vite-plugin/auto-detect.ts","../src/vite-plugin/transform-html-hook.ts","../src/vite-plugin/inject-devtools.ts","../src/vite-plugin/inject-entry-client.ts","../src/vite-plugin/inject-stylesheets.ts","../src/router/entry-server.ts","../src/router/entry.ts","../src/router/generate.ts","../src/vite-plugin/virtual-modules-hook.ts","../src/vite-plugin/integrations.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,WAAAC,UAAS,WAAAC,gBAAe;AACjC,SAAS,qBAAqB;;;ACF9B,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AAiBjB,SAAS,cAAc,KAA6C;AAEzE,QAAM,MAAM,WAAW,QAAQ,IAAI,YAAY,UAAU,CAAC,IAAI,QAAQ;AAKtE,QAAM,oBAA8B,CAAC;AACrC,aAAW,aAAa,CAAC,kBAAkB,gBAAgB,cAAc,GAAG;AAC1E,UAAM,OAAO,QAAQ,IAAI,aAAa,SAAS;AAC/C,QAAI,WAAW,IAAI,EAAG,mBAAkB,KAAK,KAAK,SAAS,EAAE;AAAA,EAC/D;AAIA,QAAM,gBACJ,IAAI,YAAY,OAAO,KAAK,IAAI,QAAQ,EAAE,SAAS,IAC/C,yBAAyB,IAAI,QAAQ,IACrC;AAQN,SAAO;AAAA,IACL,WAAW;AAAA,IACX,cAAc;AAAA,MACZ,GAAI,IAAI,oBAAoB,SAAS,IAAI,EAAE,SAAS,IAAI,oBAAoB,IAAI,CAAC;AAAA,MACjF,OAAO;AAAA,IACT;AAAA,IACA,QAAQ;AAAA,MACN,GAAI,kBAAkB,SAAS,IAAI,EAAE,QAAQ,EAAE,aAAa,kBAAkB,EAAE,IAAI,CAAC;AAAA,MACrF,GAAI,kBAAkB,SAAY,EAAE,OAAO,cAAc,IAAI,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAM9D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Q,gBAAgB;AAAA,MACrF,CAAC;AAAA,IACH;AAAA;AAAA;AAAA;AAAA,IAKA,oBAAoB;AAAA,MAClB,OAAO;AAAA,MACP,QAAQ,MAAsB;AAC5B,eAAO,sBAAsB,MAAM;AAAA,UACjC,WAAW;AAAA,UACX;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAKA,UAAU,IAAY;AACpB,aAAO,uBAAuB,IAAI,kBAAkB;AAAA,IACtD;AAAA;AAAA;AAAA;AAAA,IAKA,KAAK,IAAY,aAAiC;AAChD,aAAO,kBAAkB,IAAI;AAAA,QAC3B,UAAU,aAAa,QAAQ;AAAA,QAC/B,KAAK;AAAA,QACL;AAAA,QACA;AAAA,QACA,kBAAkB,QAAQ,iBAAiB;AAAA,QAC3C;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,MAAM,gBAAgB,QAAQ;AAC5B,YAAM,mBAAmB,QAAQ;AAAA,QAC/B;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,WAAW;AAAA,QACX;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,UAAU,QAAQ;AAAA,QAClB,WAAW,QAAQ;AAAA,QACnB,4BAA4B,QAAQ;AAAA,QACpC,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,MACtB,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["existsSync","resolve","dirname","existsSync","resolve","resolve","existsSync","resolve","existsSync","resolve","existsSync","join","resolve","existsSync","join","resolve","randomUUID","messageOf","PREFIX","randomUUID","resolve","resolve","readFileSync","resolve","resolve","readFileSync","resolve","existsSync","readFileSync","dirname","join","pathToFileURL","existsSync","readFileSync","dirname","join","join","existsSync","readFileSync","pathToFileURL","dirname","join","existsSync","pathToFileURL","existsSync","resolve","SCRIPT_TAG","existsSync","resolve","basename","resolve","existsSync","dirname"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/_internal/process-singleton.ts","../src/server/agent/provider-resolver.ts","../src/server/agent/approval-registry.ts"],"sourcesContent":["/**\n * One object per PROCESS, whatever the bundler did to the module holding it.\n *\n * ## The defect this exists to remove\n *\n * A module-level `let x` gives one instance per **module instance**, and a bundler is free to place\n * the same source in more than one chunk. When it does, each chunk gets its own `x` and any state\n * written through one is invisible through the other.\n *\n * Measured in this repository's own `dist` (usetheokit/theokit#401) by grepping the built chunks for\n * each module's marker: `provider-resolver` lands in two chunks, and `approval-registry` in two.\n * Neither copy is redundant — one of the provider chunks is tree-shaken to `resolveProvider` and\n * does not carry `resetProviderRegistry` at all, which is precisely how the halves diverge: an\n * application calling `registerProvider` — public API, with a documented self-hosting example —\n * mutated the array in one chunk while `theokit start` resolved against the array in the other.\n *\n * The second is worse in kind, because `approval-registry.ts` states the requirement in its own\n * source: *\"the approval a request awaits and the approval the route resolves MUST be the same\n * object, so a single instance per process is not a convenience but a correctness requirement.\"* A\n * chunk boundary can break that silently, and the symptom would be a HITL pause that never resumes.\n *\n * ## Why `globalThis` and not better chunking\n *\n * Chunking is a bundler heuristic that changes between versions and with the shape of the import\n * graph. A fix that depends on tsup continuing to place this module in exactly one chunk is a fix\n * that holds until someone adds an import. `Symbol.for` gives a key that is equal across every\n * module instance in the realm, so identity stops depending on the build at all.\n *\n * @internal\n */\n\n/** Namespaced so a key cannot collide with an unrelated global. */\nconst NAMESPACE = 'theokit.singleton.'\n\n/**\n * The object registered under `key`, creating it with `factory` the first time.\n *\n * `factory` runs at most once per process. A later call with the same key returns what the first\n * call built and never replaces it — replacing it is the same defect wearing a different hat, since\n * two callers would again hold different objects.\n */\nexport function processSingleton<T extends object>(key: string, factory: () => T): T {\n const slot = Symbol.for(NAMESPACE + key)\n const host = globalThis as unknown as Record<symbol, T | undefined>\n\n const existing = host[slot]\n if (existing !== undefined) return existing\n\n const created = factory()\n host[slot] = created\n return created\n}\n","import { processSingleton } from '../_internal/process-singleton.js'\n\n/**\n * Provider Resolver — Strategy + Registry pattern (FAANG-grade).\n *\n * Inspiration: Dapr Conversation Registry (`dapr/pkg/components/conversation/registry.go`)\n * + Encore Manager provider array (`encore/runtimes/go/pubsub/manager_internal.go`).\n *\n * Principle: provider routing is the FRAMEWORK's responsibility, not the consumer's — but the\n * consumer still gets to SAY which provider it wants, and it says so in the model id.\n *\n * `provider/model` is the convention every agent in this ecosystem already writes\n * (`anthropic/claude-sonnet-4-6`, `openrouter/anthropic/claude-haiku-4.5`), and it is the one the\n * SDK routes on. Until theokit#326 this resolver ignored it entirely and picked by env-var\n * priority, so an agent that declared `anthropic/...` was handed an OpenRouter key whenever one\n * happened to be present — and every turn failed with `auth_failed (HTTP 401)` against a provider\n * nobody asked for. The declared provider now wins; priority is the fallback for a bare model id.\n *\n * Wire protocol: OpenAI Chat Completions (universal — implemented by every\n * os providers: OpenRouter, Groq, Mistral, Together, Anthropic via proxy, etc).\n *\n * Resolution by priority (FIRST match wins):\n * 1. OPENROUTER_API_KEY → baseUrl=openrouter.ai (multi-model gateway)\n * 2. OPENAI_API_KEY → baseUrl=api.openai.com\n * 3. ANTHROPIC_API_KEY → direct Anthropic (Messages API, not OpenAI-compat)\n *\n * Escape hatch: an explicit `options.apiKey` OVERRIDES auto-resolution\n * (the consumer can force a specific provider if it wants to).\n */\n\n/**\n * Provider configuration descriptor — Registry entry shape.\n *\n * @public\n */\nexport interface ProviderDescriptor {\n /** Stable name used internally — not exposed on the wire. */\n name: string\n /**\n * Environment variable that holds the API key for this provider.\n *\n * **Absent means the provider needs no credential** — a model running on the developer's own\n * machine has nothing to authenticate against. Such a provider is reachable ONLY when a model id\n * names it (`ollama/llama3.2`); it never participates in the priority walk, because the walk\n * reads \"this variable is set\" as \"a human configured this provider\", and a keyless entry offers\n * no equivalent signal. Including it would route every bare model id to localhost the moment no\n * cloud key was set (usetheokit/theokit#407).\n */\n envKey?: string\n /** Base URL for the provider's OpenAI-compatible (or native) API. */\n baseUrl: string\n /**\n * Environment variable that OVERRIDES {@link baseUrl} when set.\n *\n * Scoped honestly: every caller inside this framework takes `.apiKey` from the resolved provider\n * and discards `.baseUrl` (`cli/commands/start/handlers.ts`, `vite-plugin/api-middleware.ts`,\n * `cli/commands/agent.ts`), so the endpoint a request actually reaches is chosen by the SDK, from\n * its own profile — which reads `OLLAMA_HOST` itself. This field therefore does not redirect\n * traffic today.\n *\n * It exists so that the `baseUrl` this function REPORTS agrees with where the request goes, for\n * the consumers that read it — `resolveProvider` is public API, and a reported endpoint that\n * contradicts the real one is a debugging trap rather than a harmless inaccuracy.\n */\n baseUrlEnv?: string\n /**\n * True when this provider is a GATEWAY — it serves other providers' catalogs under their own\n * model ids, reachable by prefixing its name (`openrouter/openai/gpt-4o-mini`).\n *\n * It changes nothing about resolution. It exists so the refusal below can name a model id that\n * would work instead of only the variable that is missing (#554): a scaffold shipping\n * `openai/gpt-4o-mini` and an `.env.example` asking for `OPENROUTER_API_KEY` produced an error\n * naming `OPENAI_API_KEY` — the one key the reader was never told to get — while the key they had\n * serves that exact id through the gateway.\n *\n * Deliberately NOT a licence to substitute. Every caller here takes `.apiKey` and discards\n * `.baseUrl`; the SDK picks the endpoint from the model id (measured: `openai/gpt-4o-mini` →\n * `api.openai.com`, `openrouter/openai/gpt-4o-mini` → `openrouter.ai`). Handing an OpenRouter key\n * to a request bound for OpenAI is #326 exactly, so the caller changes the id and the routing\n * follows — the framework does not change it for them.\n */\n gateway?: boolean\n /** Resolution priority (lower = higher priority). FIRST match wins. */\n priority: number\n}\n\n/**\n * Resolved provider configuration — output of `resolveProvider()`.\n *\n * @public\n */\nexport interface ResolvedProvider {\n name: string\n apiKey: string\n baseUrl: string\n}\n\n/**\n * Default provider registry. Order = priority (first = highest).\n *\n * Adding a new provider:\n * 1. Append entry below (or register via `registerProvider()`).\n * 2. Set `envKey` matching the user's env var convention.\n * 3. Set `baseUrl` to the OpenAI-compat endpoint (or native if not compat).\n * 4. Provider name used in telemetry/logs only — never wire-exposed.\n */\nconst DEFAULT_REGISTRY: ProviderDescriptor[] = [\n {\n name: 'openrouter',\n envKey: 'OPENROUTER_API_KEY',\n baseUrl: 'https://openrouter.ai/api/v1',\n gateway: true,\n priority: 1,\n },\n {\n name: 'openai',\n envKey: 'OPENAI_API_KEY',\n baseUrl: 'https://api.openai.com/v1',\n priority: 2,\n },\n {\n name: 'anthropic',\n envKey: 'ANTHROPIC_API_KEY',\n baseUrl: 'https://api.anthropic.com',\n priority: 3,\n },\n {\n // Mirrors the profile `@theokit/sdk` already ships for this provider — same default host, same\n // override variable — so the two cannot disagree about where ollama is listening. The SDK is\n // what dials it (see `baseUrlEnv`); this entry's job is to stop the resolver from rejecting the\n // model before the SDK is ever reached. No `envKey`: see that field's doc comment for why the\n // absence also keeps this entry out of the priority walk.\n name: 'ollama',\n baseUrl: 'http://localhost:11434',\n baseUrlEnv: 'OLLAMA_HOST',\n priority: 100,\n },\n]\n\n/**\n * Runtime registry — copy of DEFAULT_REGISTRY mutable via registerProvider().\n * Sorted by priority on every resolve (stable, O(n log n) — n <= ~10 providers).\n *\n * Held per PROCESS rather than per module instance (usetheokit/theokit#401). As a module-level\n * `const` it was one array per chunk, and the bundler emits this module into two of them: an\n * application calling `registerProvider` mutated one array while `theokit start` resolved against\n * another, so the call had no effect and the resulting error listed the defaults while the\n * registered provider sat in an object nobody read.\n */\nfunction registryOf(): ProviderDescriptor[] {\n return processSingleton('provider-registry', () => [...DEFAULT_REGISTRY])\n}\n\n/**\n * Providers already announced, so a boot line does not become a per-request line.\n *\n * theokit#326 — resolution was silent on success. `resolveProvider` returns `{ name, apiKey,\n * baseUrl }` and every call site consumes only the key, so an operator could only learn which\n * provider was selected from an error message: exactly when it has already failed, and never in\n * the case that hurts most — a stale key that resolves cleanly and 401s at the provider.\n */\nconst announced = new Set<string>()\n\n/** Test-only reset, so announcement state does not leak between cases. @public */\nexport function resetProviderAnnouncements(): void {\n announced.clear()\n}\n\n/** Where the announcement goes, and what it may contain. @public */\nexport interface ResolveOptions {\n /** Receives one line per provider, at most once. NEVER receives the key. */\n announce?: (line: string) => void\n /**\n * The plugins the agent declared (`compiled.plugins`), consulted for a `model-provider` one when\n * this project's registry does not know the model's prefix (#579).\n *\n * Absent ⇒ registry-only, byte-unchanged. This is what keeps `.plugins(Provider.builtins())`\n * meaning something at resolution time without making every SDK builtin nameable by every app.\n */\n plugins?: readonly unknown[]\n}\n\n/**\n * Register a new provider (Registry pattern — runtime extension point).\n * Useful for self-hosted endpoints or custom providers without touching theokit src.\n *\n * @example\n * registerProvider({\n * name: 'self-hosted',\n * envKey: 'SELF_HOSTED_API_KEY',\n * baseUrl: 'https://llm.internal.acme.com/v1',\n * priority: 0, // highest priority\n * })\n *\n * @public\n */\nexport function registerProvider(descriptor: ProviderDescriptor): void {\n // Idempotent — replace existing by name.\n const registry = registryOf()\n const idx = registry.findIndex((p) => p.name === descriptor.name)\n if (idx >= 0) registry[idx] = descriptor\n else registry.push(descriptor)\n}\n\n/**\n * Reset registry to DEFAULT_REGISTRY (test-only / dev escape hatch).\n *\n * @public\n */\nexport function resetProviderRegistry(): void {\n const registry = registryOf()\n registry.length = 0\n registry.push(...DEFAULT_REGISTRY)\n}\n\n/**\n * Get current registry snapshot (read-only — inspection).\n *\n * @public\n */\nexport function listProviders(): readonly ProviderDescriptor[] {\n return [...registryOf()].sort((a, b) => a.priority - b.priority)\n}\n\n/**\n * Says which provider was selected, once.\n *\n * Carries the provider, HOW it was chosen, and the variable the credential came from — never the\n * credential. Which env var holds it is what an operator needs to fix a mis-selection; the value\n * is what a log must never hold.\n */\nfunction announce(\n desc: ProviderDescriptor,\n how: 'declared by the model' | 'by env priority',\n options: ResolveOptions | undefined,\n): void {\n if (announced.has(desc.name)) return\n announced.add(desc.name)\n const source = desc.envKey ?? 'none (this provider takes no credential)'\n const line = `[theokit] provider=${desc.name} (${how}) source=${source} baseUrl=${baseUrlOf(desc)}`\n if (options?.announce) options.announce(line)\n // `warn` rather than `info` because the repo's lint rule allows only `warn`/`error` — and this\n // line is closer to a warning in spirit anyway: it is the one chance an operator gets to notice\n // that the provider serving their agents is not the one they expected.\n else console.warn(line)\n}\n\n/**\n * Where this provider is listening, after any environment override.\n *\n * One function so the announcement line and the resolved config can never name different hosts —\n * an operator reading a log to find out where requests went must be reading the truth.\n */\nfunction baseUrlOf(desc: ProviderDescriptor): string {\n if (desc.baseUrlEnv === undefined) return desc.baseUrl\n const override = process.env[desc.baseUrlEnv]\n return override !== undefined && override.length > 0 ? override : desc.baseUrl\n}\n\n/**\n * The provider a model id declares, or `undefined` when it declares none.\n *\n * `provider/model` and `gateway/provider/model` both resolve on the FIRST segment: a gateway is a\n * provider from the framework's point of view (it holds the credential), and everything after it\n * is the upstream namespace the gateway itself routes on.\n *\n * A bare id (`gpt-4o-mini`, `qwen2.5:3b`) declares nothing, and an unregistered prefix is treated\n * the same way rather than as an error — a project may legitimately point a custom id at a\n * registered provider's endpoint, and refusing it here would break that before it reached the SDK.\n */\nfunction providerOf(\n modelId: string | undefined,\n registered: readonly ProviderDescriptor[],\n): ProviderDescriptor | undefined {\n const prefix = declaredPrefixOf(modelId)\n if (prefix === undefined) return undefined\n return registered.find((p) => p.name === prefix)\n}\n\n/**\n * The provider name a model id declares, registered or not.\n *\n * Split out of {@link providerOf} because the two questions differ exactly where the error message\n * used to go wrong: \"which registered provider is this?\" answers `undefined` both for a bare id and\n * for `groq/…`, and the resolver needs to tell those apart to say something true about the second.\n */\nfunction declaredPrefixOf(modelId: string | undefined): string | undefined {\n if (modelId === undefined) return undefined\n const slash = modelId.indexOf('/')\n if (slash <= 0) return undefined\n return modelId.slice(0, slash)\n}\n\n/**\n * The rest of the refusal: how to reach this model with a credential that IS present.\n *\n * A credentialed gateway serves the declared provider's catalog under the same id, so prefixing it\n * turns an unreachable model into a reachable one — and that string is what the reader needs, not\n * the abstract advice to \"change the prefix\". When no gateway is credentialed the sentence stays\n * exactly as it was: naming a gateway with no key would trade one dead end for another.\n *\n * A gateway is never offered for a model already routed through one — `openrouter/openrouter/…` is\n * not a thing — which is what excluding `declared` itself accomplishes.\n */\nfunction gatewayHint(\n declared: ProviderDescriptor,\n modelId: string,\n registered: readonly ProviderDescriptor[],\n): string {\n const gateway = registered.find(\n (p) =>\n p.gateway === true &&\n p.name !== declared.name &&\n p.envKey !== undefined &&\n (process.env[p.envKey] ?? '').length > 0,\n )\n if (gateway?.envKey === undefined) return `, or change the model's provider prefix`\n return (\n `, or use \"${gateway.name}/${modelId}\" to route it through ${gateway.name} ` +\n `(${gateway.envKey} is set, and ${gateway.name} serves this model id)`\n )\n}\n\n/** A provider that authenticates — the only kind the priority walk may select. */\ntype CredentialedProvider = ProviderDescriptor & { envKey: string }\n\nfunction takesCredential(desc: ProviderDescriptor): desc is CredentialedProvider {\n return desc.envKey !== undefined\n}\n\n/**\n * Resolve the provider for a model.\n *\n * When `modelId` declares a registered provider (`anthropic/…`), THAT provider's key is\n * required — no substitution. Otherwise the registry is walked by priority, first match wins.\n *\n * @returns ResolvedProvider with apiKey + baseUrl + name\n * @throws Error if NO provider env var is set (actionable message)\n *\n * @public\n */\n/**\n * What a keyless provider reports as its key.\n *\n * This was `''` until #501, on the reasoning that an empty string is the honest value for a\n * provider that needs no credential. The reasoning was sound and the value was wrong: the SDK's\n * `createLocalAgent` calls `resolveApiKey`, which treats `''` as ABSENT, falls back to\n * `THEOKIT_API_KEY` — which nobody sets for a local model — and throws `missing_api_key` before it\n * ever looks at the provider. So #407 opened the registry door and every keyless provider,\n * including the builtin `ollama`, still could not serve a turn.\n *\n * `'local'` is the SDK's own sentinel (`LOCAL_RUNTIME_MOCK_KEY`, `internal/auth/api-key-validator`).\n * It is not a placeholder credential and does not become one: `validateApiKeyShape` short-circuits\n * on it, and `mergeExplicitApiKey` excludes it from the credential pools, so it never reaches a\n * provider as an `authorization` header. That was the objection the old comment raised against any\n * non-empty value, and it is the reason this specific value is the one that answers it — measured\n * against @theokit/sdk 4.52.1, where `apiKey: ''` throws `missing_api_key` and `apiKey: 'local'`\n * builds the agent.\n */\nconst KEYLESS_API_KEY = 'local'\n\n/**\n * The provider a MODEL-PROVIDER PLUGIN THE AGENT DECLARED serves `modelId` with (#579).\n *\n * ## Why the agent's plugins and not the SDK's catalogue\n *\n * The first version of this asked `Provider.forModel` — the SDK's global builtin lookup — and that\n * is wrong in a way the suite caught immediately: `tests/unit/unregistered-prefix-is-refused-not-\n * rerouted.test.ts` uses `openai-chatgpt/gpt-5.4` as its example of a prefix that MUST be refused\n * (#503), because a turn must never succeed against a provider nobody named. Consulting the\n * catalogue makes every one of the SDK's 44 builtins nameable by any app, whether or not it asked\n * for them — the exact permissiveness #503 exists to forbid, reintroduced one level down.\n *\n * `.plugins(Provider.builtins())` IS the app naming them. So the question is not \"does the SDK know\n * this prefix\" but \"did this agent declare a provider that serves it\", and the answer is already in\n * `compiled.plugins`, which the caller passes in. An app that declared nothing keeps getting the\n * refusal, unchanged.\n *\n * ## The shape it reads\n *\n * A `model-provider` plugin carries `profile: { name, envVars, baseUrl }`. `envVars[0]` is the\n * credential when the profile names one; naming none means the provider does not authenticate by\n * environment — Codex refreshes OAuth per request inside the profile's own `transform.fetch` — and\n * that is the keyless class `ProviderDescriptor.envKey` already describes for `ollama` (#407).\n *\n * Structural, never imported: `@theokit/sdk` is an optional peer, and this module must keep\n * resolving its own four entries without it. The plugins arrive as `unknown` and are narrowed here.\n */\nfunction declaredPluginProviderFor(\n modelId: string,\n plugins: readonly unknown[] | undefined,\n): ProviderDescriptor | undefined {\n if (plugins === undefined) return undefined\n const prefix = declaredPrefixOf(modelId)\n if (prefix === undefined) return undefined\n\n for (const plugin of plugins) {\n const profile = modelProviderProfileOf(plugin)\n if (profile === undefined) continue\n // The profile's own name, plus the aliases it declares — the SDK routes on both, and reading\n // only `name` would refuse `codex/...` for a profile that lists it as an alias of itself.\n if (profile.name !== prefix && !(profile.aliases ?? []).includes(prefix)) continue\n // `authType`, not the length of `envVars` — see the docblock above (#585).\n const needsCredential = profile.authType !== 'none' && profile.envVars.length > 0\n return {\n name: profile.name,\n ...(needsCredential ? { envKey: profile.envVars[0] } : {}),\n baseUrl: profile.baseUrl,\n // Last in the priority walk, and reachable only through the declared branch anyway: a plugin\n // provider must never win a BARE model id away from an entry this project declares.\n priority: Number.MAX_SAFE_INTEGER,\n }\n }\n return undefined\n}\n\n/** The `profile` of a value that is a model-provider plugin, or `undefined` for anything else. */\nfunction modelProviderProfileOf(plugin: unknown): ProviderProfileLike | undefined {\n if (typeof plugin !== 'object' || plugin === null) return undefined\n const candidate = plugin as { kind?: unknown; profile?: unknown }\n if (candidate.kind !== 'model-provider') return undefined\n const profile = candidate.profile\n if (typeof profile !== 'object' || profile === null) return undefined\n const shape = profile as Partial<ProviderProfileLike>\n if (typeof shape.name !== 'string' || typeof shape.baseUrl !== 'string') return undefined\n if (!Array.isArray(shape.envVars)) return undefined\n return shape as ProviderProfileLike\n}\n\n/**\n * The fields of the SDK's `ProviderProfile` this module reads.\n *\n * Structural rather than imported: importing the SDK's type would make an optional peer a\n * build-time dependency of a module that must work without it.\n */\ninterface ProviderProfileLike {\n name: string\n envVars: readonly string[]\n baseUrl: string\n aliases?: readonly string[]\n /**\n * How the provider authenticates. `'none'` means it does not, whatever `envVars` names (#585).\n *\n * Optional here although the SDK's own type requires it: this module narrows a plugin from\n * `unknown`, so a value arriving without the field is representable and must not be assumed.\n */\n authType?: string\n}\n\nexport function resolveProvider(modelId?: string, options?: ResolveOptions): ResolvedProvider {\n const sorted = [...registryOf()].sort((a, b) => a.priority - b.priority)\n\n // The local registry first, the SDK's builtins as the fallback for a prefix it does not know.\n const declared =\n modelId === undefined\n ? undefined\n : (providerOf(modelId, sorted) ?? declaredPluginProviderFor(modelId, options?.plugins))\n if (declared !== undefined && modelId !== undefined) {\n if (declared.envKey === undefined) {\n announce(declared, 'declared by the model', options)\n return { name: declared.name, apiKey: KEYLESS_API_KEY, baseUrl: baseUrlOf(declared) }\n }\n const apiKey = process.env[declared.envKey]\n if (apiKey && apiKey.length > 0) {\n announce(declared, 'declared by the model', options)\n return { name: declared.name, apiKey, baseUrl: baseUrlOf(declared) }\n }\n // Deliberately NOT falling back to another provider's key. Silently substituting one is how\n // theokit#326 produced a 401 nobody could attribute: the request went somewhere the agent\n // never named. Say which variable is missing and stop.\n //\n // #554 — but say it usefully. \"change the model's provider prefix\" is true and unactionable:\n // it does not say which prefix, and the reader may already hold a key that serves this model.\n throw new Error(\n `Model \"${modelId}\" declares provider \"${declared.name}\", but ${declared.envKey} is not set. ` +\n `Set ${declared.envKey}${gatewayHint(declared, modelId, sorted)}.`,\n )\n }\n\n // A prefix the registry does not know is a CHOICE, not a silence — refuse before the walk.\n //\n // `providerOf` returns `undefined` for an unregistered prefix, which is indistinguishable from a\n // bare model id, so the priority walk below used to claim the turn and the \"not registered\" error\n // further down became unreachable for anyone holding a key. The visible cost was a confusing\n // message; the real one was a turn that SUCCEEDED against a provider nobody named — different\n // endpoint, different account billed, prompt delivered to a vendor the operator had routed away\n // from, announced only by a `console.warn` that fires once per process (#503).\n //\n // #326 settled the principle for a registered provider: declared wins, priority is the fallback\n // for a bare model id. This extends it to the case #326 did not reach — an unregistered prefix is\n // not a bare model id either.\n const unregisteredPrefix = declared === undefined ? declaredPrefixOf(modelId) : undefined\n if (unregisteredPrefix !== undefined) {\n throw new Error(\n `Model \"${String(modelId)}\" declares provider \"${unregisteredPrefix}\", which is not registered. ` +\n `Registered providers: ${sorted.map((p) => p.name).join(', ')}. ` +\n `Register it with registerProvider({ name: '${unregisteredPrefix}', … }), or use a registered prefix.`,\n )\n }\n\n // Only providers that take a credential. A keyless entry is reachable exclusively through the\n // declared branch above; see `ProviderDescriptor.envKey` for why the walk cannot include it.\n const credentialed = sorted.filter(takesCredential)\n\n for (const desc of credentialed) {\n const apiKey = process.env[desc.envKey]\n if (apiKey && apiKey.length > 0) {\n announce(desc, 'by env priority', options)\n return {\n name: desc.name,\n apiKey,\n baseUrl: baseUrlOf(desc),\n }\n }\n }\n\n // Nothing resolved, and the model id declared nothing — the unregistered-prefix case was refused\n // above the walk, which is where it belongs (#503). This message is for the bare-id case only.\n //\n // It used to live here and it was the right message in the wrong place: reachable exactly when\n // the operator had no keys at all, which is the case that needed it least (usetheokit/theokit#407\n // is why the message exists; #503 is why it moved).\n const envKeys = credentialed.map((p) => p.envKey).join(' OR ')\n throw new Error(\n `No LLM provider API key found in environment. Set one of: ${envKeys}. ` +\n `Get a free OpenRouter key at https://openrouter.ai/keys (recommended — one key, many models).`,\n )\n}\n\n/**\n * Try to resolve — does NOT throw. Returns null if no provider available.\n * Useful for graceful degradation (e.g., mock mode).\n *\n * @public\n */\nexport function tryResolveProvider(modelId?: string): ResolvedProvider | null {\n try {\n return resolveProvider(modelId)\n } catch {\n return null\n }\n}\n","/**\n * M4 (theokit-ai-first) — the in-process HITL approval registry.\n *\n * The HITL plugin's `awaitApproval` calls `register(approvalId)` and awaits the returned Promise\n * (this is what genuinely PAUSES the SDK run — the SDK `pre_tool_call` hook is awaited). The\n * approve route calls `resolve(approvalId, approved)` to settle it. A per-approval timeout settles\n * the Promise deterministically per the `@HumanInTheLoop` `onTimeout` policy so a hung approval\n * never leaks the paused stream.\n *\n * Single-process contract (ADR 0017 / plan Drawback 2): a multi-instance deploy needs a shared\n * registry — the interface is injectable so a durable impl (Redis, etc.) slots in without touching\n * the harness. We do NOT build a durable store now (YAGNI).\n */\n// The timeout policy vocabulary is owned by the `@HumanInTheLoop` decorator (DRY / G12) — reuse it\n// rather than re-declaring the union, so the two can never drift.\nimport type { TimeoutAction } from '@theokit/agents'\n\nimport { processSingleton } from '../_internal/process-singleton.js'\n\nexport interface RegisterOptions {\n /** Milliseconds before the approval auto-settles per `onTimeout`. */\n timeoutMs: number\n /**\n * What a timeout means. Only `'proceed'` auto-approves; `'abort'` and `'retry'` both deny — the\n * registry does NOT implement retry semantics (a timed-out `'retry'` is a deny, not a re-prompt).\n */\n onTimeout: TimeoutAction\n /** M14 — the gated tool name, surfaced by `list()` (optional; absent for legacy callers). */\n toolName?: string\n /** M14 — the approval question, surfaced by `list()` (optional). */\n question?: string\n /**\n * Who the run belongs to — the `RouteSubject.id` admitted for it (B-016).\n *\n * Absent when the run had no identity to record, which is the `'public'` agent path:\n * `admitAgentRequest` deliberately does not resolve a subject when the policy is absent or\n * `'public'`, so there is nothing to attribute the approval to. Absent therefore means \"no owner\n * was established\", never \"anyone\", and the caller must branch on the difference — a rule that\n * refused when it is absent would start turning public agents away.\n *\n * Deliberately NOT surfaced by `list()`: that listing feeds a UI, and owner ids are identity.\n */\n owner?: string\n /**\n * M20 — an optional JSON-schema descriptor of the custom payload the approver may attach. Carried\n * verbatim into `list()` + the `approval_required` event so the UI knows what to collect. Kept as\n * a plain JSON object (not a live Zod schema) so the registry stays serializable and SDK-free.\n */\n payloadSchema?: Record<string, unknown>\n}\n\n/**\n * M20 — a settled HITL decision. `approved` is the allow/deny bit (backward-compatible with the\n * legacy boolean); `reason` + `payload` are the optional approver-attached extras that surface to\n * the model (on denial, via the veto message) and to the app/UI.\n */\nexport interface ApprovalDecision {\n approved: boolean\n reason?: string\n payload?: unknown\n /**\n * What settled this, when it was not a person (usetheokit/theokit#393).\n *\n * Absent means the decision arrived through `resolve()` — a human, or whatever the application\n * wired to that route. `'timeout'` means the window closed with nobody deciding and `onTimeout`\n * was applied.\n *\n * The distinction is the whole point of a HITL gate: without it an expired approval and an\n * explicit deny are byte-identical on the wire, and the sentence the caller gets — \"denied by\n * human approver\" — asserts a fact that did not happen. It is marked on the ALLOW side too:\n * `onTimeout: 'proceed'` permits the tool BECAUSE nobody answered, and recording that as a plain\n * approval is the same fabrication with the opposite sign.\n *\n * One member rather than `timedOut: boolean`, because the question is what settled it; a second\n * cause (a cancel, a shutdown) joins the union instead of adding another boolean.\n */\n settledBy?: 'timeout'\n}\n\n/** M14 — a pending approval as surfaced by {@link ApprovalRegistry.list}. */\nexport interface PendingApproval {\n approvalId: string\n toolName?: string\n question?: string\n /** Epoch millis when the pending approval auto-settles (registeredAt + timeoutMs). */\n expiresAt: number\n /** M20 — the declared custom-payload schema, if the gated tool declares one. */\n payloadSchema?: Record<string, unknown>\n}\n\nexport interface ApprovalRegistry {\n /**\n * Register a pending approval; the returned Promise settles with the full {@link ApprovalDecision}\n * on `resolve` or timeout (M20 — was a bare boolean pre-M20).\n */\n register(approvalId: string, opts: RegisterOptions): Promise<ApprovalDecision>\n /**\n * Settle a pending approval. Accepts a full {@link ApprovalDecision} OR a bare boolean (coerced to\n * `{ approved }` — backward-compatible). Returns false if the id is unknown or already settled.\n */\n resolve(approvalId: string, decision: boolean | ApprovalDecision): boolean\n /** M14 — list the currently-pending approvals (process-wide; single-process contract). */\n list(): PendingApproval[]\n /**\n * Who owns the pending approval `approvalId`, or `undefined` (B-016).\n *\n * `undefined` covers three cases the caller treats identically — never registered, already\n * settled, and registered without an owner — because in all three there is nothing to compare a\n * caller against.\n */\n ownerOf(approvalId: string): string | undefined\n /**\n * How far this registry's answers reach — B-236.\n *\n * `'instance'` means every answer is about ONE process. `getApprovalRegistry()` resolves a\n * `processSingleton`, and every deploy target the approvals listing became reachable on is\n * multi-instance by construction: a Worker is isolates, a Lambda is concurrent invocations. So\n * an owner whose run paused on another instance was answered `200 {approvals: []}`, which is\n * indistinguishable from \"nothing is pending\".\n *\n * It is declared HERE rather than assumed by the listing handler because the interface is\n * injectable so a durable implementation can replace this one. A constant in the handler would\n * become false the day somebody wires that up, which is this defect one layer higher.\n *\n * Optional, and an implementation that declares nothing is read as `'instance'`. Silence takes\n * the narrow claim: a registry that cannot say how far it reaches must not be reported as\n * speaking for a deployment.\n */\n readonly scope?: ApprovalRegistryScope\n}\n\n/**\n * How far a registry's answers reach.\n *\n * `'shared'` is declared by an implementation backed by a store every instance reads — nothing in\n * this framework ships one today (YAGNI), and the value exists so that wiring one does not mean\n * editing the listing handler.\n */\nexport type ApprovalRegistryScope = 'instance' | 'shared'\n\ninterface Pending {\n settle: (decision: ApprovalDecision) => void\n timer: ReturnType<typeof setTimeout>\n info: PendingApproval\n /** Held beside `info` rather than inside it, so `list()` cannot leak it (B-016). */\n owner?: string\n}\n\n/**\n * The one process-wide registry the stream mount (`mountAgent`) and the approve route share.\n *\n * The in-process impl holds LIVE Promise resolvers in memory — the approval a request awaits and\n * the approval the route resolves MUST be the same object, so a single instance per process is not\n * a convenience but a correctness requirement. Lazily created; a durable/multi-instance deploy\n * swaps this accessor for a shared-store impl (ADR 0017 / plan Drawback 2) without touching callers.\n * Tests use {@link createInProcessApprovalRegistry} directly — never this singleton.\n */\nexport function getApprovalRegistry(): ApprovalRegistry {\n // Per PROCESS, not per module instance (usetheokit/theokit#401). The paragraph above calls a\n // single instance \"not a convenience but a correctness requirement\", and a module-level `let`\n // does not deliver that: it gives one instance per MODULE INSTANCE, and this module is emitted\n // into two chunks of the published bundle. A run awaiting an approval and the route resolving it\n // could hold different objects, and the symptom would be a HITL pause that never resumes.\n return processSingleton('approval-registry', () => createInProcessApprovalRegistry())\n}\n\nexport function createInProcessApprovalRegistry(): ApprovalRegistry {\n const pending = new Map<string, Pending>()\n\n return {\n // B-236 — stated rather than left for a caller to infer from the name. This map is one\n // process's, so every answer built from it is one process's.\n scope: 'instance',\n register(approvalId, opts) {\n return new Promise<ApprovalDecision>((resolve) => {\n const settle = (decision: ApprovalDecision): void => {\n const entry = pending.get(approvalId)\n if (!entry) return\n clearTimeout(entry.timer)\n pending.delete(approvalId)\n resolve(decision)\n }\n // 'proceed' → allow on timeout; 'abort'/'retry' → deny on timeout.\n const timer = setTimeout(() => {\n settle({\n approved: opts.onTimeout === 'proceed',\n settledBy: 'timeout',\n // Every value in this sentence was already here and none of it used to survive the\n // settle. `onTimeout` is named because all three of its values reach this line and two\n // of them deny — an operator who wrote `'retry'` and got a denial had nothing to read\n // that mentioned retry.\n reason: `no decision within ${String(opts.timeoutMs)} ms; onTimeout: '${opts.onTimeout}' was applied`,\n })\n }, opts.timeoutMs)\n const info: PendingApproval = {\n approvalId,\n toolName: opts.toolName,\n question: opts.question,\n expiresAt: Date.now() + opts.timeoutMs,\n ...(opts.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n }\n pending.set(approvalId, {\n settle,\n timer,\n info,\n ...(opts.owner !== undefined ? { owner: opts.owner } : {}),\n })\n })\n },\n resolve(approvalId, decision) {\n const entry = pending.get(approvalId)\n if (!entry) return false\n // M20 — coerce the legacy bare-boolean form to a decision object.\n entry.settle(typeof decision === 'boolean' ? { approved: decision } : decision)\n return true\n },\n list() {\n return [...pending.values()].map((p) => p.info)\n },\n ownerOf(approvalId) {\n // `settle` deletes the entry, so an approval that has been answered or timed out reports no\n // owner — which is what stops a later registration of the same id from inheriting one.\n return pending.get(approvalId)?.owner\n },\n }\n}\n"],"mappings":";;;;AAgCA,IAAM,YAAY;AASX,SAAS,iBAAmC,KAAa,SAAqB;AACnF,QAAM,OAAO,uBAAO,IAAI,YAAY,GAAG;AACvC,QAAM,OAAO;AAEb,QAAM,WAAW,KAAK,IAAI;AAC1B,MAAI,aAAa,OAAW,QAAO;AAEnC,QAAM,UAAU,QAAQ;AACxB,OAAK,IAAI,IAAI;AACb,SAAO;AACT;;;ACuDA,IAAM,mBAAyC;AAAA,EAC7C;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,SAAS;AAAA,IACT,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,UAAU;AAAA,EACZ;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAME,MAAM;AAAA,IACN,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,UAAU;AAAA,EACZ;AACF;AAYA,SAAS,aAAmC;AAC1C,SAAO,iBAAi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CAAC,GAAG,QAAQ,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,IAChD;AAAA,IACA,QAAQ,YAAY;AAGlB,aAAO,QAAQ,IAAI,UAAU,GAAG;AAAA,IAClC;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/storage/storage-manager.ts","../src/server/storage/use-unstorage.ts","../src/server/storage/use-database.ts"],"mappings":";AAiCO,IAAM,iBAAN,MAAqB;AAAA,EAC1B;AAAA,EACS,WAAW,oBAAI,IAAsB;AAAA,EACrC,gBAAgB,oBAAI,IAAuB;AAAA,EAC3C,kBAAkB,oBAAI,IAAqB;AAAA,EAC3C,YAAY,oBAAI,IAAoB;AAAA,EAC7C,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA,EAMZ,UAAU,QAA6B;AACrC,QAAI,KAAK,YAAY,QAAW;AAC9B,cAAQ,KAAK,+EAA+E;AAC5F;AAAA,IACF;AACA,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsBA,WAAc,MAAc,SAAqB;AAC/C,QAAI,KAAK,UAAW,OAAM,IAAI,MAAM,4BAA4B;AAChE,QAAI,KAAK,gBAAgB,IAAI,IAAI,EAAG,QAAO,KAAK,gBAAgB,IAAI,IAAI;AACxE,UAAM,SAAS,QAAQ;AACvB,SAAK,gBAAgB,IAAI,MAAM,MAAM;AACrC,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,YAAY,QAAgB,SAAoC;AAC9D,QAAI,KAAK,UAAW,OAAM,IAAI,MAAM,4BAA4B;AAChE,UAAM,SAAS,KAAK,SAAS,IAAI,MAAM;AACvC,QAAI,WAAW,OAAW,QAAO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ers.ts","../src/server/transformer.ts","../src/vite-plugin/hoist-head-tags.ts","../src/vite-plugin/ssr-dev-middleware.ts","../src/server/agent/agent-card-handler.ts","../src/server/agent/approve-agent.ts","../src/server/agent/handle-agent-run-reconnect.ts","../src/server/agent/thread-dispatcher.ts","../src/server/agent/thread-run-registry.ts","../src/server/agent/handle-thread-routes.ts","../src/server/agent/list-approvals-handler.ts","../src/server/agent/serve-aux-routes.ts","../src/server/http/plugin-lifecycle.ts","../src/server/http/resolve-agent-subject.ts"],"sourcesContent":["/**\n * Turn `config.plugins` entries that are module SPECIFIERS into plugins (usetheokit/theokit#425).\n *\n * ## Why the field grew a second shape\n *\n * `config.plugins` holds constructed objects, and a generated deploy entry cannot carry a closure:\n * there is no literal for one. So on all six Web-standards targets the entry built its request\n * context with no runner and every lifecycle hook was dead on a deployed app while firing locally.\n *\n * Two ways out were weighed:\n *\n * - **Bundle `theo.config.ts` into the entry.** Rejected on measurement. It silently drops\n * `theo.config.<NODE_ENV>.ts`, which `loadConfig` merges (`config/load-config.ts:92`) — a new\n * silent drop, which is the exact class of defect this work exists to remove. And it pulls every\n * module the config imports (database drivers, build-only helpers) into a Worker bundle that\n * builds today, so the common case would pay for the rare one.\n * - **Name the module.** A string entry says which module the plugin comes from, so the build emits\n * a static import for that module and nothing else. One declaration serves the local server and\n * the deployed entry, which is what keeps them from disagreeing.\n *\n * The second is what this implements. It is ADDITIVE: an app passing constructed objects is\n * untouched, and gets the same treatment it always got.\n *\n * ## Why this lives in `config/` and not beside `createPluginRunnerFromConfig`\n *\n * Resolving a specifier means importing a path, and that means `node:url`/`node:path`. `server/`\n * holds a no-`node:*` invariant so the same code serves the Web, Tauri and TUI targets\n * (`docs/program/three-target-parity.md`). `config/` already reads the filesystem — `load-config.ts` is\n * the module that finds `theo.config.ts` at all — and it is the one place BOTH local entry points\n * (`theokit start` and the Vite dev server) already import from. So the specifier is resolved\n * where the config is read, and `createPluginRunnerFromConfig` keeps taking what it always took:\n * objects.\n */\nimport { isAbsolute, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\n/**\n * A declared plugin module that could not be turned into a plugin.\n *\n * Its own error type because the alternative — skipping the entry — leaves an app running with one\n * fewer plugin than it declared and nothing saying so. That is the failure this issue is about,\n * reproduced at the door.\n */\nexport class UnresolvablePluginSpecifierError extends Error {\n constructor(index: number, specifier: string, reason: string) {\n super(`plugins[${index}] (${specifier}) could not be loaded: ${reason}`)\n this.name = 'UnresolvablePluginSpecifierError'\n }\n}\n\n/**\n * Resolve every string entry in `plugins` to the module's default export, in order.\n *\n * @param plugins - the raw `config.plugins` array: constructed plugins, module specifiers, or both.\n * @param cwd - the project root a relative specifier is resolved against.\n */\nexport async function resolvePluginSpecifiers(\n plugins: readonly unknown[],\n cwd: string,\n): Promise<unknown[]> {\n const resolved: unknown[] = []\n // Sequential on purpose. Plugin order is hook order, and resolving concurrently then collecting\n // as each settles would reorder an app's lifecycle by module size.\n for (const [index, entry] of plugins.entries()) {\n resolved.push(typeof entry === 'string' ? await importPlugin(entry, index, cwd) : entry)\n }\n return resolved\n}\n\nasync function importPlugin(specifier: string, index: number, cwd: string): Promise<unknown> {\n const target = isAbsolute(specifier) ? specifier : resolve(cwd, specifier)\n let mod: { default?: unknown }\n try {\n mod = (await import(/* @vite-ignore */ pathToFileURL(target).href)) as { default?: unknown }\n } catch (err) {\n throw new UnresolvablePluginSpecifierError(index, specifier, messageOf(err))\n }\n if (mod.default === undefined) {\n // Registering `undefined` would fail later inside `createPluginRunnerFromConfig` with an error\n // naming a shape rather than a file, which is the harder half of the diagnosis.\n throw new UnresolvablePluginSpecifierError(\n index,\n specifier,\n 'the module has no default export; a plugin module must `export default` its plugin',\n )\n }\n return mod.default\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","import superjson from 'superjson'\n\n/**\n * T5.2 — pluggable response/request transformer.\n *\n * `superjson` is the default, preserving Date/Map/Set/BigInt/etc.\n * `json` is the lightweight option (plain JSON.stringify/parse).\n * Users can supply a custom object implementing this contract.\n */\nexport interface TheoTransformer {\n name: string\n serialize: (value: unknown) => string\n deserialize: (raw: string) => unknown\n}\n\nexport const superjsonTransformer: TheoTransformer = {\n name: 'superjson',\n serialize: (v) => JSON.stringify(superjson.serialize(v)),\n deserialize: (raw) => {\n const parsed = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(parsed)\n },\n}\n\nexport const jsonTransformer: TheoTransformer = {\n name: 'json',\n serialize: (v) => JSON.stringify(v),\n deserialize: (raw) => JSON.parse(raw) as unknown,\n}\n\nconst BUILT_INS: Record<string, TheoTransformer> = {\n superjson: superjsonTransformer,\n json: jsonTransformer,\n}\n\nexport function resolveTransformer(\n selector: 'json' | 'superjson' | TheoTransformer,\n): TheoTransformer {\n if (typeof selector === 'string') {\n // selector is 'json' | 'superjson' literal — both keys exist in\n // BUILT_INS by construction. Type system guarantees a hit; we keep\n // a defensive fallback that the compiler cannot see is unreachable\n // at runtime, just in case someone adds a new literal to the union\n // but forgets to register the built-in.\n const built = BUILT_INS[selector]\n // Defensive: the public union ensures `built` is defined, but if a\n // future contributor extends the union without registering the impl,\n // the cast keeps the failure mode loud.\n if ((built as TheoTransformer | undefined) === undefined) {\n throw new Error(\n `Unknown transformer \"${selector}\". Built-in options: ${Object.keys(BUILT_INS).join(', ')}.`,\n )\n }\n return built\n }\n if (\n typeof selector !== 'object' ||\n typeof selector.serialize !== 'function' ||\n typeof selector.deserialize !== 'function'\n ) {\n throw new Error(\n `Custom transformer must have serialize and deserialize functions. Got: ${JSON.stringify(selector)}`,\n )\n }\n return selector\n}\n","/**\n * Moves the document metadata a route rendered into the `<head>` where it belongs.\n *\n * ## Why this exists\n *\n * React 19 hoists `<title>`, `<meta>` and `<link>` into the head — **in the browser**, by moving\n * DOM nodes after hydration. On the server it emits them inline, wherever the component sat, and\n * the SSR output is injected inside `<div id=\"root\">`. So a route's own metadata ships in the\n * BODY.\n *\n * For a reader that changes nothing: hydration moves the tags a moment later. For a crawler it\n * changes everything, because the ones that matter never run JavaScript. Every social unfurler —\n * X, LinkedIn, Slack, Discord, WhatsApp — reads the served `<head>` and stops. Without this, every\n * page of a site unfurls with whatever static fallback `index.html` happens to carry: share ten\n * different documentation pages, get ten identical cards.\n *\n * Turning SSR on to fix social previews and finding they still do not work is a bad afternoon, so\n * the framework does the hoist itself (usetheokit/theokit#319).\n *\n * ## Precedence\n *\n * The route wins over the template. `index.html` holds site-wide defaults; a page that states its\n * own title, description or canonical is being specific on purpose, and shipping both would leave\n * the crawler to pick — in practice the first one, which is the generic one.\n */\n\n/**\n * Tags React hoists, and therefore the ones worth moving.\n *\n * Two separate patterns rather than one with an alternation: a single expression covering both the\n * self-closing tags and the `<title>…</title>` pair needs a lazy `[\\s\\S]*?` next to a lazy\n * `[^>]*?`, and that nests two unbounded quantifiers — catastrophic backtracking on hostile input,\n * which here is a served HTML document. Each pattern below is linear: `[^>]` and `[^<]` cannot\n * cross the delimiter that ends the match.\n */\nconst VOID_METADATA = /<(?:meta|link)\\b[^>]*>/gi\n/** `<title>` content is text, so it cannot contain `<` — the class is what keeps this linear. */\nconst TITLE_TAG = /<title\\b[^>]*>[^<]*<\\/title>/gi\n\n/** Runs `replacer` over every hoistable tag, in document order. */\nfunction replaceHoistable(html: string, replacer: (tag: string) => string): string {\n return html.replace(TITLE_TAG, replacer).replace(VOID_METADATA, replacer)\n}\n\n/**\n * The identity of a metadata tag, used to decide what the route replaces.\n *\n * `<meta name=\"description\">` and `<meta property=\"og:title\">` are distinct slots; two `<meta>`\n * tags with different names are not duplicates. A `<link>` is keyed by `rel`, so a route's\n * canonical replaces the template's while a stylesheet link is left alone.\n *\n * Anything unkeyed (a `<link rel=\"preconnect\">`, say) returns `undefined` and is simply appended —\n * additive tags must not evict each other.\n */\nexport function metadataKey(tag: string): string | undefined {\n if (/^<title\\b/i.test(tag)) return 'title'\n\n const name = /\\bname=[\"']([^\"']+)[\"']/i.exec(tag)?.[1]\n const property = /\\bproperty=[\"']([^\"']+)[\"']/i.exec(tag)?.[1]\n const rel = /\\brel=[\"']([^\"']+)[\"']/i.exec(tag)?.[1]\n\n if (/^<meta\\b/i.test(tag)) {\n if (property !== undefined) return `property:${property.toLowerCase()}`\n if (name !== undefined) return `name:${name.toLowerCase()}`\n return undefined\n }\n\n if (/^<link\\b/i.test(tag) && rel !== undefined) {\n const slug = rel.toLowerCase()\n // Only single-valued rels are slots. `stylesheet`, `preload` and friends are additive: keying\n // them would let one page's stylesheet evict another's.\n return slug === 'canonical' || slug === 'manifest' ? `link:${slug}` : undefined\n }\n\n return undefined\n}\n\nexport interface HoistedHead {\n /** The rendered HTML with its metadata tags removed. */\n html: string\n /** Those tags, ready to be placed in the head. */\n headTags: string[]\n}\n\n/** Pulls hoistable metadata out of rendered SSR markup. */\nexport function extractHeadTags(ssrHtml: string): HoistedHead {\n const headTags: string[] = []\n const html = replaceHoistable(ssrHtml, (tag) => {\n headTags.push(tag)\n return ''\n })\n return { html, headTags }\n}\n\n/**\n * Inserts `headTags` into the template's head, dropping any template tag the route supersedes.\n *\n * Returns the template untouched when there is nothing to hoist or no `</head>` to hoist into —\n * a missing head is a malformed template, and rewriting it further would not help anyone.\n */\nexport function injectIntoHead(template: string, headTags: string[]): string {\n if (headTags.length === 0) return template\n\n const closingHead = template.toLowerCase().lastIndexOf('</head>')\n if (closingHead === -1) return template\n\n const supersededKeys = new Set(\n headTags.map((tag) => metadataKey(tag)).filter((key): key is string => key !== undefined),\n )\n\n let head = template.slice(0, closingHead)\n if (supersededKeys.size > 0) {\n head = replaceHoistable(head, (tag) => {\n const key = metadataKey(tag)\n return key !== undefined && supersededKeys.has(key) ? '' : tag\n })\n }\n\n return `${head} ${headTags.join('\\n ')}\\n ${template.slice(closingHead)}`\n}\n\n/**\n * The whole operation: strip metadata from the rendered markup and place it in the template's head.\n */\nexport function hoistHeadTags(\n template: string,\n ssrHtml: string,\n): { template: string; html: string } {\n const { html, headTags } = extractHeadTags(ssrHtml)\n const hoisted = injectIntoHead(template, headTags)\n\n // Fail SAFE, not silent. `injectIntoHead` returns the template untouched when it finds no\n // `</head>` — and if we returned the stripped body alongside it, the metadata would be removed\n // from one place and added to neither. It would vanish, with nothing to show for it.\n //\n // That is not hypothetical: a template whose COMMENT mentioned `<div id=\"root\">` split at the\n // comment, leaving a \"head\" half with no `</head>` in it, and every route silently lost its\n // title and canonical. Metadata in the wrong place still works after hydration; metadata that is\n // gone never comes back.\n if (hoisted === template) return { template, html: ssrHtml }\n\n return { template: hoisted, html }\n}\n","/**\n * T2.2 (architecture-medium-deferrals plan, ADR D2) — SSR dev middleware\n * extracted from `vite-plugin/index.ts` for SRP.\n *\n * `setupSsrDevMiddleware(server, opts)` registers a Connect-style middleware\n * on the Vite dev server that:\n * 1. Skips API, static, and HMR requests (let other middlewares handle).\n * 2. Reads `index.html`, runs `transformIndexHtml`.\n * 3. Generates per-request nonce, applies security headers (CSP + Cache-Control).\n * 4. Calls `ssrLoadModule(VIRTUAL_ENTRY_SERVER_ID).render(url, { nonce })`.\n * 5. Injects rendered HTML (with hydration script) into root div.\n * 6. On error: ssrFixStacktrace + fallback to CSR via `next()`.\n *\n * No-op when `ssrEnabled === false`. Caller's responsibility to gate.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { ViteDevServer } from 'vite'\n\nimport { findRootDiv } from '../core/contracts/find-root-div.js'\nimport {\n applySecurityHeaders,\n generateNonce,\n type SecurityHeadersConfig,\n} from '../server/internal-api.js'\n\nimport { hoistHeadTags } from './hoist-head-tags.js'\n\ninterface SsrRenderResult {\n html: string\n hydrationData: {\n loaderData?: unknown\n actionData?: unknown\n errors?: unknown\n }\n}\n\ninterface SsrEntryServer {\n render: (\n url: string,\n opts: { nonce: string },\n ) => Promise<SsrRenderResult | { redirect: Response } | string>\n}\n\n/**\n * Stamps the request nonce onto every inline `<script>` the HTML already carries.\n *\n * `transformIndexHtml` lets Vite plugins inject their own scripts, and they know nothing about our\n * CSP. `@vitejs/plugin-react` injects its refresh preamble as an INLINE module script with no\n * nonce, so a nonce-based `script-src` blocks it, `window.$RefreshReg$` is never defined, and the\n * first component module throws \"@vitejs/plugin-react can't detect preamble\". SSR still produced\n * the HTML, so the page looks fine and simply never hydrates — nothing interactive works, and the\n * one console error points at Vite rather than at us (usetheokit/theokit#319).\n *\n * Only scripts WITHOUT `src` are stamped: a same-origin `src` is already covered by `'self'`, and\n * an inline script is the only kind a nonce is needed for. Scripts that already carry a nonce are\n * left alone, so the render's own output is never rewritten.\n *\n * Deliberately not a general HTML parser: this runs per request in dev, on markup we produced or a\n * Vite plugin injected, and the pattern only ever matches an opening `<script>` tag.\n */\nexport function applyNonceToInlineScripts(html: string, nonce: string): string {\n return html.replace(\n /<script(?![^>]*\\ssrc=)(?![^>]*\\snonce=)([^>]*)>/gi,\n `<script nonce=\"${nonce}\"$1>`,\n )\n}\n\nfunction isSsrRenderResult(value: unknown): value is SsrRenderResult {\n if (typeof value !== 'object' || value === null) return false\n if (!('html' in value)) return false\n return typeof (value as Record<string, unknown>).html === 'string'\n}\n\ninterface SsrDevMiddlewareOptions {\n projectRoot: string\n virtualEntryServerId: string\n securityHeaders: SecurityHeadersConfig | undefined\n}\n\n/**\n * Attach the SSR dev middleware to a Vite dev server. Caller decides whether\n * to invoke this based on `ssrEnabled` — this function does not gate.\n */\nexport function setupSsrDevMiddleware(server: ViteDevServer, opts: SsrDevMiddlewareOptions): void {\n server.middlewares.use((req, res, next) => {\n void (async () => {\n const url = req.url ?? '/'\n // Skip API, static, and HMR requests\n if (\n url.startsWith('/api/') ||\n url.startsWith('/@') ||\n url.startsWith('/node_modules/') ||\n url.includes('.')\n ) {\n next()\n return\n }\n\n try {\n const indexPath = resolve(opts.projectRoot, 'index.html')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- projectRoot is from `theokit dev`'s caller-controlled cwd\n let template = readFileSync(indexPath, 'utf-8')\n\n // T4.1 — Generate a per-request nonce and apply security headers BEFORE render.\n // The same nonce flows into React's renderToPipeableStream({ nonce }) so every\n // emitted <script> carries it AND into the CSP script-src directive.\n // EC-3: applySecurityHeaders also forces Cache-Control: private, no-store.\n //\n // The nonce is minted BEFORE `transformIndexHtml` so the scripts Vite plugins inject can be\n // stamped with it. Minting it afterwards left the React refresh preamble unnonced, the CSP\n // blocked it, and the app never hydrated (usetheokit/theokit#319).\n const nonce = generateNonce()\n\n template = await server.transformIndexHtml(url, template)\n template = applyNonceToInlineScripts(template, nonce)\n applySecurityHeaders(\n res,\n opts.securityHeaders ?? {},\n { production: process.env.NODE_ENV === 'production' },\n { nonce },\n )\n\n const mod = (await server.ssrLoadModule(opts.virtualEntryServerId)) as SsrEntryServer\n const result = await mod.render(url, { nonce })\n\n if (result && typeof result === 'object' && 'redirect' in result) {\n res.writeHead(302, {\n Location: result.redirect.headers.get('location') ?? '/',\n })\n res.end()\n return\n }\n\n // Backward-compat: old render returned string. New shape returns\n // { html, hydrationData } so the framework can emit the hydration\n // data script OUTSIDE the React root (fixes hydration mismatch).\n let ssrHtml: string\n let hydrationScript = ''\n if (typeof result === 'string') {\n ssrHtml = result\n } else if (isSsrRenderResult(result)) {\n ssrHtml = result.html\n const dataJson = JSON.stringify(result.hydrationData).replace(/</g, '\\\\u003c')\n hydrationScript = `<script nonce=\"${nonce}\">window.__staticRouterHydrationData=${dataJson}</script>`\n } else {\n ssrHtml = ''\n }\n // Move the route's <title>/<meta>/<link> out of the rendered body and into the head.\n // React only hoists those in the browser, after hydration — a crawler that does not run JS\n // would otherwise never see a page's own title or social card (usetheokit/theokit#319).\n const hoisted = hoistHeadTags(template, ssrHtml)\n template = hoisted.template\n ssrHtml = hoisted.html\n\n const rootDiv = findRootDiv(template)\n if (!rootDiv) {\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(template)\n return\n }\n\n const splitIdx = rootDiv.insertAt\n const html =\n template.slice(0, splitIdx) + ssrHtml + hydrationScript + template.slice(splitIdx)\n\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(html)\n } catch (err) {\n server.ssrFixStacktrace(err as Error)\n console.error('[SSR Dev Error]', err)\n // Fallback to CSR\n next()\n return\n }\n })()\n })\n}\n","/**\n * M15 (theokit-ai-first) — serve the A2A agent card at `/.well-known/<name>/agent-card.json`.\n *\n * `buildAgentCard` (@theokit/agents) is the pure generator; this handler compiles a loaded agent\n * module to its tools + streaming capability, builds the card, and returns it as a Web-Standard\n * JSON `Response` (G8). The dev middleware + prod handler branch to this before the agent POST route.\n */\nimport { type AgentManifestEntry, buildAgentCard, compileLoadedAgentModule } from '@theokit/agents'\n\nconst WELL_KNOWN = /^\\/\\.well-known\\/([^/]+)\\/agent-card\\.json$/\n\n/** Return the agent name when `urlPath` is a well-known card path, else `null`. */\nexport function isAgentCardPath(urlPath: string): string | null {\n const match = WELL_KNOWN.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Build a minimal manifest entry (the subset `buildAgentCard` reads) from a compiled agent. */\nfunction toManifestEntry(name: string, route: string, mod: unknown): AgentManifestEntry {\n const compiled = compileLoadedAgentModule(mod, `agent card for \"${name}\"`)\n return {\n name,\n route,\n stream: compiled.stream,\n mainLoop: { method: '', strategy: '' },\n guards: [],\n interceptors: [],\n tools: compiled.tools.map((t) => ({\n name: t.name,\n description: t.description,\n approval: false,\n trace: false,\n audit: false,\n })),\n subAgents: [],\n }\n}\n\n/**\n * Serve the A2A card for a loaded agent module. Returns 200 with the card JSON, or 500 with an\n * error body if the module is not a valid agent (fail-clear, not a silent empty card).\n */\nexport function handleAgentCard(\n mod: unknown,\n name: string,\n route: string,\n baseUrl: string,\n): Response {\n try {\n const card = buildAgentCard(toManifestEntry(name, route, mod), { baseUrl })\n return new Response(JSON.stringify(card), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n } catch (err) {\n return new Response(\n JSON.stringify({\n error: {\n code: 'AGENT_CARD_FAILED',\n message: err instanceof Error ? err.message : 'card build failed',\n },\n }),\n { status: 500, headers: { 'content-type': 'application/json; charset=utf-8' } },\n )\n }\n}\n","/**\n * M4 (theokit-ai-first) — the HITL approve endpoint: `POST /api/agents/<name>/approve/<approvalId>`.\n *\n * The counterpart to `mountAgent`'s HITL pause. While a gated tool holds the SDK run paused (the\n * awaited `pre_tool_call` hook), the client POSTs here with `{ approved }`; this resolves the\n * pending approval in the shared registry, which un-pauses the run (allow) or vetoes the tool (deny).\n *\n * Web-Standard `Request` → `Response`, one wiring point shared by dev (vite middleware) and prod\n * (built server) so the two never drift (EC-4 parity with `mountAgent`). The registry is INJECTED —\n * dev/prod pass the process singleton (`getApprovalRegistry`), tests pass a fresh instance.\n */\nimport type { RoutePolicy } from '../../core/contracts/route-policy.js'\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { admitAgentRequest, agentAccessDenied, type AgentSubjectResolver } from './agent-access.js'\nimport type { ApprovalDecision, ApprovalRegistry } from './approval-registry.js'\nimport { closePauseSpan } from './hitl-pause-spans.js'\n\n/** The path segment separating the agent name from the approval id. */\nconst APPROVE_SEGMENT = '/approve/'\n\nconst APPROVE_PATH = /^\\/api\\/agents\\/([^/]+)\\/approve\\/([^/]+)$/\n\n/**\n * The agent named by a `/api/agents/<name>/approve/<id>` path, or `null`.\n *\n * The route's own gate is the agent's declared policy, and reading the policy needs the agent —\n * which this path carries and nothing previously read (usetheokit/theokit#365).\n */\nexport function parseApprovalAgentName(urlPath: string): string | null {\n const match = APPROVE_PATH.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/**\n * Extract the `<approvalId>` from a `/api/agents/<name>/approve/<approvalId>` path.\n * Returns `null` when the path has no `/approve/` segment or an empty / nested id.\n */\nexport function parseApprovalId(urlPath: string): string | null {\n const at = urlPath.indexOf(APPROVE_SEGMENT)\n if (at === -1) return null\n const id = urlPath.slice(at + APPROVE_SEGMENT.length)\n return id.length > 0 && !id.includes('/') ? id : null\n}\n\n/** True when `urlPath` targets a HITL approve endpoint (used by dev/prod routing to branch early). */\nexport function isApprovalPath(urlPath: string): boolean {\n return urlPath.includes(APPROVE_SEGMENT)\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * M20 — cap on the serialized custom payload (16 KiB). A payload is a small structured note\n * (edited args, a reviewer comment), not a data channel — an oversized one is rejected fail-fast\n * rather than silently truncated (Rule 8).\n */\nconst MAX_PAYLOAD_BYTES = 16 * 1024\n\n/**\n * Extract an {@link ApprovalDecision} from an untrusted body; `null` when the shape is wrong.\n *\n * M20 — accepts an optional `reason` (string) and `payload` (object, capped at\n * {@link MAX_PAYLOAD_BYTES}). Backward-compatible: `{ approved }` and `{ approved, reason }` parse\n * unchanged. A non-object or oversized `payload` is rejected (returns `null` → the route 400s).\n *\n * @public\n */\nexport function parseApprovalBody(body: unknown): ApprovalDecision | null {\n if (typeof body !== 'object' || body === null) return null\n const b = body as Record<string, unknown>\n if (typeof b.approved !== 'boolean') return null\n const decision: ApprovalDecision = { approved: b.approved }\n if (b.reason !== undefined) {\n if (typeof b.reason !== 'string') return null\n decision.reason = b.reason\n }\n if (b.payload !== undefined) {\n if (typeof b.payload !== 'object' || b.payload === null || Array.isArray(b.payload)) return null\n if (JSON.stringify(b.payload).length > MAX_PAYLOAD_BYTES) return null\n decision.payload = b.payload\n }\n return decision\n}\n\n/**\n * The gates it applies (usetheokit/theokit#365):\n *\n * CSRF, which refuses a cross-origin POST and identifies nobody — and then the agent's declared\n * `policy`, which is what makes \"who is asking\" a question this endpoint can answer at all.\n * Reproduced before the policy existed: a process holding no cookie and no credential read a\n * pending id off the listing, POSTed here, and the gated tool ran.\n *\n * Ownership, which this endpoint could NOT decide until B-016 and now can, within a stated scope.\n * `mountAgent` records the run's subject on each approval it registers, for agents that DECLARE a\n * policy, and this route refuses a caller whose identity does not match. Before it, an\n * authenticated tenant could settle another tenant's approval on an agent both were admitted to —\n * the policy was the only thing between them, and the policy cannot see whose approval it is.\n *\n * Two limits, stated rather than implied. An agent that declares `'public'` records no owner, since\n * attributing approvals there would start refusing callers the declaration admits. And a thread\n * continuation runs headless, with no request whose identity could be resolved, so its approvals\n * record nobody. In both cases the endpoint behaves exactly as it did — `params.approvalId` is\n * still passed so an application holding its own owner map can answer more than the framework does.\n *\n * Returns:\n * 403 CSRF_FAILED — strict CSRF check failed\n * 403 FORBIDDEN — the agent's policy refused this caller\n * 400 BAD_REQUEST — no `/approve/<id>` in the path, or body lacks a boolean `approved`\n * 404 NOT_PENDING — the id is unknown or already settled (idempotent double-submit)\n * 200 { resolved:true } — the approval was settled by this call\n */\n/**\n * Refuse a caller who does not own this approval, where the ledger knows the owner (B-016).\n *\n * The agent's policy answers \"may this subject touch this agent's approvals\". It cannot answer \"is\n * this approval theirs\", because it is never told — which is why an authenticated tenant could\n * settle another tenant's approval on an agent both were admitted to. `mountAgent` now records the\n * run's subject on each approval it registers, for agents that DECLARE a policy, and this reads it.\n *\n * `undefined` from `ownerOf` covers three cases the endpoint treats identically — never registered,\n * already settled, and registered with no owner — and in all three there is nothing to compare a\n * caller against, so the endpoint behaves exactly as it did. The check only ever narrows.\n */\nasync function refuseIfNotOwner(\n registry: ApprovalRegistry,\n approvalId: string,\n resolveSubject: AgentSubjectResolver | undefined,\n params: Parameters<typeof agentAccessDenied>[1],\n): Promise<Response | undefined> {\n const owner = registry.ownerOf(approvalId)\n if (owner === undefined) return undefined\n\n const subject = resolveSubject === undefined ? null : await resolveSubject()\n if (subject?.id === owner) return undefined\n\n // An unidentifiable caller is refused, deliberately. An approval that HAS an owner must not be\n // settleable by whoever reaches the endpoint without an identity — admitting there would make the\n // guarantee depend on how the host wired its resolver rather than on who is asking.\n return agentAccessDenied(\n { allowed: false, reason: 'the approval belongs to another subject' },\n params,\n )\n}\n\nexport async function handleAgentApproval(\n request: Request,\n urlPath: string,\n registry: ApprovalRegistry,\n csrfMode: CsrfMode = 'strict',\n access: { policy?: RoutePolicy; resolveSubject?: AgentSubjectResolver } = {},\n): Promise<Response> {\n if (csrfMode !== 'off') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid && csrfMode === 'strict') {\n return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n }\n\n const approvalId = parseApprovalId(urlPath)\n if (approvalId === null) {\n return jsonError(400, 'BAD_REQUEST', 'Approval path must be /api/agents/<name>/approve/<id>.')\n }\n\n const params = {\n agent: parseApprovalAgentName(urlPath) ?? 'unknown',\n endpoint: 'approve' as const,\n approvalId,\n }\n const decision = await admitAgentRequest(access.policy, access.resolveSubject, params)\n if (!decision.allowed) return agentAccessDenied(decision, params)\n\n const notOwner = await refuseIfNotOwner(registry, approvalId, access.resolveSubject, params)\n if (notOwner !== undefined) return notOwner\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → handled below as a 400 */\n }\n const parsed = parseApprovalBody(body)\n if (parsed === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request body must contain a boolean `approved`.')\n }\n\n const resolved = registry.resolve(approvalId, parsed)\n if (!resolved) {\n return jsonError(404, 'NOT_PENDING', `No pending approval for id '${approvalId}'.`)\n }\n\n // THIS is the resume instant, and it is why the span could not be closed correctly before\n // (B-028). The run's observer never sees this request; it saw the tool's output arriving later\n // and closed the pause there, so the recorded wait was the human's plus the model's — measured at\n // +1523 ms on a run whose human answered at 3306 ms. Closing here, on the request that carries\n // the answer, makes the duration the human's by construction rather than by subtraction.\n closePauseSpan(approvalId, { resumeObserved: true })\n return new Response(JSON.stringify({ resolved: true }), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n })\n}\n","import {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport type { RunEventCache } from './run-event-cache.js'\n\n/**\n * M37 (ADR-0046 D5) — the reconnect / observe endpoint handler for\n * `GET /api/agents/<name>/runs/<runId>/stream`.\n *\n * Replays the frames the client missed (`seq > Last-Event-ID`, SSE-native), then\n * — if the run is still live — follows the live tail; a SECOND client can\n * observe a run a first started. Run already ended ⇒ replay + `[DONE]`. Unknown\n * `runId` ⇒ 404. The request `AbortSignal` unsubscribes on disconnect.\n */\n\nconst RUN_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/runs\\/([^/]+)\\/stream$/\n\n/**\n * Match `GET /api/agents/<name>/runs/<runId>/stream`; returns the decoded\n * `{ name, runId }` or `null` to fall through (mirrors `isMcpPath` etc.).\n */\nexport function isAgentRunStreamPath(urlPath: string): { name: string; runId: string } | null {\n const m = RUN_STREAM_PATH.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), runId: decodeURIComponent(m[2]) } : null\n}\n\n/** Parse `Last-Event-ID` (a frame `seq`) to a number; absent/invalid ⇒ -1 (replay from the start). */\nfunction parseLastEventId(raw: string | null): number {\n if (raw === null) return -1\n const n = Number.parseInt(raw, 10)\n return Number.isInteger(n) && n >= 0 ? n : -1\n}\n\nexport function handleAgentRunReconnect(\n runId: string,\n request: Request,\n cache: RunEventCache,\n): Response {\n // Unknown run ⇒ 404 (a run never started here, or already evicted).\n if (!cache.has(runId)) {\n return new Response(\n JSON.stringify({ error: { code: 'RUN_NOT_FOUND', message: `Unknown run '${runId}'.` } }),\n {\n status: 404,\n headers: { 'content-type': 'application/json' },\n },\n )\n }\n\n const afterSeq = parseLastEventId(request.headers.get('last-event-id'))\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const safeEnqueue = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* controller already closed by an abort race — ignore */\n }\n }\n const close = (): void => {\n if (closed) return\n safeEnqueue(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n\n // Atomic: snapshot replay frames AND subscribe to the live tail in one tick.\n const res = cache.attach(\n runId,\n afterSeq,\n (frame) => {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n // Evicted between has() and attach() (rare TOCTOU) ⇒ just end the stream.\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n }\n if (res.ended) {\n close()\n return\n }\n // Client disconnects ⇒ detach the live listener + close.\n request.signal.addEventListener('abort', () => {\n res.unsubscribe()\n close()\n })\n },\n })\n\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS, [RUN_ID_HEADER]: runId } })\n}\n","/**\n * M39 (ADR-0048) — the thread follow-up dispatcher.\n *\n * Drives a run over the M37 durable cache HEADLESS — it iterates the SDK chunk\n * generator and `cache.append`s directly, NOT via a `Response` `ReadableStream`\n * (whose backpressure would stall a run with no HTTP reader). Subscribers read\n * from the cache via the thread / reconnect stream.\n *\n * - Post to an IDLE thread ⇒ start a run + pump.\n * - Post to an ACTIVE thread ⇒ FIFO-queue the follow-up.\n * - On terminal ⇒ `registry.endRun` hands back the next queued follow-up, which\n * is dispatched as a continuation on the SAME sessionId (⇒ the SDK continues\n * the conversation via its `ConversationStorageAdapter`).\n *\n * This adds NO agent loop — it reuses the SDK run (`startRun`) + the M37 cache.\n * Single-process (ADR-0048 D2).\n */\n\nimport type { WireChunk as UIMessageChunk } from '@theokit/presenter/wire'\n\nimport { type RunEventCache, mintRunId } from './run-event-cache.js'\nimport type { ThreadRunRegistry } from './thread-run-registry.js'\n\ninterface ThreadDispatchDeps {\n readonly registry: ThreadRunRegistry\n readonly cache: RunEventCache\n /** Start a run for a follow-up on `sessionId`; returns the SDK chunk stream. */\n readonly startRun: (sessionId: string, message: string) => AsyncIterable<UIMessageChunk>\n}\n\n/** Result of posting a follow-up: the started `runId` (idle thread) or `queued` (active thread). */\ntype PostFollowUpResult = { runId: string } | { queued: true }\n\n/**\n * Post a follow-up on a thread. IDLE ⇒ start a run (returns its `runId`); ACTIVE\n * ⇒ FIFO-queue it (returns `{ queued: true }`) — dispatched when the active run ends.\n */\nexport function postThreadFollowUp(\n deps: ThreadDispatchDeps,\n sessionId: string,\n message: string,\n): PostFollowUpResult {\n if (deps.registry.getActive(sessionId) !== null) {\n deps.registry.queue(sessionId, { message })\n return { queued: true }\n }\n return { runId: startAndPump(deps, sessionId, message) }\n}\n\n/** Mint a runId, mark the thread active, and pump the run into the cache headless. */\nfunction startAndPump(deps: ThreadDispatchDeps, sessionId: string, message: string): string {\n const runId = mintRunId()\n // Register the run in the cache SYNCHRONOUSLY (before the async pump appends its\n // first frame) so a subscriber resolving the active runId can attach immediately.\n deps.cache.begin(runId)\n deps.registry.startRun(sessionId, runId)\n pumpIntoCache(deps, sessionId, runId, deps.startRun(sessionId, message))\n return runId\n}\n\n/**\n * Drive `chunks` into the cache under `runId`, then end the run and dispatch the\n * next queued follow-up (if any) as a continuation. Fire-and-forget — the caller\n * does not await the run; subscribers observe it via the cache.\n */\nfunction pumpIntoCache(\n deps: ThreadDispatchDeps,\n sessionId: string,\n runId: string,\n chunks: AsyncIterable<UIMessageChunk>,\n): void {\n void (async () => {\n try {\n for await (const chunk of chunks) {\n deps.cache.append(runId, JSON.stringify(chunk))\n }\n } catch {\n // The SDK translator owns error semantics (surfaces failures as chunks);\n // the transport guarantees only a terminated, cache-ended run.\n } finally {\n deps.cache.end(runId)\n const next = deps.registry.endRun(sessionId, runId)\n if (next !== undefined) startAndPump(deps, sessionId, next.message)\n }\n })()\n}\n","/**\n * M39 (ADR-0048) — the in-process thread→run registry.\n *\n * A thread is the existing `sessionId` (the SDK conversation key). This registry\n * tracks, per thread, the single ACTIVE run, a FIFO queue of follow-ups to\n * dispatch as continuations, and one-shot \"next run\" waiters (so a client can\n * subscribe to a thread before posting a message and attach when the run starts).\n *\n * Pure state only — it never starts a run or touches the transport. The route\n * layer owns dispatch: on `endRun` it receives the next queued follow-up (if any)\n * and starts the continuation over the M37 durable transport.\n *\n * Single-process contract (ADR-0048 D2): a multi-instance deploy needs a shared\n * registry + leasing — that is infra (TheoCloud), explicitly out of M39. The\n * interface is injectable so a durable impl slots in later without touching the\n * routes. We do NOT build a distributed store now (YAGNI).\n */\n\n/** A follow-up message queued on an active thread, dispatched as a continuation. */\nexport interface FollowUp {\n readonly message: string\n}\n\nexport interface ThreadRunRegistry {\n /** The active runId for a thread, or `null` when the thread is idle. */\n getActive(sessionId: string): string | null\n /** Mark a run started for a thread (sets it active; fires + clears one-shot waiters). */\n startRun(sessionId: string, runId: string): void\n /**\n * Mark `runId` ended for a thread. A no-op unless `runId` is the current active\n * run (a stale terminal never clears a newer run). Clears the active run and\n * returns the next FIFO follow-up to dispatch as a continuation, or `undefined`.\n */\n endRun(sessionId: string, runId: string): FollowUp | undefined\n /** FIFO-enqueue a follow-up on a thread (dispatched when the active run ends). */\n queue(sessionId: string, followUp: FollowUp): void\n /**\n * Register a ONE-SHOT waiter fired with the runId of the NEXT run started on\n * this thread. Returns an unsubscribe fn. Used by subscribe-by-thread on an\n * idle thread (attach when the next run starts).\n */\n onNextRun(sessionId: string, cb: (runId: string) => void): () => void\n}\n\ninterface ThreadState {\n activeRunId: string | null\n readonly queue: FollowUp[]\n readonly waiters: Set<(runId: string) => void>\n}\n\nexport function createInProcessThreadRunRegistry(): ThreadRunRegistry {\n const threads = new Map<string, ThreadState>()\n const ensure = (sessionId: string): ThreadState => {\n let s = threads.get(sessionId)\n if (s === undefined) {\n s = { activeRunId: null, queue: [], waiters: new Set() }\n threads.set(sessionId, s)\n }\n return s\n }\n\n return {\n getActive(sessionId) {\n return threads.get(sessionId)?.activeRunId ?? null\n },\n startRun(sessionId, runId) {\n const s = ensure(sessionId)\n s.activeRunId = runId\n // Fire one-shot waiters, then clear them (single-threaded → no re-entrancy race).\n const waiters = [...s.waiters]\n s.waiters.clear()\n for (const cb of waiters) cb(runId)\n },\n endRun(sessionId, runId) {\n const s = threads.get(sessionId)\n if (s?.activeRunId !== runId) return undefined\n s.activeRunId = null\n return s.queue.shift()\n },\n queue(sessionId, followUp) {\n ensure(sessionId).queue.push(followUp)\n },\n onNextRun(sessionId, cb) {\n const s = ensure(sessionId)\n s.waiters.add(cb)\n return () => {\n s.waiters.delete(cb)\n }\n },\n }\n}\n\nlet serverRegistry: ThreadRunRegistry | undefined\n\n/** Process-wide singleton (mirrors `getRunEventCache` / `getApprovalRegistry`). */\nexport function getThreadRunRegistry(): ThreadRunRegistry {\n serverRegistry ??= createInProcessThreadRunRegistry()\n return serverRegistry\n}\n","/**\n * M39 (ADR-0048) — the thread signal routes over the M37 durable transport:\n *\n * - `POST /api/agents/<name>/threads/<sessionId>/message` — a follow-up. ACTIVE\n * run ⇒ FIFO-queue (dispatched as a continuation when it ends); IDLE ⇒ start a\n * run. Returns `202` (the run streams headless into the cache; observe it via\n * the thread stream). Spends LLM tokens ⇒ CSRF-gated (parity with mount-agent).\n * - `GET /api/agents/<name>/threads/<sessionId>/stream` — subscribe. ACTIVE ⇒\n * attach to the durable stream (reuse the M37 reconnect handler); IDLE ⇒ wait\n * (bounded) for the next run on the thread, then attach (subscribe-then-post).\n *\n * These DRIVE the SDK run (via `makeThreadStartRun`) + the M37 cache — no new loop.\n */\n\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport type { ApiKeyResolver } from './api-key-resolver.js'\nimport { makeThreadStartRun } from './build-agent-streamer.js'\nimport {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport { handleAgentRunReconnect } from './handle-agent-run-reconnect.js'\nimport { parseAgentRequestBody } from './mount-agent.js'\nimport { getRunEventCache, type RunEventCache } from './run-event-cache.js'\nimport { postThreadFollowUp } from './thread-dispatcher.js'\nimport { getThreadRunRegistry, type ThreadRunRegistry } from './thread-run-registry.js'\n\nconst THREAD_MESSAGE_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/message$/\nconst THREAD_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/stream$/\n\n/** How long a subscribe-to-idle-thread waits for the next run before closing. */\nconst DEFAULT_IDLE_WAIT_MS = 30_000\n\nfunction matchThread(re: RegExp, urlPath: string): { name: string; sessionId: string } | null {\n const m = re.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), sessionId: decodeURIComponent(m[2]) } : null\n}\n\nexport const isThreadMessagePath = (urlPath: string) => matchThread(THREAD_MESSAGE_PATH, urlPath)\nexport const isThreadStreamPath = (urlPath: string) => matchThread(THREAD_STREAM_PATH, urlPath)\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Inputs for {@link handleThreadMessage} (bundled to stay within the arity budget). */\ninterface ThreadMessageArgs {\n readonly mod: unknown\n /** theokit#328 — a resolver is passed through unresolved so the model can pick the provider. */\n readonly apiKey: string | ApiKeyResolver\n readonly sessionId: string\n readonly request: Request\n /** Labels a fail-fast `AgentDefinitionError`. Human-readable; never a telemetry key. */\n readonly source: string\n /**\n * The agent's name, as the scanner discovered it — the attribute an operator groups runs by.\n * Separate from {@link ThreadMessageArgs.source} since usetheokit/theokit#406: one field was\n * carrying both, and this route's `source` is the label `agent \"chat\"`.\n */\n readonly agentName: string\n readonly csrfMode?: CsrfMode\n}\n\n/** POST a follow-up on a thread. Returns `202` with `{ runId }` (started) or `{ queued: true }`. */\nexport async function handleThreadMessage(args: ThreadMessageArgs): Promise<Response> {\n const { mod, apiKey, sessionId, request, source, agentName, csrfMode = 'strict' } = args\n // A follow-up drives the agent (spends LLM tokens) — reject a cross-origin POST.\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → 400 below */\n }\n const input = parseAgentRequestBody(body)\n if (input === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request must contain a non-empty message.')\n }\n const result = postThreadFollowUp(\n {\n registry: getThreadRunRegistry(),\n cache: getRunEventCache(),\n // usetheokit/theokit#381 — the request goes with it, so the run's spans join the trace of\n // the caller that queued it instead of opening one of their own.\n startRun: makeThreadStartRun(mod, apiKey, source, agentName, request),\n },\n sessionId,\n input.message,\n )\n const headers: Record<string, string> = { 'content-type': 'application/json; charset=utf-8' }\n if ('runId' in result) headers[RUN_ID_HEADER] = result.runId\n return new Response(JSON.stringify(result), { status: 202, headers })\n}\n\n/** GET the thread's durable stream. Active ⇒ attach now; idle ⇒ wait (bounded) for the next run. */\nexport function handleThreadStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry = getThreadRunRegistry(),\n cache: RunEventCache = getRunEventCache(),\n idleWaitMs = DEFAULT_IDLE_WAIT_MS,\n): Response {\n const active = registry.getActive(sessionId)\n if (active !== null && cache.has(active)) {\n // Reuse the M37 reconnect handler — replay + live tail on the active run.\n return handleAgentRunReconnect(active, request, cache)\n }\n return waitThenAttachStream(sessionId, request, registry, cache, idleWaitMs)\n}\n\n/** Subscribe to an idle thread: wait (bounded) for the NEXT run to start, then attach + tail. */\nfunction waitThenAttachStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry,\n cache: RunEventCache,\n idleWaitMs: number,\n): Response {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const send = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* closed by an abort race */\n }\n }\n let detachAttach: (() => void) | undefined\n const close = (): void => {\n if (closed) return\n send(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n const offNext = registry.onNextRun(sessionId, (runId) => {\n const res = cache.attach(\n runId,\n -1,\n (frame) => {\n send(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) send(formatSseFrame(frame.seq, frame.data))\n if (res.ended) {\n close()\n return\n }\n detachAttach = res.unsubscribe\n })\n // HIGH-1 — the waiter teardown MUST run on BOTH the idle-wait timeout AND the\n // client abort, else the (one-shot) `onNextRun` waiter leaks in the registry\n // when a timed-out subscriber's session never receives another run.\n const teardownWaiter = (): void => {\n offNext()\n detachAttach?.()\n }\n const timer = setTimeout(() => {\n teardownWaiter()\n close()\n }, idleWaitMs)\n timer.unref()\n request.signal.addEventListener('abort', () => {\n teardownWaiter()\n clearTimeout(timer)\n close()\n })\n },\n })\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS } })\n}\n","/**\n * M14 (theokit-ai-first) — GET /api/agents/<name>/approvals: list pending HITL approvals.\n *\n * Serves the approvals the CALLER owns, plus the ownerless ones, as JSON. Web Standards Response (G8).\n *\n * ## Why this is scoped, and what it closes\n *\n * The registry is process-wide by contract (ADR 0017): `list()` returns every pending approval, and\n * the `<name>` segment is accepted for a future per-agent store. That was the whole answer here, so\n * one admitted tenant of one agent received every pending approval in the process — other tenants',\n * other agents' — each with the `approvalId` the settle route needs.\n *\n * The draft advisory `GHSA-g94h-459g-rjhj` describes two steps: list without authentication, then\n * settle with an id from the listing. Both halves were closed around this file and neither in it —\n * `admitAux` refuses a caller the agent's policy does not admit (usetheokit/theokit#365), and\n * `approve-agent.ts` refuses a settle by a caller who is not the owner (B-016). The door was gated\n * and the window left open: an ADMITTED caller still read everyone's ids.\n *\n * ## An ownerless approval stays visible, deliberately\n *\n * The registry records an owner only for agents that DECLARE a policy — `admitAgentRequest` resolves\n * no subject for `'public'` or for an undeclared agent, so there is nothing to attribute. The settle\n * route already treats an absent owner as \"nothing to compare a caller against\" and refuses nobody\n * on it. Listing follows the same rule rather than inventing a second one, because hiding those\n * would blank a public agent's own approvals UI while protecting nobody.\n *\n * The filter asks `ownerOf` per approval rather than reading an owner off the listing, because\n * `owner` is held BESIDE `info` precisely so `list()` cannot leak it (B-016). Scoping the response\n * must not put the identity back into it.\n */\nimport type { ApprovalRegistry } from './approval-registry.js'\n\nconst LIST_PATH = /^\\/api\\/agents\\/([^/]+)\\/approvals$/\n\n/** Return the agent name when `urlPath` is the approvals-listing path, else `null`. */\nexport function isListApprovalsPath(urlPath: string): string | null {\n const match = LIST_PATH.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/**\n * Serve the pending approvals this caller may see as `{ approvals: [...], scope }` JSON.\n *\n * `scope` says how far the answer reaches — `'instance'` for the in-process registry this\n * framework ships, which is every answer it can currently give (B-236). It is present on every\n * response, empty or not.\n *\n * `subject` is the admitted caller's id, or `undefined` when the agent declares no policy and none\n * was resolved. An approval is included when it has no owner, or when its owner is this subject.\n */\nexport function handleListApprovals(\n registry: ApprovalRegistry,\n subject: string | undefined,\n): Response {\n const visible = registry.list().filter((approval) => {\n const owner = registry.ownerOf(approval.approvalId)\n return owner === undefined || owner === subject\n })\n // B-236 — every answer carries how far it reaches, including a non-empty one: a listing of two\n // from one instance can be two of five, so a caveat that appeared only when the list was empty\n // would vanish exactly when a caller starts trusting the numbers. Read from the registry, not\n // written here, so a shared implementation reports itself without this file changing.\n return new Response(JSON.stringify({ approvals: visible, scope: registry.scope ?? 'instance' }), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n","/**\n * M15/M16 follow-up — shared dispatcher for the agent AUXILIARY routes that BOTH dev (vite\n * middleware) and prod (`theokit start` handler) must serve identically. Before this, these routes\n * were wired only into the dev middleware, so a built/deployed app served none of them (agent cards,\n * MCP, pending-approvals listing all 404'd in production).\n *\n * Single source of truth (DRY): one Web-Request→Response dispatcher, two callers. It handles the\n * routes that derive purely from the agent module + shared registry:\n * - **M15** `GET /.well-known/<name>/agent-card.json` → {@link handleAgentCard}\n * - **M14** `GET /api/agents/<name>/approvals` → {@link handleListApprovals}\n * - **M16** `POST /api/agents/<name>/mcp` → {@link handleMcpJsonRpc}\n * - **M37** `GET /api/agents/<name>/runs/<id>/stream` → {@link handleAgentRunReconnect}\n * - **M39** the two thread routes → {@link handleThreadMessage} / {@link handleThreadStream}\n *\n * Channels (M27) are NOT here: a channel webhook needs app-supplied `validators` + `onMessage`, so\n * the app wires `handleChannelWebhook` in its own route (it cannot be auto-derived from the module).\n * The HITL approve route stays in each caller (it carries caller-specific rate-limiting/CSRF plumbing).\n *\n * ## Deciding and answering are two functions, and that is the fix\n *\n * This used to be one call that took a not-yet-converted request, decided whether it owned the path\n * and answered in the same breath. A caller could therefore learn \"this is an agent aux route\" only\n * by receiving the finished `Response` — too late to run anything around the handler. So the plugin\n * lifecycle, which every other branch of `theokit start` runs, was never run here: `onRequest`,\n * `onResponse` and `onError` fired for a file route and for the plain agent route and for none of\n * these six, and the observability plugin therefore emitted no `http.request` span for the endpoints\n * that spend tokens and settle human decisions (usetheokit/theokit#405).\n *\n * {@link matchAgentAuxRoute} decides; {@link serveMatchedAuxRoute} answers. A caller brackets the\n * gap with whatever the request lifecycle owes — and a seventh route added to the match table\n * inherits that bracket instead of having to remember it.\n */\nimport type { RouteSubject } from '../../core/contracts/route-policy.js'\nimport type { AgentNode } from '../scan/agent-scan.js'\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport {\n AgentIdentityUnavailableError,\n admitAgentRequest,\n agentAccessDenied,\n readAgentPolicy,\n type AgentAccessParams,\n type AgentSubjectResolver,\n} from './agent-access.js'\nimport { isAgentCardPath, handleAgentCard } from './agent-card-handler.js'\nimport type { ApiKeyResolver } from './api-key-resolver.js'\nimport { getApprovalRegistry } from './approval-registry.js'\nimport { handleAgentRunReconnect, isAgentRunStreamPath } from './handle-agent-run-reconnect.js'\nimport {\n handleThreadMessage,\n handleThreadStream,\n isThreadMessagePath,\n isThreadStreamPath,\n} from './handle-thread-routes.js'\nimport { isListApprovalsPath, handleListApprovals } from './list-approvals-handler.js'\nimport { extractAppResources } from './mcp-app-resources.js'\nimport { isMcpPath, handleMcpJsonRpc } from './mcp-handler.js'\nimport { getRunEventCache } from './run-event-cache.js'\n\n/** JSON error envelope (mirrors mount-agent.ts:37 — the parity source for the MCP CSRF gate). */\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Dependencies the aux dispatcher needs from its caller (dev or prod). */\ninterface AuxRouteDeps {\n /** Discovered agents (from `scanAgents`). */\n agents: readonly AgentNode[]\n /** Load an agent module from its file path (dev: vite loader; prod: dynamic import). */\n loadModule: (filePath: string) => Promise<unknown>\n /** Absolute base URL (`http(s)://host`) for the agent-card endpoint URLs. */\n baseUrl: string\n /**\n * M34 (#97) — CSRF enforcement mode for the MCP route. `POST /api/agents/<name>/mcp` drives the\n * agent (spends LLM tokens), so a cross-origin POST MUST be rejected in `'strict'` — parity with\n * the agent-run route (`mount-agent.ts:83-91`). Defaults to `'strict'` (safe-by-default); a caller\n * that already gated upstream may pass `'off'`.\n */\n csrfMode?: CsrfMode\n /**\n * M39 — lazily resolve the provider apiKey. Required only for the thread\n * follow-up route (which drives the agent); resolved on demand so non-agent\n * aux routes (card, approvals, stream) never need a provider key.\n *\n * theokit#328 — it receives the model the agent declares, so the credential matches the provider\n * the agent asked for. It was called with no argument, before the module was even compiled, so\n * an agent declaring `anthropic/…` was handed whichever key env priority found first.\n */\n resolveApiKey?: ApiKeyResolver\n /**\n * Who is asking (usetheokit/theokit#365). Invoked ONLY from {@link serveMatchedAuxRoute}, and only\n * when the matched path's agent declares a policy — so the application's `createContext` never\n * runs for a url this dispatcher merely declines. {@link matchAgentAuxRoute} is not given it, for\n * the same reason it is not given the request body: deciding must cost nothing.\n */\n resolveSubject?: AgentSubjectResolver\n}\n\n/**\n * One aux route, already decided. Carries what the match resolved so the serve half re-derives\n * nothing: the agent node it looked up, and for MCP the module it had to open in order to answer\n * the opt-in question at all.\n */\nexport type AgentAuxRoute =\n | { readonly kind: 'card'; readonly agent: AgentNode }\n | { readonly kind: 'approvals'; readonly agent: AgentNode }\n | { readonly kind: 'run-stream'; readonly agent: AgentNode; readonly runId: string }\n | { readonly kind: 'thread-stream'; readonly agent: AgentNode; readonly sessionId: string }\n | { readonly kind: 'thread-message'; readonly agent: AgentNode; readonly sessionId: string }\n | { readonly kind: 'mcp'; readonly agent: AgentNode; readonly mod: unknown }\n\n/**\n * Resolve `name` to a discovered agent and build a route from it, or `null` when there is no name\n * (the path did not match) or no such agent (fall through to the caller's 404).\n *\n * Both misses collapse to `null` deliberately: every one of them means \"this dispatcher does not\n * answer this url\", and the path families below are mutually exclusive, so a family that declines\n * can safely let the next matcher look.\n */\nfunction routeFor<R>(\n deps: AuxRouteDeps,\n name: string | null,\n build: (agent: AgentNode) => R,\n): R | null {\n if (name === null) return null\n const agent = deps.agents.find((a) => a.name === name)\n return agent === undefined ? null : build(agent)\n}\n\n/** The GET-only aux routes: agent card, approvals listing, run stream, thread stream. */\nfunction matchGetAuxRoute(verb: string, urlPath: string, deps: AuxRouteDeps): AgentAuxRoute | null {\n if (verb !== 'GET') return null\n\n // M15 — A2A agent card at `/.well-known/<name>/agent-card.json`.\n const card = routeFor(\n deps,\n isAgentCardPath(urlPath),\n (agent) => ({ kind: 'card', agent }) as const,\n )\n if (card !== null) return card\n\n // M14 — the pending HITL approvals of one agent.\n const approvals = routeFor(\n deps,\n isListApprovalsPath(urlPath),\n (agent) => ({ kind: 'approvals', agent }) as const,\n )\n if (approvals !== null) return approvals\n\n // M37 — the durable run stream (`/runs/<runId>/stream`), reconnect or observe.\n const run = isAgentRunStreamPath(urlPath)\n if (run !== null) {\n return routeFor(\n deps,\n run.name,\n (agent) => ({ kind: 'run-stream', agent, runId: run.runId }) as const,\n )\n }\n\n // M39 — subscribe to a thread (`/threads/<sessionId>/stream`).\n const stream = isThreadStreamPath(urlPath)\n if (stream === null) return null\n return routeFor(\n deps,\n stream.name,\n (agent) => ({ kind: 'thread-stream', agent, sessionId: stream.sessionId }) as const,\n )\n}\n\n/** The POST-only aux routes: thread follow-up and MCP. */\nasync function matchPostAuxRoute(\n verb: string,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<AgentAuxRoute | null> {\n if (verb !== 'POST') return null\n\n // M39 — a follow-up message on a thread.\n const msg = isThreadMessagePath(urlPath)\n if (msg !== null) {\n return routeFor(\n deps,\n msg.name,\n (agent) => ({ kind: 'thread-message', agent, sessionId: msg.sessionId }) as const,\n )\n }\n\n // M16 — the JSON-RPC MCP server, behind the M34 opt-in.\n const agent = routeFor(deps, isMcpPath(urlPath), (found) => found)\n if (agent === null) return null\n // M34 — DEFAULT-DENY: an agent is NOT exposed on MCP unless it explicitly opts in with a named\n // `export const mcp = true` (blueprint D5 — default-EXPOSE is the footgun magnified by the\n // multi-surface thesis). Absent the opt-in, fall through to 404 (the agent is web-only). This is a\n // breaking change from the M16 auto-mount (documented in the CHANGELOG § Security).\n const mod = await deps.loadModule(agent.filePath)\n return isMcpExposed(mod) ? { kind: 'mcp', agent, mod } : null\n}\n\n/**\n * Does this dispatcher own `urlPath`? Returns the matched route, or `null` to fall through (not an\n * aux path, wrong method, unknown agent, or an agent that did not opt into MCP).\n *\n * theokit#400 — this function is where the \"convert only on a path you are about to answer\" rule\n * now lives, and it is enforced by the signature rather than by discipline: it is handed a method\n * and a url and has no request to convert. Converting in order to decide is what drained the Node\n * body stream on every path this dispatcher declined, so an ordinary `POST /api/…` file route then\n * waited forever for an `'end'` that had already fired — no status, no timeout, no response.\n *\n * The one branch that does real work here is MCP, which must open the module to read its\n * `export const mcp` opt-in. That is deliberate: a match that could still fall through would hand\n * the caller a request it had already started a lifecycle for, and the span opened for it would\n * either double-count or never close.\n */\nexport async function matchAgentAuxRoute(\n method: string,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<AgentAuxRoute | null> {\n const verb = method.toUpperCase()\n return matchGetAuxRoute(verb, urlPath, deps) ?? (await matchPostAuxRoute(verb, urlPath, deps))\n}\n\n/** What {@link admitAux} decided, and — when a policy declared one — who was admitted. */\ninterface Admission {\n readonly refusal: Response | null\n /** The admitted caller's id, or `undefined` when no policy asked for one. */\n readonly subject: string | undefined\n}\n\n/**\n * Evaluate the agent's declared policy for one aux endpoint.\n *\n * Returns the refusal `Response`, or `null` when the caller is admitted. Loading the module here is\n * what makes the gate reachable at all: the policy is an export of the agent file, and three of\n * these branches previously answered without ever opening it.\n */\nasync function admitAux(\n deps: AuxRouteDeps,\n agent: AgentNode,\n params: AgentAccessParams,\n body?: unknown,\n): Promise<Admission> {\n const mod = await deps.loadModule(agent.filePath)\n // The subject is RECORDED rather than resolved twice. `admitAgentRequest` returns before touching\n // the resolver when the policy is absent or `'public'`, which is the guarantee `resolveSubject`'s\n // own docblock makes: the application's `createContext` must not run for a url this dispatcher\n // merely declines. Wrapping preserves that exactly — `seen` stays `undefined` in those cases —\n // while the approvals branch gets the id it needs to scope its answer.\n const resolve = deps.resolveSubject\n // A box rather than a `let`: the assignment happens inside a closure the compiler cannot see as\n // reachable before the read, so a plain binding narrows to `never` and `seen?.id` stops compiling.\n const admitted: { subject: RouteSubject | null } = { subject: null }\n const recording: AgentSubjectResolver | undefined =\n resolve === undefined\n ? undefined\n : async () => {\n // B-254 — the APP's resolution is wrapped, not the whole admission. A policy that throws\n // is a different failure with a different cause, and tagging both the same way would hand\n // an operator one code for two problems.\n try {\n admitted.subject = await resolve()\n } catch (cause) {\n throw new AgentIdentityUnavailableError(cause)\n }\n return admitted.subject\n }\n let decision\n try {\n decision = await admitAgentRequest(\n readAgentPolicy(mod, agent.filePath),\n recording,\n params,\n body,\n )\n } catch (err) {\n // B-254 — only the identity failure is shaped here. Anything else keeps escaping exactly as it\n // did, because turning every throw on this path into a 500 would swallow the ones a caller\n // SHOULD see differently — `AgentPolicyTypeError` is a developer's mistake, not an outage.\n if (!(err instanceof AgentIdentityUnavailableError)) throw err\n console.error('[theokit] agent identity resolution failed', err)\n // Returned through `refusal`, which is this function's channel for \"answer with this Response\"\n // — the caller writes it out and never looks at `subject`. `subject: undefined` is the honest\n // value: nobody was identified, and it must not read as an anonymous caller who WAS.\n return {\n refusal: jsonError(\n 500,\n 'IDENTITY_UNAVAILABLE',\n 'The application could not resolve the caller. This is not a refusal: `createContext` in ' +\n 'server/context.ts threw, so there was no identity to judge. The server log carries the cause.',\n ),\n subject: undefined,\n }\n }\n const refusal = decision.allowed ? null : agentAccessDenied(decision, params)\n return { refusal, subject: admitted.subject?.id }\n}\n\n/**\n * Answer a route {@link matchAgentAuxRoute} already claimed. Always returns a `Response` — every\n * fall-through was decided upstream, which is what lets a caller open a request span before this\n * runs and be sure something will close it.\n */\nexport async function serveMatchedAuxRoute(\n route: AgentAuxRoute,\n request: Request,\n deps: AuxRouteDeps,\n): Promise<Response> {\n if (route.kind === 'card') {\n const mod = await deps.loadModule(route.agent.filePath)\n return handleAgentCard(mod, route.agent.name, route.agent.agentPath, deps.baseUrl)\n }\n\n // usetheokit/theokit#365 — the approvals listing used to answer 200 with every pending approval\n // id to anyone who asked, and the id is all the approve route needs to settle a paused tool.\n if (route.kind === 'approvals') {\n const admission = await admitAux(deps, route.agent, {\n agent: route.agent.name,\n endpoint: 'approvals',\n })\n if (admission.refusal !== null) return admission.refusal\n // SCOPED to this caller. `admitAux` answered \"may you touch this agent's approvals\"; it cannot\n // answer \"which of them are yours\", and the registry is process-wide by contract (ADR 0017).\n return handleListApprovals(getApprovalRegistry(), admission.subject)\n }\n\n // M37 — INTENTIONALLY open (no CSRF, no auth gate): a GET is not CSRF-vulnerable, the run-start\n // POST is already gated, and the `runId` is a 122-bit UUID minted BY THE SERVER (`mintRunId`) and\n // handed only to the caller that started the run — a capability the framework issued rather than\n // a name the caller chose. That is the property the thread and conversation keys lack, and it is\n // the whole of the difference. Observe-by-runId is a FEATURE (ADR-0046 D5). Do NOT add a\n // custom-header CSRF check here: browsers send NO custom headers with `EventSource`, so it would\n // break native SSE reconnect.\n if (route.kind === 'run-stream') {\n return handleAgentRunReconnect(route.runId, request, getRunEventCache())\n }\n\n if (route.kind === 'mcp') return serveMcpRoute(route, request, deps)\n\n return serveThreadRoute(route, request, deps)\n}\n\n/**\n * M39 — serve the thread routes:\n * - `POST .../threads/<sessionId>/message` (follow-up) — loads the module, drives\n * the run headless via the thread dispatcher. Needs `resolveApiKey` (drives the\n * agent) → 501 when absent (rather than a silent 404).\n * - `GET .../threads/<sessionId>/stream` (subscribe) — attach to the active/next\n * run's durable stream. INTENTIONALLY open (GET, no custom headers — like the\n * M37 reconnect route).\n *\n * SECURITY (thread stream): unlike the M37 reconnect route — keyed on an\n * `mintRunId()` UUID (122-bit unguessable) — the thread stream is keyed on the\n * caller-supplied `sessionId`, so an app using a PREDICTABLE sessionId (a user id,\n * an email, a tenant-derived key) is one guess away from another party reading the\n * thread's live conversation.\n *\n * usetheokit/theokit#365 — this paragraph used to end by telling the application it\n * \"MUST add its own auth gate before this endpoint\", and no such gate was constructible:\n * the URL is dispatched before route matching, so no `route()` and no middleware ever\n * saw it. The gate is the agent's own `export const policy`, evaluated here, and the\n * instruction is now one an application can follow.\n */\nasync function serveThreadRoute(\n route: Extract<AgentAuxRoute, { kind: 'thread-stream' | 'thread-message' }>,\n request: Request,\n deps: AuxRouteDeps,\n): Promise<Response> {\n const { agent, sessionId } = route\n\n if (route.kind === 'thread-stream') {\n const { refusal } = await admitAux(deps, agent, {\n agent: agent.name,\n endpoint: 'thread-stream',\n sessionId,\n })\n return refusal ?? handleThreadStream(sessionId, request)\n }\n\n const { refusal } = await admitAux(deps, agent, {\n agent: agent.name,\n endpoint: 'thread-message',\n sessionId,\n })\n if (refusal !== null) return refusal\n if (deps.resolveApiKey === undefined) {\n // MEDIUM-1 — the path matched but the caller wired no provider-key resolver.\n // Fail loudly (501) instead of a silent 404 that reads as \"route not found\".\n return jsonError(\n 501,\n 'NOT_CONFIGURED',\n 'Thread follow-up requires a provider API key (resolveApiKey was not provided to serveMatchedAuxRoute).',\n )\n }\n const mod = await deps.loadModule(agent.filePath)\n return handleThreadMessage({\n mod,\n // Passed unresolved: `makeThreadStartRun` calls it once the module is compiled and the\n // model is known (theokit#328).\n apiKey: deps.resolveApiKey,\n sessionId,\n request,\n source: `agent \"${agent.name}\"`,\n // usetheokit/theokit#406 — the label above reads well in an `AgentDefinitionError` and is not\n // a name; the spans get the name, so the same agent is one series whichever route started it.\n agentName: agent.name,\n csrfMode: deps.csrfMode ?? 'strict',\n })\n}\n\n/**\n * Serve the MCP route with the M34 gates. The opt-in check already ran in the match (it is what\n * decides ownership), so what is left here is: default-DENY policy → CSRF → dispatch.\n */\nasync function serveMcpRoute(\n route: Extract<AgentAuxRoute, { kind: 'mcp' }>,\n request: Request,\n deps: AuxRouteDeps,\n): Promise<Response> {\n const { agent, mod } = route\n\n // usetheokit/theokit#365 — the MCP route drives the agent and reaches its tools, so it answers to\n // the same declared policy as the run route.\n const mcpParams = { agent: agent.name, endpoint: 'mcp' as const }\n const mcpDecision = await admitAgentRequest(\n readAgentPolicy(mod, agent.filePath),\n deps.resolveSubject,\n mcpParams,\n )\n if (!mcpDecision.allowed) return agentAccessDenied(mcpDecision, mcpParams)\n\n // M34 (#97) — enforce CSRF BEFORE any work. The MCP route drives the agent (real LLM tokens), so a\n // cross-origin POST must be rejected — parity with the agent-run route (`mount-agent.ts:83-91`).\n const csrfMode = deps.csrfMode ?? 'strict'\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* malformed/empty JSON → handleMcpJsonRpc returns a -32600 envelope */\n }\n // M30 — pass the agent's declared `ui://` App resources (named `appResources` export) so the MCP\n // server advertises + serves them via resources/list + resources/read.\n return handleMcpJsonRpc(mod, agent.name, body, extractAppResources(mod))\n}\n\n/**\n * M34 — DEFAULT-DENY opt-in check: is this agent module exposed on the MCP surface? An agent opts in\n * with a named `export const mcp = true` (mirroring the `appResources` named-export convention).\n * Anything else (absent / falsy) → NOT exposed. Read at the emit layer (blueprint D5).\n */\nfunction isMcpExposed(mod: unknown): boolean {\n return (mod as { mcp?: unknown } | null | undefined)?.mcp === true\n}\n","/**\n * One bracket around a Node-dispatched request, so every agent branch has the same lifecycle\n * (theokit#324, usetheokit/theokit#405).\n *\n * ## Why this is a function and not a paragraph in a review checklist\n *\n * `executeRoute` and `executeAction` have run the plugin lifecycle since the beginning. The agent\n * branches did not, and they were fixed one at a time: theokit#324 taught the plain\n * `POST /api/agents/<name>` to call `applyDecorations` → `runOnRequest` → handler →\n * `runOnResponse`, with `runOnError` on the failure path, and copied that shape into the dev\n * middleware. The aux routes (thread message and stream, MCP, agent card, approvals listing) and the\n * HITL approve route kept answering without it, in BOTH surfaces, so an application embedding\n * TheoKit had no supported place to observe six endpoints — two of which spend tokens and one of\n * which settles a human decision. The observability plugin is the case that made it legible: no\n * `onRequest` means no `http.request` span, and an operator reading HTTP latency or error rate sees\n * no traffic for endpoints that are serving traffic (usetheokit/theokit#405).\n *\n * A copied bracket is what let five branches drift from one. This is the bracket, once.\n *\n * ## The conversion is here, and only here\n *\n * The lifecycle needs a Web `Request` (that is what `PluginContext` carries), and converting an\n * `IncomingMessage` drains its body exactly once — a second conversion yields a Request whose body\n * is an empty closed stream, which is a silent truncation (theokit#400). So callers hand over a\n * {@link WebRequestSource}, whose `toRequest()` memoizes, and hand the SAME source to the handler\n * they wrap. Converting is therefore idempotent across the bracket, by construction rather than by\n * anyone noticing.\n *\n * The caller must still only enter this bracket on a path it is about to answer: `toRequest()` runs\n * here, and running it to decide ownership is the theokit#400 hang.\n */\nimport type { ServerResponse } from 'node:http'\n\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\n\nimport type { WebRequestSource } from './node-request.js'\nimport { sendError } from './send-response.js'\n\n/** What the bracket needs from the branch it wraps. */\nexport interface PluginLifecycleTarget {\n /** The unconverted request. Converted once, here — see the module docstring. */\n source: WebRequestSource\n res: ServerResponse\n requestId: string\n /** Absent ⇒ no plugins are registered, and the bracket costs one object allocation. */\n pluginRunner: PluginRunner | undefined\n /** The 500 message when the handler (or the conversion) throws, e.g. `'Agent handler failed'`. */\n failureMessage: string\n}\n\nfunction messageOf(err: unknown, fallback: string): string {\n return err instanceof Error ? err.message : fallback\n}\n\n/**\n * Run `serve` inside the plugin lifecycle: decorations, `onRequest` (which may short-circuit),\n * the handler, `onError` on a throw, and `onResponse` after the response is written.\n *\n * Mirrors `executeRoute`'s shape deliberately — same `PluginContext`, same short-circuit contract,\n * same `onError` placement. An agent route should not have a lifecycle of its own.\n *\n * Never throws: a handler failure becomes a 500 through the same `sendError` envelope the branches\n * used before, so the caller's `logRequest` still reads a settled `res.statusCode`.\n */\nexport async function serveThroughPluginLifecycle(\n target: PluginLifecycleTarget,\n serve: (request: Request, pluginCtx: PluginContext) => Promise<void>,\n): Promise<void> {\n const { res, requestId, pluginRunner, failureMessage } = target\n\n let request: Request\n try {\n request = target.source.toRequest()\n } catch (err) {\n // A request the adapter cannot represent is a 500, exactly as it was before these branches grew\n // a lifecycle — the conversion used to sit inside the handler's own try.\n sendError(res, 'INTERNAL', messageOf(err, failureMessage), 500, undefined, requestId)\n return\n }\n\n const pluginCtx: PluginContext = { request, response: res, ctx: {}, requestId }\n\n if (pluginRunner) {\n pluginRunner.applyDecorations(pluginCtx.ctx)\n const onRequest = await pluginRunner.runOnRequest(pluginCtx)\n // A hook that answered the request stops the pipeline — the same guarantee `executeRoute` gives.\n if (onRequest.shortCircuited) return\n }\n\n try {\n await serve(request, pluginCtx)\n } catch (err) {\n if (pluginRunner) await pluginRunner.runOnError(pluginCtx, err)\n sendError(res, 'INTERNAL', messageOf(err, failureMessage), 500, undefined, requestId)\n }\n\n // After the response is written, as `executeRoute` does — a hook here observes a completed turn.\n if (pluginRunner) await pluginRunner.runOnResponse(pluginCtx)\n}\n","/**\n * Who is asking, on the Node dispatch path that serves the agent endpoints\n * (usetheokit/theokit#365).\n *\n * `executeRoute` answers this with `subjectFromContext(ctx)`, where `ctx` is the run context built\n * from the application's `server/context.ts` plus plugin decorations. The agent branches build no\n * such context — which is why `mountAgent`'s `subject` option had nowhere to come from and every\n * caller left it out. This builds the same context from the same two sources, so the agent surface\n * reads identity from the seam the routes already read it from rather than from a second one.\n *\n * ## Why it returns a resolver instead of a subject\n *\n * `tryServeAgentAux` runs for EVERY url, including the ones it does not own. Resolving eagerly\n * there would execute the application's `createContext` twice on every route request — once in the\n * aux branch that falls through, once in the route executor. So callers get a memoized thunk and\n * invoke it only on a path they are about to answer, which is the same discipline theokit#400\n * imposed on `source.toRequest()` for the same dispatcher.\n *\n * ## What `createContext` can read here, and what it cannot (usetheokit/theokit#415)\n *\n * **Headers and cookies: yes. The request body: no.**\n *\n * This used to state the opposite as a MUST — \"invoke it before converting the request to a Web\n * `Request`\" — and no caller could honour it. The laziness argued for directly above is what makes\n * it unsatisfiable: the invocation necessarily happens INSIDE the handler, and the handler is\n * entered after `serveThroughPluginLifecycle` has already called `source.toRequest()` at the top of\n * its bracket. `incomingMessageToWebRequest` attaches the Node readable as the request body\n * (`body: webStream, duplex: 'half'`), so by the time an application's `createContext` receives\n * that `IncomingMessage`, the stream is consumed.\n *\n * The contract was written for an EAGER resolver and kept when the resolver became lazy. Both\n * decisions were right on their own; the sentence joining them was not, and it pointed callers at\n * something impossible while implying a capability that does not exist.\n *\n * Practically this costs little — identity is overwhelmingly a header or a cookie, and both survive\n * the conversion untouched. What it costs an application that resolves identity from the BODY is an\n * empty read or a wait for an `'end'` that already fired, which is why saying so plainly matters\n * more than the frequency suggests.\n *\n * Restoring body access would mean resolving eagerly — running the application's `createContext`\n * twice on every route request, which is exactly what the laziness exists to prevent — or buffering\n * every agent request body to replay it, which is a cost paid by every caller for a case almost\n * none has.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { subjectFromContext, type RouteSubject } from '../../core/contracts/route-policy.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\nimport type { LoadModule } from '../scan/module-loader.js'\n\nimport { createServerContext } from './middleware-runner.js'\n\n/** What {@link createAgentSubjectResolver} needs in order to build the run context. */\nexport interface AgentSubjectSources {\n req: IncomingMessage\n res: ServerResponse\n loadModule: LoadModule\n /** The app's `server/` directory. Absent ⇒ there is no `context.ts` to consult. */\n serverDir: string | undefined\n pluginRunner: PluginRunner | undefined\n}\n\n/**\n * Build a memoized resolver for the caller's identity.\n *\n * Decorations are applied ON TOP of the factory's result, matching `executeRoute`: a plugin\n * decoration wins only where `context.ts` did not set the same key.\n *\n * A `createContext` that throws is not swallowed — an application whose identity resolution is\n * broken must not be treated as an anonymous caller, because that reads as a clean refusal and\n * hides the fault. The throw reaches the branch's own error handler and becomes a 500.\n */\nexport function createAgentSubjectResolver(\n sources: AgentSubjectSources,\n): () => Promise<RouteSubject | null> {\n let pending: Promise<RouteSubject | null> | undefined\n return () => {\n pending ??= resolve(sources)\n return pending\n }\n}\n\nasync function resolve(sources: AgentSubjectSources): Promise<RouteSubject | null> {\n const { req, res, loadModule, serverDir, pluginRunner } = sources\n const produced =\n serverDir === undefined ? {} : await createServerContext(req, res, loadModule, serverDir)\n return subjectFrom(produced, pluginRunner)\n}\n\n/**\n * The app's `createContext`, as a host that is not Node sees it.\n *\n * Deliberately NOT `middleware-runner`'s `ContextFactory`, which types its argument as\n * `IncomingMessage`/`ServerResponse`. Those are exactly right for the dev path and wrong here: on\n * every deploy target the pair is what `createWebShim` synthesises over a Web `Request`. Widening\n * to `unknown` says what is actually true at this boundary rather than casting a lie past the\n * type system — the app's own `createContext` is typed by the app, and a generated fragment is the\n * one caller that cannot promise it Node objects.\n */\nexport type HostContextFactory = (args: { request: unknown; response: unknown }) => unknown\n\n/**\n * The half that CALLS an already-resolved context factory (B-185, ADR 0014).\n *\n * {@link createAgentSubjectResolver} does two things: it LOCATES `context.ts` on a filesystem —\n * `existsSync` plus `loadModule`, inside `createServerContext` — and then CALLS what it found. A\n * deploy target with no filesystem can do the second and not the first, so the generator bakes the\n * module as a static import (the way routes, agents and plugins already are) and hands the factory\n * here directly.\n *\n * Measured before this existed: passing `serverDir: undefined` to the resolver above takes its\n * `produced = {}` branch, never touches `req`/`res`/`loadModule`, and returns\n * `subjectFromContext({})` — which is null for every caller. Satisfying its types would have\n * satisfied nothing.\n *\n * `request`/`response` are whatever the host has. On every deploy target that is the\n * `ShimRequest`/`ShimResponse` pair `createWebShim` synthesises over a Web `Request`, which is the\n * same contract routes on those targets have crossed since they were baked.\n */\nexport function createSubjectResolverFromFactory(\n createContext: HostContextFactory | undefined,\n request: unknown,\n response: unknown,\n pluginRunner?: PluginRunner,\n): () => Promise<RouteSubject | null> {\n let pending: Promise<RouteSubject | null> | undefined\n return () => {\n pending ??= (async () =>\n subjectFrom(\n // An app with no `context.ts` bakes no factory, and an anonymous caller is the honest\n // answer — not an error, and not a subject invented to fill the slot.\n createContext === undefined ? {} : await createContext({ request, response }),\n pluginRunner,\n ))()\n return pending\n }\n}\n\n/**\n * Decorations are applied ON TOP of the factory's result, matching `executeRoute`. Shared by both\n * entries so the rule — and the deliberate non-swallowing of a throwing factory, which reaches the\n * branch's own error handler as a 500 rather than reading as a clean refusal — has one home.\n */\nfunction subjectFrom(\n produced: unknown,\n pluginRunner: PluginRunner | undefined,\n): RouteSubject | null {\n const ctx = (produced ?? {}) as Record<string, unknown>\n pluginRunner?.applyDecorations(ctx)\n return subjectFromContext(ctx)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,YAAY,eAAe;AACpC,SAAS,qBAAqB;AASvB,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAC1D,YAAY,OAAe,WAAmB,QAAgB;AAC5D,UAAM,WAAW,KAAK,MAAM,SAAS,0BAA0B,MAAM,EAAE;AACvE,SAAK,OAAO;AAAA,EACd;AACF;AAQA,eAAsB,wBACpB,SACA,KACoB;AACpB,QAAM,WAAsB,CAAC;AAG7B,aAAW,CAAC,OAAO,KAAK,KAAK,QAAQ,QAAQ,GAAG;AAC9C,aAAS,KAAK,OAAO,UAAU,WAAW,MAAM,aAAa,OAAO,OAA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A,WAAU,KAAK,cAAc,GAAG,KAAK,QAAW,SAAS;AACpF;AAAA,EACF;AAEA,QAAM,YAA2B,EAAE,SAAS,UAAU,KAAK,KAAK,CAAC,GAAG,UAAU;AAE9E,MAAI,cAAc;AAChB,iBAAa,iBAAiB,UAAU,GAAG;AAC3C,UAAM,YAAY,MAAM,aAAa,aAAa,SAAS;AAE3D,QAAI,UAAU,eAAgB;AAAA,EAChC;AAEA,MAAI;AACF,UAAM,MAAM,SAAS,SAAS;AAAA,EAChC,SAAS,KAAK;AACZ,QAAI,aAAc,OAAM,aAAa,WAAW,WAAW,GAAG;AAC9D,cAAU,KAAK,YAAYA,WAAU,KAAK,cAAc,GAAG,KAAK,QAAW,SAAS;AAAA,EACtF;AAGA,MAAI,aAAc,OAAM,aAAa,cAAc,SAAS;AAC9D;;;AC3BO,SAAS,2BACd,SACoC;AACpC,MAAI;AACJ,SAAO,MAAM;AACX,gBAAYC,SAAQ,OAAO;AAC3B,WAAO;AAAA,EACT;AACF;AAEA,eAAeA,SAAQ,SAA4D;AACjF,QAAM,EAAE,KAAK,KAAK,YAAY,WAAW,aAAa,IAAI;AAC1D,QAAM,WACJ,cAAc,SAAY,CAAC,IAAI,MAAM,oBAAoB,KAAK,KAAK,YAAY,SAAS;AAC1F,SAAO,YAAY,UAAU,YAAY;AAC3C;AAwDA,SAAS,YACP,UACA,cACqB;AACrB,QAAM,MAAO,YAAY,CAAC;AAC1B,gBAAc,iBAAiB,GAAG;AAClC,SAAO,mBAAmB,GAAG;AAC/B;","names":["resolve","resolve","jsonError","jsonError","agent","resolve","refusal","messageOf","resolve"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/_internal/process-singleton.ts","../src/server/agent/provider-resolver.ts"],"mappings":";AAgCA,IAAM,YAAY;AASX,SAAS,iBAAmC,KAAa,SAAqB;AACnF,QAAM,OAAO,uBAAO,IAAI,YAAY,GAAG;AACvC,QAAM,OAAO;AAEb,QAAM,WAAW,KA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:fs";
|
|
3
|
-
import { dirname } from "node:path";
|
|
4
|
-
function writeAtomic(path, content) {
|
|
5
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
6
|
-
const randBuf = new Uint8Array(4);
|
|
7
|
-
globalThis.crypto.getRandomValues(randBuf);
|
|
8
|
-
let suffix = "";
|
|
9
|
-
for (const b of randBuf) suffix += b.toString(16).padStart(2, "0");
|
|
10
|
-
const tmp = `${path}.tmp-${process.pid}-${suffix}`;
|
|
11
|
-
writeFileSync(tmp, content, "utf8");
|
|
12
|
-
renameSync(tmp, path);
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export {
|
|
16
|
-
writeAtomic
|
|
17
|
-
};
|
|
18
|
-
//# sourceMappingURL=chunk-IDEZ7FU2.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/_internal/atomic-write.ts"],"mappings":";AASA,SAAS,WAAW,YAAY,qBAAqB;AACrD,SAAS,eAAe;AAkBjB,SAAS,YAAY,MAAc,SAAuB;AAC/D,YAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAK5C,QAAM,UAAU,IAAI,WAAW,CAAC;AAChC,aAAW,OAAO,gBAAgB,OAAO;AACzC,MAAI,SAAS;AACb,aAAW,KAAK,QAAS,WAAU,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AACjE,QAAM,MAAM,GAAG,IAAI,QAAQ,QAAQ,GAAG,IAAI,MAAM;AAChD,gBAAc,KAAK,SAAS,MAAM;AAClC,aAAW,KAAK,IAAI;AACtB;","names":[]}
|