@mcpcloud/runtime 0.5.0 → 0.7.1

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/node.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! @mcpcloud/runtime v0.5.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.7.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
2
  import{timingSafeEqual as Z}from"node:crypto";import{createServer as _}from"node:http";import{Readable as $}from"node:stream";function Y(){return typeof process>"u"?{}:process.env}function Q(j=Y()){return j.MCP_BEARER_TOKEN?.trim()||null}function C(j,x){let G=Buffer.from(j),z=Buffer.from(x);return G.length===z.length&&Z(G,z)}function D(j,x){let G=Q(x);if(!G)return null;if(new URL(j.url).pathname==="/health")return null;let z=j.headers.get("authorization")??"",F=/^Bearer\s+(.+)$/i.exec(z.trim());if(F&&C(F[1].trim(),G))return null;return Response.json({error:"unauthorized",message:"This MCP endpoint requires a bearer token (set in Authorization: Bearer <token>)."},{status:401,headers:{"www-authenticate":"Bearer"}})}function W(j,x){let G=new URL(j.url??"/",x),z=new Headers;for(let[I,J]of Object.entries(j.headers))if(Array.isArray(J))for(let N of J)z.append(I,N);else if(typeof J==="string")z.set(I,J);let F=j.method??"GET",L=F==="GET"||F==="HEAD"?void 0:$.toWeb(j);return new Request(G,{method:F,headers:z,body:L,...L?{duplex:"half"}:{}})}async function H(j,x){if(x.statusCode=j.status,j.headers.forEach((z,F)=>{x.setHeader(F,z)}),!j.body){x.end();return}let G=j.body.getReader();for(;;){let{done:z,value:F}=await G.read();if(z)break;x.write(F)}x.end()}function A(j,x={}){let G=x.port??Number(process.env.PORT??8080),z=x.hostname??"0.0.0.0",F=_((L,I)=>{let J=`http://${L.headers.host??`${z}:${G}`}`,N=W(L,J),O=D(N,x.env);(O?Promise.resolve(O):j.handleRequest(N,x.env)).then((X)=>H(X,I)).catch(()=>{I.statusCode=500,I.end(JSON.stringify({error:"internal_error"}))})});return F.listen(G,z),F}export{A as serve};
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Run agent-authored JavaScript in a QuickJS context that has nothing in it.
3
+ *
4
+ * §5: "Nothing is exposed to guest code by default — no fetch, no filesystem, no
5
+ * env, no globals. We build the guest's entire universe by hand, and that
6
+ * hand-built surface is where every policy decision lands." This module is that
7
+ * surface. It deliberately provides NO way to reach outward; tool bindings are
8
+ * added in P2, through a host function that routes via the existing policy path.
9
+ *
10
+ * The engine is our own build of quickjs-ng 0.16.0 (packages/runtime/engine),
11
+ * not the published variant, which ships 0.12.1 and ten advisories.
12
+ */
13
+ import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
14
+ import type { SandboxLimits, SandboxResult } from './types';
15
+ export declare const DEFAULT_SANDBOX_LIMITS: SandboxLimits;
16
+ export interface CreateSandboxOptions {
17
+ /** Loaded once per isolate and reused; instantiation is the expensive part. */
18
+ engine: QuickJSWASMModule;
19
+ limits?: Partial<SandboxLimits>;
20
+ }
21
+ /**
22
+ * Execute `source` and return a discriminated result.
23
+ *
24
+ * Never throws for guest-caused failures — a thrown guest error, a syntax error
25
+ * and an exhausted budget are all ordinary `ok: false` results, because the
26
+ * caller has to act on them rather than crash. Genuine host bugs still throw.
27
+ *
28
+ * Disposal is in a `finally` so it happens on every path, including one where
29
+ * the guest throws. §4 measured a 3.5x slowdown from a single leaked handle per
30
+ * tool call, so this is structural rather than a discipline to remember. The one
31
+ * deliberate exception is the poisoned path — see STACK_ESCAPE_NOTE.
32
+ */
33
+ export declare function runInSandbox(options: CreateSandboxOptions, source: string): SandboxResult;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The sandbox's public shapes: what you may configure, and what you get back.
3
+ *
4
+ * Kept separate from the implementation so callers (and the dispatch worker,
5
+ * which will only ever hold a result) can import the types without pulling in
6
+ * the engine.
7
+ */
8
+ /**
9
+ * Ceilings applied to a single execution. Every one is required — there is no
10
+ * "unlimited" default, because an unbounded sandbox running agent-authored code
11
+ * is the thing this module exists to prevent.
12
+ */
13
+ export interface SandboxLimits {
14
+ /**
15
+ * Interrupt-handler ticks before the execution is killed.
16
+ *
17
+ * This is the primary control and the metering unit (§3): it is deterministic,
18
+ * reproducible, and independent of how loaded the machine is — unlike
19
+ * wall-clock, which is neither.
20
+ */
21
+ opcodeBudget: number;
22
+ /** Guest heap ceiling, well inside the 128 MB isolate limit. */
23
+ memoryBytes: number;
24
+ /** Guards runaway recursion, which memory alone does not catch quickly. */
25
+ stackBytes: number;
26
+ /**
27
+ * Wall-clock backstop, in milliseconds.
28
+ *
29
+ * Deliberately secondary. On workerd — our primary host — `Date.now()` does
30
+ * not advance during synchronous execution, so a deadline cannot fire in the
31
+ * middle of a tight loop. Opcodes catch that case; this catches an execution
32
+ * that is slow because it is waiting, once tool calls exist in P2.
33
+ */
34
+ wallClockMs: number;
35
+ }
36
+ /** Which ceiling an execution hit. Named so a caller can retry narrower. */
37
+ export type SandboxBudget = 'opcodes' | 'memory' | 'stack' | 'wall_clock';
38
+ /**
39
+ * Why an execution failed.
40
+ *
41
+ * `budget_exhausted` is separated from `runtime_error` on purpose: they call for
42
+ * opposite responses. A guest exception means the code is wrong; a budget means
43
+ * the code may be fine and the input too large. §8.3 turns on that distinction —
44
+ * naming the budget lets an agent retry with a narrower query instead of
45
+ * rewriting working code.
46
+ */
47
+ export type SandboxFailureKind = 'syntax_error' | 'runtime_error' | 'budget_exhausted' | 'timeout';
48
+ export interface SandboxSuccess {
49
+ ok: true;
50
+ /** Whatever the guest returned, marshalled through JSON. */
51
+ value: unknown;
52
+ /** Interrupt ticks consumed. The metering read (§3). */
53
+ opcodesUsed: number;
54
+ }
55
+ export interface SandboxFailure {
56
+ ok: false;
57
+ kind: SandboxFailureKind;
58
+ message: string;
59
+ /** Present only when `kind` is `budget_exhausted`. */
60
+ budget?: SandboxBudget;
61
+ /** Guest stack, when the engine produced one. Harness frames are stripped. */
62
+ stack?: string;
63
+ opcodesUsed: number;
64
+ }
65
+ export type SandboxResult = SandboxSuccess | SandboxFailure;
package/dist/stdio.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @mcpcloud/runtime v0.5.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.7.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
2
  var T4=Object.defineProperty;var _4=(W)=>W;function Z4(W,Q){this[W]=_4.bind(null,Q)}var YY=(W,Q)=>{for(var Y in Q)T4(W,Y,{get:Q[Y],enumerable:!0,configurable:!0,set:Z4.bind(Q,Y)})};import E4 from"node:process";var J2=Object.freeze({status:"aborted"});function K(W,Q,Y){function X(w,q){if(!w._zod)Object.defineProperty(w,"_zod",{value:{def:q,constr:H,traits:new Set},enumerable:!1});if(w._zod.traits.has(W))return;w._zod.traits.add(W),Q(w,q);let L=H.prototype,B=Object.keys(L);for(let z=0;z<B.length;z++){let I=B[z];if(!(I in w))w[I]=L[I].bind(w)}}let G=Y?.Parent??Object;class J extends G{}Object.defineProperty(J,"name",{value:W});function H(w){var q;let L=Y?.Parent?new J:this;X(L,w),(q=L._zod).deferred??(q.deferred=[]);for(let B of L._zod.deferred)B();return L}return Object.defineProperty(H,"init",{value:X}),Object.defineProperty(H,Symbol.hasInstance,{value:(w)=>{if(Y?.Parent&&w instanceof Y.Parent)return!0;return w?._zod?.traits?.has(W)}}),Object.defineProperty(H,"name",{value:W}),H}var H2=Symbol("zod_brand");class a extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class MW extends Error{constructor(W){super(`Encountered unidirectional transform during encode: ${W}`);this.name="ZodEncodeError"}}var vW={};function r(W){if(W)Object.assign(vW,W);return vW}var D={};YY(D,{unwrapMessage:()=>zW,uint8ArrayToHex:()=>Q6,uint8ArrayToBase64url:()=>s4,uint8ArrayToBase64:()=>qY,stringifyPrimitive:()=>cW,slugify:()=>wQ,shallowClone:()=>GY,safeExtend:()=>d4,required:()=>t4,randomString:()=>y4,propertyKeyTypes:()=>qQ,promiseAllObject:()=>u4,primitiveTypes:()=>JY,prefixIssues:()=>QW,pick:()=>l4,partial:()=>i4,parsedType:()=>BQ,optionalKeys:()=>KQ,omit:()=>r4,objectClone:()=>h4,numKeys:()=>m4,nullish:()=>IW,normalizeParams:()=>U,mergeDefs:()=>s,merge:()=>n4,jsonStringifyReplacer:()=>AW,joinValues:()=>gW,issue:()=>KW,isPlainObject:()=>XW,isObject:()=>HW,hexToUint8Array:()=>W6,getSizableOrigin:()=>wY,getParsedType:()=>f4,getLengthableOrigin:()=>OW,getEnumValues:()=>UW,getElementAtPath:()=>c4,floatSafeRemainder:()=>HQ,finalizeIssue:()=>t,extend:()=>p4,escapeRegex:()=>WW,esc:()=>hW,defineLazy:()=>F,createTransparentProxy:()=>o4,cloneDef:()=>x4,clone:()=>i,cleanRegex:()=>VW,cleanEnum:()=>e4,captureStackTrace:()=>xW,cached:()=>qW,base64urlToUint8Array:()=>a4,base64ToUint8Array:()=>AY,assignProp:()=>YW,assertNotEqual:()=>j4,assertNever:()=>v4,assertIs:()=>k4,assertEqual:()=>C4,assert:()=>g4,allowsEval:()=>AQ,aborted:()=>GW,NUMBER_FORMAT_RANGES:()=>LQ,Class:()=>KY,BIGINT_FORMAT_RANGES:()=>HY});function C4(W){return W}function j4(W){return W}function k4(W){}function v4(W){throw Error("Unexpected value in exhaustive check")}function g4(W){}function UW(W){let Q=Object.values(W).filter((X)=>typeof X==="number");return Object.entries(W).filter(([X,G])=>Q.indexOf(+X)===-1).map(([X,G])=>G)}function gW(W,Q="|"){return W.map((Y)=>cW(Y)).join(Q)}function AW(W,Q){if(typeof Q==="bigint")return Q.toString();return Q}function qW(W){return{get value(){{let Y=W();return Object.defineProperty(this,"value",{value:Y}),Y}throw Error("cached value already set")}}}function IW(W){return W===null||W===void 0}function VW(W){let Q=W.startsWith("^")?1:0,Y=W.endsWith("$")?W.length-1:W.length;return W.slice(Q,Y)}function HQ(W,Q){let Y=(W.toString().split(".")[1]||"").length,X=Q.toString(),G=(X.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(X)){let q=X.match(/\d?e-(\d?)/);if(q?.[1])G=Number.parseInt(q[1])}let J=Y>G?Y:G,H=Number.parseInt(W.toFixed(J).replace(".","")),w=Number.parseInt(Q.toFixed(J).replace(".",""));return H%w/10**J}var XY=Symbol("evaluating");function F(W,Q,Y){let X=void 0;Object.defineProperty(W,Q,{get(){if(X===XY)return;if(X===void 0)X=XY,X=Y();return X},set(G){Object.defineProperty(W,Q,{value:G})},configurable:!0})}function h4(W){return Object.create(Object.getPrototypeOf(W),Object.getOwnPropertyDescriptors(W))}function YW(W,Q,Y){Object.defineProperty(W,Q,{value:Y,writable:!0,enumerable:!0,configurable:!0})}function s(...W){let Q={};for(let Y of W){let X=Object.getOwnPropertyDescriptors(Y);Object.assign(Q,X)}return Object.defineProperties({},Q)}function x4(W){return s(W._zod.def)}function c4(W,Q){if(!Q)return W;return Q.reduce((Y,X)=>Y?.[X],W)}function u4(W){let Q=Object.keys(W),Y=Q.map((X)=>W[X]);return Promise.all(Y).then((X)=>{let G={};for(let J=0;J<Q.length;J++)G[Q[J]]=X[J];return G})}function y4(W=10){let Y="";for(let X=0;X<W;X++)Y+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Y}function hW(W){return JSON.stringify(W)}function wQ(W){return W.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var xW="captureStackTrace"in Error?Error.captureStackTrace:(...W)=>{};function HW(W){return typeof W==="object"&&W!==null&&!Array.isArray(W)}var AQ=qW(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(W){return!1}});function XW(W){if(HW(W)===!1)return!1;let Q=W.constructor;if(Q===void 0)return!0;if(typeof Q!=="function")return!0;let Y=Q.prototype;if(HW(Y)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Y,"isPrototypeOf")===!1)return!1;return!0}function GY(W){if(XW(W))return{...W};if(Array.isArray(W))return[...W];return W}function m4(W){let Q=0;for(let Y in W)if(Object.prototype.hasOwnProperty.call(W,Y))Q++;return Q}var f4=(W)=>{let Q=typeof W;switch(Q){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(W)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(W))return"array";if(W===null)return"null";if(W.then&&typeof W.then==="function"&&W.catch&&typeof W.catch==="function")return"promise";if(typeof Map<"u"&&W instanceof Map)return"map";if(typeof Set<"u"&&W instanceof Set)return"set";if(typeof Date<"u"&&W instanceof Date)return"date";if(typeof File<"u"&&W instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Q}`)}},qQ=new Set(["string","number","symbol"]),JY=new Set(["string","number","bigint","boolean","symbol","undefined"]);function WW(W){return W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(W,Q,Y){let X=new W._zod.constr(Q??W._zod.def);if(!Q||Y?.parent)X._zod.parent=W;return X}function U(W){let Q=W;if(!Q)return{};if(typeof Q==="string")return{error:()=>Q};if(Q?.message!==void 0){if(Q?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Q.error=Q.message}if(delete Q.message,typeof Q.error==="string")return{...Q,error:()=>Q.error};return Q}function o4(W){let Q;return new Proxy({},{get(Y,X,G){return Q??(Q=W()),Reflect.get(Q,X,G)},set(Y,X,G,J){return Q??(Q=W()),Reflect.set(Q,X,G,J)},has(Y,X){return Q??(Q=W()),Reflect.has(Q,X)},deleteProperty(Y,X){return Q??(Q=W()),Reflect.deleteProperty(Q,X)},ownKeys(Y){return Q??(Q=W()),Reflect.ownKeys(Q)},getOwnPropertyDescriptor(Y,X){return Q??(Q=W()),Reflect.getOwnPropertyDescriptor(Q,X)},defineProperty(Y,X,G){return Q??(Q=W()),Reflect.defineProperty(Q,X,G)}})}function cW(W){if(typeof W==="bigint")return W.toString()+"n";if(typeof W==="string")return`"${W}"`;return`${W}`}function KQ(W){return Object.keys(W).filter((Q)=>{return W[Q]._zod.optin==="optional"&&W[Q]._zod.optout==="optional"})}var LQ={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},HY={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function l4(W,Q){let Y=W._zod.def,X=Y.checks;if(X&&X.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let J=s(W._zod.def,{get shape(){let H={};for(let w in Q){if(!(w in Y.shape))throw Error(`Unrecognized key: "${w}"`);if(!Q[w])continue;H[w]=Y.shape[w]}return YW(this,"shape",H),H},checks:[]});return i(W,J)}function r4(W,Q){let Y=W._zod.def,X=Y.checks;if(X&&X.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let J=s(W._zod.def,{get shape(){let H={...W._zod.def.shape};for(let w in Q){if(!(w in Y.shape))throw Error(`Unrecognized key: "${w}"`);if(!Q[w])continue;delete H[w]}return YW(this,"shape",H),H},checks:[]});return i(W,J)}function p4(W,Q){if(!XW(Q))throw Error("Invalid input to extend: expected a plain object");let Y=W._zod.def.checks;if(Y&&Y.length>0){let J=W._zod.def.shape;for(let H in Q)if(Object.getOwnPropertyDescriptor(J,H)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let G=s(W._zod.def,{get shape(){let J={...W._zod.def.shape,...Q};return YW(this,"shape",J),J}});return i(W,G)}function d4(W,Q){if(!XW(Q))throw Error("Invalid input to safeExtend: expected a plain object");let Y=s(W._zod.def,{get shape(){let X={...W._zod.def.shape,...Q};return YW(this,"shape",X),X}});return i(W,Y)}function n4(W,Q){let Y=s(W._zod.def,{get shape(){let X={...W._zod.def.shape,...Q._zod.def.shape};return YW(this,"shape",X),X},get catchall(){return Q._zod.def.catchall},checks:[]});return i(W,Y)}function i4(W,Q,Y){let G=Q._zod.def.checks;if(G&&G.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let H=s(Q._zod.def,{get shape(){let w=Q._zod.def.shape,q={...w};if(Y)for(let L in Y){if(!(L in w))throw Error(`Unrecognized key: "${L}"`);if(!Y[L])continue;q[L]=W?new W({type:"optional",innerType:w[L]}):w[L]}else for(let L in w)q[L]=W?new W({type:"optional",innerType:w[L]}):w[L];return YW(this,"shape",q),q},checks:[]});return i(Q,H)}function t4(W,Q,Y){let X=s(Q._zod.def,{get shape(){let G=Q._zod.def.shape,J={...G};if(Y)for(let H in Y){if(!(H in J))throw Error(`Unrecognized key: "${H}"`);if(!Y[H])continue;J[H]=new W({type:"nonoptional",innerType:G[H]})}else for(let H in G)J[H]=new W({type:"nonoptional",innerType:G[H]});return YW(this,"shape",J),J}});return i(Q,X)}function GW(W,Q=0){if(W.aborted===!0)return!0;for(let Y=Q;Y<W.issues.length;Y++)if(W.issues[Y]?.continue!==!0)return!0;return!1}function QW(W,Q){return Q.map((Y)=>{var X;return(X=Y).path??(X.path=[]),Y.path.unshift(W),Y})}function zW(W){return typeof W==="string"?W:W?.message}function t(W,Q,Y){let X={...W,path:W.path??[]};if(!W.message){let G=zW(W.inst?._zod.def?.error?.(W))??zW(Q?.error?.(W))??zW(Y.customError?.(W))??zW(Y.localeError?.(W))??"Invalid input";X.message=G}if(delete X.inst,delete X.continue,!Q?.reportInput)delete X.input;return X}function wY(W){if(W instanceof Set)return"set";if(W instanceof Map)return"map";if(W instanceof File)return"file";return"unknown"}function OW(W){if(Array.isArray(W))return"array";if(typeof W==="string")return"string";return"unknown"}function BQ(W){let Q=typeof W;switch(Q){case"number":return Number.isNaN(W)?"nan":"number";case"object":{if(W===null)return"null";if(Array.isArray(W))return"array";let Y=W;if(Y&&Object.getPrototypeOf(Y)!==Object.prototype&&"constructor"in Y&&Y.constructor)return Y.constructor.name}}return Q}function KW(...W){let[Q,Y,X]=W;if(typeof Q==="string")return{message:Q,code:"custom",input:Y,inst:X};return{...Q}}function e4(W){return Object.entries(W).filter(([Q,Y])=>{return Number.isNaN(Number.parseInt(Q,10))}).map((Q)=>Q[1])}function AY(W){let Q=atob(W),Y=new Uint8Array(Q.length);for(let X=0;X<Q.length;X++)Y[X]=Q.charCodeAt(X);return Y}function qY(W){let Q="";for(let Y=0;Y<W.length;Y++)Q+=String.fromCharCode(W[Y]);return btoa(Q)}function a4(W){let Q=W.replace(/-/g,"+").replace(/_/g,"/"),Y="=".repeat((4-Q.length%4)%4);return AY(Q+Y)}function s4(W){return qY(W).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function W6(W){let Q=W.replace(/^0x/,"");if(Q.length%2!==0)throw Error("Invalid hex string length");let Y=new Uint8Array(Q.length/2);for(let X=0;X<Q.length;X+=2)Y[X/2]=Number.parseInt(Q.slice(X,X+2),16);return Y}function Q6(W){return Array.from(W).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class KY{constructor(...W){}}var LY=(W,Q)=>{W.name="$ZodError",Object.defineProperty(W,"_zod",{value:W._zod,enumerable:!1}),Object.defineProperty(W,"issues",{value:Q,enumerable:!1}),W.message=JSON.stringify(Q,AW,2),Object.defineProperty(W,"toString",{value:()=>W.message,enumerable:!1})},uW=K("$ZodError",LY),NQ=K("$ZodError",LY,{Parent:Error});function BY(W,Q=(Y)=>Y.message){let Y={},X=[];for(let G of W.issues)if(G.path.length>0)Y[G.path[0]]=Y[G.path[0]]||[],Y[G.path[0]].push(Q(G));else X.push(Q(G));return{formErrors:X,fieldErrors:Y}}function NY(W,Q=(Y)=>Y.message){let Y={_errors:[]},X=(G)=>{for(let J of G.issues)if(J.code==="invalid_union"&&J.errors.length)J.errors.map((H)=>X({issues:H}));else if(J.code==="invalid_key")X({issues:J.issues});else if(J.code==="invalid_element")X({issues:J.issues});else if(J.path.length===0)Y._errors.push(Q(J));else{let H=Y,w=0;while(w<J.path.length){let q=J.path[w];if(w!==J.path.length-1)H[q]=H[q]||{_errors:[]};else H[q]=H[q]||{_errors:[]},H[q]._errors.push(Q(J));H=H[q],w++}}};return X(W),Y}var yW=(W)=>(Q,Y,X,G)=>{let J=X?Object.assign(X,{async:!1}):{async:!1},H=Q._zod.run({value:Y,issues:[]},J);if(H instanceof Promise)throw new a;if(H.issues.length){let w=new(G?.Err??W)(H.issues.map((q)=>t(q,J,r())));throw xW(w,G?.callee),w}return H.value};var mW=(W)=>async(Q,Y,X,G)=>{let J=X?Object.assign(X,{async:!0}):{async:!0},H=Q._zod.run({value:Y,issues:[]},J);if(H instanceof Promise)H=await H;if(H.issues.length){let w=new(G?.Err??W)(H.issues.map((q)=>t(q,J,r())));throw xW(w,G?.callee),w}return H.value};var DW=(W)=>(Q,Y,X)=>{let G=X?{...X,async:!1}:{async:!1},J=Q._zod.run({value:Y,issues:[]},G);if(J instanceof Promise)throw new a;return J.issues.length?{success:!1,error:new(W??uW)(J.issues.map((H)=>t(H,G,r())))}:{success:!0,data:J.value}},MY=DW(NQ),FW=(W)=>async(Q,Y,X)=>{let G=X?Object.assign(X,{async:!0}):{async:!0},J=Q._zod.run({value:Y,issues:[]},G);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new W(J.issues.map((H)=>t(H,G,r())))}:{success:!0,data:J.value}},zY=FW(NQ),UY=(W)=>(Q,Y,X)=>{let G=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return yW(W)(Q,Y,G)};var IY=(W)=>(Q,Y,X)=>{return yW(W)(Q,Y,X)};var VY=(W)=>async(Q,Y,X)=>{let G=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return mW(W)(Q,Y,G)};var OY=(W)=>async(Q,Y,X)=>{return mW(W)(Q,Y,X)};var DY=(W)=>(Q,Y,X)=>{let G=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return DW(W)(Q,Y,G)};var FY=(W)=>(Q,Y,X)=>{return DW(W)(Q,Y,X)};var $Y=(W)=>async(Q,Y,X)=>{let G=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return FW(W)(Q,Y,G)};var PY=(W)=>async(Q,Y,X)=>{return FW(W)(Q,Y,X)};var EY=/^[cC][^\s-]{8,}$/,RY=/^[0-9a-z]+$/,SY=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bY=/^[0-9a-vA-V]{20}$/,TY=/^[A-Za-z0-9]{27}$/,_Y=/^[a-zA-Z0-9_-]{21}$/,ZY=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var CY=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,MQ=(W)=>{if(!W)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${W}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var jY=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var X6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function kY(){return new RegExp(X6,"u")}var vY=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,gY=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var hY=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,xY=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cY=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zQ=/^[A-Za-z0-9_-]*$/;var uY=/^\+[1-9]\d{6,14}$/,yY="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",mY=new RegExp(`^${yY}$`);function fY(W){return typeof W.precision==="number"?W.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":W.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${W.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function oY(W){return new RegExp(`^${fY(W)}$`)}function lY(W){let Q=fY({precision:W.precision}),Y=["Z"];if(W.local)Y.push("");if(W.offset)Y.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let X=`${Q}(?:${Y.join("|")})`;return new RegExp(`^${yY}T(?:${X})$`)}var rY=(W)=>{let Q=W?`[\\s\\S]{${W?.minimum??0},${W?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Q}$`)};var pY=/^-?\d+$/,fW=/^-?\d+(?:\.\d+)?$/,dY=/^(?:true|false)$/i,nY=/^null$/i;var iY=/^[^A-Z]*$/,tY=/^[^a-z]*$/;var g=K("$ZodCheck",(W,Q)=>{var Y;W._zod??(W._zod={}),W._zod.def=Q,(Y=W._zod).onattach??(Y.onattach=[])}),eY={number:"number",bigint:"bigint",object:"date"},UQ=K("$ZodCheckLessThan",(W,Q)=>{g.init(W,Q);let Y=eY[typeof Q.value];W._zod.onattach.push((X)=>{let G=X._zod.bag,J=(Q.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(Q.value<J)if(Q.inclusive)G.maximum=Q.value;else G.exclusiveMaximum=Q.value}),W._zod.check=(X)=>{if(Q.inclusive?X.value<=Q.value:X.value<Q.value)return;X.issues.push({origin:Y,code:"too_big",maximum:typeof Q.value==="object"?Q.value.getTime():Q.value,input:X.value,inclusive:Q.inclusive,inst:W,continue:!Q.abort})}}),IQ=K("$ZodCheckGreaterThan",(W,Q)=>{g.init(W,Q);let Y=eY[typeof Q.value];W._zod.onattach.push((X)=>{let G=X._zod.bag,J=(Q.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(Q.value>J)if(Q.inclusive)G.minimum=Q.value;else G.exclusiveMinimum=Q.value}),W._zod.check=(X)=>{if(Q.inclusive?X.value>=Q.value:X.value>Q.value)return;X.issues.push({origin:Y,code:"too_small",minimum:typeof Q.value==="object"?Q.value.getTime():Q.value,input:X.value,inclusive:Q.inclusive,inst:W,continue:!Q.abort})}}),aY=K("$ZodCheckMultipleOf",(W,Q)=>{g.init(W,Q),W._zod.onattach.push((Y)=>{var X;(X=Y._zod.bag).multipleOf??(X.multipleOf=Q.value)}),W._zod.check=(Y)=>{if(typeof Y.value!==typeof Q.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof Y.value==="bigint"?Y.value%Q.value===BigInt(0):HQ(Y.value,Q.value)===0)return;Y.issues.push({origin:typeof Y.value,code:"not_multiple_of",divisor:Q.value,input:Y.value,inst:W,continue:!Q.abort})}}),sY=K("$ZodCheckNumberFormat",(W,Q)=>{g.init(W,Q),Q.format=Q.format||"float64";let Y=Q.format?.includes("int"),X=Y?"int":"number",[G,J]=LQ[Q.format];W._zod.onattach.push((H)=>{let w=H._zod.bag;if(w.format=Q.format,w.minimum=G,w.maximum=J,Y)w.pattern=pY}),W._zod.check=(H)=>{let w=H.value;if(Y){if(!Number.isInteger(w)){H.issues.push({expected:X,format:Q.format,code:"invalid_type",continue:!1,input:w,inst:W});return}if(!Number.isSafeInteger(w)){if(w>0)H.issues.push({input:w,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:W,origin:X,inclusive:!0,continue:!Q.abort});else H.issues.push({input:w,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:W,origin:X,inclusive:!0,continue:!Q.abort});return}}if(w<G)H.issues.push({origin:"number",input:w,code:"too_small",minimum:G,inclusive:!0,inst:W,continue:!Q.abort});if(w>J)H.issues.push({origin:"number",input:w,code:"too_big",maximum:J,inclusive:!0,inst:W,continue:!Q.abort})}});var W0=K("$ZodCheckMaxLength",(W,Q)=>{var Y;g.init(W,Q),(Y=W._zod.def).when??(Y.when=(X)=>{let G=X.value;return!IW(G)&&G.length!==void 0}),W._zod.onattach.push((X)=>{let G=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Q.maximum<G)X._zod.bag.maximum=Q.maximum}),W._zod.check=(X)=>{let G=X.value;if(G.length<=Q.maximum)return;let H=OW(G);X.issues.push({origin:H,code:"too_big",maximum:Q.maximum,inclusive:!0,input:G,inst:W,continue:!Q.abort})}}),Q0=K("$ZodCheckMinLength",(W,Q)=>{var Y;g.init(W,Q),(Y=W._zod.def).when??(Y.when=(X)=>{let G=X.value;return!IW(G)&&G.length!==void 0}),W._zod.onattach.push((X)=>{let G=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Q.minimum>G)X._zod.bag.minimum=Q.minimum}),W._zod.check=(X)=>{let G=X.value;if(G.length>=Q.minimum)return;let H=OW(G);X.issues.push({origin:H,code:"too_small",minimum:Q.minimum,inclusive:!0,input:G,inst:W,continue:!Q.abort})}}),Y0=K("$ZodCheckLengthEquals",(W,Q)=>{var Y;g.init(W,Q),(Y=W._zod.def).when??(Y.when=(X)=>{let G=X.value;return!IW(G)&&G.length!==void 0}),W._zod.onattach.push((X)=>{let G=X._zod.bag;G.minimum=Q.length,G.maximum=Q.length,G.length=Q.length}),W._zod.check=(X)=>{let G=X.value,J=G.length;if(J===Q.length)return;let H=OW(G),w=J>Q.length;X.issues.push({origin:H,...w?{code:"too_big",maximum:Q.length}:{code:"too_small",minimum:Q.length},inclusive:!0,exact:!0,input:X.value,inst:W,continue:!Q.abort})}}),$W=K("$ZodCheckStringFormat",(W,Q)=>{var Y,X;if(g.init(W,Q),W._zod.onattach.push((G)=>{let J=G._zod.bag;if(J.format=Q.format,Q.pattern)J.patterns??(J.patterns=new Set),J.patterns.add(Q.pattern)}),Q.pattern)(Y=W._zod).check??(Y.check=(G)=>{if(Q.pattern.lastIndex=0,Q.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:Q.format,input:G.value,...Q.pattern?{pattern:Q.pattern.toString()}:{},inst:W,continue:!Q.abort})});else(X=W._zod).check??(X.check=()=>{})}),X0=K("$ZodCheckRegex",(W,Q)=>{$W.init(W,Q),W._zod.check=(Y)=>{if(Q.pattern.lastIndex=0,Q.pattern.test(Y.value))return;Y.issues.push({origin:"string",code:"invalid_format",format:"regex",input:Y.value,pattern:Q.pattern.toString(),inst:W,continue:!Q.abort})}}),G0=K("$ZodCheckLowerCase",(W,Q)=>{Q.pattern??(Q.pattern=iY),$W.init(W,Q)}),J0=K("$ZodCheckUpperCase",(W,Q)=>{Q.pattern??(Q.pattern=tY),$W.init(W,Q)}),H0=K("$ZodCheckIncludes",(W,Q)=>{g.init(W,Q);let Y=WW(Q.includes),X=new RegExp(typeof Q.position==="number"?`^.{${Q.position}}${Y}`:Y);Q.pattern=X,W._zod.onattach.push((G)=>{let J=G._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(X)}),W._zod.check=(G)=>{if(G.value.includes(Q.includes,Q.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:Q.includes,input:G.value,inst:W,continue:!Q.abort})}}),w0=K("$ZodCheckStartsWith",(W,Q)=>{g.init(W,Q);let Y=new RegExp(`^${WW(Q.prefix)}.*`);Q.pattern??(Q.pattern=Y),W._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Y)}),W._zod.check=(X)=>{if(X.value.startsWith(Q.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:Q.prefix,input:X.value,inst:W,continue:!Q.abort})}}),A0=K("$ZodCheckEndsWith",(W,Q)=>{g.init(W,Q);let Y=new RegExp(`.*${WW(Q.suffix)}$`);Q.pattern??(Q.pattern=Y),W._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Y)}),W._zod.check=(X)=>{if(X.value.endsWith(Q.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:Q.suffix,input:X.value,inst:W,continue:!Q.abort})}});var q0=K("$ZodCheckOverwrite",(W,Q)=>{g.init(W,Q),W._zod.check=(Y)=>{Y.value=Q.tx(Y.value)}});class VQ{constructor(W=[]){if(this.content=[],this.indent=0,this)this.args=W}indented(W){this.indent+=1,W(this),this.indent-=1}write(W){if(typeof W==="function"){W(this,{execution:"sync"}),W(this,{execution:"async"});return}let Y=W.split(`
3
3
  `).filter((J)=>J),X=Math.min(...Y.map((J)=>J.length-J.trimStart().length)),G=Y.map((J)=>J.slice(X)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of G)this.content.push(J)}compile(){let W=Function,Q=this?.args,X=[...(this?.content??[""]).map((G)=>` ${G}`)];return new W(...Q,X.join(`
4
4
  `))}}var L0={major:4,minor:3,patch:6};var E=K("$ZodType",(W,Q)=>{var Y;W??(W={}),W._zod.def=Q,W._zod.bag=W._zod.bag||{},W._zod.version=L0;let X=[...W._zod.def.checks??[]];if(W._zod.traits.has("$ZodCheck"))X.unshift(W);for(let G of X)for(let J of G._zod.onattach)J(W);if(X.length===0)(Y=W._zod).deferred??(Y.deferred=[]),W._zod.deferred?.push(()=>{W._zod.run=W._zod.parse});else{let G=(H,w,q)=>{let L=GW(H),B;for(let z of w){if(z._zod.def.when){if(!z._zod.def.when(H))continue}else if(L)continue;let I=H.issues.length,V=z._zod.check(H);if(V instanceof Promise&&q?.async===!1)throw new a;if(B||V instanceof Promise)B=(B??Promise.resolve()).then(async()=>{if(await V,H.issues.length===I)return;if(!L)L=GW(H,I)});else{if(H.issues.length===I)continue;if(!L)L=GW(H,I)}}if(B)return B.then(()=>{return H});return H},J=(H,w,q)=>{if(GW(H))return H.aborted=!0,H;let L=G(w,X,q);if(L instanceof Promise){if(q.async===!1)throw new a;return L.then((B)=>W._zod.parse(B,q))}return W._zod.parse(L,q)};W._zod.run=(H,w)=>{if(w.skipChecks)return W._zod.parse(H,w);if(w.direction==="backward"){let L=W._zod.parse({value:H.value,issues:[]},{...w,skipChecks:!0});if(L instanceof Promise)return L.then((B)=>{return J(B,H,w)});return J(L,H,w)}let q=W._zod.parse(H,w);if(q instanceof Promise){if(w.async===!1)throw new a;return q.then((L)=>G(L,X,w))}return G(q,X,w)}}F(W,"~standard",()=>({validate:(G)=>{try{let J=MY(W,G);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return zY(W,G).then((H)=>H.success?{value:H.data}:{issues:H.error?.issues})}},vendor:"zod",version:1}))}),pW=K("$ZodString",(W,Q)=>{E.init(W,Q),W._zod.pattern=[...W?._zod.bag?.patterns??[]].pop()??rY(W._zod.bag),W._zod.parse=(Y,X)=>{if(Q.coerce)try{Y.value=String(Y.value)}catch(G){}if(typeof Y.value==="string")return Y;return Y.issues.push({expected:"string",code:"invalid_type",input:Y.value,inst:W}),Y}}),R=K("$ZodStringFormat",(W,Q)=>{$W.init(W,Q),pW.init(W,Q)}),D0=K("$ZodGUID",(W,Q)=>{Q.pattern??(Q.pattern=CY),R.init(W,Q)}),F0=K("$ZodUUID",(W,Q)=>{if(Q.version){let X={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[Q.version];if(X===void 0)throw Error(`Invalid UUID version: "${Q.version}"`);Q.pattern??(Q.pattern=MQ(X))}else Q.pattern??(Q.pattern=MQ());R.init(W,Q)}),$0=K("$ZodEmail",(W,Q)=>{Q.pattern??(Q.pattern=jY),R.init(W,Q)}),P0=K("$ZodURL",(W,Q)=>{R.init(W,Q),W._zod.check=(Y)=>{try{let X=Y.value.trim(),G=new URL(X);if(Q.hostname){if(Q.hostname.lastIndex=0,!Q.hostname.test(G.hostname))Y.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Q.hostname.source,input:Y.value,inst:W,continue:!Q.abort})}if(Q.protocol){if(Q.protocol.lastIndex=0,!Q.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))Y.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:Q.protocol.source,input:Y.value,inst:W,continue:!Q.abort})}if(Q.normalize)Y.value=G.href;else Y.value=X;return}catch(X){Y.issues.push({code:"invalid_format",format:"url",input:Y.value,inst:W,continue:!Q.abort})}}}),E0=K("$ZodEmoji",(W,Q)=>{Q.pattern??(Q.pattern=kY()),R.init(W,Q)}),R0=K("$ZodNanoID",(W,Q)=>{Q.pattern??(Q.pattern=_Y),R.init(W,Q)}),S0=K("$ZodCUID",(W,Q)=>{Q.pattern??(Q.pattern=EY),R.init(W,Q)}),b0=K("$ZodCUID2",(W,Q)=>{Q.pattern??(Q.pattern=RY),R.init(W,Q)}),T0=K("$ZodULID",(W,Q)=>{Q.pattern??(Q.pattern=SY),R.init(W,Q)}),_0=K("$ZodXID",(W,Q)=>{Q.pattern??(Q.pattern=bY),R.init(W,Q)}),Z0=K("$ZodKSUID",(W,Q)=>{Q.pattern??(Q.pattern=TY),R.init(W,Q)}),C0=K("$ZodISODateTime",(W,Q)=>{Q.pattern??(Q.pattern=lY(Q)),R.init(W,Q)}),j0=K("$ZodISODate",(W,Q)=>{Q.pattern??(Q.pattern=mY),R.init(W,Q)}),k0=K("$ZodISOTime",(W,Q)=>{Q.pattern??(Q.pattern=oY(Q)),R.init(W,Q)}),v0=K("$ZodISODuration",(W,Q)=>{Q.pattern??(Q.pattern=ZY),R.init(W,Q)}),g0=K("$ZodIPv4",(W,Q)=>{Q.pattern??(Q.pattern=vY),R.init(W,Q),W._zod.bag.format="ipv4"}),h0=K("$ZodIPv6",(W,Q)=>{Q.pattern??(Q.pattern=gY),R.init(W,Q),W._zod.bag.format="ipv6",W._zod.check=(Y)=>{try{new URL(`http://[${Y.value}]`)}catch{Y.issues.push({code:"invalid_format",format:"ipv6",input:Y.value,inst:W,continue:!Q.abort})}}});var x0=K("$ZodCIDRv4",(W,Q)=>{Q.pattern??(Q.pattern=hY),R.init(W,Q)}),c0=K("$ZodCIDRv6",(W,Q)=>{Q.pattern??(Q.pattern=xY),R.init(W,Q),W._zod.check=(Y)=>{let X=Y.value.split("/");try{if(X.length!==2)throw Error();let[G,J]=X;if(!J)throw Error();let H=Number(J);if(`${H}`!==J)throw Error();if(H<0||H>128)throw Error();new URL(`http://[${G}]`)}catch{Y.issues.push({code:"invalid_format",format:"cidrv6",input:Y.value,inst:W,continue:!Q.abort})}}});function u0(W){if(W==="")return!0;if(W.length%4!==0)return!1;try{return atob(W),!0}catch{return!1}}var y0=K("$ZodBase64",(W,Q)=>{Q.pattern??(Q.pattern=cY),R.init(W,Q),W._zod.bag.contentEncoding="base64",W._zod.check=(Y)=>{if(u0(Y.value))return;Y.issues.push({code:"invalid_format",format:"base64",input:Y.value,inst:W,continue:!Q.abort})}});function G6(W){if(!zQ.test(W))return!1;let Q=W.replace(/[-_]/g,(X)=>X==="-"?"+":"/"),Y=Q.padEnd(Math.ceil(Q.length/4)*4,"=");return u0(Y)}var m0=K("$ZodBase64URL",(W,Q)=>{Q.pattern??(Q.pattern=zQ),R.init(W,Q),W._zod.bag.contentEncoding="base64url",W._zod.check=(Y)=>{if(G6(Y.value))return;Y.issues.push({code:"invalid_format",format:"base64url",input:Y.value,inst:W,continue:!Q.abort})}}),f0=K("$ZodE164",(W,Q)=>{Q.pattern??(Q.pattern=uY),R.init(W,Q)});function J6(W,Q=null){try{let Y=W.split(".");if(Y.length!==3)return!1;let[X]=Y;if(!X)return!1;let G=JSON.parse(atob(X));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(Q&&(!("alg"in G)||G.alg!==Q))return!1;return!0}catch{return!1}}var o0=K("$ZodJWT",(W,Q)=>{R.init(W,Q),W._zod.check=(Y)=>{if(J6(Y.value,Q.alg))return;Y.issues.push({code:"invalid_format",format:"jwt",input:Y.value,inst:W,continue:!Q.abort})}});var DQ=K("$ZodNumber",(W,Q)=>{E.init(W,Q),W._zod.pattern=W._zod.bag.pattern??fW,W._zod.parse=(Y,X)=>{if(Q.coerce)try{Y.value=Number(Y.value)}catch(H){}let G=Y.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return Y;let J=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return Y.issues.push({expected:"number",code:"invalid_type",input:G,inst:W,...J?{received:J}:{}}),Y}}),l0=K("$ZodNumberFormat",(W,Q)=>{sY.init(W,Q),DQ.init(W,Q)}),r0=K("$ZodBoolean",(W,Q)=>{E.init(W,Q),W._zod.pattern=dY,W._zod.parse=(Y,X)=>{if(Q.coerce)try{Y.value=Boolean(Y.value)}catch(J){}let G=Y.value;if(typeof G==="boolean")return Y;return Y.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:W}),Y}});var p0=K("$ZodNull",(W,Q)=>{E.init(W,Q),W._zod.pattern=nY,W._zod.values=new Set([null]),W._zod.parse=(Y,X)=>{let G=Y.value;if(G===null)return Y;return Y.issues.push({expected:"null",code:"invalid_type",input:G,inst:W}),Y}});var d0=K("$ZodUnknown",(W,Q)=>{E.init(W,Q),W._zod.parse=(Y)=>Y}),n0=K("$ZodNever",(W,Q)=>{E.init(W,Q),W._zod.parse=(Y,X)=>{return Y.issues.push({expected:"never",code:"invalid_type",input:Y.value,inst:W}),Y}});function B0(W,Q,Y){if(W.issues.length)Q.issues.push(...QW(Y,W.issues));Q.value[Y]=W.value}var i0=K("$ZodArray",(W,Q)=>{E.init(W,Q),W._zod.parse=(Y,X)=>{let G=Y.value;if(!Array.isArray(G))return Y.issues.push({expected:"array",code:"invalid_type",input:G,inst:W}),Y;Y.value=Array(G.length);let J=[];for(let H=0;H<G.length;H++){let w=G[H],q=Q.element._zod.run({value:w,issues:[]},X);if(q instanceof Promise)J.push(q.then((L)=>B0(L,Y,H)));else B0(q,Y,H)}if(J.length)return Promise.all(J).then(()=>Y);return Y}});function rW(W,Q,Y,X,G){if(W.issues.length){if(G&&!(Y in X))return;Q.issues.push(...QW(Y,W.issues))}if(W.value===void 0){if(Y in X)Q.value[Y]=void 0}else Q.value[Y]=W.value}function t0(W){let Q=Object.keys(W.shape);for(let X of Q)if(!W.shape?.[X]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${X}": expected a Zod schema`);let Y=KQ(W.shape);return{...W,keys:Q,keySet:new Set(Q),numKeys:Q.length,optionalKeys:new Set(Y)}}function e0(W,Q,Y,X,G,J){let H=[],w=G.keySet,q=G.catchall._zod,L=q.def.type,B=q.optout==="optional";for(let z in Q){if(w.has(z))continue;if(L==="never"){H.push(z);continue}let I=q.run({value:Q[z],issues:[]},X);if(I instanceof Promise)W.push(I.then((V)=>rW(V,Y,z,Q,B)));else rW(I,Y,z,Q,B)}if(H.length)Y.issues.push({code:"unrecognized_keys",keys:H,input:Q,inst:J});if(!W.length)return Y;return Promise.all(W).then(()=>{return Y})}var H6=K("$ZodObject",(W,Q)=>{if(E.init(W,Q),!Object.getOwnPropertyDescriptor(Q,"shape")?.get){let w=Q.shape;Object.defineProperty(Q,"shape",{get:()=>{let q={...w};return Object.defineProperty(Q,"shape",{value:q}),q}})}let X=qW(()=>t0(Q));F(W._zod,"propValues",()=>{let w=Q.shape,q={};for(let L in w){let B=w[L]._zod;if(B.values){q[L]??(q[L]=new Set);for(let z of B.values)q[L].add(z)}}return q});let G=HW,J=Q.catchall,H;W._zod.parse=(w,q)=>{H??(H=X.value);let L=w.value;if(!G(L))return w.issues.push({expected:"object",code:"invalid_type",input:L,inst:W}),w;w.value={};let B=[],z=H.shape;for(let I of H.keys){let V=z[I],c=V._zod.optout==="optional",v=V._zod.run({value:L[I],issues:[]},q);if(v instanceof Promise)B.push(v.then((kW)=>rW(kW,w,I,L,c)));else rW(v,w,I,L,c)}if(!J)return B.length?Promise.all(B).then(()=>w):w;return e0(B,L,w,q,X.value,W)}}),a0=K("$ZodObjectJIT",(W,Q)=>{H6.init(W,Q);let Y=W._zod.parse,X=qW(()=>t0(Q)),G=(I)=>{let V=new VQ(["shape","payload","ctx"]),c=X.value,v=(e)=>{let m=hW(e);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};V.write("const input = payload.value;");let kW=Object.create(null),R4=0;for(let e of c.keys)kW[e]=`key_${R4++}`;V.write("const newResult = {};");for(let e of c.keys){let m=kW[e],n=hW(e),b4=I[e]?._zod?.optout==="optional";if(V.write(`const ${m} = ${v(e)};`),b4)V.write(`
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Classification for tool-call failures, and the `_meta` that carries it.
3
+ *
4
+ * The MCP SDK catches whatever a tool handler throws and flattens it to
5
+ * `{ content: [{ type: 'text', text }], isError: true }` — no code, no status,
6
+ * no data. That loss shows up in two places at once:
7
+ *
8
+ * - **For the caller.** A rate limit, a bad argument, and an upstream outage
9
+ * are the same shape, so a model cannot tell "wait and retry" from "fix the
10
+ * arguments". The expensive mistake is rewriting a working call because the
11
+ * upstream returned 429.
12
+ * - **For us.** `workers/dispatch/src/tool-call-tracing.ts` reads the failure
13
+ * message off `result._meta.error`, and nothing in the runtime has ever
14
+ * written it — so every failed tool call was recorded with
15
+ * `errorMessage: null`. We could see that a call failed, never why.
16
+ *
17
+ * So the runtime catches first, classifies, and attaches `_meta` itself.
18
+ * `_meta.error` is a plain string because that is what the tracer reads; the
19
+ * structured siblings are additive and safe for clients that ignore them.
20
+ *
21
+ * Both bundle layouts need this logic. The `inline` layout (still the default)
22
+ * gets a string-emitted copy from `convex/lib/codegen/toolErrorsBuilder.ts` —
23
+ * keep the two in step, and see `toolErrorsBuilder.test.ts`, which pins the
24
+ * parts that must not drift.
25
+ */
26
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
27
+ export type ToolErrorClass =
28
+ /** Arguments were rejected before the request left us. Fix the call, not the code. */
29
+ 'BINDING_MISUSE'
30
+ /** The upstream API failed. Retry when `retryable`; never a reason to rewrite. */
31
+ | 'UPSTREAM'
32
+ /** Blocked by policy (scope, rate, credits). `terminal` says whether waiting helps. */
33
+ | 'POLICY_DENIED'
34
+ /** Our bug, or a failure we could not classify. */
35
+ | 'INTERNAL';
36
+ export declare function isRetryableUpstreamStatus(status: number): boolean;
37
+ /** An upstream (customer API) call that came back non-OK. */
38
+ export declare class UpstreamHttpError extends Error {
39
+ readonly status: number;
40
+ readonly retryable: boolean;
41
+ /** Seconds the upstream asked us to wait, when it said so. */
42
+ readonly retryAfterSeconds: number | null;
43
+ constructor(message: string, status: number, retryAfterSeconds?: number | null);
44
+ }
45
+ /** Arguments that failed this tool's own input schema. */
46
+ export declare class ToolInputError extends Error {
47
+ readonly toolName: string;
48
+ readonly issues: readonly string[];
49
+ constructor(toolName: string, issues: readonly string[]);
50
+ }
51
+ export interface ToolErrorMeta {
52
+ /**
53
+ * The human-readable message. A plain string by contract — the dispatch
54
+ * tracer stores it only when `typeof === 'string'`.
55
+ */
56
+ error: string;
57
+ errorClass: ToolErrorClass;
58
+ /** Upstream HTTP status, when the failure came from the upstream API. */
59
+ httpStatus?: number;
60
+ /** Whether retrying the identical call could succeed. */
61
+ retryable?: boolean;
62
+ retryAfterSeconds?: number;
63
+ }
64
+ export declare function classifyToolError(error: unknown): ToolErrorMeta;
65
+ /**
66
+ * True when the error must reach the client as a real JSON-RPC error rather
67
+ * than an `isError` result.
68
+ *
69
+ * `UrlElicitationRequired` is the one code the SDK deliberately rethrows
70
+ * unwrapped, because the client has to act on it (OAuth / BYOK credential
71
+ * prompts). Swallowing it into an `isError` result would silently break
72
+ * elicitation, so this check gates the catch below.
73
+ *
74
+ * Deliberately structural rather than `instanceof McpError`. Generated bundles
75
+ * throw this from the vendored `runtime/mcp-runtime.js`, which carries its own
76
+ * copy of the SDK classes — an `instanceof` against the npm copy would be false
77
+ * there, and elicitation would break silently in exactly the servers that use
78
+ * it. Matching on the numeric code holds across both copies.
79
+ */
80
+ export declare function mustRethrow(error: unknown): boolean;
81
+ /**
82
+ * Turn a thrown tool failure into the `CallToolResult` the SDK would have
83
+ * produced, plus the `_meta` it drops.
84
+ *
85
+ * The `content` text is unchanged from the SDK's own `createToolError`, so
86
+ * clients reading `content[0].text` see exactly what they saw before.
87
+ */
88
+ export declare function toToolErrorResult(error: unknown): CallToolResult;
89
+ /**
90
+ * Run a tool handler, converting a throw into a classified error result.
91
+ * Elicitation errors pass straight through.
92
+ */
93
+ export declare function runToolHandler(invoke: () => Promise<CallToolResult>): Promise<CallToolResult>;
package/dist/types.d.ts CHANGED
@@ -73,6 +73,24 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> {
73
73
  inputExample: unknown | null;
74
74
  outputExample: unknown | null;
75
75
  responseProjection?: string | null;
76
+ /**
77
+ * MCP behavioural hints, computed at codegen time from the tool's effect
78
+ * class (see shared/mcpToolAnnotations.ts) and forwarded verbatim to
79
+ * `registerTool`. Optional: definitions generated before this existed simply
80
+ * advertise nothing, which is the correct "no claim" state.
81
+ */
82
+ annotations?: McpToolAnnotations | null;
76
83
  _input?: TInput;
77
84
  _output?: TOutput;
78
85
  }
86
+ /**
87
+ * Structural copy of the hints we populate. Declared here rather than imported
88
+ * so the runtime package stays dependency-free of `shared/`; the values are
89
+ * produced by codegen, never computed here.
90
+ */
91
+ export interface McpToolAnnotations {
92
+ readOnlyHint?: boolean;
93
+ destructiveHint?: boolean;
94
+ idempotentHint?: boolean;
95
+ openWorldHint?: boolean;
96
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcpcloud/runtime",
3
- "version": "0.5.0",
3
+ "version": "0.7.1",
4
4
  "description": "MCPCloud generated-server runtime: transports, config, upstream auth/HTTP, validation, projection, and discovery for MCP servers built on MCPCloud.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -34,8 +34,10 @@
34
34
  "prepublishOnly": "bun run typecheck && bun run test && bun run build"
35
35
  },
36
36
  "dependencies": {
37
+ "@jitl/quickjs-ffi-types": "^0.32.0",
37
38
  "@metrichor/jmespath": "^0.3.1",
38
39
  "@modelcontextprotocol/sdk": "^1.29.0",
40
+ "quickjs-emscripten-core": "^0.32.0",
39
41
  "zod": "^4.4.3"
40
42
  },
41
43
  "devDependencies": {