theokit 0.30.1 → 0.30.2
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-PBLLMJY4.js → actions-virtual-module-XHVLBFNN.js} +7 -7
- package/dist/{app-typed-client-EXHUWPOI.js → app-typed-client-4PAUHTO6.js} +7 -7
- package/dist/boot/index.js +3 -3
- package/dist/{chunk-UYFZ6DDW.js → chunk-4MTCKE5I.js} +1 -189
- package/dist/chunk-4MTCKE5I.js.map +1 -0
- package/dist/chunk-63BUBV5L.js +64 -0
- package/dist/chunk-63BUBV5L.js.map +1 -0
- package/dist/{chunk-EHUT4FMG.js → chunk-HAOPVC47.js} +29 -27
- package/dist/{chunk-EHUT4FMG.js.map → chunk-HAOPVC47.js.map} +1 -1
- package/dist/chunk-HZ6USUHC.js +191 -0
- package/dist/chunk-HZ6USUHC.js.map +1 -0
- package/dist/chunk-SPFMJAFW.js +326 -0
- package/dist/chunk-SPFMJAFW.js.map +1 -0
- package/dist/{chunk-DMGVH3VG.js → chunk-V3X5FWJA.js} +5 -62
- package/dist/chunk-V3X5FWJA.js.map +1 -0
- package/dist/define-agent-tool-ChaGymol.d.ts +88 -0
- package/dist/index.js +11 -10
- package/dist/index.js.map +1 -1
- package/dist/{internal-api-JIR3HRKF.js → internal-api-QSP2HCUU.js} +20 -20
- package/dist/server/agent/index.d.ts +387 -0
- package/dist/server/agent/index.js +43 -0
- package/dist/server/agent/index.js.map +1 -0
- package/dist/server/auth/index.js +1 -1
- package/dist/server/define/index.d.ts +3 -86
- package/dist/server/define/index.js +4 -2
- package/dist/server/index.d.ts +10 -387
- package/dist/server/index.js +112 -398
- package/dist/server/index.js.map +1 -1
- package/dist/server/jobs/index.js +4 -4
- package/dist/server/scan/index.js +1 -1
- package/dist/server/webhook/index.d.ts +4 -45
- package/dist/vite-plugin/index.js +11 -10
- package/dist/webhook-types-CNUZY7o1.d.ts +45 -0
- package/package.json +6 -2
- package/dist/chunk-DMGVH3VG.js.map +0 -1
- package/dist/chunk-UYFZ6DDW.js.map +0 -1
- /package/dist/{actions-virtual-module-PBLLMJY4.js.map → actions-virtual-module-XHVLBFNN.js.map} +0 -0
- /package/dist/{app-typed-client-EXHUWPOI.js.map → app-typed-client-4PAUHTO6.js.map} +0 -0
- /package/dist/{internal-api-JIR3HRKF.js.map → internal-api-QSP2HCUU.js.map} +0 -0
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import "./chunk-RSVN727G.js";
|
|
2
|
+
import "./chunk-TGTNRUH3.js";
|
|
3
|
+
import "./chunk-GY5Q27BJ.js";
|
|
2
4
|
import "./chunk-5QW7IQQU.js";
|
|
5
|
+
import "./chunk-WFNLNIJX.js";
|
|
3
6
|
import "./chunk-IAJ2JVEH.js";
|
|
4
7
|
import "./chunk-VMEWD57H.js";
|
|
5
8
|
import "./chunk-JQSKBMXP.js";
|
|
@@ -7,17 +10,14 @@ import {
|
|
|
7
10
|
scanServerActionsEnriched
|
|
8
11
|
} from "./chunk-RKDH4DWL.js";
|
|
9
12
|
import "./chunk-WSJKACWB.js";
|
|
10
|
-
import "./chunk-JBCHWRKF.js";
|
|
11
|
-
import "./chunk-C3ZZ56YZ.js";
|
|
12
|
-
import "./chunk-X2VVCJ4V.js";
|
|
13
|
-
import "./chunk-TGTNRUH3.js";
|
|
14
|
-
import "./chunk-GY5Q27BJ.js";
|
|
15
|
-
import "./chunk-WFNLNIJX.js";
|
|
16
13
|
import "./chunk-ZEGYW52B.js";
|
|
14
|
+
import "./chunk-JBCHWRKF.js";
|
|
17
15
|
import "./chunk-TSLSIRBR.js";
|
|
18
16
|
import "./chunk-UD3LFGDL.js";
|
|
19
17
|
import "./chunk-X32XEJXR.js";
|
|
20
18
|
import "./chunk-UVXB2ER7.js";
|
|
19
|
+
import "./chunk-C3ZZ56YZ.js";
|
|
20
|
+
import "./chunk-X2VVCJ4V.js";
|
|
21
21
|
import "./chunk-DGUM43GV.js";
|
|
22
22
|
|
|
23
23
|
// src/vite-plugin/actions-virtual-module.ts
|
|
@@ -221,4 +221,4 @@ export const actions = manifest
|
|
|
221
221
|
export {
|
|
222
222
|
actionsVirtualModule
|
|
223
223
|
};
|
|
224
|
-
//# sourceMappingURL=actions-virtual-module-
|
|
224
|
+
//# sourceMappingURL=actions-virtual-module-XHVLBFNN.js.map
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import "./chunk-RSVN727G.js";
|
|
2
|
+
import "./chunk-TGTNRUH3.js";
|
|
3
|
+
import "./chunk-GY5Q27BJ.js";
|
|
2
4
|
import "./chunk-5QW7IQQU.js";
|
|
5
|
+
import "./chunk-WFNLNIJX.js";
|
|
3
6
|
import "./chunk-IAJ2JVEH.js";
|
|
4
7
|
import "./chunk-VMEWD57H.js";
|
|
5
8
|
import "./chunk-JQSKBMXP.js";
|
|
@@ -9,17 +12,14 @@ import {
|
|
|
9
12
|
import {
|
|
10
13
|
HTTP_METHODS
|
|
11
14
|
} from "./chunk-WSJKACWB.js";
|
|
12
|
-
import "./chunk-JBCHWRKF.js";
|
|
13
|
-
import "./chunk-C3ZZ56YZ.js";
|
|
14
|
-
import "./chunk-X2VVCJ4V.js";
|
|
15
|
-
import "./chunk-TGTNRUH3.js";
|
|
16
|
-
import "./chunk-GY5Q27BJ.js";
|
|
17
|
-
import "./chunk-WFNLNIJX.js";
|
|
18
15
|
import "./chunk-ZEGYW52B.js";
|
|
16
|
+
import "./chunk-JBCHWRKF.js";
|
|
19
17
|
import "./chunk-TSLSIRBR.js";
|
|
20
18
|
import "./chunk-UD3LFGDL.js";
|
|
21
19
|
import "./chunk-X32XEJXR.js";
|
|
22
20
|
import "./chunk-UVXB2ER7.js";
|
|
21
|
+
import "./chunk-C3ZZ56YZ.js";
|
|
22
|
+
import "./chunk-X2VVCJ4V.js";
|
|
23
23
|
import "./chunk-DGUM43GV.js";
|
|
24
24
|
|
|
25
25
|
// src/vite-plugin/app-typed-client.ts
|
|
@@ -296,4 +296,4 @@ export {
|
|
|
296
296
|
emitClientDts,
|
|
297
297
|
generateClientDts
|
|
298
298
|
};
|
|
299
|
-
//# sourceMappingURL=app-typed-client-
|
|
299
|
+
//# sourceMappingURL=app-typed-client-4PAUHTO6.js.map
|
package/dist/boot/index.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
serveReservedRoute
|
|
3
|
-
} from "../chunk-V3LJN2GS.js";
|
|
4
1
|
import {
|
|
5
2
|
envelopeCodeToStatus
|
|
6
3
|
} from "../chunk-X32XEJXR.js";
|
|
@@ -8,6 +5,9 @@ import {
|
|
|
8
5
|
NotFoundError,
|
|
9
6
|
serverErrorToEnvelope
|
|
10
7
|
} from "../chunk-UVXB2ER7.js";
|
|
8
|
+
import {
|
|
9
|
+
serveReservedRoute
|
|
10
|
+
} from "../chunk-V3LJN2GS.js";
|
|
11
11
|
import "../chunk-DGUM43GV.js";
|
|
12
12
|
|
|
13
13
|
// src/server/boot.ts
|
|
@@ -146,48 +146,6 @@ function resolveTransformer(selector) {
|
|
|
146
146
|
return selector;
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
-
// src/server/agent/mcp-app-resources.ts
|
|
150
|
-
function defineAppResource(input) {
|
|
151
|
-
if (!input.uri.startsWith("ui://")) {
|
|
152
|
-
throw new Error(
|
|
153
|
-
`defineAppResource: uri must use the ui:// scheme (an app UI resource). Got: ${JSON.stringify(input.uri)}`
|
|
154
|
-
);
|
|
155
|
-
}
|
|
156
|
-
if (input.html.length === 0) {
|
|
157
|
-
throw new Error(`defineAppResource(${JSON.stringify(input.uri)}): html must be non-empty.`);
|
|
158
|
-
}
|
|
159
|
-
return {
|
|
160
|
-
uri: input.uri,
|
|
161
|
-
name: input.name,
|
|
162
|
-
mimeType: "text/html",
|
|
163
|
-
html: input.html,
|
|
164
|
-
...input.description !== void 0 ? { description: input.description } : {}
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
function buildResourceDescriptors(resources) {
|
|
168
|
-
return resources.map((r) => ({
|
|
169
|
-
uri: r.uri,
|
|
170
|
-
name: r.name,
|
|
171
|
-
mimeType: r.mimeType,
|
|
172
|
-
...r.description !== void 0 ? { description: r.description } : {}
|
|
173
|
-
}));
|
|
174
|
-
}
|
|
175
|
-
function readAppResource(resources, uri) {
|
|
176
|
-
const found = resources.find((r) => r.uri === uri);
|
|
177
|
-
if (!found) return null;
|
|
178
|
-
return { contents: [{ uri: found.uri, mimeType: "text/html", text: found.html }] };
|
|
179
|
-
}
|
|
180
|
-
function isAppResource(v) {
|
|
181
|
-
if (typeof v !== "object" || v === null) return false;
|
|
182
|
-
const r = v;
|
|
183
|
-
return typeof r.uri === "string" && r.uri.startsWith("ui://") && r.mimeType === "text/html" && typeof r.html === "string";
|
|
184
|
-
}
|
|
185
|
-
function extractAppResources(mod) {
|
|
186
|
-
const raw = mod?.appResources;
|
|
187
|
-
if (!Array.isArray(raw)) return [];
|
|
188
|
-
return raw.filter(isAppResource);
|
|
189
|
-
}
|
|
190
|
-
|
|
191
149
|
// src/server/http/validate-route-input.ts
|
|
192
150
|
function validateRouteInput(config, raw) {
|
|
193
151
|
let query = raw.query;
|
|
@@ -487,159 +445,13 @@ async function runErrorHooks(err, hookCtx, onError) {
|
|
|
487
445
|
return mergeHookHeaders(errorResponse, hookCtx.responseHeaders);
|
|
488
446
|
}
|
|
489
447
|
|
|
490
|
-
// src/server/agent/mcp-handler.ts
|
|
491
|
-
import { compileAgentModule } from "@theokit/agents";
|
|
492
|
-
var MCP_PATH = /^\/api\/agents\/([^/]+)\/mcp$/;
|
|
493
|
-
var MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
494
|
-
function toolDescriptors(tools) {
|
|
495
|
-
return tools.map((t) => ({
|
|
496
|
-
name: t.name,
|
|
497
|
-
description: t.description,
|
|
498
|
-
// The compiled tool already carries a JSON Schema (via `z.toJSONSchema()` in defineAgentTool).
|
|
499
|
-
// Fall back to a permissive object only when a tool genuinely declared no schema.
|
|
500
|
-
inputSchema: t.inputSchema && typeof t.inputSchema === "object" ? t.inputSchema : { type: "object", properties: {} }
|
|
501
|
-
}));
|
|
502
|
-
}
|
|
503
|
-
function isMcpPath(urlPath) {
|
|
504
|
-
const match = MCP_PATH.exec(urlPath);
|
|
505
|
-
return match ? decodeURIComponent(match[1]) : null;
|
|
506
|
-
}
|
|
507
|
-
function isJsonRpcRequest(body) {
|
|
508
|
-
return typeof body === "object" && body !== null && body.jsonrpc === "2.0" && typeof body.method === "string";
|
|
509
|
-
}
|
|
510
|
-
function jsonResponse(payload) {
|
|
511
|
-
return new Response(JSON.stringify(payload), {
|
|
512
|
-
status: 200,
|
|
513
|
-
headers: { "content-type": "application/json; charset=utf-8" }
|
|
514
|
-
});
|
|
515
|
-
}
|
|
516
|
-
async function callTool(tools, toolName, args, hitl) {
|
|
517
|
-
if (typeof toolName !== "string") {
|
|
518
|
-
return {
|
|
519
|
-
content: [{ type: "text", text: "tools/call requires a string `name`." }],
|
|
520
|
-
isError: true
|
|
521
|
-
};
|
|
522
|
-
}
|
|
523
|
-
const tool = tools.find((t) => t.name === toolName);
|
|
524
|
-
if (!tool) {
|
|
525
|
-
return { content: [{ type: "text", text: `Unknown tool: ${toolName}` }], isError: true };
|
|
526
|
-
}
|
|
527
|
-
if (hitl?.has(toolName)) {
|
|
528
|
-
return {
|
|
529
|
-
content: [
|
|
530
|
-
{
|
|
531
|
-
type: "text",
|
|
532
|
-
text: `Tool "${toolName}" requires human approval, which is not available over MCP. Refused.`
|
|
533
|
-
}
|
|
534
|
-
],
|
|
535
|
-
isError: true
|
|
536
|
-
};
|
|
537
|
-
}
|
|
538
|
-
try {
|
|
539
|
-
const result = await tool.handler(args);
|
|
540
|
-
const text = typeof result === "string" ? result : JSON.stringify(result);
|
|
541
|
-
return { content: [{ type: "text", text }] };
|
|
542
|
-
} catch (err) {
|
|
543
|
-
return {
|
|
544
|
-
content: [
|
|
545
|
-
{ type: "text", text: err instanceof Error ? err.message : "Tool execution failed" }
|
|
546
|
-
],
|
|
547
|
-
isError: true
|
|
548
|
-
};
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
function handleResourcesRead(id, params, appResources) {
|
|
552
|
-
const uri = params?.uri;
|
|
553
|
-
if (typeof uri !== "string") {
|
|
554
|
-
return jsonResponse({
|
|
555
|
-
jsonrpc: "2.0",
|
|
556
|
-
id,
|
|
557
|
-
error: { code: -32602, message: "resources/read requires a string `uri` param." }
|
|
558
|
-
});
|
|
559
|
-
}
|
|
560
|
-
const contents = readAppResource(appResources, uri);
|
|
561
|
-
if (contents === null) {
|
|
562
|
-
return jsonResponse({
|
|
563
|
-
jsonrpc: "2.0",
|
|
564
|
-
id,
|
|
565
|
-
error: { code: -32602, message: `Resource not found: ${uri}` }
|
|
566
|
-
});
|
|
567
|
-
}
|
|
568
|
-
return jsonResponse({ jsonrpc: "2.0", id, result: contents });
|
|
569
|
-
}
|
|
570
|
-
async function handleMcpJsonRpc(mod, name, body, appResources = []) {
|
|
571
|
-
if (!isJsonRpcRequest(body)) {
|
|
572
|
-
return jsonResponse({
|
|
573
|
-
jsonrpc: "2.0",
|
|
574
|
-
id: null,
|
|
575
|
-
error: { code: -32600, message: "Invalid Request" }
|
|
576
|
-
});
|
|
577
|
-
}
|
|
578
|
-
const { id, method, params } = body;
|
|
579
|
-
try {
|
|
580
|
-
const compiled = compileAgentModule(mod, `mcp server for "${name}"`);
|
|
581
|
-
if (method === "initialize") {
|
|
582
|
-
const capabilities = { tools: {} };
|
|
583
|
-
if (appResources.length > 0) capabilities.resources = {};
|
|
584
|
-
return jsonResponse({
|
|
585
|
-
jsonrpc: "2.0",
|
|
586
|
-
id,
|
|
587
|
-
result: {
|
|
588
|
-
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
589
|
-
capabilities,
|
|
590
|
-
serverInfo: { name, version: "1.0" }
|
|
591
|
-
}
|
|
592
|
-
});
|
|
593
|
-
}
|
|
594
|
-
if (method === "tools/list") {
|
|
595
|
-
return jsonResponse({
|
|
596
|
-
jsonrpc: "2.0",
|
|
597
|
-
id,
|
|
598
|
-
result: { tools: toolDescriptors(compiled.tools) }
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
if (method === "tools/call") {
|
|
602
|
-
const p = params;
|
|
603
|
-
const result = await callTool(compiled.tools, p?.name, p?.arguments ?? {}, compiled.hitl);
|
|
604
|
-
return jsonResponse({ jsonrpc: "2.0", id, result });
|
|
605
|
-
}
|
|
606
|
-
if (method === "resources/list") {
|
|
607
|
-
return jsonResponse({
|
|
608
|
-
jsonrpc: "2.0",
|
|
609
|
-
id,
|
|
610
|
-
result: { resources: buildResourceDescriptors(appResources) }
|
|
611
|
-
});
|
|
612
|
-
}
|
|
613
|
-
if (method === "resources/read") {
|
|
614
|
-
return handleResourcesRead(id, params, appResources);
|
|
615
|
-
}
|
|
616
|
-
return jsonResponse({
|
|
617
|
-
jsonrpc: "2.0",
|
|
618
|
-
id,
|
|
619
|
-
error: { code: -32601, message: `Method not found: ${method}` }
|
|
620
|
-
});
|
|
621
|
-
} catch (err) {
|
|
622
|
-
return jsonResponse({
|
|
623
|
-
jsonrpc: "2.0",
|
|
624
|
-
id,
|
|
625
|
-
error: { code: -32603, message: err instanceof Error ? err.message : "Internal error" }
|
|
626
|
-
});
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
|
|
630
448
|
export {
|
|
631
449
|
_resetEnvCache,
|
|
632
450
|
loadEnv,
|
|
633
451
|
superjsonTransformer,
|
|
634
452
|
jsonTransformer,
|
|
635
453
|
resolveTransformer,
|
|
636
|
-
defineAppResource,
|
|
637
|
-
buildResourceDescriptors,
|
|
638
|
-
readAppResource,
|
|
639
|
-
extractAppResources,
|
|
640
|
-
isMcpPath,
|
|
641
|
-
handleMcpJsonRpc,
|
|
642
454
|
validateRouteInput,
|
|
643
455
|
executeWebRequest
|
|
644
456
|
};
|
|
645
|
-
//# sourceMappingURL=chunk-
|
|
457
|
+
//# sourceMappingURL=chunk-4MTCKE5I.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config/load-env.ts","../src/server/transformer.ts","../src/server/http/validate-route-input.ts","../src/server/http/web-middleware-runner.ts","../src/server/web-handler.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Reads `.env` files from a CLI-controlled `cwd`. File names are a fixed\n * literal set. Build-time + CLI tool; no HTTP input.\n */\n/**\n * `loadEnv()` — auto-loads `.env` files into `process.env` for server code.\n *\n * Implements the Next.js `loadEnvConfig` algorithm\n * (`referencias/next.js/packages/next-env/index.ts:114-180`) with TheoKit\n * adaptations:\n *\n * - EC-1: 1MB file-size cap (anti-OOM, anti-supply-chain).\n * - EC-2: `_resetEnvCache()` test-only side-door.\n * - EC-8: `dotenv-expand` circular-ref safe (lib-provided).\n * - EC-13: log when `.env` is a symlink (transparency).\n * - D6: real `process.env` wins over `.env`-file values.\n * - NODE_ENV stash: `.env`-set NODE_ENV NEVER overrides the real\n * `process.env.NODE_ENV`. Stashed in `__THEOKIT_USER_NODE_ENV` instead.\n */\n\nimport { lstatSync, readFileSync, realpathSync, statSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport dotenv from 'dotenv'\nimport { expand, type DotenvPopulateInput } from 'dotenv-expand'\n\nimport type { LoadEnvOptions, LoadEnvResult } from './load-env-types.js'\n\n/** EC-1: 1MB cap. Real `.env`s are < 10KB. */\nconst MAX_ENV_FILE_BYTES = 1_048_576\n\nconst cache = new Map<string, LoadEnvResult>()\n\n/** Test-only side-door for EC-2 — clear the module-level cache between vitest test files. */\nexport function _resetEnvCache(): void {\n cache.clear()\n}\n\nfunction envFilesInPriorityOrder(mode: string): string[] {\n // Top of list = highest priority. Will be read in REVERSE so first-in\n // wins via overwrite during merge.\n const files = [`.env.${mode}.local`, `.env.local`, `.env.${mode}`, `.env`]\n // Test mode skips `.env.local` per dotenv convention (avoid leaking dev\n // secrets into the test suite).\n if (mode === 'test') {\n return files.filter((f) => f !== '.env.local')\n }\n return files\n}\n\nfunction readEnvFile(path: string): Record<string, string> | null {\n let stat\n try {\n stat = statSync(path)\n } catch {\n return null // ENOENT / EACCES → skip\n }\n\n // Allow files + FIFOs (1Password/SOPS pipe support).\n if (!stat.isFile() && !stat.isFIFO()) return null\n\n // EC-1 — anti-OOM cap.\n if (stat.size > MAX_ENV_FILE_BYTES) {\n console.warn(\n `[theokit] .env file at ${path} exceeds ${MAX_ENV_FILE_BYTES} bytes — skipping (likely a generated artifact, not a real env file)`,\n )\n return null\n }\n\n // EC-13 — symlink transparency. Don't refuse; just log.\n try {\n const lstat = lstatSync(path)\n if (lstat.isSymbolicLink()) {\n const real = realpathSync(path)\n // eslint-disable-next-line no-console -- intentional transparency log on a build-time tool\n console.info(`[theokit] .env at ${path} is a symlink → ${real}`)\n }\n } catch {\n // lstat failure is non-fatal — fall through to read.\n }\n\n try {\n const content = readFileSync(path, 'utf-8')\n return dotenv.parse(content)\n } catch {\n return null\n }\n}\n\n// eslint-disable-next-line complexity -- canonical env-load algorithm (priority → expand → guards → apply); inlining branches is clearer than extracting micro-helpers\nexport function loadEnv(options: LoadEnvOptions = {}): LoadEnvResult {\n const cwd = options.cwd ?? process.cwd()\n const mode = options.mode ?? process.env.NODE_ENV ?? 'development'\n const cacheKey = `${cwd}:${mode}`\n\n if (!options.forceReload) {\n const cached = cache.get(cacheKey)\n if (cached) return cached\n }\n\n const fileNames = envFilesInPriorityOrder(mode)\n const filePaths = fileNames.map((f) => resolve(cwd, f))\n\n // Read in REVERSE — lower-priority files first, so higher-priority\n // (lower-index) overwrites during merge.\n const merged: Record<string, string> = {}\n const loadedFromFiles: string[] = []\n for (const path of [...filePaths].reverse()) {\n const parsed = readEnvFile(path)\n if (parsed === null) continue\n for (const [k, v] of Object.entries(parsed)) {\n merged[k] = v\n }\n loadedFromFiles.unshift(path) // keep priority order in result\n }\n\n // NODE_ENV stash — `.env`-set NODE_ENV never overrides real process.env.NODE_ENV.\n if (merged.NODE_ENV && process.env.__THEOKIT_USER_NODE_ENV === undefined) {\n process.env.__THEOKIT_USER_NODE_ENV = merged.NODE_ENV\n }\n delete merged.NODE_ENV // never propagate\n\n // EC-8 — dotenv-expand@11 stack-overflows on circular refs (A=${B}, B=${A}).\n // Wrap in try/catch — on overflow, leave the parsed map untouched (literal\n // values survive). Tested via test_loadEnv_circular_expand_no_loop_EC8.\n // Pass a CLONE of process.env (string-only, filtered) so expand can\n // reference real env without mutating it.\n const processEnvClone: DotenvPopulateInput = {}\n for (const [k, v] of Object.entries(process.env)) {\n if (typeof v === 'string') processEnvClone[k] = v\n }\n try {\n expand({ parsed: merged, processEnv: processEnvClone })\n } catch (err) {\n if (err instanceof RangeError) {\n console.warn(\n `[theokit] .env expansion overflow (likely circular reference like A=\\${B}, B=\\${A}). Leaving values as literals.`,\n )\n } else {\n throw err\n }\n }\n\n // Apply: D6 — real process.env wins over file values.\n const loaded: Record<string, string> = {}\n for (const [k, v] of Object.entries(merged)) {\n if (process.env[k] !== undefined) continue // real env wins\n process.env[k] = v\n loaded[k] = v\n }\n\n // Sentinel\n process.env.__THEOKIT_PROCESSED_ENV = 'true'\n\n const result: LoadEnvResult = { loaded, loadedFromFiles }\n cache.set(cacheKey, result)\n return result\n}\n","import superjson from 'superjson'\n\n/**\n * T5.2 — pluggable response/request transformer.\n *\n * `superjson` is the default, preserving Date/Map/Set/BigInt/etc.\n * `json` is the lightweight option (plain JSON.stringify/parse).\n * Users can supply a custom object implementing this contract.\n */\nexport interface TheoTransformer {\n name: string\n serialize: (value: unknown) => string\n deserialize: (raw: string) => unknown\n}\n\nexport const superjsonTransformer: TheoTransformer = {\n name: 'superjson',\n serialize: (v) => JSON.stringify(superjson.serialize(v)),\n deserialize: (raw) => {\n const parsed = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(parsed)\n },\n}\n\nexport const jsonTransformer: TheoTransformer = {\n name: 'json',\n serialize: (v) => JSON.stringify(v),\n deserialize: (raw) => JSON.parse(raw) as unknown,\n}\n\nconst BUILT_INS: Record<string, TheoTransformer> = {\n superjson: superjsonTransformer,\n json: jsonTransformer,\n}\n\nexport function resolveTransformer(\n selector: 'json' | 'superjson' | TheoTransformer,\n): TheoTransformer {\n if (typeof selector === 'string') {\n // selector is 'json' | 'superjson' literal — both keys exist in\n // BUILT_INS by construction. Type system guarantees a hit; we keep\n // a defensive fallback that the compiler cannot see is unreachable\n // at runtime, just in case someone adds a new literal to the union\n // but forgets to register the built-in.\n const built = BUILT_INS[selector]\n // Defensive: the public union ensures `built` is defined, but if a\n // future contributor extends the union without registering the impl,\n // the cast keeps the failure mode loud.\n if ((built as TheoTransformer | undefined) === undefined) {\n throw new Error(\n `Unknown transformer \"${selector}\". Built-in options: ${Object.keys(BUILT_INS).join(', ')}.`,\n )\n }\n return built\n }\n if (\n typeof selector !== 'object' ||\n typeof selector.serialize !== 'function' ||\n typeof selector.deserialize !== 'function'\n ) {\n throw new Error(\n `Custom transformer must have serialize and deserialize functions. Got: ${JSON.stringify(selector)}`,\n )\n }\n return selector\n}\n","/**\n * M33 — the SINGLE route-input validation pipeline, shared by the HTTP path (`web-handler.ts`\n * `runHandler`) and the in-process caller (`in-process-caller.ts` `callProcedure`).\n *\n * Both surfaces validate the same three channels (`query`/`body`/`params`) against the same\n * `RouteConfig` Zod schemas. Extracting the logic here means there is ONE validation pipeline\n * (no duplication, no drift) — each caller only differs in how it MAPS a failure: the HTTP path\n * emits a 400 Response, the in-process path throws a typed error.\n */\nimport type { z } from 'zod'\n\n/** The three request-input channels a route may declare a Zod schema for. */\nexport type RouteInputChannel = 'query' | 'body' | 'params'\n\n/**\n * The minimal structural shape the validator needs: the three optional channel schemas. Both\n * `RouteConfig` (the 5-arity generic contract) and `WebRouteHandlerConfig` (the Web runtime shape)\n * satisfy this — the validator depends only on the schemas, not the full route generic.\n */\nexport interface RouteInputSchemas {\n query?: z.ZodType\n body?: z.ZodType\n params?: z.ZodType\n}\n\n/** Raw (pre-validation) channel values. A channel absent from the config passes through unchanged. */\nexport interface RawRouteInput {\n query?: unknown\n body?: unknown\n params?: unknown\n}\n\n/** Discriminated result — each caller maps `ok:false` to its own surface (Response vs throw). */\nexport type RouteInputValidation =\n | { ok: true; query: unknown; body: unknown; params: unknown }\n | { ok: false; channel: RouteInputChannel; error: z.ZodError }\n\n/**\n * Validate the three input channels against the route's declared Zod schemas. A channel with no\n * declared schema passes its raw value through. First failing channel short-circuits (query → body\n * → params order, matching `runHandler`).\n */\nexport function validateRouteInput(\n config: RouteInputSchemas,\n raw: RawRouteInput,\n): RouteInputValidation {\n let query: unknown = raw.query\n if (config.query !== undefined) {\n const parsed = config.query.safeParse(raw.query)\n if (!parsed.success) return { ok: false, channel: 'query', error: parsed.error }\n query = parsed.data\n }\n let body: unknown = raw.body\n if (config.body !== undefined) {\n const parsed = config.body.safeParse(raw.body)\n if (!parsed.success) return { ok: false, channel: 'body', error: parsed.error }\n body = parsed.data\n }\n let params: unknown = raw.params\n if (config.params !== undefined) {\n const parsed = config.params.safeParse(raw.params)\n if (!parsed.success) return { ok: false, channel: 'params', error: parsed.error }\n params = parsed.data\n }\n return { ok: true, query, body, params }\n}\n","/**\n * T3.2 — Web-Standards middleware runner for the `executeWebRequest` path.\n *\n * The Node request path (`http/execute.ts`) runs middleware via\n * `runMiddlewareAndContext`, which is coupled to Node `req`/`res`. Per G8\n * (Web Standards over Node APIs) the Web path needs a `Request`-shaped runner;\n * this is it. Extracted to a sibling so `web-handler.ts` stays under its LoC\n * budget (G6).\n *\n * Ordering invariant (EC-3): the caller runs the CSRF gate BEFORE invoking this\n * runner, mirroring the Node path (CSRF stage precedes user middleware).\n *\n * NOTE (D4 / EC-12): this is its own middleware contract — `(request, context)`.\n * Full semantic parity with the Node `defineMiddleware` contract is part of the\n * deferred Node→Web pipeline convergence, not this slice.\n */\n\n/** A Web-path middleware: mutate `context`, or return a `Response` to short-circuit. */\nexport type WebMiddleware = (\n request: Request,\n context: Record<string, unknown>,\n // A middleware may mutate `context` and return nothing (void) OR return a\n // `Response` to short-circuit (Express/Koa-style). `void` in this union is\n // intentional — `runWebMiddleware` only inspects `instanceof Response`, so a\n // void return means \"continue to the next middleware / handler\".\n // eslint-disable-next-line @typescript-eslint/no-invalid-void-type\n) => Promise<Response | undefined> | Response | undefined | void\n\n/**\n * Run middleware in order against a shared mutable `context`. The first\n * middleware that returns a `Response` short-circuits the chain (the handler\n * is not reached); its `Response` is returned verbatim so headers like\n * `Set-Cookie` are preserved (EC-11). Returns `undefined` when every\n * middleware passes (the handler should run next).\n */\nexport async function runWebMiddleware(\n request: Request,\n middleware: readonly WebMiddleware[],\n context: Record<string, unknown>,\n): Promise<Response | undefined> {\n for (const mw of middleware) {\n const result = await mw(request, context)\n if (result instanceof Response) return result\n }\n return undefined\n}\n","/**\n * T5a.2 Phase A — Foundation: Web-Standards request handler entry-point.\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase A. Bridges the gap between Web `Request`/`Response` and the\n * existing `defineRoute` config shape (which is consumed today by the Node-\n * shaped `executeRoute`).\n *\n * This is the entry-point T1.2 RED tests expect:\n * `executeWebRequest(request: Request, routeModule: { GET?, POST?, ... }): Promise<Response>`\n *\n * Architecture per ADR-0028 (R3a) — this function accepts a native Web\n * `Request` and returns a native Web `Response`. No `node:*` is required in\n * the implementation (Zod + native Headers/URL/Response cover the surface).\n *\n * **Scope (intentionally narrow):**\n * - Method dispatch (GET/POST/PUT/PATCH/DELETE).\n * - Zod validation for `query` (from URL.searchParams), `body` (from\n * request.json() OR request.text()), `params` (consumer-supplied OR\n * parsed from path).\n * - Handler invocation.\n * - Result → JSON Response (200 default, 204 for void return).\n * - Error → envelope-shaped JSON Response (400 for validation, 500 for\n * handler throws) per G5 boundary translation (serverErrorToEnvelope).\n *\n * **NOT included (deferred to T5a.2 Phase B-G):**\n * - Plugin runner integration (onRequest/preHandler/onResponse hooks).\n * - CSRF / CORS / security headers / rate limiting / cookies / auth.\n * - Middleware chain. SSR rendering. WebSocket upgrade. File upload.\n * - File-system routing scan; consumer provides the route module\n * explicitly (Web Request entry doesn't yet know about scan results).\n *\n * The narrow scope makes this a viable Phase A landing zone — turns the\n * 7 T1.2 RED tests GREEN without prematurely refactoring the full\n * IncomingMessage→Request boundary across server/http/ files.\n */\nimport type { z } from 'zod'\n\nimport { envelopeCodeToStatus } from '../core/contracts/envelope-code-to-status.js'\nimport type { TheoErrorEnvelope } from '../core/contracts/error-envelope.js'\nimport { serverErrorToEnvelope } from '../core/contracts/server-error-to-envelope.js'\nimport { TheoError } from '../core/contracts/theo-error.js'\n\nimport { isZodLike } from './http/execute-stages.js'\nimport { validateRouteInput } from './http/validate-route-input.js'\nimport { runWebMiddleware, type WebMiddleware } from './http/web-middleware-runner.js'\nimport type {\n WebOnErrorHook,\n WebOnRequestHook,\n WebOnResponseHook,\n WebPluginContext,\n WebPluginErrorContext,\n WebPreHandlerHook,\n} from './plugin-types.js'\nimport { validateCsrfRequest } from './security/csrf.js'\n\nexport type { WebMiddleware }\n\n/**\n * Minimal structural type for a `defineRoute` config. Mirrors\n * `core/contracts/route-config.ts` shape but only the fields this entry\n * point needs at runtime (Zod schemas + handler). Kept structural to\n * avoid a hard dep on the full RouteConfig generic chain.\n */\ninterface WebRouteHandlerConfig {\n query?: z.ZodType\n body?: z.ZodType\n params?: z.ZodType\n /** Optional Zod schema validating a plain-object handler return (D1/D2). */\n response?: z.ZodType\n /** Honored for plain-object returns to match the Node runner (D3). */\n status?: number\n handler: (ctx: {\n query: unknown\n body: unknown\n params: unknown\n request: Request\n /** Mutable per-request context populated by the Web middleware chain (T3.2). */\n context: Record<string, unknown>\n }) => unknown\n}\n\n/**\n * The route module exported by a `server/routes/*.ts` file (after T2.6 G6\n * router lockdown). Method-named exports map to `defineRoute` results.\n */\ntype WebRouteModule = Partial<Record<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', unknown>>\n\n/**\n * Coerce URL.searchParams into a plain `{ key: value }` object so Zod\n * `z.object({...})` schemas work without per-route adapters. Repeated keys\n * become arrays (most browsers serialize multi-select that way).\n */\nfunction searchParamsToObject(params: URLSearchParams): Record<string, string | string[]> {\n const out: Record<string, string | string[]> = {}\n for (const [key, value] of params.entries()) {\n if (!Object.hasOwn(out, key)) {\n out[key] = value\n continue\n }\n const existing = out[key]\n if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n out[key] = [existing, value]\n }\n }\n return out\n}\n\n/**\n * Parse request body based on Content-Type. JSON is the canonical path;\n * empty body returns `undefined` (the handler treats as \"no body\").\n *\n * **Inline-only mode (default):** handles `application/json` and `text/*`.\n * Other content-types return `undefined`. Multipart/form-data requires\n * the opt-in `bodyParser: 'full'` mode (T5a.2 Phase E).\n */\nasync function parseBodyInline(request: Request): Promise<unknown> {\n // GET/HEAD have no body by spec; even if the consumer sets one, ignore it\n // (matches Web Request semantics — `body` is null for GET/HEAD anyway).\n if (request.method === 'GET' || request.method === 'HEAD') return undefined\n const contentType = request.headers.get('content-type') ?? ''\n if (contentType.includes('application/json')) {\n const text = await request.text()\n if (text.length === 0) return undefined\n try {\n return JSON.parse(text)\n } catch {\n // Malformed JSON — return undefined; Zod schema (if any) will fail with\n // a more useful \"required\" message than a raw SyntaxError.\n return undefined\n }\n }\n // text/plain or no body: return raw text or undefined\n if (contentType.startsWith('text/')) {\n const text = await request.text()\n return text.length === 0 ? undefined : text\n }\n return undefined\n}\n\n/**\n * T5a.2 Phase E — \"full\" body parser delegating to `parseWebRequestBody`.\n * Returns a `ParsedWebBody` (`{ json?, fields, files }`) for JSON OR\n * multipart, or `undefined` when the body is empty / unparseable.\n *\n * Handler downstream pattern:\n * `body?.json` (JSON requests)\n * `body?.fields` + `body?.files` (multipart upload requests)\n *\n * Limits enforced by parseWebRequestBody:\n * - declared Content-Length cap (default 10MB × maxFiles + 1MB margin)\n * - per-file size cap (default 10MB)\n * - max files (default 10)\n */\nasync function parseBodyFull(request: Request): Promise<unknown> {\n if (request.method === 'GET' || request.method === 'HEAD') return undefined\n const { parseWebRequestBody } = await import('./body-parser-web.js')\n try {\n const parsed = await parseWebRequestBody(request)\n // If nothing parsed (empty body OR unhandled content-type), return undefined\n // so Zod schemas treat it as missing — same semantics as inline parser.\n if (\n parsed.json === undefined &&\n Object.keys(parsed.fields).length === 0 &&\n parsed.files.length === 0\n ) {\n return undefined\n }\n return parsed\n } catch {\n return undefined\n }\n}\n\n/**\n * Build an envelope-shaped 400 Response for a Zod validation failure. Uses\n * the canonical `TheoErrorEnvelope` shape per G5 D3 (boundary translation).\n */\nfunction validationErrorResponse(zodError: z.ZodError, field: string): Response {\n const envelope: TheoErrorEnvelope = {\n code: 'BAD_REQUEST',\n message: `Validation failed: ${field}`,\n ext: {\n fields: zodError.issues.map((issue) => ({\n path: issue.path.join('.'),\n message: issue.message,\n })),\n },\n }\n return new Response(JSON.stringify(envelope), {\n status: 400,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * Run a `defineRoute` config against a parsed Web Request. Returns the raw\n * handler result; serialization to Response happens in the caller.\n *\n * Throws if Zod validation fails (caller catches and emits 400).\n */\nasync function runHandler(\n config: WebRouteHandlerConfig,\n request: Request,\n bodyParser: 'inline' | 'full' = 'inline',\n paramsInput: Record<string, string> = {},\n context: Record<string, unknown> = {},\n): Promise<{ ok: true; result: unknown } | { ok: false; response: Response }> {\n const url = new URL(request.url)\n const queryRaw = searchParamsToObject(url.searchParams)\n const bodyRaw =\n bodyParser === 'full' ? await parseBodyFull(request) : await parseBodyInline(request)\n // T3.1 — route params resolved upstream (matchRoute) and threaded via\n // opts.params. Defaults to `{}` so callers that don't supply params keep the\n // prior behavior (a route declaring config.params then fails validation).\n const paramsRaw = paramsInput\n\n // M33 — validate the three input channels via the SINGLE shared pipeline (`validateRouteInput`),\n // the same one the in-process caller (`callProcedure`) uses. The HTTP path maps a failure to a\n // 400 Response; the in-process path throws. One pipeline, no drift.\n const validated = validateRouteInput(config, {\n query: queryRaw,\n body: bodyRaw,\n params: paramsRaw,\n })\n if (!validated.ok) {\n return { ok: false, response: validationErrorResponse(validated.error, validated.channel) }\n }\n const { query, body, params } = validated\n\n const result = await config.handler({ query, body, params, request, context })\n return validateResponseOutput(config.response, result) ?? { ok: true, result }\n}\n\n/**\n * Validate a plain-object handler return against `config.response` (D1/D2). A\n * mismatch is a SERVER fault → 500 envelope. `Response`-instance returns and\n * `undefined`/`null` (→ 204) skip validation — parity with the Node runner,\n * which validates only in its plain-object branch. Returns `undefined` when no\n * validation applies (caller forwards the raw result).\n */\nfunction validateResponseOutput(\n response: unknown,\n result: unknown,\n): { ok: true; result: unknown } | { ok: false; response: Response } | undefined {\n const validatable = result !== undefined && result !== null && !(result instanceof Response)\n if (!validatable || !isZodLike(response)) return undefined\n const parsed = response.safeParse(result)\n if (parsed.success) return { ok: true, result: parsed.data }\n const err = new TheoError({\n code: 'INTERNAL_SERVER_ERROR',\n message: 'response validation failed',\n ext: { issues: parsed.error?.issues },\n })\n return { ok: false, response: handlerErrorResponse(err) }\n}\n\n/**\n * Serialize a handler return value into a native Web `Response`. Conventions:\n * - `undefined` / `void` → 204 No Content.\n * - existing `Response` instance → pass through unchanged.\n * - everything else → 200 JSON.\n */\nfunction toResponse(result: unknown, status?: number): Response {\n if (result === undefined) {\n return new Response(null, { status: 204 })\n }\n if (result instanceof Response) {\n return result\n }\n return new Response(JSON.stringify(result), {\n status: status ?? 200,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * Build an envelope-shaped 500 Response when a handler throws. Uses\n * `serverErrorToEnvelope` so existing ad-hoc Error classes (AuthRequired,\n * FileTooLarge, etc.) get mapped to canonical envelope codes.\n */\nfunction handlerErrorResponse(err: unknown): Response {\n const envelope = serverErrorToEnvelope(err)\n // Map envelope code → HTTP status when possible. Default to 500 for\n // INTERNAL_SERVER_ERROR. Other codes map per HTTP semantics.\n const status = envelopeCodeToStatus(envelope.code)\n return new Response(JSON.stringify(envelope), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n// envelopeCodeToStatus extracted to core/contracts/envelope-code-to-status.ts\n// (architecture-remediation T1.2, 2026-06-12)\n\n/**\n * Optional behavior knobs for `executeWebRequest`. Each knob defaults to\n * the safe \"no-op\" stance so existing Phase A consumers (T1.2 fixture\n * tests) keep working unchanged.\n *\n * **`csrfMode`** (T5a.2 Phase B slice 1/6) — when set to `'strict'`, the\n * Web-Standards request gate runs `validateCsrfRequest` BEFORE method\n * dispatch on state-changing methods (POST/PUT/PATCH/DELETE) and emits a\n * `403 FORBIDDEN` envelope when the check fails. Default: `'off'` (no\n * CSRF enforcement) to preserve Phase A backward compat. Production\n * consumers SHOULD pass `csrfMode: 'strict'`.\n *\n * Per the T5a.2 plan v1.0 § Phase B header-only leaves: csrf.ts is the\n * first leaf to be migrated (slice 1/6); 5 more sibling leaves remain\n * (csrf-multi-header, csrf-readiness-endpoint, csp-report, cors, cookies).\n */\nexport interface ExecuteWebRequestOptions {\n csrfMode?: 'off' | 'strict'\n /**\n * T3.1 — route params resolved upstream by `matchRoute` (e.g. `{ id: '42' }`\n * for `/users/:id`). Threaded to the handler's `params` input and validated\n * against `config.params` (Zod) when declared. Defaults to `{}` — callers\n * that don't supply params keep the prior behavior (additive, backward-compat).\n */\n params?: Record<string, string>\n /**\n * T3.2 — Web-Standards middleware chain. Runs in order AFTER the CSRF gate\n * (EC-3) and BEFORE the handler. A middleware returning a `Response`\n * short-circuits (handler not reached); mutating `context` passes data to\n * the handler. Omitted → zero overhead (handler runs directly).\n */\n middleware?: readonly WebMiddleware[]\n /**\n * T5a.2 Phase E — body parser strategy.\n *\n * - `'inline'` (default): handle `application/json` + `text/*` only.\n * Returns the parsed value (object for JSON, string for text). Other\n * content-types (e.g., multipart) return `undefined`.\n * - `'full'`: delegate to `parseWebRequestBody` for multipart support\n * + per-file size caps + max-files cap (Web Standards `request.formData()`\n * under the hood). Returns a `ParsedWebBody` object:\n * `{ json?, fields, files }`. Multipart consumers MUST opt into this\n * mode; JSON-only routes pay zero cost staying on `'inline'`.\n */\n bodyParser?: 'inline' | 'full'\n /**\n * T5a.2 Phase G slice 1/N — plugin lifecycle hooks.\n *\n * Adapters (Node, CF Workers, Bun, Deno) wire `WebPluginContext`-shaped\n * hooks at the executeWebRequest lifecycle. Lifecycle order mirrors the\n * Fastify / Hono convention:\n *\n * 1. CSRF check (when opts.csrfMode === 'strict')\n * 2. onRequest — earliest, before body parsing. Plugins can short-circuit\n * by setting `ctx.response` (handler skipped; subsequent hooks see\n * the short-circuit response).\n * 3. body parse (inline OR full per opts.bodyParser)\n * 4. preHandler — after body parsed, before handler runs. Same\n * short-circuit semantic.\n * 5. handler invocation\n * 6. onResponse — after handler returns OR after a hook short-circuit.\n * `ctx.response` is populated.\n * 7. onError — fires if any of (handler, onRequest, preHandler) throws.\n * `ctx.response` is the envelope-shaped error response built via\n * serverErrorToEnvelope.\n *\n * `responseHeaders` is shared across hooks; the final Response merges\n * them with the handler's Response headers (handler headers win on\n * conflict; hook headers add new ones). Decorations made via\n * `ctx.ctx[key] = value` persist across hooks (request-scoped state).\n *\n * `hooks: undefined` (default) → no plugin lifecycle, Phase A behavior\n * preserved. Production consumers wire via the WebPluginRunner facade\n * (a future Phase G slice).\n */\n hooks?: {\n onRequest?: readonly WebOnRequestHook[]\n preHandler?: readonly WebPreHandlerHook[]\n onResponse?: readonly WebOnResponseHook[]\n onError?: readonly WebOnErrorHook[]\n }\n /**\n * Stable request identifier propagated into hook contexts. Adapters\n * resolve via traceparent / x-request-id / generated UUID (see\n * `extractTraceIdFromRequest` from Phase C slice 1/2). Default:\n * `globalThis.crypto.randomUUID()`.\n */\n requestId?: string\n}\n\n/**\n * Methods that require CSRF enforcement when `csrfMode: 'strict'`. GET\n * and HEAD are read-only per HTTP semantics and bypass CSRF (the threat\n * model is state-changing requests forged via cross-origin POSTs); OPTIONS\n * is the CORS preflight and also bypasses.\n */\nexport const CSRF_PROTECTED_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Web-Standards entry-point for executing a route module against a native\n * Web `Request`. Returns a native Web `Response`.\n *\n * Method dispatch: looks up the handler keyed by `request.method`\n * (uppercase). Returns 405 if the method isn't exported.\n *\n * @example\n * import * as users from './app/users/route.js'\n * import { executeWebRequest } from 'theokit/server'\n *\n * const response = await executeWebRequest(\n * new Request('http://localhost/api/users', { method: 'GET' }),\n * users,\n * { csrfMode: 'strict' },\n * )\n */\n/**\n * T5a.2 Phase G slice 1/N — merge hook-mutated response headers into the\n * handler's Response. Handler-set headers win on conflict (the handler\n * has the most context about its own response); hook headers add new\n * entries (e.g., CORS, Set-Cookie). Returns a new Response with the\n * merged headers + same body/status as the source.\n *\n * Set-Cookie is multi-value at the Web spec layer — `getSetCookie()` is\n * the only way to retrieve multiple values. The merge appends ALL hook-\n * set Set-Cookie values to the response (multiple Set-Cookie headers is\n * spec-correct and how browsers expect cookie issuance).\n */\nfunction mergeHookHeaders(response: Response, hookHeaders: Headers): Response {\n if ([...hookHeaders].length === 0) return response\n const merged = new Headers(response.headers)\n for (const [k, v] of hookHeaders.entries()) {\n if (k.toLowerCase() === 'set-cookie') continue // handled separately\n if (!merged.has(k)) merged.set(k, v)\n }\n for (const sc of hookHeaders.getSetCookie()) {\n merged.append('Set-Cookie', sc)\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: merged,\n })\n}\n\n/** Build a 405 envelope Response. */\nfunction methodNotAllowedResponse(method: string): Response {\n const envelope: TheoErrorEnvelope = {\n code: 'METHOD_NOT_ALLOWED',\n message: `Method ${method} not allowed`,\n }\n return new Response(JSON.stringify(envelope), {\n status: 405,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/** Build a 403 CSRF envelope Response. */\nfunction csrfFailedResponse(reason: string): Response {\n const envelope: TheoErrorEnvelope = {\n code: 'FORBIDDEN',\n message: `CSRF check failed: ${reason}`,\n }\n return new Response(JSON.stringify(envelope), {\n status: 403,\n headers: { 'content-type': 'application/json' },\n })\n}\n\nexport async function executeWebRequest(\n request: Request,\n routeModule: WebRouteModule,\n opts: ExecuteWebRequestOptions = {},\n): Promise<Response> {\n const method = request.method.toUpperCase() as keyof WebRouteModule\n const config = routeModule[method] as WebRouteHandlerConfig | undefined\n\n // T5a.2 Phase G slice 1/N — plugin lifecycle hooks.\n // When opts.hooks is undefined, skip the entire hook orchestration to\n // preserve Phase A backward compat (zero overhead for consumers not\n // wiring hooks). In the no-hooks branch, dispatch + CSRF gates run\n // FIRST and 405 short-circuits before the handler runs.\n if (opts.hooks === undefined) {\n if (config === undefined || typeof config.handler !== 'function') {\n return methodNotAllowedResponse(method)\n }\n if (opts.csrfMode === 'strict' && CSRF_PROTECTED_METHODS.has(method)) {\n const csrfCheck = validateCsrfRequest(request)\n if (!csrfCheck.valid) return csrfFailedResponse(csrfCheck.reason)\n }\n try {\n // T3.2 — middleware runs AFTER the CSRF gate (EC-3), BEFORE the handler.\n const context: Record<string, unknown> = {}\n if (opts.middleware?.length) {\n const shortCircuit = await runWebMiddleware(request, opts.middleware, context)\n if (shortCircuit) return shortCircuit\n }\n const outcome = await runHandler(\n config,\n request,\n opts.bodyParser ?? 'inline',\n opts.params ?? {},\n context,\n )\n if (!outcome.ok) return outcome.response\n return toResponse(outcome.result, config.status)\n } catch (err) {\n return handlerErrorResponse(err)\n }\n }\n\n // With hooks: onRequest hooks run BEFORE method dispatch (Hono /\n // Fastify convention) so CORS preflight plugins can intercept OPTIONS\n // requests regardless of route shape. If no hook short-circuits, then\n // 405 fires when the method isn't exported by the route module.\n return runWithHooks(request, config, opts, opts.hooks)\n}\n\n/**\n * Run the request through the full plugin lifecycle. Extracted to keep\n * `executeWebRequest`'s cyclomatic + cognitive complexity under the lint\n * caps (15/20). Pure side-effect surface — same return type as the\n * no-hooks branch.\n */\n/**\n * Pre-handler pipeline: onRequest hooks → CSRF gate → preHandler hooks →\n * method dispatch + handler. Mutates `hookCtx.response` on short-circuit\n * OR on handler completion. Extracted from `runWithHooks` to keep the\n * latter's cyclomatic complexity under the lint cap (15).\n */\nasync function runPreHandlerPipeline(\n hookCtx: WebPluginContext,\n request: Request,\n config: WebRouteHandlerConfig | undefined,\n opts: ExecuteWebRequestOptions,\n hooks: NonNullable<ExecuteWebRequestOptions['hooks']>,\n): Promise<void> {\n const method = request.method.toUpperCase()\n const runList = async (list: readonly WebOnRequestHook[]): Promise<void> => {\n for (const hook of list) {\n if (hookCtx.response !== undefined) return\n await hook(hookCtx)\n }\n }\n // onRequest first (CORS preflight + auth gate intercept before dispatch).\n if (hooks.onRequest) await runList(hooks.onRequest)\n // CSRF gate AFTER onRequest (auth-short-circuit avoids CSRF cost) but\n // BEFORE the handler.\n if (\n hookCtx.response === undefined &&\n opts.csrfMode === 'strict' &&\n CSRF_PROTECTED_METHODS.has(method)\n ) {\n const csrfCheck = validateCsrfRequest(request)\n if (!csrfCheck.valid) hookCtx.response = csrfFailedResponse(csrfCheck.reason)\n }\n if (hookCtx.response === undefined && hooks.preHandler) {\n await runList(hooks.preHandler)\n }\n if (hookCtx.response === undefined) {\n await runHandlerStage(hookCtx, request, config, opts, method)\n }\n}\n\n/**\n * T3.2 — the middleware + handler stage of the hook pipeline. Extracted from\n * `runPreHandlerPipeline` to keep its cyclomatic complexity under the lint cap.\n * Order: 405 check → user middleware (after CSRF + preHandler) → handler.\n */\nasync function runHandlerStage(\n hookCtx: WebPluginContext,\n request: Request,\n config: WebRouteHandlerConfig | undefined,\n opts: ExecuteWebRequestOptions,\n method: string,\n): Promise<void> {\n // 405 if route module doesn't export this method.\n if (config === undefined || typeof config.handler !== 'function') {\n hookCtx.response = methodNotAllowedResponse(method)\n return\n }\n // hookCtx.ctx is the shared per-request context the middleware mutates.\n if (opts.middleware?.length) {\n const shortCircuit = await runWebMiddleware(request, opts.middleware, hookCtx.ctx)\n if (shortCircuit) {\n hookCtx.response = shortCircuit\n return\n }\n }\n const outcome = await runHandler(\n config,\n request,\n opts.bodyParser ?? 'inline',\n opts.params ?? {},\n hookCtx.ctx,\n )\n hookCtx.response = outcome.ok ? toResponse(outcome.result, config.status) : outcome.response\n}\n\nasync function runWithHooks(\n request: Request,\n config: WebRouteHandlerConfig | undefined,\n opts: ExecuteWebRequestOptions,\n hooks: NonNullable<ExecuteWebRequestOptions['hooks']>,\n): Promise<Response> {\n const hookCtx: WebPluginContext = {\n request,\n responseHeaders: new Headers(),\n ctx: {},\n requestId: opts.requestId ?? globalThis.crypto.randomUUID(),\n }\n try {\n await runPreHandlerPipeline(hookCtx, request, config, opts, hooks)\n if (hooks.onResponse) {\n for (const hook of hooks.onResponse) {\n await hook(hookCtx)\n }\n }\n // runPreHandlerPipeline guarantees hookCtx.response is set (via either\n // a hook short-circuit OR handler outcome OR 405). TS doesn't infer this\n // post-mutation; the assertion is safe per the function's contract.\n const finalResponse =\n hookCtx.response ??\n new Response(\n JSON.stringify({ code: 'INTERNAL_SERVER_ERROR', message: 'No response built' }),\n {\n status: 500,\n headers: { 'content-type': 'application/json' },\n },\n )\n return mergeHookHeaders(finalResponse, hookCtx.responseHeaders)\n } catch (err) {\n return runErrorHooks(err, hookCtx, hooks.onError)\n }\n}\n\n/**\n * Run onError hooks against an envelope-shaped error response. EC-9 —\n * each hook throw is swallowed to avoid error-in-error-handler recursion.\n * Returns the merged final Response.\n */\nasync function runErrorHooks(\n err: unknown,\n hookCtx: WebPluginContext,\n onError: readonly WebOnErrorHook[] | undefined,\n): Promise<Response> {\n const errorResponse = handlerErrorResponse(err)\n if (onError !== undefined) {\n const errorCtx: WebPluginErrorContext = {\n ...hookCtx,\n response: errorResponse,\n error: err,\n }\n for (const hook of onError) {\n try {\n await hook(errorCtx)\n } catch {\n // EC-9: error in error handler — swallow to avoid recursion.\n }\n }\n }\n return mergeHookHeaders(errorResponse, hookCtx.responseHeaders)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,SAAS,WAAW,cAAc,cAAc,gBAAgB;AAChE,SAAS,eAAe;AAExB,OAAO,YAAY;AACnB,SAAS,cAAwC;AAKjD,IAAM,qBAAqB;AAE3B,IAAM,QAAQ,oBAAI,IAA2B;AAGtC,SAAS,iBAAuB;AAC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AAO,iBAAiB,eAAe,QAAQ,eAAe;AAAA,EAChE,SAAS,KAAK;AACZ,WAAO,cAAc,KAAK,SAAS,MAAM,OAAO;AAAA,EAClD;AACF;AAOA,eAAe,cACb,KACA,SACA,SACmB;AACnB,QAAM,gBAAgB,qBAAqB,GAAG;AAC9C,MAAI,YAAY,QAAW;AACzB,UAAM,WAAkC;AAAA,MACtC,GAAG;AAAA,MACH,UAAU;AAAA,MACV,OAAO;AAAA,IACT;AACA,eAAW,QAAQ,SAAS;AAC1B,UAAI;AACF,cAAM,KAAK,QAAQ;AAAA,MACrB,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACA,SAAO,iBAAiB,eAAe,QAAQ,eAAe;AAChE;","names":[]}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// src/server/define/define-agent-tool.ts
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
var TOOL_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
|
|
4
|
+
function isZodObject(schema) {
|
|
5
|
+
let current = schema;
|
|
6
|
+
for (let depth = 0; depth < 10; depth++) {
|
|
7
|
+
if (current instanceof z.ZodObject) return true;
|
|
8
|
+
const z4 = current.def;
|
|
9
|
+
if (z4?.type === "object") return true;
|
|
10
|
+
const z3 = current._def;
|
|
11
|
+
if (z3?.typeName === "ZodObject") return true;
|
|
12
|
+
const next = z4?.innerType ?? z4?.in ?? z3?.schema ?? z3?.innerType;
|
|
13
|
+
if (next !== void 0) {
|
|
14
|
+
current = next;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
function defineAgentTool(spec) {
|
|
22
|
+
if (!TOOL_NAME_REGEX.test(spec.name)) {
|
|
23
|
+
throw new Error(
|
|
24
|
+
`defineAgentTool: name must match ${TOOL_NAME_REGEX.source}. Got: ${JSON.stringify(spec.name)}`
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
if (!isZodObject(spec.inputSchema)) {
|
|
28
|
+
throw new Error("defineAgentTool: inputSchema must be a ZodObject (z.object({...}))");
|
|
29
|
+
}
|
|
30
|
+
if (spec.description.length === 0) {
|
|
31
|
+
console.warn(
|
|
32
|
+
`defineAgentTool(${JSON.stringify(spec.name)}): empty description degrades LLM tool selection \u2014 provide a one-sentence summary.`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
const { $schema: _$schema, ...inputSchema } = z.toJSONSchema(spec.inputSchema);
|
|
36
|
+
return {
|
|
37
|
+
name: spec.name,
|
|
38
|
+
description: spec.description,
|
|
39
|
+
inputSchema,
|
|
40
|
+
handler: async (input, ctx) => {
|
|
41
|
+
const parsed = spec.inputSchema.parse(input);
|
|
42
|
+
const result = await spec.handler(parsed, ctx);
|
|
43
|
+
if (spec.toModelOutput) return spec.toModelOutput(result);
|
|
44
|
+
if (typeof result !== "string") {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`defineAgentTool(${JSON.stringify(spec.name)}): handler returned a non-string; provide toModelOutput to map it to a string for the model.`
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
return result;
|
|
50
|
+
},
|
|
51
|
+
// M18 — carry the per-target formatters for the app (ignored by the SDK wire).
|
|
52
|
+
...spec.transform !== void 0 ? { transform: spec.transform } : {}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function applyTransform(tool, result, target) {
|
|
56
|
+
const fn = tool.transform?.[target];
|
|
57
|
+
return fn ? fn(result) : result;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export {
|
|
61
|
+
defineAgentTool,
|
|
62
|
+
applyTransform
|
|
63
|
+
};
|
|
64
|
+
//# sourceMappingURL=chunk-63BUBV5L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/define/define-agent-tool.ts"],"sourcesContent":["import { z } from 'zod'\n\n/**\n * Item #4 — `defineAgentTool`\n *\n * Sugar over the `@theokit/sdk` `CustomTool` contract. Takes a Zod schema +\n * handler and produces a structurally-compatible `CustomTool` that\n * `Agent.create({ tools: [...] })` accepts.\n *\n * Uses Zod v4's native `z.toJSONSchema()` to convert the input schema to\n * JSON Schema for LLM providers.\n *\n * Handler error propagation:\n * `defineAgentTool` parses the input via the Zod schema BEFORE calling the\n * user handler. Invalid input throws a `ZodError`, which the SDK's tool-\n * dispatcher treats as a tool failure and surfaces to the model as a tool\n * error (the SDK owns the wire; ADR D3).\n */\n\n/**\n * Local mirror of the SDK's `CustomTool` interface. We don't `import type`\n * from `@theokit/sdk` because the SDK is an optional peer (consumers who\n * never call `defineAgentTool` shouldn't need it installed). The shape is\n * the wire contract; any structurally-matching object is accepted by\n * `Agent.create({ tools })`.\n *\n * @public\n */\nexport interface CustomTool {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n handler: (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown },\n ) => string | Promise<string>\n /** M18 — optional per-target formatters for the app's UI/transcript (ignored by the SDK wire). */\n transform?: ToolTransform\n}\n\n/**\n * M18 — per-target formatters. `display` shapes the rich handler result for the UI; `transcript`\n * shapes it for a saved transcript. Applied by {@link applyTransform}, never by the model wire.\n */\nexport interface ToolTransform<R = unknown> {\n display?: (result: R) => unknown\n transcript?: (result: R) => unknown\n}\n\n/**\n * Spec accepted by {@link defineAgentTool}. `inputSchema` is a Zod 3 schema\n * rooted in `z.object(...)`. The `handler` argument type is inferred via\n * `z.infer<T>`.\n *\n * @public\n */\nexport interface DefineAgentToolSpec<T extends z.ZodType, R = string> {\n /** Tool name surfaced to the LLM. Must match `^[a-zA-Z][a-zA-Z0-9_-]{0,63}$`. */\n name: string\n /** Description surfaced to the LLM. Required — drives tool-selection accuracy. */\n description: string\n /** Zod schema describing the input. Must be `z.object(...)` at the root. */\n inputSchema: T\n /**\n * Handler invoked with the parsed input and, optionally, the run `ctx` (M7). `ctx.context`\n * is the object supplied once at the agent level (`defineAgent({ context })`) or per-run —\n * read it for shared config like `projectRoot` instead of baking it into the factory.\n * `ctx.signal` is the abort signal. Optional so existing one-arg handlers keep working.\n *\n * M18 — the handler may return RICH data `R` (not just a string) when `toModelOutput` is\n * provided to map it to the model-visible string.\n */\n handler: (\n input: z.infer<T>,\n ctx?: { signal?: AbortSignal; context?: unknown },\n ) => R | Promise<R>\n /**\n * M18 — map the rich handler result `R` to the string the model sees. Required (in practice)\n * when `handler` returns a non-string; absent ⇒ the handler must return a string.\n */\n toModelOutput?: (result: R) => string\n /** M18 — per-target formatters (`display` / `transcript`) for the app, applied by {@link applyTransform}. */\n transform?: ToolTransform<R>\n}\n\nconst TOOL_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/\n\nfunction isZodObject(schema: z.ZodType): boolean {\n // Refinements (`.refine`), transforms (`.transform`), and defaults wrap the\n // underlying schema — walk the chain until we hit a ZodObject (or give up).\n // Supports both zod 4 (`instanceof z.ZodObject`, `def.type === 'object'`,\n // wrappers via `def.innerType` / pipe via `def.in`) and zod 3\n // (`_def.typeName === 'ZodObject'`, wrappers via `_def.schema`/`_def.innerType`).\n let current: unknown = schema\n for (let depth = 0; depth < 10; depth++) {\n if (current instanceof z.ZodObject) return true\n const z4 = (current as { def?: { type?: string; innerType?: unknown; in?: unknown } }).def\n if (z4?.type === 'object') return true\n const z3 = (current as { _def?: { typeName?: string; schema?: unknown; innerType?: unknown } })\n ._def\n if (z3?.typeName === 'ZodObject') return true\n const next = z4?.innerType ?? z4?.in ?? z3?.schema ?? z3?.innerType\n if (next !== undefined) {\n current = next\n continue\n }\n return false\n }\n return false\n}\n\n/**\n * Build a {@link CustomTool} from a Zod 3 schema + handler.\n *\n * Behavior:\n * - Validates `name` matches the LLM tool-name regex.\n * - Requires `inputSchema` to be a `ZodObject` (Anthropic + SDK contract).\n * - Warns (not throws) if `description` is empty — empty descriptions\n * degrade LLM tool selection.\n * - Converts the Zod schema to JSON Schema 7 inline (no `$ref`s — LLMs handle\n * inline schemas more reliably).\n * - Strips the top-level `$schema` field (Anthropic rejects schemas with\n * `$schema` at root in some provider modes).\n * - Wraps the handler to parse the input via the Zod schema BEFORE invoking\n * the user code — bad LLM-supplied input throws `ZodError`, which the SDK\n * converts to `tool_result(isError)`.\n *\n * @public\n */\nexport function defineAgentTool<T extends z.ZodType, R = string>(\n spec: DefineAgentToolSpec<T, R>,\n): CustomTool {\n if (!TOOL_NAME_REGEX.test(spec.name)) {\n throw new Error(\n `defineAgentTool: name must match ${TOOL_NAME_REGEX.source}. Got: ${JSON.stringify(spec.name)}`,\n )\n }\n if (!isZodObject(spec.inputSchema)) {\n throw new Error('defineAgentTool: inputSchema must be a ZodObject (z.object({...}))')\n }\n if (spec.description.length === 0) {\n console.warn(\n `defineAgentTool(${JSON.stringify(spec.name)}): empty description degrades LLM tool selection — provide a one-sentence summary.`,\n )\n }\n\n // Zod v4 native JSON Schema conversion — replaces zod-to-json-schema dep.\n // Strip $schema (Anthropic + some providers reject it).\n const { $schema: _$schema, ...inputSchema } = z.toJSONSchema(spec.inputSchema) as Record<\n string,\n unknown\n > & {\n $schema?: unknown\n }\n\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown },\n ): Promise<string> => {\n const parsed = spec.inputSchema.parse(input)\n // M7 — forward the run ctx so the handler can read `ctx.context` (e.g. projectRoot).\n const result = await spec.handler(parsed, ctx)\n // M18 — shape the (possibly rich) result into the model-visible string.\n if (spec.toModelOutput) return spec.toModelOutput(result)\n if (typeof result !== 'string') {\n throw new Error(\n `defineAgentTool(${JSON.stringify(spec.name)}): handler returned a non-string; provide toModelOutput to map it to a string for the model.`,\n )\n }\n return result\n },\n // M18 — carry the per-target formatters for the app (ignored by the SDK wire).\n ...(spec.transform !== undefined ? { transform: spec.transform as ToolTransform } : {}),\n }\n}\n\n/**\n * M18 — apply a tool's `transform` for a target (`display` / `transcript`). Returns the formatted\n * value, or the raw `result` when the tool declares no transform for that target.\n */\nexport function applyTransform(\n tool: CustomTool,\n result: unknown,\n target: 'display' | 'transcript',\n): unknown {\n const fn = tool.transform?.[target]\n return fn ? fn(result) : result\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAqFlB,IAAM,kBAAkB;AAExB,SAAS,YAAY,QAA4B;AAM/C,MAAI,UAAmB;AACvB,WAAS,QAAQ,GAAG,QAAQ,IAAI,SAAS;AACvC,QAAI,mBAAmB,EAAE,UAAW,QAAO;AAC3C,UAAM,KAAM,QAA2E;AACvF,QAAI,IAAI,SAAS,SAAU,QAAO;AAClC,UAAM,KAAM,QACT;AACH,QAAI,IAAI,aAAa,YAAa,QAAO;AACzC,UAAM,OAAO,IAAI,aAAa,IAAI,MAAM,IAAI,UAAU,IAAI;AAC1D,QAAI,SAAS,QAAW;AACtB,gBAAU;AACV;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAoBO,SAAS,gBACd,MACY;AACZ,MAAI,CAAC,gBAAgB,KAAK,KAAK,IAAI,GAAG;AACpC,UAAM,IAAI;AAAA,MACR,oCAAoC,gBAAgB,MAAM,UAAU,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,IAC/F;AAAA,EACF;AACA,MAAI,CAAC,YAAY,KAAK,WAAW,GAAG;AAClC,UAAM,IAAI,MAAM,oEAAoE;AAAA,EACtF;AACA,MAAI,KAAK,YAAY,WAAW,GAAG;AACjC,YAAQ;AAAA,MACN,mBAAmB,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,IAC9C;AAAA,EACF;AAIA,QAAM,EAAE,SAAS,UAAU,GAAG,YAAY,IAAI,EAAE,aAAa,KAAK,WAAW;AAO7E,SAAO;AAAA,IACL,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA,IAClB;AAAA,IACA,SAAS,OACP,OACA,QACoB;AACpB,YAAM,SAAS,KAAK,YAAY,MAAM,KAAK;AAE3C,YAAM,SAAS,MAAM,KAAK,QAAQ,QAAQ,GAAG;AAE7C,UAAI,KAAK,cAAe,QAAO,KAAK,cAAc,MAAM;AACxD,UAAI,OAAO,WAAW,UAAU;AAC9B,cAAM,IAAI;AAAA,UACR,mBAAmB,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,QAC9C;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA;AAAA,IAEA,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAA2B,IAAI,CAAC;AAAA,EACvF;AACF;AAMO,SAAS,eACd,MACA,QACA,QACS;AACT,QAAM,KAAK,KAAK,YAAY,MAAM;AAClC,SAAO,KAAK,GAAG,MAAM,IAAI;AAC3B;","names":[]}
|
|
@@ -1,20 +1,30 @@
|
|
|
1
|
-
import {
|
|
2
|
-
broadcastToDevtools
|
|
3
|
-
} from "./chunk-7BIM27LV.js";
|
|
4
1
|
import {
|
|
5
2
|
buildServicesProxyConfig,
|
|
6
3
|
servicesConfigSchema
|
|
7
4
|
} from "./chunk-D7ZH7DTG.js";
|
|
8
5
|
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
6
|
+
broadcastToDevtools
|
|
7
|
+
} from "./chunk-7BIM27LV.js";
|
|
8
|
+
import {
|
|
12
9
|
loadEnv,
|
|
13
10
|
resolveTransformer
|
|
14
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-4MTCKE5I.js";
|
|
12
|
+
import {
|
|
13
|
+
BATCH_PATH,
|
|
14
|
+
TRACE_HEADER,
|
|
15
|
+
createCorsHandler,
|
|
16
|
+
executeAction,
|
|
17
|
+
executeRoute,
|
|
18
|
+
extractTraceId,
|
|
19
|
+
handleBatchRequest,
|
|
20
|
+
sendError
|
|
21
|
+
} from "./chunk-TGTNRUH3.js";
|
|
15
22
|
import {
|
|
16
23
|
findSuggestion
|
|
17
24
|
} from "./chunk-5QW7IQQU.js";
|
|
25
|
+
import {
|
|
26
|
+
logRequest
|
|
27
|
+
} from "./chunk-WFNLNIJX.js";
|
|
18
28
|
import {
|
|
19
29
|
createPluginRunnerFromConfig
|
|
20
30
|
} from "./chunk-IAJ2JVEH.js";
|
|
@@ -38,28 +48,20 @@ import {
|
|
|
38
48
|
handleCspReport,
|
|
39
49
|
handleCsrfReadiness
|
|
40
50
|
} from "./chunk-JBCHWRKF.js";
|
|
51
|
+
import {
|
|
52
|
+
validateCsrfRequest
|
|
53
|
+
} from "./chunk-TSLSIRBR.js";
|
|
54
|
+
import {
|
|
55
|
+
extractAppResources,
|
|
56
|
+
handleMcpJsonRpc,
|
|
57
|
+
isMcpPath
|
|
58
|
+
} from "./chunk-HZ6USUHC.js";
|
|
41
59
|
import {
|
|
42
60
|
generateNonce
|
|
43
61
|
} from "./chunk-C3ZZ56YZ.js";
|
|
44
62
|
import {
|
|
45
63
|
importUserModule
|
|
46
64
|
} from "./chunk-7MQOHNHE.js";
|
|
47
|
-
import {
|
|
48
|
-
BATCH_PATH,
|
|
49
|
-
TRACE_HEADER,
|
|
50
|
-
createCorsHandler,
|
|
51
|
-
executeAction,
|
|
52
|
-
executeRoute,
|
|
53
|
-
extractTraceId,
|
|
54
|
-
handleBatchRequest,
|
|
55
|
-
sendError
|
|
56
|
-
} from "./chunk-TGTNRUH3.js";
|
|
57
|
-
import {
|
|
58
|
-
logRequest
|
|
59
|
-
} from "./chunk-WFNLNIJX.js";
|
|
60
|
-
import {
|
|
61
|
-
validateCsrfRequest
|
|
62
|
-
} from "./chunk-TSLSIRBR.js";
|
|
63
65
|
|
|
64
66
|
// src/vite-plugin/index.ts
|
|
65
67
|
import { existsSync as existsSync9 } from "fs";
|
|
@@ -3342,19 +3344,19 @@ async function theoPluginAsync(rootOrOptions) {
|
|
|
3342
3344
|
})
|
|
3343
3345
|
);
|
|
3344
3346
|
}
|
|
3345
|
-
const { appTypedClientPlugin } = await import("./app-typed-client-
|
|
3347
|
+
const { appTypedClientPlugin } = await import("./app-typed-client-4PAUHTO6.js");
|
|
3346
3348
|
const appClientPlugin = appTypedClientPlugin({
|
|
3347
3349
|
cwd: projectRoot,
|
|
3348
3350
|
serverDir: serverDirAbs,
|
|
3349
3351
|
distDir: resolve9(projectRoot, ".theokit")
|
|
3350
3352
|
});
|
|
3351
|
-
const { actionsVirtualModule } = await import("./actions-virtual-module-
|
|
3353
|
+
const { actionsVirtualModule } = await import("./actions-virtual-module-XHVLBFNN.js");
|
|
3352
3354
|
const actionsPlugin = actionsVirtualModule({
|
|
3353
3355
|
serverDir: serverDirAbs,
|
|
3354
3356
|
distDir: resolve9(projectRoot, ".theokit")
|
|
3355
3357
|
});
|
|
3356
3358
|
const { agentsTypedClientPlugin } = await import("./agents-typed-client-MAAILRI6.js");
|
|
3357
|
-
const { generateManifest } = await import("./internal-api-
|
|
3359
|
+
const { generateManifest } = await import("./internal-api-QSP2HCUU.js");
|
|
3358
3360
|
const agentsClientPlugin = agentsTypedClientPlugin({
|
|
3359
3361
|
projectRoot,
|
|
3360
3362
|
agentsDir: agentsDirName,
|
|
@@ -3537,4 +3539,4 @@ export {
|
|
|
3537
3539
|
theoPluginAsync,
|
|
3538
3540
|
theoPlugin
|
|
3539
3541
|
};
|
|
3540
|
-
//# sourceMappingURL=chunk-
|
|
3542
|
+
//# sourceMappingURL=chunk-HAOPVC47.js.map
|