@fibteq/myrel-runner 0.42.0 → 0.42.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/README.md +5 -0
- package/dist/cli.js +51 -51
- package/dist/index.js +40 -40
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Lx=Object.defineProperty;var ut=(e,t)=>{for(var r in t)Lx(e,r,{get:t[r],enumerable:!0})};import{fileURLToPath as Mx}from"node:url";import{parseArgs as OT}from"node:util";var Zx={message:"cmsg",thread:"thr",project:"proj",usage:"use",apiKey:"key",invite:"inv",runner:"rnr",task:"task",artifact:"art",routine:"rtn",notification:"ntf",connector:"mcp",skill:"skl",suggestion:"sug",question:"qst",sshHost:"ssh",sshRun:"sshr",check:"chk",report:"rep",research:"rsch"};function de(e){return new RegExp(`^${Zx[e]}_[0-9A-HJKMNP-TV-Z]{26}$`)}var s={};ut(s,{$brand:()=>Hs,$input:()=>wl,$output:()=>xl,INVALID:()=>xe,NEVER:()=>qs,TimePrecision:()=>Nl,ZodAny:()=>xp,ZodArray:()=>Sp,ZodBase64:()=>Oa,ZodBase64URL:()=>Na,ZodBigInt:()=>er,ZodBigIntFormat:()=>Ea,ZodBoolean:()=>Qn,ZodCIDRv4:()=>Ta,ZodCIDRv6:()=>Ca,ZodCUID:()=>ka,ZodCUID2:()=>Sa,ZodCatch:()=>Bp,ZodCodec:()=>li,ZodCompileAsyncError:()=>qe,ZodCompileUnsupportedError:()=>F,ZodCreditCard:()=>mp,ZodCustom:()=>di,ZodCustomStringFormat:()=>tn,ZodDate:()=>ii,ZodDefault:()=>Lp,ZodDiscriminatedUnion:()=>zp,ZodE164:()=>Da,ZodEmail:()=>$a,ZodEmoji:()=>wa,ZodEnum:()=>Hn,ZodError:()=>aI,ZodExactOptional:()=>Za,ZodFile:()=>Rp,ZodFirstPartyTypeKind:()=>am,ZodFunction:()=>nm,ZodGUID:()=>xa,ZodIBAN:()=>fp,ZodIPv4:()=>Aa,ZodIPv6:()=>ja,ZodISODate:()=>jt,ZodISODateTime:()=>At,ZodISODuration:()=>Ct,ZodISOTime:()=>Tt,ZodInstanceOf:()=>om,ZodIntersection:()=>Pp,ZodIssueCode:()=>uI,ZodJWT:()=>Ra,ZodKSUID:()=>Pa,ZodLazy:()=>Qp,ZodLiteral:()=>Dp,ZodMAC:()=>pp,ZodMap:()=>Op,ZodNaN:()=>Gp,ZodNanoID:()=>_a,ZodNever:()=>_p,ZodNonOptional:()=>Fa,ZodNull:()=>bp,ZodNullable:()=>Mp,ZodNumber:()=>Yn,ZodNumberFormat:()=>nn,ZodObject:()=>ai,ZodOptional:()=>ci,ZodPipe:()=>ui,ZodPrefault:()=>Fp,ZodPreprocess:()=>qp,ZodPromise:()=>tm,ZodReadonly:()=>Hp,ZodRealError:()=>je,ZodRecord:()=>qn,ZodSet:()=>Np,ZodString:()=>Xn,ZodStringFormat:()=>q,ZodSuccess:()=>Jp,ZodSymbol:()=>vp,ZodTemplateLiteral:()=>Yp,ZodTransform:()=>Ep,ZodTuple:()=>jp,ZodType:()=>M,ZodULID:()=>Ia,ZodURL:()=>ri,ZodUUID:()=>it,ZodUndefined:()=>yp,ZodUnion:()=>si,ZodUnknown:()=>wp,ZodVoid:()=>kp,ZodXID:()=>za,ZodXor:()=>Ip,_ZodString:()=>ba,_default:()=>Zp,_function:()=>ay,any:()=>Ev,array:()=>oi,base64:()=>vv,base64url:()=>yv,bigint:()=>Cv,boolean:()=>hp,catch:()=>Wp,check:()=>sy,cidrv4:()=>gv,cidrv6:()=>hv,clone:()=>J,codec:()=>ny,coerce:()=>cm,compile:()=>Il,config:()=>ie,core:()=>ft,creditCard:()=>$v,cuid:()=>sv,cuid2:()=>cv,currencyCode:()=>Iv,custom:()=>cy,date:()=>Mv,decode:()=>op,decodeAsync:()=>sp,deepPartial:()=>xy,describe:()=>uy,discriminatedUnion:()=>Jv,e164:()=>bv,email:()=>Xh,emoji:()=>ov,encode:()=>ip,encodeAsync:()=>ap,endsWith:()=>Un,enum:()=>Ma,exactOptional:()=>Up,file:()=>Yv,flattenError:()=>Ir,float32:()=>Pv,float64:()=>Av,formatError:()=>zr,fromJSONSchema:()=>by,function:()=>ay,getDiscriminatedOption:()=>qu,getErrorMap:()=>dI,globalRegistry:()=>ge,gt:()=>nt,gte:()=>Ee,guid:()=>Yh,hash:()=>zv,hex:()=>Sv,hostname:()=>kv,httpUrl:()=>iv,iban:()=>xv,includes:()=>Rn,input:()=>_y,instanceof:()=>dy,int:()=>va,int32:()=>jv,int64:()=>Ov,intersection:()=>Ap,invertCodec:()=>ry,ipv4:()=>pv,ipv6:()=>fv,iso:()=>pi,json:()=>my,jwt:()=>wv,keyof:()=>Lv,ksuid:()=>dv,lazy:()=>em,length:()=>Ht,literal:()=>Xv,locales:()=>Wr,looseObject:()=>Vv,looseRecord:()=>Wv,lowercase:()=>Nn,lt:()=>tt,lte:()=>Re,mac:()=>mv,map:()=>Gv,maxLength:()=>qt,maxSize:()=>St,memoizer:()=>Jr,meta:()=>ly,mime:()=>Ln,minLength:()=>mt,minSize:()=>rt,multipleOf:()=>kt,nan:()=>ty,nanoid:()=>av,nativeEnum:()=>Hv,negative:()=>aa,never:()=>Ua,nonnegative:()=>ca,nonoptional:()=>Kp,nonpositive:()=>sa,normalize:()=>Zn,null:()=>$p,nullable:()=>ni,nullish:()=>Qv,number:()=>gp,object:()=>Zv,optional:()=>Qt,output:()=>ky,overwrite:()=>He,parse:()=>ep,parseAsync:()=>tp,partialRecord:()=>Bv,pipe:()=>ya,positive:()=>oa,prefault:()=>Vp,preprocess:()=>fy,prettifyError:()=>tc,promise:()=>oy,properties:()=>Mn,property:()=>ua,readonly:()=>Xp,record:()=>Cp,refine:()=>rm,regex:()=>On,regexes:()=>Fe,registry:()=>No,safeDecode:()=>up,safeDecodeAsync:()=>dp,safeEncode:()=>cp,safeEncodeAsync:()=>lp,safeParse:()=>np,safeParseAsync:()=>rp,set:()=>qv,setErrorMap:()=>lI,size:()=>Gt,slugify:()=>Jn,startsWith:()=>En,strictObject:()=>Fv,string:()=>ti,stringFormat:()=>_v,stringbool:()=>py,success:()=>ey,superRefine:()=>im,symbol:()=>Dv,templateLiteral:()=>iy,toJSONSchema:()=>ma,toLowerCase:()=>Vn,toUpperCase:()=>Kn,toZod:()=>hr,transform:()=>La,treeifyError:()=>ec,trim:()=>Fn,tuple:()=>Tp,uint32:()=>Tv,uint64:()=>Nv,ulid:()=>uv,undefined:()=>Rv,union:()=>tr,unknown:()=>Yt,uppercase:()=>Dn,url:()=>rv,util:()=>b,uuid:()=>Qh,uuidv4:()=>ev,uuidv6:()=>tv,uuidv7:()=>nv,validate:()=>Pr,validateAsync:()=>Ar,void:()=>Uv,withParser:()=>Do,xid:()=>lv,xor:()=>Kv});var ft={};ut(ft,{$ZodAny:()=>Lu,$ZodArray:()=>Bu,$ZodAsyncError:()=>Pe,$ZodBase64:()=>Pu,$ZodBase64URL:()=>Au,$ZodBigInt:()=>$o,$ZodBigIntFormat:()=>Ru,$ZodBoolean:()=>Mr,$ZodCIDRv4:()=>Iu,$ZodCIDRv6:()=>zu,$ZodCUID:()=>fu,$ZodCUID2:()=>gu,$ZodCatch:()=>dl,$ZodCheck:()=>H,$ZodCheckBigIntFormat:()=>Zc,$ZodCheckEndsWith:()=>Qc,$ZodCheckGreaterThan:()=>ro,$ZodCheckIncludes:()=>Xc,$ZodCheckLengthEquals:()=>Wc,$ZodCheckLessThan:()=>no,$ZodCheckLowerCase:()=>qc,$ZodCheckMaxLength:()=>Jc,$ZodCheckMaxSize:()=>Fc,$ZodCheckMimeType:()=>nu,$ZodCheckMinLength:()=>Bc,$ZodCheckMinSize:()=>Vc,$ZodCheckMultipleOf:()=>Mc,$ZodCheckNumberFormat:()=>Lc,$ZodCheckOverwrite:()=>ru,$ZodCheckProperties:()=>tu,$ZodCheckProperty:()=>eu,$ZodCheckRegex:()=>Gc,$ZodCheckSizeEquals:()=>Kc,$ZodCheckStartsWith:()=>Yc,$ZodCheckStringFormat:()=>Pn,$ZodCheckUpperCase:()=>Hc,$ZodCodec:()=>Zr,$ZodCreditCard:()=>Tu,$ZodCustom:()=>yl,$ZodCustomStringFormat:()=>Nu,$ZodCyclicError:()=>zo,$ZodDate:()=>Ku,$ZodDefault:()=>sl,$ZodDiscriminatedUnion:()=>Hu,$ZodE164:()=>ju,$ZodEmail:()=>cu,$ZodEmoji:()=>pu,$ZodEncodeError:()=>wt,$ZodEnum:()=>tl,$ZodError:()=>Qs,$ZodExactOptional:()=>ol,$ZodFile:()=>rl,$ZodFunction:()=>hl,$ZodGUID:()=>au,$ZodIBAN:()=>Cu,$ZodIPv4:()=>_u,$ZodIPv6:()=>ku,$ZodISODate:()=>$u,$ZodISODateTime:()=>bu,$ZodISODuration:()=>wu,$ZodISOTime:()=>xu,$ZodIntersection:()=>Xu,$ZodJWT:()=>Ou,$ZodKSUID:()=>yu,$ZodLazy:()=>Fr,$ZodLiteral:()=>nl,$ZodMAC:()=>Su,$ZodMap:()=>Qu,$ZodNaN:()=>pl,$ZodNanoID:()=>mu,$ZodNever:()=>Fu,$ZodNonOptional:()=>ul,$ZodNull:()=>Mu,$ZodNullable:()=>al,$ZodNumber:()=>bo,$ZodNumberFormat:()=>Du,$ZodObject:()=>sg,$ZodObjectJIT:()=>Wu,$ZodOptional:()=>wo,$ZodPipe:()=>_o,$ZodPrefault:()=>cl,$ZodPreprocess:()=>ml,$ZodPromise:()=>vl,$ZodReadonly:()=>fl,$ZodRealError:()=>Ae,$ZodRecord:()=>Yu,$ZodRegistry:()=>Oo,$ZodSet:()=>el,$ZodString:()=>Kt,$ZodStringFormat:()=>B,$ZodSuccess:()=>ll,$ZodSymbol:()=>Eu,$ZodTemplateLiteral:()=>gl,$ZodTransform:()=>il,$ZodTuple:()=>xo,$ZodType:()=>D,$ZodULID:()=>hu,$ZodURL:()=>du,$ZodUUID:()=>su,$ZodUndefined:()=>Uu,$ZodUnion:()=>Lr,$ZodUnknown:()=>Zu,$ZodVoid:()=>Vu,$ZodXID:()=>vu,$ZodXor:()=>Gu,$brand:()=>Hs,$constructor:()=>h,$input:()=>wl,$output:()=>xl,Doc:()=>Vt,INVALID:()=>xe,JSONSchema:()=>Gh,JSONSchemaGenerator:()=>fa,NEVER:()=>qs,TimePrecision:()=>Nl,URL_BAD_FORMAT:()=>uu,URL_UNPARSEABLE:()=>Nr,ZodCompileAsyncError:()=>qe,ZodCompileUnsupportedError:()=>F,_any:()=>Xl,_array:()=>id,_base64:()=>ta,_base64url:()=>na,_bigint:()=>Kl,_boolean:()=>Fl,_catch:()=>GS,_check:()=>Ch,_cidrv4:()=>Qo,_cidrv6:()=>ea,_coercedBigint:()=>Jl,_coercedBoolean:()=>Vl,_coercedDate:()=>nd,_coercedNumber:()=>Rl,_coercedString:()=>jl,_creditCard:()=>Cl,_cuid:()=>Bo,_cuid2:()=>Wo,_custom:()=>ad,_date:()=>td,_decode:()=>Ji,_decodeAsync:()=>Wi,_default:()=>JS,_discriminatedUnion:()=>OS,_e164:()=>ra,_email:()=>Uo,_emoji:()=>Ko,_encode:()=>Ki,_encodeAsync:()=>Bi,_endsWith:()=>Un,_enum:()=>MS,_file:()=>od,_float32:()=>Ul,_float64:()=>Ml,_gt:()=>nt,_gte:()=>Ee,_guid:()=>Mo,_iban:()=>Ol,_includes:()=>Rn,_int:()=>El,_int32:()=>Ll,_int64:()=>Bl,_intersection:()=>NS,_ipv4:()=>Xo,_ipv6:()=>Yo,_isoDate:()=>Hr,_isoDateTime:()=>qr,_isoDuration:()=>Yr,_isoTime:()=>Xr,_jwt:()=>ia,_ksuid:()=>Ho,_lazy:()=>YS,_length:()=>Ht,_literal:()=>ZS,_lowercase:()=>Nn,_lt:()=>tt,_lte:()=>Re,_mac:()=>Tl,_map:()=>ES,_max:()=>Re,_maxLength:()=>qt,_maxSize:()=>St,_mime:()=>Ln,_min:()=>Ee,_minLength:()=>mt,_minSize:()=>rt,_multipleOf:()=>kt,_nan:()=>rd,_nanoid:()=>Jo,_nativeEnum:()=>LS,_negative:()=>aa,_never:()=>Ql,_nonnegative:()=>ca,_nonoptional:()=>BS,_nonpositive:()=>sa,_normalize:()=>Zn,_null:()=>Hl,_nullable:()=>KS,_number:()=>Dl,_optional:()=>VS,_overwrite:()=>He,_parse:()=>kn,_parseAsync:()=>Sn,_pipe:()=>qS,_positive:()=>oa,_promise:()=>QS,_properties:()=>Mn,_property:()=>ua,_readonly:()=>HS,_record:()=>RS,_refine:()=>sd,_regex:()=>On,_safeDecode:()=>qi,_safeDecodeAsync:()=>Xi,_safeEncode:()=>Gi,_safeEncodeAsync:()=>Hi,_safeParse:()=>In,_safeParseAsync:()=>zn,_set:()=>US,_size:()=>Gt,_slugify:()=>Jn,_startsWith:()=>En,_string:()=>Al,_stringFormat:()=>Xt,_stringbool:()=>dd,_success:()=>WS,_superRefine:()=>cd,_symbol:()=>Gl,_templateLiteral:()=>XS,_toLowerCase:()=>Vn,_toUpperCase:()=>Kn,_transform:()=>FS,_trim:()=>Fn,_tuple:()=>DS,_uint32:()=>Zl,_uint64:()=>Wl,_ulid:()=>Go,_undefined:()=>ql,_union:()=>TS,_unknown:()=>Yl,_uppercase:()=>Dn,_url:()=>Gr,_uuid:()=>Lo,_uuidv4:()=>Zo,_uuidv6:()=>Fo,_uuidv7:()=>Vo,_void:()=>ed,_xid:()=>qo,_xor:()=>CS,base64Charset:()=>fo,base64urlCharset:()=>Ur,canParseURL:()=>lu,clone:()=>J,compile:()=>Il,compileFn:()=>Ro,config:()=>ie,createStandardJSONSchemaMethod:()=>Bn,createToJSONSchemaMethod:()=>md,decode:()=>Cw,decodeAsync:()=>Nw,describe:()=>ud,encode:()=>Tw,encodeAsync:()=>Ow,extractDefs:()=>zt,finalize:()=>Pt,flattenError:()=>Ir,formatError:()=>zr,getDiscriminatedOption:()=>qu,globalConfig:()=>pe,globalRegistry:()=>ge,handleUnrepresentable:()=>ue,initializeContext:()=>It,isBackEdge:()=>Ao,isRecursiveSchema:()=>Po,isValidBase64:()=>Er,isValidBase64URL:()=>go,isValidCIDRv6:()=>mo,isValidCreditCard:()=>ho,isValidIBAN:()=>vo,isValidIPv6:()=>Rr,isValidJWT:()=>yo,locales:()=>Wr,memoizer:()=>Jr,mergeValues:()=>An,meta:()=>ld,parse:()=>Fi,parseAsync:()=>Vi,parseURLObject:()=>ig,prettifyError:()=>tc,process:()=>W,processSchema:()=>W,regexes:()=>Fe,registry:()=>No,safeDecode:()=>Rw,safeDecodeAsync:()=>Uw,safeEncode:()=>Dw,safeEncodeAsync:()=>Ew,safeParse:()=>Iw,safeParseAsync:()=>zw,standardProps:()=>co,stripTabAndNewline:()=>Dr,toDotPath:()=>Ef,toJSONSchema:()=>ma,toZod:()=>hr,treeifyError:()=>ec,urlHostnameOk:()=>lo,urlProtocolOk:()=>po,util:()=>b,validate:()=>Pr,validateAsync:()=>Ar,validateURL:()=>uo,version:()=>iu,withParser:()=>Do});var b={};ut(b,{BIGINT_FORMAT_RANGES:()=>xr,CONSTANT_CATCH:()=>Li,Class:()=>Ms,NUMBER_FORMAT_RANGES:()=>$r,aborted:()=>$e,allowsEval:()=>Fs,assert:()=>Bx,assertEqual:()=>Fx,assertIs:()=>Kx,assertNever:()=>Jx,assertNotEqual:()=>Vx,assignProp:()=>fe,attachSchema:()=>wr,base64ToUint8Array:()=>Tf,base64urlToUint8Array:()=>dw,cached:()=>$n,captureStackTrace:()=>Ui,cleanEnum:()=>lw,cleanRegex:()=>dt,clone:()=>J,cloneDef:()=>qx,codePointLength:()=>Zt,constantCatch:()=>Ws,createTransparentProxy:()=>tw,defineLazy:()=>Ls,defineLazyInternal:()=>L,derived:()=>gw,esc:()=>be,escapeRegex:()=>Ze,explicitlyAborted:()=>Js,extend:()=>iw,finalizeIssue:()=>ze,floatSafeRemainder:()=>vr,getElementAtPath:()=>Hx,getEnumValues:()=>yn,getLengthableOrigin:()=>kr,getParsedType:()=>ew,getSizableOrigin:()=>_r,hexToUint8Array:()=>mw,hide:()=>Sr,installLazyProp:()=>bw,isObject:()=>Lt,isPlainObject:()=>Le,issue:()=>_n,joinValues:()=>v,jsonStringifyReplacer:()=>bn,members:()=>Bs,merge:()=>aw,mergeDefs:()=>Ge,normalizeParams:()=>S,nullish:()=>Ei,numKeys:()=>Qx,objectClone:()=>Wx,omit:()=>rw,optionalKeys:()=>Ks,own:()=>xt,parsedType:()=>x,partial:()=>sw,pick:()=>nw,prefixIssues:()=>Ie,primitiveTypes:()=>Vs,promiseAllObject:()=>Xx,propertyKeyTypes:()=>br,randomString:()=>Yx,rawShape:()=>xn,required:()=>cw,safeExtend:()=>ow,shallowClone:()=>yr,sizeCaps:()=>wn,slugify:()=>Zs,stringifyPrimitive:()=>$,toZod:()=>hr,uint8ArrayToBase64:()=>Cf,uint8ArrayToBase64url:()=>pw,uint8ArrayToHex:()=>fw,unwrapMessage:()=>vn});function Fx(e){return e}function Vx(e){return e}function hr(){return e=>e}function Kx(e){}function Jx(e){throw new Error("Unexpected value in exhaustive check")}function Bx(e){}function yn(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function v(e,t="|"){return e.map(r=>$(r)).join(t)}function bn(e,t){return typeof t=="bigint"?t.toString():t}var Us=class{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}};function $n(e){return new Us(e)}function Ei(e){return e==null}function dt(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function vr(e,t){let r=e/t,o=Math.round(r),n=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var zf=Symbol("evaluating");function Ls(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==zf)return o===void 0&&(o=zf,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Wx(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function fe(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function xn(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function lt(e){return xn(e._zod.def)??e._zod.def.shape}function Pf(e,t,r){Object.defineProperty(e,t,{get(){let o=r();return fe(this,t,o),o},enumerable:!0,configurable:!0})}function Af(e,t,r){t in e?fe(e,t,r):e[t]=r}function Mt(e,t,r,o){let n=lt(t);for(let i of r){let a=Object.getOwnPropertyDescriptor(n,i);a.enumerable&&(a.get?Pf(e,i,()=>{let c=t._zod.def.shape[i];return o?o(c,i):c}):Af(e,i,o?o(a.value,i):a.value))}}function Gx(e,t){for(let r of Reflect.ownKeys(t)){let o=Object.getOwnPropertyDescriptor(t,r);o.enumerable&&(o.get?Pf(e,r,()=>t[r]):Af(e,r,o.value))}}function Ge(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function qx(e){return Ge(e._zod.def)}function Hx(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function Xx(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function Yx(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function be(e){return JSON.stringify(e)}function Zs(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Ui="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Fs=$n(()=>{if(pe.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Le(e){if(Lt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Lt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function yr(e){return Le(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Qx(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var ew=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},br=new Set(["string","number","symbol"]),Vs=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ze(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function S(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function tw(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function $(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ks(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var $r={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},xr={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function nw(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i={};return Mt(i,e,Mi(e,t)),J(e,Ge(r,{shape:i,checks:[]}))}function Mi(e,t){let r=lt(e),o=[];for(let n of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,n)?.enumerable)throw new Error(`Unrecognized key: "${String(n)}"`);t[n]&&o.push(n)}return o}function rw(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(Mi(e,t)),a={};return Mt(a,e,Reflect.ownKeys(lt(e)).filter(c=>!i.has(c))),J(e,Ge(r,{shape:a,checks:[]}))}function iw(e,t){if(!Le(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let n=lt(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return J(e,Ge(e._zod.def,{shape:jf(e,t)}))}function jf(e,t){let r={};return Mt(r,e,Reflect.ownKeys(lt(e))),Gx(r,t),r}function ow(e,t){if(!Le(t))throw new Error("Invalid input to safeExtend: expected a plain object");return J(e,Ge(e._zod.def,{shape:jf(e,t)}))}function aw(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};Mt(r,e,Reflect.ownKeys(lt(e))),Mt(r,t,Reflect.ownKeys(lt(t)));let o=Ge(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return J(e,o)}function sw(e,t,r,o="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${o}() cannot be used on object schemas containing refinements`);let c=r?new Set(Mi(t,r)):void 0,u={};return Mt(u,t,Reflect.ownKeys(lt(t)),e&&((l,d)=>c&&!c.has(d)?l:new e({type:"optional",innerType:l}))),J(t,Ge(t._zod.def,{shape:u,checks:[]}))}function cw(e,t,r){let o=r?new Set(Mi(t,r)):void 0,n={};return Mt(n,t,Reflect.ownKeys(lt(t)),(i,a)=>o&&!o.has(a)?i:new e({type:"nonoptional",innerType:i})),J(t,Ge(t._zod.def,{shape:n}))}function $e(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Js(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Ie(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function vn(e){return typeof e=="string"?e:e?.message}function wn(e){let t=[];for(let r of e??[]){let o=r._zod.def;if(!/_(length|size)$|_equals$/.test(o.check))break;let n=o.maximum??o.length??o.size;n>=0&&t.push([n,r])}return t}function wr(e,t,r){var o;for(let n=t;n<e.length;n++)(o=e[n]).schema??(o.schema=r)}function ze(e,t,r){var o;let n=e.inst?._zod?.traits;n?.has("$ZodType")&&(n.has("$ZodCheck")?(o=e).schema??(o.schema=e.inst):e.schema=e.inst);let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:vn(e.inst?._zod.def?.error?.(e))??vn(i?.(e))??vn(t?.error?.(e))??vn(r.customError?.(e))??vn(r.localeError?.(e))??"Invalid input",c={};for(let u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(c[u]=e[u]);return c.path??(c.path=[]),c.message=a,t?.reportInput&&(c.input=e.input),c}function _r(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}var uw=/[\uD800-\uDBFF]/;function Zt(e){let t=e.length;if(!uw.test(e))return t;let r=t;for(let o=0;o<t-1;o++)(e.charCodeAt(o)&64512)===55296&&(e.charCodeAt(o+1)&64512)===56320&&(r--,o++);return r}function kr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function x(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function _n(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function lw(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Tf(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function Cf(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function dw(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return Tf(t+r)}function pw(e){return Cf(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function mw(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function fw(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ms=class{constructor(...t){}};function Bs(e,t){for(let r in t){let o=Object.getOwnPropertyDescriptor(t,r);o.get?Object.defineProperty(e,r,{...o,enumerable:!1}):hw(e,r,o.value)}}function xt(e,t,r,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function Sr(e,t,r){return xt(e,t,r,!1)}function gw(e,t){for(let r in e){let o=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return xt(this,r,o(this))},set(n){xt(this,r,n)}})}return t}function hw(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:xt(this,t,r.bind(this))},set(o){xt(this,t,o)}})}function vw(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var Es,$t=!1,yw={configurable:!0,get(){$t=!0}};function L(e,t,r){let o=Object.getPrototypeOf(e._zod);if(t in o&&Es!==e._zod){Es=void 0;return}Es=e._zod,Object.defineProperty(o,t,{configurable:!0,get(){Object.defineProperty(this,t,yw);let n=$t;$t=!1;try{let i=r(this);return $t?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i}),$t=$t||n,i}catch(i){throw delete this[t],$t=$t||n,i}},set(n){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:n})}})}function bw(e,t,r,o){let n=vw(e,t);n&&Object.defineProperty(n,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:o,value:void 0};return Object.defineProperty(this,t,i),i.value=r(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:o,value:i})}})}var Li="~constantCatch";function Ws(e){let t=()=>e;return t[Li]=!0,t}var Of,qs=Object.freeze({status:"aborted"}),Gs={value:void 0,enumerable:!1},Nf="captureStackTrace"in Error?Error:null;function $w(e){let t=Nf;if(t){let r=t.stackTraceLimit;if(typeof r=="number"){try{t.stackTraceLimit=0}catch{return Nf=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function h(e,t,r,o){let n={};function i(f){this.def=f,this.constr=p,this.traits=new Set}i.prototype=n;let a=r,c=a&&new WeakSet;function u(f,m){if(f._zod){if(f._zod.traits.has(e))return}else{Gs.value=new i(m);try{Object.defineProperty(f,"_zod",Gs)}finally{Gs.value=void 0}}if(f._zod.traits.add(e),t(f,m),c){let y=Object.getPrototypeOf(f),_=f._zod.constr.prototype,I=y;for(;I&&I!==_;)I=Object.getPrototypeOf(I);let k=I??y;c.has(k)||(c.add(k),Bs(k,a))}let g=p.prototype;for(let y in g)Object.prototype.hasOwnProperty.call(g,y)&&(y in f||(f[y]=g[y].bind(f)))}let l=o?.Parent??Object;class d extends l{}Object.defineProperty(d,"name",{value:e});function p(f){let m=o?.Parent?$w(d):this;u(m,f);let g=m._zod.deferred;if(g){for(let _ of g)_();m._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;return y&&y(m),m}return Object.defineProperty(p,"init",{value:u}),Object.defineProperty(p,Symbol.hasInstance,{value:f=>o?.Parent&&f instanceof o.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(p,"name",{value:e}),p}var Hs=Symbol("zod_brand"),Pe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},wt=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(Of=globalThis).__zod_globalConfig??(Of.__zod_globalConfig={});var pe=globalThis.__zod_globalConfig;function ie(e){return e&&Object.assign(pe,e),pe}function xw(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,bn,2)),e.message}function ww(e){this._zod.message=e}var _w={get:xw,set:ww,enumerable:!0,configurable:!0},Ys={value:void 0,enumerable:!1},Df=new WeakSet([Object.prototype,Error.prototype]),Rf=(e,t)=>{e.name="$ZodError",Ys.value=t,Object.defineProperty(e,"issues",Ys),Ys.value=void 0,Object.defineProperty(e,"message",_w);let r=Object.getPrototypeOf(e);Df.has(r)||(Df.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let o=()=>this.message;return Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0})}}))},Qs=h("$ZodError",Rf),Ae=h("$ZodError",Rf,void 0,{Parent:Error});function kw(e,t,r){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0}):e[t]=r()),e[t]}function Ir(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?kw(r,n.path[0],()=>[]).push(t(n)):o.push(t(n));return{formErrors:o,fieldErrors:r}}function zr(e,t=r=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let a of n.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>o({issues:c},[...i,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...i,...a.path]);else{let c=[...i,...a.path];if(c.length===0)r._errors.push(t(a));else{let u=r,l=0;for(;l<c.length;){let d=c[l],p=l===c.length-1;if(d==="_errors"){p&&u._errors.push(t(a)),l++;continue}Object.prototype.hasOwnProperty.call(u,d)||Object.defineProperty(u,d,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let f=u[d];p&&f._errors.push(t(a)),u=f,l++}}}};return o(e),r}function ec(e,t=r=>r.message){let r={errors:[]},o=(n,i=[])=>{var a;for(let c of n.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(u=>o({issues:u},[...i,...c.path]));else if(c.code==="invalid_key")o({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")o({issues:c.issues},[...i,...c.path]);else{let u=[...i,...c.path];if(u.length===0){r.errors.push(t(c));continue}let l=r,d=0;for(;d<u.length;){let p=u[d],f=d===u.length-1;typeof p=="string"?(l.properties??(l.properties={}),Object.prototype.hasOwnProperty.call(l.properties,p)||Object.defineProperty(l.properties,p,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),l=l.properties[p]):(l.items??(l.items=[]),(a=l.items)[p]??(a[p]={errors:[]}),l=l.items[p]),f&&l.errors.push(t(c)),d++}}};return o(e),r}function Ef(e){let t=[],r=e.map(o=>typeof o=="object"?o.key:o);for(let o of r)typeof o=="number"?t.push(`[${o}]`):typeof o=="symbol"?t.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?t.push(`[${JSON.stringify(o)}]`):(t.length&&t.push("."),t.push(o));return t.join("")}function tc(e){let t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)t.push(`\u2716 ${o.message}`),o.path?.length&&t.push(` \u2192 at ${Ef(o.path)}`);return t.join(`
|
|
2
|
+
var Lx=Object.defineProperty;var ut=(e,t)=>{for(var r in t)Lx(e,r,{get:t[r],enumerable:!0})};import{fileURLToPath as Mx}from"node:url";import{parseArgs as NT}from"node:util";var Zx={message:"cmsg",thread:"thr",project:"proj",usage:"use",apiKey:"key",invite:"inv",runner:"rnr",task:"task",artifact:"art",routine:"rtn",notification:"ntf",connector:"mcp",skill:"skl",suggestion:"sug",question:"qst",sshHost:"ssh",sshRun:"sshr",check:"chk",report:"rep",research:"rsch"};function de(e){return new RegExp(`^${Zx[e]}_[0-9A-HJKMNP-TV-Z]{26}$`)}var s={};ut(s,{$brand:()=>Hs,$input:()=>wl,$output:()=>xl,INVALID:()=>xe,NEVER:()=>qs,TimePrecision:()=>Nl,ZodAny:()=>xp,ZodArray:()=>Sp,ZodBase64:()=>Oa,ZodBase64URL:()=>Na,ZodBigInt:()=>er,ZodBigIntFormat:()=>Ea,ZodBoolean:()=>Qn,ZodCIDRv4:()=>Ta,ZodCIDRv6:()=>Ca,ZodCUID:()=>ka,ZodCUID2:()=>Sa,ZodCatch:()=>Bp,ZodCodec:()=>li,ZodCompileAsyncError:()=>qe,ZodCompileUnsupportedError:()=>F,ZodCreditCard:()=>mp,ZodCustom:()=>di,ZodCustomStringFormat:()=>tn,ZodDate:()=>ii,ZodDefault:()=>Lp,ZodDiscriminatedUnion:()=>zp,ZodE164:()=>Da,ZodEmail:()=>$a,ZodEmoji:()=>wa,ZodEnum:()=>Hn,ZodError:()=>aI,ZodExactOptional:()=>Za,ZodFile:()=>Rp,ZodFirstPartyTypeKind:()=>am,ZodFunction:()=>nm,ZodGUID:()=>xa,ZodIBAN:()=>fp,ZodIPv4:()=>Aa,ZodIPv6:()=>ja,ZodISODate:()=>jt,ZodISODateTime:()=>At,ZodISODuration:()=>Ct,ZodISOTime:()=>Tt,ZodInstanceOf:()=>om,ZodIntersection:()=>Pp,ZodIssueCode:()=>uI,ZodJWT:()=>Ra,ZodKSUID:()=>Pa,ZodLazy:()=>Qp,ZodLiteral:()=>Dp,ZodMAC:()=>pp,ZodMap:()=>Op,ZodNaN:()=>Gp,ZodNanoID:()=>_a,ZodNever:()=>_p,ZodNonOptional:()=>Fa,ZodNull:()=>bp,ZodNullable:()=>Mp,ZodNumber:()=>Yn,ZodNumberFormat:()=>nn,ZodObject:()=>ai,ZodOptional:()=>ci,ZodPipe:()=>ui,ZodPrefault:()=>Fp,ZodPreprocess:()=>qp,ZodPromise:()=>tm,ZodReadonly:()=>Hp,ZodRealError:()=>je,ZodRecord:()=>qn,ZodSet:()=>Np,ZodString:()=>Xn,ZodStringFormat:()=>q,ZodSuccess:()=>Jp,ZodSymbol:()=>vp,ZodTemplateLiteral:()=>Yp,ZodTransform:()=>Ep,ZodTuple:()=>jp,ZodType:()=>M,ZodULID:()=>Ia,ZodURL:()=>ri,ZodUUID:()=>it,ZodUndefined:()=>yp,ZodUnion:()=>si,ZodUnknown:()=>wp,ZodVoid:()=>kp,ZodXID:()=>za,ZodXor:()=>Ip,_ZodString:()=>ba,_default:()=>Zp,_function:()=>ay,any:()=>Ev,array:()=>oi,base64:()=>vv,base64url:()=>yv,bigint:()=>Cv,boolean:()=>hp,catch:()=>Wp,check:()=>sy,cidrv4:()=>gv,cidrv6:()=>hv,clone:()=>J,codec:()=>ny,coerce:()=>cm,compile:()=>Il,config:()=>ie,core:()=>ft,creditCard:()=>$v,cuid:()=>sv,cuid2:()=>cv,currencyCode:()=>Iv,custom:()=>cy,date:()=>Mv,decode:()=>op,decodeAsync:()=>sp,deepPartial:()=>xy,describe:()=>uy,discriminatedUnion:()=>Jv,e164:()=>bv,email:()=>Xh,emoji:()=>ov,encode:()=>ip,encodeAsync:()=>ap,endsWith:()=>Un,enum:()=>Ma,exactOptional:()=>Up,file:()=>Yv,flattenError:()=>Ir,float32:()=>Pv,float64:()=>Av,formatError:()=>zr,fromJSONSchema:()=>by,function:()=>ay,getDiscriminatedOption:()=>qu,getErrorMap:()=>dI,globalRegistry:()=>ge,gt:()=>nt,gte:()=>Ee,guid:()=>Yh,hash:()=>zv,hex:()=>Sv,hostname:()=>kv,httpUrl:()=>iv,iban:()=>xv,includes:()=>Rn,input:()=>_y,instanceof:()=>dy,int:()=>va,int32:()=>jv,int64:()=>Ov,intersection:()=>Ap,invertCodec:()=>ry,ipv4:()=>pv,ipv6:()=>fv,iso:()=>pi,json:()=>my,jwt:()=>wv,keyof:()=>Lv,ksuid:()=>dv,lazy:()=>em,length:()=>Ht,literal:()=>Xv,locales:()=>Wr,looseObject:()=>Vv,looseRecord:()=>Wv,lowercase:()=>Nn,lt:()=>tt,lte:()=>Re,mac:()=>mv,map:()=>Gv,maxLength:()=>qt,maxSize:()=>St,memoizer:()=>Jr,meta:()=>ly,mime:()=>Ln,minLength:()=>mt,minSize:()=>rt,multipleOf:()=>kt,nan:()=>ty,nanoid:()=>av,nativeEnum:()=>Hv,negative:()=>aa,never:()=>Ua,nonnegative:()=>ca,nonoptional:()=>Kp,nonpositive:()=>sa,normalize:()=>Zn,null:()=>$p,nullable:()=>ni,nullish:()=>Qv,number:()=>gp,object:()=>Zv,optional:()=>Qt,output:()=>ky,overwrite:()=>He,parse:()=>ep,parseAsync:()=>tp,partialRecord:()=>Bv,pipe:()=>ya,positive:()=>oa,prefault:()=>Vp,preprocess:()=>fy,prettifyError:()=>tc,promise:()=>oy,properties:()=>Mn,property:()=>ua,readonly:()=>Xp,record:()=>Cp,refine:()=>rm,regex:()=>On,regexes:()=>Fe,registry:()=>No,safeDecode:()=>up,safeDecodeAsync:()=>dp,safeEncode:()=>cp,safeEncodeAsync:()=>lp,safeParse:()=>np,safeParseAsync:()=>rp,set:()=>qv,setErrorMap:()=>lI,size:()=>Gt,slugify:()=>Jn,startsWith:()=>En,strictObject:()=>Fv,string:()=>ti,stringFormat:()=>_v,stringbool:()=>py,success:()=>ey,superRefine:()=>im,symbol:()=>Dv,templateLiteral:()=>iy,toJSONSchema:()=>ma,toLowerCase:()=>Vn,toUpperCase:()=>Kn,toZod:()=>hr,transform:()=>La,treeifyError:()=>ec,trim:()=>Fn,tuple:()=>Tp,uint32:()=>Tv,uint64:()=>Nv,ulid:()=>uv,undefined:()=>Rv,union:()=>tr,unknown:()=>Yt,uppercase:()=>Dn,url:()=>rv,util:()=>b,uuid:()=>Qh,uuidv4:()=>ev,uuidv6:()=>tv,uuidv7:()=>nv,validate:()=>Pr,validateAsync:()=>Ar,void:()=>Uv,withParser:()=>Do,xid:()=>lv,xor:()=>Kv});var ft={};ut(ft,{$ZodAny:()=>Lu,$ZodArray:()=>Bu,$ZodAsyncError:()=>Pe,$ZodBase64:()=>Pu,$ZodBase64URL:()=>Au,$ZodBigInt:()=>$o,$ZodBigIntFormat:()=>Ru,$ZodBoolean:()=>Mr,$ZodCIDRv4:()=>Iu,$ZodCIDRv6:()=>zu,$ZodCUID:()=>fu,$ZodCUID2:()=>gu,$ZodCatch:()=>dl,$ZodCheck:()=>H,$ZodCheckBigIntFormat:()=>Zc,$ZodCheckEndsWith:()=>Qc,$ZodCheckGreaterThan:()=>ro,$ZodCheckIncludes:()=>Xc,$ZodCheckLengthEquals:()=>Wc,$ZodCheckLessThan:()=>no,$ZodCheckLowerCase:()=>qc,$ZodCheckMaxLength:()=>Jc,$ZodCheckMaxSize:()=>Fc,$ZodCheckMimeType:()=>nu,$ZodCheckMinLength:()=>Bc,$ZodCheckMinSize:()=>Vc,$ZodCheckMultipleOf:()=>Mc,$ZodCheckNumberFormat:()=>Lc,$ZodCheckOverwrite:()=>ru,$ZodCheckProperties:()=>tu,$ZodCheckProperty:()=>eu,$ZodCheckRegex:()=>Gc,$ZodCheckSizeEquals:()=>Kc,$ZodCheckStartsWith:()=>Yc,$ZodCheckStringFormat:()=>Pn,$ZodCheckUpperCase:()=>Hc,$ZodCodec:()=>Zr,$ZodCreditCard:()=>Tu,$ZodCustom:()=>yl,$ZodCustomStringFormat:()=>Nu,$ZodCyclicError:()=>zo,$ZodDate:()=>Ku,$ZodDefault:()=>sl,$ZodDiscriminatedUnion:()=>Hu,$ZodE164:()=>ju,$ZodEmail:()=>cu,$ZodEmoji:()=>pu,$ZodEncodeError:()=>wt,$ZodEnum:()=>tl,$ZodError:()=>Qs,$ZodExactOptional:()=>ol,$ZodFile:()=>rl,$ZodFunction:()=>hl,$ZodGUID:()=>au,$ZodIBAN:()=>Cu,$ZodIPv4:()=>_u,$ZodIPv6:()=>ku,$ZodISODate:()=>$u,$ZodISODateTime:()=>bu,$ZodISODuration:()=>wu,$ZodISOTime:()=>xu,$ZodIntersection:()=>Xu,$ZodJWT:()=>Ou,$ZodKSUID:()=>yu,$ZodLazy:()=>Fr,$ZodLiteral:()=>nl,$ZodMAC:()=>Su,$ZodMap:()=>Qu,$ZodNaN:()=>pl,$ZodNanoID:()=>mu,$ZodNever:()=>Fu,$ZodNonOptional:()=>ul,$ZodNull:()=>Mu,$ZodNullable:()=>al,$ZodNumber:()=>bo,$ZodNumberFormat:()=>Du,$ZodObject:()=>sg,$ZodObjectJIT:()=>Wu,$ZodOptional:()=>wo,$ZodPipe:()=>_o,$ZodPrefault:()=>cl,$ZodPreprocess:()=>ml,$ZodPromise:()=>vl,$ZodReadonly:()=>fl,$ZodRealError:()=>Ae,$ZodRecord:()=>Yu,$ZodRegistry:()=>Oo,$ZodSet:()=>el,$ZodString:()=>Kt,$ZodStringFormat:()=>B,$ZodSuccess:()=>ll,$ZodSymbol:()=>Eu,$ZodTemplateLiteral:()=>gl,$ZodTransform:()=>il,$ZodTuple:()=>xo,$ZodType:()=>D,$ZodULID:()=>hu,$ZodURL:()=>du,$ZodUUID:()=>su,$ZodUndefined:()=>Uu,$ZodUnion:()=>Lr,$ZodUnknown:()=>Zu,$ZodVoid:()=>Vu,$ZodXID:()=>vu,$ZodXor:()=>Gu,$brand:()=>Hs,$constructor:()=>h,$input:()=>wl,$output:()=>xl,Doc:()=>Vt,INVALID:()=>xe,JSONSchema:()=>Gh,JSONSchemaGenerator:()=>fa,NEVER:()=>qs,TimePrecision:()=>Nl,URL_BAD_FORMAT:()=>uu,URL_UNPARSEABLE:()=>Nr,ZodCompileAsyncError:()=>qe,ZodCompileUnsupportedError:()=>F,_any:()=>Xl,_array:()=>id,_base64:()=>ta,_base64url:()=>na,_bigint:()=>Kl,_boolean:()=>Fl,_catch:()=>GS,_check:()=>Ch,_cidrv4:()=>Qo,_cidrv6:()=>ea,_coercedBigint:()=>Jl,_coercedBoolean:()=>Vl,_coercedDate:()=>nd,_coercedNumber:()=>Rl,_coercedString:()=>jl,_creditCard:()=>Cl,_cuid:()=>Bo,_cuid2:()=>Wo,_custom:()=>ad,_date:()=>td,_decode:()=>Ji,_decodeAsync:()=>Wi,_default:()=>JS,_discriminatedUnion:()=>OS,_e164:()=>ra,_email:()=>Uo,_emoji:()=>Ko,_encode:()=>Ki,_encodeAsync:()=>Bi,_endsWith:()=>Un,_enum:()=>MS,_file:()=>od,_float32:()=>Ul,_float64:()=>Ml,_gt:()=>nt,_gte:()=>Ee,_guid:()=>Mo,_iban:()=>Ol,_includes:()=>Rn,_int:()=>El,_int32:()=>Ll,_int64:()=>Bl,_intersection:()=>NS,_ipv4:()=>Xo,_ipv6:()=>Yo,_isoDate:()=>Hr,_isoDateTime:()=>qr,_isoDuration:()=>Yr,_isoTime:()=>Xr,_jwt:()=>ia,_ksuid:()=>Ho,_lazy:()=>YS,_length:()=>Ht,_literal:()=>ZS,_lowercase:()=>Nn,_lt:()=>tt,_lte:()=>Re,_mac:()=>Tl,_map:()=>ES,_max:()=>Re,_maxLength:()=>qt,_maxSize:()=>St,_mime:()=>Ln,_min:()=>Ee,_minLength:()=>mt,_minSize:()=>rt,_multipleOf:()=>kt,_nan:()=>rd,_nanoid:()=>Jo,_nativeEnum:()=>LS,_negative:()=>aa,_never:()=>Ql,_nonnegative:()=>ca,_nonoptional:()=>BS,_nonpositive:()=>sa,_normalize:()=>Zn,_null:()=>Hl,_nullable:()=>KS,_number:()=>Dl,_optional:()=>VS,_overwrite:()=>He,_parse:()=>kn,_parseAsync:()=>Sn,_pipe:()=>qS,_positive:()=>oa,_promise:()=>QS,_properties:()=>Mn,_property:()=>ua,_readonly:()=>HS,_record:()=>RS,_refine:()=>sd,_regex:()=>On,_safeDecode:()=>qi,_safeDecodeAsync:()=>Xi,_safeEncode:()=>Gi,_safeEncodeAsync:()=>Hi,_safeParse:()=>In,_safeParseAsync:()=>zn,_set:()=>US,_size:()=>Gt,_slugify:()=>Jn,_startsWith:()=>En,_string:()=>Al,_stringFormat:()=>Xt,_stringbool:()=>dd,_success:()=>WS,_superRefine:()=>cd,_symbol:()=>Gl,_templateLiteral:()=>XS,_toLowerCase:()=>Vn,_toUpperCase:()=>Kn,_transform:()=>FS,_trim:()=>Fn,_tuple:()=>DS,_uint32:()=>Zl,_uint64:()=>Wl,_ulid:()=>Go,_undefined:()=>ql,_union:()=>TS,_unknown:()=>Yl,_uppercase:()=>Dn,_url:()=>Gr,_uuid:()=>Lo,_uuidv4:()=>Zo,_uuidv6:()=>Fo,_uuidv7:()=>Vo,_void:()=>ed,_xid:()=>qo,_xor:()=>CS,base64Charset:()=>fo,base64urlCharset:()=>Ur,canParseURL:()=>lu,clone:()=>J,compile:()=>Il,compileFn:()=>Ro,config:()=>ie,createStandardJSONSchemaMethod:()=>Bn,createToJSONSchemaMethod:()=>md,decode:()=>Cw,decodeAsync:()=>Nw,describe:()=>ud,encode:()=>Tw,encodeAsync:()=>Ow,extractDefs:()=>zt,finalize:()=>Pt,flattenError:()=>Ir,formatError:()=>zr,getDiscriminatedOption:()=>qu,globalConfig:()=>pe,globalRegistry:()=>ge,handleUnrepresentable:()=>ue,initializeContext:()=>It,isBackEdge:()=>Ao,isRecursiveSchema:()=>Po,isValidBase64:()=>Er,isValidBase64URL:()=>go,isValidCIDRv6:()=>mo,isValidCreditCard:()=>ho,isValidIBAN:()=>vo,isValidIPv6:()=>Rr,isValidJWT:()=>yo,locales:()=>Wr,memoizer:()=>Jr,mergeValues:()=>An,meta:()=>ld,parse:()=>Fi,parseAsync:()=>Vi,parseURLObject:()=>ig,prettifyError:()=>tc,process:()=>W,processSchema:()=>W,regexes:()=>Fe,registry:()=>No,safeDecode:()=>Rw,safeDecodeAsync:()=>Uw,safeEncode:()=>Dw,safeEncodeAsync:()=>Ew,safeParse:()=>Iw,safeParseAsync:()=>zw,standardProps:()=>co,stripTabAndNewline:()=>Dr,toDotPath:()=>Ef,toJSONSchema:()=>ma,toZod:()=>hr,treeifyError:()=>ec,urlHostnameOk:()=>lo,urlProtocolOk:()=>po,util:()=>b,validate:()=>Pr,validateAsync:()=>Ar,validateURL:()=>uo,version:()=>iu,withParser:()=>Do});var b={};ut(b,{BIGINT_FORMAT_RANGES:()=>xr,CONSTANT_CATCH:()=>Li,Class:()=>Ms,NUMBER_FORMAT_RANGES:()=>$r,aborted:()=>$e,allowsEval:()=>Fs,assert:()=>Bx,assertEqual:()=>Fx,assertIs:()=>Kx,assertNever:()=>Jx,assertNotEqual:()=>Vx,assignProp:()=>fe,attachSchema:()=>wr,base64ToUint8Array:()=>Tf,base64urlToUint8Array:()=>dw,cached:()=>$n,captureStackTrace:()=>Ui,cleanEnum:()=>lw,cleanRegex:()=>dt,clone:()=>J,cloneDef:()=>qx,codePointLength:()=>Zt,constantCatch:()=>Ws,createTransparentProxy:()=>tw,defineLazy:()=>Ls,defineLazyInternal:()=>L,derived:()=>gw,esc:()=>be,escapeRegex:()=>Ze,explicitlyAborted:()=>Js,extend:()=>iw,finalizeIssue:()=>ze,floatSafeRemainder:()=>vr,getElementAtPath:()=>Hx,getEnumValues:()=>yn,getLengthableOrigin:()=>kr,getParsedType:()=>ew,getSizableOrigin:()=>_r,hexToUint8Array:()=>mw,hide:()=>Sr,installLazyProp:()=>bw,isObject:()=>Lt,isPlainObject:()=>Le,issue:()=>_n,joinValues:()=>v,jsonStringifyReplacer:()=>bn,members:()=>Bs,merge:()=>aw,mergeDefs:()=>Ge,normalizeParams:()=>S,nullish:()=>Ei,numKeys:()=>Qx,objectClone:()=>Wx,omit:()=>rw,optionalKeys:()=>Ks,own:()=>xt,parsedType:()=>x,partial:()=>sw,pick:()=>nw,prefixIssues:()=>Ie,primitiveTypes:()=>Vs,promiseAllObject:()=>Xx,propertyKeyTypes:()=>br,randomString:()=>Yx,rawShape:()=>xn,required:()=>cw,safeExtend:()=>ow,shallowClone:()=>yr,sizeCaps:()=>wn,slugify:()=>Zs,stringifyPrimitive:()=>$,toZod:()=>hr,uint8ArrayToBase64:()=>Cf,uint8ArrayToBase64url:()=>pw,uint8ArrayToHex:()=>fw,unwrapMessage:()=>vn});function Fx(e){return e}function Vx(e){return e}function hr(){return e=>e}function Kx(e){}function Jx(e){throw new Error("Unexpected value in exhaustive check")}function Bx(e){}function yn(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function v(e,t="|"){return e.map(r=>$(r)).join(t)}function bn(e,t){return typeof t=="bigint"?t.toString():t}var Us=class{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}};function $n(e){return new Us(e)}function Ei(e){return e==null}function dt(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function vr(e,t){let r=e/t,o=Math.round(r),n=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var zf=Symbol("evaluating");function Ls(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==zf)return o===void 0&&(o=zf,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Wx(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function fe(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function xn(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function lt(e){return xn(e._zod.def)??e._zod.def.shape}function Pf(e,t,r){Object.defineProperty(e,t,{get(){let o=r();return fe(this,t,o),o},enumerable:!0,configurable:!0})}function Af(e,t,r){t in e?fe(e,t,r):e[t]=r}function Mt(e,t,r,o){let n=lt(t);for(let i of r){let a=Object.getOwnPropertyDescriptor(n,i);a.enumerable&&(a.get?Pf(e,i,()=>{let c=t._zod.def.shape[i];return o?o(c,i):c}):Af(e,i,o?o(a.value,i):a.value))}}function Gx(e,t){for(let r of Reflect.ownKeys(t)){let o=Object.getOwnPropertyDescriptor(t,r);o.enumerable&&(o.get?Pf(e,r,()=>t[r]):Af(e,r,o.value))}}function Ge(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function qx(e){return Ge(e._zod.def)}function Hx(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function Xx(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function Yx(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function be(e){return JSON.stringify(e)}function Zs(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Ui="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Fs=$n(()=>{if(pe.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Le(e){if(Lt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Lt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function yr(e){return Le(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Qx(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var ew=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},br=new Set(["string","number","symbol"]),Vs=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ze(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function S(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function tw(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function $(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ks(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var $r={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},xr={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function nw(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i={};return Mt(i,e,Mi(e,t)),J(e,Ge(r,{shape:i,checks:[]}))}function Mi(e,t){let r=lt(e),o=[];for(let n of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,n)?.enumerable)throw new Error(`Unrecognized key: "${String(n)}"`);t[n]&&o.push(n)}return o}function rw(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(Mi(e,t)),a={};return Mt(a,e,Reflect.ownKeys(lt(e)).filter(c=>!i.has(c))),J(e,Ge(r,{shape:a,checks:[]}))}function iw(e,t){if(!Le(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let n=lt(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return J(e,Ge(e._zod.def,{shape:jf(e,t)}))}function jf(e,t){let r={};return Mt(r,e,Reflect.ownKeys(lt(e))),Gx(r,t),r}function ow(e,t){if(!Le(t))throw new Error("Invalid input to safeExtend: expected a plain object");return J(e,Ge(e._zod.def,{shape:jf(e,t)}))}function aw(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};Mt(r,e,Reflect.ownKeys(lt(e))),Mt(r,t,Reflect.ownKeys(lt(t)));let o=Ge(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return J(e,o)}function sw(e,t,r,o="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${o}() cannot be used on object schemas containing refinements`);let c=r?new Set(Mi(t,r)):void 0,u={};return Mt(u,t,Reflect.ownKeys(lt(t)),e&&((l,d)=>c&&!c.has(d)?l:new e({type:"optional",innerType:l}))),J(t,Ge(t._zod.def,{shape:u,checks:[]}))}function cw(e,t,r){let o=r?new Set(Mi(t,r)):void 0,n={};return Mt(n,t,Reflect.ownKeys(lt(t)),(i,a)=>o&&!o.has(a)?i:new e({type:"nonoptional",innerType:i})),J(t,Ge(t._zod.def,{shape:n}))}function $e(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Js(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Ie(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function vn(e){return typeof e=="string"?e:e?.message}function wn(e){let t=[];for(let r of e??[]){let o=r._zod.def;if(!/_(length|size)$|_equals$/.test(o.check))break;let n=o.maximum??o.length??o.size;n>=0&&t.push([n,r])}return t}function wr(e,t,r){var o;for(let n=t;n<e.length;n++)(o=e[n]).schema??(o.schema=r)}function ze(e,t,r){var o;let n=e.inst?._zod?.traits;n?.has("$ZodType")&&(n.has("$ZodCheck")?(o=e).schema??(o.schema=e.inst):e.schema=e.inst);let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:vn(e.inst?._zod.def?.error?.(e))??vn(i?.(e))??vn(t?.error?.(e))??vn(r.customError?.(e))??vn(r.localeError?.(e))??"Invalid input",c={};for(let u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(c[u]=e[u]);return c.path??(c.path=[]),c.message=a,t?.reportInput&&(c.input=e.input),c}function _r(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}var uw=/[\uD800-\uDBFF]/;function Zt(e){let t=e.length;if(!uw.test(e))return t;let r=t;for(let o=0;o<t-1;o++)(e.charCodeAt(o)&64512)===55296&&(e.charCodeAt(o+1)&64512)===56320&&(r--,o++);return r}function kr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function x(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function _n(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function lw(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Tf(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function Cf(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function dw(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return Tf(t+r)}function pw(e){return Cf(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function mw(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function fw(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ms=class{constructor(...t){}};function Bs(e,t){for(let r in t){let o=Object.getOwnPropertyDescriptor(t,r);o.get?Object.defineProperty(e,r,{...o,enumerable:!1}):hw(e,r,o.value)}}function xt(e,t,r,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function Sr(e,t,r){return xt(e,t,r,!1)}function gw(e,t){for(let r in e){let o=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return xt(this,r,o(this))},set(n){xt(this,r,n)}})}return t}function hw(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:xt(this,t,r.bind(this))},set(o){xt(this,t,o)}})}function vw(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var Es,$t=!1,yw={configurable:!0,get(){$t=!0}};function L(e,t,r){let o=Object.getPrototypeOf(e._zod);if(t in o&&Es!==e._zod){Es=void 0;return}Es=e._zod,Object.defineProperty(o,t,{configurable:!0,get(){Object.defineProperty(this,t,yw);let n=$t;$t=!1;try{let i=r(this);return $t?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i}),$t=$t||n,i}catch(i){throw delete this[t],$t=$t||n,i}},set(n){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:n})}})}function bw(e,t,r,o){let n=vw(e,t);n&&Object.defineProperty(n,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:o,value:void 0};return Object.defineProperty(this,t,i),i.value=r(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:o,value:i})}})}var Li="~constantCatch";function Ws(e){let t=()=>e;return t[Li]=!0,t}var Of,qs=Object.freeze({status:"aborted"}),Gs={value:void 0,enumerable:!1},Nf="captureStackTrace"in Error?Error:null;function $w(e){let t=Nf;if(t){let r=t.stackTraceLimit;if(typeof r=="number"){try{t.stackTraceLimit=0}catch{return Nf=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function h(e,t,r,o){let n={};function i(f){this.def=f,this.constr=p,this.traits=new Set}i.prototype=n;let a=r,c=a&&new WeakSet;function u(f,m){if(f._zod){if(f._zod.traits.has(e))return}else{Gs.value=new i(m);try{Object.defineProperty(f,"_zod",Gs)}finally{Gs.value=void 0}}if(f._zod.traits.add(e),t(f,m),c){let y=Object.getPrototypeOf(f),_=f._zod.constr.prototype,I=y;for(;I&&I!==_;)I=Object.getPrototypeOf(I);let k=I??y;c.has(k)||(c.add(k),Bs(k,a))}let g=p.prototype;for(let y in g)Object.prototype.hasOwnProperty.call(g,y)&&(y in f||(f[y]=g[y].bind(f)))}let l=o?.Parent??Object;class d extends l{}Object.defineProperty(d,"name",{value:e});function p(f){let m=o?.Parent?$w(d):this;u(m,f);let g=m._zod.deferred;if(g){for(let _ of g)_();m._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;return y&&y(m),m}return Object.defineProperty(p,"init",{value:u}),Object.defineProperty(p,Symbol.hasInstance,{value:f=>o?.Parent&&f instanceof o.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(p,"name",{value:e}),p}var Hs=Symbol("zod_brand"),Pe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},wt=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(Of=globalThis).__zod_globalConfig??(Of.__zod_globalConfig={});var pe=globalThis.__zod_globalConfig;function ie(e){return e&&Object.assign(pe,e),pe}function xw(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,bn,2)),e.message}function ww(e){this._zod.message=e}var _w={get:xw,set:ww,enumerable:!0,configurable:!0},Ys={value:void 0,enumerable:!1},Df=new WeakSet([Object.prototype,Error.prototype]),Rf=(e,t)=>{e.name="$ZodError",Ys.value=t,Object.defineProperty(e,"issues",Ys),Ys.value=void 0,Object.defineProperty(e,"message",_w);let r=Object.getPrototypeOf(e);Df.has(r)||(Df.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let o=()=>this.message;return Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0})}}))},Qs=h("$ZodError",Rf),Ae=h("$ZodError",Rf,void 0,{Parent:Error});function kw(e,t,r){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0}):e[t]=r()),e[t]}function Ir(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?kw(r,n.path[0],()=>[]).push(t(n)):o.push(t(n));return{formErrors:o,fieldErrors:r}}function zr(e,t=r=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let a of n.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>o({issues:c},[...i,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...i,...a.path]);else{let c=[...i,...a.path];if(c.length===0)r._errors.push(t(a));else{let u=r,l=0;for(;l<c.length;){let d=c[l],p=l===c.length-1;if(d==="_errors"){p&&u._errors.push(t(a)),l++;continue}Object.prototype.hasOwnProperty.call(u,d)||Object.defineProperty(u,d,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let f=u[d];p&&f._errors.push(t(a)),u=f,l++}}}};return o(e),r}function ec(e,t=r=>r.message){let r={errors:[]},o=(n,i=[])=>{var a;for(let c of n.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(u=>o({issues:u},[...i,...c.path]));else if(c.code==="invalid_key")o({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")o({issues:c.issues},[...i,...c.path]);else{let u=[...i,...c.path];if(u.length===0){r.errors.push(t(c));continue}let l=r,d=0;for(;d<u.length;){let p=u[d],f=d===u.length-1;typeof p=="string"?(l.properties??(l.properties={}),Object.prototype.hasOwnProperty.call(l.properties,p)||Object.defineProperty(l.properties,p,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),l=l.properties[p]):(l.items??(l.items=[]),(a=l.items)[p]??(a[p]={errors:[]}),l=l.items[p]),f&&l.errors.push(t(c)),d++}}};return o(e),r}function Ef(e){let t=[],r=e.map(o=>typeof o=="object"?o.key:o);for(let o of r)typeof o=="number"?t.push(`[${o}]`):typeof o=="symbol"?t.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?t.push(`[${JSON.stringify(o)}]`):(t.length&&t.push("."),t.push(o));return t.join("")}function tc(e){let t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)t.push(`\u2716 ${o.message}`),o.path?.length&&t.push(` \u2192 at ${Ef(o.path)}`);return t.join(`
|
|
3
3
|
`)}function Zi(e,t){return{callee:t?.callee??e,Err:t?.Err}}var kn=e=>{let t=(r,o,n,i)=>{let a=n?{...n,async:!1}:{async:!1},c=r._zod.run({value:o,issues:[]},a);if(c instanceof Promise)throw new Pe;if(c.issues.length){let u=new(i?.Err??e)(c.issues.map(l=>ze(l,a,ie())));throw Ui(u,i?.callee??t),u}return c.value};return t},Fi=kn(Ae),Sn=e=>{let t=async(r,o,n,i)=>{let a=n?{...n,async:!0}:{async:!0},c=r._zod.run({value:o,issues:[]},a);if(c instanceof Promise&&(c=await c),c.issues.length){let u=new(i?.Err??e)(c.issues.map(l=>ze(l,a,ie())));throw Ui(u,i?.callee??t),u}return c.value};return t},Vi=Sn(Ae),In=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new Pe;return i.issues.length?Uf(e,i.issues,n):{success:!0,data:i.value}},Iw=In(Ae);function Uf(e,t,r){let o;return{success:!1,get error(){return o||(o=new e(t.map(n=>ze(n,r,ie()))),t=void 0,r=void 0),o},set error(n){o=n,t=void 0,r=void 0}}}var zn=e=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?Uf(e,i.issues,n):{success:!0,data:i.value}},zw=zn(Ae),Pw=Symbol.for("zod.compile.invalid"),Aw=Symbol.for("zod.compile.fallback"),Pr=((e,t,r)=>{let o=e._zod.bag.validator;if(o!==void 0){if(o(t)!==Pw)return!0;if(o.definite===!0&&r===void 0)return!1}return jw(e,t,r)});function jw(e,t,r){let o=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},n=e._zod.bag.fallbackRun,i;if(n?(o[Aw]=!0,i=n({value:t,issues:[]},o)):i=e._zod.run({value:t,issues:[]},o),i instanceof Promise)throw new Pe;return i.issues.length===0}var Ar=async(e,t,r)=>{let o=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},n=e._zod.run({value:t,issues:[]},o);return n instanceof Promise&&(n=await n),n.issues.length===0},Ki=e=>{let t=kn(e),r=(o,n,i,a)=>{let c=i?{...i,direction:"backward"}:{direction:"backward"};return t(o,n,c,Zi(r,a))};return r},Tw=Ki(Ae),Ji=e=>{let t=kn(e),r=(o,n,i,a)=>t(o,n,i,Zi(r,a));return r},Cw=Ji(Ae),Bi=e=>{let t=Sn(e),r=async(o,n,i,a)=>{let c=i?{...i,direction:"backward"}:{direction:"backward"};return await t(o,n,c,Zi(r,a))};return r},Ow=Bi(Ae),Wi=e=>{let t=Sn(e),r=async(o,n,i,a)=>await t(o,n,i,Zi(r,a));return r},Nw=Wi(Ae),Gi=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return In(e)(t,r,n)},Dw=Gi(Ae),qi=e=>(t,r,o)=>In(e)(t,r,o),Rw=qi(Ae),Hi=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return zn(e)(t,r,n)},Ew=Hi(Ae),Xi=e=>async(t,r,o)=>zn(e)(t,r,o),Uw=Xi(Ae);var Fe={};ut(Fe,{anyString:()=>Pc,base64:()=>bc,base64url:()=>$c,bigint:()=>jc,boolean:()=>Tc,browserEmail:()=>Bw,cidrv4:()=>vc,cidrv6:()=>yc,creditCard:()=>Yi,cuid:()=>rc,cuid2:()=>ic,currencyCode:()=>kc,date:()=>Sc,datetime:()=>zc,domain:()=>wc,duration:()=>lc,e164:()=>_c,email:()=>pc,emoji:()=>mc,extendedDuration:()=>Mw,guid:()=>dc,hex:()=>Rc,hostname:()=>xc,html5Email:()=>Vw,httpProtocol:()=>jr,iban:()=>Qi,idnEmail:()=>Jw,integer:()=>Tr,ipv4:()=>fc,ipv6:()=>gc,ksuid:()=>sc,lowercase:()=>Nc,mac:()=>hc,md5_base64:()=>Hw,md5_base64url:()=>Xw,md5_hex:()=>qw,nanoid:()=>cc,nanoidOfLength:()=>uc,null:()=>Cc,number:()=>pt,rfc5322Email:()=>Kw,sha1_base64:()=>Qw,sha1_base64url:()=>e_,sha1_hex:()=>Yw,sha256_base64:()=>n_,sha256_base64url:()=>r_,sha256_hex:()=>t_,sha384_base64:()=>o_,sha384_base64url:()=>a_,sha384_hex:()=>i_,sha512_base64:()=>c_,sha512_base64url:()=>u_,sha512_hex:()=>s_,string:()=>Ac,time:()=>Ic,ulid:()=>oc,undefined:()=>Oc,unicodeEmail:()=>Mf,uppercase:()=>Dc,uuid:()=>Ft,uuid4:()=>Lw,uuid6:()=>Zw,uuid7:()=>Fw,xid:()=>ac});var rc=/^[cC][0-9a-z]{6,}$/,ic=/^[0-9a-z]+$/,oc=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,ac=/^[0-9a-vA-V]{20}$/,sc=/^[A-Za-z0-9]{27}$/,cc=/^[a-zA-Z0-9_-]{21}$/;function uc(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var lc=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Mw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,dc=/^([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})$/,Ft=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,Lw=Ft(4),Zw=Ft(6),Fw=Ft(7),pc=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Vw=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Kw=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Mf=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Jw=Mf,Bw=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Ww="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function mc(){return new RegExp(Ww,"u")}var fc=/^(?:(?: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])$/,gc=/^(([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}|:))$/,hc=e=>{let t=Ze(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},vc=/^((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])$/,yc=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bc=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$c=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,xc=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,wc=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,jr=/^https?$/,_c=/^\+[1-9]\d{6,14}$/,Yi=/^\d(?:[ -]?\d){11,18}$/,kc=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,Qi=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,Lf="(?:(?:\\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])))";function Gw(e){return new RegExp(`^${e}$`)}var Sc=Gw(Lf);function nc(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ic(e){return new RegExp(`^${nc(e)}$`)}function zc(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${nc({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,o=e.local?`${r}|${nc({precision:e.precision})}`:r;return new RegExp(`^${Lf}T(?:${o})$`)}var Pc=/^[\s\S]{0,}$/,Ac=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},jc=/^-?\d+n?$/,Tr=/^-?\d+$/,pt=/^-?\d+(?:\.\d+)?$/,Tc=/^(?:true|false)$/i,Cc=/^null$/i;var Oc=/^undefined$/i;var Nc=/^[^A-Z]*$/,Dc=/^[^a-z]*$/,Rc=/^[0-9a-fA-F]*$/;function Cr(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Or(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var qw=/^[0-9a-fA-F]{32}$/,Hw=Cr(22,"=="),Xw=Or(22),Yw=/^[0-9a-fA-F]{40}$/,Qw=Cr(27,"="),e_=Or(27),t_=/^[0-9a-fA-F]{64}$/,n_=Cr(43,"="),r_=Or(43),i_=/^[0-9a-fA-F]{96}$/,o_=Cr(64,""),a_=Or(64),s_=/^[0-9a-fA-F]{128}$/,c_=Cr(86,"=="),u_=Or(86);var H=h("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Ec=e=>{let t=e.value;return!Ei(t)&&t.size!==void 0},Uc=e=>{let t=e.value;return!Ei(t)&&t.length!==void 0},eo={number:"number",bigint:"bigint",object:"date"},no=h("$ZodCheckLessThan",(e,t)=>{H.init(e,t);let r=eo[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:eo[typeof o.value]??r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ro=h("$ZodCheckGreaterThan",(e,t)=>{H.init(e,t);let r=eo[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:eo[typeof o.value]??r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Mc=h("$ZodCheckMultipleOf",(e,t)=>{H.init(e,t),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):vr(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Lc=h("$ZodCheckNumberFormat",(e,t)=>{H.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=$r[t.format];e._zod.check=a=>{let c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}c<n&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),c>i&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Zc=h("$ZodCheckBigIntFormat",(e,t)=>{H.init(e,t);let[r,o]=xr[t.format];e._zod.check=n=>{let i=n.value;i<r&&n.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>o&&n.issues.push({origin:"bigint",input:i,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Fc=h("$ZodCheckMaxSize",(e,t)=>{var r;H.init(e,t),(r=e._zod.def).when??(r.when=Ec),e._zod.check=o=>{let n=o.value;n.size<=t.maximum||o.issues.push({origin:_r(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Vc=h("$ZodCheckMinSize",(e,t)=>{var r;H.init(e,t),(r=e._zod.def).when??(r.when=Ec),e._zod.check=o=>{let n=o.value;n.size>=t.minimum||o.issues.push({origin:_r(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Kc=h("$ZodCheckSizeEquals",(e,t)=>{var r;H.init(e,t),(r=e._zod.def).when??(r.when=Ec),e._zod.check=o=>{let n=o.value,i=n.size;if(i===t.size)return;let a=i>t.size;o.issues.push({origin:_r(n),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Jc=h("$ZodCheckMaxLength",(e,t)=>{var r;H.init(e,t),(r=e._zod.def).when??(r.when=Uc),e._zod.check=o=>{let n=o.value,i=n.length;if((typeof n=="string"&&i>t.maximum?Zt(n):i)<=t.maximum)return;let c=kr(n);o.issues.push({origin:c,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Bc=h("$ZodCheckMinLength",(e,t)=>{var r;H.init(e,t),(r=e._zod.def).when??(r.when=Uc),e._zod.check=o=>{let n=o.value,i=n.length;if((typeof n=="string"&&i>=t.minimum&&i<t.minimum*2?Zt(n):i)>=t.minimum)return;let c=kr(n);o.issues.push({origin:c,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Wc=h("$ZodCheckLengthEquals",(e,t)=>{var r;H.init(e,t),(r=e._zod.def).when??(r.when=Uc),e._zod.check=o=>{let n=o.value,i=n.length,a=typeof n=="string"&&i>=t.length&&i<=t.length*2?Zt(n):i;if(a===t.length)return;let c=kr(n),u=a>t.length;o.issues.push({origin:c,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Pn=h("$ZodCheckStringFormat",(e,t)=>{var r,o;H.init(e,t),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),Gc=h("$ZodCheckRegex",(e,t)=>{Pn.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),qc=h("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Nc),Pn.init(e,t)}),Hc=h("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Dc),Pn.init(e,t)}),Xc=h("$ZodCheckIncludes",(e,t)=>{H.init(e,t);let r=Ze(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position},}${r}`:r);t.pattern=o,e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Yc=h("$ZodCheckStartsWith",(e,t)=>{H.init(e,t);let r=new RegExp(`^${Ze(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Qc=h("$ZodCheckEndsWith",(e,t)=>{H.init(e,t);let r=new RegExp(`.*${Ze(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});function to(e,t,r){e.issues.length&&t.issues.push(...Ie(r,e.issues))}var eu=h("$ZodCheckProperty",(e,t)=>{H.init(e,t),e._zod.check=r=>{let o=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(o instanceof Promise)return o.then(n=>to(n,r,t.property));to(o,r,t.property)}}),tu=h("$ZodCheckProperties",(e,t)=>{H.init(e,t),Sr(e,Symbol.iterator,function*(){yield e});let r;e._zod.check=o=>{if(o.value==null){o.issues.push({expected:"object",code:"invalid_type",input:o.value,inst:e});return}r??(r=Reflect.ownKeys(t.shape).map(a=>[a,t.shape[a]]));let n=o.value,i;for(let[a,c]of r){let u=c._zod.run({value:n[a],issues:[]},{});u instanceof Promise?(i??(i=[]),i.push(u.then(l=>to(l,o,a)))):to(u,o,a)}if(i)return Promise.all(i).then(()=>{})}}),nu=h("$ZodCheckMimeType",(e,t)=>{H.init(e,t);let r=new Set(t.mime);e._zod.check=o=>{r.has(o.value.type)||o.issues.push({code:"invalid_value",values:t.mime,input:o.value.type,inst:e,continue:!t.abort})}}),ru=h("$ZodCheckOverwrite",(e,t)=>{H.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Vt=class{constructor(t=[],r={}){this.content=[],this.indent=0,this.args=t,this.closed=r}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
|
|
4
4
|
`).filter(a=>a),n=Math.min(...o.map(a=>a.length-a.trimStart().length)),i=o.map(a=>a.slice(n)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let t=Function,r=this?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
5
5
|
${r.join(`
|
|
@@ -15,7 +15,7 @@ ${r.join(`
|
|
|
15
15
|
if (${C}_ab && ctx && ctx.abortEarly) {
|
|
16
16
|
payload.value = newResult;
|
|
17
17
|
return payload;
|
|
18
|
-
}`;_.write("const input = payload.value;");let A=Object.create(null),Z=0;for(let C of g.allKeys)A[C]=`key_${Z++}`;_.write(n?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let C of g.allKeys){if(C==="__proto__")continue;let E=A[C],P=typeof C=="symbol"?`syms[${y.indexOf(C)}]`:be(C),Q=`${P} in input`,re=m[C],Ne=re?._zod?.optin,
|
|
18
|
+
}`;_.write("const input = payload.value;");let A=Object.create(null),Z=0;for(let C of g.allKeys)A[C]=`key_${Z++}`;_.write(n?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let C of g.allKeys){if(C==="__proto__")continue;let E=A[C],P=typeof C=="symbol"?`syms[${y.indexOf(C)}]`:be(C),Q=`${P} in input`,re=m[C],Ne=re?._zod?.optin,O=Ne!==void 0,We=re?._zod?.optout==="optional";if(_.write(`const ${E} = ${I(P)};`),O&&We){let Et=Ne==="optional"?`${E}_present`:`${E}.value !== undefined || ${E}_present`;_.write(`
|
|
19
19
|
const ${E}_present = ${Q};
|
|
20
20
|
if (!${E}.issues.length || ${E}_present) {
|
|
21
21
|
if (${E}.issues.length) {${k(E,P)}
|
|
@@ -26,7 +26,7 @@ ${r.join(`
|
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
`)}else
|
|
29
|
+
`)}else O?(_.write(`
|
|
30
30
|
if (${E}.issues.length) {${k(E,P)}
|
|
31
31
|
}
|
|
32
32
|
`),Ne==="defaulted"?_.write(`newResult[${P}] = ${E}.value;`):_.write(`
|
|
@@ -58,15 +58,15 @@ ${r.join(`
|
|
|
58
58
|
`),l=t?.debug?a.length>0?`// Constants: ${a.join(", ")}
|
|
59
59
|
${u}`:u:"",d=Function,p=`return (input) => {
|
|
60
60
|
${u}
|
|
61
|
-
}`,f;try{f=new d(...a,p)(...c)}catch(m){throw new F(`this schema (generated code failed to evaluate: ${m.message})`)}return t?.debug&&(f.code=l),f.definite=o.definite,f}function O(e,t){for(let[o,n]of e.constants)if(n===t)return o;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function Bt(e,t){return e.definite=!1,O(e,t)}function T(e){return`v${e.varCounter++}`}function Nk(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return xe;let o=r;return o.issues.length===0?o.value:xe}function he(e,t,r,o,n=!0){let i=e.content.length,a=t.constants.size,c=t.constantCounter,u=t.varCounter;try{return te(e,t,r,o,n)}catch(l){if(!(l instanceof F)||!l.islandable)throw l;if(e.content.length=i,t.constants.size>a){let d=Array.from(t.constants.keys()).slice(a);for(let p of d)t.constants.delete(p)}return t.constantCounter=c,t.varCounter=u,Dk(e,t,r,o)}}function Dk(e,t,r,o){t.definite=!1;let n=O(t,r),i=O(t,Nk),a=T(t);return e.write(`const ${a} = ${i}(${n}, ${o});`),e.write(`if (${a} === INVALID) return INVALID;`),a}var Rk=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Ek(e,t,r,o){let n=r._zod.def.checks;if(!n||n.length===0)return o;let i=o;for(let a of n){let c=a._zod.def;if(c.when&&!Rk.has(c.check))throw new F('check with a custom "when" condition');switch(c.check){case"greater_than":Uk(e,t,c,i);break;case"less_than":Mk(e,t,c,i);break;case"multiple_of":Lk(e,t,c,i);break;case"number_format":jh(e,c,i);break;case"min_length":{let u=_t(c.minimum,"min_length"),l=_l(e,t,i,`${i}.length >= ${u} && ${i}.length < ${c.minimum*2}`);e.write(`if (${l} < ${u}) return INVALID;`);break}case"max_length":{let u=_t(c.maximum,"max_length"),l=_l(e,t,i,`${i}.length > ${u}`);e.write(`if (${l} > ${u}) return INVALID;`);break}case"length_equals":{let u=_t(c.length,"length_equals"),l=_l(e,t,i,`${i}.length >= ${u} && ${i}.length <= ${c.length*2}`);e.write(`if (${l} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${i}.size < ${_t(c.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${i}.size > ${_t(c.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${i}.size !== ${_t(c.size,"size_equals")}) return INVALID;`);break;case"string_format":i=Th(e,t,c,i);break;case"custom":i=Bk(e,t,a,i);break;case"bigint_format":Zk(e,c,i);break;case"mime_type":Fk(e,t,c,i);break;case"property":Kk(e,t,c,i);break;case"properties":Vk(e,t,c,i);break;case"overwrite":{let u=T(t);Jk(e,t,a,i,u),i=u;break}default:throw new F(`check type ${c.check}`)}}return i}function _l(e,t,r,o){let n=O(t,Zt),i=T(t);return e.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function _t(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new F(`${t} bound of type ${typeof e}`);return`${e}`}function Ah(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new F("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new F("comparison check with Invalid Date bound");return O(e,t)}throw new F(`comparison check bound of type ${typeof t}`)}function Uk(e,t,r,o){let n=r.inclusive?"<":"<=";e.write(`if (${o} ${n} ${Ah(t,r.value)}) return INVALID;`)}function Mk(e,t,r,o){let n=r.inclusive?">":">=";e.write(`if (${o} ${n} ${Ah(t,r.value)}) return INVALID;`)}function Lk(e,t,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new F("multiple_of check with a zero divisor");e.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=O(t,vr);e.write(`if (${n}(${o}, ${_t(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function jh(e,t,r){let o=t.format;switch(o){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new F(`number format ${o}`)}}function Zk(e,t,r){let o=t.format;if(o)switch(o){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new F(`bigint format ${o}`)}}function Fk(e,t,r,o){let n=r.mime;if(n&&n.length>0){let i=O(t,new Set(n));e.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function Vk(e,t,r,o){if(r.when)throw new F('check with a custom "when" condition');e.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let a=typeof i=="symbol"?O(t,i):be(i),c=T(t);e.write(`const ${c} = ${o}[${a}];`),he(e,t,n[i],c,!1)}}function Kk(e,t,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;te(e,t,r.schema,n)}function Jk(e,t,r,o,n){let i=r._zod.def.tx;if(!i)throw new F("overwrite check without a transform function");if(Wt(i))throw new qe("z.compile: async overwrite transforms are not supported");let a=O(t,i);e.write(`const ${n} = ${a}(${o});`)}function kl(){throw new Pe}function zl(e){this.issues.push(e)}function Bk(e,t,r,o){let n=r._zod.def;if(n.fn){if(Wt(n.fn))throw new qe("z.compile: async .refine() predicates are not supported");let i=Bt(t,n.fn),a=O(t,kl),c=T(t);return e.write(`const ${c} = ${i}(${o});`),e.write(`if (${c} instanceof Promise) ${a}();`),e.write(`if (!${c}) return INVALID;`),o}if(r._zod.check){if(Wt(r._zod.check))throw new qe("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,c=Bt(t,l=>{let d={value:l,issues:[],addIssue:zl};return i(d)instanceof Promise&&kl(),d.issues.length===0?d.value:xe}),u=T(t);return e.write(`const ${u} = ${c}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new F("custom check without a predicate or check function")}var Wk=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function Th(e,t,r,o,n=!0){let i=r.format;if(i==="base64"){let l=O(t,Er);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="base64url"){let l=O(t,go);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="jwt"){let l=O(t,yo),d=O(t,r.alg??null);return e.write(`if (!${l}(${o}, ${d})) return INVALID;`),o}if(i==="ipv6"){let l=O(t,Rr);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="cidrv6"){let l=O(t,mo);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="credit_card"){let l=O(t,ho);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="iban"){let l=O(t,vo);return e.write(`if (!${l}(${o})) return INVALID;`),o}let a=r;if(i==="url"||i==="httpurl"||a.normalize||a.hostname!==void 0||a.protocol!==void 0){let l=O(t,uo),d=O(t,r),p=T(t),f=T(t);if(e.write(`const ${p} = ${o}.trim();`),e.write(`const ${f} = ${l}(${p}, ${d});`),e.write(`if (typeof ${f} === "number") return INVALID;`),a.hostname!==void 0){let y=O(t,lo);e.write(`if (!${y}(${f}, ${d}.hostname)) return INVALID;`)}if(a.protocol!==void 0){let y=O(t,po);e.write(`if (!${y}(${f}, ${d}.protocol)) return INVALID;`)}if(!n)return null;let m=T(t),g=a.normalize?`${f}.href`:`${O(t,Dr)}(${p})`;return e.write(`const ${m} = ${g};`),m}let c=r.fn;if(c){if(Wt(c))throw new F(`async string format ${i}`);let l=O(t,c);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(Wk.has(i)&&r.pattern){let l=O(t,r.pattern);return e.write(`${l}.lastIndex = 0;`),e.write(`if (!${l}.test(${o})) return INVALID;`),o}let u=r.format;switch(u){case"regex":throw new F("regex format without a pattern");case"lowercase":e.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${o}.includes(${be(r.includes)})) return INVALID;`);break;case"starts_with":{let l=r.prefix;e.write(`if (${o}.slice(0, ${l.length}) !== ${be(l)}) return INVALID;`);break}case"ends_with":{let l=r.suffix;e.write(`if (${o}.slice(-${l.length}) !== ${be(l)}) return INVALID;`);break}default:throw new F(`string format ${u}`)}return o}function te(e,t,r,o,n=!0){let i=r._zod.def,a=i.type;if(i.coerce)throw new F(`coercion (z.coerce.${a}())`);let c=n||!!i.checks?.length,u;switch(a){case"string":u=Gk(e,t,r,o,c);break;case"number":u=qk(e,r,o);break;case"boolean":u=Hk(e,o);break;case"bigint":u=Xk(e,r,o);break;case"symbol":u=Yk(e,o);break;case"undefined":u=Qk(e,o);break;case"null":u=eS(e,o);break;case"any":case"unknown":u=o;break;case"never":e.write("return INVALID;"),u=o;break;case"void":u=tS(e,o);break;case"nan":u=nS(e,o);break;case"date":u=rS(e,o);break;case"object":u=iS(e,t,r,o,c);break;case"optional":u=oS(e,t,r,o,c);break;case"nullable":u=cS(e,t,r,o,c);break;case"array":u=uS(e,t,r,o,c);break;case"literal":u=lS(e,t,r,o);break;case"enum":u=dS(e,t,r,o);break;case"readonly":{let l=Ih(e,t,r,o),d=T(t);e.write(`const ${d} = Object.freeze(${l});`),u=d;break}case"success":Ih(e,t,r,o),u="true";break;case"default":case"prefault":u=pS(e,t,r,o);break;case"nonoptional":u=mS(e,t,r,o);break;case"tuple":u=fS(e,t,r,o);break;case"union":u=gS(e,t,r,o);break;case"intersection":u=yS(e,t,r,o);break;case"record":u=bS(e,t,r,o);break;case"map":u=xS(e,t,r,o);break;case"set":u=wS(e,t,r,o);break;case"file":u=_S(e,o);break;case"template_literal":u=kS(e,t,r,o);break;case"lazy":u=SS(e,t,r,o);break;case"pipe":u=IS(e,t,r,o);break;case"custom":u=zS(e,t,r,o);break;case"transform":u=jS(e,t,r,o);break;case"catch":u=AS(e,t,r,o);break;default:throw new F(`schema type ${a}`)}return u===null?null:Ek(e,t,r,u)}function Gk(e,t,r,o,n=!0){e.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:Th(e,t,i,o,n)}function qk(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=t._zod.def;return o.check==="number_format"&&o.format&&jh(e,{format:o.format},r),r}function Hk(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function Xk(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=t._zod.def;if(o.format)switch(o.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function Yk(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function Qk(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function eS(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function tS(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function nS(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function rS(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function iS(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let a=i.shape,c=Object.keys(a),u=Object.getOwnPropertySymbols(a),l=u.length?[...c,...u]:c,d=k=>typeof k=="symbol"?O(t,k):be(k),p=k=>typeof k=="symbol"?`[${d(k)}]`:be(k),f=a;if(c.includes("__proto__"))throw new F('object shape key "__proto__"');let m=new Map;for(let k of l){let A=f[k],Z=d(k),C=T(t);if(e.write(`const ${C} = ${o}[${Z}];`),A._zod.optin!==void 0){let E=T(t);e.write(`let ${E} = (() => {`),e.indented(P=>{let Q=he(P,t,A,C);P.write(`return ${Q};`)}),e.write("})();"),A._zod.optout==="optional"?(e.write(`if (${E} === INVALID) {`),e.indented(P=>{P.write(`if (${Z} in ${o}) return INVALID;`),P.write(`${E} = undefined;`)}),e.write("}")):e.write(`if (${E} === INVALID) return INVALID;`),m.set(k,E)}else{sS(A)&&e.write(`if (!(${Z} in ${o})) return INVALID;`);let E=he(e,t,A,C,n);E!==null&&m.set(k,E)}}let g=i.catchall,y="none";if(g){let k=g._zod.def.type;if(k==="never"){let A=c.map(Z=>`k !== ${be(Z)}`).join(" && ")||"true";e.write(`for (const k in ${o}) {`),e.indented(Z=>{Z.write(`if (${A}) return INVALID;`)}),e.write("}")}else(k==="unknown"||k==="any")&&!g._zod.def.checks?.length?y="passthrough":y="schema"}let _=T(t),I=l.some(k=>Sh(f[k])||Sl(f[k]));if(!n){if(y==="schema"){let k=c.length>0?O(t,new Set(c)):null;e.write(`for (const k in ${o}) {`),e.indented(A=>{A.write('if (k === "__proto__") continue;'),k&&A.write(`if (${k}.has(k)) continue;`);let Z=T(t);A.write(`const ${Z} = ${o}[k];`),he(A,t,g,Z,!1)}),e.write("}")}return null}if(I){e.write(`const ${_} = {};`);for(let k of l){let A=d(k),Z=m.get(k);Sl(f[k])?e.write(`if (${A} in ${o}) ${_}[${A}] = ${Z};`):Sh(f[k])?e.write(`if (${Z} !== undefined || ${A} in ${o}) ${_}[${A}] = ${Z};`):e.write(`${_}[${A}] = ${Z};`)}}else{let k=l.map(A=>`${p(A)}: ${m.get(A)}`).join(", ");e.write(`const ${_} = { ${k} };`)}if(y!=="none"){let k=c.length>0?O(t,new Set(c)):null;e.write(`for (const k in ${o}) {`),e.indented(A=>{if(A.write('if (k === "__proto__") continue;'),k&&A.write(`if (${k}.has(k)) continue;`),y==="passthrough")A.write(`${_}[k] = ${o}[k];`);else{let Z=T(t);A.write(`const ${Z} = ${o}[k];`);let C=he(A,t,g,Z);A.write(`${_}[k] = ${C};`)}}),e.write("}")}return _}function oS(e,t,r,o,n=!0){let i=r._zod.def;if(aS(r))return te(e,t,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let c=T(t),u=T(t);return e.write(`let ${c};`),e.write(`if (${o} === undefined) {`),e.indented(l=>{l.write(`const ${u} = (() => {`),l.indented(d=>{let p=te(d,t,i.innerType,o);d.write(`return ${p};`)}),l.write("})();"),l.write(`if (${u} !== INVALID) ${c} = ${u};`)}),e.write("} else {"),e.indented(l=>{let d=te(l,t,i.innerType,o);l.write(`${c} = ${d};`)}),e.write("}"),c}let a=n?T(t):null;return a&&e.write(`let ${a};`),e.write(`if (${o} !== undefined) {`),e.indented(c=>{let u=te(c,t,i.innerType,o,n);a&&u!==null&&c.write(`${a} = ${u};`)}),e.write("}"),a}function aS(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function sS(e){return e._zod.optin===void 0&&Jt(e)}function Jt(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?Jt(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?Jt(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Jt):!0;case"intersection":return!t.left||!t.right?!0:Jt(t.left)&&Jt(t.right);case"pipe":return t.in?Jt(t.in):!0;default:return!0}}function Sl(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function Sh(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&Cn(e)}function Cn(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?Cn(t.innerType):!0;case"union":return t.options?t.options.some(Cn):!0;case"intersection":return!t.left||!t.right||Cn(t.left)||Cn(t.right);case"pipe":return t.out?Cn(t.out):!0;default:return!0}}function cS(e,t,r,o,n=!0){let i=r._zod.def,a=n?T(t):null;return a&&e.write(`let ${a} = null;`),e.write(`if (${o} !== null) {`),e.indented(c=>{let u=te(c,t,i.innerType,o,n);a&&u!==null&&c.write(`${a} = ${u};`)}),e.write("}"),a}function Pl(e,t,r){for(let[o,n]of wn(t._zod.def.checks))e.write(`if (${r} > ${_t(o,n._zod.def.check)}) return INVALID;`)}function uS(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (!Array.isArray(${o})) return INVALID;`),Pl(e,r,`${o}.length`);let a=n?T(t):null,c=T(t),u=T(t);return a&&e.write(`const ${a} = new Array(${o}.length);`),e.write(`for (let ${c} = 0; ${c} < ${o}.length; ${c}++) {`),e.indented(l=>{l.write(`const ${u} = ${o}[${c}];`);let d=he(l,t,i.element,u,n);a&&d!==null&&l.write(`${a}[${c}] = ${d};`)}),e.write("}"),a}function lS(e,t,r,o){let i=r._zod.def.values;if(i.length!==1){let c=O(t,new Set(i));return e.write(`if (!${c}.has(${o})) return INVALID;`),o}let a=i[0];if(typeof a=="number"&&Number.isNaN(a)){let c=O(t,new Set(i));return e.write(`if (!${c}.has(${o})) return INVALID;`),o}if(typeof a=="string")e.write(`if (${o} !== ${be(a)}) return INVALID;`);else if(typeof a=="number"||typeof a=="boolean")e.write(`if (${o} !== ${a}) return INVALID;`);else if(a===null)e.write(`if (${o} !== null) return INVALID;`);else if(a===void 0)e.write(`if (${o} !== undefined) return INVALID;`);else if(typeof a=="bigint")e.write(`if (${o} !== ${a}n) return INVALID;`);else throw new F(`literal type ${typeof a}`);return o}function dS(e,t,r,o){let n=r._zod.values;if(!n)throw new F("enum schema without enumerated values");let i=O(t,n);return e.write(`if (!${i}.has(${o})) return INVALID;`),o}function Ih(e,t,r,o){let n=r._zod.def;return te(e,t,n.innerType,o)}function pS(e,t,r,o){let n=r._zod.def,a=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!a)return te(e,t,n.innerType,o);let u=O(t,a),l=T(t);return e.write(`let ${l} = ${o};`),e.write(`if (${o} === undefined) ${l} = ${u}();`),te(e,t,n.innerType,l)}let c=T(t);if(a){let u=O(t,a),l=O(t,yr);e.write(`let ${c};`),e.write(`if (${o} === undefined) {`),e.indented(d=>{d.write(`${c} = ${l}(${u}());`)}),e.write("} else {"),e.indented(d=>{let p=te(d,t,n.innerType,o);d.write(`${c} = ${p} === undefined ? ${l}(${u}()) : ${p};`)}),e.write("}")}else e.write(`let ${c};`),e.write(`if (${o} !== undefined) {`),e.indented(u=>{let l=te(u,t,n.innerType,o);u.write(`${c} = ${l};`)}),e.write("}");return c}function mS(e,t,r,o){let n=r._zod.def,i=te(e,t,n.innerType,o),a=T(t);return e.write(`const ${a} = ${i};`),e.write(`if (${a} === undefined) return INVALID;`),a}function fS(e,t,r,o){let n=r._zod.def,i=n.items,a=n.rest;e.write(`if (!Array.isArray(${o})) return INVALID;`);let c=zh(i,"optin"),u=zh(i,"optout");a?e.write(`if (${o}.length < ${c}) return INVALID;`):e.write(`if (${o}.length < ${c} || ${o}.length > ${i.length}) return INVALID;`);let l=T(t);e.write(`const ${l} = [];`);for(let d=0;d<i.length;d++){let p=i[d];if(d>=u)e.write(`if (${l}.length === ${d}) {`),e.indented(f=>{f.write(`if (${d} < ${o}.length) {`),f.indented(m=>{let g=T(t);m.write(`const ${g} = ${o}[${d}];`);let y=he(m,t,p,g);m.write(`${l}[${d}] = ${y};`)}),f.write("} else {"),f.indented(m=>{if(Sl(p)){m.write(`${l}.length = ${d};`);return}let g=T(t),y=T(t);m.write(`const ${g} = undefined;`),m.write(`const ${y} = (() => {`),m.indented(_=>{let I=he(_,t,p,g);_.write(`return ${I};`)}),m.write("})();"),m.write(`if (${y} === INVALID || ${y} === undefined) ${l}.length = ${d};`),m.write(`else ${l}[${d}] = ${y};`)}),f.write("}")}),e.write("}");else{let f=T(t);e.write(`const ${f} = ${o}[${d}];`);let m=he(e,t,p,f);e.write(`${l}[${d}] = ${m};`)}}if(a){let d=T(t),p=T(t);e.write(`for (let ${d} = ${i.length}; ${d} < ${o}.length; ${d}++) {`),e.indented(f=>{f.write(`const ${p} = ${o}[${d}];`);let m=he(f,t,a,p);f.write(`${l}[${d}] = ${m};`)}),e.write("}")}return l}function zh(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function gS(e,t,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return hS(e,t,n,o);if(n.inclusive===!1)throw new F("exclusive unions (z.xor)");if(i.length===0)return e.write("return INVALID;"),o;if(i.length===1)return te(e,t,i[0],o);if(i.every(u=>u._zod.def.type==="literal"&&!u._zod.def.checks?.length)){let u=new Set(i.flatMap(d=>d._zod.def.values)),l=O(t,u);return e.write(`if (!${l}.has(${o})) return INVALID;`),o}let c=T(t);e.write(`let ${c};`);for(let u=0;u<i.length;u++){let l=i[u];u===0?e.write(`${c} = (() => {`):e.write(`if (${c} === INVALID) ${c} = (() => {`),e.indented(d=>{let p=te(d,t,l,o);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${c} === INVALID) return INVALID;`),c}function hS(e,t,r,o){if(r.unionFallback)throw new F("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),o;let n=T(t),i=T(t);e.write(`const ${n} = ${o}?.[${be(r.discriminator)}];`),e.write(`let ${i};`);let a=!0,c=new Set;for(let u of r.options){let l=u._zod.propValues?.[r.discriminator];if(!l||l.size===0)throw new F("discriminated union option without static discriminator values");for(let f of l){if(c.has(f))throw new F(`duplicate discriminator value ${String(f)}`);c.add(f)}let d=Array.from(l,f=>vS(t,n,f)),p=a?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(f=>{let m=te(f,t,u,o);f.write(`${i} = ${m};`)}),e.write("}"),a=!1}return e.write("else { return INVALID; }"),i}function vS(e,t,r){if(typeof r=="string")return`${t} === ${be(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let o=O(e,r);return`${t} === ${o}`}throw new F(`literal discriminator value ${String(r)}`)}function yS(e,t,r,o){let n=r._zod.def;t.definite=!1;let i=he(e,t,n.left,o),a=he(e,t,n.right,o),c=O(t,An),u=T(t);return e.write(`const ${u} = ${c}(${i}, ${a});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function bS(e,t,r,o){let n=r._zod.def,i=O(t,Le);e.write(`if (!${i}(${o})) return INVALID;`);let a=T(t),c=T(t),u=T(t);e.write(`const ${a} = {};`);let l=n,d=l.partial?void 0:n.keyType._zod.values;if(d){let m=[];for(let y of d){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new F(`record key value ${String(y)}`);let _=typeof y=="number"?y.toString():y;if(_==="__proto__")throw new F('record key "__proto__"');m.push(_);let I=O(t,y),k=te(e,t,n.keyType,I),A=T(t);e.write(`const ${A} = ${o}[${$S(t,_)}];`);let Z=he(e,t,n.valueType,A);e.write(`${a}[${k}] = ${Z};`)}let g=O(t,new Set(m));return e.write(`for (const ${c} in ${o}) {`),e.indented(y=>{y.write(`if (${g}.has(${c})) continue;`),l.mode==="loose"?y.write(`if (${c} !== "__proto__") ${a}[${c}] = ${o}[${c}];`):y.write("return INVALID;")}),e.write("}"),a}let p=n.keyType._zod.def;if(!(p.type==="string"&&p.format===void 0&&!p.coerce&&(p.checks?.length??0)===0)){let m=n.mode==="loose",g=Ro(n.keyType);g.definite===!1&&(t.definite=!1);let y=O(t,g),_=O(t,pt),I=T(t);return Ph(e,t,o,c,k=>{k.write(`let ${I} = ${y}(${c});`),k.write(`if (${I} === INVALID && typeof ${c} === "string" && ${_}.test(${c})) ${I} = ${y}(Number(${c}));`),m?k.write(`if (${I} === INVALID) { ${a}[${c}] = ${o}[${c}]; continue; }`):k.write(`if (${I} === INVALID) return INVALID;`),k.write(`if (${I} === "__proto__") continue;`);let A=T(t);k.write(`const ${A} = ${o}[${c}];`);let Z=he(k,t,n.valueType,A);k.write(`${a}[${I}] = ${Z};`)}),a}return Ph(e,t,o,c,m=>{m.write(`const ${u} = ${o}[${c}];`);let g=he(m,t,n.valueType,u);m.write(`${a}[${c}] = ${g};`)},"return INVALID;"),a}function Ph(e,t,r,o,n,i){let a=O(t,Object.prototype.propertyIsEnumerable),c=T(t),u=T(t),l=T(t);e.write(`const ${c} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${u} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${l} = 0; ${l} < ${u}.length; ${l}++) {`),e.indented(d=>{d.write(`const ${o} = ${u}[${l}];`),d.write(`if (${o} === "__proto__" || !${a}.call(${r}, ${o})) continue;`),n(d)}),e.write("}"),e.write(`for (let ${l} = 0; ${l} < ${c}.length; ${l}++) {`),e.indented(d=>{d.write(`const ${o} = ${c}[${l}];`),d.write(`if (!${a}.call(${r}, ${o})) continue;`),i?d.write(i):n(d)}),e.write("}")}function $S(e,t){return typeof t=="string"?be(t):O(e,t)}function xS(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Map)) return INVALID;`),Pl(e,r,`${o}.size`);let i=T(t),a=T(t),c=T(t);return e.write(`const ${i} = new Map();`),e.write(`for (const [${a}, ${c}] of ${o}) {`),e.indented(u=>{let l=te(u,t,n.keyType,a),d=te(u,t,n.valueType,c);u.write(`${i}.set(${l}, ${d});`)}),e.write("}"),i}function wS(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Set)) return INVALID;`),Pl(e,r,`${o}.size`);let i=T(t),a=T(t);return e.write(`const ${i} = new Set();`),e.write(`for (const ${a} of ${o}) {`),e.indented(c=>{let u=te(c,t,n.valueType,a);c.write(`${i}.add(${u});`)}),e.write("}"),i}function _S(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function kS(e,t,r,o){e.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=O(t,n);e.write(`${i}.lastIndex = 0;`),e.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function SS(e,t,r,o){let n=r._zod.def,i=Bt(t,n.getter),a=O(t,{parser:null});e.write(`if (!${a}.parser) {`),e.indented(u=>{u.write(`const inner = ${i}();`),u.write(`${a}.parser = function(input) {`),u.indented(l=>{l.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),l.write("return result.issues.length === 0 ? result.value : INVALID;")}),u.write("};")}),e.write("}");let c=T(t);return e.write(`const ${c} = ${a}.parser(${o});`),e.write(`if (${c} === INVALID) return INVALID;`),c}function IS(e,t,r,o){let n=r._zod.def,i=te(e,t,n.in,o);if(n.transform){if(Wt(n.transform))throw new qe("z.compile: async transforms in pipes are not supported");let a=n.transform,u=Bt(t,d=>{let p={value:d,issues:[],addIssue:zl},f=a(d,p);return f instanceof Promise?xe:p.issues.length===0?f:xe}),l=T(t);return e.write(`const ${l} = ${u}(${i});`),e.write(`if (${l} === INVALID) return INVALID;`),te(e,t,n.out,l)}else return te(e,t,n.out,i)}function Wt(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function zS(e,t,r,o){let n=r._zod.def;if(n.fn){if(Wt(n.fn))throw new qe("z.compile: async custom predicates are not supported");let i=Bt(t,n.fn),a=O(t,kl),c=T(t);e.write(`const ${c} = ${i}(${o});`),e.write(`if (${c} instanceof Promise) ${a}();`),e.write(`if (!${c}) return INVALID;`)}else throw new F("custom schema without a predicate function");return o}function PS(e,t,r){let o=e._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return xe;let n=o;return n.issues.length===0?n.value:t()}function AS(e,t,r,o){let n=r._zod.def;if(!n.catchValue[Li])throw new F("catch with a callback (only a constant catch value compiles)",!1);let i=T(t);e.write(`let ${i} = (() => {`),e.indented(l=>{let d=he(l,t,n.innerType,o);l.write(`return ${d};`)}),e.write("})();");let a=O(t,n.innerType),c=Bt(t,n.catchValue),u=O(t,PS);return e.write(`if (${i} === INVALID) {`),e.indented(l=>{l.write(`${i} = ${u}(${a}, ${c}, ${o});`),l.write(`if (${i} === INVALID) return INVALID;`)}),e.write("}"),i}function jS(e,t,r,o){let n=r._zod.def;if(n.transform){if(Wt(n.transform))throw new qe("z.compile: async transforms are not supported");let i=n.transform,c=Bt(t,l=>{let d={value:l,issues:[],addIssue:zl},p=i(l,d);return p instanceof Promise?xe:d.issues.length===0?p:xe}),u=T(t);return e.write(`const ${u} = ${c}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return o}function Eo(e){return e.checks&&(e.checks=[...e.checks]),e}function Al(e,t){return new e(Eo({type:"string",...S(t)}))}function jl(e,t){return new e(Eo({type:"string",coerce:!0,...S(t)}))}function Uo(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...S(t)})}function Mo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...S(t)})}function Lo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...S(t)})}function Zo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...S(t)})}function Fo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...S(t)})}function Vo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...S(t)})}function Gr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...S(t)})}function Ko(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...S(t)})}function Jo(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...S(t)})}function Bo(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...S(t)})}function Wo(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...S(t)})}function Go(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...S(t)})}function qo(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...S(t)})}function Ho(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...S(t)})}function Xo(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...S(t)})}function Yo(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...S(t)})}function Tl(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...S(t)})}function Qo(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...S(t)})}function ea(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...S(t)})}function ta(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...S(t)})}function na(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...S(t)})}function ra(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...S(t)})}function Cl(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...S(t)})}function Ol(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...S(t)})}function ia(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...S(t)})}var Nl={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function qr(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...S(t)})}function Hr(e,t){return new e({type:"string",format:"date",check:"string_format",...S(t)})}function Xr(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...S(t)})}function Yr(e,t){return new e({type:"string",format:"duration",check:"string_format",...S(t)})}function Dl(e,t){return new e(Eo({type:"number",checks:[],...S(t)}))}function Rl(e,t){return new e(Eo({type:"number",coerce:!0,checks:[],...S(t)}))}function El(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...S(t)})}function Ul(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...S(t)})}function Ml(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...S(t)})}function Ll(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...S(t)})}function Zl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...S(t)})}function Fl(e,t){return new e({type:"boolean",...S(t)})}function Vl(e,t){return new e({type:"boolean",coerce:!0,...S(t)})}function Kl(e,t){return new e({type:"bigint",...S(t)})}function Jl(e,t){return new e({type:"bigint",coerce:!0,...S(t)})}function Bl(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...S(t)})}function Wl(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...S(t)})}function Gl(e,t){return new e({type:"symbol",...S(t)})}function ql(e,t){return new e({type:"undefined",...S(t)})}function Hl(e,t){return new e({type:"null",...S(t)})}function Xl(e){return new e({type:"any"})}function Yl(e){return new e({type:"unknown"})}function Ql(e,t){return new e({type:"never",...S(t)})}function ed(e,t){return new e({type:"void",...S(t)})}function td(e,t){return new e({type:"date",...S(t)})}function nd(e,t){return new e({type:"date",coerce:!0,...S(t)})}function rd(e,t){return new e({type:"nan",...S(t)})}function tt(e,t){return new no({check:"less_than",...S(t),value:e,inclusive:!1})}function Re(e,t){return new no({check:"less_than",...S(t),value:e,inclusive:!0})}function nt(e,t){return new ro({check:"greater_than",...S(t),value:e,inclusive:!1})}function Ee(e,t){return new ro({check:"greater_than",...S(t),value:e,inclusive:!0})}function oa(e){return nt(0,e)}function aa(e){return tt(0,e)}function sa(e){return Re(0,e)}function ca(e){return Ee(0,e)}function kt(e,t){return new Mc({check:"multiple_of",...S(t),value:e})}function St(e,t){return new Fc({check:"max_size",...S(t),maximum:e})}function rt(e,t){return new Vc({check:"min_size",...S(t),minimum:e})}function Gt(e,t){return new Kc({check:"size_equals",...S(t),size:e})}function qt(e,t){return new Jc({check:"max_length",...S(t),maximum:e})}function mt(e,t){return new Bc({check:"min_length",...S(t),minimum:e})}function Ht(e,t){return new Wc({check:"length_equals",...S(t),length:e})}function On(e,t){return new Gc({check:"string_format",format:"regex",...S(t),pattern:e})}function Nn(e){return new qc({check:"string_format",format:"lowercase",...S(e)})}function Dn(e){return new Hc({check:"string_format",format:"uppercase",...S(e)})}function Rn(e,t){return new Xc({check:"string_format",format:"includes",...S(t),includes:e})}function En(e,t){return new Yc({check:"string_format",format:"starts_with",...S(t),prefix:e})}function Un(e,t){return new Qc({check:"string_format",format:"ends_with",...S(t),suffix:e})}function ua(e,t,r){return new eu({check:"property",property:e,schema:t,...S(r)})}function Mn(e,t){return new tu({check:"properties",shape:e,...S(t)})}function Ln(e,t){return new nu({check:"mime_type",mime:e,...S(t)})}function He(e){return new ru({check:"overwrite",tx:e})}function Zn(e){return He(t=>t.normalize(e))}function Fn(){return He(e=>e.trim())}function Vn(){return He(e=>e.toLowerCase())}function Kn(){return He(e=>e.toUpperCase())}function Jn(){return He(e=>Zs(e))}function id(e,t,r){return new e({type:"array",element:t,...S(r)})}function TS(e,t,r){return new e({type:"union",options:t,...S(r)})}function CS(e,t,r){return new e({type:"union",options:t,inclusive:!1,...S(r)})}function OS(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...S(o)})}function NS(e,t,r){return new e({type:"intersection",left:t,right:r})}function DS(e,t,r,o){let n=r instanceof D,i=n?o:r,a=n?r:null;return new e({type:"tuple",items:t,rest:a,...S(i)})}function RS(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...S(o)})}function ES(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...S(o)})}function US(e,t,r){return new e({type:"set",valueType:t,...S(r)})}function MS(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...S(r)})}function LS(e,t,r){return new e({type:"enum",entries:t,...S(r)})}function ZS(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...S(r)})}function od(e,t){return new e({type:"file",...S(t)})}function FS(e,t){return new e({type:"transform",transform:t})}function VS(e,t){return new e({type:"optional",innerType:t})}function KS(e,t){return new e({type:"nullable",innerType:t})}function JS(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():yr(r)}})}function BS(e,t,r){return new e({type:"nonoptional",innerType:t,...S(r)})}function WS(e,t){return new e({type:"success",innerType:t})}function GS(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:Ws(r)})}function qS(e,t,r){return new e({type:"pipe",in:t,out:r})}function HS(e,t){return new e({type:"readonly",innerType:t})}function XS(e,t,r){return new e({type:"template_literal",parts:t,...S(r)})}function YS(e,t){return new e({type:"lazy",getter:t})}function QS(e,t){return new e({type:"promise",innerType:t})}function ad(e,t,r){let o=S(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function sd(e,t,r){return new e({type:"custom",check:"custom",fn:t,...S(r)})}function cd(e,t){let r=Ch(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(_n(n,o.value,r._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(_n(i))}},e(o.value,o)),t);return r}function Ch(e,t){let r=new H({check:"custom",...S(t)});return r._zod.check=e,r}function ud(e){let t=new H({check:"describe"});return t._zod.onattach=[r=>{let o=ge.get(r)??{};ge.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function ld(e){let t=new H({check:"meta"});return t._zod.onattach=[r=>{let o=ge.get(r)??{};ge.add(r,{...o,...e})}],t._zod.check=()=>{},t}function dd(e,t){let r=S(t),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(m=>typeof m=="string"?m.toLowerCase():m),n=n.map(m=>typeof m=="string"?m.toLowerCase():m));let i=new Set(o),a=new Set(n),c=e.Codec??Zr,u=e.Boolean??Mr,l=e.String??Kt,d=new l({type:"string",error:r.error}),p=new u({type:"boolean",error:r.error}),f=new c({type:"pipe",in:d,out:p,transform:((m,g)=>{let y=m;return r.case!=="sensitive"&&(y=y.toLowerCase()),i.has(y)?!0:a.has(y)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...a],input:g.value,inst:f,continue:!1}),{})}),reverseTransform:((m,g)=>m===!0?o[0]||"true":n[0]||"false"),error:r.error});return f._zod.bag.truthy=o,f._zod.bag.falsy=n,f._zod.bag.case=r.case??"insensitive",f}function Xt(e,t,r,o={}){let n=S(o),i={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:c=>r.test(c),...n};return r instanceof RegExp&&(i.pattern=r),new e(i)}function Qr(e,...t){for(let r of t)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&fe(e,o,r[o]);return e}function It(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ge,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function ue(e,t,r,o,n){let i=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:o.path,message:n}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function W(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,d);else{let f=a.schema,m=t.processors[n.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);m(e,t,f,d)}let p=e._zod.parent;p&&(a.ref||(a.ref=p),W(p,t,d),t.seen.get(p).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&Qr(a.schema,u),t.io==="input"&&we(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&"_prefault"in a.schema&&((o=a.schema).default??(o.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Oh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function zt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let o=new Map;for(let a of e.seen.entries()){let c=e.metadataRegistry.get(a[0])?.id;if(c){let u=o.get(c);if(u&&u!==a[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(c,a[0])}}let n=a=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(a[0])?.id,f=e.external.uri??(g=>g);if(p)return{ref:f(p)};let m=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=m,{defId:m,ref:`${f("__shared")}#/${c}/${Oh(m)}`}}let u="#",l=`${u}/${c}/`;if(a[1]===r&&!a[1].schema.id)return{ref:u};let d=a[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:l+Oh(d)}},i=a=>{if(a[1].schema.$ref)return;let c=a[1],{ref:u,defId:l}=n(a);c.def={...c.schema},l&&(c.defId=l);let d=c.schema;for(let p in d)delete d[p];d.$ref=u};if(e.cycles==="throw")for(let a of e.seen.entries()){let c=a[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
61
|
+
}`,f;try{f=new d(...a,p)(...c)}catch(m){throw new F(`this schema (generated code failed to evaluate: ${m.message})`)}return t?.debug&&(f.code=l),f.definite=o.definite,f}function N(e,t){for(let[o,n]of e.constants)if(n===t)return o;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function Bt(e,t){return e.definite=!1,N(e,t)}function T(e){return`v${e.varCounter++}`}function Nk(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return xe;let o=r;return o.issues.length===0?o.value:xe}function he(e,t,r,o,n=!0){let i=e.content.length,a=t.constants.size,c=t.constantCounter,u=t.varCounter;try{return te(e,t,r,o,n)}catch(l){if(!(l instanceof F)||!l.islandable)throw l;if(e.content.length=i,t.constants.size>a){let d=Array.from(t.constants.keys()).slice(a);for(let p of d)t.constants.delete(p)}return t.constantCounter=c,t.varCounter=u,Dk(e,t,r,o)}}function Dk(e,t,r,o){t.definite=!1;let n=N(t,r),i=N(t,Nk),a=T(t);return e.write(`const ${a} = ${i}(${n}, ${o});`),e.write(`if (${a} === INVALID) return INVALID;`),a}var Rk=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Ek(e,t,r,o){let n=r._zod.def.checks;if(!n||n.length===0)return o;let i=o;for(let a of n){let c=a._zod.def;if(c.when&&!Rk.has(c.check))throw new F('check with a custom "when" condition');switch(c.check){case"greater_than":Uk(e,t,c,i);break;case"less_than":Mk(e,t,c,i);break;case"multiple_of":Lk(e,t,c,i);break;case"number_format":jh(e,c,i);break;case"min_length":{let u=_t(c.minimum,"min_length"),l=_l(e,t,i,`${i}.length >= ${u} && ${i}.length < ${c.minimum*2}`);e.write(`if (${l} < ${u}) return INVALID;`);break}case"max_length":{let u=_t(c.maximum,"max_length"),l=_l(e,t,i,`${i}.length > ${u}`);e.write(`if (${l} > ${u}) return INVALID;`);break}case"length_equals":{let u=_t(c.length,"length_equals"),l=_l(e,t,i,`${i}.length >= ${u} && ${i}.length <= ${c.length*2}`);e.write(`if (${l} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${i}.size < ${_t(c.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${i}.size > ${_t(c.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${i}.size !== ${_t(c.size,"size_equals")}) return INVALID;`);break;case"string_format":i=Th(e,t,c,i);break;case"custom":i=Bk(e,t,a,i);break;case"bigint_format":Zk(e,c,i);break;case"mime_type":Fk(e,t,c,i);break;case"property":Kk(e,t,c,i);break;case"properties":Vk(e,t,c,i);break;case"overwrite":{let u=T(t);Jk(e,t,a,i,u),i=u;break}default:throw new F(`check type ${c.check}`)}}return i}function _l(e,t,r,o){let n=N(t,Zt),i=T(t);return e.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function _t(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new F(`${t} bound of type ${typeof e}`);return`${e}`}function Ah(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new F("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new F("comparison check with Invalid Date bound");return N(e,t)}throw new F(`comparison check bound of type ${typeof t}`)}function Uk(e,t,r,o){let n=r.inclusive?"<":"<=";e.write(`if (${o} ${n} ${Ah(t,r.value)}) return INVALID;`)}function Mk(e,t,r,o){let n=r.inclusive?">":">=";e.write(`if (${o} ${n} ${Ah(t,r.value)}) return INVALID;`)}function Lk(e,t,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new F("multiple_of check with a zero divisor");e.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=N(t,vr);e.write(`if (${n}(${o}, ${_t(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function jh(e,t,r){let o=t.format;switch(o){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new F(`number format ${o}`)}}function Zk(e,t,r){let o=t.format;if(o)switch(o){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new F(`bigint format ${o}`)}}function Fk(e,t,r,o){let n=r.mime;if(n&&n.length>0){let i=N(t,new Set(n));e.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function Vk(e,t,r,o){if(r.when)throw new F('check with a custom "when" condition');e.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let a=typeof i=="symbol"?N(t,i):be(i),c=T(t);e.write(`const ${c} = ${o}[${a}];`),he(e,t,n[i],c,!1)}}function Kk(e,t,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;te(e,t,r.schema,n)}function Jk(e,t,r,o,n){let i=r._zod.def.tx;if(!i)throw new F("overwrite check without a transform function");if(Wt(i))throw new qe("z.compile: async overwrite transforms are not supported");let a=N(t,i);e.write(`const ${n} = ${a}(${o});`)}function kl(){throw new Pe}function zl(e){this.issues.push(e)}function Bk(e,t,r,o){let n=r._zod.def;if(n.fn){if(Wt(n.fn))throw new qe("z.compile: async .refine() predicates are not supported");let i=Bt(t,n.fn),a=N(t,kl),c=T(t);return e.write(`const ${c} = ${i}(${o});`),e.write(`if (${c} instanceof Promise) ${a}();`),e.write(`if (!${c}) return INVALID;`),o}if(r._zod.check){if(Wt(r._zod.check))throw new qe("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,c=Bt(t,l=>{let d={value:l,issues:[],addIssue:zl};return i(d)instanceof Promise&&kl(),d.issues.length===0?d.value:xe}),u=T(t);return e.write(`const ${u} = ${c}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new F("custom check without a predicate or check function")}var Wk=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function Th(e,t,r,o,n=!0){let i=r.format;if(i==="base64"){let l=N(t,Er);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="base64url"){let l=N(t,go);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="jwt"){let l=N(t,yo),d=N(t,r.alg??null);return e.write(`if (!${l}(${o}, ${d})) return INVALID;`),o}if(i==="ipv6"){let l=N(t,Rr);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="cidrv6"){let l=N(t,mo);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="credit_card"){let l=N(t,ho);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="iban"){let l=N(t,vo);return e.write(`if (!${l}(${o})) return INVALID;`),o}let a=r;if(i==="url"||i==="httpurl"||a.normalize||a.hostname!==void 0||a.protocol!==void 0){let l=N(t,uo),d=N(t,r),p=T(t),f=T(t);if(e.write(`const ${p} = ${o}.trim();`),e.write(`const ${f} = ${l}(${p}, ${d});`),e.write(`if (typeof ${f} === "number") return INVALID;`),a.hostname!==void 0){let y=N(t,lo);e.write(`if (!${y}(${f}, ${d}.hostname)) return INVALID;`)}if(a.protocol!==void 0){let y=N(t,po);e.write(`if (!${y}(${f}, ${d}.protocol)) return INVALID;`)}if(!n)return null;let m=T(t),g=a.normalize?`${f}.href`:`${N(t,Dr)}(${p})`;return e.write(`const ${m} = ${g};`),m}let c=r.fn;if(c){if(Wt(c))throw new F(`async string format ${i}`);let l=N(t,c);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(Wk.has(i)&&r.pattern){let l=N(t,r.pattern);return e.write(`${l}.lastIndex = 0;`),e.write(`if (!${l}.test(${o})) return INVALID;`),o}let u=r.format;switch(u){case"regex":throw new F("regex format without a pattern");case"lowercase":e.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${o}.includes(${be(r.includes)})) return INVALID;`);break;case"starts_with":{let l=r.prefix;e.write(`if (${o}.slice(0, ${l.length}) !== ${be(l)}) return INVALID;`);break}case"ends_with":{let l=r.suffix;e.write(`if (${o}.slice(-${l.length}) !== ${be(l)}) return INVALID;`);break}default:throw new F(`string format ${u}`)}return o}function te(e,t,r,o,n=!0){let i=r._zod.def,a=i.type;if(i.coerce)throw new F(`coercion (z.coerce.${a}())`);let c=n||!!i.checks?.length,u;switch(a){case"string":u=Gk(e,t,r,o,c);break;case"number":u=qk(e,r,o);break;case"boolean":u=Hk(e,o);break;case"bigint":u=Xk(e,r,o);break;case"symbol":u=Yk(e,o);break;case"undefined":u=Qk(e,o);break;case"null":u=eS(e,o);break;case"any":case"unknown":u=o;break;case"never":e.write("return INVALID;"),u=o;break;case"void":u=tS(e,o);break;case"nan":u=nS(e,o);break;case"date":u=rS(e,o);break;case"object":u=iS(e,t,r,o,c);break;case"optional":u=oS(e,t,r,o,c);break;case"nullable":u=cS(e,t,r,o,c);break;case"array":u=uS(e,t,r,o,c);break;case"literal":u=lS(e,t,r,o);break;case"enum":u=dS(e,t,r,o);break;case"readonly":{let l=Ih(e,t,r,o),d=T(t);e.write(`const ${d} = Object.freeze(${l});`),u=d;break}case"success":Ih(e,t,r,o),u="true";break;case"default":case"prefault":u=pS(e,t,r,o);break;case"nonoptional":u=mS(e,t,r,o);break;case"tuple":u=fS(e,t,r,o);break;case"union":u=gS(e,t,r,o);break;case"intersection":u=yS(e,t,r,o);break;case"record":u=bS(e,t,r,o);break;case"map":u=xS(e,t,r,o);break;case"set":u=wS(e,t,r,o);break;case"file":u=_S(e,o);break;case"template_literal":u=kS(e,t,r,o);break;case"lazy":u=SS(e,t,r,o);break;case"pipe":u=IS(e,t,r,o);break;case"custom":u=zS(e,t,r,o);break;case"transform":u=jS(e,t,r,o);break;case"catch":u=AS(e,t,r,o);break;default:throw new F(`schema type ${a}`)}return u===null?null:Ek(e,t,r,u)}function Gk(e,t,r,o,n=!0){e.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:Th(e,t,i,o,n)}function qk(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=t._zod.def;return o.check==="number_format"&&o.format&&jh(e,{format:o.format},r),r}function Hk(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function Xk(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=t._zod.def;if(o.format)switch(o.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function Yk(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function Qk(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function eS(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function tS(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function nS(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function rS(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function iS(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let a=i.shape,c=Object.keys(a),u=Object.getOwnPropertySymbols(a),l=u.length?[...c,...u]:c,d=k=>typeof k=="symbol"?N(t,k):be(k),p=k=>typeof k=="symbol"?`[${d(k)}]`:be(k),f=a;if(c.includes("__proto__"))throw new F('object shape key "__proto__"');let m=new Map;for(let k of l){let A=f[k],Z=d(k),C=T(t);if(e.write(`const ${C} = ${o}[${Z}];`),A._zod.optin!==void 0){let E=T(t);e.write(`let ${E} = (() => {`),e.indented(P=>{let Q=he(P,t,A,C);P.write(`return ${Q};`)}),e.write("})();"),A._zod.optout==="optional"?(e.write(`if (${E} === INVALID) {`),e.indented(P=>{P.write(`if (${Z} in ${o}) return INVALID;`),P.write(`${E} = undefined;`)}),e.write("}")):e.write(`if (${E} === INVALID) return INVALID;`),m.set(k,E)}else{sS(A)&&e.write(`if (!(${Z} in ${o})) return INVALID;`);let E=he(e,t,A,C,n);E!==null&&m.set(k,E)}}let g=i.catchall,y="none";if(g){let k=g._zod.def.type;if(k==="never"){let A=c.map(Z=>`k !== ${be(Z)}`).join(" && ")||"true";e.write(`for (const k in ${o}) {`),e.indented(Z=>{Z.write(`if (${A}) return INVALID;`)}),e.write("}")}else(k==="unknown"||k==="any")&&!g._zod.def.checks?.length?y="passthrough":y="schema"}let _=T(t),I=l.some(k=>Sh(f[k])||Sl(f[k]));if(!n){if(y==="schema"){let k=c.length>0?N(t,new Set(c)):null;e.write(`for (const k in ${o}) {`),e.indented(A=>{A.write('if (k === "__proto__") continue;'),k&&A.write(`if (${k}.has(k)) continue;`);let Z=T(t);A.write(`const ${Z} = ${o}[k];`),he(A,t,g,Z,!1)}),e.write("}")}return null}if(I){e.write(`const ${_} = {};`);for(let k of l){let A=d(k),Z=m.get(k);Sl(f[k])?e.write(`if (${A} in ${o}) ${_}[${A}] = ${Z};`):Sh(f[k])?e.write(`if (${Z} !== undefined || ${A} in ${o}) ${_}[${A}] = ${Z};`):e.write(`${_}[${A}] = ${Z};`)}}else{let k=l.map(A=>`${p(A)}: ${m.get(A)}`).join(", ");e.write(`const ${_} = { ${k} };`)}if(y!=="none"){let k=c.length>0?N(t,new Set(c)):null;e.write(`for (const k in ${o}) {`),e.indented(A=>{if(A.write('if (k === "__proto__") continue;'),k&&A.write(`if (${k}.has(k)) continue;`),y==="passthrough")A.write(`${_}[k] = ${o}[k];`);else{let Z=T(t);A.write(`const ${Z} = ${o}[k];`);let C=he(A,t,g,Z);A.write(`${_}[k] = ${C};`)}}),e.write("}")}return _}function oS(e,t,r,o,n=!0){let i=r._zod.def;if(aS(r))return te(e,t,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let c=T(t),u=T(t);return e.write(`let ${c};`),e.write(`if (${o} === undefined) {`),e.indented(l=>{l.write(`const ${u} = (() => {`),l.indented(d=>{let p=te(d,t,i.innerType,o);d.write(`return ${p};`)}),l.write("})();"),l.write(`if (${u} !== INVALID) ${c} = ${u};`)}),e.write("} else {"),e.indented(l=>{let d=te(l,t,i.innerType,o);l.write(`${c} = ${d};`)}),e.write("}"),c}let a=n?T(t):null;return a&&e.write(`let ${a};`),e.write(`if (${o} !== undefined) {`),e.indented(c=>{let u=te(c,t,i.innerType,o,n);a&&u!==null&&c.write(`${a} = ${u};`)}),e.write("}"),a}function aS(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function sS(e){return e._zod.optin===void 0&&Jt(e)}function Jt(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?Jt(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?Jt(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Jt):!0;case"intersection":return!t.left||!t.right?!0:Jt(t.left)&&Jt(t.right);case"pipe":return t.in?Jt(t.in):!0;default:return!0}}function Sl(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function Sh(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&Cn(e)}function Cn(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?Cn(t.innerType):!0;case"union":return t.options?t.options.some(Cn):!0;case"intersection":return!t.left||!t.right||Cn(t.left)||Cn(t.right);case"pipe":return t.out?Cn(t.out):!0;default:return!0}}function cS(e,t,r,o,n=!0){let i=r._zod.def,a=n?T(t):null;return a&&e.write(`let ${a} = null;`),e.write(`if (${o} !== null) {`),e.indented(c=>{let u=te(c,t,i.innerType,o,n);a&&u!==null&&c.write(`${a} = ${u};`)}),e.write("}"),a}function Pl(e,t,r){for(let[o,n]of wn(t._zod.def.checks))e.write(`if (${r} > ${_t(o,n._zod.def.check)}) return INVALID;`)}function uS(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (!Array.isArray(${o})) return INVALID;`),Pl(e,r,`${o}.length`);let a=n?T(t):null,c=T(t),u=T(t);return a&&e.write(`const ${a} = new Array(${o}.length);`),e.write(`for (let ${c} = 0; ${c} < ${o}.length; ${c}++) {`),e.indented(l=>{l.write(`const ${u} = ${o}[${c}];`);let d=he(l,t,i.element,u,n);a&&d!==null&&l.write(`${a}[${c}] = ${d};`)}),e.write("}"),a}function lS(e,t,r,o){let i=r._zod.def.values;if(i.length!==1){let c=N(t,new Set(i));return e.write(`if (!${c}.has(${o})) return INVALID;`),o}let a=i[0];if(typeof a=="number"&&Number.isNaN(a)){let c=N(t,new Set(i));return e.write(`if (!${c}.has(${o})) return INVALID;`),o}if(typeof a=="string")e.write(`if (${o} !== ${be(a)}) return INVALID;`);else if(typeof a=="number"||typeof a=="boolean")e.write(`if (${o} !== ${a}) return INVALID;`);else if(a===null)e.write(`if (${o} !== null) return INVALID;`);else if(a===void 0)e.write(`if (${o} !== undefined) return INVALID;`);else if(typeof a=="bigint")e.write(`if (${o} !== ${a}n) return INVALID;`);else throw new F(`literal type ${typeof a}`);return o}function dS(e,t,r,o){let n=r._zod.values;if(!n)throw new F("enum schema without enumerated values");let i=N(t,n);return e.write(`if (!${i}.has(${o})) return INVALID;`),o}function Ih(e,t,r,o){let n=r._zod.def;return te(e,t,n.innerType,o)}function pS(e,t,r,o){let n=r._zod.def,a=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!a)return te(e,t,n.innerType,o);let u=N(t,a),l=T(t);return e.write(`let ${l} = ${o};`),e.write(`if (${o} === undefined) ${l} = ${u}();`),te(e,t,n.innerType,l)}let c=T(t);if(a){let u=N(t,a),l=N(t,yr);e.write(`let ${c};`),e.write(`if (${o} === undefined) {`),e.indented(d=>{d.write(`${c} = ${l}(${u}());`)}),e.write("} else {"),e.indented(d=>{let p=te(d,t,n.innerType,o);d.write(`${c} = ${p} === undefined ? ${l}(${u}()) : ${p};`)}),e.write("}")}else e.write(`let ${c};`),e.write(`if (${o} !== undefined) {`),e.indented(u=>{let l=te(u,t,n.innerType,o);u.write(`${c} = ${l};`)}),e.write("}");return c}function mS(e,t,r,o){let n=r._zod.def,i=te(e,t,n.innerType,o),a=T(t);return e.write(`const ${a} = ${i};`),e.write(`if (${a} === undefined) return INVALID;`),a}function fS(e,t,r,o){let n=r._zod.def,i=n.items,a=n.rest;e.write(`if (!Array.isArray(${o})) return INVALID;`);let c=zh(i,"optin"),u=zh(i,"optout");a?e.write(`if (${o}.length < ${c}) return INVALID;`):e.write(`if (${o}.length < ${c} || ${o}.length > ${i.length}) return INVALID;`);let l=T(t);e.write(`const ${l} = [];`);for(let d=0;d<i.length;d++){let p=i[d];if(d>=u)e.write(`if (${l}.length === ${d}) {`),e.indented(f=>{f.write(`if (${d} < ${o}.length) {`),f.indented(m=>{let g=T(t);m.write(`const ${g} = ${o}[${d}];`);let y=he(m,t,p,g);m.write(`${l}[${d}] = ${y};`)}),f.write("} else {"),f.indented(m=>{if(Sl(p)){m.write(`${l}.length = ${d};`);return}let g=T(t),y=T(t);m.write(`const ${g} = undefined;`),m.write(`const ${y} = (() => {`),m.indented(_=>{let I=he(_,t,p,g);_.write(`return ${I};`)}),m.write("})();"),m.write(`if (${y} === INVALID || ${y} === undefined) ${l}.length = ${d};`),m.write(`else ${l}[${d}] = ${y};`)}),f.write("}")}),e.write("}");else{let f=T(t);e.write(`const ${f} = ${o}[${d}];`);let m=he(e,t,p,f);e.write(`${l}[${d}] = ${m};`)}}if(a){let d=T(t),p=T(t);e.write(`for (let ${d} = ${i.length}; ${d} < ${o}.length; ${d}++) {`),e.indented(f=>{f.write(`const ${p} = ${o}[${d}];`);let m=he(f,t,a,p);f.write(`${l}[${d}] = ${m};`)}),e.write("}")}return l}function zh(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function gS(e,t,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return hS(e,t,n,o);if(n.inclusive===!1)throw new F("exclusive unions (z.xor)");if(i.length===0)return e.write("return INVALID;"),o;if(i.length===1)return te(e,t,i[0],o);if(i.every(u=>u._zod.def.type==="literal"&&!u._zod.def.checks?.length)){let u=new Set(i.flatMap(d=>d._zod.def.values)),l=N(t,u);return e.write(`if (!${l}.has(${o})) return INVALID;`),o}let c=T(t);e.write(`let ${c};`);for(let u=0;u<i.length;u++){let l=i[u];u===0?e.write(`${c} = (() => {`):e.write(`if (${c} === INVALID) ${c} = (() => {`),e.indented(d=>{let p=te(d,t,l,o);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${c} === INVALID) return INVALID;`),c}function hS(e,t,r,o){if(r.unionFallback)throw new F("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),o;let n=T(t),i=T(t);e.write(`const ${n} = ${o}?.[${be(r.discriminator)}];`),e.write(`let ${i};`);let a=!0,c=new Set;for(let u of r.options){let l=u._zod.propValues?.[r.discriminator];if(!l||l.size===0)throw new F("discriminated union option without static discriminator values");for(let f of l){if(c.has(f))throw new F(`duplicate discriminator value ${String(f)}`);c.add(f)}let d=Array.from(l,f=>vS(t,n,f)),p=a?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(f=>{let m=te(f,t,u,o);f.write(`${i} = ${m};`)}),e.write("}"),a=!1}return e.write("else { return INVALID; }"),i}function vS(e,t,r){if(typeof r=="string")return`${t} === ${be(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let o=N(e,r);return`${t} === ${o}`}throw new F(`literal discriminator value ${String(r)}`)}function yS(e,t,r,o){let n=r._zod.def;t.definite=!1;let i=he(e,t,n.left,o),a=he(e,t,n.right,o),c=N(t,An),u=T(t);return e.write(`const ${u} = ${c}(${i}, ${a});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function bS(e,t,r,o){let n=r._zod.def,i=N(t,Le);e.write(`if (!${i}(${o})) return INVALID;`);let a=T(t),c=T(t),u=T(t);e.write(`const ${a} = {};`);let l=n,d=l.partial?void 0:n.keyType._zod.values;if(d){let m=[];for(let y of d){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new F(`record key value ${String(y)}`);let _=typeof y=="number"?y.toString():y;if(_==="__proto__")throw new F('record key "__proto__"');m.push(_);let I=N(t,y),k=te(e,t,n.keyType,I),A=T(t);e.write(`const ${A} = ${o}[${$S(t,_)}];`);let Z=he(e,t,n.valueType,A);e.write(`${a}[${k}] = ${Z};`)}let g=N(t,new Set(m));return e.write(`for (const ${c} in ${o}) {`),e.indented(y=>{y.write(`if (${g}.has(${c})) continue;`),l.mode==="loose"?y.write(`if (${c} !== "__proto__") ${a}[${c}] = ${o}[${c}];`):y.write("return INVALID;")}),e.write("}"),a}let p=n.keyType._zod.def;if(!(p.type==="string"&&p.format===void 0&&!p.coerce&&(p.checks?.length??0)===0)){let m=n.mode==="loose",g=Ro(n.keyType);g.definite===!1&&(t.definite=!1);let y=N(t,g),_=N(t,pt),I=T(t);return Ph(e,t,o,c,k=>{k.write(`let ${I} = ${y}(${c});`),k.write(`if (${I} === INVALID && typeof ${c} === "string" && ${_}.test(${c})) ${I} = ${y}(Number(${c}));`),m?k.write(`if (${I} === INVALID) { ${a}[${c}] = ${o}[${c}]; continue; }`):k.write(`if (${I} === INVALID) return INVALID;`),k.write(`if (${I} === "__proto__") continue;`);let A=T(t);k.write(`const ${A} = ${o}[${c}];`);let Z=he(k,t,n.valueType,A);k.write(`${a}[${I}] = ${Z};`)}),a}return Ph(e,t,o,c,m=>{m.write(`const ${u} = ${o}[${c}];`);let g=he(m,t,n.valueType,u);m.write(`${a}[${c}] = ${g};`)},"return INVALID;"),a}function Ph(e,t,r,o,n,i){let a=N(t,Object.prototype.propertyIsEnumerable),c=T(t),u=T(t),l=T(t);e.write(`const ${c} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${u} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${l} = 0; ${l} < ${u}.length; ${l}++) {`),e.indented(d=>{d.write(`const ${o} = ${u}[${l}];`),d.write(`if (${o} === "__proto__" || !${a}.call(${r}, ${o})) continue;`),n(d)}),e.write("}"),e.write(`for (let ${l} = 0; ${l} < ${c}.length; ${l}++) {`),e.indented(d=>{d.write(`const ${o} = ${c}[${l}];`),d.write(`if (!${a}.call(${r}, ${o})) continue;`),i?d.write(i):n(d)}),e.write("}")}function $S(e,t){return typeof t=="string"?be(t):N(e,t)}function xS(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Map)) return INVALID;`),Pl(e,r,`${o}.size`);let i=T(t),a=T(t),c=T(t);return e.write(`const ${i} = new Map();`),e.write(`for (const [${a}, ${c}] of ${o}) {`),e.indented(u=>{let l=te(u,t,n.keyType,a),d=te(u,t,n.valueType,c);u.write(`${i}.set(${l}, ${d});`)}),e.write("}"),i}function wS(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Set)) return INVALID;`),Pl(e,r,`${o}.size`);let i=T(t),a=T(t);return e.write(`const ${i} = new Set();`),e.write(`for (const ${a} of ${o}) {`),e.indented(c=>{let u=te(c,t,n.valueType,a);c.write(`${i}.add(${u});`)}),e.write("}"),i}function _S(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function kS(e,t,r,o){e.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=N(t,n);e.write(`${i}.lastIndex = 0;`),e.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function SS(e,t,r,o){let n=r._zod.def,i=Bt(t,n.getter),a=N(t,{parser:null});e.write(`if (!${a}.parser) {`),e.indented(u=>{u.write(`const inner = ${i}();`),u.write(`${a}.parser = function(input) {`),u.indented(l=>{l.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),l.write("return result.issues.length === 0 ? result.value : INVALID;")}),u.write("};")}),e.write("}");let c=T(t);return e.write(`const ${c} = ${a}.parser(${o});`),e.write(`if (${c} === INVALID) return INVALID;`),c}function IS(e,t,r,o){let n=r._zod.def,i=te(e,t,n.in,o);if(n.transform){if(Wt(n.transform))throw new qe("z.compile: async transforms in pipes are not supported");let a=n.transform,u=Bt(t,d=>{let p={value:d,issues:[],addIssue:zl},f=a(d,p);return f instanceof Promise?xe:p.issues.length===0?f:xe}),l=T(t);return e.write(`const ${l} = ${u}(${i});`),e.write(`if (${l} === INVALID) return INVALID;`),te(e,t,n.out,l)}else return te(e,t,n.out,i)}function Wt(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function zS(e,t,r,o){let n=r._zod.def;if(n.fn){if(Wt(n.fn))throw new qe("z.compile: async custom predicates are not supported");let i=Bt(t,n.fn),a=N(t,kl),c=T(t);e.write(`const ${c} = ${i}(${o});`),e.write(`if (${c} instanceof Promise) ${a}();`),e.write(`if (!${c}) return INVALID;`)}else throw new F("custom schema without a predicate function");return o}function PS(e,t,r){let o=e._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return xe;let n=o;return n.issues.length===0?n.value:t()}function AS(e,t,r,o){let n=r._zod.def;if(!n.catchValue[Li])throw new F("catch with a callback (only a constant catch value compiles)",!1);let i=T(t);e.write(`let ${i} = (() => {`),e.indented(l=>{let d=he(l,t,n.innerType,o);l.write(`return ${d};`)}),e.write("})();");let a=N(t,n.innerType),c=Bt(t,n.catchValue),u=N(t,PS);return e.write(`if (${i} === INVALID) {`),e.indented(l=>{l.write(`${i} = ${u}(${a}, ${c}, ${o});`),l.write(`if (${i} === INVALID) return INVALID;`)}),e.write("}"),i}function jS(e,t,r,o){let n=r._zod.def;if(n.transform){if(Wt(n.transform))throw new qe("z.compile: async transforms are not supported");let i=n.transform,c=Bt(t,l=>{let d={value:l,issues:[],addIssue:zl},p=i(l,d);return p instanceof Promise?xe:d.issues.length===0?p:xe}),u=T(t);return e.write(`const ${u} = ${c}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return o}function Eo(e){return e.checks&&(e.checks=[...e.checks]),e}function Al(e,t){return new e(Eo({type:"string",...S(t)}))}function jl(e,t){return new e(Eo({type:"string",coerce:!0,...S(t)}))}function Uo(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...S(t)})}function Mo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...S(t)})}function Lo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...S(t)})}function Zo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...S(t)})}function Fo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...S(t)})}function Vo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...S(t)})}function Gr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...S(t)})}function Ko(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...S(t)})}function Jo(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...S(t)})}function Bo(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...S(t)})}function Wo(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...S(t)})}function Go(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...S(t)})}function qo(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...S(t)})}function Ho(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...S(t)})}function Xo(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...S(t)})}function Yo(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...S(t)})}function Tl(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...S(t)})}function Qo(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...S(t)})}function ea(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...S(t)})}function ta(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...S(t)})}function na(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...S(t)})}function ra(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...S(t)})}function Cl(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...S(t)})}function Ol(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...S(t)})}function ia(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...S(t)})}var Nl={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function qr(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...S(t)})}function Hr(e,t){return new e({type:"string",format:"date",check:"string_format",...S(t)})}function Xr(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...S(t)})}function Yr(e,t){return new e({type:"string",format:"duration",check:"string_format",...S(t)})}function Dl(e,t){return new e(Eo({type:"number",checks:[],...S(t)}))}function Rl(e,t){return new e(Eo({type:"number",coerce:!0,checks:[],...S(t)}))}function El(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...S(t)})}function Ul(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...S(t)})}function Ml(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...S(t)})}function Ll(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...S(t)})}function Zl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...S(t)})}function Fl(e,t){return new e({type:"boolean",...S(t)})}function Vl(e,t){return new e({type:"boolean",coerce:!0,...S(t)})}function Kl(e,t){return new e({type:"bigint",...S(t)})}function Jl(e,t){return new e({type:"bigint",coerce:!0,...S(t)})}function Bl(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...S(t)})}function Wl(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...S(t)})}function Gl(e,t){return new e({type:"symbol",...S(t)})}function ql(e,t){return new e({type:"undefined",...S(t)})}function Hl(e,t){return new e({type:"null",...S(t)})}function Xl(e){return new e({type:"any"})}function Yl(e){return new e({type:"unknown"})}function Ql(e,t){return new e({type:"never",...S(t)})}function ed(e,t){return new e({type:"void",...S(t)})}function td(e,t){return new e({type:"date",...S(t)})}function nd(e,t){return new e({type:"date",coerce:!0,...S(t)})}function rd(e,t){return new e({type:"nan",...S(t)})}function tt(e,t){return new no({check:"less_than",...S(t),value:e,inclusive:!1})}function Re(e,t){return new no({check:"less_than",...S(t),value:e,inclusive:!0})}function nt(e,t){return new ro({check:"greater_than",...S(t),value:e,inclusive:!1})}function Ee(e,t){return new ro({check:"greater_than",...S(t),value:e,inclusive:!0})}function oa(e){return nt(0,e)}function aa(e){return tt(0,e)}function sa(e){return Re(0,e)}function ca(e){return Ee(0,e)}function kt(e,t){return new Mc({check:"multiple_of",...S(t),value:e})}function St(e,t){return new Fc({check:"max_size",...S(t),maximum:e})}function rt(e,t){return new Vc({check:"min_size",...S(t),minimum:e})}function Gt(e,t){return new Kc({check:"size_equals",...S(t),size:e})}function qt(e,t){return new Jc({check:"max_length",...S(t),maximum:e})}function mt(e,t){return new Bc({check:"min_length",...S(t),minimum:e})}function Ht(e,t){return new Wc({check:"length_equals",...S(t),length:e})}function On(e,t){return new Gc({check:"string_format",format:"regex",...S(t),pattern:e})}function Nn(e){return new qc({check:"string_format",format:"lowercase",...S(e)})}function Dn(e){return new Hc({check:"string_format",format:"uppercase",...S(e)})}function Rn(e,t){return new Xc({check:"string_format",format:"includes",...S(t),includes:e})}function En(e,t){return new Yc({check:"string_format",format:"starts_with",...S(t),prefix:e})}function Un(e,t){return new Qc({check:"string_format",format:"ends_with",...S(t),suffix:e})}function ua(e,t,r){return new eu({check:"property",property:e,schema:t,...S(r)})}function Mn(e,t){return new tu({check:"properties",shape:e,...S(t)})}function Ln(e,t){return new nu({check:"mime_type",mime:e,...S(t)})}function He(e){return new ru({check:"overwrite",tx:e})}function Zn(e){return He(t=>t.normalize(e))}function Fn(){return He(e=>e.trim())}function Vn(){return He(e=>e.toLowerCase())}function Kn(){return He(e=>e.toUpperCase())}function Jn(){return He(e=>Zs(e))}function id(e,t,r){return new e({type:"array",element:t,...S(r)})}function TS(e,t,r){return new e({type:"union",options:t,...S(r)})}function CS(e,t,r){return new e({type:"union",options:t,inclusive:!1,...S(r)})}function OS(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...S(o)})}function NS(e,t,r){return new e({type:"intersection",left:t,right:r})}function DS(e,t,r,o){let n=r instanceof D,i=n?o:r,a=n?r:null;return new e({type:"tuple",items:t,rest:a,...S(i)})}function RS(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...S(o)})}function ES(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...S(o)})}function US(e,t,r){return new e({type:"set",valueType:t,...S(r)})}function MS(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...S(r)})}function LS(e,t,r){return new e({type:"enum",entries:t,...S(r)})}function ZS(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...S(r)})}function od(e,t){return new e({type:"file",...S(t)})}function FS(e,t){return new e({type:"transform",transform:t})}function VS(e,t){return new e({type:"optional",innerType:t})}function KS(e,t){return new e({type:"nullable",innerType:t})}function JS(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():yr(r)}})}function BS(e,t,r){return new e({type:"nonoptional",innerType:t,...S(r)})}function WS(e,t){return new e({type:"success",innerType:t})}function GS(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:Ws(r)})}function qS(e,t,r){return new e({type:"pipe",in:t,out:r})}function HS(e,t){return new e({type:"readonly",innerType:t})}function XS(e,t,r){return new e({type:"template_literal",parts:t,...S(r)})}function YS(e,t){return new e({type:"lazy",getter:t})}function QS(e,t){return new e({type:"promise",innerType:t})}function ad(e,t,r){let o=S(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function sd(e,t,r){return new e({type:"custom",check:"custom",fn:t,...S(r)})}function cd(e,t){let r=Ch(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(_n(n,o.value,r._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(_n(i))}},e(o.value,o)),t);return r}function Ch(e,t){let r=new H({check:"custom",...S(t)});return r._zod.check=e,r}function ud(e){let t=new H({check:"describe"});return t._zod.onattach=[r=>{let o=ge.get(r)??{};ge.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function ld(e){let t=new H({check:"meta"});return t._zod.onattach=[r=>{let o=ge.get(r)??{};ge.add(r,{...o,...e})}],t._zod.check=()=>{},t}function dd(e,t){let r=S(t),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(m=>typeof m=="string"?m.toLowerCase():m),n=n.map(m=>typeof m=="string"?m.toLowerCase():m));let i=new Set(o),a=new Set(n),c=e.Codec??Zr,u=e.Boolean??Mr,l=e.String??Kt,d=new l({type:"string",error:r.error}),p=new u({type:"boolean",error:r.error}),f=new c({type:"pipe",in:d,out:p,transform:((m,g)=>{let y=m;return r.case!=="sensitive"&&(y=y.toLowerCase()),i.has(y)?!0:a.has(y)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...a],input:g.value,inst:f,continue:!1}),{})}),reverseTransform:((m,g)=>m===!0?o[0]||"true":n[0]||"false"),error:r.error});return f._zod.bag.truthy=o,f._zod.bag.falsy=n,f._zod.bag.case=r.case??"insensitive",f}function Xt(e,t,r,o={}){let n=S(o),i={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:c=>r.test(c),...n};return r instanceof RegExp&&(i.pattern=r),new e(i)}function Qr(e,...t){for(let r of t)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&fe(e,o,r[o]);return e}function It(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ge,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function ue(e,t,r,o,n){let i=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:o.path,message:n}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function W(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,d);else{let f=a.schema,m=t.processors[n.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);m(e,t,f,d)}let p=e._zod.parent;p&&(a.ref||(a.ref=p),W(p,t,d),t.seen.get(p).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&Qr(a.schema,u),t.io==="input"&&we(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&"_prefault"in a.schema&&((o=a.schema).default??(o.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Oh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function zt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let o=new Map;for(let a of e.seen.entries()){let c=e.metadataRegistry.get(a[0])?.id;if(c){let u=o.get(c);if(u&&u!==a[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(c,a[0])}}let n=a=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(a[0])?.id,f=e.external.uri??(g=>g);if(p)return{ref:f(p)};let m=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=m,{defId:m,ref:`${f("__shared")}#/${c}/${Oh(m)}`}}let u="#",l=`${u}/${c}/`;if(a[1]===r&&!a[1].schema.id)return{ref:u};let d=a[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:l+Oh(d)}},i=a=>{if(a[1].schema.$ref)return;let c=a[1],{ref:u,defId:l}=n(a);c.def={...c.schema},l&&(c.defId=l);let d=c.schema;for(let p in d)delete d[p];d.$ref=u};if(e.cycles==="throw")for(let a of e.seen.entries()){let c=a[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
62
62
|
|
|
63
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let c=a[1];if(t===a[0]){i(a);continue}if(e.external){let l=e.external.registry.get(a[0])?.id;if(t!==a[0]&&l){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(c.cycle){i(a);continue}c.count>1&&e.reused==="ref"&&i(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Rh(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let o of t){if(!o||typeof o!="object")return;Rh(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let a of Array.isArray(i)?i:[i]){if(typeof a!="string")return;r.includes(a)||r.push(a)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Eh=new Set(["type","properties","required","additionalProperties"]),Nh=["oneOf","anyOf"];function Dh(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function pd(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Eh.has(a))return null;t.push(i)}let r={},o=new Set;for(let i of t){for(let a in i.properties){if(Object.prototype.hasOwnProperty.call(r,a))continue;let c=[];for(let l of t){let d=l.properties?.[a]??Dh(l);d!=null&&(c.some(p=>JSON.stringify(p)===JSON.stringify(d))||c.push(d))}let u=c.length===1?c[0]:pd(c)??{allOf:c};fe(r,a,u)}for(let a of i.required??[])o.add(a)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),t.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let a of t){let c=Dh(a);c&&!i.some(u=>JSON.stringify(u)===JSON.stringify(c))&&i.push(c)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function eI(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Eh)if(n in e)return;let r=t.filter(n=>Nh.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=pd(t);else{let n=r[0],i=Nh.find(u=>Array.isArray(n[u]));if(Object.keys(n).length!==1)return;let a=t.filter(u=>u!==n),c=n[i].map(u=>pd([...a,u]));if(c.some(u=>!u))return;o={[i]:c}}o&&(delete e.allOf,Qr(e,o))}function Pt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=c=>{let u=e.seen.get(c);if(u.ref===null)return;let l=u.def??u.schema,d={...l},p=u.ref;if(u.ref=null,p){o(p);let m=e.seen.get(p),g=m.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(g)):Qr(l,g),Qr(l,d),c._zod.parent===p)for(let _ in l)_==="$ref"||_==="allOf"||_ in d||delete l[_];if(g.$ref&&m.def)for(let _ in l)_==="$ref"||_==="allOf"||_ in m.def&&JSON.stringify(l[_])===JSON.stringify(m.def[_])&&delete l[_]}let f=c._zod.parent;if(f&&f!==p){o(f);let m=e.seen.get(f);if(m?.schema.$ref&&(l.$ref=m.schema.$ref,m.def))for(let g in l)g==="$ref"||g==="allOf"||g in m.def&&JSON.stringify(l[g])===JSON.stringify(m.def[g])&&delete l[g]}e.override({zodSchema:c,jsonSchema:l,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let c of[...e.seen.entries()].reverse())o(c[0]);if(e.target!=="openapi-3.0")for(let c of e.seen.entries())Rh(c[1].def??c[1].schema);for(let c of e.deferred)c();if(e.intersections.length){let c=new Map;for(let u of e.seen.values())for(let l of[u.schema,u.def]){let d=l?.allOf;if(!Array.isArray(d))continue;let p=c.get(d);p?p.push(l):c.set(d,[l])}for(let u of e.intersections)for(let l of c.get(u)??[])eI(l)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let c=e.external.registry.get(t)?.id;if(!c)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(c)}Qr(n,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&n.id===i&&delete n.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let c of e.seen.entries()){let u=c[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,fe(a,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?n.$defs=a:n.definitions=a);try{let c=JSON.parse(JSON.stringify(n));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:Bn(t,"input",e.processors),output:Bn(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function we(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return we(o.element,r);if(o.type==="set")return we(o.valueType,r);if(o.type==="lazy")return we(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return we(o.innerType,r);if(o.type==="intersection")return we(o.left,r)||we(o.right,r);if(o.type==="record"||o.type==="map")return we(o.keyType,r)||we(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:we(o.in,r)||we(o.out,r);if(o.type==="object"){for(let n in o.shape)if(we(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(we(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(we(n,r))return!0;return!!(o.rest&&we(o.rest,r))}return!1}var md=(e,t={})=>r=>{let o=It({...r,processors:t});return W(e,o),zt(o,e),Pt(o,e)},Bn=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=It({...n??{},target:i,io:t,processors:r});return W(e,a),zt(a,e),Pt(a,e)};var Wn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Gn=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Uh=(e,t)=>{Wn(e,"minimum",t),Gn(e,"maximum",t)},Fh=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Vh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Kh=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Jh=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Mh=(e,t)=>Wn(e,"minimum",t.minimum),Lh=(e,t)=>Gn(e,"maximum",t.maximum),Zh=e=>(t,r)=>{Jh(t,r.format);let[o,n]=e[r.format];Wn(t,"minimum",o),Gn(t,"maximum",n)},tI={greater_than:(e,t)=>Wn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Gn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Fh(e,t.value),number_format:Zh($r),bigint_format:Zh(xr),min_length:Mh,max_length:Lh,length_equals:(e,t)=>Uh(e,t.length),min_size:Mh,max_size:Lh,size_equals:(e,t)=>Uh(e,t.size),string_format:(e,t)=>{Jh(e,t.format),t.pattern&&Vh(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Kh(e,t.mime)};function le(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)tI[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Wn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Wn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Gn(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Gn(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&Fh(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&Kh(t,n.mime);for(let i of n.patterns??[])Vh(t,i);return t}var nI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},rI=new Map([[fo,bc],[Ur,$c]]),Bh=e=>rI.get(e)??e,hd=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:a,format:c,patterns:u,contentEncoding:l,laxFormat:d}=le(e);if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),c&&(n.format=nI[c]??c,n.format===""&&delete n.format,(c==="time"||d)&&delete n.format),l&&(n.contentEncoding=l),u&&u.size>0){let p=[...u].map(Bh);p.length===1?n.pattern=p[0].source:p.length>1&&(n.allOf=[...p.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},vd=(e,t,r,o)=>{let n=r,{minimum:i,maximum:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l,isInt:d}=le(e);n.type=d?"integer":"number";let p=typeof l=="number"&&l>=(i??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),m=t.target==="draft-04"||t.target==="openapi-3.0";if(p?m?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof i=="number"&&(n.minimum=i),f?m?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),c){let g=new Set;for(let I of c)Number.isFinite(I)&&I!==0?g.add(Math.abs(I)):ue(e,t,n,o,`A multipleOf divisor of ${I} cannot be represented in JSON Schema`);let[y,..._]=g;y!==void 0&&(n.multipleOf=y),_.length&&(n.allOf=[...n.allOf??[],..._.map(I=>({multipleOf:I}))])}},yd=(e,t,r,o)=>{r.type="boolean"},bd=(e,t,r,o)=>{ue(e,t,r,o,"BigInt cannot be represented in JSON Schema")},$d=(e,t,r,o)=>{ue(e,t,r,o,"Symbols cannot be represented in JSON Schema")},xd=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},wd=(e,t,r,o)=>{ue(e,t,r,o,"Undefined cannot be represented in JSON Schema")},_d=(e,t,r,o)=>{ue(e,t,r,o,"Void cannot be represented in JSON Schema")},kd=(e,t,r,o)=>{r.not={}},Sd=(e,t,r,o)=>{},Id=(e,t,r,o)=>{},zd=(e,t,r,o)=>{ue(e,t,r,o,"Date cannot be represented in JSON Schema")},Pd=(e,t,r,o)=>{let n=e._zod.def,i=yn(n.entries);if(i.length===0){r.not={};return}i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Ad=(e,t,r,o)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let a of n.values)if(a===void 0){if(ue(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(ue(e,t,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},jd=(e,t,r,o)=>{ue(e,t,r,o,"NaN cannot be represented in JSON Schema")},Td=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},Cd=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:a,mime:c}=le(e);i!==void 0&&(n.minLength=i),a!==void 0&&(n.maxLength=a),c&&(c.length===0?n.not={}:c.length===1?n.contentMediaType=c[0]:n.anyOf=c.map(u=>({contentMediaType:u})))},Od=(e,t,r,o)=>{r.type="boolean"},Nd=(e,t,r,o)=>{ue(e,t,r,o,"Custom types cannot be represented in JSON Schema")},Dd=(e,t,r,o)=>{ue(e,t,r,o,"Function types cannot be represented in JSON Schema")},Rd=(e,t,r,o)=>{ue(e,t,r,o,"Transforms cannot be represented in JSON Schema")},Ed=(e,t,r,o)=>{ue(e,t,r,o,"Map cannot be represented in JSON Schema")},Ud=(e,t,r,o)=>{ue(e,t,r,o,"Set cannot be represented in JSON Schema")},Md=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:a,maximum:c}=le(e);typeof a=="number"&&(n.minItems=a),typeof c=="number"&&(n.maxItems=c),n.type="array",n.items=W(i.element,t,{...o,path:[...o.path,"items"]})};function ei(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?ei(t.out):t.type==="catch"?ei(t.innerType):e._zod.optin}var Ld=(e,t,r,o)=>{let n=r,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&ue(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let l in a)fe(n.properties,l,W(a[l],t,{...o,path:[...o.path,"properties",l]}));let u=[];for(let l of Object.keys(a)){let d=i.shape[l];(t.io==="input"?ei(d)===void 0:d._zod.optout===void 0)&&u.push(l)}u.length>0&&(n.required=u),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=W(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},da=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((c,u)=>W(c,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},Zd=(e,t,r,o)=>{let n=e._zod.def,i=W(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=W(n.right,t,{...o,path:[...o.path,"allOf",1]}),c=l=>"allOf"in l&&Object.keys(l).length===1,u=[...c(i)?i.allOf:[i],...c(a)?a.allOf:[a]];r.allOf=u,t.intersections.push(u)},Fd=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",c=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((y,_)=>W(y,t,{...o,path:[...o.path,a,_]})),l=i.rest?W(i.rest,t,{...o,path:[...o.path,c,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,d=i.items.length;for(;d>0;){let y=i.items[d-1];if(!(t.io==="input"?ei(y)!==void 0:y._zod.optout==="optional"))break;d--}let p=i.items.length,f=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,f?n.items=!1:l&&(n.items=l),d>0&&(n.minItems=d),f&&(n.maxItems=p)):t.target==="openapi-3.0"?(n.items={anyOf:u},l&&n.items.anyOf.push(l),d>0&&(n.minItems=d),f&&(n.maxItems=p)):(n.items=u,f?n.additionalItems=!1:l&&(n.additionalItems=l),d>0&&(n.minItems=d),f&&(n.maxItems=p));let{minimum:m,maximum:g}=le(e);typeof m=="number"&&(n.minItems=m),typeof g=="number"&&(n.maxItems=g)};function fd(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let y=fd(e,g,r);return y===g?t:y}for(let g of["anyOf","oneOf"]){let y=t[g];if(!Array.isArray(y))continue;let _=y.map(I=>fd(e,I,r));_.some((I,k)=>I!==y[k])&&(t={...t,[g]:_})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(g=>g==="number"||g==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(g=>typeof g=="number"))return t;let{minimum:a,maximum:c,exclusiveMinimum:u,exclusiveMaximum:l,multipleOf:d,format:p,id:f,...m}=t;return m.enum?m.enum=m.enum.map(g=>typeof g=="number"?String(g):g):typeof m.const=="number"&&(m.const=String(m.const)),n&&(m.type="string",i||(m.pattern=(o.includes("number")?pt:Tr).source)),m}var gd=new WeakMap;function iI(e){let t=new Map;for(let o of e.seen.values())o.def&&!t.has(o.schema)&&t.set(o.schema,o);let r=new Map;for(let o of gd.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=fd(t,i,new Set);a!==i&&r.set(i,a)}if(r.size)for(let o of e.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var Vd=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let a=i.keyType,c=le(a).patterns;if(i.mode==="loose"&&c&&c.size>0){let d=W(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of c)fe(n.patternProperties,Bh(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=W(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let d=gd.get(t);d||(d=[],gd.set(t,d),t.deferred.push(()=>iI(t))),d.push(e)}n.additionalProperties=W(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,l=t.io==="input"&&ei(i.valueType)!==void 0;if(u&&!i.partial&&!l){let d=[...u].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(n.required=d.map(String))}},Kd=(e,t,r,o)=>{let n=e._zod.def,i=W(n.innerType,t,o),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},Jd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Bd=Symbol();function Wh(e,t,r,o,n){let i=!1,a=JSON.stringify(e,(c,u)=>typeof u!="bigint"?u:(i=!0,null));return i?(ue(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),Bd):JSON.parse(a)}var Wd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=Wh(n.defaultValue,e,t,r,o);a!==Bd&&(r.default=a)},Gd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=Wh(n.defaultValue,e,t,r,o);a!==Bd&&(r._prefault=a)},qd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{ue(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=a},Hd=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?i?n.out:n.in:n.out;W(a,t,o);let c=t.seen.get(e);c.ref=a},Xd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},Yd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},pa=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Qd=(e,t,r,o)=>{let n=e._zod.innerType;W(n,t,o);let i=t.seen.get(e);i.ref=n},la={string:hd,number:vd,boolean:yd,bigint:bd,symbol:$d,null:xd,undefined:wd,void:_d,never:kd,any:Sd,unknown:Id,date:zd,enum:Pd,literal:Ad,nan:jd,template_literal:Td,file:Cd,success:Od,custom:Nd,function:Dd,transform:Rd,map:Ed,set:Ud,array:Md,object:Ld,union:da,intersection:Zd,tuple:Fd,record:Vd,nullable:Kd,nonoptional:Jd,default:Wd,prefault:Gd,catch:qd,pipe:Hd,readonly:Xd,promise:Yd,optional:pa,lazy:Qd};function ma(e,t){if("_idmap"in e){let o=e,n=It({...t,processors:la}),i={};for(let u of o._idmap.entries()){let[l,d]=u;W(d,n)}let a={},c={registry:o,uri:t?.uri,defs:i};n.external=c;for(let u of o._idmap.entries()){let[l,d]=u;zt(n,d),fe(a,l,Pt(n,d))}if(Object.keys(i).length>0){let u=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:i}}return{schemas:a}}let r=It({...t,processors:la});return W(e,r),zt(r,e),Pt(r,e)}var fa=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=It({processors:la,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return W(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,zt(this.ctx,t);let o=Pt(this.ctx,t),{"~standard":n,...i}=o;return i}};var Gh={};var nr={};ut(nr,{ZodAny:()=>xp,ZodArray:()=>Sp,ZodBase64:()=>Oa,ZodBase64URL:()=>Na,ZodBigInt:()=>er,ZodBigIntFormat:()=>Ea,ZodBoolean:()=>Qn,ZodCIDRv4:()=>Ta,ZodCIDRv6:()=>Ca,ZodCUID:()=>ka,ZodCUID2:()=>Sa,ZodCatch:()=>Bp,ZodCodec:()=>li,ZodCreditCard:()=>mp,ZodCustom:()=>di,ZodCustomStringFormat:()=>tn,ZodDate:()=>ii,ZodDefault:()=>Lp,ZodDiscriminatedUnion:()=>zp,ZodE164:()=>Da,ZodEmail:()=>$a,ZodEmoji:()=>wa,ZodEnum:()=>Hn,ZodExactOptional:()=>Za,ZodFile:()=>Rp,ZodFunction:()=>nm,ZodGUID:()=>xa,ZodIBAN:()=>fp,ZodIPv4:()=>Aa,ZodIPv6:()=>ja,ZodISODate:()=>jt,ZodISODateTime:()=>At,ZodISODuration:()=>Ct,ZodISOTime:()=>Tt,ZodInstanceOf:()=>om,ZodIntersection:()=>Pp,ZodJWT:()=>Ra,ZodKSUID:()=>Pa,ZodLazy:()=>Qp,ZodLiteral:()=>Dp,ZodMAC:()=>pp,ZodMap:()=>Op,ZodNaN:()=>Gp,ZodNanoID:()=>_a,ZodNever:()=>_p,ZodNonOptional:()=>Fa,ZodNull:()=>bp,ZodNullable:()=>Mp,ZodNumber:()=>Yn,ZodNumberFormat:()=>nn,ZodObject:()=>ai,ZodOptional:()=>ci,ZodPipe:()=>ui,ZodPrefault:()=>Fp,ZodPreprocess:()=>qp,ZodPromise:()=>tm,ZodReadonly:()=>Hp,ZodRecord:()=>qn,ZodSet:()=>Np,ZodString:()=>Xn,ZodStringFormat:()=>q,ZodSuccess:()=>Jp,ZodSymbol:()=>vp,ZodTemplateLiteral:()=>Yp,ZodTransform:()=>Ep,ZodTuple:()=>jp,ZodType:()=>M,ZodULID:()=>Ia,ZodURL:()=>ri,ZodUUID:()=>it,ZodUndefined:()=>yp,ZodUnion:()=>si,ZodUnknown:()=>wp,ZodVoid:()=>kp,ZodXID:()=>za,ZodXor:()=>Ip,_ZodString:()=>ba,_default:()=>Zp,_function:()=>ay,any:()=>Ev,array:()=>oi,base64:()=>vv,base64url:()=>yv,bigint:()=>Cv,boolean:()=>hp,catch:()=>Wp,check:()=>sy,cidrv4:()=>gv,cidrv6:()=>hv,codec:()=>ny,creditCard:()=>$v,cuid:()=>sv,cuid2:()=>cv,currencyCode:()=>Iv,custom:()=>cy,date:()=>Mv,describe:()=>uy,discriminatedUnion:()=>Jv,e164:()=>bv,email:()=>Xh,emoji:()=>ov,enum:()=>Ma,exactOptional:()=>Up,file:()=>Yv,float32:()=>Pv,float64:()=>Av,function:()=>ay,guid:()=>Yh,hash:()=>zv,hex:()=>Sv,hostname:()=>kv,httpUrl:()=>iv,iban:()=>xv,instanceof:()=>dy,int:()=>va,int32:()=>jv,int64:()=>Ov,intersection:()=>Ap,invertCodec:()=>ry,ipv4:()=>pv,ipv6:()=>fv,json:()=>my,jwt:()=>wv,keyof:()=>Lv,ksuid:()=>dv,lazy:()=>em,literal:()=>Xv,looseObject:()=>Vv,looseRecord:()=>Wv,mac:()=>mv,map:()=>Gv,meta:()=>ly,nan:()=>ty,nanoid:()=>av,nativeEnum:()=>Hv,never:()=>Ua,nonoptional:()=>Kp,null:()=>$p,nullable:()=>ni,nullish:()=>Qv,number:()=>gp,object:()=>Zv,optional:()=>Qt,partialRecord:()=>Bv,pipe:()=>ya,prefault:()=>Vp,preprocess:()=>fy,promise:()=>oy,readonly:()=>Xp,record:()=>Cp,refine:()=>rm,set:()=>qv,strictObject:()=>Fv,string:()=>ti,stringFormat:()=>_v,stringbool:()=>py,success:()=>ey,superRefine:()=>im,symbol:()=>Dv,templateLiteral:()=>iy,transform:()=>La,tuple:()=>Tp,uint32:()=>Tv,uint64:()=>Nv,ulid:()=>uv,undefined:()=>Rv,union:()=>tr,unknown:()=>Yt,url:()=>rv,uuid:()=>Qh,uuidv4:()=>ev,uuidv6:()=>tv,uuidv7:()=>nv,void:()=>Uv,xid:()=>lv,xor:()=>Kv});var ga={};ut(ga,{endsWith:()=>Un,gt:()=>nt,gte:()=>Ee,includes:()=>Rn,length:()=>Ht,lowercase:()=>Nn,lt:()=>tt,lte:()=>Re,maxLength:()=>qt,maxSize:()=>St,mime:()=>Ln,minLength:()=>mt,minSize:()=>rt,multipleOf:()=>kt,negative:()=>aa,nonnegative:()=>ca,nonpositive:()=>sa,normalize:()=>Zn,overwrite:()=>He,positive:()=>oa,properties:()=>Mn,property:()=>ua,regex:()=>On,size:()=>Gt,slugify:()=>Jn,startsWith:()=>En,toLowerCase:()=>Vn,toUpperCase:()=>Kn,trim:()=>Fn,uppercase:()=>Dn});var qh=new WeakSet([Object.prototype,Error.prototype]);function ha(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}var Hh=(e,t)=>{Qs.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);qh.has(r)||(qh.add(r),ha(r,"format",o=>n=>zr(o,n)),ha(r,"flatten",o=>n=>Ir(o,n)),ha(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,bn,2)}),ha(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,bn,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},aI=h("ZodError",Hh),je=h("ZodError",Hh,void 0,{Parent:Error});var ep=kn(je),tp=Sn(je),np=In(je),rp=zn(je),ip=Ki(je),op=Ji(je),ap=Bi(je),sp=Wi(je),cp=Gi(je),up=qi(je),lp=Hi(je),dp=Xi(je);function cI(){pe.localeError||ie(jo())}function en(){pe.memoizer||ie({memoizer:Jr()})}var M=h("ZodType",(e,t)=>(cI(),D.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(b.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return J(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rm(e,t))},superRefine(e,t){return this.check(im(e,t))},overwrite(e){return this.check(He(e))},optional(){return Qt(this)},exactOptional(){return Up(this)},nullable(){return ni(this)},nullish(){return Qt(ni(this))},nonoptional(e){return Kp(this,e)},array(){return oi(this)},or(e){return tr([this,e])},and(e){return Ap(this,e)},transform(e){return ya(this,La(e))},default(e){return Zp(this,e)},prefault(e){return Vp(this,e)},catch(e){return Wp(this,e)},pipe(e){return ya(this,e)},readonly(){return Xp(this)},describe(e){let t=this.clone();return ge.add(t,{description:e}),t},meta(...e){if(e.length===0)return ge.get(this);let t=this.clone();return ge.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return b.hide(this,"~standard",{...co(this),jsonSchema:{input:Bn(this,"input"),output:Bn(this,"output")}})},set"~standard"(e){b.own(this,"~standard",e)},parse:function e(t,r){return ep(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await tp(this,t,r,{callee:e})},safeParse(e,t){return np(this,e,t)},async safeParseAsync(e,t){return rp(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){b.own(this,"spa",e)},validate(e,t){return Pr(this,e,t)},validateAsync(e,t){return Ar(this,e,t)},encode:function e(t,r){return ip(this,t,r,{callee:e})},decode:function e(t,r){return op(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await ap(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await sp(this,t,r,{callee:e})},safeEncode(e,t){return cp(this,e,t)},safeDecode(e,t){return up(this,e,t)},async safeEncodeAsync(e,t){return lp(this,e,t)},async safeDecodeAsync(e,t){return dp(this,e,t)},toJSONSchema(e){return md(this,{})(e)},get description(){return ge.get(this)?.description},get _def(){return this._zod.def}}),ba=h("_ZodString",(e,t)=>{Kt.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hd(e,r,o,n)},b.derived({format:e=>le(e).format??null,minLength:e=>le(e).minimum??null,maxLength:e=>le(e).maximum??null},{regex(...e){return this.check(On(...e))},includes(...e){return this.check(Rn(...e))},startsWith(...e){return this.check(En(...e))},endsWith(...e){return this.check(Un(...e))},min(...e){return this.check(mt(...e))},max(...e){return this.check(qt(...e))},length(...e){return this.check(Ht(...e))},nonempty(...e){return this.check(mt(1,...e))},lowercase(e){return this.check(Nn(e))},uppercase(e){return this.check(Dn(e))},trim(){return this.check(Fn())},normalize(...e){return this.check(Zn(...e))},toLowerCase(){return this.check(Vn())},toUpperCase(){return this.check(Kn())},slugify(){return this.check(Jn())}})),Xn=h("ZodString",(e,t)=>{Kt.init(e,t),ba.init(e,t)},{email(e){return this.check(Uo($a,e))},url(e){return this.check(Gr(ri,e))},jwt(e){return this.check(ia(Ra,e))},emoji(e){return this.check(Ko(wa,e))},guid(e){return this.check(Mo(xa,e))},uuid(e){return this.check(Lo(it,e))},uuidv4(e){return this.check(Zo(it,e))},uuidv6(e){return this.check(Fo(it,e))},uuidv7(e){return this.check(Vo(it,e))},nanoid(e){return this.check(Jo(_a,e))},cuid(e){return this.check(Bo(ka,e))},cuid2(e){return this.check(Wo(Sa,e))},ulid(e){return this.check(Go(Ia,e))},base64(e){return this.check(ta(Oa,e))},base64url(e){return this.check(na(Na,e))},xid(e){return this.check(qo(za,e))},ksuid(e){return this.check(Ho(Pa,e))},ipv4(e){return this.check(Xo(Aa,e))},ipv6(e){return this.check(Yo(ja,e))},cidrv4(e){return this.check(Qo(Ta,e))},cidrv6(e){return this.check(ea(Ca,e))},e164(e){return this.check(ra(Da,e))},datetime(e){return this.check(qr(At,e))},date(e){return this.check(Hr(jt,e))},time(e){return this.check(Xr(Tt,e))},duration(e){return this.check(Yr(Ct,e))}});function ti(e){return Al(Xn,e)}var q=h("ZodStringFormat",(e,t)=>{B.init(e,t),ba.init(e,t)}),At=h("ZodISODateTime",(e,t)=>{bu.init(e,t),q.init(e,t)}),jt=h("ZodISODate",(e,t)=>{$u.init(e,t),q.init(e,t)}),Tt=h("ZodISOTime",(e,t)=>{xu.init(e,t),q.init(e,t)}),Ct=h("ZodISODuration",(e,t)=>{wu.init(e,t),q.init(e,t)}),$a=h("ZodEmail",(e,t)=>{cu.init(e,t),q.init(e,t)});function Xh(e){return Uo($a,e)}var xa=h("ZodGUID",(e,t)=>{au.init(e,t),q.init(e,t)});function Yh(e){return Mo(xa,e)}var it=h("ZodUUID",(e,t)=>{su.init(e,t),q.init(e,t)});function Qh(e){return Lo(it,e)}function ev(e){return Zo(it,e)}function tv(e){return Fo(it,e)}function nv(e){return Vo(it,e)}var ri=h("ZodURL",(e,t)=>{du.init(e,t),q.init(e,t)});function rv(e){return Gr(ri,e)}function iv(e){return Gr(ri,{protocol:jr,hostname:wc,...b.normalizeParams(e)})}var wa=h("ZodEmoji",(e,t)=>{pu.init(e,t),q.init(e,t)});function ov(e){return Ko(wa,e)}var _a=h("ZodNanoID",(e,t)=>{mu.init(e,t),q.init(e,t)});function av(e){return Jo(_a,e)}var ka=h("ZodCUID",(e,t)=>{fu.init(e,t),q.init(e,t)});function sv(e){return Bo(ka,e)}var Sa=h("ZodCUID2",(e,t)=>{gu.init(e,t),q.init(e,t)});function cv(e){return Wo(Sa,e)}var Ia=h("ZodULID",(e,t)=>{hu.init(e,t),q.init(e,t)});function uv(e){return Go(Ia,e)}var za=h("ZodXID",(e,t)=>{vu.init(e,t),q.init(e,t)});function lv(e){return qo(za,e)}var Pa=h("ZodKSUID",(e,t)=>{yu.init(e,t),q.init(e,t)});function dv(e){return Ho(Pa,e)}var Aa=h("ZodIPv4",(e,t)=>{_u.init(e,t),q.init(e,t)});function pv(e){return Xo(Aa,e)}var pp=h("ZodMAC",(e,t)=>{Su.init(e,t),q.init(e,t)});function mv(e){return Tl(pp,e)}var ja=h("ZodIPv6",(e,t)=>{ku.init(e,t),q.init(e,t)});function fv(e){return Yo(ja,e)}var Ta=h("ZodCIDRv4",(e,t)=>{Iu.init(e,t),q.init(e,t)});function gv(e){return Qo(Ta,e)}var Ca=h("ZodCIDRv6",(e,t)=>{zu.init(e,t),q.init(e,t)});function hv(e){return ea(Ca,e)}var Oa=h("ZodBase64",(e,t)=>{Pu.init(e,t),q.init(e,t)});function vv(e){return ta(Oa,e)}var Na=h("ZodBase64URL",(e,t)=>{Au.init(e,t),q.init(e,t)});function yv(e){return na(Na,e)}var Da=h("ZodE164",(e,t)=>{ju.init(e,t),q.init(e,t)});function bv(e){return ra(Da,e)}var mp=h("ZodCreditCard",(e,t)=>{Tu.init(e,t),q.init(e,t)});function $v(e){return Cl(mp,e)}var fp=h("ZodIBAN",(e,t)=>{Cu.init(e,t),q.init(e,t)});function xv(e){return Ol(fp,e)}var Ra=h("ZodJWT",(e,t)=>{Ou.init(e,t),q.init(e,t)});function wv(e){return ia(Ra,e)}var tn=h("ZodCustomStringFormat",(e,t)=>{Nu.init(e,t),q.init(e,t)});function _v(e,t,r={}){return Xt(tn,e,t,r)}function kv(e){return Xt(tn,"hostname",xc,e)}function Sv(e){return Xt(tn,"hex",Rc,e)}function Iv(e){return Xt(tn,"currency_code",kc,e)}function zv(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Fe[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Xt(tn,o,n,t)}var Yn=h("ZodNumber",(e,t)=>{bo.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vd(e,r,o,n),e.isFinite=!0},b.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=le(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=le(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=le(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>le(e).format??null},{gt(e,t){return this.check(nt(e,t))},gte(e,t){return this.check(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},lt(e,t){return this.check(tt(e,t))},lte(e,t){return this.check(Re(e,t))},max(e,t){return this.check(Re(e,t))},int(e){return this.check(va(e))},safe(e){return this.check(va(e))},positive(e){return this.check(nt(0,e))},nonnegative(e){return this.check(Ee(0,e))},negative(e){return this.check(tt(0,e))},nonpositive(e){return this.check(Re(0,e))},multipleOf(e,t){return this.check(kt(e,t))},step(e,t){return this.check(kt(e,t))},finite(){return this}}));function gp(e){return Dl(Yn,e)}var nn=h("ZodNumberFormat",(e,t)=>{Du.init(e,t),Yn.init(e,t)});function va(e){return El(nn,e)}function Pv(e){return Ul(nn,e)}function Av(e){return Ml(nn,e)}function jv(e){return Ll(nn,e)}function Tv(e){return Zl(nn,e)}var Qn=h("ZodBoolean",(e,t)=>{Mr.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yd(e,r,o,n)});function hp(e){return Fl(Qn,e)}var er=h("ZodBigInt",(e,t)=>{$o.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bd(e,r,o,n)},b.derived({minValue:e=>le(e).minimum??null,maxValue:e=>le(e).maximum??null,format:e=>le(e).format??null},{gte(e,t){return this.check(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},gt(e,t){return this.check(nt(e,t))},lt(e,t){return this.check(tt(e,t))},lte(e,t){return this.check(Re(e,t))},max(e,t){return this.check(Re(e,t))},positive(e){return this.check(nt(BigInt(0),e))},negative(e){return this.check(tt(BigInt(0),e))},nonpositive(e){return this.check(Re(BigInt(0),e))},nonnegative(e){return this.check(Ee(BigInt(0),e))},multipleOf(e,t){return this.check(kt(e,t))}}));function Cv(e){return Kl(er,e)}var Ea=h("ZodBigIntFormat",(e,t)=>{Ru.init(e,t),er.init(e,t)});function Ov(e){return Bl(Ea,e)}function Nv(e){return Wl(Ea,e)}var vp=h("ZodSymbol",(e,t)=>{Eu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$d(e,r,o,n)});function Dv(e){return Gl(vp,e)}var yp=h("ZodUndefined",(e,t)=>{Uu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wd(e,r,o,n)});function Rv(e){return ql(yp,e)}var bp=h("ZodNull",(e,t)=>{Mu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xd(e,r,o,n)});function $p(e){return Hl(bp,e)}var xp=h("ZodAny",(e,t)=>{Lu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sd(e,r,o,n)});function Ev(){return Xl(xp)}var wp=h("ZodUnknown",(e,t)=>{Zu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Id(e,r,o,n)});function Yt(){return Yl(wp)}var _p=h("ZodNever",(e,t)=>{Fu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kd(e,r,o,n)});function Ua(e){return Ql(_p,e)}var kp=h("ZodVoid",(e,t)=>{Vu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_d(e,r,o,n)});function Uv(e){return ed(kp,e)}var ii=h("ZodDate",(e,t)=>{Ku.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zd(e,r,o,n),e.min=(r,o)=>e.check(Ee(r,o)),e.max=(r,o)=>e.check(Re(r,o))},b.derived({minDate:e=>{let{minimum:t}=le(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=le(e);return t?new Date(t):null}},{}));function Mv(e){return td(ii,e)}var Sp=h("ZodArray",(e,t)=>{en(),Bu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Md(e,r,o,n),e.element=t.element},{min(e,t){return this.check(mt(e,t))},nonempty(e){return this.check(mt(1,e))},max(e,t){return this.check(qt(e,t))},length(e,t){return this.check(Ht(e,t))},unwrap(){return this.element}});function oi(e,t){return id(Sp,e,t)}function Lv(e){let t=e._zod.def.shape;return Ma(Object.keys(t))}var ai=h("ZodObject",(e,t)=>{en(),Wu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ld(e,r,o,n),b.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Ma(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(b.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Yt()}))},loose(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Yt()}))},strict(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Ua()}))},strip(){return this.clone(b.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return b.extend(this,e)},safeExtend(e){return b.safeExtend(this,e)},merge(e){return b.merge(this,e)},pick(e){return b.pick(this,e)},omit(e){return b.omit(this,e)},partial(...e){return b.partial(ci,this,e[0])},exactPartial(...e){return b.partial(Za,this,e[0],"exactPartial")},required(...e){return b.required(Fa,this,e[0])}});function Zv(e,t){let r={type:"object",shape:e??{},...b.normalizeParams(t)};return new ai(r)}function Fv(e,t){return new ai({type:"object",shape:e,catchall:Ua(),...b.normalizeParams(t)})}function Vv(e,t){return new ai({type:"object",shape:e,catchall:Yt(),...b.normalizeParams(t)})}var si=h("ZodUnion",(e,t)=>{Lr.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>da(e,r,o,n),e.options=t.options});function tr(e,t){return new si({type:"union",options:e,...b.normalizeParams(t)})}var Ip=h("ZodXor",(e,t)=>{si.init(e,t),Gu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>da(e,r,o,n),e.options=t.options});function Kv(e,t){return new Ip({type:"union",options:e,inclusive:!1,...b.normalizeParams(t)})}var zp=h("ZodDiscriminatedUnion",(e,t)=>{si.init(e,t),Hu.init(e,t)});function Jv(e,t,r){return new zp({type:"union",options:t,discriminator:e,...b.normalizeParams(r)})}var Pp=h("ZodIntersection",(e,t)=>{Xu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zd(e,r,o,n)});function Ap(e,t){return new Pp({type:"intersection",left:e,right:t})}var jp=h("ZodTuple",(e,t)=>{en(),xo.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fd(e,r,o,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new ci({type:"optional",innerType:t}))})}});function Tp(e,t,r){let o=t instanceof D,n=o?r:t,i=o?t:null;return new jp({type:"tuple",items:e,rest:i,...b.normalizeParams(n)})}var qn=h("ZodRecord",(e,t)=>{en(),Yu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Cp(e,t,r){return!t||!t._zod?new qn({type:"record",keyType:ti(),valueType:e,...b.normalizeParams(t)}):new qn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r)})}function Bv(e,t,r){return new qn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r),partial:!0})}function Wv(e,t,r){return new qn({type:"record",keyType:e,valueType:t,mode:"loose",...b.normalizeParams(r)})}var Op=h("ZodMap",(e,t)=>{en(),Qu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ed(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(rt(...r)),e.nonempty=r=>e.check(rt(1,r)),e.max=(...r)=>e.check(St(...r)),e.size=(...r)=>e.check(Gt(...r))});function Gv(e,t,r){return new Op({type:"map",keyType:e,valueType:t,...b.normalizeParams(r)})}var Np=h("ZodSet",(e,t)=>{en(),el.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ud(e,r,o,n),e.min=(...r)=>e.check(rt(...r)),e.nonempty=r=>e.check(rt(1,r)),e.max=(...r)=>e.check(St(...r)),e.size=(...r)=>e.check(Gt(...r))});function qv(e,t){return new Np({type:"set",valueType:e,...b.normalizeParams(t)})}var Hn=h("ZodEnum",(e,t)=>{tl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Pd(e,o,n,i),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let a of o)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Hn({...t,checks:[],...b.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let a of o)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Hn({...t,checks:[],...b.normalizeParams(n),entries:i})}});function Ma(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Hn({type:"enum",entries:r,...b.normalizeParams(t)})}function Hv(e,t){return new Hn({type:"enum",entries:e,...b.normalizeParams(t)})}var Dp=h("ZodLiteral",(e,t)=>{nl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ad(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Xv(e,t){return new Dp({type:"literal",values:Array.isArray(e)?e:[e],...b.normalizeParams(t)})}var Rp=h("ZodFile",(e,t)=>{rl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cd(e,r,o,n),e.min=(r,o)=>e.check(rt(r,o)),e.max=(r,o)=>e.check(St(r,o)),e.mime=(r,o)=>e.check(Ln(Array.isArray(r)?r:[r],o))});function Yv(e){return od(Rp,e)}var Ep=h("ZodTransform",(e,t)=>{en(),il.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rd(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new wt(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(b.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=r.value),a.inst??(a.inst=e),r.issues.push(b.issue(a))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function La(e){return new Ep({type:"transform",transform:e})}var ci=h("ZodOptional",(e,t)=>{wo.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pa(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Qt(e){return new ci({type:"optional",innerType:e})}var Za=h("ZodExactOptional",(e,t)=>{ol.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pa(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Up(e){return new Za({type:"optional",innerType:e})}var Mp=h("ZodNullable",(e,t)=>{al.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ni(e){return new Mp({type:"nullable",innerType:e})}function Qv(e){return Qt(ni(e))}var Lp=h("ZodDefault",(e,t)=>{sl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Zp(e,t){return new Lp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var Fp=h("ZodPrefault",(e,t)=>{cl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Vp(e,t){return new Fp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var Fa=h("ZodNonOptional",(e,t)=>{ul.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Kp(e,t){return new Fa({type:"nonoptional",innerType:e,...b.normalizeParams(t)})}var Jp=h("ZodSuccess",(e,t)=>{ll.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Od(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ey(e){return new Jp({type:"success",innerType:e})}var Bp=h("ZodCatch",(e,t)=>{dl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>qd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wp(e,t){return new Bp({type:"catch",innerType:e,catchValue:typeof t=="function"?t:b.constantCatch(t)})}var Gp=h("ZodNaN",(e,t)=>{pl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jd(e,r,o,n)});function ty(e){return rd(Gp,e)}var ui=h("ZodPipe",(e,t)=>{_o.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hd(e,r,o,n),e.in=t.in,e.out=t.out});function ya(e,t){return new ui({type:"pipe",in:e,out:t})}var li=h("ZodCodec",(e,t)=>{ui.init(e,t),Zr.init(e,t)});function ny(e,t,r){return new li({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function ry(e){let t=e._zod.def;return new li({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var qp=h("ZodPreprocess",(e,t)=>{ui.init(e,t),ml.init(e,t)}),Hp=h("ZodReadonly",(e,t)=>{fl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Xp(e){return new Hp({type:"readonly",innerType:e})}var Yp=h("ZodTemplateLiteral",(e,t)=>{gl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Td(e,r,o,n)});function iy(e,t){return new Yp({type:"template_literal",parts:e,...b.normalizeParams(t)})}var Qp=h("ZodLazy",(e,t)=>{Fr.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Qd(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function em(e){return new Qp({type:"lazy",getter:e})}var tm=h("ZodPromise",(e,t)=>{vl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function oy(e){return new tm({type:"promise",innerType:e})}var nm=h("ZodFunction",(e,t)=>{hl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dd(e,r,o,n)});function ay(e){return new nm({type:"function",input:Array.isArray(e?.input)?Tp(e?.input):e?.input??oi(Yt()),output:e?.output??Yt()})}var di=h("ZodCustom",(e,t)=>{yl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nd(e,r,o,n)});function sy(e){let t=new H({check:"custom"});return t._zod.check=e,t}function cy(e,t){return ad(di,e??(()=>!0),t)}function rm(e,t={}){return sd(di,e,t)}function im(e,t){return cd(e,t)}var uy=ud,ly=ld,om=h("ZodInstanceOf",(e,t)=>{di.init(e,t)},{properties(e,t){return this.check(Mn(e,t))}});function dy(e,t={}){let r=new om({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...b.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var py=(...e)=>dd({Codec:li,Boolean:Qn,String:Xn},...e);function my(e){let t=em(()=>tr([ti(e),gp(),hp(),$p(),oi(t),Cp(ti(),t)]));return t}function fy(e,t){return new qp({type:"pipe",in:La(e),out:t})}var uI={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function lI(e){ie({customError:e})}function dI(){return ie().customError}var am;am||(am={});var pi={};ut(pi,{ZodISODate:()=>jt,ZodISODateTime:()=>At,ZodISODuration:()=>Ct,ZodISOTime:()=>Tt,date:()=>mI,datetime:()=>pI,duration:()=>gI,time:()=>fI});function pI(e){return qr(At,e)}function mI(e){return Hr(jt,e)}function fI(e){return Xr(Tt,e)}function gI(e){return Yr(Ct,e)}var z={...nr,...ga,iso:pi},hI=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function vI(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function gy(e,t){return e.map((r,o)=>o<t?r:r.optional())}function yI(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function bI(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:yI(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function $I(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&i.length<t.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let a of i){let c=t.keySchema.safeParse(a);c.success||o.issues.push({code:"invalid_key",origin:"record",issues:c.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function sm(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let o=String(e);return`${r[0]}${o.length}:${o}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let i=[];for(let a of e){let c=sm(a,t);if(c===null)return null;i.push(c)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let a=sm(e[i],t);if(a===null)return null;n.push(`${i.length}:${i}=${a}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var xI=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),wI=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function mi(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(mi):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>xI.has(t)?mi(r):!wI.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(mi))}function hy(e){return e===1?"element":"elements"}function _I(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let i=new Map;for(let a=0;a<n.length;a++){let c=sm(n[a],new Set);if(c===null)continue;let u=i.get(c);if(u===void 0){i.set(c,a);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${a} duplicates the one at index ${u}`,input:n,path:[a],continue:!0})}}if(t.containsSchema){let i=t.minContains??1,a=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,c=0;for(let u of n)if(t.containsSchema.safeParse(u).success&&++c>=a)break;c<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${hy(i)}; found ${c}`,input:n,continue:!0}),t.maxContains!==void 0&&c>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${hy(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function vy(e,t){if(e!==!1)return e===void 0||e===!0?z.any():_e(e,t)}var kI=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function yy(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return z.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=bI(n,t),a=_e(i,t);return t.refs.set(n,a),t.processing.delete(n),a}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return z.null();if(n.length===0)return z.never();if(n.length===1)return z.literal(n[0]);if(n.every(a=>typeof a=="string"))return z.enum(n);let i=n.map(a=>z.literal(a));return i.length<2?i[0]:z.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return z.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let a={...e,type:i};return yy(a,t)});return n.length===0?z.never():n.length===1?n[0]:z.union(n)}if(!r)return z.any();let o;switch(r){case"string":{let n=z.string();if(e.format){let i=e.format;i==="email"?n=n.check(z.email()):i==="uri"||i==="uri-reference"?n=n.check(z.url()):i==="uuid"||i==="guid"?n=n.check(z.uuid()):i==="date-time"?n=n.check(z.iso.datetime({offset:!0})):i==="date"?n=n.check(z.iso.date()):i==="time"?n=n.check(z.regex(kI)):i==="duration"?n=n.check(z.iso.duration()):i==="hostname"?n=n.check(z.hostname()):i==="ipv4"?n=n.check(z.ipv4()):i==="ipv6"?n=n.check(z.ipv6()):i==="mac"?n=n.check(z.mac()):i==="cidr"?n=n.check(z.cidrv4()):i==="cidr-v6"?n=n.check(z.cidrv6()):i==="base64"?n=n.check(z.base64()):i==="base64url"?n=n.check(z.base64url()):i==="e164"?n=n.check(z.e164()):i==="credit_card"?n=n.check(z.creditCard()):i==="iban"?n=n.check(z.iban()):i==="jwt"?n=n.check(z.jwt()):i==="emoji"?n=n.check(z.emoji()):i==="nanoid"?n=n.check(z.nanoid()):i==="cuid"?n=n.check(z.cuid()):i==="cuid2"?n=n.check(z.cuid2()):i==="ulid"?n=n.check(z.ulid()):i==="xid"?n=n.check(z.xid()):i==="ksuid"&&(n=n.check(z.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?z.number().int():z.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=z.boolean();break}case"null":{o=z.null();break}case"object":{let n={},i=e.properties||{},a=new Set(e.required||[]),c=typeof e.additionalProperties=="object"?_e(e.additionalProperties,t):void 0;for(let[p,f]of Object.entries(i)){let m=_e(f,t);fe(n,p,a.has(p)?m:m.optional())}if(e.patternProperties){let p=e.patternProperties,f=Object.keys(p),m=[];for(let y of f){let _=_e(p[y],t),I=z.string().regex(new RegExp(y));m.push(z.looseRecord(I,_))}let g=[];if(Object.keys(n).length>0&&g.push(z.object(n).passthrough()),g.push(...m),g.length===0)o=z.object({}).passthrough();else if(g.length===1)o=g[0];else{let y=z.intersection(g[0],g[1]);for(let _=2;_<g.length;_++)y=z.intersection(y,g[_]);o=y}if(e.additionalProperties===!1){let y=Object.keys(n),_=f.map(k=>new RegExp(k)),I=o;o=o.check(k=>{if(!Le(k.value))return;let A=[];for(let Z of Object.keys(k.value))y.includes(Z)||_.some(C=>C.test(Z))||A.push(Z);A.length&&k.issues.push({code:"unrecognized_keys",keys:A,input:k.value,inst:I})})}}else{let p=z.object(n);e.additionalProperties===!1?o=p.strict():c?o=p.catchall(c):o=p.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,l=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||l!==void 0||d!==void 0){let p;if(u){let f=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=_e(f,t)}o=$I(o,{keySchema:p,minProperties:l,maxProperties:d})}break}case"array":{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems=="number"?e.minItems:0,c=n.map(p=>_e(p,t)),u=gy(c,a),l=Array.isArray(i)?void 0:vy(i,t),d=z.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(Array.isArray(i)){let a=typeof e.minItems=="number"?e.minItems:0,c=i.map(p=>_e(p,t)),u=gy(c,a),l=vy(e.additionalItems,t),d=z.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(i!==void 0){let a=_e(i,t),c=z.array(a);typeof e.minItems=="number"&&(c=c.min(e.minItems)),typeof e.maxItems=="number"&&(c=c.max(e.maxItems)),o=c}else o=z.array(z.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=_I(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?_e(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function _e(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r=yy(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let c=e.anyOf.map(l=>_e(l,t)),u=z.union(c);r=o?z.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let c=e.oneOf.map(l=>_e(l,t)),u=z.xor(c);r=o?z.intersection(r,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:z.any();else{let c=o?r:_e(e.allOf[0],t),u=o?0:1;for(let l=u;l<e.allOf.length;l++)c=z.intersection(c,_e(e.allOf[l],t));r=c}e.nullable===!0&&t.version==="openapi-3.0"&&(r=z.nullable(r)),e.readOnly===!0&&(r=z.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let c of i)c in e&&(n[c]=e[c]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let c of a)c in e&&(n[c]=e[c]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!mi(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let c of["minProperties","maxProperties"])e[c]!==void 0&&(n[c]=e[c])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!mi(e.contains)&&(n.contains=e.contains);for(let c of["uniqueItems","minContains","maxContains"])e[c]!==void 0&&(n[c]=e[c])}for(let c of Object.keys(e))hI.has(c)||fe(n,c,e[c]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function by(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=vI(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??ge};return _e(r,i)}var $y=Symbol("z.visit/resolving");function fi(e,t){let r=typeof t=="function"?t:(a,c)=>{let u=t[a._zod.def.type];return u?u(a,c):a},o=new Map;function n(a){let c=o.get(a);if(c===$y)return new Fr({type:"lazy",getter:()=>o.get(a)});if(c!==void 0)return c;o.set(a,$y);let u=i(a),l=r(u,u!==a);return o.set(a,l),l}function i(a){let c=a._zod.def,u=c.type;switch(u){case"object":{let l=c.shape,d=Object.keys(l),p=!1,f={};for(let g of d){let y=n(l[g]);y!==l[g]&&(p=!0),f[g]=y}let m=c.catchall;return c.catchall&&(m=n(c.catchall),m!==c.catchall&&(p=!0)),p?J(a,{...c,shape:f,catchall:m}):a}case"array":{let l=n(c.element);return l===c.element?a:J(a,{...c,element:l})}case"tuple":{let l=c.items,d=!1,p=[];for(let m of l){let g=n(m);g!==m&&(d=!0),p.push(g)}let f=c.rest;return c.rest&&(f=n(c.rest),f!==c.rest&&(d=!0)),d?J(a,{...c,items:p,rest:f}):a}case"record":case"map":{let l=n(c.keyType),d=n(c.valueType);return l===c.keyType&&d===c.valueType?a:J(a,{...c,keyType:l,valueType:d})}case"set":{let l=n(c.valueType);return l===c.valueType?a:J(a,{...c,valueType:l})}case"union":{let l=c.options,d=!1,p=[];for(let f of l){let m=n(f);m!==f&&(d=!0),p.push(m)}return d?J(a,{...c,options:p}):a}case"intersection":{let l=n(c.left),d=n(c.right);return l===c.left&&d===c.right?a:J(a,{...c,left:l,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let l=n(c.innerType);return l===c.innerType?a:J(a,{...c,innerType:l})}case"pipe":{let l=n(c.in),d=n(c.out);return l===c.in&&d===c.out?a:J(a,{...c,in:l,out:d})}case"function":{let l=n(c.input),d=n(c.output);return l===c.input&&d===c.output?a:J(a,{...c,input:l,output:d})}case"lazy":{let l=c.getter,{_cachedInner:d,...p}=c;return J(a,{...p,getter:()=>n(l())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return a;default:return a}}return n(e)}function xy(e){return fi(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:tr(r.options)}})}function SI(e,t){if(!t?.length)return e;let r=e._zod.def;return J(e,Ge(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function wy(e){return SI(e.out,e.checks)}function II(e){return e.in._zod.traits.has("$ZodTransform")?wy(e):e.in}function _y(e){return fi(e,{pipe:t=>II(t._zod.def),default:(t,r)=>r?Qt(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function ky(e){return fi(e,{pipe:t=>wy(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var cm={};ut(cm,{bigint:()=>jI,boolean:()=>AI,date:()=>TI,number:()=>PI,string:()=>zI});function zI(e){return jl(Xn,e)}function PI(e){return Rl(Yn,e)}function AI(e){return Vl(Qn,e)}function jI(e){return Jl(er,e)}function TI(e){return nd(ii,e)}var jD=s.object({question:s.string().min(1).max(300),options:s.array(s.object({label:s.string().min(1).max(40),consequence:s.string().max(200).default("")})).min(2).max(4),recommended:s.number().int().nonnegative().optional(),danger:s.boolean().optional()});var Va=s.object({messageId:s.string().regex(de("message")),card:s.number().int().nonnegative().max(20),question:s.string().max(300).optional()});var rr=s.string().min(1).max(512).refine(CI,"Invalid path: use segments like notes/plan.md, without .. or a leading /");function CI(e){return/[\u0000-\u001f\u007f\\]/.test(e)?!1:e.split("/").every(r=>r.length>0&&r.length<=255&&r!=="."&&r!=="..")}var rn=s.string().regex(de("message")),X=s.string().regex(de("thread")),Te=s.string().regex(de("project")),Ce=s.string().regex(de("task")),gi=s.string().regex(de("artifact")),R=s.iso.datetime(),hi=s.enum(["user","agent","system"]),OI=s.object({path:rr,name:s.string(),size:s.number().int().nonnegative(),contentType:s.string()}),NI=s.object({artifactId:gi,version:s.number().int().positive(),title:s.string()}),Sy=s.enum(["cloud","local"]),ee=s.number().int().nonnegative(),DI=s.object({title:s.string(),harness:s.string(),runtime:Sy,model:s.string().nullable(),durationMs:ee,inputTokens:ee,outputTokens:ee,costMicros:ee.nullable()}),RI=s.object({chars:ee,limit:ee,parts:s.object({instructions:ee,skills:ee,knowledge:ee,brief:ee,conversation:ee,notes:ee,other:ee}),droppedMessages:ee,droppedNotes:ee,cut:s.boolean()}),EI=s.object({model:s.string(),durationMs:ee,calls:ee,inputTokens:ee,cachedInputTokens:ee,outputTokens:ee,costMicros:ee.nullable(),runtime:Sy,computer:s.string().optional(),harness:s.string().optional(),task:DI.optional(),prompt:RI.optional()}),UI=s.enum(["brief","follow_up","reply","relay","answer"]),MI=s.object({kind:UI,threadId:X,fromThreadId:X.optional(),note:s.string()}),Ka=8,on=s.object({id:rn,projectId:Te,threadId:X.nullable(),authorKind:hi,authorId:s.string().min(1),body:s.string(),attachments:s.array(OI).optional(),artifacts:s.array(NI).optional(),stats:EI.optional(),relay:MI.optional(),clis:s.array(s.string().max(40)).max(Ka).optional(),pick:Va.optional(),seq:s.number().int().positive(),createdAt:R,editedAt:R.optional()}),LI=s.enum(["working","blocked","review_ready","done","failed"]),Iy=s.enum(["decision","blocked","review"]),ZI=s.object({id:s.string().max(40),options:s.array(s.string().max(40)).max(Ka),by:s.enum(["person","coordinator"]),reason:s.string().max(300).nullable(),account:s.string().max(40).nullable().optional()}),FI=s.object({cli:s.string().max(40),model:s.string().max(200).nullable(),effort:s.string().max(20).nullable()}),zy="cloud",VI=s.object({id:s.string().max(60),by:s.enum(["person","auto","coordinator"]),reason:s.string().max(300).nullable().default(null)}),um=s.enum(["duplicate","misrouted","cancelled"]),KI=s.object({replies:ee,usage:s.object({tokens:ee,durationMs:ee,costMicros:ee.nullable()}).nullable(),planMessageId:rn.nullable()}),lm=s.object({id:X,projectId:Te,rootMessageId:rn,ackMessageId:rn.nullable().default(null),title:s.string(),status:LI,statusText:s.string().nullable(),needs:Iy.nullable().default(null),resolved:s.boolean(),closeReason:um.nullable().default(null),duplicateOf:X.nullable().default(null),label:s.string().nullable(),cli:ZI.nullable().default(null),runner:VI.nullable().default(null),model:FI.nullable().default(null),parentId:X.nullable().default(null),seenSeq:s.number().int().nonnegative().nullable().default(null),summary:KI.nullable().default(null),createdAt:R,updatedAt:R});var JI=s.enum(["running","done","failed","cancelled"]),Py=s.object({id:Ce,threadId:X,title:s.string(),harness:s.string(),backend:s.string(),status:JI,prUrl:s.string().nullable(),summary:s.string().nullable(),createdAt:R,finishedAt:R.nullable()}),UD=s.object({ref:s.string(),commits:s.array(s.object({hash:s.string(),message:s.string(),at:s.string()})),entries:s.array(s.object({name:s.string(),path:s.string(),type:s.enum(["file","folder"])})).nullable(),file:s.object({path:s.string(),text:s.string().nullable(),size:s.number(),truncated:s.boolean()}).nullable()}),dm=s.object({id:s.string().min(1).max(200),label:s.string().max(100),state:s.enum(["started","done","failed"]).optional(),model:s.string().max(200).optional(),tokens:s.number().int().nonnegative().optional()}),Ay=s.object({stream:s.enum(["stdout","stderr","system"]),text:s.string(),at:s.number().optional(),ms:s.number().nonnegative().optional(),tool:s.boolean().optional(),agent:dm.optional()}),pm=s.object({messageId:rn,emoji:s.string().min(1).max(32),authorKind:hi,authorId:s.string().min(1)}),Ja=s.enum(["owner","admin","member"]),BI=s.object({working:s.number().int().nonnegative(),waiting:s.number().int().nonnegative()}),WI=s.object({id:X,title:s.string(),state:s.enum(["working","queued","waiting","failed"]),needs:Iy.nullable(),step:s.string().nullable(),progress:s.string().nullable(),updatedAt:R}),GI=s.object({monthMicros:s.number().int().nonnegative(),totalMicros:s.number().int().nonnegative()}),Ba=s.enum(["indigo","blue","teal","green","amber","orange","red","pink","purple","gray"]),Wa=s.enum(["folder","rocket","code","terminal","globe","smartphone","server","database","cpu","bot","book","pen","palette","camera","music","gamepad","briefcase","cart","chart","shield","flask","leaf","heart","star","zap","home"]),MD=s.object({id:Te,name:s.string().min(1).max(120),role:Ja,icon:Wa.nullable().optional(),color:Ba.nullable().optional(),createdAt:R,activity:BI.optional(),live:s.array(WI).optional(),lastActivityAt:R.optional(),cost:GI.optional(),pinned:s.boolean().optional()}),LD=s.object({pinned:s.boolean()}),ZD=s.object({name:s.string().trim().min(1).max(120)}),FD=s.object({id:s.string(),name:s.string(),role:Ja,email:s.string().optional(),blocked:s.boolean().optional()}),mm=32e3,qI=s.object({id:s.number().int(),accountLogin:s.string(),accountType:s.enum(["User","Organization"]),accountAvatarUrl:s.string().nullable()}),VD=s.object({configured:s.boolean(),installUrl:s.string().nullable(),installations:s.array(qI)}),KD=s.object({id:s.number().int(),installationId:s.number().int(),fullName:s.string(),defaultBranch:s.string(),private:s.boolean(),description:s.string().nullable()}),JD=s.object({repoId:s.number().int(),installationId:s.number().int(),fullName:s.string(),defaultBranch:s.string(),private:s.boolean(),createdAt:R}),jy=s.object({repo:s.string(),number:s.number().int(),title:s.string(),state:s.enum(["open","closed"]),url:s.string(),author:s.string(),member:s.boolean(),labels:s.array(s.string()),comments:s.number().int(),createdAt:s.string(),updatedAt:s.string()}),BD=s.object({repo:s.string(),issues:s.array(jy),error:s.enum(["no_access","failed"]).optional()}),HI=s.object({author:s.string(),member:s.boolean(),body:s.string(),createdAt:s.string()}),WD=jy.extend({body:s.string(),commentList:s.array(HI),moreComments:s.boolean()}),Ty=s.object({repo:s.string(),number:s.number().int(),url:s.string(),threadId:X,title:s.string(),state:s.enum(["open","closed","merged"]),draft:s.boolean(),checks:s.enum(["pending","success","failure"]).nullable(),review:s.enum(["approved","changes_requested"]).nullable(),conflict:s.boolean().default(!1),branch:s.string().default(""),additions:s.number().int().nullable().default(null),deletions:s.number().int().nullable().default(null),changedFiles:s.number().int().nullable().default(null),createdAt:R.nullable().default(null),updatedAt:R}),XI=s.object({path:s.string(),previousPath:s.string().nullable(),status:s.enum(["added","removed","modified","renamed","copied","changed","unchanged"]),additions:s.number().int(),deletions:s.number().int(),patch:s.string().nullable()}),GD=s.object({files:s.array(XI),truncated:s.boolean(),nextPage:s.number().int().nullable().default(null)}),Cy=s.enum(["merge","squash","rebase"]),qD=s.object({permitted:s.boolean(),blocked:s.enum(["closed","draft","conflict","checks_failed","checks_pending","changes_requested","protected","checking"]).nullable(),methods:s.array(Cy),sha:s.string()}),HD=s.object({method:Cy,sha:s.string().min(1),deleteBranch:s.boolean().default(!1)}),XD=s.object({merged:s.literal(!0),branchDeleted:s.boolean(),branchKept:s.enum(["fork","default","protected","gone","in_use","reopened","failed"]).nullable()}),YD=s.object({installationId:s.number().int().positive(),repoId:s.number().int().positive()});var YI=16e3,QI=16e3,rR=25*1024*1024,Oy=10;var iR=s.object({path:rr,size:s.number().int().nonnegative(),contentType:s.string(),updatedAt:R,updatedByKind:hi,updatedBy:s.string()}),e0=s.string().trim().min(1).max(80).regex(/^[\p{L}\p{N}][\p{L}\p{N} _.-]*$/u,"Use letters, numbers, spaces, dots, dashes or underscores"),t0=s.enum(["ok","stale"]),n0=s.object({name:e0,description:s.string().max(300),content:s.string().max(QI),updatedAt:R,updatedByKind:hi,updatedBy:s.string(),status:t0.default("ok"),staleReason:s.string().max(300).nullable().default(null),verifiedAt:R.nullable().default(null),previousContent:s.string().nullable().default(null),previousAt:R.nullable().default(null)}),oR=n0.pick({description:!0,content:!0}),aR=s.discriminatedUnion("status",[s.object({status:s.literal("ok")}),s.object({status:s.literal("stale"),reason:s.string().trim().min(1).max(300)})]),r0=s.object({text:s.string().max(YI),updatedAt:R.nullable(),updatedBy:s.string().nullable()}),sR=r0.pick({text:!0}),Ny=s.enum(["files","memory","instructions"]),Dy=s.enum(["auto","on","off"]),cR=s.object({mode:Dy,active:s.boolean(),lastRunAt:R.nullable(),threadsSince:s.number().int().nonnegative(),threadsNeeded:s.number().int().positive(),threadId:s.string().nullable()}),uR=s.object({mode:Dy});var fm=s.object({id:gi,projectId:Te,threadId:X.nullable(),title:s.string(),description:s.string().nullable(),version:s.number().int().positive(),createdAt:R,updatedAt:R}),mR=s.object({version:s.number().int().positive(),size:s.number().int().nonnegative(),threadId:X.nullable(),createdAt:R}),fR=s.object({version:s.number().int().positive(),url:s.string().nullable(),expiresAt:R.nullable()}),gR=2*1024*1024;var gm=s.string().regex(de("routine")),i0=/^(\*|\d+(-\d+)?)(\/\d+)?(,(\*|\d+(-\d+)?)(\/\d+)?)*$/,o0=s.string().trim().refine(e=>{let t=e.split(/\s+/);return t.length===5&&t.every(r=>i0.test(r))},"Expected a five-field cron expression, e.g. 0 9 * * 1-5"),a0=s.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}},"Unknown time zone"),hm=s.discriminatedUnion("kind",[s.object({kind:s.literal("cron"),cron:o0,timezone:a0.default("UTC")}),s.object({kind:s.literal("once"),at:R})]),vm=s.discriminatedUnion("kind",[s.object({kind:s.literal("coordinator")}),s.object({kind:s.literal("thread"),threadId:X})]),ym=s.object({id:gm,projectId:Te,name:s.string(),prompt:s.string(),target:vm,schedule:hm,paused:s.boolean(),nextRunAt:R.nullable(),lastRunAt:R.nullable(),runCount:s.number().int().nonnegative(),createdBy:s.string(),createdAt:R});var $R=s.object({name:s.string().trim().min(1).max(120),prompt:s.string().trim().min(1).max(8e3),target:vm.default({kind:"coordinator"}),schedule:hm}),xR=s.object({name:s.string().trim().min(1).max(120),prompt:s.string().trim().min(1).max(8e3),target:vm,schedule:hm,paused:s.boolean()}).partial();var bm=s.object({text:s.string(),until:s.string(),createdBy:s.string(),createdAt:s.string(),wakes:s.number().int().nonnegative(),threads:s.number().int().nonnegative(),idle:s.number().int().nonnegative()});var s0=s.string().regex(de("sshHost")),$m=s.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Use lowercase letters, digits, - and _ (up to 40)."),Ga=s.string().trim().min(1).max(253).regex(/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*\.?|\[?[0-9A-Fa-f:.]+\]?)$/,"Enter a host name or IP address."),Ry=s.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/,"Enter the user name on the server."),Ey=s.enum(["ask","off"]),PR=s.string().max(16e3).regex(/^(?:ssh|ecdsa|sk)-[\w@.-]+ [A-Za-z0-9+/=]+(?: .*)?$/),Uy=s.string().max(200).regex(/^SHA256:[A-Za-z0-9+/=]+$/),c0=s.object({id:s0,projectId:Te,alias:$m,host:s.string(),port:s.number().int(),user:s.string(),runnerId:s.string(),runnerName:s.string(),mine:s.boolean(),keySource:s.enum(["new","existing"]),publicKey:s.string().nullable(),keyFingerprint:s.string().nullable(),hostFingerprint:s.string().nullable(),rule:Ey,testedAt:R.nullable(),createdAt:R}),u0=s.object({id:s.string(),alias:s.string(),threadId:s.string().nullable(),command:s.string(),reason:s.string().nullable(),decision:s.enum(["once","turn","deny","timeout","failed"]),approvedBy:s.string().nullable(),exitCode:s.number().int().nullable(),ms:s.number().int().nullable(),at:R}),AR=s.object({hosts:s.array(c0),history:s.array(u0)}),jR=s.object({runnerId:s.string(),alias:$m,host:Ga,port:s.number().int().min(1).max(65535).default(22),user:Ry,existingKey:s.string().min(1).max(1024).optional()}),TR=s.object({rule:Ey}),CR=s.object({hostKey:s.string().min(1).max(16e3)}),My=s.object({type:s.string().max(60),key:s.string().max(16e3),fingerprint:Uy}),Ly=s.object({path:s.string().max(1024),name:s.string().max(255),type:s.string().max(60),fingerprint:Uy,comment:s.string().max(500)}),Zy=s.object({exitCode:s.number().int().nullable(),stdout:s.string(),stderr:s.string(),truncated:s.boolean(),ms:s.number().int().nonnegative(),error:s.enum(["hostkey","auth","connect","timeout","nokey","other"]).optional()}),Fy=300*1e3,Vy=200*1024,qa=s.object({projectId:Te,alias:$m}),xm=qa.extend({host:Ga,port:s.number().int().min(1).max(65535),user:Ry,hostKey:s.string().min(1).max(16e3)});var Wy=2,Ve=s.string().regex(de("runner")),Ke=s.enum(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi","qwen"]),Xa={claude:"Claude Code",codex:"Codex CLI",antigravity:"Antigravity CLI",opencode:"OpenCode",hermes:"Hermes Agent",cursor:"Cursor CLI",muse:"Muse Code",kimi:"Kimi Code",qwen:"Qwen Code"},Gy=s.object({path:s.string().min(1).max(1024),name:s.string().max(255)}),l0=s.object({kind:s.string().max(40),usedPercent:s.number().min(0).max(1e3).nullable(),resetsAt:R.nullable()}),qy=s.object({status:s.enum(["ok","warning","limited"]).optional(),windows:s.array(l0).max(8),at:R});var d0=s.object({id:s.string().min(1).max(200),name:s.string().max(200),efforts:s.array(s.string().min(1).max(20)).max(10)});var Ot=s.string().regex(/^[a-z0-9][a-z0-9-]{0,39}$/);var p0=s.object({id:Ot,name:s.string().min(1).max(80),limits:qy.optional().catch(void 0)});var m0=s.object({id:Ke,version:s.string().max(200).nullable(),limits:qy.optional().catch(void 0),models:s.array(d0).max(100).optional().catch(void 0),accounts:s.array(p0).max(10).optional().catch(void 0),defaultAccount:s.string().min(1).max(80).optional().catch(void 0)}),f0=s.enum(["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","update","models","github-token","git-token","git-tokens","steer","steer-claude","ssh","stats","cli-accounts","shared-folder","coordinator"]),g0=s.discriminatedUnion("transport",[s.object({transport:s.literal("http"),name:s.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),path:s.string().regex(/^\/api\/[\w/-]+$/).max(300)}),s.object({transport:s.literal("stdio"),name:s.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),command:s.string().min(1).max(200),args:s.array(s.string().max(2e3)).max(50),env:s.record(s.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),s.string().max(4e3))})]),h0=s.enum(["read","edit","auto","full"]),_m=s.object({access:h0,worktrees:s.boolean(),autoUpdate:s.boolean(),remote:s.boolean()}),Hy=_m.omit({remote:!0}).partial(),v0=s.enum(["service","app","manual"]),wm=s.object({state:s.enum(["waiting","downloading","restarting","failed","rolled-back"]),version:s.string().max(50),running:s.number().int().nonnegative().optional(),message:s.string().max(500).optional(),at:R}),y0=s.object({status:s.enum(["ok","missing-libs","unknown"]),missing:s.array(s.string().max(80)).max(30).optional()});var Xy=s.object({version:s.string().max(50),hostname:s.string().max(255),platform:s.string().max(50),folders:s.array(Gy).max(200),clis:s.array(s.unknown()).max(10).transform(e=>e.flatMap(t=>{let r=m0.safeParse(t);return r.success?[r.data]:[]})),features:s.array(s.string().max(50)).max(40).default([]).transform(e=>e.filter(t=>f0.safeParse(t).success)),settings:_m.optional().catch(void 0),updates:v0.optional().catch(void 0),update:wm.optional().catch(void 0),browser:y0.optional().catch(void 0)}),an=s.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Ha=s.object({at:R,cpu:s.object({percent:s.number().min(0).max(100).optional(),cores:s.number().int().min(1).max(1024)}),memory:s.object({total:an,available:an}),swap:s.object({total:an,used:an}).optional(),disk:s.object({total:an,free:an}).optional(),tasks:s.number().int().nonnegative().max(1e3),runnerMemory:an.optional()}),vi=1e5,ne=s.string().min(1).max(64),b0=s.object({name:s.string().max(255),path:s.string().max(1024)}),$0=s.object({path:s.string().max(1024),parent:s.string().max(1024).nullable(),home:s.string().max(1024),dirs:s.array(b0).max(1e3)}),Ky=s.object({inputTokens:s.number().int().nonnegative(),outputTokens:s.number().int().nonnegative(),model:s.string().max(200).optional()}),km=512*1024,x0=s.object({path:s.string().max(4096),size:s.number().int().nonnegative(),data:s.string().max(Math.ceil(km/3)*4+4),truncated:s.boolean()}),w0=s.object({model:s.string().min(1).max(200).optional(),effort:s.string().min(1).max(20).optional()}),Jy=s.object({token:s.string().min(20).max(4096),expiresAt:R,repos:s.array(s.string().regex(/^[\w.-]+\/[\w.-]+$/).max(200)).max(100)}),By=Jy.extend({more:s.array(Jy).max(20).optional()}),UR=s.discriminatedUnion("type",[Xy.extend({type:s.literal("hello"),protocol:s.number().int().positive(),running:s.array(Ce).max(100).default([]),interrupted:s.array(Ce).max(100).default([]),stats:Ha.optional().catch(void 0)}),s.object({type:s.literal("task.progress"),taskId:Ce,text:s.string().max(2e3),usage:Ky.optional(),agent:dm.optional(),ms:s.number().nonnegative().optional()}),s.object({type:s.literal("task.done"),taskId:Ce,ok:s.boolean(),usage:Ky.optional(),result:s.string().max(vi),cancelled:s.boolean().optional()}),s.object({type:s.literal("ping"),stats:Ha.optional().catch(void 0)}),s.object({type:s.literal("task.folders"),taskId:Ce,folders:s.array(s.string().min(1).max(1024)).max(60)}),$0.extend({type:s.literal("dirs"),requestId:ne}),s.object({type:s.literal("folders"),requestId:ne,folders:s.array(Gy).max(200)}),s.object({type:s.literal("request.failed"),requestId:ne,message:s.string().max(500)}),x0.extend({type:s.literal("file"),requestId:ne}),s.object({type:s.literal("settings"),requestId:ne,settings:_m}),s.object({type:s.literal("update.accepted"),requestId:ne,update:wm}),s.object({type:s.literal("update.status"),update:wm.nullable()}),s.object({type:s.literal("task.steered"),requestId:ne,taken:s.boolean()}),s.object({type:s.literal("ssh.key"),requestId:ne,publicKey:s.string().max(16e3),fingerprint:s.string().max(200),protected:s.boolean()}),s.object({type:s.literal("ssh.keylist"),requestId:ne,keys:s.array(Ly).max(100)}),s.object({type:s.literal("ssh.hostkeylist"),requestId:ne,keys:s.array(My).max(10)}),Zy.extend({type:s.literal("ssh.result"),requestId:ne})]),Yy=s.discriminatedUnion("type",[s.object({type:s.literal("welcome"),runnerId:Ve,name:s.string()}),s.object({type:s.literal("task.start"),taskId:Ce,threadId:X,folder:s.string().min(1).max(1024),cli:Ke,prompt:s.string().min(1).max(vi),model:w0.optional(),reviewModel:s.string().min(1).max(200).optional(),account:Ot.optional(),folders:s.array(s.string().min(1).max(1024)).max(50).optional(),worktree:s.boolean().optional(),agent:s.object({mcpPath:s.string().regex(/^\/api\/[\w/-]+$/).max(300),token:s.string().min(20).max(200),connectors:s.array(g0).max(30).optional(),skills:s.object({path:s.string().regex(/^\/api\/[\w/-]+$/).max(300)}).optional(),resume:s.object({after:Ce,prompt:s.string().min(1).max(vi)}).optional()}).optional(),github:By.optional(),coordinator:s.object({system:s.string().min(1).max(vi)}).optional()}),s.object({type:s.literal("task.github"),taskId:Ce,github:By}),s.object({type:s.literal("task.steer"),requestId:ne,taskId:Ce,text:s.string().min(1).max(vi)}),s.object({type:s.literal("task.cancel"),taskId:Ce}),s.object({type:s.literal("pong")}),s.object({type:s.literal("dirs.list"),requestId:ne,path:s.string().max(1024).optional()}),s.object({type:s.literal("folder.share"),requestId:ne,path:s.string().min(1).max(1024)}),s.object({type:s.literal("folder.unshare"),requestId:ne,path:s.string().min(1).max(1024)}),s.object({type:s.literal("file.read"),requestId:ne,path:s.string().min(1).max(4096),folders:s.array(s.string().min(1).max(1024)).min(1).max(51),threadId:X.optional(),worktrees:s.boolean().optional()}),s.object({type:s.literal("settings.set"),requestId:ne,settings:Hy}),s.object({type:s.literal("runner.update"),requestId:ne,version:s.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/).max(50),now:s.boolean().default(!1)}),qa.extend({type:s.literal("ssh.keygen"),requestId:ne,comment:s.string().max(200),existing:s.string().min(1).max(1024).optional()}),s.object({type:s.literal("ssh.keys"),requestId:ne}),s.object({type:s.literal("ssh.hostkeys"),requestId:ne,host:Ga,port:s.number().int().min(1).max(65535)}),s.object({type:s.literal("ssh.test"),requestId:ne,target:xm}),s.object({type:s.literal("ssh.run"),requestId:ne,target:xm,command:s.string().min(1).max(2e4)}),qa.extend({type:s.literal("ssh.forget"),requestId:ne})]),_0=Xy.extend({id:Ve,name:s.string(),version:s.string().nullable(),online:s.boolean(),lastSeenAt:R.nullable(),createdAt:R,stats:Ha.optional()}),MR=s.object({name:s.string().trim().min(1).max(80).optional(),settings:Hy.optional()}),LR=s.object({now:s.boolean().default(!1)}),ZR=s.object({runners:s.array(_0),latestVersion:s.string().nullable()}),FR=s.object({code:s.string(),expiresAt:R}),VR=s.object({code:s.string().trim().min(4).max(20),name:s.string().trim().min(1).max(80),hostname:s.string().max(255).default(""),platform:s.string().max(50).default("")}),Qy=s.object({runner:s.object({id:Ve,name:s.string()}),token:s.string()}),KR=s.object({projectId:Te,runnerId:Ve,runnerName:s.string(),path:s.string(),folders:s.array(s.string()).default([]),cli:Ke,online:s.boolean(),isDefault:s.boolean().default(!0),stats:Ha.optional()}),JR=s.object({path:s.string().trim().min(1).max(1024)}),BR=s.object({runnerId:Ve,path:s.string().min(1).max(1024),cli:Ke,add:s.boolean().optional()}),WR=s.object({path:s.string().min(1).max(1024),runnerId:Ve.optional()}),GR=s.object({runnerId:Ve});function eb(e,t){let r=i=>i.split("-")[0].split(".").map(a=>Number.parseInt(a,10)||0),[o,n]=[r(e),r(t)];for(let i=0;i<3;i++)if((o[i]??0)!==(n[i]??0))return(o[i]??0)>(n[i]??0);return!1}var k0=200,S0=s.object({threadId:X.nullable(),hasEarlier:s.boolean()});var oE=s.discriminatedUnion("type",[s.object({type:s.literal("message.send"),clientId:s.string().max(64).optional(),threadId:X.nullable().default(null),body:s.string().trim().max(mm),attachments:s.array(rr).max(Oy).default([]),clis:s.array(Ke).max(Ka).optional(),pick:Va.optional()}).refine(e=>e.body.length>0||e.attachments.length>0,"Write something or attach a file"),s.object({type:s.literal("message.edit"),messageId:on.shape.id,body:s.string().trim().max(mm)}),s.object({type:s.literal("thread.resolve"),threadId:X,resolved:s.boolean(),reason:um.optional()}),s.object({type:s.literal("thread.cli"),threadId:X,cli:Ke.nullable(),account:Ot.nullable().optional()}),s.object({type:s.literal("thread.runner"),threadId:X,runnerId:s.union([Ve,s.literal(zy)]).nullable()}),s.object({type:s.literal("thread.model"),threadId:X,cli:Ke,model:s.string().trim().min(1).max(200).nullable(),effort:s.string().trim().min(1).max(20).nullable()}),s.object({type:s.literal("goal.stop")}),s.object({type:s.literal("sync"),afterSeq:s.number().int().nonnegative(),all:s.boolean().optional(),recent:s.number().int().positive().max(k0).optional()})]),aE=s.discriminatedUnion("type",[s.object({type:s.literal("message.created"),message:on}),s.object({type:s.literal("message.updated"),message:on}),s.object({type:s.literal("message.ack"),clientId:s.string(),messageId:on.shape.id,seq:on.shape.seq}),s.object({type:s.literal("sync.result"),messages:s.array(on),hasMore:s.boolean(),streamed:s.boolean().optional(),threads:s.array(lm).default([]),reactions:s.array(pm).default([]),artifacts:s.array(fm).default([]),routines:s.array(ym).default([]),goal:bm.nullable().optional(),windows:s.array(S0).optional(),reset:s.boolean().optional(),lastSeq:s.number().int().nonnegative().optional()}),s.object({type:s.literal("thread.updated"),thread:lm}),s.object({type:s.literal("reaction.added"),reaction:pm}),s.object({type:s.literal("artifact.updated"),artifact:fm}),s.object({type:s.literal("routine.updated"),routine:ym}),s.object({type:s.literal("routine.deleted"),routineId:gm}),s.object({type:s.literal("goal.updated"),goal:bm.nullable()}),s.object({type:s.literal("agent.activity"),threadId:X.nullable(),active:s.boolean(),label:s.string().max(200).optional()}),s.object({type:s.literal("knowledge.changed"),kind:Ny}),s.object({type:s.literal("workspace.changed")}),s.object({type:s.literal("task.updated"),task:Py}),s.object({type:s.literal("task.output"),taskId:Ce,threadId:X,lines:s.array(Ay)}),s.object({type:s.literal("pr.updated"),pullRequest:Ty}),s.object({type:s.literal("error"),code:s.string(),message:s.string()})]);var uE=s.object({app:s.literal("myrel"),apiVersion:s.number().int().positive(),name:s.string(),auth:s.object({emailPassword:s.boolean(),signUp:s.boolean().default(!0),emailVerification:s.boolean().default(!1),captcha:s.object({provider:s.literal("turnstile"),siteKey:s.string()}).nullable().default(null),passwordReset:s.boolean().default(!1)}),billing:s.boolean().default(!1),legal:s.object({terms:s.string().url(),privacy:s.string().url(),version:s.string()}).nullable().default(null)});var yi=s.enum(["fireworks","anthropic","openai"]),hE=s.object({id:yi,name:s.string(),defaultModel:s.string(),serverKey:s.boolean()}),vE=s.object({id:s.string(),provider:yi,label:s.string(),hint:s.string(),scope:s.enum(["user","instance"]),createdAt:s.iso.datetime()}),yE=s.object({provider:yi,label:s.string().trim().min(1).max(80),key:s.string().trim().min(8).max(500),scope:s.enum(["user","instance"]).default("user")}),tb=s.enum(["auto","local","cloud"]),nb=s.enum(["opencode","claude","codex"]),I0=s.object({model:s.string().trim().min(1).max(200).nullable(),effort:s.string().trim().min(1).max(20).nullable(),account:Ot.nullable().optional(),reviewModel:s.string().trim().min(1).max(200).nullable().optional()});var rb=s.partialRecord(Ke,s.string().trim().min(1).max(200)),Sm=s.partialRecord(Ke,I0),Ya=Sm,z0=["claude"],P0=s.enum(z0),A0=s.discriminatedUnion("mode",[s.object({mode:s.literal("model")}),s.object({mode:s.literal("cli"),runnerId:Ve,computer:s.string(),by:s.string(),cli:Ke,model:s.string().nullable(),effort:s.string().nullable(),account:Ot.nullable().catch(null).default(null)})]),j0=s.discriminatedUnion("mode",[s.object({mode:s.literal("model")}),s.object({mode:s.literal("cli"),runnerId:Ve,cli:P0,model:s.string().trim().min(1).max(200).nullable(),effort:s.string().trim().min(1).max(20).nullable(),account:Ot.nullable().optional()})]),bE=s.object({name:s.string(),provider:yi.nullable(),model:s.string().nullable(),keyId:s.string().nullable(),taskTarget:tb,icon:Wa.nullable().default(null),color:Ba.nullable().default(null),cloudCli:nb.default("opencode"),cliModels:Sm.default({}),visualCheck:s.boolean().default(!1),checkModels:Ya.default({}),worktrees:s.boolean().default(!0),coordinator:A0.catch({mode:"model"}).default({mode:"model"})}),$E=s.object({name:s.string().trim().min(1).max(120).optional(),provider:yi.nullable().optional(),model:s.string().trim().max(200).nullable().optional(),keyId:s.string().nullable().optional(),taskTarget:tb.optional(),icon:Wa.nullable().optional(),color:Ba.nullable().optional(),cloudCli:nb.optional(),cliModels:Sm.optional(),visualCheck:s.boolean().optional(),checkModels:Ya.optional(),worktrees:s.boolean().optional(),coordinator:j0.optional()}),ib=s.enum(["admin","member"]),xE=s.object({id:s.string(),projectId:s.string(),projectName:s.string(),email:s.string(),role:ib,invitedBy:s.string(),createdAt:s.iso.datetime()}),wE=s.object({email:s.email().trim().toLowerCase(),role:ib.default("member")}),_E=s.object({role:Ja}),T0=s.enum(["admin","user"]),kE=s.enum(["computer","decision"]),SE=s.object({id:s.string(),name:s.string(),email:s.string(),role:T0,onboarded:s.boolean().optional(),tips:s.array(s.string()).optional(),checkModels:Ya.optional(),reviewModels:rb.optional()}),IE=s.object({checkModels:Ya}),zE=s.object({reviewModels:rb}),C0=s.object({signUpEnabled:s.boolean()}),O0=s.enum(["api","agent","cron","web","desktop","mobile"]),PE=s.object({platform:s.enum(["web","desktop","mobile"]),where:s.string().trim().min(1).max(200),name:s.string().max(100).default("Error"),message:s.string().max(500),stack:s.string().max(4e3).optional(),version:s.string().max(40).optional()}),AE=s.object({id:s.string(),source:O0,where:s.string(),name:s.string(),message:s.string(),stack:s.string().nullable(),count:s.number().int(),firstSeenAt:s.number(),lastSeenAt:s.number()}),jE=s.object({days:s.number().int(),signedUp:s.number().int(),verified:s.number().int(),inProject:s.number().int(),asked:s.number().int(),threadRan:s.number().int(),pairedComputer:s.number().int()}),TE=C0.partial();var ob=s.string().regex(de("notification")),N0=s.enum(["done","ready","decision","blocked","failed"]),RE=s.object({id:ob,projectId:Te,threadId:X.nullable(),kind:N0,title:s.string(),body:s.string(),url:s.string(),readAt:R.nullable(),createdAt:R}),EE=s.object({email:s.boolean(),push:s.boolean()}),UE=s.object({webPushKey:s.string().nullable(),email:s.boolean()}),D0=[/^fcm\.googleapis\.com$/,/^updates\.push\.services\.mozilla\.com$/,/^web\.push\.apple\.com$/,/^[a-z0-9-]+\.notify\.windows\.com$/];function R0(e){try{let t=new URL(e);return t.protocol==="https:"&&D0.some(r=>r.test(t.hostname))}catch{return!1}}var ME=s.discriminatedUnion("kind",[s.object({kind:s.literal("webpush"),endpoint:s.url().max(2048).refine(R0,"Not a browser push service"),keys:s.object({p256dh:s.string().min(1).max(256),auth:s.string().min(1).max(64)})}),s.object({kind:s.literal("expo"),token:s.string().regex(/^Expo(nent)?PushToken\[[^\]]+\]$/).max(256)})]),LE=s.union([s.object({ids:s.array(ob).min(1).max(200)}),s.object({all:s.literal(!0)})]);var E0=new RegExp(de("thread").source.slice(1,-1)),BE=new RegExp(`^#(${E0.source})$`);var U0=s.enum(["http","stdio"]),M0=s.enum(["user","project"]),zm=s.enum(["cloud","local","both"]),L0=s.enum(["unknown","ok","error","needs_auth"]),Z0=s.enum(["none","headers","oauth"]),ab=s.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).refine(e=>e!=="myrel","That name is taken by Myrel's own tools."),F0=s.object({name:s.string(),description:s.string().optional()}),V0=/^[A-Za-z_][\w-]{0,99}$/,K0=/^[A-Za-z_][A-Za-z0-9_]{0,99}$/,sb=(e,t,r)=>s.record(s.string().regex(e),s.string().max(4e3),{error:o=>o.code==="invalid_key"?`${t} name ${JSON.stringify(o.input)} is not valid: use only ${r}, with no spaces or ":". Put the value in its own field.`:void 0}),cb=sb(V0,"Header","letters, digits, - and _"),J0=sb(K0,"Variable","letters, digits and _"),qE=s.object({id:s.string(),name:s.string(),slug:s.string(),scope:M0,transport:U0,url:s.string().nullable(),auth:Z0,command:s.string().nullable(),args:s.array(s.string()),runsOn:zm,secretNames:s.array(s.string()),enabled:s.boolean(),status:L0,lastError:s.string().nullable(),tools:s.array(F0),canEdit:s.boolean(),createdAt:s.iso.datetime(),official:s.object({id:s.string(),title:s.string(),iconUrl:s.string().nullable()}).nullable().default(null)}),Im=s.string().trim().min(1).max(60),HE=s.discriminatedUnion("transport",[s.object({transport:s.literal("http"),name:Im,slug:ab.optional(),url:s.url({protocol:/^https$/}).max(2e3),auth:s.enum(["headers","oauth"]).default("headers"),headers:cb.default({})}),s.object({transport:s.literal("stdio"),name:Im,slug:ab.optional(),command:s.string().trim().min(1).max(200),args:s.array(s.string().max(2e3)).max(50).default([]),env:J0.default({}),runsOn:zm.default("both")})]),XE=s.object({name:Im.optional(),enabled:s.boolean().optional(),url:s.url({protocol:/^https$/}).max(2e3).optional(),command:s.string().trim().min(1).max(200).optional(),args:s.array(s.string().max(2e3)).max(50).optional(),runsOn:zm.optional(),secrets:cb.optional()});var YE=s.object({authorizeUrl:s.url()});var B0=["developer","productivity","communication","design","data","sales","finance","search","ai","other"],ub=s.enum(B0);var W0=s.object({id:s.string(),title:s.string(),description:s.string(),websiteUrl:s.string().nullable(),iconUrl:s.string().nullable(),url:s.string(),auth:s.enum(["oauth","headers"]),headerHint:s.object({name:s.string(),placeholder:s.string()}).nullable(),category:ub,official:s.boolean()}),QE=s.object({connectors:s.array(W0),nextOffset:s.number().nullable(),syncedAt:s.iso.datetime().nullable(),categories:s.array(s.object({id:ub,count:s.number()}))}),G0=[{id:"com.notion/mcp",category:"productivity"},{id:"app.linear/linear",category:"productivity"},{id:"com.atlassian/atlassian-mcp-server",category:"productivity"},{id:"com.figma.mcp/mcp",category:"design"},{id:"com.stripe/mcp",category:"finance"},{id:"com.canva.mcp/mcp",category:"design"},{id:"com.vercel/vercel-mcp",category:"developer"},{id:"com.gitlab/mcp",category:"developer"},{id:"io.github.PostHog/mcp",category:"data"},{id:"com.zapier/mcp",category:"productivity"},{id:"com.airtable/mcp",category:"data"},{id:"com.monday/monday.com",category:"productivity"},{id:"com.paypal.mcp/mcp",category:"finance"},{id:"com.webflow/mcp",category:"design"},{id:"com.wix/mcp",category:"design"},{id:"com.neon/mcp",category:"developer"},{id:"com.railway/mcp",category:"developer"},{id:"co.huggingface/hf-mcp-server",category:"ai"},{id:"com.cloudflare.mcp/mcp",category:"developer"},{id:"com.apify/apify-mcp-server",category:"search"},{id:"ai.exa/exa",category:"search"},{id:"com.microsoft/microsoft-learn-mcp",category:"search"}],eU=G0.map(e=>e.id);var q0=s.enum(["user","project"]),H0=s.string().max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,"Use lowercase letters, digits and hyphens, like pdf-forms."),lb=s.string().trim().min(1).max(1024),X0=s.string().min(1).max(300).regex(/^[\w@+=,.~ -]+(\/[\w@+=,.~ -]+)*$/,"Invalid file path.").refine(e=>!e.split("/").some(t=>t==="."||t===".."),"Invalid file path."),db={files:200,bytes:5*1024*1024,fileBytes:1024*1024};var Y0=s.discriminatedUnion("kind",[s.object({kind:s.literal("write")}),s.object({kind:s.literal("upload")}),s.object({kind:s.literal("github"),repo:s.string(),path:s.string(),ref:s.string().optional(),commit:s.string()})]),Q0=s.object({path:s.string(),size:s.number().int().nonnegative()}),ez=s.object({id:s.string(),name:s.string(),description:s.string(),scope:q0,source:Y0,enabled:s.boolean(),files:s.array(Q0),size:s.number().int().nonnegative(),canEdit:s.boolean(),createdAt:s.iso.datetime(),updatedAt:s.iso.datetime()}),rU=ez.extend({skillMd:s.string()}),tz=s.object({path:X0,content:s.string().max(Math.ceil(db.fileBytes*4/3)+4)}),iU=s.discriminatedUnion("kind",[s.object({kind:s.literal("write"),name:H0,description:lb,instructions:s.string().max(1e5)}),s.object({kind:s.literal("upload"),files:s.array(tz).min(1).max(db.files)}),s.object({kind:s.literal("github"),source:s.string().trim().min(3).max(500),skill:s.string().max(64).optional()})]),oU=s.object({error:s.literal("choose_skill"),skills:s.array(s.object({name:s.string(),description:s.string(),path:s.string()}))}),aU=s.object({enabled:s.boolean().optional(),description:lb.optional(),instructions:s.string().max(1e5).optional()}),sU=s.object({skills:s.array(s.object({name:s.string(),files:s.array(s.object({path:s.string(),content:s.string()}))}))});var cU=s.object({on:s.boolean()});var nz=s.object({id:s.string().min(1).max(200),name:s.string().min(1).max(80),description:s.string().max(300).default(""),url:s.string().max(2e3),auth:s.enum(["oauth","headers"]),headerHint:s.object({name:s.string(),placeholder:s.string()}).nullable().default(null),iconUrl:s.string().nullable().default(null),official:s.boolean().default(!1),featured:s.boolean().default(!1)}),rz=s.enum(["open","connected","dismissed"]),dU=s.object({id:s.string(),reason:s.string().min(1).max(400),offers:s.array(nz).min(1).max(3),state:rz.default("open"),connected:s.string().optional(),signIn:s.boolean().optional()});var pU=s.object({offerId:s.string().min(1).max(200),headers:s.record(s.string().regex(/^[A-Za-z_][\w-]{0,99}$/),s.string().min(1).max(4e3)).optional()}),mU=s.object({authorizeUrl:s.string().optional(),connected:s.boolean()});var iz=s.enum(["running","passed","failed","partial","not_checked"]),Qa=s.number().int().min(1).max(10),hU=s.object({id:s.string(),round:s.number().int().min(1),status:iz,evaluatorThreadId:s.string().nullable().default(null),folder:s.string(),branch:s.string().max(255).optional(),evaluator:s.object({cli:s.string(),model:s.string(),effort:s.string().optional()}).optional(),vision:s.enum(["passed","failed","skipped"]).optional(),scores:s.object({functionality:Qa,craft:Qa,design:Qa,originality:Qa}).optional(),deterministic:s.object({shots:s.number(),blocking:s.number(),warnings:s.number()}).optional(),blocking:s.array(s.object({n:s.number().int().min(1).optional(),screen:s.string().max(200),problem:s.string().max(2e3),evidence:s.string().max(400),image:s.string().max(400).optional()})).max(20).default([]),acceptance:s.array(s.object({criterion:s.string().max(500),met:s.boolean()})).max(30).default([]),sheets:s.array(s.string().max(400)).max(12).default([]),diffs:s.array(s.string().max(400)).max(12).default([]),acceptedBy:s.string().max(120).optional(),baselineBy:s.string().max(120).optional(),summary:s.string().max(400).optional(),note:s.string().max(600).optional(),command:s.string().max(300).optional()});var vU=s.enum(["accept","baseline"]);var pb=s.enum(["running","budget","done","failed"]),oz=s.object({kind:s.enum(["search","read"]),text:s.string().max(400)}),$U=s.object({id:s.string(),title:s.string().max(200),status:pb,partial:s.enum(["budget","time","stopped"]).optional(),spentCents:s.number().int().nonnegative(),budgetCents:s.number().int().positive(),searches:s.number().int().nonnegative().default(0),pages:s.number().int().nonnegative().default(0),steps:s.array(oz).max(6).default([]),startedAt:s.string(),endedAt:s.string().optional(),model:s.string().max(80),approverName:s.string().max(120).optional(),stoppedBy:s.string().max(120).optional(),report:s.string().max(400).optional(),summary:s.string().max(600).optional(),note:s.string().max(600).optional()});var xU=s.enum(["stop"]),wU=s.object({id:s.string(),threadId:s.string(),threadTitle:s.string(),title:s.string(),status:pb,partial:s.enum(["budget","time","stopped"]).optional(),spentCents:s.number().int().nonnegative(),budgetCents:s.number().int().positive(),approverName:s.string().optional(),startedAt:s.string(),endedAt:s.string().optional(),report:s.string().optional()});var az=/^(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(\S[\s\S]*)$/;function ir(e){let t=az.exec(e.trim());return t?sz(t[1])??e:e}function sz(e){let t="",r=0;for(;r<e.length;){let o=e[r];if(o==="'"){let n=e.indexOf("'",r+1);if(n<0)return null;t+=e.slice(r+1,n),r=n+1}else if(o==='"'){for(r++;;){if(r>=e.length)return null;let n=e[r];if(n==='"')break;n==="\\"&&r+1<e.length&&'"\\$`\n'.includes(e[r+1])?(t+=e[r+1],r+=2):(t+=n,r++)}r++}else if(o==="\\"){if(r+1>=e.length)return null;t+=e[r+1],r+=2}else{if(/\s/.test(o)||"|&;<>()$`".includes(o))return null;t+=o,r++}}return t}var cz=s.enum(["spam","harassment","hate","sexual","violence","illegal","other"]),uz=1e3,lz=s.discriminatedUnion("kind",[s.object({kind:s.literal("message"),messageId:rn}),s.object({kind:s.literal("artifact"),artifactId:gi,version:s.number().int().positive().optional()})]),NU=s.object({target:lz,reason:cz,note:s.string().trim().max(uz).optional()});import{execFile as bz,spawn as $z}from"node:child_process";import{mkdir as xz}from"node:fs/promises";import{homedir as wz}from"node:os";import{join as jm,resolve as gb}from"node:path";import{mkdir as dz,readFile as pz,rename as mz,writeFile as fz}from"node:fs/promises";import{homedir as gz}from"node:os";import{basename as hz,join as Pm,resolve as fb}from"node:path";function Y(){return process.env.MYREL_RUNNER_HOME||Pm(gz(),".myrel-runner")}var Nt=()=>Pm(Y(),"config.json");async function me(){let e=await ve(Nt()),t={folders:[],access:"edit",...e};return process.env.MYREL_SERVER&&(t.server=process.env.MYREL_SERVER),process.env.MYREL_RUNNER_TOKEN&&(t.token=process.env.MYREL_RUNNER_TOKEN),t}var vz=["MYREL_RUNNER_TOKEN"],yz=["SSH_AUTH_SOCK"];function Ue(e){let t={...process.env,...e};for(let r of[...vz,...yz])delete t[r];return t}async function Oe(e){let t={...e};process.env.MYREL_RUNNER_TOKEN&&t.token===process.env.MYREL_RUNNER_TOKEN&&(t.token=(await ve(Nt()))?.token),await Xe(Nt(),t)}function ts(e,t){let r=fb(t);return e.folders.some(o=>o.path===r)?!1:(e.folders.push({path:r,name:hz(r)||r}),!0)}function ns(e,t){let r=fb(t),o=e.folders.length;return e.folders=e.folders.filter(n=>n.path!==r),e.folders.length!==o}var es=class{constructor(t=Pm(Y(),"sessions.json")){this.path=t}path;async get(t,r="claude",o){let n=(await ve(this.path))?.[mb(t,r,o)];return typeof n=="string"?{id:n}:n}async set(t,r,o,n){let i=await ve(this.path)??{};i[mb(t,r,n)]=o,await Xe(this.path,i)}},mb=(e,t,r)=>r?`${t}@${r}:${e}`:t==="claude"?e:`${t}:${e}`;async function ve(e){try{return JSON.parse(await pz(e,"utf8"))}catch(t){if(t.code==="ENOENT")return;throw t}}async function Xe(e,t){await dz(Y(),{recursive:!0,mode:448});let r=`${e}.${process.pid}.tmp`;await fz(r,`${JSON.stringify(t,null,2)}
|
|
63
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let c=a[1];if(t===a[0]){i(a);continue}if(e.external){let l=e.external.registry.get(a[0])?.id;if(t!==a[0]&&l){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(c.cycle){i(a);continue}c.count>1&&e.reused==="ref"&&i(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Rh(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let o of t){if(!o||typeof o!="object")return;Rh(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let a of Array.isArray(i)?i:[i]){if(typeof a!="string")return;r.includes(a)||r.push(a)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Eh=new Set(["type","properties","required","additionalProperties"]),Nh=["oneOf","anyOf"];function Dh(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function pd(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Eh.has(a))return null;t.push(i)}let r={},o=new Set;for(let i of t){for(let a in i.properties){if(Object.prototype.hasOwnProperty.call(r,a))continue;let c=[];for(let l of t){let d=l.properties?.[a]??Dh(l);d!=null&&(c.some(p=>JSON.stringify(p)===JSON.stringify(d))||c.push(d))}let u=c.length===1?c[0]:pd(c)??{allOf:c};fe(r,a,u)}for(let a of i.required??[])o.add(a)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),t.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let a of t){let c=Dh(a);c&&!i.some(u=>JSON.stringify(u)===JSON.stringify(c))&&i.push(c)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function eI(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Eh)if(n in e)return;let r=t.filter(n=>Nh.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=pd(t);else{let n=r[0],i=Nh.find(u=>Array.isArray(n[u]));if(Object.keys(n).length!==1)return;let a=t.filter(u=>u!==n),c=n[i].map(u=>pd([...a,u]));if(c.some(u=>!u))return;o={[i]:c}}o&&(delete e.allOf,Qr(e,o))}function Pt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=c=>{let u=e.seen.get(c);if(u.ref===null)return;let l=u.def??u.schema,d={...l},p=u.ref;if(u.ref=null,p){o(p);let m=e.seen.get(p),g=m.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(g)):Qr(l,g),Qr(l,d),c._zod.parent===p)for(let _ in l)_==="$ref"||_==="allOf"||_ in d||delete l[_];if(g.$ref&&m.def)for(let _ in l)_==="$ref"||_==="allOf"||_ in m.def&&JSON.stringify(l[_])===JSON.stringify(m.def[_])&&delete l[_]}let f=c._zod.parent;if(f&&f!==p){o(f);let m=e.seen.get(f);if(m?.schema.$ref&&(l.$ref=m.schema.$ref,m.def))for(let g in l)g==="$ref"||g==="allOf"||g in m.def&&JSON.stringify(l[g])===JSON.stringify(m.def[g])&&delete l[g]}e.override({zodSchema:c,jsonSchema:l,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let c of[...e.seen.entries()].reverse())o(c[0]);if(e.target!=="openapi-3.0")for(let c of e.seen.entries())Rh(c[1].def??c[1].schema);for(let c of e.deferred)c();if(e.intersections.length){let c=new Map;for(let u of e.seen.values())for(let l of[u.schema,u.def]){let d=l?.allOf;if(!Array.isArray(d))continue;let p=c.get(d);p?p.push(l):c.set(d,[l])}for(let u of e.intersections)for(let l of c.get(u)??[])eI(l)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let c=e.external.registry.get(t)?.id;if(!c)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(c)}Qr(n,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&n.id===i&&delete n.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let c of e.seen.entries()){let u=c[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,fe(a,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?n.$defs=a:n.definitions=a);try{let c=JSON.parse(JSON.stringify(n));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:Bn(t,"input",e.processors),output:Bn(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function we(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return we(o.element,r);if(o.type==="set")return we(o.valueType,r);if(o.type==="lazy")return we(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return we(o.innerType,r);if(o.type==="intersection")return we(o.left,r)||we(o.right,r);if(o.type==="record"||o.type==="map")return we(o.keyType,r)||we(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:we(o.in,r)||we(o.out,r);if(o.type==="object"){for(let n in o.shape)if(we(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(we(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(we(n,r))return!0;return!!(o.rest&&we(o.rest,r))}return!1}var md=(e,t={})=>r=>{let o=It({...r,processors:t});return W(e,o),zt(o,e),Pt(o,e)},Bn=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=It({...n??{},target:i,io:t,processors:r});return W(e,a),zt(a,e),Pt(a,e)};var Wn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Gn=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Uh=(e,t)=>{Wn(e,"minimum",t),Gn(e,"maximum",t)},Fh=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Vh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Kh=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Jh=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Mh=(e,t)=>Wn(e,"minimum",t.minimum),Lh=(e,t)=>Gn(e,"maximum",t.maximum),Zh=e=>(t,r)=>{Jh(t,r.format);let[o,n]=e[r.format];Wn(t,"minimum",o),Gn(t,"maximum",n)},tI={greater_than:(e,t)=>Wn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Gn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Fh(e,t.value),number_format:Zh($r),bigint_format:Zh(xr),min_length:Mh,max_length:Lh,length_equals:(e,t)=>Uh(e,t.length),min_size:Mh,max_size:Lh,size_equals:(e,t)=>Uh(e,t.size),string_format:(e,t)=>{Jh(e,t.format),t.pattern&&Vh(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Kh(e,t.mime)};function le(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)tI[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Wn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Wn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Gn(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Gn(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&Fh(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&Kh(t,n.mime);for(let i of n.patterns??[])Vh(t,i);return t}var nI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},rI=new Map([[fo,bc],[Ur,$c]]),Bh=e=>rI.get(e)??e,hd=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:a,format:c,patterns:u,contentEncoding:l,laxFormat:d}=le(e);if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),c&&(n.format=nI[c]??c,n.format===""&&delete n.format,(c==="time"||d)&&delete n.format),l&&(n.contentEncoding=l),u&&u.size>0){let p=[...u].map(Bh);p.length===1?n.pattern=p[0].source:p.length>1&&(n.allOf=[...p.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},vd=(e,t,r,o)=>{let n=r,{minimum:i,maximum:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l,isInt:d}=le(e);n.type=d?"integer":"number";let p=typeof l=="number"&&l>=(i??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),m=t.target==="draft-04"||t.target==="openapi-3.0";if(p?m?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof i=="number"&&(n.minimum=i),f?m?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),c){let g=new Set;for(let I of c)Number.isFinite(I)&&I!==0?g.add(Math.abs(I)):ue(e,t,n,o,`A multipleOf divisor of ${I} cannot be represented in JSON Schema`);let[y,..._]=g;y!==void 0&&(n.multipleOf=y),_.length&&(n.allOf=[...n.allOf??[],..._.map(I=>({multipleOf:I}))])}},yd=(e,t,r,o)=>{r.type="boolean"},bd=(e,t,r,o)=>{ue(e,t,r,o,"BigInt cannot be represented in JSON Schema")},$d=(e,t,r,o)=>{ue(e,t,r,o,"Symbols cannot be represented in JSON Schema")},xd=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},wd=(e,t,r,o)=>{ue(e,t,r,o,"Undefined cannot be represented in JSON Schema")},_d=(e,t,r,o)=>{ue(e,t,r,o,"Void cannot be represented in JSON Schema")},kd=(e,t,r,o)=>{r.not={}},Sd=(e,t,r,o)=>{},Id=(e,t,r,o)=>{},zd=(e,t,r,o)=>{ue(e,t,r,o,"Date cannot be represented in JSON Schema")},Pd=(e,t,r,o)=>{let n=e._zod.def,i=yn(n.entries);if(i.length===0){r.not={};return}i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Ad=(e,t,r,o)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let a of n.values)if(a===void 0){if(ue(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(ue(e,t,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},jd=(e,t,r,o)=>{ue(e,t,r,o,"NaN cannot be represented in JSON Schema")},Td=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},Cd=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:a,mime:c}=le(e);i!==void 0&&(n.minLength=i),a!==void 0&&(n.maxLength=a),c&&(c.length===0?n.not={}:c.length===1?n.contentMediaType=c[0]:n.anyOf=c.map(u=>({contentMediaType:u})))},Od=(e,t,r,o)=>{r.type="boolean"},Nd=(e,t,r,o)=>{ue(e,t,r,o,"Custom types cannot be represented in JSON Schema")},Dd=(e,t,r,o)=>{ue(e,t,r,o,"Function types cannot be represented in JSON Schema")},Rd=(e,t,r,o)=>{ue(e,t,r,o,"Transforms cannot be represented in JSON Schema")},Ed=(e,t,r,o)=>{ue(e,t,r,o,"Map cannot be represented in JSON Schema")},Ud=(e,t,r,o)=>{ue(e,t,r,o,"Set cannot be represented in JSON Schema")},Md=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:a,maximum:c}=le(e);typeof a=="number"&&(n.minItems=a),typeof c=="number"&&(n.maxItems=c),n.type="array",n.items=W(i.element,t,{...o,path:[...o.path,"items"]})};function ei(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?ei(t.out):t.type==="catch"?ei(t.innerType):e._zod.optin}var Ld=(e,t,r,o)=>{let n=r,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&ue(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let l in a)fe(n.properties,l,W(a[l],t,{...o,path:[...o.path,"properties",l]}));let u=[];for(let l of Object.keys(a)){let d=i.shape[l];(t.io==="input"?ei(d)===void 0:d._zod.optout===void 0)&&u.push(l)}u.length>0&&(n.required=u),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=W(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},da=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((c,u)=>W(c,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},Zd=(e,t,r,o)=>{let n=e._zod.def,i=W(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=W(n.right,t,{...o,path:[...o.path,"allOf",1]}),c=l=>"allOf"in l&&Object.keys(l).length===1,u=[...c(i)?i.allOf:[i],...c(a)?a.allOf:[a]];r.allOf=u,t.intersections.push(u)},Fd=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",c=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((y,_)=>W(y,t,{...o,path:[...o.path,a,_]})),l=i.rest?W(i.rest,t,{...o,path:[...o.path,c,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,d=i.items.length;for(;d>0;){let y=i.items[d-1];if(!(t.io==="input"?ei(y)!==void 0:y._zod.optout==="optional"))break;d--}let p=i.items.length,f=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,f?n.items=!1:l&&(n.items=l),d>0&&(n.minItems=d),f&&(n.maxItems=p)):t.target==="openapi-3.0"?(n.items={anyOf:u},l&&n.items.anyOf.push(l),d>0&&(n.minItems=d),f&&(n.maxItems=p)):(n.items=u,f?n.additionalItems=!1:l&&(n.additionalItems=l),d>0&&(n.minItems=d),f&&(n.maxItems=p));let{minimum:m,maximum:g}=le(e);typeof m=="number"&&(n.minItems=m),typeof g=="number"&&(n.maxItems=g)};function fd(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let y=fd(e,g,r);return y===g?t:y}for(let g of["anyOf","oneOf"]){let y=t[g];if(!Array.isArray(y))continue;let _=y.map(I=>fd(e,I,r));_.some((I,k)=>I!==y[k])&&(t={...t,[g]:_})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(g=>g==="number"||g==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(g=>typeof g=="number"))return t;let{minimum:a,maximum:c,exclusiveMinimum:u,exclusiveMaximum:l,multipleOf:d,format:p,id:f,...m}=t;return m.enum?m.enum=m.enum.map(g=>typeof g=="number"?String(g):g):typeof m.const=="number"&&(m.const=String(m.const)),n&&(m.type="string",i||(m.pattern=(o.includes("number")?pt:Tr).source)),m}var gd=new WeakMap;function iI(e){let t=new Map;for(let o of e.seen.values())o.def&&!t.has(o.schema)&&t.set(o.schema,o);let r=new Map;for(let o of gd.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=fd(t,i,new Set);a!==i&&r.set(i,a)}if(r.size)for(let o of e.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var Vd=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let a=i.keyType,c=le(a).patterns;if(i.mode==="loose"&&c&&c.size>0){let d=W(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of c)fe(n.patternProperties,Bh(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=W(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let d=gd.get(t);d||(d=[],gd.set(t,d),t.deferred.push(()=>iI(t))),d.push(e)}n.additionalProperties=W(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,l=t.io==="input"&&ei(i.valueType)!==void 0;if(u&&!i.partial&&!l){let d=[...u].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(n.required=d.map(String))}},Kd=(e,t,r,o)=>{let n=e._zod.def,i=W(n.innerType,t,o),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},Jd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Bd=Symbol();function Wh(e,t,r,o,n){let i=!1,a=JSON.stringify(e,(c,u)=>typeof u!="bigint"?u:(i=!0,null));return i?(ue(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),Bd):JSON.parse(a)}var Wd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=Wh(n.defaultValue,e,t,r,o);a!==Bd&&(r.default=a)},Gd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=Wh(n.defaultValue,e,t,r,o);a!==Bd&&(r._prefault=a)},qd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{ue(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=a},Hd=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?i?n.out:n.in:n.out;W(a,t,o);let c=t.seen.get(e);c.ref=a},Xd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},Yd=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},pa=(e,t,r,o)=>{let n=e._zod.def;W(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Qd=(e,t,r,o)=>{let n=e._zod.innerType;W(n,t,o);let i=t.seen.get(e);i.ref=n},la={string:hd,number:vd,boolean:yd,bigint:bd,symbol:$d,null:xd,undefined:wd,void:_d,never:kd,any:Sd,unknown:Id,date:zd,enum:Pd,literal:Ad,nan:jd,template_literal:Td,file:Cd,success:Od,custom:Nd,function:Dd,transform:Rd,map:Ed,set:Ud,array:Md,object:Ld,union:da,intersection:Zd,tuple:Fd,record:Vd,nullable:Kd,nonoptional:Jd,default:Wd,prefault:Gd,catch:qd,pipe:Hd,readonly:Xd,promise:Yd,optional:pa,lazy:Qd};function ma(e,t){if("_idmap"in e){let o=e,n=It({...t,processors:la}),i={};for(let u of o._idmap.entries()){let[l,d]=u;W(d,n)}let a={},c={registry:o,uri:t?.uri,defs:i};n.external=c;for(let u of o._idmap.entries()){let[l,d]=u;zt(n,d),fe(a,l,Pt(n,d))}if(Object.keys(i).length>0){let u=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:i}}return{schemas:a}}let r=It({...t,processors:la});return W(e,r),zt(r,e),Pt(r,e)}var fa=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=It({processors:la,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return W(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,zt(this.ctx,t);let o=Pt(this.ctx,t),{"~standard":n,...i}=o;return i}};var Gh={};var nr={};ut(nr,{ZodAny:()=>xp,ZodArray:()=>Sp,ZodBase64:()=>Oa,ZodBase64URL:()=>Na,ZodBigInt:()=>er,ZodBigIntFormat:()=>Ea,ZodBoolean:()=>Qn,ZodCIDRv4:()=>Ta,ZodCIDRv6:()=>Ca,ZodCUID:()=>ka,ZodCUID2:()=>Sa,ZodCatch:()=>Bp,ZodCodec:()=>li,ZodCreditCard:()=>mp,ZodCustom:()=>di,ZodCustomStringFormat:()=>tn,ZodDate:()=>ii,ZodDefault:()=>Lp,ZodDiscriminatedUnion:()=>zp,ZodE164:()=>Da,ZodEmail:()=>$a,ZodEmoji:()=>wa,ZodEnum:()=>Hn,ZodExactOptional:()=>Za,ZodFile:()=>Rp,ZodFunction:()=>nm,ZodGUID:()=>xa,ZodIBAN:()=>fp,ZodIPv4:()=>Aa,ZodIPv6:()=>ja,ZodISODate:()=>jt,ZodISODateTime:()=>At,ZodISODuration:()=>Ct,ZodISOTime:()=>Tt,ZodInstanceOf:()=>om,ZodIntersection:()=>Pp,ZodJWT:()=>Ra,ZodKSUID:()=>Pa,ZodLazy:()=>Qp,ZodLiteral:()=>Dp,ZodMAC:()=>pp,ZodMap:()=>Op,ZodNaN:()=>Gp,ZodNanoID:()=>_a,ZodNever:()=>_p,ZodNonOptional:()=>Fa,ZodNull:()=>bp,ZodNullable:()=>Mp,ZodNumber:()=>Yn,ZodNumberFormat:()=>nn,ZodObject:()=>ai,ZodOptional:()=>ci,ZodPipe:()=>ui,ZodPrefault:()=>Fp,ZodPreprocess:()=>qp,ZodPromise:()=>tm,ZodReadonly:()=>Hp,ZodRecord:()=>qn,ZodSet:()=>Np,ZodString:()=>Xn,ZodStringFormat:()=>q,ZodSuccess:()=>Jp,ZodSymbol:()=>vp,ZodTemplateLiteral:()=>Yp,ZodTransform:()=>Ep,ZodTuple:()=>jp,ZodType:()=>M,ZodULID:()=>Ia,ZodURL:()=>ri,ZodUUID:()=>it,ZodUndefined:()=>yp,ZodUnion:()=>si,ZodUnknown:()=>wp,ZodVoid:()=>kp,ZodXID:()=>za,ZodXor:()=>Ip,_ZodString:()=>ba,_default:()=>Zp,_function:()=>ay,any:()=>Ev,array:()=>oi,base64:()=>vv,base64url:()=>yv,bigint:()=>Cv,boolean:()=>hp,catch:()=>Wp,check:()=>sy,cidrv4:()=>gv,cidrv6:()=>hv,codec:()=>ny,creditCard:()=>$v,cuid:()=>sv,cuid2:()=>cv,currencyCode:()=>Iv,custom:()=>cy,date:()=>Mv,describe:()=>uy,discriminatedUnion:()=>Jv,e164:()=>bv,email:()=>Xh,emoji:()=>ov,enum:()=>Ma,exactOptional:()=>Up,file:()=>Yv,float32:()=>Pv,float64:()=>Av,function:()=>ay,guid:()=>Yh,hash:()=>zv,hex:()=>Sv,hostname:()=>kv,httpUrl:()=>iv,iban:()=>xv,instanceof:()=>dy,int:()=>va,int32:()=>jv,int64:()=>Ov,intersection:()=>Ap,invertCodec:()=>ry,ipv4:()=>pv,ipv6:()=>fv,json:()=>my,jwt:()=>wv,keyof:()=>Lv,ksuid:()=>dv,lazy:()=>em,literal:()=>Xv,looseObject:()=>Vv,looseRecord:()=>Wv,mac:()=>mv,map:()=>Gv,meta:()=>ly,nan:()=>ty,nanoid:()=>av,nativeEnum:()=>Hv,never:()=>Ua,nonoptional:()=>Kp,null:()=>$p,nullable:()=>ni,nullish:()=>Qv,number:()=>gp,object:()=>Zv,optional:()=>Qt,partialRecord:()=>Bv,pipe:()=>ya,prefault:()=>Vp,preprocess:()=>fy,promise:()=>oy,readonly:()=>Xp,record:()=>Cp,refine:()=>rm,set:()=>qv,strictObject:()=>Fv,string:()=>ti,stringFormat:()=>_v,stringbool:()=>py,success:()=>ey,superRefine:()=>im,symbol:()=>Dv,templateLiteral:()=>iy,transform:()=>La,tuple:()=>Tp,uint32:()=>Tv,uint64:()=>Nv,ulid:()=>uv,undefined:()=>Rv,union:()=>tr,unknown:()=>Yt,url:()=>rv,uuid:()=>Qh,uuidv4:()=>ev,uuidv6:()=>tv,uuidv7:()=>nv,void:()=>Uv,xid:()=>lv,xor:()=>Kv});var ga={};ut(ga,{endsWith:()=>Un,gt:()=>nt,gte:()=>Ee,includes:()=>Rn,length:()=>Ht,lowercase:()=>Nn,lt:()=>tt,lte:()=>Re,maxLength:()=>qt,maxSize:()=>St,mime:()=>Ln,minLength:()=>mt,minSize:()=>rt,multipleOf:()=>kt,negative:()=>aa,nonnegative:()=>ca,nonpositive:()=>sa,normalize:()=>Zn,overwrite:()=>He,positive:()=>oa,properties:()=>Mn,property:()=>ua,regex:()=>On,size:()=>Gt,slugify:()=>Jn,startsWith:()=>En,toLowerCase:()=>Vn,toUpperCase:()=>Kn,trim:()=>Fn,uppercase:()=>Dn});var qh=new WeakSet([Object.prototype,Error.prototype]);function ha(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}var Hh=(e,t)=>{Qs.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);qh.has(r)||(qh.add(r),ha(r,"format",o=>n=>zr(o,n)),ha(r,"flatten",o=>n=>Ir(o,n)),ha(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,bn,2)}),ha(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,bn,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},aI=h("ZodError",Hh),je=h("ZodError",Hh,void 0,{Parent:Error});var ep=kn(je),tp=Sn(je),np=In(je),rp=zn(je),ip=Ki(je),op=Ji(je),ap=Bi(je),sp=Wi(je),cp=Gi(je),up=qi(je),lp=Hi(je),dp=Xi(je);function cI(){pe.localeError||ie(jo())}function en(){pe.memoizer||ie({memoizer:Jr()})}var M=h("ZodType",(e,t)=>(cI(),D.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(b.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return J(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rm(e,t))},superRefine(e,t){return this.check(im(e,t))},overwrite(e){return this.check(He(e))},optional(){return Qt(this)},exactOptional(){return Up(this)},nullable(){return ni(this)},nullish(){return Qt(ni(this))},nonoptional(e){return Kp(this,e)},array(){return oi(this)},or(e){return tr([this,e])},and(e){return Ap(this,e)},transform(e){return ya(this,La(e))},default(e){return Zp(this,e)},prefault(e){return Vp(this,e)},catch(e){return Wp(this,e)},pipe(e){return ya(this,e)},readonly(){return Xp(this)},describe(e){let t=this.clone();return ge.add(t,{description:e}),t},meta(...e){if(e.length===0)return ge.get(this);let t=this.clone();return ge.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return b.hide(this,"~standard",{...co(this),jsonSchema:{input:Bn(this,"input"),output:Bn(this,"output")}})},set"~standard"(e){b.own(this,"~standard",e)},parse:function e(t,r){return ep(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await tp(this,t,r,{callee:e})},safeParse(e,t){return np(this,e,t)},async safeParseAsync(e,t){return rp(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){b.own(this,"spa",e)},validate(e,t){return Pr(this,e,t)},validateAsync(e,t){return Ar(this,e,t)},encode:function e(t,r){return ip(this,t,r,{callee:e})},decode:function e(t,r){return op(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await ap(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await sp(this,t,r,{callee:e})},safeEncode(e,t){return cp(this,e,t)},safeDecode(e,t){return up(this,e,t)},async safeEncodeAsync(e,t){return lp(this,e,t)},async safeDecodeAsync(e,t){return dp(this,e,t)},toJSONSchema(e){return md(this,{})(e)},get description(){return ge.get(this)?.description},get _def(){return this._zod.def}}),ba=h("_ZodString",(e,t)=>{Kt.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hd(e,r,o,n)},b.derived({format:e=>le(e).format??null,minLength:e=>le(e).minimum??null,maxLength:e=>le(e).maximum??null},{regex(...e){return this.check(On(...e))},includes(...e){return this.check(Rn(...e))},startsWith(...e){return this.check(En(...e))},endsWith(...e){return this.check(Un(...e))},min(...e){return this.check(mt(...e))},max(...e){return this.check(qt(...e))},length(...e){return this.check(Ht(...e))},nonempty(...e){return this.check(mt(1,...e))},lowercase(e){return this.check(Nn(e))},uppercase(e){return this.check(Dn(e))},trim(){return this.check(Fn())},normalize(...e){return this.check(Zn(...e))},toLowerCase(){return this.check(Vn())},toUpperCase(){return this.check(Kn())},slugify(){return this.check(Jn())}})),Xn=h("ZodString",(e,t)=>{Kt.init(e,t),ba.init(e,t)},{email(e){return this.check(Uo($a,e))},url(e){return this.check(Gr(ri,e))},jwt(e){return this.check(ia(Ra,e))},emoji(e){return this.check(Ko(wa,e))},guid(e){return this.check(Mo(xa,e))},uuid(e){return this.check(Lo(it,e))},uuidv4(e){return this.check(Zo(it,e))},uuidv6(e){return this.check(Fo(it,e))},uuidv7(e){return this.check(Vo(it,e))},nanoid(e){return this.check(Jo(_a,e))},cuid(e){return this.check(Bo(ka,e))},cuid2(e){return this.check(Wo(Sa,e))},ulid(e){return this.check(Go(Ia,e))},base64(e){return this.check(ta(Oa,e))},base64url(e){return this.check(na(Na,e))},xid(e){return this.check(qo(za,e))},ksuid(e){return this.check(Ho(Pa,e))},ipv4(e){return this.check(Xo(Aa,e))},ipv6(e){return this.check(Yo(ja,e))},cidrv4(e){return this.check(Qo(Ta,e))},cidrv6(e){return this.check(ea(Ca,e))},e164(e){return this.check(ra(Da,e))},datetime(e){return this.check(qr(At,e))},date(e){return this.check(Hr(jt,e))},time(e){return this.check(Xr(Tt,e))},duration(e){return this.check(Yr(Ct,e))}});function ti(e){return Al(Xn,e)}var q=h("ZodStringFormat",(e,t)=>{B.init(e,t),ba.init(e,t)}),At=h("ZodISODateTime",(e,t)=>{bu.init(e,t),q.init(e,t)}),jt=h("ZodISODate",(e,t)=>{$u.init(e,t),q.init(e,t)}),Tt=h("ZodISOTime",(e,t)=>{xu.init(e,t),q.init(e,t)}),Ct=h("ZodISODuration",(e,t)=>{wu.init(e,t),q.init(e,t)}),$a=h("ZodEmail",(e,t)=>{cu.init(e,t),q.init(e,t)});function Xh(e){return Uo($a,e)}var xa=h("ZodGUID",(e,t)=>{au.init(e,t),q.init(e,t)});function Yh(e){return Mo(xa,e)}var it=h("ZodUUID",(e,t)=>{su.init(e,t),q.init(e,t)});function Qh(e){return Lo(it,e)}function ev(e){return Zo(it,e)}function tv(e){return Fo(it,e)}function nv(e){return Vo(it,e)}var ri=h("ZodURL",(e,t)=>{du.init(e,t),q.init(e,t)});function rv(e){return Gr(ri,e)}function iv(e){return Gr(ri,{protocol:jr,hostname:wc,...b.normalizeParams(e)})}var wa=h("ZodEmoji",(e,t)=>{pu.init(e,t),q.init(e,t)});function ov(e){return Ko(wa,e)}var _a=h("ZodNanoID",(e,t)=>{mu.init(e,t),q.init(e,t)});function av(e){return Jo(_a,e)}var ka=h("ZodCUID",(e,t)=>{fu.init(e,t),q.init(e,t)});function sv(e){return Bo(ka,e)}var Sa=h("ZodCUID2",(e,t)=>{gu.init(e,t),q.init(e,t)});function cv(e){return Wo(Sa,e)}var Ia=h("ZodULID",(e,t)=>{hu.init(e,t),q.init(e,t)});function uv(e){return Go(Ia,e)}var za=h("ZodXID",(e,t)=>{vu.init(e,t),q.init(e,t)});function lv(e){return qo(za,e)}var Pa=h("ZodKSUID",(e,t)=>{yu.init(e,t),q.init(e,t)});function dv(e){return Ho(Pa,e)}var Aa=h("ZodIPv4",(e,t)=>{_u.init(e,t),q.init(e,t)});function pv(e){return Xo(Aa,e)}var pp=h("ZodMAC",(e,t)=>{Su.init(e,t),q.init(e,t)});function mv(e){return Tl(pp,e)}var ja=h("ZodIPv6",(e,t)=>{ku.init(e,t),q.init(e,t)});function fv(e){return Yo(ja,e)}var Ta=h("ZodCIDRv4",(e,t)=>{Iu.init(e,t),q.init(e,t)});function gv(e){return Qo(Ta,e)}var Ca=h("ZodCIDRv6",(e,t)=>{zu.init(e,t),q.init(e,t)});function hv(e){return ea(Ca,e)}var Oa=h("ZodBase64",(e,t)=>{Pu.init(e,t),q.init(e,t)});function vv(e){return ta(Oa,e)}var Na=h("ZodBase64URL",(e,t)=>{Au.init(e,t),q.init(e,t)});function yv(e){return na(Na,e)}var Da=h("ZodE164",(e,t)=>{ju.init(e,t),q.init(e,t)});function bv(e){return ra(Da,e)}var mp=h("ZodCreditCard",(e,t)=>{Tu.init(e,t),q.init(e,t)});function $v(e){return Cl(mp,e)}var fp=h("ZodIBAN",(e,t)=>{Cu.init(e,t),q.init(e,t)});function xv(e){return Ol(fp,e)}var Ra=h("ZodJWT",(e,t)=>{Ou.init(e,t),q.init(e,t)});function wv(e){return ia(Ra,e)}var tn=h("ZodCustomStringFormat",(e,t)=>{Nu.init(e,t),q.init(e,t)});function _v(e,t,r={}){return Xt(tn,e,t,r)}function kv(e){return Xt(tn,"hostname",xc,e)}function Sv(e){return Xt(tn,"hex",Rc,e)}function Iv(e){return Xt(tn,"currency_code",kc,e)}function zv(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Fe[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Xt(tn,o,n,t)}var Yn=h("ZodNumber",(e,t)=>{bo.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vd(e,r,o,n),e.isFinite=!0},b.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=le(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=le(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=le(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>le(e).format??null},{gt(e,t){return this.check(nt(e,t))},gte(e,t){return this.check(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},lt(e,t){return this.check(tt(e,t))},lte(e,t){return this.check(Re(e,t))},max(e,t){return this.check(Re(e,t))},int(e){return this.check(va(e))},safe(e){return this.check(va(e))},positive(e){return this.check(nt(0,e))},nonnegative(e){return this.check(Ee(0,e))},negative(e){return this.check(tt(0,e))},nonpositive(e){return this.check(Re(0,e))},multipleOf(e,t){return this.check(kt(e,t))},step(e,t){return this.check(kt(e,t))},finite(){return this}}));function gp(e){return Dl(Yn,e)}var nn=h("ZodNumberFormat",(e,t)=>{Du.init(e,t),Yn.init(e,t)});function va(e){return El(nn,e)}function Pv(e){return Ul(nn,e)}function Av(e){return Ml(nn,e)}function jv(e){return Ll(nn,e)}function Tv(e){return Zl(nn,e)}var Qn=h("ZodBoolean",(e,t)=>{Mr.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yd(e,r,o,n)});function hp(e){return Fl(Qn,e)}var er=h("ZodBigInt",(e,t)=>{$o.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bd(e,r,o,n)},b.derived({minValue:e=>le(e).minimum??null,maxValue:e=>le(e).maximum??null,format:e=>le(e).format??null},{gte(e,t){return this.check(Ee(e,t))},min(e,t){return this.check(Ee(e,t))},gt(e,t){return this.check(nt(e,t))},lt(e,t){return this.check(tt(e,t))},lte(e,t){return this.check(Re(e,t))},max(e,t){return this.check(Re(e,t))},positive(e){return this.check(nt(BigInt(0),e))},negative(e){return this.check(tt(BigInt(0),e))},nonpositive(e){return this.check(Re(BigInt(0),e))},nonnegative(e){return this.check(Ee(BigInt(0),e))},multipleOf(e,t){return this.check(kt(e,t))}}));function Cv(e){return Kl(er,e)}var Ea=h("ZodBigIntFormat",(e,t)=>{Ru.init(e,t),er.init(e,t)});function Ov(e){return Bl(Ea,e)}function Nv(e){return Wl(Ea,e)}var vp=h("ZodSymbol",(e,t)=>{Eu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$d(e,r,o,n)});function Dv(e){return Gl(vp,e)}var yp=h("ZodUndefined",(e,t)=>{Uu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wd(e,r,o,n)});function Rv(e){return ql(yp,e)}var bp=h("ZodNull",(e,t)=>{Mu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xd(e,r,o,n)});function $p(e){return Hl(bp,e)}var xp=h("ZodAny",(e,t)=>{Lu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sd(e,r,o,n)});function Ev(){return Xl(xp)}var wp=h("ZodUnknown",(e,t)=>{Zu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Id(e,r,o,n)});function Yt(){return Yl(wp)}var _p=h("ZodNever",(e,t)=>{Fu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kd(e,r,o,n)});function Ua(e){return Ql(_p,e)}var kp=h("ZodVoid",(e,t)=>{Vu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_d(e,r,o,n)});function Uv(e){return ed(kp,e)}var ii=h("ZodDate",(e,t)=>{Ku.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zd(e,r,o,n),e.min=(r,o)=>e.check(Ee(r,o)),e.max=(r,o)=>e.check(Re(r,o))},b.derived({minDate:e=>{let{minimum:t}=le(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=le(e);return t?new Date(t):null}},{}));function Mv(e){return td(ii,e)}var Sp=h("ZodArray",(e,t)=>{en(),Bu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Md(e,r,o,n),e.element=t.element},{min(e,t){return this.check(mt(e,t))},nonempty(e){return this.check(mt(1,e))},max(e,t){return this.check(qt(e,t))},length(e,t){return this.check(Ht(e,t))},unwrap(){return this.element}});function oi(e,t){return id(Sp,e,t)}function Lv(e){let t=e._zod.def.shape;return Ma(Object.keys(t))}var ai=h("ZodObject",(e,t)=>{en(),Wu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ld(e,r,o,n),b.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Ma(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(b.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Yt()}))},loose(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Yt()}))},strict(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Ua()}))},strip(){return this.clone(b.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return b.extend(this,e)},safeExtend(e){return b.safeExtend(this,e)},merge(e){return b.merge(this,e)},pick(e){return b.pick(this,e)},omit(e){return b.omit(this,e)},partial(...e){return b.partial(ci,this,e[0])},exactPartial(...e){return b.partial(Za,this,e[0],"exactPartial")},required(...e){return b.required(Fa,this,e[0])}});function Zv(e,t){let r={type:"object",shape:e??{},...b.normalizeParams(t)};return new ai(r)}function Fv(e,t){return new ai({type:"object",shape:e,catchall:Ua(),...b.normalizeParams(t)})}function Vv(e,t){return new ai({type:"object",shape:e,catchall:Yt(),...b.normalizeParams(t)})}var si=h("ZodUnion",(e,t)=>{Lr.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>da(e,r,o,n),e.options=t.options});function tr(e,t){return new si({type:"union",options:e,...b.normalizeParams(t)})}var Ip=h("ZodXor",(e,t)=>{si.init(e,t),Gu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>da(e,r,o,n),e.options=t.options});function Kv(e,t){return new Ip({type:"union",options:e,inclusive:!1,...b.normalizeParams(t)})}var zp=h("ZodDiscriminatedUnion",(e,t)=>{si.init(e,t),Hu.init(e,t)});function Jv(e,t,r){return new zp({type:"union",options:t,discriminator:e,...b.normalizeParams(r)})}var Pp=h("ZodIntersection",(e,t)=>{Xu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zd(e,r,o,n)});function Ap(e,t){return new Pp({type:"intersection",left:e,right:t})}var jp=h("ZodTuple",(e,t)=>{en(),xo.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fd(e,r,o,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new ci({type:"optional",innerType:t}))})}});function Tp(e,t,r){let o=t instanceof D,n=o?r:t,i=o?t:null;return new jp({type:"tuple",items:e,rest:i,...b.normalizeParams(n)})}var qn=h("ZodRecord",(e,t)=>{en(),Yu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Cp(e,t,r){return!t||!t._zod?new qn({type:"record",keyType:ti(),valueType:e,...b.normalizeParams(t)}):new qn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r)})}function Bv(e,t,r){return new qn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r),partial:!0})}function Wv(e,t,r){return new qn({type:"record",keyType:e,valueType:t,mode:"loose",...b.normalizeParams(r)})}var Op=h("ZodMap",(e,t)=>{en(),Qu.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ed(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(rt(...r)),e.nonempty=r=>e.check(rt(1,r)),e.max=(...r)=>e.check(St(...r)),e.size=(...r)=>e.check(Gt(...r))});function Gv(e,t,r){return new Op({type:"map",keyType:e,valueType:t,...b.normalizeParams(r)})}var Np=h("ZodSet",(e,t)=>{en(),el.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ud(e,r,o,n),e.min=(...r)=>e.check(rt(...r)),e.nonempty=r=>e.check(rt(1,r)),e.max=(...r)=>e.check(St(...r)),e.size=(...r)=>e.check(Gt(...r))});function qv(e,t){return new Np({type:"set",valueType:e,...b.normalizeParams(t)})}var Hn=h("ZodEnum",(e,t)=>{tl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Pd(e,o,n,i),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let a of o)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Hn({...t,checks:[],...b.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let a of o)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Hn({...t,checks:[],...b.normalizeParams(n),entries:i})}});function Ma(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Hn({type:"enum",entries:r,...b.normalizeParams(t)})}function Hv(e,t){return new Hn({type:"enum",entries:e,...b.normalizeParams(t)})}var Dp=h("ZodLiteral",(e,t)=>{nl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ad(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Xv(e,t){return new Dp({type:"literal",values:Array.isArray(e)?e:[e],...b.normalizeParams(t)})}var Rp=h("ZodFile",(e,t)=>{rl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cd(e,r,o,n),e.min=(r,o)=>e.check(rt(r,o)),e.max=(r,o)=>e.check(St(r,o)),e.mime=(r,o)=>e.check(Ln(Array.isArray(r)?r:[r],o))});function Yv(e){return od(Rp,e)}var Ep=h("ZodTransform",(e,t)=>{en(),il.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rd(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new wt(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(b.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=r.value),a.inst??(a.inst=e),r.issues.push(b.issue(a))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function La(e){return new Ep({type:"transform",transform:e})}var ci=h("ZodOptional",(e,t)=>{wo.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pa(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Qt(e){return new ci({type:"optional",innerType:e})}var Za=h("ZodExactOptional",(e,t)=>{ol.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pa(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Up(e){return new Za({type:"optional",innerType:e})}var Mp=h("ZodNullable",(e,t)=>{al.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ni(e){return new Mp({type:"nullable",innerType:e})}function Qv(e){return Qt(ni(e))}var Lp=h("ZodDefault",(e,t)=>{sl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Zp(e,t){return new Lp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var Fp=h("ZodPrefault",(e,t)=>{cl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Vp(e,t){return new Fp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var Fa=h("ZodNonOptional",(e,t)=>{ul.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Kp(e,t){return new Fa({type:"nonoptional",innerType:e,...b.normalizeParams(t)})}var Jp=h("ZodSuccess",(e,t)=>{ll.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Od(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ey(e){return new Jp({type:"success",innerType:e})}var Bp=h("ZodCatch",(e,t)=>{dl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>qd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wp(e,t){return new Bp({type:"catch",innerType:e,catchValue:typeof t=="function"?t:b.constantCatch(t)})}var Gp=h("ZodNaN",(e,t)=>{pl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jd(e,r,o,n)});function ty(e){return rd(Gp,e)}var ui=h("ZodPipe",(e,t)=>{_o.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hd(e,r,o,n),e.in=t.in,e.out=t.out});function ya(e,t){return new ui({type:"pipe",in:e,out:t})}var li=h("ZodCodec",(e,t)=>{ui.init(e,t),Zr.init(e,t)});function ny(e,t,r){return new li({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function ry(e){let t=e._zod.def;return new li({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var qp=h("ZodPreprocess",(e,t)=>{ui.init(e,t),ml.init(e,t)}),Hp=h("ZodReadonly",(e,t)=>{fl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Xp(e){return new Hp({type:"readonly",innerType:e})}var Yp=h("ZodTemplateLiteral",(e,t)=>{gl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Td(e,r,o,n)});function iy(e,t){return new Yp({type:"template_literal",parts:e,...b.normalizeParams(t)})}var Qp=h("ZodLazy",(e,t)=>{Fr.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Qd(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function em(e){return new Qp({type:"lazy",getter:e})}var tm=h("ZodPromise",(e,t)=>{vl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function oy(e){return new tm({type:"promise",innerType:e})}var nm=h("ZodFunction",(e,t)=>{hl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dd(e,r,o,n)});function ay(e){return new nm({type:"function",input:Array.isArray(e?.input)?Tp(e?.input):e?.input??oi(Yt()),output:e?.output??Yt()})}var di=h("ZodCustom",(e,t)=>{yl.init(e,t),M.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nd(e,r,o,n)});function sy(e){let t=new H({check:"custom"});return t._zod.check=e,t}function cy(e,t){return ad(di,e??(()=>!0),t)}function rm(e,t={}){return sd(di,e,t)}function im(e,t){return cd(e,t)}var uy=ud,ly=ld,om=h("ZodInstanceOf",(e,t)=>{di.init(e,t)},{properties(e,t){return this.check(Mn(e,t))}});function dy(e,t={}){let r=new om({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...b.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var py=(...e)=>dd({Codec:li,Boolean:Qn,String:Xn},...e);function my(e){let t=em(()=>tr([ti(e),gp(),hp(),$p(),oi(t),Cp(ti(),t)]));return t}function fy(e,t){return new qp({type:"pipe",in:La(e),out:t})}var uI={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function lI(e){ie({customError:e})}function dI(){return ie().customError}var am;am||(am={});var pi={};ut(pi,{ZodISODate:()=>jt,ZodISODateTime:()=>At,ZodISODuration:()=>Ct,ZodISOTime:()=>Tt,date:()=>mI,datetime:()=>pI,duration:()=>gI,time:()=>fI});function pI(e){return qr(At,e)}function mI(e){return Hr(jt,e)}function fI(e){return Xr(Tt,e)}function gI(e){return Yr(Ct,e)}var z={...nr,...ga,iso:pi},hI=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function vI(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function gy(e,t){return e.map((r,o)=>o<t?r:r.optional())}function yI(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function bI(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:yI(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function $I(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&i.length<t.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let a of i){let c=t.keySchema.safeParse(a);c.success||o.issues.push({code:"invalid_key",origin:"record",issues:c.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function sm(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let o=String(e);return`${r[0]}${o.length}:${o}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let i=[];for(let a of e){let c=sm(a,t);if(c===null)return null;i.push(c)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let a=sm(e[i],t);if(a===null)return null;n.push(`${i.length}:${i}=${a}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var xI=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),wI=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function mi(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(mi):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>xI.has(t)?mi(r):!wI.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(mi))}function hy(e){return e===1?"element":"elements"}function _I(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let i=new Map;for(let a=0;a<n.length;a++){let c=sm(n[a],new Set);if(c===null)continue;let u=i.get(c);if(u===void 0){i.set(c,a);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${a} duplicates the one at index ${u}`,input:n,path:[a],continue:!0})}}if(t.containsSchema){let i=t.minContains??1,a=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,c=0;for(let u of n)if(t.containsSchema.safeParse(u).success&&++c>=a)break;c<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${hy(i)}; found ${c}`,input:n,continue:!0}),t.maxContains!==void 0&&c>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${hy(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function vy(e,t){if(e!==!1)return e===void 0||e===!0?z.any():_e(e,t)}var kI=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function yy(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return z.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=bI(n,t),a=_e(i,t);return t.refs.set(n,a),t.processing.delete(n),a}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return z.null();if(n.length===0)return z.never();if(n.length===1)return z.literal(n[0]);if(n.every(a=>typeof a=="string"))return z.enum(n);let i=n.map(a=>z.literal(a));return i.length<2?i[0]:z.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return z.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let a={...e,type:i};return yy(a,t)});return n.length===0?z.never():n.length===1?n[0]:z.union(n)}if(!r)return z.any();let o;switch(r){case"string":{let n=z.string();if(e.format){let i=e.format;i==="email"?n=n.check(z.email()):i==="uri"||i==="uri-reference"?n=n.check(z.url()):i==="uuid"||i==="guid"?n=n.check(z.uuid()):i==="date-time"?n=n.check(z.iso.datetime({offset:!0})):i==="date"?n=n.check(z.iso.date()):i==="time"?n=n.check(z.regex(kI)):i==="duration"?n=n.check(z.iso.duration()):i==="hostname"?n=n.check(z.hostname()):i==="ipv4"?n=n.check(z.ipv4()):i==="ipv6"?n=n.check(z.ipv6()):i==="mac"?n=n.check(z.mac()):i==="cidr"?n=n.check(z.cidrv4()):i==="cidr-v6"?n=n.check(z.cidrv6()):i==="base64"?n=n.check(z.base64()):i==="base64url"?n=n.check(z.base64url()):i==="e164"?n=n.check(z.e164()):i==="credit_card"?n=n.check(z.creditCard()):i==="iban"?n=n.check(z.iban()):i==="jwt"?n=n.check(z.jwt()):i==="emoji"?n=n.check(z.emoji()):i==="nanoid"?n=n.check(z.nanoid()):i==="cuid"?n=n.check(z.cuid()):i==="cuid2"?n=n.check(z.cuid2()):i==="ulid"?n=n.check(z.ulid()):i==="xid"?n=n.check(z.xid()):i==="ksuid"&&(n=n.check(z.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?z.number().int():z.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=z.boolean();break}case"null":{o=z.null();break}case"object":{let n={},i=e.properties||{},a=new Set(e.required||[]),c=typeof e.additionalProperties=="object"?_e(e.additionalProperties,t):void 0;for(let[p,f]of Object.entries(i)){let m=_e(f,t);fe(n,p,a.has(p)?m:m.optional())}if(e.patternProperties){let p=e.patternProperties,f=Object.keys(p),m=[];for(let y of f){let _=_e(p[y],t),I=z.string().regex(new RegExp(y));m.push(z.looseRecord(I,_))}let g=[];if(Object.keys(n).length>0&&g.push(z.object(n).passthrough()),g.push(...m),g.length===0)o=z.object({}).passthrough();else if(g.length===1)o=g[0];else{let y=z.intersection(g[0],g[1]);for(let _=2;_<g.length;_++)y=z.intersection(y,g[_]);o=y}if(e.additionalProperties===!1){let y=Object.keys(n),_=f.map(k=>new RegExp(k)),I=o;o=o.check(k=>{if(!Le(k.value))return;let A=[];for(let Z of Object.keys(k.value))y.includes(Z)||_.some(C=>C.test(Z))||A.push(Z);A.length&&k.issues.push({code:"unrecognized_keys",keys:A,input:k.value,inst:I})})}}else{let p=z.object(n);e.additionalProperties===!1?o=p.strict():c?o=p.catchall(c):o=p.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,l=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||l!==void 0||d!==void 0){let p;if(u){let f=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=_e(f,t)}o=$I(o,{keySchema:p,minProperties:l,maxProperties:d})}break}case"array":{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems=="number"?e.minItems:0,c=n.map(p=>_e(p,t)),u=gy(c,a),l=Array.isArray(i)?void 0:vy(i,t),d=z.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(Array.isArray(i)){let a=typeof e.minItems=="number"?e.minItems:0,c=i.map(p=>_e(p,t)),u=gy(c,a),l=vy(e.additionalItems,t),d=z.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(i!==void 0){let a=_e(i,t),c=z.array(a);typeof e.minItems=="number"&&(c=c.min(e.minItems)),typeof e.maxItems=="number"&&(c=c.max(e.maxItems)),o=c}else o=z.array(z.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=_I(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?_e(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function _e(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r=yy(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let c=e.anyOf.map(l=>_e(l,t)),u=z.union(c);r=o?z.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let c=e.oneOf.map(l=>_e(l,t)),u=z.xor(c);r=o?z.intersection(r,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:z.any();else{let c=o?r:_e(e.allOf[0],t),u=o?0:1;for(let l=u;l<e.allOf.length;l++)c=z.intersection(c,_e(e.allOf[l],t));r=c}e.nullable===!0&&t.version==="openapi-3.0"&&(r=z.nullable(r)),e.readOnly===!0&&(r=z.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let c of i)c in e&&(n[c]=e[c]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let c of a)c in e&&(n[c]=e[c]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!mi(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let c of["minProperties","maxProperties"])e[c]!==void 0&&(n[c]=e[c])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!mi(e.contains)&&(n.contains=e.contains);for(let c of["uniqueItems","minContains","maxContains"])e[c]!==void 0&&(n[c]=e[c])}for(let c of Object.keys(e))hI.has(c)||fe(n,c,e[c]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function by(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=vI(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??ge};return _e(r,i)}var $y=Symbol("z.visit/resolving");function fi(e,t){let r=typeof t=="function"?t:(a,c)=>{let u=t[a._zod.def.type];return u?u(a,c):a},o=new Map;function n(a){let c=o.get(a);if(c===$y)return new Fr({type:"lazy",getter:()=>o.get(a)});if(c!==void 0)return c;o.set(a,$y);let u=i(a),l=r(u,u!==a);return o.set(a,l),l}function i(a){let c=a._zod.def,u=c.type;switch(u){case"object":{let l=c.shape,d=Object.keys(l),p=!1,f={};for(let g of d){let y=n(l[g]);y!==l[g]&&(p=!0),f[g]=y}let m=c.catchall;return c.catchall&&(m=n(c.catchall),m!==c.catchall&&(p=!0)),p?J(a,{...c,shape:f,catchall:m}):a}case"array":{let l=n(c.element);return l===c.element?a:J(a,{...c,element:l})}case"tuple":{let l=c.items,d=!1,p=[];for(let m of l){let g=n(m);g!==m&&(d=!0),p.push(g)}let f=c.rest;return c.rest&&(f=n(c.rest),f!==c.rest&&(d=!0)),d?J(a,{...c,items:p,rest:f}):a}case"record":case"map":{let l=n(c.keyType),d=n(c.valueType);return l===c.keyType&&d===c.valueType?a:J(a,{...c,keyType:l,valueType:d})}case"set":{let l=n(c.valueType);return l===c.valueType?a:J(a,{...c,valueType:l})}case"union":{let l=c.options,d=!1,p=[];for(let f of l){let m=n(f);m!==f&&(d=!0),p.push(m)}return d?J(a,{...c,options:p}):a}case"intersection":{let l=n(c.left),d=n(c.right);return l===c.left&&d===c.right?a:J(a,{...c,left:l,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let l=n(c.innerType);return l===c.innerType?a:J(a,{...c,innerType:l})}case"pipe":{let l=n(c.in),d=n(c.out);return l===c.in&&d===c.out?a:J(a,{...c,in:l,out:d})}case"function":{let l=n(c.input),d=n(c.output);return l===c.input&&d===c.output?a:J(a,{...c,input:l,output:d})}case"lazy":{let l=c.getter,{_cachedInner:d,...p}=c;return J(a,{...p,getter:()=>n(l())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return a;default:return a}}return n(e)}function xy(e){return fi(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:tr(r.options)}})}function SI(e,t){if(!t?.length)return e;let r=e._zod.def;return J(e,Ge(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function wy(e){return SI(e.out,e.checks)}function II(e){return e.in._zod.traits.has("$ZodTransform")?wy(e):e.in}function _y(e){return fi(e,{pipe:t=>II(t._zod.def),default:(t,r)=>r?Qt(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function ky(e){return fi(e,{pipe:t=>wy(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var cm={};ut(cm,{bigint:()=>jI,boolean:()=>AI,date:()=>TI,number:()=>PI,string:()=>zI});function zI(e){return jl(Xn,e)}function PI(e){return Rl(Yn,e)}function AI(e){return Vl(Qn,e)}function jI(e){return Jl(er,e)}function TI(e){return nd(ii,e)}var TD=s.object({question:s.string().min(1).max(300),options:s.array(s.object({label:s.string().min(1).max(40),consequence:s.string().max(200).default("")})).min(2).max(4),recommended:s.number().int().nonnegative().optional(),danger:s.boolean().optional()});var Va=s.object({messageId:s.string().regex(de("message")),card:s.number().int().nonnegative().max(20),question:s.string().max(300).optional()});var rr=s.string().min(1).max(512).refine(CI,"Invalid path: use segments like notes/plan.md, without .. or a leading /");function CI(e){return/[\u0000-\u001f\u007f\\]/.test(e)?!1:e.split("/").every(r=>r.length>0&&r.length<=255&&r!=="."&&r!=="..")}var rn=s.string().regex(de("message")),X=s.string().regex(de("thread")),Te=s.string().regex(de("project")),Ce=s.string().regex(de("task")),gi=s.string().regex(de("artifact")),R=s.iso.datetime(),hi=s.enum(["user","agent","system"]),OI=s.object({path:rr,name:s.string(),size:s.number().int().nonnegative(),contentType:s.string()}),NI=s.object({artifactId:gi,version:s.number().int().positive(),title:s.string()}),Sy=s.enum(["cloud","local"]),ee=s.number().int().nonnegative(),DI=s.object({title:s.string(),harness:s.string(),runtime:Sy,model:s.string().nullable(),durationMs:ee,inputTokens:ee,outputTokens:ee,costMicros:ee.nullable()}),RI=s.object({chars:ee,limit:ee,parts:s.object({instructions:ee,skills:ee,knowledge:ee,brief:ee,conversation:ee,notes:ee,other:ee}),droppedMessages:ee,droppedNotes:ee,cut:s.boolean()}),EI=s.object({model:s.string(),durationMs:ee,calls:ee,inputTokens:ee,cachedInputTokens:ee,outputTokens:ee,costMicros:ee.nullable(),runtime:Sy,computer:s.string().optional(),harness:s.string().optional(),task:DI.optional(),prompt:RI.optional()}),UI=s.enum(["brief","follow_up","reply","relay","answer"]),MI=s.object({kind:UI,threadId:X,fromThreadId:X.optional(),note:s.string()}),Ka=8,on=s.object({id:rn,projectId:Te,threadId:X.nullable(),authorKind:hi,authorId:s.string().min(1),body:s.string(),attachments:s.array(OI).optional(),artifacts:s.array(NI).optional(),stats:EI.optional(),relay:MI.optional(),clis:s.array(s.string().max(40)).max(Ka).optional(),pick:Va.optional(),seq:s.number().int().positive(),createdAt:R,editedAt:R.optional()}),LI=s.enum(["working","blocked","review_ready","done","failed"]),Iy=s.enum(["decision","blocked","review"]),ZI=s.object({id:s.string().max(40),options:s.array(s.string().max(40)).max(Ka),by:s.enum(["person","coordinator"]),reason:s.string().max(300).nullable(),account:s.string().max(40).nullable().optional()}),FI=s.object({cli:s.string().max(40),model:s.string().max(200).nullable(),effort:s.string().max(20).nullable()}),zy="cloud",VI=s.object({id:s.string().max(60),by:s.enum(["person","auto","coordinator"]),reason:s.string().max(300).nullable().default(null)}),um=s.enum(["duplicate","misrouted","cancelled"]),KI=s.object({replies:ee,usage:s.object({tokens:ee,durationMs:ee,costMicros:ee.nullable()}).nullable(),planMessageId:rn.nullable()}),lm=s.object({id:X,projectId:Te,rootMessageId:rn,ackMessageId:rn.nullable().default(null),title:s.string(),status:LI,statusText:s.string().nullable(),needs:Iy.nullable().default(null),resolved:s.boolean(),closeReason:um.nullable().default(null),duplicateOf:X.nullable().default(null),label:s.string().nullable(),cli:ZI.nullable().default(null),runner:VI.nullable().default(null),model:FI.nullable().default(null),parentId:X.nullable().default(null),seenSeq:s.number().int().nonnegative().nullable().default(null),summary:KI.nullable().default(null),createdAt:R,updatedAt:R});var JI=s.enum(["running","done","failed","cancelled"]),Py=s.object({id:Ce,threadId:X,title:s.string(),harness:s.string(),backend:s.string(),status:JI,prUrl:s.string().nullable(),summary:s.string().nullable(),createdAt:R,finishedAt:R.nullable()}),MD=s.object({ref:s.string(),commits:s.array(s.object({hash:s.string(),message:s.string(),at:s.string()})),entries:s.array(s.object({name:s.string(),path:s.string(),type:s.enum(["file","folder"])})).nullable(),file:s.object({path:s.string(),text:s.string().nullable(),size:s.number(),truncated:s.boolean()}).nullable()}),dm=s.object({id:s.string().min(1).max(200),label:s.string().max(100),state:s.enum(["started","done","failed"]).optional(),model:s.string().max(200).optional(),tokens:s.number().int().nonnegative().optional()}),Ay=s.object({stream:s.enum(["stdout","stderr","system"]),text:s.string(),at:s.number().optional(),ms:s.number().nonnegative().optional(),tool:s.boolean().optional(),agent:dm.optional()}),pm=s.object({messageId:rn,emoji:s.string().min(1).max(32),authorKind:hi,authorId:s.string().min(1)}),Ja=s.enum(["owner","admin","member"]),BI=s.object({working:s.number().int().nonnegative(),waiting:s.number().int().nonnegative()}),WI=s.object({id:X,title:s.string(),state:s.enum(["working","queued","waiting","failed"]),needs:Iy.nullable(),step:s.string().nullable(),progress:s.string().nullable(),updatedAt:R}),GI=s.object({monthMicros:s.number().int().nonnegative(),totalMicros:s.number().int().nonnegative()}),Ba=s.enum(["indigo","blue","teal","green","amber","orange","red","pink","purple","gray"]),Wa=s.enum(["folder","rocket","code","terminal","globe","smartphone","server","database","cpu","bot","book","pen","palette","camera","music","gamepad","briefcase","cart","chart","shield","flask","leaf","heart","star","zap","home"]),LD=s.object({id:Te,name:s.string().min(1).max(120),role:Ja,icon:Wa.nullable().optional(),color:Ba.nullable().optional(),createdAt:R,activity:BI.optional(),live:s.array(WI).optional(),lastActivityAt:R.optional(),cost:GI.optional(),pinned:s.boolean().optional()}),ZD=s.object({pinned:s.boolean()}),FD=s.object({name:s.string().trim().min(1).max(120)}),VD=s.object({id:s.string(),name:s.string(),role:Ja,email:s.string().optional(),blocked:s.boolean().optional()}),mm=32e3,qI=s.object({id:s.number().int(),accountLogin:s.string(),accountType:s.enum(["User","Organization"]),accountAvatarUrl:s.string().nullable()}),KD=s.object({configured:s.boolean(),installUrl:s.string().nullable(),installations:s.array(qI)}),JD=s.object({id:s.number().int(),installationId:s.number().int(),fullName:s.string(),defaultBranch:s.string(),private:s.boolean(),description:s.string().nullable()}),BD=s.object({repoId:s.number().int(),installationId:s.number().int(),fullName:s.string(),defaultBranch:s.string(),private:s.boolean(),createdAt:R}),jy=s.object({repo:s.string(),number:s.number().int(),title:s.string(),state:s.enum(["open","closed"]),url:s.string(),author:s.string(),member:s.boolean(),labels:s.array(s.string()),comments:s.number().int(),createdAt:s.string(),updatedAt:s.string()}),WD=s.object({repo:s.string(),issues:s.array(jy),error:s.enum(["no_access","failed"]).optional()}),HI=s.object({author:s.string(),member:s.boolean(),body:s.string(),createdAt:s.string()}),GD=jy.extend({body:s.string(),commentList:s.array(HI),moreComments:s.boolean()}),Ty=s.object({repo:s.string(),number:s.number().int(),url:s.string(),threadId:X,title:s.string(),state:s.enum(["open","closed","merged"]),draft:s.boolean(),checks:s.enum(["pending","success","failure"]).nullable(),review:s.enum(["approved","changes_requested"]).nullable(),conflict:s.boolean().default(!1),branch:s.string().default(""),additions:s.number().int().nullable().default(null),deletions:s.number().int().nullable().default(null),changedFiles:s.number().int().nullable().default(null),createdAt:R.nullable().default(null),updatedAt:R}),XI=s.object({path:s.string(),previousPath:s.string().nullable(),status:s.enum(["added","removed","modified","renamed","copied","changed","unchanged"]),additions:s.number().int(),deletions:s.number().int(),patch:s.string().nullable()}),qD=s.object({files:s.array(XI),truncated:s.boolean(),nextPage:s.number().int().nullable().default(null)}),Cy=s.enum(["merge","squash","rebase"]),HD=s.object({permitted:s.boolean(),blocked:s.enum(["closed","draft","conflict","checks_failed","checks_pending","changes_requested","protected","checking"]).nullable(),methods:s.array(Cy),sha:s.string()}),XD=s.object({method:Cy,sha:s.string().min(1),deleteBranch:s.boolean().default(!1)}),YD=s.object({merged:s.literal(!0),branchDeleted:s.boolean(),branchKept:s.enum(["fork","default","protected","gone","in_use","reopened","failed"]).nullable()}),QD=s.object({installationId:s.number().int().positive(),repoId:s.number().int().positive()});var YI=16e3,QI=16e3,iR=25*1024*1024,Oy=10;var oR=s.object({path:rr,size:s.number().int().nonnegative(),contentType:s.string(),updatedAt:R,updatedByKind:hi,updatedBy:s.string()}),e0=s.string().trim().min(1).max(80).regex(/^[\p{L}\p{N}][\p{L}\p{N} _.-]*$/u,"Use letters, numbers, spaces, dots, dashes or underscores"),t0=s.enum(["ok","stale"]),n0=s.object({name:e0,description:s.string().max(300),content:s.string().max(QI),updatedAt:R,updatedByKind:hi,updatedBy:s.string(),status:t0.default("ok"),staleReason:s.string().max(300).nullable().default(null),verifiedAt:R.nullable().default(null),previousContent:s.string().nullable().default(null),previousAt:R.nullable().default(null)}),aR=n0.pick({description:!0,content:!0}),sR=s.discriminatedUnion("status",[s.object({status:s.literal("ok")}),s.object({status:s.literal("stale"),reason:s.string().trim().min(1).max(300)})]),r0=s.object({text:s.string().max(YI),updatedAt:R.nullable(),updatedBy:s.string().nullable()}),cR=r0.pick({text:!0}),Ny=s.enum(["files","memory","instructions"]),Dy=s.enum(["auto","on","off"]),uR=s.object({mode:Dy,active:s.boolean(),lastRunAt:R.nullable(),threadsSince:s.number().int().nonnegative(),threadsNeeded:s.number().int().positive(),threadId:s.string().nullable()}),lR=s.object({mode:Dy});var fm=s.object({id:gi,projectId:Te,threadId:X.nullable(),title:s.string(),description:s.string().nullable(),version:s.number().int().positive(),createdAt:R,updatedAt:R}),fR=s.object({version:s.number().int().positive(),size:s.number().int().nonnegative(),threadId:X.nullable(),createdAt:R}),gR=s.object({version:s.number().int().positive(),url:s.string().nullable(),expiresAt:R.nullable()}),hR=2*1024*1024;var gm=s.string().regex(de("routine")),i0=/^(\*|\d+(-\d+)?)(\/\d+)?(,(\*|\d+(-\d+)?)(\/\d+)?)*$/,o0=s.string().trim().refine(e=>{let t=e.split(/\s+/);return t.length===5&&t.every(r=>i0.test(r))},"Expected a five-field cron expression, e.g. 0 9 * * 1-5"),a0=s.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}},"Unknown time zone"),hm=s.discriminatedUnion("kind",[s.object({kind:s.literal("cron"),cron:o0,timezone:a0.default("UTC")}),s.object({kind:s.literal("once"),at:R})]),vm=s.discriminatedUnion("kind",[s.object({kind:s.literal("coordinator")}),s.object({kind:s.literal("thread"),threadId:X})]),ym=s.object({id:gm,projectId:Te,name:s.string(),prompt:s.string(),target:vm,schedule:hm,paused:s.boolean(),nextRunAt:R.nullable(),lastRunAt:R.nullable(),runCount:s.number().int().nonnegative(),createdBy:s.string(),createdAt:R});var xR=s.object({name:s.string().trim().min(1).max(120),prompt:s.string().trim().min(1).max(8e3),target:vm.default({kind:"coordinator"}),schedule:hm}),wR=s.object({name:s.string().trim().min(1).max(120),prompt:s.string().trim().min(1).max(8e3),target:vm,schedule:hm,paused:s.boolean()}).partial();var bm=s.object({text:s.string(),until:s.string(),createdBy:s.string(),createdAt:s.string(),wakes:s.number().int().nonnegative(),threads:s.number().int().nonnegative(),idle:s.number().int().nonnegative()});var s0=s.string().regex(de("sshHost")),$m=s.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Use lowercase letters, digits, - and _ (up to 40)."),Ga=s.string().trim().min(1).max(253).regex(/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*\.?|\[?[0-9A-Fa-f:.]+\]?)$/,"Enter a host name or IP address."),Ry=s.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/,"Enter the user name on the server."),Ey=s.enum(["ask","off"]),AR=s.string().max(16e3).regex(/^(?:ssh|ecdsa|sk)-[\w@.-]+ [A-Za-z0-9+/=]+(?: .*)?$/),Uy=s.string().max(200).regex(/^SHA256:[A-Za-z0-9+/=]+$/),c0=s.object({id:s0,projectId:Te,alias:$m,host:s.string(),port:s.number().int(),user:s.string(),runnerId:s.string(),runnerName:s.string(),mine:s.boolean(),keySource:s.enum(["new","existing"]),publicKey:s.string().nullable(),keyFingerprint:s.string().nullable(),hostFingerprint:s.string().nullable(),rule:Ey,testedAt:R.nullable(),createdAt:R}),u0=s.object({id:s.string(),alias:s.string(),threadId:s.string().nullable(),command:s.string(),reason:s.string().nullable(),decision:s.enum(["once","turn","deny","timeout","failed"]),approvedBy:s.string().nullable(),exitCode:s.number().int().nullable(),ms:s.number().int().nullable(),at:R}),jR=s.object({hosts:s.array(c0),history:s.array(u0)}),TR=s.object({runnerId:s.string(),alias:$m,host:Ga,port:s.number().int().min(1).max(65535).default(22),user:Ry,existingKey:s.string().min(1).max(1024).optional()}),CR=s.object({rule:Ey}),OR=s.object({hostKey:s.string().min(1).max(16e3)}),My=s.object({type:s.string().max(60),key:s.string().max(16e3),fingerprint:Uy}),Ly=s.object({path:s.string().max(1024),name:s.string().max(255),type:s.string().max(60),fingerprint:Uy,comment:s.string().max(500)}),Zy=s.object({exitCode:s.number().int().nullable(),stdout:s.string(),stderr:s.string(),truncated:s.boolean(),ms:s.number().int().nonnegative(),error:s.enum(["hostkey","auth","connect","timeout","nokey","other"]).optional()}),Fy=300*1e3,Vy=200*1024,qa=s.object({projectId:Te,alias:$m}),xm=qa.extend({host:Ga,port:s.number().int().min(1).max(65535),user:Ry,hostKey:s.string().min(1).max(16e3)});var Wy=2,Ve=s.string().regex(de("runner")),Ke=s.enum(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi","qwen"]),Xa={claude:"Claude Code",codex:"Codex CLI",antigravity:"Antigravity CLI",opencode:"OpenCode",hermes:"Hermes Agent",cursor:"Cursor CLI",muse:"Muse Code",kimi:"Kimi Code",qwen:"Qwen Code"},Gy=s.object({path:s.string().min(1).max(1024),name:s.string().max(255)}),l0=s.object({kind:s.string().max(40),usedPercent:s.number().min(0).max(1e3).nullable(),resetsAt:R.nullable()}),qy=s.object({status:s.enum(["ok","warning","limited"]).optional(),windows:s.array(l0).max(8),at:R});var d0=s.object({id:s.string().min(1).max(200),name:s.string().max(200),efforts:s.array(s.string().min(1).max(20)).max(10)});var Ot=s.string().regex(/^[a-z0-9][a-z0-9-]{0,39}$/);var p0=s.object({id:Ot,name:s.string().min(1).max(80),limits:qy.optional().catch(void 0)});var m0=s.object({id:Ke,version:s.string().max(200).nullable(),limits:qy.optional().catch(void 0),models:s.array(d0).max(100).optional().catch(void 0),accounts:s.array(p0).max(10).optional().catch(void 0),defaultAccount:s.string().min(1).max(80).optional().catch(void 0)}),f0=s.enum(["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","update","models","github-token","git-token","git-tokens","steer","steer-claude","ssh","stats","cli-accounts","shared-folder","coordinator"]),g0=s.discriminatedUnion("transport",[s.object({transport:s.literal("http"),name:s.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),path:s.string().regex(/^\/api\/[\w/-]+$/).max(300)}),s.object({transport:s.literal("stdio"),name:s.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),command:s.string().min(1).max(200),args:s.array(s.string().max(2e3)).max(50),env:s.record(s.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),s.string().max(4e3))})]),h0=s.enum(["read","edit","auto","full"]),_m=s.object({access:h0,worktrees:s.boolean(),autoUpdate:s.boolean(),remote:s.boolean()}),Hy=_m.omit({remote:!0}).partial(),v0=s.enum(["service","app","manual"]),wm=s.object({state:s.enum(["waiting","downloading","restarting","failed","rolled-back"]),version:s.string().max(50),running:s.number().int().nonnegative().optional(),message:s.string().max(500).optional(),at:R}),y0=s.object({status:s.enum(["ok","missing-libs","unknown"]),missing:s.array(s.string().max(80)).max(30).optional()});var Xy=s.object({version:s.string().max(50),hostname:s.string().max(255),platform:s.string().max(50),folders:s.array(Gy).max(200),clis:s.array(s.unknown()).max(10).transform(e=>e.flatMap(t=>{let r=m0.safeParse(t);return r.success?[r.data]:[]})),features:s.array(s.string().max(50)).max(40).default([]).transform(e=>e.filter(t=>f0.safeParse(t).success)),settings:_m.optional().catch(void 0),updates:v0.optional().catch(void 0),update:wm.optional().catch(void 0),browser:y0.optional().catch(void 0)}),an=s.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Ha=s.object({at:R,cpu:s.object({percent:s.number().min(0).max(100).optional(),cores:s.number().int().min(1).max(1024)}),memory:s.object({total:an,available:an}),swap:s.object({total:an,used:an}).optional(),disk:s.object({total:an,free:an}).optional(),tasks:s.number().int().nonnegative().max(1e3),runnerMemory:an.optional()}),vi=1e5,ne=s.string().min(1).max(64),b0=s.object({name:s.string().max(255),path:s.string().max(1024)}),$0=s.object({path:s.string().max(1024),parent:s.string().max(1024).nullable(),home:s.string().max(1024),dirs:s.array(b0).max(1e3)}),Ky=s.object({inputTokens:s.number().int().nonnegative(),outputTokens:s.number().int().nonnegative(),model:s.string().max(200).optional()}),km=512*1024,x0=s.object({path:s.string().max(4096),size:s.number().int().nonnegative(),data:s.string().max(Math.ceil(km/3)*4+4),truncated:s.boolean()}),w0=s.object({model:s.string().min(1).max(200).optional(),effort:s.string().min(1).max(20).optional()}),Jy=s.object({token:s.string().min(20).max(4096),expiresAt:R,repos:s.array(s.string().regex(/^[\w.-]+\/[\w.-]+$/).max(200)).max(100)}),By=Jy.extend({more:s.array(Jy).max(20).optional()}),MR=s.discriminatedUnion("type",[Xy.extend({type:s.literal("hello"),protocol:s.number().int().positive(),running:s.array(Ce).max(100).default([]),interrupted:s.array(Ce).max(100).default([]),stats:Ha.optional().catch(void 0)}),s.object({type:s.literal("task.progress"),taskId:Ce,text:s.string().max(2e3),usage:Ky.optional(),agent:dm.optional(),ms:s.number().nonnegative().optional()}),s.object({type:s.literal("task.done"),taskId:Ce,ok:s.boolean(),usage:Ky.optional(),result:s.string().max(vi),cancelled:s.boolean().optional()}),s.object({type:s.literal("ping"),stats:Ha.optional().catch(void 0)}),s.object({type:s.literal("task.folders"),taskId:Ce,folders:s.array(s.string().min(1).max(1024)).max(60)}),$0.extend({type:s.literal("dirs"),requestId:ne}),s.object({type:s.literal("folders"),requestId:ne,folders:s.array(Gy).max(200)}),s.object({type:s.literal("request.failed"),requestId:ne,message:s.string().max(500)}),x0.extend({type:s.literal("file"),requestId:ne}),s.object({type:s.literal("settings"),requestId:ne,settings:_m}),s.object({type:s.literal("update.accepted"),requestId:ne,update:wm}),s.object({type:s.literal("update.status"),update:wm.nullable()}),s.object({type:s.literal("task.steered"),requestId:ne,taken:s.boolean()}),s.object({type:s.literal("ssh.key"),requestId:ne,publicKey:s.string().max(16e3),fingerprint:s.string().max(200),protected:s.boolean()}),s.object({type:s.literal("ssh.keylist"),requestId:ne,keys:s.array(Ly).max(100)}),s.object({type:s.literal("ssh.hostkeylist"),requestId:ne,keys:s.array(My).max(10)}),Zy.extend({type:s.literal("ssh.result"),requestId:ne})]),Yy=s.discriminatedUnion("type",[s.object({type:s.literal("welcome"),runnerId:Ve,name:s.string()}),s.object({type:s.literal("task.start"),taskId:Ce,threadId:X,folder:s.string().min(1).max(1024),cli:Ke,prompt:s.string().min(1).max(vi),model:w0.optional(),reviewModel:s.string().min(1).max(200).optional(),account:Ot.optional(),folders:s.array(s.string().min(1).max(1024)).max(50).optional(),worktree:s.boolean().optional(),agent:s.object({mcpPath:s.string().regex(/^\/api\/[\w/-]+$/).max(300),token:s.string().min(20).max(200),connectors:s.array(g0).max(30).optional(),skills:s.object({path:s.string().regex(/^\/api\/[\w/-]+$/).max(300)}).optional(),resume:s.object({after:Ce,prompt:s.string().min(1).max(vi)}).optional()}).optional(),github:By.optional(),coordinator:s.object({system:s.string().min(1).max(vi)}).optional()}),s.object({type:s.literal("task.github"),taskId:Ce,github:By}),s.object({type:s.literal("task.steer"),requestId:ne,taskId:Ce,text:s.string().min(1).max(vi)}),s.object({type:s.literal("task.cancel"),taskId:Ce}),s.object({type:s.literal("pong")}),s.object({type:s.literal("dirs.list"),requestId:ne,path:s.string().max(1024).optional()}),s.object({type:s.literal("folder.share"),requestId:ne,path:s.string().min(1).max(1024)}),s.object({type:s.literal("folder.unshare"),requestId:ne,path:s.string().min(1).max(1024)}),s.object({type:s.literal("file.read"),requestId:ne,path:s.string().min(1).max(4096),folders:s.array(s.string().min(1).max(1024)).min(1).max(51),threadId:X.optional(),worktrees:s.boolean().optional()}),s.object({type:s.literal("settings.set"),requestId:ne,settings:Hy}),s.object({type:s.literal("runner.update"),requestId:ne,version:s.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/).max(50),now:s.boolean().default(!1)}),qa.extend({type:s.literal("ssh.keygen"),requestId:ne,comment:s.string().max(200),existing:s.string().min(1).max(1024).optional()}),s.object({type:s.literal("ssh.keys"),requestId:ne}),s.object({type:s.literal("ssh.hostkeys"),requestId:ne,host:Ga,port:s.number().int().min(1).max(65535)}),s.object({type:s.literal("ssh.test"),requestId:ne,target:xm}),s.object({type:s.literal("ssh.run"),requestId:ne,target:xm,command:s.string().min(1).max(2e4)}),qa.extend({type:s.literal("ssh.forget"),requestId:ne})]),_0=Xy.extend({id:Ve,name:s.string(),version:s.string().nullable(),online:s.boolean(),lastSeenAt:R.nullable(),createdAt:R,stats:Ha.optional()}),LR=s.object({name:s.string().trim().min(1).max(80).optional(),settings:Hy.optional()}),ZR=s.object({now:s.boolean().default(!1)}),FR=s.object({runners:s.array(_0),latestVersion:s.string().nullable()}),VR=s.object({code:s.string(),expiresAt:R}),KR=s.object({code:s.string().trim().min(4).max(20),name:s.string().trim().min(1).max(80),hostname:s.string().max(255).default(""),platform:s.string().max(50).default("")}),Qy=s.object({runner:s.object({id:Ve,name:s.string()}),token:s.string()}),JR=s.object({projectId:Te,runnerId:Ve,runnerName:s.string(),path:s.string(),folders:s.array(s.string()).default([]),cli:Ke,online:s.boolean(),isDefault:s.boolean().default(!0),stats:Ha.optional()}),BR=s.object({path:s.string().trim().min(1).max(1024)}),WR=s.object({runnerId:Ve,path:s.string().min(1).max(1024),cli:Ke,add:s.boolean().optional()}),GR=s.object({path:s.string().min(1).max(1024),runnerId:Ve.optional()}),qR=s.object({runnerId:Ve});function eb(e,t){let r=i=>i.split("-")[0].split(".").map(a=>Number.parseInt(a,10)||0),[o,n]=[r(e),r(t)];for(let i=0;i<3;i++)if((o[i]??0)!==(n[i]??0))return(o[i]??0)>(n[i]??0);return!1}var k0=200,S0=s.object({threadId:X.nullable(),hasEarlier:s.boolean()});var aE=s.discriminatedUnion("type",[s.object({type:s.literal("message.send"),clientId:s.string().max(64).optional(),threadId:X.nullable().default(null),body:s.string().trim().max(mm),attachments:s.array(rr).max(Oy).default([]),clis:s.array(Ke).max(Ka).optional(),pick:Va.optional()}).refine(e=>e.body.length>0||e.attachments.length>0,"Write something or attach a file"),s.object({type:s.literal("message.edit"),messageId:on.shape.id,body:s.string().trim().max(mm)}),s.object({type:s.literal("thread.resolve"),threadId:X,resolved:s.boolean(),reason:um.optional()}),s.object({type:s.literal("thread.cli"),threadId:X,cli:Ke.nullable(),account:Ot.nullable().optional()}),s.object({type:s.literal("thread.runner"),threadId:X,runnerId:s.union([Ve,s.literal(zy)]).nullable()}),s.object({type:s.literal("thread.model"),threadId:X,cli:Ke,model:s.string().trim().min(1).max(200).nullable(),effort:s.string().trim().min(1).max(20).nullable()}),s.object({type:s.literal("goal.stop")}),s.object({type:s.literal("sync"),afterSeq:s.number().int().nonnegative(),all:s.boolean().optional(),recent:s.number().int().positive().max(k0).optional()})]),sE=s.discriminatedUnion("type",[s.object({type:s.literal("message.created"),message:on}),s.object({type:s.literal("message.updated"),message:on}),s.object({type:s.literal("message.ack"),clientId:s.string(),messageId:on.shape.id,seq:on.shape.seq}),s.object({type:s.literal("sync.result"),messages:s.array(on),hasMore:s.boolean(),streamed:s.boolean().optional(),threads:s.array(lm).default([]),reactions:s.array(pm).default([]),artifacts:s.array(fm).default([]),routines:s.array(ym).default([]),goal:bm.nullable().optional(),windows:s.array(S0).optional(),reset:s.boolean().optional(),lastSeq:s.number().int().nonnegative().optional()}),s.object({type:s.literal("thread.updated"),thread:lm}),s.object({type:s.literal("reaction.added"),reaction:pm}),s.object({type:s.literal("artifact.updated"),artifact:fm}),s.object({type:s.literal("routine.updated"),routine:ym}),s.object({type:s.literal("routine.deleted"),routineId:gm}),s.object({type:s.literal("goal.updated"),goal:bm.nullable()}),s.object({type:s.literal("agent.activity"),threadId:X.nullable(),active:s.boolean(),label:s.string().max(200).optional()}),s.object({type:s.literal("knowledge.changed"),kind:Ny}),s.object({type:s.literal("workspace.changed")}),s.object({type:s.literal("task.updated"),task:Py}),s.object({type:s.literal("task.output"),taskId:Ce,threadId:X,lines:s.array(Ay)}),s.object({type:s.literal("pr.updated"),pullRequest:Ty}),s.object({type:s.literal("error"),code:s.string(),message:s.string()})]);var lE=s.object({app:s.literal("myrel"),apiVersion:s.number().int().positive(),name:s.string(),auth:s.object({emailPassword:s.boolean(),signUp:s.boolean().default(!0),emailVerification:s.boolean().default(!1),captcha:s.object({provider:s.literal("turnstile"),siteKey:s.string()}).nullable().default(null),passwordReset:s.boolean().default(!1)}),billing:s.boolean().default(!1),legal:s.object({terms:s.string().url(),privacy:s.string().url(),version:s.string()}).nullable().default(null)});var yi=s.enum(["fireworks","anthropic","openai"]),vE=s.object({id:yi,name:s.string(),defaultModel:s.string(),serverKey:s.boolean()}),yE=s.object({id:s.string(),provider:yi,label:s.string(),hint:s.string(),scope:s.enum(["user","instance"]),createdAt:s.iso.datetime()}),bE=s.object({provider:yi,label:s.string().trim().min(1).max(80),key:s.string().trim().min(8).max(500),scope:s.enum(["user","instance"]).default("user")}),tb=s.enum(["auto","local","cloud"]),nb=s.enum(["opencode","claude","codex"]),I0=s.object({model:s.string().trim().min(1).max(200).nullable(),effort:s.string().trim().min(1).max(20).nullable(),account:Ot.nullable().optional(),reviewModel:s.string().trim().min(1).max(200).nullable().optional()});var rb=s.partialRecord(Ke,s.string().trim().min(1).max(200)),Sm=s.partialRecord(Ke,I0),Ya=Sm,z0=["claude"],P0=s.enum(z0),A0=s.discriminatedUnion("mode",[s.object({mode:s.literal("model")}),s.object({mode:s.literal("cli"),runnerId:Ve,computer:s.string(),by:s.string(),cli:Ke,model:s.string().nullable(),effort:s.string().nullable(),account:Ot.nullable().catch(null).default(null)})]),j0=s.discriminatedUnion("mode",[s.object({mode:s.literal("model")}),s.object({mode:s.literal("cli"),runnerId:Ve,cli:P0,model:s.string().trim().min(1).max(200).nullable(),effort:s.string().trim().min(1).max(20).nullable(),account:Ot.nullable().optional()})]),$E=s.object({name:s.string(),provider:yi.nullable(),model:s.string().nullable(),keyId:s.string().nullable(),taskTarget:tb,icon:Wa.nullable().default(null),color:Ba.nullable().default(null),cloudCli:nb.default("opencode"),cliModels:Sm.default({}),visualCheck:s.boolean().default(!1),checkModels:Ya.default({}),worktrees:s.boolean().default(!0),coordinator:A0.catch({mode:"model"}).default({mode:"model"})}),xE=s.object({name:s.string().trim().min(1).max(120).optional(),provider:yi.nullable().optional(),model:s.string().trim().max(200).nullable().optional(),keyId:s.string().nullable().optional(),taskTarget:tb.optional(),icon:Wa.nullable().optional(),color:Ba.nullable().optional(),cloudCli:nb.optional(),cliModels:Sm.optional(),visualCheck:s.boolean().optional(),checkModels:Ya.optional(),worktrees:s.boolean().optional(),coordinator:j0.optional()}),ib=s.enum(["admin","member"]),wE=s.object({id:s.string(),projectId:s.string(),projectName:s.string(),email:s.string(),role:ib,invitedBy:s.string(),createdAt:s.iso.datetime()}),_E=s.object({email:s.email().trim().toLowerCase(),role:ib.default("member")}),kE=s.object({role:Ja}),T0=s.enum(["admin","user"]),SE=s.enum(["computer","decision"]),IE=s.object({id:s.string(),name:s.string(),email:s.string(),role:T0,onboarded:s.boolean().optional(),tips:s.array(s.string()).optional(),checkModels:Ya.optional(),reviewModels:rb.optional()}),zE=s.object({checkModels:Ya}),PE=s.object({reviewModels:rb}),C0=s.object({signUpEnabled:s.boolean()}),O0=s.enum(["api","agent","cron","web","desktop","mobile"]),AE=s.object({platform:s.enum(["web","desktop","mobile"]),where:s.string().trim().min(1).max(200),name:s.string().max(100).default("Error"),message:s.string().max(500),stack:s.string().max(4e3).optional(),version:s.string().max(40).optional()}),jE=s.object({id:s.string(),source:O0,where:s.string(),name:s.string(),message:s.string(),stack:s.string().nullable(),count:s.number().int(),firstSeenAt:s.number(),lastSeenAt:s.number()}),TE=s.object({days:s.number().int(),signedUp:s.number().int(),verified:s.number().int(),inProject:s.number().int(),asked:s.number().int(),threadRan:s.number().int(),pairedComputer:s.number().int()}),CE=C0.partial();var ob=s.string().regex(de("notification")),N0=s.enum(["done","ready","decision","blocked","failed"]),EE=s.object({id:ob,projectId:Te,threadId:X.nullable(),kind:N0,title:s.string(),body:s.string(),url:s.string(),readAt:R.nullable(),createdAt:R}),UE=s.object({email:s.boolean(),push:s.boolean()}),ME=s.object({webPushKey:s.string().nullable(),email:s.boolean()}),D0=[/^fcm\.googleapis\.com$/,/^updates\.push\.services\.mozilla\.com$/,/^web\.push\.apple\.com$/,/^[a-z0-9-]+\.notify\.windows\.com$/];function R0(e){try{let t=new URL(e);return t.protocol==="https:"&&D0.some(r=>r.test(t.hostname))}catch{return!1}}var LE=s.discriminatedUnion("kind",[s.object({kind:s.literal("webpush"),endpoint:s.url().max(2048).refine(R0,"Not a browser push service"),keys:s.object({p256dh:s.string().min(1).max(256),auth:s.string().min(1).max(64)})}),s.object({kind:s.literal("expo"),token:s.string().regex(/^Expo(nent)?PushToken\[[^\]]+\]$/).max(256)})]),ZE=s.union([s.object({ids:s.array(ob).min(1).max(200)}),s.object({all:s.literal(!0)})]);var E0=new RegExp(de("thread").source.slice(1,-1)),WE=new RegExp(`^#(${E0.source})$`);var U0=s.enum(["http","stdio"]),M0=s.enum(["user","project"]),zm=s.enum(["cloud","local","both"]),L0=s.enum(["unknown","ok","error","needs_auth"]),Z0=s.enum(["none","headers","oauth"]),ab=s.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).refine(e=>e!=="myrel","That name is taken by Myrel's own tools."),F0=s.object({name:s.string(),description:s.string().optional()}),V0=/^[A-Za-z_][\w-]{0,99}$/,K0=/^[A-Za-z_][A-Za-z0-9_]{0,99}$/,sb=(e,t,r)=>s.record(s.string().regex(e),s.string().max(4e3),{error:o=>o.code==="invalid_key"?`${t} name ${JSON.stringify(o.input)} is not valid: use only ${r}, with no spaces or ":". Put the value in its own field.`:void 0}),cb=sb(V0,"Header","letters, digits, - and _"),J0=sb(K0,"Variable","letters, digits and _"),HE=s.object({id:s.string(),name:s.string(),slug:s.string(),scope:M0,transport:U0,url:s.string().nullable(),auth:Z0,command:s.string().nullable(),args:s.array(s.string()),runsOn:zm,secretNames:s.array(s.string()),enabled:s.boolean(),status:L0,lastError:s.string().nullable(),tools:s.array(F0),canEdit:s.boolean(),createdAt:s.iso.datetime(),official:s.object({id:s.string(),title:s.string(),iconUrl:s.string().nullable()}).nullable().default(null)}),Im=s.string().trim().min(1).max(60),XE=s.discriminatedUnion("transport",[s.object({transport:s.literal("http"),name:Im,slug:ab.optional(),url:s.url({protocol:/^https$/}).max(2e3),auth:s.enum(["headers","oauth"]).default("headers"),headers:cb.default({})}),s.object({transport:s.literal("stdio"),name:Im,slug:ab.optional(),command:s.string().trim().min(1).max(200),args:s.array(s.string().max(2e3)).max(50).default([]),env:J0.default({}),runsOn:zm.default("both")})]),YE=s.object({name:Im.optional(),enabled:s.boolean().optional(),url:s.url({protocol:/^https$/}).max(2e3).optional(),command:s.string().trim().min(1).max(200).optional(),args:s.array(s.string().max(2e3)).max(50).optional(),runsOn:zm.optional(),secrets:cb.optional()});var QE=s.object({authorizeUrl:s.url()});var B0=["developer","productivity","communication","design","data","sales","finance","search","ai","other"],ub=s.enum(B0);var W0=s.object({id:s.string(),title:s.string(),description:s.string(),websiteUrl:s.string().nullable(),iconUrl:s.string().nullable(),url:s.string(),auth:s.enum(["oauth","headers"]),headerHint:s.object({name:s.string(),placeholder:s.string()}).nullable(),category:ub,official:s.boolean()}),eU=s.object({connectors:s.array(W0),nextOffset:s.number().nullable(),syncedAt:s.iso.datetime().nullable(),categories:s.array(s.object({id:ub,count:s.number()}))}),G0=[{id:"com.notion/mcp",category:"productivity"},{id:"app.linear/linear",category:"productivity"},{id:"com.atlassian/atlassian-mcp-server",category:"productivity"},{id:"com.figma.mcp/mcp",category:"design"},{id:"com.stripe/mcp",category:"finance"},{id:"com.canva.mcp/mcp",category:"design"},{id:"com.vercel/vercel-mcp",category:"developer"},{id:"com.gitlab/mcp",category:"developer"},{id:"io.github.PostHog/mcp",category:"data"},{id:"com.zapier/mcp",category:"productivity"},{id:"com.airtable/mcp",category:"data"},{id:"com.monday/monday.com",category:"productivity"},{id:"com.paypal.mcp/mcp",category:"finance"},{id:"com.webflow/mcp",category:"design"},{id:"com.wix/mcp",category:"design"},{id:"com.neon/mcp",category:"developer"},{id:"com.railway/mcp",category:"developer"},{id:"co.huggingface/hf-mcp-server",category:"ai"},{id:"com.cloudflare.mcp/mcp",category:"developer"},{id:"com.apify/apify-mcp-server",category:"search"},{id:"ai.exa/exa",category:"search"},{id:"com.microsoft/microsoft-learn-mcp",category:"search"}],tU=G0.map(e=>e.id);var q0=s.enum(["user","project"]),H0=s.string().max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,"Use lowercase letters, digits and hyphens, like pdf-forms."),lb=s.string().trim().min(1).max(1024),X0=s.string().min(1).max(300).regex(/^[\w@+=,.~ -]+(\/[\w@+=,.~ -]+)*$/,"Invalid file path.").refine(e=>!e.split("/").some(t=>t==="."||t===".."),"Invalid file path."),db={files:200,bytes:5*1024*1024,fileBytes:1024*1024};var Y0=s.discriminatedUnion("kind",[s.object({kind:s.literal("write")}),s.object({kind:s.literal("upload")}),s.object({kind:s.literal("github"),repo:s.string(),path:s.string(),ref:s.string().optional(),commit:s.string()})]),Q0=s.object({path:s.string(),size:s.number().int().nonnegative()}),ez=s.object({id:s.string(),name:s.string(),description:s.string(),scope:q0,source:Y0,enabled:s.boolean(),files:s.array(Q0),size:s.number().int().nonnegative(),canEdit:s.boolean(),createdAt:s.iso.datetime(),updatedAt:s.iso.datetime()}),iU=ez.extend({skillMd:s.string()}),tz=s.object({path:X0,content:s.string().max(Math.ceil(db.fileBytes*4/3)+4)}),oU=s.discriminatedUnion("kind",[s.object({kind:s.literal("write"),name:H0,description:lb,instructions:s.string().max(1e5)}),s.object({kind:s.literal("upload"),files:s.array(tz).min(1).max(db.files)}),s.object({kind:s.literal("github"),source:s.string().trim().min(3).max(500),skill:s.string().max(64).optional()})]),aU=s.object({error:s.literal("choose_skill"),skills:s.array(s.object({name:s.string(),description:s.string(),path:s.string()}))}),sU=s.object({enabled:s.boolean().optional(),description:lb.optional(),instructions:s.string().max(1e5).optional()}),cU=s.object({skills:s.array(s.object({name:s.string(),files:s.array(s.object({path:s.string(),content:s.string()}))}))});var uU=s.object({on:s.boolean()});var nz=s.object({id:s.string().min(1).max(200),name:s.string().min(1).max(80),description:s.string().max(300).default(""),url:s.string().max(2e3),auth:s.enum(["oauth","headers"]),headerHint:s.object({name:s.string(),placeholder:s.string()}).nullable().default(null),iconUrl:s.string().nullable().default(null),official:s.boolean().default(!1),featured:s.boolean().default(!1)}),rz=s.enum(["open","connected","dismissed"]),pU=s.object({id:s.string(),reason:s.string().min(1).max(400),offers:s.array(nz).min(1).max(3),state:rz.default("open"),connected:s.string().optional(),signIn:s.boolean().optional()});var mU=s.object({offerId:s.string().min(1).max(200),headers:s.record(s.string().regex(/^[A-Za-z_][\w-]{0,99}$/),s.string().min(1).max(4e3)).optional()}),fU=s.object({authorizeUrl:s.string().optional(),connected:s.boolean()});var iz=s.enum(["running","passed","failed","partial","not_checked"]),Qa=s.number().int().min(1).max(10),vU=s.object({id:s.string(),round:s.number().int().min(1),status:iz,evaluatorThreadId:s.string().nullable().default(null),folder:s.string(),branch:s.string().max(255).optional(),evaluator:s.object({cli:s.string(),model:s.string(),effort:s.string().optional()}).optional(),vision:s.enum(["passed","failed","skipped"]).optional(),scores:s.object({functionality:Qa,craft:Qa,design:Qa,originality:Qa}).optional(),deterministic:s.object({shots:s.number(),blocking:s.number(),warnings:s.number()}).optional(),blocking:s.array(s.object({n:s.number().int().min(1).optional(),screen:s.string().max(200),problem:s.string().max(2e3),evidence:s.string().max(400),image:s.string().max(400).optional()})).max(20).default([]),acceptance:s.array(s.object({criterion:s.string().max(500),met:s.boolean()})).max(30).default([]),sheets:s.array(s.string().max(400)).max(12).default([]),diffs:s.array(s.string().max(400)).max(12).default([]),acceptedBy:s.string().max(120).optional(),baselineBy:s.string().max(120).optional(),summary:s.string().max(400).optional(),note:s.string().max(600).optional(),command:s.string().max(300).optional()});var yU=s.enum(["accept","baseline"]);var pb=s.enum(["running","budget","done","failed"]),oz=s.object({kind:s.enum(["search","read"]),text:s.string().max(400)}),xU=s.object({id:s.string(),title:s.string().max(200),status:pb,partial:s.enum(["budget","time","stopped"]).optional(),spentCents:s.number().int().nonnegative(),budgetCents:s.number().int().positive(),searches:s.number().int().nonnegative().default(0),pages:s.number().int().nonnegative().default(0),steps:s.array(oz).max(6).default([]),startedAt:s.string(),endedAt:s.string().optional(),model:s.string().max(80),approverName:s.string().max(120).optional(),stoppedBy:s.string().max(120).optional(),report:s.string().max(400).optional(),summary:s.string().max(600).optional(),note:s.string().max(600).optional()});var wU=s.enum(["stop"]),_U=s.object({id:s.string(),threadId:s.string(),threadTitle:s.string(),title:s.string(),status:pb,partial:s.enum(["budget","time","stopped"]).optional(),spentCents:s.number().int().nonnegative(),budgetCents:s.number().int().positive(),approverName:s.string().optional(),startedAt:s.string(),endedAt:s.string().optional(),report:s.string().optional()});var az=/^(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(\S[\s\S]*)$/;function ir(e){let t=az.exec(e.trim());return t?sz(t[1])??e:e}function sz(e){let t="",r=0;for(;r<e.length;){let o=e[r];if(o==="'"){let n=e.indexOf("'",r+1);if(n<0)return null;t+=e.slice(r+1,n),r=n+1}else if(o==='"'){for(r++;;){if(r>=e.length)return null;let n=e[r];if(n==='"')break;n==="\\"&&r+1<e.length&&'"\\$`\n'.includes(e[r+1])?(t+=e[r+1],r+=2):(t+=n,r++)}r++}else if(o==="\\"){if(r+1>=e.length)return null;t+=e[r+1],r+=2}else{if(/\s/.test(o)||"|&;<>()$`".includes(o))return null;t+=o,r++}}return t}var cz=s.enum(["spam","harassment","hate","sexual","violence","illegal","other"]),uz=1e3,lz=s.discriminatedUnion("kind",[s.object({kind:s.literal("message"),messageId:rn}),s.object({kind:s.literal("artifact"),artifactId:gi,version:s.number().int().positive().optional()})]),DU=s.object({target:lz,reason:cz,note:s.string().trim().max(uz).optional()});import{execFile as bz,spawn as $z}from"node:child_process";import{mkdir as xz}from"node:fs/promises";import{homedir as wz}from"node:os";import{join as jm,resolve as gb}from"node:path";import{mkdir as dz,readFile as pz,rename as mz,writeFile as fz}from"node:fs/promises";import{homedir as gz}from"node:os";import{basename as hz,join as Pm,resolve as fb}from"node:path";function Y(){return process.env.MYREL_RUNNER_HOME||Pm(gz(),".myrel-runner")}var Nt=()=>Pm(Y(),"config.json");async function me(){let e=await ve(Nt()),t={folders:[],access:"edit",...e};return process.env.MYREL_SERVER&&(t.server=process.env.MYREL_SERVER),process.env.MYREL_RUNNER_TOKEN&&(t.token=process.env.MYREL_RUNNER_TOKEN),t}var vz=["MYREL_RUNNER_TOKEN"],yz=["SSH_AUTH_SOCK"];function Ue(e){let t={...process.env,...e};for(let r of[...vz,...yz])delete t[r];return t}async function Oe(e){let t={...e};process.env.MYREL_RUNNER_TOKEN&&t.token===process.env.MYREL_RUNNER_TOKEN&&(t.token=(await ve(Nt()))?.token),await Xe(Nt(),t)}function ts(e,t){let r=fb(t);return e.folders.some(o=>o.path===r)?!1:(e.folders.push({path:r,name:hz(r)||r}),!0)}function ns(e,t){let r=fb(t),o=e.folders.length;return e.folders=e.folders.filter(n=>n.path!==r),e.folders.length!==o}var es=class{constructor(t=Pm(Y(),"sessions.json")){this.path=t}path;async get(t,r="claude",o){let n=(await ve(this.path))?.[mb(t,r,o)];return typeof n=="string"?{id:n}:n}async set(t,r,o,n){let i=await ve(this.path)??{};i[mb(t,r,n)]=o,await Xe(this.path,i)}},mb=(e,t,r)=>r?`${t}@${r}:${e}`:t==="claude"?e:`${t}:${e}`;async function ve(e){try{return JSON.parse(await pz(e,"utf8"))}catch(t){if(t.code==="ENOENT")return;throw t}}async function Xe(e,t){await dz(Y(),{recursive:!0,mode:448});let r=`${e}.${process.pid}.tmp`;await fz(r,`${JSON.stringify(t,null,2)}
|
|
64
64
|
`,{mode:384}),await mz(r,e)}var hb=new Set(["claude"]),Am=10,_z=()=>jm(Y(),"claude"),Tm=()=>process.env.CLAUDE_CONFIG_DIR?.trim()?gb(process.env.CLAUDE_CONFIG_DIR):jm(wz(),".claude"),kz={\u0131:"i",\u0130:"i",\u015F:"s",\u015E:"s",\u011F:"g",\u011E:"g",\u00E7:"c",\u00C7:"c",\u00F6:"o",\u00D6:"o",\u00FC:"u",\u00DC:"u"};function Sz(e,t){let r=e.replace(/[ıİşŞğĞçÇöÖüÜ]/g,n=>kz[n]).normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32).replace(/-+$/,"")||"account",o=r==="default"?"default-2":r;for(let n=2;t.includes(o);n++)o=`${r}-${n}`;return o}function rs(e,t){let r=t.trim().toLocaleLowerCase();return e.claudeAccounts?.find(o=>o.id===r||o.name.toLocaleLowerCase()===r)}function vb(e){let t=e.trim();if(!t||t.length>80)throw new Error('Give the account a name of up to 80 characters, e.g. myrel-runner claude add "Work".');return t}function yb(e,t,r){let o=n=>n!==void 0&&n!==r&&n.toLocaleLowerCase()===t.toLocaleLowerCase();if(o(e.claudeDefaultName)||(e.claudeAccounts??[]).some(n=>o(n.name)))throw new Error(`There is already a Claude Code account named "${t}".`)}async function bb(e,t,r){let o=vb(t),n=e.claudeAccounts??[];if(n.length>=Am)throw new Error(`This computer already has ${Am} other Claude Code accounts; remove one first.`);yb(e,o);let i=Sz(o,n.map(l=>l.id)),a=gb(r??jm(_z(),i));if(a===Tm())throw new Error(`${a} is Claude Code's own login, which Myrel already uses. Name it with: myrel-runner claude rename default "${o}"`);let c=n.find(l=>l.dir===a);if(c)throw new Error(`${a} is already the account "${c.name}".`);await xz(a,{recursive:!0,mode:448});let u={id:i,name:o,dir:a};return e.claudeAccounts=[...n,u],u}function $b(e,t){let r=rs(e,t);if(r)return e.claudeAccounts=e.claudeAccounts.filter(o=>o!==r),e.claudeAccounts.length||delete e.claudeAccounts,r}function xb(e,t,r){let o=vb(r),n=t.trim().toLocaleLowerCase(),i=n==="default"||n===e.claudeDefaultName?.toLocaleLowerCase(),a=i?void 0:rs(e,t);return!i&&!a?!1:(yb(e,o,i?e.claudeDefaultName:a.name),a?a.name=o:e.claudeDefaultName=o,!0)}function wb(e,t,r){if(!r)return{};let o=hb.has(t)?e.claudeAccounts?.find(n=>n.id===r):void 0;return o?{CLAUDE_CONFIG_DIR:o.dir}:{error:`This computer has no ${t==="claude"?"Claude Code ":""}account "${r}" any more. Choose another one for the thread, or add it again with \`myrel-runner claude add\`.`}}var Cm=(e,t)=>t?`${e}@${t}`:e;function _b(e,t,r){let o=hb.has(t)?(e.claudeAccounts??[]).slice(0,Am):[];return o.length?{accounts:o.map(n=>{let i=r[Cm(t,n.id)];return{id:n.id,name:n.name.slice(0,80),...i&&{limits:i}}}),...e.claudeDefaultName&&{defaultAccount:e.claudeDefaultName.slice(0,80)}}:{}}function is(e){return new Promise(t=>{bz("claude",["auth","status","--json"],{timeout:2e4,shell:process.platform==="win32",env:Ue(e?{CLAUDE_CONFIG_DIR:e}:void 0),windowsHide:!0},(r,o)=>{try{let n=JSON.parse(o);if(typeof n.loggedIn!="boolean")return t(null);t({loggedIn:n.loggedIn,...typeof n.subscriptionType=="string"&&{subscriptionType:n.subscriptionType}})}catch{t(null)}})})}function Om(e){return new Promise((t,r)=>{let o=$z("claude",["auth","login"],{stdio:"inherit",env:Ue({CLAUDE_CONFIG_DIR:e}),shell:process.platform==="win32"});o.once("error",r),o.once("close",n=>t(n??1))})}import{spawn as Iz}from"node:child_process";import{mkdir as zz,readFile as zb,rename as Pz,writeFile as Az}from"node:fs/promises";import{homedir as Pb}from"node:os";import{dirname as jz,join as kb}from"node:path";import{createInterface as Ab}from"node:readline";var Em="MYREL_MCP_BRIDGE";function Tz(e=Pb()){return{mcp:kb(e,".gemini","config","mcp_config.json"),settings:kb(e,".gemini","antigravity-cli","settings.json")}}function bi(){let e=process.argv[1],t=!e||/\$bunfs|~BUN/.test(e);return{command:process.execPath,args:t?[]:[e]}}async function jb(e,t=Pb()){let r=Tz(t),o=bi(),n={command:o.command,args:[...o.args,"mcp-bridge"]};await Sb(r.mcp,a=>{let c=Nm(a.mcpServers)?a.mcpServers:{};return JSON.stringify(c[e])===JSON.stringify(n)?!1:(a.mcpServers={...c,[e]:n},!0)});let i=`mcp(${e}/*)`;await Sb(r.settings,a=>{let c=Nm(a.permissions)?a.permissions:{},u=Array.isArray(c.allow)?c.allow:[];return u.includes(i)?!1:(a.permissions={...c,allow:[...u,i]},!0)})}async function Sb(e,t){let r=await zb(e,"utf8").catch(i=>{if(i.code==="ENOENT")return"";throw i}),o={};if(r.trim())try{o=JSON.parse(r)}catch{throw new Error(`Could not read ${e} as JSON, so Myrel's tools were not added to Antigravity CLI. Fix the file and try again.`)}if(!Nm(o))throw new Error(`${e} is not a JSON object, so Myrel's tools were not added to Antigravity CLI.`);if(!t(o))return;await zz(jz(e),{recursive:!0});let n=`${e}.myrel-${process.pid}`;await Az(n,`${JSON.stringify(o,null,2)}
|
|
65
65
|
`,{mode:384}),await Pz(n,e)}function Nm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var sn=class extends Error{constructor(r){super(typeof r?.message=="string"?r.message:"MCP error");this.error=r}error},Dm=class{constructor(t,r){this.url=t;this.token=r}url;token;session;version;next=1;async request(t,r){let o=this.next++,n=await this.post({jsonrpc:"2.0",id:o,method:t,...r!==void 0&&{params:r}}),i=await this.answer(n,o);if(t==="initialize"&&(this.version=i.result?.protocolVersion),i.error)throw new sn(i.error);return i.result}async notify(t,r){await(await this.post({jsonrpc:"2.0",method:t,...r!==void 0&&{params:r}})).body?.cancel()}close(){}async post(t){let r=await fetch(this.url,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.token}`,...this.session&&{"mcp-session-id":this.session},...this.version&&{"mcp-protocol-version":this.version}},body:JSON.stringify(t)});if(this.session=r.headers.get("mcp-session-id")??this.session,!r.ok&&r.status!==202)throw await r.body?.cancel(),new Error(`${this.url} answered ${r.status}`);return r}async answer(t,r){if(!(t.headers.get("content-type")??"").includes("text/event-stream"))return await t.json();let o=t.body.pipeThrough(new TextDecoderStream).getReader(),n="";try{for(;;){let{done:i,value:a}=await o.read();if(i)break;n+=a;let c;for(;(c=n.search(/\r?\n\r?\n/))>=0;){let u=n.slice(0,c);n=n.slice(c).replace(/^\r?\n\r?\n/,"");let l=u.split(/\r?\n/).filter(p=>p.startsWith("data:")).map(p=>p.slice(5).trimStart()).join(`
|
|
66
66
|
`);if(!l)continue;let d=JSON.parse(l);if(d.id===r)return d}}}finally{o.cancel().catch(()=>{})}throw new Error(`${this.url} closed the stream without an answer`)}},Rm=class{child;waiting=new Map;next=1;constructor(t,r,o){this.child=Iz(t,r,{env:{...process.env,...o},stdio:["pipe","pipe","inherit"],shell:process.platform==="win32"}),this.child.on("error",()=>this.fail(`could not start ${t}`)),this.child.on("exit",()=>this.fail(`${t} exited`)),Ab({input:this.child.stdout}).on("line",n=>{try{let i=JSON.parse(n);typeof i.id=="number"&&!i.method&&this.waiting.get(i.id)?.(i)}catch{}})}request(t,r){let o=this.next++;return new Promise((n,i)=>{this.waiting.set(o,a=>{this.waiting.delete(o),a.error?i(new sn(a.error)):n(a.result)}),this.write({jsonrpc:"2.0",id:o,method:t,...r!==void 0&&{params:r}})})}async notify(t,r){this.write({jsonrpc:"2.0",method:t,...r!==void 0&&{params:r}})}close(){this.child.kill()}write(t){this.child.stdin?.write(`${JSON.stringify(t)}
|
|
67
67
|
`)}fail(t){for(let[r,o]of this.waiting)o({jsonrpc:"2.0",id:r,error:{code:-32e3,message:t}})}},Cz="__";async function Tb(e){let{run:t,write:r}=e,o=new Map;for(let m of t?.servers??[])o.set(m.name,m.transport==="http"?new Dm(m.url,t.token):new Rm(m.command,m.args,m.env));let n=t?.servers[0]?.name,i=new Map,a,c,u=m=>a??=Promise.all([...o].map(async([g,y])=>{try{return await y.request("initialize",m),await y.notify("notifications/initialized"),g}catch(_){return process.stderr.write(`myrel-runner mcp-bridge: ${g}: ${_.message}
|
|
68
68
|
`),null}})).then(g=>g.filter(y=>y!==null)),l=async()=>{let m=await(a??u(Ib(e.version)));return(await Promise.all(m.map(async y=>{let _=[],I;try{do{let k=await o.get(y).request("tools/list",I?{cursor:I}:{});_.push(...k.tools??[]),I=k.nextCursor}while(I)}catch(k){process.stderr.write(`myrel-runner mcp-bridge: ${y}: ${k.message}
|
|
69
|
-
`)}return _.map(k=>{let A=y===n?k.name:`${y}${Cz}${k.name}`;return i.set(A,{server:y,tool:k.name}),{...k,name:A}})}))).flat()},d=async m=>{switch(m.method){case"initialize":{let g=m.params??{};return u({...Ib(e.version),...g.protocolVersion&&{protocolVersion:g.protocolVersion}}),{protocolVersion:g.protocolVersion??"2025-06-18",capabilities:{tools:{}},serverInfo:{name:"myrel",version:e.version}}}case"ping":return{};case"tools/list":return{tools:await(c=l())};case"tools/call":{let g=m.params??{};await(c??=l());let y=g.name?i.get(g.name):void 0;if(!y)throw new sn({code:-32602,message:`Unknown tool: ${g.name}`});return o.get(y.server).request("tools/call",{...g,name:y.tool})}default:throw new sn({code:-32601,message:`Method not found: ${m.method}`})}},p=Ab({input:e.input}),f=[];for await(let m of p){let g;try{g=JSON.parse(m)}catch{continue}if(g.id===void 0||g.id===null||!g.method)continue;let y=g.id;f.push(d(g).then(_=>r(JSON.stringify({jsonrpc:"2.0",id:y,result:_})),_=>{let I=_ instanceof sn?_.error:{code:-32603,message:_.message};r(JSON.stringify({jsonrpc:"2.0",id:y,error:I}))}))}await Promise.all(f);for(let m of o.values())m.close()}function Ib(e){return{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"myrel-runner",version:e}}}async function Cb(){let e=process.env[Em];if(!e)return null;let t=await zb(e,"utf8").catch(()=>null);if(!t)return null;try{return JSON.parse(t)}catch{return null}}import{execFile as Mm}from"node:child_process";import{mkdir as cs,readdir as nP,readFile as r$,symlink as rP,writeFile as wi}from"node:fs/promises";import{homedir as i$}from"node:os";import{join as
|
|
69
|
+
`)}return _.map(k=>{let A=y===n?k.name:`${y}${Cz}${k.name}`;return i.set(A,{server:y,tool:k.name}),{...k,name:A}})}))).flat()},d=async m=>{switch(m.method){case"initialize":{let g=m.params??{};return u({...Ib(e.version),...g.protocolVersion&&{protocolVersion:g.protocolVersion}}),{protocolVersion:g.protocolVersion??"2025-06-18",capabilities:{tools:{}},serverInfo:{name:"myrel",version:e.version}}}case"ping":return{};case"tools/list":return{tools:await(c=l())};case"tools/call":{let g=m.params??{};await(c??=l());let y=g.name?i.get(g.name):void 0;if(!y)throw new sn({code:-32602,message:`Unknown tool: ${g.name}`});return o.get(y.server).request("tools/call",{...g,name:y.tool})}default:throw new sn({code:-32601,message:`Method not found: ${m.method}`})}},p=Ab({input:e.input}),f=[];for await(let m of p){let g;try{g=JSON.parse(m)}catch{continue}if(g.id===void 0||g.id===null||!g.method)continue;let y=g.id;f.push(d(g).then(_=>r(JSON.stringify({jsonrpc:"2.0",id:y,result:_})),_=>{let I=_ instanceof sn?_.error:{code:-32603,message:_.message};r(JSON.stringify({jsonrpc:"2.0",id:y,error:I}))}))}await Promise.all(f);for(let m of o.values())m.close()}function Ib(e){return{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"myrel-runner",version:e}}}async function Cb(){let e=process.env[Em];if(!e)return null;let t=await zb(e,"utf8").catch(()=>null);if(!t)return null;try{return JSON.parse(t)}catch{return null}}import{execFile as Mm}from"node:child_process";import{mkdir as cs,readdir as nP,readFile as r$,symlink as rP,writeFile as wi}from"node:fs/promises";import{homedir as i$}from"node:os";import{join as se}from"node:path";import{open as Oz,readdir as Nz,stat as Dz}from"node:fs/promises";import{homedir as Rz}from"node:os";import{join as cn}from"node:path";var Ez={five_hour:"session",seven_day:"weekly",seven_day_opus:"weekly_opus",seven_day_sonnet:"weekly_sonnet"},or=e=>typeof e=="number"&&Number.isFinite(e)?e:null,Ob=e=>e!==null&&e>0?new Date(e*1e3).toISOString():null,Nb=e=>e===null?null:Math.min(1e3,Math.max(0,Math.round(e*10)/10));function Db(e,t){if(!e||typeof e!="object")return t;let r=e,o=new Map((t?.windows??[]).map(a=>[a.kind,a])),n=(a,c,u)=>{let l=typeof a=="string"?Ez[a]:void 0;if(!l)return;let d=or(c),p=o.get(l);o.set(l,{kind:l,usedPercent:d===null?p?.usedPercent??null:Nb(d*100),resetsAt:Ob(or(u))??p?.resetsAt??null})};if(n(r.rateLimitType,r.utilization,r.resetsAt),r.unifiedWindows&&typeof r.unifiedWindows=="object")for(let[a,c]of Object.entries(r.unifiedWindows))c&&typeof c=="object"&&n(a,c.utilization,c.resetsAt);let i={allowed:"ok",allowed_warning:"warning",rejected:"limited"}[String(r.status)];return!o.size&&!i?t:{...i&&{status:i},windows:[...o.values()].slice(0,8),at:new Date().toISOString()}}function Uz(e){return e===300?"session":e===10080?"weekly":e?`${e}m`:"other"}function Um(e,t){if(!e||typeof e!="object")return;let r=[];for(let n of["primary","secondary"]){let i=e[n];if(!i||typeof i!="object")continue;let a=or(i.resets_in_seconds),c=Ob(or(i.resets_at))??(a!==null?new Date(new Date(t).getTime()+a*1e3).toISOString():null);r.push({kind:Uz(or(i.window_minutes)),usedPercent:Nb(or(i.used_percent)),resetsAt:c})}return r.length?{status:r.some(n=>(n.usedPercent??0)>=100&&(!n.resetsAt||n.resetsAt>new Date().toISOString()))?"limited":"ok",windows:r,at:t}:void 0}function Mz(){return process.env.CODEX_HOME||cn(Rz(),".codex")}async function os(e){return(await Nz(e).catch(()=>[])).sort().reverse()}var Lz=256*1024;async function Zz(e){let t=await Oz(e,"r").catch(()=>null);if(t)try{let{size:r}=await t.stat(),o=Math.min(r,Lz),n=Buffer.alloc(o);await t.read(n,0,o,r-o);let i=n.toString("utf8").split(`
|
|
70
70
|
`).reverse();for(let a of i)if(a.includes('"rate_limits"'))try{let c=JSON.parse(a);if(c.payload?.type!=="token_count")continue;let u=typeof c.timestamp=="string"&&!Number.isNaN(Date.parse(c.timestamp))?new Date(c.timestamp).toISOString():(await Dz(e)).mtime.toISOString(),l=Um(c.payload.rate_limits,u);if(l)return l}catch{}return}finally{await t.close()}}async function as(e){let t=cn(Mz(),"sessions"),r=0;for(let o of await os(t))for(let n of await os(cn(t,o)))for(let i of await os(cn(t,o,n))){let a=cn(t,o,n,i);for(let c of await os(a)){if(!c.endsWith(".jsonl")||e&&!c.includes(e))continue;let u=await Zz(cn(a,c));if(u||e)return u;if(++r>=20)return}if(e&&++r>=14)return}}var Rb=()=>cn(Y(),"limits.json");async function Eb(){return await ve(Rb()).catch(()=>{})??{}}async function Ub(e){await Xe(Rb(),e)}import{mkdir as Fz,writeFile as Vz}from"node:fs/promises";import{join as Mb}from"node:path";var Kz=String.raw`
|
|
71
71
|
const REVIEW_MS = 60_000;
|
|
72
72
|
const ASK_MS = 15 * 60_000;
|
|
@@ -257,64 +257,64 @@ export default {
|
|
|
257
257
|
},
|
|
258
258
|
};
|
|
259
259
|
`;async function Lb(e,t){let{url:r,folders:o,reviewModel:n}=t,i=n?.indexOf("/")??-1,a=i>0?{providerID:n.slice(0,i),id:n.slice(i+1)}:void 0,c=Mb(e,"opencode-review");return await Fz(c,{recursive:!0,mode:448}),await Vz(Mb(c,"index.js"),Kz,{mode:384}),{package:c,options:{url:r,folders:o,...a&&{model:a}}}}import{execFile as Jz}from"node:child_process";import{existsSync as Zb}from"node:fs";import{homedir as Fb}from"node:os";import{delimiter as Vb,dirname as Bz,join as ke}from"node:path";async function Kb(){let e=[Bz(process.execPath),...process.platform==="win32"?[...await Xz(),...Yz()]:Qz()];process.env.PATH=Wz(process.env.PATH??"",e,Vb,process.platform==="win32")}function Wz(e,t,r=Vb,o=!1){let n=c=>{let u=c.trim().replace(/[\\/]+$/,"");return o?u.toLowerCase():u},i=e.split(r).filter(Boolean),a=new Set(i.map(n));for(let c of t)!c.trim()||a.has(n(c))||(a.add(n(c)),i.push(c.trim()));return i.join(r)}function Gz(e,t=process.env){let r=new Map(Object.entries(t).map(([o,n])=>[o.toLowerCase(),n]));return e.replace(/%([^%;]+)%/g,(o,n)=>r.get(n.toLowerCase())??o)}function qz(e){return e.split(/\r?\n/).find(r=>/^\s*Path\s+REG_(EXPAND_)?SZ\s/i.test(r))?.replace(/^\s*Path\s+REG_(EXPAND_)?SZ\s+/i,"").trim()||void 0}var Hz=["HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment","HKCU\\Environment"];async function Xz(){return(await Promise.all(Hz.map(t=>new Promise(r=>{Jz("reg",["query",t,"/v","Path"],{timeout:5e3,windowsHide:!0},(o,n)=>r(o?void 0:qz(n)))})))).flatMap(t=>t?Gz(t).split(";"):[])}function Yz(){let e=Fb(),t=process.env.APPDATA??ke(e,"AppData","Roaming"),r=process.env.LOCALAPPDATA??ke(e,"AppData","Local");return[ke(t,"npm"),process.env.PNPM_HOME??ke(r,"pnpm"),ke(e,".bun","bin"),ke(e,".local","bin"),ke(e,"scoop","shims"),ke(r,"Microsoft","WinGet","Links"),ke(r,"Volta","bin")].filter(o=>Zb(o))}function Qz(e=Fb()){return[ke(e,".local","bin"),ke(e,".opencode","bin"),ke(e,".bun","bin"),ke(e,".npm-global","bin"),process.env.PNPM_HOME??ke(e,process.platform==="darwin"?"Library/pnpm":".local/share/pnpm"),ke(e,".volta","bin")].filter(t=>Zb(t))}function un(e,t,r){e.progress=t;let o=r&&eP(e,r);o?e.progressAgent=o:delete e.progressAgent}function Dt(e,t,r,o="",n={}){let i=e.agents??=new Map;if(i.has(t)||i.size>=100)return;let a=r.trim().slice(0,100)||`Agent ${i.size+1}`;i.set(t,{label:a,started:Date.now(),...n.background&&{background:!0},...n.model&&{model:n.model.slice(0,200)}}),(e.agentNotes??=[]).push({text:tP(o),agent:{id:t,label:a,state:"started"}})}function Ye(e,t,r,o=""){let n=e.agents?.get(t);if(!n||n.done)return;n.done=!0;let i={id:t,label:n.label,state:r?"done":"failed",...n.model&&{model:n.model},...n.tokens&&{tokens:n.tokens}};(e.agentNotes??=[]).push({text:o.trim().slice(0,2e3),agent:i,ms:Date.now()-n.started})}function ss(e,t,r,o){let n=e.agents?.get(t);n&&(n.tokens=(n.tokens??0)+Math.max(0,Math.round(r)),o&&!n.model&&(n.model=o.slice(0,200)))}function eP(e,t){e.agents?.has(t)||Dt(e,t,"");let r=e.agents?.get(t);return r&&{id:t,label:r.label}}function tP(e){return(e.trim().split(`
|
|
260
|
-
`)[0]??"").slice(0,200)}function Qe(e){return!!e&&e.length<=200&&/^[A-Za-z0-9][\w.:/@+-]*$/.test(e)}function ls(e){let t={...Qe(e?.model)&&{model:e.model},...Qe(e?.effort)&&{effort:e.effort}};return t.model||t.effort?t:void 0}function Lm(e,t){let r=ls(t);return r&&e.modelArgs?e.modelArgs(r):[]}function ht(e,t,r=2e4){return new Promise(o=>{Mm(e,t,{timeout:r,maxBuffer:4*1024*1024,shell:process.platform==="win32",env:Ue()},(n,i)=>{o(n?null:i)})})}function iP(e){let t=e.replace(/\s+/g," "),r=Jb(t,"--model <model>","(e.g. ")?.match(/'[a-z0-9-]+'/g)?.map(n=>n.slice(1,-1));if(!r?.length)return;let o=Jb(t,"--effort <level>","(")?.split(",").map(n=>n.trim()).filter(Qe)??[];return[...r,...r.includes("haiku")?[]:["haiku"]].map(n=>({id:n,name:n[0].toUpperCase()+n.slice(1),efforts:n==="haiku"?[]:o}))}function Jb(e,t,r){let o=e.indexOf(t);if(o<0)return;let n=e.slice(o+t.length,o+t.length+400),i=n.indexOf(r),a=i<0?-1:n.indexOf(")",i+r.length);return a<0?void 0:n.slice(i+r.length,a)}function oP(e){try{let{models:t}=JSON.parse(e);if(!Array.isArray(t))return;let r=t.flatMap(o=>{if(typeof o.slug!="string"||!Qe(o.slug)||o.visibility==="hide")return[];let i=(Array.isArray(o.supported_reasoning_levels)?o.supported_reasoning_levels:[]).map(a=>a?.effort).filter(a=>typeof a=="string"&&Qe(a));return[{id:o.slug,name:typeof o.display_name=="string"?o.display_name:o.slug,efforts:i}]});return r.length?r.slice(0,100):void 0}catch{return}}function Zm(e){let t=e.split(/\r?\n/).flatMap(r=>{let o=r.trim(),n=o.indexOf(" "),i=n>=0?n:o.indexOf(" - "),a=i>=0?o.slice(0,i).trim():o,c=i>=0?o.slice(i+(n>=0?1:3)).trim():"";return!Qe(a)||/^(available|fetching|loading)$/i.test(a)||a.endsWith(":")?[]:[{id:a,name:c||a,efforts:[]}]});return t.length?t.slice(0,100):void 0}var ye="myrel",aP="mcp__myrel__approve_access",sP=new Set(["failed","needs-auth"]),cP=900*1e3,Bb=1e4,us="MYREL_MCP_TOKEN";function Je(e){return process.platform==="win32"?`"${e}"`:e}async function $i(e,t,r){let o=
|
|
260
|
+
`)[0]??"").slice(0,200)}function Qe(e){return!!e&&e.length<=200&&/^[A-Za-z0-9][\w.:/@+-]*$/.test(e)}function ls(e){let t={...Qe(e?.model)&&{model:e.model},...Qe(e?.effort)&&{effort:e.effort}};return t.model||t.effort?t:void 0}function Lm(e,t){let r=ls(t);return r&&e.modelArgs?e.modelArgs(r):[]}function ht(e,t,r=2e4){return new Promise(o=>{Mm(e,t,{timeout:r,maxBuffer:4*1024*1024,shell:process.platform==="win32",env:Ue()},(n,i)=>{o(n?null:i)})})}function iP(e){let t=e.replace(/\s+/g," "),r=Jb(t,"--model <model>","(e.g. ")?.match(/'[a-z0-9-]+'/g)?.map(n=>n.slice(1,-1));if(!r?.length)return;let o=Jb(t,"--effort <level>","(")?.split(",").map(n=>n.trim()).filter(Qe)??[];return[...r,...r.includes("haiku")?[]:["haiku"]].map(n=>({id:n,name:n[0].toUpperCase()+n.slice(1),efforts:n==="haiku"?[]:o}))}function Jb(e,t,r){let o=e.indexOf(t);if(o<0)return;let n=e.slice(o+t.length,o+t.length+400),i=n.indexOf(r),a=i<0?-1:n.indexOf(")",i+r.length);return a<0?void 0:n.slice(i+r.length,a)}function oP(e){try{let{models:t}=JSON.parse(e);if(!Array.isArray(t))return;let r=t.flatMap(o=>{if(typeof o.slug!="string"||!Qe(o.slug)||o.visibility==="hide")return[];let i=(Array.isArray(o.supported_reasoning_levels)?o.supported_reasoning_levels:[]).map(a=>a?.effort).filter(a=>typeof a=="string"&&Qe(a));return[{id:o.slug,name:typeof o.display_name=="string"?o.display_name:o.slug,efforts:i}]});return r.length?r.slice(0,100):void 0}catch{return}}function Zm(e){let t=e.split(/\r?\n/).flatMap(r=>{let o=r.trim(),n=o.indexOf(" "),i=n>=0?n:o.indexOf(" - "),a=i>=0?o.slice(0,i).trim():o,c=i>=0?o.slice(i+(n>=0?1:3)).trim():"";return!Qe(a)||/^(available|fetching|loading)$/i.test(a)||a.endsWith(":")?[]:[{id:a,name:c||a,efforts:[]}]});return t.length?t.slice(0,100):void 0}var ye="myrel",aP="mcp__myrel__approve_access",sP=new Set(["failed","needs-auth"]),cP=900*1e3,Bb=1e4,us="MYREL_MCP_TOKEN";function Je(e){return process.platform==="win32"?`"${e}"`:e}async function $i(e,t,r){let o=se(e,t);return await wi(o,JSON.stringify(r),{mode:384}),process.platform==="win32"?`"${o}"`:o}var uP=["create","comment","edit","close","reopen","delete"].map(e=>`Bash(gh issue ${e}:*)`),Wb=["ssh","scp","sftp","rsync"].map(e=>`Bash(${e}:*)`),lP=["~/.ssh/**","~/.myrel-runner/ssh/**"].flatMap(e=>[`Read(${e})`,`Edit(${e})`]),dP={id:"claude",bin:"claude",args:({access:e,resume:t,extra:r=[],dirs:o=[],asks:n,stream:i})=>["-p","--output-format","stream-json","--verbose",...i?["--input-format","stream-json","--replay-user-messages"]:[],"--permission-mode",{read:"plan",edit:"acceptEdits",auto:"auto",full:n?"acceptEdits":"bypassPermissions"}[e],...o.flatMap(a=>["--add-dir",Je(a)]),...n?["--permission-prompt-tool",aP]:[],...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n,asks:i,access:a}){let c={Authorization:`Bearer ${t}`},u={[ye]:{type:"http",url:e,headers:c,alwaysLoad:!0}};for(let m of o)u[m.name]=m.transport==="http"?{type:"http",url:m.url,headers:c}:{type:"stdio",command:m.command,args:m.args,env:m.env};let l=await $i(r,"mcp.json",{mcpServers:u}),d=[ye,...o.map(m=>m.name)].map(m=>`mcp__${m}`);i&&a==="full"&&d.push("Bash","WebFetch","WebSearch");let p=await $i(r,"settings.json",{permissions:{...i&&{ask:Wb},deny:lP}}),f=n?["--plugin-dir",Je(n.plugin),"--add-dir",Je(n.dir)]:[];return{args:["--mcp-config",l,"--strict-mcp-config","--allowedTools",d.join(","),"--disallowedTools",["Bash(gh pr create:*)",...uP,...i?[]:Wb].join(","),"--settings",p,...f],env:{ENABLE_CLAUDEAI_MCP_SERVERS:"false",...!process.env.MCP_TIMEOUT&&{MCP_TIMEOUT:String(Bb)},...i&&{MCP_TOOL_TIMEOUT:String(cP)}}}},streamInput:!0,async coordinator({url:e,token:t,dir:r,system:o}){if(!await RP("claude"))return null;let n=await $i(r,"mcp.json",{mcpServers:{[ye]:{type:"http",url:e,headers:{Authorization:`Bearer ${t}`},alwaysLoad:!0}}}),i=se(r,"system.md");return await wi(i,o,{mode:384}),{args:["-p","--output-format","stream-json","--verbose","--tools",process.platform==="win32"?'""':"","--permission-mode","dontAsk","--mcp-config",n,"--strict-mcp-config","--allowedTools",`mcp__${ye}`,"--system-prompt-file",Je(i),"--disable-slash-commands","--no-session-persistence"],env:{ENABLE_CLAUDEAI_MCP_SERVERS:"false",...!process.env.MCP_TIMEOUT&&{MCP_TIMEOUT:String(Bb)}}}},line(e,t){let r=sr(e);if(!r)return;if(t.claudeStream?.receive(r),typeof r.session_id=="string"&&(t.sessionId=r.session_id),r.type==="system"&&typeof r.model=="string"&&(t.model=r.model),r.type==="system"&&r.subtype==="init"&&Array.isArray(r.mcp_servers)){let n=r.mcp_servers.find(i=>i?.name===ye);typeof n?.status=="string"&&sP.has(n.status)&&(t.mcpDown=n.status)}r.type==="rate_limit_event"&&(t.limits=Db(r.rate_limit_info,t.limits));let o=typeof r.parent_tool_use_id=="string"&&r.parent_tool_use_id?r.parent_tool_use_id:void 0;if(r.type==="assistant"){let n=r.message??{};if(typeof n.model=="string"&&!o&&(t.model=n.model),typeof n.id=="string"&&n.usage&&!t.counted?.has(n.id)){(t.counted??=new Set).add(n.id);let a=n$(n.usage);Km(t,a),o&&ss(t,o,a.inputTokens+a.outputTokens,typeof n.model=="string"?n.model:void 0)}let i=n.content??[];for(let a of i)if(a.type==="tool_use"){let c=a.input??{};if(UP.has(String(a.name))&&typeof a.id=="string"){let u=typeof c.subagent_type=="string"?c.subagent_type:"Agent",l=typeof c.description=="string"?c.description:"";Dt(t,a.id,u,l,{background:c.run_in_background===!0})}else un(t,Rt(String(a.name),a.input),o)}else a.type==="text"&&typeof a.text=="string"&&a.text.trim()&&un(t,gt(a.text),o)}if(r.type==="user"){let n=(r.message??{}).content;for(let i of Array.isArray(n)?n:[]){let a=i.type==="tool_result"&&typeof i.tool_use_id=="string"?t.agents?.get(i.tool_use_id):void 0;a&&!a.background&&Ye(t,i.tool_use_id,i.is_error!==!0,MP(i.content))}}if(r.type==="system"&&r.subtype==="task_notification"&&typeof r.tool_use_id=="string"){let n=typeof r.summary=="string"?r.summary:"";Ye(t,r.tool_use_id,r.status==="completed",n)}if(r.type==="result"){if(r.usage){let n=n$(r.usage),i=t.usage??{inputTokens:0,outputTokens:0};t.usage={inputTokens:Math.max(i.inputTokens,n.inputTokens),outputTokens:Math.max(i.outputTokens,n.outputTokens)}}t.result=typeof r.result=="string"?r.result:"",t.failed=r.is_error===!0||typeof r.subtype=="string"&&r.subtype!=="success"}},models:async()=>iP(await ht("claude",["--help"])??""),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]},Gb={read:"read-only",edit:"workspace-write",auto:"workspace-write",full:"danger-full-access"},pP={id:"codex",bin:"codex",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["exec","--json","--skip-git-repo-check","--sandbox",Gb[e],...o.flatMap(n=>["--add-dir",Je(n)]),...r,...t?["resume",t]:[],"-"],agent:async({url:e,token:t,connectors:r=[],access:o})=>{let n=c=>["-c",`mcp_servers.${c}.default_tools_approval_mode="approve"`],i=(c,u)=>["-c",`mcp_servers.${c}.url=${JSON.stringify(u)}`,"-c",`mcp_servers.${c}.bearer_token_env_var=${JSON.stringify(us)}`,...n(c)],a=i(ye,e);for(let c of r){if(c.transport==="http"){a.push(...i(c.name,c.url));continue}let u=Object.entries(c.env).map(([l,d])=>`${l} = ${JSON.stringify(d)}`);a.push("-c",`mcp_servers.${c.name}.command=${JSON.stringify(c.command)}`,"-c",`mcp_servers.${c.name}.args=${JSON.stringify(c.args)}`),u.length&&a.push("-c",`mcp_servers.${c.name}.env={ ${u.join(", ")} }`),a.push(...n(c.name))}return o&&o!=="read"&&a.push("-c",'apps._default.default_tools_approval_mode="approve"'),{args:a,env:{[us]:t}}},appServer:({access:e,dirs:t,asks:r})=>({...t.length&&{config:{"sandbox_workspace_write.writable_roots":t}},sandbox:Gb[e],approvalPolicy:e==="auto"||r&&e==="edit"?"on-request":"never",approvalsReviewer:e==="auto"?"auto_review":"user"}),line(e,t){if(t.appServer)return t.appServer.receive(e);let r=sr(e);if(!r)return;r.type==="thread.started"&&typeof r.thread_id=="string"&&(t.sessionId=r.thread_id);let o=r.item;if(o?.type==="command_execution"&&typeof o.command=="string"&&(t.progress=gt(`$ ${ir(o.command)}`)),r.type==="item.completed"&&o?.type==="agent_message"&&typeof o.text=="string"&&(t.result=o.text,t.progress=gt(o.text)),r.type==="turn.completed"&&r.usage){let i=r.usage;Km(t,{inputTokens:oe(i.input_tokens),outputTokens:oe(i.output_tokens)})}let n=r.error?.message??r.message;r.type==="error"&&typeof n=="string"&&(t.error=n),r.type==="turn.failed"&&(t.failed=!0,t.result=typeof n=="string"?n:t.error),r.type==="turn.completed"&&(t.failed=!1)},limits:e=>as(e.sessionId),models:async()=>oP(await ht("codex",["debug","models"])??""),modelArgs:({model:e,effort:t})=>[...e?["-m",e]:[],...t?["-c",`model_reasoning_effort=${JSON.stringify(t)}`]:[]]},mP="(myrel-runner: in this run you cannot run shell commands, open web pages or use any tool that needs approval: asking for one ends your run at once, with no answer. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",fP={id:"antigravity",bin:"agy",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["--output-format","stream-json","--input-format","stream-json",...{read:["--mode","plan"],edit:["--mode","accept-edits"],auto:["--mode","accept-edits"],full:["--dangerously-skip-permissions"]}[e],...o.flatMap(n=>["--add-dir",Je(n)]),...t?["--conversation",t]:[],...r],input:(e,t)=>{let r=t==="full"?e:`${e}
|
|
261
261
|
|
|
262
262
|
${mP}`;return`${JSON.stringify({event:"user",message:{content:r}})}
|
|
263
|
-
`},async agent({url:e,token:t,dir:r,connectors:o=[],skills:n}){await jb(ye);let i={token:t,servers:[{transport:"http",name:ye,url:e},...o]},a=await $i(r,"bridge.json",i);return{args:n?["--add-dir",Je(n.dir)]:[],env:{[Em]:a.replace(/^"|"$/g,"")}}},line(e,t){let r=sr(e);if(!r)return;typeof r.conversation_id=="string"&&r.conversation_id&&(t.sessionId=r.conversation_id);let o=r.init;if(r.event==="init"&&typeof o?.model=="string"&&(t.model=o.model),r.event==="step_update"){let n=r.step_update??{},i=n.tool_info;if(n.step_type==="tool"&&n.state==="ACTIVE"){let a=typeof i?.name=="string"?i.name:n.tool_name;typeof a=="string"&&(t.progress=Rt(a,i?.parameters))}n.step_type==="agent_response"&&typeof n.text_delta=="string"&&(t.draft=n.step_index===t.draftStep?(t.draft??"")+n.text_delta:n.text_delta,t.draftStep=n.step_index,t.draft.trim()&&(t.progress=gt(t.draft)))}if(r.event==="result"){let n=r.result??{};typeof n.conversation_id=="string"&&n.conversation_id&&(t.sessionId=n.conversation_id);let i=n.usage??{},a=oe(i.output_tokens)+oe(i.thinking_tokens),c=Math.max(oe(i.input_tokens),oe(i.total_tokens)-a);(c||a)&&(t.usage={inputTokens:c,outputTokens:a}),t.failed=n.status!=="SUCCESS",t.result=t.failed&&typeof n.error=="string"&&n.error?n.error:typeof n.response=="string"?n.response:"";let u=Array.isArray(n.denied_actions)?n.denied_actions:[];if(u.length&&!t.result.trim()){let l=[...new Set(u.map(d=>String(d.action??"a tool")))].join(", ");t.failed=!0,t.result=`Antigravity CLI stopped: a step needed the "${l}" permission, which it cannot ask for when Myrel runs it. Set this computer's access to full in Myrel > Devices, or allow it under permissions.allow in ~/.gemini/antigravity-cli/settings.json (for example command(git)).`}}},models:async()=>Zm(await ht("agy",["models"],3e4)??""),modelArgs:({model:e})=>e?["--model",e]:[]},o$={read:{edit:"deny",bash:"deny"},edit:{edit:"allow",bash:"deny"},auto:{edit:"allow",bash:"deny"},full:{edit:"allow",bash:"allow"}},gP={id:"opencode",bin:"opencode",args:({access:e,resume:t,extra:r=[]})=>["run","--format","json",...e==="full"?["--auto"]:[],...t?["--session",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n,access:i="edit",dirs:a=[],reviewModel:c}){let u=await _i("opencode"),l={Authorization:`Bearer {env:${us}}`},d={[ye]:{type:"remote",url:e,headers:l,oauth:!1}};for(let m of o)d[m.name]=m.transport==="http"?{type:"remote",url:m.url,headers:l,oauth:!1}:{type:"local",command:[m.command,...m.args],environment:m.env};let p=[...a,...n?[n.dir]:[]],f;if(a$(u)>=2)f=
|
|
263
|
+
`},async agent({url:e,token:t,dir:r,connectors:o=[],skills:n}){await jb(ye);let i={token:t,servers:[{transport:"http",name:ye,url:e},...o]},a=await $i(r,"bridge.json",i);return{args:n?["--add-dir",Je(n.dir)]:[],env:{[Em]:a.replace(/^"|"$/g,"")}}},line(e,t){let r=sr(e);if(!r)return;typeof r.conversation_id=="string"&&r.conversation_id&&(t.sessionId=r.conversation_id);let o=r.init;if(r.event==="init"&&typeof o?.model=="string"&&(t.model=o.model),r.event==="step_update"){let n=r.step_update??{},i=n.tool_info;if(n.step_type==="tool"&&n.state==="ACTIVE"){let a=typeof i?.name=="string"?i.name:n.tool_name;typeof a=="string"&&(t.progress=Rt(a,i?.parameters))}n.step_type==="agent_response"&&typeof n.text_delta=="string"&&(t.draft=n.step_index===t.draftStep?(t.draft??"")+n.text_delta:n.text_delta,t.draftStep=n.step_index,t.draft.trim()&&(t.progress=gt(t.draft)))}if(r.event==="result"){let n=r.result??{};typeof n.conversation_id=="string"&&n.conversation_id&&(t.sessionId=n.conversation_id);let i=n.usage??{},a=oe(i.output_tokens)+oe(i.thinking_tokens),c=Math.max(oe(i.input_tokens),oe(i.total_tokens)-a);(c||a)&&(t.usage={inputTokens:c,outputTokens:a}),t.failed=n.status!=="SUCCESS",t.result=t.failed&&typeof n.error=="string"&&n.error?n.error:typeof n.response=="string"?n.response:"";let u=Array.isArray(n.denied_actions)?n.denied_actions:[];if(u.length&&!t.result.trim()){let l=[...new Set(u.map(d=>String(d.action??"a tool")))].join(", ");t.failed=!0,t.result=`Antigravity CLI stopped: a step needed the "${l}" permission, which it cannot ask for when Myrel runs it. Set this computer's access to full in Myrel > Devices, or allow it under permissions.allow in ~/.gemini/antigravity-cli/settings.json (for example command(git)).`}}},models:async()=>Zm(await ht("agy",["models"],3e4)??""),modelArgs:({model:e})=>e?["--model",e]:[]},o$={read:{edit:"deny",bash:"deny"},edit:{edit:"allow",bash:"deny"},auto:{edit:"allow",bash:"deny"},full:{edit:"allow",bash:"allow"}},gP="Cancelled a request for input this run cannot answer",hP={id:"opencode",bin:"opencode",args:({access:e,resume:t,extra:r=[]})=>["run","--format","json",...e==="full"?["--auto"]:[],...t?["--session",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n,access:i="edit",dirs:a=[],reviewModel:c}){let u=await _i("opencode"),l={Authorization:`Bearer {env:${us}}`},d={[ye]:{type:"remote",url:e,headers:l,oauth:!1}};for(let m of o)d[m.name]=m.transport==="http"?{type:"remote",url:m.url,headers:l,oauth:!1}:{type:"local",command:[m.command,...m.args],environment:m.env};let p=[...a,...n?[n.dir]:[]],f;if(a$(u)>=2)f=yP(d,i,p,n?.dir),i==="auto"&&(f.permissions.push({action:"shell",resource:"*",effect:"ask"}),f.plugins=[await Lb(r,{url:e,folders:p,...Qe(c)&&{reviewModel:c}})]);else{let m={...o$[i]};for(let g of Object.keys(d))m[`${g}_*`]="allow";p.length&&(m.external_directory=Object.fromEntries(p.flatMap(g=>[[g,"allow"],[se(g,"*"),"allow"]]))),f={mcp:d,permission:m,...n&&{skills:{paths:[n.dir]}},experimental:{continue_loop_on_deny:!0}}}return{args:vP(u),env:{OPENCODE_CONFIG_CONTENT:JSON.stringify(f),[us]:t}}},line(e,t){let r=sr(e);if(!r)return;typeof r.sessionID=="string"&&r.sessionID&&(t.sessionId=r.sessionID);let o=r.part??{};if(r.type==="tool_use"&&typeof o.tool=="string"&&(t.progress=Rt(o.tool,o.state?.input)),r.type==="text"&&typeof o.text=="string"&&o.text.trim()&&(t.draft=o.messageID===t.draftStep&&t.draft?`${t.draft}
|
|
264
264
|
|
|
265
|
-
${o.text}`:o.text,t.draftStep=o.messageID,t.result=t.draft,t.progress=gt(o.text)),r.type==="step_finish"){let n=o.tokens??{},i=n.cache??{};Km(t,{inputTokens:oe(n.input)+oe(i.read)+oe(i.write),outputTokens:oe(n.output)+oe(n.reasoning)})}if(r.type==="error"){let n=r.error??{},i=[n.data?.message,n.message,n.name].find(a=>typeof a=="string"&&a);t.failed=!0,t.result=typeof i=="string"?i:"opencode reported an error."}},models:async()=>Zm(await ht("opencode",["models"])??""),modelArgs:({model:e})=>e?["--model",e]:[]};function a$(e){return Number(/\d+/.exec(e??"")?.[0]??0)}function
|
|
265
|
+
${o.text}`:o.text,t.draftStep=o.messageID,t.result=t.draft,t.progress=gt(o.text)),(r.type==="step_start"||r.type==="step_finish")&&(t.draftDone=r.type==="step_finish"&&o.reason==="stop"),r.type==="step_finish"){let n=o.tokens??{},i=n.cache??{};Km(t,{inputTokens:oe(n.input)+oe(i.read)+oe(i.write),outputTokens:oe(n.output)+oe(n.reasoning)})}if(r.type==="error"){let n=r.error??{},i=[n.data?.message,n.message,n.name].find(a=>typeof a=="string"&&a);if(t.draftDone&&typeof i=="string"&&i.startsWith(gP)){t.completed=!0;return}t.failed=!0,t.result=typeof i=="string"?i:"opencode reported an error."}},models:async()=>Zm(await ht("opencode",["models"])??""),modelArgs:({model:e})=>e?["--model",e]:[]};function a$(e){return Number(/\d+/.exec(e??"")?.[0]??0)}function vP(e){return a$(e)>=2?["--standalone"]:[]}function yP(e,t,r,o){let n=[];t!=="full"&&n.push({action:"external_directory",resource:"*",effect:"deny"});for(let c of r)n.push({action:"external_directory",resource:c,effect:"allow"}),n.push({action:"external_directory",resource:se(c,"*"),effect:"allow"});let i=o$[t];n.push({action:"edit",resource:"*",effect:i.edit}),n.push({action:"shell",resource:"*",effect:i.bash});for(let c of Object.keys(e))n.push({action:`${c}_*`,resource:"*",effect:"allow"});let a={};for(let[c,u]of Object.entries(e))a[c]={...u,codemode:!1};return{mcp:{servers:a},permissions:n,...o&&{skills:[o]}}}var qb={read:"(myrel-runner: this run may only read. Do not change files or run commands that change anything: steps that need approval are declined.)",edit:"(myrel-runner: steps that need approval, such as dangerous commands or sensitive files, are declined in this run. Do not run commands that change anything outside this folder.)",auto:"(myrel-runner: steps that need approval, such as dangerous commands or sensitive files, are declined in this run. Do not run commands that change anything outside this folder.)",full:null};function Fm({url:e,token:t,connectors:r=[]}){let o=[{name:"Authorization",value:`Bearer ${t}`}],n=[{type:"http",name:ye,url:e,headers:o}];for(let i of r)n.push(i.transport==="http"?{type:"http",name:i.name,url:i.url,headers:o}:{name:i.name,command:i.command,args:i.args,env:Object.entries(i.env).map(([a,c])=>({name:a,value:c}))});return n}var bP={id:"hermes",bin:"hermes",args:({extra:e=[]})=>["acp",...e],acp:e=>({mode:{read:"default",edit:"accept_edits",auto:"accept_edits",full:"dont_ask"}[e],allow:e==="full"}),input:(e,t)=>qb[t]?`${e}
|
|
266
266
|
|
|
267
|
-
${qb[t]}`:e,agent:async e=>({args:[],mcpServers:Fm(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>e.startsWith("Hermes Agent")}
|
|
267
|
+
${qb[t]}`:e,agent:async e=>({args:[],mcpServers:Fm(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>e.startsWith("Hermes Agent")},$P={read:["--mode","ask"],edit:["--sandbox","enabled"],auto:["--sandbox","enabled"],full:["--force","--sandbox","disabled"]},xP={id:"cursor",bin:"cursor-agent",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["-p","--output-format","stream-json","--trust",...$P[e],...o.flatMap(n=>["--add-dir",Je(n)]),...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n}){let i=se(r,ye);await cs(se(i,".cursor-plugin"),{recursive:!0}),await wi(se(i,".cursor-plugin","plugin.json"),JSON.stringify({name:ye,description:"Myrel's tools for this run.",version:"1.0.0"}));let a={Authorization:`Bearer ${t}`},c={[ye]:{url:e,headers:a}};for(let d of o)c[d.name]=d.transport==="http"?{url:d.url,headers:a}:{command:d.command,args:d.args,env:d.env};await $i(i,"mcp.json",{mcpServers:c}),n&&(await cs(se(n.plugin,".cursor-plugin"),{recursive:!0}),await wi(se(n.plugin,".cursor-plugin","plugin.json"),JSON.stringify({name:`${ye}-skills`,description:"Skills added in Myrel for this run.",version:"1.0.0"})));let u=await _P(se(r,"cursor-config"),Object.keys(c).map(d=>`Mcp(plugin-${ye}-${d}:*)`));return{args:["--approve-mcps",...[i,...n?[n.plugin]:[]].flatMap(d=>["--plugin-dir",Je(d)])],env:{CURSOR_CONFIG_DIR:u}}},line(e,t){let r=sr(e);if(r){if(typeof r.session_id=="string"&&r.session_id&&(t.sessionId=r.session_id),r.type==="system"&&typeof r.model=="string"&&(t.model=r.model),r.type==="tool_call"&&r.subtype==="started"){let o=r.tool_call??{},[n,i]=Object.entries(o).find(([c])=>c.endsWith("ToolCall")||c==="function")??[],a=i?.args;n==="mcpToolCall"&&typeof a?.toolName=="string"?t.progress=Rt(a.toolName,a.args):n==="function"&&typeof i?.name=="string"?t.progress=Rt(i.name,l$(i.arguments)):n&&(t.progress=Rt(n.replace(/ToolCall$/,""),a))}if(r.type==="assistant"){let n=(r.message?.content??[]).map(i=>i.type==="text"&&typeof i.text=="string"?i.text:"").join("");n.trim()&&(t.draft=n,t.progress=gt(n))}if(r.type==="result"){t.result=t.draft??(typeof r.result=="string"?r.result:""),t.failed=r.is_error===!0||r.subtype!=="success";let o=r.usage??{},n=oe(o.inputTokens)+oe(o.cacheReadTokens)+oe(o.cacheWriteTokens);(n||oe(o.outputTokens))&&(t.usage={inputTokens:n,outputTokens:oe(o.outputTokens)})}}},models:async()=>Zm(await ht("cursor-agent",["models"])??""),modelArgs:({model:e})=>e?["--model",e]:[]};function wP(){return process.env.CURSOR_CONFIG_DIR?.trim()||(process.env.XDG_CONFIG_HOME?.trim()?se(process.env.XDG_CONFIG_HOME,"cursor"):se(i$(),".cursor"))}async function _P(e,t,r=wP()){await cs(e,{recursive:!0});let o=await r$(se(r,"cli-config.json"),"utf8").then(JSON.parse,()=>null)??{version:1},n=o.permissions??{};return o.permissions={...n,allow:[...Array.isArray(n.allow)?n.allow:[],...t]},await wi(se(e,"cli-config.json"),JSON.stringify(o),{mode:384}),await cs(se(r,"chats"),{recursive:!0}).then(()=>rP(se(r,"chats"),se(e,"chats"),process.platform==="win32"?"junction":"dir")).catch(()=>{}),e}var kP={read:["--approval-mode","never","--disable-write","--disable-shell"],edit:["--approval-mode","never","--trust-workspace"],auto:["--approval-mode","never","--trust-workspace"],full:["--yolo"]},SP=["--context-compaction-soft-threshold","0.15"],Hb="MYREL_MCP_AUTH",IP={id:"muse",bin:"muse",promptFile:!0,args:({access:e,resume:t,extra:r=[],promptFile:o})=>["exec","--json",...SP,...kP[e],...t?["--session-id",t]:[],...r,...o?["--prompt-file",Je(o)]:[]],async agent({url:e,token:t,connectors:r=[]}){let o={[Hb]:`Bearer ${t}`},n={Authorization:`\${${Hb}}`},i=[[ye,{url:e,headers:n}]];for(let[a,c]of r.entries()){if(c.transport==="http"){i.push([c.name,{url:c.url,headers:n}]);continue}let u=Object.entries(c.env).map(([l,d],p)=>{let f=`MYREL_MCP_${a}_${p}`;return o[f]=d,[l,`\${${f}}`]});i.push([c.name,{command:c.command,args:c.args,env:Object.fromEntries(u)}])}return{args:i.flatMap(([a,c])=>["-c",`mcpServers.${a}=${JSON.stringify(c)}`]),env:o}},line(e,t){let r=sr(e);if(!r)return;let o=r.stream;o?.kind==="session"&&typeof o.id=="string"&&o.id&&(t.sessionId=o.id);let n=r.payload??{};switch(r.payload_type){case"run.model.configured":typeof n.model_id=="string"&&(t.model=n.model_id);break;case"task.lifecycle.proposed":{let i=n.event?.task_kind;typeof i=="string"&&i.startsWith("tool.")&&(t.progress=Rt(i.slice(5),void 0),t.draft=void 0);break}case"tool.result":{let i=n.correlation_facts?.tool_name,a=n.edit_facts,c=typeof n.text=="string"&&n.text.startsWith("{")?l$(n.text)?.command:void 0;typeof c=="string"?t.progress=gt(`$ ${ir(c)}`):typeof i=="string"&&(t.progress=Rt(i,a));break}case"run.output.delta":typeof n.text=="string"&&(t.draft=(t.draft??"")+n.text,t.draft.trim()&&(t.progress=gt(t.draft)));break;case"run.usage":{let i=Array.isArray(n.models)?n.models:[],a=i.reduce((u,l)=>u+oe(l.input_tokens),0),c=i.reduce((u,l)=>u+oe(l.output_tokens),0);(a||c)&&(t.usage={inputTokens:a,outputTokens:c});break}default:if(typeof r.payload_type=="string"&&r.payload_type.startsWith("run.terminal.")){t.failed=n.terminal!=="completed";let i=typeof n.text=="string"?n.text:"",a=typeof n.reason=="string"?n.reason:"";t.result=t.failed?i||a||`Muse Code stopped (${String(n.terminal??"failed")}).`:i||t.draft||""}}},isMine:e=>e.startsWith("Muse Code"),models:()=>zP(),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]};async function zP(){let e=se(process.env.XDG_DATA_HOME?.trim()||se(i$(),".local","share"),"muse","model-catalog"),t=await nP(e).catch(()=>[]),r=await Promise.all(t.filter(i=>i.endsWith(".json")).map(i=>r$(se(e,i),"utf8").then(PP,()=>{}))),o=new Set,n=r.flatMap(i=>i??[]).filter(i=>!o.has(i.id)&&o.add(i.id));return n.length?n:void 0}function PP(e){try{let{rows:t}=JSON.parse(e);return Array.isArray(t)?t.flatMap(r=>{if(typeof r.model_id!="string"||!Qe(r.model_id)||r.visibility==="hidden")return[];let n=(Array.isArray(r.reasoning_effort_variants)?r.reasoning_effort_variants:[]).map(a=>a?.tier).filter(a=>typeof a=="string"&&Qe(a)),i=typeof r.display_label=="string"&&r.display_label?r.display_label:r.model_id;return[{id:r.model_id,name:i,efforts:n}]}):void 0}catch{return}}var Xb={read:"(myrel-runner: this run may only read. Do not change files, run commands that change anything, write a plan file or call ExitPlanMode: steps that need approval are declined. Answer with Myrel's tools.)",edit:"(myrel-runner: in this run shell commands and edits outside this folder's git repository are declined, as is anything else that needs approval. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",auto:"(myrel-runner: in this run shell commands and edits outside this folder's git repository are declined, as is anything else that needs approval. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",full:null},AP={id:"kimi",bin:"kimi",args:({extra:e=[]})=>["acp",...e],acp:(e,t)=>({mode:{read:"plan",edit:"default",auto:"default",full:"auto"}[e],allow:e==="full",serverTools:r=>`mcp__${r}__`,config:[...t?.model?[{id:"model",value:t.model}]:[],...t?.effort?[{id:"thinking",value:t.effort}]:[]]}),input:(e,t)=>Xb[t]?`${e}
|
|
268
268
|
|
|
269
|
-
${Xb[t]}`:e,agent:async e=>({args:[],mcpServers:Fm(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>/^v?\d+\.\d+/.test(e),models:async()=>
|
|
270
|
-
`)[0]??"";return`CodeMode: ${o.length?o.slice(0,10).join(", "):n}`}function
|
|
269
|
+
${Xb[t]}`:e,agent:async e=>({args:[],mcpServers:Fm(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>/^v?\d+\.\d+/.test(e),models:async()=>DP(await ht("kimi",["provider","list","--json"])??"")},Yb={read:"(myrel-runner: this run may only read. Do not change files or run commands: steps that need approval are declined, and a declined step may end your run at once. Answer with Myrel's tools.)",edit:"(myrel-runner: in this run shell commands, web pages and anything else that needs approval are declined, and a declined step may end your run at once. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",auto:"(myrel-runner: in this run a step Qwen Code's safety check does not let through is declined, and a declined step may end your run at once. Keep to this folder and Myrel's tools. If a blocked command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",full:null},jP={read:["run_shell_command","monitor","web_fetch","write_file","edit","notebook_edit","ask_user_question"],edit:["run_shell_command","monitor","web_fetch","ask_user_question"],auto:["ask_user_question"],full:["ask_user_question"]};function TP(e,t){return Number(/^v?(\d+)\./.exec(e??"")?.[1]??0)>=1?[]:jP[t].flatMap(o=>["--exclude-tools",o])}function s$(e){let t=e._meta??{},r=t.qwen?.toolName??t.toolName;return typeof r=="string"?r:void 0}function CP(e){let t=e.rawInput?.code;if(s$(e)!=="CodeMode"||typeof t!="string")return;let r=[...t.matchAll(/\btools(?:\.([A-Za-z_$][\w$]*)|\[\s*(["'`])([^"'`]+)\2\s*\])/g)].map(i=>i[1]??i[3]),o=[...new Set(r)],n=t.trim().split(`
|
|
270
|
+
`)[0]??"";return`CodeMode: ${o.length?o.slice(0,10).join(", "):n}`}function OP(e){let t=s$(e)??e.title;if(t!=="Agent"&&t!=="agent")return;let r=e.rawInput??{},o=n=>typeof n=="string"?n.trim():"";return{label:o(r.subagent_type)||"Agent",purpose:o(r.description),background:r.run_in_background===!0}}var NP={id:"qwen",bin:"qwen",args:({extra:e=[],dirs:t=[]})=>["--acp",...t.flatMap(r=>["--add-dir",Je(r)]),...e],acp:e=>({mode:{read:"default",edit:["acceptEdits","auto-edit"],auto:"auto",full:"yolo"}[e],allow:e==="full",serverTools:t=>`mcp__${t}__`,describe:CP,subagent:OP}),input:(e,t)=>Yb[t]?`${e}
|
|
271
271
|
|
|
272
|
-
${Yb[t]}`:e,agent:async e=>({args:[...
|
|
273
|
-
`)[0]||"failed"}function oe(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0}function n$(e){let t=e??{};return{inputTokens:oe(t.input_tokens)+oe(t.cache_read_input_tokens)+oe(t.cache_creation_input_tokens),outputTokens:oe(t.output_tokens)}}function Km(e,t){let r=e.usage??={inputTokens:0,outputTokens:0};r.inputTokens+=t.inputTokens,r.outputTokens+=t.outputTokens}function sr(e){if(!e.startsWith("{"))return null;try{return JSON.parse(e)}catch{return null}}function l$(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var
|
|
272
|
+
${Yb[t]}`:e,agent:async e=>({args:[...TP(await _i("qwen"),e.access??"edit"),...e.skills?["--add-dir",Je(e.skills.dir)]:[]],mcpServers:Fm(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>/^v?\d+\.\d+/.test(e)};function DP(e){try{let{models:t}=JSON.parse(e);if(!t||typeof t!="object")return;let r=Object.entries(t).flatMap(([o,n])=>{if(!Qe(o)||!n||typeof n!="object")return[];let u=((Array.isArray(n.capabilities)?n.capabilities:[]).some(d=>d==="thinking"||d==="always_thinking")&&Array.isArray(n.supportEfforts)?n.supportEfforts:[]).filter(d=>typeof d=="string"&&d!=="off"&&Qe(d)),l=[n.displayName,n.model].find(d=>typeof d=="string"&&!!d)??o;return[{id:o,name:l,efforts:u}]});return r.length?r.slice(0,100):void 0}catch{return}}var ar={claude:dP,codex:pP,antigravity:fP,opencode:hP,hermes:bP,cursor:xP,muse:IP,kimi:AP,qwen:NP},Vm=process.platform==="win32"?3e4:1e4;function _i(e){return new Promise(t=>{Mm(e,["--version"],{timeout:Vm,shell:process.platform==="win32",env:Ue()},(r,o)=>{t(r?null:xi(o)||null)})})}var Qb=new Map;async function c$(e){if(process.env.MYREL_CODEX_EXEC==="1")return!1;let t=await _i(e);if(!t)return!1;let r=Qb.get(t);return r||(r=ht(e,["app-server","--help"],1e4).then(o=>!!o?.includes("--listen")),Qb.set(t,r)),r}var e$=new Map;async function u$(e){if(process.env.MYREL_CLAUDE_ONESHOT==="1")return!1;let t=await _i(e);if(!t)return!1;let r=e$.get(t);return r||(r=ht(e,["--help"],1e4).then(o=>!!o?.includes("--replay-user-messages")),e$.set(t,r)),r}var t$=new Map;async function RP(e){let t=await _i(e);if(!t)return!1;let r=t$.get(t);return r||(r=ht(e,["--help"],1e4).then(o=>!!o?.includes("--tools <")&&o.includes("dontAsk")),t$.set(t,r)),r}async function ki(e){return await Kb().catch(()=>{}),(await Promise.all(Object.values(ar).map(r=>new Promise(o=>{Mm(r.bin,["--version"],{timeout:Vm,shell:process.platform==="win32",env:Ue(),windowsHide:!0},(n,i,a)=>{if(n||r.isMine&&!r.isMine(xi(i)))return e?.push({id:r.id,reason:n?EP(n,a):`\`${r.bin} --version\` printed "${xi(i)}"`}),o(null);o({id:r.id,version:xi(i)||null})})})))).filter(r=>r!==null)}function EP(e,t=""){return e.killed?`no answer in ${Vm/1e3}s`:e.code==="ENOENT"?"not on PATH":xi(t)||e.message.split(`
|
|
273
|
+
`)[0]||"failed"}function oe(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0}function n$(e){let t=e??{};return{inputTokens:oe(t.input_tokens)+oe(t.cache_read_input_tokens)+oe(t.cache_creation_input_tokens),outputTokens:oe(t.output_tokens)}}function Km(e,t){let r=e.usage??={inputTokens:0,outputTokens:0};r.inputTokens+=t.inputTokens,r.outputTokens+=t.outputTokens}function sr(e){if(!e.startsWith("{"))return null;try{return JSON.parse(e)}catch{return null}}function l$(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var UP=new Set(["Agent","Task"]);function MP(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?String(t.text??""):"").filter(Boolean).join(`
|
|
274
274
|
`):""}function Rt(e,t){let r=t??{},o=r.command??r.file_path??r.filePath??r.path??r.pattern??r.description;return typeof o=="string"?gt(`${e}: ${o}`):e}function gt(e){return e.trim().slice(0,2e3)}function xi(e){return(e.trim().split(`
|
|
275
|
-
`)[0]??"").slice(0,200)}import{randomBytes as
|
|
275
|
+
`)[0]??"").slice(0,200)}import{randomBytes as LP}from"node:crypto";import{createServer as ZP}from"node:http";var m$="MYREL_GIT_CREDENTIALS",FP=40;function d$(e){let t=new Map;for(let{token:r,expiresAt:o,repos:n}of[e,...e.more??[]])for(let i of n)t.set(i.toLowerCase(),{token:r,expiresAt:Date.parse(o)});return t}var ds=class{lent=new Map;keyOf=new Map;port=null;server=null;async lend(t,r){let o=LP(32).toString("hex");this.keyOf.set(t,o),this.lent.set(o,d$(r));try{let n=[r,...r.more??[]].flatMap(i=>i.repos);return VP(`http://127.0.0.1:${await this.listen()}/${o}`,n)}catch(n){throw this.end(t),n}}renew(t,r){let o=this.keyOf.get(t);o&&this.lent.set(o,d$(r))}end(t){let r=this.keyOf.get(t);r&&(this.keyOf.delete(t),this.lent.delete(r),this.lent.size===0&&this.server&&(this.server.close(),this.server=null,this.port=null))}listen(){return this.port??=new Promise((t,r)=>{let o=ZP((n,i)=>{let[a="",...c]=(n.url??"").slice(1).split("/"),u=n.method==="GET"?this.lent.get(a)?.get(c.join("/").toLowerCase()):void 0;if(!u||u.expiresAt<=Date.now()){i.writeHead(404).end();return}i.writeHead(200,{"content-type":"text/plain","cache-control":"no-store"}),i.end(`username=x-access-token
|
|
276
276
|
password=${u.token}
|
|
277
|
-
`)});o.once("error",n=>{this.server=null,this.port=null,r(n)}),this.server=o,o.listen(0,"127.0.0.1",()=>{o.unref(),t(o.address().port)})}),this.port}};function
|
|
278
|
-
`).filter(c=>c.includes("=")).map(c=>[c.slice(0,c.indexOf("=")),c.slice(c.indexOf("=")+1)]));if(!(a.get("protocol")!=="https"||a.get("host")!=="github.com"))try{let c=await fetch(`${i}/${e}`,{signal:AbortSignal.timeout(5e3)});c.ok&&o(await c.text())}catch{}}import{watchFile as
|
|
277
|
+
`)});o.once("error",n=>{this.server=null,this.port=null,r(n)}),this.server=o,o.listen(0,"127.0.0.1",()=>{o.unref(),t(o.address().port)})}),this.port}};function VP(e,t,r=process.env.GIT_CONFIG_PARAMETERS,o=bi()){let n=u=>`!${[o.command,...o.args].map(p$).join(" ")} git-credential ${p$(u)}`,i=[],a=[...new Set(t.slice(0,FP).flatMap(u=>[u,u.toLowerCase()]))];for(let u of a){for(let l of[`https://github.com/${u}`,`https://github.com/${u}.git`])i.push([`credential.${l}.helper`,""],[`credential.${l}.helper`,n(u)]);i.push([`url.https://github.com/${u}.git.insteadOf`,`git@github.com:${u}.git`],[`url.https://github.com/${u}.git.insteadOf`,`ssh://git@github.com/${u}.git`])}let c=i.map(([u,l])=>KP(`${u}=${l}`)).join(" ");return{[m$]:e,GIT_CONFIG_PARAMETERS:r?`${r} ${c}`:c}}var KP=e=>`'${e.replaceAll("'","'\\''")}'`;function p$(e){return`"${(process.platform==="win32"?e.replaceAll("\\","/"):e).replace(/["\\$`]/g,"\\$&")}"`}async function f$(e,t,r,o){let n="";for await(let c of r)n+=String(c);let i=process.env[m$];if(t!=="get"||!i||!e)return;let a=new Map(n.split(`
|
|
278
|
+
`).filter(c=>c.includes("=")).map(c=>[c.slice(0,c.indexOf("=")),c.slice(c.indexOf("=")+1)]));if(!(a.get("protocol")!=="https"||a.get("host")!=="github.com"))try{let c=await fetch(`${i}/${e}`,{signal:AbortSignal.timeout(5e3)});c.ok&&o(await c.text())}catch{}}import{watchFile as IT,unwatchFile as zT}from"node:fs";import{hostname as kf,platform as Dx}from"node:os";import{execFile as JP}from"node:child_process";import{platform as BP}from"node:os";import{promisify as WP}from"node:util";var g$=WP(JP),GP=["libnss3.so","libnspr4.so","libatk-1.0.so.0","libatk-bridge-2.0.so.0","libcups.so.2","libdrm.so.2","libxkbcommon.so.0","libXcomposite.so.1","libXdamage.so.1","libXfixes.so.3","libXrandr.so.2","libgbm.so.1","libpango-1.0.so.0","libcairo.so.2","libasound.so.2"];async function h$(){if(BP()!=="linux")return{status:"ok"};let e;try{e=(await g$("ldconfig",["-p"],{timeout:5e3,maxBuffer:8*1024*1024})).stdout}catch{try{e=(await g$("/sbin/ldconfig",["-p"],{timeout:5e3,maxBuffer:8*1024*1024})).stdout}catch{return{status:"unknown"}}}let t=GP.filter(r=>!e.includes(r));return t.length?{status:"missing-libs",missing:t}:{status:"ok"}}import{spawn as qP}from"node:child_process";import{access as HP,constants as XP,mkdtemp as YP,readdir as QP,readFile as v$,realpath as eA,rm as tA,stat as $$,writeFile as nA}from"node:fs/promises";import{tmpdir as rA,userInfo as iA}from"node:os";import{basename as Jm,delimiter as oA,dirname as ps,join as cr}from"node:path";var aA="/proc/sys/kernel/apparmor_restrict_unprivileged_userns";function sA(e=Wm(),t="/etc/apparmor.d"){return cr(t,`myrel-runner-${e}`)}function Wm(){return iA().username.replace(/[^A-Za-z0-9_.-]/g,"_")||"user"}async function ln(e={}){let t=e.user??Wm(),r=sA(t,e.profileDir),o={restricted:!1,applies:!1,binaries:[],blocked:[],file:r};if((e.platform??process.platform)!=="linux")return o;let n=await v$(e.restrict??aA,"utf8").catch(()=>null);if(n===null)return o;o.applies=!0,o.restricted=n.trim()==="1",o.binaries=await cA(e.env??process.env);let i=await v$(r,"utf8").catch(()=>"");return o.blocked=o.binaries.filter(a=>!i.includes(x$(a.attach))),o}async function cA(e=process.env){let t=[],r=await y$("muse",e);if(r){let n=ps(r),i=(await QP(n).catch(()=>[])).filter(a=>a.startsWith("muse-bin-")).sort();(Jm(r).startsWith("muse-bin-")||i.length)&&t.push({cli:"muse",path:Jm(r).startsWith("muse-bin-")?r:cr(n,i.at(-1)),attach:`${Bm(n)}/muse-bin-*`})}let o=await y$("codex",e);if(o){let n=ps(ps(o)),i=cr(n,"codex-resources","bwrap");if(await uA(i)){let a=ps(n);t.push({cli:"codex",path:i,attach:Jm(a)==="releases"?`${Bm(a)}/*/codex-resources/bwrap`:Bm(i)})}}return t}async function y$(e,t){for(let r of(t.PATH??"").split(oA)){if(!r)continue;let o=cr(r,e);try{if(await HP(o,XP.X_OK),!(await $$(o)).isFile())continue;return await eA(o)}catch{}}}async function uA(e){return $$(e).then(t=>t.isFile(),()=>!1)}function Bm(e){return e.replace(/[\\"*?[\]{}^]/g,t=>`\\${t}`)}function x$(e){return`"${e}" flags=(unconfined)`}function Gm(e,t=Wm()){let r=["# Written by myrel-runner (`myrel-runner sandbox fix`). Lets the bubblewrap that Muse Code and Codex","# bring with them sandbox their commands under Ubuntu's restriction on unprivileged user namespaces.","# Remove: sudo apparmor_parser -R <this file> && sudo rm <this file>","abi <abi/4.0>,","include <tunables/global>"];for(let o of e){let n=`myrel-runner-${t}-${o.cli}`;r.push("",`profile ${n} ${x$(o.attach)} {`," userns,",` include if exists <local/${n}>`,"}")}return`${r.join(`
|
|
279
279
|
`)}
|
|
280
|
-
`}function w$(e,t){return e==="codex"?t!=="full":e==="muse"?t==="edit"||t==="auto":!1}async function _$(e,t){if(e!=="muse"&&e!=="codex")return null;let r=t??await ln();return!r.restricted||!r.blocked.some(o=>o.cli===e)?null:"(myrel-runner: on this computer Ubuntu's AppArmor blocks this CLI's sandbox, so every shell command fails with \"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted\". Do not retry commands or work around it. Read and edit files, use Myrel's tools, and tell the person to run `npx myrel-runner sandbox fix` once in a terminal on this computer (it asks for their sudo password), or to give this computer full access in Myrel > Devices.)"}function Si(e){return!e.restricted||!e.blocked.length?null:`Ubuntu's AppArmor blocks the sandbox of ${[...new Set(e.blocked.map(r=>r.cli==="muse"?"Muse Code":"Codex"))].join(" and ")}, so their commands fail below full access. Fix it once with \`myrel-runner sandbox fix\`.`}async function k$(e=console.log){if(process.platform!=="linux")return e("Only Linux needs this; nothing to do here.");if(process.getuid?.()===0&&process.env.SUDO_USER)throw new Error("Run it without sudo, as yourself: it finds your CLIs in your home and asks for sudo by itself.");let t=await ln();if(!t.applies)return e("This computer does not restrict user namespaces with AppArmor; nothing to do.");if(!t.binaries.length)return e("Neither Muse Code nor Codex with its own bubblewrap is installed; nothing to do.");if(!t.blocked.length)return e(`The profile in ${t.file} already covers ${t.binaries.map(o=>o.path).join(" and ")}.`);let r=await
|
|
280
|
+
`}function w$(e,t){return e==="codex"?t!=="full":e==="muse"?t==="edit"||t==="auto":!1}async function _$(e,t){if(e!=="muse"&&e!=="codex")return null;let r=t??await ln();return!r.restricted||!r.blocked.some(o=>o.cli===e)?null:"(myrel-runner: on this computer Ubuntu's AppArmor blocks this CLI's sandbox, so every shell command fails with \"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted\". Do not retry commands or work around it. Read and edit files, use Myrel's tools, and tell the person to run `npx myrel-runner sandbox fix` once in a terminal on this computer (it asks for their sudo password), or to give this computer full access in Myrel > Devices.)"}function Si(e){return!e.restricted||!e.blocked.length?null:`Ubuntu's AppArmor blocks the sandbox of ${[...new Set(e.blocked.map(r=>r.cli==="muse"?"Muse Code":"Codex"))].join(" and ")}, so their commands fail below full access. Fix it once with \`myrel-runner sandbox fix\`.`}async function k$(e=console.log){if(process.platform!=="linux")return e("Only Linux needs this; nothing to do here.");if(process.getuid?.()===0&&process.env.SUDO_USER)throw new Error("Run it without sudo, as yourself: it finds your CLIs in your home and asks for sudo by itself.");let t=await ln();if(!t.applies)return e("This computer does not restrict user namespaces with AppArmor; nothing to do.");if(!t.binaries.length)return e("Neither Muse Code nor Codex with its own bubblewrap is installed; nothing to do.");if(!t.blocked.length)return e(`The profile in ${t.file} already covers ${t.binaries.map(o=>o.path).join(" and ")}.`);let r=await YP(cr(rA(),"myrel-apparmor-"));try{let o=cr(r,"profile");await nA(o,Gm(t.binaries),{mode:420}),e(`Writing ${t.file} for:
|
|
281
281
|
${t.binaries.map(i=>` ${i.attach}`).join(`
|
|
282
|
-
`)}`);let n=process.getuid?.()===0;await b$(n?"install":"sudo",[...n?[]:["install"],"-m","0644",o,t.file]),await b$(n?"apparmor_parser":"sudo",[...n?[]:["apparmor_parser"],"-r",t.file])}finally{await
|
|
283
|
-
`)}};function
|
|
284
|
-
`)[0]}`:t}function
|
|
285
|
-
`):""}import{request as
|
|
286
|
-
`)}};function
|
|
282
|
+
`)}`);let n=process.getuid?.()===0;await b$(n?"install":"sudo",[...n?[]:["install"],"-m","0644",o,t.file]),await b$(n?"apparmor_parser":"sudo",[...n?[]:["apparmor_parser"],"-r",t.file])}finally{await tA(r,{recursive:!0,force:!0})}e(t.restricted?"Done: Muse Code and Codex can sandbox their commands now. Running tasks pick it up with their next command.":"Done. The restriction is off right now, so nothing changes yet; the CLIs keep working once it is back on (after a restart, for example).")}function b$(e,t){return new Promise((r,o)=>{let n=qP(e,t,{stdio:"inherit"});n.once("error",i=>o(new Error(`Could not run ${e}: ${i.message}`))),n.once("close",i=>i===0?r():o(new Error(`\`${e} ${t.join(" ")}\` failed (exit ${i}).`)))})}import{open as oj,realpath as Z$,stat as aj}from"node:fs/promises";import{isAbsolute as sj,join as cj,relative as uj,resolve as lj,sep as L$}from"node:path";import{spawn as qA}from"node:child_process";import{mkdir as HA,mkdtemp as ef,realpath as R$,rm as tf,writeFile as XA}from"node:fs/promises";import{tmpdir as nf}from"node:os";import{join as zi,sep as YA}from"node:path";var ms=class{constructor(t,r,o){this.io=t;this.opts=r;this.state=o}io;opts;state;nextId=0;pending=new Map;finished=!1;prompting=!1;modes=[];calls=new Map;latest;background=new Set;message;start(){this.call("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}},t=>{let{cwd:r,mcpServers:o,resume:n,dirs:i=[]}=this.opts,a=t?.agentCapabilities?.sessionCapabilities,c=i.length&&a?.additionalDirectories?{additionalDirectories:i}:{};n?this.call("session/resume",{sessionId:n,cwd:r,mcpServers:o},u=>{this.listed(u),this.opened(n)}):this.call("session/new",{cwd:r,mcpServers:o,...c},u=>{this.configured(u),this.listed(u),this.opened(String(u.sessionId??""))})})}receive(t){let r;try{r=JSON.parse(t)}catch{return}if(r.method&&r.id!==void 0)return this.answer(r);if(r.method==="session/update")return this.update(r.params?.update??{});if(typeof r.id=="number"){let o=this.pending.get(r.id);this.pending.delete(r.id),o?.(r)}}opened(t){if(!t)return this.fail("The agent started no session.");this.state.sessionId=t;let r=()=>{this.prompting=!0,this.call("session/prompt",{sessionId:t,prompt:[{type:"text",text:this.opts.prompt}]},a=>{let{stopReason:c,usage:u}=a??{},l=p=>typeof p=="number"&&p>0?Math.round(p):0,d=u&&{inputTokens:l(u.inputTokens),outputTokens:l(u.outputTokens)+l(u.thoughtTokens)};d&&d.inputTokens+d.outputTokens>0&&(this.state.usage=d),this.state.failed=c==="refusal"||c==="cancelled",this.state.result=(this.state.draft??"").trim()||this.message||"",this.state.failed&&!this.state.result&&(this.state.result=`The agent stopped: ${String(c)}.`),this.finish()})},o=[...this.opts.config??[]],n=()=>{let a=o.shift();if(!a)return r();this.request("session/set_config_option",{sessionId:t,configId:a.id,value:a.value},c=>{c.error||this.configured(c.result),n()})},i=this.mode();i?this.call("session/set_mode",{sessionId:t,modeId:i},n):n()}listed(t){let r=t?.modes?.availableModes;Array.isArray(r)&&(this.modes=r.map(o=>o?.id).filter(o=>typeof o=="string"))}mode(){let{mode:t}=this.opts;return Array.isArray(t)?t.find(r=>this.modes.includes(r))??t[0]:t}configured(t){let r=t?.configOptions;if(!Array.isArray(r))return;let o=r.find(n=>n.category==="model");typeof o?.currentValue=="string"&&o.currentValue&&(this.state.model=o.currentValue)}update(t){if(!this.prompting)return;let r=t.content;if(t.sessionUpdate==="agent_message_chunk"&&typeof r?.text=="string"){let o=t._meta??{};if(o.backgroundTask||o.qwenDiscreteMessage){this.settle();let n=o.backgroundTask?.toolUseId;typeof n=="string"&&this.background.has(n)&&Ye(this.state,n,o.backgroundTask?.status!=="failed","");return}this.state.draft=(this.state.draft??"")+r.text}(t.sessionUpdate==="tool_call"||t.sessionUpdate==="tool_call_update")&&this.tool(t)}settle(){let t=this.state.draft?.trim();this.state.draft=void 0,t&&(this.message=t,(this.state.lines??=[]).push(t.slice(0,2e3)))}tool(t){let r=typeof t.toolCallId=="string"?t.toolCallId:"",o=t.sessionUpdate==="tool_call";o&&(this.settle(),this.message=void 0);let n={...this.calls.get(r)??{}};typeof t.title=="string"&&t.title&&(n.title=t.title),typeof t.kind=="string"&&(n.kind=t.kind),typeof t.status=="string"&&(n.status=t.status),t.rawInput&&typeof t.rawInput=="object"&&Object.keys(t.rawInput).length&&(n.rawInput=t.rawInput),t._meta&&typeof t._meta=="object"&&!("toolLifecycle"in t._meta)&&(n._meta=t._meta),r&&this.calls.set(r,n);let i=r?this.opts.subagent?.(n):void 0;if(i){let c=n.status==="completed"||n.status==="failed";if((n.rawInput||c)&&Dt(this.state,r,i.label,i.purpose,{background:i.background}),!c||this.background.has(r))return;let u=dA(t.content);i.background||/^(Background|Async) agent launched/.test(u)?this.background.add(r):Ye(this.state,r,n.status==="completed",u);return}if(o&&(this.latest=r),r!==this.latest||!o&&!t.title&&!t.rawInput)return;let a=this.opts.describe?.(n)??lA(n);a&&un(this.state,a.slice(0,2e3))}answer(t){if(t.method==="session/request_permission"){let r=t.params??{},o=r.options??[],n=this.opts.allow||this.ownTool(r.toolCall),i=o.find(c=>c.kind===(n?"allow_once":"reject_once")),a=i?{outcome:"selected",optionId:i.optionId}:{outcome:"cancelled"};return this.send({jsonrpc:"2.0",id:t.id,result:{outcome:a}})}this.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`${t.method} is not offered by myrel-runner`}})}ownTool(t){let{serverTools:r,mcpServers:o}=this.opts;if(!r||!t)return!1;let n=t._meta??{};return[t.title,n.toolName,...Object.values(n).map(a=>a?.toolName)].some(a=>typeof a=="string"&&o.some(c=>a.startsWith(r(c.name))))}call(t,r,o){this.request(t,r,n=>n.error?this.fail(n.error.message||`${t} failed`):o(n.result))}request(t,r,o){let n=++this.nextId;this.pending.set(n,o),this.send({jsonrpc:"2.0",id:n,method:t,params:r})}fail(t){this.state.failed=!0,this.state.result=t,this.finish()}finish(){this.finished||(this.finished=!0,this.io.end())}send(t){this.io.write(`${JSON.stringify(t)}
|
|
283
|
+
`)}};function lA(e){let t=e.title?.trim(),r=e.rawInput??{},o=[r.command,r.file_path,r.absolute_path,r.path,r.pattern,r.query,r.url,r.description].find(n=>typeof n=="string"&&!!n.trim());return t&&/^[\w.-]+$/.test(t)&&o?`${t}: ${o.trim().split(`
|
|
284
|
+
`)[0]}`:t}function dA(e){return Array.isArray(e)?e.map(t=>t?.content?.type==="text"&&typeof t.content.text=="string"?t.content.text:"").filter(Boolean).join(`
|
|
285
|
+
`):""}import{request as pA}from"node:http";import{request as mA}from"node:https";var K=e=>e&&typeof e=="object"?e:{},G=e=>typeof e=="string"&&e?e:void 0,fs=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0,fA=e=>e.trim().slice(0,2e3),gs=class{constructor(t,r,o){this.io=t;this.opts=r;this.state=o}io;opts;state;nextId=0;pending=new Map;finished=!1;threadId;turnId;stopping=!1;steering=new Set;changes=new Map;start(){this.call("initialize",{clientInfo:{name:"myrel-runner",title:"Myrel",version:this.opts.clientVersion}},()=>{this.send({jsonrpc:"2.0",method:"initialized"});let{cwd:t,resume:r,sandbox:o,approvalPolicy:n,approvalsReviewer:i,model:a,config:c}=this.opts,u={cwd:t,sandbox:o,approvalPolicy:n,...i&&{approvalsReviewer:i},...a?.model&&{model:a.model},...c&&{config:c}};r?this.call("thread/resume",{...u,threadId:r},l=>this.opened(l)):this.call("thread/start",u,l=>this.opened(l))})}interrupt(){return this.finished?!1:(this.stopping=!0,this.threadId&&this.turnId&&this.request("turn/interrupt",{threadId:this.threadId,turnId:this.turnId},()=>{}),!0)}steer(t){let{threadId:r,turnId:o}=this;return this.finished||this.stopping||!r||!o?Promise.resolve(!1):new Promise(n=>{let i=a=>{this.steering.delete(i),n(a)};this.steering.add(i),this.request("turn/steer",{threadId:r,expectedTurnId:o,input:[{type:"text",text:t}]},a=>i(!a.error))})}receive(t){if(!t.startsWith("{"))return;let r;try{r=JSON.parse(t)}catch{return}if(r.method&&r.id!==void 0)return void this.answer(r);if(r.method)return this.notified(r.method,K(r.params));if(typeof r.id=="number"){let o=this.pending.get(r.id);this.pending.delete(r.id),o?.(r)}}opened(t){if(this.opts.approvalsReviewer==="auto_review"&&!["auto_review","guardian_subagent"].includes(String(K(t).approvalsReviewer)))return this.fail("Codex did not enable Approve for me. Update Codex to a version with auto-review support, or choose edit access for manual approvals.");let r=K(K(t).thread),o=G(r.id);if(!o)return this.fail("Codex started no session.");this.threadId=o,this.state.sessionId=o;let n=G(K(t).model)??G(r.model);n&&(this.state.model=n);let i=this.opts.model?.effort;this.call("turn/start",{threadId:o,input:[{type:"text",text:this.opts.prompt}],...i&&{effort:i}},a=>{this.turnId=G(K(K(a).turn).id),this.stopping&&this.interrupt()})}notified(t,r){if(this.threadId&&r.threadId!==void 0&&r.threadId!==this.threadId)return this.subagent(t,r,String(r.threadId));switch(t){case"item/started":case"item/completed":return this.item(t,K(r.item));case"thread/tokenUsage/updated":return this.addUsage(r);case"account/rateLimits/updated":{let o=gA(r.rateLimits);o&&(this.state.limits=o);return}case"model/rerouted":{let o=G(r.toModel)??G(r.model);o&&(this.state.model=o);return}case"error":{let o=G(K(r.error).message);o&&(this.state.error=o);return}case"turn/completed":return this.completed(K(r.turn))}}subagent(t,r,o){if(t==="item/started"||t==="item/completed")return this.item(t,K(r.item),o);if(t==="thread/tokenUsage/updated"){let n=K(K(r.tokenUsage).last);return ss(this.state,o,fs(n.inputTokens)+fs(n.outputTokens)),this.addUsage(r)}}addUsage(t){let r=K(K(t.tokenUsage).last),o=this.state.usage??={inputTokens:0,outputTokens:0};o.inputTokens+=fs(r.inputTokens),o.outputTokens+=fs(r.outputTokens)}item(t,r,o){let n=i=>un(this.state,fA(i),o);switch(r.type){case"commandExecution":{if(t!=="item/started")return;let a=G(K(r.commandActions?.[0]).command)??ir(G(r.command)??"");a&&n(`$ ${a}`);return}case"fileChange":{let i=Array.isArray(r.changes)?r.changes.map(a=>G(K(a).path)).filter(a=>!!a):[];typeof r.id=="string"&&i.length&&this.changes.set(r.id,i),t==="item/started"&&i.length&&n(`Edit ${i.join(", ")}`);return}case"mcpToolCall":t==="item/started"&&n(`${G(r.server)??"mcp"}.${G(r.tool)??"tool"}`);return;case"webSearch":t==="item/started"&&G(r.query)&&n(`Search ${G(r.query)}`);return;case"agentMessage":{let i=G(r.text)?.trim();if(t!=="item/completed"||!i)return;n(i),o||(this.state.result=i);return}case"collabAgentToolCall":return this.collab(t,r);case"subAgentActivity":{let i=G(r.agentThreadId);if(!i)return;r.kind==="started"?Dt(this.state,i,yA(r.agentPath),"",{model:G(r.model)}):r.kind==="completed"?Ye(this.state,i,!0):r.kind==="interrupted"&&Ye(this.state,i,!1);return}}}collab(t,r){let o=Array.isArray(r.receiverThreadIds)?r.receiverThreadIds.filter(n=>typeof n=="string"):[];if(r.tool==="spawnAgent")for(let n of o)Dt(this.state,n,"",G(r.prompt)??"",{model:G(r.model)});if(t==="item/completed")for(let[n,i]of Object.entries(K(r.agentsStates))){let a=K(i),c=G(a.message)??"";a.status==="completed"||a.status==="shutdown"?Ye(this.state,n,!0,c):(a.status==="errored"||a.status==="interrupted")&&Ye(this.state,n,!1,c)}}completed(t){if(this.turnId&&t.id!==void 0&&t.id!==this.turnId)return;let r=t.status;if(r!=="completed"){this.state.failed=!0;let o=G(K(t.error).message)??this.state.error;r==="interrupted"?this.state.result??="Codex stopped.":this.state.result=o??`Codex ended the turn: ${String(r)}.`}else this.state.failed=!1;this.finish()}async answer(t){let r=K(t.params),o=n=>this.send({jsonrpc:"2.0",id:t.id,result:n});switch(t.method){case"item/commandExecution/requestApproval":{let i=G(K(r.commandActions?.[0]).command)??ir(G(r.command)??""),a=!!i&&await this.ask("Bash",{command:i,...G(r.reason)&&{description:G(r.reason)}});return o({decision:a?"accept":"decline"})}case"item/fileChange/requestApproval":{let n=[...G(r.grantRoot)?[G(r.grantRoot)]:[],...this.changes.get(String(r.itemId))??[]],i=n.length>0;for(let a of n)i&&(i=await this.ask("Edit",{file_path:a}));return o({decision:i?"accept":"decline"})}case"item/permissions/requestApproval":{let n=K(r.permissions),i=K(n.fileSystem),a=[...i.write??[],...i.read??[]].filter(l=>typeof l=="string"),c=K(n.network).enabled===!0,u=a.length>0||c;for(let l of a)u&&(u=await this.ask("Edit",{file_path:l}));return u&&c&&(u=await this.ask("Bash",{command:G(r.reason)??"network access"})),o({permissions:u?n:{},scope:"turn"})}case"mcpServer/elicitation/request":return o({action:"decline"});case"applyPatchApproval":case"execCommandApproval":return o({decision:"denied"});default:return this.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`${t.method} is not offered by myrel-runner`}})}}async ask(t,r){return!this.opts.ask||this.finished?!1:this.opts.ask(t,r).catch(()=>!1)}call(t,r,o){this.request(t,r,n=>n.error?this.fail(n.error.message||`${t} failed`):o(n.result))}request(t,r,o){let n=++this.nextId;this.pending.set(n,o),this.send({jsonrpc:"2.0",id:n,method:t,params:r})}fail(t){this.state.failed=!0,this.state.result=t,this.finish()}finish(){if(!this.finished){this.finished=!0;for(let t of[...this.steering])t(!1);this.io.end()}}send(t){this.finished||this.io.write(`${JSON.stringify(t)}
|
|
286
|
+
`)}};function gA(e){let t=K(e),r=o=>{let n=K(o);return Object.keys(n).length?{used_percent:n.usedPercent,window_minutes:n.windowDurationMins,resets_at:n.resetsAt}:null};return Um({primary:r(t.primary),secondary:r(t.secondary)},new Date().toISOString())}var hA=900*1e3;function S$(e,t){return(r,o)=>new Promise(n=>{let i=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"approve_access",arguments:{tool_name:r,input:o}}}),c=(e.startsWith("https:")?mA:pA)(e,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",authorization:`Bearer ${t}`,"content-length":Buffer.byteLength(i)},timeout:hA},u=>{let l="";u.setEncoding("utf8"),u.on("data",d=>{l.length<1e6&&(l+=d)}),u.on("end",()=>n(u.statusCode===200&&vA(l))),u.on("error",()=>n(!1))});c.on("timeout",()=>c.destroy()),c.on("error",()=>n(!1)),c.end(i)})}function vA(e){try{let t=K(K(JSON.parse(e)).result).content,r=Array.isArray(t)?G(K(t[0]).text):void 0;return!!r&&K(JSON.parse(r)).behavior==="allow"}catch{return!1}}function yA(e){return(G(e)??"").split("/").filter(Boolean).pop()??""}var hs=class{constructor(t,r){this.io=t;this.prompt=r}io;prompt;written=0;echoed=0;ended=!1;stopping=!1;requests=0;start(){this.user(this.prompt)}steer(t){return this.ended||this.stopping?Promise.resolve(!1):(this.user(t),Promise.resolve(!0))}interrupt(){return this.ended?!1:(this.stopping=!0,this.io.write(`${JSON.stringify({type:"control_request",request_id:`myrel-${++this.requests}`,request:{subtype:"interrupt"}})}
|
|
287
287
|
`),!0)}receive(t){this.ended||(t.type==="user"&&t.isReplay===!0&&this.echoed++,t.type==="result"&&(this.stopping||this.echoed>=this.written)&&this.end())}end(){this.ended||(this.ended=!0,this.io.end())}user(t){this.written++;let r={type:"user",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null,session_id:""};this.io.write(`${JSON.stringify(r)}
|
|
288
|
-
`)}};import{chmod as
|
|
288
|
+
`)}};import{chmod as bA,mkdir as I$,writeFile as z$}from"node:fs/promises";import{dirname as $A,join as Ii,resolve as xA,sep as wA}from"node:path";var _A="myrel",kA=/^[a-z0-9]+(-[a-z0-9]+)*$/;async function P$(e,t,r,o=fetch){let n;try{let u=await o(e,{headers:{Authorization:`Bearer ${t}`}});if(!u.ok)return null;n=await u.json()}catch{return null}let i=Ii(r,"plugin"),a=Ii(i,"skills"),c=0;for(let u of n.skills??[]){if(!kA.test(u.name))continue;let l=Ii(a,u.name);for(let d of u.files??[]){let p=xA(l,d.path);p.startsWith(l+wA)&&(await I$($A(p),{recursive:!0}),await z$(p,Buffer.from(d.content,"base64")),(/\.(sh|py)$/.test(d.path)||d.path.startsWith("scripts/"))&&await bA(p,493).catch(()=>{}))}c++}return c?(await I$(Ii(i,".claude-plugin"),{recursive:!0}),await z$(Ii(i,".claude-plugin","plugin.json"),JSON.stringify({name:_A,description:"Skills added in Myrel for this run.",version:"1.0.0"})),{plugin:i,skills:a,count:c}):null}import{spawn as SA}from"node:child_process";import{chmod as IA,mkdir as zA,writeFile as qm}from"node:fs/promises";import{request as PA}from"node:http";import{request as AA}from"node:https";import{delimiter as A$,join as vs}from"node:path";var Hm="MYREL_SSH_SHIM",jA=["ssh","scp","sftp"],TA=960*1e3;async function j$(e,t,r=process.platform){let o=vs(e,"ssh-bin");await zA(o,{recursive:!0,mode:448});let n=bi();for(let c of jA)if(r==="win32"){let u=[n.command,...n.args].map(l=>`"${l}"`).join(" ");await qm(vs(o,`${c}.cmd`),`@echo off\r
|
|
289
289
|
${u} ssh-shim ${c} %*\r
|
|
290
290
|
`,{mode:448})}else{let u=[n.command,...n.args].map(d=>`'${d.replaceAll("'","'\\''")}'`).join(" "),l=vs(o,c);await qm(l,`#!/bin/sh
|
|
291
291
|
exec ${u} ssh-shim ${c} "$@"
|
|
292
|
-
`,{mode:448}),await
|
|
293
|
-
`),255;if(o.kind==="passthrough")return
|
|
294
|
-
`),255;let i=await
|
|
292
|
+
`,{mode:448}),await IA(l,448)}let i=vs(e,"ssh-shim.json");await qm(i,JSON.stringify(t),{mode:384});let a=Object.keys(process.env).find(c=>c.toUpperCase()==="PATH")??"PATH";return{[a]:[o,process.env[a]].filter(Boolean).join(r==="win32"?";":":"),[Hm]:i}}var CA=new Set("qTn46vxCa".split("")),OA=new Set(["p","l"]),NA=/^(?:BatchMode|ConnectTimeout|ServerAliveInterval|ServerAliveCountMax|LogLevel|StrictHostKeyChecking|UserKnownHostsFile|ConnectionAttempts)=/i,DA=/^(?:git[- ](?:upload-pack|receive-pack|upload-archive) '[^'\n]*'|git-lfs-(?:authenticate|transfer) '?[\w./~-]+'? (?:upload|download))$/,Xm="Copying files over SSH (scp, sftp, rsync) is not available to Myrel's agents yet. Run a command on the server with ssh_run instead (e.g. cat a file to read it).";function RA(e){if(e.length>1&&DA.test(e[e.length-1]))return{kind:"passthrough"};let t=0,r;for(;t<e.length;t++){let d=e[t];if(d==="--"){t++;break}if(!d.startsWith("-")||d==="-")break;let p=d.slice(1);for(let f=0;f<p.length;f++){let m=p[f];if(!CA.has(m)){if(OA.has(m)||m==="o"){let g=p.slice(f+1)||e[++t];if(g===void 0)return{kind:"refuse",message:`ssh: -${m} needs a value.`};if(m==="l"&&(r=g),m==="o"&&!NA.test(g))return{kind:"refuse",message:`ssh -o ${g.split("=")[0]} is not available to Myrel's agents: Myrel sets up the connection itself.`};break}return m==="s"?{kind:"refuse",message:Xm}:"LRDW".includes(m)?{kind:"refuse",message:"Port forwarding over SSH is not available to Myrel's agents."}:m==="A"?{kind:"refuse",message:"Agent forwarding is not available to Myrel's agents."}:"tN".includes(m)?{kind:"refuse",message:"Interactive SSH sessions are not available to Myrel's agents: run one command at a time, e.g. `ssh <host> uptime`."}:{kind:"refuse",message:`ssh -${m} is not available to Myrel's agents. Use \`ssh <host> <command>\`, or Myrel's ssh_run tool.`}}}}let o=e[t];if(!o)return{kind:"refuse",message:"Usage: ssh <host> <command> (a host from the project's SSH settings)."};let i=e.slice(t+1).join(" ").trim();if(/^(?:rsync\s+--server|scp\s+-[\w ]*[tf]\b|sftp-server|internal-sftp)/.test(i))return{kind:"refuse",message:Xm};if(!i)return{kind:"refuse",message:"Interactive SSH sessions are not available to Myrel's agents: run one command at a time, e.g. `ssh <host> uptime`."};let a=o.replace(/^ssh:\/\//,"").replace(/:\d+$/,""),c=a.lastIndexOf("@"),u=c>=0?a.slice(c+1):a,l=c>=0?a.slice(0,c):r;return{kind:"run",host:l?`${l}@${u}`:u,command:i}}async function T$(e,t,r={out:process.stdout,err:process.stderr}){let o=e==="ssh"?RA(t):{kind:"refuse",message:Xm};if(o.kind==="refuse")return r.err.write(`${o.message}
|
|
293
|
+
`),255;if(o.kind==="passthrough")return MA(t);let n=process.env[Hm]?await ve(process.env[Hm]).catch(()=>{}):void 0;if(!n)return r.err.write(`SSH from this run goes through Myrel, but the run's settings are gone. Use Myrel's ssh_run tool.
|
|
294
|
+
`),255;let i=await EA(n,{host:o.host,command:o.command,reason:"Asked from the shell (ssh)."});if(!i.ok)return r.err.write(`${i.text}
|
|
295
295
|
`),255;try{let a=JSON.parse(i.text);return a.stdout&&r.out.write(a.stdout),a.stderr&&r.err.write(a.stderr),typeof a.exit_code=="number"?a.exit_code:255}catch{return r.err.write(`${i.text}
|
|
296
|
-
`),255}}function
|
|
297
|
-
To run tasks in the folder itself instead, run \`myrel-runner worktrees off\`.`)}let c=a?.cwd??n,u=this.opts.log??(()=>{}),l=c===n?[]:[n];for(let P of t.folders??[]){let Q=await _s(o,P);Q?Q!==c&&!l.includes(Q)&&l.push(Q):u(` skipping ${P}: not shared on this computer`)}let d=ar[t.cli],p=!!d.appServer&&await c$(d.bin);if(t.cli==="codex"&&o.access==="auto"&&!p)return r("Codex auto access needs its app server for Approve for me. Update Codex and unset MYREL_CODEX_EXEC, or choose edit access for codex exec.");let f=!!t.agent&&t.cli==="claude",m=E$.has(t.cli)&&!a?.created?await this.opts.sessions.get(t.threadId,t.cli,t.account):void 0,g=m&&await
|
|
296
|
+
`),255}}function EA(e,t){return new Promise(r=>{let o=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"ssh_run",arguments:t}}),i=(e.url.startsWith("https:")?AA:PA)(e.url,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",authorization:`Bearer ${e.token}`,"content-length":Buffer.byteLength(o)},timeout:TA},a=>{let c="";a.setEncoding("utf8"),a.on("data",u=>{c.length<2e6&&(c+=u)}),a.on("end",()=>r(UA(a.statusCode,c))),a.on("error",()=>r({ok:!1,text:"Lost the connection to Myrel."}))});i.on("timeout",()=>i.destroy()),i.on("error",()=>r({ok:!1,text:"Could not reach Myrel to ask about this SSH command."})),i.end(o)})}function UA(e,t){if(e!==200)return{ok:!1,text:e===401?"This run's turn has ended; SSH through Myrel is closed.":`Myrel answered ${e}.`};try{let r=JSON.parse(t);if(r.error)return{ok:!1,text:r.error.message??"Myrel refused the call."};let o=r.result?.content?.[0]?.text??"";return{ok:!r.result?.isError,text:o}}catch{return{ok:!1,text:"Myrel's answer could not be read."}}}function MA(e){let t=Object.keys(process.env).find(o=>o.toUpperCase()==="PATH")??"PATH",r=(process.env[t]??"").split(A$).filter(o=>!o.endsWith(`${process.platform==="win32"?"\\":"/"}ssh-bin`)).join(A$);return new Promise(o=>{let n=SA("ssh",e,{stdio:"inherit",env:{...process.env,[t]:r}});n.once("error",()=>o(255)),n.once("close",i=>o(i??255))})}import{execFile as LA}from"node:child_process";import{createHash as ZA}from"node:crypto";import{mkdir as FA,realpath as Ym,stat as C$}from"node:fs/promises";import{basename as VA,join as ys,relative as KA}from"node:path";import{promisify as JA}from"node:util";var BA=JA(LA),WA=1440*60*1e3,O$=()=>ys(Y(),"worktrees.json"),ot=(e,t)=>BA("git",["-C",e,...t],{maxBuffer:4*1024*1024,env:Ue()});async function vt(){return await ve(O$())??[]}async function N$(e){await Xe(O$(),e)}function GA(e){return`myrel/thr-${e.slice(-10).toLowerCase()}`}async function D$(e,t){let r=await ot(e,["rev-parse","--show-toplevel"]).then(a=>Ym(a.stdout.trim())).catch(()=>null);if(!r||!await ot(r,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>null))return null;let o=await vt(),n=o.find(a=>a.repo===r&&a.threadId===t),i=!1;if(!n||!await C$(n.path).catch(()=>null)){let a=ZA("sha256").update(r).digest("hex").slice(0,8),c=ys(Y(),"worktrees",`${VA(r)}-${a}`);await FA(c,{recursive:!0,mode:448});let u=ys(await Ym(c),t.slice(-10).toLowerCase()),l=GA(t);await ot(r,["worktree","prune"]).catch(()=>{});let d=await ot(r,["rev-parse","--verify","--quiet",`refs/heads/${l}`]).catch(()=>null);await ot(r,d?["worktree","add",u,l]:["worktree","add","-b",l,u,"HEAD"]),n={threadId:t,repo:r,path:u,branch:l,lastUsed:Date.now()},i=!0}return n.lastUsed=Date.now(),await N$([...o.filter(a=>!(a.repo===r&&a.threadId===t)),n]),{cwd:ys(n.path,KA(r,await Ym(e))),worktree:n,created:i}}async function bs(e){if(!await C$(e.path).catch(()=>null))return{missing:!0,dirty:!1,merged:!0};let t=await ot(e.path,["status","--porcelain"]).catch(()=>null),r=await ot(e.repo,["merge-base","--is-ancestor",e.branch,"HEAD"]).then(()=>!0).catch(()=>!1);return{missing:!1,dirty:t===null||t.stdout.trim()!=="",merged:r}}async function Qm(e,{force:t=!1}={}){let r=await bs(e);if(r.dirty&&!t)throw new Error(`${e.path} has uncommitted changes. Commit them, or remove it with --force.`);r.missing||await ot(e.repo,["worktree","remove",...t?["--force"]:[],e.path]),await ot(e.repo,["worktree","prune"]).catch(()=>{}),r.merged&&await ot(e.repo,["branch","-d",e.branch]).catch(()=>{}),await N$((await vt()).filter(o=>o.path!==e.path))}async function $s(e=()=>!1,t=Date.now()){let r=[];for(let o of await vt()){if(e(o)||t-o.lastUsed<WA)continue;let n=await bs(o).catch(()=>null);!n||n.dirty||!n.merged||await Qm(o).then(()=>r.push(o)).catch(()=>{})}return r}var E$=new Set(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi","qwen"]),U$=9e4,QA=3600*1e3,ej=1e3,tj=5e3,ws=class{constructor(t){this.opts=t}opts;running=new Map;turns=new Map;worktrees=new Map;cancelled=new Set;interrupted=new Set;git=new ds;send=()=>{};setSender(t){this.send=t}runningIds(){return[...this.running.keys()]}inUse(t){return[...this.worktrees.values()].includes(t.path)}async start(t){let r=P=>this.send({type:"task.done",taskId:t.taskId,ok:!1,result:P}),o=this.opts.config(),n=await _s(o,t.folder);if(!n)return r(`The folder ${t.folder} is not shared on this computer. Run \`myrel-runner share\` in it.`);let i=wb(o,t.cli,t.account);if("error"in i)return r(i.error);if(t.coordinator)return this.startCoordinator(t,t.coordinator.system,i);let a=null;if(o.worktrees!==!1&&t.worktree!==!1&&o.access!=="read")try{a=await D$(n,t.threadId)}catch(P){return r(`Could not make a git worktree for this thread in ${n}: ${xs(P)}
|
|
297
|
+
To run tasks in the folder itself instead, run \`myrel-runner worktrees off\`.`)}let c=a?.cwd??n,u=this.opts.log??(()=>{}),l=c===n?[]:[n];for(let P of t.folders??[]){let Q=await _s(o,P);Q?Q!==c&&!l.includes(Q)&&l.push(Q):u(` skipping ${P}: not shared on this computer`)}let d=ar[t.cli],p=!!d.appServer&&await c$(d.bin);if(t.cli==="codex"&&o.access==="auto"&&!p)return r("Codex auto access needs its app server for Approve for me. Update Codex and unset MYREL_CODEX_EXEC, or choose edit access for codex exec.");let f=!!t.agent&&t.cli==="claude",m=E$.has(t.cli)&&!a?.created?await this.opts.sessions.get(t.threadId,t.cli,t.account):void 0,g=m&&await rj(m,c,a?null:{folder:n,threadId:t.threadId})?m:void 0,y=g&&t.agent?.resume&&g.task===t.agent.resume.after?t.agent.resume.prompt:void 0;u(`\u25B6 ${d.id}${t.account?`@${t.account}`:""} in ${c}: ${t.prompt.split(`
|
|
298
298
|
`)[0].slice(0,80)}`);let _,I={args:[]},k=null,A;if(t.agent&&o.server){_=await ef(zi(nf(),"myrel-agent-"));let P=o.server.replace(/\/$/,"");A=S$(`${P}${t.agent.mcpPath}`,t.agent.token);let Q=(t.agent.connectors??[]).map(re=>re.transport==="http"?{transport:re.transport,name:re.name,url:`${P}${re.path}`}:re);k=t.agent.skills?await P$(`${P}${t.agent.skills.path}`,t.agent.token,_):null,I=await d.agent({url:`${P}${t.agent.mcpPath}`,token:t.agent.token,dir:_,connectors:Q,asks:f,access:o.access,dirs:l,...t.reviewModel&&{reviewModel:t.reviewModel},...k&&{skills:{plugin:k.plugin,dir:k.skills}}})}let Z=()=>_?tf(_,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve(),C=a?`
|
|
299
299
|
|
|
300
|
-
(myrel-runner: worked on branch ${a.worktree.branch} in ${a.cwd}, a git worktree of ${n}.)`:"";a&&this.worktrees.set(t.taskId,a.worktree.path),t.agent&&this.send({type:"task.folders",taskId:t.taskId,folders:[c,...l]});let E={...i,...I.env,...t.github&&await this.git.lend(t.taskId,t.github)};if(t.agent&&_&&o.server){let P=await j$(_,{url:`${o.server.replace(/\/$/,"")}${t.agent.mcpPath}`,token:t.agent.token}).catch(Q=>(u(` could not put Myrel's ssh on PATH: ${xs(Q)}`),{}));E={...E,...P}}try{let P=p?{...d.appServer({access:o.access,dirs:l,asks:!!A}),ask:A}:void 0;P&&u(" as its app server");let Q=!!d.streamInput&&await u$(d.bin),re={cwd:c,adapter:d,agent:I,env:E,dirs:l,asks:f&&!!_,skills:k,where:C,cleanup:Z,appServer:P,stream:Q};await this.attempt(t,re,g?.id,y??t.prompt)&&(u(` could not resume the ${d.id} session; starting a new one`),await this.attempt(t,re,void 0,t.prompt))}finally{this.git.end(t.taskId)}}async startCoordinator(t,r,o){let n=l=>this.send({type:"task.done",taskId:t.taskId,ok:!1,result:l}),i=this.opts.config(),a=ar[t.cli];if(!t.agent||!i.server)return n("A coordinator turn needs Myrel's coordinator endpoint.");if(!a.coordinator)return n(`${a.bin} cannot work as the coordinator: it cannot run without its own tools.`);let c=await ef(zi(nf(),"myrel-coordinator-")),u=()=>tf(c,{recursive:!0,force:!0}).catch(()=>{});try{let l=zi(c,"work");await
|
|
300
|
+
(myrel-runner: worked on branch ${a.worktree.branch} in ${a.cwd}, a git worktree of ${n}.)`:"";a&&this.worktrees.set(t.taskId,a.worktree.path),t.agent&&this.send({type:"task.folders",taskId:t.taskId,folders:[c,...l]});let E={...i,...I.env,...t.github&&await this.git.lend(t.taskId,t.github)};if(t.agent&&_&&o.server){let P=await j$(_,{url:`${o.server.replace(/\/$/,"")}${t.agent.mcpPath}`,token:t.agent.token}).catch(Q=>(u(` could not put Myrel's ssh on PATH: ${xs(Q)}`),{}));E={...E,...P}}try{let P=p?{...d.appServer({access:o.access,dirs:l,asks:!!A}),ask:A}:void 0;P&&u(" as its app server");let Q=!!d.streamInput&&await u$(d.bin),re={cwd:c,adapter:d,agent:I,env:E,dirs:l,asks:f&&!!_,skills:k,where:C,cleanup:Z,appServer:P,stream:Q};await this.attempt(t,re,g?.id,y??t.prompt)&&(u(` could not resume the ${d.id} session; starting a new one`),await this.attempt(t,re,void 0,t.prompt))}finally{this.git.end(t.taskId)}}async startCoordinator(t,r,o){let n=l=>this.send({type:"task.done",taskId:t.taskId,ok:!1,result:l}),i=this.opts.config(),a=ar[t.cli];if(!t.agent||!i.server)return n("A coordinator turn needs Myrel's coordinator endpoint.");if(!a.coordinator)return n(`${a.bin} cannot work as the coordinator: it cannot run without its own tools.`);let c=await ef(zi(nf(),"myrel-coordinator-")),u=()=>tf(c,{recursive:!0,force:!0}).catch(()=>{});try{let l=zi(c,"work");await HA(l);let d=`${i.server.replace(/\/$/,"")}${t.agent.mcpPath}`,p=await a.coordinator({url:d,token:t.agent.token,dir:c,system:r});if(!p)return await u(),n(`This computer's ${a.bin} is too old to work as the coordinator, which needs it without its own tools. Update it.`);(this.opts.log??(()=>{}))(`\u25B6 ${a.id}${t.account?`@${t.account}`:""} as the coordinator`);let f={...o,...p.env};await this.attempt(t,{cwd:l,adapter:a,agent:{args:[]},env:f,dirs:[],asks:!1,skills:null,where:"",cleanup:u,fixed:p.args},void 0,t.prompt)}catch(l){await u(),n(`Could not start ${a.bin} as the coordinator: ${xs(l)}`)}}async steer(t,r){return await this.turns.get(t)?.steer(r)??!1}renewGithub(t,r){this.git.renew(t,r)}async attempt(t,r,o,n){let i=this.opts.config(),a=this.opts.log??(()=>{}),{cwd:c,adapter:u,agent:l,dirs:d,skills:p,where:f,cleanup:m}=r,g=p?`${n}
|
|
301
301
|
|
|
302
302
|
Skills folder for this run: ${p.skills}`:n,y=!r.fixed&&w$(u.id,i.access)?await _$(u.id).catch(()=>null):null,_=y?`${g}
|
|
303
303
|
|
|
304
|
-
${y}`:g,I=u.input?u.input(_,i.access):_,k=u.promptFile?await ef(zi(nf(),"myrel-prompt-")):void 0,A=k?zi(k,"prompt.md"):void 0;A&&await
|
|
305
|
-
`);bt=w.pop();for(let U of w)u.line(U.trim(),
|
|
306
|
-
`).at(-1);function M$(e,t){let r=Math.round(t/6e4);return`${e} wrote nothing for ${r} minutes, so Myrel stopped it as stuck. Write here to continue; the next turn picks up where it left off.`}function
|
|
307
|
-
${o}`}async function F$(e,t){let r=await
|
|
308
|
-
`,{mode:384})}import{spawn as
|
|
309
|
-
`,timeoutMs:15e3});if(o.code!==0||/error/i.test(o.stderr))throw new Error(`Keychain: ${o.stderr.trim()||`exit ${o.code}`}`)},async get(t){let r=await at("security",["find-generic-password","-a",t,"-s",ur,"-w"],{timeoutMs:15e3});return r.code===0?r.stdout.replace(/\n$/,""):null},async remove(t){await at("security",["delete-generic-password","-a",t,"-s",ur],{timeoutMs:15e3}).catch(()=>{})}}:e==="linux"?{async set(t,r){let o=await at("secret-tool",["store",`--label=Myrel SSH key ${t}`,"service",ur,"account",t],{input:r,timeoutMs:15e3});if(o.code!==0)throw new Error(`Secret Service: ${o.stderr.trim()||`exit ${o.code}`}`)},async get(t){let r=await at("secret-tool",["lookup","service",ur,"account",t],{timeoutMs:15e3});return r.code===0&&r.stdout?r.stdout.replace(/\n$/,""):null},async remove(t){await at("secret-tool",["clear","service",ur,"account",t],{timeoutMs:15e3}).catch(()=>{})}}:null}async function
|
|
310
|
-
`).pop()})`:""}.`);return o}var
|
|
311
|
-
`)){if(!o.trim()||o.startsWith("#"))continue;let[,n,i]=o.trim().split(/\s+/);if(!n||!i||!/^[A-Za-z0-9+/=]+$/.test(i))continue;let a=`${n} ${i}`;t.some(c=>c.key===a)||t.push({type:n,key:a,fingerprint:Ss(a)})}let r=o=>
|
|
304
|
+
${y}`:g,I=u.input?u.input(_,i.access):_,k=u.promptFile?await ef(zi(nf(),"myrel-prompt-")):void 0,A=k?zi(k,"prompt.md"):void 0;A&&await XA(A,I,{mode:384});let Z=[...r.appServer?[]:Lm(u,t.model),...l.args],C=r.fixed?[...r.fixed,...Lm(u,t.model)]:r.appServer?["app-server",...l.args]:u.args({access:i.access,resume:o,extra:Z,dirs:d,asks:r.asks,promptFile:A,stream:r.stream}),E=!r.fixed&&E$.has(t.cli),P=(this.opts.spawn??qA)(u.bin,C,{cwd:c,env:Ue({...r.env,...process.platform!=="win32"&&{PWD:c}}),stdio:["pipe","pipe","pipe"],shell:process.platform==="win32"});if(k){let V=()=>{tf(k,{recursive:!0,force:!0}).catch(()=>{})};P.once("close",V),P.once("error",V)}this.running.set(t.taskId,P),this.opts.onChange?.(this.runningIds());let Q=this.opts.idleMs??QA,re=!1,Ne=setTimeout(()=>{re=!0,P.kill("SIGTERM"),setTimeout(()=>P.exitCode===null&&P.kill("SIGKILL"),5e3).unref()},Q),O={},We="",Et="",bt="",Ri=0,dr,gn="",pr,mr,Ut=!1,fr=V=>{!V||V===pr||(pr=V,this.opts.onLimits?.(t.cli,V,t.account))},et=()=>O.usage?{...O.usage,...O.model&&{model:O.model.slice(0,200)}}:void 0,Rs=()=>{for(let U of O.lines?.splice(0)??[])this.send({type:"task.progress",taskId:t.taskId,text:U});for(let U of O.agentNotes?.splice(0)??[])this.send({type:"task.progress",taskId:t.taskId,text:U.text,agent:U.agent,...U.ms!==void 0&&{ms:U.ms}});let V=et(),w=V?JSON.stringify(V):"",j=!!O.progress&&O.progress!==dr;if(j||w!==gn){dr=O.progress,gn=w,Ri=Date.now();let U=j&&O.progressAgent;this.send({type:"task.progress",taskId:t.taskId,text:j?O.progress:"",...V&&{usage:V},...U&&{agent:U}})}};if(P.stdout.setEncoding("utf8"),P.stdout.on("data",V=>{Ne.refresh(),We.length<4*U$&&(We+=V),bt+=V;let w=bt.split(`
|
|
305
|
+
`);bt=w.pop();for(let U of w)u.line(U.trim(),O);if(O.mcpDown&&t.agent){Ut||(Ut=!0,P.kill("SIGTERM"),setTimeout(()=>P.exitCode===null&&P.signalCode===null&&P.kill("SIGKILL"),5e3).unref());return}fr(O.limits),O.sessionId&&O.sessionId!==mr&&E&&(mr=O.sessionId,this.opts.sessions.set(t.threadId,t.cli,{id:O.sessionId,task:t.taskId,cwd:c},t.account).catch(()=>{}));let j=et();(Date.now()-Ri>=ej||j&&JSON.stringify(j)!==gn||O.agentNotes?.length||O.lines?.length)&&Rs()}),P.stderr.setEncoding("utf8"),P.stderr.on("data",V=>{Ne.refresh(),Et.length<2e4&&(Et+=V)}),P.stdin.on("error",()=>{}),u.acp){let V={write:j=>{P.stdin.write(j)},end:()=>P.stdin.end()},w={cwd:c,prompt:I,mcpServers:l.mcpServers??[],resume:o,dirs:d,...u.acp(i.access,ls(t.model))};O.acp=new ms(V,w,O),O.acp.start()}else if(r.appServer){let V={write:j=>{P.stdin.write(j)},end:()=>P.stdin.end()},w={cwd:c,prompt:I,resume:o,model:ls(t.model),clientVersion:this.opts.version??"0",...r.appServer};O.appServer=new gs(V,w,O),this.turns.set(t.taskId,O.appServer),O.appServer.start()}else if(r.stream){let V={write:w=>{P.stdin.write(w)},end:()=>P.stdin.end()};O.claudeStream=new hs(V,I),this.turns.set(t.taskId,O.claudeStream),O.claudeStream.start()}else P.stdin.end(A?"":I);return await new Promise(V=>{let w=!1,j=(ae,ce)=>{if(w)return;if(w=!0,clearTimeout(Ne),m(),this.running.delete(t.taskId),this.turns.delete(t.taskId),this.worktrees.delete(t.taskId),this.opts.onChange?.(this.runningIds()),this.interrupted.delete(t.taskId))return a(`\u25A0 ${u.id} task interrupted; it continues after the runner restarts`),V(!1);if(this.cancelled.delete(t.taskId))return a(`\u25A0 ${u.id} task stopped`),this.send({type:"task.done",taskId:t.taskId,ok:!1,cancelled:!0,result:"Stopped from Myrel."}),V(!1);a(`${ae?"\u2713":"\u2717"} ${u.id} task finished`);let De=et();this.send({type:"task.done",taskId:t.taskId,ok:ae,result:ce.slice(0,U$-f.length)+f,...De&&{usage:De}}),V(!1)};P.on("error",ae=>{j(!1,ae.code==="ENOENT"?`${u.bin} is not installed on this computer, or not on PATH for myrel-runner.`:`Could not start ${u.bin}: ${ae.message}`)});let U=!1,ct=async()=>{if(U||w)return;U=!0,clearTimeout(Ne),this.turns.delete(t.taskId);let ae=await this.mcpProbe(t);if(r.again)return j(!1,nj(u.bin,O.mcpDown,ae));if(a(` ${u.bin} could not connect to Myrel's tools (${O.mcpDown}${ae?`; ${ae}`:""}); starting it again`),await new Promise(ce=>setTimeout(ce,this.opts.mcpRetryMs??tj)),this.cancelled.has(t.taskId)||this.interrupted.has(t.taskId))return j(!1,"");w=!0,V(await this.attempt(t,{...r,again:!0},o,n))};P.on("exit",()=>{this.cancelled.has(t.taskId)||this.interrupted.has(t.taskId)?j(!1,""):Ut?ct():re&&j(!1,M$(u.bin,Q))}),P.on("close",async(ae,ce)=>{if(Ut)return;bt.trim()&&u.line(bt.trim(),O),u.end?.(We,O),fr(O.limits??await u.limits?.(O).catch(()=>{}));let De=(ae===0||ae===1&&!!O.completed)&&!O.failed&&!re;if(o&&!De&&!re&&!O.usage&&!O.progress&&!this.cancelled.has(t.taskId))return w=!0,clearTimeout(Ne),this.running.delete(t.taskId),this.turns.delete(t.taskId),this.interrupted.has(t.taskId)?(this.interrupted.delete(t.taskId),this.worktrees.delete(t.taskId),this.opts.onChange?.(this.runningIds()),m(),V(!1)):V(!0);O.sessionId&&E&&await this.opts.sessions.set(t.threadId,t.cli,{id:O.sessionId,task:t.taskId,cwd:c},t.account).catch(()=>{});let gr=re?M$(u.bin,Q):O.result??(De?We.trim():ij(u.bin,ae,ce,O.error??(Et.trim()||We.trim())));j(De,gr||"(no output)")})})}cancel(t){let r=this.running.get(t);if(!r)return;this.cancelled.add(t);let o=this.turns.get(t)?.interrupt()?5e3:0,n=()=>{r.exitCode===null&&(r.kill("SIGTERM"),setTimeout(()=>r.exitCode===null&&r.kill("SIGKILL"),5e3).unref())};o?setTimeout(n,o).unref():n()}stopAll(){let t=this.runningIds();for(let[r,o]of this.running)this.interrupted.add(r),o.kill("SIGTERM");return t}async mcpProbe(t){let r=this.opts.config().server;if(!r||!t.agent)return;let o=Date.now();try{let n=await fetch(`${r.replace(/\/$/,"")}${t.agent.mcpPath}`,{method:"POST",headers:{authorization:`Bearer ${t.agent.token}`,"content-type":"application/json",accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"myrel-runner",version:this.opts.version??"0"}}}),signal:AbortSignal.timeout(15e3)});return await n.body?.cancel(),n.ok?`Myrel answers now, in ${((Date.now()-o)/1e3).toFixed(1)} s`:`Myrel answers HTTP ${n.status}`}catch(n){let i=n.cause?.code,a=n.name==="TimeoutError"?"no answer in 15 s":typeof i=="string"?i:xs(n);return`${new URL(r).host} cannot be reached from here (${a})`}}};function nj(e,t,r){return[`${e} could not connect to Myrel's tools twice (its MCP server: ${t}${r?`; ${r}`:""}), so it was stopped before doing anything.`,"This is usually Myrel answering too slowly for a moment or this computer's connection dropping: send your message again."].join(" ")}async function _s(e,t){let r=await R$(t).catch(()=>null);if(!r)return null;for(let o of e.folders)if(await R$(o.path).catch(()=>null)===r)return r;return null}async function rj(e,t,r){if(e.cwd)return e.cwd===t;if(!r)return!0;let{folder:o,threadId:n}=r;return!(await vt().catch(()=>[])).some(i=>i.threadId===n&&(o===i.repo||o.startsWith(i.repo+YA)))}var xs=e=>(e.stderr||e.message||String(e)).trim().split(`
|
|
306
|
+
`).at(-1);function M$(e,t){let r=Math.round(t/6e4);return`${e} wrote nothing for ${r} minutes, so Myrel stopped it as stuck. Write here to continue; the next turn picks up where it left off.`}function ij(e,t,r,o){return r==="SIGKILL"?`${e} was killed (SIGKILL), most likely because this computer ran out of memory. Stop programs it does not need (dev servers left running, say) or add swap, then send the message again.`:`${e} exited with ${r??`code ${t}`}.
|
|
307
|
+
${o}`}async function F$(e,t){let r=await dj(e,t.folders,t.worktrees===!1?void 0:t.threadId);if(!r.length)throw new Error("None of this project's folders is shared on this computer.");let o=pj(t.path),n=sj(o)?[o]:r.map(i=>lj(i,o));for(let i of n){let a=await Z$(i).catch(()=>null);if(!a||!r.some(p=>V$(a,p)))continue;let c=await aj(a);if(!c.isFile())continue;let u=Math.min(c.size,km),l=Buffer.alloc(u),d=await oj(a,"r");try{await d.read(l,0,u,0)}finally{await d.close()}return{path:a,size:c.size,data:l.toString("base64"),truncated:c.size>u}}throw new Error(`${t.path} is not a file in this project's folders.`)}async function dj(e,t,r){let o=(await Promise.all(t.map(a=>_s(e,a)))).filter(a=>a!==null),n=r?(await vt()).filter(a=>a.threadId===r):[],i=[];for(let a of o)for(let c of n){if(!V$(a,c.repo))continue;let u=await Z$(cj(c.path,uj(c.repo,a))).catch(()=>null);u&&i.push(u)}return[...i,...o]}function pj(e){let t=e.trim();t.startsWith("file://")&&(t=t.slice(7));try{t=decodeURIComponent(t)}catch{}return t.replace(/#L\d+(-L?\d+)?$/,"").replace(/(:\d+){1,2}$/,"")}function V$(e,t){return e===t||e.startsWith(t.endsWith(L$)?t:t+L$)}import{readdir as mj,realpath as rf,stat as K$}from"node:fs/promises";import{homedir as J$}from"node:os";import{dirname as fj,isAbsolute as gj,join as hj,parse as vj}from"node:path";var yj=1e3;async function B$(e){let t=J$(),r=await rf(e?G$(e):t),n=(await mj(r,{withFileTypes:!0})).filter(u=>(u.isDirectory()||u.isSymbolicLink())&&!u.name.startsWith(".")).map(u=>({name:u.name,path:hj(r,u.name)})),a=(await Promise.all(n.map(async u=>(await K$(u.path).catch(()=>null))?.isDirectory()?u:null))).filter(u=>u!==null);a.sort((u,l)=>u.name.localeCompare(l.name,void 0,{sensitivity:"base"}));let c=fj(r);return{path:r,parent:c===r?null:c,home:t,dirs:a.slice(0,yj)}}async function W$(e){let t=await rf(G$(e)).catch(()=>{throw new Error(`${e} does not exist on this computer.`)});if(!(await K$(t)).isDirectory())throw new Error(`${e} is not a folder.`);if(t===vj(t).root||t===await rf(J$()))throw new Error("Pick a project folder, not your whole home folder or disk.");return t}function G$(e){if(!gj(e))throw new Error(`${e} is not a full path.`);return e}import{readFileSync as bj,rmSync as $j,writeFileSync as xj,mkdirSync as wj}from"node:fs";import{join as q$}from"node:path";var _j=3600*1e3,of=()=>q$(Y(),"interrupted.json"),H$=()=>q$(Y(),"running.json");function X$(e,t=Date.now()){if(!e.length)return;let r=[...Q$(t),...e.map(o=>({taskId:o,at:t}))];tx(of(),r)}function Y$(e=Date.now()){let t=[...new Set(Q$(e).map(r=>r.taskId))];return $j(of(),{force:!0}),t}function Q$(e){let t=ex(of());return Array.isArray(t)?t.filter(r=>typeof r?.taskId=="string"&&e-r.at<_j):[]}function af(e){try{tx(H$(),{pid:process.pid,running:e})}catch{}}function sf(){let e=ex(H$());return!e?.pid||!Array.isArray(e.running)||!kj(e.pid)?[]:e.running}function kj(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function ex(e){try{return JSON.parse(bj(e,"utf8"))}catch{return}}function tx(e,t){wj(Y(),{recursive:!0,mode:448}),xj(e,`${JSON.stringify(t)}
|
|
308
|
+
`,{mode:384})}import{spawn as Sj}from"node:child_process";import{createHash as Ij,randomBytes as zj}from"node:crypto";import{access as lf,chmod as Pj,mkdir as ks,readdir as Aj,readFile as df,rm as nx,writeFile as ix}from"node:fs/promises";import{homedir as ox}from"node:os";import{dirname as jj,join as yt,relative as Tj,resolve as rx}from"node:path";var pn=()=>yt(Y(),"ssh"),Pi=()=>yt(pn(),"keys.json"),cf=()=>yt(pn(),"known_hosts"),Cj=()=>yt(pn(),"askpass.sh"),ur="myrel-runner-ssh",Oj=3e4,pf=e=>yt(pn(),e.projectId,e.alias),dn=e=>`${e.projectId}/${e.alias}`,ax=e=>`myrel.${e.projectId}.${e.alias}`;function Ss(e){let t=e.trim().split(/\s+/)[1]??"";return`SHA256:${Ij("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}function at(e,t,r={}){let o=r.max??Vy;return new Promise((n,i)=>{let a=Sj(e,t,{env:r.env??uf(),stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],windowsHide:!0}),c="",u="",l=!1,d=!1,p=(m,g)=>m.length+g.length<=o?m+g:(l=!0,m+g.slice(0,Math.max(0,o-m.length)));a.stdout.setEncoding("utf8").on("data",m=>c=p(c,m)),a.stderr.setEncoding("utf8").on("data",m=>u=p(u,m));let f=r.timeoutMs?setTimeout(()=>{d=!0,a.kill("SIGKILL")},r.timeoutMs):void 0;a.once("error",m=>{clearTimeout(f),i(m)}),a.once("close",m=>{clearTimeout(f),n({code:m,stdout:c,stderr:u,truncated:l,timedOut:d})}),r.input!==void 0&&a.stdin.end(r.input)})}function uf(e={}){let t={...process.env,...e};for(let r of["SSH_AUTH_SOCK","SSH_AGENT_PID","SSH_ASKPASS","SSH_ASKPASS_REQUIRE","MYREL_RUNNER_TOKEN"])r in e||delete t[r];return t}function mf(e=process.platform){return e==="darwin"?{async set(t,r){let o=await at("security",["-i"],{input:`add-generic-password -U -a "${t}" -s "${ur}" -w "${r}"
|
|
309
|
+
`,timeoutMs:15e3});if(o.code!==0||/error/i.test(o.stderr))throw new Error(`Keychain: ${o.stderr.trim()||`exit ${o.code}`}`)},async get(t){let r=await at("security",["find-generic-password","-a",t,"-s",ur,"-w"],{timeoutMs:15e3});return r.code===0?r.stdout.replace(/\n$/,""):null},async remove(t){await at("security",["delete-generic-password","-a",t,"-s",ur],{timeoutMs:15e3}).catch(()=>{})}}:e==="linux"?{async set(t,r){let o=await at("secret-tool",["store",`--label=Myrel SSH key ${t}`,"service",ur,"account",t],{input:r,timeoutMs:15e3});if(o.code!==0)throw new Error(`Secret Service: ${o.stderr.trim()||`exit ${o.code}`}`)},async get(t){let r=await at("secret-tool",["lookup","service",ur,"account",t],{timeoutMs:15e3});return r.code===0&&r.stdout?r.stdout.replace(/\n$/,""):null},async remove(t){await at("secret-tool",["clear","service",ur,"account",t],{timeoutMs:15e3}).catch(()=>{})}}:null}async function Nj(e,t,r){if(!e)return!1;try{return await e.set(t,r),await e.get(t)===r}catch{return!1}}async function sx(e,t,r,o=mf()){if(await ks(pn(),{recursive:!0,mode:448}),await ff(e,o),r){let l=await Dj(r),d=await at("ssh-keygen",["-y","-P","","-f",l],{timeoutMs:15e3});if(d.code!==0)throw new Error(/passphrase|incorrect/i.test(d.stderr)?"This key has a passphrase, so Myrel cannot use it on its own. Let Myrel make a new key instead.":`Could not read ${l}: ${d.stderr.trim()||`exit ${d.code}`}`);let p=await ve(Pi())??{};p[dn(e)]=l,await Xe(Pi(),p);let f=d.stdout.trim();return{publicKey:f,fingerprint:Ss(f),protected:!1}}let n=pf(e);await ks(jj(n),{recursive:!0,mode:448});let i=zj(24).toString("base64url"),a=await Nj(o,dn(e),i),c=await at("ssh-keygen",["-q","-t","ed25519","-N",a?i:"","-C",t,"-f",n],{timeoutMs:3e4});if(c.code!==0)throw new Error(`ssh-keygen failed: ${c.stderr.trim()||`exit ${c.code}`}. Is OpenSSH installed on this computer?`);await Pj(n,384).catch(()=>{});let u=(await df(`${n}.pub`,"utf8")).trim();return{publicKey:u,fingerprint:Ss(u),protected:a}}async function Dj(e,t=ox()){let r=yt(t,".ssh"),o=rx(r,e),n=Tj(r,o);if(!n||n.startsWith("..")||rx(r,n)!==o)throw new Error("Only keys in ~/.ssh can be used.");return await lf(o),o}async function cx(e=ox()){let t=yt(e,".ssh"),r=await Aj(t).catch(()=>[]),o=[];for(let n of r.filter(i=>i.endsWith(".pub")).sort()){let i=yt(t,n.slice(0,-4));if(!await lf(i).then(()=>!0,()=>!1))continue;let a=(await df(yt(t,n),"utf8").catch(()=>"")).trim(),[c,u,...l]=a.split(/\s+/);!c||!u||o.push({path:i,name:n.slice(0,-4),type:c,fingerprint:Ss(a),comment:l.join(" ").slice(0,500)})}return o.slice(0,100)}async function ff(e,t=mf()){let r=pf(e);await nx(r,{force:!0}),await nx(`${r}.pub`,{force:!0}),await t?.remove(dn(e));let o=await ve(Pi());o&&dn(e)in o&&(delete o[dn(e)],await Xe(Pi(),o)),await lx(e,null)}async function Rj(e,t){let r=(await ve(Pi()))?.[dn(e)];if(r)return{path:r,passphrase:null};let o=pf(e);return await lf(o).then(()=>!0,()=>!1)?{path:o,passphrase:await t?.get(dn(e)).catch(()=>null)??null}:null}async function ux(e,t){let r=await at("ssh-keyscan",["-T","10","-p",String(t),"-t","ed25519,ecdsa,rsa","--",e],{timeoutMs:3e4}),o=Uj(r.stdout);if(!o.length)throw new Error(`${e}:${t} did not answer with a server key${r.stderr.trim()?` (${r.stderr.trim().split(`
|
|
310
|
+
`).pop()})`:""}.`);return o}var Ej=["ssh-ed25519","ecdsa-sha2-nistp256","ecdsa-sha2-nistp384","ecdsa-sha2-nistp521","rsa-sha2-512","ssh-rsa"];function Uj(e){let t=[];for(let o of e.split(`
|
|
311
|
+
`)){if(!o.trim()||o.startsWith("#"))continue;let[,n,i]=o.trim().split(/\s+/);if(!n||!i||!/^[A-Za-z0-9+/=]+$/.test(i))continue;let a=`${n} ${i}`;t.some(c=>c.key===a)||t.push({type:n,key:a,fingerprint:Ss(a)})}let r=o=>Ej.indexOf(o)+1||99;return t.sort((o,n)=>r(o.type)-r(n.type)).slice(0,10)}async function lx(e,t,r=!0){let o=ax(e),n=(await df(cf(),"utf8").catch(()=>"")).split(`
|
|
312
312
|
`).filter(Boolean),i=n.filter(u=>u.startsWith(`${o} `)),a=t?`${o} ${t.trim().split(/\s+/).slice(0,2).join(" ")}`:null;if(!r&&i.length){if(a&&i.includes(a))return;throw new Is}let c=[...n.filter(u=>!u.startsWith(`${o} `)),...a?[a]:[]];!a&&!i.length||(await ks(pn(),{recursive:!0,mode:448}),await ix(cf(),c.length?`${c.join(`
|
|
313
313
|
`)}
|
|
314
|
-
`:"",{mode:384}))}var Is=class extends Error{constructor(){super("The server's key is not the one confirmed in Myrel.")}};function
|
|
314
|
+
`:"",{mode:384}))}var Is=class extends Error{constructor(){super("The server's key is not the one confirmed in Myrel.")}};function Mj(e,t,r){let o=n=>["-o",n];return["-F","none","-T","-n",...o(`BatchMode=${r.passphrase?"no":"yes"}`),...o("IdentitiesOnly=yes"),...o("IdentityAgent=none"),...o("PasswordAuthentication=no"),...o("KbdInteractiveAuthentication=no"),...o("StrictHostKeyChecking=yes"),...o(`UserKnownHostsFile=${cf()}`),...o(`GlobalKnownHostsFile=${process.platform==="win32"?"NUL":"/dev/null"}`),...o(`HostKeyAlias=${ax(e)}`),...o("UpdateHostKeys=no"),...o("ForwardAgent=no"),...o("ForwardX11=no"),...o("ClearAllForwardings=yes"),...o("PermitLocalCommand=no"),...o(`ConnectTimeout=${r.timeoutSec}`),"-i",t,"-p",String(e.port),"-l",e.user,"--",e.host]}async function gf(e,t,r={}){let o=Date.now(),n=(p,f)=>({exitCode:null,stdout:"",stderr:f,truncated:!1,ms:Date.now()-o,error:p}),i=r.keychain===void 0?mf():r.keychain,a=await Rj(e,i);if(!a)return n("nokey","This computer has no key for this server. Set it up again in the project's SSH settings.");try{await lx(e,e.hostKey,!!r.trust)}catch(p){if(p instanceof Is)return n("hostkey",p.message);throw p}let c=r.timeoutMs??Fy,u=a.passphrase?uf({SSH_ASKPASS:await Zj(),SSH_ASKPASS_REQUIRE:"force",DISPLAY:process.env.DISPLAY||":0",MYREL_SSH_PASSPHRASE:a.passphrase}):uf(),l=await at("ssh",[...Mj(e,a.path,{passphrase:!!a.passphrase,timeoutSec:15}),t],{env:u,timeoutMs:c}),d=Date.now()-o;return l.timedOut?{exitCode:null,stdout:l.stdout,stderr:l.stderr,truncated:l.truncated,ms:d,error:"timeout"}:{exitCode:l.code,stdout:l.stdout,stderr:l.stderr,truncated:l.truncated,ms:d,...l.code===255&&{error:Lj(l.stderr)}}}var dx=(e,t)=>gf(e,"true",{trust:!0,keychain:t,timeoutMs:Oj});function Lj(e){return/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key verification failed|No .* host key is known/i.test(e)?"hostkey":/Permission denied|Too many authentication failures|no mutual signature/i.test(e)?"auth":/Connection (refused|timed out|closed)|Could not resolve|No route to host|Network is unreachable|Operation timed out/i.test(e)?"connect":"other"}async function Zj(){let e=Cj();return await ks(pn(),{recursive:!0,mode:448}),await ix(e,`#!/bin/sh
|
|
315
315
|
printf "%s\\n" "$MYREL_SSH_PASSPHRASE"
|
|
316
|
-
`,{mode:448}),e}import{execFile as
|
|
317
|
-
`).filter(Boolean).at(-1)}). Use \`myrel-runner start\` instead.`)}}else await zs(i.file,
|
|
316
|
+
`,{mode:448}),e}import{execFile as nT}from"node:child_process";import{createHash as rT}from"node:crypto";import{copyFile as wx,rename as iT,rm as _x,stat as kx,writeFile as oT}from"node:fs/promises";import{join as xf,resolve as aT}from"node:path";import{promisify as sT}from"node:util";import{gunzipSync as cT}from"node:zlib";import{execFile as Fj,spawn as fx}from"node:child_process";import{copyFile as Vj,mkdir as hf,readFile as Kj,rm as gx,stat as Jj,writeFile as zs}from"node:fs/promises";import{homedir as lr,platform as hx}from"node:os";import{delimiter as px,join as st}from"node:path";import{promisify as Bj}from"node:util";var Me=Bj(Fj),mn="io.fibteq.myrel-runner",fn="myrel-runner.service";async function yf(e){let t=Ps(),r=ji();await hf(st(Y(),"bin"),{recursive:!0,mode:448}),e!==r&&await Vj(e,r);let o=[process.execPath,r,"start"],n=Gj(),i=await As(t);if(t==="launchd")await hf(st(lr(),"Library","LaunchAgents"),{recursive:!0}),await zs(i.file,qj(o,n,i.log)),await Wj(i.file);else if(t==="systemd"){await hf(st(lr(),".config","systemd","user"),{recursive:!0}),await zs(i.file,Hj(o,n));try{await Me("systemctl",["--user","daemon-reload"]),await Me("systemctl",["--user","enable",fn]),await Me("systemctl",["--user","restart",fn])}catch(a){throw await gx(i.file,{force:!0}),new Error(`Could not register with systemd (${a.message.split(`
|
|
317
|
+
`).filter(Boolean).at(-1)}). Use \`myrel-runner start\` instead.`)}}else await zs(i.file,Yj(o,i.log)),fx("wscript.exe",[i.file],{detached:!0,stdio:"ignore"}).unref();return Ti()}var ji=()=>st(Y(),"bin","myrel-runner.mjs");async function vx(){if(Ps()!=="startup")return;let e=await As("startup");e.installed&&fx("wscript.exe",[e.file],{detached:!0,stdio:"ignore"}).unref()}async function Wj(e){let t=`gui/${process.getuid?.()}`,r=()=>Me("launchctl",["print",`${t}/${mn}`]).then(()=>!0,()=>!1);await Me("launchctl",["bootout",`${t}/${mn}`]).catch(()=>{});for(let o=0;o<50&&await r();o++)await vf(100);for(let o=1;;o++)try{await Me("launchctl",["bootstrap",t,e]);break}catch(n){if(o>=5)throw n;await vf(500*o)}for(let o=0;o<30;o++){if((await Me("launchctl",["print",`${t}/${mn}`]).catch(()=>null))?.stdout.includes("state = running"))return;await vf(100)}}var vf=e=>new Promise(t=>setTimeout(t,e));async function yx(){let e=Ps(),t=await As(e);return e==="launchd"?await Me("launchctl",["bootout",`gui/${process.getuid?.()}/${mn}`]).catch(()=>{}):e==="systemd"&&await Me("systemctl",["--user","disable","--now",fn]).catch(()=>{}),await gx(t.file,{force:!0}),e==="systemd"&&await Me("systemctl",["--user","daemon-reload"]).catch(()=>{}),Ti()}async function Ti(){let e=await As(Ps());if(!e.installed)return{...e,running:!1};if(e.manager==="launchd"){let t=await Me("launchctl",["print",`gui/${process.getuid?.()}/${mn}`]).catch(()=>null);return{...e,running:!!t?.stdout.includes("state = running")}}if(e.manager==="systemd"){let t=await Me("systemctl",["--user","is-active",fn]).catch(()=>null);return{...e,running:t?.stdout.trim()==="active"}}return{...e,running:null}}function Ps(){let e=hx();if(e==="darwin")return"launchd";if(e==="linux")return"systemd";if(e==="win32")return"startup";throw new Error(`Running in the background is not supported on ${e} yet. Use \`myrel-runner start\`.`)}async function As(e){let t=e==="launchd"?st(lr(),"Library","LaunchAgents",`${mn}.plist`):e==="systemd"?st(lr(),".config","systemd","user",fn):st(process.env.APPDATA??st(lr(),"AppData","Roaming"),"Microsoft","Windows","Start Menu","Programs","Startup","myrel-runner.vbs"),r=e==="systemd"?`journalctl --user -u ${fn}`:st(Y(),"runner.log"),o=!!await Jj(t).catch(()=>null);return{manager:e,file:t,installed:o,log:r}}function Gj(){let t={PATH:(process.env.PATH??"").split(px).filter(r=>r&&!/[\\/]_npx[\\/]/.test(r)).join(px)};return process.env.MYREL_RUNNER_HOME&&(t.MYREL_RUNNER_HOME=process.env.MYREL_RUNNER_HOME),t}var Ai=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function qj(e,t,r){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
318
318
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
319
319
|
<plist version="1.0">
|
|
320
320
|
<dict>
|
|
@@ -337,7 +337,7 @@ ${Object.entries(t).map(([o,n])=>` <key>${Ai(o)}</key><string>${Ai(n)}</strin
|
|
|
337
337
|
<key>StandardErrorPath</key><string>${Ai(r)}</string>
|
|
338
338
|
</dict>
|
|
339
339
|
</plist>
|
|
340
|
-
`}var mx=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`;function
|
|
340
|
+
`}var mx=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`;function Hj(e,t){return`[Unit]
|
|
341
341
|
Description=Myrel runner (connects this computer to Myrel)
|
|
342
342
|
After=network-online.target
|
|
343
343
|
|
|
@@ -351,12 +351,12 @@ ${bx}
|
|
|
351
351
|
|
|
352
352
|
[Install]
|
|
353
353
|
WantedBy=default.target
|
|
354
|
-
`}var bx="OOMPolicy=continue";function
|
|
355
|
-
${bx}`)}async function $x(){if(hx()!=="linux")return;let e=st(lr(),".config","systemd","user",fn),t=
|
|
354
|
+
`}var bx="OOMPolicy=continue";function Xj(e){return/^OOMPolicy=/m.test(e)||!/^RestartSec=.*$/m.test(e)?null:e.replace(/^RestartSec=.*$/m,t=>`${t}
|
|
355
|
+
${bx}`)}async function $x(){if(hx()!=="linux")return;let e=st(lr(),".config","systemd","user",fn),t=Xj(await Kj(e,"utf8").catch(()=>""));t&&(await zs(e,t),await Me("systemctl",["--user","daemon-reload"]))}function Yj(e,t){return`' Starts myrel-runner at login. Remove with: myrel-runner service uninstall\r
|
|
356
356
|
CreateObject("WScript.Shell").Run "${`cmd.exe /c "${e.map(o=>`"${o}"`).join(" ")} >> "${t}" 2>&1"`.replace(/"/g,'""')}", 0, False\r
|
|
357
|
-
`}import{spawn as
|
|
358
|
-
`)[0]}), so it was not installed.`)}await kx(r).catch(()=>null)&&await wx(r,$f()),await rT(o,r)}async function Tx(){return await kx($f()).catch(()=>null)?(await wx($f(),ji()),!0):!1}import{execFile as lT}from"node:child_process";import{readFile as dT,statfs as Cx}from"node:fs/promises";import{cpus as Ox,freemem as pT,homedir as mT,platform as fT,totalmem as gT}from"node:os";import{promisify as hT}from"node:util";var vT=hT(lT);function yT(e=Ox()){let t=0,r=0;for(let{times:o}of e)t+=o.idle,r+=o.user+o.nice+o.sys+o.idle+o.irq;return{idle:t,total:r}}function bT(e,t){let r=t.total-e.total;if(r<=0)return;let o=r-(t.idle-e.idle);return Math.round(Math.min(100,Math.max(0,o/r*100))*10)/10}function $T(e){let t=a=>{let c=e.match(new RegExp(`^${a}:\\s+(\\d+)\\s*kB`,"m"));return c?Number(c[1])*1024:void 0},r=t("MemTotal"),o=t("MemAvailable")??t("MemFree");if(r===void 0||o===void 0)return;let n=t("SwapTotal"),i=t("SwapFree");return{total:r,available:Math.min(r,o),...n!==void 0&&i!==void 0&&{swap:{total:n,used:Math.max(0,n-i)}}}}function xT(e,t){let r=Number(e.match(/page size of (\d+) bytes/)?.[1]),o=i=>Number(e.match(new RegExp(`^${i}:\\s+(\\d+)\\.`,"m"))?.[1]),n=(o("Pages active")+o("Pages wired down")+o("Pages occupied by compressor"))*r;if(!(!Number.isFinite(n)||!Number.isFinite(r)))return{total:t,available:Math.min(t,Math.max(0,t-n))}}var wT=()=>({platform:fT(),cores:()=>Ox().length,cpuTimes:yT,totalmem:gT,freemem:pT,meminfo:()=>dT("/proc/meminfo","utf8"),vmStat:async()=>(await vT("vm_stat",[],{timeout:5e3,env:Ue()})).stdout,disk:async()=>{let e=Y(),t=await Cx(e).catch(()=>Cx(mT()));return{total:t.blocks*t.bsize,free:t.bavail*t.bsize}},runnerMemory:()=>process.memoryUsage.rss(),now:()=>new Date}),Cs=class{constructor(t,r={}){this.tasks=t;this.sources={...wT(),...r}}tasks;sources;previous;latest;async sample(){let t=this.sources,r=t.cpuTimes(),o=this.previous?bT(this.previous,r):void 0;this.previous=r;let[n,i]=await Promise.all([this.memory(),t.disk().catch(()=>{})]),a={at:t.now().toISOString(),cpu:{...o!==void 0&&{percent:o},cores:Math.max(1,t.cores())},memory:{total:n.total,available:n.available},...n.swap&&{swap:n.swap},...i&&Number.isFinite(i.total)&&Number.isFinite(i.free)&&{disk:{total:Math.round(i.total),free:Math.round(i.free)}},tasks:this.tasks(),runnerMemory:t.runnerMemory()};return this.latest=a,a}async memory(){let t=this.sources,r=t.totalmem(),o={total:r,available:Math.min(r,t.freemem())};try{if(t.platform==="linux")return $T(await t.meminfo())??o;if(t.platform==="darwin")return xT(await t.vmStat(),r)??o}catch{}return o}};var _T=600*1e3,kT=360*60*1e3,Nx=120*1e3,Os=class{constructor(t){this.opts=t}opts;current=null;pending=null;busy=!1;hurry=!1;until=0;get now(){return(this.opts.now??Date.now)()}state(){return this.current??void 0}async init(){let t=await zx();if(!t)return!1;if(t.state==="restarting"&&t.version===this.opts.version)return this.pending=t,!0;if(t.state==="restarting")return await this.fail(t.version,"The new version did not start, so this one kept running.","failed",!1),!1;if((t.state==="failed"||t.state==="rolled-back")&&this.now-Date.parse(t.at)<Px){let{from:r,...o}=t;return this.current=o,!1}return await _f(),!1}async confirmed(){this.pending&&(this.opts.log(`\u25CF Updated myrel-runner from ${this.pending.from} to ${this.opts.version}.`),this.pending=null,this.current=null,await _f(),this.opts.report(null))}async rollback(t){let r=this.pending;if(r){if(this.pending=null,!await(this.opts.restore??Tx)().catch(()=>!1)){this.opts.log(`myrel-runner ${this.opts.version} could not connect (${t}), and there is no previous version to go back to.`);return}this.opts.log(`myrel-runner ${this.opts.version} could not connect (${t}); going back to ${r.from}.`),await Ts({state:"rolled-back",version:this.opts.version,from:r.from,message:t.slice(0,500),at:new Date(this.now).toISOString()}),this.opts.restart()}}get confirming(){return this.pending!==null}request(t,r=!1,o=!1){if(!Ci(t,this.opts.version))throw new Error(`myrel-runner ${this.opts.version} is already up to date.`);let n=this.now+(o?this.opts.autoWaitMs??kT:this.opts.waitMs??_T);return this.busy?(r&&(this.hurry=!0),this.until=Math.min(this.until,n),this.current):(this.busy=!0,this.hurry=r,this.until=n,this.set({state:"waiting",version:t,running:this.opts.running().length}),this.run(t).finally(()=>{this.busy=!1}),this.current)}async checkNewest(){if(this.busy||this.pending)return;let t=await(this.opts.latest??js)();!t||!Ci(t,this.opts.version)||this.current&&this.current.version===t&&this.current.state!=="waiting"||(this.opts.log(`Installing myrel-runner ${t} (auto-update is on).`),this.request(t,!1,!0))}async run(t){for(let o=this.opts.running();o.length&&!this.hurry&&this.now<this.until;o=this.opts.running())o.length!==this.current?.running&&this.set({state:"waiting",version:t,running:o.length}),await new Promise(n=>setTimeout(n,this.opts.pollMs??2e3));try{this.set({state:"downloading",version:t});let o=await(this.opts.download??Ax)(t);await(this.opts.install??jx)(o,t)}catch(o){await this.fail(t,o.message);return}let r={state:"restarting",version:t,from:this.opts.version,at:new Date(this.now).toISOString()};await Ts(r),this.set({state:"restarting",version:t}),this.opts.log(`Restarting on myrel-runner ${t}\u2026`),this.opts.restart()}async fail(t,r,o="failed",n=!0){n&&this.opts.log(`Could not update to myrel-runner ${t}: ${r}`);let i=new Date(this.now).toISOString();await Ts({state:o,version:t,from:this.opts.version,message:r.slice(0,500),at:i}).catch(()=>{}),this.set({state:o,version:t,message:r.slice(0,500)})}set(t){this.current={...t,at:new Date(this.now).toISOString()},this.opts.report(this.current)}};var Be="0.42.0",zT=360*60*1e3;async function Rx(e){let t=e.server.replace(/\/+$/,""),r=await fetch(`${t}/api/runner/pair`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:e.code,name:e.name||kf(),hostname:kf(),platform:Dx()})}),o=await r.json().catch(()=>null);if(!r.ok)throw new Error(o?.message??`Pairing failed (${r.status})`);let n=Qy.parse(o),i=await me();return Object.assign(i,{server:t,runnerId:n.runner.id,token:n.token}),await Oe(i),i}async function Ni(e){if(!e.server||!e.token)return"invalid";try{let t=await fetch(`${e.server}/api/runner/me`,{headers:{authorization:`Bearer ${e.token}`},signal:AbortSignal.timeout(1e4)});return t.ok?"ok":t.status===401?"invalid":"unknown"}catch{return"unknown"}}var PT="This computer is not paired with Myrel any more (it was removed, or paired again elsewhere). Get a new code in Myrel > Devices and run `myrel-runner pair <code> --server <url>`.",AT=900*1e3,Ex=75,jT=300*1e3;function TT(e,t){return e.length===t.length&&e.every(r=>t.some(o=>o.id===r.id&&o.version===r.version))}async function Ux(e={}){let t=e.log??(w=>console.log(w)),r=e.onStatus??(()=>{}),o=await me();if(!o.server||!o.token)throw new Error("This computer is not paired yet. Run `myrel-runner pair <code> --server <url>` first.");let n=await ki(),i=await h$().catch(()=>{}),a=await Eb(),c=(w,j,U)=>{let ct=Cm(w,U),se=a[ct];!j||se&&se.at>=j.at||(a[ct]=j,Ub(a).catch(()=>{}),JSON.stringify({...se,at:""})!==JSON.stringify({...j,at:""})&&re())},u=()=>{n.some(w=>w.id==="codex")&&as().then(w=>c("codex",w),()=>{})},l=new ws({config:()=>o,sessions:new es,log:t,onLimits:c,onChange:af,version:Be}),d=Y$();d.length&&t(`${d.length} task(s) stopped when the runner restarted; Myrel continues them.`),af([]);let p="stopped",f=null,m=!1,g=0,y,_=new Promise(w=>y=w),I=Ix();I==="service"&&$x().catch(()=>{});let k=new Os({version:Be,running:()=>l.runningIds(),report:w=>C({type:"update.status",update:w}),log:t,restart:()=>{vx().catch(()=>{}).finally(()=>{p="restart",et()})}}),A;await k.init()&&(A=setTimeout(()=>{Ni(o).then(w=>{w==="ok"&&k.confirming&&k.rollback("it did not connect within 2 minutes")})},Nx),A.unref?.());let Z=new Map,C=w=>{w.type==="task.done"&&(r({state:"task",taskId:w.taskId,event:"done",ok:w.ok}),Z.set(w.taskId,{frame:w,at:Date.now()})),f?.readyState===WebSocket.OPEN&&f.send(JSON.stringify(w))},E=()=>{for(let[w,{frame:j,at:U}]of Z)Date.now()-U>AT?Z.delete(w):C(j)},P=new Cs(()=>l.runningIds().length),Q=()=>o.stats!==!1;Q()&&await P.sample().catch(()=>{});let re=()=>C({type:"hello",protocol:Wy,version:Be,hostname:kf(),platform:Dx(),folders:o.folders,clis:n.map(w=>({...w,...a[w.id]&&{limits:a[w.id]},..._b(o,w.id,a)})),features:["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","models","git-token","git-tokens","steer","steer-claude","ssh","cli-accounts","shared-folder","coordinator",...I==="service"?["update"]:[],...Q()?["stats"]:[]],settings:Oi(o),updates:I,...k.state()&&{update:k.state()},...i&&{browser:i},running:l.runningIds(),interrupted:d,...Q()&&P.latest&&{stats:P.latest}});l.setSender(C);let Ne=async()=>{o=await me().catch(()=>o),re()};ST(Nt(),{interval:2e3},Ne);let N=setInterval(()=>{if(f?.readyState===WebSocket.OPEN){if(!Q())return C({type:"ping"});P.sample().then(w=>C({type:"ping",stats:w}),()=>C({type:"ping"}))}},25e3),We=()=>{Promise.all(n.map(async w=>{let j=await ar[w.id].models?.().catch(()=>{}),U=JSON.stringify(j)!==JSON.stringify(w.models);return j&&(w.models=j),U&&!!j})).then(w=>w.some(Boolean)&&re())};We(),u();let Et=()=>{ki().then(w=>{if(TT(n,w))return;let j=new Map(n.map(U=>[U.id,U]));n.splice(0,n.length,...w.map(U=>j.get(U.id)?.version===U.version?j.get(U.id):U)),t(`CLIs found: ${n.map(U=>U.id).join(", ")||"none"}`),re(),We(),u()},()=>{})},bt=setInterval(u,600*1e3),Ri=setInterval(We,360*60*1e3),dr=setInterval(Et,jT);bt.unref?.(),dr.unref?.();let gn=()=>{$s(w=>l.inUse(w)).then(w=>w.forEach(j=>t(`Removed the finished worktree ${j.path} (${j.branch})`))).catch(()=>{})};gn();let pr=setInterval(gn,360*60*1e3);pr.unref?.();let mr=()=>{I==="service"&&o.autoUpdate&&k.checkNewest().catch(()=>{})},Ut=setTimeout(mr,600*1e3);Ut.unref?.();let fr=setInterval(mr,zT);fr.unref?.();let et=()=>{m=!0,clearInterval(N),clearInterval(pr),clearInterval(bt),clearInterval(Ri),clearInterval(dr),clearInterval(fr),clearTimeout(Ut),clearTimeout(A),IT(Nt(),Ne),X$(l.stopAll()),f?.close(1e3),r({state:"stopped",reason:p}),y(p)},Rs=async w=>{let{requestId:j}=w;if(w.type==="dirs.list")return C({type:"dirs",requestId:j,...await B$(w.path)});if(w.type==="task.steer")return C({type:"task.steered",requestId:j,taken:await l.steer(w.taskId,w.text)});if(w.type==="file.read")return C({type:"file",requestId:j,...await F$(o,w)});if(w.type==="ssh.keygen"){let U=await sx({projectId:w.projectId,alias:w.alias},w.comment,w.existing);return t(`${w.existing?"Using":"Made"} an SSH key for ${w.alias} (${U.fingerprint}, from Myrel)`),C({type:"ssh.key",requestId:j,...U})}if(w.type==="ssh.keys")return C({type:"ssh.keylist",requestId:j,keys:await cx()});if(w.type==="ssh.hostkeys")return C({type:"ssh.hostkeylist",requestId:j,keys:await ux(w.host,w.port)});if(w.type==="ssh.test")return C({type:"ssh.result",requestId:j,...await dx(w.target)});if(w.type==="ssh.run")return t(`SSH ${w.target.alias}: ${w.command.split(`
|
|
359
|
-
`)[0].slice(0,80)}`),C({type:"ssh.result",requestId:j,...await gf(w.target,w.command)});if(w.type==="ssh.forget")return await ff({projectId:w.projectId,alias:w.alias}),t(`Forgot the SSH key for ${w.alias} (from Myrel)`),C({type:"ssh.result",requestId:j,exitCode:0,stdout:"",stderr:"",truncated:!1,ms:0});if(w.type==="runner.update"){if(I!=="service")throw new Error(I==="app"?"This runner came with the Myrel desktop app; it updates with the app.":"This runner was started in a terminal, so it cannot restart itself. Start it again with `npx myrel-runner@latest start`.");return t(`Updating to myrel-runner ${w.version} (from Myrel)${w.now?"":" once the running tasks finish"}`),C({type:"update.accepted",requestId:j,update:k.request(w.version,w.now)})}if(o=await me(),w.type==="settings.set")return Sx(o,w.settings),await Oe(o),t(`Settings changed from Myrel: ${Object.entries(w.settings).map(([U,ct])=>`${U} ${ct}`).join(", ")}`),C({type:"settings",requestId:j,settings:Oi(o)});if(w.type==="folder.share"){let U=await W$(w.path);ts(o,U)&&t(`Shared ${U} (from Myrel)`)}else ns(o,w.path)&&t(`Stopped sharing ${w.path} (from Myrel)`);await Oe(o),C({type:"folders",requestId:j,folders:o.folders})},V=()=>{if(m)return;let w=`${o.server.replace(/^http/,"ws")}/api/runner/connect`;r({state:"connecting"});let j=new WebSocket(w,{headers:{authorization:`Bearer ${o.token}`}});f=j;let U=!1;j.onopen=()=>{U=!0,g=0,E(),re()},j.onmessage=ce=>{let De=JSON.parse(String(ce.data)),gr=Yy.safeParse(De);if(!gr.success){let hn=De;if(hn?.type==="task.start"&&typeof hn.taskId=="string"){let Sf=gr.error.issues[0],If=`${Sf?.path.join(".")||"frame"}: ${Sf?.message??"invalid"}`;t(`\u2717 could not read task ${hn.taskId} (${If})`),C({type:"task.done",taskId:hn.taskId,ok:!1,result:`myrel-runner ${Be} could not read this task (${If}). Update myrel-runner.`})}return}let Se=gr.data;Se.type==="welcome"&&(t(`\u25CF Connected to ${o.server} as "${Se.name}"`),r({state:"online",name:Se.name}),k.confirmed()),Se.type==="task.start"&&(r({state:"task",taskId:Se.taskId,event:"started"}),l.start(Se)),Se.type==="task.cancel"&&l.cancel(Se.taskId),Se.type==="task.github"&&l.renewGithub(Se.taskId,Se.github),"requestId"in Se&&Rs(Se).catch(hn=>C({type:"request.failed",requestId:Se.requestId,message:
|
|
357
|
+
`}import{spawn as Qj}from"node:child_process";var eT="@fibteq/myrel-runner",bf="@fibteq%2Fmyrel-runner",tT=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;async function js(e="https://registry.npmjs.org"){try{let t=await fetch(`${e}/${bf}/latest`,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return null;let{version:r}=await t.json();return typeof r=="string"&&tT.test(r)?r:null}catch{return null}}var Ci=eb;function xx(e,t){let r=process.platform==="win32"?"npx.cmd":"npx";return new Promise((o,n)=>{let i=Qj(r,["--yes",`--package=${eT}@${e}`,"--","myrel-runner",...t],{stdio:"inherit",shell:process.platform==="win32",env:{...process.env,MYREL_RUNNER_UPDATING:e}});i.on("error",n),i.on("exit",a=>o(a??1))})}var uT=sT(nT);function Oi(e){return{access:e.access,worktrees:e.worktrees!==!1,autoUpdate:e.autoUpdate===!0,remote:e.remoteSettings!==!1}}function Sx(e,t){if(e.remoteSettings===!1)throw new Error("Changing settings from Myrel is turned off on this computer. Turn it on there with `myrel-runner settings remote on`.");t.access&&(e.access=t.access),t.worktrees!==void 0&&(e.worktrees=t.worktrees),t.autoUpdate!==void 0&&(e.autoUpdate=t.autoUpdate)}function Ix(e=process.argv[1]){return process.versions.bun?"app":e&&aT(e)===ji()?"service":"manual"}var $f=()=>xf(Y(),"bin","myrel-runner.prev.mjs"),wf=()=>xf(Y(),"update.json"),zx=()=>ve(wf()).catch(()=>{}),Ts=e=>Xe(wf(),e),_f=()=>_x(wf(),{force:!0}),Px=1440*60*1e3;async function Ax(e,t="https://registry.npmjs.org"){let r=await fetch(`${t}/${bf}/${e}`,{signal:AbortSignal.timeout(3e4)});if(!r.ok)throw new Error(`npm does not have myrel-runner ${e} (${r.status}).`);let{dist:o}=await r.json(),n=o?.integrity?.match(/^sha512-([A-Za-z0-9+/=]+)$/)?.[1];if(!o?.tarball||!n)throw new Error("npm sent no download for this version.");let i=await fetch(o.tarball,{signal:AbortSignal.timeout(12e4)});if(!i.ok)throw new Error(`Could not download myrel-runner ${e} (${i.status}).`);let a=Buffer.from(await i.arrayBuffer());if(rT("sha512").update(a).digest("base64")!==n)throw new Error("The download does not match npm's checksum, so it was not installed.");let c=lT(cT(a),"package/dist/cli.js");if(!c)throw new Error("The download has no dist/cli.js.");return c}function lT(e,t){let r;for(let o=0;o+512<=e.length;){let n=e.subarray(o,o+512);if(n.every(p=>p===0))return null;let i=(p,f)=>n.toString("utf8",p,p+f).replace(/\0.*$/s,""),a=Number.parseInt(i(124,12).trim()||"0",8),c=i(156,1),u=e.subarray(o+512,o+512+a);if(o+=512+Math.ceil(a/512)*512,c==="x"){r=u.toString("utf8").match(/^\d+ path=(.*)$/m)?.[1];continue}let l=i(345,155),d=r??(l?`${l}/${i(0,100)}`:i(0,100));if(r=void 0,(c==="0"||c==="")&&d===t)return Buffer.from(u)}return null}async function jx(e,t){let r=ji(),o=xf(Y(),"bin","myrel-runner.next.mjs");await oT(o,e,{mode:448});try{let{stdout:n}=await uT(process.execPath,[o,"--version"],{timeout:3e4});if(n.trim()!==t)throw new Error(`it says it is ${n.trim()||"nothing"}`)}catch(n){throw await _x(o,{force:!0}),new Error(`The new version does not start (${n.message.split(`
|
|
358
|
+
`)[0]}), so it was not installed.`)}await kx(r).catch(()=>null)&&await wx(r,$f()),await iT(o,r)}async function Tx(){return await kx($f()).catch(()=>null)?(await wx($f(),ji()),!0):!1}import{execFile as dT}from"node:child_process";import{readFile as pT,statfs as Cx}from"node:fs/promises";import{cpus as Ox,freemem as mT,homedir as fT,platform as gT,totalmem as hT}from"node:os";import{promisify as vT}from"node:util";var yT=vT(dT);function bT(e=Ox()){let t=0,r=0;for(let{times:o}of e)t+=o.idle,r+=o.user+o.nice+o.sys+o.idle+o.irq;return{idle:t,total:r}}function $T(e,t){let r=t.total-e.total;if(r<=0)return;let o=r-(t.idle-e.idle);return Math.round(Math.min(100,Math.max(0,o/r*100))*10)/10}function xT(e){let t=a=>{let c=e.match(new RegExp(`^${a}:\\s+(\\d+)\\s*kB`,"m"));return c?Number(c[1])*1024:void 0},r=t("MemTotal"),o=t("MemAvailable")??t("MemFree");if(r===void 0||o===void 0)return;let n=t("SwapTotal"),i=t("SwapFree");return{total:r,available:Math.min(r,o),...n!==void 0&&i!==void 0&&{swap:{total:n,used:Math.max(0,n-i)}}}}function wT(e,t){let r=Number(e.match(/page size of (\d+) bytes/)?.[1]),o=i=>Number(e.match(new RegExp(`^${i}:\\s+(\\d+)\\.`,"m"))?.[1]),n=(o("Pages active")+o("Pages wired down")+o("Pages occupied by compressor"))*r;if(!(!Number.isFinite(n)||!Number.isFinite(r)))return{total:t,available:Math.min(t,Math.max(0,t-n))}}var _T=()=>({platform:gT(),cores:()=>Ox().length,cpuTimes:bT,totalmem:hT,freemem:mT,meminfo:()=>pT("/proc/meminfo","utf8"),vmStat:async()=>(await yT("vm_stat",[],{timeout:5e3,env:Ue()})).stdout,disk:async()=>{let e=Y(),t=await Cx(e).catch(()=>Cx(fT()));return{total:t.blocks*t.bsize,free:t.bavail*t.bsize}},runnerMemory:()=>process.memoryUsage.rss(),now:()=>new Date}),Cs=class{constructor(t,r={}){this.tasks=t;this.sources={..._T(),...r}}tasks;sources;previous;latest;async sample(){let t=this.sources,r=t.cpuTimes(),o=this.previous?$T(this.previous,r):void 0;this.previous=r;let[n,i]=await Promise.all([this.memory(),t.disk().catch(()=>{})]),a={at:t.now().toISOString(),cpu:{...o!==void 0&&{percent:o},cores:Math.max(1,t.cores())},memory:{total:n.total,available:n.available},...n.swap&&{swap:n.swap},...i&&Number.isFinite(i.total)&&Number.isFinite(i.free)&&{disk:{total:Math.round(i.total),free:Math.round(i.free)}},tasks:this.tasks(),runnerMemory:t.runnerMemory()};return this.latest=a,a}async memory(){let t=this.sources,r=t.totalmem(),o={total:r,available:Math.min(r,t.freemem())};try{if(t.platform==="linux")return xT(await t.meminfo())??o;if(t.platform==="darwin")return wT(await t.vmStat(),r)??o}catch{}return o}};var kT=600*1e3,ST=360*60*1e3,Nx=120*1e3,Os=class{constructor(t){this.opts=t}opts;current=null;pending=null;busy=!1;hurry=!1;until=0;get now(){return(this.opts.now??Date.now)()}state(){return this.current??void 0}async init(){let t=await zx();if(!t)return!1;if(t.state==="restarting"&&t.version===this.opts.version)return this.pending=t,!0;if(t.state==="restarting")return await this.fail(t.version,"The new version did not start, so this one kept running.","failed",!1),!1;if((t.state==="failed"||t.state==="rolled-back")&&this.now-Date.parse(t.at)<Px){let{from:r,...o}=t;return this.current=o,!1}return await _f(),!1}async confirmed(){this.pending&&(this.opts.log(`\u25CF Updated myrel-runner from ${this.pending.from} to ${this.opts.version}.`),this.pending=null,this.current=null,await _f(),this.opts.report(null))}async rollback(t){let r=this.pending;if(r){if(this.pending=null,!await(this.opts.restore??Tx)().catch(()=>!1)){this.opts.log(`myrel-runner ${this.opts.version} could not connect (${t}), and there is no previous version to go back to.`);return}this.opts.log(`myrel-runner ${this.opts.version} could not connect (${t}); going back to ${r.from}.`),await Ts({state:"rolled-back",version:this.opts.version,from:r.from,message:t.slice(0,500),at:new Date(this.now).toISOString()}),this.opts.restart()}}get confirming(){return this.pending!==null}request(t,r=!1,o=!1){if(!Ci(t,this.opts.version))throw new Error(`myrel-runner ${this.opts.version} is already up to date.`);let n=this.now+(o?this.opts.autoWaitMs??ST:this.opts.waitMs??kT);return this.busy?(r&&(this.hurry=!0),this.until=Math.min(this.until,n),this.current):(this.busy=!0,this.hurry=r,this.until=n,this.set({state:"waiting",version:t,running:this.opts.running().length}),this.run(t).finally(()=>{this.busy=!1}),this.current)}async checkNewest(){if(this.busy||this.pending)return;let t=await(this.opts.latest??js)();!t||!Ci(t,this.opts.version)||this.current&&this.current.version===t&&this.current.state!=="waiting"||(this.opts.log(`Installing myrel-runner ${t} (auto-update is on).`),this.request(t,!1,!0))}async run(t){for(let o=this.opts.running();o.length&&!this.hurry&&this.now<this.until;o=this.opts.running())o.length!==this.current?.running&&this.set({state:"waiting",version:t,running:o.length}),await new Promise(n=>setTimeout(n,this.opts.pollMs??2e3));try{this.set({state:"downloading",version:t});let o=await(this.opts.download??Ax)(t);await(this.opts.install??jx)(o,t)}catch(o){await this.fail(t,o.message);return}let r={state:"restarting",version:t,from:this.opts.version,at:new Date(this.now).toISOString()};await Ts(r),this.set({state:"restarting",version:t}),this.opts.log(`Restarting on myrel-runner ${t}\u2026`),this.opts.restart()}async fail(t,r,o="failed",n=!0){n&&this.opts.log(`Could not update to myrel-runner ${t}: ${r}`);let i=new Date(this.now).toISOString();await Ts({state:o,version:t,from:this.opts.version,message:r.slice(0,500),at:i}).catch(()=>{}),this.set({state:o,version:t,message:r.slice(0,500)})}set(t){this.current={...t,at:new Date(this.now).toISOString()},this.opts.report(this.current)}};var Be="0.42.1",PT=360*60*1e3;async function Rx(e){let t=e.server.replace(/\/+$/,""),r=await fetch(`${t}/api/runner/pair`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:e.code,name:e.name||kf(),hostname:kf(),platform:Dx()})}),o=await r.json().catch(()=>null);if(!r.ok)throw new Error(o?.message??`Pairing failed (${r.status})`);let n=Qy.parse(o),i=await me();return Object.assign(i,{server:t,runnerId:n.runner.id,token:n.token}),await Oe(i),i}async function Ni(e){if(!e.server||!e.token)return"invalid";try{let t=await fetch(`${e.server}/api/runner/me`,{headers:{authorization:`Bearer ${e.token}`},signal:AbortSignal.timeout(1e4)});return t.ok?"ok":t.status===401?"invalid":"unknown"}catch{return"unknown"}}var AT="This computer is not paired with Myrel any more (it was removed, or paired again elsewhere). Get a new code in Myrel > Devices and run `myrel-runner pair <code> --server <url>`.",jT=900*1e3,Ex=75,TT=300*1e3;function CT(e,t){return e.length===t.length&&e.every(r=>t.some(o=>o.id===r.id&&o.version===r.version))}async function Ux(e={}){let t=e.log??(w=>console.log(w)),r=e.onStatus??(()=>{}),o=await me();if(!o.server||!o.token)throw new Error("This computer is not paired yet. Run `myrel-runner pair <code> --server <url>` first.");let n=await ki(),i=await h$().catch(()=>{}),a=await Eb(),c=(w,j,U)=>{let ct=Cm(w,U),ae=a[ct];!j||ae&&ae.at>=j.at||(a[ct]=j,Ub(a).catch(()=>{}),JSON.stringify({...ae,at:""})!==JSON.stringify({...j,at:""})&&re())},u=()=>{n.some(w=>w.id==="codex")&&as().then(w=>c("codex",w),()=>{})},l=new ws({config:()=>o,sessions:new es,log:t,onLimits:c,onChange:af,version:Be}),d=Y$();d.length&&t(`${d.length} task(s) stopped when the runner restarted; Myrel continues them.`),af([]);let p="stopped",f=null,m=!1,g=0,y,_=new Promise(w=>y=w),I=Ix();I==="service"&&$x().catch(()=>{});let k=new Os({version:Be,running:()=>l.runningIds(),report:w=>C({type:"update.status",update:w}),log:t,restart:()=>{vx().catch(()=>{}).finally(()=>{p="restart",et()})}}),A;await k.init()&&(A=setTimeout(()=>{Ni(o).then(w=>{w==="ok"&&k.confirming&&k.rollback("it did not connect within 2 minutes")})},Nx),A.unref?.());let Z=new Map,C=w=>{w.type==="task.done"&&(r({state:"task",taskId:w.taskId,event:"done",ok:w.ok}),Z.set(w.taskId,{frame:w,at:Date.now()})),f?.readyState===WebSocket.OPEN&&f.send(JSON.stringify(w))},E=()=>{for(let[w,{frame:j,at:U}]of Z)Date.now()-U>jT?Z.delete(w):C(j)},P=new Cs(()=>l.runningIds().length),Q=()=>o.stats!==!1;Q()&&await P.sample().catch(()=>{});let re=()=>C({type:"hello",protocol:Wy,version:Be,hostname:kf(),platform:Dx(),folders:o.folders,clis:n.map(w=>({...w,...a[w.id]&&{limits:a[w.id]},..._b(o,w.id,a)})),features:["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","models","git-token","git-tokens","steer","steer-claude","ssh","cli-accounts","shared-folder","coordinator",...I==="service"?["update"]:[],...Q()?["stats"]:[]],settings:Oi(o),updates:I,...k.state()&&{update:k.state()},...i&&{browser:i},running:l.runningIds(),interrupted:d,...Q()&&P.latest&&{stats:P.latest}});l.setSender(C);let Ne=async()=>{o=await me().catch(()=>o),re()};IT(Nt(),{interval:2e3},Ne);let O=setInterval(()=>{if(f?.readyState===WebSocket.OPEN){if(!Q())return C({type:"ping"});P.sample().then(w=>C({type:"ping",stats:w}),()=>C({type:"ping"}))}},25e3),We=()=>{Promise.all(n.map(async w=>{let j=await ar[w.id].models?.().catch(()=>{}),U=JSON.stringify(j)!==JSON.stringify(w.models);return j&&(w.models=j),U&&!!j})).then(w=>w.some(Boolean)&&re())};We(),u();let Et=()=>{ki().then(w=>{if(CT(n,w))return;let j=new Map(n.map(U=>[U.id,U]));n.splice(0,n.length,...w.map(U=>j.get(U.id)?.version===U.version?j.get(U.id):U)),t(`CLIs found: ${n.map(U=>U.id).join(", ")||"none"}`),re(),We(),u()},()=>{})},bt=setInterval(u,600*1e3),Ri=setInterval(We,360*60*1e3),dr=setInterval(Et,TT);bt.unref?.(),dr.unref?.();let gn=()=>{$s(w=>l.inUse(w)).then(w=>w.forEach(j=>t(`Removed the finished worktree ${j.path} (${j.branch})`))).catch(()=>{})};gn();let pr=setInterval(gn,360*60*1e3);pr.unref?.();let mr=()=>{I==="service"&&o.autoUpdate&&k.checkNewest().catch(()=>{})},Ut=setTimeout(mr,600*1e3);Ut.unref?.();let fr=setInterval(mr,PT);fr.unref?.();let et=()=>{m=!0,clearInterval(O),clearInterval(pr),clearInterval(bt),clearInterval(Ri),clearInterval(dr),clearInterval(fr),clearTimeout(Ut),clearTimeout(A),zT(Nt(),Ne),X$(l.stopAll()),f?.close(1e3),r({state:"stopped",reason:p}),y(p)},Rs=async w=>{let{requestId:j}=w;if(w.type==="dirs.list")return C({type:"dirs",requestId:j,...await B$(w.path)});if(w.type==="task.steer")return C({type:"task.steered",requestId:j,taken:await l.steer(w.taskId,w.text)});if(w.type==="file.read")return C({type:"file",requestId:j,...await F$(o,w)});if(w.type==="ssh.keygen"){let U=await sx({projectId:w.projectId,alias:w.alias},w.comment,w.existing);return t(`${w.existing?"Using":"Made"} an SSH key for ${w.alias} (${U.fingerprint}, from Myrel)`),C({type:"ssh.key",requestId:j,...U})}if(w.type==="ssh.keys")return C({type:"ssh.keylist",requestId:j,keys:await cx()});if(w.type==="ssh.hostkeys")return C({type:"ssh.hostkeylist",requestId:j,keys:await ux(w.host,w.port)});if(w.type==="ssh.test")return C({type:"ssh.result",requestId:j,...await dx(w.target)});if(w.type==="ssh.run")return t(`SSH ${w.target.alias}: ${w.command.split(`
|
|
359
|
+
`)[0].slice(0,80)}`),C({type:"ssh.result",requestId:j,...await gf(w.target,w.command)});if(w.type==="ssh.forget")return await ff({projectId:w.projectId,alias:w.alias}),t(`Forgot the SSH key for ${w.alias} (from Myrel)`),C({type:"ssh.result",requestId:j,exitCode:0,stdout:"",stderr:"",truncated:!1,ms:0});if(w.type==="runner.update"){if(I!=="service")throw new Error(I==="app"?"This runner came with the Myrel desktop app; it updates with the app.":"This runner was started in a terminal, so it cannot restart itself. Start it again with `npx myrel-runner@latest start`.");return t(`Updating to myrel-runner ${w.version} (from Myrel)${w.now?"":" once the running tasks finish"}`),C({type:"update.accepted",requestId:j,update:k.request(w.version,w.now)})}if(o=await me(),w.type==="settings.set")return Sx(o,w.settings),await Oe(o),t(`Settings changed from Myrel: ${Object.entries(w.settings).map(([U,ct])=>`${U} ${ct}`).join(", ")}`),C({type:"settings",requestId:j,settings:Oi(o)});if(w.type==="folder.share"){let U=await W$(w.path);ts(o,U)&&t(`Shared ${U} (from Myrel)`)}else ns(o,w.path)&&t(`Stopped sharing ${w.path} (from Myrel)`);await Oe(o),C({type:"folders",requestId:j,folders:o.folders})},V=()=>{if(m)return;let w=`${o.server.replace(/^http/,"ws")}/api/runner/connect`;r({state:"connecting"});let j=new WebSocket(w,{headers:{authorization:`Bearer ${o.token}`}});f=j;let U=!1;j.onopen=()=>{U=!0,g=0,E(),re()},j.onmessage=ce=>{let De=JSON.parse(String(ce.data)),gr=Yy.safeParse(De);if(!gr.success){let hn=De;if(hn?.type==="task.start"&&typeof hn.taskId=="string"){let Sf=gr.error.issues[0],If=`${Sf?.path.join(".")||"frame"}: ${Sf?.message??"invalid"}`;t(`\u2717 could not read task ${hn.taskId} (${If})`),C({type:"task.done",taskId:hn.taskId,ok:!1,result:`myrel-runner ${Be} could not read this task (${If}). Update myrel-runner.`})}return}let Se=gr.data;Se.type==="welcome"&&(t(`\u25CF Connected to ${o.server} as "${Se.name}"`),r({state:"online",name:Se.name}),k.confirmed()),Se.type==="task.start"&&(r({state:"task",taskId:Se.taskId,event:"started"}),l.start(Se)),Se.type==="task.cancel"&&l.cancel(Se.taskId),Se.type==="task.github"&&l.renewGithub(Se.taskId,Se.github),"requestId"in Se&&Rs(Se).catch(hn=>C({type:"request.failed",requestId:Se.requestId,message:OT(hn)}))};let ct=!1,ae=async ce=>{if(ct||f!==j||m)return;if(ct=!0,!U&&await Ni(o)==="invalid")return t(AT),e.onRevoked?.(),p="revoked",et();if(ce.code===4401)return t("This computer was removed from Myrel. Pair it again with `myrel-runner pair`."),e.onRevoked?.(),p="revoked",et();if(ce.code===4e3)return t("myrel-runner was started somewhere else with this computer's login, so this one stops."),p="replaced",et();if(ce.code===4400)return t(`The server refused this runner: ${ce.reason}`),k.confirming&&(await k.rollback(`the server refused it: ${ce.reason}`),m)?void 0:(p="refused",et());let De=Math.min(3e4,1e3*2**g++);t(`\u25CB Disconnected${ce.reason?` (${ce.reason})`:""}. Reconnecting in ${Math.round(De/1e3)}s\u2026`),r({state:"offline",reason:ce.reason||`code ${ce.code}`,retryInMs:De}),setTimeout(V,De)};j.onclose=ce=>{ae(ce)},j.onerror=()=>{U||ae({code:1006,reason:""})}};return V(),t(`Sharing ${o.folders.length} folder(s); CLIs found: ${n.map(w=>w.id).join(", ")||"none"}`),ln().then(w=>{let j=Si(w);j&&t(j)}),{stop:et,done:_}}function OT(e){return(e instanceof Error?e.message:String(e)).slice(0,500)}var DT=`myrel-runner ${Be}
|
|
360
360
|
Connects this computer to Myrel, so projects can work in folders you share
|
|
361
361
|
using your own Claude Code, Codex, Antigravity CLI, OpenCode, Hermes Agent, Cursor CLI, Muse Code, Kimi Code or Qwen Code. Your CLI logins never leave
|
|
362
362
|
this computer.
|
|
@@ -404,7 +404,7 @@ threads work in its folder itself (its Folders tab in Myrel), one at a time.
|
|
|
404
404
|
|
|
405
405
|
Environment: MYREL_SERVER and MYREL_RUNNER_TOKEN override the saved pairing;
|
|
406
406
|
MYREL_RUNNER_HOME moves the config folder (default ~/.myrel-runner).
|
|
407
|
-
`;async function
|
|
407
|
+
`;async function RT(e){if(e[0]==="ssh-shim"){process.exitCode=await T$(e[1],e.slice(2));return}let{values:t,positionals:r}=NT({args:e,allowPositionals:!0,options:{server:{type:"string"},name:{type:"string"},access:{type:"string"},json:{type:"boolean"},force:{type:"boolean"},now:{type:"boolean"},dir:{type:"string"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}}}),[o,n]=r;if(t.version)return console.log(Be);if(t.help||!o)return console.log(DT);switch(o){case"mcp-bridge":return Tb({input:process.stdin,write:i=>process.stdout.write(`${i}
|
|
408
408
|
`),run:await Cb(),version:Be});case"git-credential":return f$(n,r[2],process.stdin,i=>process.stdout.write(i));case"pair":{let i=t.server??(await me()).server;if(!n||!i)throw new Error("Usage: myrel-runner pair <code> --server <url>");let a=await Rx({server:i,code:n,name:t.name});console.log(`Paired with ${a.server}.`),console.log("Next: `myrel-runner service install` to keep it running in the background, then add folders in Myrel > Devices.");return}case"share":{let i=await me(),a=ts(i,n??process.cwd());await Oe(i),console.log(a?`Shared ${i.folders.at(-1).path}`:"That folder is already shared.");return}case"unshare":{if(!n)throw new Error("Usage: myrel-runner unshare <folder>");let i=await me(),a=ns(i,n);await Oe(i),console.log(a?"Stopped sharing it.":"That folder was not shared.");return}case"status":{let i=await me(),a=[],[c,u]=await Promise.all([ki(a),Ni(i)]);if(t.json){let{token:p,...f}=i;return console.log(JSON.stringify({...f,paired:!!(p&&i.server),pairing:u,clis:c}))}let l={ok:"",invalid:" (not paired any more: run myrel-runner pair)",unknown:" (could not reach it)"};console.log(`Server: ${i.server?`${i.server}${l[u]}`:"(not paired)"}`),console.log(`Config: ${Nt()}`),console.log(`Access: ${i.access}${i.autoUpdate?" \xB7 auto-update on":""}`),console.log(`Folders: ${i.folders.map(p=>`
|
|
409
409
|
${p.path}`).join("")||"none"}`),console.log(`CLIs: ${c.map(p=>`
|
|
410
410
|
${Xa[p.id]} ${p.version??""}`).join("")||"none found"}`),i.claudeAccounts?.length&&console.log(`Claude Code accounts:
|
|
@@ -415,10 +415,10 @@ MYREL_RUNNER_HOME moves the config folder (default ~/.myrel-runner).
|
|
|
415
415
|
${a}`),i.blocked.length&&console.log(`
|
|
416
416
|
\`myrel-runner sandbox fix\` installs this profile with sudo:
|
|
417
417
|
|
|
418
|
-
${Gm(i.binaries)}`);return}case"start":{t.access&&await Ns(t.access);let i=await Ux(t.json?{log:()=>{},onStatus:a=>console.log(JSON.stringify(a))}:{});for(let a of["SIGINT","SIGTERM"])process.once(a,()=>i.stop());process.exit(await i.done==="restart"?Ex:0)}case"service":{if(n==="install"){let i=await me();if(!i.server||!i.token)throw new Error("Pair this computer first: myrel-runner pair <code> --server <url>");if(await Ni(i)==="invalid")throw new Error(`${i.server} does not know this computer any more. Get a new code in Myrel > Devices and run \`myrel-runner pair <code> --server ${i.server}\` first.`);t.access&&await Ns(t.access),Ds(await yf(Mx(import.meta.url)),t.json);return}if(n==="uninstall")return Ds(await yx(),t.json);if(n==="status"||!n)return Ds(await Ti(),t.json);throw new Error("Usage: myrel-runner service install|uninstall|status")}case"update":{let i=process.env.MYREL_RUNNER_UPDATING,a=i?null:await js();if(!i&&!a&&console.log("Could not reach npm to look for a newer version."),a&&Ci(a,Be)){console.log(`Updating myrel-runner ${Be} to ${a}\u2026`),process.exitCode=await xx(a,e);return}if(!i&&a&&console.log(`myrel-runner ${Be} is the newest version.`),!(await Ti().catch(()=>null))?.installed){console.log("The background runner is not installed, so there is nothing to restart. Install it with `myrel-runner service install`.");return}t.access&&await Ns(t.access),t.now||await
|
|
418
|
+
${Gm(i.binaries)}`);return}case"start":{t.access&&await Ns(t.access);let i=await Ux(t.json?{log:()=>{},onStatus:a=>console.log(JSON.stringify(a))}:{});for(let a of["SIGINT","SIGTERM"])process.once(a,()=>i.stop());process.exit(await i.done==="restart"?Ex:0)}case"service":{if(n==="install"){let i=await me();if(!i.server||!i.token)throw new Error("Pair this computer first: myrel-runner pair <code> --server <url>");if(await Ni(i)==="invalid")throw new Error(`${i.server} does not know this computer any more. Get a new code in Myrel > Devices and run \`myrel-runner pair <code> --server ${i.server}\` first.`);t.access&&await Ns(t.access),Ds(await yf(Mx(import.meta.url)),t.json);return}if(n==="uninstall")return Ds(await yx(),t.json);if(n==="status"||!n)return Ds(await Ti(),t.json);throw new Error("Usage: myrel-runner service install|uninstall|status")}case"update":{let i=process.env.MYREL_RUNNER_UPDATING,a=i?null:await js();if(!i&&!a&&console.log("Could not reach npm to look for a newer version."),a&&Ci(a,Be)){console.log(`Updating myrel-runner ${Be} to ${a}\u2026`),process.exitCode=await xx(a,e);return}if(!i&&a&&console.log(`myrel-runner ${Be} is the newest version.`),!(await Ti().catch(()=>null))?.installed){console.log("The background runner is not installed, so there is nothing to restart. Install it with `myrel-runner service install`.");return}t.access&&await Ns(t.access),t.now||await MT();let c=await yf(Mx(import.meta.url));console.log(`Restarted the background runner on ${Be}.`),Ds(c,t.json);return}case"worktrees":{if(n==="on"||n==="off"){let u=await me();u.worktrees=n==="on",await Oe(u),console.log(n==="on"?"Each thread now works in its own git worktree.":"Threads now work in the shared folder itself. Two threads at once can change the same files.");return}if(n==="prune"){let u=await $s();console.log(u.length?u.map(l=>`Removed ${l.path} (${l.branch})`).join(`
|
|
419
419
|
`):"Nothing to clean up.");return}let i=await vt();if(n==="remove"){let u=r[2],l=i.find(d=>d.path===u||d.branch===u);if(!l)throw new Error("Usage: myrel-runner worktrees remove <path or branch> [--force] (see myrel-runner worktrees)");await Qm(l,{force:t.force}),console.log(`Removed ${l.path}. The branch ${l.branch} is kept unless it was merged.`);return}if(n)throw new Error("Usage: myrel-runner worktrees [on|off|prune|remove <path>]");let a=await Promise.all(i.map(u=>bs(u).catch(()=>null)));if(t.json)return console.log(JSON.stringify(i.map((u,l)=>({...u,...a[l]}))));let c=(await me()).worktrees!==!1;console.log(`Worktrees: ${c?"on":"off (threads share the folder)"}`);for(let[u,l]of i.entries()){let d=a[u],p=[d?.missing&&"missing",d?.dirty&&"uncommitted changes",d?.merged&&"merged"].filter(Boolean).join(", ");console.log(`
|
|
420
420
|
${l.branch}${p?` (${p})`:""}
|
|
421
421
|
${l.path}
|
|
422
|
-
from ${l.repo}, last used ${new Date(l.lastUsed).toLocaleString()}`)}i.length||console.log("No worktrees yet.");return}case"settings":{let i=await me(),a=r[2];if(n==="access"&&a)await Ns(a);else if((n==="auto-update"||n==="remote"||n==="stats")&&(a==="on"||a==="off"))i[n==="remote"?"remoteSettings":n==="stats"?"stats":"autoUpdate"]=a==="on",await Oe(i);else if(n)throw new Error("Usage: myrel-runner settings [access read|edit|auto|full | auto-update on|off | remote on|off | stats on|off]");let c=await me(),u=Oi(c),l=c.stats!==!1;if(t.json)return console.log(JSON.stringify({...u,stats:l}));console.log(`Access: ${u.access}`),console.log(`Worktrees: ${u.worktrees?"on":"off"}`),console.log(`Auto-update: ${u.autoUpdate?"on (background runner only)":"off"}`),console.log(`From Myrel: ${u.remote?"can be changed in Myrel > Devices":"off: only here"}`),console.log(`Usage: ${l?"CPU, memory and disk are shown in Myrel > Devices":"off: not sent to Myrel"}`);return}case"claude":return
|
|
422
|
+
from ${l.repo}, last used ${new Date(l.lastUsed).toLocaleString()}`)}i.length||console.log("No worktrees yet.");return}case"settings":{let i=await me(),a=r[2];if(n==="access"&&a)await Ns(a);else if((n==="auto-update"||n==="remote"||n==="stats")&&(a==="on"||a==="off"))i[n==="remote"?"remoteSettings":n==="stats"?"stats":"autoUpdate"]=a==="on",await Oe(i);else if(n)throw new Error("Usage: myrel-runner settings [access read|edit|auto|full | auto-update on|off | remote on|off | stats on|off]");let c=await me(),u=Oi(c),l=c.stats!==!1;if(t.json)return console.log(JSON.stringify({...u,stats:l}));console.log(`Access: ${u.access}`),console.log(`Worktrees: ${u.worktrees?"on":"off"}`),console.log(`Auto-update: ${u.autoUpdate?"on (background runner only)":"off"}`),console.log(`From Myrel: ${u.remote?"can be changed in Myrel > Devices":"off: only here"}`),console.log(`Usage: ${l?"CPU, memory and disk are shown in Myrel > Devices":"off: not sent to Myrel"}`);return}case"claude":return ET(r.slice(1),t);case"logout":{let i=await me();delete i.token,delete i.runnerId,await Oe(i),console.log("Forgot this computer's pairing. Remove it in Myrel > Devices too.");return}default:throw new Error(`Unknown command "${o}". Run myrel-runner --help.`)}}var Di="Usage: myrel-runner claude [list | add <name> [--dir <folder>] | login <name> | rename <name|default> <new name> | remove <name>]";async function ET([e="list",t,r],o){let n=await me();switch(e){case"list":{let a=[{id:null,name:n.claudeDefaultName??null,dir:Tm()},...n.claudeAccounts??[]],c=await Promise.all(a.map(u=>is(u.id?u.dir:void 0)));if(o.json)return console.log(JSON.stringify(a.map((u,l)=>({...u,auth:c[l]}))));for(let[u,l]of a.entries()){let d=c[u],p=d?d.loggedIn?`signed in${d.subscriptionType?` (${d.subscriptionType})`:""}`:"not signed in":"could not ask Claude Code";console.log(`${l.name??"Claude Code's own login"}${l.id?` [${l.id}]`:" (default)"}: ${p}
|
|
423
423
|
${l.dir}`)}n.claudeAccounts?.length||console.log(`
|
|
424
|
-
Add another account with: myrel-runner claude add "Work"`);return}case"add":{if(!t)throw new Error(Di);let i=await bb(n,t,o.dir);if(!(await is(i.dir))?.loggedIn&&(console.log(`Signing in to Claude Code for "${i.name}". Use the account you want threads to run with.`),await Om(i.dir),!(await is(i.dir))?.loggedIn))throw new Error(`Not added: Claude Code did not finish signing in. Run \`myrel-runner claude add "${i.name}"\` again.`);await Oe(n),console.log(`Added "${i.name}" (${i.dir}). Threads in Myrel can now choose Claude Code \xB7 ${i.name}.`),n.claudeDefaultName||console.log('Name your own login too, e.g.: myrel-runner claude rename default "Personal"');return}case"login":{let i=t?rs(n,t):void 0;if(!i)throw new Error(t?`No Claude Code account "${t}". See myrel-runner claude list.`:Di);process.exitCode=await Om(i.dir);return}case"rename":{if(!t||!r)throw new Error(Di);if(!xb(n,t,r))throw new Error(`No Claude Code account "${t}". See myrel-runner claude list.`);await Oe(n),console.log(`Renamed it to "${r.trim()}".`);return}case"remove":{let i=t?$b(n,t):void 0;if(!i)throw new Error(t?`No Claude Code account "${t}". See myrel-runner claude list.`:Di);await Oe(n),console.log(`Removed "${i.name}": threads that chose it run with Claude Code's own login from their next turn.`),console.log(`Its login is still in ${i.dir}; delete that folder to remove it from this computer too.`);return}default:throw new Error(Di)}}var
|
|
424
|
+
Add another account with: myrel-runner claude add "Work"`);return}case"add":{if(!t)throw new Error(Di);let i=await bb(n,t,o.dir);if(!(await is(i.dir))?.loggedIn&&(console.log(`Signing in to Claude Code for "${i.name}". Use the account you want threads to run with.`),await Om(i.dir),!(await is(i.dir))?.loggedIn))throw new Error(`Not added: Claude Code did not finish signing in. Run \`myrel-runner claude add "${i.name}"\` again.`);await Oe(n),console.log(`Added "${i.name}" (${i.dir}). Threads in Myrel can now choose Claude Code \xB7 ${i.name}.`),n.claudeDefaultName||console.log('Name your own login too, e.g.: myrel-runner claude rename default "Personal"');return}case"login":{let i=t?rs(n,t):void 0;if(!i)throw new Error(t?`No Claude Code account "${t}". See myrel-runner claude list.`:Di);process.exitCode=await Om(i.dir);return}case"rename":{if(!t||!r)throw new Error(Di);if(!xb(n,t,r))throw new Error(`No Claude Code account "${t}". See myrel-runner claude list.`);await Oe(n),console.log(`Renamed it to "${r.trim()}".`);return}case"remove":{let i=t?$b(n,t):void 0;if(!i)throw new Error(t?`No Claude Code account "${t}". See myrel-runner claude list.`:Di);await Oe(n),console.log(`Removed "${i.name}": threads that chose it run with Claude Code's own login from their next turn.`),console.log(`Its login is still in ${i.dir}; delete that folder to remove it from this computer too.`);return}default:throw new Error(Di)}}var UT=600*1e3;async function MT(){let e=Date.now()+UT,t=0;for(let r=sf();r.length;r=sf()){if(Date.now()>=e){console.log(`Restarting now; Myrel continues the ${r.length} task(s) still running after the restart.`);return}r.length!==t&&(t=r.length,console.log(`${t} task(s) running; restarting once they finish (at most 10 minutes; --now to restart right away)\u2026`)),await new Promise(o=>setTimeout(o,5e3))}}async function Ns(e){if(!["read","edit","auto","full"].includes(e))throw new Error("--access must be read, edit, auto or full");let t=await me();t.access=e,await Oe(t)}function Ds(e,t){if(t)return console.log(JSON.stringify(e));if(!e.installed)return console.log("The background runner is not installed. Install it with `myrel-runner service install`.");let r=e.running===null?"installed":e.running?"running":"installed, not running";console.log(`Background runner: ${r}. It starts at every login.`),console.log(`Service: ${e.file}`),console.log(`Logs: ${e.log}`)}RT(process.argv.slice(2)).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|