@fibteq/myrel-runner 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Q$=Object.defineProperty;var rt=(e,t)=>{for(var r in t)Q$(e,r,{get:t[r],enumerable:!0})};import{fileURLToPath as Y$}from"node:url";import{parseArgs as aA}from"node:util";var e_={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"};function me(e){return new RegExp(`^${e_[e]}_[0-9A-HJKMNP-TV-Z]{26}$`)}var c={};rt(c,{$brand:()=>Es,$input:()=>ul,$output:()=>cl,INVALID:()=>be,NEVER:()=>Cs,TimePrecision:()=>_l,ZodAny:()=>cp,ZodArray:()=>pp,ZodBase64:()=>ka,ZodBase64URL:()=>wa,ZodBigInt:()=>Gn,ZodBigIntFormat:()=>za,ZodBoolean:()=>Wn,ZodCIDRv4:()=>_a,ZodCIDRv6:()=>xa,ZodCUID:()=>ma,ZodCUID2:()=>ga,ZodCatch:()=>Np,ZodCodec:()=>ni,ZodCompileAsyncError:()=>Ze,ZodCompileUnsupportedError:()=>L,ZodCreditCard:()=>ep,ZodCustom:()=>ri,ZodCustomStringFormat:()=>Gt,ZodDate:()=>Hr,ZodDefault:()=>zp,ZodDiscriminatedUnion:()=>mp,ZodE164:()=>Sa,ZodEmail:()=>la,ZodEmoji:()=>pa,ZodEnum:()=>Jn,ZodError:()=>bS,ZodExactOptional:()=>Ta,ZodFile:()=>kp,ZodFirstPartyTypeKind:()=>Wp,ZodFunction:()=>Vp,ZodGUID:()=>da,ZodIBAN:()=>tp,ZodIPv4:()=>ba,ZodIPv6:()=>$a,ZodISODate:()=>St,ZodISODateTime:()=>wt,ZodISODuration:()=>zt,ZodISOTime:()=>It,ZodInstanceOf:()=>Bp,ZodIntersection:()=>gp,ZodIssueCode:()=>xS,ZodJWT:()=>Ia,ZodKSUID:()=>ya,ZodLazy:()=>Lp,ZodLiteral:()=>xp,ZodMAC:()=>Qd,ZodMap:()=>$p,ZodNaN:()=>Up,ZodNanoID:()=>fa,ZodNever:()=>lp,ZodNonOptional:()=>Oa,ZodNull:()=>ap,ZodNullable:()=>Ip,ZodNumber:()=>Bn,ZodNumberFormat:()=>qt,ZodObject:()=>Yr,ZodOptional:()=>ei,ZodPipe:()=>ti,ZodPrefault:()=>jp,ZodPreprocess:()=>Cp,ZodPromise:()=>Fp,ZodReadonly:()=>Ep,ZodRealError:()=>ze,ZodRecord:()=>Vn,ZodSet:()=>_p,ZodString:()=>Kn,ZodStringFormat:()=>G,ZodSuccess:()=>Op,ZodSymbol:()=>ip,ZodTemplateLiteral:()=>Mp,ZodTransform:()=>wp,ZodTuple:()=>vp,ZodType:()=>E,ZodULID:()=>ha,ZodURL:()=>qr,ZodUUID:()=>Ge,ZodUndefined:()=>op,ZodUnion:()=>Qr,ZodUnknown:()=>up,ZodVoid:()=>dp,ZodXID:()=>va,ZodXor:()=>fp,_ZodString:()=>ua,_default:()=>Pp,_function:()=>Zv,any:()=>yv,array:()=>Xr,base64:()=>Yh,base64url:()=>Qh,bigint:()=>fv,boolean:()=>rp,catch:()=>Dp,check:()=>Fv,cidrv4:()=>Hh,cidrv6:()=>Xh,clone:()=>V,codec:()=>Ev,coerce:()=>qp,compile:()=>fl,config:()=>ne,core:()=>ct,creditCard:()=>tv,cuid:()=>Fh,cuid2:()=>Vh,currencyCode:()=>sv,custom:()=>Vv,date:()=>$v,decode:()=>Bd,decodeAsync:()=>Gd,deepPartial:()=>ny,describe:()=>Jv,discriminatedUnion:()=>Iv,e164:()=>ev,email:()=>Oh,emoji:()=>Lh,encode:()=>Kd,encodeAsync:()=>Wd,endsWith:()=>On,enum:()=>ja,exactOptional:()=>Sp,file:()=>Nv,flattenError:()=>yr,float32:()=>uv,float64:()=>lv,formatError:()=>br,fromJSONSchema:()=>ey,function:()=>Zv,getDiscriminatedOption:()=>Cu,getErrorMap:()=>wS,globalRegistry:()=>de,gt:()=>Be,gte:()=>Oe,guid:()=>Nh,hash:()=>cv,hex:()=>av,hostname:()=>ov,httpUrl:()=>Mh,iban:()=>nv,includes:()=>An,input:()=>iy,instanceof:()=>Bv,int:()=>sa,int32:()=>dv,int64:()=>mv,intersection:()=>hp,invertCodec:()=>Rv,ipv4:()=>Wh,ipv6:()=>qh,iso:()=>ii,json:()=>Gv,jwt:()=>rv,keyof:()=>_v,ksuid:()=>Bh,lazy:()=>Zp,length:()=>Vt,literal:()=>Ov,locales:()=>Mr,looseObject:()=>wv,looseRecord:()=>Pv,lowercase:()=>Pn,lt:()=>Ke,lte:()=>Te,mac:()=>Gh,map:()=>jv,maxLength:()=>Ft,maxSize:()=>$t,memoizer:()=>Er,meta:()=>Kv,mime:()=>Dn,minLength:()=>st,minSize:()=>We,multipleOf:()=>bt,nan:()=>Cv,nanoid:()=>Zh,nativeEnum:()=>Tv,negative:()=>Ho,never:()=>Pa,nonnegative:()=>Yo,nonoptional:()=>Tp,nonpositive:()=>Xo,normalize:()=>Un,null:()=>sp,nullable:()=>Gr,nullish:()=>Dv,number:()=>np,object:()=>xv,optional:()=>Bt,output:()=>oy,overwrite:()=>Fe,parse:()=>Zd,parseAsync:()=>Fd,partialRecord:()=>zv,pipe:()=>ca,positive:()=>qo,prefault:()=>Ap,preprocess:()=>qv,prettifyError:()=>Fs,promise:()=>Lv,properties:()=>Nn,property:()=>Qo,readonly:()=>Rp,record:()=>bp,refine:()=>Jp,regex:()=>zn,regexes:()=>Ee,registry:()=>wo,safeDecode:()=>Hd,safeDecodeAsync:()=>Yd,safeEncode:()=>qd,safeEncodeAsync:()=>Xd,safeParse:()=>Vd,safeParseAsync:()=>Jd,set:()=>Av,setErrorMap:()=>kS,size:()=>Zt,slugify:()=>Mn,startsWith:()=>Tn,strictObject:()=>kv,string:()=>Wr,stringFormat:()=>iv,stringbool:()=>Wv,success:()=>Uv,superRefine:()=>Kp,symbol:()=>hv,templateLiteral:()=>Mv,toJSONSchema:()=>ra,toLowerCase:()=>En,toUpperCase:()=>Rn,toZod:()=>cr,transform:()=>Aa,treeifyError:()=>Zs,trim:()=>Cn,tuple:()=>yp,uint32:()=>pv,uint64:()=>gv,ulid:()=>Jh,undefined:()=>vv,union:()=>qn,unknown:()=>Kt,uppercase:()=>jn,url:()=>Rh,util:()=>b,uuid:()=>Dh,uuidv4:()=>Uh,uuidv6:()=>Ch,uuidv7:()=>Eh,validate:()=>$r,validateAsync:()=>_r,void:()=>bv,withParser:()=>So,xid:()=>Kh,xor:()=>Sv});var ct={};rt(ct,{$ZodAny:()=>zu,$ZodArray:()=>Nu,$ZodAsyncError:()=>Se,$ZodBase64:()=>gu,$ZodBase64URL:()=>hu,$ZodBigInt:()=>uo,$ZodBigIntFormat:()=>ku,$ZodBoolean:()=>Tr,$ZodCIDRv4:()=>fu,$ZodCIDRv6:()=>mu,$ZodCUID:()=>tu,$ZodCUID2:()=>nu,$ZodCatch:()=>Yu,$ZodCheck:()=>q,$ZodCheckBigIntFormat:()=>Pc,$ZodCheckEndsWith:()=>Lc,$ZodCheckGreaterThan:()=>Wi,$ZodCheckIncludes:()=>Rc,$ZodCheckLengthEquals:()=>Dc,$ZodCheckLessThan:()=>Bi,$ZodCheckLowerCase:()=>Cc,$ZodCheckMaxLength:()=>Oc,$ZodCheckMaxSize:()=>jc,$ZodCheckMimeType:()=>Vc,$ZodCheckMinLength:()=>Nc,$ZodCheckMinSize:()=>Ac,$ZodCheckMultipleOf:()=>Ic,$ZodCheckNumberFormat:()=>zc,$ZodCheckOverwrite:()=>Jc,$ZodCheckProperties:()=>Fc,$ZodCheckProperty:()=>Zc,$ZodCheckRegex:()=>Uc,$ZodCheckSizeEquals:()=>Tc,$ZodCheckStartsWith:()=>Mc,$ZodCheckStringFormat:()=>xn,$ZodCheckUpperCase:()=>Ec,$ZodCodec:()=>Nr,$ZodCreditCard:()=>yu,$ZodCustom:()=>ol,$ZodCustomStringFormat:()=>_u,$ZodCyclicError:()=>vo,$ZodDate:()=>Tu,$ZodDefault:()=>Gu,$ZodDiscriminatedUnion:()=>Eu,$ZodE164:()=>vu,$ZodEmail:()=>qc,$ZodEmoji:()=>Qc,$ZodEncodeError:()=>vt,$ZodEnum:()=>Fu,$ZodError:()=>Ls,$ZodExactOptional:()=>Bu,$ZodFile:()=>Ju,$ZodFunction:()=>rl,$ZodGUID:()=>Wc,$ZodIBAN:()=>bu,$ZodIPv4:()=>lu,$ZodIPv6:()=>du,$ZodISODate:()=>su,$ZodISODateTime:()=>au,$ZodISODuration:()=>uu,$ZodISOTime:()=>cu,$ZodIntersection:()=>Ru,$ZodJWT:()=>$u,$ZodKSUID:()=>ou,$ZodLazy:()=>Dr,$ZodLiteral:()=>Vu,$ZodMAC:()=>pu,$ZodMap:()=>Lu,$ZodNaN:()=>Qu,$ZodNanoID:()=>eu,$ZodNever:()=>ju,$ZodNonOptional:()=>Hu,$ZodNull:()=>Iu,$ZodNullable:()=>Wu,$ZodNumber:()=>co,$ZodNumberFormat:()=>xu,$ZodObject:()=>Fm,$ZodObjectJIT:()=>Du,$ZodOptional:()=>po,$ZodPipe:()=>fo,$ZodPrefault:()=>qu,$ZodPreprocess:()=>el,$ZodPromise:()=>il,$ZodReadonly:()=>tl,$ZodRealError:()=>Ie,$ZodRecord:()=>Mu,$ZodRegistry:()=>ko,$ZodSet:()=>Zu,$ZodString:()=>Et,$ZodStringFormat:()=>J,$ZodSuccess:()=>Xu,$ZodSymbol:()=>wu,$ZodTemplateLiteral:()=>nl,$ZodTransform:()=>Ku,$ZodTuple:()=>lo,$ZodType:()=>U,$ZodULID:()=>ru,$ZodURL:()=>Yc,$ZodUUID:()=>Gc,$ZodUndefined:()=>Su,$ZodUnion:()=>Or,$ZodUnknown:()=>Pu,$ZodVoid:()=>Au,$ZodXID:()=>iu,$ZodXor:()=>Uu,$brand:()=>Es,$constructor:()=>h,$input:()=>ul,$output:()=>cl,Doc:()=>Ct,INVALID:()=>be,JSONSchema:()=>jh,JSONSchemaGenerator:()=>ia,NEVER:()=>Cs,TimePrecision:()=>_l,URL_BAD_FORMAT:()=>Hc,URL_UNPARSEABLE:()=>Ir,ZodCompileAsyncError:()=>Ze,ZodCompileUnsupportedError:()=>L,_any:()=>Rl,_array:()=>Kl,_base64:()=>Ko,_base64url:()=>Bo,_bigint:()=>Tl,_boolean:()=>jl,_catch:()=>sS,_check:()=>fh,_cidrv4:()=>Vo,_cidrv6:()=>Jo,_coercedBigint:()=>Ol,_coercedBoolean:()=>Al,_coercedDate:()=>Vl,_coercedNumber:()=>kl,_coercedString:()=>vl,_creditCard:()=>bl,_cuid:()=>Co,_cuid2:()=>Eo,_custom:()=>Wl,_date:()=>Fl,_decode:()=>Ui,_decodeAsync:()=>Ei,_default:()=>iS,_discriminatedUnion:()=>Bw,_e164:()=>Wo,_email:()=>Po,_emoji:()=>Do,_encode:()=>Di,_encodeAsync:()=>Ci,_endsWith:()=>On,_enum:()=>Yw,_file:()=>Bl,_float32:()=>Sl,_float64:()=>Il,_gt:()=>Be,_gte:()=>Oe,_guid:()=>jo,_iban:()=>$l,_includes:()=>An,_int:()=>wl,_int32:()=>zl,_int64:()=>Nl,_intersection:()=>Ww,_ipv4:()=>Zo,_ipv6:()=>Fo,_isoDate:()=>Fr,_isoDateTime:()=>Zr,_isoDuration:()=>Jr,_isoTime:()=>Vr,_jwt:()=>Go,_ksuid:()=>Lo,_lazy:()=>dS,_length:()=>Vt,_literal:()=>eS,_lowercase:()=>Pn,_lt:()=>Ke,_lte:()=>Te,_mac:()=>yl,_map:()=>Hw,_max:()=>Te,_maxLength:()=>Ft,_maxSize:()=>$t,_mime:()=>Dn,_min:()=>Oe,_minLength:()=>st,_minSize:()=>We,_multipleOf:()=>bt,_nan:()=>Jl,_nanoid:()=>Uo,_nativeEnum:()=>Qw,_negative:()=>Ho,_never:()=>Ll,_nonnegative:()=>Yo,_nonoptional:()=>oS,_nonpositive:()=>Xo,_normalize:()=>Un,_null:()=>El,_nullable:()=>rS,_number:()=>xl,_optional:()=>nS,_overwrite:()=>Fe,_parse:()=>yn,_parseAsync:()=>bn,_pipe:()=>cS,_positive:()=>qo,_promise:()=>pS,_properties:()=>Nn,_property:()=>Qo,_readonly:()=>uS,_record:()=>qw,_refine:()=>Gl,_regex:()=>zn,_safeDecode:()=>Mi,_safeDecodeAsync:()=>Zi,_safeEncode:()=>Ri,_safeEncodeAsync:()=>Li,_safeParse:()=>$n,_safeParseAsync:()=>_n,_set:()=>Xw,_size:()=>Zt,_slugify:()=>Mn,_startsWith:()=>Tn,_string:()=>hl,_stringFormat:()=>Jt,_stringbool:()=>Yl,_success:()=>aS,_superRefine:()=>ql,_symbol:()=>Ul,_templateLiteral:()=>lS,_toLowerCase:()=>En,_toUpperCase:()=>Rn,_transform:()=>tS,_trim:()=>Cn,_tuple:()=>Gw,_uint32:()=>Pl,_uint64:()=>Dl,_ulid:()=>Ro,_undefined:()=>Cl,_union:()=>Jw,_unknown:()=>Ml,_uppercase:()=>jn,_url:()=>Lr,_uuid:()=>Ao,_uuidv4:()=>To,_uuidv6:()=>Oo,_uuidv7:()=>No,_void:()=>Zl,_xid:()=>Mo,_xor:()=>Kw,base64Charset:()=>ro,base64urlCharset:()=>Ar,canParseURL:()=>Xc,clone:()=>V,compile:()=>fl,compileFn:()=>Io,config:()=>ne,createStandardJSONSchemaMethod:()=>Ln,createToJSONSchemaMethod:()=>ed,decode:()=>K_,decodeAsync:()=>W_,describe:()=>Hl,encode:()=>J_,encodeAsync:()=>B_,extractDefs:()=>xt,finalize:()=>kt,flattenError:()=>yr,formatError:()=>br,getDiscriminatedOption:()=>Cu,globalConfig:()=>ce,globalRegistry:()=>de,handleUnrepresentable:()=>oe,initializeContext:()=>_t,isBackEdge:()=>bo,isRecursiveSchema:()=>yo,isValidBase64:()=>jr,isValidBase64URL:()=>io,isValidCIDRv6:()=>no,isValidCreditCard:()=>oo,isValidIBAN:()=>ao,isValidIPv6:()=>Pr,isValidJWT:()=>so,locales:()=>Mr,memoizer:()=>Er,mergeValues:()=>kn,meta:()=>Xl,parse:()=>Oi,parseAsync:()=>Ni,parseURLObject:()=>Mm,prettifyError:()=>Fs,process:()=>K,processSchema:()=>K,regexes:()=>Ee,registry:()=>wo,safeDecode:()=>q_,safeDecodeAsync:()=>X_,safeEncode:()=>G_,safeEncodeAsync:()=>H_,safeParse:()=>M_,safeParseAsync:()=>L_,standardProps:()=>Yi,stripTabAndNewline:()=>zr,toDotPath:()=>ym,toJSONSchema:()=>ra,toZod:()=>cr,treeifyError:()=>Zs,urlHostnameOk:()=>eo,urlProtocolOk:()=>to,util:()=>b,validate:()=>$r,validateAsync:()=>_r,validateURL:()=>Qi,version:()=>Kc,withParser:()=>So});var b={};rt(b,{BIGINT_FORMAT_RANGES:()=>fr,CONSTANT_CATCH:()=>Ai,Class:()=>Is,NUMBER_FORMAT_RANGES:()=>pr,aborted:()=>ye,allowsEval:()=>js,assert:()=>o_,assertEqual:()=>t_,assertIs:()=>r_,assertNever:()=>i_,assertNotEqual:()=>n_,assignProp:()=>le,attachSchema:()=>mr,base64ToUint8Array:()=>pm,base64urlToUint8Array:()=>w_,cached:()=>mn,captureStackTrace:()=>Pi,cleanEnum:()=>k_,cleanRegex:()=>ot,clone:()=>V,cloneDef:()=>c_,codePointLength:()=>Dt,constantCatch:()=>Ds,createTransparentProxy:()=>m_,defineLazy:()=>zs,defineLazyInternal:()=>M,derived:()=>P_,esc:()=>ve,escapeRegex:()=>Ce,explicitlyAborted:()=>Os,extend:()=>v_,finalizeIssue:()=>we,floatSafeRemainder:()=>ur,getElementAtPath:()=>u_,getEnumValues:()=>pn,getLengthableOrigin:()=>hr,getParsedType:()=>f_,getSizableOrigin:()=>gr,hexToUint8Array:()=>I_,hide:()=>vr,installLazyProp:()=>O_,isObject:()=>Nt,isPlainObject:()=>Ue,issue:()=>vn,joinValues:()=>v,jsonStringifyReplacer:()=>fn,members:()=>Ns,merge:()=>b_,mergeDefs:()=>Le,normalizeParams:()=>w,nullish:()=>zi,numKeys:()=>p_,objectClone:()=>a_,omit:()=>h_,optionalKeys:()=>Ts,own:()=>ht,parsedType:()=>_,partial:()=>$_,pick:()=>g_,prefixIssues:()=>ke,primitiveTypes:()=>As,promiseAllObject:()=>l_,propertyKeyTypes:()=>dr,randomString:()=>d_,rawShape:()=>gn,required:()=>__,safeExtend:()=>y_,shallowClone:()=>lr,sizeCaps:()=>hn,slugify:()=>Ps,stringifyPrimitive:()=>$,toZod:()=>cr,uint8ArrayToBase64:()=>fm,uint8ArrayToBase64url:()=>S_,uint8ArrayToHex:()=>z_,unwrapMessage:()=>dn});function t_(e){return e}function n_(e){return e}function cr(){return e=>e}function r_(e){}function i_(e){throw new Error("Unexpected value in exhaustive check")}function o_(e){}function pn(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 fn(e,t){return typeof t=="bigint"?t.toString():t}var Ss=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 mn(e){return new Ss(e)}function zi(e){return e==null}function ot(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ur(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 cm=Symbol("evaluating");function zs(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==cm)return o===void 0&&(o=cm,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function a_(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function le(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function gn(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function it(e){return gn(e._zod.def)??e._zod.def.shape}function um(e,t,r){Object.defineProperty(e,t,{get(){let o=r();return le(this,t,o),o},enumerable:!0,configurable:!0})}function lm(e,t,r){t in e?le(e,t,r):e[t]=r}function Ot(e,t,r,o){let n=it(t);for(let i of r){let a=Object.getOwnPropertyDescriptor(n,i);a.enumerable&&(a.get?um(e,i,()=>{let s=t._zod.def.shape[i];return o?o(s,i):s}):lm(e,i,o?o(a.value,i):a.value))}}function s_(e,t){for(let r of Reflect.ownKeys(t)){let o=Object.getOwnPropertyDescriptor(t,r);o.enumerable&&(o.get?um(e,r,()=>t[r]):lm(e,r,o.value))}}function Le(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function c_(e){return Le(e._zod.def)}function u_(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function l_(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 d_(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function ve(e){return JSON.stringify(e)}function Ps(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Pi="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var js=mn(()=>{if(ce.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Ue(e){if(Nt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Nt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function lr(e){return Ue(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function p_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var f_=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}`)}},dr=new Set(["string","number","symbol"]),As=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ce(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function V(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function w(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 m_(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 Ts(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var pr={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]},fr={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function g_(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 Ot(i,e,ji(e,t)),V(e,Le(r,{shape:i,checks:[]}))}function ji(e,t){let r=it(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 h_(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(ji(e,t)),a={};return Ot(a,e,Reflect.ownKeys(it(e)).filter(s=>!i.has(s))),V(e,Le(r,{shape:a,checks:[]}))}function v_(e,t){if(!Ue(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=it(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 V(e,Le(e._zod.def,{shape:dm(e,t)}))}function dm(e,t){let r={};return Ot(r,e,Reflect.ownKeys(it(e))),s_(r,t),r}function y_(e,t){if(!Ue(t))throw new Error("Invalid input to safeExtend: expected a plain object");return V(e,Le(e._zod.def,{shape:dm(e,t)}))}function b_(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={};Ot(r,e,Reflect.ownKeys(it(e))),Ot(r,t,Reflect.ownKeys(it(t)));let o=Le(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return V(e,o)}function $_(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 s=r?new Set(ji(t,r)):void 0,u={};return Ot(u,t,Reflect.ownKeys(it(t)),e&&((l,d)=>s&&!s.has(d)?l:new e({type:"optional",innerType:l}))),V(t,Le(t._zod.def,{shape:u,checks:[]}))}function __(e,t,r){let o=r?new Set(ji(t,r)):void 0,n={};return Ot(n,t,Reflect.ownKeys(it(t)),(i,a)=>o&&!o.has(a)?i:new e({type:"nonoptional",innerType:i})),V(t,Le(t._zod.def,{shape:n}))}function ye(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 Os(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 ke(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function dn(e){return typeof e=="string"?e:e?.message}function hn(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 mr(e,t,r){var o;for(let n=t;n<e.length;n++)(o=e[n]).schema??(o.schema=r)}function we(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:dn(e.inst?._zod.def?.error?.(e))??dn(i?.(e))??dn(t?.error?.(e))??dn(r.customError?.(e))??dn(r.localeError?.(e))??"Invalid input",s={};for(let u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(s[u]=e[u]);return s.path??(s.path=[]),s.message=a,t?.reportInput&&(s.input=e.input),s}function gr(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}var x_=/[\uD800-\uDBFF]/;function Dt(e){let t=e.length;if(!x_.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 hr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function _(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 vn(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function k_(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function pm(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 fm(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function w_(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return pm(t+r)}function S_(e){return fm(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function I_(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 z_(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Is=class{constructor(...t){}};function Ns(e,t){for(let r in t){let o=Object.getOwnPropertyDescriptor(t,r);o.get?Object.defineProperty(e,r,{...o,enumerable:!1}):j_(e,r,o.value)}}function ht(e,t,r,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function vr(e,t,r){return ht(e,t,r,!1)}function P_(e,t){for(let r in e){let o=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return ht(this,r,o(this))},set(n){ht(this,r,n)}})}return t}function j_(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:ht(this,t,r.bind(this))},set(o){ht(this,t,o)}})}function A_(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var ws,gt=!1,T_={configurable:!0,get(){gt=!0}};function M(e,t,r){let o=Object.getPrototypeOf(e._zod);if(t in o&&ws!==e._zod){ws=void 0;return}ws=e._zod,Object.defineProperty(o,t,{configurable:!0,get(){Object.defineProperty(this,t,T_);let n=gt;gt=!1;try{let i=r(this);return gt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i}),gt=gt||n,i}catch(i){throw delete this[t],gt=gt||n,i}},set(n){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:n})}})}function O_(e,t,r,o){let n=A_(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 Ai="~constantCatch";function Ds(e){let t=()=>e;return t[Ai]=!0,t}var mm,Cs=Object.freeze({status:"aborted"}),Us={value:void 0,enumerable:!1},gm="captureStackTrace"in Error?Error:null;function N_(e){let t=gm;if(t){let r=t.stackTraceLimit;if(typeof r=="number"){try{t.stackTraceLimit=0}catch{return gm=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function h(e,t,r,o){let n={};function i(m){this.def=m,this.constr=p,this.traits=new Set}i.prototype=n;let a=r,s=a&&new WeakSet;function u(m,f){if(m._zod){if(m._zod.traits.has(e))return}else{Us.value=new i(f);try{Object.defineProperty(m,"_zod",Us)}finally{Us.value=void 0}}if(m._zod.traits.add(e),t(m,f),s){let y=Object.getPrototypeOf(m),x=m._zod.constr.prototype,I=y;for(;I&&I!==x;)I=Object.getPrototypeOf(I);let S=I??y;s.has(S)||(s.add(S),Ns(S,a))}let g=p.prototype;for(let y in g)Object.prototype.hasOwnProperty.call(g,y)&&(y in m||(m[y]=g[y].bind(m)))}let l=o?.Parent??Object;class d extends l{}Object.defineProperty(d,"name",{value:e});function p(m){let f=o?.Parent?N_(d):this;u(f,m);let g=f._zod.deferred;if(g){for(let x of g)x();f._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;return y&&y(f),f}return Object.defineProperty(p,"init",{value:u}),Object.defineProperty(p,Symbol.hasInstance,{value:m=>o?.Parent&&m instanceof o.Parent?!0:m?._zod?.traits?.has(e)}),Object.defineProperty(p,"name",{value:e}),p}var Es=Symbol("zod_brand"),Se=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},vt=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(mm=globalThis).__zod_globalConfig??(mm.__zod_globalConfig={});var ce=globalThis.__zod_globalConfig;function ne(e){return e&&Object.assign(ce,e),ce}function D_(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,fn,2)),e.message}function U_(e){this._zod.message=e}var C_={get:D_,set:U_,enumerable:!0,configurable:!0},Ms={value:void 0,enumerable:!1},hm=new WeakSet([Object.prototype,Error.prototype]),vm=(e,t)=>{e.name="$ZodError",Ms.value=t,Object.defineProperty(e,"issues",Ms),Ms.value=void 0,Object.defineProperty(e,"message",C_);let r=Object.getPrototypeOf(e);hm.has(r)||(hm.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})}}))},Ls=h("$ZodError",vm),Ie=h("$ZodError",vm,void 0,{Parent:Error});function E_(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 yr(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?E_(r,n.path[0],()=>[]).push(t(n)):o.push(t(n));return{formErrors:o,fieldErrors:r}}function br(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(s=>o({issues:s},[...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 s=[...i,...a.path];if(s.length===0)r._errors.push(t(a));else{let u=r,l=0;for(;l<s.length;){let d=s[l],p=l===s.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 m=u[d];p&&m._errors.push(t(a)),u=m,l++}}}};return o(e),r}function Zs(e,t=r=>r.message){let r={errors:[]},o=(n,i=[])=>{var a;for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(u=>o({issues:u},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let u=[...i,...s.path];if(u.length===0){r.errors.push(t(s));continue}let l=r,d=0;for(;d<u.length;){let p=u[d],m=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]),m&&l.errors.push(t(s)),d++}}};return o(e),r}function ym(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 Fs(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 ${ym(o.path)}`);return t.join(`
2
+ var Q$=Object.defineProperty;var rt=(e,t)=>{for(var r in t)Q$(e,r,{get:t[r],enumerable:!0})};import{fileURLToPath as Y$}from"node:url";import{parseArgs as sA}from"node:util";var e_={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"};function me(e){return new RegExp(`^${e_[e]}_[0-9A-HJKMNP-TV-Z]{26}$`)}var c={};rt(c,{$brand:()=>Es,$input:()=>ul,$output:()=>cl,INVALID:()=>be,NEVER:()=>Cs,TimePrecision:()=>_l,ZodAny:()=>cp,ZodArray:()=>pp,ZodBase64:()=>ka,ZodBase64URL:()=>wa,ZodBigInt:()=>Gn,ZodBigIntFormat:()=>za,ZodBoolean:()=>Wn,ZodCIDRv4:()=>_a,ZodCIDRv6:()=>xa,ZodCUID:()=>ma,ZodCUID2:()=>ga,ZodCatch:()=>Np,ZodCodec:()=>ni,ZodCompileAsyncError:()=>Ze,ZodCompileUnsupportedError:()=>L,ZodCreditCard:()=>ep,ZodCustom:()=>ri,ZodCustomStringFormat:()=>Gt,ZodDate:()=>Hr,ZodDefault:()=>zp,ZodDiscriminatedUnion:()=>mp,ZodE164:()=>Sa,ZodEmail:()=>la,ZodEmoji:()=>pa,ZodEnum:()=>Jn,ZodError:()=>bS,ZodExactOptional:()=>Ta,ZodFile:()=>kp,ZodFirstPartyTypeKind:()=>Wp,ZodFunction:()=>Vp,ZodGUID:()=>da,ZodIBAN:()=>tp,ZodIPv4:()=>ba,ZodIPv6:()=>$a,ZodISODate:()=>St,ZodISODateTime:()=>wt,ZodISODuration:()=>zt,ZodISOTime:()=>It,ZodInstanceOf:()=>Bp,ZodIntersection:()=>gp,ZodIssueCode:()=>xS,ZodJWT:()=>Ia,ZodKSUID:()=>ya,ZodLazy:()=>Lp,ZodLiteral:()=>xp,ZodMAC:()=>Qd,ZodMap:()=>$p,ZodNaN:()=>Up,ZodNanoID:()=>fa,ZodNever:()=>lp,ZodNonOptional:()=>Oa,ZodNull:()=>ap,ZodNullable:()=>Ip,ZodNumber:()=>Bn,ZodNumberFormat:()=>qt,ZodObject:()=>Yr,ZodOptional:()=>ei,ZodPipe:()=>ti,ZodPrefault:()=>jp,ZodPreprocess:()=>Cp,ZodPromise:()=>Fp,ZodReadonly:()=>Ep,ZodRealError:()=>ze,ZodRecord:()=>Vn,ZodSet:()=>_p,ZodString:()=>Kn,ZodStringFormat:()=>G,ZodSuccess:()=>Op,ZodSymbol:()=>ip,ZodTemplateLiteral:()=>Mp,ZodTransform:()=>wp,ZodTuple:()=>vp,ZodType:()=>E,ZodULID:()=>ha,ZodURL:()=>qr,ZodUUID:()=>Ge,ZodUndefined:()=>op,ZodUnion:()=>Qr,ZodUnknown:()=>up,ZodVoid:()=>dp,ZodXID:()=>va,ZodXor:()=>fp,_ZodString:()=>ua,_default:()=>Pp,_function:()=>Zv,any:()=>yv,array:()=>Xr,base64:()=>Yh,base64url:()=>Qh,bigint:()=>fv,boolean:()=>rp,catch:()=>Dp,check:()=>Fv,cidrv4:()=>Hh,cidrv6:()=>Xh,clone:()=>V,codec:()=>Ev,coerce:()=>qp,compile:()=>fl,config:()=>ne,core:()=>ct,creditCard:()=>tv,cuid:()=>Fh,cuid2:()=>Vh,currencyCode:()=>sv,custom:()=>Vv,date:()=>$v,decode:()=>Bd,decodeAsync:()=>Gd,deepPartial:()=>ny,describe:()=>Jv,discriminatedUnion:()=>Iv,e164:()=>ev,email:()=>Oh,emoji:()=>Lh,encode:()=>Kd,encodeAsync:()=>Wd,endsWith:()=>On,enum:()=>ja,exactOptional:()=>Sp,file:()=>Nv,flattenError:()=>yr,float32:()=>uv,float64:()=>lv,formatError:()=>br,fromJSONSchema:()=>ey,function:()=>Zv,getDiscriminatedOption:()=>Cu,getErrorMap:()=>wS,globalRegistry:()=>de,gt:()=>Be,gte:()=>Oe,guid:()=>Nh,hash:()=>cv,hex:()=>av,hostname:()=>ov,httpUrl:()=>Mh,iban:()=>nv,includes:()=>An,input:()=>iy,instanceof:()=>Bv,int:()=>sa,int32:()=>dv,int64:()=>mv,intersection:()=>hp,invertCodec:()=>Rv,ipv4:()=>Wh,ipv6:()=>qh,iso:()=>ii,json:()=>Gv,jwt:()=>rv,keyof:()=>_v,ksuid:()=>Bh,lazy:()=>Zp,length:()=>Vt,literal:()=>Ov,locales:()=>Mr,looseObject:()=>wv,looseRecord:()=>Pv,lowercase:()=>Pn,lt:()=>Ke,lte:()=>Te,mac:()=>Gh,map:()=>jv,maxLength:()=>Ft,maxSize:()=>$t,memoizer:()=>Er,meta:()=>Kv,mime:()=>Dn,minLength:()=>st,minSize:()=>We,multipleOf:()=>bt,nan:()=>Cv,nanoid:()=>Zh,nativeEnum:()=>Tv,negative:()=>Ho,never:()=>Pa,nonnegative:()=>Yo,nonoptional:()=>Tp,nonpositive:()=>Xo,normalize:()=>Un,null:()=>sp,nullable:()=>Gr,nullish:()=>Dv,number:()=>np,object:()=>xv,optional:()=>Bt,output:()=>oy,overwrite:()=>Fe,parse:()=>Zd,parseAsync:()=>Fd,partialRecord:()=>zv,pipe:()=>ca,positive:()=>qo,prefault:()=>Ap,preprocess:()=>qv,prettifyError:()=>Fs,promise:()=>Lv,properties:()=>Nn,property:()=>Qo,readonly:()=>Rp,record:()=>bp,refine:()=>Jp,regex:()=>zn,regexes:()=>Ee,registry:()=>wo,safeDecode:()=>Hd,safeDecodeAsync:()=>Yd,safeEncode:()=>qd,safeEncodeAsync:()=>Xd,safeParse:()=>Vd,safeParseAsync:()=>Jd,set:()=>Av,setErrorMap:()=>kS,size:()=>Zt,slugify:()=>Mn,startsWith:()=>Tn,strictObject:()=>kv,string:()=>Wr,stringFormat:()=>iv,stringbool:()=>Wv,success:()=>Uv,superRefine:()=>Kp,symbol:()=>hv,templateLiteral:()=>Mv,toJSONSchema:()=>ra,toLowerCase:()=>En,toUpperCase:()=>Rn,toZod:()=>cr,transform:()=>Aa,treeifyError:()=>Zs,trim:()=>Cn,tuple:()=>yp,uint32:()=>pv,uint64:()=>gv,ulid:()=>Jh,undefined:()=>vv,union:()=>qn,unknown:()=>Kt,uppercase:()=>jn,url:()=>Rh,util:()=>b,uuid:()=>Dh,uuidv4:()=>Uh,uuidv6:()=>Ch,uuidv7:()=>Eh,validate:()=>$r,validateAsync:()=>_r,void:()=>bv,withParser:()=>So,xid:()=>Kh,xor:()=>Sv});var ct={};rt(ct,{$ZodAny:()=>zu,$ZodArray:()=>Nu,$ZodAsyncError:()=>Se,$ZodBase64:()=>gu,$ZodBase64URL:()=>hu,$ZodBigInt:()=>uo,$ZodBigIntFormat:()=>ku,$ZodBoolean:()=>Tr,$ZodCIDRv4:()=>fu,$ZodCIDRv6:()=>mu,$ZodCUID:()=>tu,$ZodCUID2:()=>nu,$ZodCatch:()=>Yu,$ZodCheck:()=>q,$ZodCheckBigIntFormat:()=>Pc,$ZodCheckEndsWith:()=>Lc,$ZodCheckGreaterThan:()=>Wi,$ZodCheckIncludes:()=>Rc,$ZodCheckLengthEquals:()=>Dc,$ZodCheckLessThan:()=>Bi,$ZodCheckLowerCase:()=>Cc,$ZodCheckMaxLength:()=>Oc,$ZodCheckMaxSize:()=>jc,$ZodCheckMimeType:()=>Vc,$ZodCheckMinLength:()=>Nc,$ZodCheckMinSize:()=>Ac,$ZodCheckMultipleOf:()=>Ic,$ZodCheckNumberFormat:()=>zc,$ZodCheckOverwrite:()=>Jc,$ZodCheckProperties:()=>Fc,$ZodCheckProperty:()=>Zc,$ZodCheckRegex:()=>Uc,$ZodCheckSizeEquals:()=>Tc,$ZodCheckStartsWith:()=>Mc,$ZodCheckStringFormat:()=>xn,$ZodCheckUpperCase:()=>Ec,$ZodCodec:()=>Nr,$ZodCreditCard:()=>yu,$ZodCustom:()=>ol,$ZodCustomStringFormat:()=>_u,$ZodCyclicError:()=>vo,$ZodDate:()=>Tu,$ZodDefault:()=>Gu,$ZodDiscriminatedUnion:()=>Eu,$ZodE164:()=>vu,$ZodEmail:()=>qc,$ZodEmoji:()=>Qc,$ZodEncodeError:()=>vt,$ZodEnum:()=>Fu,$ZodError:()=>Ls,$ZodExactOptional:()=>Bu,$ZodFile:()=>Ju,$ZodFunction:()=>rl,$ZodGUID:()=>Wc,$ZodIBAN:()=>bu,$ZodIPv4:()=>lu,$ZodIPv6:()=>du,$ZodISODate:()=>su,$ZodISODateTime:()=>au,$ZodISODuration:()=>uu,$ZodISOTime:()=>cu,$ZodIntersection:()=>Ru,$ZodJWT:()=>$u,$ZodKSUID:()=>ou,$ZodLazy:()=>Dr,$ZodLiteral:()=>Vu,$ZodMAC:()=>pu,$ZodMap:()=>Lu,$ZodNaN:()=>Qu,$ZodNanoID:()=>eu,$ZodNever:()=>ju,$ZodNonOptional:()=>Hu,$ZodNull:()=>Iu,$ZodNullable:()=>Wu,$ZodNumber:()=>co,$ZodNumberFormat:()=>xu,$ZodObject:()=>Fm,$ZodObjectJIT:()=>Du,$ZodOptional:()=>po,$ZodPipe:()=>fo,$ZodPrefault:()=>qu,$ZodPreprocess:()=>el,$ZodPromise:()=>il,$ZodReadonly:()=>tl,$ZodRealError:()=>Ie,$ZodRecord:()=>Mu,$ZodRegistry:()=>ko,$ZodSet:()=>Zu,$ZodString:()=>Et,$ZodStringFormat:()=>J,$ZodSuccess:()=>Xu,$ZodSymbol:()=>wu,$ZodTemplateLiteral:()=>nl,$ZodTransform:()=>Ku,$ZodTuple:()=>lo,$ZodType:()=>U,$ZodULID:()=>ru,$ZodURL:()=>Yc,$ZodUUID:()=>Gc,$ZodUndefined:()=>Su,$ZodUnion:()=>Or,$ZodUnknown:()=>Pu,$ZodVoid:()=>Au,$ZodXID:()=>iu,$ZodXor:()=>Uu,$brand:()=>Es,$constructor:()=>h,$input:()=>ul,$output:()=>cl,Doc:()=>Ct,INVALID:()=>be,JSONSchema:()=>jh,JSONSchemaGenerator:()=>ia,NEVER:()=>Cs,TimePrecision:()=>_l,URL_BAD_FORMAT:()=>Hc,URL_UNPARSEABLE:()=>Ir,ZodCompileAsyncError:()=>Ze,ZodCompileUnsupportedError:()=>L,_any:()=>Rl,_array:()=>Kl,_base64:()=>Ko,_base64url:()=>Bo,_bigint:()=>Tl,_boolean:()=>jl,_catch:()=>sS,_check:()=>fh,_cidrv4:()=>Vo,_cidrv6:()=>Jo,_coercedBigint:()=>Ol,_coercedBoolean:()=>Al,_coercedDate:()=>Vl,_coercedNumber:()=>kl,_coercedString:()=>vl,_creditCard:()=>bl,_cuid:()=>Co,_cuid2:()=>Eo,_custom:()=>Wl,_date:()=>Fl,_decode:()=>Ui,_decodeAsync:()=>Ei,_default:()=>iS,_discriminatedUnion:()=>Bw,_e164:()=>Wo,_email:()=>Po,_emoji:()=>Do,_encode:()=>Di,_encodeAsync:()=>Ci,_endsWith:()=>On,_enum:()=>Yw,_file:()=>Bl,_float32:()=>Sl,_float64:()=>Il,_gt:()=>Be,_gte:()=>Oe,_guid:()=>jo,_iban:()=>$l,_includes:()=>An,_int:()=>wl,_int32:()=>zl,_int64:()=>Nl,_intersection:()=>Ww,_ipv4:()=>Zo,_ipv6:()=>Fo,_isoDate:()=>Fr,_isoDateTime:()=>Zr,_isoDuration:()=>Jr,_isoTime:()=>Vr,_jwt:()=>Go,_ksuid:()=>Lo,_lazy:()=>dS,_length:()=>Vt,_literal:()=>eS,_lowercase:()=>Pn,_lt:()=>Ke,_lte:()=>Te,_mac:()=>yl,_map:()=>Hw,_max:()=>Te,_maxLength:()=>Ft,_maxSize:()=>$t,_mime:()=>Dn,_min:()=>Oe,_minLength:()=>st,_minSize:()=>We,_multipleOf:()=>bt,_nan:()=>Jl,_nanoid:()=>Uo,_nativeEnum:()=>Qw,_negative:()=>Ho,_never:()=>Ll,_nonnegative:()=>Yo,_nonoptional:()=>oS,_nonpositive:()=>Xo,_normalize:()=>Un,_null:()=>El,_nullable:()=>rS,_number:()=>xl,_optional:()=>nS,_overwrite:()=>Fe,_parse:()=>yn,_parseAsync:()=>bn,_pipe:()=>cS,_positive:()=>qo,_promise:()=>pS,_properties:()=>Nn,_property:()=>Qo,_readonly:()=>uS,_record:()=>qw,_refine:()=>Gl,_regex:()=>zn,_safeDecode:()=>Mi,_safeDecodeAsync:()=>Zi,_safeEncode:()=>Ri,_safeEncodeAsync:()=>Li,_safeParse:()=>$n,_safeParseAsync:()=>_n,_set:()=>Xw,_size:()=>Zt,_slugify:()=>Mn,_startsWith:()=>Tn,_string:()=>hl,_stringFormat:()=>Jt,_stringbool:()=>Yl,_success:()=>aS,_superRefine:()=>ql,_symbol:()=>Ul,_templateLiteral:()=>lS,_toLowerCase:()=>En,_toUpperCase:()=>Rn,_transform:()=>tS,_trim:()=>Cn,_tuple:()=>Gw,_uint32:()=>Pl,_uint64:()=>Dl,_ulid:()=>Ro,_undefined:()=>Cl,_union:()=>Jw,_unknown:()=>Ml,_uppercase:()=>jn,_url:()=>Lr,_uuid:()=>Ao,_uuidv4:()=>To,_uuidv6:()=>Oo,_uuidv7:()=>No,_void:()=>Zl,_xid:()=>Mo,_xor:()=>Kw,base64Charset:()=>ro,base64urlCharset:()=>Ar,canParseURL:()=>Xc,clone:()=>V,compile:()=>fl,compileFn:()=>Io,config:()=>ne,createStandardJSONSchemaMethod:()=>Ln,createToJSONSchemaMethod:()=>ed,decode:()=>K_,decodeAsync:()=>W_,describe:()=>Hl,encode:()=>J_,encodeAsync:()=>B_,extractDefs:()=>xt,finalize:()=>kt,flattenError:()=>yr,formatError:()=>br,getDiscriminatedOption:()=>Cu,globalConfig:()=>ce,globalRegistry:()=>de,handleUnrepresentable:()=>oe,initializeContext:()=>_t,isBackEdge:()=>bo,isRecursiveSchema:()=>yo,isValidBase64:()=>jr,isValidBase64URL:()=>io,isValidCIDRv6:()=>no,isValidCreditCard:()=>oo,isValidIBAN:()=>ao,isValidIPv6:()=>Pr,isValidJWT:()=>so,locales:()=>Mr,memoizer:()=>Er,mergeValues:()=>kn,meta:()=>Xl,parse:()=>Oi,parseAsync:()=>Ni,parseURLObject:()=>Mm,prettifyError:()=>Fs,process:()=>K,processSchema:()=>K,regexes:()=>Ee,registry:()=>wo,safeDecode:()=>q_,safeDecodeAsync:()=>X_,safeEncode:()=>G_,safeEncodeAsync:()=>H_,safeParse:()=>M_,safeParseAsync:()=>L_,standardProps:()=>Yi,stripTabAndNewline:()=>zr,toDotPath:()=>ym,toJSONSchema:()=>ra,toZod:()=>cr,treeifyError:()=>Zs,urlHostnameOk:()=>eo,urlProtocolOk:()=>to,util:()=>b,validate:()=>$r,validateAsync:()=>_r,validateURL:()=>Qi,version:()=>Kc,withParser:()=>So});var b={};rt(b,{BIGINT_FORMAT_RANGES:()=>fr,CONSTANT_CATCH:()=>Ai,Class:()=>Is,NUMBER_FORMAT_RANGES:()=>pr,aborted:()=>ye,allowsEval:()=>js,assert:()=>o_,assertEqual:()=>t_,assertIs:()=>r_,assertNever:()=>i_,assertNotEqual:()=>n_,assignProp:()=>le,attachSchema:()=>mr,base64ToUint8Array:()=>pm,base64urlToUint8Array:()=>w_,cached:()=>mn,captureStackTrace:()=>Pi,cleanEnum:()=>k_,cleanRegex:()=>ot,clone:()=>V,cloneDef:()=>c_,codePointLength:()=>Dt,constantCatch:()=>Ds,createTransparentProxy:()=>m_,defineLazy:()=>zs,defineLazyInternal:()=>M,derived:()=>P_,esc:()=>ve,escapeRegex:()=>Ce,explicitlyAborted:()=>Os,extend:()=>v_,finalizeIssue:()=>we,floatSafeRemainder:()=>ur,getElementAtPath:()=>u_,getEnumValues:()=>pn,getLengthableOrigin:()=>hr,getParsedType:()=>f_,getSizableOrigin:()=>gr,hexToUint8Array:()=>I_,hide:()=>vr,installLazyProp:()=>O_,isObject:()=>Nt,isPlainObject:()=>Ue,issue:()=>vn,joinValues:()=>v,jsonStringifyReplacer:()=>fn,members:()=>Ns,merge:()=>b_,mergeDefs:()=>Le,normalizeParams:()=>w,nullish:()=>zi,numKeys:()=>p_,objectClone:()=>a_,omit:()=>h_,optionalKeys:()=>Ts,own:()=>ht,parsedType:()=>_,partial:()=>$_,pick:()=>g_,prefixIssues:()=>ke,primitiveTypes:()=>As,promiseAllObject:()=>l_,propertyKeyTypes:()=>dr,randomString:()=>d_,rawShape:()=>gn,required:()=>__,safeExtend:()=>y_,shallowClone:()=>lr,sizeCaps:()=>hn,slugify:()=>Ps,stringifyPrimitive:()=>$,toZod:()=>cr,uint8ArrayToBase64:()=>fm,uint8ArrayToBase64url:()=>S_,uint8ArrayToHex:()=>z_,unwrapMessage:()=>dn});function t_(e){return e}function n_(e){return e}function cr(){return e=>e}function r_(e){}function i_(e){throw new Error("Unexpected value in exhaustive check")}function o_(e){}function pn(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 fn(e,t){return typeof t=="bigint"?t.toString():t}var Ss=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 mn(e){return new Ss(e)}function zi(e){return e==null}function ot(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ur(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 cm=Symbol("evaluating");function zs(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==cm)return o===void 0&&(o=cm,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function a_(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function le(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function gn(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function it(e){return gn(e._zod.def)??e._zod.def.shape}function um(e,t,r){Object.defineProperty(e,t,{get(){let o=r();return le(this,t,o),o},enumerable:!0,configurable:!0})}function lm(e,t,r){t in e?le(e,t,r):e[t]=r}function Ot(e,t,r,o){let n=it(t);for(let i of r){let a=Object.getOwnPropertyDescriptor(n,i);a.enumerable&&(a.get?um(e,i,()=>{let s=t._zod.def.shape[i];return o?o(s,i):s}):lm(e,i,o?o(a.value,i):a.value))}}function s_(e,t){for(let r of Reflect.ownKeys(t)){let o=Object.getOwnPropertyDescriptor(t,r);o.enumerable&&(o.get?um(e,r,()=>t[r]):lm(e,r,o.value))}}function Le(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function c_(e){return Le(e._zod.def)}function u_(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function l_(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 d_(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function ve(e){return JSON.stringify(e)}function Ps(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Pi="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var js=mn(()=>{if(ce.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Ue(e){if(Nt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Nt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function lr(e){return Ue(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function p_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var f_=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}`)}},dr=new Set(["string","number","symbol"]),As=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ce(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function V(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function w(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 m_(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 Ts(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var pr={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]},fr={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function g_(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 Ot(i,e,ji(e,t)),V(e,Le(r,{shape:i,checks:[]}))}function ji(e,t){let r=it(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 h_(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(ji(e,t)),a={};return Ot(a,e,Reflect.ownKeys(it(e)).filter(s=>!i.has(s))),V(e,Le(r,{shape:a,checks:[]}))}function v_(e,t){if(!Ue(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=it(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 V(e,Le(e._zod.def,{shape:dm(e,t)}))}function dm(e,t){let r={};return Ot(r,e,Reflect.ownKeys(it(e))),s_(r,t),r}function y_(e,t){if(!Ue(t))throw new Error("Invalid input to safeExtend: expected a plain object");return V(e,Le(e._zod.def,{shape:dm(e,t)}))}function b_(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={};Ot(r,e,Reflect.ownKeys(it(e))),Ot(r,t,Reflect.ownKeys(it(t)));let o=Le(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return V(e,o)}function $_(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 s=r?new Set(ji(t,r)):void 0,u={};return Ot(u,t,Reflect.ownKeys(it(t)),e&&((l,d)=>s&&!s.has(d)?l:new e({type:"optional",innerType:l}))),V(t,Le(t._zod.def,{shape:u,checks:[]}))}function __(e,t,r){let o=r?new Set(ji(t,r)):void 0,n={};return Ot(n,t,Reflect.ownKeys(it(t)),(i,a)=>o&&!o.has(a)?i:new e({type:"nonoptional",innerType:i})),V(t,Le(t._zod.def,{shape:n}))}function ye(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 Os(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 ke(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function dn(e){return typeof e=="string"?e:e?.message}function hn(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 mr(e,t,r){var o;for(let n=t;n<e.length;n++)(o=e[n]).schema??(o.schema=r)}function we(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:dn(e.inst?._zod.def?.error?.(e))??dn(i?.(e))??dn(t?.error?.(e))??dn(r.customError?.(e))??dn(r.localeError?.(e))??"Invalid input",s={};for(let u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(s[u]=e[u]);return s.path??(s.path=[]),s.message=a,t?.reportInput&&(s.input=e.input),s}function gr(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}var x_=/[\uD800-\uDBFF]/;function Dt(e){let t=e.length;if(!x_.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 hr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function _(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 vn(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function k_(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function pm(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 fm(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function w_(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return pm(t+r)}function S_(e){return fm(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function I_(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 z_(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Is=class{constructor(...t){}};function Ns(e,t){for(let r in t){let o=Object.getOwnPropertyDescriptor(t,r);o.get?Object.defineProperty(e,r,{...o,enumerable:!1}):j_(e,r,o.value)}}function ht(e,t,r,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function vr(e,t,r){return ht(e,t,r,!1)}function P_(e,t){for(let r in e){let o=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return ht(this,r,o(this))},set(n){ht(this,r,n)}})}return t}function j_(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:ht(this,t,r.bind(this))},set(o){ht(this,t,o)}})}function A_(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var ws,gt=!1,T_={configurable:!0,get(){gt=!0}};function M(e,t,r){let o=Object.getPrototypeOf(e._zod);if(t in o&&ws!==e._zod){ws=void 0;return}ws=e._zod,Object.defineProperty(o,t,{configurable:!0,get(){Object.defineProperty(this,t,T_);let n=gt;gt=!1;try{let i=r(this);return gt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i}),gt=gt||n,i}catch(i){throw delete this[t],gt=gt||n,i}},set(n){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:n})}})}function O_(e,t,r,o){let n=A_(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 Ai="~constantCatch";function Ds(e){let t=()=>e;return t[Ai]=!0,t}var mm,Cs=Object.freeze({status:"aborted"}),Us={value:void 0,enumerable:!1},gm="captureStackTrace"in Error?Error:null;function N_(e){let t=gm;if(t){let r=t.stackTraceLimit;if(typeof r=="number"){try{t.stackTraceLimit=0}catch{return gm=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function h(e,t,r,o){let n={};function i(m){this.def=m,this.constr=p,this.traits=new Set}i.prototype=n;let a=r,s=a&&new WeakSet;function u(m,f){if(m._zod){if(m._zod.traits.has(e))return}else{Us.value=new i(f);try{Object.defineProperty(m,"_zod",Us)}finally{Us.value=void 0}}if(m._zod.traits.add(e),t(m,f),s){let y=Object.getPrototypeOf(m),x=m._zod.constr.prototype,I=y;for(;I&&I!==x;)I=Object.getPrototypeOf(I);let S=I??y;s.has(S)||(s.add(S),Ns(S,a))}let g=p.prototype;for(let y in g)Object.prototype.hasOwnProperty.call(g,y)&&(y in m||(m[y]=g[y].bind(m)))}let l=o?.Parent??Object;class d extends l{}Object.defineProperty(d,"name",{value:e});function p(m){let f=o?.Parent?N_(d):this;u(f,m);let g=f._zod.deferred;if(g){for(let x of g)x();f._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;return y&&y(f),f}return Object.defineProperty(p,"init",{value:u}),Object.defineProperty(p,Symbol.hasInstance,{value:m=>o?.Parent&&m instanceof o.Parent?!0:m?._zod?.traits?.has(e)}),Object.defineProperty(p,"name",{value:e}),p}var Es=Symbol("zod_brand"),Se=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},vt=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(mm=globalThis).__zod_globalConfig??(mm.__zod_globalConfig={});var ce=globalThis.__zod_globalConfig;function ne(e){return e&&Object.assign(ce,e),ce}function D_(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,fn,2)),e.message}function U_(e){this._zod.message=e}var C_={get:D_,set:U_,enumerable:!0,configurable:!0},Ms={value:void 0,enumerable:!1},hm=new WeakSet([Object.prototype,Error.prototype]),vm=(e,t)=>{e.name="$ZodError",Ms.value=t,Object.defineProperty(e,"issues",Ms),Ms.value=void 0,Object.defineProperty(e,"message",C_);let r=Object.getPrototypeOf(e);hm.has(r)||(hm.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})}}))},Ls=h("$ZodError",vm),Ie=h("$ZodError",vm,void 0,{Parent:Error});function E_(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 yr(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?E_(r,n.path[0],()=>[]).push(t(n)):o.push(t(n));return{formErrors:o,fieldErrors:r}}function br(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(s=>o({issues:s},[...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 s=[...i,...a.path];if(s.length===0)r._errors.push(t(a));else{let u=r,l=0;for(;l<s.length;){let d=s[l],p=l===s.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 m=u[d];p&&m._errors.push(t(a)),u=m,l++}}}};return o(e),r}function Zs(e,t=r=>r.message){let r={errors:[]},o=(n,i=[])=>{var a;for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(u=>o({issues:u},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let u=[...i,...s.path];if(u.length===0){r.errors.push(t(s));continue}let l=r,d=0;for(;d<u.length;){let p=u[d],m=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]),m&&l.errors.push(t(s)),d++}}};return o(e),r}function ym(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 Fs(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 ${ym(o.path)}`);return t.join(`
3
3
  `)}function Ti(e,t){return{callee:t?.callee??e,Err:t?.Err}}var yn=e=>{let t=(r,o,n,i)=>{let a=n?{...n,async:!1}:{async:!1},s=r._zod.run({value:o,issues:[]},a);if(s instanceof Promise)throw new Se;if(s.issues.length){let u=new(i?.Err??e)(s.issues.map(l=>we(l,a,ne())));throw Pi(u,i?.callee??t),u}return s.value};return t},Oi=yn(Ie),bn=e=>{let t=async(r,o,n,i)=>{let a=n?{...n,async:!0}:{async:!0},s=r._zod.run({value:o,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){let u=new(i?.Err??e)(s.issues.map(l=>we(l,a,ne())));throw Pi(u,i?.callee??t),u}return s.value};return t},Ni=bn(Ie),$n=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 Se;return i.issues.length?bm(e,i.issues,n):{success:!0,data:i.value}},M_=$n(Ie);function bm(e,t,r){let o;return{success:!1,get error(){return o||(o=new e(t.map(n=>we(n,r,ne()))),t=void 0,r=void 0),o},set error(n){o=n,t=void 0,r=void 0}}}var _n=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?bm(e,i.issues,n):{success:!0,data:i.value}},L_=_n(Ie),Z_=Symbol.for("zod.compile.invalid"),F_=Symbol.for("zod.compile.fallback"),$r=((e,t,r)=>{let o=e._zod.bag.validator;if(o!==void 0){if(o(t)!==Z_)return!0;if(o.definite===!0&&r===void 0)return!1}return V_(e,t,r)});function V_(e,t,r){let o=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},n=e._zod.bag.fallbackRun,i;if(n?(o[F_]=!0,i=n({value:t,issues:[]},o)):i=e._zod.run({value:t,issues:[]},o),i instanceof Promise)throw new Se;return i.issues.length===0}var _r=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},Di=e=>{let t=yn(e),r=(o,n,i,a)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return t(o,n,s,Ti(r,a))};return r},J_=Di(Ie),Ui=e=>{let t=yn(e),r=(o,n,i,a)=>t(o,n,i,Ti(r,a));return r},K_=Ui(Ie),Ci=e=>{let t=bn(e),r=async(o,n,i,a)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return await t(o,n,s,Ti(r,a))};return r},B_=Ci(Ie),Ei=e=>{let t=bn(e),r=async(o,n,i,a)=>await t(o,n,i,Ti(r,a));return r},W_=Ei(Ie),Ri=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return $n(e)(t,r,n)},G_=Ri(Ie),Mi=e=>(t,r,o)=>$n(e)(t,r,o),q_=Mi(Ie),Li=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return _n(e)(t,r,n)},H_=Li(Ie),Zi=e=>async(t,r,o)=>_n(e)(t,r,o),X_=Zi(Ie);var Ee={};rt(Ee,{anyString:()=>gc,base64:()=>ac,base64url:()=>sc,bigint:()=>vc,boolean:()=>yc,browserEmail:()=>ox,cidrv4:()=>ic,cidrv6:()=>oc,creditCard:()=>Fi,cuid:()=>Js,cuid2:()=>Ks,currencyCode:()=>dc,date:()=>pc,datetime:()=>mc,domain:()=>uc,duration:()=>Xs,e164:()=>lc,email:()=>Qs,emoji:()=>ec,extendedDuration:()=>Y_,guid:()=>Ys,hex:()=>kc,hostname:()=>cc,html5Email:()=>nx,httpProtocol:()=>xr,iban:()=>Vi,idnEmail:()=>ix,integer:()=>kr,ipv4:()=>tc,ipv6:()=>nc,ksuid:()=>Gs,lowercase:()=>_c,mac:()=>rc,md5_base64:()=>ux,md5_base64url:()=>lx,md5_hex:()=>cx,nanoid:()=>qs,nanoidOfLength:()=>Hs,null:()=>bc,number:()=>at,rfc5322Email:()=>rx,sha1_base64:()=>px,sha1_base64url:()=>fx,sha1_hex:()=>dx,sha256_base64:()=>gx,sha256_base64url:()=>hx,sha256_hex:()=>mx,sha384_base64:()=>yx,sha384_base64url:()=>bx,sha384_hex:()=>vx,sha512_base64:()=>_x,sha512_base64url:()=>xx,sha512_hex:()=>$x,string:()=>hc,time:()=>fc,ulid:()=>Bs,undefined:()=>$c,unicodeEmail:()=>$m,uppercase:()=>xc,uuid:()=>Ut,uuid4:()=>Q_,uuid6:()=>ex,uuid7:()=>tx,xid:()=>Ws});var Js=/^[cC][0-9a-z]{6,}$/,Ks=/^[0-9a-z]+$/,Bs=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Ws=/^[0-9a-vA-V]{20}$/,Gs=/^[A-Za-z0-9]{27}$/,qs=/^[a-zA-Z0-9_-]{21}$/;function Hs(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Xs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Y_=/^[-+]?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)?)??$/,Ys=/^([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})$/,Ut=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)$/,Q_=Ut(4),ex=Ut(6),tx=Ut(7),Qs=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nx=/^[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])?)*$/,rx=/^(([^<>()\[\]\\.,;:\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,}))$/,$m=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,ix=$m,ox=/^[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])?)*$/,ax="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function ec(){return new RegExp(ax,"u")}var tc=/^(?:(?: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])$/,nc=/^(([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}|:))$/,rc=e=>{let t=Ce(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},ic=/^((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])$/,oc=/^(([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])$/,ac=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,sc=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,cc=/^(?=.{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])?)*\.?$/,uc=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,xr=/^https?$/,lc=/^\+[1-9]\d{6,14}$/,Fi=/^\d(?:[ -]?\d){11,18}$/,dc=/^(?: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)$/,Vi=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,_m="(?:(?:\\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 sx(e){return new RegExp(`^${e}$`)}var pc=sx(_m);function Vs(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 fc(e){return new RegExp(`^${Vs(e)}$`)}function mc(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${Vs({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,o=e.local?`${r}|${Vs({precision:e.precision})}`:r;return new RegExp(`^${_m}T(?:${o})$`)}var gc=/^[\s\S]{0,}$/,hc=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},vc=/^-?\d+n?$/,kr=/^-?\d+$/,at=/^-?\d+(?:\.\d+)?$/,yc=/^(?:true|false)$/i,bc=/^null$/i;var $c=/^undefined$/i;var _c=/^[^A-Z]*$/,xc=/^[^a-z]*$/,kc=/^[0-9a-fA-F]*$/;function wr(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Sr(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var cx=/^[0-9a-fA-F]{32}$/,ux=wr(22,"=="),lx=Sr(22),dx=/^[0-9a-fA-F]{40}$/,px=wr(27,"="),fx=Sr(27),mx=/^[0-9a-fA-F]{64}$/,gx=wr(43,"="),hx=Sr(43),vx=/^[0-9a-fA-F]{96}$/,yx=wr(64,""),bx=Sr(64),$x=/^[0-9a-fA-F]{128}$/,_x=wr(86,"=="),xx=Sr(86);var q=h("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),wc=e=>{let t=e.value;return!zi(t)&&t.size!==void 0},Sc=e=>{let t=e.value;return!zi(t)&&t.length!==void 0},Ji={number:"number",bigint:"bigint",object:"date"},Bi=h("$ZodCheckLessThan",(e,t)=>{q.init(e,t);let r=Ji[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:Ji[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})}}),Wi=h("$ZodCheckGreaterThan",(e,t)=>{q.init(e,t);let r=Ji[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:Ji[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})}}),Ic=h("$ZodCheckMultipleOf",(e,t)=>{q.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):ur(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})}}),zc=h("$ZodCheckNumberFormat",(e,t)=>{q.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=pr[t.format];e._zod.check=a=>{let s=a.value;if(r){if(!Number.isInteger(s)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,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:s,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}}s<n&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Pc=h("$ZodCheckBigIntFormat",(e,t)=>{q.init(e,t);let[r,o]=fr[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})}}),jc=h("$ZodCheckMaxSize",(e,t)=>{var r;q.init(e,t),(r=e._zod.def).when??(r.when=wc),e._zod.check=o=>{let n=o.value;n.size<=t.maximum||o.issues.push({origin:gr(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Ac=h("$ZodCheckMinSize",(e,t)=>{var r;q.init(e,t),(r=e._zod.def).when??(r.when=wc),e._zod.check=o=>{let n=o.value;n.size>=t.minimum||o.issues.push({origin:gr(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Tc=h("$ZodCheckSizeEquals",(e,t)=>{var r;q.init(e,t),(r=e._zod.def).when??(r.when=wc),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:gr(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})}}),Oc=h("$ZodCheckMaxLength",(e,t)=>{var r;q.init(e,t),(r=e._zod.def).when??(r.when=Sc),e._zod.check=o=>{let n=o.value,i=n.length;if((typeof n=="string"&&i>t.maximum?Dt(n):i)<=t.maximum)return;let s=hr(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Nc=h("$ZodCheckMinLength",(e,t)=>{var r;q.init(e,t),(r=e._zod.def).when??(r.when=Sc),e._zod.check=o=>{let n=o.value,i=n.length;if((typeof n=="string"&&i>=t.minimum&&i<t.minimum*2?Dt(n):i)>=t.minimum)return;let s=hr(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Dc=h("$ZodCheckLengthEquals",(e,t)=>{var r;q.init(e,t),(r=e._zod.def).when??(r.when=Sc),e._zod.check=o=>{let n=o.value,i=n.length,a=typeof n=="string"&&i>=t.length&&i<=t.length*2?Dt(n):i;if(a===t.length)return;let s=hr(n),u=a>t.length;o.issues.push({origin:s,...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})}}),xn=h("$ZodCheckStringFormat",(e,t)=>{var r,o;q.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=()=>{})}),Uc=h("$ZodCheckRegex",(e,t)=>{xn.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})}}),Cc=h("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=_c),xn.init(e,t)}),Ec=h("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=xc),xn.init(e,t)}),Rc=h("$ZodCheckIncludes",(e,t)=>{q.init(e,t);let r=Ce(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})}}),Mc=h("$ZodCheckStartsWith",(e,t)=>{q.init(e,t);let r=new RegExp(`^${Ce(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})}}),Lc=h("$ZodCheckEndsWith",(e,t)=>{q.init(e,t);let r=new RegExp(`.*${Ce(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 Ki(e,t,r){e.issues.length&&t.issues.push(...ke(r,e.issues))}var Zc=h("$ZodCheckProperty",(e,t)=>{q.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=>Ki(n,r,t.property));Ki(o,r,t.property)}}),Fc=h("$ZodCheckProperties",(e,t)=>{q.init(e,t),vr(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,s]of r){let u=s._zod.run({value:n[a],issues:[]},{});u instanceof Promise?(i??(i=[]),i.push(u.then(l=>Ki(l,o,a)))):Ki(u,o,a)}if(i)return Promise.all(i).then(()=>{})}}),Vc=h("$ZodCheckMimeType",(e,t)=>{q.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})}}),Jc=h("$ZodCheckOverwrite",(e,t)=>{q.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Ct=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(`
@@ -60,7 +60,7 @@ ${u}`:u:"",d=Function,p=`return (input) => {
60
60
  ${u}
61
61
  }`,m;try{m=new d(...a,p)(...s)}catch(f){throw new L(`this schema (generated code failed to evaluate: ${f.message})`)}return t?.debug&&(m.code=l),m.definite=o.definite,m}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 Mt(e,t){return e.definite=!1,N(e,t)}function O(e){return`v${e.varCounter++}`}function Wk(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return be;let o=r;return o.issues.length===0?o.value:be}function ge(e,t,r,o,n=!0){let i=e.content.length,a=t.constants.size,s=t.constantCounter,u=t.varCounter;try{return Y(e,t,r,o,n)}catch(l){if(!(l instanceof L)||!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=s,t.varCounter=u,Gk(e,t,r,o)}}function Gk(e,t,r,o){t.definite=!1;let n=N(t,r),i=N(t,Wk),a=O(t);return e.write(`const ${a} = ${i}(${n}, ${o});`),e.write(`if (${a} === INVALID) return INVALID;`),a}var qk=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Hk(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 s=a._zod.def;if(s.when&&!qk.has(s.check))throw new L('check with a custom "when" condition');switch(s.check){case"greater_than":Xk(e,t,s,i);break;case"less_than":Yk(e,t,s,i);break;case"multiple_of":Qk(e,t,s,i);break;case"number_format":dh(e,s,i);break;case"min_length":{let u=yt(s.minimum,"min_length"),l=ll(e,t,i,`${i}.length >= ${u} && ${i}.length < ${s.minimum*2}`);e.write(`if (${l} < ${u}) return INVALID;`);break}case"max_length":{let u=yt(s.maximum,"max_length"),l=ll(e,t,i,`${i}.length > ${u}`);e.write(`if (${l} > ${u}) return INVALID;`);break}case"length_equals":{let u=yt(s.length,"length_equals"),l=ll(e,t,i,`${i}.length >= ${u} && ${i}.length <= ${s.length*2}`);e.write(`if (${l} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${i}.size < ${yt(s.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${i}.size > ${yt(s.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${i}.size !== ${yt(s.size,"size_equals")}) return INVALID;`);break;case"string_format":i=ph(e,t,s,i);break;case"custom":i=ow(e,t,a,i);break;case"bigint_format":ew(e,s,i);break;case"mime_type":tw(e,t,s,i);break;case"property":rw(e,t,s,i);break;case"properties":nw(e,t,s,i);break;case"overwrite":{let u=O(t);iw(e,t,a,i,u),i=u;break}default:throw new L(`check type ${s.check}`)}}return i}function ll(e,t,r,o){let n=N(t,Dt),i=O(t);return e.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function yt(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new L(`${t} bound of type ${typeof e}`);return`${e}`}function lh(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new L("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new L("comparison check with Invalid Date bound");return N(e,t)}throw new L(`comparison check bound of type ${typeof t}`)}function Xk(e,t,r,o){let n=r.inclusive?"<":"<=";e.write(`if (${o} ${n} ${lh(t,r.value)}) return INVALID;`)}function Yk(e,t,r,o){let n=r.inclusive?">":">=";e.write(`if (${o} ${n} ${lh(t,r.value)}) return INVALID;`)}function Qk(e,t,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new L("multiple_of check with a zero divisor");e.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=N(t,ur);e.write(`if (${n}(${o}, ${yt(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function dh(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 L(`number format ${o}`)}}function ew(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 L(`bigint format ${o}`)}}function tw(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 nw(e,t,r,o){if(r.when)throw new L('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):ve(i),s=O(t);e.write(`const ${s} = ${o}[${a}];`),ge(e,t,n[i],s,!1)}}function rw(e,t,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;Y(e,t,r.schema,n)}function iw(e,t,r,o,n){let i=r._zod.def.tx;if(!i)throw new L("overwrite check without a transform function");if(Lt(i))throw new Ze("z.compile: async overwrite transforms are not supported");let a=N(t,i);e.write(`const ${n} = ${a}(${o});`)}function dl(){throw new Se}function ml(e){this.issues.push(e)}function ow(e,t,r,o){let n=r._zod.def;if(n.fn){if(Lt(n.fn))throw new Ze("z.compile: async .refine() predicates are not supported");let i=Mt(t,n.fn),a=N(t,dl),s=O(t);return e.write(`const ${s} = ${i}(${o});`),e.write(`if (${s} instanceof Promise) ${a}();`),e.write(`if (!${s}) return INVALID;`),o}if(r._zod.check){if(Lt(r._zod.check))throw new Ze("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,s=Mt(t,l=>{let d={value:l,issues:[],addIssue:ml};return i(d)instanceof Promise&&dl(),d.issues.length===0?d.value:be}),u=O(t);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new L("custom check without a predicate or check function")}var aw=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 ph(e,t,r,o,n=!0){let i=r.format;if(i==="base64"){let l=N(t,jr);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="base64url"){let l=N(t,io);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="jwt"){let l=N(t,so),d=N(t,r.alg??null);return e.write(`if (!${l}(${o}, ${d})) return INVALID;`),o}if(i==="ipv6"){let l=N(t,Pr);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="cidrv6"){let l=N(t,no);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="credit_card"){let l=N(t,oo);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="iban"){let l=N(t,ao);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,Qi),d=N(t,r),p=O(t),m=O(t);if(e.write(`const ${p} = ${o}.trim();`),e.write(`const ${m} = ${l}(${p}, ${d});`),e.write(`if (typeof ${m} === "number") return INVALID;`),a.hostname!==void 0){let y=N(t,eo);e.write(`if (!${y}(${m}, ${d}.hostname)) return INVALID;`)}if(a.protocol!==void 0){let y=N(t,to);e.write(`if (!${y}(${m}, ${d}.protocol)) return INVALID;`)}if(!n)return null;let f=O(t),g=a.normalize?`${m}.href`:`${N(t,zr)}(${p})`;return e.write(`const ${f} = ${g};`),f}let s=r.fn;if(s){if(Lt(s))throw new L(`async string format ${i}`);let l=N(t,s);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(aw.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 L("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(${ve(r.includes)})) return INVALID;`);break;case"starts_with":{let l=r.prefix;e.write(`if (${o}.slice(0, ${l.length}) !== ${ve(l)}) return INVALID;`);break}case"ends_with":{let l=r.suffix;e.write(`if (${o}.slice(-${l.length}) !== ${ve(l)}) return INVALID;`);break}default:throw new L(`string format ${u}`)}return o}function Y(e,t,r,o,n=!0){let i=r._zod.def,a=i.type;if(i.coerce)throw new L(`coercion (z.coerce.${a}())`);let s=n||!!i.checks?.length,u;switch(a){case"string":u=sw(e,t,r,o,s);break;case"number":u=cw(e,r,o);break;case"boolean":u=uw(e,o);break;case"bigint":u=lw(e,r,o);break;case"symbol":u=dw(e,o);break;case"undefined":u=pw(e,o);break;case"null":u=fw(e,o);break;case"any":case"unknown":u=o;break;case"never":e.write("return INVALID;"),u=o;break;case"void":u=mw(e,o);break;case"nan":u=gw(e,o);break;case"date":u=hw(e,o);break;case"object":u=vw(e,t,r,o,s);break;case"optional":u=yw(e,t,r,o,s);break;case"nullable":u=_w(e,t,r,o,s);break;case"array":u=xw(e,t,r,o,s);break;case"literal":u=kw(e,t,r,o);break;case"enum":u=ww(e,t,r,o);break;case"readonly":{let l=sh(e,t,r,o),d=O(t);e.write(`const ${d} = Object.freeze(${l});`),u=d;break}case"success":sh(e,t,r,o),u="true";break;case"default":case"prefault":u=Sw(e,t,r,o);break;case"nonoptional":u=Iw(e,t,r,o);break;case"tuple":u=zw(e,t,r,o);break;case"union":u=Pw(e,t,r,o);break;case"intersection":u=Tw(e,t,r,o);break;case"record":u=Ow(e,t,r,o);break;case"map":u=Dw(e,t,r,o);break;case"set":u=Uw(e,t,r,o);break;case"file":u=Cw(e,o);break;case"template_literal":u=Ew(e,t,r,o);break;case"lazy":u=Rw(e,t,r,o);break;case"pipe":u=Mw(e,t,r,o);break;case"custom":u=Lw(e,t,r,o);break;case"transform":u=Vw(e,t,r,o);break;case"catch":u=Fw(e,t,r,o);break;default:throw new L(`schema type ${a}`)}return u===null?null:Hk(e,t,r,u)}function sw(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:ph(e,t,i,o,n)}function cw(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&&dh(e,{format:o.format},r),r}function uw(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function lw(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 dw(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function pw(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function fw(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function mw(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function gw(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function hw(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function vw(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,s=Object.keys(a),u=Object.getOwnPropertySymbols(a),l=u.length?[...s,...u]:s,d=S=>typeof S=="symbol"?N(t,S):ve(S),p=S=>typeof S=="symbol"?`[${d(S)}]`:ve(S),m=a;if(s.includes("__proto__"))throw new L('object shape key "__proto__"');let f=new Map;for(let S of l){let T=m[S],P=d(S),C=O(t);if(e.write(`const ${C} = ${o}[${P}];`),T._zod.optin!==void 0){let j=O(t);e.write(`let ${j} = (() => {`),e.indented(A=>{let ue=ge(A,t,T,C);A.write(`return ${ue};`)}),e.write("})();"),T._zod.optout==="optional"?(e.write(`if (${j} === INVALID) {`),e.indented(A=>{A.write(`if (${P} in ${o}) return INVALID;`),A.write(`${j} = undefined;`)}),e.write("}")):e.write(`if (${j} === INVALID) return INVALID;`),f.set(S,j)}else{$w(T)&&e.write(`if (!(${P} in ${o})) return INVALID;`);let j=ge(e,t,T,C,n);j!==null&&f.set(S,j)}}let g=i.catchall,y="none";if(g){let S=g._zod.def.type;if(S==="never"){let T=s.map(P=>`k !== ${ve(P)}`).join(" && ")||"true";e.write(`for (const k in ${o}) {`),e.indented(P=>{P.write(`if (${T}) return INVALID;`)}),e.write("}")}else(S==="unknown"||S==="any")&&!g._zod.def.checks?.length?y="passthrough":y="schema"}let x=O(t),I=l.some(S=>ah(m[S])||pl(m[S]));if(!n){if(y==="schema"){let S=s.length>0?N(t,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(T=>{T.write('if (k === "__proto__") continue;'),S&&T.write(`if (${S}.has(k)) continue;`);let P=O(t);T.write(`const ${P} = ${o}[k];`),ge(T,t,g,P,!1)}),e.write("}")}return null}if(I){e.write(`const ${x} = {};`);for(let S of l){let T=d(S),P=f.get(S);pl(m[S])?e.write(`if (${T} in ${o}) ${x}[${T}] = ${P};`):ah(m[S])?e.write(`if (${P} !== undefined || ${T} in ${o}) ${x}[${T}] = ${P};`):e.write(`${x}[${T}] = ${P};`)}}else{let S=l.map(T=>`${p(T)}: ${f.get(T)}`).join(", ");e.write(`const ${x} = { ${S} };`)}if(y!=="none"){let S=s.length>0?N(t,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(T=>{if(T.write('if (k === "__proto__") continue;'),S&&T.write(`if (${S}.has(k)) continue;`),y==="passthrough")T.write(`${x}[k] = ${o}[k];`);else{let P=O(t);T.write(`const ${P} = ${o}[k];`);let C=ge(T,t,g,P);T.write(`${x}[k] = ${C};`)}}),e.write("}")}return x}function yw(e,t,r,o,n=!0){let i=r._zod.def;if(bw(r))return Y(e,t,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let s=O(t),u=O(t);return e.write(`let ${s};`),e.write(`if (${o} === undefined) {`),e.indented(l=>{l.write(`const ${u} = (() => {`),l.indented(d=>{let p=Y(d,t,i.innerType,o);d.write(`return ${p};`)}),l.write("})();"),l.write(`if (${u} !== INVALID) ${s} = ${u};`)}),e.write("} else {"),e.indented(l=>{let d=Y(l,t,i.innerType,o);l.write(`${s} = ${d};`)}),e.write("}"),s}let a=n?O(t):null;return a&&e.write(`let ${a};`),e.write(`if (${o} !== undefined) {`),e.indented(s=>{let u=Y(s,t,i.innerType,o,n);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function bw(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function $w(e){return e._zod.optin===void 0&&Rt(e)}function Rt(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?Rt(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?Rt(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Rt):!0;case"intersection":return!t.left||!t.right?!0:Rt(t.left)&&Rt(t.right);case"pipe":return t.in?Rt(t.in):!0;default:return!0}}function pl(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function ah(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&In(e)}function In(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?In(t.innerType):!0;case"union":return t.options?t.options.some(In):!0;case"intersection":return!t.left||!t.right||In(t.left)||In(t.right);case"pipe":return t.out?In(t.out):!0;default:return!0}}function _w(e,t,r,o,n=!0){let i=r._zod.def,a=n?O(t):null;return a&&e.write(`let ${a} = null;`),e.write(`if (${o} !== null) {`),e.indented(s=>{let u=Y(s,t,i.innerType,o,n);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function gl(e,t,r){for(let[o,n]of hn(t._zod.def.checks))e.write(`if (${r} > ${yt(o,n._zod.def.check)}) return INVALID;`)}function xw(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (!Array.isArray(${o})) return INVALID;`),gl(e,r,`${o}.length`);let a=n?O(t):null,s=O(t),u=O(t);return a&&e.write(`const ${a} = new Array(${o}.length);`),e.write(`for (let ${s} = 0; ${s} < ${o}.length; ${s}++) {`),e.indented(l=>{l.write(`const ${u} = ${o}[${s}];`);let d=ge(l,t,i.element,u,n);a&&d!==null&&l.write(`${a}[${s}] = ${d};`)}),e.write("}"),a}function kw(e,t,r,o){let i=r._zod.def.values;if(i.length!==1){let s=N(t,new Set(i));return e.write(`if (!${s}.has(${o})) return INVALID;`),o}let a=i[0];if(typeof a=="number"&&Number.isNaN(a)){let s=N(t,new Set(i));return e.write(`if (!${s}.has(${o})) return INVALID;`),o}if(typeof a=="string")e.write(`if (${o} !== ${ve(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 L(`literal type ${typeof a}`);return o}function ww(e,t,r,o){let n=r._zod.values;if(!n)throw new L("enum schema without enumerated values");let i=N(t,n);return e.write(`if (!${i}.has(${o})) return INVALID;`),o}function sh(e,t,r,o){let n=r._zod.def;return Y(e,t,n.innerType,o)}function Sw(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 Y(e,t,n.innerType,o);let u=N(t,a),l=O(t);return e.write(`let ${l} = ${o};`),e.write(`if (${o} === undefined) ${l} = ${u}();`),Y(e,t,n.innerType,l)}let s=O(t);if(a){let u=N(t,a),l=N(t,lr);e.write(`let ${s};`),e.write(`if (${o} === undefined) {`),e.indented(d=>{d.write(`${s} = ${l}(${u}());`)}),e.write("} else {"),e.indented(d=>{let p=Y(d,t,n.innerType,o);d.write(`${s} = ${p} === undefined ? ${l}(${u}()) : ${p};`)}),e.write("}")}else e.write(`let ${s};`),e.write(`if (${o} !== undefined) {`),e.indented(u=>{let l=Y(u,t,n.innerType,o);u.write(`${s} = ${l};`)}),e.write("}");return s}function Iw(e,t,r,o){let n=r._zod.def,i=Y(e,t,n.innerType,o),a=O(t);return e.write(`const ${a} = ${i};`),e.write(`if (${a} === undefined) return INVALID;`),a}function zw(e,t,r,o){let n=r._zod.def,i=n.items,a=n.rest;e.write(`if (!Array.isArray(${o})) return INVALID;`);let s=ch(i,"optin"),u=ch(i,"optout");a?e.write(`if (${o}.length < ${s}) return INVALID;`):e.write(`if (${o}.length < ${s} || ${o}.length > ${i.length}) return INVALID;`);let l=O(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(m=>{m.write(`if (${d} < ${o}.length) {`),m.indented(f=>{let g=O(t);f.write(`const ${g} = ${o}[${d}];`);let y=ge(f,t,p,g);f.write(`${l}[${d}] = ${y};`)}),m.write("} else {"),m.indented(f=>{if(pl(p)){f.write(`${l}.length = ${d};`);return}let g=O(t),y=O(t);f.write(`const ${g} = undefined;`),f.write(`const ${y} = (() => {`),f.indented(x=>{let I=ge(x,t,p,g);x.write(`return ${I};`)}),f.write("})();"),f.write(`if (${y} === INVALID || ${y} === undefined) ${l}.length = ${d};`),f.write(`else ${l}[${d}] = ${y};`)}),m.write("}")}),e.write("}");else{let m=O(t);e.write(`const ${m} = ${o}[${d}];`);let f=ge(e,t,p,m);e.write(`${l}[${d}] = ${f};`)}}if(a){let d=O(t),p=O(t);e.write(`for (let ${d} = ${i.length}; ${d} < ${o}.length; ${d}++) {`),e.indented(m=>{m.write(`const ${p} = ${o}[${d}];`);let f=ge(m,t,a,p);m.write(`${l}[${d}] = ${f};`)}),e.write("}")}return l}function ch(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 Pw(e,t,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return jw(e,t,n,o);if(n.inclusive===!1)throw new L("exclusive unions (z.xor)");if(i.length===0)return e.write("return INVALID;"),o;if(i.length===1)return Y(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 s=O(t);e.write(`let ${s};`);for(let u=0;u<i.length;u++){let l=i[u];u===0?e.write(`${s} = (() => {`):e.write(`if (${s} === INVALID) ${s} = (() => {`),e.indented(d=>{let p=Y(d,t,l,o);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${s} === INVALID) return INVALID;`),s}function jw(e,t,r,o){if(r.unionFallback)throw new L("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),o;let n=O(t),i=O(t);e.write(`const ${n} = ${o}?.[${ve(r.discriminator)}];`),e.write(`let ${i};`);let a=!0,s=new Set;for(let u of r.options){let l=u._zod.propValues?.[r.discriminator];if(!l||l.size===0)throw new L("discriminated union option without static discriminator values");for(let m of l){if(s.has(m))throw new L(`duplicate discriminator value ${String(m)}`);s.add(m)}let d=Array.from(l,m=>Aw(t,n,m)),p=a?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(m=>{let f=Y(m,t,u,o);m.write(`${i} = ${f};`)}),e.write("}"),a=!1}return e.write("else { return INVALID; }"),i}function Aw(e,t,r){if(typeof r=="string")return`${t} === ${ve(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 L(`literal discriminator value ${String(r)}`)}function Tw(e,t,r,o){let n=r._zod.def;t.definite=!1;let i=ge(e,t,n.left,o),a=ge(e,t,n.right,o),s=N(t,kn),u=O(t);return e.write(`const ${u} = ${s}(${i}, ${a});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function Ow(e,t,r,o){let n=r._zod.def,i=N(t,Ue);e.write(`if (!${i}(${o})) return INVALID;`);let a=O(t),s=O(t),u=O(t);e.write(`const ${a} = {};`);let l=n,d=l.partial?void 0:n.keyType._zod.values;if(d){let f=[];for(let y of d){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new L(`record key value ${String(y)}`);let x=typeof y=="number"?y.toString():y;if(x==="__proto__")throw new L('record key "__proto__"');f.push(x);let I=N(t,y),S=Y(e,t,n.keyType,I),T=O(t);e.write(`const ${T} = ${o}[${Nw(t,x)}];`);let P=ge(e,t,n.valueType,T);e.write(`${a}[${S}] = ${P};`)}let g=N(t,new Set(f));return e.write(`for (const ${s} in ${o}) {`),e.indented(y=>{y.write(`if (${g}.has(${s})) continue;`),l.mode==="loose"?y.write(`if (${s} !== "__proto__") ${a}[${s}] = ${o}[${s}];`):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 f=n.mode==="loose",g=Io(n.keyType);g.definite===!1&&(t.definite=!1);let y=N(t,g),x=N(t,at),I=O(t);return uh(e,t,o,s,S=>{S.write(`let ${I} = ${y}(${s});`),S.write(`if (${I} === INVALID && typeof ${s} === "string" && ${x}.test(${s})) ${I} = ${y}(Number(${s}));`),f?S.write(`if (${I} === INVALID) { ${a}[${s}] = ${o}[${s}]; continue; }`):S.write(`if (${I} === INVALID) return INVALID;`),S.write(`if (${I} === "__proto__") continue;`);let T=O(t);S.write(`const ${T} = ${o}[${s}];`);let P=ge(S,t,n.valueType,T);S.write(`${a}[${I}] = ${P};`)}),a}return uh(e,t,o,s,f=>{f.write(`const ${u} = ${o}[${s}];`);let g=ge(f,t,n.valueType,u);f.write(`${a}[${s}] = ${g};`)},"return INVALID;"),a}function uh(e,t,r,o,n,i){let a=N(t,Object.prototype.propertyIsEnumerable),s=O(t),u=O(t),l=O(t);e.write(`const ${s} = 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} < ${s}.length; ${l}++) {`),e.indented(d=>{d.write(`const ${o} = ${s}[${l}];`),d.write(`if (!${a}.call(${r}, ${o})) continue;`),i?d.write(i):n(d)}),e.write("}")}function Nw(e,t){return typeof t=="string"?ve(t):N(e,t)}function Dw(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Map)) return INVALID;`),gl(e,r,`${o}.size`);let i=O(t),a=O(t),s=O(t);return e.write(`const ${i} = new Map();`),e.write(`for (const [${a}, ${s}] of ${o}) {`),e.indented(u=>{let l=Y(u,t,n.keyType,a),d=Y(u,t,n.valueType,s);u.write(`${i}.set(${l}, ${d});`)}),e.write("}"),i}function Uw(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Set)) return INVALID;`),gl(e,r,`${o}.size`);let i=O(t),a=O(t);return e.write(`const ${i} = new Set();`),e.write(`for (const ${a} of ${o}) {`),e.indented(s=>{let u=Y(s,t,n.valueType,a);s.write(`${i}.add(${u});`)}),e.write("}"),i}function Cw(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function Ew(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 Rw(e,t,r,o){let n=r._zod.def,i=Mt(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 s=O(t);return e.write(`const ${s} = ${a}.parser(${o});`),e.write(`if (${s} === INVALID) return INVALID;`),s}function Mw(e,t,r,o){let n=r._zod.def,i=Y(e,t,n.in,o);if(n.transform){if(Lt(n.transform))throw new Ze("z.compile: async transforms in pipes are not supported");let a=n.transform,u=Mt(t,d=>{let p={value:d,issues:[],addIssue:ml},m=a(d,p);return m instanceof Promise?be:p.issues.length===0?m:be}),l=O(t);return e.write(`const ${l} = ${u}(${i});`),e.write(`if (${l} === INVALID) return INVALID;`),Y(e,t,n.out,l)}else return Y(e,t,n.out,i)}function Lt(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function Lw(e,t,r,o){let n=r._zod.def;if(n.fn){if(Lt(n.fn))throw new Ze("z.compile: async custom predicates are not supported");let i=Mt(t,n.fn),a=N(t,dl),s=O(t);e.write(`const ${s} = ${i}(${o});`),e.write(`if (${s} instanceof Promise) ${a}();`),e.write(`if (!${s}) return INVALID;`)}else throw new L("custom schema without a predicate function");return o}function Zw(e,t,r){let o=e._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return be;let n=o;return n.issues.length===0?n.value:t()}function Fw(e,t,r,o){let n=r._zod.def;if(!n.catchValue[Ai])throw new L("catch with a callback (only a constant catch value compiles)",!1);let i=O(t);e.write(`let ${i} = (() => {`),e.indented(l=>{let d=ge(l,t,n.innerType,o);l.write(`return ${d};`)}),e.write("})();");let a=N(t,n.innerType),s=Mt(t,n.catchValue),u=N(t,Zw);return e.write(`if (${i} === INVALID) {`),e.indented(l=>{l.write(`${i} = ${u}(${a}, ${s}, ${o});`),l.write(`if (${i} === INVALID) return INVALID;`)}),e.write("}"),i}function Vw(e,t,r,o){let n=r._zod.def;if(n.transform){if(Lt(n.transform))throw new Ze("z.compile: async transforms are not supported");let i=n.transform,s=Mt(t,l=>{let d={value:l,issues:[],addIssue:ml},p=i(l,d);return p instanceof Promise?be:d.issues.length===0?p:be}),u=O(t);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return o}function zo(e){return e.checks&&(e.checks=[...e.checks]),e}function hl(e,t){return new e(zo({type:"string",...w(t)}))}function vl(e,t){return new e(zo({type:"string",coerce:!0,...w(t)}))}function Po(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...w(t)})}function jo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...w(t)})}function Ao(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...w(t)})}function To(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...w(t)})}function Oo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...w(t)})}function No(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...w(t)})}function Lr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...w(t)})}function Do(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...w(t)})}function Uo(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...w(t)})}function Co(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...w(t)})}function Eo(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...w(t)})}function Ro(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...w(t)})}function Mo(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...w(t)})}function Lo(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...w(t)})}function Zo(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...w(t)})}function Fo(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...w(t)})}function yl(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...w(t)})}function Vo(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...w(t)})}function Jo(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...w(t)})}function Ko(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...w(t)})}function Bo(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...w(t)})}function Wo(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...w(t)})}function bl(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...w(t)})}function $l(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...w(t)})}function Go(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...w(t)})}var _l={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Zr(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...w(t)})}function Fr(e,t){return new e({type:"string",format:"date",check:"string_format",...w(t)})}function Vr(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...w(t)})}function Jr(e,t){return new e({type:"string",format:"duration",check:"string_format",...w(t)})}function xl(e,t){return new e(zo({type:"number",checks:[],...w(t)}))}function kl(e,t){return new e(zo({type:"number",coerce:!0,checks:[],...w(t)}))}function wl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...w(t)})}function Sl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...w(t)})}function Il(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...w(t)})}function zl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...w(t)})}function Pl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...w(t)})}function jl(e,t){return new e({type:"boolean",...w(t)})}function Al(e,t){return new e({type:"boolean",coerce:!0,...w(t)})}function Tl(e,t){return new e({type:"bigint",...w(t)})}function Ol(e,t){return new e({type:"bigint",coerce:!0,...w(t)})}function Nl(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...w(t)})}function Dl(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...w(t)})}function Ul(e,t){return new e({type:"symbol",...w(t)})}function Cl(e,t){return new e({type:"undefined",...w(t)})}function El(e,t){return new e({type:"null",...w(t)})}function Rl(e){return new e({type:"any"})}function Ml(e){return new e({type:"unknown"})}function Ll(e,t){return new e({type:"never",...w(t)})}function Zl(e,t){return new e({type:"void",...w(t)})}function Fl(e,t){return new e({type:"date",...w(t)})}function Vl(e,t){return new e({type:"date",coerce:!0,...w(t)})}function Jl(e,t){return new e({type:"nan",...w(t)})}function Ke(e,t){return new Bi({check:"less_than",...w(t),value:e,inclusive:!1})}function Te(e,t){return new Bi({check:"less_than",...w(t),value:e,inclusive:!0})}function Be(e,t){return new Wi({check:"greater_than",...w(t),value:e,inclusive:!1})}function Oe(e,t){return new Wi({check:"greater_than",...w(t),value:e,inclusive:!0})}function qo(e){return Be(0,e)}function Ho(e){return Ke(0,e)}function Xo(e){return Te(0,e)}function Yo(e){return Oe(0,e)}function bt(e,t){return new Ic({check:"multiple_of",...w(t),value:e})}function $t(e,t){return new jc({check:"max_size",...w(t),maximum:e})}function We(e,t){return new Ac({check:"min_size",...w(t),minimum:e})}function Zt(e,t){return new Tc({check:"size_equals",...w(t),size:e})}function Ft(e,t){return new Oc({check:"max_length",...w(t),maximum:e})}function st(e,t){return new Nc({check:"min_length",...w(t),minimum:e})}function Vt(e,t){return new Dc({check:"length_equals",...w(t),length:e})}function zn(e,t){return new Uc({check:"string_format",format:"regex",...w(t),pattern:e})}function Pn(e){return new Cc({check:"string_format",format:"lowercase",...w(e)})}function jn(e){return new Ec({check:"string_format",format:"uppercase",...w(e)})}function An(e,t){return new Rc({check:"string_format",format:"includes",...w(t),includes:e})}function Tn(e,t){return new Mc({check:"string_format",format:"starts_with",...w(t),prefix:e})}function On(e,t){return new Lc({check:"string_format",format:"ends_with",...w(t),suffix:e})}function Qo(e,t,r){return new Zc({check:"property",property:e,schema:t,...w(r)})}function Nn(e,t){return new Fc({check:"properties",shape:e,...w(t)})}function Dn(e,t){return new Vc({check:"mime_type",mime:e,...w(t)})}function Fe(e){return new Jc({check:"overwrite",tx:e})}function Un(e){return Fe(t=>t.normalize(e))}function Cn(){return Fe(e=>e.trim())}function En(){return Fe(e=>e.toLowerCase())}function Rn(){return Fe(e=>e.toUpperCase())}function Mn(){return Fe(e=>Ps(e))}function Kl(e,t,r){return new e({type:"array",element:t,...w(r)})}function Jw(e,t,r){return new e({type:"union",options:t,...w(r)})}function Kw(e,t,r){return new e({type:"union",options:t,inclusive:!1,...w(r)})}function Bw(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...w(o)})}function Ww(e,t,r){return new e({type:"intersection",left:t,right:r})}function Gw(e,t,r,o){let n=r instanceof U,i=n?o:r,a=n?r:null;return new e({type:"tuple",items:t,rest:a,...w(i)})}function qw(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...w(o)})}function Hw(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...w(o)})}function Xw(e,t,r){return new e({type:"set",valueType:t,...w(r)})}function Yw(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...w(r)})}function Qw(e,t,r){return new e({type:"enum",entries:t,...w(r)})}function eS(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...w(r)})}function Bl(e,t){return new e({type:"file",...w(t)})}function tS(e,t){return new e({type:"transform",transform:t})}function nS(e,t){return new e({type:"optional",innerType:t})}function rS(e,t){return new e({type:"nullable",innerType:t})}function iS(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():lr(r)}})}function oS(e,t,r){return new e({type:"nonoptional",innerType:t,...w(r)})}function aS(e,t){return new e({type:"success",innerType:t})}function sS(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:Ds(r)})}function cS(e,t,r){return new e({type:"pipe",in:t,out:r})}function uS(e,t){return new e({type:"readonly",innerType:t})}function lS(e,t,r){return new e({type:"template_literal",parts:t,...w(r)})}function dS(e,t){return new e({type:"lazy",getter:t})}function pS(e,t){return new e({type:"promise",innerType:t})}function Wl(e,t,r){let o=w(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Gl(e,t,r){return new e({type:"custom",check:"custom",fn:t,...w(r)})}function ql(e,t){let r=fh(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(vn(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(vn(i))}},e(o.value,o)),t);return r}function fh(e,t){let r=new q({check:"custom",...w(t)});return r._zod.check=e,r}function Hl(e){let t=new q({check:"describe"});return t._zod.onattach=[r=>{let o=de.get(r)??{};de.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function Xl(e){let t=new q({check:"meta"});return t._zod.onattach=[r=>{let o=de.get(r)??{};de.add(r,{...o,...e})}],t._zod.check=()=>{},t}function Yl(e,t){let r=w(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(f=>typeof f=="string"?f.toLowerCase():f),n=n.map(f=>typeof f=="string"?f.toLowerCase():f));let i=new Set(o),a=new Set(n),s=e.Codec??Nr,u=e.Boolean??Tr,l=e.String??Et,d=new l({type:"string",error:r.error}),p=new u({type:"boolean",error:r.error}),m=new s({type:"pipe",in:d,out:p,transform:((f,g)=>{let y=f;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:m,continue:!1}),{})}),reverseTransform:((f,g)=>f===!0?o[0]||"true":n[0]||"false"),error:r.error});return m._zod.bag.truthy=o,m._zod.bag.falsy=n,m._zod.bag.case=r.case??"insensitive",m}function Jt(e,t,r,o={}){let n=w(o),i={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:s=>r.test(s),...n};return r instanceof RegExp&&(i.pattern=r),new e(i)}function Kr(e,...t){for(let r of t)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&le(e,o,r[o]);return e}function _t(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??de,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 oe(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 K(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 s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,d);else{let m=a.schema,f=t.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(e,t,m,d)}let p=e._zod.parent;p&&(a.ref||(a.ref=p),K(p,t,d),t.seen.get(p).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&Kr(a.schema,u),t.io==="input"&&$e(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 mh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function xt(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 s=e.metadataRegistry.get(a[0])?.id;if(s){let u=o.get(s);if(u&&u!==a[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(s,a[0])}}let n=a=>{let s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(a[0])?.id,m=e.external.uri??(g=>g);if(p)return{ref:m(p)};let f=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=f,{defId:f,ref:`${m("__shared")}#/${s}/${mh(f)}`}}let u="#",l=`${u}/${s}/`;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+mh(d)}},i=a=>{if(a[1].schema.$ref)return;let s=a[1],{ref:u,defId:l}=n(a);s.def={...s.schema},l&&(s.defId=l);let d=s.schema;for(let p in d)delete d[p];d.$ref=u};if(e.cycles==="throw")for(let a of e.seen.entries()){let s=a[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.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 s=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(s.cycle){i(a);continue}s.count>1&&e.reused==="ref"&&i(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function vh(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;vh(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 yh=new Set(["type","properties","required","additionalProperties"]),gh=["oneOf","anyOf"];function hh(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Ql(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!yh.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 s=[];for(let l of t){let d=l.properties?.[a]??hh(l);d!=null&&(s.some(p=>JSON.stringify(p)===JSON.stringify(d))||s.push(d))}let u=s.length===1?s[0]:Ql(s)??{allOf:s};le(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 s=hh(a);s&&!i.some(u=>JSON.stringify(u)===JSON.stringify(s))&&i.push(s)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function fS(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of yh)if(n in e)return;let r=t.filter(n=>gh.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Ql(t);else{let n=r[0],i=gh.find(u=>Array.isArray(n[u]));if(Object.keys(n).length!==1)return;let a=t.filter(u=>u!==n),s=n[i].map(u=>Ql([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,Kr(e,o))}function kt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{let u=e.seen.get(s);if(u.ref===null)return;let l=u.def??u.schema,d={...l},p=u.ref;if(u.ref=null,p){o(p);let f=e.seen.get(p),g=f.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)):Kr(l,g),Kr(l,d),s._zod.parent===p)for(let x in l)x==="$ref"||x==="allOf"||x in d||delete l[x];if(g.$ref&&f.def)for(let x in l)x==="$ref"||x==="allOf"||x in f.def&&JSON.stringify(l[x])===JSON.stringify(f.def[x])&&delete l[x]}let m=s._zod.parent;if(m&&m!==p){o(m);let f=e.seen.get(m);if(f?.schema.$ref&&(l.$ref=f.schema.$ref,f.def))for(let g in l)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(l[g])===JSON.stringify(f.def[g])&&delete l[g]}e.override({zodSchema:s,jsonSchema:l,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())o(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())vh(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=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=s.get(d);p?p.push(l):s.set(d,[l])}for(let u of e.intersections)for(let l of s.get(u)??[])fS(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 s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(s)}Kr(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 s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,le(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 s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ln(t,"input",e.processors),output:Ln(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function $e(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 $e(o.element,r);if(o.type==="set")return $e(o.valueType,r);if(o.type==="lazy")return $e(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 $e(o.innerType,r);if(o.type==="intersection")return $e(o.left,r)||$e(o.right,r);if(o.type==="record"||o.type==="map")return $e(o.keyType,r)||$e(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:$e(o.in,r)||$e(o.out,r);if(o.type==="object"){for(let n in o.shape)if($e(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if($e(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if($e(n,r))return!0;return!!(o.rest&&$e(o.rest,r))}return!1}var ed=(e,t={})=>r=>{let o=_t({...r,processors:t});return K(e,o),xt(o,e),kt(o,e)},Ln=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=_t({...n??{},target:i,io:t,processors:r});return K(e,a),xt(a,e),kt(a,e)};var Zn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Fn=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},bh=(e,t)=>{Zn(e,"minimum",t),Fn(e,"maximum",t)},kh=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},wh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Sh=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Ih=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},$h=(e,t)=>Zn(e,"minimum",t.minimum),_h=(e,t)=>Fn(e,"maximum",t.maximum),xh=e=>(t,r)=>{Ih(t,r.format);let[o,n]=e[r.format];Zn(t,"minimum",o),Fn(t,"maximum",n)},mS={greater_than:(e,t)=>Zn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Fn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>kh(e,t.value),number_format:xh(pr),bigint_format:xh(fr),min_length:$h,max_length:_h,length_equals:(e,t)=>bh(e,t.length),min_size:$h,max_size:_h,size_equals:(e,t)=>bh(e,t.size),string_format:(e,t)=>{Ih(e,t.format),t.pattern&&wh(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)=>Sh(e,t.mime)};function ae(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)mS[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Zn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Zn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Fn(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Fn(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&kh(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&Sh(t,n.mime);for(let i of n.patterns??[])wh(t,i);return t}var gS={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},hS=new Map([[ro,ac],[Ar,sc]]),zh=e=>hS.get(e)??e,rd=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:a,format:s,patterns:u,contentEncoding:l,laxFormat:d}=ae(e);if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),s&&(n.format=gS[s]??s,n.format===""&&delete n.format,(s==="time"||d)&&delete n.format),l&&(n.contentEncoding=l),u&&u.size>0){let p=[...u].map(zh);p.length===1?n.pattern=p[0].source:p.length>1&&(n.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},id=(e,t,r,o)=>{let n=r,{minimum:i,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:l,isInt:d}=ae(e);n.type=d?"integer":"number";let p=typeof l=="number"&&l>=(i??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(p?f?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof i=="number"&&(n.minimum=i),m?f?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),s){let g=new Set;for(let I of s)Number.isFinite(I)&&I!==0?g.add(Math.abs(I)):oe(e,t,n,o,`A multipleOf divisor of ${I} cannot be represented in JSON Schema`);let[y,...x]=g;y!==void 0&&(n.multipleOf=y),x.length&&(n.allOf=[...n.allOf??[],...x.map(I=>({multipleOf:I}))])}},od=(e,t,r,o)=>{r.type="boolean"},ad=(e,t,r,o)=>{oe(e,t,r,o,"BigInt cannot be represented in JSON Schema")},sd=(e,t,r,o)=>{oe(e,t,r,o,"Symbols cannot be represented in JSON Schema")},cd=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},ud=(e,t,r,o)=>{oe(e,t,r,o,"Undefined cannot be represented in JSON Schema")},ld=(e,t,r,o)=>{oe(e,t,r,o,"Void cannot be represented in JSON Schema")},dd=(e,t,r,o)=>{r.not={}},pd=(e,t,r,o)=>{},fd=(e,t,r,o)=>{},md=(e,t,r,o)=>{oe(e,t,r,o,"Date cannot be represented in JSON Schema")},gd=(e,t,r,o)=>{let n=e._zod.def,i=pn(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},hd=(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(oe(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(oe(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},vd=(e,t,r,o)=>{oe(e,t,r,o,"NaN cannot be represented in JSON Schema")},yd=(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},bd=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:a,mime:s}=ae(e);i!==void 0&&(n.minLength=i),a!==void 0&&(n.maxLength=a),s&&(s.length===0?n.not={}:s.length===1?n.contentMediaType=s[0]:n.anyOf=s.map(u=>({contentMediaType:u})))},$d=(e,t,r,o)=>{r.type="boolean"},_d=(e,t,r,o)=>{oe(e,t,r,o,"Custom types cannot be represented in JSON Schema")},xd=(e,t,r,o)=>{oe(e,t,r,o,"Function types cannot be represented in JSON Schema")},kd=(e,t,r,o)=>{oe(e,t,r,o,"Transforms cannot be represented in JSON Schema")},wd=(e,t,r,o)=>{oe(e,t,r,o,"Map cannot be represented in JSON Schema")},Sd=(e,t,r,o)=>{oe(e,t,r,o,"Set cannot be represented in JSON Schema")},Id=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:a,maximum:s}=ae(e);typeof a=="number"&&(n.minItems=a),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=K(i.element,t,{...o,path:[...o.path,"items"]})};function Br(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Br(t.out):t.type==="catch"?Br(t.innerType):e._zod.optin}var zd=(e,t,r,o)=>{let n=r,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&oe(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let l in a)le(n.properties,l,K(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"?Br(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=K(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},ta=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((s,u)=>K(s,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},Pd=(e,t,r,o)=>{let n=e._zod.def,i=K(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=K(n.right,t,{...o,path:[...o.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,u=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=u,t.intersections.push(u)},jd=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((y,x)=>K(y,t,{...o,path:[...o.path,a,x]})),l=i.rest?K(i.rest,t,{...o,path:[...o.path,s,...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"?Br(y)!==void 0:y._zod.optout==="optional"))break;d--}let p=i.items.length,m=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,m?n.items=!1:l&&(n.items=l),d>0&&(n.minItems=d),m&&(n.maxItems=p)):t.target==="openapi-3.0"?(n.items={anyOf:u},l&&n.items.anyOf.push(l),d>0&&(n.minItems=d),m&&(n.maxItems=p)):(n.items=u,m?n.additionalItems=!1:l&&(n.additionalItems=l),d>0&&(n.minItems=d),m&&(n.maxItems=p));let{minimum:f,maximum:g}=ae(e);typeof f=="number"&&(n.minItems=f),typeof g=="number"&&(n.maxItems=g)};function td(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=td(e,g,r);return y===g?t:y}for(let g of["anyOf","oneOf"]){let y=t[g];if(!Array.isArray(y))continue;let x=y.map(I=>td(e,I,r));x.some((I,S)=>I!==y[S])&&(t={...t,[g]:x})}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:s,exclusiveMinimum:u,exclusiveMaximum:l,multipleOf:d,format:p,id:m,...f}=t;return f.enum?f.enum=f.enum.map(g=>typeof g=="number"?String(g):g):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?at:kr).source)),f}var nd=new WeakMap;function vS(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 nd.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=td(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 Ad=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let a=i.keyType,s=ae(a).patterns;if(i.mode==="loose"&&s&&s.size>0){let d=K(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of s)le(n.patternProperties,zh(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=K(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let d=nd.get(t);d||(d=[],nd.set(t,d),t.deferred.push(()=>vS(t))),d.push(e)}n.additionalProperties=K(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,l=t.io==="input"&&Br(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))}},Td=(e,t,r,o)=>{let n=e._zod.def,i=K(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"}]},Od=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Nd=Symbol();function Ph(e,t,r,o,n){let i=!1,a=JSON.stringify(e,(s,u)=>typeof u!="bigint"?u:(i=!0,null));return i?(oe(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),Nd):JSON.parse(a)}var Dd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=Ph(n.defaultValue,e,t,r,o);a!==Nd&&(r.default=a)},Ud=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=Ph(n.defaultValue,e,t,r,o);a!==Nd&&(r._prefault=a)},Cd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{oe(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=a},Ed=(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;K(a,t,o);let s=t.seen.get(e);s.ref=a},Rd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},Md=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},na=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Ld=(e,t,r,o)=>{let n=e._zod.innerType;K(n,t,o);let i=t.seen.get(e);i.ref=n},ea={string:rd,number:id,boolean:od,bigint:ad,symbol:sd,null:cd,undefined:ud,void:ld,never:dd,any:pd,unknown:fd,date:md,enum:gd,literal:hd,nan:vd,template_literal:yd,file:bd,success:$d,custom:_d,function:xd,transform:kd,map:wd,set:Sd,array:Id,object:zd,union:ta,intersection:Pd,tuple:jd,record:Ad,nullable:Td,nonoptional:Od,default:Dd,prefault:Ud,catch:Cd,pipe:Ed,readonly:Rd,promise:Md,optional:na,lazy:Ld};function ra(e,t){if("_idmap"in e){let o=e,n=_t({...t,processors:ea}),i={};for(let u of o._idmap.entries()){let[l,d]=u;K(d,n)}let a={},s={registry:o,uri:t?.uri,defs:i};n.external=s;for(let u of o._idmap.entries()){let[l,d]=u;xt(n,d),le(a,l,kt(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=_t({...t,processors:ea});return K(e,r),xt(r,e),kt(r,e)}var ia=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=_t({processors:ea,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 K(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,xt(this.ctx,t);let o=kt(this.ctx,t),{"~standard":n,...i}=o;return i}};var jh={};var Hn={};rt(Hn,{ZodAny:()=>cp,ZodArray:()=>pp,ZodBase64:()=>ka,ZodBase64URL:()=>wa,ZodBigInt:()=>Gn,ZodBigIntFormat:()=>za,ZodBoolean:()=>Wn,ZodCIDRv4:()=>_a,ZodCIDRv6:()=>xa,ZodCUID:()=>ma,ZodCUID2:()=>ga,ZodCatch:()=>Np,ZodCodec:()=>ni,ZodCreditCard:()=>ep,ZodCustom:()=>ri,ZodCustomStringFormat:()=>Gt,ZodDate:()=>Hr,ZodDefault:()=>zp,ZodDiscriminatedUnion:()=>mp,ZodE164:()=>Sa,ZodEmail:()=>la,ZodEmoji:()=>pa,ZodEnum:()=>Jn,ZodExactOptional:()=>Ta,ZodFile:()=>kp,ZodFunction:()=>Vp,ZodGUID:()=>da,ZodIBAN:()=>tp,ZodIPv4:()=>ba,ZodIPv6:()=>$a,ZodISODate:()=>St,ZodISODateTime:()=>wt,ZodISODuration:()=>zt,ZodISOTime:()=>It,ZodInstanceOf:()=>Bp,ZodIntersection:()=>gp,ZodJWT:()=>Ia,ZodKSUID:()=>ya,ZodLazy:()=>Lp,ZodLiteral:()=>xp,ZodMAC:()=>Qd,ZodMap:()=>$p,ZodNaN:()=>Up,ZodNanoID:()=>fa,ZodNever:()=>lp,ZodNonOptional:()=>Oa,ZodNull:()=>ap,ZodNullable:()=>Ip,ZodNumber:()=>Bn,ZodNumberFormat:()=>qt,ZodObject:()=>Yr,ZodOptional:()=>ei,ZodPipe:()=>ti,ZodPrefault:()=>jp,ZodPreprocess:()=>Cp,ZodPromise:()=>Fp,ZodReadonly:()=>Ep,ZodRecord:()=>Vn,ZodSet:()=>_p,ZodString:()=>Kn,ZodStringFormat:()=>G,ZodSuccess:()=>Op,ZodSymbol:()=>ip,ZodTemplateLiteral:()=>Mp,ZodTransform:()=>wp,ZodTuple:()=>vp,ZodType:()=>E,ZodULID:()=>ha,ZodURL:()=>qr,ZodUUID:()=>Ge,ZodUndefined:()=>op,ZodUnion:()=>Qr,ZodUnknown:()=>up,ZodVoid:()=>dp,ZodXID:()=>va,ZodXor:()=>fp,_ZodString:()=>ua,_default:()=>Pp,_function:()=>Zv,any:()=>yv,array:()=>Xr,base64:()=>Yh,base64url:()=>Qh,bigint:()=>fv,boolean:()=>rp,catch:()=>Dp,check:()=>Fv,cidrv4:()=>Hh,cidrv6:()=>Xh,codec:()=>Ev,creditCard:()=>tv,cuid:()=>Fh,cuid2:()=>Vh,currencyCode:()=>sv,custom:()=>Vv,date:()=>$v,describe:()=>Jv,discriminatedUnion:()=>Iv,e164:()=>ev,email:()=>Oh,emoji:()=>Lh,enum:()=>ja,exactOptional:()=>Sp,file:()=>Nv,float32:()=>uv,float64:()=>lv,function:()=>Zv,guid:()=>Nh,hash:()=>cv,hex:()=>av,hostname:()=>ov,httpUrl:()=>Mh,iban:()=>nv,instanceof:()=>Bv,int:()=>sa,int32:()=>dv,int64:()=>mv,intersection:()=>hp,invertCodec:()=>Rv,ipv4:()=>Wh,ipv6:()=>qh,json:()=>Gv,jwt:()=>rv,keyof:()=>_v,ksuid:()=>Bh,lazy:()=>Zp,literal:()=>Ov,looseObject:()=>wv,looseRecord:()=>Pv,mac:()=>Gh,map:()=>jv,meta:()=>Kv,nan:()=>Cv,nanoid:()=>Zh,nativeEnum:()=>Tv,never:()=>Pa,nonoptional:()=>Tp,null:()=>sp,nullable:()=>Gr,nullish:()=>Dv,number:()=>np,object:()=>xv,optional:()=>Bt,partialRecord:()=>zv,pipe:()=>ca,prefault:()=>Ap,preprocess:()=>qv,promise:()=>Lv,readonly:()=>Rp,record:()=>bp,refine:()=>Jp,set:()=>Av,strictObject:()=>kv,string:()=>Wr,stringFormat:()=>iv,stringbool:()=>Wv,success:()=>Uv,superRefine:()=>Kp,symbol:()=>hv,templateLiteral:()=>Mv,transform:()=>Aa,tuple:()=>yp,uint32:()=>pv,uint64:()=>gv,ulid:()=>Jh,undefined:()=>vv,union:()=>qn,unknown:()=>Kt,url:()=>Rh,uuid:()=>Dh,uuidv4:()=>Uh,uuidv6:()=>Ch,uuidv7:()=>Eh,void:()=>bv,xid:()=>Kh,xor:()=>Sv});var oa={};rt(oa,{endsWith:()=>On,gt:()=>Be,gte:()=>Oe,includes:()=>An,length:()=>Vt,lowercase:()=>Pn,lt:()=>Ke,lte:()=>Te,maxLength:()=>Ft,maxSize:()=>$t,mime:()=>Dn,minLength:()=>st,minSize:()=>We,multipleOf:()=>bt,negative:()=>Ho,nonnegative:()=>Yo,nonpositive:()=>Xo,normalize:()=>Un,overwrite:()=>Fe,positive:()=>qo,properties:()=>Nn,property:()=>Qo,regex:()=>zn,size:()=>Zt,slugify:()=>Mn,startsWith:()=>Tn,toLowerCase:()=>En,toUpperCase:()=>Rn,trim:()=>Cn,uppercase:()=>jn});var Ah=new WeakSet([Object.prototype,Error.prototype]);function aa(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 Th=(e,t)=>{Ls.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);Ah.has(r)||(Ah.add(r),aa(r,"format",o=>n=>br(o,n)),aa(r,"flatten",o=>n=>yr(o,n)),aa(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,fn,2)}),aa(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,fn,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},bS=h("ZodError",Th),ze=h("ZodError",Th,void 0,{Parent:Error});var Zd=yn(ze),Fd=bn(ze),Vd=$n(ze),Jd=_n(ze),Kd=Di(ze),Bd=Ui(ze),Wd=Ci(ze),Gd=Ei(ze),qd=Ri(ze),Hd=Mi(ze),Xd=Li(ze),Yd=Zi(ze);function _S(){ce.localeError||ne($o())}function Wt(){ce.memoizer||ne({memoizer:Er()})}var E=h("ZodType",(e,t)=>(_S(),U.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 V(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Jp(e,t))},superRefine(e,t){return this.check(Kp(e,t))},overwrite(e){return this.check(Fe(e))},optional(){return Bt(this)},exactOptional(){return Sp(this)},nullable(){return Gr(this)},nullish(){return Bt(Gr(this))},nonoptional(e){return Tp(this,e)},array(){return Xr(this)},or(e){return qn([this,e])},and(e){return hp(this,e)},transform(e){return ca(this,Aa(e))},default(e){return Pp(this,e)},prefault(e){return Ap(this,e)},catch(e){return Dp(this,e)},pipe(e){return ca(this,e)},readonly(){return Rp(this)},describe(e){let t=this.clone();return de.add(t,{description:e}),t},meta(...e){if(e.length===0)return de.get(this);let t=this.clone();return de.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",{...Yi(this),jsonSchema:{input:Ln(this,"input"),output:Ln(this,"output")}})},set"~standard"(e){b.own(this,"~standard",e)},parse:function e(t,r){return Zd(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await Fd(this,t,r,{callee:e})},safeParse(e,t){return Vd(this,e,t)},async safeParseAsync(e,t){return Jd(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){b.own(this,"spa",e)},validate(e,t){return $r(this,e,t)},validateAsync(e,t){return _r(this,e,t)},encode:function e(t,r){return Kd(this,t,r,{callee:e})},decode:function e(t,r){return Bd(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await Wd(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Gd(this,t,r,{callee:e})},safeEncode(e,t){return qd(this,e,t)},safeDecode(e,t){return Hd(this,e,t)},async safeEncodeAsync(e,t){return Xd(this,e,t)},async safeDecodeAsync(e,t){return Yd(this,e,t)},toJSONSchema(e){return ed(this,{})(e)},get description(){return de.get(this)?.description},get _def(){return this._zod.def}}),ua=h("_ZodString",(e,t)=>{Et.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rd(e,r,o,n)},b.derived({format:e=>ae(e).format??null,minLength:e=>ae(e).minimum??null,maxLength:e=>ae(e).maximum??null},{regex(...e){return this.check(zn(...e))},includes(...e){return this.check(An(...e))},startsWith(...e){return this.check(Tn(...e))},endsWith(...e){return this.check(On(...e))},min(...e){return this.check(st(...e))},max(...e){return this.check(Ft(...e))},length(...e){return this.check(Vt(...e))},nonempty(...e){return this.check(st(1,...e))},lowercase(e){return this.check(Pn(e))},uppercase(e){return this.check(jn(e))},trim(){return this.check(Cn())},normalize(...e){return this.check(Un(...e))},toLowerCase(){return this.check(En())},toUpperCase(){return this.check(Rn())},slugify(){return this.check(Mn())}})),Kn=h("ZodString",(e,t)=>{Et.init(e,t),ua.init(e,t)},{email(e){return this.check(Po(la,e))},url(e){return this.check(Lr(qr,e))},jwt(e){return this.check(Go(Ia,e))},emoji(e){return this.check(Do(pa,e))},guid(e){return this.check(jo(da,e))},uuid(e){return this.check(Ao(Ge,e))},uuidv4(e){return this.check(To(Ge,e))},uuidv6(e){return this.check(Oo(Ge,e))},uuidv7(e){return this.check(No(Ge,e))},nanoid(e){return this.check(Uo(fa,e))},cuid(e){return this.check(Co(ma,e))},cuid2(e){return this.check(Eo(ga,e))},ulid(e){return this.check(Ro(ha,e))},base64(e){return this.check(Ko(ka,e))},base64url(e){return this.check(Bo(wa,e))},xid(e){return this.check(Mo(va,e))},ksuid(e){return this.check(Lo(ya,e))},ipv4(e){return this.check(Zo(ba,e))},ipv6(e){return this.check(Fo($a,e))},cidrv4(e){return this.check(Vo(_a,e))},cidrv6(e){return this.check(Jo(xa,e))},e164(e){return this.check(Wo(Sa,e))},datetime(e){return this.check(Zr(wt,e))},date(e){return this.check(Fr(St,e))},time(e){return this.check(Vr(It,e))},duration(e){return this.check(Jr(zt,e))}});function Wr(e){return hl(Kn,e)}var G=h("ZodStringFormat",(e,t)=>{J.init(e,t),ua.init(e,t)}),wt=h("ZodISODateTime",(e,t)=>{au.init(e,t),G.init(e,t)}),St=h("ZodISODate",(e,t)=>{su.init(e,t),G.init(e,t)}),It=h("ZodISOTime",(e,t)=>{cu.init(e,t),G.init(e,t)}),zt=h("ZodISODuration",(e,t)=>{uu.init(e,t),G.init(e,t)}),la=h("ZodEmail",(e,t)=>{qc.init(e,t),G.init(e,t)});function Oh(e){return Po(la,e)}var da=h("ZodGUID",(e,t)=>{Wc.init(e,t),G.init(e,t)});function Nh(e){return jo(da,e)}var Ge=h("ZodUUID",(e,t)=>{Gc.init(e,t),G.init(e,t)});function Dh(e){return Ao(Ge,e)}function Uh(e){return To(Ge,e)}function Ch(e){return Oo(Ge,e)}function Eh(e){return No(Ge,e)}var qr=h("ZodURL",(e,t)=>{Yc.init(e,t),G.init(e,t)});function Rh(e){return Lr(qr,e)}function Mh(e){return Lr(qr,{protocol:xr,hostname:uc,...b.normalizeParams(e)})}var pa=h("ZodEmoji",(e,t)=>{Qc.init(e,t),G.init(e,t)});function Lh(e){return Do(pa,e)}var fa=h("ZodNanoID",(e,t)=>{eu.init(e,t),G.init(e,t)});function Zh(e){return Uo(fa,e)}var ma=h("ZodCUID",(e,t)=>{tu.init(e,t),G.init(e,t)});function Fh(e){return Co(ma,e)}var ga=h("ZodCUID2",(e,t)=>{nu.init(e,t),G.init(e,t)});function Vh(e){return Eo(ga,e)}var ha=h("ZodULID",(e,t)=>{ru.init(e,t),G.init(e,t)});function Jh(e){return Ro(ha,e)}var va=h("ZodXID",(e,t)=>{iu.init(e,t),G.init(e,t)});function Kh(e){return Mo(va,e)}var ya=h("ZodKSUID",(e,t)=>{ou.init(e,t),G.init(e,t)});function Bh(e){return Lo(ya,e)}var ba=h("ZodIPv4",(e,t)=>{lu.init(e,t),G.init(e,t)});function Wh(e){return Zo(ba,e)}var Qd=h("ZodMAC",(e,t)=>{pu.init(e,t),G.init(e,t)});function Gh(e){return yl(Qd,e)}var $a=h("ZodIPv6",(e,t)=>{du.init(e,t),G.init(e,t)});function qh(e){return Fo($a,e)}var _a=h("ZodCIDRv4",(e,t)=>{fu.init(e,t),G.init(e,t)});function Hh(e){return Vo(_a,e)}var xa=h("ZodCIDRv6",(e,t)=>{mu.init(e,t),G.init(e,t)});function Xh(e){return Jo(xa,e)}var ka=h("ZodBase64",(e,t)=>{gu.init(e,t),G.init(e,t)});function Yh(e){return Ko(ka,e)}var wa=h("ZodBase64URL",(e,t)=>{hu.init(e,t),G.init(e,t)});function Qh(e){return Bo(wa,e)}var Sa=h("ZodE164",(e,t)=>{vu.init(e,t),G.init(e,t)});function ev(e){return Wo(Sa,e)}var ep=h("ZodCreditCard",(e,t)=>{yu.init(e,t),G.init(e,t)});function tv(e){return bl(ep,e)}var tp=h("ZodIBAN",(e,t)=>{bu.init(e,t),G.init(e,t)});function nv(e){return $l(tp,e)}var Ia=h("ZodJWT",(e,t)=>{$u.init(e,t),G.init(e,t)});function rv(e){return Go(Ia,e)}var Gt=h("ZodCustomStringFormat",(e,t)=>{_u.init(e,t),G.init(e,t)});function iv(e,t,r={}){return Jt(Gt,e,t,r)}function ov(e){return Jt(Gt,"hostname",cc,e)}function av(e){return Jt(Gt,"hex",kc,e)}function sv(e){return Jt(Gt,"currency_code",dc,e)}function cv(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Ee[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Jt(Gt,o,n,t)}var Bn=h("ZodNumber",(e,t)=>{co.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>id(e,r,o,n),e.isFinite=!0},b.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=ae(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=ae(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=ae(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>ae(e).format??null},{gt(e,t){return this.check(Be(e,t))},gte(e,t){return this.check(Oe(e,t))},min(e,t){return this.check(Oe(e,t))},lt(e,t){return this.check(Ke(e,t))},lte(e,t){return this.check(Te(e,t))},max(e,t){return this.check(Te(e,t))},int(e){return this.check(sa(e))},safe(e){return this.check(sa(e))},positive(e){return this.check(Be(0,e))},nonnegative(e){return this.check(Oe(0,e))},negative(e){return this.check(Ke(0,e))},nonpositive(e){return this.check(Te(0,e))},multipleOf(e,t){return this.check(bt(e,t))},step(e,t){return this.check(bt(e,t))},finite(){return this}}));function np(e){return xl(Bn,e)}var qt=h("ZodNumberFormat",(e,t)=>{xu.init(e,t),Bn.init(e,t)});function sa(e){return wl(qt,e)}function uv(e){return Sl(qt,e)}function lv(e){return Il(qt,e)}function dv(e){return zl(qt,e)}function pv(e){return Pl(qt,e)}var Wn=h("ZodBoolean",(e,t)=>{Tr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>od(e,r,o,n)});function rp(e){return jl(Wn,e)}var Gn=h("ZodBigInt",(e,t)=>{uo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ad(e,r,o,n)},b.derived({minValue:e=>ae(e).minimum??null,maxValue:e=>ae(e).maximum??null,format:e=>ae(e).format??null},{gte(e,t){return this.check(Oe(e,t))},min(e,t){return this.check(Oe(e,t))},gt(e,t){return this.check(Be(e,t))},lt(e,t){return this.check(Ke(e,t))},lte(e,t){return this.check(Te(e,t))},max(e,t){return this.check(Te(e,t))},positive(e){return this.check(Be(BigInt(0),e))},negative(e){return this.check(Ke(BigInt(0),e))},nonpositive(e){return this.check(Te(BigInt(0),e))},nonnegative(e){return this.check(Oe(BigInt(0),e))},multipleOf(e,t){return this.check(bt(e,t))}}));function fv(e){return Tl(Gn,e)}var za=h("ZodBigIntFormat",(e,t)=>{ku.init(e,t),Gn.init(e,t)});function mv(e){return Nl(za,e)}function gv(e){return Dl(za,e)}var ip=h("ZodSymbol",(e,t)=>{wu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sd(e,r,o,n)});function hv(e){return Ul(ip,e)}var op=h("ZodUndefined",(e,t)=>{Su.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ud(e,r,o,n)});function vv(e){return Cl(op,e)}var ap=h("ZodNull",(e,t)=>{Iu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>cd(e,r,o,n)});function sp(e){return El(ap,e)}var cp=h("ZodAny",(e,t)=>{zu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pd(e,r,o,n)});function yv(){return Rl(cp)}var up=h("ZodUnknown",(e,t)=>{Pu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>fd(e,r,o,n)});function Kt(){return Ml(up)}var lp=h("ZodNever",(e,t)=>{ju.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>dd(e,r,o,n)});function Pa(e){return Ll(lp,e)}var dp=h("ZodVoid",(e,t)=>{Au.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ld(e,r,o,n)});function bv(e){return Zl(dp,e)}var Hr=h("ZodDate",(e,t)=>{Tu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>md(e,r,o,n),e.min=(r,o)=>e.check(Oe(r,o)),e.max=(r,o)=>e.check(Te(r,o))},b.derived({minDate:e=>{let{minimum:t}=ae(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=ae(e);return t?new Date(t):null}},{}));function $v(e){return Fl(Hr,e)}var pp=h("ZodArray",(e,t)=>{Wt(),Nu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Id(e,r,o,n),e.element=t.element},{min(e,t){return this.check(st(e,t))},nonempty(e){return this.check(st(1,e))},max(e,t){return this.check(Ft(e,t))},length(e,t){return this.check(Vt(e,t))},unwrap(){return this.element}});function Xr(e,t){return Kl(pp,e,t)}function _v(e){let t=e._zod.def.shape;return ja(Object.keys(t))}var Yr=h("ZodObject",(e,t)=>{Wt(),Du.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zd(e,r,o,n),b.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return ja(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:Kt()}))},loose(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Kt()}))},strict(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Pa()}))},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(ei,this,e[0])},exactPartial(...e){return b.partial(Ta,this,e[0],"exactPartial")},required(...e){return b.required(Oa,this,e[0])}});function xv(e,t){let r={type:"object",shape:e??{},...b.normalizeParams(t)};return new Yr(r)}function kv(e,t){return new Yr({type:"object",shape:e,catchall:Pa(),...b.normalizeParams(t)})}function wv(e,t){return new Yr({type:"object",shape:e,catchall:Kt(),...b.normalizeParams(t)})}var Qr=h("ZodUnion",(e,t)=>{Or.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ta(e,r,o,n),e.options=t.options});function qn(e,t){return new Qr({type:"union",options:e,...b.normalizeParams(t)})}var fp=h("ZodXor",(e,t)=>{Qr.init(e,t),Uu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ta(e,r,o,n),e.options=t.options});function Sv(e,t){return new fp({type:"union",options:e,inclusive:!1,...b.normalizeParams(t)})}var mp=h("ZodDiscriminatedUnion",(e,t)=>{Qr.init(e,t),Eu.init(e,t)});function Iv(e,t,r){return new mp({type:"union",options:t,discriminator:e,...b.normalizeParams(r)})}var gp=h("ZodIntersection",(e,t)=>{Ru.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pd(e,r,o,n)});function hp(e,t){return new gp({type:"intersection",left:e,right:t})}var vp=h("ZodTuple",(e,t)=>{Wt(),lo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jd(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 ei({type:"optional",innerType:t}))})}});function yp(e,t,r){let o=t instanceof U,n=o?r:t,i=o?t:null;return new vp({type:"tuple",items:e,rest:i,...b.normalizeParams(n)})}var Vn=h("ZodRecord",(e,t)=>{Wt(),Mu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ad(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function bp(e,t,r){return!t||!t._zod?new Vn({type:"record",keyType:Wr(),valueType:e,...b.normalizeParams(t)}):new Vn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r)})}function zv(e,t,r){return new Vn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r),partial:!0})}function Pv(e,t,r){return new Vn({type:"record",keyType:e,valueType:t,mode:"loose",...b.normalizeParams(r)})}var $p=h("ZodMap",(e,t)=>{Wt(),Lu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(We(...r)),e.nonempty=r=>e.check(We(1,r)),e.max=(...r)=>e.check($t(...r)),e.size=(...r)=>e.check(Zt(...r))});function jv(e,t,r){return new $p({type:"map",keyType:e,valueType:t,...b.normalizeParams(r)})}var _p=h("ZodSet",(e,t)=>{Wt(),Zu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sd(e,r,o,n),e.min=(...r)=>e.check(We(...r)),e.nonempty=r=>e.check(We(1,r)),e.max=(...r)=>e.check($t(...r)),e.size=(...r)=>e.check(Zt(...r))});function Av(e,t){return new _p({type:"set",valueType:e,...b.normalizeParams(t)})}var Jn=h("ZodEnum",(e,t)=>{Fu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(o,n,i)=>gd(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 Jn({...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 Jn({...t,checks:[],...b.normalizeParams(n),entries:i})}});function ja(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Jn({type:"enum",entries:r,...b.normalizeParams(t)})}function Tv(e,t){return new Jn({type:"enum",entries:e,...b.normalizeParams(t)})}var xp=h("ZodLiteral",(e,t)=>{Vu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hd(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 Ov(e,t){return new xp({type:"literal",values:Array.isArray(e)?e:[e],...b.normalizeParams(t)})}var kp=h("ZodFile",(e,t)=>{Ju.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bd(e,r,o,n),e.min=(r,o)=>e.check(We(r,o)),e.max=(r,o)=>e.check($t(r,o)),e.mime=(r,o)=>e.check(Dn(Array.isArray(r)?r:[r],o))});function Nv(e){return Bl(kp,e)}var wp=h("ZodTransform",(e,t)=>{Wt(),Ku.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kd(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new vt(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 Aa(e){return new wp({type:"transform",transform:e})}var ei=h("ZodOptional",(e,t)=>{po.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>na(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Bt(e){return new ei({type:"optional",innerType:e})}var Ta=h("ZodExactOptional",(e,t)=>{Bu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>na(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Sp(e){return new Ta({type:"optional",innerType:e})}var Ip=h("ZodNullable",(e,t)=>{Wu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Td(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Gr(e){return new Ip({type:"nullable",innerType:e})}function Dv(e){return Bt(Gr(e))}var zp=h("ZodDefault",(e,t)=>{Gu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Pp(e,t){return new zp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var jp=h("ZodPrefault",(e,t)=>{qu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ud(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ap(e,t){return new jp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var Oa=h("ZodNonOptional",(e,t)=>{Hu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Od(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Tp(e,t){return new Oa({type:"nonoptional",innerType:e,...b.normalizeParams(t)})}var Op=h("ZodSuccess",(e,t)=>{Xu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$d(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Uv(e){return new Op({type:"success",innerType:e})}var Np=h("ZodCatch",(e,t)=>{Yu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Dp(e,t){return new Np({type:"catch",innerType:e,catchValue:typeof t=="function"?t:b.constantCatch(t)})}var Up=h("ZodNaN",(e,t)=>{Qu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vd(e,r,o,n)});function Cv(e){return Jl(Up,e)}var ti=h("ZodPipe",(e,t)=>{fo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ed(e,r,o,n),e.in=t.in,e.out=t.out});function ca(e,t){return new ti({type:"pipe",in:e,out:t})}var ni=h("ZodCodec",(e,t)=>{ti.init(e,t),Nr.init(e,t)});function Ev(e,t,r){return new ni({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function Rv(e){let t=e._zod.def;return new ni({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var Cp=h("ZodPreprocess",(e,t)=>{ti.init(e,t),el.init(e,t)}),Ep=h("ZodReadonly",(e,t)=>{tl.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Rp(e){return new Ep({type:"readonly",innerType:e})}var Mp=h("ZodTemplateLiteral",(e,t)=>{nl.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yd(e,r,o,n)});function Mv(e,t){return new Mp({type:"template_literal",parts:e,...b.normalizeParams(t)})}var Lp=h("ZodLazy",(e,t)=>{Dr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ld(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Zp(e){return new Lp({type:"lazy",getter:e})}var Fp=h("ZodPromise",(e,t)=>{il.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Md(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Lv(e){return new Fp({type:"promise",innerType:e})}var Vp=h("ZodFunction",(e,t)=>{rl.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xd(e,r,o,n)});function Zv(e){return new Vp({type:"function",input:Array.isArray(e?.input)?yp(e?.input):e?.input??Xr(Kt()),output:e?.output??Kt()})}var ri=h("ZodCustom",(e,t)=>{ol.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_d(e,r,o,n)});function Fv(e){let t=new q({check:"custom"});return t._zod.check=e,t}function Vv(e,t){return Wl(ri,e??(()=>!0),t)}function Jp(e,t={}){return Gl(ri,e,t)}function Kp(e,t){return ql(e,t)}var Jv=Hl,Kv=Xl,Bp=h("ZodInstanceOf",(e,t)=>{ri.init(e,t)},{properties(e,t){return this.check(Nn(e,t))}});function Bv(e,t={}){let r=new Bp({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 Wv=(...e)=>Yl({Codec:ni,Boolean:Wn,String:Kn},...e);function Gv(e){let t=Zp(()=>qn([Wr(e),np(),rp(),sp(),Xr(t),bp(Wr(),t)]));return t}function qv(e,t){return new Cp({type:"pipe",in:Aa(e),out:t})}var xS={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 kS(e){ne({customError:e})}function wS(){return ne().customError}var Wp;Wp||(Wp={});var ii={};rt(ii,{ZodISODate:()=>St,ZodISODateTime:()=>wt,ZodISODuration:()=>zt,ZodISOTime:()=>It,date:()=>IS,datetime:()=>SS,duration:()=>PS,time:()=>zS});function SS(e){return Zr(wt,e)}function IS(e){return Fr(St,e)}function zS(e){return Vr(It,e)}function PS(e){return Jr(zt,e)}var z={...Hn,...oa,iso:ii},jS=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 AS(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 Hv(e,t){return e.map((r,o)=>o<t?r:r.optional())}function TS(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function OS(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:TS(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 NS(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 s=t.keySchema.safeParse(a);s.success||o.issues.push({code:"invalid_key",origin:"record",issues:s.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function Gp(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 s=Gp(a,t);if(s===null)return null;i.push(s)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let a=Gp(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 DS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),US=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function oi(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(oi):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>DS.has(t)?oi(r):!US.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(oi))}function Xv(e){return e===1?"element":"elements"}function CS(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 s=Gp(n[a],new Set);if(s===null)continue;let u=i.get(s);if(u===void 0){i.set(s,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,s=0;for(let u of n)if(t.containsSchema.safeParse(u).success&&++s>=a)break;s<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${Xv(i)}; found ${s}`,input:n,continue:!0}),t.maxContains!==void 0&&s>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${Xv(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Yv(e,t){if(e!==!1)return e===void 0||e===!0?z.any():_e(e,t)}var ES=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Qv(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=OS(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 Qv(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(ES)):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||[]),s=typeof e.additionalProperties=="object"?_e(e.additionalProperties,t):void 0;for(let[p,m]of Object.entries(i)){let f=_e(m,t);le(n,p,a.has(p)?f:f.optional())}if(e.patternProperties){let p=e.patternProperties,m=Object.keys(p),f=[];for(let y of m){let x=_e(p[y],t),I=z.string().regex(new RegExp(y));f.push(z.looseRecord(I,x))}let g=[];if(Object.keys(n).length>0&&g.push(z.object(n).passthrough()),g.push(...f),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 x=2;x<g.length;x++)y=z.intersection(y,g[x]);o=y}if(e.additionalProperties===!1){let y=Object.keys(n),x=m.map(S=>new RegExp(S)),I=o;o=o.check(S=>{if(!Ue(S.value))return;let T=[];for(let P of Object.keys(S.value))y.includes(P)||x.some(C=>C.test(P))||T.push(P);T.length&&S.issues.push({code:"unrecognized_keys",keys:T,input:S.value,inst:I})})}}else{let p=z.object(n);e.additionalProperties===!1?o=p.strict():s?o=p.catchall(s):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 m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=_e(m,t)}o=NS(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,s=n.map(p=>_e(p,t)),u=Hv(s,a),l=Array.isArray(i)?void 0:Yv(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,s=i.map(p=>_e(p,t)),u=Hv(s,a),l=Yv(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),s=z.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=z.array(z.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=CS(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=Qv(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(l=>_e(l,t)),u=z.union(s);r=o?z.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(l=>_e(l,t)),u=z.xor(s);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 s=o?r:_e(e.allOf[0],t),u=o?0:1;for(let l=u;l<e.allOf.length;l++)s=z.intersection(s,_e(e.allOf[l],t));r=s}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 s of i)s in e&&(n[s]=e[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in e&&(n[s]=e[s]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!oi(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let s of["minProperties","maxProperties"])e[s]!==void 0&&(n[s]=e[s])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!oi(e.contains)&&(n.contains=e.contains);for(let s of["uniqueItems","minContains","maxContains"])e[s]!==void 0&&(n[s]=e[s])}for(let s of Object.keys(e))jS.has(s)||le(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function ey(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=AS(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??de};return _e(r,i)}var ty=Symbol("z.visit/resolving");function ai(e,t){let r=typeof t=="function"?t:(a,s)=>{let u=t[a._zod.def.type];return u?u(a,s):a},o=new Map;function n(a){let s=o.get(a);if(s===ty)return new Dr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,ty);let u=i(a),l=r(u,u!==a);return o.set(a,l),l}function i(a){let s=a._zod.def,u=s.type;switch(u){case"object":{let l=s.shape,d=Object.keys(l),p=!1,m={};for(let g of d){let y=n(l[g]);y!==l[g]&&(p=!0),m[g]=y}let f=s.catchall;return s.catchall&&(f=n(s.catchall),f!==s.catchall&&(p=!0)),p?V(a,{...s,shape:m,catchall:f}):a}case"array":{let l=n(s.element);return l===s.element?a:V(a,{...s,element:l})}case"tuple":{let l=s.items,d=!1,p=[];for(let f of l){let g=n(f);g!==f&&(d=!0),p.push(g)}let m=s.rest;return s.rest&&(m=n(s.rest),m!==s.rest&&(d=!0)),d?V(a,{...s,items:p,rest:m}):a}case"record":case"map":{let l=n(s.keyType),d=n(s.valueType);return l===s.keyType&&d===s.valueType?a:V(a,{...s,keyType:l,valueType:d})}case"set":{let l=n(s.valueType);return l===s.valueType?a:V(a,{...s,valueType:l})}case"union":{let l=s.options,d=!1,p=[];for(let m of l){let f=n(m);f!==m&&(d=!0),p.push(f)}return d?V(a,{...s,options:p}):a}case"intersection":{let l=n(s.left),d=n(s.right);return l===s.left&&d===s.right?a:V(a,{...s,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(s.innerType);return l===s.innerType?a:V(a,{...s,innerType:l})}case"pipe":{let l=n(s.in),d=n(s.out);return l===s.in&&d===s.out?a:V(a,{...s,in:l,out:d})}case"function":{let l=n(s.input),d=n(s.output);return l===s.input&&d===s.output?a:V(a,{...s,input:l,output:d})}case"lazy":{let l=s.getter,{_cachedInner:d,...p}=s;return V(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 ny(e){return ai(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:qn(r.options)}})}function RS(e,t){if(!t?.length)return e;let r=e._zod.def;return V(e,Le(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function ry(e){return RS(e.out,e.checks)}function MS(e){return e.in._zod.traits.has("$ZodTransform")?ry(e):e.in}function iy(e){return ai(e,{pipe:t=>MS(t._zod.def),default:(t,r)=>r?Bt(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function oy(e){return ai(e,{pipe:t=>ry(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var qp={};rt(qp,{bigint:()=>VS,boolean:()=>FS,date:()=>JS,number:()=>ZS,string:()=>LS});function LS(e){return vl(Kn,e)}function ZS(e){return kl(Bn,e)}function FS(e){return Al(Wn,e)}function VS(e){return Ol(Gn,e)}function JS(e){return Vl(Hr,e)}var Xn=c.string().min(1).max(512).refine(KS,"Invalid path: use segments like notes/plan.md, without .. or a leading /");function KS(e){return/[\u0000-\u001f\u007f\\]/.test(e)?!1:e.split("/").every(r=>r.length>0&&r.length<=255&&r!=="."&&r!=="..")}var si=c.string().regex(me("message")),H=c.string().regex(me("thread")),Pe=c.string().regex(me("project")),je=c.string().regex(me("task")),Hp=c.string().regex(me("artifact")),R=c.iso.datetime(),ci=c.enum(["user","agent","system"]),BS=c.object({path:Xn,name:c.string(),size:c.number().int().nonnegative(),contentType:c.string()}),WS=c.object({artifactId:Hp,version:c.number().int().positive(),title:c.string()}),ay=c.enum(["cloud","local"]),X=c.number().int().nonnegative(),GS=c.object({title:c.string(),harness:c.string(),runtime:ay,model:c.string().nullable(),durationMs:X,inputTokens:X,outputTokens:X,costMicros:X.nullable()}),qS=c.object({chars:X,limit:X,parts:c.object({instructions:X,skills:X,knowledge:X,brief:X,conversation:X,notes:X,other:X}),droppedMessages:X,droppedNotes:X,cut:c.boolean()}),HS=c.object({model:c.string(),durationMs:X,calls:X,inputTokens:X,cachedInputTokens:X,outputTokens:X,costMicros:X.nullable(),runtime:ay,computer:c.string().optional(),harness:c.string().optional(),task:GS.optional(),prompt:qS.optional()}),XS=c.enum(["brief","follow_up","reply","relay","answer"]),YS=c.object({kind:XS,threadId:H,fromThreadId:H.optional(),note:c.string()}),Na=8,Ht=c.object({id:si,projectId:Pe,threadId:H.nullable(),authorKind:ci,authorId:c.string().min(1),body:c.string(),attachments:c.array(BS).optional(),artifacts:c.array(WS).optional(),stats:HS.optional(),relay:YS.optional(),clis:c.array(c.string().max(40)).max(Na).optional(),seq:c.number().int().positive(),createdAt:R,editedAt:R.optional()}),QS=c.enum(["working","blocked","review_ready","done","failed"]),eI=c.object({id:c.string().max(40),options:c.array(c.string().max(40)).max(Na),by:c.enum(["person","coordinator"]),reason:c.string().max(300).nullable()}),tI=c.object({cli:c.string().max(40),model:c.string().max(200).nullable(),effort:c.string().max(20).nullable()}),sy="cloud",nI=c.object({id:c.string().max(60),by:c.enum(["person","auto","coordinator"]),reason:c.string().max(300).nullable().default(null)}),Xp=c.enum(["duplicate","misrouted","cancelled"]),rI=c.object({replies:X,usage:c.object({tokens:X,durationMs:X,costMicros:X.nullable()}).nullable(),planMessageId:si.nullable()}),Yp=c.object({id:H,projectId:Pe,rootMessageId:si,ackMessageId:si.nullable().default(null),title:c.string(),status:QS,statusText:c.string().nullable(),resolved:c.boolean(),closeReason:Xp.nullable().default(null),duplicateOf:H.nullable().default(null),label:c.string().nullable(),cli:eI.nullable().default(null),runner:nI.nullable().default(null),model:tI.nullable().default(null),seenSeq:c.number().int().nonnegative().nullable().default(null),summary:rI.nullable().default(null),createdAt:R,updatedAt:R}),iI=c.enum(["running","done","failed","cancelled"]),cy=c.object({id:je,threadId:H,title:c.string(),harness:c.string(),backend:c.string(),status:iI,prUrl:c.string().nullable(),summary:c.string().nullable(),createdAt:R,finishedAt:R.nullable()}),oD=c.object({ref:c.string(),commits:c.array(c.object({hash:c.string(),message:c.string(),at:c.string()})),entries:c.array(c.object({name:c.string(),path:c.string(),type:c.enum(["file","folder"])})).nullable(),file:c.object({path:c.string(),text:c.string().nullable(),size:c.number(),truncated:c.boolean()}).nullable()}),Qp=c.object({id:c.string().min(1).max(200),label:c.string().max(100),state:c.enum(["started","done","failed"]).optional(),model:c.string().max(200).optional(),tokens:c.number().int().nonnegative().optional()}),uy=c.object({stream:c.enum(["stdout","stderr","system"]),text:c.string(),at:c.number().optional(),ms:c.number().nonnegative().optional(),tool:c.boolean().optional(),agent:Qp.optional()}),ef=c.object({messageId:si,emoji:c.string().min(1).max(32),authorKind:ci,authorId:c.string().min(1)}),Da=c.enum(["owner","admin","member"]),oI=c.object({working:c.number().int().nonnegative(),waiting:c.number().int().nonnegative()}),aI=c.object({monthMicros:c.number().int().nonnegative(),totalMicros:c.number().int().nonnegative()}),Ua=c.enum(["indigo","blue","teal","green","amber","orange","red","pink","purple","gray"]),Ca=c.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"]),aD=c.object({id:Pe,name:c.string().min(1).max(120),role:Da,icon:Ca.nullable().optional(),color:Ua.nullable().optional(),createdAt:R,activity:oI.optional(),cost:aI.optional(),pinned:c.boolean().optional()}),sD=c.object({pinned:c.boolean()}),cD=c.object({name:c.string().trim().min(1).max(120)}),uD=c.object({id:c.string(),name:c.string(),role:Da,email:c.string().optional()}),tf=32e3,sI=c.object({id:c.number().int(),accountLogin:c.string(),accountType:c.enum(["User","Organization"]),accountAvatarUrl:c.string().nullable()}),lD=c.object({configured:c.boolean(),installUrl:c.string().nullable(),installations:c.array(sI)}),dD=c.object({id:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),description:c.string().nullable()}),pD=c.object({repoId:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),createdAt:R}),ly=c.object({repo:c.string(),number:c.number().int(),url:c.string(),threadId:H,title:c.string(),state:c.enum(["open","closed","merged"]),draft:c.boolean(),checks:c.enum(["pending","success","failure"]).nullable(),review:c.enum(["approved","changes_requested"]).nullable(),conflict:c.boolean().default(!1),branch:c.string().default(""),additions:c.number().int().nullable().default(null),deletions:c.number().int().nullable().default(null),changedFiles:c.number().int().nullable().default(null),updatedAt:R}),cI=c.object({path:c.string(),previousPath:c.string().nullable(),status:c.enum(["added","removed","modified","renamed","copied","changed","unchanged"]),additions:c.number().int(),deletions:c.number().int(),patch:c.string().nullable()}),fD=c.object({files:c.array(cI),truncated:c.boolean()}),dy=c.enum(["merge","squash","rebase"]),mD=c.object({permitted:c.boolean(),blocked:c.enum(["closed","draft","conflict","checks_failed","checks_pending","changes_requested","protected","checking"]).nullable(),methods:c.array(dy),sha:c.string()}),gD=c.object({method:dy,sha:c.string().min(1),deleteBranch:c.boolean().default(!1)}),hD=c.object({merged:c.literal(!0),branchDeleted:c.boolean(),branchKept:c.enum(["fork","default","protected","gone","in_use","reopened","failed"]).nullable()}),vD=c.object({installationId:c.number().int().positive(),repoId:c.number().int().positive()});var uI=16e3,lI=16e3,xD=25*1024*1024,py=10;var kD=c.object({path:Xn,size:c.number().int().nonnegative(),contentType:c.string(),updatedAt:R,updatedByKind:ci,updatedBy:c.string()}),dI=c.string().trim().min(1).max(80).regex(/^[\p{L}\p{N}][\p{L}\p{N} _.-]*$/u,"Use letters, numbers, spaces, dots, dashes or underscores"),pI=c.enum(["ok","stale"]),fI=c.object({name:dI,description:c.string().max(300),content:c.string().max(lI),updatedAt:R,updatedByKind:ci,updatedBy:c.string(),status:pI.default("ok"),staleReason:c.string().max(300).nullable().default(null),verifiedAt:R.nullable().default(null),previousContent:c.string().nullable().default(null),previousAt:R.nullable().default(null)}),wD=fI.pick({description:!0,content:!0}),SD=c.discriminatedUnion("status",[c.object({status:c.literal("ok")}),c.object({status:c.literal("stale"),reason:c.string().trim().min(1).max(300)})]),mI=c.object({text:c.string().max(uI),updatedAt:R.nullable(),updatedBy:c.string().nullable()}),ID=mI.pick({text:!0}),fy=c.enum(["files","memory","instructions"]),my=c.enum(["auto","on","off"]),zD=c.object({mode:my,active:c.boolean(),lastRunAt:R.nullable(),threadsSince:c.number().int().nonnegative(),threadsNeeded:c.number().int().positive(),threadId:c.string().nullable()}),PD=c.object({mode:my});var nf=c.object({id:Hp,projectId:Pe,threadId:H.nullable(),title:c.string(),description:c.string().nullable(),version:c.number().int().positive(),createdAt:R,updatedAt:R}),OD=c.object({version:c.number().int().positive(),size:c.number().int().nonnegative(),threadId:H.nullable(),createdAt:R}),ND=c.object({version:c.number().int().positive(),url:c.string().nullable(),expiresAt:R.nullable()}),DD=2*1024*1024;var rf=c.string().regex(me("routine")),gI=/^(\*|\d+(-\d+)?)(\/\d+)?(,(\*|\d+(-\d+)?)(\/\d+)?)*$/,hI=c.string().trim().refine(e=>{let t=e.split(/\s+/);return t.length===5&&t.every(r=>gI.test(r))},"Expected a five-field cron expression, e.g. 0 9 * * 1-5"),vI=c.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}},"Unknown time zone"),of=c.discriminatedUnion("kind",[c.object({kind:c.literal("cron"),cron:hI,timezone:vI.default("UTC")}),c.object({kind:c.literal("once"),at:R})]),af=c.discriminatedUnion("kind",[c.object({kind:c.literal("coordinator")}),c.object({kind:c.literal("thread"),threadId:H})]),sf=c.object({id:rf,projectId:Pe,name:c.string(),prompt:c.string(),target:af,schedule:of,paused:c.boolean(),nextRunAt:R.nullable(),lastRunAt:R.nullable(),runCount:c.number().int().nonnegative(),createdBy:c.string(),createdAt:R});var MD=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:af.default({kind:"coordinator"}),schedule:of}),LD=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:af,schedule:of,paused:c.boolean()}).partial();var cf=c.object({text:c.string(),until:c.string(),createdBy:c.string(),createdAt:c.string(),wakes:c.number().int().nonnegative(),threads:c.number().int().nonnegative(),idle:c.number().int().nonnegative()});var yI=c.string().regex(me("sshHost")),uf=c.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Use lowercase letters, digits, - and _ (up to 40)."),Ea=c.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."),gy=c.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/,"Enter the user name on the server."),hy=c.enum(["ask","off"]),WD=c.string().max(16e3).regex(/^(?:ssh|ecdsa|sk)-[\w@.-]+ [A-Za-z0-9+/=]+(?: .*)?$/),vy=c.string().max(200).regex(/^SHA256:[A-Za-z0-9+/=]+$/),bI=c.object({id:yI,projectId:Pe,alias:uf,host:c.string(),port:c.number().int(),user:c.string(),runnerId:c.string(),runnerName:c.string(),mine:c.boolean(),keySource:c.enum(["new","existing"]),publicKey:c.string().nullable(),keyFingerprint:c.string().nullable(),hostFingerprint:c.string().nullable(),rule:hy,testedAt:R.nullable(),createdAt:R}),$I=c.object({id:c.string(),alias:c.string(),threadId:c.string().nullable(),command:c.string(),reason:c.string().nullable(),decision:c.enum(["once","turn","deny","timeout","failed"]),approvedBy:c.string().nullable(),exitCode:c.number().int().nullable(),ms:c.number().int().nullable(),at:R}),GD=c.object({hosts:c.array(bI),history:c.array($I)}),qD=c.object({runnerId:c.string(),alias:uf,host:Ea,port:c.number().int().min(1).max(65535).default(22),user:gy,existingKey:c.string().min(1).max(1024).optional()}),HD=c.object({rule:hy}),XD=c.object({hostKey:c.string().min(1).max(16e3)}),yy=c.object({type:c.string().max(60),key:c.string().max(16e3),fingerprint:vy}),by=c.object({path:c.string().max(1024),name:c.string().max(255),type:c.string().max(60),fingerprint:vy,comment:c.string().max(500)}),$y=c.object({exitCode:c.number().int().nullable(),stdout:c.string(),stderr:c.string(),truncated:c.boolean(),ms:c.number().int().nonnegative(),error:c.enum(["hostkey","auth","connect","timeout","nokey","other"]).optional()}),_y=300*1e3,xy=200*1024,Ra=c.object({projectId:Pe,alias:uf}),lf=Ra.extend({host:Ea,port:c.number().int().min(1).max(65535),user:gy,hostKey:c.string().min(1).max(16e3)});var Sy=2,ut=c.string().regex(me("runner")),qe=c.enum(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]),Za={claude:"Claude Code",codex:"Codex CLI",antigravity:"Antigravity CLI",opencode:"OpenCode",hermes:"Hermes Agent",cursor:"Cursor CLI",muse:"Muse Code",kimi:"Kimi Code"},Iy=c.object({path:c.string().min(1).max(1024),name:c.string().max(255)}),_I=c.object({kind:c.string().max(40),usedPercent:c.number().min(0).max(1e3).nullable(),resetsAt:R.nullable()}),xI=c.object({status:c.enum(["ok","warning","limited"]).optional(),windows:c.array(_I).max(8),at:R});var kI=c.object({id:c.string().min(1).max(200),name:c.string().max(200),efforts:c.array(c.string().min(1).max(20)).max(10)});var wI=c.object({id:qe,version:c.string().max(200).nullable(),limits:xI.optional().catch(void 0),models:c.array(kI).max(100).optional().catch(void 0)}),SI=c.enum(["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","update","models","github-token","git-token","steer","steer-claude","ssh","stats"]),II=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:c.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}),c.object({transport:c.literal("stdio"),name:c.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),command:c.string().min(1).max(200),args:c.array(c.string().max(2e3)).max(50),env:c.record(c.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),c.string().max(4e3))})]),zI=c.enum(["read","edit","auto","full"]),pf=c.object({access:zI,worktrees:c.boolean(),autoUpdate:c.boolean(),remote:c.boolean()}),zy=pf.omit({remote:!0}).partial(),PI=c.enum(["service","app","manual"]),df=c.object({state:c.enum(["waiting","downloading","restarting","failed","rolled-back"]),version:c.string().max(50),running:c.number().int().nonnegative().optional(),message:c.string().max(500).optional(),at:R}),Py=c.object({version:c.string().max(50),hostname:c.string().max(255),platform:c.string().max(50),folders:c.array(Iy).max(200),clis:c.array(c.unknown()).max(10).transform(e=>e.flatMap(t=>{let r=wI.safeParse(t);return r.success?[r.data]:[]})),features:c.array(c.string().max(50)).max(20).default([]).transform(e=>e.filter(t=>SI.safeParse(t).success)),settings:pf.optional().catch(void 0),updates:PI.optional().catch(void 0),update:df.optional().catch(void 0)}),Xt=c.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),La=c.object({at:R,cpu:c.object({percent:c.number().min(0).max(100).optional(),cores:c.number().int().min(1).max(1024)}),memory:c.object({total:Xt,available:Xt}),swap:c.object({total:Xt,used:Xt}).optional(),disk:c.object({total:Xt,free:Xt}).optional(),tasks:c.number().int().nonnegative().max(1e3),runnerMemory:Xt.optional()}),Ma=1e5,Q=c.string().min(1).max(64),jI=c.object({name:c.string().max(255),path:c.string().max(1024)}),AI=c.object({path:c.string().max(1024),parent:c.string().max(1024).nullable(),home:c.string().max(1024),dirs:c.array(jI).max(1e3)}),ky=c.object({inputTokens:c.number().int().nonnegative(),outputTokens:c.number().int().nonnegative(),model:c.string().max(200).optional()}),ff=512*1024,TI=c.object({path:c.string().max(4096),size:c.number().int().nonnegative(),data:c.string().max(Math.ceil(ff/3)*4+4),truncated:c.boolean()}),OI=c.object({model:c.string().min(1).max(200).optional(),effort:c.string().min(1).max(20).optional()}),wy=c.object({token:c.string().min(20).max(4096),expiresAt:R,repos:c.array(c.string().regex(/^[\w.-]+\/[\w.-]+$/).max(200)).max(100)}),rU=c.discriminatedUnion("type",[Py.extend({type:c.literal("hello"),protocol:c.number().int().positive(),running:c.array(je).max(100).default([]),interrupted:c.array(je).max(100).default([]),stats:La.optional().catch(void 0)}),c.object({type:c.literal("task.progress"),taskId:je,text:c.string().max(2e3),usage:ky.optional(),agent:Qp.optional(),ms:c.number().nonnegative().optional()}),c.object({type:c.literal("task.done"),taskId:je,ok:c.boolean(),usage:ky.optional(),result:c.string().max(Ma),cancelled:c.boolean().optional()}),c.object({type:c.literal("ping"),stats:La.optional().catch(void 0)}),c.object({type:c.literal("task.folders"),taskId:je,folders:c.array(c.string().min(1).max(1024)).max(60)}),AI.extend({type:c.literal("dirs"),requestId:Q}),c.object({type:c.literal("folders"),requestId:Q,folders:c.array(Iy).max(200)}),c.object({type:c.literal("request.failed"),requestId:Q,message:c.string().max(500)}),TI.extend({type:c.literal("file"),requestId:Q}),c.object({type:c.literal("settings"),requestId:Q,settings:pf}),c.object({type:c.literal("update.accepted"),requestId:Q,update:df}),c.object({type:c.literal("update.status"),update:df.nullable()}),c.object({type:c.literal("task.steered"),requestId:Q,taken:c.boolean()}),c.object({type:c.literal("ssh.key"),requestId:Q,publicKey:c.string().max(16e3),fingerprint:c.string().max(200),protected:c.boolean()}),c.object({type:c.literal("ssh.keylist"),requestId:Q,keys:c.array(by).max(100)}),c.object({type:c.literal("ssh.hostkeylist"),requestId:Q,keys:c.array(yy).max(10)}),$y.extend({type:c.literal("ssh.result"),requestId:Q})]),jy=c.discriminatedUnion("type",[c.object({type:c.literal("welcome"),runnerId:ut,name:c.string()}),c.object({type:c.literal("task.start"),taskId:je,threadId:H,folder:c.string().min(1).max(1024),cli:qe,prompt:c.string().min(1).max(Ma),model:OI.optional(),folders:c.array(c.string().min(1).max(1024)).max(50).optional(),agent:c.object({mcpPath:c.string().regex(/^\/api\/[\w/-]+$/).max(300),token:c.string().min(20).max(200),connectors:c.array(II).max(30).optional(),skills:c.object({path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}).optional(),resume:c.object({after:je,prompt:c.string().min(1).max(Ma)}).optional()}).optional(),github:wy.optional()}),c.object({type:c.literal("task.github"),taskId:je,github:wy}),c.object({type:c.literal("task.steer"),requestId:Q,taskId:je,text:c.string().min(1).max(Ma)}),c.object({type:c.literal("task.cancel"),taskId:je}),c.object({type:c.literal("pong")}),c.object({type:c.literal("dirs.list"),requestId:Q,path:c.string().max(1024).optional()}),c.object({type:c.literal("folder.share"),requestId:Q,path:c.string().min(1).max(1024)}),c.object({type:c.literal("folder.unshare"),requestId:Q,path:c.string().min(1).max(1024)}),c.object({type:c.literal("file.read"),requestId:Q,path:c.string().min(1).max(4096),folders:c.array(c.string().min(1).max(1024)).min(1).max(51),threadId:H.optional()}),c.object({type:c.literal("settings.set"),requestId:Q,settings:zy}),c.object({type:c.literal("runner.update"),requestId:Q,version:c.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/).max(50),now:c.boolean().default(!1)}),Ra.extend({type:c.literal("ssh.keygen"),requestId:Q,comment:c.string().max(200),existing:c.string().min(1).max(1024).optional()}),c.object({type:c.literal("ssh.keys"),requestId:Q}),c.object({type:c.literal("ssh.hostkeys"),requestId:Q,host:Ea,port:c.number().int().min(1).max(65535)}),c.object({type:c.literal("ssh.test"),requestId:Q,target:lf}),c.object({type:c.literal("ssh.run"),requestId:Q,target:lf,command:c.string().min(1).max(2e4)}),Ra.extend({type:c.literal("ssh.forget"),requestId:Q})]),NI=Py.extend({id:ut,name:c.string(),version:c.string().nullable(),online:c.boolean(),lastSeenAt:R.nullable(),createdAt:R,stats:La.optional()}),iU=c.object({name:c.string().trim().min(1).max(80).optional(),settings:zy.optional()}),oU=c.object({now:c.boolean().default(!1)}),aU=c.object({runners:c.array(NI),latestVersion:c.string().nullable()}),sU=c.object({code:c.string(),expiresAt:R}),cU=c.object({code:c.string().trim().min(4).max(20),name:c.string().trim().min(1).max(80),hostname:c.string().max(255).default(""),platform:c.string().max(50).default("")}),Ay=c.object({runner:c.object({id:ut,name:c.string()}),token:c.string()}),uU=c.object({projectId:Pe,runnerId:ut,runnerName:c.string(),path:c.string(),folders:c.array(c.string()).default([]),cli:qe,online:c.boolean(),isDefault:c.boolean().default(!0),stats:La.optional()}),lU=c.object({path:c.string().trim().min(1).max(1024)}),dU=c.object({runnerId:ut,path:c.string().min(1).max(1024),cli:qe,add:c.boolean().optional()}),pU=c.object({path:c.string().min(1).max(1024),runnerId:ut.optional()}),fU=c.object({runnerId:ut});function Ty(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 DI=200,UI=c.object({threadId:H.nullable(),hasEarlier:c.boolean()});var kU=c.discriminatedUnion("type",[c.object({type:c.literal("message.send"),clientId:c.string().max(64).optional(),threadId:H.nullable().default(null),body:c.string().trim().max(tf),attachments:c.array(Xn).max(py).default([]),clis:c.array(qe).max(Na).optional()}).refine(e=>e.body.length>0||e.attachments.length>0,"Write something or attach a file"),c.object({type:c.literal("message.edit"),messageId:Ht.shape.id,body:c.string().trim().max(tf)}),c.object({type:c.literal("thread.resolve"),threadId:H,resolved:c.boolean(),reason:Xp.optional()}),c.object({type:c.literal("thread.cli"),threadId:H,cli:qe.nullable()}),c.object({type:c.literal("thread.runner"),threadId:H,runnerId:c.union([ut,c.literal(sy)]).nullable()}),c.object({type:c.literal("thread.model"),threadId:H,cli:qe,model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),c.object({type:c.literal("goal.stop")}),c.object({type:c.literal("sync"),afterSeq:c.number().int().nonnegative(),all:c.boolean().optional(),recent:c.number().int().positive().max(DI).optional()})]),wU=c.discriminatedUnion("type",[c.object({type:c.literal("message.created"),message:Ht}),c.object({type:c.literal("message.updated"),message:Ht}),c.object({type:c.literal("message.ack"),clientId:c.string(),messageId:Ht.shape.id,seq:Ht.shape.seq}),c.object({type:c.literal("sync.result"),messages:c.array(Ht),hasMore:c.boolean(),streamed:c.boolean().optional(),threads:c.array(Yp).default([]),reactions:c.array(ef).default([]),artifacts:c.array(nf).default([]),routines:c.array(sf).default([]),goal:cf.nullable().optional(),windows:c.array(UI).optional(),reset:c.boolean().optional(),lastSeq:c.number().int().nonnegative().optional()}),c.object({type:c.literal("thread.updated"),thread:Yp}),c.object({type:c.literal("reaction.added"),reaction:ef}),c.object({type:c.literal("artifact.updated"),artifact:nf}),c.object({type:c.literal("routine.updated"),routine:sf}),c.object({type:c.literal("routine.deleted"),routineId:rf}),c.object({type:c.literal("goal.updated"),goal:cf.nullable()}),c.object({type:c.literal("agent.activity"),threadId:H.nullable(),active:c.boolean(),label:c.string().max(200).optional()}),c.object({type:c.literal("knowledge.changed"),kind:fy}),c.object({type:c.literal("workspace.changed")}),c.object({type:c.literal("task.updated"),task:cy}),c.object({type:c.literal("task.output"),taskId:je,threadId:H,lines:c.array(uy)}),c.object({type:c.literal("pr.updated"),pullRequest:ly}),c.object({type:c.literal("error"),code:c.string(),message:c.string()})]);var zU=c.object({app:c.literal("myrel"),apiVersion:c.number().int().positive(),name:c.string(),auth:c.object({emailPassword:c.boolean(),signUp:c.boolean().default(!0),emailVerification:c.boolean().default(!1),captcha:c.object({provider:c.literal("turnstile"),siteKey:c.string()}).nullable().default(null),passwordReset:c.boolean().default(!1)}),billing:c.boolean().default(!1),legal:c.object({terms:c.string().url(),privacy:c.string().url(),version:c.string()}).nullable().default(null)});var AU=c.object({question:c.string().min(1).max(300),options:c.array(c.object({label:c.string().min(1).max(40),consequence:c.string().max(200).default("")})).min(2).max(4),recommended:c.number().int().nonnegative().optional(),danger:c.boolean().optional()});var ui=c.enum(["fireworks","anthropic","openai"]),EU=c.object({id:ui,name:c.string(),defaultModel:c.string(),serverKey:c.boolean()}),RU=c.object({id:c.string(),provider:ui,label:c.string(),hint:c.string(),scope:c.enum(["user","instance"]),createdAt:c.iso.datetime()}),MU=c.object({provider:ui,label:c.string().trim().min(1).max(80),key:c.string().trim().min(8).max(500),scope:c.enum(["user","instance"]).default("user")}),Oy=c.enum(["auto","local","cloud"]),Ny=c.enum(["opencode","claude","codex"]),CI=c.object({model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),Dy=c.partialRecord(qe,CI),LU=c.object({name:c.string(),provider:ui.nullable(),model:c.string().nullable(),keyId:c.string().nullable(),taskTarget:Oy,icon:Ca.nullable().default(null),color:Ua.nullable().default(null),cloudCli:Ny.default("opencode"),cliModels:Dy.default({})}),ZU=c.object({name:c.string().trim().min(1).max(120).optional(),provider:ui.nullable().optional(),model:c.string().trim().max(200).nullable().optional(),keyId:c.string().nullable().optional(),taskTarget:Oy.optional(),icon:Ca.nullable().optional(),color:Ua.nullable().optional(),cloudCli:Ny.optional(),cliModels:Dy.optional()}),Uy=c.enum(["admin","member"]),FU=c.object({id:c.string(),projectId:c.string(),projectName:c.string(),email:c.string(),role:Uy,invitedBy:c.string(),createdAt:c.iso.datetime()}),VU=c.object({email:c.email().trim().toLowerCase(),role:Uy.default("member")}),JU=c.object({role:Da}),EI=c.enum(["admin","user"]),KU=c.enum(["computer","decision"]),BU=c.object({id:c.string(),name:c.string(),email:c.string(),role:EI,onboarded:c.boolean().optional(),tips:c.array(c.string()).optional()}),RI=c.object({signUpEnabled:c.boolean()}),MI=c.enum(["api","agent","cron","web","desktop","mobile"]),WU=c.object({platform:c.enum(["web","desktop","mobile"]),where:c.string().trim().min(1).max(200),name:c.string().max(100).default("Error"),message:c.string().max(500),stack:c.string().max(4e3).optional(),version:c.string().max(40).optional()}),GU=c.object({id:c.string(),source:MI,where:c.string(),name:c.string(),message:c.string(),stack:c.string().nullable(),count:c.number().int(),firstSeenAt:c.number(),lastSeenAt:c.number()}),qU=c.object({days:c.number().int(),signedUp:c.number().int(),verified:c.number().int(),inProject:c.number().int(),asked:c.number().int(),threadRan:c.number().int(),pairedComputer:c.number().int()}),HU=RI.partial();var Cy=c.string().regex(me("notification")),LI=c.enum(["done","ready","decision","blocked","failed"]),t4=c.object({id:Cy,projectId:Pe,threadId:H.nullable(),kind:LI,title:c.string(),body:c.string(),url:c.string(),readAt:R.nullable(),createdAt:R}),n4=c.object({email:c.boolean(),push:c.boolean()}),r4=c.object({webPushKey:c.string().nullable(),email:c.boolean()}),ZI=[/^fcm\.googleapis\.com$/,/^updates\.push\.services\.mozilla\.com$/,/^web\.push\.apple\.com$/,/^[a-z0-9-]+\.notify\.windows\.com$/];function FI(e){try{let t=new URL(e);return t.protocol==="https:"&&ZI.some(r=>r.test(t.hostname))}catch{return!1}}var i4=c.discriminatedUnion("kind",[c.object({kind:c.literal("webpush"),endpoint:c.url().max(2048).refine(FI,"Not a browser push service"),keys:c.object({p256dh:c.string().min(1).max(256),auth:c.string().min(1).max(64)})}),c.object({kind:c.literal("expo"),token:c.string().regex(/^Expo(nent)?PushToken\[[^\]]+\]$/).max(256)})]),o4=c.union([c.object({ids:c.array(Cy).min(1).max(200)}),c.object({all:c.literal(!0)})]);var VI=new RegExp(me("thread").source.slice(1,-1)),d4=new RegExp(`^#(${VI.source})$`);var JI=c.enum(["http","stdio"]),KI=c.enum(["user","project"]),gf=c.enum(["cloud","local","both"]),BI=c.enum(["unknown","ok","error","needs_auth"]),WI=c.enum(["none","headers","oauth"]),Ey=c.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).refine(e=>e!=="myrel","That name is taken by Myrel's own tools."),GI=c.object({name:c.string(),description:c.string().optional()}),qI=/^[A-Za-z_][\w-]{0,99}$/,HI=/^[A-Za-z_][A-Za-z0-9_]{0,99}$/,Ry=(e,t,r)=>c.record(c.string().regex(e),c.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}),My=Ry(qI,"Header","letters, digits, - and _"),XI=Ry(HI,"Variable","letters, digits and _"),m4=c.object({id:c.string(),name:c.string(),slug:c.string(),scope:KI,transport:JI,url:c.string().nullable(),auth:WI,command:c.string().nullable(),args:c.array(c.string()),runsOn:gf,secretNames:c.array(c.string()),enabled:c.boolean(),status:BI,lastError:c.string().nullable(),tools:c.array(GI),canEdit:c.boolean(),createdAt:c.iso.datetime(),official:c.object({id:c.string(),title:c.string(),iconUrl:c.string().nullable()}).nullable().default(null)}),mf=c.string().trim().min(1).max(60),g4=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:mf,slug:Ey.optional(),url:c.url({protocol:/^https$/}).max(2e3),auth:c.enum(["headers","oauth"]).default("headers"),headers:My.default({})}),c.object({transport:c.literal("stdio"),name:mf,slug:Ey.optional(),command:c.string().trim().min(1).max(200),args:c.array(c.string().max(2e3)).max(50).default([]),env:XI.default({}),runsOn:gf.default("both")})]),h4=c.object({name:mf.optional(),enabled:c.boolean().optional(),url:c.url({protocol:/^https$/}).max(2e3).optional(),command:c.string().trim().min(1).max(200).optional(),args:c.array(c.string().max(2e3)).max(50).optional(),runsOn:gf.optional(),secrets:My.optional()});var v4=c.object({authorizeUrl:c.url()});var YI=["developer","productivity","communication","design","data","sales","finance","search","ai","other"],Ly=c.enum(YI);var QI=c.object({id:c.string(),title:c.string(),description:c.string(),websiteUrl:c.string().nullable(),iconUrl:c.string().nullable(),url:c.string(),auth:c.enum(["oauth","headers"]),headerHint:c.object({name:c.string(),placeholder:c.string()}).nullable(),category:Ly,official:c.boolean()}),y4=c.object({connectors:c.array(QI),nextOffset:c.number().nullable(),syncedAt:c.iso.datetime().nullable(),categories:c.array(c.object({id:Ly,count:c.number()}))}),ez=[{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"}],b4=ez.map(e=>e.id);var tz=c.enum(["user","project"]),nz=c.string().max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,"Use lowercase letters, digits and hyphens, like pdf-forms."),Zy=c.string().trim().min(1).max(1024),rz=c.string().min(1).max(300).regex(/^[\w@+=,.~ -]+(\/[\w@+=,.~ -]+)*$/,"Invalid file path.").refine(e=>!e.split("/").some(t=>t==="."||t===".."),"Invalid file path."),Fy={files:200,bytes:5*1024*1024,fileBytes:1024*1024};var iz=c.discriminatedUnion("kind",[c.object({kind:c.literal("write")}),c.object({kind:c.literal("upload")}),c.object({kind:c.literal("github"),repo:c.string(),path:c.string(),ref:c.string().optional(),commit:c.string()})]),oz=c.object({path:c.string(),size:c.number().int().nonnegative()}),az=c.object({id:c.string(),name:c.string(),description:c.string(),scope:tz,source:iz,enabled:c.boolean(),files:c.array(oz),size:c.number().int().nonnegative(),canEdit:c.boolean(),createdAt:c.iso.datetime(),updatedAt:c.iso.datetime()}),x4=az.extend({skillMd:c.string()}),sz=c.object({path:rz,content:c.string().max(Math.ceil(Fy.fileBytes*4/3)+4)}),k4=c.discriminatedUnion("kind",[c.object({kind:c.literal("write"),name:nz,description:Zy,instructions:c.string().max(1e5)}),c.object({kind:c.literal("upload"),files:c.array(sz).min(1).max(Fy.files)}),c.object({kind:c.literal("github"),source:c.string().trim().min(3).max(500),skill:c.string().max(64).optional()})]),w4=c.object({error:c.literal("choose_skill"),skills:c.array(c.object({name:c.string(),description:c.string(),path:c.string()}))}),S4=c.object({enabled:c.boolean().optional(),description:Zy.optional(),instructions:c.string().max(1e5).optional()}),I4=c.object({skills:c.array(c.object({name:c.string(),files:c.array(c.object({path:c.string(),content:c.string()}))}))});var z4=c.object({on:c.boolean()});var cz=c.object({id:c.string().min(1).max(200),name:c.string().min(1).max(80),description:c.string().max(300).default(""),url:c.string().max(2e3),auth:c.enum(["oauth","headers"]),headerHint:c.object({name:c.string(),placeholder:c.string()}).nullable().default(null),iconUrl:c.string().nullable().default(null),official:c.boolean().default(!1),featured:c.boolean().default(!1)}),uz=c.enum(["open","connected","dismissed"]),A4=c.object({id:c.string(),reason:c.string().min(1).max(400),offers:c.array(cz).min(1).max(3),state:uz.default("open"),connected:c.string().optional(),signIn:c.boolean().optional()});var T4=c.object({offerId:c.string().min(1).max(200),headers:c.record(c.string().regex(/^[A-Za-z_][\w-]{0,99}$/),c.string().min(1).max(4e3)).optional()}),O4=c.object({authorizeUrl:c.string().optional(),connected:c.boolean()});var lz=/^(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(\S[\s\S]*)$/;function Yn(e){let t=lz.exec(e.trim());return t?dz(t[1])??e:e}function dz(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}import{spawn as pz}from"node:child_process";import{mkdir as fz,readFile as By,rename as mz,writeFile as gz}from"node:fs/promises";import{homedir as Wy}from"node:os";import{dirname as hz,join as Vy}from"node:path";import{createInterface as Gy}from"node:readline";var bf="MYREL_MCP_BRIDGE";function vz(e=Wy()){return{mcp:Vy(e,".gemini","config","mcp_config.json"),settings:Vy(e,".gemini","antigravity-cli","settings.json")}}function li(){let e=process.argv[1],t=!e||/\$bunfs|~BUN/.test(e);return{command:process.execPath,args:t?[]:[e]}}async function qy(e,t=Wy()){let r=vz(t),o=li(),n={command:o.command,args:[...o.args,"mcp-bridge"]};await Jy(r.mcp,a=>{let s=hf(a.mcpServers)?a.mcpServers:{};return JSON.stringify(s[e])===JSON.stringify(n)?!1:(a.mcpServers={...s,[e]:n},!0)});let i=`mcp(${e}/*)`;await Jy(r.settings,a=>{let s=hf(a.permissions)?a.permissions:{},u=Array.isArray(s.allow)?s.allow:[];return u.includes(i)?!1:(a.permissions={...s,allow:[...u,i]},!0)})}async function Jy(e,t){let r=await By(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(!hf(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 fz(hz(e),{recursive:!0});let n=`${e}.myrel-${process.pid}`;await gz(n,`${JSON.stringify(o,null,2)}
63
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=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(s.cycle){i(a);continue}s.count>1&&e.reused==="ref"&&i(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function vh(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;vh(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 yh=new Set(["type","properties","required","additionalProperties"]),gh=["oneOf","anyOf"];function hh(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Ql(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!yh.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 s=[];for(let l of t){let d=l.properties?.[a]??hh(l);d!=null&&(s.some(p=>JSON.stringify(p)===JSON.stringify(d))||s.push(d))}let u=s.length===1?s[0]:Ql(s)??{allOf:s};le(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 s=hh(a);s&&!i.some(u=>JSON.stringify(u)===JSON.stringify(s))&&i.push(s)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function fS(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of yh)if(n in e)return;let r=t.filter(n=>gh.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Ql(t);else{let n=r[0],i=gh.find(u=>Array.isArray(n[u]));if(Object.keys(n).length!==1)return;let a=t.filter(u=>u!==n),s=n[i].map(u=>Ql([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,Kr(e,o))}function kt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{let u=e.seen.get(s);if(u.ref===null)return;let l=u.def??u.schema,d={...l},p=u.ref;if(u.ref=null,p){o(p);let f=e.seen.get(p),g=f.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)):Kr(l,g),Kr(l,d),s._zod.parent===p)for(let x in l)x==="$ref"||x==="allOf"||x in d||delete l[x];if(g.$ref&&f.def)for(let x in l)x==="$ref"||x==="allOf"||x in f.def&&JSON.stringify(l[x])===JSON.stringify(f.def[x])&&delete l[x]}let m=s._zod.parent;if(m&&m!==p){o(m);let f=e.seen.get(m);if(f?.schema.$ref&&(l.$ref=f.schema.$ref,f.def))for(let g in l)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(l[g])===JSON.stringify(f.def[g])&&delete l[g]}e.override({zodSchema:s,jsonSchema:l,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())o(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())vh(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=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=s.get(d);p?p.push(l):s.set(d,[l])}for(let u of e.intersections)for(let l of s.get(u)??[])fS(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 s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(s)}Kr(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 s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,le(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 s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ln(t,"input",e.processors),output:Ln(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function $e(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 $e(o.element,r);if(o.type==="set")return $e(o.valueType,r);if(o.type==="lazy")return $e(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 $e(o.innerType,r);if(o.type==="intersection")return $e(o.left,r)||$e(o.right,r);if(o.type==="record"||o.type==="map")return $e(o.keyType,r)||$e(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:$e(o.in,r)||$e(o.out,r);if(o.type==="object"){for(let n in o.shape)if($e(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if($e(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if($e(n,r))return!0;return!!(o.rest&&$e(o.rest,r))}return!1}var ed=(e,t={})=>r=>{let o=_t({...r,processors:t});return K(e,o),xt(o,e),kt(o,e)},Ln=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=_t({...n??{},target:i,io:t,processors:r});return K(e,a),xt(a,e),kt(a,e)};var Zn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Fn=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},bh=(e,t)=>{Zn(e,"minimum",t),Fn(e,"maximum",t)},kh=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},wh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Sh=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Ih=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},$h=(e,t)=>Zn(e,"minimum",t.minimum),_h=(e,t)=>Fn(e,"maximum",t.maximum),xh=e=>(t,r)=>{Ih(t,r.format);let[o,n]=e[r.format];Zn(t,"minimum",o),Fn(t,"maximum",n)},mS={greater_than:(e,t)=>Zn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Fn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>kh(e,t.value),number_format:xh(pr),bigint_format:xh(fr),min_length:$h,max_length:_h,length_equals:(e,t)=>bh(e,t.length),min_size:$h,max_size:_h,size_equals:(e,t)=>bh(e,t.size),string_format:(e,t)=>{Ih(e,t.format),t.pattern&&wh(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)=>Sh(e,t.mime)};function ae(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)mS[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Zn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Zn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Fn(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Fn(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&kh(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&Sh(t,n.mime);for(let i of n.patterns??[])wh(t,i);return t}var gS={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},hS=new Map([[ro,ac],[Ar,sc]]),zh=e=>hS.get(e)??e,rd=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:a,format:s,patterns:u,contentEncoding:l,laxFormat:d}=ae(e);if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),s&&(n.format=gS[s]??s,n.format===""&&delete n.format,(s==="time"||d)&&delete n.format),l&&(n.contentEncoding=l),u&&u.size>0){let p=[...u].map(zh);p.length===1?n.pattern=p[0].source:p.length>1&&(n.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},id=(e,t,r,o)=>{let n=r,{minimum:i,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:l,isInt:d}=ae(e);n.type=d?"integer":"number";let p=typeof l=="number"&&l>=(i??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(p?f?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof i=="number"&&(n.minimum=i),m?f?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),s){let g=new Set;for(let I of s)Number.isFinite(I)&&I!==0?g.add(Math.abs(I)):oe(e,t,n,o,`A multipleOf divisor of ${I} cannot be represented in JSON Schema`);let[y,...x]=g;y!==void 0&&(n.multipleOf=y),x.length&&(n.allOf=[...n.allOf??[],...x.map(I=>({multipleOf:I}))])}},od=(e,t,r,o)=>{r.type="boolean"},ad=(e,t,r,o)=>{oe(e,t,r,o,"BigInt cannot be represented in JSON Schema")},sd=(e,t,r,o)=>{oe(e,t,r,o,"Symbols cannot be represented in JSON Schema")},cd=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},ud=(e,t,r,o)=>{oe(e,t,r,o,"Undefined cannot be represented in JSON Schema")},ld=(e,t,r,o)=>{oe(e,t,r,o,"Void cannot be represented in JSON Schema")},dd=(e,t,r,o)=>{r.not={}},pd=(e,t,r,o)=>{},fd=(e,t,r,o)=>{},md=(e,t,r,o)=>{oe(e,t,r,o,"Date cannot be represented in JSON Schema")},gd=(e,t,r,o)=>{let n=e._zod.def,i=pn(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},hd=(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(oe(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(oe(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},vd=(e,t,r,o)=>{oe(e,t,r,o,"NaN cannot be represented in JSON Schema")},yd=(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},bd=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:a,mime:s}=ae(e);i!==void 0&&(n.minLength=i),a!==void 0&&(n.maxLength=a),s&&(s.length===0?n.not={}:s.length===1?n.contentMediaType=s[0]:n.anyOf=s.map(u=>({contentMediaType:u})))},$d=(e,t,r,o)=>{r.type="boolean"},_d=(e,t,r,o)=>{oe(e,t,r,o,"Custom types cannot be represented in JSON Schema")},xd=(e,t,r,o)=>{oe(e,t,r,o,"Function types cannot be represented in JSON Schema")},kd=(e,t,r,o)=>{oe(e,t,r,o,"Transforms cannot be represented in JSON Schema")},wd=(e,t,r,o)=>{oe(e,t,r,o,"Map cannot be represented in JSON Schema")},Sd=(e,t,r,o)=>{oe(e,t,r,o,"Set cannot be represented in JSON Schema")},Id=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:a,maximum:s}=ae(e);typeof a=="number"&&(n.minItems=a),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=K(i.element,t,{...o,path:[...o.path,"items"]})};function Br(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Br(t.out):t.type==="catch"?Br(t.innerType):e._zod.optin}var zd=(e,t,r,o)=>{let n=r,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&oe(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let l in a)le(n.properties,l,K(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"?Br(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=K(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},ta=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((s,u)=>K(s,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},Pd=(e,t,r,o)=>{let n=e._zod.def,i=K(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=K(n.right,t,{...o,path:[...o.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,u=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=u,t.intersections.push(u)},jd=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((y,x)=>K(y,t,{...o,path:[...o.path,a,x]})),l=i.rest?K(i.rest,t,{...o,path:[...o.path,s,...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"?Br(y)!==void 0:y._zod.optout==="optional"))break;d--}let p=i.items.length,m=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,m?n.items=!1:l&&(n.items=l),d>0&&(n.minItems=d),m&&(n.maxItems=p)):t.target==="openapi-3.0"?(n.items={anyOf:u},l&&n.items.anyOf.push(l),d>0&&(n.minItems=d),m&&(n.maxItems=p)):(n.items=u,m?n.additionalItems=!1:l&&(n.additionalItems=l),d>0&&(n.minItems=d),m&&(n.maxItems=p));let{minimum:f,maximum:g}=ae(e);typeof f=="number"&&(n.minItems=f),typeof g=="number"&&(n.maxItems=g)};function td(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=td(e,g,r);return y===g?t:y}for(let g of["anyOf","oneOf"]){let y=t[g];if(!Array.isArray(y))continue;let x=y.map(I=>td(e,I,r));x.some((I,S)=>I!==y[S])&&(t={...t,[g]:x})}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:s,exclusiveMinimum:u,exclusiveMaximum:l,multipleOf:d,format:p,id:m,...f}=t;return f.enum?f.enum=f.enum.map(g=>typeof g=="number"?String(g):g):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?at:kr).source)),f}var nd=new WeakMap;function vS(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 nd.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=td(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 Ad=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let a=i.keyType,s=ae(a).patterns;if(i.mode==="loose"&&s&&s.size>0){let d=K(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of s)le(n.patternProperties,zh(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=K(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let d=nd.get(t);d||(d=[],nd.set(t,d),t.deferred.push(()=>vS(t))),d.push(e)}n.additionalProperties=K(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,l=t.io==="input"&&Br(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))}},Td=(e,t,r,o)=>{let n=e._zod.def,i=K(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"}]},Od=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Nd=Symbol();function Ph(e,t,r,o,n){let i=!1,a=JSON.stringify(e,(s,u)=>typeof u!="bigint"?u:(i=!0,null));return i?(oe(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),Nd):JSON.parse(a)}var Dd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=Ph(n.defaultValue,e,t,r,o);a!==Nd&&(r.default=a)},Ud=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=Ph(n.defaultValue,e,t,r,o);a!==Nd&&(r._prefault=a)},Cd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{oe(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=a},Ed=(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;K(a,t,o);let s=t.seen.get(e);s.ref=a},Rd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},Md=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},na=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Ld=(e,t,r,o)=>{let n=e._zod.innerType;K(n,t,o);let i=t.seen.get(e);i.ref=n},ea={string:rd,number:id,boolean:od,bigint:ad,symbol:sd,null:cd,undefined:ud,void:ld,never:dd,any:pd,unknown:fd,date:md,enum:gd,literal:hd,nan:vd,template_literal:yd,file:bd,success:$d,custom:_d,function:xd,transform:kd,map:wd,set:Sd,array:Id,object:zd,union:ta,intersection:Pd,tuple:jd,record:Ad,nullable:Td,nonoptional:Od,default:Dd,prefault:Ud,catch:Cd,pipe:Ed,readonly:Rd,promise:Md,optional:na,lazy:Ld};function ra(e,t){if("_idmap"in e){let o=e,n=_t({...t,processors:ea}),i={};for(let u of o._idmap.entries()){let[l,d]=u;K(d,n)}let a={},s={registry:o,uri:t?.uri,defs:i};n.external=s;for(let u of o._idmap.entries()){let[l,d]=u;xt(n,d),le(a,l,kt(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=_t({...t,processors:ea});return K(e,r),xt(r,e),kt(r,e)}var ia=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=_t({processors:ea,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 K(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,xt(this.ctx,t);let o=kt(this.ctx,t),{"~standard":n,...i}=o;return i}};var jh={};var Hn={};rt(Hn,{ZodAny:()=>cp,ZodArray:()=>pp,ZodBase64:()=>ka,ZodBase64URL:()=>wa,ZodBigInt:()=>Gn,ZodBigIntFormat:()=>za,ZodBoolean:()=>Wn,ZodCIDRv4:()=>_a,ZodCIDRv6:()=>xa,ZodCUID:()=>ma,ZodCUID2:()=>ga,ZodCatch:()=>Np,ZodCodec:()=>ni,ZodCreditCard:()=>ep,ZodCustom:()=>ri,ZodCustomStringFormat:()=>Gt,ZodDate:()=>Hr,ZodDefault:()=>zp,ZodDiscriminatedUnion:()=>mp,ZodE164:()=>Sa,ZodEmail:()=>la,ZodEmoji:()=>pa,ZodEnum:()=>Jn,ZodExactOptional:()=>Ta,ZodFile:()=>kp,ZodFunction:()=>Vp,ZodGUID:()=>da,ZodIBAN:()=>tp,ZodIPv4:()=>ba,ZodIPv6:()=>$a,ZodISODate:()=>St,ZodISODateTime:()=>wt,ZodISODuration:()=>zt,ZodISOTime:()=>It,ZodInstanceOf:()=>Bp,ZodIntersection:()=>gp,ZodJWT:()=>Ia,ZodKSUID:()=>ya,ZodLazy:()=>Lp,ZodLiteral:()=>xp,ZodMAC:()=>Qd,ZodMap:()=>$p,ZodNaN:()=>Up,ZodNanoID:()=>fa,ZodNever:()=>lp,ZodNonOptional:()=>Oa,ZodNull:()=>ap,ZodNullable:()=>Ip,ZodNumber:()=>Bn,ZodNumberFormat:()=>qt,ZodObject:()=>Yr,ZodOptional:()=>ei,ZodPipe:()=>ti,ZodPrefault:()=>jp,ZodPreprocess:()=>Cp,ZodPromise:()=>Fp,ZodReadonly:()=>Ep,ZodRecord:()=>Vn,ZodSet:()=>_p,ZodString:()=>Kn,ZodStringFormat:()=>G,ZodSuccess:()=>Op,ZodSymbol:()=>ip,ZodTemplateLiteral:()=>Mp,ZodTransform:()=>wp,ZodTuple:()=>vp,ZodType:()=>E,ZodULID:()=>ha,ZodURL:()=>qr,ZodUUID:()=>Ge,ZodUndefined:()=>op,ZodUnion:()=>Qr,ZodUnknown:()=>up,ZodVoid:()=>dp,ZodXID:()=>va,ZodXor:()=>fp,_ZodString:()=>ua,_default:()=>Pp,_function:()=>Zv,any:()=>yv,array:()=>Xr,base64:()=>Yh,base64url:()=>Qh,bigint:()=>fv,boolean:()=>rp,catch:()=>Dp,check:()=>Fv,cidrv4:()=>Hh,cidrv6:()=>Xh,codec:()=>Ev,creditCard:()=>tv,cuid:()=>Fh,cuid2:()=>Vh,currencyCode:()=>sv,custom:()=>Vv,date:()=>$v,describe:()=>Jv,discriminatedUnion:()=>Iv,e164:()=>ev,email:()=>Oh,emoji:()=>Lh,enum:()=>ja,exactOptional:()=>Sp,file:()=>Nv,float32:()=>uv,float64:()=>lv,function:()=>Zv,guid:()=>Nh,hash:()=>cv,hex:()=>av,hostname:()=>ov,httpUrl:()=>Mh,iban:()=>nv,instanceof:()=>Bv,int:()=>sa,int32:()=>dv,int64:()=>mv,intersection:()=>hp,invertCodec:()=>Rv,ipv4:()=>Wh,ipv6:()=>qh,json:()=>Gv,jwt:()=>rv,keyof:()=>_v,ksuid:()=>Bh,lazy:()=>Zp,literal:()=>Ov,looseObject:()=>wv,looseRecord:()=>Pv,mac:()=>Gh,map:()=>jv,meta:()=>Kv,nan:()=>Cv,nanoid:()=>Zh,nativeEnum:()=>Tv,never:()=>Pa,nonoptional:()=>Tp,null:()=>sp,nullable:()=>Gr,nullish:()=>Dv,number:()=>np,object:()=>xv,optional:()=>Bt,partialRecord:()=>zv,pipe:()=>ca,prefault:()=>Ap,preprocess:()=>qv,promise:()=>Lv,readonly:()=>Rp,record:()=>bp,refine:()=>Jp,set:()=>Av,strictObject:()=>kv,string:()=>Wr,stringFormat:()=>iv,stringbool:()=>Wv,success:()=>Uv,superRefine:()=>Kp,symbol:()=>hv,templateLiteral:()=>Mv,transform:()=>Aa,tuple:()=>yp,uint32:()=>pv,uint64:()=>gv,ulid:()=>Jh,undefined:()=>vv,union:()=>qn,unknown:()=>Kt,url:()=>Rh,uuid:()=>Dh,uuidv4:()=>Uh,uuidv6:()=>Ch,uuidv7:()=>Eh,void:()=>bv,xid:()=>Kh,xor:()=>Sv});var oa={};rt(oa,{endsWith:()=>On,gt:()=>Be,gte:()=>Oe,includes:()=>An,length:()=>Vt,lowercase:()=>Pn,lt:()=>Ke,lte:()=>Te,maxLength:()=>Ft,maxSize:()=>$t,mime:()=>Dn,minLength:()=>st,minSize:()=>We,multipleOf:()=>bt,negative:()=>Ho,nonnegative:()=>Yo,nonpositive:()=>Xo,normalize:()=>Un,overwrite:()=>Fe,positive:()=>qo,properties:()=>Nn,property:()=>Qo,regex:()=>zn,size:()=>Zt,slugify:()=>Mn,startsWith:()=>Tn,toLowerCase:()=>En,toUpperCase:()=>Rn,trim:()=>Cn,uppercase:()=>jn});var Ah=new WeakSet([Object.prototype,Error.prototype]);function aa(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 Th=(e,t)=>{Ls.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);Ah.has(r)||(Ah.add(r),aa(r,"format",o=>n=>br(o,n)),aa(r,"flatten",o=>n=>yr(o,n)),aa(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,fn,2)}),aa(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,fn,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},bS=h("ZodError",Th),ze=h("ZodError",Th,void 0,{Parent:Error});var Zd=yn(ze),Fd=bn(ze),Vd=$n(ze),Jd=_n(ze),Kd=Di(ze),Bd=Ui(ze),Wd=Ci(ze),Gd=Ei(ze),qd=Ri(ze),Hd=Mi(ze),Xd=Li(ze),Yd=Zi(ze);function _S(){ce.localeError||ne($o())}function Wt(){ce.memoizer||ne({memoizer:Er()})}var E=h("ZodType",(e,t)=>(_S(),U.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 V(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Jp(e,t))},superRefine(e,t){return this.check(Kp(e,t))},overwrite(e){return this.check(Fe(e))},optional(){return Bt(this)},exactOptional(){return Sp(this)},nullable(){return Gr(this)},nullish(){return Bt(Gr(this))},nonoptional(e){return Tp(this,e)},array(){return Xr(this)},or(e){return qn([this,e])},and(e){return hp(this,e)},transform(e){return ca(this,Aa(e))},default(e){return Pp(this,e)},prefault(e){return Ap(this,e)},catch(e){return Dp(this,e)},pipe(e){return ca(this,e)},readonly(){return Rp(this)},describe(e){let t=this.clone();return de.add(t,{description:e}),t},meta(...e){if(e.length===0)return de.get(this);let t=this.clone();return de.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",{...Yi(this),jsonSchema:{input:Ln(this,"input"),output:Ln(this,"output")}})},set"~standard"(e){b.own(this,"~standard",e)},parse:function e(t,r){return Zd(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await Fd(this,t,r,{callee:e})},safeParse(e,t){return Vd(this,e,t)},async safeParseAsync(e,t){return Jd(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){b.own(this,"spa",e)},validate(e,t){return $r(this,e,t)},validateAsync(e,t){return _r(this,e,t)},encode:function e(t,r){return Kd(this,t,r,{callee:e})},decode:function e(t,r){return Bd(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await Wd(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Gd(this,t,r,{callee:e})},safeEncode(e,t){return qd(this,e,t)},safeDecode(e,t){return Hd(this,e,t)},async safeEncodeAsync(e,t){return Xd(this,e,t)},async safeDecodeAsync(e,t){return Yd(this,e,t)},toJSONSchema(e){return ed(this,{})(e)},get description(){return de.get(this)?.description},get _def(){return this._zod.def}}),ua=h("_ZodString",(e,t)=>{Et.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rd(e,r,o,n)},b.derived({format:e=>ae(e).format??null,minLength:e=>ae(e).minimum??null,maxLength:e=>ae(e).maximum??null},{regex(...e){return this.check(zn(...e))},includes(...e){return this.check(An(...e))},startsWith(...e){return this.check(Tn(...e))},endsWith(...e){return this.check(On(...e))},min(...e){return this.check(st(...e))},max(...e){return this.check(Ft(...e))},length(...e){return this.check(Vt(...e))},nonempty(...e){return this.check(st(1,...e))},lowercase(e){return this.check(Pn(e))},uppercase(e){return this.check(jn(e))},trim(){return this.check(Cn())},normalize(...e){return this.check(Un(...e))},toLowerCase(){return this.check(En())},toUpperCase(){return this.check(Rn())},slugify(){return this.check(Mn())}})),Kn=h("ZodString",(e,t)=>{Et.init(e,t),ua.init(e,t)},{email(e){return this.check(Po(la,e))},url(e){return this.check(Lr(qr,e))},jwt(e){return this.check(Go(Ia,e))},emoji(e){return this.check(Do(pa,e))},guid(e){return this.check(jo(da,e))},uuid(e){return this.check(Ao(Ge,e))},uuidv4(e){return this.check(To(Ge,e))},uuidv6(e){return this.check(Oo(Ge,e))},uuidv7(e){return this.check(No(Ge,e))},nanoid(e){return this.check(Uo(fa,e))},cuid(e){return this.check(Co(ma,e))},cuid2(e){return this.check(Eo(ga,e))},ulid(e){return this.check(Ro(ha,e))},base64(e){return this.check(Ko(ka,e))},base64url(e){return this.check(Bo(wa,e))},xid(e){return this.check(Mo(va,e))},ksuid(e){return this.check(Lo(ya,e))},ipv4(e){return this.check(Zo(ba,e))},ipv6(e){return this.check(Fo($a,e))},cidrv4(e){return this.check(Vo(_a,e))},cidrv6(e){return this.check(Jo(xa,e))},e164(e){return this.check(Wo(Sa,e))},datetime(e){return this.check(Zr(wt,e))},date(e){return this.check(Fr(St,e))},time(e){return this.check(Vr(It,e))},duration(e){return this.check(Jr(zt,e))}});function Wr(e){return hl(Kn,e)}var G=h("ZodStringFormat",(e,t)=>{J.init(e,t),ua.init(e,t)}),wt=h("ZodISODateTime",(e,t)=>{au.init(e,t),G.init(e,t)}),St=h("ZodISODate",(e,t)=>{su.init(e,t),G.init(e,t)}),It=h("ZodISOTime",(e,t)=>{cu.init(e,t),G.init(e,t)}),zt=h("ZodISODuration",(e,t)=>{uu.init(e,t),G.init(e,t)}),la=h("ZodEmail",(e,t)=>{qc.init(e,t),G.init(e,t)});function Oh(e){return Po(la,e)}var da=h("ZodGUID",(e,t)=>{Wc.init(e,t),G.init(e,t)});function Nh(e){return jo(da,e)}var Ge=h("ZodUUID",(e,t)=>{Gc.init(e,t),G.init(e,t)});function Dh(e){return Ao(Ge,e)}function Uh(e){return To(Ge,e)}function Ch(e){return Oo(Ge,e)}function Eh(e){return No(Ge,e)}var qr=h("ZodURL",(e,t)=>{Yc.init(e,t),G.init(e,t)});function Rh(e){return Lr(qr,e)}function Mh(e){return Lr(qr,{protocol:xr,hostname:uc,...b.normalizeParams(e)})}var pa=h("ZodEmoji",(e,t)=>{Qc.init(e,t),G.init(e,t)});function Lh(e){return Do(pa,e)}var fa=h("ZodNanoID",(e,t)=>{eu.init(e,t),G.init(e,t)});function Zh(e){return Uo(fa,e)}var ma=h("ZodCUID",(e,t)=>{tu.init(e,t),G.init(e,t)});function Fh(e){return Co(ma,e)}var ga=h("ZodCUID2",(e,t)=>{nu.init(e,t),G.init(e,t)});function Vh(e){return Eo(ga,e)}var ha=h("ZodULID",(e,t)=>{ru.init(e,t),G.init(e,t)});function Jh(e){return Ro(ha,e)}var va=h("ZodXID",(e,t)=>{iu.init(e,t),G.init(e,t)});function Kh(e){return Mo(va,e)}var ya=h("ZodKSUID",(e,t)=>{ou.init(e,t),G.init(e,t)});function Bh(e){return Lo(ya,e)}var ba=h("ZodIPv4",(e,t)=>{lu.init(e,t),G.init(e,t)});function Wh(e){return Zo(ba,e)}var Qd=h("ZodMAC",(e,t)=>{pu.init(e,t),G.init(e,t)});function Gh(e){return yl(Qd,e)}var $a=h("ZodIPv6",(e,t)=>{du.init(e,t),G.init(e,t)});function qh(e){return Fo($a,e)}var _a=h("ZodCIDRv4",(e,t)=>{fu.init(e,t),G.init(e,t)});function Hh(e){return Vo(_a,e)}var xa=h("ZodCIDRv6",(e,t)=>{mu.init(e,t),G.init(e,t)});function Xh(e){return Jo(xa,e)}var ka=h("ZodBase64",(e,t)=>{gu.init(e,t),G.init(e,t)});function Yh(e){return Ko(ka,e)}var wa=h("ZodBase64URL",(e,t)=>{hu.init(e,t),G.init(e,t)});function Qh(e){return Bo(wa,e)}var Sa=h("ZodE164",(e,t)=>{vu.init(e,t),G.init(e,t)});function ev(e){return Wo(Sa,e)}var ep=h("ZodCreditCard",(e,t)=>{yu.init(e,t),G.init(e,t)});function tv(e){return bl(ep,e)}var tp=h("ZodIBAN",(e,t)=>{bu.init(e,t),G.init(e,t)});function nv(e){return $l(tp,e)}var Ia=h("ZodJWT",(e,t)=>{$u.init(e,t),G.init(e,t)});function rv(e){return Go(Ia,e)}var Gt=h("ZodCustomStringFormat",(e,t)=>{_u.init(e,t),G.init(e,t)});function iv(e,t,r={}){return Jt(Gt,e,t,r)}function ov(e){return Jt(Gt,"hostname",cc,e)}function av(e){return Jt(Gt,"hex",kc,e)}function sv(e){return Jt(Gt,"currency_code",dc,e)}function cv(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Ee[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Jt(Gt,o,n,t)}var Bn=h("ZodNumber",(e,t)=>{co.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>id(e,r,o,n),e.isFinite=!0},b.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=ae(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=ae(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=ae(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>ae(e).format??null},{gt(e,t){return this.check(Be(e,t))},gte(e,t){return this.check(Oe(e,t))},min(e,t){return this.check(Oe(e,t))},lt(e,t){return this.check(Ke(e,t))},lte(e,t){return this.check(Te(e,t))},max(e,t){return this.check(Te(e,t))},int(e){return this.check(sa(e))},safe(e){return this.check(sa(e))},positive(e){return this.check(Be(0,e))},nonnegative(e){return this.check(Oe(0,e))},negative(e){return this.check(Ke(0,e))},nonpositive(e){return this.check(Te(0,e))},multipleOf(e,t){return this.check(bt(e,t))},step(e,t){return this.check(bt(e,t))},finite(){return this}}));function np(e){return xl(Bn,e)}var qt=h("ZodNumberFormat",(e,t)=>{xu.init(e,t),Bn.init(e,t)});function sa(e){return wl(qt,e)}function uv(e){return Sl(qt,e)}function lv(e){return Il(qt,e)}function dv(e){return zl(qt,e)}function pv(e){return Pl(qt,e)}var Wn=h("ZodBoolean",(e,t)=>{Tr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>od(e,r,o,n)});function rp(e){return jl(Wn,e)}var Gn=h("ZodBigInt",(e,t)=>{uo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ad(e,r,o,n)},b.derived({minValue:e=>ae(e).minimum??null,maxValue:e=>ae(e).maximum??null,format:e=>ae(e).format??null},{gte(e,t){return this.check(Oe(e,t))},min(e,t){return this.check(Oe(e,t))},gt(e,t){return this.check(Be(e,t))},lt(e,t){return this.check(Ke(e,t))},lte(e,t){return this.check(Te(e,t))},max(e,t){return this.check(Te(e,t))},positive(e){return this.check(Be(BigInt(0),e))},negative(e){return this.check(Ke(BigInt(0),e))},nonpositive(e){return this.check(Te(BigInt(0),e))},nonnegative(e){return this.check(Oe(BigInt(0),e))},multipleOf(e,t){return this.check(bt(e,t))}}));function fv(e){return Tl(Gn,e)}var za=h("ZodBigIntFormat",(e,t)=>{ku.init(e,t),Gn.init(e,t)});function mv(e){return Nl(za,e)}function gv(e){return Dl(za,e)}var ip=h("ZodSymbol",(e,t)=>{wu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sd(e,r,o,n)});function hv(e){return Ul(ip,e)}var op=h("ZodUndefined",(e,t)=>{Su.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ud(e,r,o,n)});function vv(e){return Cl(op,e)}var ap=h("ZodNull",(e,t)=>{Iu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>cd(e,r,o,n)});function sp(e){return El(ap,e)}var cp=h("ZodAny",(e,t)=>{zu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pd(e,r,o,n)});function yv(){return Rl(cp)}var up=h("ZodUnknown",(e,t)=>{Pu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>fd(e,r,o,n)});function Kt(){return Ml(up)}var lp=h("ZodNever",(e,t)=>{ju.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>dd(e,r,o,n)});function Pa(e){return Ll(lp,e)}var dp=h("ZodVoid",(e,t)=>{Au.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ld(e,r,o,n)});function bv(e){return Zl(dp,e)}var Hr=h("ZodDate",(e,t)=>{Tu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>md(e,r,o,n),e.min=(r,o)=>e.check(Oe(r,o)),e.max=(r,o)=>e.check(Te(r,o))},b.derived({minDate:e=>{let{minimum:t}=ae(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=ae(e);return t?new Date(t):null}},{}));function $v(e){return Fl(Hr,e)}var pp=h("ZodArray",(e,t)=>{Wt(),Nu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Id(e,r,o,n),e.element=t.element},{min(e,t){return this.check(st(e,t))},nonempty(e){return this.check(st(1,e))},max(e,t){return this.check(Ft(e,t))},length(e,t){return this.check(Vt(e,t))},unwrap(){return this.element}});function Xr(e,t){return Kl(pp,e,t)}function _v(e){let t=e._zod.def.shape;return ja(Object.keys(t))}var Yr=h("ZodObject",(e,t)=>{Wt(),Du.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zd(e,r,o,n),b.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return ja(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:Kt()}))},loose(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Kt()}))},strict(){return this.clone(b.mergeDefs(this._zod.def,{catchall:Pa()}))},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(ei,this,e[0])},exactPartial(...e){return b.partial(Ta,this,e[0],"exactPartial")},required(...e){return b.required(Oa,this,e[0])}});function xv(e,t){let r={type:"object",shape:e??{},...b.normalizeParams(t)};return new Yr(r)}function kv(e,t){return new Yr({type:"object",shape:e,catchall:Pa(),...b.normalizeParams(t)})}function wv(e,t){return new Yr({type:"object",shape:e,catchall:Kt(),...b.normalizeParams(t)})}var Qr=h("ZodUnion",(e,t)=>{Or.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ta(e,r,o,n),e.options=t.options});function qn(e,t){return new Qr({type:"union",options:e,...b.normalizeParams(t)})}var fp=h("ZodXor",(e,t)=>{Qr.init(e,t),Uu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ta(e,r,o,n),e.options=t.options});function Sv(e,t){return new fp({type:"union",options:e,inclusive:!1,...b.normalizeParams(t)})}var mp=h("ZodDiscriminatedUnion",(e,t)=>{Qr.init(e,t),Eu.init(e,t)});function Iv(e,t,r){return new mp({type:"union",options:t,discriminator:e,...b.normalizeParams(r)})}var gp=h("ZodIntersection",(e,t)=>{Ru.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pd(e,r,o,n)});function hp(e,t){return new gp({type:"intersection",left:e,right:t})}var vp=h("ZodTuple",(e,t)=>{Wt(),lo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jd(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 ei({type:"optional",innerType:t}))})}});function yp(e,t,r){let o=t instanceof U,n=o?r:t,i=o?t:null;return new vp({type:"tuple",items:e,rest:i,...b.normalizeParams(n)})}var Vn=h("ZodRecord",(e,t)=>{Wt(),Mu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ad(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function bp(e,t,r){return!t||!t._zod?new Vn({type:"record",keyType:Wr(),valueType:e,...b.normalizeParams(t)}):new Vn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r)})}function zv(e,t,r){return new Vn({type:"record",keyType:e,valueType:t,...b.normalizeParams(r),partial:!0})}function Pv(e,t,r){return new Vn({type:"record",keyType:e,valueType:t,mode:"loose",...b.normalizeParams(r)})}var $p=h("ZodMap",(e,t)=>{Wt(),Lu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(We(...r)),e.nonempty=r=>e.check(We(1,r)),e.max=(...r)=>e.check($t(...r)),e.size=(...r)=>e.check(Zt(...r))});function jv(e,t,r){return new $p({type:"map",keyType:e,valueType:t,...b.normalizeParams(r)})}var _p=h("ZodSet",(e,t)=>{Wt(),Zu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sd(e,r,o,n),e.min=(...r)=>e.check(We(...r)),e.nonempty=r=>e.check(We(1,r)),e.max=(...r)=>e.check($t(...r)),e.size=(...r)=>e.check(Zt(...r))});function Av(e,t){return new _p({type:"set",valueType:e,...b.normalizeParams(t)})}var Jn=h("ZodEnum",(e,t)=>{Fu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(o,n,i)=>gd(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 Jn({...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 Jn({...t,checks:[],...b.normalizeParams(n),entries:i})}});function ja(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Jn({type:"enum",entries:r,...b.normalizeParams(t)})}function Tv(e,t){return new Jn({type:"enum",entries:e,...b.normalizeParams(t)})}var xp=h("ZodLiteral",(e,t)=>{Vu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hd(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 Ov(e,t){return new xp({type:"literal",values:Array.isArray(e)?e:[e],...b.normalizeParams(t)})}var kp=h("ZodFile",(e,t)=>{Ju.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bd(e,r,o,n),e.min=(r,o)=>e.check(We(r,o)),e.max=(r,o)=>e.check($t(r,o)),e.mime=(r,o)=>e.check(Dn(Array.isArray(r)?r:[r],o))});function Nv(e){return Bl(kp,e)}var wp=h("ZodTransform",(e,t)=>{Wt(),Ku.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kd(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new vt(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 Aa(e){return new wp({type:"transform",transform:e})}var ei=h("ZodOptional",(e,t)=>{po.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>na(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Bt(e){return new ei({type:"optional",innerType:e})}var Ta=h("ZodExactOptional",(e,t)=>{Bu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>na(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Sp(e){return new Ta({type:"optional",innerType:e})}var Ip=h("ZodNullable",(e,t)=>{Wu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Td(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Gr(e){return new Ip({type:"nullable",innerType:e})}function Dv(e){return Bt(Gr(e))}var zp=h("ZodDefault",(e,t)=>{Gu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Pp(e,t){return new zp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var jp=h("ZodPrefault",(e,t)=>{qu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ud(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ap(e,t){return new jp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var Oa=h("ZodNonOptional",(e,t)=>{Hu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Od(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Tp(e,t){return new Oa({type:"nonoptional",innerType:e,...b.normalizeParams(t)})}var Op=h("ZodSuccess",(e,t)=>{Xu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$d(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Uv(e){return new Op({type:"success",innerType:e})}var Np=h("ZodCatch",(e,t)=>{Yu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Dp(e,t){return new Np({type:"catch",innerType:e,catchValue:typeof t=="function"?t:b.constantCatch(t)})}var Up=h("ZodNaN",(e,t)=>{Qu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vd(e,r,o,n)});function Cv(e){return Jl(Up,e)}var ti=h("ZodPipe",(e,t)=>{fo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ed(e,r,o,n),e.in=t.in,e.out=t.out});function ca(e,t){return new ti({type:"pipe",in:e,out:t})}var ni=h("ZodCodec",(e,t)=>{ti.init(e,t),Nr.init(e,t)});function Ev(e,t,r){return new ni({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function Rv(e){let t=e._zod.def;return new ni({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var Cp=h("ZodPreprocess",(e,t)=>{ti.init(e,t),el.init(e,t)}),Ep=h("ZodReadonly",(e,t)=>{tl.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Rp(e){return new Ep({type:"readonly",innerType:e})}var Mp=h("ZodTemplateLiteral",(e,t)=>{nl.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yd(e,r,o,n)});function Mv(e,t){return new Mp({type:"template_literal",parts:e,...b.normalizeParams(t)})}var Lp=h("ZodLazy",(e,t)=>{Dr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ld(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Zp(e){return new Lp({type:"lazy",getter:e})}var Fp=h("ZodPromise",(e,t)=>{il.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Md(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Lv(e){return new Fp({type:"promise",innerType:e})}var Vp=h("ZodFunction",(e,t)=>{rl.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xd(e,r,o,n)});function Zv(e){return new Vp({type:"function",input:Array.isArray(e?.input)?yp(e?.input):e?.input??Xr(Kt()),output:e?.output??Kt()})}var ri=h("ZodCustom",(e,t)=>{ol.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_d(e,r,o,n)});function Fv(e){let t=new q({check:"custom"});return t._zod.check=e,t}function Vv(e,t){return Wl(ri,e??(()=>!0),t)}function Jp(e,t={}){return Gl(ri,e,t)}function Kp(e,t){return ql(e,t)}var Jv=Hl,Kv=Xl,Bp=h("ZodInstanceOf",(e,t)=>{ri.init(e,t)},{properties(e,t){return this.check(Nn(e,t))}});function Bv(e,t={}){let r=new Bp({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 Wv=(...e)=>Yl({Codec:ni,Boolean:Wn,String:Kn},...e);function Gv(e){let t=Zp(()=>qn([Wr(e),np(),rp(),sp(),Xr(t),bp(Wr(),t)]));return t}function qv(e,t){return new Cp({type:"pipe",in:Aa(e),out:t})}var xS={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 kS(e){ne({customError:e})}function wS(){return ne().customError}var Wp;Wp||(Wp={});var ii={};rt(ii,{ZodISODate:()=>St,ZodISODateTime:()=>wt,ZodISODuration:()=>zt,ZodISOTime:()=>It,date:()=>IS,datetime:()=>SS,duration:()=>PS,time:()=>zS});function SS(e){return Zr(wt,e)}function IS(e){return Fr(St,e)}function zS(e){return Vr(It,e)}function PS(e){return Jr(zt,e)}var z={...Hn,...oa,iso:ii},jS=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 AS(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 Hv(e,t){return e.map((r,o)=>o<t?r:r.optional())}function TS(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function OS(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:TS(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 NS(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 s=t.keySchema.safeParse(a);s.success||o.issues.push({code:"invalid_key",origin:"record",issues:s.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function Gp(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 s=Gp(a,t);if(s===null)return null;i.push(s)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let a=Gp(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 DS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),US=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function oi(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(oi):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>DS.has(t)?oi(r):!US.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(oi))}function Xv(e){return e===1?"element":"elements"}function CS(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 s=Gp(n[a],new Set);if(s===null)continue;let u=i.get(s);if(u===void 0){i.set(s,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,s=0;for(let u of n)if(t.containsSchema.safeParse(u).success&&++s>=a)break;s<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${Xv(i)}; found ${s}`,input:n,continue:!0}),t.maxContains!==void 0&&s>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${Xv(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Yv(e,t){if(e!==!1)return e===void 0||e===!0?z.any():_e(e,t)}var ES=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Qv(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=OS(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 Qv(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(ES)):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||[]),s=typeof e.additionalProperties=="object"?_e(e.additionalProperties,t):void 0;for(let[p,m]of Object.entries(i)){let f=_e(m,t);le(n,p,a.has(p)?f:f.optional())}if(e.patternProperties){let p=e.patternProperties,m=Object.keys(p),f=[];for(let y of m){let x=_e(p[y],t),I=z.string().regex(new RegExp(y));f.push(z.looseRecord(I,x))}let g=[];if(Object.keys(n).length>0&&g.push(z.object(n).passthrough()),g.push(...f),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 x=2;x<g.length;x++)y=z.intersection(y,g[x]);o=y}if(e.additionalProperties===!1){let y=Object.keys(n),x=m.map(S=>new RegExp(S)),I=o;o=o.check(S=>{if(!Ue(S.value))return;let T=[];for(let P of Object.keys(S.value))y.includes(P)||x.some(C=>C.test(P))||T.push(P);T.length&&S.issues.push({code:"unrecognized_keys",keys:T,input:S.value,inst:I})})}}else{let p=z.object(n);e.additionalProperties===!1?o=p.strict():s?o=p.catchall(s):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 m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=_e(m,t)}o=NS(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,s=n.map(p=>_e(p,t)),u=Hv(s,a),l=Array.isArray(i)?void 0:Yv(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,s=i.map(p=>_e(p,t)),u=Hv(s,a),l=Yv(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),s=z.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=z.array(z.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=CS(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=Qv(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(l=>_e(l,t)),u=z.union(s);r=o?z.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(l=>_e(l,t)),u=z.xor(s);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 s=o?r:_e(e.allOf[0],t),u=o?0:1;for(let l=u;l<e.allOf.length;l++)s=z.intersection(s,_e(e.allOf[l],t));r=s}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 s of i)s in e&&(n[s]=e[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in e&&(n[s]=e[s]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!oi(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let s of["minProperties","maxProperties"])e[s]!==void 0&&(n[s]=e[s])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!oi(e.contains)&&(n.contains=e.contains);for(let s of["uniqueItems","minContains","maxContains"])e[s]!==void 0&&(n[s]=e[s])}for(let s of Object.keys(e))jS.has(s)||le(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function ey(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=AS(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??de};return _e(r,i)}var ty=Symbol("z.visit/resolving");function ai(e,t){let r=typeof t=="function"?t:(a,s)=>{let u=t[a._zod.def.type];return u?u(a,s):a},o=new Map;function n(a){let s=o.get(a);if(s===ty)return new Dr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,ty);let u=i(a),l=r(u,u!==a);return o.set(a,l),l}function i(a){let s=a._zod.def,u=s.type;switch(u){case"object":{let l=s.shape,d=Object.keys(l),p=!1,m={};for(let g of d){let y=n(l[g]);y!==l[g]&&(p=!0),m[g]=y}let f=s.catchall;return s.catchall&&(f=n(s.catchall),f!==s.catchall&&(p=!0)),p?V(a,{...s,shape:m,catchall:f}):a}case"array":{let l=n(s.element);return l===s.element?a:V(a,{...s,element:l})}case"tuple":{let l=s.items,d=!1,p=[];for(let f of l){let g=n(f);g!==f&&(d=!0),p.push(g)}let m=s.rest;return s.rest&&(m=n(s.rest),m!==s.rest&&(d=!0)),d?V(a,{...s,items:p,rest:m}):a}case"record":case"map":{let l=n(s.keyType),d=n(s.valueType);return l===s.keyType&&d===s.valueType?a:V(a,{...s,keyType:l,valueType:d})}case"set":{let l=n(s.valueType);return l===s.valueType?a:V(a,{...s,valueType:l})}case"union":{let l=s.options,d=!1,p=[];for(let m of l){let f=n(m);f!==m&&(d=!0),p.push(f)}return d?V(a,{...s,options:p}):a}case"intersection":{let l=n(s.left),d=n(s.right);return l===s.left&&d===s.right?a:V(a,{...s,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(s.innerType);return l===s.innerType?a:V(a,{...s,innerType:l})}case"pipe":{let l=n(s.in),d=n(s.out);return l===s.in&&d===s.out?a:V(a,{...s,in:l,out:d})}case"function":{let l=n(s.input),d=n(s.output);return l===s.input&&d===s.output?a:V(a,{...s,input:l,output:d})}case"lazy":{let l=s.getter,{_cachedInner:d,...p}=s;return V(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 ny(e){return ai(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:qn(r.options)}})}function RS(e,t){if(!t?.length)return e;let r=e._zod.def;return V(e,Le(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function ry(e){return RS(e.out,e.checks)}function MS(e){return e.in._zod.traits.has("$ZodTransform")?ry(e):e.in}function iy(e){return ai(e,{pipe:t=>MS(t._zod.def),default:(t,r)=>r?Bt(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function oy(e){return ai(e,{pipe:t=>ry(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var qp={};rt(qp,{bigint:()=>VS,boolean:()=>FS,date:()=>JS,number:()=>ZS,string:()=>LS});function LS(e){return vl(Kn,e)}function ZS(e){return kl(Bn,e)}function FS(e){return Al(Wn,e)}function VS(e){return Ol(Gn,e)}function JS(e){return Vl(Hr,e)}var Xn=c.string().min(1).max(512).refine(KS,"Invalid path: use segments like notes/plan.md, without .. or a leading /");function KS(e){return/[\u0000-\u001f\u007f\\]/.test(e)?!1:e.split("/").every(r=>r.length>0&&r.length<=255&&r!=="."&&r!=="..")}var si=c.string().regex(me("message")),H=c.string().regex(me("thread")),Pe=c.string().regex(me("project")),je=c.string().regex(me("task")),Hp=c.string().regex(me("artifact")),R=c.iso.datetime(),ci=c.enum(["user","agent","system"]),BS=c.object({path:Xn,name:c.string(),size:c.number().int().nonnegative(),contentType:c.string()}),WS=c.object({artifactId:Hp,version:c.number().int().positive(),title:c.string()}),ay=c.enum(["cloud","local"]),X=c.number().int().nonnegative(),GS=c.object({title:c.string(),harness:c.string(),runtime:ay,model:c.string().nullable(),durationMs:X,inputTokens:X,outputTokens:X,costMicros:X.nullable()}),qS=c.object({chars:X,limit:X,parts:c.object({instructions:X,skills:X,knowledge:X,brief:X,conversation:X,notes:X,other:X}),droppedMessages:X,droppedNotes:X,cut:c.boolean()}),HS=c.object({model:c.string(),durationMs:X,calls:X,inputTokens:X,cachedInputTokens:X,outputTokens:X,costMicros:X.nullable(),runtime:ay,computer:c.string().optional(),harness:c.string().optional(),task:GS.optional(),prompt:qS.optional()}),XS=c.enum(["brief","follow_up","reply","relay","answer"]),YS=c.object({kind:XS,threadId:H,fromThreadId:H.optional(),note:c.string()}),Na=8,Ht=c.object({id:si,projectId:Pe,threadId:H.nullable(),authorKind:ci,authorId:c.string().min(1),body:c.string(),attachments:c.array(BS).optional(),artifacts:c.array(WS).optional(),stats:HS.optional(),relay:YS.optional(),clis:c.array(c.string().max(40)).max(Na).optional(),seq:c.number().int().positive(),createdAt:R,editedAt:R.optional()}),QS=c.enum(["working","blocked","review_ready","done","failed"]),eI=c.object({id:c.string().max(40),options:c.array(c.string().max(40)).max(Na),by:c.enum(["person","coordinator"]),reason:c.string().max(300).nullable()}),tI=c.object({cli:c.string().max(40),model:c.string().max(200).nullable(),effort:c.string().max(20).nullable()}),sy="cloud",nI=c.object({id:c.string().max(60),by:c.enum(["person","auto","coordinator"]),reason:c.string().max(300).nullable().default(null)}),Xp=c.enum(["duplicate","misrouted","cancelled"]),rI=c.object({replies:X,usage:c.object({tokens:X,durationMs:X,costMicros:X.nullable()}).nullable(),planMessageId:si.nullable()}),Yp=c.object({id:H,projectId:Pe,rootMessageId:si,ackMessageId:si.nullable().default(null),title:c.string(),status:QS,statusText:c.string().nullable(),resolved:c.boolean(),closeReason:Xp.nullable().default(null),duplicateOf:H.nullable().default(null),label:c.string().nullable(),cli:eI.nullable().default(null),runner:nI.nullable().default(null),model:tI.nullable().default(null),seenSeq:c.number().int().nonnegative().nullable().default(null),summary:rI.nullable().default(null),createdAt:R,updatedAt:R}),iI=c.enum(["running","done","failed","cancelled"]),cy=c.object({id:je,threadId:H,title:c.string(),harness:c.string(),backend:c.string(),status:iI,prUrl:c.string().nullable(),summary:c.string().nullable(),createdAt:R,finishedAt:R.nullable()}),aD=c.object({ref:c.string(),commits:c.array(c.object({hash:c.string(),message:c.string(),at:c.string()})),entries:c.array(c.object({name:c.string(),path:c.string(),type:c.enum(["file","folder"])})).nullable(),file:c.object({path:c.string(),text:c.string().nullable(),size:c.number(),truncated:c.boolean()}).nullable()}),Qp=c.object({id:c.string().min(1).max(200),label:c.string().max(100),state:c.enum(["started","done","failed"]).optional(),model:c.string().max(200).optional(),tokens:c.number().int().nonnegative().optional()}),uy=c.object({stream:c.enum(["stdout","stderr","system"]),text:c.string(),at:c.number().optional(),ms:c.number().nonnegative().optional(),tool:c.boolean().optional(),agent:Qp.optional()}),ef=c.object({messageId:si,emoji:c.string().min(1).max(32),authorKind:ci,authorId:c.string().min(1)}),Da=c.enum(["owner","admin","member"]),oI=c.object({working:c.number().int().nonnegative(),waiting:c.number().int().nonnegative()}),aI=c.object({monthMicros:c.number().int().nonnegative(),totalMicros:c.number().int().nonnegative()}),Ua=c.enum(["indigo","blue","teal","green","amber","orange","red","pink","purple","gray"]),Ca=c.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"]),sD=c.object({id:Pe,name:c.string().min(1).max(120),role:Da,icon:Ca.nullable().optional(),color:Ua.nullable().optional(),createdAt:R,activity:oI.optional(),cost:aI.optional(),pinned:c.boolean().optional()}),cD=c.object({pinned:c.boolean()}),uD=c.object({name:c.string().trim().min(1).max(120)}),lD=c.object({id:c.string(),name:c.string(),role:Da,email:c.string().optional()}),tf=32e3,sI=c.object({id:c.number().int(),accountLogin:c.string(),accountType:c.enum(["User","Organization"]),accountAvatarUrl:c.string().nullable()}),dD=c.object({configured:c.boolean(),installUrl:c.string().nullable(),installations:c.array(sI)}),pD=c.object({id:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),description:c.string().nullable()}),fD=c.object({repoId:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),createdAt:R}),ly=c.object({repo:c.string(),number:c.number().int(),url:c.string(),threadId:H,title:c.string(),state:c.enum(["open","closed","merged"]),draft:c.boolean(),checks:c.enum(["pending","success","failure"]).nullable(),review:c.enum(["approved","changes_requested"]).nullable(),conflict:c.boolean().default(!1),branch:c.string().default(""),additions:c.number().int().nullable().default(null),deletions:c.number().int().nullable().default(null),changedFiles:c.number().int().nullable().default(null),updatedAt:R}),cI=c.object({path:c.string(),previousPath:c.string().nullable(),status:c.enum(["added","removed","modified","renamed","copied","changed","unchanged"]),additions:c.number().int(),deletions:c.number().int(),patch:c.string().nullable()}),mD=c.object({files:c.array(cI),truncated:c.boolean()}),dy=c.enum(["merge","squash","rebase"]),gD=c.object({permitted:c.boolean(),blocked:c.enum(["closed","draft","conflict","checks_failed","checks_pending","changes_requested","protected","checking"]).nullable(),methods:c.array(dy),sha:c.string()}),hD=c.object({method:dy,sha:c.string().min(1),deleteBranch:c.boolean().default(!1)}),vD=c.object({merged:c.literal(!0),branchDeleted:c.boolean(),branchKept:c.enum(["fork","default","protected","gone","in_use","reopened","failed"]).nullable()}),yD=c.object({installationId:c.number().int().positive(),repoId:c.number().int().positive()});var uI=16e3,lI=16e3,kD=25*1024*1024,py=10;var wD=c.object({path:Xn,size:c.number().int().nonnegative(),contentType:c.string(),updatedAt:R,updatedByKind:ci,updatedBy:c.string()}),dI=c.string().trim().min(1).max(80).regex(/^[\p{L}\p{N}][\p{L}\p{N} _.-]*$/u,"Use letters, numbers, spaces, dots, dashes or underscores"),pI=c.enum(["ok","stale"]),fI=c.object({name:dI,description:c.string().max(300),content:c.string().max(lI),updatedAt:R,updatedByKind:ci,updatedBy:c.string(),status:pI.default("ok"),staleReason:c.string().max(300).nullable().default(null),verifiedAt:R.nullable().default(null),previousContent:c.string().nullable().default(null),previousAt:R.nullable().default(null)}),SD=fI.pick({description:!0,content:!0}),ID=c.discriminatedUnion("status",[c.object({status:c.literal("ok")}),c.object({status:c.literal("stale"),reason:c.string().trim().min(1).max(300)})]),mI=c.object({text:c.string().max(uI),updatedAt:R.nullable(),updatedBy:c.string().nullable()}),zD=mI.pick({text:!0}),fy=c.enum(["files","memory","instructions"]),my=c.enum(["auto","on","off"]),PD=c.object({mode:my,active:c.boolean(),lastRunAt:R.nullable(),threadsSince:c.number().int().nonnegative(),threadsNeeded:c.number().int().positive(),threadId:c.string().nullable()}),jD=c.object({mode:my});var nf=c.object({id:Hp,projectId:Pe,threadId:H.nullable(),title:c.string(),description:c.string().nullable(),version:c.number().int().positive(),createdAt:R,updatedAt:R}),ND=c.object({version:c.number().int().positive(),size:c.number().int().nonnegative(),threadId:H.nullable(),createdAt:R}),DD=c.object({version:c.number().int().positive(),url:c.string().nullable(),expiresAt:R.nullable()}),UD=2*1024*1024;var rf=c.string().regex(me("routine")),gI=/^(\*|\d+(-\d+)?)(\/\d+)?(,(\*|\d+(-\d+)?)(\/\d+)?)*$/,hI=c.string().trim().refine(e=>{let t=e.split(/\s+/);return t.length===5&&t.every(r=>gI.test(r))},"Expected a five-field cron expression, e.g. 0 9 * * 1-5"),vI=c.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}},"Unknown time zone"),of=c.discriminatedUnion("kind",[c.object({kind:c.literal("cron"),cron:hI,timezone:vI.default("UTC")}),c.object({kind:c.literal("once"),at:R})]),af=c.discriminatedUnion("kind",[c.object({kind:c.literal("coordinator")}),c.object({kind:c.literal("thread"),threadId:H})]),sf=c.object({id:rf,projectId:Pe,name:c.string(),prompt:c.string(),target:af,schedule:of,paused:c.boolean(),nextRunAt:R.nullable(),lastRunAt:R.nullable(),runCount:c.number().int().nonnegative(),createdBy:c.string(),createdAt:R});var LD=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:af.default({kind:"coordinator"}),schedule:of}),ZD=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:af,schedule:of,paused:c.boolean()}).partial();var cf=c.object({text:c.string(),until:c.string(),createdBy:c.string(),createdAt:c.string(),wakes:c.number().int().nonnegative(),threads:c.number().int().nonnegative(),idle:c.number().int().nonnegative()});var yI=c.string().regex(me("sshHost")),uf=c.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Use lowercase letters, digits, - and _ (up to 40)."),Ea=c.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."),gy=c.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/,"Enter the user name on the server."),hy=c.enum(["ask","off"]),GD=c.string().max(16e3).regex(/^(?:ssh|ecdsa|sk)-[\w@.-]+ [A-Za-z0-9+/=]+(?: .*)?$/),vy=c.string().max(200).regex(/^SHA256:[A-Za-z0-9+/=]+$/),bI=c.object({id:yI,projectId:Pe,alias:uf,host:c.string(),port:c.number().int(),user:c.string(),runnerId:c.string(),runnerName:c.string(),mine:c.boolean(),keySource:c.enum(["new","existing"]),publicKey:c.string().nullable(),keyFingerprint:c.string().nullable(),hostFingerprint:c.string().nullable(),rule:hy,testedAt:R.nullable(),createdAt:R}),$I=c.object({id:c.string(),alias:c.string(),threadId:c.string().nullable(),command:c.string(),reason:c.string().nullable(),decision:c.enum(["once","turn","deny","timeout","failed"]),approvedBy:c.string().nullable(),exitCode:c.number().int().nullable(),ms:c.number().int().nullable(),at:R}),qD=c.object({hosts:c.array(bI),history:c.array($I)}),HD=c.object({runnerId:c.string(),alias:uf,host:Ea,port:c.number().int().min(1).max(65535).default(22),user:gy,existingKey:c.string().min(1).max(1024).optional()}),XD=c.object({rule:hy}),YD=c.object({hostKey:c.string().min(1).max(16e3)}),yy=c.object({type:c.string().max(60),key:c.string().max(16e3),fingerprint:vy}),by=c.object({path:c.string().max(1024),name:c.string().max(255),type:c.string().max(60),fingerprint:vy,comment:c.string().max(500)}),$y=c.object({exitCode:c.number().int().nullable(),stdout:c.string(),stderr:c.string(),truncated:c.boolean(),ms:c.number().int().nonnegative(),error:c.enum(["hostkey","auth","connect","timeout","nokey","other"]).optional()}),_y=300*1e3,xy=200*1024,Ra=c.object({projectId:Pe,alias:uf}),lf=Ra.extend({host:Ea,port:c.number().int().min(1).max(65535),user:gy,hostKey:c.string().min(1).max(16e3)});var Sy=2,ut=c.string().regex(me("runner")),qe=c.enum(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]),Za={claude:"Claude Code",codex:"Codex CLI",antigravity:"Antigravity CLI",opencode:"OpenCode",hermes:"Hermes Agent",cursor:"Cursor CLI",muse:"Muse Code",kimi:"Kimi Code"},Iy=c.object({path:c.string().min(1).max(1024),name:c.string().max(255)}),_I=c.object({kind:c.string().max(40),usedPercent:c.number().min(0).max(1e3).nullable(),resetsAt:R.nullable()}),xI=c.object({status:c.enum(["ok","warning","limited"]).optional(),windows:c.array(_I).max(8),at:R});var kI=c.object({id:c.string().min(1).max(200),name:c.string().max(200),efforts:c.array(c.string().min(1).max(20)).max(10)});var wI=c.object({id:qe,version:c.string().max(200).nullable(),limits:xI.optional().catch(void 0),models:c.array(kI).max(100).optional().catch(void 0)}),SI=c.enum(["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","update","models","github-token","git-token","steer","steer-claude","ssh","stats"]),II=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:c.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}),c.object({transport:c.literal("stdio"),name:c.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),command:c.string().min(1).max(200),args:c.array(c.string().max(2e3)).max(50),env:c.record(c.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),c.string().max(4e3))})]),zI=c.enum(["read","edit","auto","full"]),pf=c.object({access:zI,worktrees:c.boolean(),autoUpdate:c.boolean(),remote:c.boolean()}),zy=pf.omit({remote:!0}).partial(),PI=c.enum(["service","app","manual"]),df=c.object({state:c.enum(["waiting","downloading","restarting","failed","rolled-back"]),version:c.string().max(50),running:c.number().int().nonnegative().optional(),message:c.string().max(500).optional(),at:R}),Py=c.object({version:c.string().max(50),hostname:c.string().max(255),platform:c.string().max(50),folders:c.array(Iy).max(200),clis:c.array(c.unknown()).max(10).transform(e=>e.flatMap(t=>{let r=wI.safeParse(t);return r.success?[r.data]:[]})),features:c.array(c.string().max(50)).max(20).default([]).transform(e=>e.filter(t=>SI.safeParse(t).success)),settings:pf.optional().catch(void 0),updates:PI.optional().catch(void 0),update:df.optional().catch(void 0)}),Xt=c.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),La=c.object({at:R,cpu:c.object({percent:c.number().min(0).max(100).optional(),cores:c.number().int().min(1).max(1024)}),memory:c.object({total:Xt,available:Xt}),swap:c.object({total:Xt,used:Xt}).optional(),disk:c.object({total:Xt,free:Xt}).optional(),tasks:c.number().int().nonnegative().max(1e3),runnerMemory:Xt.optional()}),Ma=1e5,Q=c.string().min(1).max(64),jI=c.object({name:c.string().max(255),path:c.string().max(1024)}),AI=c.object({path:c.string().max(1024),parent:c.string().max(1024).nullable(),home:c.string().max(1024),dirs:c.array(jI).max(1e3)}),ky=c.object({inputTokens:c.number().int().nonnegative(),outputTokens:c.number().int().nonnegative(),model:c.string().max(200).optional()}),ff=512*1024,TI=c.object({path:c.string().max(4096),size:c.number().int().nonnegative(),data:c.string().max(Math.ceil(ff/3)*4+4),truncated:c.boolean()}),OI=c.object({model:c.string().min(1).max(200).optional(),effort:c.string().min(1).max(20).optional()}),wy=c.object({token:c.string().min(20).max(4096),expiresAt:R,repos:c.array(c.string().regex(/^[\w.-]+\/[\w.-]+$/).max(200)).max(100)}),iU=c.discriminatedUnion("type",[Py.extend({type:c.literal("hello"),protocol:c.number().int().positive(),running:c.array(je).max(100).default([]),interrupted:c.array(je).max(100).default([]),stats:La.optional().catch(void 0)}),c.object({type:c.literal("task.progress"),taskId:je,text:c.string().max(2e3),usage:ky.optional(),agent:Qp.optional(),ms:c.number().nonnegative().optional()}),c.object({type:c.literal("task.done"),taskId:je,ok:c.boolean(),usage:ky.optional(),result:c.string().max(Ma),cancelled:c.boolean().optional()}),c.object({type:c.literal("ping"),stats:La.optional().catch(void 0)}),c.object({type:c.literal("task.folders"),taskId:je,folders:c.array(c.string().min(1).max(1024)).max(60)}),AI.extend({type:c.literal("dirs"),requestId:Q}),c.object({type:c.literal("folders"),requestId:Q,folders:c.array(Iy).max(200)}),c.object({type:c.literal("request.failed"),requestId:Q,message:c.string().max(500)}),TI.extend({type:c.literal("file"),requestId:Q}),c.object({type:c.literal("settings"),requestId:Q,settings:pf}),c.object({type:c.literal("update.accepted"),requestId:Q,update:df}),c.object({type:c.literal("update.status"),update:df.nullable()}),c.object({type:c.literal("task.steered"),requestId:Q,taken:c.boolean()}),c.object({type:c.literal("ssh.key"),requestId:Q,publicKey:c.string().max(16e3),fingerprint:c.string().max(200),protected:c.boolean()}),c.object({type:c.literal("ssh.keylist"),requestId:Q,keys:c.array(by).max(100)}),c.object({type:c.literal("ssh.hostkeylist"),requestId:Q,keys:c.array(yy).max(10)}),$y.extend({type:c.literal("ssh.result"),requestId:Q})]),jy=c.discriminatedUnion("type",[c.object({type:c.literal("welcome"),runnerId:ut,name:c.string()}),c.object({type:c.literal("task.start"),taskId:je,threadId:H,folder:c.string().min(1).max(1024),cli:qe,prompt:c.string().min(1).max(Ma),model:OI.optional(),folders:c.array(c.string().min(1).max(1024)).max(50).optional(),agent:c.object({mcpPath:c.string().regex(/^\/api\/[\w/-]+$/).max(300),token:c.string().min(20).max(200),connectors:c.array(II).max(30).optional(),skills:c.object({path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}).optional(),resume:c.object({after:je,prompt:c.string().min(1).max(Ma)}).optional()}).optional(),github:wy.optional()}),c.object({type:c.literal("task.github"),taskId:je,github:wy}),c.object({type:c.literal("task.steer"),requestId:Q,taskId:je,text:c.string().min(1).max(Ma)}),c.object({type:c.literal("task.cancel"),taskId:je}),c.object({type:c.literal("pong")}),c.object({type:c.literal("dirs.list"),requestId:Q,path:c.string().max(1024).optional()}),c.object({type:c.literal("folder.share"),requestId:Q,path:c.string().min(1).max(1024)}),c.object({type:c.literal("folder.unshare"),requestId:Q,path:c.string().min(1).max(1024)}),c.object({type:c.literal("file.read"),requestId:Q,path:c.string().min(1).max(4096),folders:c.array(c.string().min(1).max(1024)).min(1).max(51),threadId:H.optional()}),c.object({type:c.literal("settings.set"),requestId:Q,settings:zy}),c.object({type:c.literal("runner.update"),requestId:Q,version:c.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/).max(50),now:c.boolean().default(!1)}),Ra.extend({type:c.literal("ssh.keygen"),requestId:Q,comment:c.string().max(200),existing:c.string().min(1).max(1024).optional()}),c.object({type:c.literal("ssh.keys"),requestId:Q}),c.object({type:c.literal("ssh.hostkeys"),requestId:Q,host:Ea,port:c.number().int().min(1).max(65535)}),c.object({type:c.literal("ssh.test"),requestId:Q,target:lf}),c.object({type:c.literal("ssh.run"),requestId:Q,target:lf,command:c.string().min(1).max(2e4)}),Ra.extend({type:c.literal("ssh.forget"),requestId:Q})]),NI=Py.extend({id:ut,name:c.string(),version:c.string().nullable(),online:c.boolean(),lastSeenAt:R.nullable(),createdAt:R,stats:La.optional()}),oU=c.object({name:c.string().trim().min(1).max(80).optional(),settings:zy.optional()}),aU=c.object({now:c.boolean().default(!1)}),sU=c.object({runners:c.array(NI),latestVersion:c.string().nullable()}),cU=c.object({code:c.string(),expiresAt:R}),uU=c.object({code:c.string().trim().min(4).max(20),name:c.string().trim().min(1).max(80),hostname:c.string().max(255).default(""),platform:c.string().max(50).default("")}),Ay=c.object({runner:c.object({id:ut,name:c.string()}),token:c.string()}),lU=c.object({projectId:Pe,runnerId:ut,runnerName:c.string(),path:c.string(),folders:c.array(c.string()).default([]),cli:qe,online:c.boolean(),isDefault:c.boolean().default(!0),stats:La.optional()}),dU=c.object({path:c.string().trim().min(1).max(1024)}),pU=c.object({runnerId:ut,path:c.string().min(1).max(1024),cli:qe,add:c.boolean().optional()}),fU=c.object({path:c.string().min(1).max(1024),runnerId:ut.optional()}),mU=c.object({runnerId:ut});function Ty(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 DI=200,UI=c.object({threadId:H.nullable(),hasEarlier:c.boolean()});var wU=c.discriminatedUnion("type",[c.object({type:c.literal("message.send"),clientId:c.string().max(64).optional(),threadId:H.nullable().default(null),body:c.string().trim().max(tf),attachments:c.array(Xn).max(py).default([]),clis:c.array(qe).max(Na).optional()}).refine(e=>e.body.length>0||e.attachments.length>0,"Write something or attach a file"),c.object({type:c.literal("message.edit"),messageId:Ht.shape.id,body:c.string().trim().max(tf)}),c.object({type:c.literal("thread.resolve"),threadId:H,resolved:c.boolean(),reason:Xp.optional()}),c.object({type:c.literal("thread.cli"),threadId:H,cli:qe.nullable()}),c.object({type:c.literal("thread.runner"),threadId:H,runnerId:c.union([ut,c.literal(sy)]).nullable()}),c.object({type:c.literal("thread.model"),threadId:H,cli:qe,model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),c.object({type:c.literal("goal.stop")}),c.object({type:c.literal("sync"),afterSeq:c.number().int().nonnegative(),all:c.boolean().optional(),recent:c.number().int().positive().max(DI).optional()})]),SU=c.discriminatedUnion("type",[c.object({type:c.literal("message.created"),message:Ht}),c.object({type:c.literal("message.updated"),message:Ht}),c.object({type:c.literal("message.ack"),clientId:c.string(),messageId:Ht.shape.id,seq:Ht.shape.seq}),c.object({type:c.literal("sync.result"),messages:c.array(Ht),hasMore:c.boolean(),streamed:c.boolean().optional(),threads:c.array(Yp).default([]),reactions:c.array(ef).default([]),artifacts:c.array(nf).default([]),routines:c.array(sf).default([]),goal:cf.nullable().optional(),windows:c.array(UI).optional(),reset:c.boolean().optional(),lastSeq:c.number().int().nonnegative().optional()}),c.object({type:c.literal("thread.updated"),thread:Yp}),c.object({type:c.literal("reaction.added"),reaction:ef}),c.object({type:c.literal("artifact.updated"),artifact:nf}),c.object({type:c.literal("routine.updated"),routine:sf}),c.object({type:c.literal("routine.deleted"),routineId:rf}),c.object({type:c.literal("goal.updated"),goal:cf.nullable()}),c.object({type:c.literal("agent.activity"),threadId:H.nullable(),active:c.boolean(),label:c.string().max(200).optional()}),c.object({type:c.literal("knowledge.changed"),kind:fy}),c.object({type:c.literal("workspace.changed")}),c.object({type:c.literal("task.updated"),task:cy}),c.object({type:c.literal("task.output"),taskId:je,threadId:H,lines:c.array(uy)}),c.object({type:c.literal("pr.updated"),pullRequest:ly}),c.object({type:c.literal("error"),code:c.string(),message:c.string()})]);var PU=c.object({app:c.literal("myrel"),apiVersion:c.number().int().positive(),name:c.string(),auth:c.object({emailPassword:c.boolean(),signUp:c.boolean().default(!0),emailVerification:c.boolean().default(!1),captcha:c.object({provider:c.literal("turnstile"),siteKey:c.string()}).nullable().default(null),passwordReset:c.boolean().default(!1)}),billing:c.boolean().default(!1),legal:c.object({terms:c.string().url(),privacy:c.string().url(),version:c.string()}).nullable().default(null)});var TU=c.object({question:c.string().min(1).max(300),options:c.array(c.object({label:c.string().min(1).max(40),consequence:c.string().max(200).default("")})).min(2).max(4),recommended:c.number().int().nonnegative().optional(),danger:c.boolean().optional()});var ui=c.enum(["fireworks","anthropic","openai"]),RU=c.object({id:ui,name:c.string(),defaultModel:c.string(),serverKey:c.boolean()}),MU=c.object({id:c.string(),provider:ui,label:c.string(),hint:c.string(),scope:c.enum(["user","instance"]),createdAt:c.iso.datetime()}),LU=c.object({provider:ui,label:c.string().trim().min(1).max(80),key:c.string().trim().min(8).max(500),scope:c.enum(["user","instance"]).default("user")}),Oy=c.enum(["auto","local","cloud"]),Ny=c.enum(["opencode","claude","codex"]),CI=c.object({model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),Dy=c.partialRecord(qe,CI),ZU=c.object({name:c.string(),provider:ui.nullable(),model:c.string().nullable(),keyId:c.string().nullable(),taskTarget:Oy,icon:Ca.nullable().default(null),color:Ua.nullable().default(null),cloudCli:Ny.default("opencode"),cliModels:Dy.default({})}),FU=c.object({name:c.string().trim().min(1).max(120).optional(),provider:ui.nullable().optional(),model:c.string().trim().max(200).nullable().optional(),keyId:c.string().nullable().optional(),taskTarget:Oy.optional(),icon:Ca.nullable().optional(),color:Ua.nullable().optional(),cloudCli:Ny.optional(),cliModels:Dy.optional()}),Uy=c.enum(["admin","member"]),VU=c.object({id:c.string(),projectId:c.string(),projectName:c.string(),email:c.string(),role:Uy,invitedBy:c.string(),createdAt:c.iso.datetime()}),JU=c.object({email:c.email().trim().toLowerCase(),role:Uy.default("member")}),KU=c.object({role:Da}),EI=c.enum(["admin","user"]),BU=c.enum(["computer","decision"]),WU=c.object({id:c.string(),name:c.string(),email:c.string(),role:EI,onboarded:c.boolean().optional(),tips:c.array(c.string()).optional()}),RI=c.object({signUpEnabled:c.boolean()}),MI=c.enum(["api","agent","cron","web","desktop","mobile"]),GU=c.object({platform:c.enum(["web","desktop","mobile"]),where:c.string().trim().min(1).max(200),name:c.string().max(100).default("Error"),message:c.string().max(500),stack:c.string().max(4e3).optional(),version:c.string().max(40).optional()}),qU=c.object({id:c.string(),source:MI,where:c.string(),name:c.string(),message:c.string(),stack:c.string().nullable(),count:c.number().int(),firstSeenAt:c.number(),lastSeenAt:c.number()}),HU=c.object({days:c.number().int(),signedUp:c.number().int(),verified:c.number().int(),inProject:c.number().int(),asked:c.number().int(),threadRan:c.number().int(),pairedComputer:c.number().int()}),XU=RI.partial();var Cy=c.string().regex(me("notification")),LI=c.enum(["done","ready","decision","blocked","failed"]),n4=c.object({id:Cy,projectId:Pe,threadId:H.nullable(),kind:LI,title:c.string(),body:c.string(),url:c.string(),readAt:R.nullable(),createdAt:R}),r4=c.object({email:c.boolean(),push:c.boolean()}),i4=c.object({webPushKey:c.string().nullable(),email:c.boolean()}),ZI=[/^fcm\.googleapis\.com$/,/^updates\.push\.services\.mozilla\.com$/,/^web\.push\.apple\.com$/,/^[a-z0-9-]+\.notify\.windows\.com$/];function FI(e){try{let t=new URL(e);return t.protocol==="https:"&&ZI.some(r=>r.test(t.hostname))}catch{return!1}}var o4=c.discriminatedUnion("kind",[c.object({kind:c.literal("webpush"),endpoint:c.url().max(2048).refine(FI,"Not a browser push service"),keys:c.object({p256dh:c.string().min(1).max(256),auth:c.string().min(1).max(64)})}),c.object({kind:c.literal("expo"),token:c.string().regex(/^Expo(nent)?PushToken\[[^\]]+\]$/).max(256)})]),a4=c.union([c.object({ids:c.array(Cy).min(1).max(200)}),c.object({all:c.literal(!0)})]);var VI=new RegExp(me("thread").source.slice(1,-1)),p4=new RegExp(`^#(${VI.source})$`);var JI=c.enum(["http","stdio"]),KI=c.enum(["user","project"]),gf=c.enum(["cloud","local","both"]),BI=c.enum(["unknown","ok","error","needs_auth"]),WI=c.enum(["none","headers","oauth"]),Ey=c.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).refine(e=>e!=="myrel","That name is taken by Myrel's own tools."),GI=c.object({name:c.string(),description:c.string().optional()}),qI=/^[A-Za-z_][\w-]{0,99}$/,HI=/^[A-Za-z_][A-Za-z0-9_]{0,99}$/,Ry=(e,t,r)=>c.record(c.string().regex(e),c.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}),My=Ry(qI,"Header","letters, digits, - and _"),XI=Ry(HI,"Variable","letters, digits and _"),g4=c.object({id:c.string(),name:c.string(),slug:c.string(),scope:KI,transport:JI,url:c.string().nullable(),auth:WI,command:c.string().nullable(),args:c.array(c.string()),runsOn:gf,secretNames:c.array(c.string()),enabled:c.boolean(),status:BI,lastError:c.string().nullable(),tools:c.array(GI),canEdit:c.boolean(),createdAt:c.iso.datetime(),official:c.object({id:c.string(),title:c.string(),iconUrl:c.string().nullable()}).nullable().default(null)}),mf=c.string().trim().min(1).max(60),h4=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:mf,slug:Ey.optional(),url:c.url({protocol:/^https$/}).max(2e3),auth:c.enum(["headers","oauth"]).default("headers"),headers:My.default({})}),c.object({transport:c.literal("stdio"),name:mf,slug:Ey.optional(),command:c.string().trim().min(1).max(200),args:c.array(c.string().max(2e3)).max(50).default([]),env:XI.default({}),runsOn:gf.default("both")})]),v4=c.object({name:mf.optional(),enabled:c.boolean().optional(),url:c.url({protocol:/^https$/}).max(2e3).optional(),command:c.string().trim().min(1).max(200).optional(),args:c.array(c.string().max(2e3)).max(50).optional(),runsOn:gf.optional(),secrets:My.optional()});var y4=c.object({authorizeUrl:c.url()});var YI=["developer","productivity","communication","design","data","sales","finance","search","ai","other"],Ly=c.enum(YI);var QI=c.object({id:c.string(),title:c.string(),description:c.string(),websiteUrl:c.string().nullable(),iconUrl:c.string().nullable(),url:c.string(),auth:c.enum(["oauth","headers"]),headerHint:c.object({name:c.string(),placeholder:c.string()}).nullable(),category:Ly,official:c.boolean()}),b4=c.object({connectors:c.array(QI),nextOffset:c.number().nullable(),syncedAt:c.iso.datetime().nullable(),categories:c.array(c.object({id:Ly,count:c.number()}))}),ez=[{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"}],$4=ez.map(e=>e.id);var tz=c.enum(["user","project"]),nz=c.string().max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,"Use lowercase letters, digits and hyphens, like pdf-forms."),Zy=c.string().trim().min(1).max(1024),rz=c.string().min(1).max(300).regex(/^[\w@+=,.~ -]+(\/[\w@+=,.~ -]+)*$/,"Invalid file path.").refine(e=>!e.split("/").some(t=>t==="."||t===".."),"Invalid file path."),Fy={files:200,bytes:5*1024*1024,fileBytes:1024*1024};var iz=c.discriminatedUnion("kind",[c.object({kind:c.literal("write")}),c.object({kind:c.literal("upload")}),c.object({kind:c.literal("github"),repo:c.string(),path:c.string(),ref:c.string().optional(),commit:c.string()})]),oz=c.object({path:c.string(),size:c.number().int().nonnegative()}),az=c.object({id:c.string(),name:c.string(),description:c.string(),scope:tz,source:iz,enabled:c.boolean(),files:c.array(oz),size:c.number().int().nonnegative(),canEdit:c.boolean(),createdAt:c.iso.datetime(),updatedAt:c.iso.datetime()}),k4=az.extend({skillMd:c.string()}),sz=c.object({path:rz,content:c.string().max(Math.ceil(Fy.fileBytes*4/3)+4)}),w4=c.discriminatedUnion("kind",[c.object({kind:c.literal("write"),name:nz,description:Zy,instructions:c.string().max(1e5)}),c.object({kind:c.literal("upload"),files:c.array(sz).min(1).max(Fy.files)}),c.object({kind:c.literal("github"),source:c.string().trim().min(3).max(500),skill:c.string().max(64).optional()})]),S4=c.object({error:c.literal("choose_skill"),skills:c.array(c.object({name:c.string(),description:c.string(),path:c.string()}))}),I4=c.object({enabled:c.boolean().optional(),description:Zy.optional(),instructions:c.string().max(1e5).optional()}),z4=c.object({skills:c.array(c.object({name:c.string(),files:c.array(c.object({path:c.string(),content:c.string()}))}))});var P4=c.object({on:c.boolean()});var cz=c.object({id:c.string().min(1).max(200),name:c.string().min(1).max(80),description:c.string().max(300).default(""),url:c.string().max(2e3),auth:c.enum(["oauth","headers"]),headerHint:c.object({name:c.string(),placeholder:c.string()}).nullable().default(null),iconUrl:c.string().nullable().default(null),official:c.boolean().default(!1),featured:c.boolean().default(!1)}),uz=c.enum(["open","connected","dismissed"]),T4=c.object({id:c.string(),reason:c.string().min(1).max(400),offers:c.array(cz).min(1).max(3),state:uz.default("open"),connected:c.string().optional(),signIn:c.boolean().optional()});var O4=c.object({offerId:c.string().min(1).max(200),headers:c.record(c.string().regex(/^[A-Za-z_][\w-]{0,99}$/),c.string().min(1).max(4e3)).optional()}),N4=c.object({authorizeUrl:c.string().optional(),connected:c.boolean()});var lz=/^(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(\S[\s\S]*)$/;function Yn(e){let t=lz.exec(e.trim());return t?dz(t[1])??e:e}function dz(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}import{spawn as pz}from"node:child_process";import{mkdir as fz,readFile as By,rename as mz,writeFile as gz}from"node:fs/promises";import{homedir as Wy}from"node:os";import{dirname as hz,join as Vy}from"node:path";import{createInterface as Gy}from"node:readline";var bf="MYREL_MCP_BRIDGE";function vz(e=Wy()){return{mcp:Vy(e,".gemini","config","mcp_config.json"),settings:Vy(e,".gemini","antigravity-cli","settings.json")}}function li(){let e=process.argv[1],t=!e||/\$bunfs|~BUN/.test(e);return{command:process.execPath,args:t?[]:[e]}}async function qy(e,t=Wy()){let r=vz(t),o=li(),n={command:o.command,args:[...o.args,"mcp-bridge"]};await Jy(r.mcp,a=>{let s=hf(a.mcpServers)?a.mcpServers:{};return JSON.stringify(s[e])===JSON.stringify(n)?!1:(a.mcpServers={...s,[e]:n},!0)});let i=`mcp(${e}/*)`;await Jy(r.settings,a=>{let s=hf(a.permissions)?a.permissions:{},u=Array.isArray(s.allow)?s.allow:[];return u.includes(i)?!1:(a.permissions={...s,allow:[...u,i]},!0)})}async function Jy(e,t){let r=await By(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(!hf(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 fz(hz(e),{recursive:!0});let n=`${e}.myrel-${process.pid}`;await gz(n,`${JSON.stringify(o,null,2)}
64
64
  `,{mode:384}),await mz(n,e)}function hf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Yt=class extends Error{constructor(r){super(typeof r?.message=="string"?r.message:"MCP error");this.error=r}error},vf=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 Yt(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 s;for(;(s=n.search(/\r?\n\r?\n/))>=0;){let u=n.slice(0,s);n=n.slice(s).replace(/^\r?\n\r?\n/,"");let l=u.split(/\r?\n/).filter(p=>p.startsWith("data:")).map(p=>p.slice(5).trimStart()).join(`
65
65
  `);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`)}},yf=class{child;waiting=new Map;next=1;constructor(t,r,o){this.child=pz(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`)),Gy({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 Yt(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)}
66
66
  `)}fail(t){for(let[r,o]of this.waiting)o({jsonrpc:"2.0",id:r,error:{code:-32e3,message:t}})}},yz="__";async function Hy(e){let{run:t,write:r}=e,o=new Map;for(let f of t?.servers??[])o.set(f.name,f.transport==="http"?new vf(f.url,t.token):new yf(f.command,f.args,f.env));let n=t?.servers[0]?.name,i=new Map,a,s,u=f=>a??=Promise.all([...o].map(async([g,y])=>{try{return await y.request("initialize",f),await y.notify("notifications/initialized"),g}catch(x){return process.stderr.write(`myrel-runner mcp-bridge: ${g}: ${x.message}
@@ -68,38 +68,38 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
68
68
  `)}return x.map(S=>{let T=y===n?S.name:`${y}${yz}${S.name}`;return i.set(T,{server:y,tool:S.name}),{...S,name:T}})}))).flat()},d=async f=>{switch(f.method){case"initialize":{let g=f.params??{};return u({...Ky(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(s=l())};case"tools/call":{let g=f.params??{};await(s??=l());let y=g.name?i.get(g.name):void 0;if(!y)throw new Yt({code:-32602,message:`Unknown tool: ${g.name}`});return o.get(y.server).request("tools/call",{...g,name:y.tool})}default:throw new Yt({code:-32601,message:`Method not found: ${f.method}`})}},p=Gy({input:e.input}),m=[];for await(let f of p){let g;try{g=JSON.parse(f)}catch{continue}if(g.id===void 0||g.id===null||!g.method)continue;let y=g.id;m.push(d(g).then(x=>r(JSON.stringify({jsonrpc:"2.0",id:y,result:x})),x=>{let I=x instanceof Yt?x.error:{code:-32603,message:x.message};r(JSON.stringify({jsonrpc:"2.0",id:y,error:I}))}))}await Promise.all(m);for(let f of o.values())f.close()}function Ky(e){return{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"myrel-runner",version:e}}}async function Xy(){let e=process.env[bf];if(!e)return null;let t=await By(e,"utf8").catch(()=>null);if(!t)return null;try{return JSON.parse(t)}catch{return null}}import{execFile as xf}from"node:child_process";import{mkdir as Ga,readdir as Gz,readFile as vb,symlink as qz,writeFile as qa}from"node:fs/promises";import{homedir as yb}from"node:os";import{join as se}from"node:path";import{mkdir as bz,readFile as $z,rename as _z,writeFile as xz}from"node:fs/promises";import{homedir as kz}from"node:os";import{basename as wz,join as $f,resolve as Qy}from"node:path";function ee(){return process.env.MYREL_RUNNER_HOME||$f(kz(),".myrel-runner")}var Pt=()=>$f(ee(),"config.json");async function pe(){let e=await he(Pt()),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 Sz=["MYREL_RUNNER_TOKEN"],Iz=["SSH_AUTH_SOCK"];function He(e){let t={...process.env,...e};for(let r of[...Sz,...Iz])delete t[r];return t}async function Ve(e){let t={...e};process.env.MYREL_RUNNER_TOKEN&&t.token===process.env.MYREL_RUNNER_TOKEN&&(t.token=(await he(Pt()))?.token),await Je(Pt(),t)}function Va(e,t){let r=Qy(t);return e.folders.some(o=>o.path===r)?!1:(e.folders.push({path:r,name:wz(r)||r}),!0)}function Ja(e,t){let r=Qy(t),o=e.folders.length;return e.folders=e.folders.filter(n=>n.path!==r),e.folders.length!==o}var Fa=class{constructor(t=$f(ee(),"sessions.json")){this.path=t}path;async get(t,r="claude"){let o=(await he(this.path))?.[Yy(t,r)];return typeof o=="string"?{id:o}:o}async set(t,r,o){let n=await he(this.path)??{};n[Yy(t,r)]=o,await Je(this.path,n)}},Yy=(e,t)=>t==="claude"?e:`${t}:${e}`;async function he(e){try{return JSON.parse(await $z(e,"utf8"))}catch(t){if(t.code==="ENOENT")return;throw t}}async function Je(e,t){await bz(ee(),{recursive:!0,mode:448});let r=`${e}.${process.pid}.tmp`;await xz(r,`${JSON.stringify(t,null,2)}
69
69
  `,{mode:384}),await _z(r,e)}import{open as zz,readdir as Pz,stat as jz}from"node:fs/promises";import{homedir as Az}from"node:os";import{join as Qt}from"node:path";var Tz={five_hour:"session",seven_day:"weekly",seven_day_opus:"weekly_opus",seven_day_sonnet:"weekly_sonnet"},Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:null,eb=e=>e!==null&&e>0?new Date(e*1e3).toISOString():null,tb=e=>e===null?null:Math.min(1e3,Math.max(0,Math.round(e*10)/10));function nb(e,t){if(!e||typeof e!="object")return t;let r=e,o=new Map((t?.windows??[]).map(a=>[a.kind,a])),n=(a,s,u)=>{let l=typeof a=="string"?Tz[a]:void 0;if(!l)return;let d=Qn(s),p=o.get(l);o.set(l,{kind:l,usedPercent:d===null?p?.usedPercent??null:tb(d*100),resetsAt:eb(Qn(u))??p?.resetsAt??null})};if(n(r.rateLimitType,r.utilization,r.resetsAt),r.unifiedWindows&&typeof r.unifiedWindows=="object")for(let[a,s]of Object.entries(r.unifiedWindows))s&&typeof s=="object"&&n(a,s.utilization,s.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 Oz(e){return e===300?"session":e===10080?"weekly":e?`${e}m`:"other"}function _f(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=Qn(i.resets_in_seconds),s=eb(Qn(i.resets_at))??(a!==null?new Date(new Date(t).getTime()+a*1e3).toISOString():null);r.push({kind:Oz(Qn(i.window_minutes)),usedPercent:tb(Qn(i.used_percent)),resetsAt:s})}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 Nz(){return process.env.CODEX_HOME||Qt(Az(),".codex")}async function Ka(e){return(await Pz(e).catch(()=>[])).sort().reverse()}var Dz=256*1024;async function Uz(e){let t=await zz(e,"r").catch(()=>null);if(t)try{let{size:r}=await t.stat(),o=Math.min(r,Dz),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 s=JSON.parse(a);if(s.payload?.type!=="token_count")continue;let u=typeof s.timestamp=="string"&&!Number.isNaN(Date.parse(s.timestamp))?new Date(s.timestamp).toISOString():(await jz(e)).mtime.toISOString(),l=_f(s.payload.rate_limits,u);if(l)return l}catch{}return}finally{await t.close()}}async function Ba(e){let t=Qt(Nz(),"sessions"),r=0;for(let o of await Ka(t))for(let n of await Ka(Qt(t,o)))for(let i of await Ka(Qt(t,o,n))){let a=Qt(t,o,n,i);for(let s of await Ka(a)){if(!s.endsWith(".jsonl")||e&&!s.includes(e))continue;let u=await Uz(Qt(a,s));if(u||e)return u;if(++r>=20)return}if(e&&++r>=14)return}}var rb=()=>Qt(ee(),"limits.json");async function ib(){return await he(rb()).catch(()=>{})??{}}async function ob(e){await Je(rb(),e)}import{execFile as Cz}from"node:child_process";import{existsSync as Ez}from"node:fs";import{homedir as Rz}from"node:os";import{delimiter as ab,dirname as Mz,join as lt}from"node:path";async function sb(){let e=[Mz(process.execPath),...process.platform==="win32"?[...await Jz(),...Kz()]:[]];process.env.PATH=Lz(process.env.PATH??"",e,ab,process.platform==="win32")}function Lz(e,t,r=ab,o=!1){let n=s=>{let u=s.trim().replace(/[\\/]+$/,"");return o?u.toLowerCase():u},i=e.split(r).filter(Boolean),a=new Set(i.map(n));for(let s of t)!s.trim()||a.has(n(s))||(a.add(n(s)),i.push(s.trim()));return i.join(r)}function Zz(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 Fz(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 Vz=["HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment","HKCU\\Environment"];async function Jz(){return(await Promise.all(Vz.map(t=>new Promise(r=>{Cz("reg",["query",t,"/v","Path"],{timeout:5e3,windowsHide:!0},(o,n)=>r(o?void 0:Fz(n)))})))).flatMap(t=>t?Zz(t).split(";"):[])}function Kz(){let e=Rz(),t=process.env.APPDATA??lt(e,"AppData","Roaming"),r=process.env.LOCALAPPDATA??lt(e,"AppData","Local");return[lt(t,"npm"),process.env.PNPM_HOME??lt(r,"pnpm"),lt(e,".bun","bin"),lt(e,".local","bin"),lt(e,"scoop","shims"),lt(r,"Microsoft","WinGet","Links"),lt(r,"Volta","bin")].filter(o=>Ez(o))}function di(e,t,r){e.progress=t;let o=r&&Bz(e,r);o?e.progressAgent=o:delete e.progressAgent}function er(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:Wz(o),agent:{id:t,label:a,state:"started"}})}function jt(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 Wa(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 Bz(e,t){e.agents?.has(t)||er(e,t,"");let r=e.agents?.get(t);return r&&{id:t,label:r.label}}function Wz(e){return(e.trim().split(`
71
- `)[0]??"").slice(0,200)}function Xe(e){return!!e&&e.length<=200&&/^[A-Za-z0-9][\w.:/@+-]*$/.test(e)}function Ya(e){let t={...Xe(e?.model)&&{model:e.model},...Xe(e?.effort)&&{effort:e.effort}};return t.model||t.effort?t:void 0}function bb(e,t){let r=Ya(t);return r&&e.modelArgs?e.modelArgs(r):[]}function Tt(e,t,r=2e4){return new Promise(o=>{xf(e,t,{timeout:r,maxBuffer:4*1024*1024,shell:process.platform==="win32",env:He()},(n,i)=>{o(n?null:i)})})}function Hz(e){let t=e.replace(/\s+/g," "),r=cb(t,"--model <model>","(e.g. ")?.match(/'[a-z0-9-]+'/g)?.map(n=>n.slice(1,-1));if(!r?.length)return;let o=cb(t,"--effort <level>","(")?.split(",").map(n=>n.trim()).filter(Xe)??[];return[...r,...r.includes("haiku")?[]:["haiku"]].map(n=>({id:n,name:n[0].toUpperCase()+n.slice(1),efforts:n==="haiku"?[]:o}))}function cb(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 Xz(e){try{let{models:t}=JSON.parse(e);if(!Array.isArray(t))return;let r=t.flatMap(o=>{if(typeof o.slug!="string"||!Xe(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"&&Xe(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 kf(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,s=i>=0?o.slice(i+(n>=0?1:3)).trim():"";return!Xe(a)||/^(available|fetching|loading)$/i.test(a)||a.endsWith(":")?[]:[{id:a,name:s||a,efforts:[]}]});return t.length?t.slice(0,100):void 0}var Ne="myrel",Yz="mcp__myrel__approve_access",Qz=900*1e3,e0=1e4,Ha="MYREL_MCP_TOKEN";function dt(e){return process.platform==="win32"?`"${e}"`:e}async function Xa(e,t,r){let o=se(e,t);return await qa(o,JSON.stringify(r),{mode:384}),process.platform==="win32"?`"${o}"`:o}var ub=["ssh","scp","sftp","rsync"].map(e=>`Bash(${e}:*)`),t0=["~/.ssh/**","~/.myrel-runner/ssh/**"].flatMap(e=>[`Read(${e})`,`Edit(${e})`]),n0={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",dt(a)]),...n?["--permission-prompt-tool",Yz]:[],...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n,asks:i,access:a}){let s={Authorization:`Bearer ${t}`},u={[Ne]:{type:"http",url:e,headers:s,alwaysLoad:!0}};for(let f of o)u[f.name]=f.transport==="http"?{type:"http",url:f.url,headers:s}:{type:"stdio",command:f.command,args:f.args,env:f.env};let l=await Xa(r,"mcp.json",{mcpServers:u}),d=[Ne,...o.map(f=>f.name)].map(f=>`mcp__${f}`);i&&a==="full"&&d.push("Bash","WebFetch","WebSearch");let p=await Xa(r,"settings.json",{permissions:{...i&&{ask:ub},deny:t0}}),m=n?["--plugin-dir",dt(n.plugin),"--add-dir",dt(n.dir)]:[];return{args:["--mcp-config",l,"--strict-mcp-config","--allowedTools",d.join(","),"--disallowedTools",["Bash(gh pr create:*)",...i?[]:ub].join(","),"--settings",p,...m],env:{ENABLE_CLAUDEAI_MCP_SERVERS:"false",...!process.env.MCP_TIMEOUT&&{MCP_TIMEOUT:String(e0)},...i&&{MCP_TOOL_TIMEOUT:String(Qz)}}}},streamInput:!0,line(e,t){let r=tr(e);if(!r)return;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==="rate_limit_event"&&(t.limits=nb(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=hb(n.usage);If(t,a),o&&Wa(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 s=a.input??{};if(_0.has(String(a.name))&&typeof a.id=="string"){let u=typeof s.subagent_type=="string"?s.subagent_type:"Agent",l=typeof s.description=="string"?s.description:"";er(t,a.id,u,l,{background:s.run_in_background===!0})}else di(t,At(String(a.name),a.input),o)}else a.type==="text"&&typeof a.text=="string"&&a.text.trim()&&di(t,pt(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&&jt(t,i.tool_use_id,i.is_error!==!0,x0(i.content))}}if(r.type==="system"&&r.subtype==="task_notification"&&typeof r.tool_use_id=="string"){let n=typeof r.summary=="string"?r.summary:"";jt(t,r.tool_use_id,r.status==="completed",n)}if(r.type==="result"){if(r.usage){let n=hb(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()=>Hz(await Tt("claude",["--help"])??""),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]},lb={read:"read-only",edit:"workspace-write",auto:"workspace-write",full:"danger-full-access"},r0={id:"codex",bin:"codex",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["exec","--json","--skip-git-repo-check","--sandbox",lb[e],...o.flatMap(n=>["--add-dir",dt(n)]),...r,...t?["resume",t]:[],"-"],agent:async({url:e,token:t,connectors:r=[],access:o})=>{let n=s=>["-c",`mcp_servers.${s}.default_tools_approval_mode="approve"`],i=(s,u)=>["-c",`mcp_servers.${s}.url=${JSON.stringify(u)}`,"-c",`mcp_servers.${s}.bearer_token_env_var=${JSON.stringify(Ha)}`,...n(s)],a=i(Ne,e);for(let s of r){if(s.transport==="http"){a.push(...i(s.name,s.url));continue}let u=Object.entries(s.env).map(([l,d])=>`${l} = ${JSON.stringify(d)}`);a.push("-c",`mcp_servers.${s.name}.command=${JSON.stringify(s.command)}`,"-c",`mcp_servers.${s.name}.args=${JSON.stringify(s.args)}`),u.length&&a.push("-c",`mcp_servers.${s.name}.env={ ${u.join(", ")} }`),a.push(...n(s.name))}return o&&o!=="read"&&a.push("-c",'apps._default.default_tools_approval_mode="approve"'),{args:a,env:{[Ha]:t}}},appServer:({access:e,dirs:t,asks:r})=>({...t.length&&{config:{"sandbox_workspace_write.writable_roots":t}},sandbox:lb[e],approvalPolicy:r&&(e==="edit"||e==="auto")?"on-request":"never"}),line(e,t){if(t.appServer)return t.appServer.receive(e);let r=tr(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=pt(`$ ${Yn(o.command)}`)),r.type==="item.completed"&&o?.type==="agent_message"&&typeof o.text=="string"&&(t.result=o.text,t.progress=pt(o.text)),r.type==="turn.completed"&&r.usage){let i=r.usage;If(t,{inputTokens:re(i.input_tokens),outputTokens:re(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=>Ba(e.sessionId),models:async()=>Xz(await Tt("codex",["debug","models"])??""),modelArgs:({model:e,effort:t})=>[...e?["-m",e]:[],...t?["-c",`model_reasoning_effort=${JSON.stringify(t)}`]:[]]},i0="(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.)",o0={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",dt(n)]),...t?["--conversation",t]:[],...r],input:(e,t)=>{let r=t==="full"?e:`${e}
71
+ `)[0]??"").slice(0,200)}function Xe(e){return!!e&&e.length<=200&&/^[A-Za-z0-9][\w.:/@+-]*$/.test(e)}function Ya(e){let t={...Xe(e?.model)&&{model:e.model},...Xe(e?.effort)&&{effort:e.effort}};return t.model||t.effort?t:void 0}function bb(e,t){let r=Ya(t);return r&&e.modelArgs?e.modelArgs(r):[]}function Tt(e,t,r=2e4){return new Promise(o=>{xf(e,t,{timeout:r,maxBuffer:4*1024*1024,shell:process.platform==="win32",env:He()},(n,i)=>{o(n?null:i)})})}function Hz(e){let t=e.replace(/\s+/g," "),r=cb(t,"--model <model>","(e.g. ")?.match(/'[a-z0-9-]+'/g)?.map(n=>n.slice(1,-1));if(!r?.length)return;let o=cb(t,"--effort <level>","(")?.split(",").map(n=>n.trim()).filter(Xe)??[];return[...r,...r.includes("haiku")?[]:["haiku"]].map(n=>({id:n,name:n[0].toUpperCase()+n.slice(1),efforts:n==="haiku"?[]:o}))}function cb(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 Xz(e){try{let{models:t}=JSON.parse(e);if(!Array.isArray(t))return;let r=t.flatMap(o=>{if(typeof o.slug!="string"||!Xe(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"&&Xe(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 kf(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,s=i>=0?o.slice(i+(n>=0?1:3)).trim():"";return!Xe(a)||/^(available|fetching|loading)$/i.test(a)||a.endsWith(":")?[]:[{id:a,name:s||a,efforts:[]}]});return t.length?t.slice(0,100):void 0}var Ne="myrel",Yz="mcp__myrel__approve_access",Qz=900*1e3,e0=1e4,Ha="MYREL_MCP_TOKEN";function dt(e){return process.platform==="win32"?`"${e}"`:e}async function Xa(e,t,r){let o=se(e,t);return await qa(o,JSON.stringify(r),{mode:384}),process.platform==="win32"?`"${o}"`:o}var ub=["ssh","scp","sftp","rsync"].map(e=>`Bash(${e}:*)`),t0=["~/.ssh/**","~/.myrel-runner/ssh/**"].flatMap(e=>[`Read(${e})`,`Edit(${e})`]),n0={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",dt(a)]),...n?["--permission-prompt-tool",Yz]:[],...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n,asks:i,access:a}){let s={Authorization:`Bearer ${t}`},u={[Ne]:{type:"http",url:e,headers:s,alwaysLoad:!0}};for(let f of o)u[f.name]=f.transport==="http"?{type:"http",url:f.url,headers:s}:{type:"stdio",command:f.command,args:f.args,env:f.env};let l=await Xa(r,"mcp.json",{mcpServers:u}),d=[Ne,...o.map(f=>f.name)].map(f=>`mcp__${f}`);i&&a==="full"&&d.push("Bash","WebFetch","WebSearch");let p=await Xa(r,"settings.json",{permissions:{...i&&{ask:ub},deny:t0}}),m=n?["--plugin-dir",dt(n.plugin),"--add-dir",dt(n.dir)]:[];return{args:["--mcp-config",l,"--strict-mcp-config","--allowedTools",d.join(","),"--disallowedTools",["Bash(gh pr create:*)",...i?[]:ub].join(","),"--settings",p,...m],env:{ENABLE_CLAUDEAI_MCP_SERVERS:"false",...!process.env.MCP_TIMEOUT&&{MCP_TIMEOUT:String(e0)},...i&&{MCP_TOOL_TIMEOUT:String(Qz)}}}},streamInput:!0,line(e,t){let r=tr(e);if(!r)return;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==="rate_limit_event"&&(t.limits=nb(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=hb(n.usage);If(t,a),o&&Wa(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 s=a.input??{};if(x0.has(String(a.name))&&typeof a.id=="string"){let u=typeof s.subagent_type=="string"?s.subagent_type:"Agent",l=typeof s.description=="string"?s.description:"";er(t,a.id,u,l,{background:s.run_in_background===!0})}else di(t,At(String(a.name),a.input),o)}else a.type==="text"&&typeof a.text=="string"&&a.text.trim()&&di(t,pt(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&&jt(t,i.tool_use_id,i.is_error!==!0,k0(i.content))}}if(r.type==="system"&&r.subtype==="task_notification"&&typeof r.tool_use_id=="string"){let n=typeof r.summary=="string"?r.summary:"";jt(t,r.tool_use_id,r.status==="completed",n)}if(r.type==="result"){if(r.usage){let n=hb(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()=>Hz(await Tt("claude",["--help"])??""),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]},lb={read:"read-only",edit:"workspace-write",auto:"workspace-write",full:"danger-full-access"},r0={id:"codex",bin:"codex",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["exec","--json","--skip-git-repo-check","--sandbox",lb[e],...o.flatMap(n=>["--add-dir",dt(n)]),...r,...t?["resume",t]:[],"-"],agent:async({url:e,token:t,connectors:r=[],access:o})=>{let n=s=>["-c",`mcp_servers.${s}.default_tools_approval_mode="approve"`],i=(s,u)=>["-c",`mcp_servers.${s}.url=${JSON.stringify(u)}`,"-c",`mcp_servers.${s}.bearer_token_env_var=${JSON.stringify(Ha)}`,...n(s)],a=i(Ne,e);for(let s of r){if(s.transport==="http"){a.push(...i(s.name,s.url));continue}let u=Object.entries(s.env).map(([l,d])=>`${l} = ${JSON.stringify(d)}`);a.push("-c",`mcp_servers.${s.name}.command=${JSON.stringify(s.command)}`,"-c",`mcp_servers.${s.name}.args=${JSON.stringify(s.args)}`),u.length&&a.push("-c",`mcp_servers.${s.name}.env={ ${u.join(", ")} }`),a.push(...n(s.name))}return o&&o!=="read"&&a.push("-c",'apps._default.default_tools_approval_mode="approve"'),{args:a,env:{[Ha]:t}}},appServer:({access:e,dirs:t,asks:r})=>({...t.length&&{config:{"sandbox_workspace_write.writable_roots":t}},sandbox:lb[e],approvalPolicy:r&&(e==="edit"||e==="auto")?"on-request":"never"}),line(e,t){if(t.appServer)return t.appServer.receive(e);let r=tr(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=pt(`$ ${Yn(o.command)}`)),r.type==="item.completed"&&o?.type==="agent_message"&&typeof o.text=="string"&&(t.result=o.text,t.progress=pt(o.text)),r.type==="turn.completed"&&r.usage){let i=r.usage;If(t,{inputTokens:re(i.input_tokens),outputTokens:re(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=>Ba(e.sessionId),models:async()=>Xz(await Tt("codex",["debug","models"])??""),modelArgs:({model:e,effort:t})=>[...e?["-m",e]:[],...t?["-c",`model_reasoning_effort=${JSON.stringify(t)}`]:[]]},i0="(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.)",o0={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",dt(n)]),...t?["--conversation",t]:[],...r],input:(e,t)=>{let r=t==="full"?e:`${e}
72
72
 
73
73
  ${i0}`;return`${JSON.stringify({event:"user",message:{content:r}})}
74
74
  `},async agent({url:e,token:t,dir:r,connectors:o=[],skills:n}){await qy(Ne);let i={token:t,servers:[{transport:"http",name:Ne,url:e},...o]},a=await Xa(r,"bridge.json",i);return{args:n?["--add-dir",dt(n.dir)]:[],env:{[bf]:a.replace(/^"|"$/g,"")}}},line(e,t){let r=tr(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=At(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=pt(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=re(i.output_tokens)+re(i.thinking_tokens),s=Math.max(re(i.input_tokens),re(i.total_tokens)-a);(s||a)&&(t.usage={inputTokens:s,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()=>kf(await Tt("agy",["models"],3e4)??""),modelArgs:({model:e})=>e?["--model",e]:[]},$b={read:{edit:"deny",bash:"deny"},edit:{edit:"allow",bash:"deny"},auto:{edit:"allow",bash:"deny"},full:{edit:"allow",bash:"allow"}},a0={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,connectors:r=[],skills:o,access:n="edit",dirs:i=[]}){let a=await Sf("opencode"),s={Authorization:`Bearer {env:${Ha}}`},u={[Ne]:{type:"remote",url:e,headers:s,oauth:!1}};for(let p of r)u[p.name]=p.transport==="http"?{type:"remote",url:p.url,headers:s,oauth:!1}:{type:"local",command:[p.command,...p.args],environment:p.env};let l=[...i,...o?[o.dir]:[]],d;if(_b(a)>=2)d=c0(u,n,l,o?.dir);else{let p={...$b[n]};for(let m of Object.keys(u))p[`${m}_*`]="allow";l.length&&(p.external_directory=Object.fromEntries(l.flatMap(m=>[[m,"allow"],[se(m,"*"),"allow"]]))),d={mcp:u,permission:p,...o&&{skills:{paths:[o.dir]}},experimental:{continue_loop_on_deny:!0}}}return{args:s0(a),env:{OPENCODE_CONFIG_CONTENT:JSON.stringify(d),[Ha]:t}}},line(e,t){let r=tr(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=At(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}
75
75
 
76
76
  ${o.text}`:o.text,t.draftStep=o.messageID,t.result=t.draft,t.progress=pt(o.text)),r.type==="step_finish"){let n=o.tokens??{},i=n.cache??{};If(t,{inputTokens:re(n.input)+re(i.read)+re(i.write),outputTokens:re(n.output)+re(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()=>kf(await Tt("opencode",["models"])??""),modelArgs:({model:e})=>e?["--model",e]:[]};function _b(e){return Number(/\d+/.exec(e??"")?.[0]??0)}function s0(e){return _b(e)>=2?["--standalone"]:[]}function c0(e,t,r,o){let n=[];t!=="full"&&n.push({action:"external_directory",resource:"*",effect:"deny"});for(let s of r)n.push({action:"external_directory",resource:s,effect:"allow"}),n.push({action:"external_directory",resource:se(s,"*"),effect:"allow"});let i=$b[t];n.push({action:"edit",resource:"*",effect:i.edit}),n.push({action:"shell",resource:"*",effect:i.bash});for(let s of Object.keys(e))n.push({action:`${s}_*`,resource:"*",effect:"allow"});let a={};for(let[s,u]of Object.entries(e))a[s]={...u,codemode:!1};return{mcp:{servers:a},permissions:n,...o&&{skills:[o]}}}var db={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 xb({url:e,token:t,connectors:r=[]}){let o=[{name:"Authorization",value:`Bearer ${t}`}],n=[{type:"http",name:Ne,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,s])=>({name:a,value:s}))});return n}var u0={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)=>db[t]?`${e}
77
77
 
78
- ${db[t]}`:e,agent:async e=>({args:[],mcpServers:xb(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>e.startsWith("Hermes Agent")},l0={read:["--mode","ask"],edit:["--sandbox","enabled"],auto:["--sandbox","enabled"],full:["--force","--sandbox","disabled"]},d0={id:"cursor",bin:"cursor-agent",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["-p","--output-format","stream-json","--trust",...l0[e],...o.flatMap(n=>["--add-dir",dt(n)]),...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n}){let i=se(r,Ne);await Ga(se(i,".cursor-plugin"),{recursive:!0}),await qa(se(i,".cursor-plugin","plugin.json"),JSON.stringify({name:Ne,description:"Myrel's tools for this run.",version:"1.0.0"}));let a={Authorization:`Bearer ${t}`},s={[Ne]:{url:e,headers:a}};for(let d of o)s[d.name]=d.transport==="http"?{url:d.url,headers:a}:{command:d.command,args:d.args,env:d.env};await Xa(i,"mcp.json",{mcpServers:s}),n&&(await Ga(se(n.plugin,".cursor-plugin"),{recursive:!0}),await qa(se(n.plugin,".cursor-plugin","plugin.json"),JSON.stringify({name:`${Ne}-skills`,description:"Skills added in Myrel for this run.",version:"1.0.0"})));let u=await f0(se(r,"cursor-config"),Object.keys(s).map(d=>`Mcp(plugin-${Ne}-${d}:*)`));return{args:["--approve-mcps",...[i,...n?[n.plugin]:[]].flatMap(d=>["--plugin-dir",dt(d)])],env:{CURSOR_CONFIG_DIR:u}}},line(e,t){let r=tr(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(([s])=>s.endsWith("ToolCall")||s==="function")??[],a=i?.args;n==="mcpToolCall"&&typeof a?.toolName=="string"?t.progress=At(a.toolName,a.args):n==="function"&&typeof i?.name=="string"?t.progress=At(i.name,Sb(i.arguments)):n&&(t.progress=At(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=pt(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=re(o.inputTokens)+re(o.cacheReadTokens)+re(o.cacheWriteTokens);(n||re(o.outputTokens))&&(t.usage={inputTokens:n,outputTokens:re(o.outputTokens)})}}},models:async()=>kf(await Tt("cursor-agent",["models"])??""),modelArgs:({model:e})=>e?["--model",e]:[]};function p0(){return process.env.CURSOR_CONFIG_DIR?.trim()||(process.env.XDG_CONFIG_HOME?.trim()?se(process.env.XDG_CONFIG_HOME,"cursor"):se(yb(),".cursor"))}async function f0(e,t,r=p0()){await Ga(e,{recursive:!0});let o=await vb(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 qa(se(e,"cli-config.json"),JSON.stringify(o),{mode:384}),await Ga(se(r,"chats"),{recursive:!0}).then(()=>qz(se(r,"chats"),se(e,"chats"),process.platform==="win32"?"junction":"dir")).catch(()=>{}),e}var m0={read:["--approval-mode","never","--disable-write","--disable-shell"],edit:["--approval-mode","never","--trust-workspace"],auto:["--approval-mode","never","--trust-workspace"],full:["--yolo"]},pb="MYREL_MCP_AUTH",g0={id:"muse",bin:"muse",promptFile:!0,args:({access:e,resume:t,extra:r=[],promptFile:o})=>["exec","--json",...m0[e],...t?["--session-id",t]:[],...r,...o?["--prompt-file",dt(o)]:[]],async agent({url:e,token:t,connectors:r=[]}){let o={[pb]:`Bearer ${t}`},n={Authorization:`\${${pb}}`},i=[[Ne,{url:e,headers:n}]];for(let[a,s]of r.entries()){if(s.transport==="http"){i.push([s.name,{url:s.url,headers:n}]);continue}let u=Object.entries(s.env).map(([l,d],p)=>{let m=`MYREL_MCP_${a}_${p}`;return o[m]=d,[l,`\${${m}}`]});i.push([s.name,{command:s.command,args:s.args,env:Object.fromEntries(u)}])}return{args:i.flatMap(([a,s])=>["-c",`mcpServers.${a}=${JSON.stringify(s)}`]),env:o}},line(e,t){let r=tr(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=At(i.slice(5),void 0),t.draft=void 0);break}case"tool.result":{let i=n.correlation_facts?.tool_name,a=n.edit_facts,s=typeof n.text=="string"&&n.text.startsWith("{")?Sb(n.text)?.command:void 0;typeof s=="string"?t.progress=pt(`$ ${Yn(s)}`):typeof i=="string"&&(t.progress=At(i,a));break}case"run.output.delta":typeof n.text=="string"&&(t.draft=(t.draft??"")+n.text,t.draft.trim()&&(t.progress=pt(t.draft)));break;case"run.usage":{let i=Array.isArray(n.models)?n.models:[],a=i.reduce((u,l)=>u+re(l.input_tokens),0),s=i.reduce((u,l)=>u+re(l.output_tokens),0);(a||s)&&(t.usage={inputTokens:a,outputTokens:s});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:()=>h0(),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]};async function h0(){let e=se(process.env.XDG_DATA_HOME?.trim()||se(yb(),".local","share"),"muse","model-catalog"),t=await Gz(e).catch(()=>[]),r=await Promise.all(t.filter(i=>i.endsWith(".json")).map(i=>vb(se(e,i),"utf8").then(v0,()=>{}))),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 v0(e){try{let{rows:t}=JSON.parse(e);return Array.isArray(t)?t.flatMap(r=>{if(typeof r.model_id!="string"||!Xe(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"&&Xe(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 fb={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},y0={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)=>fb[t]?`${e}
78
+ ${db[t]}`:e,agent:async e=>({args:[],mcpServers:xb(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>e.startsWith("Hermes Agent")},l0={read:["--mode","ask"],edit:["--sandbox","enabled"],auto:["--sandbox","enabled"],full:["--force","--sandbox","disabled"]},d0={id:"cursor",bin:"cursor-agent",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["-p","--output-format","stream-json","--trust",...l0[e],...o.flatMap(n=>["--add-dir",dt(n)]),...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n}){let i=se(r,Ne);await Ga(se(i,".cursor-plugin"),{recursive:!0}),await qa(se(i,".cursor-plugin","plugin.json"),JSON.stringify({name:Ne,description:"Myrel's tools for this run.",version:"1.0.0"}));let a={Authorization:`Bearer ${t}`},s={[Ne]:{url:e,headers:a}};for(let d of o)s[d.name]=d.transport==="http"?{url:d.url,headers:a}:{command:d.command,args:d.args,env:d.env};await Xa(i,"mcp.json",{mcpServers:s}),n&&(await Ga(se(n.plugin,".cursor-plugin"),{recursive:!0}),await qa(se(n.plugin,".cursor-plugin","plugin.json"),JSON.stringify({name:`${Ne}-skills`,description:"Skills added in Myrel for this run.",version:"1.0.0"})));let u=await f0(se(r,"cursor-config"),Object.keys(s).map(d=>`Mcp(plugin-${Ne}-${d}:*)`));return{args:["--approve-mcps",...[i,...n?[n.plugin]:[]].flatMap(d=>["--plugin-dir",dt(d)])],env:{CURSOR_CONFIG_DIR:u}}},line(e,t){let r=tr(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(([s])=>s.endsWith("ToolCall")||s==="function")??[],a=i?.args;n==="mcpToolCall"&&typeof a?.toolName=="string"?t.progress=At(a.toolName,a.args):n==="function"&&typeof i?.name=="string"?t.progress=At(i.name,Sb(i.arguments)):n&&(t.progress=At(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=pt(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=re(o.inputTokens)+re(o.cacheReadTokens)+re(o.cacheWriteTokens);(n||re(o.outputTokens))&&(t.usage={inputTokens:n,outputTokens:re(o.outputTokens)})}}},models:async()=>kf(await Tt("cursor-agent",["models"])??""),modelArgs:({model:e})=>e?["--model",e]:[]};function p0(){return process.env.CURSOR_CONFIG_DIR?.trim()||(process.env.XDG_CONFIG_HOME?.trim()?se(process.env.XDG_CONFIG_HOME,"cursor"):se(yb(),".cursor"))}async function f0(e,t,r=p0()){await Ga(e,{recursive:!0});let o=await vb(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 qa(se(e,"cli-config.json"),JSON.stringify(o),{mode:384}),await Ga(se(r,"chats"),{recursive:!0}).then(()=>qz(se(r,"chats"),se(e,"chats"),process.platform==="win32"?"junction":"dir")).catch(()=>{}),e}var m0={read:["--approval-mode","never","--disable-write","--disable-shell"],edit:["--approval-mode","never","--trust-workspace"],auto:["--approval-mode","never","--trust-workspace"],full:["--yolo"]},g0=["--context-compaction-soft-threshold","0.15"],pb="MYREL_MCP_AUTH",h0={id:"muse",bin:"muse",promptFile:!0,args:({access:e,resume:t,extra:r=[],promptFile:o})=>["exec","--json",...g0,...m0[e],...t?["--session-id",t]:[],...r,...o?["--prompt-file",dt(o)]:[]],async agent({url:e,token:t,connectors:r=[]}){let o={[pb]:`Bearer ${t}`},n={Authorization:`\${${pb}}`},i=[[Ne,{url:e,headers:n}]];for(let[a,s]of r.entries()){if(s.transport==="http"){i.push([s.name,{url:s.url,headers:n}]);continue}let u=Object.entries(s.env).map(([l,d],p)=>{let m=`MYREL_MCP_${a}_${p}`;return o[m]=d,[l,`\${${m}}`]});i.push([s.name,{command:s.command,args:s.args,env:Object.fromEntries(u)}])}return{args:i.flatMap(([a,s])=>["-c",`mcpServers.${a}=${JSON.stringify(s)}`]),env:o}},line(e,t){let r=tr(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=At(i.slice(5),void 0),t.draft=void 0);break}case"tool.result":{let i=n.correlation_facts?.tool_name,a=n.edit_facts,s=typeof n.text=="string"&&n.text.startsWith("{")?Sb(n.text)?.command:void 0;typeof s=="string"?t.progress=pt(`$ ${Yn(s)}`):typeof i=="string"&&(t.progress=At(i,a));break}case"run.output.delta":typeof n.text=="string"&&(t.draft=(t.draft??"")+n.text,t.draft.trim()&&(t.progress=pt(t.draft)));break;case"run.usage":{let i=Array.isArray(n.models)?n.models:[],a=i.reduce((u,l)=>u+re(l.input_tokens),0),s=i.reduce((u,l)=>u+re(l.output_tokens),0);(a||s)&&(t.usage={inputTokens:a,outputTokens:s});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:()=>v0(),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]};async function v0(){let e=se(process.env.XDG_DATA_HOME?.trim()||se(yb(),".local","share"),"muse","model-catalog"),t=await Gz(e).catch(()=>[]),r=await Promise.all(t.filter(i=>i.endsWith(".json")).map(i=>vb(se(e,i),"utf8").then(y0,()=>{}))),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 y0(e){try{let{rows:t}=JSON.parse(e);return Array.isArray(t)?t.flatMap(r=>{if(typeof r.model_id!="string"||!Xe(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"&&Xe(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 fb={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},b0={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)=>fb[t]?`${e}
79
79
 
80
- ${fb[t]}`:e,agent:async e=>({args:[],mcpServers:xb(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>/^v?\d+\.\d+/.test(e),models:async()=>b0(await Tt("kimi",["provider","list","--json"])??"")};function b0(e){try{let{models:t}=JSON.parse(e);if(!t||typeof t!="object")return;let r=Object.entries(t).flatMap(([o,n])=>{if(!Xe(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"&&Xe(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 fi={claude:n0,codex:r0,antigravity:o0,opencode:a0,hermes:u0,cursor:d0,muse:g0,kimi:y0},wf=process.platform==="win32"?3e4:1e4;function Sf(e){return new Promise(t=>{xf(e,["--version"],{timeout:wf,shell:process.platform==="win32",env:He()},(r,o)=>{t(r?null:pi(o)||null)})})}var mb=new Map;async function kb(e){if(process.env.MYREL_CODEX_EXEC==="1")return!1;let t=await Sf(e);if(!t)return!1;let r=mb.get(t);return r||(r=Tt(e,["app-server","--help"],1e4).then(o=>!!o?.includes("--listen")),mb.set(t,r)),r}var gb=new Map;async function wb(e){if(process.env.MYREL_CLAUDE_ONESHOT==="1")return!1;let t=await Sf(e);if(!t)return!1;let r=gb.get(t);return r||(r=Tt(e,["--help"],1e4).then(o=>!!o?.includes("--replay-user-messages")),gb.set(t,r)),r}async function mi(e){return await sb().catch(()=>{}),(await Promise.all(Object.values(fi).map(r=>new Promise(o=>{xf(r.bin,["--version"],{timeout:wf,shell:process.platform==="win32",env:He(),windowsHide:!0},(n,i,a)=>{if(n||r.isMine&&!r.isMine(pi(i)))return e?.push({id:r.id,reason:n?$0(n,a):`\`${r.bin} --version\` printed "${pi(i)}"`}),o(null);o({id:r.id,version:pi(i)||null})})})))).filter(r=>r!==null)}function $0(e,t=""){return e.killed?`no answer in ${wf/1e3}s`:e.code==="ENOENT"?"not on PATH":pi(t)||e.message.split(`
81
- `)[0]||"failed"}function re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0}function hb(e){let t=e??{};return{inputTokens:re(t.input_tokens)+re(t.cache_read_input_tokens)+re(t.cache_creation_input_tokens),outputTokens:re(t.output_tokens)}}function If(e,t){let r=e.usage??={inputTokens:0,outputTokens:0};r.inputTokens+=t.inputTokens,r.outputTokens+=t.outputTokens}function tr(e){if(!e.startsWith("{"))return null;try{return JSON.parse(e)}catch{return null}}function Sb(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var _0=new Set(["Agent","Task"]);function x0(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?String(t.text??""):"").filter(Boolean).join(`
80
+ ${fb[t]}`:e,agent:async e=>({args:[],mcpServers:xb(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>/^v?\d+\.\d+/.test(e),models:async()=>$0(await Tt("kimi",["provider","list","--json"])??"")};function $0(e){try{let{models:t}=JSON.parse(e);if(!t||typeof t!="object")return;let r=Object.entries(t).flatMap(([o,n])=>{if(!Xe(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"&&Xe(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 fi={claude:n0,codex:r0,antigravity:o0,opencode:a0,hermes:u0,cursor:d0,muse:h0,kimi:b0},wf=process.platform==="win32"?3e4:1e4;function Sf(e){return new Promise(t=>{xf(e,["--version"],{timeout:wf,shell:process.platform==="win32",env:He()},(r,o)=>{t(r?null:pi(o)||null)})})}var mb=new Map;async function kb(e){if(process.env.MYREL_CODEX_EXEC==="1")return!1;let t=await Sf(e);if(!t)return!1;let r=mb.get(t);return r||(r=Tt(e,["app-server","--help"],1e4).then(o=>!!o?.includes("--listen")),mb.set(t,r)),r}var gb=new Map;async function wb(e){if(process.env.MYREL_CLAUDE_ONESHOT==="1")return!1;let t=await Sf(e);if(!t)return!1;let r=gb.get(t);return r||(r=Tt(e,["--help"],1e4).then(o=>!!o?.includes("--replay-user-messages")),gb.set(t,r)),r}async function mi(e){return await sb().catch(()=>{}),(await Promise.all(Object.values(fi).map(r=>new Promise(o=>{xf(r.bin,["--version"],{timeout:wf,shell:process.platform==="win32",env:He(),windowsHide:!0},(n,i,a)=>{if(n||r.isMine&&!r.isMine(pi(i)))return e?.push({id:r.id,reason:n?_0(n,a):`\`${r.bin} --version\` printed "${pi(i)}"`}),o(null);o({id:r.id,version:pi(i)||null})})})))).filter(r=>r!==null)}function _0(e,t=""){return e.killed?`no answer in ${wf/1e3}s`:e.code==="ENOENT"?"not on PATH":pi(t)||e.message.split(`
81
+ `)[0]||"failed"}function re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0}function hb(e){let t=e??{};return{inputTokens:re(t.input_tokens)+re(t.cache_read_input_tokens)+re(t.cache_creation_input_tokens),outputTokens:re(t.output_tokens)}}function If(e,t){let r=e.usage??={inputTokens:0,outputTokens:0};r.inputTokens+=t.inputTokens,r.outputTokens+=t.outputTokens}function tr(e){if(!e.startsWith("{"))return null;try{return JSON.parse(e)}catch{return null}}function Sb(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var x0=new Set(["Agent","Task"]);function k0(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?String(t.text??""):"").filter(Boolean).join(`
82
82
  `):""}function At(e,t){let r=t??{},o=r.command??r.file_path??r.filePath??r.path??r.pattern??r.description;return typeof o=="string"?pt(`${e}: ${o}`):e}function pt(e){return e.trim().slice(0,2e3)}function pi(e){return(e.trim().split(`
83
- `)[0]??"").slice(0,200)}import{randomBytes as k0}from"node:crypto";import{createServer as w0}from"node:http";var Ib="MYREL_GIT_CREDENTIALS",S0=40,Qa=class{lent=new Map;keyOf=new Map;port=null;server=null;async lend(t,r){let o=k0(32).toString("hex");this.keyOf.set(t,o),this.lent.set(o,{token:r.token,expiresAt:Date.parse(r.expiresAt)});try{return I0(`http://127.0.0.1:${await this.listen()}/${o}`,r.repos)}catch(n){throw this.end(t),n}}renew(t,r){let o=this.keyOf.get(t);o&&this.lent.set(o,{token:r.token,expiresAt:Date.parse(r.expiresAt)})}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=w0((n,i)=>{let a=n.method==="GET"?this.lent.get((n.url??"").slice(1)):void 0;if(!a||a.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
83
+ `)[0]??"").slice(0,200)}import{randomBytes as w0}from"node:crypto";import{createServer as S0}from"node:http";var Ib="MYREL_GIT_CREDENTIALS",I0=40,Qa=class{lent=new Map;keyOf=new Map;port=null;server=null;async lend(t,r){let o=w0(32).toString("hex");this.keyOf.set(t,o),this.lent.set(o,{token:r.token,expiresAt:Date.parse(r.expiresAt)});try{return z0(`http://127.0.0.1:${await this.listen()}/${o}`,r.repos)}catch(n){throw this.end(t),n}}renew(t,r){let o=this.keyOf.get(t);o&&this.lent.set(o,{token:r.token,expiresAt:Date.parse(r.expiresAt)})}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=S0((n,i)=>{let a=n.method==="GET"?this.lent.get((n.url??"").slice(1)):void 0;if(!a||a.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
84
84
  password=${a.token}
85
- `)});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 I0(e,t,r=process.env.GIT_CONFIG_PARAMETERS,o=li()){let n=`!${[o.command,...o.args].map(P0).join(" ")} git-credential`,i=[],a=[...new Set(t.slice(0,S0).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]);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 s=i.map(([u,l])=>z0(`${u}=${l}`)).join(" ");return{[Ib]:e,GIT_CONFIG_PARAMETERS:r?`${r} ${s}`:s}}var z0=e=>`'${e.replaceAll("'","'\\''")}'`;function P0(e){return`"${(process.platform==="win32"?e.replaceAll("\\","/"):e).replace(/["\\$`]/g,"\\$&")}"`}async function zb(e,t,r){let o="";for await(let a of t)o+=String(a);let n=process.env[Ib];if(e!=="get"||!n)return;let i=new Map(o.split(`
86
- `).filter(a=>a.includes("=")).map(a=>[a.slice(0,a.indexOf("=")),a.slice(a.indexOf("=")+1)]));if(!(i.get("protocol")!=="https"||i.get("host")!=="github.com"))try{let a=await fetch(n,{signal:AbortSignal.timeout(5e3)});a.ok&&r(await a.text())}catch{}}import{watchFile as Yj,unwatchFile as Qj}from"node:fs";import{hostname as im,platform as G$}from"node:os";import{spawn as j0}from"node:child_process";import{access as A0,constants as T0,mkdtemp as O0,readdir as N0,readFile as Pb,realpath as D0,rm as U0,stat as Tb,writeFile as C0}from"node:fs/promises";import{tmpdir as E0,userInfo as R0}from"node:os";import{basename as zf,delimiter as M0,dirname as es,join as nr}from"node:path";var L0="/proc/sys/kernel/apparmor_restrict_unprivileged_userns";function Z0(e=jf(),t="/etc/apparmor.d"){return nr(t,`myrel-runner-${e}`)}function jf(){return R0().username.replace(/[^A-Za-z0-9_.-]/g,"_")||"user"}async function en(e={}){let t=e.user??jf(),r=Z0(t,e.profileDir),o={restricted:!1,applies:!1,binaries:[],blocked:[],file:r};if((e.platform??process.platform)!=="linux")return o;let n=await Pb(e.restrict??L0,"utf8").catch(()=>null);if(n===null)return o;o.applies=!0,o.restricted=n.trim()==="1",o.binaries=await F0(e.env??process.env);let i=await Pb(r,"utf8").catch(()=>"");return o.blocked=o.binaries.filter(a=>!i.includes(Ob(a.attach))),o}async function F0(e=process.env){let t=[],r=await jb("muse",e);if(r){let n=es(r),i=(await N0(n).catch(()=>[])).filter(a=>a.startsWith("muse-bin-")).sort();(zf(r).startsWith("muse-bin-")||i.length)&&t.push({cli:"muse",path:zf(r).startsWith("muse-bin-")?r:nr(n,i.at(-1)),attach:`${Pf(n)}/muse-bin-*`})}let o=await jb("codex",e);if(o){let n=es(es(o)),i=nr(n,"codex-resources","bwrap");if(await V0(i)){let a=es(n);t.push({cli:"codex",path:i,attach:zf(a)==="releases"?`${Pf(a)}/*/codex-resources/bwrap`:Pf(i)})}}return t}async function jb(e,t){for(let r of(t.PATH??"").split(M0)){if(!r)continue;let o=nr(r,e);try{if(await A0(o,T0.X_OK),!(await Tb(o)).isFile())continue;return await D0(o)}catch{}}}async function V0(e){return Tb(e).then(t=>t.isFile(),()=>!1)}function Pf(e){return e.replace(/[\\"*?[\]{}^]/g,t=>`\\${t}`)}function Ob(e){return`"${e}" flags=(unconfined)`}function Af(e,t=jf()){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} ${Ob(o.attach)} {`," userns,",` include if exists <local/${n}>`,"}")}return`${r.join(`
85
+ `)});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 z0(e,t,r=process.env.GIT_CONFIG_PARAMETERS,o=li()){let n=`!${[o.command,...o.args].map(j0).join(" ")} git-credential`,i=[],a=[...new Set(t.slice(0,I0).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]);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 s=i.map(([u,l])=>P0(`${u}=${l}`)).join(" ");return{[Ib]:e,GIT_CONFIG_PARAMETERS:r?`${r} ${s}`:s}}var P0=e=>`'${e.replaceAll("'","'\\''")}'`;function j0(e){return`"${(process.platform==="win32"?e.replaceAll("\\","/"):e).replace(/["\\$`]/g,"\\$&")}"`}async function zb(e,t,r){let o="";for await(let a of t)o+=String(a);let n=process.env[Ib];if(e!=="get"||!n)return;let i=new Map(o.split(`
86
+ `).filter(a=>a.includes("=")).map(a=>[a.slice(0,a.indexOf("=")),a.slice(a.indexOf("=")+1)]));if(!(i.get("protocol")!=="https"||i.get("host")!=="github.com"))try{let a=await fetch(n,{signal:AbortSignal.timeout(5e3)});a.ok&&r(await a.text())}catch{}}import{watchFile as Qj,unwatchFile as eA}from"node:fs";import{hostname as im,platform as G$}from"node:os";import{spawn as A0}from"node:child_process";import{access as T0,constants as O0,mkdtemp as N0,readdir as D0,readFile as Pb,realpath as U0,rm as C0,stat as Tb,writeFile as E0}from"node:fs/promises";import{tmpdir as R0,userInfo as M0}from"node:os";import{basename as zf,delimiter as L0,dirname as es,join as nr}from"node:path";var Z0="/proc/sys/kernel/apparmor_restrict_unprivileged_userns";function F0(e=jf(),t="/etc/apparmor.d"){return nr(t,`myrel-runner-${e}`)}function jf(){return M0().username.replace(/[^A-Za-z0-9_.-]/g,"_")||"user"}async function en(e={}){let t=e.user??jf(),r=F0(t,e.profileDir),o={restricted:!1,applies:!1,binaries:[],blocked:[],file:r};if((e.platform??process.platform)!=="linux")return o;let n=await Pb(e.restrict??Z0,"utf8").catch(()=>null);if(n===null)return o;o.applies=!0,o.restricted=n.trim()==="1",o.binaries=await V0(e.env??process.env);let i=await Pb(r,"utf8").catch(()=>"");return o.blocked=o.binaries.filter(a=>!i.includes(Ob(a.attach))),o}async function V0(e=process.env){let t=[],r=await jb("muse",e);if(r){let n=es(r),i=(await D0(n).catch(()=>[])).filter(a=>a.startsWith("muse-bin-")).sort();(zf(r).startsWith("muse-bin-")||i.length)&&t.push({cli:"muse",path:zf(r).startsWith("muse-bin-")?r:nr(n,i.at(-1)),attach:`${Pf(n)}/muse-bin-*`})}let o=await jb("codex",e);if(o){let n=es(es(o)),i=nr(n,"codex-resources","bwrap");if(await J0(i)){let a=es(n);t.push({cli:"codex",path:i,attach:zf(a)==="releases"?`${Pf(a)}/*/codex-resources/bwrap`:Pf(i)})}}return t}async function jb(e,t){for(let r of(t.PATH??"").split(L0)){if(!r)continue;let o=nr(r,e);try{if(await T0(o,O0.X_OK),!(await Tb(o)).isFile())continue;return await U0(o)}catch{}}}async function J0(e){return Tb(e).then(t=>t.isFile(),()=>!1)}function Pf(e){return e.replace(/[\\"*?[\]{}^]/g,t=>`\\${t}`)}function Ob(e){return`"${e}" flags=(unconfined)`}function Af(e,t=jf()){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} ${Ob(o.attach)} {`," userns,",` include if exists <local/${n}>`,"}")}return`${r.join(`
87
87
  `)}
88
- `}function Nb(e,t){return e==="codex"?t!=="full":e==="muse"?t==="edit"||t==="auto":!1}async function Db(e,t){if(e!=="muse"&&e!=="codex")return null;let r=t??await en();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 gi(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 Ub(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 en();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 O0(nr(E0(),"myrel-apparmor-"));try{let o=nr(r,"profile");await C0(o,Af(t.binaries),{mode:420}),e(`Writing ${t.file} for:
88
+ `}function Nb(e,t){return e==="codex"?t!=="full":e==="muse"?t==="edit"||t==="auto":!1}async function Db(e,t){if(e!=="muse"&&e!=="codex")return null;let r=t??await en();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 gi(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 Ub(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 en();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 N0(nr(R0(),"myrel-apparmor-"));try{let o=nr(r,"profile");await E0(o,Af(t.binaries),{mode:420}),e(`Writing ${t.file} for:
89
89
  ${t.binaries.map(i=>` ${i.attach}`).join(`
90
- `)}`);let n=process.getuid?.()===0;await Ab(n?"install":"sudo",[...n?[]:["install"],"-m","0644",o,t.file]),await Ab(n?"apparmor_parser":"sudo",[...n?[]:["apparmor_parser"],"-r",t.file])}finally{await U0(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 Ab(e,t){return new Promise((r,o)=>{let n=j0(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 TP,realpath as e$,stat as OP}from"node:fs/promises";import{isAbsolute as NP,join as DP,relative as UP,resolve as CP,sep as Qb}from"node:path";import{spawn as zP}from"node:child_process";import{mkdtemp as Wb,realpath as Gb,rm as qb,writeFile as PP}from"node:fs/promises";import{tmpdir as Hb}from"node:os";import{join as Cf}from"node:path";var ts=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;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,s=i.length&&a?.additionalDirectories?{additionalDirectories:i}:{};n?this.call("session/resume",{sessionId:n,cwd:r,mcpServers:o},()=>this.opened(n)):this.call("session/new",{cwd:r,mcpServers:o,...s},u=>{this.configured(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}]},i=>{let{stopReason:a,usage:s}=i??{};if(s){let u=l=>typeof l=="number"&&l>0?Math.round(l):0;this.state.usage={inputTokens:u(s.inputTokens),outputTokens:u(s.outputTokens)+u(s.thoughtTokens)}}this.state.failed=a==="refusal"||a==="cancelled",this.state.result=(this.state.draft??"").trim(),this.state.failed&&!this.state.result&&(this.state.result=`The agent stopped: ${String(a)}.`),this.finish()})},o=[...this.opts.config??[]],n=()=>{let i=o.shift();if(!i)return r();this.request("session/set_config_option",{sessionId:t,configId:i.id,value:i.value},a=>{a.error||this.configured(a.result),n()})};this.opts.mode?this.call("session/set_mode",{sessionId:t,modeId:this.opts.mode},n):n()}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;t.sessionUpdate==="agent_message_chunk"&&typeof r?.text=="string"&&(this.state.draft=(this.state.draft??"")+r.text,this.state.draft.trim()&&(this.state.progress=this.state.draft.trim().slice(0,2e3))),t.sessionUpdate==="tool_call"&&(this.state.draft=void 0,typeof t.title=="string"&&t.title&&(this.state.progress=t.title.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?.title),i=o.find(s=>s.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;return!!r&&typeof t=="string"&&o.some(n=>t.startsWith(r(n.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)}
91
- `)}};import{request as J0}from"node:http";import{request as K0}from"node:https";var W=e=>e&&typeof e=="object"?e:{},B=e=>typeof e=="string"&&e?e:void 0,ns=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0,B0=e=>e.trim().slice(0,2e3),rs=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,model:i,config:a}=this.opts,s={cwd:t,sandbox:o,approvalPolicy:n,...i?.model&&{model:i.model},...a&&{config:a}};r?this.call("thread/resume",{...s,threadId:r},u=>this.opened(u)):this.call("thread/start",s,u=>this.opened(u))})}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,W(r.params));if(typeof r.id=="number"){let o=this.pending.get(r.id);this.pending.delete(r.id),o?.(r)}}opened(t){let r=W(W(t).thread),o=B(r.id);if(!o)return this.fail("Codex started no session.");this.threadId=o,this.state.sessionId=o;let n=B(W(t).model)??B(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=B(W(W(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,W(r.item));case"thread/tokenUsage/updated":return this.addUsage(r);case"account/rateLimits/updated":{let o=W0(r.rateLimits);o&&(this.state.limits=o);return}case"model/rerouted":{let o=B(r.toModel)??B(r.model);o&&(this.state.model=o);return}case"error":{let o=B(W(r.error).message);o&&(this.state.error=o);return}case"turn/completed":return this.completed(W(r.turn))}}subagent(t,r,o){if(t==="item/started"||t==="item/completed")return this.item(t,W(r.item),o);if(t==="thread/tokenUsage/updated"){let n=W(W(r.tokenUsage).last);return Wa(this.state,o,ns(n.inputTokens)+ns(n.outputTokens)),this.addUsage(r)}}addUsage(t){let r=W(W(t.tokenUsage).last),o=this.state.usage??={inputTokens:0,outputTokens:0};o.inputTokens+=ns(r.inputTokens),o.outputTokens+=ns(r.outputTokens)}item(t,r,o){let n=i=>di(this.state,B0(i),o);switch(r.type){case"commandExecution":{if(t!=="item/started")return;let a=B(W(r.commandActions?.[0]).command)??Yn(B(r.command)??"");a&&n(`$ ${a}`);return}case"fileChange":{let i=Array.isArray(r.changes)?r.changes.map(a=>B(W(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(`${B(r.server)??"mcp"}.${B(r.tool)??"tool"}`);return;case"webSearch":t==="item/started"&&B(r.query)&&n(`Search ${B(r.query)}`);return;case"agentMessage":{let i=B(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=B(r.agentThreadId);if(!i)return;r.kind==="started"?er(this.state,i,H0(r.agentPath),"",{model:B(r.model)}):r.kind==="completed"?jt(this.state,i,!0):r.kind==="interrupted"&&jt(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)er(this.state,n,"",B(r.prompt)??"",{model:B(r.model)});if(t==="item/completed")for(let[n,i]of Object.entries(W(r.agentsStates))){let a=W(i),s=B(a.message)??"";a.status==="completed"||a.status==="shutdown"?jt(this.state,n,!0,s):(a.status==="errored"||a.status==="interrupted")&&jt(this.state,n,!1,s)}}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=B(W(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=W(t.params),o=n=>this.send({jsonrpc:"2.0",id:t.id,result:n});switch(t.method){case"item/commandExecution/requestApproval":{let i=B(W(r.commandActions?.[0]).command)??Yn(B(r.command)??""),a=!!i&&await this.ask("Bash",{command:i,...B(r.reason)&&{description:B(r.reason)}});return o({decision:a?"accept":"decline"})}case"item/fileChange/requestApproval":{let n=[...B(r.grantRoot)?[B(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=W(r.permissions),i=W(n.fileSystem),a=[...i.write??[],...i.read??[]].filter(l=>typeof l=="string"),s=W(n.network).enabled===!0,u=a.length>0||s;for(let l of a)u&&(u=await this.ask("Edit",{file_path:l}));return u&&s&&(u=await this.ask("Bash",{command:B(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)}
92
- `)}};function W0(e){let t=W(e),r=o=>{let n=W(o);return Object.keys(n).length?{used_percent:n.usedPercent,window_minutes:n.windowDurationMins,resets_at:n.resetsAt}:null};return _f({primary:r(t.primary),secondary:r(t.secondary)},new Date().toISOString())}var G0=900*1e3;function Cb(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}}}),s=(e.startsWith("https:")?K0:J0)(e,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",authorization:`Bearer ${t}`,"content-length":Buffer.byteLength(i)},timeout:G0},u=>{let l="";u.setEncoding("utf8"),u.on("data",d=>{l.length<1e6&&(l+=d)}),u.on("end",()=>n(u.statusCode===200&&q0(l))),u.on("error",()=>n(!1))});s.on("timeout",()=>s.destroy()),s.on("error",()=>n(!1)),s.end(i)})}function q0(e){try{let t=W(W(JSON.parse(e)).result).content,r=Array.isArray(t)?B(W(t[0]).text):void 0;return!!r&&W(JSON.parse(r)).behavior==="allow"}catch{return!1}}function H0(e){return(B(e)??"").split("/").filter(Boolean).pop()??""}var is=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"}})}
90
+ `)}`);let n=process.getuid?.()===0;await Ab(n?"install":"sudo",[...n?[]:["install"],"-m","0644",o,t.file]),await Ab(n?"apparmor_parser":"sudo",[...n?[]:["apparmor_parser"],"-r",t.file])}finally{await C0(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 Ab(e,t){return new Promise((r,o)=>{let n=A0(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 OP,realpath as e$,stat as NP}from"node:fs/promises";import{isAbsolute as DP,join as UP,relative as CP,resolve as EP,sep as Qb}from"node:path";import{spawn as PP}from"node:child_process";import{mkdtemp as Wb,realpath as Gb,rm as qb,writeFile as jP}from"node:fs/promises";import{tmpdir as Hb}from"node:os";import{join as Cf}from"node:path";var ts=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;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,s=i.length&&a?.additionalDirectories?{additionalDirectories:i}:{};n?this.call("session/resume",{sessionId:n,cwd:r,mcpServers:o},()=>this.opened(n)):this.call("session/new",{cwd:r,mcpServers:o,...s},u=>{this.configured(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}]},i=>{let{stopReason:a,usage:s}=i??{};if(s){let u=l=>typeof l=="number"&&l>0?Math.round(l):0;this.state.usage={inputTokens:u(s.inputTokens),outputTokens:u(s.outputTokens)+u(s.thoughtTokens)}}this.state.failed=a==="refusal"||a==="cancelled",this.state.result=(this.state.draft??"").trim(),this.state.failed&&!this.state.result&&(this.state.result=`The agent stopped: ${String(a)}.`),this.finish()})},o=[...this.opts.config??[]],n=()=>{let i=o.shift();if(!i)return r();this.request("session/set_config_option",{sessionId:t,configId:i.id,value:i.value},a=>{a.error||this.configured(a.result),n()})};this.opts.mode?this.call("session/set_mode",{sessionId:t,modeId:this.opts.mode},n):n()}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;t.sessionUpdate==="agent_message_chunk"&&typeof r?.text=="string"&&(this.state.draft=(this.state.draft??"")+r.text,this.state.draft.trim()&&(this.state.progress=this.state.draft.trim().slice(0,2e3))),t.sessionUpdate==="tool_call"&&(this.state.draft=void 0,typeof t.title=="string"&&t.title&&(this.state.progress=t.title.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?.title),i=o.find(s=>s.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;return!!r&&typeof t=="string"&&o.some(n=>t.startsWith(r(n.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)}
91
+ `)}};import{request as K0}from"node:http";import{request as B0}from"node:https";var W=e=>e&&typeof e=="object"?e:{},B=e=>typeof e=="string"&&e?e:void 0,ns=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0,W0=e=>e.trim().slice(0,2e3),rs=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,model:i,config:a}=this.opts,s={cwd:t,sandbox:o,approvalPolicy:n,...i?.model&&{model:i.model},...a&&{config:a}};r?this.call("thread/resume",{...s,threadId:r},u=>this.opened(u)):this.call("thread/start",s,u=>this.opened(u))})}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,W(r.params));if(typeof r.id=="number"){let o=this.pending.get(r.id);this.pending.delete(r.id),o?.(r)}}opened(t){let r=W(W(t).thread),o=B(r.id);if(!o)return this.fail("Codex started no session.");this.threadId=o,this.state.sessionId=o;let n=B(W(t).model)??B(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=B(W(W(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,W(r.item));case"thread/tokenUsage/updated":return this.addUsage(r);case"account/rateLimits/updated":{let o=G0(r.rateLimits);o&&(this.state.limits=o);return}case"model/rerouted":{let o=B(r.toModel)??B(r.model);o&&(this.state.model=o);return}case"error":{let o=B(W(r.error).message);o&&(this.state.error=o);return}case"turn/completed":return this.completed(W(r.turn))}}subagent(t,r,o){if(t==="item/started"||t==="item/completed")return this.item(t,W(r.item),o);if(t==="thread/tokenUsage/updated"){let n=W(W(r.tokenUsage).last);return Wa(this.state,o,ns(n.inputTokens)+ns(n.outputTokens)),this.addUsage(r)}}addUsage(t){let r=W(W(t.tokenUsage).last),o=this.state.usage??={inputTokens:0,outputTokens:0};o.inputTokens+=ns(r.inputTokens),o.outputTokens+=ns(r.outputTokens)}item(t,r,o){let n=i=>di(this.state,W0(i),o);switch(r.type){case"commandExecution":{if(t!=="item/started")return;let a=B(W(r.commandActions?.[0]).command)??Yn(B(r.command)??"");a&&n(`$ ${a}`);return}case"fileChange":{let i=Array.isArray(r.changes)?r.changes.map(a=>B(W(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(`${B(r.server)??"mcp"}.${B(r.tool)??"tool"}`);return;case"webSearch":t==="item/started"&&B(r.query)&&n(`Search ${B(r.query)}`);return;case"agentMessage":{let i=B(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=B(r.agentThreadId);if(!i)return;r.kind==="started"?er(this.state,i,X0(r.agentPath),"",{model:B(r.model)}):r.kind==="completed"?jt(this.state,i,!0):r.kind==="interrupted"&&jt(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)er(this.state,n,"",B(r.prompt)??"",{model:B(r.model)});if(t==="item/completed")for(let[n,i]of Object.entries(W(r.agentsStates))){let a=W(i),s=B(a.message)??"";a.status==="completed"||a.status==="shutdown"?jt(this.state,n,!0,s):(a.status==="errored"||a.status==="interrupted")&&jt(this.state,n,!1,s)}}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=B(W(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=W(t.params),o=n=>this.send({jsonrpc:"2.0",id:t.id,result:n});switch(t.method){case"item/commandExecution/requestApproval":{let i=B(W(r.commandActions?.[0]).command)??Yn(B(r.command)??""),a=!!i&&await this.ask("Bash",{command:i,...B(r.reason)&&{description:B(r.reason)}});return o({decision:a?"accept":"decline"})}case"item/fileChange/requestApproval":{let n=[...B(r.grantRoot)?[B(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=W(r.permissions),i=W(n.fileSystem),a=[...i.write??[],...i.read??[]].filter(l=>typeof l=="string"),s=W(n.network).enabled===!0,u=a.length>0||s;for(let l of a)u&&(u=await this.ask("Edit",{file_path:l}));return u&&s&&(u=await this.ask("Bash",{command:B(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)}
92
+ `)}};function G0(e){let t=W(e),r=o=>{let n=W(o);return Object.keys(n).length?{used_percent:n.usedPercent,window_minutes:n.windowDurationMins,resets_at:n.resetsAt}:null};return _f({primary:r(t.primary),secondary:r(t.secondary)},new Date().toISOString())}var q0=900*1e3;function Cb(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}}}),s=(e.startsWith("https:")?B0:K0)(e,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",authorization:`Bearer ${t}`,"content-length":Buffer.byteLength(i)},timeout:q0},u=>{let l="";u.setEncoding("utf8"),u.on("data",d=>{l.length<1e6&&(l+=d)}),u.on("end",()=>n(u.statusCode===200&&H0(l))),u.on("error",()=>n(!1))});s.on("timeout",()=>s.destroy()),s.on("error",()=>n(!1)),s.end(i)})}function H0(e){try{let t=W(W(JSON.parse(e)).result).content,r=Array.isArray(t)?B(W(t[0]).text):void 0;return!!r&&W(JSON.parse(r)).behavior==="allow"}catch{return!1}}function X0(e){return(B(e)??"").split("/").filter(Boolean).pop()??""}var is=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"}})}
93
93
  `),!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)}
94
- `)}};import{chmod as X0,mkdir as Eb,writeFile as Rb}from"node:fs/promises";import{dirname as Y0,join as hi,resolve as Q0,sep as eP}from"node:path";var tP="myrel",nP=/^[a-z0-9]+(-[a-z0-9]+)*$/;async function Mb(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=hi(r,"plugin"),a=hi(i,"skills"),s=0;for(let u of n.skills??[]){if(!nP.test(u.name))continue;let l=hi(a,u.name);for(let d of u.files??[]){let p=Q0(l,d.path);p.startsWith(l+eP)&&(await Eb(Y0(p),{recursive:!0}),await Rb(p,Buffer.from(d.content,"base64")),(/\.(sh|py)$/.test(d.path)||d.path.startsWith("scripts/"))&&await X0(p,493).catch(()=>{}))}s++}return s?(await Eb(hi(i,".claude-plugin"),{recursive:!0}),await Rb(hi(i,".claude-plugin","plugin.json"),JSON.stringify({name:tP,description:"Skills added in Myrel for this run.",version:"1.0.0"})),{plugin:i,skills:a,count:s}):null}import{spawn as rP}from"node:child_process";import{chmod as iP,mkdir as oP,writeFile as Tf}from"node:fs/promises";import{request as aP}from"node:http";import{request as sP}from"node:https";import{delimiter as Lb,join as os}from"node:path";var Of="MYREL_SSH_SHIM",cP=["ssh","scp","sftp"],uP=960*1e3;async function Zb(e,t,r=process.platform){let o=os(e,"ssh-bin");await oP(o,{recursive:!0,mode:448});let n=li();for(let s of cP)if(r==="win32"){let u=[n.command,...n.args].map(l=>`"${l}"`).join(" ");await Tf(os(o,`${s}.cmd`),`@echo off\r
94
+ `)}};import{chmod as Y0,mkdir as Eb,writeFile as Rb}from"node:fs/promises";import{dirname as Q0,join as hi,resolve as eP,sep as tP}from"node:path";var nP="myrel",rP=/^[a-z0-9]+(-[a-z0-9]+)*$/;async function Mb(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=hi(r,"plugin"),a=hi(i,"skills"),s=0;for(let u of n.skills??[]){if(!rP.test(u.name))continue;let l=hi(a,u.name);for(let d of u.files??[]){let p=eP(l,d.path);p.startsWith(l+tP)&&(await Eb(Q0(p),{recursive:!0}),await Rb(p,Buffer.from(d.content,"base64")),(/\.(sh|py)$/.test(d.path)||d.path.startsWith("scripts/"))&&await Y0(p,493).catch(()=>{}))}s++}return s?(await Eb(hi(i,".claude-plugin"),{recursive:!0}),await Rb(hi(i,".claude-plugin","plugin.json"),JSON.stringify({name:nP,description:"Skills added in Myrel for this run.",version:"1.0.0"})),{plugin:i,skills:a,count:s}):null}import{spawn as iP}from"node:child_process";import{chmod as oP,mkdir as aP,writeFile as Tf}from"node:fs/promises";import{request as sP}from"node:http";import{request as cP}from"node:https";import{delimiter as Lb,join as os}from"node:path";var Of="MYREL_SSH_SHIM",uP=["ssh","scp","sftp"],lP=960*1e3;async function Zb(e,t,r=process.platform){let o=os(e,"ssh-bin");await aP(o,{recursive:!0,mode:448});let n=li();for(let s of uP)if(r==="win32"){let u=[n.command,...n.args].map(l=>`"${l}"`).join(" ");await Tf(os(o,`${s}.cmd`),`@echo off\r
95
95
  ${u} ssh-shim ${s} %*\r
96
96
  `,{mode:448})}else{let u=[n.command,...n.args].map(d=>`'${d.replaceAll("'","'\\''")}'`).join(" "),l=os(o,s);await Tf(l,`#!/bin/sh
97
97
  exec ${u} ssh-shim ${s} "$@"
98
- `,{mode:448}),await iP(l,448)}let i=os(e,"ssh-shim.json");await Tf(i,JSON.stringify(t),{mode:384});let a=Object.keys(process.env).find(s=>s.toUpperCase()==="PATH")??"PATH";return{[a]:[o,process.env[a]].filter(Boolean).join(r==="win32"?";":":"),[Of]:i}}var lP=new Set("qTn46vxCa".split("")),dP=new Set(["p","l"]),pP=/^(?:BatchMode|ConnectTimeout|ServerAliveInterval|ServerAliveCountMax|LogLevel|StrictHostKeyChecking|UserKnownHostsFile|ConnectionAttempts)=/i,fP=/^(?:git[- ](?:upload-pack|receive-pack|upload-archive) '[^'\n]*'|git-lfs-(?:authenticate|transfer) '?[\w./~-]+'? (?:upload|download))$/,Nf="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 mP(e){if(e.length>1&&fP.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 m=0;m<p.length;m++){let f=p[m];if(!lP.has(f)){if(dP.has(f)||f==="o"){let g=p.slice(m+1)||e[++t];if(g===void 0)return{kind:"refuse",message:`ssh: -${f} needs a value.`};if(f==="l"&&(r=g),f==="o"&&!pP.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 f==="s"?{kind:"refuse",message:Nf}:"LRDW".includes(f)?{kind:"refuse",message:"Port forwarding over SSH is not available to Myrel's agents."}:f==="A"?{kind:"refuse",message:"Agent forwarding is not available to Myrel's agents."}:"tN".includes(f)?{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 -${f} 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:Nf};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+$/,""),s=a.lastIndexOf("@"),u=s>=0?a.slice(s+1):a,l=s>=0?a.slice(0,s):r;return{kind:"run",host:l?`${l}@${u}`:u,command:i}}async function Fb(e,t,r={out:process.stdout,err:process.stderr}){let o=e==="ssh"?mP(t):{kind:"refuse",message:Nf};if(o.kind==="refuse")return r.err.write(`${o.message}
99
- `),255;if(o.kind==="passthrough")return vP(t);let n=process.env[Of]?await he(process.env[Of]).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.
100
- `),255;let i=await gP(n,{host:o.host,command:o.command,reason:"Asked from the shell (ssh)."});if(!i.ok)return r.err.write(`${i.text}
98
+ `,{mode:448}),await oP(l,448)}let i=os(e,"ssh-shim.json");await Tf(i,JSON.stringify(t),{mode:384});let a=Object.keys(process.env).find(s=>s.toUpperCase()==="PATH")??"PATH";return{[a]:[o,process.env[a]].filter(Boolean).join(r==="win32"?";":":"),[Of]:i}}var dP=new Set("qTn46vxCa".split("")),pP=new Set(["p","l"]),fP=/^(?:BatchMode|ConnectTimeout|ServerAliveInterval|ServerAliveCountMax|LogLevel|StrictHostKeyChecking|UserKnownHostsFile|ConnectionAttempts)=/i,mP=/^(?:git[- ](?:upload-pack|receive-pack|upload-archive) '[^'\n]*'|git-lfs-(?:authenticate|transfer) '?[\w./~-]+'? (?:upload|download))$/,Nf="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 gP(e){if(e.length>1&&mP.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 m=0;m<p.length;m++){let f=p[m];if(!dP.has(f)){if(pP.has(f)||f==="o"){let g=p.slice(m+1)||e[++t];if(g===void 0)return{kind:"refuse",message:`ssh: -${f} needs a value.`};if(f==="l"&&(r=g),f==="o"&&!fP.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 f==="s"?{kind:"refuse",message:Nf}:"LRDW".includes(f)?{kind:"refuse",message:"Port forwarding over SSH is not available to Myrel's agents."}:f==="A"?{kind:"refuse",message:"Agent forwarding is not available to Myrel's agents."}:"tN".includes(f)?{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 -${f} 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:Nf};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+$/,""),s=a.lastIndexOf("@"),u=s>=0?a.slice(s+1):a,l=s>=0?a.slice(0,s):r;return{kind:"run",host:l?`${l}@${u}`:u,command:i}}async function Fb(e,t,r={out:process.stdout,err:process.stderr}){let o=e==="ssh"?gP(t):{kind:"refuse",message:Nf};if(o.kind==="refuse")return r.err.write(`${o.message}
99
+ `),255;if(o.kind==="passthrough")return yP(t);let n=process.env[Of]?await he(process.env[Of]).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.
100
+ `),255;let i=await hP(n,{host:o.host,command:o.command,reason:"Asked from the shell (ssh)."});if(!i.ok)return r.err.write(`${i.text}
101
101
  `),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}
102
- `),255}}function gP(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:")?sP:aP)(e.url,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",authorization:`Bearer ${e.token}`,"content-length":Buffer.byteLength(o)},timeout:uP},a=>{let s="";a.setEncoding("utf8"),a.on("data",u=>{s.length<2e6&&(s+=u)}),a.on("end",()=>r(hP(a.statusCode,s))),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 hP(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 vP(e){let t=Object.keys(process.env).find(o=>o.toUpperCase()==="PATH")??"PATH",r=(process.env[t]??"").split(Lb).filter(o=>!o.endsWith(`${process.platform==="win32"?"\\":"/"}ssh-bin`)).join(Lb);return new Promise(o=>{let n=rP("ssh",e,{stdio:"inherit",env:{...process.env,[t]:r}});n.once("error",()=>o(255)),n.once("close",i=>o(i??255))})}import{execFile as yP}from"node:child_process";import{createHash as bP}from"node:crypto";import{mkdir as $P,realpath as Df,stat as Vb}from"node:fs/promises";import{basename as _P,join as as,relative as xP}from"node:path";import{promisify as kP}from"node:util";var wP=kP(yP),SP=1440*60*1e3,Jb=()=>as(ee(),"worktrees.json"),Ye=(e,t)=>wP("git",["-C",e,...t],{maxBuffer:4*1024*1024,env:He()});async function tn(){return await he(Jb())??[]}async function Kb(e){await Je(Jb(),e)}function IP(e){return`myrel/thr-${e.slice(-10).toLowerCase()}`}async function Bb(e,t){let r=await Ye(e,["rev-parse","--show-toplevel"]).then(a=>Df(a.stdout.trim())).catch(()=>null);if(!r||!await Ye(r,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>null))return null;let o=await tn(),n=o.find(a=>a.repo===r&&a.threadId===t),i=!1;if(!n||!await Vb(n.path).catch(()=>null)){let a=bP("sha256").update(r).digest("hex").slice(0,8),s=as(ee(),"worktrees",`${_P(r)}-${a}`);await $P(s,{recursive:!0,mode:448});let u=as(await Df(s),t.slice(-10).toLowerCase()),l=IP(t);await Ye(r,["worktree","prune"]).catch(()=>{});let d=await Ye(r,["rev-parse","--verify","--quiet",`refs/heads/${l}`]).catch(()=>null);await Ye(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 Kb([...o.filter(a=>!(a.repo===r&&a.threadId===t)),n]),{cwd:as(n.path,xP(r,await Df(e))),worktree:n,created:i}}async function ss(e){if(!await Vb(e.path).catch(()=>null))return{missing:!0,dirty:!1,merged:!0};let t=await Ye(e.path,["status","--porcelain"]).catch(()=>null),r=await Ye(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 Uf(e,{force:t=!1}={}){let r=await ss(e);if(r.dirty&&!t)throw new Error(`${e.path} has uncommitted changes. Commit them, or remove it with --force.`);r.missing||await Ye(e.repo,["worktree","remove",...t?["--force"]:[],e.path]),await Ye(e.repo,["worktree","prune"]).catch(()=>{}),r.merged&&await Ye(e.repo,["branch","-d",e.branch]).catch(()=>{}),await Kb((await tn()).filter(o=>o.path!==e.path))}async function cs(e=()=>!1,t=Date.now()){let r=[];for(let o of await tn()){if(e(o)||t-o.lastUsed<SP)continue;let n=await ss(o).catch(()=>null);!n||n.dirty||!n.merged||await Uf(o).then(()=>r.push(o)).catch(()=>{})}return r}var Ef=new Set(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]),Xb=9e4,jP=1e3,us=class{constructor(t){this.opts=t}opts;running=new Map;turns=new Map;worktrees=new Map;cancelled=new Set;interrupted=new Set;git=new Qa;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 ls(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=null;if(o.worktrees!==!1&&o.access!=="read")try{i=await Bb(n,t.threadId)}catch(P){return r(`Could not make a git worktree for this thread in ${n}: ${Yb(P)}
102
+ `),255}}function hP(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:")?cP:sP)(e.url,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",authorization:`Bearer ${e.token}`,"content-length":Buffer.byteLength(o)},timeout:lP},a=>{let s="";a.setEncoding("utf8"),a.on("data",u=>{s.length<2e6&&(s+=u)}),a.on("end",()=>r(vP(a.statusCode,s))),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 vP(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 yP(e){let t=Object.keys(process.env).find(o=>o.toUpperCase()==="PATH")??"PATH",r=(process.env[t]??"").split(Lb).filter(o=>!o.endsWith(`${process.platform==="win32"?"\\":"/"}ssh-bin`)).join(Lb);return new Promise(o=>{let n=iP("ssh",e,{stdio:"inherit",env:{...process.env,[t]:r}});n.once("error",()=>o(255)),n.once("close",i=>o(i??255))})}import{execFile as bP}from"node:child_process";import{createHash as $P}from"node:crypto";import{mkdir as _P,realpath as Df,stat as Vb}from"node:fs/promises";import{basename as xP,join as as,relative as kP}from"node:path";import{promisify as wP}from"node:util";var SP=wP(bP),IP=1440*60*1e3,Jb=()=>as(ee(),"worktrees.json"),Ye=(e,t)=>SP("git",["-C",e,...t],{maxBuffer:4*1024*1024,env:He()});async function tn(){return await he(Jb())??[]}async function Kb(e){await Je(Jb(),e)}function zP(e){return`myrel/thr-${e.slice(-10).toLowerCase()}`}async function Bb(e,t){let r=await Ye(e,["rev-parse","--show-toplevel"]).then(a=>Df(a.stdout.trim())).catch(()=>null);if(!r||!await Ye(r,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>null))return null;let o=await tn(),n=o.find(a=>a.repo===r&&a.threadId===t),i=!1;if(!n||!await Vb(n.path).catch(()=>null)){let a=$P("sha256").update(r).digest("hex").slice(0,8),s=as(ee(),"worktrees",`${xP(r)}-${a}`);await _P(s,{recursive:!0,mode:448});let u=as(await Df(s),t.slice(-10).toLowerCase()),l=zP(t);await Ye(r,["worktree","prune"]).catch(()=>{});let d=await Ye(r,["rev-parse","--verify","--quiet",`refs/heads/${l}`]).catch(()=>null);await Ye(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 Kb([...o.filter(a=>!(a.repo===r&&a.threadId===t)),n]),{cwd:as(n.path,kP(r,await Df(e))),worktree:n,created:i}}async function ss(e){if(!await Vb(e.path).catch(()=>null))return{missing:!0,dirty:!1,merged:!0};let t=await Ye(e.path,["status","--porcelain"]).catch(()=>null),r=await Ye(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 Uf(e,{force:t=!1}={}){let r=await ss(e);if(r.dirty&&!t)throw new Error(`${e.path} has uncommitted changes. Commit them, or remove it with --force.`);r.missing||await Ye(e.repo,["worktree","remove",...t?["--force"]:[],e.path]),await Ye(e.repo,["worktree","prune"]).catch(()=>{}),r.merged&&await Ye(e.repo,["branch","-d",e.branch]).catch(()=>{}),await Kb((await tn()).filter(o=>o.path!==e.path))}async function cs(e=()=>!1,t=Date.now()){let r=[];for(let o of await tn()){if(e(o)||t-o.lastUsed<IP)continue;let n=await ss(o).catch(()=>null);!n||n.dirty||!n.merged||await Uf(o).then(()=>r.push(o)).catch(()=>{})}return r}var Ef=new Set(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]),Xb=9e4,AP=1e3,us=class{constructor(t){this.opts=t}opts;running=new Map;turns=new Map;worktrees=new Map;cancelled=new Set;interrupted=new Set;git=new Qa;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 ls(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=null;if(o.worktrees!==!1&&o.access!=="read")try{i=await Bb(n,t.threadId)}catch(P){return r(`Could not make a git worktree for this thread in ${n}: ${Yb(P)}
103
103
  To run tasks in the folder itself instead, run \`myrel-runner worktrees off\`.`)}let a=i?.cwd??n,s=this.opts.log??(()=>{}),u=a===n?[]:[n];for(let P of t.folders??[]){let C=await ls(o,P);C?C!==a&&!u.includes(C)&&u.push(C):s(` skipping ${P}: not shared on this computer`)}let l=fi[t.cli],d=!!t.agent&&t.cli==="claude",p=Ef.has(t.cli)&&!i?.created?await this.opts.sessions.get(t.threadId,t.cli):void 0,m=p&&t.agent?.resume&&p.task===t.agent.resume.after?t.agent.resume.prompt:void 0;s(`\u25B6 ${l.id} in ${a}: ${t.prompt.split(`
104
104
  `)[0].slice(0,80)}`);let f,g={args:[]},y=null,x;if(t.agent&&o.server){f=await Wb(Cf(Hb(),"myrel-agent-"));let P=o.server.replace(/\/$/,"");x=Cb(`${P}${t.agent.mcpPath}`,t.agent.token);let C=(t.agent.connectors??[]).map(j=>j.transport==="http"?{transport:j.transport,name:j.name,url:`${P}${j.path}`}:j);y=t.agent.skills?await Mb(`${P}${t.agent.skills.path}`,t.agent.token,f):null,g=await l.agent({url:`${P}${t.agent.mcpPath}`,token:t.agent.token,dir:f,connectors:C,asks:d,access:o.access,dirs:u,...y&&{skills:{plugin:y.plugin,dir:y.skills}}})}let I=()=>f?qb(f,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve(),S=i?`
105
105
 
@@ -107,20 +107,20 @@ To run tasks in the folder itself instead, run \`myrel-runner worktrees off\`.`)
107
107
 
108
108
  Skills folder for this run: ${p.skills}`:n,y=Nb(u.id,i.access)?await Db(u.id).catch(()=>null):null,x=y?`${g}
109
109
 
110
- ${y}`:g,I=u.input?u.input(x,i.access):x,S=u.promptFile?await Wb(Cf(Hb(),"myrel-prompt-")):void 0,T=S?Cf(S,"prompt.md"):void 0;T&&await PP(T,I,{mode:384});let P=[...r.appServer?[]:bb(u,t.model),...l.args],C=r.appServer?["app-server",...l.args]:u.args({access:i.access,resume:o,extra:P,dirs:d,asks:r.asks,promptFile:T,stream:r.stream}),j=(this.opts.spawn??zP)(u.bin,C,{cwd:s,env:He(r.env),stdio:["pipe","pipe","pipe"],shell:process.platform==="win32"});if(S){let Z=()=>{qb(S,{recursive:!0,force:!0}).catch(()=>{})};j.once("close",Z),j.once("error",Z)}this.running.set(t.taskId,j),this.opts.onChange?.(this.runningIds());let A={},ue="",tt="",Me="",nt=0,sn,mt="",wi,or,ar=Z=>{!Z||Z===wi||(wi=Z,this.opts.onLimits?.(t.cli,Z))},cn=()=>A.usage?{...A.usage,...A.model&&{model:A.model.slice(0,200)}}:void 0,Si=()=>{for(let ie of A.agentNotes?.splice(0)??[])this.send({type:"task.progress",taskId:t.taskId,text:ie.text,agent:ie.agent,...ie.ms!==void 0&&{ms:ie.ms}});let Z=cn(),te=Z?JSON.stringify(Z):"",fe=!!A.progress&&A.progress!==sn;if(fe||te!==mt){sn=A.progress,mt=te,nt=Date.now();let ie=fe&&A.progressAgent;this.send({type:"task.progress",taskId:t.taskId,text:fe?A.progress:"",...Z&&{usage:Z},...ie&&{agent:ie}})}};if(j.stdout.setEncoding("utf8"),j.stdout.on("data",Z=>{ue.length<4*Xb&&(ue+=Z),Me+=Z;let te=Me.split(`
111
- `);Me=te.pop();for(let ie of te)u.line(ie.trim(),A);ar(A.limits),A.sessionId&&A.sessionId!==or&&Ef.has(t.cli)&&(or=A.sessionId,this.opts.sessions.set(t.threadId,t.cli,{id:A.sessionId,task:t.taskId}).catch(()=>{}));let fe=cn();(Date.now()-nt>=jP||fe&&JSON.stringify(fe)!==mt||A.agentNotes?.length)&&Si()}),j.stderr.setEncoding("utf8"),j.stderr.on("data",Z=>{tt.length<2e4&&(tt+=Z)}),j.stdin.on("error",()=>{}),u.acp){let Z={write:fe=>{j.stdin.write(fe)},end:()=>j.stdin.end()},te={cwd:s,prompt:I,mcpServers:l.mcpServers??[],resume:o,dirs:d,...u.acp(i.access,Ya(t.model))};A.acp=new ts(Z,te,A),A.acp.start()}else if(r.appServer){let Z={write:fe=>{j.stdin.write(fe)},end:()=>j.stdin.end()},te={cwd:s,prompt:I,resume:o,model:Ya(t.model),clientVersion:this.opts.version??"0",...r.appServer};A.appServer=new rs(Z,te,A),this.turns.set(t.taskId,A.appServer),A.appServer.start()}else if(r.stream){let Z={write:te=>{j.stdin.write(te)},end:()=>j.stdin.end()};A.claudeStream=new is(Z,I),this.turns.set(t.taskId,A.claudeStream),A.claudeStream.start()}else j.stdin.end(T?"":I);let sr=setTimeout(()=>j.kill("SIGTERM"),this.opts.timeoutMs??3600*1e3);return await new Promise(Z=>{let te=!1,fe=(ie,k)=>{if(te)return;if(te=!0,clearTimeout(sr),f(),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`),Z(!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."}),Z(!1);a(`${ie?"\u2713":"\u2717"} ${u.id} task finished`);let D=cn();this.send({type:"task.done",taskId:t.taskId,ok:ie,result:k.slice(0,Xb-m.length)+m,...D&&{usage:D}}),Z(!1)};j.on("error",ie=>{fe(!1,ie.code==="ENOENT"?`${u.bin} is not installed on this computer, or not on PATH for myrel-runner.`:`Could not start ${u.bin}: ${ie.message}`)}),j.on("exit",()=>{(this.cancelled.has(t.taskId)||this.interrupted.has(t.taskId))&&fe(!1,"")}),j.on("close",async(ie,k)=>{Me.trim()&&u.line(Me.trim(),A),u.end?.(ue,A),ar(A.limits??await u.limits?.(A).catch(()=>{}));let D=ie===0&&!A.failed;if(o&&!D&&!A.usage&&!A.progress&&!this.cancelled.has(t.taskId))return te=!0,clearTimeout(sr),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()),f(),Z(!1)):Z(!0);A.sessionId&&Ef.has(t.cli)&&await this.opts.sessions.set(t.threadId,t.cli,{id:A.sessionId,task:t.taskId}).catch(()=>{});let F=A.result??(D?ue.trim():AP(u.bin,ie,k,A.error??(tt.trim()||ue.trim())));fe(D,F||"(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 function ls(e,t){let r=await Gb(t).catch(()=>null);if(!r)return null;for(let o of e.folders)if(await Gb(o.path).catch(()=>null)===r)return r;return null}var Yb=e=>(e.stderr||e.message||String(e)).trim().split(`
112
- `).at(-1);function AP(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}`}.
113
- ${o}`}async function t$(e,t){let r=await EP(e,t.folders,t.threadId);if(!r.length)throw new Error("None of this project's folders is shared on this computer.");let o=RP(t.path),n=NP(o)?[o]:r.map(i=>CP(i,o));for(let i of n){let a=await e$(i).catch(()=>null);if(!a||!r.some(p=>n$(a,p)))continue;let s=await OP(a);if(!s.isFile())continue;let u=Math.min(s.size,ff),l=Buffer.alloc(u),d=await TP(a,"r");try{await d.read(l,0,u,0)}finally{await d.close()}return{path:a,size:s.size,data:l.toString("base64"),truncated:s.size>u}}throw new Error(`${t.path} is not a file in this project's folders.`)}async function EP(e,t,r){let o=(await Promise.all(t.map(a=>ls(e,a)))).filter(a=>a!==null),n=r?(await tn()).filter(a=>a.threadId===r):[],i=[];for(let a of o)for(let s of n){if(!n$(a,s.repo))continue;let u=await e$(DP(s.path,UP(s.repo,a))).catch(()=>null);u&&i.push(u)}return[...i,...o]}function RP(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 n$(e,t){return e===t||e.startsWith(t.endsWith(Qb)?t:t+Qb)}import{readdir as MP,realpath as Rf,stat as r$}from"node:fs/promises";import{homedir as i$}from"node:os";import{dirname as LP,isAbsolute as ZP,join as FP,parse as VP}from"node:path";var JP=1e3;async function o$(e){let t=i$(),r=await Rf(e?s$(e):t),n=(await MP(r,{withFileTypes:!0})).filter(u=>(u.isDirectory()||u.isSymbolicLink())&&!u.name.startsWith(".")).map(u=>({name:u.name,path:FP(r,u.name)})),a=(await Promise.all(n.map(async u=>(await r$(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 s=LP(r);return{path:r,parent:s===r?null:s,home:t,dirs:a.slice(0,JP)}}async function a$(e){let t=await Rf(s$(e)).catch(()=>{throw new Error(`${e} does not exist on this computer.`)});if(!(await r$(t)).isDirectory())throw new Error(`${e} is not a folder.`);if(t===VP(t).root||t===await Rf(i$()))throw new Error("Pick a project folder, not your whole home folder or disk.");return t}function s$(e){if(!ZP(e))throw new Error(`${e} is not a full path.`);return e}import{readFileSync as KP,rmSync as BP,writeFileSync as WP,mkdirSync as GP}from"node:fs";import{join as c$}from"node:path";var qP=3600*1e3,Mf=()=>c$(ee(),"interrupted.json"),u$=()=>c$(ee(),"running.json");function l$(e,t=Date.now()){if(!e.length)return;let r=[...p$(t),...e.map(o=>({taskId:o,at:t}))];m$(Mf(),r)}function d$(e=Date.now()){let t=[...new Set(p$(e).map(r=>r.taskId))];return BP(Mf(),{force:!0}),t}function p$(e){let t=f$(Mf());return Array.isArray(t)?t.filter(r=>typeof r?.taskId=="string"&&e-r.at<qP):[]}function Lf(e){try{m$(u$(),{pid:process.pid,running:e})}catch{}}function Zf(){let e=f$(u$());return!e?.pid||!Array.isArray(e.running)||!HP(e.pid)?[]:e.running}function HP(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function f$(e){try{return JSON.parse(KP(e,"utf8"))}catch{return}}function m$(e,t){GP(ee(),{recursive:!0,mode:448}),WP(e,`${JSON.stringify(t)}
114
- `,{mode:384})}import{spawn as XP}from"node:child_process";import{createHash as YP,randomBytes as QP}from"node:crypto";import{access as Jf,chmod as ej,mkdir as ds,readdir as tj,readFile as Kf,rm as g$,writeFile as v$}from"node:fs/promises";import{homedir as y$}from"node:os";import{dirname as nj,join as ft,relative as rj,resolve as h$}from"node:path";var rn=()=>ft(ee(),"ssh"),vi=()=>ft(rn(),"keys.json"),Ff=()=>ft(rn(),"known_hosts"),ij=()=>ft(rn(),"askpass.sh"),rr="myrel-runner-ssh",oj=3e4,Bf=e=>ft(rn(),e.projectId,e.alias),nn=e=>`${e.projectId}/${e.alias}`,b$=e=>`myrel.${e.projectId}.${e.alias}`;function ps(e){let t=e.trim().split(/\s+/)[1]??"";return`SHA256:${YP("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}function Qe(e,t,r={}){let o=r.max??xy;return new Promise((n,i)=>{let a=XP(e,t,{env:r.env??Vf(),stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],windowsHide:!0}),s="",u="",l=!1,d=!1,p=(f,g)=>f.length+g.length<=o?f+g:(l=!0,f+g.slice(0,Math.max(0,o-f.length)));a.stdout.setEncoding("utf8").on("data",f=>s=p(s,f)),a.stderr.setEncoding("utf8").on("data",f=>u=p(u,f));let m=r.timeoutMs?setTimeout(()=>{d=!0,a.kill("SIGKILL")},r.timeoutMs):void 0;a.once("error",f=>{clearTimeout(m),i(f)}),a.once("close",f=>{clearTimeout(m),n({code:f,stdout:s,stderr:u,truncated:l,timedOut:d})}),r.input!==void 0&&a.stdin.end(r.input)})}function Vf(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 Wf(e=process.platform){return e==="darwin"?{async set(t,r){let o=await Qe("security",["-i"],{input:`add-generic-password -U -a "${t}" -s "${rr}" -w "${r}"
115
- `,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 Qe("security",["find-generic-password","-a",t,"-s",rr,"-w"],{timeoutMs:15e3});return r.code===0?r.stdout.replace(/\n$/,""):null},async remove(t){await Qe("security",["delete-generic-password","-a",t,"-s",rr],{timeoutMs:15e3}).catch(()=>{})}}:e==="linux"?{async set(t,r){let o=await Qe("secret-tool",["store",`--label=Myrel SSH key ${t}`,"service",rr,"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 Qe("secret-tool",["lookup","service",rr,"account",t],{timeoutMs:15e3});return r.code===0&&r.stdout?r.stdout.replace(/\n$/,""):null},async remove(t){await Qe("secret-tool",["clear","service",rr,"account",t],{timeoutMs:15e3}).catch(()=>{})}}:null}async function aj(e,t,r){if(!e)return!1;try{return await e.set(t,r),await e.get(t)===r}catch{return!1}}async function $$(e,t,r,o=Wf()){if(await ds(rn(),{recursive:!0,mode:448}),await Gf(e,o),r){let l=await sj(r),d=await Qe("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 he(vi())??{};p[nn(e)]=l,await Je(vi(),p);let m=d.stdout.trim();return{publicKey:m,fingerprint:ps(m),protected:!1}}let n=Bf(e);await ds(nj(n),{recursive:!0,mode:448});let i=QP(24).toString("base64url"),a=await aj(o,nn(e),i),s=await Qe("ssh-keygen",["-q","-t","ed25519","-N",a?i:"","-C",t,"-f",n],{timeoutMs:3e4});if(s.code!==0)throw new Error(`ssh-keygen failed: ${s.stderr.trim()||`exit ${s.code}`}. Is OpenSSH installed on this computer?`);await ej(n,384).catch(()=>{});let u=(await Kf(`${n}.pub`,"utf8")).trim();return{publicKey:u,fingerprint:ps(u),protected:a}}async function sj(e,t=y$()){let r=ft(t,".ssh"),o=h$(r,e),n=rj(r,o);if(!n||n.startsWith("..")||h$(r,n)!==o)throw new Error("Only keys in ~/.ssh can be used.");return await Jf(o),o}async function _$(e=y$()){let t=ft(e,".ssh"),r=await tj(t).catch(()=>[]),o=[];for(let n of r.filter(i=>i.endsWith(".pub")).sort()){let i=ft(t,n.slice(0,-4));if(!await Jf(i).then(()=>!0,()=>!1))continue;let a=(await Kf(ft(t,n),"utf8").catch(()=>"")).trim(),[s,u,...l]=a.split(/\s+/);!s||!u||o.push({path:i,name:n.slice(0,-4),type:s,fingerprint:ps(a),comment:l.join(" ").slice(0,500)})}return o.slice(0,100)}async function Gf(e,t=Wf()){let r=Bf(e);await g$(r,{force:!0}),await g$(`${r}.pub`,{force:!0}),await t?.remove(nn(e));let o=await he(vi());o&&nn(e)in o&&(delete o[nn(e)],await Je(vi(),o)),await k$(e,null)}async function cj(e,t){let r=(await he(vi()))?.[nn(e)];if(r)return{path:r,passphrase:null};let o=Bf(e);return await Jf(o).then(()=>!0,()=>!1)?{path:o,passphrase:await t?.get(nn(e)).catch(()=>null)??null}:null}async function x$(e,t){let r=await Qe("ssh-keyscan",["-T","10","-p",String(t),"-t","ed25519,ecdsa,rsa","--",e],{timeoutMs:3e4}),o=lj(r.stdout);if(!o.length)throw new Error(`${e}:${t} did not answer with a server key${r.stderr.trim()?` (${r.stderr.trim().split(`
116
- `).pop()})`:""}.`);return o}var uj=["ssh-ed25519","ecdsa-sha2-nistp256","ecdsa-sha2-nistp384","ecdsa-sha2-nistp521","rsa-sha2-512","ssh-rsa"];function lj(e){let t=[];for(let o of e.split(`
117
- `)){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(s=>s.key===a)||t.push({type:n,key:a,fingerprint:ps(a)})}let r=o=>uj.indexOf(o)+1||99;return t.sort((o,n)=>r(o.type)-r(n.type)).slice(0,10)}async function k$(e,t,r=!0){let o=b$(e),n=(await Kf(Ff(),"utf8").catch(()=>"")).split(`
110
+ ${y}`:g,I=u.input?u.input(x,i.access):x,S=u.promptFile?await Wb(Cf(Hb(),"myrel-prompt-")):void 0,T=S?Cf(S,"prompt.md"):void 0;T&&await jP(T,I,{mode:384});let P=[...r.appServer?[]:bb(u,t.model),...l.args],C=r.appServer?["app-server",...l.args]:u.args({access:i.access,resume:o,extra:P,dirs:d,asks:r.asks,promptFile:T,stream:r.stream}),j=(this.opts.spawn??PP)(u.bin,C,{cwd:s,env:He(r.env),stdio:["pipe","pipe","pipe"],shell:process.platform==="win32"});if(S){let Z=()=>{qb(S,{recursive:!0,force:!0}).catch(()=>{})};j.once("close",Z),j.once("error",Z)}this.running.set(t.taskId,j),this.opts.onChange?.(this.runningIds());let A={},ue="",tt="",Me="",nt=0,sn,mt="",wi,or,ar=Z=>{!Z||Z===wi||(wi=Z,this.opts.onLimits?.(t.cli,Z))},cn=()=>A.usage?{...A.usage,...A.model&&{model:A.model.slice(0,200)}}:void 0,Si=()=>{for(let ie of A.agentNotes?.splice(0)??[])this.send({type:"task.progress",taskId:t.taskId,text:ie.text,agent:ie.agent,...ie.ms!==void 0&&{ms:ie.ms}});let Z=cn(),te=Z?JSON.stringify(Z):"",fe=!!A.progress&&A.progress!==sn;if(fe||te!==mt){sn=A.progress,mt=te,nt=Date.now();let ie=fe&&A.progressAgent;this.send({type:"task.progress",taskId:t.taskId,text:fe?A.progress:"",...Z&&{usage:Z},...ie&&{agent:ie}})}};if(j.stdout.setEncoding("utf8"),j.stdout.on("data",Z=>{ue.length<4*Xb&&(ue+=Z),Me+=Z;let te=Me.split(`
111
+ `);Me=te.pop();for(let ie of te)u.line(ie.trim(),A);ar(A.limits),A.sessionId&&A.sessionId!==or&&Ef.has(t.cli)&&(or=A.sessionId,this.opts.sessions.set(t.threadId,t.cli,{id:A.sessionId,task:t.taskId}).catch(()=>{}));let fe=cn();(Date.now()-nt>=AP||fe&&JSON.stringify(fe)!==mt||A.agentNotes?.length)&&Si()}),j.stderr.setEncoding("utf8"),j.stderr.on("data",Z=>{tt.length<2e4&&(tt+=Z)}),j.stdin.on("error",()=>{}),u.acp){let Z={write:fe=>{j.stdin.write(fe)},end:()=>j.stdin.end()},te={cwd:s,prompt:I,mcpServers:l.mcpServers??[],resume:o,dirs:d,...u.acp(i.access,Ya(t.model))};A.acp=new ts(Z,te,A),A.acp.start()}else if(r.appServer){let Z={write:fe=>{j.stdin.write(fe)},end:()=>j.stdin.end()},te={cwd:s,prompt:I,resume:o,model:Ya(t.model),clientVersion:this.opts.version??"0",...r.appServer};A.appServer=new rs(Z,te,A),this.turns.set(t.taskId,A.appServer),A.appServer.start()}else if(r.stream){let Z={write:te=>{j.stdin.write(te)},end:()=>j.stdin.end()};A.claudeStream=new is(Z,I),this.turns.set(t.taskId,A.claudeStream),A.claudeStream.start()}else j.stdin.end(T?"":I);let sr=setTimeout(()=>j.kill("SIGTERM"),this.opts.timeoutMs??3600*1e3);return await new Promise(Z=>{let te=!1,fe=(ie,k)=>{if(te)return;if(te=!0,clearTimeout(sr),f(),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`),Z(!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."}),Z(!1);a(`${ie?"\u2713":"\u2717"} ${u.id} task finished`);let D=cn();this.send({type:"task.done",taskId:t.taskId,ok:ie,result:k.slice(0,Xb-m.length)+m,...D&&{usage:D}}),Z(!1)};j.on("error",ie=>{fe(!1,ie.code==="ENOENT"?`${u.bin} is not installed on this computer, or not on PATH for myrel-runner.`:`Could not start ${u.bin}: ${ie.message}`)}),j.on("exit",()=>{(this.cancelled.has(t.taskId)||this.interrupted.has(t.taskId))&&fe(!1,"")}),j.on("close",async(ie,k)=>{Me.trim()&&u.line(Me.trim(),A),u.end?.(ue,A),ar(A.limits??await u.limits?.(A).catch(()=>{}));let D=ie===0&&!A.failed;if(o&&!D&&!A.usage&&!A.progress&&!this.cancelled.has(t.taskId))return te=!0,clearTimeout(sr),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()),f(),Z(!1)):Z(!0);A.sessionId&&Ef.has(t.cli)&&await this.opts.sessions.set(t.threadId,t.cli,{id:A.sessionId,task:t.taskId}).catch(()=>{});let F=A.result??(D?ue.trim():TP(u.bin,ie,k,A.error??(tt.trim()||ue.trim())));fe(D,F||"(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 function ls(e,t){let r=await Gb(t).catch(()=>null);if(!r)return null;for(let o of e.folders)if(await Gb(o.path).catch(()=>null)===r)return r;return null}var Yb=e=>(e.stderr||e.message||String(e)).trim().split(`
112
+ `).at(-1);function TP(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}`}.
113
+ ${o}`}async function t$(e,t){let r=await RP(e,t.folders,t.threadId);if(!r.length)throw new Error("None of this project's folders is shared on this computer.");let o=MP(t.path),n=DP(o)?[o]:r.map(i=>EP(i,o));for(let i of n){let a=await e$(i).catch(()=>null);if(!a||!r.some(p=>n$(a,p)))continue;let s=await NP(a);if(!s.isFile())continue;let u=Math.min(s.size,ff),l=Buffer.alloc(u),d=await OP(a,"r");try{await d.read(l,0,u,0)}finally{await d.close()}return{path:a,size:s.size,data:l.toString("base64"),truncated:s.size>u}}throw new Error(`${t.path} is not a file in this project's folders.`)}async function RP(e,t,r){let o=(await Promise.all(t.map(a=>ls(e,a)))).filter(a=>a!==null),n=r?(await tn()).filter(a=>a.threadId===r):[],i=[];for(let a of o)for(let s of n){if(!n$(a,s.repo))continue;let u=await e$(UP(s.path,CP(s.repo,a))).catch(()=>null);u&&i.push(u)}return[...i,...o]}function MP(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 n$(e,t){return e===t||e.startsWith(t.endsWith(Qb)?t:t+Qb)}import{readdir as LP,realpath as Rf,stat as r$}from"node:fs/promises";import{homedir as i$}from"node:os";import{dirname as ZP,isAbsolute as FP,join as VP,parse as JP}from"node:path";var KP=1e3;async function o$(e){let t=i$(),r=await Rf(e?s$(e):t),n=(await LP(r,{withFileTypes:!0})).filter(u=>(u.isDirectory()||u.isSymbolicLink())&&!u.name.startsWith(".")).map(u=>({name:u.name,path:VP(r,u.name)})),a=(await Promise.all(n.map(async u=>(await r$(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 s=ZP(r);return{path:r,parent:s===r?null:s,home:t,dirs:a.slice(0,KP)}}async function a$(e){let t=await Rf(s$(e)).catch(()=>{throw new Error(`${e} does not exist on this computer.`)});if(!(await r$(t)).isDirectory())throw new Error(`${e} is not a folder.`);if(t===JP(t).root||t===await Rf(i$()))throw new Error("Pick a project folder, not your whole home folder or disk.");return t}function s$(e){if(!FP(e))throw new Error(`${e} is not a full path.`);return e}import{readFileSync as BP,rmSync as WP,writeFileSync as GP,mkdirSync as qP}from"node:fs";import{join as c$}from"node:path";var HP=3600*1e3,Mf=()=>c$(ee(),"interrupted.json"),u$=()=>c$(ee(),"running.json");function l$(e,t=Date.now()){if(!e.length)return;let r=[...p$(t),...e.map(o=>({taskId:o,at:t}))];m$(Mf(),r)}function d$(e=Date.now()){let t=[...new Set(p$(e).map(r=>r.taskId))];return WP(Mf(),{force:!0}),t}function p$(e){let t=f$(Mf());return Array.isArray(t)?t.filter(r=>typeof r?.taskId=="string"&&e-r.at<HP):[]}function Lf(e){try{m$(u$(),{pid:process.pid,running:e})}catch{}}function Zf(){let e=f$(u$());return!e?.pid||!Array.isArray(e.running)||!XP(e.pid)?[]:e.running}function XP(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function f$(e){try{return JSON.parse(BP(e,"utf8"))}catch{return}}function m$(e,t){qP(ee(),{recursive:!0,mode:448}),GP(e,`${JSON.stringify(t)}
114
+ `,{mode:384})}import{spawn as YP}from"node:child_process";import{createHash as QP,randomBytes as ej}from"node:crypto";import{access as Jf,chmod as tj,mkdir as ds,readdir as nj,readFile as Kf,rm as g$,writeFile as v$}from"node:fs/promises";import{homedir as y$}from"node:os";import{dirname as rj,join as ft,relative as ij,resolve as h$}from"node:path";var rn=()=>ft(ee(),"ssh"),vi=()=>ft(rn(),"keys.json"),Ff=()=>ft(rn(),"known_hosts"),oj=()=>ft(rn(),"askpass.sh"),rr="myrel-runner-ssh",aj=3e4,Bf=e=>ft(rn(),e.projectId,e.alias),nn=e=>`${e.projectId}/${e.alias}`,b$=e=>`myrel.${e.projectId}.${e.alias}`;function ps(e){let t=e.trim().split(/\s+/)[1]??"";return`SHA256:${QP("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}function Qe(e,t,r={}){let o=r.max??xy;return new Promise((n,i)=>{let a=YP(e,t,{env:r.env??Vf(),stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],windowsHide:!0}),s="",u="",l=!1,d=!1,p=(f,g)=>f.length+g.length<=o?f+g:(l=!0,f+g.slice(0,Math.max(0,o-f.length)));a.stdout.setEncoding("utf8").on("data",f=>s=p(s,f)),a.stderr.setEncoding("utf8").on("data",f=>u=p(u,f));let m=r.timeoutMs?setTimeout(()=>{d=!0,a.kill("SIGKILL")},r.timeoutMs):void 0;a.once("error",f=>{clearTimeout(m),i(f)}),a.once("close",f=>{clearTimeout(m),n({code:f,stdout:s,stderr:u,truncated:l,timedOut:d})}),r.input!==void 0&&a.stdin.end(r.input)})}function Vf(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 Wf(e=process.platform){return e==="darwin"?{async set(t,r){let o=await Qe("security",["-i"],{input:`add-generic-password -U -a "${t}" -s "${rr}" -w "${r}"
115
+ `,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 Qe("security",["find-generic-password","-a",t,"-s",rr,"-w"],{timeoutMs:15e3});return r.code===0?r.stdout.replace(/\n$/,""):null},async remove(t){await Qe("security",["delete-generic-password","-a",t,"-s",rr],{timeoutMs:15e3}).catch(()=>{})}}:e==="linux"?{async set(t,r){let o=await Qe("secret-tool",["store",`--label=Myrel SSH key ${t}`,"service",rr,"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 Qe("secret-tool",["lookup","service",rr,"account",t],{timeoutMs:15e3});return r.code===0&&r.stdout?r.stdout.replace(/\n$/,""):null},async remove(t){await Qe("secret-tool",["clear","service",rr,"account",t],{timeoutMs:15e3}).catch(()=>{})}}:null}async function sj(e,t,r){if(!e)return!1;try{return await e.set(t,r),await e.get(t)===r}catch{return!1}}async function $$(e,t,r,o=Wf()){if(await ds(rn(),{recursive:!0,mode:448}),await Gf(e,o),r){let l=await cj(r),d=await Qe("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 he(vi())??{};p[nn(e)]=l,await Je(vi(),p);let m=d.stdout.trim();return{publicKey:m,fingerprint:ps(m),protected:!1}}let n=Bf(e);await ds(rj(n),{recursive:!0,mode:448});let i=ej(24).toString("base64url"),a=await sj(o,nn(e),i),s=await Qe("ssh-keygen",["-q","-t","ed25519","-N",a?i:"","-C",t,"-f",n],{timeoutMs:3e4});if(s.code!==0)throw new Error(`ssh-keygen failed: ${s.stderr.trim()||`exit ${s.code}`}. Is OpenSSH installed on this computer?`);await tj(n,384).catch(()=>{});let u=(await Kf(`${n}.pub`,"utf8")).trim();return{publicKey:u,fingerprint:ps(u),protected:a}}async function cj(e,t=y$()){let r=ft(t,".ssh"),o=h$(r,e),n=ij(r,o);if(!n||n.startsWith("..")||h$(r,n)!==o)throw new Error("Only keys in ~/.ssh can be used.");return await Jf(o),o}async function _$(e=y$()){let t=ft(e,".ssh"),r=await nj(t).catch(()=>[]),o=[];for(let n of r.filter(i=>i.endsWith(".pub")).sort()){let i=ft(t,n.slice(0,-4));if(!await Jf(i).then(()=>!0,()=>!1))continue;let a=(await Kf(ft(t,n),"utf8").catch(()=>"")).trim(),[s,u,...l]=a.split(/\s+/);!s||!u||o.push({path:i,name:n.slice(0,-4),type:s,fingerprint:ps(a),comment:l.join(" ").slice(0,500)})}return o.slice(0,100)}async function Gf(e,t=Wf()){let r=Bf(e);await g$(r,{force:!0}),await g$(`${r}.pub`,{force:!0}),await t?.remove(nn(e));let o=await he(vi());o&&nn(e)in o&&(delete o[nn(e)],await Je(vi(),o)),await k$(e,null)}async function uj(e,t){let r=(await he(vi()))?.[nn(e)];if(r)return{path:r,passphrase:null};let o=Bf(e);return await Jf(o).then(()=>!0,()=>!1)?{path:o,passphrase:await t?.get(nn(e)).catch(()=>null)??null}:null}async function x$(e,t){let r=await Qe("ssh-keyscan",["-T","10","-p",String(t),"-t","ed25519,ecdsa,rsa","--",e],{timeoutMs:3e4}),o=dj(r.stdout);if(!o.length)throw new Error(`${e}:${t} did not answer with a server key${r.stderr.trim()?` (${r.stderr.trim().split(`
116
+ `).pop()})`:""}.`);return o}var lj=["ssh-ed25519","ecdsa-sha2-nistp256","ecdsa-sha2-nistp384","ecdsa-sha2-nistp521","rsa-sha2-512","ssh-rsa"];function dj(e){let t=[];for(let o of e.split(`
117
+ `)){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(s=>s.key===a)||t.push({type:n,key:a,fingerprint:ps(a)})}let r=o=>lj.indexOf(o)+1||99;return t.sort((o,n)=>r(o.type)-r(n.type)).slice(0,10)}async function k$(e,t,r=!0){let o=b$(e),n=(await Kf(Ff(),"utf8").catch(()=>"")).split(`
118
118
  `).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 fs}let s=[...n.filter(u=>!u.startsWith(`${o} `)),...a?[a]:[]];!a&&!i.length||(await ds(rn(),{recursive:!0,mode:448}),await v$(Ff(),s.length?`${s.join(`
119
119
  `)}
120
- `:"",{mode:384}))}var fs=class extends Error{constructor(){super("The server's key is not the one confirmed in Myrel.")}};function dj(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=${Ff()}`),...o(`GlobalKnownHostsFile=${process.platform==="win32"?"NUL":"/dev/null"}`),...o(`HostKeyAlias=${b$(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 qf(e,t,r={}){let o=Date.now(),n=(p,m)=>({exitCode:null,stdout:"",stderr:m,truncated:!1,ms:Date.now()-o,error:p}),i=r.keychain===void 0?Wf():r.keychain,a=await cj(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 k$(e,e.hostKey,!!r.trust)}catch(p){if(p instanceof fs)return n("hostkey",p.message);throw p}let s=r.timeoutMs??_y,u=a.passphrase?Vf({SSH_ASKPASS:await fj(),SSH_ASKPASS_REQUIRE:"force",DISPLAY:process.env.DISPLAY||":0",MYREL_SSH_PASSPHRASE:a.passphrase}):Vf(),l=await Qe("ssh",[...dj(e,a.path,{passphrase:!!a.passphrase,timeoutSec:15}),t],{env:u,timeoutMs:s}),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:pj(l.stderr)}}}var w$=(e,t)=>qf(e,"true",{trust:!0,keychain:t,timeoutMs:oj});function pj(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 fj(){let e=ij();return await ds(rn(),{recursive:!0,mode:448}),await v$(e,`#!/bin/sh
120
+ `:"",{mode:384}))}var fs=class extends Error{constructor(){super("The server's key is not the one confirmed in Myrel.")}};function pj(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=${Ff()}`),...o(`GlobalKnownHostsFile=${process.platform==="win32"?"NUL":"/dev/null"}`),...o(`HostKeyAlias=${b$(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 qf(e,t,r={}){let o=Date.now(),n=(p,m)=>({exitCode:null,stdout:"",stderr:m,truncated:!1,ms:Date.now()-o,error:p}),i=r.keychain===void 0?Wf():r.keychain,a=await uj(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 k$(e,e.hostKey,!!r.trust)}catch(p){if(p instanceof fs)return n("hostkey",p.message);throw p}let s=r.timeoutMs??_y,u=a.passphrase?Vf({SSH_ASKPASS:await mj(),SSH_ASKPASS_REQUIRE:"force",DISPLAY:process.env.DISPLAY||":0",MYREL_SSH_PASSPHRASE:a.passphrase}):Vf(),l=await Qe("ssh",[...pj(e,a.path,{passphrase:!!a.passphrase,timeoutSec:15}),t],{env:u,timeoutMs:s}),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:fj(l.stderr)}}}var w$=(e,t)=>qf(e,"true",{trust:!0,keychain:t,timeoutMs:aj});function fj(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 mj(){let e=oj();return await ds(rn(),{recursive:!0,mode:448}),await v$(e,`#!/bin/sh
121
121
  printf "%s\\n" "$MYREL_SSH_PASSPHRASE"
122
- `,{mode:448}),e}import{execFile as Pj}from"node:child_process";import{createHash as jj}from"node:crypto";import{copyFile as U$,rename as Aj,rm as C$,stat as E$,writeFile as Tj}from"node:fs/promises";import{join as tm,resolve as Oj}from"node:path";import{promisify as Nj}from"node:util";import{gunzipSync as Dj}from"node:zlib";import{execFile as mj,spawn as z$}from"node:child_process";import{copyFile as gj,mkdir as Hf,readFile as hj,rm as P$,stat as vj,writeFile as ms}from"node:fs/promises";import{homedir as ir,platform as j$}from"node:os";import{delimiter as S$,join as et}from"node:path";import{promisify as yj}from"node:util";var De=yj(mj),on="io.fibteq.myrel-runner",an="myrel-runner.service";async function Yf(e){let t=gs(),r=bi();await Hf(et(ee(),"bin"),{recursive:!0,mode:448}),e!==r&&await gj(e,r);let o=[process.execPath,r,"start"],n=$j(),i=await hs(t);if(t==="launchd")await Hf(et(ir(),"Library","LaunchAgents"),{recursive:!0}),await ms(i.file,_j(o,n,i.log)),await bj(i.file);else if(t==="systemd"){await Hf(et(ir(),".config","systemd","user"),{recursive:!0}),await ms(i.file,xj(o,n));try{await De("systemctl",["--user","daemon-reload"]),await De("systemctl",["--user","enable",an]),await De("systemctl",["--user","restart",an])}catch(a){throw await P$(i.file,{force:!0}),new Error(`Could not register with systemd (${a.message.split(`
123
- `).filter(Boolean).at(-1)}). Use \`myrel-runner start\` instead.`)}}else await ms(i.file,wj(o,i.log)),z$("wscript.exe",[i.file],{detached:!0,stdio:"ignore"}).unref();return $i()}var bi=()=>et(ee(),"bin","myrel-runner.mjs");async function A$(){if(gs()!=="startup")return;let e=await hs("startup");e.installed&&z$("wscript.exe",[e.file],{detached:!0,stdio:"ignore"}).unref()}async function bj(e){let t=`gui/${process.getuid?.()}`,r=()=>De("launchctl",["print",`${t}/${on}`]).then(()=>!0,()=>!1);await De("launchctl",["bootout",`${t}/${on}`]).catch(()=>{});for(let o=0;o<50&&await r();o++)await Xf(100);for(let o=1;;o++)try{await De("launchctl",["bootstrap",t,e]);break}catch(n){if(o>=5)throw n;await Xf(500*o)}for(let o=0;o<30;o++){if((await De("launchctl",["print",`${t}/${on}`]).catch(()=>null))?.stdout.includes("state = running"))return;await Xf(100)}}var Xf=e=>new Promise(t=>setTimeout(t,e));async function T$(){let e=gs(),t=await hs(e);return e==="launchd"?await De("launchctl",["bootout",`gui/${process.getuid?.()}/${on}`]).catch(()=>{}):e==="systemd"&&await De("systemctl",["--user","disable","--now",an]).catch(()=>{}),await P$(t.file,{force:!0}),e==="systemd"&&await De("systemctl",["--user","daemon-reload"]).catch(()=>{}),$i()}async function $i(){let e=await hs(gs());if(!e.installed)return{...e,running:!1};if(e.manager==="launchd"){let t=await De("launchctl",["print",`gui/${process.getuid?.()}/${on}`]).catch(()=>null);return{...e,running:!!t?.stdout.includes("state = running")}}if(e.manager==="systemd"){let t=await De("systemctl",["--user","is-active",an]).catch(()=>null);return{...e,running:t?.stdout.trim()==="active"}}return{...e,running:null}}function gs(){let e=j$();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 hs(e){let t=e==="launchd"?et(ir(),"Library","LaunchAgents",`${on}.plist`):e==="systemd"?et(ir(),".config","systemd","user",an):et(process.env.APPDATA??et(ir(),"AppData","Roaming"),"Microsoft","Windows","Start Menu","Programs","Startup","myrel-runner.vbs"),r=e==="systemd"?`journalctl --user -u ${an}`:et(ee(),"runner.log"),o=!!await vj(t).catch(()=>null);return{manager:e,file:t,installed:o,log:r}}function $j(){let t={PATH:(process.env.PATH??"").split(S$).filter(r=>r&&!/[\\/]_npx[\\/]/.test(r)).join(S$)};return process.env.MYREL_RUNNER_HOME&&(t.MYREL_RUNNER_HOME=process.env.MYREL_RUNNER_HOME),t}var yi=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function _j(e,t,r){return`<?xml version="1.0" encoding="UTF-8"?>
122
+ `,{mode:448}),e}import{execFile as jj}from"node:child_process";import{createHash as Aj}from"node:crypto";import{copyFile as U$,rename as Tj,rm as C$,stat as E$,writeFile as Oj}from"node:fs/promises";import{join as tm,resolve as Nj}from"node:path";import{promisify as Dj}from"node:util";import{gunzipSync as Uj}from"node:zlib";import{execFile as gj,spawn as z$}from"node:child_process";import{copyFile as hj,mkdir as Hf,readFile as vj,rm as P$,stat as yj,writeFile as ms}from"node:fs/promises";import{homedir as ir,platform as j$}from"node:os";import{delimiter as S$,join as et}from"node:path";import{promisify as bj}from"node:util";var De=bj(gj),on="io.fibteq.myrel-runner",an="myrel-runner.service";async function Yf(e){let t=gs(),r=bi();await Hf(et(ee(),"bin"),{recursive:!0,mode:448}),e!==r&&await hj(e,r);let o=[process.execPath,r,"start"],n=_j(),i=await hs(t);if(t==="launchd")await Hf(et(ir(),"Library","LaunchAgents"),{recursive:!0}),await ms(i.file,xj(o,n,i.log)),await $j(i.file);else if(t==="systemd"){await Hf(et(ir(),".config","systemd","user"),{recursive:!0}),await ms(i.file,kj(o,n));try{await De("systemctl",["--user","daemon-reload"]),await De("systemctl",["--user","enable",an]),await De("systemctl",["--user","restart",an])}catch(a){throw await P$(i.file,{force:!0}),new Error(`Could not register with systemd (${a.message.split(`
123
+ `).filter(Boolean).at(-1)}). Use \`myrel-runner start\` instead.`)}}else await ms(i.file,Sj(o,i.log)),z$("wscript.exe",[i.file],{detached:!0,stdio:"ignore"}).unref();return $i()}var bi=()=>et(ee(),"bin","myrel-runner.mjs");async function A$(){if(gs()!=="startup")return;let e=await hs("startup");e.installed&&z$("wscript.exe",[e.file],{detached:!0,stdio:"ignore"}).unref()}async function $j(e){let t=`gui/${process.getuid?.()}`,r=()=>De("launchctl",["print",`${t}/${on}`]).then(()=>!0,()=>!1);await De("launchctl",["bootout",`${t}/${on}`]).catch(()=>{});for(let o=0;o<50&&await r();o++)await Xf(100);for(let o=1;;o++)try{await De("launchctl",["bootstrap",t,e]);break}catch(n){if(o>=5)throw n;await Xf(500*o)}for(let o=0;o<30;o++){if((await De("launchctl",["print",`${t}/${on}`]).catch(()=>null))?.stdout.includes("state = running"))return;await Xf(100)}}var Xf=e=>new Promise(t=>setTimeout(t,e));async function T$(){let e=gs(),t=await hs(e);return e==="launchd"?await De("launchctl",["bootout",`gui/${process.getuid?.()}/${on}`]).catch(()=>{}):e==="systemd"&&await De("systemctl",["--user","disable","--now",an]).catch(()=>{}),await P$(t.file,{force:!0}),e==="systemd"&&await De("systemctl",["--user","daemon-reload"]).catch(()=>{}),$i()}async function $i(){let e=await hs(gs());if(!e.installed)return{...e,running:!1};if(e.manager==="launchd"){let t=await De("launchctl",["print",`gui/${process.getuid?.()}/${on}`]).catch(()=>null);return{...e,running:!!t?.stdout.includes("state = running")}}if(e.manager==="systemd"){let t=await De("systemctl",["--user","is-active",an]).catch(()=>null);return{...e,running:t?.stdout.trim()==="active"}}return{...e,running:null}}function gs(){let e=j$();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 hs(e){let t=e==="launchd"?et(ir(),"Library","LaunchAgents",`${on}.plist`):e==="systemd"?et(ir(),".config","systemd","user",an):et(process.env.APPDATA??et(ir(),"AppData","Roaming"),"Microsoft","Windows","Start Menu","Programs","Startup","myrel-runner.vbs"),r=e==="systemd"?`journalctl --user -u ${an}`:et(ee(),"runner.log"),o=!!await yj(t).catch(()=>null);return{manager:e,file:t,installed:o,log:r}}function _j(){let t={PATH:(process.env.PATH??"").split(S$).filter(r=>r&&!/[\\/]_npx[\\/]/.test(r)).join(S$)};return process.env.MYREL_RUNNER_HOME&&(t.MYREL_RUNNER_HOME=process.env.MYREL_RUNNER_HOME),t}var yi=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function xj(e,t,r){return`<?xml version="1.0" encoding="UTF-8"?>
124
124
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
125
125
  <plist version="1.0">
126
126
  <dict>
@@ -143,7 +143,7 @@ ${Object.entries(t).map(([o,n])=>` <key>${yi(o)}</key><string>${yi(n)}</strin
143
143
  <key>StandardErrorPath</key><string>${yi(r)}</string>
144
144
  </dict>
145
145
  </plist>
146
- `}var I$=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`;function xj(e,t){return`[Unit]
146
+ `}var I$=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`;function kj(e,t){return`[Unit]
147
147
  Description=Myrel runner (connects this computer to Myrel)
148
148
  After=network-online.target
149
149
 
@@ -157,12 +157,12 @@ ${O$}
157
157
 
158
158
  [Install]
159
159
  WantedBy=default.target
160
- `}var O$="OOMPolicy=continue";function kj(e){return/^OOMPolicy=/m.test(e)||!/^RestartSec=.*$/m.test(e)?null:e.replace(/^RestartSec=.*$/m,t=>`${t}
161
- ${O$}`)}async function N$(){if(j$()!=="linux")return;let e=et(ir(),".config","systemd","user",an),t=kj(await hj(e,"utf8").catch(()=>""));t&&(await ms(e,t),await De("systemctl",["--user","daemon-reload"]))}function wj(e,t){return`' Starts myrel-runner at login. Remove with: myrel-runner service uninstall\r
160
+ `}var O$="OOMPolicy=continue";function wj(e){return/^OOMPolicy=/m.test(e)||!/^RestartSec=.*$/m.test(e)?null:e.replace(/^RestartSec=.*$/m,t=>`${t}
161
+ ${O$}`)}async function N$(){if(j$()!=="linux")return;let e=et(ir(),".config","systemd","user",an),t=wj(await vj(e,"utf8").catch(()=>""));t&&(await ms(e,t),await De("systemctl",["--user","daemon-reload"]))}function Sj(e,t){return`' Starts myrel-runner at login. Remove with: myrel-runner service uninstall\r
162
162
  CreateObject("WScript.Shell").Run "${`cmd.exe /c "${e.map(o=>`"${o}"`).join(" ")} >> "${t}" 2>&1"`.replace(/"/g,'""')}", 0, False\r
163
- `}import{spawn as Sj}from"node:child_process";var Ij="@fibteq/myrel-runner",Qf="@fibteq%2Fmyrel-runner",zj=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;async function vs(e="https://registry.npmjs.org"){try{let t=await fetch(`${e}/${Qf}/latest`,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return null;let{version:r}=await t.json();return typeof r=="string"&&zj.test(r)?r:null}catch{return null}}var _i=Ty;function D$(e,t){let r=process.platform==="win32"?"npx.cmd":"npx";return new Promise((o,n)=>{let i=Sj(r,["--yes",`--package=${Ij}@${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 Uj=Nj(Pj);function xi(e){return{access:e.access,worktrees:e.worktrees!==!1,autoUpdate:e.autoUpdate===!0,remote:e.remoteSettings!==!1}}function R$(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 M$(e=process.argv[1]){return process.versions.bun?"app":e&&Oj(e)===bi()?"service":"manual"}var em=()=>tm(ee(),"bin","myrel-runner.prev.mjs"),nm=()=>tm(ee(),"update.json"),L$=()=>he(nm()).catch(()=>{}),ys=e=>Je(nm(),e),rm=()=>C$(nm(),{force:!0}),Z$=1440*60*1e3;async function F$(e,t="https://registry.npmjs.org"){let r=await fetch(`${t}/${Qf}/${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(jj("sha512").update(a).digest("base64")!==n)throw new Error("The download does not match npm's checksum, so it was not installed.");let s=Cj(Dj(a),"package/dist/cli.js");if(!s)throw new Error("The download has no dist/cli.js.");return s}function Cj(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,m)=>n.toString("utf8",p,p+m).replace(/\0.*$/s,""),a=Number.parseInt(i(124,12).trim()||"0",8),s=i(156,1),u=e.subarray(o+512,o+512+a);if(o+=512+Math.ceil(a/512)*512,s==="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,(s==="0"||s==="")&&d===t)return Buffer.from(u)}return null}async function V$(e,t){let r=bi(),o=tm(ee(),"bin","myrel-runner.next.mjs");await Tj(o,e,{mode:448});try{let{stdout:n}=await Uj(process.execPath,[o,"--version"],{timeout:3e4});if(n.trim()!==t)throw new Error(`it says it is ${n.trim()||"nothing"}`)}catch(n){throw await C$(o,{force:!0}),new Error(`The new version does not start (${n.message.split(`
164
- `)[0]}), so it was not installed.`)}await E$(r).catch(()=>null)&&await U$(r,em()),await Aj(o,r)}async function J$(){return await E$(em()).catch(()=>null)?(await U$(em(),bi()),!0):!1}import{execFile as Ej}from"node:child_process";import{readFile as Rj,statfs as K$}from"node:fs/promises";import{cpus as B$,freemem as Mj,homedir as Lj,platform as Zj,totalmem as Fj}from"node:os";import{promisify as Vj}from"node:util";var Jj=Vj(Ej);function Kj(e=B$()){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 Bj(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 Wj(e){let t=a=>{let s=e.match(new RegExp(`^${a}:\\s+(\\d+)\\s*kB`,"m"));return s?Number(s[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 Gj(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 qj=()=>({platform:Zj(),cores:()=>B$().length,cpuTimes:Kj,totalmem:Fj,freemem:Mj,meminfo:()=>Rj("/proc/meminfo","utf8"),vmStat:async()=>(await Jj("vm_stat",[],{timeout:5e3,env:He()})).stdout,disk:async()=>{let e=ee(),t=await K$(e).catch(()=>K$(Lj()));return{total:t.blocks*t.bsize,free:t.bavail*t.bsize}},runnerMemory:()=>process.memoryUsage.rss(),now:()=>new Date}),bs=class{constructor(t,r={}){this.tasks=t;this.sources={...qj(),...r}}tasks;sources;previous;latest;async sample(){let t=this.sources,r=t.cpuTimes(),o=this.previous?Bj(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 Wj(await t.meminfo())??o;if(t.platform==="darwin")return Gj(await t.vmStat(),r)??o}catch{}return o}};var Hj=600*1e3,Xj=360*60*1e3,W$=120*1e3,$s=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 L$();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)<Z$){let{from:r,...o}=t;return this.current=o,!1}return await rm(),!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 rm(),this.opts.report(null))}async rollback(t){let r=this.pending;if(r){if(this.pending=null,!await(this.opts.restore??J$)().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 ys({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(!_i(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??Xj:this.opts.waitMs??Hj);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??vs)();!t||!_i(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??F$)(t);await(this.opts.install??V$)(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 ys(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 ys({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 Re="0.31.0",eA=360*60*1e3;async function q$(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||im(),hostname:im(),platform:G$()})}),o=await r.json().catch(()=>null);if(!r.ok)throw new Error(o?.message??`Pairing failed (${r.status})`);let n=Ay.parse(o),i=await pe();return Object.assign(i,{server:t,runnerId:n.runner.id,token:n.token}),await Ve(i),i}async function ki(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 tA="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>`.",nA=900*1e3,H$=75,rA=300*1e3;function iA(e,t){return e.length===t.length&&e.every(r=>t.some(o=>o.id===r.id&&o.version===r.version))}async function X$(e={}){let t=e.log??(k=>console.log(k)),r=e.onStatus??(()=>{}),o=await pe();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 mi(),i=await ib(),a=(k,D)=>{let F=i[k];!D||F&&F.at>=D.at||(i[k]=D,ob(i).catch(()=>{}),JSON.stringify({...F,at:""})!==JSON.stringify({...D,at:""})&&ue())},s=()=>{n.some(k=>k.id==="codex")&&Ba().then(k=>a("codex",k),()=>{})},u=new us({config:()=>o,sessions:new Fa,log:t,onLimits:a,onChange:Lf,version:Re}),l=d$();l.length&&t(`${l.length} task(s) stopped when the runner restarted; Myrel continues them.`),Lf([]);let d="stopped",p=null,m=!1,f=0,g,y=new Promise(k=>g=k),x=M$();x==="service"&&N$().catch(()=>{});let I=new $s({version:Re,running:()=>u.runningIds(),report:k=>P({type:"update.status",update:k}),log:t,restart:()=>{A$().catch(()=>{}).finally(()=>{d="restart",te()})}}),S;await I.init()&&(S=setTimeout(()=>{ki(o).then(k=>{k==="ok"&&I.confirming&&I.rollback("it did not connect within 2 minutes")})},W$),S.unref?.());let T=new Map,P=k=>{k.type==="task.done"&&(r({state:"task",taskId:k.taskId,event:"done",ok:k.ok}),T.set(k.taskId,{frame:k,at:Date.now()})),p?.readyState===WebSocket.OPEN&&p.send(JSON.stringify(k))},C=()=>{for(let[k,{frame:D,at:F}]of T)Date.now()-F>nA?T.delete(k):P(D)},j=new bs(()=>u.runningIds().length),A=()=>o.stats!==!1;A()&&await j.sample().catch(()=>{});let ue=()=>P({type:"hello",protocol:Sy,version:Re,hostname:im(),platform:G$(),folders:o.folders,clis:n.map(k=>i[k.id]?{...k,limits:i[k.id]}:k),features:["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","models","git-token","steer","steer-claude","ssh",...x==="service"?["update"]:[],...A()?["stats"]:[]],settings:xi(o),updates:x,...I.state()&&{update:I.state()},running:u.runningIds(),interrupted:l,...A()&&j.latest&&{stats:j.latest}});u.setSender(P);let tt=async()=>{o=await pe().catch(()=>o),ue()};Yj(Pt(),{interval:2e3},tt);let Me=setInterval(()=>{if(p?.readyState===WebSocket.OPEN){if(!A())return P({type:"ping"});j.sample().then(k=>P({type:"ping",stats:k}),()=>P({type:"ping"}))}},25e3),nt=()=>{Promise.all(n.map(async k=>{let D=await fi[k.id].models?.().catch(()=>{}),F=JSON.stringify(D)!==JSON.stringify(k.models);return D&&(k.models=D),F&&!!D})).then(k=>k.some(Boolean)&&ue())};nt(),s();let sn=()=>{mi().then(k=>{if(iA(n,k))return;let D=new Map(n.map(F=>[F.id,F]));n.splice(0,n.length,...k.map(F=>D.get(F.id)?.version===F.version?D.get(F.id):F)),t(`CLIs found: ${n.map(F=>F.id).join(", ")||"none"}`),ue(),nt(),s()},()=>{})},mt=setInterval(s,600*1e3),wi=setInterval(nt,360*60*1e3),or=setInterval(sn,rA);mt.unref?.(),or.unref?.();let ar=()=>{cs(k=>u.inUse(k)).then(k=>k.forEach(D=>t(`Removed the finished worktree ${D.path} (${D.branch})`))).catch(()=>{})};ar();let cn=setInterval(ar,360*60*1e3);cn.unref?.();let Si=()=>{x==="service"&&o.autoUpdate&&I.checkNewest().catch(()=>{})},sr=setTimeout(Si,600*1e3);sr.unref?.();let Z=setInterval(Si,eA);Z.unref?.();let te=()=>{m=!0,clearInterval(Me),clearInterval(cn),clearInterval(mt),clearInterval(wi),clearInterval(or),clearInterval(Z),clearTimeout(sr),clearTimeout(S),Qj(Pt(),tt),l$(u.stopAll()),p?.close(1e3),r({state:"stopped",reason:d}),g(d)},fe=async k=>{let{requestId:D}=k;if(k.type==="dirs.list")return P({type:"dirs",requestId:D,...await o$(k.path)});if(k.type==="task.steer")return P({type:"task.steered",requestId:D,taken:await u.steer(k.taskId,k.text)});if(k.type==="file.read")return P({type:"file",requestId:D,...await t$(o,k)});if(k.type==="ssh.keygen"){let F=await $$({projectId:k.projectId,alias:k.alias},k.comment,k.existing);return t(`${k.existing?"Using":"Made"} an SSH key for ${k.alias} (${F.fingerprint}, from Myrel)`),P({type:"ssh.key",requestId:D,...F})}if(k.type==="ssh.keys")return P({type:"ssh.keylist",requestId:D,keys:await _$()});if(k.type==="ssh.hostkeys")return P({type:"ssh.hostkeylist",requestId:D,keys:await x$(k.host,k.port)});if(k.type==="ssh.test")return P({type:"ssh.result",requestId:D,...await w$(k.target)});if(k.type==="ssh.run")return t(`SSH ${k.target.alias}: ${k.command.split(`
165
- `)[0].slice(0,80)}`),P({type:"ssh.result",requestId:D,...await qf(k.target,k.command)});if(k.type==="ssh.forget")return await Gf({projectId:k.projectId,alias:k.alias}),t(`Forgot the SSH key for ${k.alias} (from Myrel)`),P({type:"ssh.result",requestId:D,exitCode:0,stdout:"",stderr:"",truncated:!1,ms:0});if(k.type==="runner.update"){if(x!=="service")throw new Error(x==="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 ${k.version} (from Myrel)${k.now?"":" once the running tasks finish"}`),P({type:"update.accepted",requestId:D,update:I.request(k.version,k.now)})}if(o=await pe(),k.type==="settings.set")return R$(o,k.settings),await Ve(o),t(`Settings changed from Myrel: ${Object.entries(k.settings).map(([F,Ii])=>`${F} ${Ii}`).join(", ")}`),P({type:"settings",requestId:D,settings:xi(o)});if(k.type==="folder.share"){let F=await a$(k.path);Va(o,F)&&t(`Shared ${F} (from Myrel)`)}else Ja(o,k.path)&&t(`Stopped sharing ${k.path} (from Myrel)`);await Ve(o),P({type:"folders",requestId:D,folders:o.folders})},ie=()=>{if(m)return;let k=`${o.server.replace(/^http/,"ws")}/api/runner/connect`;r({state:"connecting"});let D=new WebSocket(k,{headers:{authorization:`Bearer ${o.token}`}});p=D;let F=!1;D.onopen=()=>{F=!0,f=0,C(),ue()},D.onmessage=Ae=>{let un=JSON.parse(String(Ae.data)),ks=jy.safeParse(un);if(!ks.success){let ln=un;if(ln?.type==="task.start"&&typeof ln.taskId=="string"){let am=ks.error.issues[0],sm=`${am?.path.join(".")||"frame"}: ${am?.message??"invalid"}`;t(`\u2717 could not read task ${ln.taskId} (${sm})`),P({type:"task.done",taskId:ln.taskId,ok:!1,result:`myrel-runner ${Re} could not read this task (${sm}). Update myrel-runner.`})}return}let xe=ks.data;xe.type==="welcome"&&(t(`\u25CF Connected to ${o.server} as "${xe.name}"`),r({state:"online",name:xe.name}),I.confirmed()),xe.type==="task.start"&&(r({state:"task",taskId:xe.taskId,event:"started"}),u.start(xe)),xe.type==="task.cancel"&&u.cancel(xe.taskId),xe.type==="task.github"&&u.renewGithub(xe.taskId,xe.github),"requestId"in xe&&fe(xe).catch(ln=>P({type:"request.failed",requestId:xe.requestId,message:oA(ln)}))};let Ii=!1,om=async Ae=>{if(Ii||p!==D||m)return;if(Ii=!0,!F&&await ki(o)==="invalid")return t(tA),e.onRevoked?.(),d="revoked",te();if(Ae.code===4401)return t("This computer was removed from Myrel. Pair it again with `myrel-runner pair`."),e.onRevoked?.(),d="revoked",te();if(Ae.code===4e3)return t("myrel-runner was started somewhere else with this computer's login, so this one stops."),d="replaced",te();if(Ae.code===4400)return t(`The server refused this runner: ${Ae.reason}`),I.confirming&&(await I.rollback(`the server refused it: ${Ae.reason}`),m)?void 0:(d="refused",te());let un=Math.min(3e4,1e3*2**f++);t(`\u25CB Disconnected${Ae.reason?` (${Ae.reason})`:""}. Reconnecting in ${Math.round(un/1e3)}s\u2026`),r({state:"offline",reason:Ae.reason||`code ${Ae.code}`,retryInMs:un}),setTimeout(ie,un)};D.onclose=Ae=>{om(Ae)},D.onerror=()=>{F||om({code:1006,reason:""})}};return ie(),t(`Sharing ${o.folders.length} folder(s); CLIs found: ${n.map(k=>k.id).join(", ")||"none"}`),en().then(k=>{let D=gi(k);D&&t(D)}),{stop:te,done:y}}function oA(e){return(e instanceof Error?e.message:String(e)).slice(0,500)}var sA=`myrel-runner ${Re}
163
+ `}import{spawn as Ij}from"node:child_process";var zj="@fibteq/myrel-runner",Qf="@fibteq%2Fmyrel-runner",Pj=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;async function vs(e="https://registry.npmjs.org"){try{let t=await fetch(`${e}/${Qf}/latest`,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return null;let{version:r}=await t.json();return typeof r=="string"&&Pj.test(r)?r:null}catch{return null}}var _i=Ty;function D$(e,t){let r=process.platform==="win32"?"npx.cmd":"npx";return new Promise((o,n)=>{let i=Ij(r,["--yes",`--package=${zj}@${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 Cj=Dj(jj);function xi(e){return{access:e.access,worktrees:e.worktrees!==!1,autoUpdate:e.autoUpdate===!0,remote:e.remoteSettings!==!1}}function R$(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 M$(e=process.argv[1]){return process.versions.bun?"app":e&&Nj(e)===bi()?"service":"manual"}var em=()=>tm(ee(),"bin","myrel-runner.prev.mjs"),nm=()=>tm(ee(),"update.json"),L$=()=>he(nm()).catch(()=>{}),ys=e=>Je(nm(),e),rm=()=>C$(nm(),{force:!0}),Z$=1440*60*1e3;async function F$(e,t="https://registry.npmjs.org"){let r=await fetch(`${t}/${Qf}/${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(Aj("sha512").update(a).digest("base64")!==n)throw new Error("The download does not match npm's checksum, so it was not installed.");let s=Ej(Uj(a),"package/dist/cli.js");if(!s)throw new Error("The download has no dist/cli.js.");return s}function Ej(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,m)=>n.toString("utf8",p,p+m).replace(/\0.*$/s,""),a=Number.parseInt(i(124,12).trim()||"0",8),s=i(156,1),u=e.subarray(o+512,o+512+a);if(o+=512+Math.ceil(a/512)*512,s==="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,(s==="0"||s==="")&&d===t)return Buffer.from(u)}return null}async function V$(e,t){let r=bi(),o=tm(ee(),"bin","myrel-runner.next.mjs");await Oj(o,e,{mode:448});try{let{stdout:n}=await Cj(process.execPath,[o,"--version"],{timeout:3e4});if(n.trim()!==t)throw new Error(`it says it is ${n.trim()||"nothing"}`)}catch(n){throw await C$(o,{force:!0}),new Error(`The new version does not start (${n.message.split(`
164
+ `)[0]}), so it was not installed.`)}await E$(r).catch(()=>null)&&await U$(r,em()),await Tj(o,r)}async function J$(){return await E$(em()).catch(()=>null)?(await U$(em(),bi()),!0):!1}import{execFile as Rj}from"node:child_process";import{readFile as Mj,statfs as K$}from"node:fs/promises";import{cpus as B$,freemem as Lj,homedir as Zj,platform as Fj,totalmem as Vj}from"node:os";import{promisify as Jj}from"node:util";var Kj=Jj(Rj);function Bj(e=B$()){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 Wj(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 Gj(e){let t=a=>{let s=e.match(new RegExp(`^${a}:\\s+(\\d+)\\s*kB`,"m"));return s?Number(s[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 qj(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 Hj=()=>({platform:Fj(),cores:()=>B$().length,cpuTimes:Bj,totalmem:Vj,freemem:Lj,meminfo:()=>Mj("/proc/meminfo","utf8"),vmStat:async()=>(await Kj("vm_stat",[],{timeout:5e3,env:He()})).stdout,disk:async()=>{let e=ee(),t=await K$(e).catch(()=>K$(Zj()));return{total:t.blocks*t.bsize,free:t.bavail*t.bsize}},runnerMemory:()=>process.memoryUsage.rss(),now:()=>new Date}),bs=class{constructor(t,r={}){this.tasks=t;this.sources={...Hj(),...r}}tasks;sources;previous;latest;async sample(){let t=this.sources,r=t.cpuTimes(),o=this.previous?Wj(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 Gj(await t.meminfo())??o;if(t.platform==="darwin")return qj(await t.vmStat(),r)??o}catch{}return o}};var Xj=600*1e3,Yj=360*60*1e3,W$=120*1e3,$s=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 L$();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)<Z$){let{from:r,...o}=t;return this.current=o,!1}return await rm(),!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 rm(),this.opts.report(null))}async rollback(t){let r=this.pending;if(r){if(this.pending=null,!await(this.opts.restore??J$)().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 ys({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(!_i(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??Yj:this.opts.waitMs??Xj);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??vs)();!t||!_i(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??F$)(t);await(this.opts.install??V$)(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 ys(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 ys({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 Re="0.32.0",tA=360*60*1e3;async function q$(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||im(),hostname:im(),platform:G$()})}),o=await r.json().catch(()=>null);if(!r.ok)throw new Error(o?.message??`Pairing failed (${r.status})`);let n=Ay.parse(o),i=await pe();return Object.assign(i,{server:t,runnerId:n.runner.id,token:n.token}),await Ve(i),i}async function ki(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 nA="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>`.",rA=900*1e3,H$=75,iA=300*1e3;function oA(e,t){return e.length===t.length&&e.every(r=>t.some(o=>o.id===r.id&&o.version===r.version))}async function X$(e={}){let t=e.log??(k=>console.log(k)),r=e.onStatus??(()=>{}),o=await pe();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 mi(),i=await ib(),a=(k,D)=>{let F=i[k];!D||F&&F.at>=D.at||(i[k]=D,ob(i).catch(()=>{}),JSON.stringify({...F,at:""})!==JSON.stringify({...D,at:""})&&ue())},s=()=>{n.some(k=>k.id==="codex")&&Ba().then(k=>a("codex",k),()=>{})},u=new us({config:()=>o,sessions:new Fa,log:t,onLimits:a,onChange:Lf,version:Re}),l=d$();l.length&&t(`${l.length} task(s) stopped when the runner restarted; Myrel continues them.`),Lf([]);let d="stopped",p=null,m=!1,f=0,g,y=new Promise(k=>g=k),x=M$();x==="service"&&N$().catch(()=>{});let I=new $s({version:Re,running:()=>u.runningIds(),report:k=>P({type:"update.status",update:k}),log:t,restart:()=>{A$().catch(()=>{}).finally(()=>{d="restart",te()})}}),S;await I.init()&&(S=setTimeout(()=>{ki(o).then(k=>{k==="ok"&&I.confirming&&I.rollback("it did not connect within 2 minutes")})},W$),S.unref?.());let T=new Map,P=k=>{k.type==="task.done"&&(r({state:"task",taskId:k.taskId,event:"done",ok:k.ok}),T.set(k.taskId,{frame:k,at:Date.now()})),p?.readyState===WebSocket.OPEN&&p.send(JSON.stringify(k))},C=()=>{for(let[k,{frame:D,at:F}]of T)Date.now()-F>rA?T.delete(k):P(D)},j=new bs(()=>u.runningIds().length),A=()=>o.stats!==!1;A()&&await j.sample().catch(()=>{});let ue=()=>P({type:"hello",protocol:Sy,version:Re,hostname:im(),platform:G$(),folders:o.folders,clis:n.map(k=>i[k.id]?{...k,limits:i[k.id]}:k),features:["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","models","git-token","steer","steer-claude","ssh",...x==="service"?["update"]:[],...A()?["stats"]:[]],settings:xi(o),updates:x,...I.state()&&{update:I.state()},running:u.runningIds(),interrupted:l,...A()&&j.latest&&{stats:j.latest}});u.setSender(P);let tt=async()=>{o=await pe().catch(()=>o),ue()};Qj(Pt(),{interval:2e3},tt);let Me=setInterval(()=>{if(p?.readyState===WebSocket.OPEN){if(!A())return P({type:"ping"});j.sample().then(k=>P({type:"ping",stats:k}),()=>P({type:"ping"}))}},25e3),nt=()=>{Promise.all(n.map(async k=>{let D=await fi[k.id].models?.().catch(()=>{}),F=JSON.stringify(D)!==JSON.stringify(k.models);return D&&(k.models=D),F&&!!D})).then(k=>k.some(Boolean)&&ue())};nt(),s();let sn=()=>{mi().then(k=>{if(oA(n,k))return;let D=new Map(n.map(F=>[F.id,F]));n.splice(0,n.length,...k.map(F=>D.get(F.id)?.version===F.version?D.get(F.id):F)),t(`CLIs found: ${n.map(F=>F.id).join(", ")||"none"}`),ue(),nt(),s()},()=>{})},mt=setInterval(s,600*1e3),wi=setInterval(nt,360*60*1e3),or=setInterval(sn,iA);mt.unref?.(),or.unref?.();let ar=()=>{cs(k=>u.inUse(k)).then(k=>k.forEach(D=>t(`Removed the finished worktree ${D.path} (${D.branch})`))).catch(()=>{})};ar();let cn=setInterval(ar,360*60*1e3);cn.unref?.();let Si=()=>{x==="service"&&o.autoUpdate&&I.checkNewest().catch(()=>{})},sr=setTimeout(Si,600*1e3);sr.unref?.();let Z=setInterval(Si,tA);Z.unref?.();let te=()=>{m=!0,clearInterval(Me),clearInterval(cn),clearInterval(mt),clearInterval(wi),clearInterval(or),clearInterval(Z),clearTimeout(sr),clearTimeout(S),eA(Pt(),tt),l$(u.stopAll()),p?.close(1e3),r({state:"stopped",reason:d}),g(d)},fe=async k=>{let{requestId:D}=k;if(k.type==="dirs.list")return P({type:"dirs",requestId:D,...await o$(k.path)});if(k.type==="task.steer")return P({type:"task.steered",requestId:D,taken:await u.steer(k.taskId,k.text)});if(k.type==="file.read")return P({type:"file",requestId:D,...await t$(o,k)});if(k.type==="ssh.keygen"){let F=await $$({projectId:k.projectId,alias:k.alias},k.comment,k.existing);return t(`${k.existing?"Using":"Made"} an SSH key for ${k.alias} (${F.fingerprint}, from Myrel)`),P({type:"ssh.key",requestId:D,...F})}if(k.type==="ssh.keys")return P({type:"ssh.keylist",requestId:D,keys:await _$()});if(k.type==="ssh.hostkeys")return P({type:"ssh.hostkeylist",requestId:D,keys:await x$(k.host,k.port)});if(k.type==="ssh.test")return P({type:"ssh.result",requestId:D,...await w$(k.target)});if(k.type==="ssh.run")return t(`SSH ${k.target.alias}: ${k.command.split(`
165
+ `)[0].slice(0,80)}`),P({type:"ssh.result",requestId:D,...await qf(k.target,k.command)});if(k.type==="ssh.forget")return await Gf({projectId:k.projectId,alias:k.alias}),t(`Forgot the SSH key for ${k.alias} (from Myrel)`),P({type:"ssh.result",requestId:D,exitCode:0,stdout:"",stderr:"",truncated:!1,ms:0});if(k.type==="runner.update"){if(x!=="service")throw new Error(x==="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 ${k.version} (from Myrel)${k.now?"":" once the running tasks finish"}`),P({type:"update.accepted",requestId:D,update:I.request(k.version,k.now)})}if(o=await pe(),k.type==="settings.set")return R$(o,k.settings),await Ve(o),t(`Settings changed from Myrel: ${Object.entries(k.settings).map(([F,Ii])=>`${F} ${Ii}`).join(", ")}`),P({type:"settings",requestId:D,settings:xi(o)});if(k.type==="folder.share"){let F=await a$(k.path);Va(o,F)&&t(`Shared ${F} (from Myrel)`)}else Ja(o,k.path)&&t(`Stopped sharing ${k.path} (from Myrel)`);await Ve(o),P({type:"folders",requestId:D,folders:o.folders})},ie=()=>{if(m)return;let k=`${o.server.replace(/^http/,"ws")}/api/runner/connect`;r({state:"connecting"});let D=new WebSocket(k,{headers:{authorization:`Bearer ${o.token}`}});p=D;let F=!1;D.onopen=()=>{F=!0,f=0,C(),ue()},D.onmessage=Ae=>{let un=JSON.parse(String(Ae.data)),ks=jy.safeParse(un);if(!ks.success){let ln=un;if(ln?.type==="task.start"&&typeof ln.taskId=="string"){let am=ks.error.issues[0],sm=`${am?.path.join(".")||"frame"}: ${am?.message??"invalid"}`;t(`\u2717 could not read task ${ln.taskId} (${sm})`),P({type:"task.done",taskId:ln.taskId,ok:!1,result:`myrel-runner ${Re} could not read this task (${sm}). Update myrel-runner.`})}return}let xe=ks.data;xe.type==="welcome"&&(t(`\u25CF Connected to ${o.server} as "${xe.name}"`),r({state:"online",name:xe.name}),I.confirmed()),xe.type==="task.start"&&(r({state:"task",taskId:xe.taskId,event:"started"}),u.start(xe)),xe.type==="task.cancel"&&u.cancel(xe.taskId),xe.type==="task.github"&&u.renewGithub(xe.taskId,xe.github),"requestId"in xe&&fe(xe).catch(ln=>P({type:"request.failed",requestId:xe.requestId,message:aA(ln)}))};let Ii=!1,om=async Ae=>{if(Ii||p!==D||m)return;if(Ii=!0,!F&&await ki(o)==="invalid")return t(nA),e.onRevoked?.(),d="revoked",te();if(Ae.code===4401)return t("This computer was removed from Myrel. Pair it again with `myrel-runner pair`."),e.onRevoked?.(),d="revoked",te();if(Ae.code===4e3)return t("myrel-runner was started somewhere else with this computer's login, so this one stops."),d="replaced",te();if(Ae.code===4400)return t(`The server refused this runner: ${Ae.reason}`),I.confirming&&(await I.rollback(`the server refused it: ${Ae.reason}`),m)?void 0:(d="refused",te());let un=Math.min(3e4,1e3*2**f++);t(`\u25CB Disconnected${Ae.reason?` (${Ae.reason})`:""}. Reconnecting in ${Math.round(un/1e3)}s\u2026`),r({state:"offline",reason:Ae.reason||`code ${Ae.code}`,retryInMs:un}),setTimeout(ie,un)};D.onclose=Ae=>{om(Ae)},D.onerror=()=>{F||om({code:1006,reason:""})}};return ie(),t(`Sharing ${o.folders.length} folder(s); CLIs found: ${n.map(k=>k.id).join(", ")||"none"}`),en().then(k=>{let D=gi(k);D&&t(D)}),{stop:te,done:y}}function aA(e){return(e instanceof Error?e.message:String(e)).slice(0,500)}var cA=`myrel-runner ${Re}
166
166
  Connects this computer to Myrel, so projects can work in folders you share
167
167
  using your own Claude Code, Codex, Antigravity CLI, OpenCode, Hermes Agent, Cursor CLI, Muse Code or Kimi Code. Your CLI logins never leave
168
168
  this computer.
@@ -205,7 +205,7 @@ is merged and that were not used for a day are removed automatically.
205
205
 
206
206
  Environment: MYREL_SERVER and MYREL_RUNNER_TOKEN override the saved pairing;
207
207
  MYREL_RUNNER_HOME moves the config folder (default ~/.myrel-runner).
208
- `;async function cA(e){if(e[0]==="ssh-shim"){process.exitCode=await Fb(e[1],e.slice(2));return}let{values:t,positionals:r}=aA({args:e,allowPositionals:!0,options:{server:{type:"string"},name:{type:"string"},access:{type:"string"},json:{type:"boolean"},force:{type:"boolean"},now:{type:"boolean"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}}}),[o,n]=r;if(t.version)return console.log(Re);if(t.help||!o)return console.log(sA);switch(o){case"mcp-bridge":return Hy({input:process.stdin,write:i=>process.stdout.write(`${i}
208
+ `;async function uA(e){if(e[0]==="ssh-shim"){process.exitCode=await Fb(e[1],e.slice(2));return}let{values:t,positionals:r}=sA({args:e,allowPositionals:!0,options:{server:{type:"string"},name:{type:"string"},access:{type:"string"},json:{type:"boolean"},force:{type:"boolean"},now:{type:"boolean"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}}}),[o,n]=r;if(t.version)return console.log(Re);if(t.help||!o)return console.log(cA);switch(o){case"mcp-bridge":return Hy({input:process.stdin,write:i=>process.stdout.write(`${i}
209
209
  `),run:await Xy(),version:Re});case"git-credential":return zb(n,process.stdin,i=>process.stdout.write(i));case"pair":{let i=t.server??(await pe()).server;if(!n||!i)throw new Error("Usage: myrel-runner pair <code> --server <url>");let a=await q$({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 pe(),a=Va(i,n??process.cwd());await Ve(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 pe(),a=Ja(i,n);await Ve(i),console.log(a?"Stopped sharing it.":"That folder was not shared.");return}case"status":{let i=await pe(),a=[],[s,u]=await Promise.all([mi(a),ki(i)]);if(t.json){let{token:p,...m}=i;return console.log(JSON.stringify({...m,paired:!!(p&&i.server),pairing:u,clis:s}))}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: ${Pt()}`),console.log(`Access: ${i.access}${i.autoUpdate?" \xB7 auto-update on":""}`),console.log(`Folders: ${i.folders.map(p=>`
210
210
  ${p.path}`).join("")||"none"}`),console.log(`CLIs: ${s.map(p=>`
211
211
  ${Za[p.id]} ${p.version??""}`).join("")||"none found"}`),console.log(`Not found: ${a.map(p=>`
@@ -214,8 +214,8 @@ MYREL_RUNNER_HOME moves the config folder (default ~/.myrel-runner).
214
214
  ${a}`),i.blocked.length&&console.log(`
215
215
  \`myrel-runner sandbox fix\` installs this profile with sudo:
216
216
 
217
- ${Af(i.binaries)}`);return}case"start":{t.access&&await _s(t.access);let i=await X$(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"?H$:0)}case"service":{if(n==="install"){let i=await pe();if(!i.server||!i.token)throw new Error("Pair this computer first: myrel-runner pair <code> --server <url>");if(await ki(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 _s(t.access),xs(await Yf(Y$(import.meta.url)),t.json);return}if(n==="uninstall")return xs(await T$(),t.json);if(n==="status"||!n)return xs(await $i(),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 vs();if(!i&&!a&&console.log("Could not reach npm to look for a newer version."),a&&_i(a,Re)){console.log(`Updating myrel-runner ${Re} to ${a}\u2026`),process.exitCode=await D$(a,e);return}if(!i&&a&&console.log(`myrel-runner ${Re} is the newest version.`),!(await $i().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 _s(t.access),t.now||await lA();let s=await Yf(Y$(import.meta.url));console.log(`Restarted the background runner on ${Re}.`),xs(s,t.json);return}case"worktrees":{if(n==="on"||n==="off"){let u=await pe();u.worktrees=n==="on",await Ve(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 cs();console.log(u.length?u.map(l=>`Removed ${l.path} (${l.branch})`).join(`
217
+ ${Af(i.binaries)}`);return}case"start":{t.access&&await _s(t.access);let i=await X$(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"?H$:0)}case"service":{if(n==="install"){let i=await pe();if(!i.server||!i.token)throw new Error("Pair this computer first: myrel-runner pair <code> --server <url>");if(await ki(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 _s(t.access),xs(await Yf(Y$(import.meta.url)),t.json);return}if(n==="uninstall")return xs(await T$(),t.json);if(n==="status"||!n)return xs(await $i(),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 vs();if(!i&&!a&&console.log("Could not reach npm to look for a newer version."),a&&_i(a,Re)){console.log(`Updating myrel-runner ${Re} to ${a}\u2026`),process.exitCode=await D$(a,e);return}if(!i&&a&&console.log(`myrel-runner ${Re} is the newest version.`),!(await $i().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 _s(t.access),t.now||await dA();let s=await Yf(Y$(import.meta.url));console.log(`Restarted the background runner on ${Re}.`),xs(s,t.json);return}case"worktrees":{if(n==="on"||n==="off"){let u=await pe();u.worktrees=n==="on",await Ve(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 cs();console.log(u.length?u.map(l=>`Removed ${l.path} (${l.branch})`).join(`
218
218
  `):"Nothing to clean up.");return}let i=await tn();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 Uf(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=>ss(u).catch(()=>null)));if(t.json)return console.log(JSON.stringify(i.map((u,l)=>({...u,...a[l]}))));let s=(await pe()).worktrees!==!1;console.log(`Worktrees: ${s?"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(`
219
219
  ${l.branch}${p?` (${p})`:""}
220
220
  ${l.path}
221
- from ${l.repo}, last used ${new Date(l.lastUsed).toLocaleString()}`)}i.length||console.log("No worktrees yet.");return}case"settings":{let i=await pe(),a=r[2];if(n==="access"&&a)await _s(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 Ve(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 s=await pe(),u=xi(s),l=s.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"logout":{let i=await pe();delete i.token,delete i.runnerId,await Ve(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 uA=600*1e3;async function lA(){let e=Date.now()+uA,t=0;for(let r=Zf();r.length;r=Zf()){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 _s(e){if(!["read","edit","auto","full"].includes(e))throw new Error("--access must be read, edit, auto or full");let t=await pe();t.access=e,await Ve(t)}function xs(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}`)}cA(process.argv.slice(2)).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
221
+ from ${l.repo}, last used ${new Date(l.lastUsed).toLocaleString()}`)}i.length||console.log("No worktrees yet.");return}case"settings":{let i=await pe(),a=r[2];if(n==="access"&&a)await _s(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 Ve(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 s=await pe(),u=xi(s),l=s.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"logout":{let i=await pe();delete i.token,delete i.runnerId,await Ve(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 lA=600*1e3;async function dA(){let e=Date.now()+lA,t=0;for(let r=Zf();r.length;r=Zf()){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 _s(e){if(!["read","edit","auto","full"].includes(e))throw new Error("--access must be read, edit, auto or full");let t=await pe();t.access=e,await Ve(t)}function xs(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}`)}uA(process.argv.slice(2)).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});