theokit 0.59.0 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{actions-virtual-module-L6SCJLDI.js → actions-virtual-module-345YHSEB.js} +8 -8
- package/dist/{actions-virtual-module-YQBEDNHN.js → actions-virtual-module-XI5IGBF4.js} +4 -4
- package/dist/adapters/agent-mount.d.ts +2 -2
- package/dist/adapters/agent-mount.js +3 -3
- package/dist/adapters/security-headers.d.ts +2 -2
- package/dist/adapters/security-headers.js +1 -1
- package/dist/{agent-X7RDENTI.js → agent-L45EZWPV.js} +3 -3
- package/dist/{app-typed-client-F3YLMV4N.js → app-typed-client-B7QIRDSP.js} +8 -8
- package/dist/{app-typed-client-BE4LZPK2.js → app-typed-client-GVP4V4X3.js} +4 -4
- package/dist/{aws-lambda-VKMYUMP2.js → aws-lambda-2R77AV5F.js} +3 -3
- package/dist/{build-H2UDKBV7.js → build-22OMF3NG.js} +6 -6
- package/dist/{bun-POLTY2HK.js → bun-MAAG4MKW.js} +3 -3
- package/dist/{chunk-CF2DNN5R.js → chunk-45XETXSG.js} +10 -2
- package/dist/chunk-45XETXSG.js.map +1 -0
- package/dist/{chunk-KQ27YDLG.js → chunk-4BQIJ4HE.js} +3 -3
- package/dist/{chunk-JW5UFKQ3.js → chunk-5AGNZXHJ.js} +2 -2
- package/dist/{chunk-IRQGAC4L.js → chunk-5GZROLDV.js} +2 -2
- package/dist/{chunk-IRQGAC4L.js.map → chunk-5GZROLDV.js.map} +1 -1
- package/dist/{chunk-6YRZWT5X.js → chunk-6R6UR64X.js} +9 -9
- package/dist/{chunk-YN4W7LCX.js → chunk-ENRT6DAU.js} +6 -1
- package/dist/chunk-ENRT6DAU.js.map +1 -0
- package/dist/{chunk-BPYMC7SU.js → chunk-EYRWD2AB.js} +2 -2
- package/dist/{chunk-HA35FS7U.js → chunk-FFS7IRZF.js} +2 -2
- package/dist/{chunk-M357ILK5.js → chunk-H2X5T45M.js} +3 -3
- package/dist/{chunk-GO7UWJ47.js → chunk-KPZ2JSAU.js} +53 -26
- package/dist/chunk-KPZ2JSAU.js.map +1 -0
- package/dist/{chunk-IF7CZXPW.js → chunk-KVZQJ3ZM.js} +8 -3
- package/dist/chunk-KVZQJ3ZM.js.map +1 -0
- package/dist/{chunk-VJRPOUKM.js → chunk-L2NSHQOY.js} +4 -4
- package/dist/{chunk-KZ3PXNPT.js → chunk-MIPHNT4J.js} +3 -3
- package/dist/chunk-MIPHNT4J.js.map +1 -0
- package/dist/{chunk-IJER2SYS.js → chunk-OH32SN46.js} +20 -1
- package/dist/{chunk-IJER2SYS.js.map → chunk-OH32SN46.js.map} +1 -1
- package/dist/{chunk-WOANPZBT.js → chunk-Q3UE7WIM.js} +2 -2
- package/dist/{chunk-4OTIXAUY.js → chunk-TMQ52AZR.js} +24 -1
- package/dist/chunk-TMQ52AZR.js.map +1 -0
- package/dist/{chunk-E43VJ3E5.js → chunk-VPX3MS5D.js} +2 -2
- package/dist/{chunk-RPET332G.js → chunk-VV2VU3LJ.js} +2 -2
- package/dist/chunk-VV2VU3LJ.js.map +1 -0
- package/dist/{chunk-35QIWOHT.js → chunk-WFIAYPBH.js} +10 -2
- package/dist/chunk-WFIAYPBH.js.map +1 -0
- package/dist/{chunk-MWPC7EOR.js → chunk-YXEKPMDK.js} +5 -5
- package/dist/{chunk-YGL3H3UW.js → chunk-ZXJAI4J7.js} +34 -11
- package/dist/chunk-ZXJAI4J7.js.map +1 -0
- package/dist/cli/index.js +9 -9
- package/dist/{cloudflare-SIG42OIW.js → cloudflare-F5DNYH4B.js} +3 -3
- package/dist/{deno-deploy-LQAYOOPW.js → deno-deploy-47E7GIME.js} +3 -3
- package/dist/{dev-SJE2GSAC.js → dev-BDODXUEA.js} +22 -17
- package/dist/dev-BDODXUEA.js.map +1 -0
- package/dist/{index-ADEV6pen.d.ts → index-BXGSBlxf.d.ts} +1 -1
- package/dist/index.d.ts +7 -0
- package/dist/index.js +9 -8
- package/dist/index.js.map +1 -1
- package/dist/{info-6WJ3JRNE.js → info-2H7I55YN.js} +3 -3
- package/dist/{internal-api-4FBFRQ4G.js → internal-api-QKWTQ2Q7.js} +4 -4
- package/dist/{internal-api-W5RURFU7.js → internal-api-VRUDDBEG.js} +8 -8
- package/dist/{load-config-BKUAMGO5.js → load-config-VMKOV44Y.js} +3 -3
- package/dist/{mcp-I5HCW4QF.js → mcp-WMZSXQQG.js} +4 -4
- package/dist/{netlify-C2IRCZKI.js → netlify-BJQGPMGY.js} +3 -3
- package/dist/{openapi-WDX3XX2J.js → openapi-SKKXWFX4.js} +3 -3
- package/dist/{preview-PWGO5LUE.js → preview-GUEKVBGL.js} +3 -3
- package/dist/{provider-resolver-VS61zqsw.d.ts → provider-resolver-1aWi_WSz.d.ts} +17 -0
- package/dist/{registry-3LUHO4IB.js → registry-APCN3PSJ.js} +7 -7
- package/dist/{route-config-Cm_ZMA1C.d.ts → route-config-B7FaTSby.d.ts} +1 -1
- package/dist/{route-policy-BxOycCDq.d.ts → route-policy-BHXQDzBF.d.ts} +20 -1
- package/dist/{routes-A2YLFEYC.js → routes-ECCDRHXZ.js} +3 -3
- package/dist/{schema-WKTNTGX6.js → schema-ND7GHPQK.js} +2 -2
- package/dist/{security-headers-Ccj7ncNx.d.ts → security-headers-C2cByfJn.d.ts} +5 -0
- package/dist/server/agent/index.d.ts +17 -2
- package/dist/server/agent/index.js +2 -2
- package/dist/server/define/index.d.ts +5 -4
- package/dist/server/define/index.js +1 -1
- package/dist/server/http/index.d.ts +3 -3
- package/dist/server/http/index.js +3 -3
- package/dist/server/index.d.ts +7 -7
- package/dist/server/index.js +13 -9
- package/dist/server/index.js.map +1 -1
- package/dist/server/security/index.d.ts +2 -2
- package/dist/server/security/index.js +2 -2
- package/dist/server/webhook/index.d.ts +9 -4
- package/dist/server/webhook/index.js +7 -3
- package/dist/{server-boundary-CJIXOPCF.js → server-boundary-7BRS2CWI.js} +4 -4
- package/dist/{server-boundary-WVWEJNUJ.js → server-boundary-OEBKNBEP.js} +8 -8
- package/dist/{start-KEWSYVVU.js → start-AKMBT3DW.js} +9 -9
- package/dist/{vercel-BMCQKCWE.js → vercel-BEDGUVXX.js} +3 -3
- package/dist/vite-plugin/index.js +8 -8
- package/dist/{vite-plugin-TU3HQA43.js → vite-plugin-37OQ5RDR.js} +8 -8
- package/dist/whatsapp-D_Fnl1LX.d.ts +85 -0
- package/package.json +2 -2
- package/dist/chunk-35QIWOHT.js.map +0 -1
- package/dist/chunk-4OTIXAUY.js.map +0 -1
- package/dist/chunk-CF2DNN5R.js.map +0 -1
- package/dist/chunk-GO7UWJ47.js.map +0 -1
- package/dist/chunk-IF7CZXPW.js.map +0 -1
- package/dist/chunk-KZ3PXNPT.js.map +0 -1
- package/dist/chunk-RPET332G.js.map +0 -1
- package/dist/chunk-YGL3H3UW.js.map +0 -1
- package/dist/chunk-YN4W7LCX.js.map +0 -1
- package/dist/dev-SJE2GSAC.js.map +0 -1
- package/dist/webhook-types-DGIjjcaI.d.ts +0 -43
- /package/dist/{actions-virtual-module-L6SCJLDI.js.map → actions-virtual-module-345YHSEB.js.map} +0 -0
- /package/dist/{actions-virtual-module-YQBEDNHN.js.map → actions-virtual-module-XI5IGBF4.js.map} +0 -0
- /package/dist/{agent-X7RDENTI.js.map → agent-L45EZWPV.js.map} +0 -0
- /package/dist/{app-typed-client-F3YLMV4N.js.map → app-typed-client-B7QIRDSP.js.map} +0 -0
- /package/dist/{app-typed-client-BE4LZPK2.js.map → app-typed-client-GVP4V4X3.js.map} +0 -0
- /package/dist/{aws-lambda-VKMYUMP2.js.map → aws-lambda-2R77AV5F.js.map} +0 -0
- /package/dist/{build-H2UDKBV7.js.map → build-22OMF3NG.js.map} +0 -0
- /package/dist/{bun-POLTY2HK.js.map → bun-MAAG4MKW.js.map} +0 -0
- /package/dist/{chunk-KQ27YDLG.js.map → chunk-4BQIJ4HE.js.map} +0 -0
- /package/dist/{chunk-JW5UFKQ3.js.map → chunk-5AGNZXHJ.js.map} +0 -0
- /package/dist/{chunk-6YRZWT5X.js.map → chunk-6R6UR64X.js.map} +0 -0
- /package/dist/{chunk-BPYMC7SU.js.map → chunk-EYRWD2AB.js.map} +0 -0
- /package/dist/{chunk-HA35FS7U.js.map → chunk-FFS7IRZF.js.map} +0 -0
- /package/dist/{chunk-M357ILK5.js.map → chunk-H2X5T45M.js.map} +0 -0
- /package/dist/{chunk-VJRPOUKM.js.map → chunk-L2NSHQOY.js.map} +0 -0
- /package/dist/{chunk-WOANPZBT.js.map → chunk-Q3UE7WIM.js.map} +0 -0
- /package/dist/{chunk-E43VJ3E5.js.map → chunk-VPX3MS5D.js.map} +0 -0
- /package/dist/{chunk-MWPC7EOR.js.map → chunk-YXEKPMDK.js.map} +0 -0
- /package/dist/{cloudflare-SIG42OIW.js.map → cloudflare-F5DNYH4B.js.map} +0 -0
- /package/dist/{deno-deploy-LQAYOOPW.js.map → deno-deploy-47E7GIME.js.map} +0 -0
- /package/dist/{info-6WJ3JRNE.js.map → info-2H7I55YN.js.map} +0 -0
- /package/dist/{internal-api-4FBFRQ4G.js.map → internal-api-QKWTQ2Q7.js.map} +0 -0
- /package/dist/{internal-api-W5RURFU7.js.map → internal-api-VRUDDBEG.js.map} +0 -0
- /package/dist/{load-config-BKUAMGO5.js.map → load-config-VMKOV44Y.js.map} +0 -0
- /package/dist/{mcp-I5HCW4QF.js.map → mcp-WMZSXQQG.js.map} +0 -0
- /package/dist/{netlify-C2IRCZKI.js.map → netlify-BJQGPMGY.js.map} +0 -0
- /package/dist/{openapi-WDX3XX2J.js.map → openapi-SKKXWFX4.js.map} +0 -0
- /package/dist/{preview-PWGO5LUE.js.map → preview-GUEKVBGL.js.map} +0 -0
- /package/dist/{registry-3LUHO4IB.js.map → registry-APCN3PSJ.js.map} +0 -0
- /package/dist/{routes-A2YLFEYC.js.map → routes-ECCDRHXZ.js.map} +0 -0
- /package/dist/{schema-WKTNTGX6.js.map → schema-ND7GHPQK.js.map} +0 -0
- /package/dist/{server-boundary-CJIXOPCF.js.map → server-boundary-7BRS2CWI.js.map} +0 -0
- /package/dist/{server-boundary-WVWEJNUJ.js.map → server-boundary-OEBKNBEP.js.map} +0 -0
- /package/dist/{start-KEWSYVVU.js.map → start-AKMBT3DW.js.map} +0 -0
- /package/dist/{vercel-BMCQKCWE.js.map → vercel-BEDGUVXX.js.map} +0 -0
- /package/dist/{vite-plugin-TU3HQA43.js.map → vite-plugin-37OQ5RDR.js.map} +0 -0
|
@@ -25,17 +25,17 @@ import {
|
|
|
25
25
|
parseAgentRequestBody,
|
|
26
26
|
readAgentPolicy,
|
|
27
27
|
subjectFromContext
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-KVZQJ3ZM.js";
|
|
29
29
|
import {
|
|
30
30
|
getApprovalRegistry
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-WFIAYPBH.js";
|
|
32
32
|
import {
|
|
33
33
|
sendError,
|
|
34
34
|
validateCsrfRequest
|
|
35
35
|
} from "./chunk-L4TB6FXQ.js";
|
|
36
36
|
import {
|
|
37
37
|
generateNonce
|
|
38
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-VV2VU3LJ.js";
|
|
39
39
|
|
|
40
40
|
// src/config/resolve-plugin-specifiers.ts
|
|
41
41
|
import { isAbsolute, resolve } from "path";
|
|
@@ -867,4 +867,4 @@ export {
|
|
|
867
867
|
applyNonceToInlineScripts,
|
|
868
868
|
setupSsrDevMiddleware
|
|
869
869
|
};
|
|
870
|
-
//# sourceMappingURL=chunk-
|
|
870
|
+
//# sourceMappingURL=chunk-L2NSHQOY.js.map
|
|
@@ -9,6 +9,7 @@ import "reflect-metadata";
|
|
|
9
9
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
10
10
|
import { basename, dirname, join, relative, resolve } from "path";
|
|
11
11
|
import { pathToFileURL } from "url";
|
|
12
|
+
import { PUBLIC_ROUTE_METADATA } from "@theokit/http";
|
|
12
13
|
import {
|
|
13
14
|
CONTROLLER_PREFIX,
|
|
14
15
|
ROUTE_METHODS,
|
|
@@ -84,7 +85,6 @@ function assertControllerPathsReachable(loaded) {
|
|
|
84
85
|
throw new UnreachableControllerPathError(cls.name || "a controller", prefix, sourceFile);
|
|
85
86
|
}
|
|
86
87
|
}
|
|
87
|
-
var PUBLIC_ROUTE_METADATA = "theokit:public";
|
|
88
88
|
var UndeclaredControllerAccessError = class extends Error {
|
|
89
89
|
constructor(controller, method, verb, file) {
|
|
90
90
|
super(
|
|
@@ -102,7 +102,7 @@ var UndeclaredControllerAccessError = class extends Error {
|
|
|
102
102
|
``,
|
|
103
103
|
` Or state that it is open on purpose \u2014 a health check, an OAuth callback:`,
|
|
104
104
|
``,
|
|
105
|
-
` @
|
|
105
|
+
` @Public() // from '@theokit/http'`,
|
|
106
106
|
``,
|
|
107
107
|
` Both are declarations. What is refused is neither.`
|
|
108
108
|
].join("\n")
|
|
@@ -186,4 +186,4 @@ export {
|
|
|
186
186
|
emitControllerArtifacts,
|
|
187
187
|
describeControllerArtifacts
|
|
188
188
|
};
|
|
189
|
-
//# sourceMappingURL=chunk-
|
|
189
|
+
//# sourceMappingURL=chunk-MIPHNT4J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/commands/build/emit-controllers.ts"],"sourcesContent":["import 'reflect-metadata'\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { PUBLIC_ROUTE_METADATA } from '@theokit/http'\nimport {\n CONTROLLER_PREFIX,\n ROUTE_METHODS,\n USE_GUARDS,\n getMeta,\n isControllerClass,\n transformControllerSource,\n} from '@theokit/http'\n\nimport { findControllerFiles } from '../../../server/http/controller-dispatch.js'\n\n/**\n * theokit#123 — compile `server/controllers/**` into `dist` so production can serve them.\n *\n * ## Why production needed anything at all\n *\n * #122 made decorator controllers first-class in `theokit dev`, where a Vite `enforce:'pre'` swc\n * transform compiles them on the fly — parameter decorators (`@Body`/`@Param`/`@Query`) emit\n * metadata esbuild cannot produce. `theokit start` has no Vite and no transform, so an uncompiled\n * `.controller.ts` simply cannot load, and controller routes 404'd in production while working in\n * dev. That split is the whole issue.\n *\n * ## Why compile at BUILD time rather than load with swc at runtime\n *\n * `loadControllerWithSwc` would work in production and was the smaller diff. It is refused on\n * purpose: `@swc/core` is a peer dependency and a native binary, so that path makes every deployed\n * app carry a compiler it only needs once, and turns a missing optional peer into a runtime 404\n * instead of a build failure. Compilation belongs where the rest of the build already is — and it\n * is what the issue's root-cause note asks for.\n *\n * ## Why NOT in `generateManifest`\n *\n * ADR-5 keeps controllers out of the manifest, and that is preserved here: the manifest is the\n * deploy-adapter contract, and adding a parallel route source to it would ripple through every\n * adapter. This emits a SEPARATE artifact (`dist/controllers.json` + `dist/controllers/*.mjs`) that\n * only the Node start path reads. An adapter that knows nothing about controllers keeps working\n * exactly as before.\n */\n\n/** The build artifact `theokit start` reads to find compiled controllers. */\ninterface ControllerBuildManifest {\n version: 1\n /** Emitted module paths, relative to `distDir`, in scan order. */\n modules: string[]\n}\n\nexport const CONTROLLER_MANIFEST_FILE = 'controllers.json'\nconst CONTROLLER_OUT_DIR = 'controllers'\n\n/**\n * Compile every controller under `<serverDir>/controllers` into `<distDir>/controllers`.\n *\n * No controllers ⇒ **no artifact at all** (not an empty one). `theokit start` treats a missing\n * manifest as \"this app has no controllers\" and skips the whole branch, so a routes-only app pays\n * nothing and its `dist` is byte-identical to before — the ADR-5 posture, kept.\n */\n/**\n * Point a compiled controller's RELATIVE imports back at the app's own source tree.\n *\n * theokit#516 — controllers are compiled into `<distDir>/controllers` because parameter decorators\n * need metadata only swc emits. File routes are never compiled: in production `importUserModule`\n * loads them straight from the source, which is why THEIR relative imports resolve. A controller's\n * did not — `../auth/index.js` resolved from `dist`, where the app does not exist — so a controller\n * that imported anything of the app's worked under `theokit dev` and failed the build.\n *\n * Rewriting to an ABSOLUTE path into the source tree is the smallest fix that keeps one definition\n * of every module. The alternatives each cost more than they buy: copying the app's modules beside\n * the controller duplicates them, and bundling inlines them, so in both a module with state exists\n * twice and the two copies drift.\n *\n * The extension is mapped back to what is on disk. TypeScript source writes `./x.js` for `./x.ts`\n * (NodeNext), and the emitted module has to name the file that exists, since it is loaded by the\n * same `importUserModule` path a file route takes — `.ts` included.\n *\n * BARE specifiers are left exactly as written. `@theokit/http`, `zod` and every other package\n * resolve through `node_modules` from any directory, so rewriting them would replace something that\n * works with a path that pins a version.\n */\nfunction rewriteLocalImports(code: string, sourceFile: string): string {\n const fromDir = dirname(sourceFile)\n return code.replace(\n /(\\bfrom\\s*|\\bimport\\s*\\(\\s*)(['\"])(\\.[^'\"]*)\\2/g,\n (whole, lead: string, quote: string, spec: string) => {\n const resolved = resolve(fromDir, spec)\n const onDisk = existingSourcePath(resolved)\n if (onDisk === undefined) return whole\n return `${lead}${quote}${pathToFileURL(onDisk).href}${quote}`\n },\n )\n}\n\n/**\n * The file a compiled specifier names, as it exists on disk — or `undefined` when nothing does.\n *\n * `./x.js` may be `x.ts`, `x.tsx`, a literal `x.js`, or a directory holding `index.*`. Returning\n * `undefined` for the rest is deliberate: a specifier this cannot resolve is left UNCHANGED, so the\n * runtime reports the missing module by the name the author wrote. Substituting a guess would move\n * the error somewhere the author never typed.\n */\nfunction existingSourcePath(resolved: string): string | undefined {\n const withoutExt = resolved.replace(/\\.(js|mjs|cjs)$/, '')\n const candidates = [\n ...(resolved === withoutExt ? [] : [`${withoutExt}.ts`, `${withoutExt}.tsx`, resolved]),\n ...(resolved === withoutExt ? [`${resolved}.ts`, `${resolved}.tsx`, `${resolved}.js`] : []),\n join(withoutExt, 'index.ts'),\n join(withoutExt, 'index.tsx'),\n join(withoutExt, 'index.js'),\n ]\n return candidates.find((c) => existsSync(c))\n}\n\n/**\n * The URL prefix both runtimes gate the controller fall-through on.\n *\n * `start/handlers.ts` and `vite-plugin/api-middleware.ts` each return early unless the request URL\n * starts with `/api/`, so a controller declaring anything else describes a path that branch never\n * visits. Written here as a constant rather than a literal in the check, because the day that gate\n * moves this is the line that has to move with it.\n */\nconst SERVED_PREFIX = 'api'\n\n/**\n * A controller compiled successfully and mounted at a path the runtime never routes to.\n *\n * Its own class so a caller can tell it from a compile failure: the source is fine, the decorators\n * are fine, and the app would start — the route simply answers 404 forever. That is the failure\n * this module's docblock already refuses for compile errors, reached by a different road.\n *\n * Measured against `theokit@0.56.0`: `@Controller('probe')` built clean, emitted a module, wrote\n * the manifest, and `/api/probe` returned 404. `/probe` returned **200** — the SPA fallback serving\n * `index.html`, so the status code agreed with success while the body was a web page. A defect that\n * survives a status-code check is exactly the kind a build gate has to catch instead.\n */\nexport class UnreachableControllerPathError extends Error {\n override readonly name = 'UnreachableControllerPathError'\n constructor(\n readonly controller: string,\n readonly declaredPath: string,\n readonly file: string,\n ) {\n super(\n [\n `${controller} declares \\`@Controller('${declaredPath}')\\`, which this runtime never routes to.`,\n ``,\n ` ${file}`,\n ``,\n ` Controller routes are served from a fall-through that runs only for URLs under`,\n ` \\`/${SERVED_PREFIX}/\\` — a file-route miss is what reaches it. A path outside that`,\n ` prefix compiles, emits, and then answers 404 for the life of the app.`,\n ``,\n ` Write it as:`,\n ``,\n ` @Controller('${SERVED_PREFIX}/${declaredPath.replace(/^\\/+/, '')}')`,\n ``,\n ` Refused at build rather than left to 404, for the reason this module already refuses a`,\n ` compile error: shipping a route nothing can reach, with nothing pointing back at why.`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Is `prefix` reachable from the served path?\n *\n * `'api'`, `'/api'`, `'api/x'` and `'/api/x'` are the same URL written four ways, so all four pass:\n * the gate is about reachability, not spelling. A prefix that merely STARTS with the letters —\n * `'apiary'` — is not, which is why the check is segment-wise rather than a `startsWith`.\n */\nfunction isReachable(prefix: string): boolean {\n const segments = prefix.split('/').filter((s) => s.length > 0)\n return segments[0] === SERVED_PREFIX\n}\n\n/**\n * Refuse any emitted controller whose declared path the runtime cannot route to.\n *\n * Reads the prefix off the COMPILED module rather than the source: the decorator metadata is what\n * the runtime will actually match on, and a regex over source text would disagree with it the first\n * time someone writes the prefix as anything other than a literal.\n */\nfunction assertControllerPathsReachable(\n loaded: readonly { cls: ControllerClass; sourceFile: string }[],\n): void {\n for (const { cls, sourceFile } of loaded) {\n const meta = getMeta<{ prefix?: string }>(CONTROLLER_PREFIX, cls)\n const prefix = meta?.prefix ?? ''\n if (isReachable(prefix)) continue\n throw new UnreachableControllerPathError(cls.name || 'a controller', prefix, sourceFile)\n }\n}\n\n/**\n * The metadata key an explicitly-open controller route sets — IMPORTED, no longer redeclared.\n *\n * The counterpart of `'public'` on the file path, and it exists for the same routes: a health check\n * a load balancer calls with no session, an OAuth callback the provider redirects to.\n *\n * This was a local `const` under a docblock arguing that exporting it \"would publish a new surface\n * for a string that appears once per open route\". #574 measured the cost of that reasoning in the\n * first real adopter — 8 controllers, 6 hand-written copies of `'theokit:public'` — and\n * `@theokit/http` now exports both the key and `@Public()`. Keeping a second copy here would leave\n * the gate and the decorator agreeing by coincidence rather than by construction.\n *\n * It is an opt-out, never a default. A route that is open says so in the file, where review sees\n * it; a route nobody thought about is the one that ships open, which is the whole reason ADR 0001\n * made absence stop meaning open on the file path.\n */\n\n/**\n * A controller route that declares no access decision at all.\n *\n * Distinct from a guard REFUSING a request — that is the system working. This is a route where\n * nobody wrote down whether it should be reachable, which on the file path is a build failure and\n * on the decorator path was, until now, silence.\n *\n * Measured against theokit@0.56.0: a `@Controller` with no guard answered 200 to a request with no\n * session, while the file route it would replace answered 403, on the same server in the same\n * second. The mechanism was never missing — `@UseGuards` works and returns `403 FORBIDDEN`. Only\n * the refusal of absence was.\n */\nexport class UndeclaredControllerAccessError extends Error {\n override readonly name = 'UndeclaredControllerAccessError'\n constructor(\n readonly controller: string,\n readonly method: string,\n readonly verb: string,\n readonly file: string,\n ) {\n super(\n [\n `${controller}.${method}() serves ${verb} and declares no access decision.`,\n ``,\n ` ${file}`,\n ``,\n ` A file route with no \\`.policy\\` fails this build for the same reason (ADR 0001): a route`,\n ` nobody thought about is the one that ships open. The decorator path now says the same.`,\n ``,\n ` Require a session:`,\n ``,\n ` @UseGuards(AuthGuard) // on the method, or on the @Controller to cover all of them`,\n ``,\n ` Or state that it is open on purpose — a health check, an OAuth callback:`,\n ``,\n ` @Public() // from '@theokit/http'`,\n ``,\n ` Both are declarations. What is refused is neither.`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Refuse any controller route whose access decision nobody wrote down.\n *\n * A guard on the CLASS covers every method under it, which is the shape most controllers want and\n * mirrors how `@UseGuards` already behaves at runtime — the gate must agree with the dispatcher or\n * it would refuse code that works.\n *\n * Read off the compiled module for the reason the prefix check is: decorator metadata is what the\n * runtime matches on. The per-method key lives on the CLASS with the property name, not on the\n * prototype and not on the descriptor — measured, after both of those returned `undefined`.\n */\nfunction assertControllerAccessDeclared(\n loaded: readonly { cls: ControllerClass; sourceFile: string }[],\n): void {\n for (const { cls, sourceFile } of loaded) {\n // Class level covers every method under it — for BOTH forms. A guard on the class already\n // behaves that way at runtime, and a controller whose routes are all open (a health group, an\n // OAuth callback group) must be declarable once for the same reason. Checking one at class\n // level and not the other would refuse code that is correct.\n if (getMeta<unknown[]>(USE_GUARDS, cls) !== undefined) continue\n if (Reflect.getMetadata(PUBLIC_ROUTE_METADATA, cls) === true) continue\n\n const routes = getMeta<{ verb: string; propertyKey: string }[]>(ROUTE_METHODS, cls) ?? []\n for (const { verb, propertyKey } of routes) {\n if (getMeta<unknown[]>(USE_GUARDS, cls, propertyKey) !== undefined) continue\n // `Reflect` directly, not `getMeta`: `@SetMetadata` writes through `Reflect.defineMetadata`\n // with the key as given, and `getMeta` is typed for the symbol keys this package defines.\n if (Reflect.getMetadata(PUBLIC_ROUTE_METADATA, cls, propertyKey) === true) continue\n throw new UndeclaredControllerAccessError(\n cls.name || 'a controller',\n propertyKey,\n verb,\n sourceFile,\n )\n }\n }\n}\n\n/**\n * Load every emitted controller class once, for both checks below.\n *\n * One pass rather than one per check: the alternative loads each module twice and doubles the\n * surface on which a stale import could fool a gate.\n *\n * The `?t=` is a cache-bust. `emitControllerArtifacts` runs once per build process today, so it\n * changes nothing now — it is here because these are SECURITY gates, and the failure mode if a\n * watch mode is ever added is one that reads metadata from a version of the file that no longer\n * exists and passes it. `parsimony-ladder.md` is explicit that security is not what the ladder\n * trims, and the cost is a query parameter.\n */\nasync function loadEmittedControllers(\n emitted: readonly { modulePath: string; sourceFile: string }[],\n): Promise<{ cls: ControllerClass; sourceFile: string }[]> {\n const out: { cls: ControllerClass; sourceFile: string }[] = []\n for (const { modulePath, sourceFile } of emitted) {\n const url = `${pathToFileURL(modulePath).href}?t=${Date.now()}`\n const mod: Record<string, unknown> = await import(url)\n for (const exported of Object.values(mod)) {\n if (typeof exported !== 'function' || !isControllerClass(exported)) continue\n out.push({ cls: exported as ControllerClass, sourceFile })\n }\n }\n return out\n}\n\n/** A class carrying `@Controller` metadata — narrowed once so both checks read the same shape. */\ntype ControllerClass = (new (...args: never[]) => unknown) & { name: string }\n\nexport async function emitControllerArtifacts(opts: {\n serverDir: string\n distDir: string\n}): Promise<ControllerBuildManifest | null> {\n const controllersDir = resolve(opts.serverDir, CONTROLLER_OUT_DIR)\n const files = findControllerFiles(controllersDir)\n if (files.length === 0) return null\n\n const outDir = resolve(opts.distDir, CONTROLLER_OUT_DIR)\n mkdirSync(outDir, { recursive: true })\n\n const modules: string[] = []\n const emitted: { modulePath: string; sourceFile: string }[] = []\n for (const file of files) {\n // Errors are NOT caught. A controller that fails to compile must fail the BUILD — swallowing it\n // here would ship an app whose routes 404 at runtime with nothing pointing back at the cause,\n // which is the exact failure mode this issue reports (error-handling.md § 2).\n const compiled = await transformControllerSource(readFileSync(file, 'utf-8'), file)\n const code = rewriteLocalImports(compiled, file)\n\n // Mirror the source tree under `dist/controllers` so two files with the same basename in\n // different folders cannot overwrite each other.\n const rel = relative(controllersDir, file).replace(/\\.controller\\.ts$/, '.controller.mjs')\n const outPath = join(outDir, rel)\n mkdirSync(dirname(outPath), { recursive: true })\n writeFileSync(outPath, code)\n modules.push(`${CONTROLLER_OUT_DIR}/${rel.split('\\\\').join('/')}`)\n emitted.push({ modulePath: outPath, sourceFile: file })\n }\n\n // AFTER writing, because reading the prefix means loading the compiled module — and a module that\n // failed to compile has already thrown above. Before the manifest, so a refused build leaves no\n // artifact claiming a route that does not answer.\n const loaded = await loadEmittedControllers(emitted)\n assertControllerPathsReachable(loaded)\n assertControllerAccessDeclared(loaded)\n\n const manifest: ControllerBuildManifest = { version: 1, modules }\n writeFileSync(\n resolve(opts.distDir, CONTROLLER_MANIFEST_FILE),\n JSON.stringify(manifest, null, 2) + '\\n',\n )\n return manifest\n}\n\n/** Human-facing summary for the build log (mirrors the cron/job emitters). */\nexport function describeControllerArtifacts(manifest: ControllerBuildManifest | null): string {\n if (manifest === null) return 'controllers: none'\n const names = manifest.modules.map((m) => basename(m, '.mjs')).join(', ')\n return `controllers: ${manifest.modules.length} compiled (${names})`\n}\n"],"mappings":";;;;;;;AAAA,OAAO;AAEP,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,UAAU,SAAS,MAAM,UAAU,eAAe;AAC3D,SAAS,qBAAqB;AAE9B,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuCA,IAAM,2BAA2B;AACxC,IAAM,qBAAqB;AA+B3B,SAAS,oBAAoB,MAAc,YAA4B;AACrE,QAAM,UAAU,QAAQ,UAAU;AAClC,SAAO,KAAK;AAAA,IACV;AAAA,IACA,CAAC,OAAO,MAAc,OAAe,SAAiB;AACpD,YAAM,WAAW,QAAQ,SAAS,IAAI;AACtC,YAAM,SAAS,mBAAmB,QAAQ;AAC1C,UAAI,WAAW,OAAW,QAAO;AACjC,aAAO,GAAG,IAAI,GAAG,KAAK,GAAG,cAAc,MAAM,EAAE,IAAI,GAAG,KAAK;AAAA,IA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4B,UAAkD;AAC5F,MAAI,aAAa,KAAM,QAAO;AAC9B,QAAM,QAAQ,SAAS,QAAQ,IAAI,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,EAAE,KAAK,IAAI;AACxE,SAAO,gBAAgB,SAAS,QAAQ,MAAM,cAAc,KAAK;AACnE;","names":[]}
|
|
@@ -207,6 +207,24 @@ function jsonError(status, code, message) {
|
|
|
207
207
|
headers: { "content-type": "application/json" }
|
|
208
208
|
});
|
|
209
209
|
}
|
|
210
|
+
async function handleSubscribe(request, platform, config) {
|
|
211
|
+
const subscribe = config.subscribe?.[platform];
|
|
212
|
+
if (subscribe === void 0) {
|
|
213
|
+
return jsonError(
|
|
214
|
+
405,
|
|
215
|
+
"SUBSCRIBE_UNSUPPORTED",
|
|
216
|
+
`Platform '${platform}' declared no subscribe handshake. Add one to \`subscribe\` (e.g. whatsappSubscribe({ verifyToken })).`
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
const result = await subscribe(request);
|
|
220
|
+
if (!result.ok) {
|
|
221
|
+
return jsonError(401, "INVALID_SUBSCRIBE", `Subscribe handshake failed: ${result.reason}`);
|
|
222
|
+
}
|
|
223
|
+
return new Response(result.challenge, {
|
|
224
|
+
status: 200,
|
|
225
|
+
headers: { "content-type": "text/plain; charset=utf-8" }
|
|
226
|
+
});
|
|
227
|
+
}
|
|
210
228
|
async function handleChannelWebhook(request, urlPath, config) {
|
|
211
229
|
const parsed = parseChannelPath(urlPath);
|
|
212
230
|
if (parsed === null) {
|
|
@@ -223,6 +241,7 @@ async function handleChannelWebhook(request, urlPath, config) {
|
|
|
223
241
|
`No validator configured for platform '${parsed.platform}'.`
|
|
224
242
|
);
|
|
225
243
|
}
|
|
244
|
+
if (request.method === "GET") return await handleSubscribe(request, parsed.platform, config);
|
|
226
245
|
const verify = config.validators[parsed.platform];
|
|
227
246
|
const verifyResult = await verify(request.clone());
|
|
228
247
|
if (!verifyResult.ok) {
|
|
@@ -289,4 +308,4 @@ export {
|
|
|
289
308
|
streamAgentTurnInProcess,
|
|
290
309
|
InProcessApprovalRequiredError
|
|
291
310
|
};
|
|
292
|
-
//# sourceMappingURL=chunk-
|
|
311
|
+
//# sourceMappingURL=chunk-OH32SN46.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/agent/workflow-tool.ts","../src/server/agent/acp-tool.ts","../src/server/agent/vendor-agent-tool.ts","../src/server/agent/code-mode.ts","../src/server/agent/channel-webhook.ts","../src/server/agent/index.ts","../src/server/agent/mcp-stdio.ts"],"mappings":";;;;;;;;AASA,SAAS,SAAS;AAuBlB,IAAM,mBAAmB,oBAAI,IAAI,CAAC,UAAU,SAAS,aAAa,UAAU,CAAC;AAOtE,SAAS,mBAAmB,UAAwB,QAAwC;AACjG,QAAM,QAAS,UAAmD;AAClE,MAAI,OAAO,UAAU,YAAY;AAC/B,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AAEA,QAAM,cAAc,OAAO,eAAe,EAAE,YAAY,CAAC,CAAC;AAE1D,SAAO,gBAAgB;AAAA,IACrB,MAAM,OAAO;AAAA,IACb,aAAa,OAAO;AAAA,IACpB;AAAA,IACA,SAAS,OAAO,UAAoC;AAClD,YAAM,MAAM,MAAM,SAAS,IAAI,KAAK;AACpC,UAAI,iBAAiB,IAAI,IAAI,MAAM,GAAG;AACpC,cAAM,IAAI;AAAA,UACR,sBAAsB,KAAK,UAAU,OAAO,IAAI,CAAC,mBAC/C,IAAI,QAAQ,IAAI,IAAI,KAAK,OAAO,EAClC,uBAAuB,IAAI,MAAM;AAAA,QACnC;AAAA,MACF;AACA,aAAO,OAAO,IAAI,WAAW,WAAW,IAAI,SAAS,KAAK,UAAU,IAAI,MAAM;AAAA,IAChF;AAAA,EACF,CAAC;AACH;;;AC1DA,SAAS,aAAuC;AAGhD,SAAS,iBAAoC;AAItC,IAAM,mBAAN,MAA+C;AAAA;AAAA,EAEnC;AAAA,EAEjB,YAAY,SAAiB,OAAi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AEA,QAAM,OAAO,OAAO,QAAQ;AAC5B,QAAM,OAAmB;AAAA,IACvB;AAAA,IACA,aACE,OAAO,eACP;AAAA,IACF,aAAa;AAAA,MACX,MAAM;AAAA,MACN,YAAY,EAAE,MAAM,EAAE,MAAM,UAAU,aAAa,kCAAkC,EAAE;AAAA,MACvF,UAAU,CAAC,MAAM;AAAA,IACnB;AAAA,IACA,SAAS,OAAO,UAAoD;AAClE,YAAM,OAAO,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;AAC3D,YAAM,SAAS,MAAM,OAAO,QAAQ,IAAI,MAAM,GAAG;AACjD,aAAO,OAAO,WAAW,WAAW,SAAS,KAAK,UAAU,MAAM;AAAA,IACpE;AAAA,EACF;AACA,SAAO,EAAE,MAAM,cAAc,6BAA6B,OAAO,OAAO,IAAI,EAAE;AAChF;;;
|
|
1
|
+
{"version":3,"sources":["../src/server/agent/workflow-tool.ts","../src/server/agent/acp-tool.ts","../src/server/agent/vendor-agent-tool.ts","../src/server/agent/code-mode.ts","../src/server/agent/channel-webhook.ts","../src/server/agent/index.ts","../src/server/agent/mcp-stdio.ts"],"mappings":";;;;;;;;AASA,SAAS,SAAS;AAuBlB,IAAM,mBAAmB,oBAAI,IAAI,CAAC,UAAU,SAAS,aAAa,UAAU,CAAC;AAOtE,SAAS,mBAAmB,UAAwB,QAAwC;AACjG,QAAM,QAAS,UAAmD;AAClE,MAAI,OAAO,UAAU,YAAY;AAC/B,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AAEA,QAAM,cAAc,OAAO,eAAe,EAAE,YAAY,CAAC,CAAC;AAE1D,SAAO,gBAAgB;AAAA,IACrB,MAAM,OAAO;AAAA,IACb,aAAa,OAAO;AAAA,IACpB;AAAA,IACA,SAAS,OAAO,UAAoC;AAClD,YAAM,MAAM,MAAM,SAAS,IAAI,KAAK;AACpC,UAAI,iBAAiB,IAAI,IAAI,MAAM,GAAG;AACpC,cAAM,IAAI;AAAA,UACR,sBAAsB,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O,UAAU,KAAK,eAAe,4BAA4B;AAAA,EACnE;AAEA,QAAM,OAAO,UAAU,EAAE,OAAO,OAAO,OAAO,UAAU,OAAO,UAAU,QAAQ,CAAC;AAClF,SAAO,IAAI,SAAS,KAAK,UAAU,EAAE,IAAI,KAAK,CAAC,GAAG;AAAA,IAChD,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,EAChD,CAAC;AACH;;;AChIA,SAAS,0BAA0B,sCAAsC;;;ACTzE,eAAsB,mBACpB,MACA,KACA,MACA,eAAuC,CAAC,GAChB;AACxB,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAO,KAAK,UAAU;AAAA,MACpB,SAAS;AAAA,MACT,IAAI;AAAA,MACJ,OAAO,EAAE,MAAM,QAAQ,SAAS,cAAc;AAAA,IAChD,CAAC;AAAA,EACH;AACA,QAAM,WAAW,MAAM,iBAAiB,KAAK,MAAM,MAAM,YAAY;AACrE,QAAM,UAAmB,MAAM,SAAS,KAAK;AAC7C,SAAO,KAAK,UAAU,OAAO;AAC/B;AAcA,eAAsB,cACpB,KACA,MACA,cACA,SACe;AACf,mBAAiB,QAAQ,QAAQ,OAAO;AACtC,UAAM,MAAM,MAAM,mBAAmB,MAAM,KAAK,MAAM,YAAY;AAClE,QAAI,QAAQ,KAAM,SAAQ,MAAM,GAAG,GAAG;AAAA,CAAI;AAAA,EAC5C;AACF;","names":["tool"]}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
dispatchCsrfWarn,
|
|
3
3
|
incomingMessageToWebRequest,
|
|
4
4
|
sendError
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-5AGNZXHJ.js";
|
|
6
6
|
import {
|
|
7
7
|
enforceCsrf
|
|
8
8
|
} from "./chunk-P6OS7652.js";
|
|
@@ -130,4 +130,4 @@ export {
|
|
|
130
130
|
scanControllerModules,
|
|
131
131
|
dispatchControllerRequest
|
|
132
132
|
};
|
|
133
|
-
//# sourceMappingURL=chunk-
|
|
133
|
+
//# sourceMappingURL=chunk-Q3UE7WIM.js.map
|
|
@@ -87,6 +87,29 @@ var theoConfigSchema = z.object({
|
|
|
87
87
|
* is still distinguishable from "somebody said localhost".
|
|
88
88
|
*/
|
|
89
89
|
host: z.union([z.string(), z.boolean()]).optional(),
|
|
90
|
+
/**
|
|
91
|
+
* Hostnames `theokit dev` will answer for, beyond the loopback names Vite permits out of the
|
|
92
|
+
* box — Vite's `server.allowedHosts` (#555).
|
|
93
|
+
*
|
|
94
|
+
* This is NOT {@link host}. That one is the bind ADDRESS; this one is the `Host` header check
|
|
95
|
+
* that runs after the connection is accepted, so binding `0.0.0.0` does not make a tunnelled
|
|
96
|
+
* request pass. Developing against any webhook platform needs a public URL, which means a
|
|
97
|
+
* tunnel or a reverse proxy, which means a `Host` the check refuses by default — and a
|
|
98
|
+
* scaffolded app has no `vite.config.ts` in which to allow it.
|
|
99
|
+
*
|
|
100
|
+
* Vite's own matching rules apply, not globs: a leading dot allows a domain and its
|
|
101
|
+
* subdomains (`.trycloudflare.com`), and anything else is compared literally.
|
|
102
|
+
*
|
|
103
|
+
* `true` disables the check. It is here because a tunnel that mints a fresh random hostname
|
|
104
|
+
* per run cannot be listed, and the alternative — editing config between runs — is what makes
|
|
105
|
+
* people reach for the production server instead. It also removes the protection against
|
|
106
|
+
* DNS-rebinding that the check exists to provide, so prefer the list whenever the hostname is
|
|
107
|
+
* knowable. `theokit start` is unaffected either way: this is dev-server-only.
|
|
108
|
+
*
|
|
109
|
+
* Deliberately NOT defaulted — an empty array is a decision that blocks every host including
|
|
110
|
+
* the loopback names, so "nobody said" has to stay distinguishable from "somebody said none".
|
|
111
|
+
*/
|
|
112
|
+
allowedHosts: z.union([z.array(z.string()), z.literal(true)]).optional(),
|
|
90
113
|
/** Automatically open browser on `theokit dev`. */
|
|
91
114
|
open: z.union([z.boolean(), z.string()]).default(false),
|
|
92
115
|
/** Exit if port is already in use instead of trying next available. */
|
|
@@ -280,4 +303,4 @@ var theoConfigSchema = z.object({
|
|
|
280
303
|
export {
|
|
281
304
|
theoConfigSchema
|
|
282
305
|
};
|
|
283
|
-
//# sourceMappingURL=chunk-
|
|
306
|
+
//# sourceMappingURL=chunk-TMQ52AZR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config/schema.ts","../src/core/contracts/theo-ui-theme.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport { THEME_NAME_PATTERN } from '../core/contracts/theo-ui-theme.js'\nimport { servicesConfigSchema } from '../services/index.js'\n\nimport {\n cacheSchema,\n loggingSchema,\n observabilitySchema,\n rateLimitSchema,\n securitySchema,\n storageSchema,\n uploadSchema,\n type FormatErrorContext,\n type FormatErrorHook,\n} from './schemas/index.js'\n\n// Re-export per-concern schemas + types so downstream consumers\n// (`adapters/*`, vite-plugin, generators) keep their existing imports valid.\n// Per plan T2.3 — pure structural split; zero behavior change at the call site.\n//\n// `rateLimitSchema` and `securitySchema` are NOT re-exported: they are composed into\n// `theoConfigSchema` below and nothing imports them from here. They remain available at their\n// source of truth, `./schemas/index.js`.\nexport { cacheSchema, corsSchema, securityHeadersSchema, storageSchema } from './schemas/index.js'\n\nexport type { StorageConfig } from './schemas/index.js'\n\n/**\n * Root `theo.config.ts` schema — composer assembled from the per-concern\n * primitives re-exported above.\n *\n * Embedded blocks that exist ONLY as part of the root config (`agents`,\n * `ui`, `devtools`, `jobs`, `openapi`) stay inline below. They have no\n * external consumers; splitting them would create lonely files (M5\n * smell) without comprehension benefit.\n */\nexport const theoConfigSchema = z\n .object({\n /**\n * Plan v1.2 T2.1 — project identifier propagated into\n * `.theokit/services.json` v2 `project` field. DNS-1123 compatible (drives\n * Gitea repo + ArgoCD App naming on TheoCloud). When omitted, the build\n * emits services.json v1 with the legacy `services-bundle` fallback\n * (ADR D10) and logs a deprecation warning.\n */\n name: z\n .string()\n .max(63)\n .refine(\n // DNS-1123 equivalent expressed as explicit single-char anchors so\n // security/detect-unsafe-regex stays clean (no backtracking).\n (value) =>\n value.length > 0 &&\n /^[a-z0-9-]+$/u.test(value) &&\n !value.startsWith('-') &&\n !value.endsWith('-'),\n 'name must match DNS-1123 (lowercase alphanumeric+hyphens, 1-63 chars, no leading/trailing hyphen)',\n )\n .optional(),\n appDir: z.string().default('app'),\n serverDir: z.string().default('server'),\n /**\n * Directory (relative to the project root) holding `agents/<name>.ts` definitions, scanned by\n * dev/build/terminal/mcp. Defaults to `\"agents\"` — apps that keep the canonical layout are\n * unaffected. Set to e.g. `\"core/agents\"` to organize agents under a domain root (#95 follow-up).\n */\n agentsDir: z.string().default('agents'),\n /**\n * T2.2 / EC-4 — Build output directory. Must be a relative path inside\n * the project root. Refused absolute or parent-relative paths to prevent\n * `cleanOutDir` from wiping arbitrary locations (defense-in-depth on\n * top of cleanOutDir's runtime EC-3 guard).\n */\n distDir: z\n .string()\n .default('.theokit')\n .refine(\n (d) => !/^([A-Za-z]:)?[/\\\\]/.test(d) && !d.startsWith('..'),\n 'distDir must be a relative path inside the project root (e.g., \".theokit\")',\n ),\n /**\n * Agent runtime configuration.\n *\n * - `maxRegistries` (T2.3, legacy): dev-mode cleanup of stale\n * `.theokit/agents/<id>/` dirs by mtime. Now superseded by SDK's\n * native registry GC but kept for backward-compat.\n * - `registry` (Phase 6, Production-Readiness #2): forwarded to\n * `Agent.registry.configure()` lazily on first request.\n * * `maxAgents` — LRU cap. MUST be ≥ max-concurrent-active-conversations\n * (EC-17 DOCUMENT): with maxAgents:1 and 2 concurrent chats, LRU evicts\n * mid-stream → SDK aborts with code:'aborted'. Default 100 covers\n * indie/small-team; tune up for high-traffic.\n * * `idleTimeoutMs` — auto-evict idle agents (default 30 min). 0 disables\n * idle eviction (LRU only).\n */\n agents: z\n .object({\n maxRegistries: z.number().int().positive().default(100),\n registry: z\n .object({\n /** LRU cap — MUST be ≥ max-concurrent-active-conversations. */\n maxAgents: z.number().int().positive().max(10_000).default(100),\n /** Idle eviction window in ms. 0 disables idle eviction (LRU only). */\n idleTimeoutMs: z\n .number()\n .int()\n .nonnegative()\n .default(30 * 60_000),\n })\n .optional(),\n })\n .optional(),\n port: z.number().int().min(1).max(65535).default(3000),\n /** Listen on all addresses (0.0.0.0) for LAN/mobile testing. */\n /**\n * Deliberately NOT defaulted. `resolveListenTarget` ranks an explicit `host` above `HOST`,\n * because a value written into the project is a decision and an environment variable is a\n * deployment detail — and a default applied here made every app look like it had decided.\n * `HOST` was therefore inert everywhere, which is the opposite of what it was added for\n * (containers, #402). The loopback default lives in `resolveListenTarget`, where \"nobody said\"\n * is still distinguishable from \"somebody said localhost\".\n */\n host: z.union([z.string(), z.boolean()]).optional(),\n /**\n * Hostnames `theokit dev` will answer for, beyond the loopback names Vite permits out of the\n * box — Vite's `server.allowedHosts` (#555).\n *\n * This is NOT {@link host}. That one is the bind ADDRESS; this one is the `Host` header check\n * that runs after the connection is accepted, so binding `0.0.0.0` does not make a tunnelled\n * request pass. Developing against any webhook platform needs a public URL, which means a\n * tunnel or a reverse proxy, which means a `Host` the check refuses by default — and a\n * scaffolded app has no `vite.config.ts` in which to allow it.\n *\n * Vite's own matching rules apply, not globs: a leading dot allows a domain and its\n * subdomains (`.trycloudflare.com`), and anything else is compared literally.\n *\n * `true` disables the check. It is here because a tunnel that mints a fresh random hostname\n * per run cannot be listed, and the alternative — editing config between runs — is what makes\n * people reach for the production server instead. It also removes the protection against\n * DNS-rebinding that the check exists to provide, so prefer the list whenever the hostname is\n * knowable. `theokit start` is unaffected either way: this is dev-server-only.\n *\n * Deliberately NOT defaulted — an empty array is a decision that blocks every host including\n * the loopback names, so \"nobody said\" has to stay distinguishable from \"somebody said none\".\n */\n allowedHosts: z.union([z.array(z.string()), z.literal(true)]).optional(),\n /** Automatically open browser on `theokit dev`. */\n open: z.union([z.boolean(), z.string()]).default(false),\n /** Exit if port is already in use instead of trying next available. */\n strictPort: z.boolean().default(false),\n /** Forward browser console/errors to terminal — useful for AI agent dev. */\n forwardConsole: z\n .union([\n z.boolean(),\n z.object({\n unhandledErrors: z.boolean().optional(),\n logLevels: z.array(z.enum(['error', 'warn', 'info', 'log', 'debug'])).optional(),\n }),\n ])\n .default(false),\n /** Pre-transform files on startup for faster first page load. */\n warmup: z\n .object({\n clientFiles: z.array(z.string()).optional(),\n ssrFiles: z.array(z.string()).optional(),\n })\n .optional(),\n ssr: z.boolean().default(false),\n /** When true (and ssr === true), use renderToPipeableStream with progressive\n * shell flush instead of single-shot renderToString. Opt-in for streaming\n * SSR; default false preserves the current behavior. */\n ssrStreaming: z.boolean().default(false),\n rateLimit: rateLimitSchema.optional(),\n upload: uploadSchema.optional(),\n logging: loggingSchema.optional(),\n security: securitySchema.optional(),\n serialization: z.enum(['json', 'superjson']).default('json'),\n // Plugins are validated structurally at runtime by createPluginRunnerFromConfig.\n // Zod only checks the shape minimally (must be array). Type-level safety is\n // provided through defineConfig at the user surface.\n //\n // #425 — an entry MAY also be a module SPECIFIER (a string), resolved to that module's default\n // export by `config/resolve-plugin-specifiers.ts`. A constructed plugin closes over state and\n // therefore has no literal, so it is the string form — and only the string form — that a\n // generated deploy entry can carry. Both shapes are accepted here for the same reason they are\n // accepted at runtime: one declaration has to serve the local server and the deployed one.\n plugins: z.array(z.unknown()).optional(),\n /** Enable client-side batching of theoFetch calls and the\n * /api/__theo_batch__ server endpoint. */\n batching: z\n .union([z.boolean(), z.object({ max: z.number().int().positive().optional() })])\n .optional(),\n /** T4.1 — Audit log. When `logger` is provided, framework events\n * (csrf.warn, rate-limit.exceeded, session.rotated, csp.violation) are\n * emitted to it. Default: noop. */\n audit: z\n .object({\n logger: z.unknown().optional(),\n })\n .optional(),\n /** TheoUI auto-wire (T2.1). `false` = opt-out; object = explicit theme/fonts;\n * undefined = enabled when @theokit/ui is detected in node_modules. */\n ui: z\n .union([\n z.literal(false),\n z.object({\n // Any theme @theokit/ui knows — built-in or from `defineTheme()`. This was a closed\n // enum of `violet-forge | noir | paper`, two of which never existed in @theokit/ui, so\n // the only accepted value was the default and every real theme was rejected. The pattern\n // mirrors what @theokit/ui's ThemeProvider enforces, and it is load-bearing: the value is\n // interpolated into the generated entry and into a CSS selector.\n theme: z\n .string()\n .regex(\n THEME_NAME_PATTERN,\n 'must start with a letter and contain only lowercase letters, digits and hyphens',\n )\n .optional(),\n fonts: z.enum(['bundled', 'cdn']).optional(),\n }),\n ])\n .optional(),\n /**\n * Cache subsystem (caching-and-revalidation-plan).\n * Default `undefined` keeps caching disabled (backward compatible).\n * Pass `cache: {}` to opt in with defaults.\n */\n cache: cacheSchema.optional(),\n /**\n * Observability (#353). Default `undefined` keeps telemetry off. Present and\n * not `enabled: false` opts in; `provider` overrides the environment-derived\n * adapter, which is the priority `adapter-registry.ts` has always documented.\n */\n observability: observabilitySchema.optional(),\n /**\n * Devtools overlay (Phase 0.4.0+ —\n *\n * - `undefined` (default): devtools auto-injects in `pnpm dev`, NEVER in `vite build`.\n * - `false`: devtools disabled entirely (Vite plugin skips injection even in dev).\n * - `{ ... }`: devtools enabled with explicit defaults (position, theme).\n *\n * Tree-shaken to noop in prod via the dual-export pattern in\n * `packages/theo/src/devtools/index.ts` (EC-17 positive prod check).\n */\n devtools: z\n .union([\n z.literal(false),\n z.object({\n position: z.enum(['top-left', 'top-right', 'bottom-left', 'bottom-right']).optional(),\n theme: z.enum(['light', 'dark', 'system']).optional(),\n }),\n ])\n .optional(),\n /**\n * Informative list of deploy adapters the app supports. Does NOT\n * trigger per-build translations — only the `--target` CLI flag does\n * (EC-201 / ADR D2). If `config.adapters` includes a target NOT\n * matching `--target`, `theokit build` emits a cross-reference note.\n */\n adapters: z.array(z.string()).optional(),\n /**\n * Extra package names to pre-bundle via Vite's `optimizeDeps.include`.\n *\n * Framework auto-includes `@theokit/ui` and `lucide-react` when present.\n * Apps adding plugin peer-deps that rely on a runtime `import('<pkg>')`\n * (dynamic specifier) — e.g. `@theokit/plugin-canvas` consumers\n * installing `mermaid` for Mermaid SVG rendering — must declare those\n * here so Vite can resolve the literal in dev mode without\n * \"Failed to resolve module specifier\" errors. Production builds use\n * tsup/esbuild bundling and are not affected.\n *\n * Example:\n * viteOptimizeDeps: ['mermaid']\n */\n viteOptimizeDeps: z.array(z.string()).optional(),\n /**\n * Jobs backend (ADR D3 + T2.1). When configured, every request gets\n * `ctx.queue.enqueue` auto-wired via the outbox lifecycle. Pass a\n * `JobBackend` instance (InMemoryJobBackend, PostgresJobBackend, etc.).\n */\n jobs: z\n .object({\n backend: z.custom<unknown>((v) => typeof v === 'object' && v !== null),\n })\n .optional(),\n /**\n * StorageManager configuration (T1.1 / ADR-0007).\n *\n * Declares Postgres servers + databases + Redis servers. Consumed by\n * `getStorageManager().configure()` at boot via `start.ts`.\n *\n * Default `undefined` means manager exists but is not configured — adapters\n * relying on the manager (PostgresJobBackend.fromStorageManager, etc.) will\n * throw with an actionable error on first use.\n */\n storage: storageSchema.optional(),\n /**\n * Wave 2 — Polyglot services orchestration (T1.1 / ADR-0012/0013/0014/0015).\n *\n * Declarative external sidecar processes (Python FastAPI / Node Hono)\n * that boot alongside the TheoKit TS app. Empty `services: {}` is the\n * default and preserves Wave 1 behavior.\n */\n services: servicesConfigSchema,\n /**\n * G2 — OpenAPI emit (build-time only).\n *\n * When present, `theokit build` writes a generated `openapi.json` from\n * every `defineRoute()` body/query/params Zod schema. `undefined` keeps\n * the framework backward-compatible (no emit). Pass `openapi: {}` to\n * opt in with defaults.\n *\n * Defaults: spec 3.1.0 · servers `http://localhost:3000` · title\n * \"TheoKit App\" · version \"0.0.0\" · outDir \".theokit\" (next to dist).\n *\n * The env var `THEOKIT_OPENAPI_SERVERS` (CSV of URLs) overrides\n * `servers[].url` at emit time without rebuilding the config.\n */\n openapi: z\n .object({\n servers: z\n .array(\n z.object({\n url: z.url(),\n description: z.string().optional(),\n }),\n )\n .default([{ url: 'http://localhost:3000', description: 'Local development' }]),\n specVersion: z.enum(['3.1.0', '3.0.3']).default('3.1.0'),\n title: z.string().default('TheoKit App'),\n version: z.string().default('0.0.0'),\n outDir: z.string().default('.theokit'),\n })\n .optional(),\n /**\n * G5 T1.3 — error envelope transformer hook (blueprint ADR D3).\n *\n * When present, runs at framework error-boundary time to enrich the\n * envelope with consumer-defined extensions (`hint`, custom telemetry\n * tags, etc.) BEFORE the envelope is serialized to the client. The\n * function signature is preserved via the explicit `FormatErrorHook`\n * type — TS inference flows from `theo.config.ts` into `@theo/client`\n * codegen and `@theokit/ui` AgentErrorCard consumers.\n *\n * Use `z.custom<FormatErrorHook>(...)` because Zod's built-in\n * `z.function()` discards its TS signature after parse; `z.custom`\n * with a function-typed runtime guard preserves the call-site type\n * without trading off Zod runtime validation.\n */\n formatError: z\n .custom<FormatErrorHook>((val) => typeof val === 'function', {\n message: 'formatError must be a function',\n })\n .optional(),\n })\n // EC-2 fix: cross-config refine — no service may share TheoKit's web port.\n .refine((cfg) => !Object.values(cfg.services).some((s) => s.port === cfg.port), {\n message: 'service.port collides with TheoKit web port — change one of them',\n path: ['services'],\n })\n\nexport type TheoConfig = z.infer<typeof theoConfigSchema>\n\n// Silence unused-import warnings for type-only re-exports — TS strips at compile,\n// but exports above re-introduce them for downstream consumers.\ntype _FormatErrorContext = FormatErrorContext\n","/**\n * The `@theokit/ui` theme name — a contract shared by the config schema, the entry generators and\n * the Vite plugin's detector.\n *\n * It lives in `core/contracts/` because those three sit in different modules that may not depend on\n * one another: `config/` and `router/` are allowed to reach into `core/` only. Before this file the\n * union was written out separately in all three places, and all three drifted from what the design\n * system actually ships.\n */\n\n/**\n * Theme names `@theokit/ui` ships today — an autocomplete hint, NOT the accepted set.\n *\n * The accepted set used to be exactly `'violet-forge' | 'noir' | 'paper'`, and two of those three\n * were never real: the design system has no `noir` and no `paper`. So the only value config\n * validation accepted was the default, and every genuine theme — plus anything from\n * `defineTheme()` — was rejected.\n *\n * A closed union here is a copy of another package's catalogue; it rots the moment that package\n * ships a theme. This list is therefore advisory, and {@link TheoUiTheme} stays open. The\n * authoritative list is `builtinThemes`, exported by `@theokit/ui`.\n */\nexport type BuiltinThemeName =\n | 'violet-forge'\n | 'falcon-red'\n | 'classic-paper'\n | 'aurora-terminal'\n | 'vercel-mono'\n | 'github-dark'\n | 'dracula'\n | 'one-dark'\n | 'anthropic-style'\n | 'openai-style'\n | 'linear-glass'\n\n/**\n * A theme name. Built-ins autocomplete; a custom theme from `defineTheme()` is equally valid.\n *\n * `(string & {})` is the idiomatic way to keep literal suggestions on an open union — without it\n * TypeScript widens the whole type to `string` and the hints disappear.\n */\nexport type TheoUiTheme = BuiltinThemeName | (string & {})\n\n/** How fonts are delivered — bundled with the app, or fetched from a CDN. */\nexport type TheoUiFonts = 'bundled' | 'cdn'\n\n/**\n * The shape a theme name must have — mirrors the pattern `@theokit/ui`'s `ThemeProvider` enforces\n * before it writes `[data-theme=\"<name>\"]`.\n *\n * Validating here is not cosmetic. The value is interpolated into the generated entry\n * (`defaultTheme: '<name>'`) and into a CSS selector, so an unchecked name is a code-injection\n * vector — and anything this rejects would be rejected by the provider anyway, so the developer\n * gets the error at config time instead of at render time.\n */\nexport const THEME_NAME_PATTERN = /^[a-z][a-z0-9-]*$/\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;;;ACuDX,IAAM,qBAAqB;;;ADlB3B,IAAM,mBAAmB,EAC7B,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQN,MAAM,EACH,OAAO,EACP,IAAI,EAAE,EACN;AAAA;AAAA;AAAA,IAGC,CAAC,UACC,MAAM,SAAS,KACf,gBAAgB,KAAK,KAAK,KAC1B,CAAC,MAAM,WAAW,GAAG,KACrB,CAAC,MAAM,SAAS,GAAG;AAAA,IACrB;AAAA,EACF,EACC,SAAS;AAAA,EACZ,QAAQ,EAAE,OAAO,EAAE,QAAQ,KAAK;AAAA,EAChC,WAAW,EAAE,OAAO,EAAE,QAAQ,QAAQ;A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7 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import {
|
|
4
4
|
buildSecurityHeaders
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-VV2VU3LJ.js";
|
|
6
6
|
|
|
7
7
|
// src/adapters/deployed-cors.ts
|
|
8
8
|
var UnserializableCorsOriginError = class extends Error {
|
|
@@ -185,4 +185,4 @@ export {
|
|
|
185
185
|
renderSecurityHeadersConfigLiteral,
|
|
186
186
|
describeDeployedSecurityHeaders
|
|
187
187
|
};
|
|
188
|
-
//# sourceMappingURL=chunk-
|
|
188
|
+
//# sourceMappingURL=chunk-VPX3MS5D.js.map
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
|
|
4
4
|
// src/core/contracts/security-headers.ts
|
|
5
|
-
var DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws: wss:; frame-ancestors 'none'; report-uri /__theo/csp-report";
|
|
5
|
+
var DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws: wss:; frame-ancestors 'none'; report-uri /__theo/csp-report";
|
|
6
6
|
var DEFAULT_PERMISSIONS_POLICY = "geolocation=(), camera=(), microphone=(), payment=(), usb=(), accelerometer=(), gyroscope=()";
|
|
7
7
|
var DEFAULT_HSTS = "max-age=31536000; includeSubDomains";
|
|
8
8
|
function applyNonceToCsp(policy, nonce) {
|
|
@@ -81,4 +81,4 @@ export {
|
|
|
81
81
|
buildSecurityHeaders,
|
|
82
82
|
generateNonce
|
|
83
83
|
};
|
|
84
|
-
//# sourceMappingURL=chunk-
|
|
84
|
+
//# sourceMappingURL=chunk-VV2VU3LJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/contracts/security-headers.ts","../src/core/contracts/nonce.ts"],"sourcesContent":["/**\n * The security-header baseline, as a pure function of configuration.\n *\n * It lives in `core/contracts/` because **every** target needs it and none of it\n * is transport-specific: `buildSecurityHeaders` takes a config object and\n * returns `Record<string, string>`. `theokit start` writes that map onto a Node\n * `ServerResponse` (`server/security/security-headers.ts`); the six Web deploy\n * adapters write it onto a `Response` (`adapters/security-headers.ts`). Putting\n * it under `server/` made the second group import across a boundary the\n * dependency graph forbids — `adapters → server` is not a declared edge in\n * ADR-0001 v3 — and the fix is not to widen the rule but to notice that this\n * code was never server code.\n *\n * `core/contracts/<file>.ts` is the declared exception to the deep-import rule,\n * so both callers reach it directly and there is still exactly ONE definition of\n * what a configured header set means.\n *\n * Phase 6 — Default Security Headers (D4 / EC-2).\n *\n * Per-response security baseline. The framework applies these BEFORE the\n * route handler runs so a handler can still override via `res.setHeader`.\n *\n * EC-2 backward-compatibility: CSP ships in `report-only` mode by default\n * for 0.2.0. Existing apps with inline scripts or third-party CDN scripts\n * keep working but consumers see violation reports via their CSP report\n * collector (or browser DevTools). 0.3.0 will flip the default to\n * `enforce` after a release of visibility.\n */\n\n/**\n * Default Content-Security-Policy. Conservative-but-not-paralyzing:\n *\n * - default-src 'self' — every fetch falls back to same-origin\n * - script-src 'self' — T6.1 (0.3.0): `'unsafe-inline'`\n * dropped. The SSR pipeline issues a\n * per-request nonce that REPLACES\n * this directive at runtime\n * (`'nonce-<token>'`). For static /\n * non-SSR contexts where no nonce is\n * available, the policy is strict-\n * no-inline — user inline scripts\n * must be migrated to external\n * `<script src=\"...\">` or threaded\n * through `ctx.nonce`.\n * - style-src 'self' 'unsafe-inline' — Tailwind + TheoUI use style attrs\n * in animation directives\n * - img-src 'self' data: blob: — supports inline data URIs, blobs\n * from canvas exports\n * - media-src 'self' data: blob: — same reasoning for audio/video the app\n * generated itself. Absent until #553:\n * `<audio>` fell back to default-src\n * and a blob: from plugin-voice's TTS\n * was blocked in the browser\n * - font-src 'self' data: — Geist fonts inline-base64\n * - connect-src 'self' ws: wss: — WebSocket dev HMR + agent streams\n * - frame-ancestors 'none' — clickjacking defense\n */\n/**\n * T5.1 — default CSP includes the built-in report endpoint so violations\n * are visible without extra config. Apps that ship a custom `csp` string\n * override the report-uri.\n */\nexport const DEFAULT_CSP =\n \"default-src 'self'; \" +\n \"script-src 'self'; \" +\n \"style-src 'self' 'unsafe-inline'; \" +\n \"img-src 'self' data: blob:; \" +\n \"media-src 'self' data: blob:; \" +\n \"font-src 'self' data:; \" +\n \"connect-src 'self' ws: wss:; \" +\n \"frame-ancestors 'none'; \" +\n 'report-uri /__theo/csp-report'\n\n/**\n * T1.1 — Default Permissions-Policy header (default-deny stance).\n *\n * Disables sensitive Web APIs that the vast majority of apps don't use.\n * Apps that DO need any of these opt in by overriding `permissionsPolicy`\n * in `config.security.headers`.\n *\n * The seven features listed are the most-abused for: tracking\n * (geolocation, accelerometer, gyroscope), spyware (camera, microphone),\n * fraud (payment), and hardware exfiltration (usb).\n *\n * Aligns with Mozilla baseline + OWASP Secure Headers + Lighthouse PWA.\n */\nexport const DEFAULT_PERMISSIONS_POLICY =\n 'geolocation=(), camera=(), microphone=(), payment=(), usb=(), accelerometer=(), gyroscope=()'\n\nexport type CspMode = 'enforce' | 'report-only' | 'off'\n\nexport interface SecurityHeadersConfig {\n /**\n * Custom CSP policy string. When set, replaces the default verbatim.\n * Pass `false` to disable CSP entirely (alias for `cspMode: 'off'`).\n */\n csp?: string | false\n /**\n * Enforcement mode for CSP. Default `report-only` for 0.2.0 (EC-2).\n * 0.3.0 will default to `enforce`.\n */\n cspMode?: CspMode\n /**\n * Strict-Transport-Security value. Defaults to\n * `max-age=31536000; includeSubDomains` in production. Pass `false` to\n * suppress (e.g. internal LANs without TLS).\n */\n hsts?: string | false\n /** X-Frame-Options. Default DENY. */\n frameOptions?: 'DENY' | 'SAMEORIGIN'\n /** X-Content-Type-Options. Default `nosniff`. */\n contentTypeOptions?: 'nosniff'\n /** Referrer-Policy. Default `strict-origin-when-cross-origin`. */\n referrerPolicy?: string\n /**\n * T1.1 — Permissions-Policy directive string. When set, replaces the\n * default verbatim (no merge — see ADR-EC-12). Pass `false` to disable\n * the header entirely. Schema-level refinement rejects any string\n * containing CR/LF (EC-3 — CWE-113 HTTP Response Splitting mitigation).\n */\n permissionsPolicy?: string | false\n}\n\nexport interface SecurityEnv {\n production: boolean\n}\n\n/**\n * T4.1 — Per-request options passed by the SSR pipeline.\n *\n * - `nonce`: when set, the framework substitutes the `'unsafe-inline'`\n * token in `script-src` with `'nonce-<nonce>'`. EC-3 forces\n * `Cache-Control: private, no-store` so a CDN cannot cache the HTML\n * (carrying one nonce) and re-serve it with a freshly-generated CSP\n * header (carrying a different nonce).\n * - `prerender`: when true, the nonce is IGNORED. Prerendered HTML is\n * generated at build time with no nonce in the script tags; mixing a\n * runtime nonce in the header would block every script. EC-4.\n */\nexport interface SecurityHeadersOptions {\n nonce?: string\n prerender?: boolean\n}\n\nconst DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'\n\n/**\n * Apply a nonce to the script-src directive of an existing CSP policy\n * string. Replaces `'unsafe-inline'` (if present) with `'nonce-<value>'`;\n * otherwise appends the nonce directive to the script-src line.\n */\nfunction applyNonceToCsp(policy: string, nonce: string): string {\n return policy\n .split(';')\n .map((directive) => {\n const trimmed = directive.trim()\n if (!trimmed.startsWith('script-src')) return directive\n if (trimmed.includes(\"'unsafe-inline'\")) {\n return directive.replace(\"'unsafe-inline'\", `'nonce-${nonce}'`)\n }\n return `${directive} 'nonce-${nonce}'`\n })\n .join(';')\n}\n\n/**\n * Apply Content-Security-Policy header(s) to `out`. Extracted from\n * `buildSecurityHeaders` to keep that function's complexity within ceiling.\n * Handles the four shapes:\n * csp: false → opt out\n * cspMode: 'off' → opt out\n * cspMode: 'enforce' → Content-Security-Policy (T6.1 default for 0.3.0)\n * cspMode: 'report-only' → Content-Security-Policy-Report-Only (legacy 0.2.x)\n */\nfunction applyCsp(\n out: Record<string, string>,\n config: SecurityHeadersConfig,\n effectiveNonce: string | undefined,\n): void {\n if (config.csp === false || config.cspMode === 'off') return\n let policy = typeof config.csp === 'string' ? config.csp : DEFAULT_CSP\n if (effectiveNonce) {\n policy = applyNonceToCsp(policy, effectiveNonce)\n }\n // T6.1 — default flipped from 'report-only' to 'enforce' for 0.3.0.\n const mode: CspMode = config.cspMode ?? 'enforce'\n if (mode === 'enforce') {\n out['Content-Security-Policy'] = policy\n } else {\n out['Content-Security-Policy-Report-Only'] = policy\n }\n}\n\n/**\n * Build the security headers map for a given config + env. Pure function —\n * returned object can be inspected, logged, or applied to a response.\n */\nexport function buildSecurityHeaders(\n config: SecurityHeadersConfig,\n env: SecurityEnv,\n options: SecurityHeadersOptions = {},\n): Record<string, string> {\n const out: Record<string, string> = {}\n\n // EC-4: prerendered routes must NOT receive a nonce — the build-time\n // HTML carries no nonce, so a runtime nonce would mismatch.\n const effectiveNonce = options.prerender ? undefined : options.nonce\n\n applyCsp(out, config, effectiveNonce)\n\n // X-Frame-Options\n out['X-Frame-Options'] = config.frameOptions ?? 'DENY'\n\n // X-Content-Type-Options\n out['X-Content-Type-Options'] = config.contentTypeOptions ?? 'nosniff'\n\n // Referrer-Policy\n out['Referrer-Policy'] = config.referrerPolicy ?? 'strict-origin-when-cross-origin'\n\n // T1.1 — Permissions-Policy. Default-deny on geo/camera/mic/payment/usb;\n // configurable via `permissionsPolicy`; suppressed via `permissionsPolicy: false`.\n if (config.permissionsPolicy !== false) {\n out['Permissions-Policy'] =\n typeof config.permissionsPolicy === 'string'\n ? config.permissionsPolicy\n : DEFAULT_PERMISSIONS_POLICY\n }\n\n // HSTS — production only, suppressible via hsts: false\n if (env.production && config.hsts !== false) {\n out['Strict-Transport-Security'] = typeof config.hsts === 'string' ? config.hsts : DEFAULT_HSTS\n }\n\n // EC-3: when a nonce is in play, the response carries a one-shot CSP\n // header AND inline scripts in the HTML body. A CDN that caches the\n // HTML and proxies a fresh CSP per request would block every script\n // (nonces wouldn't match). Force no-store to prevent that class of\n // silent prod-only failure. Prerendered routes (which carry no nonce\n // by design — EC-4) are exempt; their HTML is meant to be cacheable.\n if (effectiveNonce) {\n out['Cache-Control'] = 'private, no-store'\n }\n\n return out\n}\n","/**\n * The per-request CSP nonce, minted the same way on every target.\n *\n * It lives in `core/contracts/` for the same reason\n * `core/contracts/security-headers.ts` does: `theokit start` needs it\n * (`cli/commands/start/request-handler.ts`) and so does the streamed Cloudflare\n * worker, which is the one deploy path that renders HTML at request time and can\n * put the same value on the script tags it emits. `adapters → server` is not an\n * edge in the module DAG (ADR-0001 v3), and a Web-Crypto call that returns a\n * base64 string was never server code.\n *\n * T4.1 — Per-request CSP nonce generation.\n *\n * Returns a 22–24 character base64-encoded string carrying 16 bytes of\n * cryptographic entropy. Used by the SSR pipeline to nonce the inline\n * hydration data script so the default CSP can drop `'unsafe-inline'`\n * from `script-src` in 0.3.0.\n *\n * Runtime portability: prefers Web Crypto (`globalThis.crypto`) because\n * it is available on every target runtime (Node 19+, Bun, Deno, Vercel\n * Edge, Cloudflare Workers). Falls back to `node:crypto` for older Node\n * builds where `globalThis.crypto` is absent.\n *\n * NOT a security primitive in the cryptographic sense — the nonce is a\n * one-shot, single-request value that defeats trivial XSS injection by\n * making the attacker guess a 128-bit string per request. It is NOT\n * suitable for signing or session tokens.\n */\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n // Prefer Buffer when available (Node, Bun) — its base64 encoder is fast\n // and well-tested. In Edge runtimes that lack Buffer, fall back to the\n // standard btoa(String.fromCharCode(...)) trick.\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64')\n }\n let binary = ''\n for (const b of bytes) {\n binary += String.fromCharCode(b)\n }\n // `btoa` exists in browsers + edge runtimes; if it doesn't, the caller\n // is on a JS runtime we don't support — let the ReferenceError bubble.\n return btoa(binary)\n}\n\n// CR-027 fix: the previous fallback path used `require('node:crypto')`,\n// which throws ReferenceError in strict ESM contexts (Bun, Deno, Vercel\n// Edge) when reached. Web Crypto has been a hard requirement since Node\n// 19; for older Node we now throw a clear error at module load time\n// instead of failing on first SSR request.\nlet cachedWebCrypto: Crypto | null | undefined\n\nfunction getWebCrypto(): Crypto {\n if (cachedWebCrypto === undefined) {\n const candidate = (globalThis as { crypto?: Crypto }).crypto\n cachedWebCrypto =\n candidate && typeof candidate.getRandomValues === 'function' ? candidate : null\n }\n if (!cachedWebCrypto) {\n throw new Error(\n 'generateNonce: Web Crypto unavailable. TheoKit requires Node.js 19+, Bun, Deno, ' +\n 'or any modern Edge runtime where `globalThis.crypto.getRandomValues` is present.',\n )\n }\n return cachedWebCrypto\n}\n\nexport function generateNonce(): string {\n const buf = new Uint8Array(16)\n getWebCrypto().getRandomValues(buf)\n return bytesToBase64(buf)\n}\n"],"mappings":";;;;AA8DO,IAAM,cACX;AAuBK,IAAM,6BACX;AAyDF,IAAM,eAAe;AAOrB,SAAS,gBAAgB,QAAgB,OAAuB;AAC9D,SAAO,OACJ,MAAM,GAAG,EACT,IAAI,CAAC,cAAc;AAClB,UAAM,UAAU,UAAU,KAAK;AAC/B,QAAI,CAAC,QAAQ,WAAW,YAAY,EAAG,QAAO;AAC9C,QAAI,QAAQ,SAAS,iBAAiB,GAAG;AACvC,aAAO,UAAU,QAAQ,mBAAmB,UAAU,KAAK,GAAG;AAAA,IAChE;AACA,WAAO,GAAG,SAAS,WAAW,KAAK;AAAA,EACrC,CAAC,EACA,KAAK,GAAG;AACb;AAWA,SAAS,SACP,KACA,QACA,gBACM;AACN,MAAI,OAAO,QAAQ,SAAS,OAAO,YAAY,MAAO;AACtD,MAAI,SAAS,OAAO,OAAO,QAAQ,WAAW,OAAO,MAAM;AAC3D,MAAI,gBAAgB;AAClB,aAAS,gBAAgB,QAAQ,cAAc;AAAA,EACjD;AAEA,QAAM,OAAgB,OAAO,WAAW;AACxC,MAAI,SAAS,WAAW;AACtB,QAAI,yBAAyB,IAAI;AAAA,EACnC,OAAO;AACL,QAAI,qCAAqC,IAAI;AAAA,EAC/C;AACF;AAMO,SAAS,qBACd,QACA,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|
|
20
20
|
envKey: "OPENROUTER_API_KEY",
|
|
21
21
|
baseUrl: "https://openrouter.ai/api/v1",
|
|
22
|
+
gateway: true,
|
|
22
23
|
priority: 1
|
|
23
24
|
},
|
|
24
25
|
{
|
|
@@ -73,6 +74,13 @@ function declaredPrefixOf(modelId) {
|
|
|
73
74
|
if (slash <= 0) return void 0;
|
|
74
75
|
return modelId.slice(0, slash);
|
|
75
76
|
}
|
|
77
|
+
function gatewayHint(declared, modelId, registered) {
|
|
78
|
+
const gateway = registered.find(
|
|
79
|
+
(p) => p.gateway === true && p.name !== declared.name && p.envKey !== void 0 && (process.env[p.envKey] ?? "").length > 0
|
|
80
|
+
);
|
|
81
|
+
if (gateway?.envKey === void 0) return `, or change the model's provider prefix`;
|
|
82
|
+
return `, or use "${gateway.name}/${modelId}" to route it through ${gateway.name} (${gateway.envKey} is set, and ${gateway.name} serves this model id)`;
|
|
83
|
+
}
|
|
76
84
|
function takesCredential(desc) {
|
|
77
85
|
return desc.envKey !== void 0;
|
|
78
86
|
}
|
|
@@ -91,7 +99,7 @@ function resolveProvider(modelId, options) {
|
|
|
91
99
|
return { name: declared.name, apiKey, baseUrl: baseUrlOf(declared) };
|
|
92
100
|
}
|
|
93
101
|
throw new Error(
|
|
94
|
-
`Model "${modelId}" declares provider "${declared.name}", but ${declared.envKey} is not set. Set ${declared.envKey},
|
|
102
|
+
`Model "${modelId}" declares provider "${declared.name}", but ${declared.envKey} is not set. Set ${declared.envKey}${gatewayHint(declared, modelId, sorted)}.`
|
|
95
103
|
);
|
|
96
104
|
}
|
|
97
105
|
const unregisteredPrefix = declared === void 0 ? declaredPrefixOf(modelId) : void 0;
|
|
@@ -179,4 +187,4 @@ export {
|
|
|
179
187
|
getApprovalRegistry,
|
|
180
188
|
resolveProvider
|
|
181
189
|
};
|
|
182
|
-
//# sourceMappingURL=chunk-
|
|
190
|
+
//# sourceMappingURL=chunk-WFIAYPBH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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\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\nexport function resolveProvider(modelId?: string, options?: ResolveOptions): ResolvedProvider {\n const sorted = [...registryOf()].sort((a, b) => a.priority - b.priority)\n\n const declared = modelId === undefined ? undefined : providerOf(modelId, sorted)\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 0038 / 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\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 0038 / 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 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,Y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import {
|
|
8
8
|
scanAgents
|
|
9
9
|
} from "./chunk-5NNFO7R7.js";
|
|
@@ -145,7 +145,7 @@ async function agentCommand(name, message, deps = {}) {
|
|
|
145
145
|
);
|
|
146
146
|
}
|
|
147
147
|
const projectRoot = deps.projectRoot ?? process.cwd();
|
|
148
|
-
const agentsDir = deps.agentsDir ?? (await (await import("./load-config-
|
|
148
|
+
const agentsDir = deps.agentsDir ?? (await (await import("./load-config-VMKOV44Y.js")).loadConfig(projectRoot)).agentsDir;
|
|
149
149
|
const agents = scanAgents(projectRoot, agentsDir);
|
|
150
150
|
const agent = agents.find((a) => a.name === name);
|
|
151
151
|
if (!agent) {
|
|
@@ -178,8 +178,8 @@ async function agentCommand(name, message, deps = {}) {
|
|
|
178
178
|
async function createAgentSsrLoader(projectRoot) {
|
|
179
179
|
const { createServer } = await import("vite");
|
|
180
180
|
const react = (await import("@vitejs/plugin-react")).default;
|
|
181
|
-
const { theoPluginAsync } = await import("./vite-plugin-
|
|
182
|
-
const { loadConfig } = await import("./load-config-
|
|
181
|
+
const { theoPluginAsync } = await import("./vite-plugin-37OQ5RDR.js");
|
|
182
|
+
const { loadConfig } = await import("./load-config-VMKOV44Y.js");
|
|
183
183
|
const config = await loadConfig(projectRoot);
|
|
184
184
|
const theoPlugins = await theoPluginAsync({
|
|
185
185
|
root: projectRoot,
|
|
@@ -212,4 +212,4 @@ export {
|
|
|
212
212
|
agentCommand,
|
|
213
213
|
createAgentSsrLoader
|
|
214
214
|
};
|
|
215
|
-
//# sourceMappingURL=chunk-
|
|
215
|
+
//# sourceMappingURL=chunk-YXEKPMDK.js.map
|