import{createRequireasAk0}from"node:module";varqk0=Object.create;var{getPrototypeOf:Vk0,defineProperty:Oj,getOwnPropertyNames:Lk0}=Object;varFk0=Object.prototype.hasOwnProperty;functionwk0($){returnthis[$]}varMk0,Ok0,I6=($,Y,U)=>{varz=$!=null&&typeof$==="object";if(z){varI=Y?Mk0??=newWeakMap:Ok0??=newWeakMap,Q=I.get($);if(Q)returnQ}U=$!=null?qk0(Vk0($)):{};letJ=Y||!$||!$.__esModule?Oj(U,"default",{value:$,enumerable:!0}):U;for(letKofLk0($))if(!Fk0.call(J,K))Oj(J,K,{get:wk0.bind($,K),enumerable:!0});if(z)I.set($,J);returnJ};varE=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);varNk0=($)=>$;functionDk0($,Y){this[$]=Nk0.bind(null,Y)}varT8=($,Y)=>{for(varUinY)Oj($,U,{get:Y[U],enumerable:!0,configurable:!0,set:Dk0.bind(Y,U)})};varm=($,Y)=>()=>($&&(Y=$($=0)),Y);varJ0=Ak0(import.meta.url);varBk0,YV,Pk0,Tk0,jk0,Ek0,E0=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports),Nr=($,Y)=>{letU={};for(varzin$)YV(U,z,{get:$[z],enumerable:!0});if(Y)YV(U,Symbol.toStringTag,{value:"Module"});returnU},Ck0=($,Y,U,z)=>{if(Y&&typeofY==="object"||typeofY==="function"){for(varI=Tk0(Y),Q=0,J=I.length,K;Q<J;Q++)if(K=I[Q],!Ek0.call($,K)&&K!==U)YV($,K,{get:((G)=>Y[G]).bind(null,K),enumerable:!(z=Pk0(Y,K))||z.enumerable})}return$},UV=($,Y,U)=>(U=$!=null?Bk0(jk0($)):{},Ck0(Y||!$||!$.__esModule?YV(U,"default",{value:$,enumerable:!0}):U,$));varNj=m(()=>{Bk0=Object.create,YV=Object.defineProperty,Pk0=Object.getOwnPropertyDescriptor,Tk0=Object.getOwnPropertyNames,jk0=Object.getPrototypeOf,Ek0=Object.prototype.hasOwnProperty});functionAr($){returntypeof$==="string"&&Dr.has($.replace(/#$/,""))}functionBr($,Y){if(!("$schema"in$)||typeof$.$schema!=="string")return"2020-12";letU=$.$schema.replace(/#$/,"");if(Rk0.has(U))return"2020-12";if(Dr.has(U))return"2019-09";if(_k0.has(U)||vk0.has(U))return"draft-7";throwError(`JSON Schema declares an unsupported dialect ("$schema": "${$.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${Y}`)}varRk0,Dr,_k0,vk0;varDj=m(()=>{Rk0=newSet(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Dr=newSet(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),_k0=newSet(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),vk0=newSet(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});functionH0($,Y,U){functionz(K,G){if(!K._zod)Object.defineProperty(K,"_zod",{value:{def:G,constr:J,traits:newSet},enumerable:!1});if(K._zod.traits.has($))return;K._zod.traits.add($),Y(K,G);letH=J.prototype,W=Object.keys(H);for(letX=0;X<W.length;X++){letZ=W[X];if(!(ZinK))K[Z]=H[Z].bind(K)}}letI=U?.Parent??Object;classQextendsI{}Object.defineProperty(Q,"name",{value:$});functionJ(K){varG;letH=U?.Parent?newQ:this;z(H,K),(G=H._zod).deferred??(G.deferred=[]);for(letWofH._zod.deferred)W();returnH}returnObject.defineProperty(J,"init",{value:z}),Object.defineProperty(J,Symbol.hasInstance,{value:(K)=>{if(U?.Parent&&KinstanceofU.Parent)return!0;returnK?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}functions4($){if($)Object.assign(TY,$);returnTY}varPr,aK,Aj,p5,jY,TY;varEY=m(()=>{aK=Object.freeze({status:"aborted"});Aj=Symbol("zod_brand");p5=classp5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};jY=classjYextendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(Pr=globalThis).__zod_globalConfig??(Pr.__zod_globalConfig={});TY=globalThis.__zod_globalConfig});vark0={};T8(k0,{unwrapMessage:()=>tK,uint8ArrayToHex:()=>Ux0,uint8ArrayToBase64url:()=>$x0,uint8ArrayToBase64:()=>Er,stringifyPrimitive:()=>_0,slugify:()=>Tj,shallowClone:()=>Ej,safeExtend:()=>ok0,required:()=>ak0,randomString:()=>ik0,propertyKeyTypes:()=>YG,promiseAllObject:()=>bk0,primitiveTypes:()=>Cj,prefixIssues:()=>b8,pick:()=>dk0,partial:()=>sk0,parsedType:()=>S0,optionalKeys:()=>Rj,omit:()=>mk0,objectClone:()=>xk0,numKeys:()=>ck0,nullish:()=>W7,normalizeParams:()=>f0,mergeDefs:()=>l9,merge:()=>rk0,jsonStringifyReplacer:()=>mz,joinValues:()=>M0,issue:()=>oz,isPlainObject:()=>Z7,isObject:()=>CY,hexToUint8Array:()=>Yx0,getSizableOrigin:()=>UG,getParsedType:()=>nk0,getLengthableOrigin:()=>zG,getEnumValues:()=>eK,getElementAtPath:()=>uk0,floatSafeRemainder:()=>Pj,finalizeIssue:()=>E8,extend:()=>lk0,explicitlyAborted:()=>hj,escapeRegex:()=>B$,esc:()=>zV,defineLazy:()=>E1,createTransparentProxy:()=>pk0,cloneDef:()=>fk0,clone:()=>j8,cleanRegex:()=>$G,cleanEnum:()=>tk0,captureStackTrace:()=>IV,cached:()=>lz,base64urlToUint8Array:()=>ek0,base64ToUint8Array:()=>jr,assignProp:()=>X7,assertNotEqual:()=>Sk0,assertNever:()=>yk0,assertIs:()=>gk0,assertEqual:()=>hk0,assert:()=>kk0,allowsEval:()=>jj,aborted:()=>q7,NUMBER_FORMAT_RANGES:()=>_j,Class:()=>CrLine truncated
`)}var Rr=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,mz,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},IG,i8;var yj=m(()=>{EY();$1();IG=H0("$ZodError",Rr),i8=H0("$ZodError",Rr,{Parent:Error})});var rz=($)=>(Y,U,z,I)=>{let Q=z?{...z,async:!1}:{async:!1},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)throw new p5;if(J.issues.length){let K=new(I?.Err??$)(J.issues.map((G)=>E8(G,Q,s4())));throw IV(K,I?.callee),K}return J.value},QV,sz=($)=>async(Y,U,z,I)=>{let Q=z?{...z,async:!0}:{async:!0},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)J=await J;if(J.issues.length){let K=new(I?.Err??$)(J.issues.map((G)=>E8(G,Q,s4())));throw IV(K,I?.callee),K}return J.value},JV,az=($)=>(Y,U,z)=>{let I=z?{...z,async:!1}:{async:!1},Q=Y._zod.run({value:U,issues:[]},I);if(Q instanceof Promise)throw new p5;return Q.issues.length?{success:!1,error:new($??IG)(Q.issues.map((J)=>E8(J,I,s4())))}:{success:!0,data:Q.value}},kj,tz=($)=>async(Y,U,z)=>{let I=z?{...z,async:!0}:{async:!0},Q=Y._zod.run({value:U,issues:[]},I);if(Q instanceof Promise)Q=await Q;return Q.issues.length?{success:!1,error:new $(Q.issues.map((J)=>E8(J,I,s4())))}:{success:!0,data:Q.value}},xj,KV=($)=>(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return rz($)(Y,U,I)},Ix0,GV=($)=>(Y,U,z)=>{return rz($)(Y,U,z)},Qx0,HV=($)=>async(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return sz($)(Y,U,I)},Jx0,WV=($)=>async(Y,U,z)=>{return sz($)(Y,U,z)},Kx0,XV=($)=>(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return az($)(Y,U,I)},Gx0,ZV=($)=>(Y,U,z)=>{return az($)(Y,U,z)},Hx0,qV=($)=>async(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return tz($)(Y,U,I)},Wx0,VV=($)=>async(Y,U,z)=>{return tz($)(Y,U,z)},Xx0;var fj=m(()=>{EY();yj();$1();QV=rz(i8),JV=sz(i8),kj=az(i8),xj=tz(i8),Ix0=KV(i8),Qx0=GV(i8),Jx0=HV(i8),Kx0=WV(i8),Gx0=XV(i8),Hx0=ZV(i8),Wx0=qV(i8),Xx0=VV(i8)});var z$={};T8(z$,{xid:()=>cj,uuid7:()=>Lx0,uuid6:()=>Vx0,uuid4:()=>qx0,uuid:()=>RY,uppercase:()=>qE,unicodeEmail:()=>vr,undefined:()=>XE,ulid:()=>ij,time:()=>IE,string:()=>JE,sha512_hex:()=>kx0,sha512_base64url:()=>fx0,sha512_base64:()=>xx0,sha384_hex:()=>Sx0,sha384_base64url:()=>yx0,sha384_base64:()=>gx0,sha256_hex:()=>_x0,sha256_base64url:()=>hx0,sha256_base64:()=>vx0,sha1_hex:()=>Ex0,sha1_base64url:()=>Rx0,sha1_base64:()=>Cx0,rfc5322Email:()=>wx0,number:()=>KG,null:()=>WE,nanoid:()=>pj,md5_hex:()=>Px0,md5_base64url:()=>jx0,md5_base64:()=>Tx0,mac:()=>aj,lowercase:()=>ZE,ksuid:()=>nj,ipv6:()=>sj,ipv4:()=>rj,integer:()=>GE,idnEmail:()=>Mx0,httpProtocol:()=>YE,html5Email:()=>Fx0,hostname:()=>Dx0,hex:()=>Bx0,guid:()=>mj,extendedDuration:()=>Zx0,emoji:()=>oj,email:()=>lj,e164:()=>UE,duration:()=>dj,domain:()=>Ax0,datetime:()=>QE,date:()=>zE,cuid2:()=>bj,cuid:()=>uj,cidrv6:()=>ej,cidrv4:()=>tj,browserEmail:()=>Ox0,boolean:()=>HE,bigint:()=>KE,base64url:()=>LV,base64:()=>$E});function oj(){return new RegExp(Nx0,"u")}function Sr($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function IE($){return new RegExp(`^${Sr($)}$`)}function QE($){let Y=Sr({precision:$.precision}),U=["Z"];if($.local)U.push("");if($.offset)U.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let z=`${Y}(?:${U.join("|")})`;return new RegExp(`^${hr}T(?:${z})$`)}function GG($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function HG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var uj,bj,ij,cj,nj,pj,dj,Zx0,mj,RY=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;returnnewRegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},qx0,Vx0,Lx0,lj,Fx0,wx0,vr,Mx0,Ox0,Nx0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rj,sj,aj=($)=>{letY=B$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},tj,ej,$E,LV,Dx0,Ax0,YE,UE,hr="(?:(?:\\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])))",zE,JE=($)=>{letY=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${Y}$`)},KE,GE,KG,HE,WE,XE,ZE,qE,Bx0,Px0,Tx0,jx0,Ex0,Cx0,Rx0,_x0,vx0,hx0,Sx0,gx0,yx0,kx0,xx0,fx0;varFV=m(()=>{$1();uj=/^[cC][0-9a-z]{6,}$/,bj=/^[0-9a-z]+$/,ij=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,cj=/^[0-9a-vA-V]{20}$/,nj=/^[A-Za-z0-9]{27}$/,pj=/^[a-zA-Z0-9_-]{21}$/,dj=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((Q)=>Q),z=Math.min(...U.map((Q)=>Q.length-Q.trimStart().length)),I=U.map((Q)=>Q.slice(z)).map((Q)=>" ".repeat(this.indent*2)+Q);for(let Q of I)this.content.push(Q)}compile(){let $=Function,Y=this?.args,z=[...(this?.content??[""]).map((I)=>`${I}`)];return new $(...Y,z.join(`
`))}}var hE;var SE=m(()=>{hE={major:4,minor:4,patch:3}});function YC($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function ar($){if(!LV.test($))return!1;let Y=$.replace(/[-_]/g,(z)=>z==="-"?"+":"/"),U=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return YC(U)}function tr($,Y=null){try{let U=$.split(".");if(U.length!==3)return!1;let[z]=U;if(!z)return!1;let I=JSON.parse(atob(z));if("typ"in I&&I?.typ!=="JWT")return!1;if(!I.alg)return!1;if(Y&&(!("alg"in I)||I.alg!==Y))return!1;return!0}catch{return!1}}function xr($,Y,U){if($.issues.length)Y.issues.push(...b8(U,$.issues));Y.value[U]=$.value}function PV($,Y,U,z,I,Q){let J=U in z;if($.issues.length){if(I&&Q&&!J)return;Y.issues.push(...b8(U,$.issues))}if(!J&&!I){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[U]});return}if($.value===void 0){if(J)Y.value[U]=void 0}else Y.value[U]=$.value}function er($){let Y=Object.keys($.shape);for(let z of Y)if(!$.shape?.[z]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${z}":expectedaZodschema`);let U=Rj($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(U)}}function $s($,Y,U,z,I,Q){let J=[],K=I.keySet,G=I.catchall._zod,H=G.def.type,W=G.optin==="optional",X=G.optout==="optional";for(let Z in Y){if(Z==="__proto__")continue;if(K.has(Z))continue;if(H==="never"){J.push(Z);continue}let q=G.run({value:Y[Z],issues:[]},z);if(q instanceof Promise)$.push(q.then((V)=>PV(V,U,Z,Y,W,X)));else PV(q,U,Z,Y,W,X)}if(J.length)U.issues.push({code:"unrecognized_keys",keys:J,input:Y,inst:Q});if(!$.length)return U;return Promise.all($).then(()=>{return U})}function fr($,Y,U,z){for(let Q of $)if(Q.issues.length===0)return Y.value=Q.value,Y;let I=$.filter((Q)=>!q7(Q));if(I.length===1)return Y.value=I[0].value,I[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((Q)=>Q.issues.map((J)=>E8(J,z,s4())))}),Y}function ur($,Y,U,z){let I=$.filter((Q)=>Q.issues.length===0);if(I.length===1)return Y.value=I[0].value,Y;if(I.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((Q)=>Q.issues.map((J)=>E8(J,z,s4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:[],inclusive:!1});return Y}function gE($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(Z7($)&&Z7(Y)){let U=Object.keys(Y),z=Object.keys($).filter((Q)=>U.indexOf(Q)!==-1),I={...$,...Y};for(let Q of z){let J=gE($[Q],Y[Q]);if(!J.valid)return{valid:!1,mergeErrorPath:[Q,...J.mergeErrorPath]};I[Q]=J.data}return{valid:!0,data:I}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let z=0;z<$.length;z++){let I=$[z],Q=Y[z],J=gE(I,Q);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};U.push(J.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function br($,Y,U){let z=new Map,I;for(let K of Y.issues)if(K.code==="unrecognized_keys"){I??(I=K);for(let G of K.keys){if(!z.has(G))z.set(G,{});z.get(G).l=!0}}else $.issues.push(K);for(let K of U.issues)if(K.code==="unrecognized_keys")for(let G of K.keys){if(!z.has(G))z.set(G,{});z.get(G).r=!0}else $.issues.push(K);let Q=[...z].filter(([,K])=>K.l&&K.r).map(([K])=>K);if(Q.length&&I)$.issues.push({...I,keys:Q});if(q7($))return $;let J=gE(Y.value,U.value);if(!J.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}function ir($,Y){for(let U=$.length-1;U>=0;U--)if($[U]._zod[Y]!=="optional")return U+1;return 0}function cr($,Y,U){if($.issues.length)Y.issues.push(...b8(U,$.issues));Y.value[U]=$.value}function nr($,Y,U,z,I){for(let Q=0;Q<U.length;Q++){let J=$[Q],K=Q<z.length;if(J.issues.length){if(!K&&Q>=I){Y.value.length=Q;break}Y.issues.push(...b8(Q,J.issues))}Y.value[Q]=J.value}for(let Q=Y.value.length-1;Q>=z.length;Q--)if(U[Q]._zod.optout==="optional"&&Y.value[Q]===void 0)Y.value.length=Q;else break;return Y}function pr($,Y,U,z,I,Q,J){if($.issues.length)if(YG.has(typeof z))U.issues.push(...b8(z,$.issues));else U.issues.push({code:"invalid_key",origin:"map",input:I,inst:Q,issues:$.issues.map((K)=>E8(K,J,s4()))});if(Y.issues.length)if(YG.has(typeof z))U.issues.push(...b8(z,Y.issues));else U.issues.push({origin:"map",code:"invalid_element",input:I,inst:Q,key:z,issues:Y.issues.map((K)=>E8(K,J,s4()))});U.value.set($.value,Y.value)}function dr($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function mr($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function lr($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function or($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function DV($,Y,U){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa
Line truncated
import{createRequireasZx0}from"node:module";varIx0=Object.create;var{getPrototypeOf:Qx0,defineProperty:EE,getOwnPropertyNames:Jx0}=Object;varKx0=Object.prototype.hasOwnProperty;functionzx0($){returnthis[$]}varGx0,Hx0,K6=($,Y,U)=>{varI=$!=null&&typeof$==="object";if(I){varQ=Y?Gx0??=newWeakMap:Hx0??=newWeakMap,J=Q.get($);if(J)returnJ}U=$!=null?Ix0(Qx0($)):{};letK=Y||!$||!$.__esModule?EE(U,"default",{value:$,enumerable:!0}):U;for(letzofJx0($))if(!Kx0.call(K,z))EE(K,z,{get:zx0.bind($,z),enumerable:!0});if(I)Q.set($,K);returnK};varj=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);varWx0=($)=>$;functionXx0($,Y){this[$]=Wx0.bind(null,Y)}varZ8=($,Y)=>{for(varUinY)EE($,U,{get:Y[U],enumerable:!0,configurable:!0,set:Xx0.bind(Y,U)})};varm=($,Y)=>()=>($&&(Y=$($=0)),Y);varK0=Zx0(import.meta.url);varqx0,zV,Vx0,Lx0,Fx0,wx0,j0=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports),yr=($,Y)=>{letU={};for(varIin$)zV(U,I,{get:$[I],enumerable:!0});if(Y)zV(U,Symbol.toStringTag,{value:"Module"});returnU},Mx0=($,Y,U,I)=>{if(Y&&typeofY==="object"||typeofY==="function"){for(varQ=Lx0(Y),J=0,K=Q.length,z;J<K;J++)if(z=Q[J],!wx0.call($,z)&&z!==U)zV($,z,{get:((G)=>Y[G]).bind(null,z),enumerable:!(I=Vx0(Y,z))||I.enumerable})}return$},GV=($,Y,U)=>(U=$!=null?qx0(Fx0($)):{},Mx0(Y||!$||!$.__esModule?zV(U,"default",{value:$,enumerable:!0}):U,$));varjE=m(()=>{qx0=Object.create,zV=Object.defineProperty,Vx0=Object.getOwnPropertyDescriptor,Lx0=Object.getOwnPropertyNames,Fx0=Object.getPrototypeOf,wx0=Object.prototype.hasOwnProperty});functionxr($){returntypeof$==="string"&&kr.has($.replace(/#$/,""))}functionfr($,Y){if(!("$schema"in$)||typeof$.$schema!=="string")return"2020-12";letU=$.$schema.replace(/#$/,"");if(Ox0.has(U))return"2020-12";if(kr.has(U))return"2019-09";if(Nx0.has(U)||Dx0.has(U))return"draft-7";throwError(`JSON Schema declares an unsupported dialect ("$schema": "${$.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${Y}`)}varOx0,kr,Nx0,Dx0;varCE=m(()=>{Ox0=newSet(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),kr=newSet(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Nx0=newSet(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Dx0=newSet(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});functionH0($,Y,U){functionI(z,G){if(!z._zod)Object.defineProperty(z,"_zod",{value:{def:G,constr:K,traits:newSet},enumerable:!1});if(z._zod.traits.has($))return;z._zod.traits.add($),Y(z,G);letH=K.prototype,W=Object.keys(H);for(letX=0;X<W.length;X++){letZ=W[X];if(!(Zinz))z[Z]=H[Z].bind(z)}}letQ=U?.Parent??Object;classJextendsQ{}Object.defineProperty(J,"name",{value:$});functionK(z){varG;letH=U?.Parent?newJ:this;I(H,z),(G=H._zod).deferred??(G.deferred=[]);for(letWofH._zod.deferred)W();returnH}returnObject.defineProperty(K,"init",{value:I}),Object.defineProperty(K,Symbol.hasInstance,{value:(z)=>{if(U?.Parent&&zinstanceofU.Parent)return!0;returnz?._zod?.traits?.has($)}}),Object.defineProperty(K,"name",{value:$}),K}functiona4($){if($)Object.assign(EY,$);returnEY}varur,$G,RE,l5,jY,EY;varCY=m(()=>{$G=Object.freeze({status:"aborted"});RE=Symbol("zod_brand");l5=classl5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};jY=classjYextendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(ur=globalThis).__zod_globalConfig??(ur.__zod_globalConfig={});EY=globalThis.__zod_globalConfig});vark0={};Z8(k0,{unwrapMessage:()=>YG,uint8ArrayToHex:()=>mx0,uint8ArrayToBase64url:()=>dx0,uint8ArrayToBase64:()=>cr,stringifyPrimitive:()=>_0,slugify:()=>SE,shallowClone:()=>gE,safeExtend:()=>fx0,required:()=>ix0,randomString:()=>vx0,propertyKeyTypes:()=>QG,promiseAllObject:()=>_x0,primitiveTypes:()=>yE,prefixIssues:()=>n8,pick:()=>yx0,partial:()=>bx0,parsedType:()=>h0,optionalKeys:()=>kE,omit:()=>kx0,objectClone:()=>jx0,numKeys:()=>Sx0,nullish:()=>q7,normalizeParams:()=>f0,mergeDefs:()=>r9,merge:()=>ux0,jsonStringifyReplacer:()=>lI,joinValues:()=>M0,issue:()=>rI,isPlainObject:()=>L7,isObject:()=>RY,hexToUint8Array:()=>px0,getSizableOrigin:()=>JG,getParsedType:()=>hx0,getLengthableOrigin:()=>KG,getEnumValues:()=>UG,getElementAtPath:()=>Rx0,floatSafeRemainder:()=>vE,finalizeIssue:()=>R8,extend:()=>xx0,explicitlyAborted:()=>uE,escapeRegex:()=>R$,esc:()=>HV,defineLazy:()=>j1,createTransparentProxy:()=>gx0,cloneDef:()=>Cx0,clone:()=>C8,cleanRegex:()=>IG,cleanEnum:()=>cx0,captureStackTrace:()=>WV,cached:()=>oI,base64urlToUint8Array:()=>nx0,base64ToUint8Array:()=>ir,assignProp:()=>V7,assertNotEqual:()=>Ax0,assertNever:()=>Tx0,assertIs:()=>Px0,assertEqual:()=>Bx0,assert:()=>Ex0,allowsEval:()=>hE,aborted:()=>F7,NUMBER_FORMAT_RANGES:()=>xE,Class:()=>nrLine truncated
`)}var dr=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,lI,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},zG,d8;var cE=m(()=>{CY();$1();zG=H0("$ZodError",dr),d8=H0("$ZodError",dr,{Parent:Error})});var sI=($)=>(Y,U,I,Q)=>{let J=I?{...I,async:!1}:{async:!1},K=Y._zod.run({value:U,issues:[]},J);if(K instanceof Promise)throw new l5;if(K.issues.length){let z=new(Q?.Err??$)(K.issues.map((G)=>R8(G,J,a4())));throw WV(z,Q?.callee),z}return K.value},XV,aI=($)=>async(Y,U,I,Q)=>{let J=I?{...I,async:!0}:{async:!0},K=Y._zod.run({value:U,issues:[]},J);if(K instanceof Promise)K=await K;if(K.issues.length){let z=new(Q?.Err??$)(K.issues.map((G)=>R8(G,J,a4())));throw WV(z,Q?.callee),z}return K.value},ZV,tI=($)=>(Y,U,I)=>{let Q=I?{...I,async:!1}:{async:!1},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)throw new l5;return J.issues.length?{success:!1,error:new($??zG)(J.issues.map((K)=>R8(K,Q,a4())))}:{success:!0,data:J.value}},nE,eI=($)=>async(Y,U,I)=>{let Q=I?{...I,async:!0}:{async:!0},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((K)=>R8(K,Q,a4())))}:{success:!0,data:J.value}},dE,qV=($)=>(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return sI($)(Y,U,Q)},ox0,VV=($)=>(Y,U,I)=>{return sI($)(Y,U,I)},rx0,LV=($)=>async(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return aI($)(Y,U,Q)},sx0,FV=($)=>async(Y,U,I)=>{return aI($)(Y,U,I)},ax0,wV=($)=>(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return tI($)(Y,U,Q)},tx0,MV=($)=>(Y,U,I)=>{return tI($)(Y,U,I)},ex0,OV=($)=>async(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return eI($)(Y,U,Q)},$f0,NV=($)=>async(Y,U,I)=>{return eI($)(Y,U,I)},Yf0;var pE=m(()=>{CY();cE();$1();XV=sI(d8),ZV=aI(d8),nE=tI(d8),dE=eI(d8),ox0=qV(d8),rx0=VV(d8),sx0=LV(d8),ax0=FV(d8),tx0=wV(d8),ex0=MV(d8),$f0=OV(d8),Yf0=NV(d8)});var G$={};Z8(G$,{xid:()=>rE,uuid7:()=>Jf0,uuid6:()=>Qf0,uuid4:()=>If0,uuid:()=>_Y,uppercase:()=>Nj,unicodeEmail:()=>mr,undefined:()=>Mj,ulid:()=>oE,time:()=>Xj,string:()=>qj,sha512_hex:()=>Ef0,sha512_base64url:()=>Cf0,sha512_base64:()=>jf0,sha384_hex:()=>Af0,sha384_base64url:()=>Tf0,sha384_base64:()=>Pf0,sha256_hex:()=>Nf0,sha256_base64url:()=>Bf0,sha256_base64:()=>Df0,sha1_hex:()=>wf0,sha1_base64url:()=>Of0,sha1_base64:()=>Mf0,rfc5322Email:()=>zf0,number:()=>WG,null:()=>wj,nanoid:()=>aE,md5_hex:()=>Vf0,md5_base64url:()=>Ff0,md5_base64:()=>Lf0,mac:()=>Qj,lowercase:()=>Oj,ksuid:()=>sE,ipv6:()=>Ij,ipv4:()=>Uj,integer:()=>Lj,idnEmail:()=>Gf0,httpProtocol:()=>Gj,html5Email:()=>Kf0,hostname:()=>Xf0,hex:()=>qf0,guid:()=>eE,extendedDuration:()=>Uf0,emoji:()=>Yj,email:()=>$j,e164:()=>Hj,duration:()=>tE,domain:()=>Zf0,datetime:()=>Zj,date:()=>Wj,cuid2:()=>lE,cuid:()=>mE,cidrv6:()=>Kj,cidrv4:()=>Jj,browserEmail:()=>Hf0,boolean:()=>Fj,bigint:()=>Vj,base64url:()=>DV,base64:()=>zj});function Yj(){return new RegExp(Wf0,"u")}function or($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Xj($){return new RegExp(`^${or($)}$`)}function Zj($){let Y=or({precision:$.precision}),U=["Z"];if($.local)U.push("");if($.offset)U.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let I=`${Y}(?:${U.join("|")})`;return new RegExp(`^${lr}T(?:${I})$`)}function XG($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function ZG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var mE,lE,oE,rE,sE,aE,tE,Uf0,eE,_Y=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;returnnewRegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},If0,Qf0,Jf0,$j,Kf0,zf0,mr,Gf0,Hf0,Wf0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Uj,Ij,Qj=($)=>{letY=R$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},Jj,Kj,zj,DV,Xf0,Zf0,Gj,Hj,lr="(?:(?:\\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])))",Wj,qj=($)=>{letY=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${Y}$`)},Vj,Lj,WG,Fj,wj,Mj,Oj,Nj,qf0,Vf0,Lf0,Ff0,wf0,Mf0,Of0,Nf0,Df0,Bf0,Af0,Pf0,Tf0,Ef0,jf0,Cf0;varBV=m(()=>{$1();mE=/^[cC][0-9a-z]{6,}$/,lE=/^[0-9a-z]+$/,oE=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,rE=/^[0-9a-vA-V]{20}$/,sE=/^[A-Za-z0-9]{27}$/,aE=/^[a-zA-Z0-9_-]{21}$/,tE=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((J)=>J),I=Math.min(...U.map((J)=>J.length-J.trimStart().length)),Q=U.map((J)=>J.slice(I)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of Q)this.content.push(J)}compile(){let $=Function,Y=this?.args,I=[...(this?.content??[""]).map((Q)=>`${Q}`)];return new $(...Y,I.join(`
`))}}var uj;var bj=m(()=>{uj={major:4,minor:4,patch:3}});function GC($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function Zs($){if(!DV.test($))return!1;let Y=$.replace(/[-_]/g,(I)=>I==="-"?"+":"/"),U=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return GC(U)}function qs($,Y=null){try{let U=$.split(".");if(U.length!==3)return!1;let[I]=U;if(!I)return!1;let Q=JSON.parse(atob(I));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(Y&&(!("alg"in Q)||Q.alg!==Y))return!1;return!0}catch{return!1}}function tr($,Y,U){if($.issues.length)Y.issues.push(...n8(U,$.issues));Y.value[U]=$.value}function _V($,Y,U,I,Q,J){let K=U in I;if($.issues.length){if(Q&&J&&!K)return;Y.issues.push(...n8(U,$.issues))}if(!K&&!Q){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[U]});return}if($.value===void 0){if(K)Y.value[U]=void 0}else Y.value[U]=$.value}function Vs($){let Y=Object.keys($.shape);for(let I of Y)if(!$.shape?.[I]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${I}":expectedaZodschema`);let U=kE($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(U)}}function Ls($,Y,U,I,Q,J){let K=[],z=Q.keySet,G=Q.catchall._zod,H=G.def.type,W=G.optin==="optional",X=G.optout==="optional";for(let Z in Y){if(Z==="__proto__")continue;if(z.has(Z))continue;if(H==="never"){K.push(Z);continue}let q=G.run({value:Y[Z],issues:[]},I);if(q instanceof Promise)$.push(q.then((V)=>_V(V,U,Z,Y,W,X)));else _V(q,U,Z,Y,W,X)}if(K.length)U.issues.push({code:"unrecognized_keys",keys:K,input:Y,inst:J});if(!$.length)return U;return Promise.all($).then(()=>{return U})}function er($,Y,U,I){for(let J of $)if(J.issues.length===0)return Y.value=J.value,Y;let Q=$.filter((J)=>!F7(J));if(Q.length===1)return Y.value=Q[0].value,Q[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((J)=>J.issues.map((K)=>R8(K,I,a4())))}),Y}function $s($,Y,U,I){let Q=$.filter((J)=>J.issues.length===0);if(Q.length===1)return Y.value=Q[0].value,Y;if(Q.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((J)=>J.issues.map((K)=>R8(K,I,a4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:[],inclusive:!1});return Y}function ij($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(L7($)&&L7(Y)){let U=Object.keys(Y),I=Object.keys($).filter((J)=>U.indexOf(J)!==-1),Q={...$,...Y};for(let J of I){let K=ij($[J],Y[J]);if(!K.valid)return{valid:!1,mergeErrorPath:[J,...K.mergeErrorPath]};Q[J]=K.data}return{valid:!0,data:Q}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let I=0;I<$.length;I++){let Q=$[I],J=Y[I],K=ij(Q,J);if(!K.valid)return{valid:!1,mergeErrorPath:[I,...K.mergeErrorPath]};U.push(K.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function Ys($,Y,U){let I=new Map,Q;for(let z of Y.issues)if(z.code==="unrecognized_keys"){Q??(Q=z);for(let G of z.keys){if(!I.has(G))I.set(G,{});I.get(G).l=!0}}else $.issues.push(z);for(let z of U.issues)if(z.code==="unrecognized_keys")for(let G of z.keys){if(!I.has(G))I.set(G,{});I.get(G).r=!0}else $.issues.push(z);let J=[...I].filter(([,z])=>z.l&&z.r).map(([z])=>z);if(J.length&&Q)$.issues.push({...Q,keys:J});if(F7($))return $;let K=ij(Y.value,U.value);if(!K.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(K.mergeErrorPath)}`);return $.value=K.data,$}function Us($,Y){for(let U=$.length-1;U>=0;U--)if($[U]._zod[Y]!=="optional")return U+1;return 0}function Is($,Y,U){if($.issues.length)Y.issues.push(...n8(U,$.issues));Y.value[U]=$.value}function Qs($,Y,U,I,Q){for(let J=0;J<U.length;J++){let K=$[J],z=J<I.length;if(K.issues.length){if(!z&&J>=Q){Y.value.length=J;break}Y.issues.push(...n8(J,K.issues))}Y.value[J]=K.value}for(let J=Y.value.length-1;J>=I.length;J--)if(U[J]._zod.optout==="optional"&&Y.value[J]===void 0)Y.value.length=J;else break;return Y}function Js($,Y,U,I,Q,J,K){if($.issues.length)if(QG.has(typeof I))U.issues.push(...n8(I,$.issues));else U.issues.push({code:"invalid_key",origin:"map",input:Q,inst:J,issues:$.issues.map((z)=>R8(z,K,a4()))});if(Y.issues.length)if(QG.has(typeof I))U.issues.push(...n8(I,Y.issues));else U.issues.push({origin:"map",code:"invalid_element",input:Q,inst:J,key:I,issues:Y.issues.map((z)=>R8(z,K,a4()))});U.value.set($.value,Y.value)}function Ks($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function zs($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function Gs($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function Hs($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function jV($,Y,U){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa
Line truncated
@@ -60,94 +60,94 @@ import{createRequire as Ak0}from"node:module";var qk0=Object.create;var{getProto
newResult[${P}]=${D}.value;
}
`)}q.write("payload.value = newResult;"),q.write("return payload;");let N=q.compile();return(O,D)=>N(Z,O,D)},Q,J=CY,K=!TY.jitless,H=K&&jj.value,W=Y.catchall,X;$._zod.parse=(Z,q)=>{X??(X=z.value);let V=Z.value;if(!J(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(K&&H&&q?.async===!1&&q.jitless!==!0){if(!Q)Q=I(Y.shape);if(Z=Q(Z,q),!W)return Z;return $s([],V,Z,q,X,$)}return U(Z,q)}});XG=H0("$ZodUnion",($,Y)=>{V1.init($,Y),E1($._zod,"optin",()=>Y.options.some((z)=>z._zod.optin==="optional")?"optional":void 0),E1($._zod,"optout",()=>Y.options.some((z)=>z._zod.optout==="optional")?"optional":void 0),E1($._zod,"values",()=>{if(Y.options.every((z)=>z._zod.values))return new Set(Y.options.flatMap((z)=>Array.from(z._zod.values)));return}),E1($._zod,"pattern",()=>{if(Y.options.every((z)=>z._zod.pattern)){let z=Y.options.map((I)=>I._zod.pattern);return new RegExp(`^(${z.map((I)=>$G(I.source)).join("|")})$`)}return});let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,I)=>{if(U)return U(z,I);let Q=!1,J=[];for(let K of Y.options){let G=K._zod.run({value:z.value,issues:[]},I);if(G instanceof Promise)J.push(G),Q=!0;else{if(G.issues.length===0)return G;J.push(G)}}if(!Q)return fr(J,z,$,I);return Promise.all(J).then((K)=>{return fr(K,z,$,I)})}});OC=H0("$ZodXor",($,Y)=>{XG.init($,Y),Y.inclusive=!1;let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,I)=>{if(U)return U(z,I);let Q=!1,J=[];for(let K of Y.options){let G=K._zod.run({value:z.value,issues:[]},I);if(G instanceof Promise)J.push(G),Q=!0;else J.push(G)}if(!Q)return ur(J,z,$,I);return Promise.all(J).then((K)=>{return ur(K,z,$,I)})}}),NC=H0("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,XG.init($,Y);let U=$._zod.parse;E1($._zod,"propValues",()=>{let I={};for(let Q of Y.options){let J=Q._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(Q)}"`);for(let[K,G]of Object.entries(J)){if(!I[K])I[K]=new Set;for(let H of G)I[K].add(H)}}return I});let z=lz(()=>{let I=Y.options,Q=new Map;for(let J of I){let K=J._zod.propValues?.[Y.discriminator];if(!K||K.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(J)}"`);for(let G of K){if(Q.has(G))throw Error(`Duplicatediscriminatorvalue"${String(G)}"`);Q.set(G,J)}}return Q});$._zod.parse=(I,Q)=>{let J=I.value;if(!CY(J))return I.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),I;let K=z.value.get(J?.[Y.discriminator]);if(K)return K._zod.run(I,Q);if(Y.unionFallback||Q.direction==="backward")return U(I,Q);return I.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(z.value.keys()),input:J,path:[Y.discriminator],inst:$}),I}}),DC=H0("$ZodIntersection",($,Y)=>{V1.init($,Y),$._zod.parse=(U,z)=>{let I=U.value,Q=Y.left._zod.run({value:I,issues:[]},z),J=Y.right._zod.run({value:I,issues:[]},z);if(Q instanceof Promise||J instanceof Promise)return Promise.all([Q,J]).then(([G,H])=>{return br(U,G,H)});return br(U,Q,J)}});EV=H0("$ZodTuple",($,Y)=>{V1.init($,Y);let U=Y.items;$._zod.parse=(z,I)=>{let Q=z.value;if(!Array.isArray(Q))return z.issues.push({input:Q,inst:$,expected:"tuple",code:"invalid_type"}),z;z.value=[];let J=[],K=ir(U,"optin"),G=ir(U,"optout");if(!Y.rest){if(Q.length<K)return z.issues.push({code:"too_small",minimum:K,inclusive:!0,input:Q,inst:$,origin:"array"}),z;if(Q.length>U.length)z.issues.push({code:"too_big",maximum:U.length,inclusive:!0,input:Q,inst:$,origin:"array"})}let H=Array(U.length);for(let W=0;W<U.length;W++){let X=U[W]._zod.run({value:Q[W],issues:[]},I);if(X instanceof Promise)J.push(X.then((Z)=>{H[W]=Z}));else H[W]=X}if(Y.rest){let W=U.length-1,X=Q.slice(U.length);for(let Z of X){W++;let q=Y.rest._zod.run({value:Z,issues:[]},I);if(q instanceof Promise)J.push(q.then((V)=>cr(V,z,W)));else cr(q,z,W)}}if(J.length)return Promise.all(J).then(()=>nr(H,z,U,Q,G));return nr(H,z,U,Q,G)}});AC=H0("$ZodRecord",($,Y)=>{V1.init($,Y),$._zod.parse=(U,z)=>{let I=U.value;if(!Z7(I))return U.issues.push({expected:"record",code:"invalid_type",input:I,inst:$}),U;let Q=[],J=Y.keyType._zod.values;if(J){U.value={};let K=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){K.add(typeof H==="number"?H.toString():H);let W=Y.keyType._zod.run({value:H,issues:[]},z);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length){U.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((q)=>E8(q,z,s4())),input:H,path:[H],inst:$});continue}let X=W.value,Z=Y.valueType._zod.run({value:I[H],issues:[]},z);if(Z instanceof Promise)Q.push(Z.then((q)=>{if(q.issues.length)U.issues.push(...b8(H,q.issues));U.value[X]=q.value}));else{if(Z.issues.length)U.issues.push(...b8(H,Z.issues));U.value[X]=Z.value}}let G;for(let H in I)if(!K.has(H))G=G??[],G.push(H);if(G&&G.length>0)U.issues.push({code:"unrec
Line truncated
`)}q.write("payload.value = newResult;"),q.write("return payload;");let N=q.compile();return(O,D)=>N(Z,O,D)},J,K=RY,z=!EY.jitless,H=z&&hE.value,W=Y.catchall,X;$._zod.parse=(Z,q)=>{X??(X=I.value);let V=Z.value;if(!K(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(z&&H&&q?.async===!1&&q.jitless!==!0){if(!J)J=Q(Y.shape);if(Z=J(Z,q),!W)return Z;return Ls([],V,Z,q,X,$)}return U(Z,q)}});VG=H0("$ZodUnion",($,Y)=>{V1.init($,Y),j1($._zod,"optin",()=>Y.options.some((I)=>I._zod.optin==="optional")?"optional":void 0),j1($._zod,"optout",()=>Y.options.some((I)=>I._zod.optout==="optional")?"optional":void 0),j1($._zod,"values",()=>{if(Y.options.every((I)=>I._zod.values))return new Set(Y.options.flatMap((I)=>Array.from(I._zod.values)));return}),j1($._zod,"pattern",()=>{if(Y.options.every((I)=>I._zod.pattern)){let I=Y.options.map((Q)=>Q._zod.pattern);return new RegExp(`^(${I.map((Q)=>IG(Q.source)).join("|")})$`)}return});let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(I,Q)=>{if(U)return U(I,Q);let J=!1,K=[];for(let z of Y.options){let G=z._zod.run({value:I.value,issues:[]},Q);if(G instanceof Promise)K.push(G),J=!0;else{if(G.issues.length===0)return G;K.push(G)}}if(!J)return er(K,I,$,Q);return Promise.all(K).then((z)=>{return er(z,I,$,Q)})}});EC=H0("$ZodXor",($,Y)=>{VG.init($,Y),Y.inclusive=!1;let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(I,Q)=>{if(U)return U(I,Q);let J=!1,K=[];for(let z of Y.options){let G=z._zod.run({value:I.value,issues:[]},Q);if(G instanceof Promise)K.push(G),J=!0;else K.push(G)}if(!J)return $s(K,I,$,Q);return Promise.all(K).then((z)=>{return $s(z,I,$,Q)})}}),jC=H0("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,VG.init($,Y);let U=$._zod.parse;j1($._zod,"propValues",()=>{let Q={};for(let J of Y.options){let K=J._zod.propValues;if(!K||Object.keys(K).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(J)}"`);for(let[z,G]of Object.entries(K)){if(!Q[z])Q[z]=new Set;for(let H of G)Q[z].add(H)}}return Q});let I=oI(()=>{let Q=Y.options,J=new Map;for(let K of Q){let z=K._zod.propValues?.[Y.discriminator];if(!z||z.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(K)}"`);for(let G of z){if(J.has(G))throw Error(`Duplicatediscriminatorvalue"${String(G)}"`);J.set(G,K)}}return J});$._zod.parse=(Q,J)=>{let K=Q.value;if(!RY(K))return Q.issues.push({code:"invalid_type",expected:"object",input:K,inst:$}),Q;let z=I.value.get(K?.[Y.discriminator]);if(z)return z._zod.run(Q,J);if(Y.unionFallback||J.direction==="backward")return U(Q,J);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(I.value.keys()),input:K,path:[Y.discriminator],inst:$}),Q}}),CC=H0("$ZodIntersection",($,Y)=>{V1.init($,Y),$._zod.parse=(U,I)=>{let Q=U.value,J=Y.left._zod.run({value:Q,issues:[]},I),K=Y.right._zod.run({value:Q,issues:[]},I);if(J instanceof Promise||K instanceof Promise)return Promise.all([J,K]).then(([G,H])=>{return Ys(U,G,H)});return Ys(U,J,K)}});hV=H0("$ZodTuple",($,Y)=>{V1.init($,Y);let U=Y.items;$._zod.parse=(I,Q)=>{let J=I.value;if(!Array.isArray(J))return I.issues.push({input:J,inst:$,expected:"tuple",code:"invalid_type"}),I;I.value=[];let K=[],z=Us(U,"optin"),G=Us(U,"optout");if(!Y.rest){if(J.length<z)return I.issues.push({code:"too_small",minimum:z,inclusive:!0,input:J,inst:$,origin:"array"}),I;if(J.length>U.length)I.issues.push({code:"too_big",maximum:U.length,inclusive:!0,input:J,inst:$,origin:"array"})}let H=Array(U.length);for(let W=0;W<U.length;W++){let X=U[W]._zod.run({value:J[W],issues:[]},Q);if(X instanceof Promise)K.push(X.then((Z)=>{H[W]=Z}));else H[W]=X}if(Y.rest){let W=U.length-1,X=J.slice(U.length);for(let Z of X){W++;let q=Y.rest._zod.run({value:Z,issues:[]},Q);if(q instanceof Promise)K.push(q.then((V)=>Is(V,I,W)));else Is(q,I,W)}}if(K.length)return Promise.all(K).then(()=>Qs(H,I,U,J,G));return Qs(H,I,U,J,G)}});RC=H0("$ZodRecord",($,Y)=>{V1.init($,Y),$._zod.parse=(U,I)=>{let Q=U.value;if(!L7(Q))return U.issues.push({expected:"record",code:"invalid_type",input:Q,inst:$}),U;let J=[],K=Y.keyType._zod.values;if(K){U.value={};let z=new Set;for(let H of K)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){z.add(typeof H==="number"?H.toString():H);let W=Y.keyType._zod.run({value:H,issues:[]},I);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length){U.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((q)=>R8(q,I,a4())),input:H,path:[H],inst:$});continue}let X=W.value,Z=Y.valueType._zod.run({value:Q[H],issues:[]},I);if(Z instanceof Promise)J.push(Z.then((q)=>{if(q.issues.length)U.issues.push(...n8(H,q.issues));U.value[X]=q.value}));else{if(Z.issues.length)U.issues.push(...n8(H,Z.issues));U.value[X]=Z.value}}let G;for(let H in Q)if(!z.has(H))G=G??[],G.push(H);if(G&&G.length>0)U.issues.push({code:"unrec
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letJof$.seen.entries()){letK=J[1];if(Y===J[0]){Q(J);continue}if($.external){letH=$.external.registry.get(J[0])?.id;if(Y!==J[0]&&H){Q(J);continue}}if($.metadataRegistry.get(J[0])?.id){Q(J);continue}if(K.cycle){Q(J);continue}if(K.count>1){if($.reused==="ref"){Q(J);continue}}}}functionM7($,Y){letU=$.seen.get(Y);if(!U)throwError("Unprocessed schema. This is a bug in Zod.");letz=(K)=>{letG=$.seen.get(K);if(G.ref===null)return;letH=G.def??G.schema,W={...H},X=G.ref;if(G.ref=null,X){z(X);letq=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(V);elseObject.assign(H,V);if(Object.assign(H,W),K._zod.parent===X)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(!(MinW))deleteH[M]}if(V.$ref&&q.def)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(Minq.def&&JSON.stringify(H[M])===JSON.stringify(q.def[M]))deleteH[M]}}letZ=K._zod.parent;if(Z&&Z!==X){z(Z);letq=$.seen.get(Z);if(q?.schema.$ref){if(H.$ref=q.schema.$ref,q.def)for(letVinH){if(V==="$ref"||V==="allOf")continue;if(Vinq.def&&JSON.stringify(H[V])===JSON.stringify(q.def[V]))deleteH[V]}}}$.override({zodSchema:K,jsonSchema:H,path:G.path??[]})};for(letKof[...$.seen.entries()].reverse())z(K[0]);letI={};if($.target==="draft-2020-12")I.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")I.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")I.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letK=$.external.registry.get(Y)?.id;if(!K)throwError("Schema is missing an `id` property");I.$id=$.external.uri(K)}Object.assign(I,U.def??U.schema);letQ=$.metadataRegistry.get(Y)?.id;if(Q!==void0&&I.id===Q)deleteI.id;letJ=$.external?.defs??{};for(letKof$.seen.entries()){letG=K[1];if(G.def&&G.defId){if(G.def.id===G.defId)deleteG.def.id;J[G.defId]=G.def}}if($.external);elseif(Object.keys(J).length>0)if($.target==="draft-2020-12")I.$defs=J;elseI.definitions=J;try{letK=JSON.parse(JSON.stringify(I));returnObject.defineProperty(K,"~standard",{value:{...Y["~standard"],jsonSchema:{input:VI(Y,"input",$.processors),output:VI(Y,"output",$.processors)}},enumerable:!1,writable:!1}),K}catch(K){throwError("Error converting schema to JSON.")}}functionR8($,Y){letU=Y??{seen:newSet};if(U.seen.has($))return!1;U.seen.add($);letz=$._zod.def;if(z.type==="transform")return!0;if(z.type==="array")returnR8(z.element,U);if(z.type==="set")returnR8(z.valueType,U);if(z.type==="lazy")returnR8(z.getter(),U);if(z.type==="promise"||z.type==="optional"||z.type==="nonoptional"||z.type==="nullable"||z.type==="readonly"||z.type==="default"||z.type==="prefault")returnR8(z.innerType,U);if(z.type==="intersection")returnR8(z.left,U)||R8(z.right,U);if(z.type==="record"||z.type==="map")returnR8(z.keyType,U)||R8(z.valueType,U);if(z.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnR8(z.in,U)||R8(z.out,U)}if(z.type==="object"){for(letIinz.shape)if(R8(z.shape[I],U))return!0;return!1}if(z.type==="union"){for(letIofz.options)if(R8(I,U))return!0;return!1}if(z.type==="tuple"){for(letIofz.items)if(R8(I,U))return!0;if(z.rest&&R8(z.rest,U))return!0;return!1}return!1}varh_=($,Y={})=>(U)=>{letz=F7({...U,processors:Y});returnK4($,z),w7(z,$),M7(z,$)},VI=($,Y,U={})=>(z)=>{let{libraryOptions:I,target:Q}=z??{},J=F7({...I??{},target:Q,io:Y,processors:U});returnK4($,J),w7(J,$),M7(J,$)};varDG=m(()=>{MG()});functiongY($,Y){if("_idmap"in$){letz=$,I=F7({...Y,processors:UL}),Q={};for(letGofz._idmap.entries()){let[H,W]=G;K4(W,I)}letJ={},K={registry:z,uri:Y?.uri,defs:Q};I.external=K;for(letGofz._idmap.entries()){let[H,W]=G;w7(I,W),J[H]=M7(I,W)}if(Object.keys(Q).length>0){letG=I.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[G]:Q}}return{schemas:J}}letU=F7({...Y,processors:UL});returnK4($,U),w7(U,$),M7(U,$)}varJu0,S_=($,Y,U,z)=>{letI=U;I.type="string";let{minimum:Q,maximum:J,format:K,patterns:G,contentEncoding:H}=$._zod.bag;if(typeofQ==="number")I.minLength=Q;if(typeofJ==="number")I.maxLength=J;if(K){if(I.format=Ju0[K]??K,I.format==="")deleteI.format;if(K==="time")deleteI.format}if(H)I.contentEncoding=H;if(G&&G.size>0){letW=[...G];if(W.length===1)I.pattern=W[0].source;elseif(W.length>1)I.allOf=[...W.map((X)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:X.source}))]}},g_=($,Y,U,z)=>{letI=U,{minimum:Q,maximum:J,format:K,multipleOf:G,exclusiveMaximum:H,exclusiveMinimum:W}=$._zod.bag;if(typeofK==="string"&&K.includes("int"))I.type="integer";elseI.type="number";letX=typeofW==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),Z=typeofH==="number"&&H<=(J??Number.POSITIVE_INFINITY),q=Y.target==="draft-04"||Y.target==="openapi-3.0";if(X)if(q)I.minimum=W,I.exclusiveMinimum=!0;elseI.exclusiveMinimuLine truncated
`}function bb0($){let Y=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Toolnameexceedsmaximumlengthof128characters(current:${$.length})`]};if($.includes(" "))Y.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))Y.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))Y.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))Y.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!ub0.test($)){let U=[...$].filter((z)=>!/[A-Za-z0-9._-]/.test(z)).filter((z,I,Q)=>Q.indexOf(z)===I);return Y.push(`Toolnamecontainsinvalidcharacters:${U.map((z)=>`"${z}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function ib0($,Y){if(Y.length>0){console.warn(`Toolnamevalidationwarningfor"${$}":`);for(let U of Y)console.warn(`-${U}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function RS($){let Y=bb0($);return ib0($,Y.warnings),Y.isValid}function cb0($){return typeof $==="object"&&$!==null&&"_zod"in $}function nb0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function pb0($){if(typeof $!=="object"||$===null)return!1;if(xI($))return!1;let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return!1;return Object.values($).every((U)=>cb0(U))}function cw($){if($===void 0)return;if(pb0($))return U0($);if(typeof $==="object"&&$!==null&&!xI($)&&Object.values($).some((Y)=>nb0(Y)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!xI($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var zS,Au0,T1,L1,Bu0,ot="2026-07-28",v7,at,ju0,Eu0,Cu0,$e,Ye,_u0,jw,Cb1,Rb1,kt,XS,ku0,xu0,yI,i0,I1,yw,Ie,uI,kw,bu0=0,iu0="private",cu0,su0,Cw,LS,Ke,_b1,vb1,Ub0,zb0,FS,Rw,FH="2026-07-28",We,Jb0,P$=($)=>cG.safeParse($).success,h7=($)=>nG.safeParse($).success,VH=($)=>PI.safeParse($).success,bw=($)=>TI.safeParse($).success,Y3=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",it="x-mcp-header",Kb0,Gb0,Hb0,Wb0,hw=-32020,hb1,Xb0,ct=!1,QS="draft-2020-12",Vb0,Ob0,Nb0,nt,Db0,Eb0,qe=250,Cb0,Rb0,we,Me,_b0,vb0,Ne=60000,Sb0,gb0,yb0,De,TS,fb0,Sb1,Ae=10485760,ES=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??Ae}append($){if((this._buffer?.length??0)+$.length>this._maxBufferSize)throw this.clear(),Error(`ReadBufferexceededmaximumsizeof${this._maxBufferSize}bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){while(this._buffer){let $=this._buffer.indexOf(`
`);if($===-1)return null;let Y=this._buffer.toString("utf8",0,$).replace(/\r$/,"");this._buffer=this._buffer.subarray($+1);try{return Be(Y)}catch(U){if(U instanceof SyntaxError)continue;throw U}}return null}clear(){this._buffer=void 0}},ub0;var nw=m(()=>{Nj();Dj();St();Ah();zS=Symbol.for("mcp.sdk.errorBrands");Au0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](Y){return kI(this,Y)}static isInstance(Y){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return kI(this,Y)}constructor(Y,U,z){super(U);this.code=Y,this.errorUri=z,this.name="OAuthError",KS(this,new.target)}toResponseObject(){let Y={error:this.code,error_description:this.message};if(this.errorUri)Y.error_uri=this.errorUri;return Y}static fromResponse(Y){return new $(Y.error,Y.error_description??Y.error,Y.error_uri)}},T1=function($){return $.NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$}({}),L1=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return kI(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return kI(this,$)}constructor($,Y,U){super(Y);this.code=$,this.data=U,this.name="SdkError",KS(this,new.target)}},Bu0=class extends L1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,Y,U){super($,Y,U);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};v7=[ot];at=["task","inputRequests","requestState"];Eu0=new Set(["const","enum","default","examples"]),Cu0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);$e={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ye={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},_u0={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};Cb1=Object.keys($e),Rb1=Object.keys(Ye);kt={ok:!1,reason:"not-in-era"};XS={era:"2025-11-25",hasRequestMethod:Ue,hasNotificationMethod:ze,validateRequest:($,Y)=>Ew(Su0($),Y),validateResult:($,Y)=>Ew(hu0($),Y),validateNotification:($,Y)=>Ew(gu0($),Y),hasInputRequestMethod:()=>!1,validateInputRequest:()=>kt,validateInputResponse:()=>kt,samplingResultVariant:($,Y)=>{let U=tt();return Ew($?U.CreateMessageResultWithToolsSchema:U.CreateMessageResultSchema,Y)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,Y){let U=st($),z=U.structuredContent;if(z===void 0)return U;let I=typeof z!=="object"||z===null||Array.isArray(z),Q=Y!==void 0&&et(Y);if(!I&&!Q)return U;return{...U,structuredContent:{result:z}}},decodeResult($,Y){if(IS(Y)&&"resultType"in Y){let U={...Y};return delete U.resultType,{kind:"complete",result:ft(U)}}return{kind:"complete",result:ft(Y)}},encodeResult($,Y){if($!=="tools/list")return Y;l
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letKof$.seen.entries()){letz=K[1];if(Y===K[0]){J(K);continue}if($.external){letH=$.external.registry.get(K[0])?.id;if(Y!==K[0]&&H){J(K);continue}}if($.metadataRegistry.get(K[0])?.id){J(K);continue}if(z.cycle){J(K);continue}if(z.count>1){if($.reused==="ref"){J(K);continue}}}}functionD7($,Y){letU=$.seen.get(Y);if(!U)throwError("Unprocessed schema. This is a bug in Zod.");letI=(z)=>{letG=$.seen.get(z);if(G.ref===null)return;letH=G.def??G.schema,W={...H},X=G.ref;if(G.ref=null,X){I(X);letq=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(V);elseObject.assign(H,V);if(Object.assign(H,W),z._zod.parent===X)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(!(MinW))deleteH[M]}if(V.$ref&&q.def)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(Minq.def&&JSON.stringify(H[M])===JSON.stringify(q.def[M]))deleteH[M]}}letZ=z._zod.parent;if(Z&&Z!==X){I(Z);letq=$.seen.get(Z);if(q?.schema.$ref){if(H.$ref=q.schema.$ref,q.def)for(letVinH){if(V==="$ref"||V==="allOf")continue;if(Vinq.def&&JSON.stringify(H[V])===JSON.stringify(q.def[V]))deleteH[V]}}}$.override({zodSchema:z,jsonSchema:H,path:G.path??[]})};for(letzof[...$.seen.entries()].reverse())I(z[0]);letQ={};if($.target==="draft-2020-12")Q.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")Q.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")Q.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letz=$.external.registry.get(Y)?.id;if(!z)throwError("Schema is missing an `id` property");Q.$id=$.external.uri(z)}Object.assign(Q,U.def??U.schema);letJ=$.metadataRegistry.get(Y)?.id;if(J!==void0&&Q.id===J)deleteQ.id;letK=$.external?.defs??{};for(letzof$.seen.entries()){letG=z[1];if(G.def&&G.defId){if(G.def.id===G.defId)deleteG.def.id;K[G.defId]=G.def}}if($.external);elseif(Object.keys(K).length>0)if($.target==="draft-2020-12")Q.$defs=K;elseQ.definitions=K;try{letz=JSON.parse(JSON.stringify(Q));returnObject.defineProperty(z,"~standard",{value:{...Y["~standard"],jsonSchema:{input:LQ(Y,"input",$.processors),output:LQ(Y,"output",$.processors)}},enumerable:!1,writable:!1}),z}catch(z){throwError("Error converting schema to JSON.")}}functionv8($,Y){letU=Y??{seen:newSet};if(U.seen.has($))return!1;U.seen.add($);letI=$._zod.def;if(I.type==="transform")return!0;if(I.type==="array")returnv8(I.element,U);if(I.type==="set")returnv8(I.valueType,U);if(I.type==="lazy")returnv8(I.getter(),U);if(I.type==="promise"||I.type==="optional"||I.type==="nonoptional"||I.type==="nullable"||I.type==="readonly"||I.type==="default"||I.type==="prefault")returnv8(I.innerType,U);if(I.type==="intersection")returnv8(I.left,U)||v8(I.right,U);if(I.type==="record"||I.type==="map")returnv8(I.keyType,U)||v8(I.valueType,U);if(I.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnv8(I.in,U)||v8(I.out,U)}if(I.type==="object"){for(letQinI.shape)if(v8(I.shape[Q],U))return!0;return!1}if(I.type==="union"){for(letQofI.options)if(v8(Q,U))return!0;return!1}if(I.type==="tuple"){for(letQofI.items)if(v8(Q,U))return!0;if(I.rest&&v8(I.rest,U))return!0;return!1}return!1}varu_=($,Y={})=>(U)=>{letI=O7({...U,processors:Y});returnz4($,I),N7(I,$),D7(I,$)},LQ=($,Y,U={})=>(I)=>{let{libraryOptions:Q,target:J}=I??{},K=O7({...Q??{},target:J,io:Y,processors:U});returnz4($,K),N7(K,$),D7(K,$)};varPG=m(()=>{DG()});functionyY($,Y){if("_idmap"in$){letI=$,Q=O7({...Y,processors:GL}),J={};for(letGofI._idmap.entries()){let[H,W]=G;z4(W,Q)}letK={},z={registry:I,uri:Y?.uri,defs:J};Q.external=z;for(letGofI._idmap.entries()){let[H,W]=G;N7(Q,W),K[H]=D7(Q,W)}if(Object.keys(J).length>0){letG=Q.target==="draft-2020-12"?"$defs":"definitions";K.__shared={[G]:J}}return{schemas:K}}letU=O7({...Y,processors:GL});returnz4($,U),N7(U,$),D7(U,$)}varsu0,b_=($,Y,U,I)=>{letQ=U;Q.type="string";let{minimum:J,maximum:K,format:z,patterns:G,contentEncoding:H}=$._zod.bag;if(typeofJ==="number")Q.minLength=J;if(typeofK==="number")Q.maxLength=K;if(z){if(Q.format=su0[z]??z,Q.format==="")deleteQ.format;if(z==="time")deleteQ.format}if(H)Q.contentEncoding=H;if(G&&G.size>0){letW=[...G];if(W.length===1)Q.pattern=W[0].source;elseif(W.length>1)Q.allOf=[...W.map((X)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:X.source}))]}},i_=($,Y,U,I)=>{letQ=U,{minimum:J,maximum:K,format:z,multipleOf:G,exclusiveMaximum:H,exclusiveMinimum:W}=$._zod.bag;if(typeofz==="string"&&z.includes("int"))Q.type="integer";elseQ.type="number";letX=typeofW==="number"&&W>=(J??Number.NEGATIVE_INFINITY),Z=typeofH==="number"&&H<=(K??Number.POSITIVE_INFINITY),q=Y.target==="draft-04"||Y.target==="openapi-3.0";if(X)if(q)Q.minimum=W,Q.exclusiveMinimum=!0;elseQ.exclusiveMinimuLine truncated
`}function _i0($){let Y=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Toolnameexceedsmaximumlengthof128characters(current:${$.length})`]};if($.includes(" "))Y.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))Y.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))Y.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))Y.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Ri0.test($)){let U=[...$].filter((I)=>!/[A-Za-z0-9._-]/.test(I)).filter((I,Q,J)=>J.indexOf(I)===Q);return Y.push(`Toolnamecontainsinvalidcharacters:${U.map((I)=>`"${I}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function vi0($,Y){if(Y.length>0){console.warn(`Toolnamevalidationwarningfor"${$}":`);for(let U of Y)console.warn(`-${U}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function kh($){let Y=_i0($);return vi0($,Y.warnings),Y.isValid}function Si0($){return typeof $==="object"&&$!==null&&"_zod"in $}function hi0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function gi0($){if(typeof $!=="object"||$===null)return!1;if(fQ($))return!1;let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return!1;return Object.values($).every((U)=>Si0(U))}function ow($){if($===void 0)return;if(gi0($))return U0($);if(typeof $==="object"&&$!==null&&!fQ($)&&Object.values($).some((Y)=>hi0(Y)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!fQ($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var Wh,Zb0,T1,L1,qb0,He="2026-07-28",g7,Ze,Fb0,wb0,Mb0,Le,Fe,Nb0,Sw,li1,oi1,at,Mh,Eb0,jb0,kQ,i0,Q1,iw,Oe,bQ,cw,_b0=0,vb0="private",Sb0,bb0,gw,Bh,Be,ri1,si1,mb0,lb0,Ah,yw,OH="2026-07-28",Te,sb0,_$=($)=>pG.safeParse($).success,y7=($)=>mG.safeParse($).success,wH=($)=>TQ.safeParse($).success,mw=($)=>EQ.safeParse($).success,I3=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",Ue="x-mcp-header",ab0,tb0,eb0,$i0,fw=-32020,ai1,Yi0,Ie=!1,Zh="draft-2020-12",Qi0,Hi0,Wi0,Qe,Xi0,wi0,Ce=250,Mi0,Oi0,Se,he,Ni0,Di0,ye=60000,Ai0,Pi0,Ti0,ke,Sh,Ci0,ti1,xe=10485760,gh=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??xe}append($){if((this._buffer?.length??0)+$.length>this._maxBufferSize)throw this.clear(),Error(`ReadBufferexceededmaximumsizeof${this._maxBufferSize}bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){while(this._buffer){let $=this._buffer.indexOf(`
`);if($===-1)return null;let Y=this._buffer.toString("utf8",0,$).replace(/\r$/,"");this._buffer=this._buffer.subarray($+1);try{return fe(Y)}catch(U){if(U instanceof SyntaxError)continue;throw U}}return null}clear(){this._buffer=void 0}},Ri0;var rw=m(()=>{jE();CE();ot();RS();Wh=Symbol.for("mcp.sdk.errorBrands");Zb0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](Y){return xQ(this,Y)}static isInstance(Y){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return xQ(this,Y)}constructor(Y,U,I){super(U);this.code=Y,this.errorUri=I,this.name="OAuthError",Vh(this,new.target)}toResponseObject(){let Y={error:this.code,error_description:this.message};if(this.errorUri)Y.error_uri=this.errorUri;return Y}static fromResponse(Y){return new $(Y.error,Y.error_description??Y.error,Y.error_uri)}},T1=function($){return $.NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$}({}),L1=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return xQ(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return xQ(this,$)}constructor($,Y,U){super(Y);this.code=$,this.data=U,this.name="SdkError",Vh(this,new.target)}},qb0=class extends L1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,Y,U){super($,Y,U);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};g7=[He];Ze=["task","inputRequests","requestState"];wb0=new Set(["const","enum","default","examples"]),Mb0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);Le={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Fe={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Nb0={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};li1=Object.keys(Le),oi1=Object.keys(Fe);at={ok:!1,reason:"not-in-era"};Mh={era:"2025-11-25",hasRequestMethod:we,hasNotificationMethod:Me,validateRequest:($,Y)=>hw(Ab0($),Y),validateResult:($,Y)=>hw(Bb0($),Y),validateNotification:($,Y)=>hw(Pb0($),Y),hasInputRequestMethod:()=>!1,validateInputRequest:()=>at,validateInputResponse:()=>at,samplingResultVariant:($,Y)=>{let U=qe();return hw($?U.CreateMessageResultWithToolsSchema:U.CreateMessageResultSchema,Y)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,Y){let U=Xe($),I=U.structuredContent;if(I===void 0)return U;let Q=typeof I!=="object"||I===null||Array.isArray(I),J=Y!==void 0&&Ve(Y);if(!Q&&!J)return U;return{...U,structuredContent:{result:I}}},decodeResult($,Y){if(Xh(Y)&&"resultType"in Y){let U={...Y};return delete U.resultType,{kind:"complete",result:et(U)}}return{kind:"complete",result:et(Y)}},encodeResult($,Y){if($!=="tools/list")return Y;l
Line truncated
*content-type
*Copyright(c)2015DouglasChristopherWilson
*MITLicensed
*/fb0=E0(($)=>{var Y=/;*([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,U=/\\([\u000b\u0020-\u00ff])/g,z=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;$.parse=I;function I(K){if(!K)throw TypeError("argument string is required");var G=typeof K==="object"?Q(K):K;if(typeof G!=="string")throw TypeError("argument string is required to be a string");var H=G.indexOf(";"),W=H!==-1?G.slice(0,H).trim():G.trim();if(!z.test(W))throw TypeError("invalid media type");var X=new J(W.toLowerCase());if(H!==-1){var Z,q,V;Y.lastIndex=H;while(q=Y.exec(G)){if(q.index!==H)throw TypeError("invalid parameter format");if(H+=q[0].length,Z=q[1].toLowerCase(),V=q[2],V.charCodeAt(0)===34){if(V=V.slice(1,-1),V.indexOf("\\")!==-1)V=V.replace(U,"$1")}X.parameters[Z]=V}if(H!==G.length)throw TypeError("invalid parameter format")}return X}function Q(K){var G;if(typeof K.getHeader==="function")G=K.getHeader("content-type");else if(typeof K.headers==="object")G=K.headers&&K.headers["content-type"];if(typeof G!=="string")throw TypeError("content-type header is missing from object");return G}function J(K){this.parameters=Object.create(null),this.type=K}}),Sb1=UV(fb0(),1);ub0=/^[A-Za-z0-9._-]{1,128}$/});function _S($){let Y=new $({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Jc0(Y),Y}var pw,Pe,F1,v1,K5,mw,db0,Te,je,dw,mb0,G5,lb0,ob0,Ee,rb0,lw,bI,MH,iI,ow,sb0,Ce,ab0,tb0,eb0,vS,$i0,hS,Re,Yi0,Ui0,zi0,Ii0,Qi0,Ji0,Ki0,Gi0,SS,Hi0,Wi0,Xi0,_e,ve,he,Zi0,qi0,Vi0,gS,Li0,Se,Fi0,wi0,Mi0,Oi0,Ni0,Di0,Ai0,Bi0,ge,Pi0,ye,ke,xe,Ti0,yS,ji0,fe,ue,be,Ei0,Ci0,ie,Ri0,_i0,vi0,ce,hi0,Si0,ne,gi0,yi0,ki0,xi0,fi0,ui0,bi0,ii0,ci0,ni0,pi0,di0,mi0,li0,oi0,ri0,si0,ai0,ti0,ei0,$c0,Yc0,Uc0,pe,zc0,Ic0,Qc0,Jc0,rw=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor($){this._userAjv=$!==void 0,this._ajv=$}get ajv(){return this._ajv??=_S(Ic0.Ajv2020)}_engineFor($){if(this._userAjv)return this.ajv;let Y=Br($,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");if(Y==="2020-12")return this.ajv;if(Y==="2019-09")return this._ajv2019??=_S(zc0.Ajv2019);return this._ajvDraft7??=_S(pe.Ajv)}getValidator($){let Y=this._engineFor($),U="$id"in $&&typeof $.$id==="string"?Y.getSchema($.$id)??Y.compile($):Y.compile($);return(z)=>{return U(z)?{valid:!0,data:z,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:Y.errorsText(U.errors)}}}},db1;var de=m(()=>{Nj();Dj();pw=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.regexpCode=$.getEsmExportName=$.getProperty=$.safeStringify=$.stringify=$.strConcat=$.addCodeArg=$.str=$._=$.nil=$._Code=$.Name=$.IDENTIFIER=$._CodeOrName=void 0;var Y=class{};$._CodeOrName=Y,$.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var U=class extends Y{constructor(F){super();if(!$.IDENTIFIER.test(F))throw Error("CodeGen: name must be a valid identifier");this.str=F}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};$.Name=U;var z=class extends Y{constructor(F){super();this._items=typeof F==="string"?[F]:F}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let F=this._items[0];return F===""||F==='""'}get str(){var F;return(F=this._str)!==null&&F!==void 0?F:this._str=this._items.reduce((N,O)=>`${N}${O}`,"")}get names(){var F;return(F=this._names)!==null&&F!==void 0?F:this._names=this._items.reduce((N,O)=>{if(O instanceof U)N[O.str]=(N[O.str]||0)+1;return N},{})}};$._Code=z,$.nil=new z("");function I(F,...N){let O=[F[0]],D=0;while(D<N.length)K(O,N[D]),O.push(F[++D]);return new z(O)}$._=I;let Q=new z("+");function J(F,...N){let O=[q(F[0])],D=0;while(D<N.length)O.push(Q),K(O,N[D]),O.push(Q,q(F[++D]));return G(O),new z(O)}$.str=J;function K(F,N){if(N instanceof z)F.push(...N._items);else if(N instanceof U)F.push(N);else F.push(X(N))}$.addCodeArg=K;function G(F){let N=1;while(N<F.length-1){if(F[N]===Q){let O=H(F[N-1],F[N+1]);if(O!==void 0){F.splice(N-1,3,O);continue}F[N++]="+"}N++}}function H(F,N){if(N==='""')return F;if(F==='""')return N;if(typeof F=="string"){if(N instanceof U||F[F.length-1]!=='"')return;if(typeof N!="string")return`${F.slice(0,-1)}${N}"`;if(N[0]==='"')return F.slice(0,-1)+N.slice(1);return}if(typeof N=="string"&&N[0]==='"'&&!(F instanceof U))return`"${F}${N.slice(1)}`}function W(F,N){return N.emptyStr()?F:F.emptyStr()?N:J`${F}${N}`}$.strConcat=W;function X(F){return typeof F=="number"||typeof F=="boolean"||F===null?F:q(Array.isArray(F)?F.join(","):F)}function Z(F){return new z(q(F))}$.stringify=Z;function q(F){return JSON.stringify(F).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$.safeStringify=q;function V(F){return typeof F=="string"&&$.IDENTIFIER.test(F)?new z(`.${F}`):I`[${F}]`}$.getProperty=V;function w(F){if(typeof F=="string"&&$.IDENTIFIER.test(F))returnnewz(`${F}`);throwError(`CodeGen: invalid export name: ${F}, use explicit $id name mapping`)}$.getEsmExportName=w;functionM(F){returnnewz(F.toStringLine truncated
deps:${W}}`};let I={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[H,W]=Q(G);J(G,H),K(G,W)}};function Q({schema:G}){let H={},W={};for(let X in G){if(X==="__proto__")continue;let Z=Array.isArray(G[X])?H:W;Z[X]=G[X]}return[H,W]}function J(G,H=G.schema){let{gen:W,data:X,it:Z}=G;if(Object.keys(H).length===0)return;let q=W.let("missing");for(let V in H){let w=H[V];if(w.length===0)continue;let M=(0,z.propertyInData)(W,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:w.length,deps:w.join(", ")}),Z.allErrors)W.if(M,()=>{for(let F of w)(0,z.checkReportMissingProp)(G,F)});else W.if(Y._`${M}&&(${(0,z.checkMissingProp)(G,w,q)})`),(0,z.reportMissingProp)(G,q),W.else()}}$.validatePropertyDeps=J;function K(G,H=G.schema){let{gen:W,data:X,keyword:Z,it:q}=G,V=W.name("valid");for(let w in H){if((0,U.alwaysValidSchema)(q,H[w]))continue;W.if((0,z.propertyInData)(W,X,w,q.opts.ownProperties),()=>{let M=G.subschema({keyword:Z,schemaProp:w},V);G.mergeValidEvaluated(M,V)},()=>W.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=K,$.default=I}),Li0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=F1(),U=v1(),z={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:I})=>Y._`{propertyName:${I.propertyName}}`},code(I){let{gen:Q,schema:J,data:K,it:G}=I;if((0,U.alwaysValidSchema)(G,J))return;let H=Q.name("valid");Q.forIn("key",K,(W)=>{I.setParams({propertyName:W}),I.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},H),Q.if((0,Y.not)(H),()=>{if(I.error(!0),!G.allErrors)Q.break()})}),I.ok(H)}};$.default=z}),Se=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=G5(),U=F1(),z=K5(),I=v1(),Q={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:J})=>U._`{additionalProperty:${J.additionalProperty}}`},code(J){let{gen:K,schema:G,parentSchema:H,data:W,errsCount:X,it:Z}=J;if(!X)throw Error("ajv implementation error");let{allErrors:q,opts:V}=Z;if(Z.props=!0,V.removeAdditional!=="all"&&(0,I.alwaysValidSchema)(Z,G))return;let w=(0,Y.allSchemaProperties)(H.properties),M=(0,Y.allSchemaProperties)(H.patternProperties);F(),J.ok(U._`${X}===${z.default.errors}`);function F(){K.forIn("key",W,(T)=>{if(!w.length&&!M.length)D(T);else K.if(N(T),()=>D(T))})}function N(T){let A;if(w.length>8){let j=(0,I.schemaRefOrVal)(Z,H.properties,"properties");A=(0,Y.isOwnProperty)(K,j,T)}else if(w.length)A=(0,U.or)(...w.map((j)=>U._`${T}===${j}`));else A=U.nil;if(M.length)A=(0,U.or)(A,...M.map((j)=>U._`${(0,Y.usePattern)(J,j)}.test(${T})`));return(0,U.not)(A)}function O(T){K.code(U._`delete${W}[${T}]`)}function D(T){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){O(T);return}if(G===!1){if(J.setParams({additionalProperty:T}),J.error(),!q)K.break();return}if(typeof G=="object"&&!(0,I.alwaysValidSchema)(Z,G)){let A=K.name("valid");if(V.removeAdditional==="failing")P(T,A,!1),K.if((0,U.not)(A),()=>{J.reset(),O(T)});else if(P(T,A),!q)K.if((0,U.not)(A),()=>K.break())}}function P(T,A,j){let C={keyword:"additionalProperties",dataProp:T,dataPropType:I.Type.Str};if(j===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});J.subschema(C,A)}}};$.default=Q}),Fi0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=bI(),U=G5(),z=v1(),I=Se(),Q={keyword:"properties",type:"object",schemaType:"object",code(J){let{gen:K,schema:G,parentSchema:H,data:W,it:X}=J;if(X.opts.removeAdditional==="all"&&H.additionalProperties===void 0)I.default.code(new Y.KeywordCxt(X,I.default,"additionalProperties"));let Z=(0,U.allSchemaProperties)(G);for(let F of Z)X.definedProperties.add(F);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=z.mergeEvaluated.props(K,(0,z.toHash)(Z),X.props);let q=Z.filter((F)=>!(0,z.alwaysValidSchema)(X,G[F]));if(q.length===0)return;let V=K.name("valid");for(let F of q){if(w(F))M(F);else{if(K.if((0,U.propertyInData)(K,W,F,X.opts.ownProperties)),M(F),!X.allErrors)K.else().var(V,!0);K.endIf()}J.it.definedProperties.add(F),J.ok(V)}function w(F){return X.opts.useDefaults&&!X.compositeRule&&G[F].default!==void 0}function M(F){J.subschema({keyword:"properties",schemaProp:F,dataProp:F},V)}}};$.default=Q}),wi0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=G5(),U=F1(),z=v1(),I=v1(),Q={keyword:"patternProperties",type:"object",schemaType:"object",code(J){let{gen:K,schema:G,data:H,parentSchema:W,it:X}=J,{opts:Z}=X,q=(0,Y.allSchemaProperties)(G),V=q.filter((P)=>(0,z.alwaysValidSchema)(X,G[P]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let w=Z.strictSchema&&!Z.allowMatchingProperties&&W.properties,M=K.name("valid");if(X.props!==!0&&!(X.props instanceof U.Name))X.props=(0,I.evaluatedPropsToName)(K,X.props);let{props:F}=X;N();function N(){for(let P of q){if(w)O(P);if(X.allErrors)
Line truncated
`)}openNode($,Y){let U=this.tos,z=this._xml;if(U&&this.open)z.push(">");this._stack.push($),z.push("<"),z.push($),ok(z,Y),this.leaf=!0,this.open=!0}addAttribute($,Y){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(Y!==void 0)L70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");ok(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(V70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),Y=this._xml;if(this.leaf)Y.push("/>");else Y.push("</"),Y.push($),Y.push(">");this.open=!1,this.leaf=!1}leafNode($,Y,U){if(this.openNode($,Y),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}rk.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};F70.exports=rk});var sk=E((Ae0)=>{var w70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function De0($){if(typeof $==="string")return $;if(w70)return w70.decode($);return $.toString()}Ae0.bufferToString=De0});var A70=E((O70)=>{Object.defineProperty(O70,"__esModule",{value:!0});O70.CHAR=`
`,$=this.i;break;case c01:{let{entityReturnState:U}=this,z=this.entity+Y.slice($,this.prevI);this.state=U;let I;if(z==="")this.fail("empty entity name."),I="&;";else I=this.parseEntity(z),this.entity="";if(U!==h8||this.textHandler!==void 0)this.text+=I;break $}case x4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(gW($))this.state=x01,this.unget(),this.xmlDeclPossible=!1;else switch($){case KN:this.state=b01,this.xmlDeclPossible=!1;break;case d70:this.state=E01,this.openWakaBang="",this.xmlDeclPossible=!1;break;case s6:this.state=h01;break;default:this.fail("disallowed character in tag name"),this.state=h8,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=Jx,this.openWakaBang="";break;case"--":this.state=Qx,this.openWakaBang="";break;case"DOCTYPE":if(this.state=Ux,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar(JN))this.state=C01}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===JN)this.state=R01,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=Qx}sCommentEnded(){let $=this.getCodeNorm();if($!==T6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Qx;else this.state=h8}sCData(){if(this.captureToChar(hQ))this.state=_01}sCDataEnding(){let $=this.getCodeNorm();if($===hQ)this.state=v01;else this.text+=`]${String.fromCodePoint($)}`,this.state=Jx}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case T6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=h8;break}case hQ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=Jx}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=f70;else if($===s6||m8($))this.fail("processing instruction without a target."),this.state=$===s6?QN:Kx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=f70}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let U=this.getCodeNorm();if(U===x4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(Y,this.prevI);let z=U===s6;if(z||m8(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=z?qU:u70}else this.state=z?QN:Kx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===s6)this.state=QN;else if(!m8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(s6))this.state=QN}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===T6){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=h8}else if(Y===s6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=Kx;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===s6){this.state=qU;return}if($!==x4)this.state=S01,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(d01);if($===s6){this.state=qU,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(m8($)||$===vQ))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expectedthename${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expectedoneof${this.xmlDeclExpects.join(", ")}`)}this.state=$===vQ?b70:g01}sXMLDeclEq(){let $=this.getCodeNorm();if($===s6){this.state=qU,this.fail("XML declaration is incomplete.");return}if(m8($))return;if($!==vQ)this.fail("value required.");this.state=b70}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===s6){this.state=qU,this.fail("XML declaration is incomplete.");return}if(m8($))return;if(!GN($))this.fail("value must be quoted."),this.q=p70;else this.q=$;this.state=y01}sXMLDeclValue(){let $=this.captureTo([this.q,s6]);if($===s6){this.state=qU,this.text="",this.fail("XML declaration is incomplete.");return}if($===x4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=Y;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("ver
Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(Y)}set headers($){this._headers=$}shouldQuote($,Y){let U=Y?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(A71.default(U))return U;if(Array.isArray(U))return U[$];if(this._headers!==null)return U[this._headers[$]];return!1}format($,Y,U){let z=`${B71.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:I}=this;if(I.quote!==""){if(z.indexOf(I.quote)!==-1)return this.quoteField(z.replace(this.REPLACE_REGEXP,I.escapedQuote))}if(z.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(Y,U))return this.quoteField(z);return z}quoteField($){let{quote:Y}=this.formatterOptions;return`${Y}${$}${Y}`}}lQ.FieldFormatter=_K0});var nf=E((vK0)=>{Object.defineProperty(vK0,"__esModule",{value:!0});vK0.isSyncTransform=void 0;vK0.isSyncTransform=($)=>$.length===1});var gK0=E((oQ)=>{var SK0=oQ&&oQ.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(oQ,"__esModule",{value:!0});oQ.RowFormatter=void 0;var T71=SK0(cN()),j71=SK0(DK0()),E71=cf(),C71=nf();class jU{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new E71.FieldFormatter($),this.headers=$.headers,this.shouldWriteHeaders=$.shouldWriteHeaders,this.hasWrittenHeaders=!1,this.headers!==null)this.fieldFormatter.headers=this.headers;if($.transform)this.rowTransform=$.transform}static isRowHashArray($){if(Array.isArray($))return Array.isArray($[0])&&$[0].length===2;return!1}static isRowArray($){return Array.isArray($)&&!this.isRowHashArray($)}static gatherHeaders($){if(jU.isRowHashArray($))return $.map((Y)=>Y[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(C71.isSyncTransform($))return(Y,U)=>{let z=null;try{z=$(Y)}catch(I){return U(I)}return U(null,z)};return(Y,U)=>{$(Y,U)}}set rowTransform($){if(!T71.default($))throw TypeError("The transform should be a function");this._rowTransform=jU.createTransform($)}format($,Y){this.callTransformer($,(U,z)=>{if(U)return Y(U);if(!$)return Y(null);let I=[];if(z){let{shouldFormatColumns:Q,headers:J}=this.checkHeaders(z);if(this.shouldWriteHeaders&&J&&!this.hasWrittenHeaders)I.push(this.formatColumns(J,!0)),this.hasWrittenHeaders=!0;if(Q){let K=this.gatherColumns(z);I.push(this.formatColumns(K,!1))}}return Y(null,I)})}finish($){let Y=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));Y.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)Y.push(this.formatterOptions.rowDelimiter);return $(null,Y)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let Y=jU.gatherHeaders($);if(this.headers=Y,this.fieldFormatter.headers=Y,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!j71.default(Y,$),headers:Y}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((Y)=>$[Y]);if(jU.isRowHashArray($))return this.headers.map((Y,U)=>{let z=$[U];if(z)return z[1];return""});if(jU.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((Y,U)=>$[U])}callTransformer($,Y){if(!this._rowTransform)return Y(null,$);return this._rowTransform($,Y)}formatColumns($,Y){let U=$.map((I,Q)=>this.fieldFormatter.format(I,Q,Y)).join(this.formatterOptions.delimiter),{rowCount:z}=this;if(this.rowCount+=1,z)return[this.formatterOptions.rowDelimiter,U].join("");return U}}oQ.RowFormatter=jU});var yK0=E((YD)=>{Object.defineProperty(YD,"__esModule",{value:!0});YD.FieldFormatter=YD.RowFormatter=void 0;var R71=gK0();Object.defineProperty(YD,"RowFormatter",{enumerable:!0,get:function(){return R71.RowFormatter}});var _71=cf();Object.defineProperty(YD,"FieldFormatter",{enumerable:!0,get:function(){return _71.FieldFormatter}})});var pf=E((xK0)=>{Object.defineProperty(xK0,"__esModule",{value:!0});xK0.CsvFormatterStream=void 0;var h71=J0("stream"),S71=yK0();class kK0 extends h71.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new S71.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,Y,U){let z=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(I,Q)=>{if(I)return z=!0,U(I);if(Q)Q.forEach((J)=>{this.push(Buffer.from(J,"utf8"))});return z=!0,U()})}catch(I){if(z)throw I;U(I)}}_flush($){this.rowFormatter.finish((Y,U)=>{if(Y)return $(Y);if(U)U.forEach((z)=>{this.push(Buffer.from(z,"utf8"))});return $()})}}xK0.CsvFormatterStream=kK0});var bK0=E((a1)=>{var uK0=a1&&a1.__createBinding||(Object.create?function($,Y,U,z){if(z===void 0)z=U;Object.defineProperty($,z,{enumerable:!0,get:function(){return Y[U]}})}:function($,Y,U,z){if(z===void 0)z=U;$[z]=Y[U]}),g71=a1&&a1.__setModuleDefault||(Object.create?function($,Y){O
Line truncated
deps:${W}}`};let Q={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[H,W]=J(G);K(G,H),z(G,W)}};function J({schema:G}){let H={},W={};for(let X in G){if(X==="__proto__")continue;let Z=Array.isArray(G[X])?H:W;Z[X]=G[X]}return[H,W]}function K(G,H=G.schema){let{gen:W,data:X,it:Z}=G;if(Object.keys(H).length===0)return;let q=W.let("missing");for(let V in H){let w=H[V];if(w.length===0)continue;let M=(0,I.propertyInData)(W,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:w.length,deps:w.join(", ")}),Z.allErrors)W.if(M,()=>{for(let F of w)(0,I.checkReportMissingProp)(G,F)});else W.if(Y._`${M}&&(${(0,I.checkMissingProp)(G,w,q)})`),(0,I.reportMissingProp)(G,q),W.else()}}$.validatePropertyDeps=K;function z(G,H=G.schema){let{gen:W,data:X,keyword:Z,it:q}=G,V=W.name("valid");for(let w in H){if((0,U.alwaysValidSchema)(q,H[w]))continue;W.if((0,I.propertyInData)(W,X,w,q.opts.ownProperties),()=>{let M=G.subschema({keyword:Z,schemaProp:w},V);G.mergeValidEvaluated(M,V)},()=>W.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=z,$.default=Q}),Jc0=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=F1(),U=v1(),I={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:Q})=>Y._`{propertyName:${Q.propertyName}}`},code(Q){let{gen:J,schema:K,data:z,it:G}=Q;if((0,U.alwaysValidSchema)(G,K))return;let H=J.name("valid");J.forIn("key",z,(W)=>{Q.setParams({propertyName:W}),Q.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},H),J.if((0,Y.not)(H),()=>{if(Q.error(!0),!G.allErrors)J.break()})}),Q.ok(H)}};$.default=I}),oe=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=Z5(),U=F1(),I=X5(),Q=v1(),J={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:K})=>U._`{additionalProperty:${K.additionalProperty}}`},code(K){let{gen:z,schema:G,parentSchema:H,data:W,errsCount:X,it:Z}=K;if(!X)throw Error("ajv implementation error");let{allErrors:q,opts:V}=Z;if(Z.props=!0,V.removeAdditional!=="all"&&(0,Q.alwaysValidSchema)(Z,G))return;let w=(0,Y.allSchemaProperties)(H.properties),M=(0,Y.allSchemaProperties)(H.patternProperties);F(),K.ok(U._`${X}===${I.default.errors}`);function F(){z.forIn("key",W,(T)=>{if(!w.length&&!M.length)D(T);else z.if(N(T),()=>D(T))})}function N(T){let B;if(w.length>8){let E=(0,Q.schemaRefOrVal)(Z,H.properties,"properties");B=(0,Y.isOwnProperty)(z,E,T)}else if(w.length)B=(0,U.or)(...w.map((E)=>U._`${T}===${E}`));else B=U.nil;if(M.length)B=(0,U.or)(B,...M.map((E)=>U._`${(0,Y.usePattern)(K,E)}.test(${T})`));return(0,U.not)(B)}function O(T){z.code(U._`delete${W}[${T}]`)}function D(T){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){O(T);return}if(G===!1){if(K.setParams({additionalProperty:T}),K.error(),!q)z.break();return}if(typeof G=="object"&&!(0,Q.alwaysValidSchema)(Z,G)){let B=z.name("valid");if(V.removeAdditional==="failing")P(T,B,!1),z.if((0,U.not)(B),()=>{K.reset(),O(T)});else if(P(T,B),!q)z.if((0,U.not)(B),()=>z.break())}}function P(T,B,E){let C={keyword:"additionalProperties",dataProp:T,dataPropType:Q.Type.Str};if(E===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});K.subschema(C,B)}}};$.default=J}),Kc0=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=iQ(),U=Z5(),I=v1(),Q=oe(),J={keyword:"properties",type:"object",schemaType:"object",code(K){let{gen:z,schema:G,parentSchema:H,data:W,it:X}=K;if(X.opts.removeAdditional==="all"&&H.additionalProperties===void 0)Q.default.code(new Y.KeywordCxt(X,Q.default,"additionalProperties"));let Z=(0,U.allSchemaProperties)(G);for(let F of Z)X.definedProperties.add(F);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=I.mergeEvaluated.props(z,(0,I.toHash)(Z),X.props);let q=Z.filter((F)=>!(0,I.alwaysValidSchema)(X,G[F]));if(q.length===0)return;let V=z.name("valid");for(let F of q){if(w(F))M(F);else{if(z.if((0,U.propertyInData)(z,W,F,X.opts.ownProperties)),M(F),!X.allErrors)z.else().var(V,!0);z.endIf()}K.it.definedProperties.add(F),K.ok(V)}function w(F){return X.opts.useDefaults&&!X.compositeRule&&G[F].default!==void 0}function M(F){K.subschema({keyword:"properties",schemaProp:F,dataProp:F},V)}}};$.default=J}),zc0=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=Z5(),U=F1(),I=v1(),Q=v1(),J={keyword:"patternProperties",type:"object",schemaType:"object",code(K){let{gen:z,schema:G,data:H,parentSchema:W,it:X}=K,{opts:Z}=X,q=(0,Y.allSchemaProperties)(G),V=q.filter((P)=>(0,I.alwaysValidSchema)(X,G[P]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let w=Z.strictSchema&&!Z.allowMatchingProperties&&W.properties,M=z.name("valid");if(X.props!==!0&&!(X.props instanceof U.Name))X.props=(0,Q.evaluatedPropsToName)(z,X.props);let{props:F}=X;N();function N(){for(let P of q){if(w)O(P);if(X.allErrors)
Line truncated
`)}openNode($,Y){let U=this.tos,I=this._xml;if(U&&this.open)I.push(">");this._stack.push($),I.push("<"),I.push($),ek(I,Y),this.leaf=!0,this.open=!0}addAttribute($,Y){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(Y!==void 0)_70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");ek(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(R70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),Y=this._xml;if(this.leaf)Y.push("/>");else Y.push("</"),Y.push($),Y.push(">");this.open=!1,this.leaf=!1}leafNode($,Y,U){if(this.openNode($,Y),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}$x.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};v70.exports=$x});var Yx=j((Z01)=>{var S70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function X01($){if(typeof $==="string")return $;if(S70)return S70.decode($);return $.toString()}Z01.bufferToString=X01});var x70=j((g70)=>{Object.defineProperty(g70,"__esModule",{value:!0});g70.CHAR=`
`,$=this.i;break;case S11:{let{entityReturnState:U}=this,I=this.entity+Y.slice($,this.prevI);this.state=U;let Q;if(I==="")this.fail("empty entity name."),Q="&;";else Q=this.parseEntity(I),this.entity="";if(U!==y8||this.textHandler!==void 0)this.text+=Q;break $}case u4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(xW($))this.state=j11,this.unget(),this.xmlDeclPossible=!1;else switch($){case LN:this.state=_11,this.xmlDeclPossible=!1;break;case K20:this.state=w11,this.openWakaBang="",this.xmlDeclPossible=!1;break;case t6:this.state=B11;break;default:this.fail("disallowed character in tag name"),this.state=y8,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=Xx,this.openWakaBang="";break;case"--":this.state=Wx,this.openWakaBang="";break;case"DOCTYPE":if(this.state=zx,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar(VN))this.state=M11}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===VN)this.state=O11,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=Wx}sCommentEnded(){let $=this.getCodeNorm();if($!==j6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Wx;else this.state=y8}sCData(){if(this.captureToChar(hJ))this.state=N11}sCDataEnding(){let $=this.getCodeNorm();if($===hJ)this.state=D11;else this.text+=`]${String.fromCodePoint($)}`,this.state=Xx}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case j6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=y8;break}case hJ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=Xx}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=e70;else if($===t6||r8($))this.fail("processing instruction without a target."),this.state=$===t6?qN:Zx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=e70}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let U=this.getCodeNorm();if(U===u4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(Y,this.prevI);let I=U===t6;if(I||r8(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=I?VU:$20}else this.state=I?qN:Zx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===t6)this.state=qN;else if(!r8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(t6))this.state=qN}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===j6){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=y8}else if(Y===t6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=Zx;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===t6){this.state=VU;return}if($!==u4)this.state=A11,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(y11);if($===t6){this.state=VU,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(r8($)||$===SJ))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expectedthename${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expectedoneof${this.xmlDeclExpects.join(", ")}`)}this.state=$===SJ?Y20:P11}sXMLDeclEq(){let $=this.getCodeNorm();if($===t6){this.state=VU,this.fail("XML declaration is incomplete.");return}if(r8($))return;if($!==SJ)this.fail("value required.");this.state=Y20}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===t6){this.state=VU,this.fail("XML declaration is incomplete.");return}if(r8($))return;if(!FN($))this.fail("value must be quoted."),this.q=J20;else this.q=$;this.state=T11}sXMLDeclValue(){let $=this.captureTo([this.q,t6]);if($===t6){this.state=VU,this.text="",this.fail("XML declaration is incomplete.");return}if($===u4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=Y;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("ver
Line truncated
See:https://github.com/isaacs/node-glob/issues/167`);return new j6($,Y).found}function j6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See:https://github.com/isaacs/node-glob/issues/167`);return new C6($,Y).found}function C6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
`+Z0[A0-1];break}}}var A1="a promise was created in a "+h+"handler "+W0+"but was not returned from it, see http://goo.gl/rRqMUw"+Q0;u._warn(A1,!0,B)}}function R(I0,B){var h=I0+" is deprecated and will be removed in a future version.";if(B)h+=" Use "+B+" instead.";return o(h)}function o(I0,B,h){if(!D0.warnings)return;var u=new I(I0),s;if(B)h._attachExtraTrace(u);else if(D0.longStackTraces&&(s=$._peekContext()))s.attachExtraTrace(u);else{var W0=o0(u);u.stack=W0.message+`
`+Z0[B0-1];break}}}var B1="a promise was created in a "+S+"handler "+W0+"but was not returned from it, see http://goo.gl/rRqMUw"+J0;u._warn(B1,!0,A)}}function R(Q0,A){var S=Q0+" is deprecated and will be removed in a future version.";if(A)S+=" Use "+A+" instead.";return o(S)}function o(Q0,A,S){if(!D0.warnings)return;var u=new Q(Q0),s;if(A)S._attachExtraTrace(u);else if(D0.longStackTraces&&(s=$._peekContext()))s.attachExtraTrace(u);else{var W0=o0(u);u.stack=W0.message+`
`)));return}}F=F._target();var N=F._bitField;if((N&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((N&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((N&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(V,w){if(typeof V!=="function")throw new K(`generatorFunctionmustbeafunction
`)));return}}F=F._target();var N=F._bitField;if((N&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((N&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((N&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(V,w){if(typeof V!=="function")throw new z(`generatorFunctionmustbeafunction
Seehttp://goo.gl/MqrFmX
`);var M=Object(w).yieldHandler,F=q,N=Error().stack;return function(){var O=V.apply(this,arguments),D=new F(void 0,void 0,M,N),P=D.promise();return D._generator=O,D._promiseFulfilled(void 0),P}},$.coroutine.addYieldHandler=function(V){if(typeof V!=="function")throw new K("expecting a function but got "+G.classString(V));X.push(V)},$.spawn=function(V){if(Q.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return Y(`generatorFunctionmustbeafunction
`);var M=Object(w).yieldHandler,F=q,N=Error().stack;return function(){var O=V.apply(this,arguments),D=new F(void 0,void 0,M,N),P=D.promise();return D._generator=O,D._promiseFulfilled(void 0),P}},$.coroutine.addYieldHandler=function(V){if(typeof V!=="function")throw new z("expecting a function but got "+G.classString(V));X.push(V)},$.spawn=function(V){if(J.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return Y(`generatorFunctionmustbeafunction
`)},Y=function(){return new g.PromiseInspection(this._target())},U=function(k){return g.reject(new X(k))};function z(){}var I={},Q=w4(),J;if(Q.isNode)J=function(){var k=process.domain;if(k===void 0)k=null;return k};else J=function(){return null};Q.notEnumerableProp(g,"_getDomain",J);var K=aU(),G=Qw0(),H=new G;K.defineProperty(g,"_async",{value:H});var W=_3(),X=g.TypeError=W.TypeError;g.RangeError=W.RangeError;var Z=g.CancellationError=W.CancellationError;g.TimeoutError=W.TimeoutError,g.OperationalError=W.OperationalError,g.RejectionError=W.OperationalError,g.AggregateError=W.AggregateError;var q=function(){},V={},w={},M=Ww0()(g,q),F=Zw0()(g,q,M,U,z),N=Vw0()(g),O=N.create,D=Fw0()(g,N),P=D.CapturedTrace,T=Mw0()(g,M),A=Nw0()(w),j=Sc(),C=Q.errorObj,b=Q.tryCatch;function x(k,d){if(typeof d!=="function")throw new X("expecting a function but got "+Q.classString(d));if(k.constructor!==g)throw new X(`thepromiseconstructorcannotbeinvokeddirectly
`)},Y=function(){return new g.PromiseInspection(this._target())},U=function(k){return g.reject(new X(k))};function I(){}var Q={},J=M4(),K;if(J.isNode)K=function(){var k=process.domain;if(k===void 0)k=null;return k};else K=function(){return null};J.notEnumerableProp(g,"_getDomain",K);var z=tU(),G=Nw0(),H=new G;z.defineProperty(g,"_async",{value:H});var W=h3(),X=g.TypeError=W.TypeError;g.RangeError=W.RangeError;var Z=g.CancellationError=W.CancellationError;g.TimeoutError=W.TimeoutError,g.OperationalError=W.OperationalError,g.RejectionError=W.OperationalError,g.AggregateError=W.AggregateError;var q=function(){},V={},w={},M=Tw0()(g,q),F=jw0()(g,q,M,U,I),N=Rw0()(g),O=N.create,D=vw0()(g,N),P=D.CapturedTrace,T=hw0()(g,M),B=yw0()(w),E=fc(),C=J.errorObj,b=J.tryCatch;function x(k,p){if(typeof p!=="function")throw new X("expecting a function but got "+J.classString(p));if(k.constructor!==g)throw new X(`thepromiseconstructorcannotbeinvokeddirectly
Seehttp://goo.gl/MqrFmX
`)}function g(k){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,k!==q)x(this,k),this._resolveFromExecutor(k);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(k){var d=arguments.length;if(d>1){var a=Array(d-1),$0=0,y;for(y=0;y<d-1;++y){var p=arguments[y];if(Q.isObject(p))a[$0++]=p;else return U("expecting an object but got A catch statement predicate "+Q.classString(p))}return a.length=$0,k=arguments[y],this.then(void 0,A(a,k,this))}return this.then(void 0,k)},g.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},g.prototype.then=function(k,d){if(D.warnings()&&arguments.length>0&&typeof k!=="function"&&typeof d!=="function"){var a=".then() only accepts functions but was passed: "+Q.classString(k);if(arguments.length>1)a+=", "+Q.classString(d);this._warn(a)}return this._then(k,d,void 0,void 0,void 0)},g.prototype.done=function(k,d){var a=this._then(k,d,void 0,void 0,void 0);a._setIsFinal()},g.prototype.spread=function(k){if(typeof k!=="function")return U("expecting a function but got "+Q.classString(k));return this.all()._then(k,void 0,void 0,V,void 0)},g.prototype.toJSON=function(){var k={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())k.fulfillmentValue=this.value(),k.isFulfilled=!0;else if(this.isRejected())k.rejectionReason=this.reason(),k.isRejected=!0;return k},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},g.prototype.error=function(k){return this.caught(Q.originatesFromRejection,k)},g.getNewLibraryCopy=yc.exports,g.is=function(k){return k instanceof g},g.fromNode=g.fromCallback=function(k){var d=new g(q);d._captureStackTrace();var a=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,$0=b(k)(j(d,a));if($0===C)d._rejectCallback($0.e,!0);if(!d._isFateSealed())d._setAsyncGuaranteed();return d},g.all=function(k){return new F(k).promise()},g.cast=function(k){var d=M(k);if(!(d instanceof g))d=new g(q),d._captureStackTrace(),d._setFulfilled(),d._rejectionHandler0=k;return d},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(k){var d=new g(q);return d._captureStackTrace(),d._rejectCallback(k,!0),d},g.setScheduler=function(k){if(typeof k!=="function")throw new X("expecting a function but got "+Q.classString(k));return H.setScheduler(k)},g.prototype._then=function(k,d,a,$0,y){var p=y!==void 0,Y0=p?y:new g(q),R=this._target(),o=R._bitField;if(!p){if(Y0._propagateFrom(this,3),Y0._captureStackTrace(),$0===void 0&&(this._bitField&2097152)!==0)if((o&50397184)!==0)$0=this._boundValue();else $0=R===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,Y0)}var e=J();if((o&50397184)!==0){var O0,T0,y0=R._settlePromiseCtx;if((o&33554432)!==0)T0=R._rejectionHandler0,O0=k;else if((o&16777216)!==0)T0=R._fulfillmentHandler0,O0=d,R._unsetRejectionIsUnhandled();else y0=R._settlePromiseLateCancellationObserver,T0=new Z("late cancellation observer"),R._attachExtraTrace(T0),O0=d;H.invoke(y0,R,{handler:e===null?O0:typeof O0==="function"&&Q.domainBind(e,O0),promise:Y0,receiver:$0,value:T0})}else R._addCallbacks(k,d,Y0,$0,e);return Y0},g.prototype._length=function(){return this._bitField&65535},g.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},g.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},g.prototype._setLength=function(k){this._bitField=this._bitField&-65536|k&65535},g.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},g.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},g.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},g.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},g.prototype._isFinal=function(){return(this._bitField&4194304)>0},g.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},g.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},g.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},g.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(k){var d=k===0?this._receiver0:this[k*4-4+3];if(d===I)return;else if(d===void 0&&this._isBound())return this._boundValue();return d},g.prototype._promiseAt=function(k){return this[k*4-4+2]},g.prototype._fulfillmentHandlerAt=function(k){return this[k*4-4+0]},g.prototype._rejectionHandlerAt=function(k){return this[k*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(k){var{_bitField:d,_fulfillmentHand
Line truncated
`)}function g(k){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,k!==q)x(this,k),this._resolveFromExecutor(k);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(k){var p=arguments.length;if(p>1){var a=Array(p-1),$0=0,y;for(y=0;y<p-1;++y){var d=arguments[y];if(J.isObject(d))a[$0++]=d;else return U("expecting an object but got A catch statement predicate "+J.classString(d))}return a.length=$0,k=arguments[y],this.then(void 0,B(a,k,this))}return this.then(void 0,k)},g.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},g.prototype.then=function(k,p){if(D.warnings()&&arguments.length>0&&typeof k!=="function"&&typeof p!=="function"){var a=".then() only accepts functions but was passed: "+J.classString(k);if(arguments.length>1)a+=", "+J.classString(p);this._warn(a)}return this._then(k,p,void 0,void 0,void 0)},g.prototype.done=function(k,p){var a=this._then(k,p,void 0,void 0,void 0);a._setIsFinal()},g.prototype.spread=function(k){if(typeof k!=="function")return U("expecting a function but got "+J.classString(k));return this.all()._then(k,void 0,void 0,V,void 0)},g.prototype.toJSON=function(){var k={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())k.fulfillmentValue=this.value(),k.isFulfilled=!0;else if(this.isRejected())k.rejectionReason=this.reason(),k.isRejected=!0;return k},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},g.prototype.error=function(k){return this.caught(J.originatesFromRejection,k)},g.getNewLibraryCopy=bc.exports,g.is=function(k){return k instanceof g},g.fromNode=g.fromCallback=function(k){var p=new g(q);p._captureStackTrace();var a=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,$0=b(k)(E(p,a));if($0===C)p._rejectCallback($0.e,!0);if(!p._isFateSealed())p._setAsyncGuaranteed();return p},g.all=function(k){return new F(k).promise()},g.cast=function(k){var p=M(k);if(!(p instanceof g))p=new g(q),p._captureStackTrace(),p._setFulfilled(),p._rejectionHandler0=k;return p},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(k){var p=new g(q);return p._captureStackTrace(),p._rejectCallback(k,!0),p},g.setScheduler=function(k){if(typeof k!=="function")throw new X("expecting a function but got "+J.classString(k));return H.setScheduler(k)},g.prototype._then=function(k,p,a,$0,y){var d=y!==void 0,Y0=d?y:new g(q),R=this._target(),o=R._bitField;if(!d){if(Y0._propagateFrom(this,3),Y0._captureStackTrace(),$0===void 0&&(this._bitField&2097152)!==0)if((o&50397184)!==0)$0=this._boundValue();else $0=R===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,Y0)}var e=K();if((o&50397184)!==0){var O0,T0,y0=R._settlePromiseCtx;if((o&33554432)!==0)T0=R._rejectionHandler0,O0=k;else if((o&16777216)!==0)T0=R._fulfillmentHandler0,O0=p,R._unsetRejectionIsUnhandled();else y0=R._settlePromiseLateCancellationObserver,T0=new Z("late cancellation observer"),R._attachExtraTrace(T0),O0=p;H.invoke(y0,R,{handler:e===null?O0:typeof O0==="function"&&J.domainBind(e,O0),promise:Y0,receiver:$0,value:T0})}else R._addCallbacks(k,p,Y0,$0,e);return Y0},g.prototype._length=function(){return this._bitField&65535},g.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},g.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},g.prototype._setLength=function(k){this._bitField=this._bitField&-65536|k&65535},g.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},g.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},g.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},g.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},g.prototype._isFinal=function(){return(this._bitField&4194304)>0},g.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},g.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},g.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},g.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(k){var p=k===0?this._receiver0:this[k*4-4+3];if(p===Q)return;else if(p===void 0&&this._isBound())return this._boundValue();return p},g.prototype._promiseAt=function(k){return this[k*4-4+2]},g.prototype._fulfillmentHandlerAt=function(k){return this[k*4-4+0]},g.prototype._rejectionHandlerAt=function(k){return this[k*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(k){var{_bitField:p,_fulfillmentHand
Line truncated
`,{mode:384}),Y}function Tp($){let Y=pA0();for(let U of Y){if(!F$(U))continue;for(let z of tB(U).filter((I)=>I.endsWith(".json")).filter((I)=>!I.startsWith("example."))){let I=j9(U,z);try{let Q=$P(I,"utf-8"),J=JSON.parse(Q);if(J&&typeof J==="object"&&J.id===$)return I}catch{}}}return}function E9($,Y){let U=Tp($);if(!U)throw Error(`Enterpriseconfignotfound:${$}`);let I={...JSON.parse($P(U,"utf-8")),...Y};for(let J of Object.keys(Y))if(Y[J]===void 0)delete I[J];let Q=hZ.parse(I);return fA0(U,`${JSON.stringify(Q,null,2)}
`,"utf-8"),Q}var Pp="SEAL_USE_ENTERPRISES_DIR",uA0="SEAL_HOME_ENTERPRISES_DIR",bA0="SEAL_USE_USER_ENTERPRISES_DIR",iA0="SEAL_HOME_USER_ENTERPRISES_DIR",cA0="SEAL_USE_CONFIG_FILE",nA0="SEAL_HOME_CONFIG_FILE",UK,eB,aB,kA0;var T5=m(()=>{sB();UK=j9(YP(),".config","seal-use","enterprises"),eB=j9(YP(),".config","seal-home","enterprises"),aB=j9(YP(),".config","seal-use","config.json"),kA0=j9(YP(),".config","seal-home","config.json")});function n2($,Y,U=[]){let z=Y.corpId?.trim()||void 0,I=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,Q=z??I;if(Q){let K=$.find((W)=>W.id===Q);if(K)return K;let G=$.find((W)=>W.id.toLowerCase()===Q.toLowerCase());if(G)return G;let H=$.find((W)=>W.name.toLowerCase()===Q.toLowerCase());if(H)return H;throw Error(`Noenterpriseconfigfoundfor${Q}`)}if(!Y.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-useconfigmodestateful` to enable a default enterprise.");let J=$[0];if(J)return J;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{existsSync as jp,mkdirSync as dD1,readFileSync as mD1,renameSync as lD1,unlinkSync as oD1,writeFileSync as rD1}from"node:fs";import{homedir as sD1}from"node:os";import{dirname as aD1,join as tD1}from"node:path";function gZ(){let $=process.env[eD1]?.trim();if($)return $;return $A1}function mA0($=new Date){return $.toISOString().slice(0,10)}function lA0($=Ep,Y=new Date){let U=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(U).toISOString().slice(0,10)}function oA0($=gZ()){if(!jp($))return{};try{let Y=mD1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&!Array.isArray(U))return U;return{}}catch{return{}}}function YA1($,Y){let U={};for(let[z,I]of Object.entries($)){if(!I||typeof I!=="object")continue;let Q={},J=!1;for(let[K,G]of Object.entries(I))if(typeof G==="number"&&G>0&&K>=Y)Q[K]=G,J=!0;if(J)U[z]=Q}return U}function UA1($,Y=gZ()){let U=aD1(Y);if(!jp(U))dD1(U,{recursive:!0,mode:448});let z=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{rD1(z,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),lD1(z,Y)}catch(I){try{if(jp(z))oD1(z)}catch{}throw I}}function rA0($,Y=new Date){if(!$||typeof $!=="string")return;try{let U=gZ(),z=oA0(U),I=mA0(Y),Q=lA0(Ep,Y),J=YA1(z,Q);J[$]=J[$]||{},J[$][I]=(J[$][I]??0)+1,UA1(J,U)}catch{}}function zA1($,Y=Ep,U=new Date){let z=new Map;try{let I=oA0(),Q=lA0(Y,U),J=mA0(U),K=$??Object.keys(I);for(let G of K){let H=I[G];if(!H){z.set(G,0);continue}let W=0;for(let[X,Z]of Object.entries(H))if(X>=Q&&X<=J&&typeof Z==="number")W+=Z;z.set(G,W)}}catch{if($)for(let I of $)z.set(I,0)}return z}function sA0($,Y,U){let z=U??zA1($.map((I)=>I.id));return[...$].sort((I,Q)=>{if(Y){if(I.id===Y&&Q.id!==Y)return-1;if(Q.id===Y&&I.id!==Y)return 1}let J=z.get(I.id)??0,K=z.get(Q.id)??0;if(J!==K)return K-J;let G=I.name??I.id,H=Q.name??Q.id,W=G.localeCompare(H,"zh-CN");if(W!==0)return W;return I.id.localeCompare(Q.id)})}var eD1="SEAL_USE_USAGE_FILE",$A1,Ep=7;var UP=m(()=>{$A1=tD1(sD1(),".config","seal-use","usage.json")});function IA1($,Y){return $.map((U)=>U.trim()).filter(Boolean).map((U)=>Y?U:U.toLowerCase())}function QA1($,Y){return Y?$:$.toLowerCase()}function JA1($,Y,U,z){let I=QA1($,z),Q=Y.filter((J)=>I.includes(J));if(U==="all"&&Q.length!==Y.length)return[];return Q}function KA1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function GA1($,Y){if(Y.fields&&!Y.fields.has($.field))return[];let U=KA1($.value),z=[];return U.forEach((I,Q)=>{let J=JA1(I,Y.keywords,Y.matchMode,Y.caseSensitive);if(J.length===0)return;let K=Math.max(0,Q-Y.contextLines),G=Math.min(U.length,Q+Y.contextLines+1),H={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Q+1,matchedKeywords:J,matchedText:zP(I,Y.maxChars),context:{before:Y.snippetOnly?[]:U.slice(K,Q).map((W)=>zP(W,Y.maxChars)),line:zP(I,Y.maxChars),after:Y.snippetOnly?[]:U.slice(Q+1,G).map((W)=>zP(W,Y.maxChars))},metadata:$.metadata};if(Y.snippetOnly)H.context={before:[],line:H.context.line,after:[]};z.push(H)}),z}function zP($,Y){if(!Y||$.length<=Y)return $;return`${$.slice(0,Math.max(0,Y))}...`}function HA1($){return[{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"description",value:$.description,metadata:{scope:$.scope,strictness:$.strictness,status:$.status}},{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"scope",value:$.scope,metadata:{strictness:$.strictness,status:$.status}}]}function tA0($){return $.rules.flatMap((Y,U)=>{let z=`${$.id}:${Y.description.slice(0,32)}`,I={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:Y.scope,strictness:Y.strictness,code:"code"in Y?Y.code:void 0,index:U};return[{area:"rules",entityType:"rule",entityId:z,title:`${$.versionName}/${Y.scope}`,field:"hi
Line truncated
`)}function zB0($){return{id:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt}}function IB0($,Y){let U=new Map;for(let z of $.rules){let I=yZ(z),Q=Y==="stable-id"?JB0(I):kZ(I.code??I.ruleCode);if(!Q)throw Error(`Ruleversion${$.versionNumber}containsarulewithouta${Y==="stable-id"?"stable rule ID":"code"}.`);if(U.has(Q))throw Error(`Ruleversion${$.versionNumber}containsduplicate${Y==="stable-id"?"stable rule ID":"code"}:${Q}`);U.set(Q,I)}return U}function MA1($,Y,U){if(U!=="auto")return U;if([...$.rules,...Y.rules].every((Q)=>Boolean(JB0(Q))))return"stable-id";if([...$.rules,...Y.rules].every((Q)=>Boolean(kZ(yZ(Q).code??yZ(Q).ruleCode))))return"code";throw Error("Rule snapshots have neither a complete stable-ID mapping nor a complete code mapping.")}function KB0($,Y,U={}){let z=MA1($,Y,U.identityMode??"auto"),I=IB0($,z),Q=IB0(Y,z),J=[...new Set([...I.keys(),...Q.keys()])],K=[],G={added:0,removed:0,modified:0,unchanged:0},H=zB0($),W=zB0(Y);for(let Z of J){let q=I.get(Z),V=Q.get(Z),w=q?Vz(q,z):void 0,M=V?Vz(V,z):void 0,F=!q?"added":!V?"removed":JSON.stringify(w)!==JSON.stringify(M)?"modified":"unchanged";if(G[F]+=1,F==="unchanged"&&!U.includeUnchanged)continue;let N=F==="modified"?[...new Set([...Object.keys(w??{}),...Object.keys(M??{})])].filter((O)=>JSON.stringify(w?.[O])!==JSON.stringify(M?.[O])):void 0;K.push({status:F,ruleId:Z,identityMode:z,...q?{before:q}:{},...V?{after:V}:{},...N?.length?{changedFields:N}:{},...F!=="unchanged"?{diff:wA1(Z,H,W,q,V,z)}:{}})}let X={from:H,to:W,identityMode:z,counts:G,changes:K,unifiedDiff:K.filter((Z)=>Z.diff).map((Z)=>Z.diff).join(`
`)};if(z==="code"){let Z=J.filter((P)=>I.has(P)&&Q.has(P)).length,q=J.filter((P)=>I.has(P)&&Q.has(P)&&JSON.stringify(Vz(I.get(P),"code"))===JSON.stringify(Vz(Q.get(P),"code"))).length,V=I.size,w=Q.size,M=Math.min(V,w)?Z/Math.min(V,w):1,F=new Map;for(let[P,T]of I)F.set(JSON.stringify(Vz(T,"code")),P);let N=0;for(let[P,T]of Q){let A=F.get(JSON.stringify(Vz(T,"code")));if(A&&A!==P)N+=1}let D=(Math.min(V,w)?q/Math.min(V,w):1)>=0.5?"high":q>0||N>0?"ambiguous":"low";X.codeStats={oldCount:V,newCount:w,sameCodeCount:Z,sameCodeUnchanged:q,sameBodyDifferentCode:N,overlapRatio:M,confidence:D,warning:"Published snapshots do not carry stableIDs; code matching can report reorderings as remove/add or modified rules."}}return X}function Rp($,Y=20000,U=!1){if(U||$.unifiedDiff.length<=Y)return{...$,truncation:{truncated:!1,maxChars:Y,omittedChars:0,hint:"Use --full only when the complete diff is required."}};let z=$.unifiedDiff.length-Y,I=`
...[difftruncated:${z}charactersomitted;rerunwith--fullforthecompletediff]`,Q=$.changes.map(({before:J,after:K,diff:G,...H})=>({...H,...G?{diff:G.length>Y?`${G.slice(0,Y)}${I}`:G}:{}}));return{...$,changes:Q,unifiedDiff:`${$.unifiedDiff.slice(0,Y)}${I}`,truncation:{truncated:!0,maxChars:Y,omittedChars:z,hint:"Use --full for the complete diff."}}}var QB0,LA1;var GB0=m(()=>{QB0=["id","ruleId","stableId"],LA1=new Set([...QB0,"runtimeRuleId","runtimeId","tenantId","createdAt","updatedAt","versionId","versionNumber"])});import{existsSync as OA1,mkdirSync as NA1,readFileSync as DA1,renameSync as AA1,writeFileSync as BA1}from"node:fs";import{homedir as PA1}from"node:os";import{join as HB0}from"node:path";function xZ($){if($===void 0||$===null)return;let Y=String($).trim().toLowerCase().replace(/^rule[-_:]?/,"").replace(/^#/,"");if(!Y)return;return/^\d+$/.test(Y)?String(Number(Y)):Y}function IP($){return JSON.stringify([$.description??"",$.scope??"",$.strictness??""])}function WB0(){return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim()||HB0(PA1(),".config","seal-use","rule-version-snapshots")}function TA1($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function XB0($,Y){return HB0(WB0(),`${TA1($)}-v${Y}.json`)}function fZ($,Y,U){let z=new Map,I=new Map;for(let W of U){let X=xZ(W.code);if(X)z.set(X,[...z.get(X)??[],W]);let Z=IP(W);I.set(Z,[...I.get(Z)??[],W])}let Q=[];for(let W of Y.rules??[]){let X=xZ(W.code),Z=X?z.get(X)??[]:[],q=I.get(IP(W))??[],V=Z.length===1?Z[0]:q.length===1?q[0]:void 0;if(!V)continue;Q.push({stableId:V.id,...W.code!==void 0?{code:W.code}:{},description:W.description,scope:W.scope,strictness:W.strictness})}let J={corpId:$,versionId:Y.id,versionNumber:Y.versionNumber,capturedAt:new Date().toISOString(),rules:Q},K=WB0();NA1(K,{recursive:!0,mode:448});let G=XB0($,Y.versionNumber),H=`${G}.${process.pid}.tmp`;return BA1(H,`${JSON.stringify(J,null,2)}
`,{mode:384}),Y}function _d($){let Y=JA0();for(let U of Y){if(!D$(U))continue;for(let I of JP(U).filter((Q)=>Q.endsWith(".json")).filter((Q)=>!Q.startsWith("example."))){let Q=C9(U,I);try{let J=zP(Q,"utf-8"),K=JSON.parse(J);if(K&&typeof K==="object"&&K.id===$)return Q}catch{}}}return}function R9($,Y){let U=_d($);if(!U)throw Error(`Enterpriseconfignotfound:${$}`);let Q={...JSON.parse(zP(U,"utf-8")),...Y};for(let K of Object.keys(Y))if(Y[K]===void 0)delete Q[K];let J=kZ.parse(Q);return eB0(U,`${JSON.stringify(J,null,2)}
`,"utf-8"),J}var Rd="SEAL_USE_ENTERPRISES_DIR",$A0="SEAL_HOME_ENTERPRISES_DIR",YA0="SEAL_USE_USER_ENTERPRISES_DIR",UA0="SEAL_HOME_USER_ENTERPRISES_DIR",IA0="SEAL_USE_CONFIG_FILE",QA0="SEAL_HOME_CONFIG_FILE",Iz,KP,QP,aB0;var l$=m(()=>{IP();Iz=C9(GP(),".config","seal-use","enterprises"),KP=C9(GP(),".config","seal-home","enterprises"),QP=C9(GP(),".config","seal-use","config.json"),aB0=C9(GP(),".config","seal-home","config.json")});function d2($,Y,U=[]){let I=Y.corpId?.trim()||void 0,Q=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,J=I??Q;if(J){let z=$.find((W)=>W.id===J);if(z)return z;let G=$.find((W)=>W.id.toLowerCase()===J.toLowerCase());if(G)return G;let H=$.find((W)=>W.name.toLowerCase()===J.toLowerCase());if(H)return H;throw Error(`Noenterpriseconfigfoundfor${J}`)}if(!Y.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-useconfigmodestateful` to enable a default enterprise.");let K=$[0];if(K)return K;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{existsSync as vd,mkdirSync as yB1,readFileSync as kB1,renameSync as xB1,unlinkSync as fB1,writeFileSync as uB1}from"node:fs";import{homedir as bB1}from"node:os";import{dirname as iB1,join as cB1}from"node:path";function fZ(){let $=process.env[nB1]?.trim();if($)return $;return dB1}function zA0($=new Date){return $.toISOString().slice(0,10)}function GA0($=Sd,Y=new Date){let U=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(U).toISOString().slice(0,10)}function HA0($=fZ()){if(!vd($))return{};try{let Y=kB1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&!Array.isArray(U))return U;return{}}catch{return{}}}function pB1($,Y){let U={};for(let[I,Q]of Object.entries($)){if(!Q||typeof Q!=="object")continue;let J={},K=!1;for(let[z,G]of Object.entries(Q))if(typeof G==="number"&&G>0&&z>=Y)J[z]=G,K=!0;if(K)U[I]=J}return U}function mB1($,Y=fZ()){let U=iB1(Y);if(!vd(U))yB1(U,{recursive:!0,mode:448});let I=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{uB1(I,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),xB1(I,Y)}catch(Q){try{if(vd(I))fB1(I)}catch{}throw Q}}function WA0($,Y=new Date){if(!$||typeof $!=="string")return;try{let U=fZ(),I=HA0(U),Q=zA0(Y),J=GA0(Sd,Y),K=pB1(I,J);K[$]=K[$]||{},K[$][Q]=(K[$][Q]??0)+1,mB1(K,U)}catch{}}function lB1($,Y=Sd,U=new Date){let I=new Map;try{let Q=HA0(),J=GA0(Y,U),K=zA0(U),z=$??Object.keys(Q);for(let G of z){let H=Q[G];if(!H){I.set(G,0);continue}let W=0;for(let[X,Z]of Object.entries(H))if(X>=J&&X<=K&&typeof Z==="number")W+=Z;I.set(G,W)}}catch{if($)for(let Q of $)I.set(Q,0)}return I}function XA0($,Y,U){let I=U??lB1($.map((Q)=>Q.id));return[...$].sort((Q,J)=>{if(Y){if(Q.id===Y&&J.id!==Y)return-1;if(J.id===Y&&Q.id!==Y)return 1}let K=I.get(Q.id)??0,z=I.get(J.id)??0;if(K!==z)return z-K;let G=Q.name??Q.id,H=J.name??J.id,W=G.localeCompare(H,"zh-CN");if(W!==0)return W;return Q.id.localeCompare(J.id)})}var nB1="SEAL_USE_USAGE_FILE",dB1,Sd=7;var HP=m(()=>{dB1=cB1(bB1(),".config","seal-use","usage.json")});var K8={};Z8(K8,{withApprovalRunFilters:()=>FA1,toDate:()=>pd,timestampOf:()=>yd,summarizeSimulationBatch:()=>YA1,summarizeRunBridge:()=>KA1,summarizeRuleVersion:()=>zA1,summarizeApprovalRuns:()=>UA1,summarizeApprovalRunResult:()=>LP,summarizeApprovalRunDocument:()=>wA0,summarizeApprovalRunDetail:()=>QA1,summarizeApprovalRun:()=>nZ,stringifyHumanResultValue:()=>dd,stringFromUnknown:()=>h4,setPath:()=>MA0,scalarIncludes:()=>ZP,runtimeRuleIndex:()=>cd,runtimeRuleIdToCode:()=>BA0,rulesHaveSameContent:()=>VA0,ruleChangedFields:()=>LA0,resolveSealBaseUrl:()=>ZA1,resolveRuleVersionSelector:()=>LA1,resolveRuleVersionForLookup:()=>GA1,resolveRuleVersion:()=>kd,resolveManualApprovalStatus:()=>PA0,resolveApprovalRunForUrl:()=>XA1,redactPreviewValue:()=>bZ,redactIntegrationSecrets:()=>tB1,projectApprovalRules:()=>rB1,presentWebhookIntegration:()=>oB1,prepareApprovalRuns:()=>wA1,pickRunFields:()=>FA0,pickRuleFields:()=>qA0,pickApprovalRuns:()=>VA1,pickApprovalRunCandidate:()=>WA1,parseFieldPaths:()=>IA1,parseDurationMs:()=>aB1,objectContainsScalar:()=>qP,numberFromUnknown:()=>OA0,normalizeUrl:()=>qA1,normalizeRuleStrictness:()=>bd,normalizeRuleCode:()=>WP,mutationPreview:()=>eB1,matchesRunLookup:()=>OA1,localParts:()=>md,localDateKey:()=>NA1,isHumanResultKey:()=>xd,getPath:()=>_9,getConfiguredSealBaseUrl:()=>ZA0,formatRuleCode:()=>Qz,formatLocalDateTime:()=>ud,flattenDocumentFields:()=>NA0,firstPath:()=>iZ,firstByLabel:()=>uZ,findRuleInVersion:()=>HA1,findKeywordLines:()=>gd,findHumanResultValue:()=>VP,filterRunsByHumanResult:()=>AA0,filterRuns:()=>nd,extractHumanResult:()=>FI,extractCitedRules:()=>JA1,countPathCandidates:()=>hd,countBy:()=>fd,compactObject:()=>LI,collectInvoiceSummary:()=>DA0,collectInvoiceObjects:()=>cZ,collectDocumentFields:()=>XP,buildSimulationBatchParams:()=>$A1,buildRulePushPlan:()=>sB1,asRecord:()=>Jz,approvalRu
Line truncated
`)}function cA0($){return{id:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt}}function nA0($,Y){let U=new Map;for(let I of $.rules){let Q=dZ(I),J=Y==="stable-id"?pA0(Q):pZ(Q.code??Q.ruleCode);if(!J)throw Error(`Ruleversion${$.versionNumber}containsarulewithouta${Y==="stable-id"?"stable rule ID":"code"}.`);if(U.has(J))throw Error(`Ruleversion${$.versionNumber}containsduplicate${Y==="stable-id"?"stable rule ID":"code"}:${J}`);U.set(J,Q)}return U}function uA1($,Y,U){if(U!=="auto")return U;if([...$.rules,...Y.rules].every((J)=>Boolean(pA0(J))))return"stable-id";if([...$.rules,...Y.rules].every((J)=>Boolean(pZ(dZ(J).code??dZ(J).ruleCode))))return"code";throw Error("Rule snapshots have neither a complete stable-ID mapping nor a complete code mapping.")}function mA0($,Y,U={}){let I=uA1($,Y,U.identityMode??"auto"),Q=nA0($,I),J=nA0(Y,I),K=[...new Set([...Q.keys(),...J.keys()])],z=[],G={added:0,removed:0,modified:0,unchanged:0},H=cA0($),W=cA0(Y);for(let Z of K){let q=Q.get(Z),V=J.get(Z),w=q?wI(q,I):void 0,M=V?wI(V,I):void 0,F=!q?"added":!V?"removed":JSON.stringify(w)!==JSON.stringify(M)?"modified":"unchanged";if(G[F]+=1,F==="unchanged"&&!U.includeUnchanged)continue;let N=F==="modified"?[...new Set([...Object.keys(w??{}),...Object.keys(M??{})])].filter((O)=>JSON.stringify(w?.[O])!==JSON.stringify(M?.[O])):void 0;z.push({status:F,ruleId:Z,identityMode:I,...q?{before:q}:{},...V?{after:V}:{},...N?.length?{changedFields:N}:{},...F!=="unchanged"?{diff:fA1(Z,H,W,q,V,I)}:{}})}let X={from:H,to:W,identityMode:I,counts:G,changes:z,unifiedDiff:z.filter((Z)=>Z.diff).map((Z)=>Z.diff).join(`
`)};if(I==="code"){let Z=K.filter((P)=>Q.has(P)&&J.has(P)).length,q=K.filter((P)=>Q.has(P)&&J.has(P)&&JSON.stringify(wI(Q.get(P),"code"))===JSON.stringify(wI(J.get(P),"code"))).length,V=Q.size,w=J.size,M=Math.min(V,w)?Z/Math.min(V,w):1,F=new Map;for(let[P,T]of Q)F.set(JSON.stringify(wI(T,"code")),P);let N=0;for(let[P,T]of J){let B=F.get(JSON.stringify(wI(T,"code")));if(B&&B!==P)N+=1}let D=(Math.min(V,w)?q/Math.min(V,w):1)>=0.5?"high":q>0||N>0?"ambiguous":"low";X.codeStats={oldCount:V,newCount:w,sameCodeCount:Z,sameCodeUnchanged:q,sameBodyDifferentCode:N,overlapRatio:M,confidence:D,warning:"Published snapshots do not carry stable IDs; code matching can report reorderings as remove/add or modified rules."}}return X}function rd($,Y=20000,U=!1){if(U||$.unifiedDiff.length<=Y)return{...$,truncation:{truncated:!1,maxChars:Y,omittedChars:0,hint:"Use --full only when the complete diff is required."}};let I=$.unifiedDiff.length-Y,Q=`
...[difftruncated:${I}charactersomitted;rerunwith--fullforthecompletediff]`,J=$.changes.map(({before:K,after:z,diff:G,...H})=>({...H,...G?{diff:G.length>Y?`${G.slice(0,Y)}${Q}`:G}:{}}));return{...$,changes:J,unifiedDiff:`${$.unifiedDiff.slice(0,Y)}${Q}`,truncation:{truncated:!0,maxChars:Y,omittedChars:I,hint:"Use --full for the complete diff."}}}var dA0,kA1;var lA0=m(()=>{dA0=["id","ruleId","stableId"],kA1=new Set([...dA0,"runtimeRuleId","runtimeId","tenantId","createdAt","updatedAt","versionId","versionNumber"])});import{existsSync as bA1,mkdirSync as iA1,readFileSync as cA1,renameSync as nA1,writeFileSync as dA1}from"node:fs";import{homedir as pA1}from"node:os";import{join as oA0}from"node:path";function mZ($){if($===void 0||$===null)return;let Y=String($).trim().toLowerCase().replace(/^rule[-_:]?/,"").replace(/^#/,"");if(!Y)return;return/^\d+$/.test(Y)?String(Number(Y)):Y}function OP($){return JSON.stringify([$.description??"",$.scope??"",$.strictness??""])}function rA0(){return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim()||oA0(pA1(),".config","seal-use","rule-version-snapshots")}function mA1($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function sA0($,Y){return oA0(rA0(),`${mA1($)}-v${Y}.json`)}function lZ($,Y,U){let I=new Map,Q=new Map;for(let W of U){let X=mZ(W.code);if(X)I.set(X,[...I.get(X)??[],W]);let Z=OP(W);Q.set(Z,[...Q.get(Z)??[],W])}let J=[];for(let W of Y.rules??[]){let X=mZ(W.code),Z=X?I.get(X)??[]:[],q=Q.get(OP(W))??[],V=Z.length===1?Z[0]:q.length===1?q[0]:void 0;if(!V)continue;J.push({stableId:V.id,...W.code!==void 0?{code:W.code}:{},description:W.description,scope:W.scope,strictness:W.strictness})}let K={corpId:$,versionId:Y.id,versionNumber:Y.versionNumber,capturedAt:new Date().toISOString(),rules:J},z=rA0();iA1(z,{recursive:!0,mode:448});let G=sA0($,Y.versionNumber),H=`${G}.${process.pid}.tmp`;return dA1(H,`${JSON.stringify(K,null,2)}
@@ -881,65 +881,65 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
}
exportdefaultlintRule;
`}});import{existsSync as Lz,mkdirSync as lA1,readFileSync as oA1,readdirSync as NB0,rmSync as rA1,unlinkSync as sA1,writeFileSync as aA1}from"node:fs";import{homedir as tA1}from"node:os";import{isAbsolute as eA1,join as b6,resolve as $B1}from"node:path";import{pathToFileURL as MB0}from"node:url";function DB0($=p$){let Y=[],U=[];try{if(!Lz($))lA1($,{recursive:!0});let z=Object.keys(fp);for(let[Q,J]of Object.entries(fp)){let K=b6($,Q),G=!0;if(Lz(K))try{if(oA1(K,"utf8")===J)G=!1}catch{G=!0}if(G)aA1(K,J,"utf8");Y.push(Q)}let I=NB0($,{withFileTypes:!0});for(let Q of I)if(!z.includes(Q.name)){let J=b6($,Q.name);try{if(Q.isDirectory())rA1(J,{recursive:!0,force:!0});else sA1(J);U.push(Q.name)}catch{}}}catch{}return{synced:Y,pruned:U}}function AB0($={syncOfficial:!0}){if($.syncOfficial!==!1)DB0();let Y=[{name:"builtin",type:"builtin",path:b6(p$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:b6(p$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:b6(p$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],U=[n$,GP];for(let z of U)if(Lz(z))try{let I=NB0(z,{withFileTypes:!0});for(let Q of I){if(Q.isDirectory())continue;let J=Q.name;if(J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")){let K=J.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((G)=>G.name===K))Y.push({name:K,type:"custom",path:b6(z,J),description:`用户自定义规则校验器(${J})`})}}}catch{}return Y}function UB1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:b6(p$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:b6(p$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(Y==="hlab"||Y==="hlab-sop"||Y==="hlab-rules"||Y==="hlab-standard"||Y==="official/hlab"||Y==="official/hlab.ts")return{path:b6(p$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(eA1(Y)||Y.startsWith("./")||Y.startsWith("../")){let z=$B1(Y);if(Lz(z))return{path:z};for(let I of[".ts",".js",".mjs"])if(Lz(`${z}${I}`))return{path:`${z}${I}`}}let U=[b6(n$,`${Y}.ts`),b6(n$,`${Y}.js`),b6(n$,`${Y}.mjs`),b6(GP,`${Y}.ts`),b6(GP,`${Y}.js`),b6(GP,`${Y}.mjs`)];for(let z of U)if(Lz(z))return{path:z};return{}}async function bp($){DB0();let Y=UB1($??"builtin");if(Y.isOfficial){let z=Y.officialKind==="strict"?FB0:Y.officialKind==="hlab"?wB0:IK,I=Y.officialKind==="builtin"?"builtin":"official",Q=Y.path;if(Q&&Lz(Q))try{let K=await import(MB0(Q).href),G=K.default??K.lintRule??K.linter??K.lint;if(typeof G==="function")return{name:Y.officialKind??"builtin",type:I,filePath:Q,linter:OB0(G,z)}}catch{}return{name:Y.officialKind??"builtin",type:I,filePath:Q,linter:z}}let U=Y.path;if(!U)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK};try{let I=await import(MB0(U).href),Q=I.default??I.lintRule??I.linter??I.lint;if(typeof Q!=="function")return console.error(`⚠️[linter]自定义校验器"${U}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK};return{name:$??"custom",type:"custom",filePath:U,linter:OB0(Q,IK)}}catch(z){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${U}"失败(语法错误或依赖缺失:${z?.message??z}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK}}}functionOB0($,Y){returnasync(U,z)=>{try{letI=await$(U,z);if(I&&typeofI==="object"&&typeofI.score==="number"&&Array.isArray(I.issues))returnI;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),Y(U,z)}catch(I){returnconsole.error("⚠️[linter]自定义校验器执行异常:",I),Y(U,z)}}}varn$,YB1="official",p$,GP;varip=m(()=>{yp();xp();up();kp();n$=b6(tA1(),".config","seal-use","linters"),p$=b6(n$,YB1),GP=b6(process.cwd(),"linters")});asyncfunctioncp($,Y,U){letz=awaitY.linter($,U);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:z.score,passed:z.passed,issues:z.issues,description:$.description}}asyncfunctionBB0($,Y,U,z){letI=z?.minScore??0,Q=z?.level??"all",J=[],K=0;for(letqof$){letV=awaitcp(q,Y,U);K+=V.score;letw=V.issues;if(Q==="error")w=V.issues.filter((F)=>F.level==="error");elseif(Q==="warning")w=V.issues.filter((F)=>F.level==="warning"||F.level==="error");letM=w.every((F)=>F.level!=="error");if(z?.summary){if(w.length>0)J.push({...V,passed:M,issues:w})}elseJ.push({...V,passed:M,issues:w})}letG=$.length,H=G===0?100:Math.round(K/G),W=J.filter((q)=>q.issues.length>0).length,X=G-Line truncated
`}});import{homedir as GP1}from"node:os";import{join as Ip}from"node:path";var HP1,B$,A$;var Qp=m(()=>{HP1=Ip(GP1(),".config","seal-use"),B$=Ip(HP1,"linters"),A$=Ip(B$,"official")});import{existsSync as MI,mkdirSync as WP1,readFileSync as XP1,readdirSync as IP0,rmSync as ZP1,unlinkSync as qP1,writeFileSync as VP1}from"node:fs";import{isAbsolute as LP1,join as B8,resolve as FP1}from"node:path";import{pathToFileURL as YP0}from"node:url";function QP0($=A$){let Y=[],U=[];try{if(!MI($))WP1($,{recursive:!0});let I=Object.keys(Yp);for(let[J,K]of Object.entries(Yp)){let z=B8($,J),G=!0;if(MI(z))try{if(XP1(z,"utf8")===K)G=!1}catch{G=!0}if(G)VP1(z,K,"utf8");Y.push(J)}let Q=IP0($,{withFileTypes:!0});for(let J of Q)if(!I.includes(J.name)){let K=B8($,J.name);try{if(J.isDirectory())ZP1(K,{recursive:!0,force:!0});else qP1(K);U.push(J.name)}catch{}}}catch{}return{synced:Y,pruned:U}}function JP0($={syncOfficial:!0}){if($.syncOfficial!==!1)QP0();let Y=[{name:"builtin",type:"builtin",path:B8(A$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:B8(A$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:B8(A$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],U=[B$,NP];for(let I of U)if(MI(I))try{let Q=IP0(I,{withFileTypes:!0});for(let J of Q){if(J.isDirectory())continue;let K=J.name;if(K.endsWith(".ts")||K.endsWith(".js")||K.endsWith(".mjs")){let z=K.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((G)=>G.name===z))Y.push({name:z,type:"custom",path:B8(I,K),description:`用户自定义规则校验器(${K})`})}}}catch{}return Y}function wP1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:B8(A$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:B8(A$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(Y==="hlab"||Y==="hlab-sop"||Y==="hlab-rules"||Y==="hlab-standard"||Y==="official/hlab"||Y==="official/hlab.ts")return{path:B8(A$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(LP1(Y)||Y.startsWith("./")||Y.startsWith("../")){let I=FP1(Y);if(MI(I))return{path:I};for(let Q of[".ts",".js",".mjs"])if(MI(`${I}${Q}`))return{path:`${I}${Q}`}}let U=[B8(B$,`${Y}.ts`),B8(B$,`${Y}.js`),B8(B$,`${Y}.mjs`),B8(NP,`${Y}.ts`),B8(NP,`${Y}.js`),B8(NP,`${Y}.mjs`)];for(let I of U)if(MI(I))return{path:I};return{}}async function Jp($){QP0();let Y=wP1($??"builtin");if(Y.isOfficial){let I=Y.officialKind==="strict"?eA0:Y.officialKind==="hlab"?$P0:Kz,Q=Y.officialKind==="builtin"?"builtin":"official",J=Y.path;if(J&&MI(J))try{let z=await import(YP0(J).href),G=z.default??z.lintRule??z.linter??z.lint;if(typeof G==="function")return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:UP0(G,I)}}catch{}return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:I}}let U=Y.path;if(!U)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:Kz};try{let Q=await import(YP0(U).href),J=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof J!=="function")return console.error(`⚠️[linter]自定义校验器"${U}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:Kz};return{name:$??"custom",type:"custom",filePath:U,linter:UP0(J,Kz)}}catch(I){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${U}"失败(语法错误或依赖缺失:${I?.message??I}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:Kz}}}functionUP0($,Y){returnasync(U,I)=>{try{letQ=await$(U,I);if(Q&&typeofQ==="object"&&typeofQ.score==="number"&&Array.isArray(Q.issues))returnQ;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),Y(U,I)}catch(Q){returnconsole.error("⚠️[linter]自定义校验器执行异常:",Q),Y(U,I)}}}varNP;varKP0=m(()=>{Qp();td();$p();Up();ed();NP=B8(process.cwd(),"linters")});asyncfunctionKp($,Y,U){letI=awaitY.linter($,U);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:I.score,passed:I.passed,issues:I.issues,description:$.description}}asyncfunctionzP0($,Y,U,I){letQ=I?.minScore??0,J=I?.level??"all",K=[],z=0;for(letqof$){letV=awaitKp(q,Y,U);z+=V.score;letw=V.issues;if(J==="error")w=V.issues.filter((F)=>F.level==="error");elseif(J==="warning")w=V.issues.filter((F)=>F.level==="warning"||F.level==="error");letM=w.every((F)=>F.level!=="error");if(I?.summary){if(w.length>0)K.push({...V,passed:M,issues:w})}elseK.push({...V,passed:M,issues:w})}letG=$.length,H=G===Line truncated
`,"utf8"),U}function XP0($){return $.map((Y,U)=>{let I;if(typeof Y.code==="number")I=`#${String(Y.code).padStart(4,"0")}`;else if(typeof Y.code==="string")I=Y.code.startsWith("#")?Y.code:`#${Y.code}`;else I=`#${String(U+1).padStart(4,"0")}`;return{id:Y.id,code:I,name:Y.name,description:Y.description,scope:Y.scope,strictness:Y.strictness}})}var ZP0=()=>{};var z$4,G$4,PP1,H$4,TP1,W$4,X$4,qP0,Z$4,q$4,VP0,V$4,L$4,F$4,w$4,M$4,O$4,N$4,D$4,B$4,A$4,P$4,T$4,E$4,j$4,C$4,R$4,_$4,v$4,S$4,h$4,g$4,y$4,k$4,x$4,f$4,u$4,Hp,EP1,jP1,LP0,CP1,b$4,i$4,c$4,n$4,d$4,p$4,FP0,m$4,l$4,RP1,wP0,o$4,r$4,s$4,a$4,t$4,e$4,$54,Y54,U54,I54,Q54,J54,K54,z54,G54,H54,W54,X54,MP0;var OP0=m(()=>{z6();H4();l$();bA0();lA0();ad();zp();ZP0();o$();({presentWebhookIntegration:z$4,getConfiguredSealBaseUrl:G$4,projectApprovalRules:PP1,pickRuleFields:H$4,buildRulePushPlan:TP1,rulesHaveSameContent:W$4,ruleChangedFields:X$4,normalizeRuleStrictness:qP0,parseDurationMs:Z$4,redactIntegrationSecrets:q$4,mutationPreview:VP0,redactPreviewValue:V$4,buildSimulationBatchParams:L$4,summarizeSimulationBatch:F$4,summarizeApprovalRun:w$4,summarizeApprovalRuns:M$4,parseFieldPaths:O$4,pickRunFields:N$4,approvalRunMetadata:D$4,summarizeApprovalRunDetail:B$4,summarizeApprovalRunResult:A$4,summarizeApprovalRunDocument:P$4,extractCitedRules:T$4,firstPath:E$4,countPathCandidates:j$4,getPath:C$4,setPath:R$4,compactObject:_$4,asRecord:v$4,numberFromUnknown:S$4,flattenDocumentFields:h$4,collectDocumentFields:g$4,firstByLabel:y$4,collectInvoiceSummary:k$4,collectInvoiceObjects:x$4,findKeywordLines:f$4,summarizeRunBridge:u$4,summarizeRuleVersion:Hp,resolveRuleVersionForLookup:EP1,findRuleInVersion:jP1,normalizeRuleCode:LP0,runtimeRuleIndex:CP1,runtimeRuleIdToCode:b$4,formatRuleCode:i$4,pickApprovalRunCandidate:c$4,resolveApprovalRunForUrl:n$4,resolveSealBaseUrl:d$4,normalizeUrl:p$4,stringFromUnknown:FP0,pickApprovalRuns:m$4,timestampOf:l$4,resolveRuleVersion:RP1,resolveRuleVersionSelector:wP0,filterRuns:o$4,scalarIncludes:r$4,objectContainsScalar:s$4,filterRunsByHumanResult:a$4,withApprovalRunFilters:t$4,resolveManualApprovalStatus:e$4,prepareApprovalRuns:$54,approvalRunAliases:Y54,extractHumanResult:U54,findHumanResultValue:I54,isHumanResultKey:Q54,stringifyHumanResultValue:J54,matchesRunLookup:K54,countBy:z54,localDateKey:G54,formatLocalDateTime:H54,toDate:W54,localParts:X54}=K8),MP0=[{name:"seal_approval_rules_list",description:"列出 Seal 当前草稿审批规则;返回的 code 属于草稿编号体系,发布版本可能重新编码;支持 countOnly、fields、limit 以避免返回规则正文",parameters:L.object({countOnly:L.boolean().optional().describe("只返回规则数量,不返回规则列表"),fields:L.array(L.enum(["id","code","tenantId","status","strictness","scope","createdAt","updatedAt","description"])).optional().describe("只返回指定字段;不传则返回完整规则"),limit:L.number().int().nonnegative().optional().describe("最多返回多少条规则;0 可配合 fields 或 countOnly 只取数量"),offset:L.number().int().nonnegative().optional().describe("跳过前多少条规则")}),handler:async($,Y)=>{let U=await q6($);return PP1(U,Y)}},{name:"seal_approval_rules_clear",description:"清空 Seal 当前草稿审批规则;用于测试环境导入规则前重置草稿规则集",parameters:L.object({dryRun:L.boolean().optional().describe("只预览将删除的规则数量,不执行删除"),recode:L.boolean().optional().describe("删除后尝试重新编排规则编号;失败会作为 warning 返回")}),handler:async($,Y,U)=>{let I=await q6($);if(Y.dryRun)return{...VP0(U,"api/v1/rules",I.rules,[],I.rules.length),corpId:U.corp.id,corpName:U.corp.name,dryRun:!0,beforeCount:I.rules.length,deleted:0,afterCount:I.rules.length,hasPendingDeletes:I.hasPendingDeletes};let Q=[],J=0;for(let H of I.rules)try{await $J($,H.id),J+=1}catch(W){Q.push({ruleId:H.id,error:W instanceof Error?W.message:String(W)})}let K=[],z;if(J>0&&Y.recode!==!1){if(z=await SM($),z&&typeof z==="object"&&"ok"in z&&z.ok!==!0)K.push("batch-recode did not complete; current rules were still deleted")}let G=await q6($);return{corpId:U.corp.id,corpName:U.corp.name,dryRun:!1,beforeCount:I.rules.length,deleted:J,failed:Q,afterCount:G.rules.length,hasPendingDeletes:G.hasPendingDeletes,warnings:K,recode:z}}},{name:"seal_approval_rule_create",description:"新建 Seal 草稿审批规则",parameters:L.object({description:L.string().describe("规则描述"),scope:L.string().describe("适用场景"),strictness:L.enum(["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]).describe("严格程度")}),handler:async($,Y)=>uH($,Y)},{name:"seal_approval_rule_update",description:"更新 Seal 草稿审批规则",parameters:L.object({ruleId:L.string().describe("规则 ID"),description:L.string().optional(),scope:L.string().optional(),strictness:L.enum(["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]).optional()}),handler:async($,Y)=>{let U=Y.ruleId;if(U&&(U.startsWith("#")||U.startsWith("rule-")||U.match(/^\d+$/))){
Line truncated
`),z=await Promise.all(O.map((D)=>H4($,D.id)))}let I=new Map,Q=0;for(let F of z){let N=F.document,O=F.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??F.documentId??F.id,D=`${U.docIdPrefix??""}${O}${U.docIdSuffix??""}`,P=[];if(U.includeAttachments!==!1){let A=c2(F,{summary:!1}).attachments,j=new Set;for(let C of A){let b=C.ossSignedUrl??C.url;if(!b)continue;let x=C.fileName??C.fileId??"attachment",g=Dp(x),i=g,c=g.lastIndexOf("."),z0=c>0?g.slice(0,c):g,k=c>0?g.slice(c):"",d=1;while(j.has(i.toLowerCase()))i=`${z0}_${d}${k}`,d++;j.add(i.toLowerCase());try{process.stderr.write(`⬇下载单据「${D}」附件:${x}...
`),await new Promise((F,N)=>{let O=vS1(V),D=new gl({zlib:{level:9}});O.on("close",()=>F()),D.on("error",(P)=>N(P)),D.pipe(O),D.append(Buffer.from(w),{name:"信息表.xlsx"});for(let P of I.values())for(let T of P)D.append(T.buffer,{name:T.zipPath});D.finalize()});let M=SS1(V);return{filePath:V,corpId:Y.id,corpName:Y.name,recordCount:z.length,attachmentCount:Q,fileSizeBytes:M.size,exportedAt:new Date().toISOString(),nextAction:`seal-usewebhookresource-packpush${V}--corp<targetCorpId>`}}var C_0;var yl=m(()=>{j_0();X6();oB();C_0=I6(_Z(),1)});import{readFileSync as fS1}from"node:fs";function uS1($){let Y=new URL($),U=Y.pathname.match(/\/webhook\/([^/]+)/);if(!U)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:U[1]}}function bS1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function iS1($,Y){if(!$.length)return;let U=new Set($.map((Q)=>{let J=Q.fileName.split("/")[0],K=J.indexOf("@");return K>=0?J.slice(0,K):J}).filter((Q)=>Q!=="信息表.xlsx")),z=[];for(let Q of Y){let J=Q.document.documentId;if((Q.documentAttachments.length>0||Object.values(Q.expenseAttachments).some((G)=>G.length>0)||Object.values(Q.personAttachments).some((G)=>G.length>0))&&!U.has(J))z.push(`Excel 会议编号「${J}」声明了附件,但在 ZIP 中找不到对应的根目录「${J}/」或「${J}@.../」。`)}let I=new Set(Y.map((Q)=>Q.document.documentId));for(let Q of U)if(!I.has(Q))z.push(`ZIP 根目录对应的编号「${Q}」在信息表中找不到对应的会议编号。`);if(z.length)throw new j5(z)}async function R_0($,Y,U){let z=[],I=$;if(bS1($,Y)){z=await uP0($),iP0(z,U);let G=z.find((H)=>H.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");I=await yd($,G)}let Q=await oP0(I);iS1(z,Q);let J=rP0(z,Q),K=Q.map((G)=>G.document);return{entries:z,parsed:Q,plans:J,documents:K,fileBuffer:$}}async function kz($,Y,U){let z=await R_0($,Y,U),I=z.parsed.map((Q,J)=>id(Q.document,z.plans[J],new Map));return{warnings:[],documents:I,attachmentPlan:z.plans}}async function OT($,Y,U){let z=await R_0($,Y,U.materialPackFilePolicy),{baseUrl:I,webhookId:Q}=uS1(U.webhookUrl),J=[];for(let K=0;K<z.parsed.length;K+=1){let G=z.parsed[K],H=z.plans[K],W=new Map,X=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let V of X)for(let w of V.paths){if(W.has(w))continue;let M=z.entries.find((T)=>T.fileName===w);if(!M)continue;process.stderr.write(`⬆ 上传附件: ${w}
`),I=await Promise.all(O.map((D)=>G4($,D.id)))}let Q=new Map,J=0;for(let F of I){let N=F.document,O=F.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??F.documentId??F.id,D=`${U.docIdPrefix??""}${O}${U.docIdSuffix??""}`,P=[];if(U.includeAttachments!==!1){let B=b3(F,{summary:!1}).attachments,E=new Set;for(let C of B){let b=C.ossSignedUrl??C.url;if(!b)continue;let x=C.fileName??C.fileId??"attachment",g=Ed(x),i=g,c=g.lastIndexOf("."),I0=c>0?g.slice(0,c):g,k=c>0?g.slice(c):"",p=1;while(E.has(i.toLowerCase()))i=`${I0}_${p}${k}`,p++;E.add(i.toLowerCase());try{process.stderr.write(`⬇下载单据「${D}」附件:${x}...
`),await new Promise((F,N)=>{let O=Qy1(V),D=new Uo({zlib:{level:9}});O.on("close",()=>F()),D.on("error",(P)=>N(P)),D.pipe(O),D.append(Buffer.from(w),{name:"信息表.xlsx"});for(let P of Q.values())for(let T of P)D.append(T.buffer,{name:T.zipPath});D.finalize()});let M=Ky1(V);return{filePath:V,corpId:Y.id,corpName:Y.name,recordCount:I.length,attachmentCount:J,fileSizeBytes:M.size,exportedAt:new Date().toISOString(),nextAction:`seal-usewebhookresource-packpush${V}--corp<targetCorpId>`}}var Dv0;var Io=m(()=>{Ov0();H4();yZ();Dv0=K6(hZ(),1)});import{readFileSync as Xy1}from"node:fs";function Zy1($){let Y=new URL($),U=Y.pathname.match(/\/webhook\/([^/]+)/);if(!U)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:U[1]}}function qy1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function Vy1($,Y){if(!$.length)return;let U=new Set($.map((J)=>{let K=J.fileName.split("/")[0],z=K.indexOf("@");return z>=0?K.slice(0,z):K}).filter((J)=>J!=="信息表.xlsx")),I=[];for(let J of Y){let K=J.document.documentId;if((J.documentAttachments.length>0||Object.values(J.expenseAttachments).some((G)=>G.length>0)||Object.values(J.personAttachments).some((G)=>G.length>0))&&!U.has(K))I.push(`Excel 会议编号「${K}」声明了附件,但在 ZIP 中找不到对应的根目录「${K}/」或「${K}@.../」。`)}let Q=new Set(Y.map((J)=>J.document.documentId));for(let J of U)if(!Q.has(J))I.push(`ZIP 根目录对应的编号「${J}」在信息表中找不到对应的会议编号。`);if(I.length)throw new R5(I)}async function Bv0($,Y,U){let I=[],Q=$;if(qy1($,Y)){I=await ST0($),gT0(I,U);let G=I.find((H)=>H.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");Q=await Im($,G)}let J=await iT0(Q);Vy1(I,J);let K=cT0(I,J),z=J.map((G)=>G.document);return{entries:I,parsed:J,plans:K,documents:z,fileBuffer:$}}async function uI($,Y,U){let I=await Bv0($,Y,U),Q=I.parsed.map((J,K)=>Hm(J.document,I.plans[K],new Map));return{warnings:[],documents:Q,attachmentPlan:I.plans}}async function gT($,Y,U){let I=await Bv0($,Y,U.materialPackFilePolicy),{baseUrl:Q,webhookId:J}=Zy1(U.webhookUrl),K=[];for(let z=0;z<I.parsed.length;z+=1){let G=I.parsed[z],H=I.plans[z],W=new Map,X=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let V of X)for(let w of V.paths){if(W.has(w))continue;let M=I.entries.find((T)=>T.fileName===w);if(!M)continue;process.stderr.write(`⬆ 上传附件: ${w}
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:W?J:Z?V:G,type:X,mode:Z?"auto_login":"direct",sealResultUrl:G,hoseDocumentUrl:J,documentUrl:J,ssoUrl:V,expiresIn:Z?q:void 0,identity:w,warning:M,hoseDomain:Q.type==="hose"?wg1(Q.domain):void 0,recordId:I.id,sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId,sourceSystem:I.sourceSystem,missing:{hoseDocumentUrl:!J?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:L.object({query:L.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:L.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:L.string().optional().describe("模拟批次 ID"),latest:L.boolean().optional().describe("只返回最新一条匹配记录"),fields:L.union([L.string(),L.array(L.string())]).optional().describe("限制返回字段"),limit:L.number().int().positive().max(100).optional(),maxScan:L.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:L.boolean().optional()}),handler:async($,Y,U)=>{let z=Y.sn??Y.query;if(!z)throw Error("query or sn is required");let I=await Mg1($,{query:z,sn:Y.sn,batchId:Y.batchId,latest:Y.latest,limit:Y.latest?1:Y.limit??20,maxScan:Y.maxScan??1000}),Q=await Promise.all(I.records.map((X)=>H4($,X.id))),J=y_0(Y.fields),K=Q.map((X)=>Vg1(X,J)),G=Q.find((X)=>X.ruleSetVersionNumber!==void 0)?.ruleSetVersionNumber,H=G===void 0?"latest":String(G),W=G===void 0?'"latestRuleVersion":true':`"ruleVersionNumber":${G}`;return{query:z,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:I.total,scanned:I.scanned,matched:K.length,records:K,next:{getSummary:`seal-useapproval-runsget<recordId>--summary--corp${U.corp.id}`,getRuleVersion:`seal-userulesversion${H}--corp${U.corp.id}`,searchRuleVersion:`seal-usetoolseal_approval_search--corp${U.corp.id}--json'{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${W}}'`,getVersionContext:`seal-usetoolseal_approval_context_get--corp${U.corp.id}--json'{${W}}'`},...Y.includeBridge?{bridge:TT(Q)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:L.object({batchId:L.string().describe("simulation batch ID"),query:L.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,Y)=>{let U=ml(await Pg($,Y.batchId),Y.query);return{batchId:Y.batchId,count:U.length,records:U.map(fz),bridge:TT(U)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:L.object({mode:L.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:L.array(L.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:L.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:L.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:L.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:L.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:L.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:L.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:L.array(L.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:L.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:L.record(L.string(),L.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:L.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:L.record(L.string(),L.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,Y)=>{let U=Y.mode??"hosecloud",z=Y.signKey;if(U==="hosecloud"&&!z){if(z=(await jg($)).find((K)=>K.signKey)?.signKey,!z)throw Error("
Line truncated
`)}function Rg1($){let Y=[];if(Y.push(`seal-use${$.area}-${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");let U=new Map;for(let I of $.commands){let Q=I.group??"",J=U.get(Q)??[];J.push(I),U.set(Q,J)}let z=[...$.groupOrder??[],...[...U.keys()].filter((I)=>!$.groupOrder?.includes(I))];for(let I of z){let Q=U.get(I);if(!Q)continue;if(I)Y.push(""),Y.push(`${I}:`);for(let J of Q)for(let K of J.usage)Y.push(`${K}`)}if($.commands.some((I)=>I.name))Y.push(""),Y.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return Y.join(`
`)}function $v0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of Yv0)for(let U of Y.commands)for(let z of U.usage)$.push(`${z}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var Yv0;var el=m(()=>{O8();Yv0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",groupOrder:["企业接入","发现与选择","企业配置","测试配对与验证","Hose 专属能力"],commands:[{name:"list",group:"发现与选择",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],group:"发现与选择",summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],group:"发现与选择",summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",group:"发现与选择",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",group:"发现与选择",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",group:"企业配置",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"rename",group:"企业配置",summary:"Rename an enterprise display name",usage:["seal-use corps rename <corpId> --name <newName>"],options:[{flag:"--name <newName>",description:"New human-readable enterprise name (required)"}],description:"Safely updates the display name of a configured enterprise without modifying underlying files manually."},{name:"bind-test",group:"测试配对与验证",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",group:"测试配对与验证",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",group:"测试配对与验证",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new versi
Line truncated
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:W?K:Z?V:G,type:X,mode:Z?"auto_login":"direct",sealResultUrl:G,hoseDocumentUrl:K,documentUrl:K,ssoUrl:V,expiresIn:Z?q:void 0,identity:w,warning:M,hoseDomain:J.type==="hose"?Ey1(J.domain):void 0,recordId:Q.id,sourceDocumentSN:Q.sourceDocumentSN,sourceDocumentId:Q.sourceDocumentId,sourceSystem:Q.sourceSystem,missing:{hoseDocumentUrl:!K?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:L.object({query:L.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:L.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:L.string().optional().describe("模拟批次 ID"),latest:L.boolean().optional().describe("只返回最新一条匹配记录"),fields:L.union([L.string(),L.array(L.string())]).optional().describe("限制返回字段"),limit:L.number().int().positive().max(100).optional(),maxScan:L.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:L.boolean().optional()}),handler:async($,Y,U)=>{let I=Y.sn??Y.query;if(!I)throw Error("query or sn is required");let Q=await Cy1($,{query:I,sn:Y.sn,batchId:Y.batchId,latest:Y.latest,limit:Y.latest?1:Y.limit??20,maxScan:Y.maxScan??1000}),J=await Promise.all(Q.records.map((X)=>G4($,X.id))),K=jv0(Y.fields),z=J.map((X)=>Ay1(X,K)),G=J.find((X)=>X.ruleSetVersionNumber!==void 0)?.ruleSetVersionNumber,H=G===void 0?"latest":String(G),W=G===void 0?'"latestRuleVersion":true':`"ruleVersionNumber":${G}`;return{query:I,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:Q.total,scanned:Q.scanned,matched:z.length,records:z,next:{getSummary:`seal-useapproval-runsget<recordId>--summary--corp${U.corp.id}`,getRuleVersion:`seal-userulesversion${H}--corp${U.corp.id}`,searchRuleVersion:`seal-usetoolseal_approval_search--corp${U.corp.id}--json'{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${W}}'`,getVersionContext:`seal-usetoolseal_approval_context_get--corp${U.corp.id}--json'{${W}}'`},...Y.includeBridge?{bridge:zo(J)}:{}}}},{name:"seal_approval_run_langfuse_bridge_get",description:"从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",parameters:L.object({recordId:L.string().optional(),sourceDocumentSN:L.string().optional(),sourceDocumentId:L.string().optional(),simulationBatchId:L.string().optional(),limit:L.number().int().positive().max(100).optional()}),handler:async($,Y)=>{let I=(Y.simulationBatchId?await bM($,Y.simulationBatchId):(await x4($,{limit:Y.limit??50,search:Y.sourceDocumentSN??Y.sourceDocumentId,sourceDocumentSN:Y.sourceDocumentSN,sourceDocumentId:Y.sourceDocumentId})).records).filter((Q)=>hy1(Q,{recordId:Y.recordId,sourceDocumentSN:Y.sourceDocumentSN,sourceDocumentId:Y.sourceDocumentId}));return{count:I.length,records:I.map(Ev0),bridge:zo(I)}}},{name:"seal_approval_runs_stats",description:"统计审核记录状态分布、来源系统分布及按单号/ID去重统计",parameters:L.object({since:L.string().optional().describe("时间范围,如 3months, 7days, 24hours"),dedupeBy:L.enum(["sourceDocumentSN","sourceDocumentId","id"]).default("sourceDocumentSN").describe("去重字段"),status:L.string().optional(),sourceSystem:L.string().optional(),taskMode:L.string().optional()}),handler:async($,Y)=>{let U=await x4($,{limit:1000,status:Y.status,sourceSystem:Y.sourceSystem,taskMode:Y.taskMode}),I=Y.dedupeBy??"sourceDocumentSN",Q=U.records,J={},K={},z=new Set;for(let H of Q){let W=H.status??"unknown";J[W]=(J[W]??0)+1;let X=H.sourceSystem??"unknown";K[X]=(K[X]??0)+1;let Z=H[I];if(Z)z.add(String(Z))}let G=Math.max(0,Q.length-z.size);return{total:Q.length,dedupeBy:I,unique:z.size,duplicateRuns:G,dedupeNote:G>0?`存在${G}笔重复运行记录(同一单据重跑或修改重推)`:"全部单据唯一,无重复记录",byStatus:J,bySourceSystem:K}}},{name:"seal_approval_runs_count",description:"统计符合条件的审核记录总数",parameters:L.object({status:L.string().optional(),sourceSystem:L.string().optional(),taskMode:L.string().optional(),search:L.string().optional(),startDate:L.string().optional().describe("起始时间戳(毫秒)或日期字符串"),endDate:L.string().optional().describe("结束时间戳(毫秒)或日期字符串")}),handler:async($,Y)=>{let U=await x4($,{limit:1,status:Y.status,sourceSystem:Y.sourceSystem,taskMode:Y.taskMode,search:Y.search,startDate:n2(Y.startDate,!1),endDate:n2(Y.endDate,!0)});return{total:U.total??U.records.l
Line truncated
`)}function sy1($){let Y=[];if(Y.push(`seal-use${$.area}-${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");let U=new Map;for(let Q of $.commands){let J=Q.group??"",K=U.get(J)??[];K.push(Q),U.set(J,K)}let I=[...$.groupOrder??[],...[...U.keys()].filter((Q)=>!$.groupOrder?.includes(Q))];for(let Q of I){let J=U.get(Q);if(!J)continue;if(Q)Y.push(""),Y.push(`${Q}:`);for(let K of J)for(let z of K.usage)Y.push(`${z}`)}if($.commands.some((Q)=>Q.name))Y.push(""),Y.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return Y.join(`
`)}function iv0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of cv0)for(let U of Y.commands)for(let I of U.usage)$.push(`${I}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var cv0;var Vo=m(()=>{J$();cv0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",groupOrder:["企业接入","发现与选择","企业配置","测试配对与验证","Hose 专属能力"],commands:[{name:"list",group:"发现与选择",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],group:"发现与选择",summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],group:"发现与选择",summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",group:"发现与选择",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",group:"发现与选择",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",group:"企业配置",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"rename",group:"企业配置",summary:"Rename an enterprise display name",usage:["seal-use corps rename <corpId> --name <newName>"],options:[{flag:"--name <newName>",description:"New human-readable enterprise name (required)"}],description:"Safely updates the display name of a configured enterprise without modifying underlying files manually."},{name:"bind-test",group:"测试配对与验证",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",group:"测试配对与验证",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",group:"测试配对与验证",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new versi
Line truncated
`;if(Y.outputFile){_g1(Y.outputFile,U),console.log(JSON.stringify({outputFile:Y.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function gg1($,Y={}){if(Y.allowFull||Y.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>Sg1)throw new JP(`Outputislarge(${U}bytes).Use--summary,--fields,--count,or--output-file;pass--fullonlywhenyoureallyneedthefullresponse.`)}function Qv0($,Y){if(Y)return;let U=$&&typeof $==="object"?$:{},z=typeof U.count==="number"?U.count:void 0,I=Array.isArray(U.rules)?U.rules.length:void 0,Q=Buffer.byteLength(JSON.stringify($),"utf-8"),J=z??I??0;if(J>vg1||Q>hg1)throw new JP(`Rulelistislarge(${J}rules,${Q}bytes).Use"seal-use rules list --summary","seal-use rules count",or--output-file;pass--fullonlywhenyoureallyneedfulldescriptions.`,"seal-use rules list --summary")}function j0($){return{allowFull:G0($.full)===!0,outputFile:S($.outputFile)??S($["output-file"])}}function Jv0($=[]){console.log(zv0($))}var vg1=100,hg1=120000,Iv0,Sg1=200000;var m1=m(()=>{Z4();O8();el();Iv0=["code","status","strictness","scope","updatedAt"]});var Yo={};T8(Yo,{selectCorp:()=>M1,runToolResult:()=>M$,runTool:()=>x0,globalConfigSummary:()=>t2});function M1($){let Y=t8(),U=v4(),z=n2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$},x3());return rA0(z.id),z}function t2($=v4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:Zz()}}async function x0($,Y,U,z,I={}){R0(await M$($,Y,U,z),I)}async function M$($,Y,U,z){let I=Pq.find((K)=>K.name===$);if(!I)throw Error(`UnknownSealtool:${$}`);let Q=Object.fromEntries(Object.entries(z).filter(([,K])=>K!==void 0)),J=I.handler;return J(Y,Q,{corp:U})}var O4=m(()=>{T5();UP();jq();m1()});import{existsSync as Kv0}from"node:fs";async function Gv0($,Y){if(!Kv0($))throw Error(`Filenotfound:${$}`);let U=xz($);console.log(JSON.stringify(await kz(U.fileBuffer,U.fileName,Y),null,2))}async function gT($,Y,U,z,I){if($==="ready"||$==="status"){let Q=Y??S(I.options.file)??S(I.options.input),J=await NT(U,z,{filePath:Q,webhook:S(I.options.webhook)??S(I.options.selector)});if(console.error(`[webhook-ready]企业环境:${J.corp.name}(${J.corp.id})[${J.stateMode}]`),J.corp.tenant?.name)console.error(`[webhook-ready]租户信息:${J.corp.tenant.name}(${J.corp.tenant.id})`);console.error(`[webhook-ready]凭证状态:${J.authStatus==="ok"?"OK":`异常 (${J.authError})`}`),console.error(`[webhook-ready]Webhook通道:${J.activeWebhooks.length}个可用`);for(let K of J.activeWebhooks){let G=K.isDefault?" [默认通道]":"";console.error(`-${K.name}(${K.id})mode=${K.mode}${G}`)}if(J.materialPack)console.error(`[webhook-ready]材料包预检:${J.materialPack.valid?`通过 (${J.materialPack.documentCount} 单)`:`失败 (${J.materialPack.errors?.join("; ")})`}`);if(J.ready)console.error(`\uD83D\uDFE2${J.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${J.nextAction}`);else console.error(`\uD83D\uDD34准备阶段未通过:${J.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${J.nextAction}`);console.log(JSON.stringify(J,null,2));return}if($==="replay"){let Q=Y??S(I.options.recordId)??S(I.options["record-id"])??S(I.options.id),J=S(I.options.recordIds)??S(I.options["record-ids"]),K=J?J.split(",").map((c)=>c.trim()).filter(Boolean):void 0,G=S(I.options.sn)??S(I.options.documentSn)??S(I.options["document-sn"]),H=S(I.options.sns)??S(I.options["document-sns"]),W=H?H.split(",").map((c)=>c.trim()).filter(Boolean):void 0,X=s0(I.options.limit),Z=S(I.options.status),q=S(I.options.startDate)??S(I.options["start-date"]),V=S(I.options.endDate)??S(I.options["end-date"]);if(!Q&&!K&&!G&&!W&&X===void 0)throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let w=S(I.options.sourceCorp)??S(I.options["source-corp"])??S(I.options.prodCorp)??S(I.options["prod-corp"]),M=S(I.options.targetCorp)??S(I.options["target-corp"])??S(I.options.testCorp)??S(I.options["test-corp"]),F=G0(I.options.force)===!0,{sourceCorp:N,targetCorp:O}=KP({sourceCorpId:w,targetCorpId:M,activeCorp:z,force:F},M1),D=N.id===z.id?U:await B1(N),P=O.id===z.id?U:await B1(O),T=S(I.options.webhook)??S(I.options.selector),A=S(I.options.snSuffix)??S(I.options["sn-suffix"]),j=S(I.options.snPrefix)??S(I.options["sn-prefix"]),C=S(I.options.docIdSuffix)??S(I.options["doc-id-suffix"]),b=S(I.options.docIdPrefix)??S(I.options["doc-id-prefix"]),x=G0(I.options.dryRun)??G0(I.options["dry-run"]),i=await zK({query:{recordId:Q,recordIds:K,sn:G,sns:W,limit:X,status:Z,startDate:q,endDate:V},sourceClient:D,targetClient:P,sourceCorp:N,targetCorp:O,webhookSelector:T,snPrefix:j,snSuffix:A,docIdPrefix:b,docIdSuffix:C,dr
Line truncated
or:seal-usecorpsbind-test<testCorpId>--corp<prodCorpId>[--confirm][--force]`);let Q=M1(z),J=M1(I);if(Q.id===J.id)throw h4(`Cannotbindenterprise'${Q.id}'toitself.`);if(Q.prodCorpId&&Q.prodCorpId!==J.id)throw h4(`Cannotuse'${Q.id}'asaproductionenterprisebecauseitisalreadyregisteredasatestenterprisefor'${Q.prodCorpId}'.Multi-tierchainingisnotpermitted.`);if(J.testCorpId&&J.testCorpId!==Q.id)throw h4(`Cannotbind'${J.id}'asatestenterprisebecauseitalreadyhasaboundtestenterprise'${J.testCorpId}'.Multi-tierchainingisnotpermitted.`);let K=G0(U.options.force)===!0;if(Q.testCorpId&&Q.testCorpId!==J.id||J.prodCorpId&&J.prodCorpId!==Q.id){if(!K)throw w$(`Enterprisebindingconflict:productionenterprise'${Q.id}'isboundto'${Q.testCorpId??"none"}',andtestenterprise'${J.id}'isboundto'${J.prodCorpId??"none"}'.Overwritinganexistingbindingrequires--forceand--confirm.`,`seal-usecorpsbind-test${Q.id}${J.id}--confirm--force`)}if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0)){let X=K?" --force":"";throw w$(`Refusingtobindtestenterprise'${J.name}'(${J.id})toproductionenterprise'${Q.name}'(${Q.id})without--confirm.Enterprisebindingestablishes1-to-1syncpairingandmarks'${J.id}'asatestenvironment.`,`seal-usecorpsbind-test${Q.id}${J.id}--confirm${X}`)}if(Q.testCorpId&&Q.testCorpId!==J.id)try{E9(Q.testCorpId,{prodCorpId:void 0})}catch{}if(J.prodCorpId&&J.prodCorpId!==Q.id)try{E9(J.prodCorpId,{testCorpId:void 0})}catch{}let H=E9(Q.id,{environment:"production",testCorpId:J.id}),W=E9(J.id,{environment:"test",prodCorpId:Q.id});return R0({success:!0,productionEnterprise:{id:H.id,name:H.name,environment:H.environment,testCorpId:H.testCorpId},testEnterprise:{id:W.id,name:W.name,environment:W.environment,prodCorpId:W.prodCorpId}}),!0}if($==="unbind-test"){let z=Y??S(U.options.corp),I=M1(z);if(!I.testCorpId&&!I.prodCorpId)return R0({unbound:!1,message:`Enterprise'${I.name}'(${I.id})doesnothaveanactivetestenterprisebinding.`}),!0;let Q=I.testCorpId?I.id:I.prodCorpId,J=I.testCorpId?I.testCorpId:I.id;if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0))throw w$(`Refusingtounbindproductionenterprise'${Q}'andtestenterprise'${J}'without--confirm.`,`seal-usecorpsunbind-test${I.id}--confirm`);E9(Q,{testCorpId:void 0});try{E9(J,{prodCorpId:void 0})}catch{}return R0({success:!0,unboundProduction:Q,unboundTest:J}),!0}return!1}var Vv0=m(()=>{T5();O4();O8();Z4();m1()});function yT($){let Y;try{Y=new URL($.trim())}catch{throw Error("Invalid Seal delegate link: expected a valid HTTPS URL")}if(Y.protocol!=="https:")throw Error("Invalid Seal delegate link: expected HTTPS");let U=Y.hostname.toLowerCase();if(!U.endsWith(Lv0))throw Error(`InvalidSealdelegatelink:expectedhostendingin${Lv0},got${U}`);let z=Y.pathname.replace(/\/+$/,"");if(z!==Fv0)throw Error(`InvalidSealdelegatelink:expectedpath${Fv0},got${z}`);let I=Y.searchParams.get("token");if(!I)throw Error("Invalid Seal delegate link: token query parameter is required");return{sealUrl:Y.origin,delegateToken:I}}async function wv0($){let Y=typeof $==="string"?yT($):$;return(await B6(Y.sealUrl,void 0).post("api/v1/delegation/preview",{json:{token:Y.delegateToken}}).json()).data}async function Mv0($){let Y=typeof $==="string"?yT($):$,U=Y.sealUrl,z=B6(U,void 0),I=await z.post("api/v1/delegation/consume",{json:{token:Y.delegateToken}}),Q=I.headers.get("set-cookie")??"",J=typeof I.headers.getSetCookie==="function"?I.headers.getSetCookie():[Q],K="";for(let M of J)if(M&&M.includes("session_token=")){K=(M.split(";")[0]??"").trim();break}let G;try{G=await z.get("api/auth/get-session",{headers:K?{cookie:K}:{}}).json()}catch{}let H=G?.session?.token;if(!H&&K){let M=K.match(/session_token=([^.;]+)/);if(M?.[1])H=decodeURIComponent(M[1])}if(!H)throw Error("Seal delegate exchange did not return a session token");let W=86400;if(G?.session?.expiresAt){let M=new Date(G.session.expiresAt).getTime();if(Number.isFinite(M)){let F=Math.floor((M-Date.now())/1000);if(F>0)W=F}}let Z=await B6(U,H).get("api/v1/auth/me").json(),q=Z.data&&typeof Z.data==="object"?Z.data:Z,V=q.user??G?.user??{},w=q.tenant??{};return{sealUrl:U,token:H,expiresIn:W,user:V,tenant:w}}function kT($){let Y=[],U=0,z="";try{let J=new URL($.trim()),K=J.hostname.toLowerCase(),G=J.pathname.replace(/\/+$/,"");if(K.endsWith(".ekuaibao.com")||K.endsWith(".hosecloud.com")||K==="ekuaibao.com"||K==="hosecloud.com")U+=40,z="host is Hose domain";if(G==="/web/thirdparty.html")U+=40,z+="; path is /web/thirdparty.html";if(J.searchParams.has("accessToken"))U+=10,z+="; has accessToken";if(J.searchParams.has("ekbCorpId"))U+=10,z+="; has ekbCorpId"}catch{U=0}if(U>0)Y.push({kind:"hose",score:U,reason:z});let I=0,Q="";try{let J=new URL($.trim()),K=J.hostname.toLowerCase(),G=J.pathname.replace(/\/+$/,"");if(K.endsWith(".sealai.cc"))I+=40,Q="host ends with .sealai.cc";if(G==="/delegate")I+=40,Q+="; path is /delegate";if(
Line truncated
`,{mode:384}),{config:U,path:I}}var Io=m(()=>{T5();sB()});function Qo($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function xT($){let Y=new Date($);if(Number.isNaN(Y.getTime()))return $;return Qo(Y.getTime())}function $5($){return typeof $==="string"&&$?$:void 0}function bg1($){return{headers:Ap.parse($.headers),cookies:Bp.parse($.cookies)}}async function ig1($,Y,U={}){let z=await Z8(B6($,Y,U));return{user:z.user??{},tenant:z.tenant??{}}}async function Ov0($){let Y=$.sealUrl.replace(/\/+$/,""),U=$.expiresIn??2592000,z=$.force===!0||$.verify===!1?!1:!0,I=bg1($),Q=z?await ig1(Y,$.token,A6(I)):void 0,J=Dv0($,{token:$.token,sealUrl:Y,expiresIn:U,expiresAt:$.expiresAt,verify:z,remote:Q,custom:I}),K=$.tenantId??$5(Q?.tenant.id),G=$.tenantSlug??$5(Q?.tenant.tenantSlug);return{...J,verified:z,tenantId:K,tenantSlug:G}}function Nv0($){let Y=$5($.session.tenant.tenantSlug),U=$5($.session.tenant.id),z=Y??U??"seal-delegate";return{...Dv0({id:z,corpId:z,name:$.name,provider:"seal",overwrite:$.overwrite},{token:$.session.token,sealUrl:$.session.sealUrl,expiresIn:$.session.expiresIn,verify:!0,remote:{user:$.session.user,tenant:$.session.tenant}}),tenantId:U,tenantSlug:Y}}function Dv0($,Y){let U=Y.remote?.user,z=Y.remote?.tenant,I=$.tenantSlug??$5(z?.tenantSlug),Q=$.tenantId??$5(z?.id),J=$.tenantName??$5(z?.name),K=$.id??I??Q;if(!K)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let G=Y.expiresAt?xT(Y.expiresAt):Qo(Date.now()+Y.expiresIn*1000),H=$.staffId??$5(U?.providerUserId)??$5(U?.id)??"seal",W=$.provider??$5(U?.provider)??$5(z?.providerConfig?.provider),X=$.corpId??I??Q??K,Z={id:K,name:$.name??J??K,environment:"production",seal:{url:Y.sealUrl,tenantSlug:I,headers:Y.custom?.headers,cookies:Y.custom?.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:Y.token,sealUrl:Y.sealUrl,expiresIn:Y.expiresIn,expiresAt:G,staffId:H,corpId:X,tenantId:Q,tenantSlug:I,tenantName:J,providerUserId:$5(U?.providerUserId),provider:W},auth:{refreshTtl:300}};return _q(Z,{overwrite:$.overwrite===!0})}var Jo=m(()=>{Io();sB();m6();X6()});async function bK($){let[Y,U]=await Promise.all([J10($),B1($)]),z=await Z8(U);return{...Y,tenantId:z.tenant.id,tenantSlug:z.tenant.tenantSlug??Y.tenantSlug,tenantName:z.tenant.name,raw:{...typeof Y.raw==="object"&&Y.raw!==null?Y.raw:{},user:{id:z.user.id,name:z.user.name,isAdmin:z.user.isAdmin,providerUserId:z.user.providerUserId,hosecloudStaff:z.user.hosecloudStaff},tenant:z.tenant}}}var fT=m(()=>{m6();Gg();X6()});async function Av0($){let Y=await rI($.appKey,$.appSecurity,$.domain),U=await FM(Y.domain,Y.openapiToken).catch(()=>[]);return{...Y,roleCount:U.reduce((z,I)=>z+I.roleDefs.length,0),roleGroups:U.map((z)=>({id:z.id,name:z.name,roleDefs:z.roleDefs.map((I)=>({id:I.id,name:I.name,sourceType:I.sourceType}))}))}}async function Bv0($){let Y=await rI($.appKey,$.appSecurity,$.domain),U=$.role??$.roleDefId??"admin",z=await FM(Y.domain,Y.openapiToken),I,Q;for(let G of z){for(let H of G.roleDefs)if(H.id===U||H.id===`${Y.corpId}:${U}`){I=H.id,Q=H.name;break}if(I)break}if(!I&&(U==="admin"||U==="主管理员"))for(let G of z){for(let H of G.roleDefs)if(H.id.endsWith(":admin")||H.name==="主管理员"){I=H.id,Q=H.name;break}if(I)break}if(!I)for(let G of z){for(let H of G.roleDefs)if(H.name.toLowerCase().includes(U.toLowerCase())){I=H.id,Q=H.name;break}if(I)break}if(!I)throw Error(`Rolenotfoundmatchingquery:'${U}'.Run'seal-use corps probe-hose'toviewallavailableroles.`);let J=await Ig(Y.domain,Y.openapiToken,I),K=await Qg(Y.domain,Y.openapiToken,J.staffs);return{domain:Y.domain,corpId:Y.corpId,corpName:Y.corpName??Y.corpId,roleId:I,roleName:Q,staffs:K}}async function vq($){let Y=$.domain,U=$.staffId??$.proxyStaffBizId,z=$.force===!0,I=z||$.verify===!1?!1:!0,Q=Y,J=$.corpId??$.corporationId,K=$.name,G;if(!Q||!J||!U){let V=await rI($.appKey,$.appSecurity,Y);Q=V.domain,J=J??V.corpId,K=K??V.corpName,G=V.openapiToken}let H=U;if(!H&&G&&Q){let V=$.role??"admin",w=await FM(Q,G).catch(()=>[]),M;for(let F of w){for(let N of F.roleDefs)if(N.id.endsWith(`:${V}`)||N.name===V||N.id===V){M=N.id;break}if(M)break}if(!M)M=w.find((F)=>F.roleDefs.some((N)=>N.id.endsWith(":admin")))?.roleDefs.find((F)=>F.id.endsWith(":admin"))?.id;if(M){let F=await Ig(Q,G,M).catch(()=>({staffs:[]})),N=await Qg(Q,G,F.staffs).catch(()=>[]);if($.staffName||$.staffPhone){let O=N.filter((D)=>{if($.staffName&&D.name!==$.staffName&&!D.name.includes($.staffName))return!1;if($.staffPhone&&(!D.cellphone||!D.cellphone.includes($.staffPhone)))return!1;return!0});if(O.length===1&&O[0])H=O[0].id;else if(O.length>1)throw Error(`Multiplestaffmembersmatched'${$.staffName??$.staffPhone}':${O.map((D)=>`${D.name}(${D.id})`).join(", ")}.PleasespecifyexactstaffId.`);else throw Error(`Nostaffmemberfoundmatching'${$.staffName??$.staffPhone}'underrole${M}.Run'seal-use corps hose-staffs'toviewcandidates.`)}else if(!z){let O=N.map(
Line truncated
`+"\uD83D\uDCA1 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。",z);if(U.keyId||U.appKey){let I=$.find((Q)=>U.keyId&&Q.id===U.keyId||U.appKey&&Q.appKey===U.appKey);if(!I)throw new bz(`指定的合思密钥不存在,请从上述候选列表中选择正确的appKey或keyId。
`;if(Y.outputFile){ay1(Y.outputFile,U),console.log(JSON.stringify({outputFile:Y.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function Yk1($,Y={}){if(Y.allowFull||Y.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>$k1)throw new rZ(`Outputislarge(${U}bytes).Use--summary,--fields,--count,or--output-file;pass--fullonlywhenyoureallyneedthefullresponse.`)}function mv0($,Y){if(Y)return;let U=$&&typeof $==="object"?$:{},I=typeof U.count==="number"?U.count:void 0,Q=Array.isArray(U.rules)?U.rules.length:void 0,J=Buffer.byteLength(JSON.stringify($),"utf-8"),K=I??Q??0;if(K>ty1||J>ey1)throw new rZ(`Rulelistislarge(${K}rules,${J}bytes).Use"seal-use rules list --summary","seal-use rules count",or--output-file;pass--fullonlywhenyoureallyneedfulldescriptions.`,"seal-use rules list --summary")}function E0($){return{allowFull:G0($.full)===!0,outputFile:h($.outputFile)??h($["output-file"])}}function lv0($=[]){console.log(dv0($))}var ty1=100,ey1=120000,pv0,$k1=200000;var l1=m(()=>{q4();J$();Vo();pv0=["code","status","strictness","scope","updatedAt"]});var Fo={};Z8(Fo,{selectCorp:()=>M1,runToolResult:()=>P$,runTool:()=>x0,globalConfigSummary:()=>e2});function M1($){let Y=Y$(),U=A4(),I=d2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$},i3());return WA0(I.id),I}function e2($=A4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:qI()}}async function x0($,Y,U,I,Q={}){R0(await P$($,Y,U,I),Q)}async function P$($,Y,U,I){let Q=vq.find((z)=>z.name===$);if(!Q)throw Error(`UnknownSealtool:${$}`);let J=Object.fromEntries(Object.entries(I).filter(([,z])=>z!==void 0)),K=Q.handler;return K(Y,J,{corp:U})}var O4=m(()=>{l$();HP();Sq();l1()});import{existsSync as ov0}from"node:fs";async function rv0($,Y){if(!ov0($))throw Error(`Filenotfound:${$}`);let U=bI($);console.log(JSON.stringify(await uI(U.fileBuffer,U.fileName,Y),null,2))}async function iT($,Y,U,I,Q){if($==="ready"||$==="status"){let J=Y??h(Q.options.file)??h(Q.options.input),K=await yT(U,I,{filePath:J,webhook:h(Q.options.webhook)??h(Q.options.selector)});if(console.error(`[webhook-ready]企业环境:${K.corp.name}(${K.corp.id})[${K.stateMode}]`),K.corp.tenant?.name)console.error(`[webhook-ready]租户信息:${K.corp.tenant.name}(${K.corp.tenant.id})`);console.error(`[webhook-ready]凭证状态:${K.authStatus==="ok"?"OK":`异常 (${K.authError})`}`),console.error(`[webhook-ready]Webhook通道:${K.activeWebhooks.length}个可用`);for(let z of K.activeWebhooks){let G=z.isDefault?" [默认通道]":"";console.error(`-${z.name}(${z.id})mode=${z.mode}${G}`)}if(K.materialPack)console.error(`[webhook-ready]材料包预检:${K.materialPack.valid?`通过 (${K.materialPack.documentCount} 单)`:`失败 (${K.materialPack.errors?.join("; ")})`}`);if(K.ready)console.error(`\uD83D\uDFE2${K.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${K.nextAction}`);else console.error(`\uD83D\uDD34准备阶段未通过:${K.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${K.nextAction}`);console.log(JSON.stringify(K,null,2));return}if($==="replay"){let J=Y??h(Q.options.recordId)??h(Q.options["record-id"])??h(Q.options.id),K=h(Q.options.recordIds)??h(Q.options["record-ids"]),z=K?K.split(",").map((c)=>c.trim()).filter(Boolean):void 0,G=h(Q.options.sn)??h(Q.options.documentSn)??h(Q.options["document-sn"]),H=h(Q.options.sns)??h(Q.options["document-sns"]),W=H?H.split(",").map((c)=>c.trim()).filter(Boolean):void 0,X=s0(Q.options.limit),Z=h(Q.options.status),q=h(Q.options.startDate)??h(Q.options["start-date"]),V=h(Q.options.endDate)??h(Q.options["end-date"]);if(!J&&!z&&!G&&!W&&X===void 0)throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let w=h(Q.options.sourceCorp)??h(Q.options["source-corp"])??h(Q.options.prodCorp)??h(Q.options["prod-corp"]),M=h(Q.options.targetCorp)??h(Q.options["target-corp"])??h(Q.options.testCorp)??h(Q.options["test-corp"]),F=G0(Q.options.force)===!0,{sourceCorp:N,targetCorp:O}=AP({sourceCorpId:w,targetCorpId:M,activeCorp:I,force:F},M1),D=N.id===I.id?U:await A1(N),P=O.id===I.id?U:await A1(O),T=h(Q.options.webhook)??h(Q.options.selector),B=h(Q.options.snSuffix)??h(Q.options["sn-suffix"]),E=h(Q.options.snPrefix)??h(Q.options["sn-prefix"]),C=h(Q.options.docIdSuffix)??h(Q.options["doc-id-suffix"]),b=h(Q.options.docIdPrefix)??h(Q.options["doc-id-prefix"]),x=G0(Q.options.dryRun)??G0(Q.options["dry-run"]),i=await Gz({query:{recordId:J,recordIds:z,sn:G,sns:W,limit:X,status:Z,startDate:q,endDate:V},sourceClient:D,targetClient:P,sourceCorp:N,targetCorp:O,webhookSelector:T,snPrefix:E,snSuffix:B,docIdPrefix:b,docIdSuffix:C,dr
Line truncated
or:seal-usecorpsbind-test<testCorpId>--corp<prodCorpId>[--confirm][--force]`);let J=M1(I),K=M1(Q);if(J.id===K.id)throw P4(`Cannotbindenterprise'${J.id}'toitself.`);if(J.prodCorpId&&J.prodCorpId!==K.id)throw P4(`Cannotuse'${J.id}'asaproductionenterprisebecauseitisalreadyregisteredasatestenterprisefor'${J.prodCorpId}'.Multi-tierchainingisnotpermitted.`);if(K.testCorpId&&K.testCorpId!==J.id)throw P4(`Cannotbind'${K.id}'asatestenterprisebecauseitalreadyhasaboundtestenterprise'${K.testCorpId}'.Multi-tierchainingisnotpermitted.`);let z=G0(U.options.force)===!0;if(J.testCorpId&&J.testCorpId!==K.id||K.prodCorpId&&K.prodCorpId!==J.id){if(!z)throw U$(`Enterprisebindingconflict:productionenterprise'${J.id}'isboundto'${J.testCorpId??"none"}',andtestenterprise'${K.id}'isboundto'${K.prodCorpId??"none"}'.Overwritinganexistingbindingrequires--forceand--confirm.`,`seal-usecorpsbind-test${J.id}${K.id}--confirm--force`)}if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0)){let X=z?" --force":"";throw U$(`Refusingtobindtestenterprise'${K.name}'(${K.id})toproductionenterprise'${J.name}'(${J.id})without--confirm.Enterprisebindingestablishes1-to-1syncpairingandmarks'${K.id}'asatestenvironment.`,`seal-usecorpsbind-test${J.id}${K.id}--confirm${X}`)}if(J.testCorpId&&J.testCorpId!==K.id)try{R9(J.testCorpId,{prodCorpId:void 0})}catch{}if(K.prodCorpId&&K.prodCorpId!==J.id)try{R9(K.prodCorpId,{testCorpId:void 0})}catch{}let H=R9(J.id,{environment:"production",testCorpId:K.id}),W=R9(K.id,{environment:"test",prodCorpId:J.id});return R0({success:!0,productionEnterprise:{id:H.id,name:H.name,environment:H.environment,testCorpId:H.testCorpId},testEnterprise:{id:W.id,name:W.name,environment:W.environment,prodCorpId:W.prodCorpId}}),!0}if($==="unbind-test"){let I=Y??h(U.options.corp),Q=M1(I);if(!Q.testCorpId&&!Q.prodCorpId)return R0({unbound:!1,message:`Enterprise'${Q.name}'(${Q.id})doesnothaveanactivetestenterprisebinding.`}),!0;let J=Q.testCorpId?Q.id:Q.prodCorpId,K=Q.testCorpId?Q.testCorpId:Q.id;if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0))throw U$(`Refusingtounbindproductionenterprise'${J}'andtestenterprise'${K}'without--confirm.`,`seal-usecorpsunbind-test${Q.id}--confirm`);R9(J,{testCorpId:void 0});try{R9(K,{prodCorpId:void 0})}catch{}return R0({success:!0,unboundProduction:J,unboundTest:K}),!0}return!1}var YS0=m(()=>{l$();O4();J$();q4();l1()});function cT($){let Y;try{Y=new URL($.trim())}catch{throw Error("Invalid Seal delegate link: expected a valid HTTPS URL")}if(Y.protocol!=="https:")throw Error("Invalid Seal delegate link: expected HTTPS");let U=Y.hostname.toLowerCase();if(!U.endsWith(US0))throw Error(`InvalidSealdelegatelink:expectedhostendingin${US0},got${U}`);let I=Y.pathname.replace(/\/+$/,"");if(I!==IS0)throw Error(`InvalidSealdelegatelink:expectedpath${IS0},got${I}`);let Q=Y.searchParams.get("token");if(!Q)throw Error("Invalid Seal delegate link: token query parameter is required");return{sealUrl:Y.origin,delegateToken:Q}}async function QS0($){let Y=typeof $==="string"?cT($):$;return(await T6(Y.sealUrl,void 0).post("api/v1/delegation/preview",{json:{token:Y.delegateToken}}).json()).data}async function JS0($){let Y=typeof $==="string"?cT($):$,U=Y.sealUrl,I=T6(U,void 0),Q=await I.post("api/v1/delegation/consume",{json:{token:Y.delegateToken}}),J=Q.headers.get("set-cookie")??"",K=typeof Q.headers.getSetCookie==="function"?Q.headers.getSetCookie():[J],z="";for(let M of K)if(M&&M.includes("session_token=")){z=(M.split(";")[0]??"").trim();break}let G;try{G=await I.get("api/auth/get-session",{headers:z?{cookie:z}:{}}).json()}catch{}let H=G?.session?.token;if(!H&&z){let M=z.match(/session_token=([^.;]+)/);if(M?.[1])H=decodeURIComponent(M[1])}if(!H)throw Error("Seal delegate exchange did not return a session token");let W=86400;if(G?.session?.expiresAt){let M=new Date(G.session.expiresAt).getTime();if(Number.isFinite(M)){let F=Math.floor((M-Date.now())/1000);if(F>0)W=F}}let Z=await T6(U,H).get("api/v1/auth/me").json(),q=Z.data&&typeof Z.data==="object"?Z.data:Z,V=q.user??G?.user??{},w=q.tenant??{};return{sealUrl:U,token:H,expiresIn:W,user:V,tenant:w}}function nT($){let Y=[],U=0,I="";try{let K=new URL($.trim()),z=K.hostname.toLowerCase(),G=K.pathname.replace(/\/+$/,"");if(z.endsWith(".ekuaibao.com")||z.endsWith(".hosecloud.com")||z==="ekuaibao.com"||z==="hosecloud.com")U+=40,I="host is Hose domain";if(G==="/web/thirdparty.html")U+=40,I+="; path is /web/thirdparty.html";if(K.searchParams.has("accessToken"))U+=10,I+="; has accessToken";if(K.searchParams.has("ekbCorpId"))U+=10,I+="; has ekbCorpId"}catch{U=0}if(U>0)Y.push({kind:"hose",score:U,reason:I});let Q=0,J="";try{let K=new URL($.trim()),z=K.hostname.toLowerCase(),G=K.pathname.replace(/\/+$/,"");if(z.endsWith(".sealai.cc"))Q+=40,J="host ends with .sealai.cc";if(G==="/delegate")Q+=40,J+="; path is /delegate";if(
Line truncated
`,{mode:384}),{config:U,path:Q}}var Oo=m(()=>{l$();IP()});function No($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function dT($){let Y=new Date($);if(Number.isNaN(Y.getTime()))return $;return No(Y.getTime())}function Q5($){return typeof $==="string"&&$?$:void 0}function zk1($){return{headers:jd.parse($.headers),cookies:Cd.parse($.cookies)}}async function Gk1($,Y,U={}){let I=await o6(T6($,Y,U));return{user:I.user??{},tenant:I.tenant??{}}}async function KS0($){let Y=$.sealUrl.replace(/\/+$/,""),U=$.expiresIn??2592000,I=$.force===!0||$.verify===!1?!1:!0,Q=zk1($),J=I?await Gk1(Y,$.token,P6(Q)):void 0,K=GS0($,{token:$.token,sealUrl:Y,expiresIn:U,expiresAt:$.expiresAt,verify:I,remote:J,custom:Q}),z=$.tenantId??Q5(J?.tenant.id),G=$.tenantSlug??Q5(J?.tenant.tenantSlug);return{...K,verified:I,tenantId:z,tenantSlug:G}}function zS0($){let Y=Q5($.session.tenant.tenantSlug),U=Q5($.session.tenant.id),I=Y??U??"seal-delegate";return{...GS0({id:I,corpId:I,name:$.name,provider:"seal",overwrite:$.overwrite},{token:$.session.token,sealUrl:$.session.sealUrl,expiresIn:$.session.expiresIn,verify:!0,remote:{user:$.session.user,tenant:$.session.tenant}}),tenantId:U,tenantSlug:Y}}function GS0($,Y){let U=Y.remote?.user,I=Y.remote?.tenant,Q=$.tenantSlug??Q5(I?.tenantSlug),J=$.tenantId??Q5(I?.id),K=$.tenantName??Q5(I?.name),z=$.id??Q??J;if(!z)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let G=Y.expiresAt?dT(Y.expiresAt):No(Date.now()+Y.expiresIn*1000),H=$.staffId??Q5(U?.providerUserId)??Q5(U?.id)??"seal",W=$.provider??Q5(U?.provider)??Q5(I?.providerConfig?.provider),X=$.corpId??Q??J??z,Z={id:z,name:$.name??K??z,environment:"production",seal:{url:Y.sealUrl,tenantSlug:Q,headers:Y.custom?.headers,cookies:Y.custom?.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:Y.token,sealUrl:Y.sealUrl,expiresIn:Y.expiresIn,expiresAt:G,staffId:H,corpId:X,tenantId:J,tenantSlug:Q,tenantName:K,providerUserId:Q5(U?.providerUserId),provider:W},auth:{refreshTtl:300}};return kq(Z,{overwrite:$.overwrite===!0})}var Do=m(()=>{Oo();IP();f6();H4()});async function nz($){let[Y,U]=await Promise.all([D10($),A1($)]),I=await o6(U);return{...Y,tenantId:I.tenant.id,tenantSlug:I.tenant.tenantSlug??Y.tenantSlug,tenantName:I.tenant.name,raw:{...typeof Y.raw==="object"&&Y.raw!==null?Y.raw:{},user:{id:I.user.id,name:I.user.name,isAdmin:I.user.isAdmin,providerUserId:I.user.providerUserId,hosecloudStaff:I.user.hosecloudStaff},tenant:I.tenant}}}var pT=m(()=>{f6();Lg();H4()});async function HS0($){let Y=await sQ($.appKey,$.appSecurity,$.domain),U=await BM(Y.domain,Y.openapiToken).catch(()=>[]);return{...Y,roleCount:U.reduce((I,Q)=>I+Q.roleDefs.length,0),roleGroups:U.map((I)=>({id:I.id,name:I.name,roleDefs:I.roleDefs.map((Q)=>({id:Q.id,name:Q.name,sourceType:Q.sourceType}))}))}}async function WS0($){let Y=await sQ($.appKey,$.appSecurity,$.domain),U=$.role??$.roleDefId??"admin",I=await BM(Y.domain,Y.openapiToken),Q,J;for(let G of I){for(let H of G.roleDefs)if(H.id===U||H.id===`${Y.corpId}:${U}`){Q=H.id,J=H.name;break}if(Q)break}if(!Q&&(U==="admin"||U==="主管理员"))for(let G of I){for(let H of G.roleDefs)if(H.id.endsWith(":admin")||H.name==="主管理员"){Q=H.id,J=H.name;break}if(Q)break}if(!Q)for(let G of I){for(let H of G.roleDefs)if(H.name.toLowerCase().includes(U.toLowerCase())){Q=H.id,J=H.name;break}if(Q)break}if(!Q)throw Error(`Rolenotfoundmatchingquery:'${U}'.Run'seal-use corps probe-hose'toviewallavailableroles.`);let K=await Xg(Y.domain,Y.openapiToken,Q),z=await Zg(Y.domain,Y.openapiToken,K.staffs);return{domain:Y.domain,corpId:Y.corpId,corpName:Y.corpName??Y.corpId,roleId:Q,roleName:J,staffs:z}}async function xq($){let Y=$.domain,U=$.staffId??$.proxyStaffBizId,I=$.force===!0,Q=I||$.verify===!1?!1:!0,J=Y,K=$.corpId??$.corporationId,z=$.name,G;if(!J||!K||!U){let V=await sQ($.appKey,$.appSecurity,Y);J=V.domain,K=K??V.corpId,z=z??V.corpName,G=V.openapiToken}let H=U;if(!H&&G&&J){let V=$.role??"admin",w=await BM(J,G).catch(()=>[]),M;for(let F of w){for(let N of F.roleDefs)if(N.id.endsWith(`:${V}`)||N.name===V||N.id===V){M=N.id;break}if(M)break}if(!M)M=w.find((F)=>F.roleDefs.some((N)=>N.id.endsWith(":admin")))?.roleDefs.find((F)=>F.id.endsWith(":admin"))?.id;if(M){let F=await Xg(J,G,M).catch(()=>({staffs:[]})),N=await Zg(J,G,F.staffs).catch(()=>[]);if($.staffName||$.staffPhone){let O=N.filter((D)=>{if($.staffName&&D.name!==$.staffName&&!D.name.includes($.staffName))return!1;if($.staffPhone&&(!D.cellphone||!D.cellphone.includes($.staffPhone)))return!1;return!0});if(O.length===1&&O[0])H=O[0].id;else if(O.length>1)throw Error(`Multiplestaffmembersmatched'${$.staffName??$.staffPhone}':${O.map((D)=>`${D.name}(${D.id})`).join(", ")}.PleasespecifyexactstaffId.`);else throw Error(`Nostaffmemberfoundmatching'${$.staffName??$.staffPhone}'underrole${M}.Run'seal-use corps hose-staffs'toviewcandidates.`)}else if(!I){let O=N.map(
Line truncated
`+"\uD83D\uDCA1 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。",I);if(U.keyId||U.appKey){let Q=$.find((J)=>U.keyId&&J.id===U.keyId||U.appKey&&J.appKey===U.appKey);if(!Q)throw new iI(`指定的合思密钥不存在,请从上述候选列表中选择正确的appKey或keyId。
`);R0({provider:"hose",capability:"privilege-elevation",corpId:z.corpId,corpName:z.corpName??z.corpId,baseUrl:z.baseUrl,staffId:z.staffId,keyCount:z.keys.length,keys:z.keys.map((Q)=>Rv0(Q,I))})}async function cT($,Y){let U=M1($),z=Y.reveal===!0;if(U.source.type!=="hose")throw new W4(`【合思子域专享能力】当前企业「${U.name}」(id:${U.id})为原生Seal(${U.source.type})租户,非合思(Hose/合思云/易快报)渠道企业。
`);R0({provider:"hose",capability:"privilege-elevation",corpId:I.corpId,corpName:I.corpName??I.corpId,baseUrl:I.baseUrl,staffId:I.staffId,keyCount:I.keys.length,keys:I.keys.map((J)=>FS0(J,Q))})}async function rT($,Y){let U=M1($),I=Y.reveal===!0;if(U.source.type!=="hose")throw new X4(`【合思子域专享能力】当前企业「${U.name}」(id:${U.id})为原生Seal(${U.source.type})租户,非合思(Hose/合思云/易快报)渠道企业。
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,w=Z.apiOrigin??"production";console.error(`•"${q}"(signKey:${V},环境:${w})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${V}--corp${I.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let w=V.outboundName??"SealAI 审批",M=V.signKey,F=V.apiOrigin??"production";console.error(`•"${w}"(signKey:${M},环境:${F})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${M}--corp${I.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,w=Z.apiOrigin??"production";console.error(`•"${q}"(signKey:${V},环境:${w})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${V}--corp${Q.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let w=V.outboundName??"SealAI 审批",M=V.signKey,F=V.apiOrigin??"production";console.error(`•"${w}"(signKey:${M},环境:${F})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${M}--corp${Q.id}
`);throw new X4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,Z.length===1?`seal-usedeployhosecloudsync${Z[0].signKey}--corp${Q.id}`:void 0)}await x0("seal_deploy_hosecloud_sync",I,Q,{signKey:H},E0(J.options));return}throw Error(`Unknowndeployhosecloudaction:${z??""}.Available:requirements,list,get,status,configure,sync.`)}var Zg0=m(()=>{O4();q4();l1();H4();J$()});var Vg0='---\nname: seal-use\ndescription: "v0.10.38: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."\nmetadata:\n version: 0.10.38\n short-description: Seal tenant and Hose approval automation (v0.10.38)\n---\n\n# Seal Use\n\nCLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。MCP 默认关闭。\n\n## 时间与输出\n\n- 机器字段保留 ISO 8601 UTC,精确到秒,不要添加毫秒,例如 `2026-09-22T04:56:06Z`。\n- 面向用户解释时间时,换算为 `Asia/Shanghai`,明确标注“北京时间”;审计或消歧时同时保留原始 UTC。\n- 不向用户暴露 Bearer、`accessToken`、`closeToken`、`appSecurity`、原始 cURL 或未脱敏手机号。\n- 不向用户直接暴露底层 UUID、`tenantSlug`、`boundCorpRole` 等内部字段;优先使用企业名称、规则编号 `#xxxx` 和脱敏后的业务信息。\n\n## 企业接入:先识别材料,再选择入口\n\n最终企业来源只有两种:`source.type:"seal"` 和 `source.type:"hose"`。不要把材料格式、认证凭据和最终来源混为一谈。\n\n| 用户材料 | 标准入口 | 最终配置形态 |\n| --- | --- | --- |\n| Hose 开放平台 `appKey+appSecurity` | `corpsadd-hose-persistent` | Hose 持久化凭据 |\n| Seal URL + Bearer,或 Seal 页面 cURL | `corpsadd-seal-bearer` | Seal Bearer 会话 |\n| Seal 原生委托链接 | `corpsadd-link<url>` | Seal 委托会话 |\n| Hose 协助链接 | `corpsadd-link<url>` | Hose Web Session;加 `--elevate-hose` 才提取长期密钥 |\n| Hose 页面 cURL | 先提取密钥;失败时 `corpsadd-hose-web-session` | Hose 持久化或 Hose Web Session |\n| 已规范化的 Hose `corpId+accessToken+baseUrl` | `corpsadd-hose-web-session` | Hose Web Session |\n\n### 凭据边界\n\n- Seal Bearer 只能给 `add-seal-bearer`;Hose `accessToken/accesstoken/closeToken` 不能直接当作 Seal Bearer。\n- Hose Web Session 保存 `closeToken+staffId`,需要调用 Seal 时才通过 SSO 换取运行时 Seal Bearer。\n- Hose 持久化配置保存 `appKey+appSecurity`,适合无人值守、部署和长期同步。\n- 会话有有效期时,Hose source 保存 `expiresIn` 和 UTC 秒级 `expiresAt`。\n- `add-link` 是 URL 混合入口,不接收 cURL:自动识别 Seal 委托链接和 Hose 协助链接。\n- `--elevate-hose` 是唯一明确的 Hose 提权动作。\n\n收到 Hose 管理员 cURL 时,按 Hose 协助链接处理:解析主机、`accesstoken`、企业标识和必要会话信息,优先调用密钥提取路径;无法提取长期密钥时才保存 Web Session。收到 Seal cURL 时,提取 Seal 主机和 `Authorization:Bearer`,走 `add-seal-bearer`。不要盲目执行 cURL,也不要把原文写入文件或日志。\n\n详细来源决策、提权边界和 cURL 处理见 `references/enterprise-onboarding.md`;首次找材料时必须使用 `references/first-time-user.md`。\n\n## 首次接入图文规则\n\n当用户首次接入、询问如何取得材料,或需要用户打开后台找凭据时:\n\n1. 先确认用户手上是 Hose 开放平台凭据、协助链接、Seal 委托链接,还是已登录网页 cURL。\n2. 读取 `references/first-time-user.md`,只渲染与当前路径对应的截图;不能只给纯文字步骤。\n3. 接收材料后由 Agent 自动发现企业、域名和管理员。除非自动发现失败,不要要求用户先填写 `corpId`、`staffId` 或域名。\n\n## `corps` 主线\n\n- 接入:`add-link`、`add-seal-bearer`、`add-hose-persistent`、`add-hose-web-session`\n- 发现:`list`、`search`/`find`、`get`/`show`、`current`、`switch`\n- 维护:`mark`、`rename`\n- 测试闭环:`bind-test`、`unbind-test`、`sync-test`、`replay-test`\n- Hose 专属:`probe-hose`、`hose-staffs`、`hose-extract-keys`、`hose-keys`\n\nHose 专属命令应从命令名或选项中明确可见:`authhose-*`、`approval-runshose-flow`、`deployhosecloud`、`simulation--modehosecloud`。跨来源入口只有在明确使用 `--elevate-hose`、`--with-flow` 或 `--typehose-document` 时才启用对应 Hose 能力。\n\n生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。\
Line truncated
display_name:"Seal Use"
short_description:"Diagnose approval feedback and publish minimal rule fixes"
default_prompt:"Use $seal-use to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation."
`;var hS0=()=>{};var yS0="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--batch<batchId>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest--fieldsrecordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-useapproval-runsget<recordId>--corp<corpId>--summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsmetadata\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.fields,result.summary\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsresult.summary,result.decision,result.riskPoints\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runsget<recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-useapproval-runsdocument-summary<recordId>--corp<corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-useapproval-runscited-rules<recordId>--corp<corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rulesget--record-id<recordId>--runtime-idrule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\n#查看附件列表摘要(包含文件名、类型、大小及直链可用性)\nseal-useapproval-runsattachments<recordId>--corp<corpId>--summary\n\n#下载全部附件到本地目录(优先使用ossSignedUrl签名直链)\nseal-useapproval-runsattachmentsdownload<recordId>--all--out-dir./downloads--corp<corpId>\n\n#按名称或fileId过滤下载单个附件\nseal-useapproval-runsattachmentsdownload<recordId>--name发票--corp<corpId>\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-useapproval-runsresult<recordId>--corp<corpId>--summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Approval Run Web Links & Auto-Login Links\n\nUse this when the user asks for a link to an approval run or wants to open the run directly in their browser:\n\n```bash\n#默认推荐:生成SealAI审核详情直达链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)\nseal-useapproval-runslink<recordId>--corp<corpId>\nseal-useapproval-runslink--sn<sourceDocumentSN>--corp<corpId>\n\n#生成合思主系统原始单据页面链接\nseal-useapproval-runslink<recordId>--typehose-document--corp<corpId>\n\n#仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带合思单次临时票据的免登直达链接\nseal-useapproval-runslink<recordId>--auto-login[--expire7200]--corp<corpId>\n```\n\n### 返回字段说明与语义规范\n- `sealResultUrl`: Seal AI 单据智能审核结果页\n- `hoseDocumentUrl`: 合思费控主系统原始报销/借款单详情页\n- `type`: 链接类型,默认为 `seal_result`,指定时可为 `hose_document`\n- `mode`: 鉴权模式,`direct`(原生直接打开)或 `auto_login`(免密换票)\n\n### 免登链接安全与声明规范\n当向用户返回 `--auto-login` 链接时
Line truncated
`;var Og0=()=>{};var Bg0="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--batch<batchId>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest--fieldsrecordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-useapproval-runsget<recordId>--corp<corpId>--summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsmetadata\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.fields,result.summary\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsresult.summary,result.decision,result.riskPoints\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runsget<recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-useapproval-runsdocument-summary<recordId>--corp<corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-useapproval-runscited-rules<recordId>--corp<corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rulesget--record-id<recordId>--runtime-idrule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\n#查看附件列表摘要(包含文件名、类型、大小及直链可用性)\nseal-useapproval-runsattachments<recordId>--corp<corpId>--summary\n\n#下载全部附件到本地目录(优先使用ossSignedUrl签名直链)\nseal-useapproval-runsattachmentsdownload<recordId>--all--out-dir./downloads--corp<corpId>\n\n#按名称或fileId过滤下载单个附件\nseal-useapproval-runsattachmentsdownload<recordId>--name发票--corp<corpId>\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-useapproval-runsresult<recordId>--corp<corpId>--summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Approval Run Web Links & Auto-Login Links\n\nUse this when the user asks for a link to an approval run or wants to open the run directly in their browser:\n\n```bash\n#默认推荐:生成SealAI审核详情直达链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)\nseal-useapproval-runslink<recordId>--corp<corpId>\nseal-useapproval-runslink--sn<sourceDocumentSN>--corp<corpId>\n\n#生成合思主系统原始单据页面链接\nseal-useapproval-runslink<recordId>--typehose-document--corp<corpId>\n\n#仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带合思单次临时票据的免登直达链接\nseal-useapproval-runslink<recordId>--auto-login[--expire7200]--corp<corpId>\n```\n\n### 返回字段说明与语义规范\n- `sealResultUrl`: Seal AI 单据智能审核结果页\n- `hoseDocumentUrl`: 合思费控主系统原始报销/借款单详情页\n- `type`: 链接类型,默认为 `seal_result`,指定时可为 `hose_document`\n- `mode`: 鉴权模式,`direct`(原生直接打开)或 `auto_login`(免密换票)\n\n### 免登链接安全与声明规范\n当向用户返回 `--auto-login` 链接时
Line truncated
3.BOTHacodeblock(\`\`\`\`text ... \`\`\`\`) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
-**DedicatedCLICommand**:Use\`seal-use auth hose-link --corp <corpId> [--expire <seconds>] [--force]\`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports \`--expire\` (default 7200, e.g. 86400 for 1 day).
-**SealAIPlatformDirectLink**:Use\`seal-use auth link --corp <corpId> [--note <note>]\`. This generates a 24-hour provisional delegation link for the Seal AI audit platform (\`https://*.sealai.cc\`).
@@ -2127,7 +2127,7 @@ Use current search only when the question is about current draft/current knowled
##OutputDiscipline
Ifarulecommandwouldreturnmanydescriptionsormorethanabout20rules,use\`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports.
`;var sS0=()=>{};var eS0="# Seal Approval Rule Linter & Quality Validation\n\nUse this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.\n\n## Key Principles\n\n- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled:false`) to avoid unsolicited noise during standard operations.\n- **Doctor Visibility**: `seal-usedoctor` audits the rule linter configuration state and active linter name in its health checks, and surfaces a one-click hint (`seal-useconfiglintenable`) when disabled.\n- **Explicit Triggering**: `seal-useruleslint` always runs regardless of global configuration.\n- **Draft Hook**: When `seal-useconfiglintenable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.\n- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.\n\n## CLI Commands\n\n### 1. Lint Current Draft Rules (Whole-RuleSet Scan)\n\n```bash\nseal-useruleslint--corp<corpId>\n```\n\n### 2. Lint Specific Historical Version or Single Rule\n\n```bash\n#Lintrulesinpublishedversion16\nseal-useruleslint--version16--corp<corpId>\n\n#Lintaspecificrulebycode(#0038)\nseal-useruleslint--code'#0038'--corp<corpId>\n\n#Summarymode(onlyshowruleswithissues)\nseal-useruleslint--summary--corp<corpId>\n```\n\n### 3. Quality Gate for CI / Release\n\n```bash\n#Ifoverallscoreisbelow85,terminateswithexitcode1\nseal-useruleslint--min-score85--levelerror--corp<corpId>\n```\n\n### 4. Configure Global Linter Settings\n\n```bash\n#Checkstatus\nseal-useconfiglintstatus\n\n#Enableautolintonruleupdates\nseal-useconfiglintenable--linterbuiltin--min-score80\n\n#Disableautolint\nseal-useconfiglintdisable\n```\n\n## Official Linters\n\n| Linter Name | Scope & Purpose | Aliases |\n| :--- | :--- | :--- |\n| `builtin` | Seal 官方标准校验器:拦截过短描述、主观模糊词与悬空例外条款。 | `default`, `official/builtin` |\n| `strict` | Seal 官方严格风控校验器:强校验字数、刚性定量约束、凭证依据与具体审批人角色。 | `official/strict` |\n| `hlab` | 合思实验室 (HLab) 结构化规则校验器:SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判。 | `hlab-sop`, `hlab-rules`, `hlab-standard`, `official/hlab` |\n\n```bash\n#Inspectavailablelinters\nseal-useruleslinters\n\n#LintrulesusingHLabSOPstandard\nseal-useruleslint--linterhlab--corp<corpId>\n\n#LintlocalruleworkspaceofflinewithHLabstandard\nseal-useruleslint--linterhlab--file./rules.local.json\n```\n\n## Built-In Detection Rules (`builtin`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |\n| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |\n| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |\n\n## HLab SOP Detection Rules (`hlab`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `MISSING_CHECK_METHOD` | `error` | Missing `**检查方法**` section in rule description. | Add `**检查方法**:` specifying fields, vouchers, and normalization logic. |\n| `MISSING_EVAL_STANDARD` | `error` | Missing `**判定标准**` section in rule description. | Add `**判定标准**:` with standard branches. |\n| `INCOMPLETE_TERNARY_BRANCH` | `error` | Incomplete ternary branch under evaluation criteria (missing `PASS`, `FAIL`, or `证据不足`). | Provide complete ternary closure: `-PASS:`, `-FAIL:`, `-证据不足:`. |\n| `INSUFFICIENT_WITHOUT_MANUAL_REVIEW` | `warning` | `证据不足` branch does not specify escalating to `人工复核`. | Add `转人工复核` at the end of `证据不足` branch. |\n| `DISPOSAL_ACTION_LEAK` | `warning` | Contains whole-bill workflow disposal actions (`驳回单据`, `直接驳回`, `进行提醒`, `退回单据`). | Decouple disposal actions from rule text; rely on rule strictness or platform workflow. |\n| `SCOPE_FALSE_SKIP_PRONE` | `warning` | Scope contains material upload conditions (`若上传了`, `若提供了`, `附件需上传`). | Keep scope pure to business triggers; handle missing materials explicitly in FAIL branch to prevent silent SKIP. |\n| `RISK_SUPPRESSION` | `erroLine truncated
`;var xg0=()=>{};var bg0="# Seal Approval Rule Linter & Quality Validation\n\nUse this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.\n\n## Key Principles\n\n- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled:false`) to avoid unsolicited noise during standard operations.\n- **Doctor Visibility**: `seal-usedoctor` audits the rule linter configuration state and active linter name in its health checks, and surfaces a one-click hint (`seal-useconfiglintenable`) when disabled.\n- **Explicit Triggering**: `seal-useruleslint` always runs regardless of global configuration.\n- **Draft Hook**: When `seal-useconfiglintenable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.\n- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.\n\n## CLI Commands\n\n### 1. Lint Current Draft Rules (Whole-RuleSet Scan)\n\n```bash\nseal-useruleslint--corp<corpId>\n```\n\n### 2. Lint Specific Historical Version or Single Rule\n\n```bash\n#Lintrulesinpublishedversion16\nseal-useruleslint--version16--corp<corpId>\n\n#Lintaspecificrulebycode(#0038)\nseal-useruleslint--code'#0038'--corp<corpId>\n\n#Summarymode(onlyshowruleswithissues)\nseal-useruleslint--summary--corp<corpId>\n```\n\n### 3. Quality Gate for CI / Release\n\n```bash\n#Ifoverallscoreisbelow85,terminateswithexitcode1\nseal-useruleslint--min-score85--levelerror--corp<corpId>\n```\n\n### 4. Configure Global Linter Settings\n\n```bash\n#Checkstatus\nseal-useconfiglintstatus\n\n#Enableautolintonruleupdates\nseal-useconfiglintenable--linterbuiltin--min-score80\n\n#Disableautolint\nseal-useconfiglintdisable\n```\n\n## Official Linters\n\n| Linter Name | Scope & Purpose | Aliases |\n| :--- | :--- | :--- |\n| `builtin` | Seal 官方标准校验器:拦截过短描述、主观模糊词与悬空例外条款。 | `default`, `official/builtin` |\n| `strict` | Seal 官方严格风控校验器:强校验字数、刚性定量约束、凭证依据与具体审批人角色。 | `official/strict` |\n| `hlab` | 合思实验室 (HLab) 结构化规则校验器:SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判。 | `hlab-sop`, `hlab-rules`, `hlab-standard`, `official/hlab` |\n\n```bash\n#Inspectavailablelinters\nseal-useruleslinters\n\n#LintrulesusingHLabSOPstandard\nseal-useruleslint--linterhlab--corp<corpId>\n\n#LintlocalruleworkspaceofflinewithHLabstandard\nseal-useruleslint--linterhlab--file./rules.local.json\n```\n\n## Built-In Detection Rules (`builtin`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |\n| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |\n| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |\n\n## HLab SOP Detection Rules (`hlab`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `MISSING_CHECK_METHOD` | `error` | Missing `**检查方法**` section in rule description. | Add `**检查方法**:` specifying fields, vouchers, and normalization logic. |\n| `MISSING_EVAL_STANDARD` | `error` | Missing `**判定标准**` section in rule description. | Add `**判定标准**:` with standard branches. |\n| `INCOMPLETE_TERNARY_BRANCH` | `error` | Incomplete ternary branch under evaluation criteria (missing `PASS`, `FAIL`, or `证据不足`). | Provide complete ternary closure: `-PASS:`, `-FAIL:`, `-证据不足:`. |\n| `INSUFFICIENT_WITHOUT_MANUAL_REVIEW` | `warning` | `证据不足` branch does not specify escalating to `人工复核`. | Add `转人工复核` at the end of `证据不足` branch. |\n| `DISPOSAL_ACTION_LEAK` | `warning` | Contains whole-bill workflow disposal actions (`驳回单据`, `直接驳回`, `进行提醒`, `退回单据`). | Decouple disposal actions from rule text; rely on rule strictness or platform workflow. |\n| `SCOPE_FALSE_SKIP_PRONE` | `warning` | Scope contains material upload conditions (`若上传了`, `若提供了`, `附件需上传`). | Keep scope pure to business triggers; handle missing materials explicitly in FAIL branch to prevent silent SKIP. |\n| `RISK_SUPPRESSION` | `erroLine truncated
`;var $g0=()=>{};var iy1="iVBORw0KGgoAAAANSUhEUgAADVgAAAdwCAYAAACUWcTmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWKADAAQAAAABAAAHcAAAAAD4n9OGAABAAElEQVR4AeydB4AdVfX/z246pNAD0hK6dOki0rsU+dMJJVIFRYoUFUFAQUCqgHSkxx8gTRCpFkB6CU06SQi9BEhC+u7/fu7b83J3dt7bt33f5nuStzNz5947M583c+fOvPO9p6Y+mMlEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4kUDsHHrMOWQREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQigd7jxo8TChEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYIwkogtUc+bXroEVABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABCBQUx9MKERABERABERABERABERABERABERABERABERABERABERABERABESgqwiMHz/eBgwY0FWb13ZFQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQATmcAKKYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwn0npMPXscuAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj2RwP8+n26vfjbd3vpyho2fPN0+mjLTJs+qs/qaOhvYp8YWGtDLFh/U25YZ3NdWnr+/rTDvgJ6IQcckAhURqKkPVlFOZRIBERABERABERABERABERABERABERABERABERABERABERABERCBDiAwfvx4GzBAP9p2AFpVKQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiMIcR+GhSnT347lT713tT7eOpM4OYqj5+LEzNEFdZ+MyKU5Zr4jLp9fat/r1ss28NtM0WG2KLzN1nDiOnw53TCUhgNaefATp+ERABERABERABERABERABERABERABERABERABERABERABEehiAhJYdfEXoM2LgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhUPYFJ08z+7+Updsc7U8OxFARURKqyIKAqCKnqbVYQUdU2CK7iOiuIr4oirLBcgxArfHZZcrDttcwCNnefXlXPRgcgApUQkMCqEkrKIwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0GEEJLDqMLSqWAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4g8MR7M+2Cp6fY5JmFSFQhRlUQStUVBVUsF0VUCKiSSFZEsKqLkawa5yH/oN5mP195qK0/dPAcQFGHOKcTkMBqTj8DdPwiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0MUEJLDq4i+gCzY/ZcqUuNUBAwZ0wda1SREQAREQAREQAREQAREQAREQAREQAREQAREQARHoHAKd8S501AszbNT/psXIUwWhVDi2IK6qj5GriGRVEE4RlSoVWlUayYry+w2fx0Yst1DnQNNWRKCLCAQ9oUwEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKCaCFz035n20JgZ1stqQowqs9qaWmJVBR1VbRBZkdLLakN0qiCzCtMGgVXMURfW1YQsTHsFEdasMC0UCSWjOIvcbte++6V9MX2mHb7ytzypS6e/+93v7H//+1/uPuy888727W9/O35yMyhRBEoQ4NyXiYAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiECPIXDbbbfZiBEjGh0PP7aSxif90dXzks68G3k8P2VTYznNm67TvAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BoGLHp1lD74zM6qh6kK4qprwqW+YMl9TR1pYHcRWtUFHhZaqLi6TFsJbhflCOYRVtbG818H6+KGOhnr+9v4ku/DlDzrj0Mpug/fz6Xv+bOa//vWvxkcmAi0loAhWLSWm/CIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAt2WAD+sdvQPp/xwy0cjYHbb00A7JgIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAI9msCo5+rt4XdDVKoaIlfVxChVHHCMPtXoyIO4KuSoy0ayqifOFeWJUxVqSCJZfW/hwfbox1/FuqiKHF4zIqt5+39qey+zYEztij/pbwC8p0/NhVc+TddpXgSaIyCBVXOEtF4EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKBqCLz66qudtq/8iPvrX/+607aX3VBniMluvPHG7Ga1LAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUIJAzT+vi2vqN9m3RA4li0DbCTw5xuyWl+qMIFQWIk8Rpqo+Cq1YDlKokL7m4v2D7IrFOgurwvqwoiaEsIpyKebNHv9wki+FdERaSKlq7fytlrEj73vLHvvoq7gNUkM4q1BPKBTque7tCbbUoH62/tDBrOkyQ1yVfUf/u9/9rmx0qy7b2VZu2H8H4FhXXHFF+3//7/+1siYVq4RATX2wSjIqjwiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BIHx48fbgAEDOqLqHlun/6ja0QfYUQKrKVOmxF3X997R36DqFwEREAEREAEREAEREAEREAEREAEREAER6EwCs074btxcr9Me78zNalvdmEB7vwudNM3ssFvNJs2oi0KqWUE0FQVUUUiF6KreLtx5QVtt0X5lqYz+cIodevfYkKcg1KpHfBXKHvadobbvdxay0R9NsgPveyOsD3KTWiQniLjCNHyYDgqhfq7bcCmbu0+vsttpy0rEUlgqLErfje+8885NBEepwMrXE83Ko16ldbVl3zqjbHqsvj0EZdmoXb5O07YTUASrtjNUDSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQqQQ6M1JXpx5YD96Yj3sZR3ntwcdZyaHNmDHDPv74Y1t00UULo95WUqiL8syaNct69eo4J5EuOqwu3Szff58+fZrsg66RJkiU0MkEGJ4YhzSZCHQmAdpEjHtNbW0Ydb4djHvX9OnTNYBBA0ucWfv169dufNvhK+oxVUydOtXq6upsrrnm6jHHpAMRAREQAREQgbYS8OhV1FN/1VFWc8B5ba2yWJ6+45gxY+ytt96y/v3729JLL22LLbZYbj+H9y4u6ilWUGJm7rnntgUXXDCu/frrr+2LL74okbNxMv3XJZZYonFia5fGjLaad0e3tnSx3JwSNezmZ2ts8vQQTSr8C9KoOA2Sp8ChJvyttQPXG9SsuMqh1VEslIviqTBdf5G5o7iK1NUWHmg/XW1Ru/iF960+aK8QVbE1j2SFwOumtz6zg749lOztbqlQygVSCIuYL2cIqDwPoirepfsy5ZgnLRv5qlydXbUu73cAjqka9h1mCMSw1kbdamv5uPEW/pHAqoXAlF0EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEuppA+oNwR0WZ6upj7Enbf+ONN+yUU06Jh3Tsscfa6quv3pMOLx7Lhx9+aMcff3yc33vvvW3LLbfMPcZbbrnF7rjjjrjuF7/4ha2yyiq5+dLEyZMn24QJE2zhhRe23r1720svvWTnn39+zPLLX/7SlllmmTR77jyORb/61a/iuv3339++973v5eZLE99++2076aSTbNlll7UtttiiojJp+WqZHz16dBQ84XziNnPmTPv00099sUVTHLMGDx6cW2bcuHHRAWSzzTazHXfc0eaZZ56Y7/HHH7eLLroozh933HG21FJL2Zlnnmm77LJLm6+Xb775xr766qvc/ckmzjvvvNFJLZveluWzzz7b3nrzTVty2DDjfG2JTZs2ze677z7bZpttGonSvvzyy4od5bLb4zqqJqHnxxNmWcHZK3skLV/u16fG5huUL2B5cPRUO
Line truncated
`,"utf8"),{detected:z,configured:!0,configPath:U,targetDir:Y,action:"prepended"}}function vo($){let Y=$?.targetSkillsDir??Qg0(),U=$?.configFile??Jg0(),z=Kg0(),I=!1;if(fq(U))try{let Q=JSON.parse(Ig0(U,"utf8"));if(Array.isArray(Q?.entries))I=Q.entries.some((J)=>J?.path===Y)}catch{}return{detected:z,configured:I,configPath:U,targetDir:Y}}var ho=()=>{};import{cpSync as ry1,existsSync as nK,lstatSync as Hg0,mkdirSync as sy1,realpathSync as $Y,rmSync as ay1,symlinkSync as ty1,unlinkSync as Gg0}from"node:fs";import{homedir as Wg0}from"node:os";import{dirname as Xg0,join as YY}from"node:path";function ey1($,Y){let U=Y?.baseHomeDir??Wg0(),z=YY(U,$.rootDirName),I=Y?.sourceSkillDir??YY(U,".agents","skills","seal-use"),Q=Xg0(I),J=YY(z,"skills"),K=YY(J,"seal-use");if(!nK(z))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"skipped_not_detected"};if(nK(J)&&nK(Q))try{if($Y(J)===$Y(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:J}}catch{}sy1(J,{recursive:!0});let G;try{G=Hg0(K)}catch{G=void 0}let H=!1;if(G)if(G.isSymbolicLink()){try{if($Y(K)===$Y(I))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"already_linked",targetPath:K}}catch{}try{Gg0(K)}catch{}}else if(G.isDirectory())ay1(K,{recursive:!0,force:!0}),H=!0;else Gg0(K);let W=process.platform==="win32"?"junction":"dir";try{return ty1(I,K,W),{id:$.id,name:$.name,detected:!0,configured:!0,mode:H?"replaced_real_dir":"linked",targetPath:K}}catch{try{return ry1(I,K,{recursive:!0}),{id:$.id,name:$.name,detected:!0,configured:!0,mode:"fallback_copied",targetPath:K}}catch(X){return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"error",targetPath:K,error:X?.message||String(X)}}}}function $k1($,Y){let U=Y?.baseHomeDir??Wg0(),z=YY(U,$.rootDirName),I=Y?.sourceSkillDir??YY(U,".agents","skills","seal-use"),Q=Xg0(I),J=YY(z,"skills"),K=YY(J,"seal-use");if(!nK(z))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"not_detected"};if(nK(J)&&nK(Q))try{if($Y(J)===$Y(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:J}}catch{}let G;try{G=Hg0(K)}catch{G=void 0}if(G){if(G.isSymbolicLink())try{if($Y(K)===$Y(I))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"single_symlinked",targetPath:K}}catch{}else if(G.isDirectory())return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"real_directory",targetPath:K}}return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"not_configured",targetPath:K}}function So($){return Zg0.map((Y)=>ey1(Y,$))}function go($){return Zg0.map((Y)=>$k1(Y,$))}var Zg0;var yo=m(()=>{Zg0=[{id:"workbuddy",name:"WorkBuddy",rootDirName:".workbuddy"},{id:"claude",name:"Claude",rootDirName:".claude"},{id:"qoder",name:"Qoder",rootDirName:".qoder"}]});var ko=m(()=>{ho();yo();ho();yo()});import{existsSync as Yk1,mkdirSync as xo,readFileSync as Uk1,rmSync as zk1,writeFileSync as qg0}from"node:fs";import{homedir as Lg0}from"node:os";import{dirname as Vg0,join as bq}from"node:path";function fo(){return Fg0["SKILL.md"]||""}function wg0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function Mg0($=bq(iz(),"SKILL.md")){try{return wg0(Uk1($,"utf8"))}catch{return}}function iz(){return bq(Lg0(),".agents","skills","seal-use")}function Qk1(){return bq(Lg0(),".agents","skills","seal-home")}function Jk1(){let $=Qk1();if(Yk1($))try{return zk1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Og0($=iz()){Jk1(),xo($,{recursive:!0});let Y=[];for(let[U,z]of Object.entries(Fg0)){let I=bq($,U);xo(Vg0(I),{recursive:!0}),qg0(I,z,"utf8"),Y.push(U)}for(let[U,z]of Object.entries(Ik1)){let I=bq($,U);xo(Vg0(I),{recursive:!0}),qg0(I,z),Y.push(U)}return{targetDir:$,files:Y}}var Fg0,Ik1,Oz4;var iq=m(()=>{Eo();Eo();ko();Fg0=Ug0,Ik1=Object.fromEntries(Object.entries(zg0).map(([$,Y])=>[$,Buffer.from(Y,"base64")]));Oz4=wg0(fo())});function Ng0(){return`#SealUse系统架构与运行规范白皮书
`;var ig0=()=>{};var Gx1="iVBORw0KGgoAAAANSUhEUgAADVgAAAdwCAYAAACUWcTmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWKADAAQAAAABAAAHcAAAAAD4n9OGAABAAElEQVR4AeydB4AdVfX/z246pNAD0hK6dOki0rsU+dMJJVIFRYoUFUFAQUCqgHSkxx8gTRCpFkB6CU06SQi9BEhC+u7/fu7b83J3dt7bt33f5nuStzNz5947M583c+fOvPO9p6Y+mMlEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4kUDsHHrMOWQREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQigd7jxo8TChEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYIwkogtUc+bXroEVABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABCBQUx9MKERABERABERABERABERABERABERABERABERABERABERABERABESgqwiMHz/eBgwY0FWb13ZFQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQATmcAKKYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwn0npMPXscuAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj2RwP8+n26vfjbd3vpyho2fPN0+mjLTJs+qs/qaOhvYp8YWGtDLFh/U25YZ3NdWnr+/rTDvgJ6IQcckAhURqKkPVlFOZRIBERABERABERABERABERABERABERABERABERABERABERABERCBDiAwfvx4GzBAP9p2AFpVKQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiMIcR+GhSnT347lT713tT7eOpM4OYqj5+LEzNEFdZ+MyKU5Zr4jLp9fat/r1ss28NtM0WG2KLzN1nDiOnw53TCUhgNaefATp+ERABERABERABERABERABERABERABERABERABERABERABEehiAhJYdfEXoM2LgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhUPYFJ08z+7+Updsc7U8OxFARURKqyIKAqCKnqbVYQUdU2CK7iOiuIr4oirLBcgxArfHZZcrDttcwCNnefXlXPRgcgApUQkMCqEkrKIwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0GEEJLDqMLSqWAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4g8MR7M+2Cp6fY5JmFSFQhRlUQStUVBVUsF0VUCKiSSFZEsKqLkawa5yH/oN5mP195qK0/dPAcQFGHOKcTkMBqTj8DdPwiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0MUEJLDq4i+gCzY/ZcqUuNUBAwZ0wda1SREQAREQAREQAREQAREQAREQAREQAREQAREQARHoHAKd8S501AszbNT/psXIUwWhVDi2IK6qj5GriGRVEE4RlSoVWlUayYry+w2fx0Yst1DnQNNWRKCLCAQ9oUwEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKCaCFz035n20JgZ1stqQowqs9qaWmJVBR1VbRBZkdLLakN0qiCzCtMGgVXMURfW1YQsTHsFEdasMC0UCSWjOIvcbte++6V9MX2mHb7ytzypS6e/+93v7H//+1/uPuy888727W9/O35yMyhRBEoQ4NyXiYAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiECPIXDbbbfZiBEjGh0PP7aSxif90dXzks68G3k8P2VTYznNm67TvAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BoGLHp1lD74zM6qh6kK4qprwqW+YMl9TR1pYHcRWtUFHhZaqLi6TFsJbhflCOYRVtbG818H6+KGOhnr+9v4ku/DlDzrj0Mpug/fz6Xv+bOa//vWvxkcmAi0loAhWLSWm/CIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAt2WAD+sdvQPp/xwy0cjYHbb00A7JgIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAI9msCo5+rt4XdDVKoaIlfVxChVHHCMPtXoyIO4KuSoy0ayqifOFeWJUxVqSCJZfW/hwfbox1/FuqiKHF4zIqt5+39qey+zYEztij/pbwC8p0/NhVc+TddpXgSaIyCBVXOEtF4EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKBqCLz66qudtq/8iPvrX/+607aX3VBniMluvPHG7Ga1LAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUIJAzT+vi2vqN9m3RA4li0DbCTw5xuyWl+qMIFQWIk8Rpqo+Cq1YDlKokL7m4v2D7IrFOgurwvqwoiaEsIpyKebNHv9wki+FdERaSKlq7fytlrEj73vLHvvoq7gNUkM4q1BPKBTque7tCbbUoH62/tDBrOkyQ1yVfUf/u9/9rmx0qy7b2VZu2H8H4FhXXHFF+3//7/+1siYVq4RATX2wSjIqjwiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BIHx48fbgAEDOqLqHlun/6ja0QfYUQKrKVOmxF3X997R36DqFwEREAEREAEREAEREAEREAEREAEREAER6EwCs074btxcr9Me78zNalvdmEB7vwudNM3ssFvNJs2oi0KqWUE0FQVUUUiF6KreLtx5QVtt0X5lqYz+cIodevfYkKcg1KpHfBXKHvadobbvdxay0R9NsgPveyOsD3KTWiQniLjCNHyYDgqhfq7bcCmbu0+vsttpy0rEUlgqLErfje+8885NBEepwMrXE83Ko16ldbVl3zqjbHqsvj0EZdmoXb5O07YTUASrtjNUDSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQqQQ6M1JXpx5YD96Yj3sZR3ntwcdZyaHNmDHDPv74Y1t00UULo95WUqiL8syaNct69eo4J5EuOqwu3Szff58+fZrsg66RJkiU0MkEGJ4YhzSZCHQmAdpEjHtNbW0Ydb4djHvX9OnTNYBBA0ucWfv169dufNvhK+oxVUydOtXq6upsrrnm6jHHpAMRAREQAREQgbYS8OhV1FN/1VFWc8B5ba2yWJ6+45gxY+ytt96y/v3729JLL22LLbZYbj+H9y4u6ilWUGJm7rnntgUXXDCu/frrr+2LL74okbNxMv3XJZZYonFia5fGjLaad0e3tnSx3JwSNezmZ2ts8vQQTSr8C9KoOA2Sp8ChJvyttQPXG9SsuMqh1VEslIviqTBdf5G5o7iK1NUWHmg/XW1Ru/iF960+aK8QVbE1j2SFwOumtz6zg749lOztbqlQygVSCIuYL2cIqDwPoirepfsy5ZgnLRv5qlydXbUu73cAjqka9h1mCMSw1kbdamv5uPEW/pHAqoXAlF0EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEuppA+oNwR0WZ6upj7Enbf+ONN+yUU06Jh3Tsscfa6quv3pMOLx7Lhx9+aMcff3yc33vvvW3LLbfMPcZbbrnF7rjjjrjuF7/4ha2yyiq5+dLEyZMn24QJE2zhhRe23r1720svvWTnn39+zPLLX/7SlllmmTR77jyORb/61a/iuv3339++973v5eZLE99++2076aSTbNlll7UtttiiojJp+WqZHz16dBQ84XziNnPmTPv00099sUVTHLMGDx6cW2bcuHHRAWSzzTazHXfc0eaZZ56Y7/HHH7eLLroozh933HG21FJL2Zlnnmm77LJLm6+Xb775xr766qvc/ckmzjvvvNFJLZveluWzzz7b3nrzTVty2DDjfG2JTZs2ze677z7bZpttGonSvvzyy4od5bLb4zqqJqHnxxNmWcHZK3skLV/u16fG5huUL2B5cPRUO
Line truncated
`,"utf8"),{detected:I,configured:!0,configPath:U,targetDir:Y,action:"prepended"}}function lo($){let Y=$?.targetSkillsDir??mg0(),U=$?.configFile??lg0(),I=og0(),Q=!1;if(dq(U))try{let J=JSON.parse(pg0(U,"utf8"));if(Array.isArray(J?.entries))Q=J.entries.some((K)=>K?.path===Y)}catch{}return{detected:I,configured:Q,configPath:U,targetDir:Y}}var oo=()=>{};import{cpSync as Fx1,existsSync as mz,lstatSync as sg0,mkdirSync as wx1,realpathSync as YY,rmSync as Mx1,symlinkSync as Ox1,unlinkSync as rg0}from"node:fs";import{homedir as ag0}from"node:os";import{dirname as tg0,join as UY}from"node:path";function Nx1($,Y){let U=Y?.baseHomeDir??ag0(),I=UY(U,$.rootDirName),Q=Y?.sourceSkillDir??UY(U,".agents","skills","seal-use"),J=tg0(Q),K=UY(I,"skills"),z=UY(K,"seal-use");if(!mz(I))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"skipped_not_detected"};if(mz(K)&&mz(J))try{if(YY(K)===YY(J))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:K}}catch{}wx1(K,{recursive:!0});let G;try{G=sg0(z)}catch{G=void 0}let H=!1;if(G)if(G.isSymbolicLink()){try{if(YY(z)===YY(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"already_linked",targetPath:z}}catch{}try{rg0(z)}catch{}}else if(G.isDirectory())Mx1(z,{recursive:!0,force:!0}),H=!0;else rg0(z);let W=process.platform==="win32"?"junction":"dir";try{return Ox1(Q,z,W),{id:$.id,name:$.name,detected:!0,configured:!0,mode:H?"replaced_real_dir":"linked",targetPath:z}}catch{try{return Fx1(Q,z,{recursive:!0}),{id:$.id,name:$.name,detected:!0,configured:!0,mode:"fallback_copied",targetPath:z}}catch(X){return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"error",targetPath:z,error:X?.message||String(X)}}}}function Dx1($,Y){let U=Y?.baseHomeDir??ag0(),I=UY(U,$.rootDirName),Q=Y?.sourceSkillDir??UY(U,".agents","skills","seal-use"),J=tg0(Q),K=UY(I,"skills"),z=UY(K,"seal-use");if(!mz(I))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"not_detected"};if(mz(K)&&mz(J))try{if(YY(K)===YY(J))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:K}}catch{}let G;try{G=sg0(z)}catch{G=void 0}if(G){if(G.isSymbolicLink())try{if(YY(z)===YY(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"single_symlinked",targetPath:z}}catch{}else if(G.isDirectory())return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"real_directory",targetPath:z}}return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"not_configured",targetPath:z}}function ro($){return eg0.map((Y)=>Nx1(Y,$))}function so($){return eg0.map((Y)=>Dx1(Y,$))}var eg0;var ao=m(()=>{eg0=[{id:"workbuddy",name:"WorkBuddy",rootDirName:".workbuddy"},{id:"claude",name:"Claude",rootDirName:".claude"},{id:"qoder",name:"Qoder",rootDirName:".qoder"}]});var to=m(()=>{oo();ao();oo();ao()});import{existsSync as Bx1,mkdirSync as eo,readFileSync as Ax1,rmSync as Px1,writeFileSync as $y0}from"node:fs";import{homedir as Uy0}from"node:os";import{dirname as Yy0,join as mq}from"node:path";function $r(){return Iy0["SKILL.md"]||""}function Qy0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function Jy0($=mq(cI(),"SKILL.md")){try{return Qy0(Ax1($,"utf8"))}catch{return}}function cI(){return mq(Uy0(),".agents","skills","seal-use")}function Ex1(){return mq(Uy0(),".agents","skills","seal-home")}function jx1(){let $=Ex1();if(Bx1($))try{return Px1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Ky0($=cI()){jx1(),eo($,{recursive:!0});let Y=[];for(let[U,I]of Object.entries(Iy0)){let Q=mq($,U);eo(Yy0(Q),{recursive:!0}),$y0(Q,I,"utf8"),Y.push(U)}for(let[U,I]of Object.entries(Tx1)){let Q=mq($,U);eo(Yy0(Q),{recursive:!0}),$y0(Q,I),Y.push(U)}return{targetDir:$,files:Y}}var Iy0,Tx1,xZ4;var lq=m(()=>{co();co();to();Iy0=ng0,Tx1=Object.fromEntries(Object.entries(dg0).map(([$,Y])=>[$,Buffer.from(Y,"base64")]));xZ4=Qy0($r())});function zy0(){return`#SealUse系统架构与运行规范白皮书
`)}var Eg0=m(()=>{X6()});async function Cg0($,Y,U){let z=($??Y??"").toLowerCase();if(z==="guide"||z==="doc"||z==="knowledge"||z==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(Ng0());return}if(z==="paths"||z==="dirs"||z==="directories"){let J=no();R0(J.directories);return}if(z==="auth"){let{selectCorp:J}=await Promise.resolve().then(() => (O4(),Yo)),{stringOption:K}=await Promise.resolve().then(() => (Z4(),tl)),{handleAuthCommand:G}=await Promise.resolve().then(() => (jo(),qS0)),H=K(U.options.corp)??(Y&&Y!==z?Y:void 0)??(U.command[2]&&U.command[2]!==z?U.command[2]:void 0),W=J(H);await G("check",W,U);return}if(z==="tenant"||z==="corp"||z==="enterprise"){let{selectCorp:J}=await Promise.resolve().then(() => (O4(),Yo)),{createSealClient:K}=await Promise.resolve().then(() => (m6(),H10)),{stringOption:G}=await Promise.resolve().then(() => (Z4(),tl)),{diagnoseTenantContract:H,formatTenantDoctorDashboard:W}=await Promise.resolve().then(() => (Eg0(),jg0)),X=G(U.options.corp)??(Y&&Y!==z?Y:void 0)??(U.command[2]&&U.command[2]!==z?U.command[2]:void 0),Z=J(X),q=await K(Z),V=await H(q,Z);if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(W(V));R0(V);return}let I=no();if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Pg0(I));R0(I)}var Rg0=m(()=>{Tg0();co();Z4();m1()});var vg0;var _g0=m(()=>{vg0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.38",description:"HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-usehttp`, or the `seal-useservicestart` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n"},servers:[{url:"http://localhost:8787",description:"Local HTTP adapter (`seal-usehttp`, or the `seal-useservicestart` daemon). Loopback-only by default."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps","x-implementation-status":"implemented",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp","x-implementation-status":"planned",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp","x-implementation-status":"planned",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig","x-implementation-status":"planned",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional i
Line truncated
`)}var Ly0=m(()=>{H4()});var Fy0={};Z8(Fy0,{formatTenantDoctorDashboard:()=>Vy0,diagnoseTenantContract:()=>qy0});var wy0=m(()=>{Ly0()});async function My0($,Y,U){let I=($??Y??"").toLowerCase();if(I==="guide"||I==="doc"||I==="knowledge"||I==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(zy0());return}if(I==="paths"||I==="dirs"||I==="directories"){let K=Jr();R0(K.directories);return}if(I==="auth"){let{selectCorp:K}=await Promise.resolve().then(() => (O4(),Fo)),{stringOption:z}=await Promise.resolve().then(() => (q4(),qo)),{handleAuthCommand:G}=await Promise.resolve().then(() => (io(),$g0)),H=z(U.options.corp)??(Y&&Y!==I?Y:void 0)??(U.command[2]&&U.command[2]!==I?U.command[2]:void 0),W=K(H);await G("check",W,U);return}if(I==="tenant"||I==="corp"||I==="enterprise"){let{selectCorp:K}=await Promise.resolve().then(() => (O4(),Fo)),{createSealClient:z}=await Promise.resolve().then(() => (f6(),P10)),{stringOption:G}=await Promise.resolve().then(() => (q4(),qo)),{diagnoseTenantContract:H,formatTenantDoctorDashboard:W}=await Promise.resolve().then(() => (wy0(),Fy0)),X=G(U.options.corp)??(Y&&Y!==I?Y:void 0)??(U.command[2]&&U.command[2]!==I?U.command[2]:void 0),Z=K(X),q=await z(Z),V=await H(q,Z);if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(W(V));R0(V);return}let Q=Jr();if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Xy0(Q));R0(Q)}var Oy0=m(()=>{Zy0();Qr();q4();l1()});var Dy0;var Ny0=m(()=>{Dy0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.38",description:"HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-usehttp`, or the `seal-useservicestart` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n"},servers:[{url:"http://localhost:8787",description:"Local HTTP adapter (`seal-usehttp`, or the `seal-useservicestart` daemon). Loopback-only by default."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps","x-implementation-status":"implemented",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp","x-implementation-status":"planned",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp","x-implementation-status":"planned",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig","x-implementation-status":"planned",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional i
Line truncated
toloopback(\`--host 127.0.0.1\`) and do not expose the port to a network or an origin you
donotcontrol.
`}},parameters:{CorpId:{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."},Offset:{name:"offset",in:"query",schema:{type:"integer",minimum:0,default:0},description:"Zero-based pagination offset."},Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50},description:"Maximum number of records to return."},RuleId:{name:"ruleId",in:"path",required:!0,schema:{type:"string"},description:"Approval rule ID."},VersionId:{name:"versionId",in:"path",required:!0,schema:{type:"string"},description:"Published rule version ID."},DocumentId:{name:"documentId",in:"path",required:!0,schema:{type:"string"},description:"Approval knowledge document ID."},RecordId:{name:"recordId",in:"path",required:!0,schema:{type:"string"},description:"seal-use approval run record ID."},BatchId:{name:"batchId",in:"path",required:!0,schema:{type:"string"},description:"Simulation batch ID."}},responses:{BadRequest:{description:"Invalid request.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},Unauthorized:{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},NotFound:{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}},schemas:{ErrorResponse:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}},CorpSummary:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}},SwitchCorpRequest:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}},SwitchCorpResponse:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}},SourceConfig:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."},AuthStage:{type:"object",additionalProperties:!0,required:["name","ok"],properties:{name:{type:"string",examples:["hose.openapi","hose.provisional","seal.sso","seal.whoami"]},ok:{type:"boolean"},error:{type:"string"}}},AuthDiagnosis:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}},SealUser:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},tenantId:{type:"string"},name:{type:"string"},isAdmin:{type:"boolean"},permissions:{type:"array",items:{type:"string"}}}},SealTenant:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},name:{type:"string"},tenantSlug:{type:"string"}}},WhoamiResponse:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}},SessionResponse:{type:"object",additionalProperties:!0,required:["user","session"],properties:{user:{$ref:"#/components/schemas/SealUser"},session:{type:"object",additionalProperties:!0}}},ApprovalRule:{type:"object",additionalProperties:!0,required:["id","description","scope","strictness"],properties:{id:{type:"string"},description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]},status:{type:"string"}}},ApprovalRuleInput:{type:"object",required:["description","scope","strictness"],properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulePatch:{type:"object",additionalProperties:!1,properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulesResponse:{type:"object",required:["rules"],properties:{rules:{type:"array",items:{$ref:"#/components/schemas/ApprovalRule"}},hasPendingDeletes:{type:"boolean"}}},RuleSetVersion:{type:"object",additionalProperties:!0,required:["id","versionNumber","versionName","rules"],properties:{id:{type:"string"},versionNumber:{type:"integer"},versionName:{type:"string"},publishedByName:{type:"string"},rules:{type:"array",items:{type:"object",additionalProperties:!0}}}},PublishRuleVersionRequest:{type:"object",required:["versionName"],properties:{versionName:{type:"string"}}},ApprovalDocument:{type:"object",additionalProperties:!0,required:["id","title","content"],properties:{id:{type:"string"},title:{typ
Line truncated
`}},parameters:{CorpId:{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."},Offset:{name:"offset",in:"query",schema:{type:"integer",minimum:0,default:0},description:"Zero-based pagination offset."},Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50},description:"Maximum number of records to return."},RuleId:{name:"ruleId",in:"path",required:!0,schema:{type:"string"},description:"Approval rule ID."},VersionId:{name:"versionId",in:"path",required:!0,schema:{type:"string"},description:"Published rule version ID."},DocumentId:{name:"documentId",in:"path",required:!0,schema:{type:"string"},description:"Approval knowledge document ID."},RecordId:{name:"recordId",in:"path",required:!0,schema:{type:"string"},description:"seal-use approval run record ID."},BatchId:{name:"batchId",in:"path",required:!0,schema:{type:"string"},description:"Simulation batch ID."}},responses:{BadRequest:{description:"Invalid request.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},Unauthorized:{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},NotFound:{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}},schemas:{ErrorResponse:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}},CorpSummary:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}},SwitchCorpRequest:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}},SwitchCorpResponse:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}},SourceConfig:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."},AuthStage:{type:"object",additionalProperties:!0,required:["name","ok"],properties:{name:{type:"string",examples:["hose.openapi","hose.provisional","seal.sso","seal.whoami"]},ok:{type:"boolean"},error:{type:"string"}}},AuthDiagnosis:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}},SealUser:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},tenantId:{type:"string"},name:{type:"string"},isAdmin:{type:"boolean"},permissions:{type:"array",items:{type:"string"}}}},SealTenant:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},name:{type:"string"},tenantSlug:{type:"string"}}},WhoamiResponse:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}},SessionResponse:{type:"object",additionalProperties:!0,required:["user","session"],properties:{user:{$ref:"#/components/schemas/SealUser"},session:{type:"object",additionalProperties:!0}}},ApprovalRule:{type:"object",additionalProperties:!0,required:["id","description","scope","strictness"],properties:{id:{type:"string"},description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]},status:{type:"string"}}},ApprovalRuleInput:{type:"object",required:["description","scope","strictness"],properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulePatch:{type:"object",additionalProperties:!1,properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulesResponse:{type:"object",required:["rules"],properties:{rules:{type:"array",items:{$ref:"#/components/schemas/ApprovalRule"}},hasPendingDeletes:{type:"boolean"}}},RuleSetVersion:{type:"object",additionalProperties:!0,required:["id","versionNumber","versionName","rules"],properties:{id:{type:"string"},versionNumber:{type:"integer"},versionName:{type:"string"},publishedByName:{type:"string"},rules:{type:"array",items:{type:"object",additionalProperties:!0}}}},PublishRuleVersionRequest:{type:"object",required:["versionName"],properties:{versionName:{type:"string"}}},ApprovalDocument:{type:"object",additionalProperties:!0,required:["id","title","content"],properties:{id:{type:"string"},title:{typ
Line truncated
`);I(z)})})}var Qj=8787,Jj="127.0.0.1";var lo=m(()=>{kg0();z3()});async function xg0($){let Y=s0($.options.port)??s0($.options.p),U=S($.options.host)??S($.options.h),z=await Kj({port:Y,host:U}),I=()=>{z.close(()=>{process.exit(0)})};process.on("SIGINT",I),process.on("SIGTERM",I),await new Promise(()=>{})}var fg0=m(()=>{Z4();lo()});async function ug0($,Y,U,z){if($==="config"||$==="get"){await x0("seal_llm_config_get",Y,U,{},j0(z.options));return}if($==="providers"||$==="list"){await x0("seal_llm_providers_list",Y,U,{},j0(z.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var bg0=m(()=>{O4();m1()});async function ig0($,Y){if($==="config"||$==="json"){oo();return}let{startServer:U}=await pg0().then(() => ng0);U()}function oo(){R0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var cg0=m(()=>{m1()});function dg0($){let Y=Uj();R0(Y,{...j0($.options),allowFull:!0})}var mg0=m(()=>{po();m1()});async function lg0($,Y,U,z){if($==="available"){await x0("seal_permissions_available_list",Y,U,{},j0(z.options));return}if($==="configs"||$==="list"){await x0("seal_permissions_configs_list",Y,U,{},j0(z.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var og0=m(()=>{O4();m1()});import{readFileSync as rg0}from"node:fs";async function sg0($,Y,U,z,I,Q,J){if(!$||$==="get"){await x0("seal_preference_get",I,Q,{},j0(J.options));return}if($==="decision"){if(Y==="update"||!Y){let K=S(J.options.input),G=K?JSON.parse(rg0(K,"utf8")):B8(J.json);if(!G||Object.keys(G).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await x0("seal_preference_decision_update",I,Q,{...G,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let K=S(J.options.default)??S(J.options.level)??z;if(K!=="medium"&&K!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await x0("seal_preference_thinking_depth_set",I,Q,{defaultLevel:K,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}if(Y==="policies"){if(U==="list"||!U){await x0("seal_preference_thinking_depth_policies_list",I,Q,{},j0(J.options));return}if(U==="upsert"){let K=S(J.options.input),G=K?JSON.parse(rg0(K,"utf8")):B8(J.json);if(!G||!G.id||!G.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await x0("seal_preference_thinking_depth_policies_upsert",I,Q,{...G,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}if(U==="remove"||U==="delete"){let K=z??S(J.options.id)??S(J.options.policyId);if(!K)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await x0("seal_preference_thinking_depth_policies_remove",I,Q,{policyId:K,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}var ag0=m(()=>{O4();Z4();m1()});async function tg0($={}){let Y=t8(),U=v4(),z=n2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},x3());console.log(`[probe]corp=${z.id}source=${z.source.type}`);let I=await bK(z);console.log("[probe] seal enterprise"),console.log(JSON.stringify(I,null,2));let Q=await B1(z),J=await SM(Q,{documentLimit:20,stylePreferencesEndpoint:z.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:J.rules.rules.length,hasPendingRuleDeletes:J.rules.hasPendingDeletes,documents:J.documents.articles.length,documentsTotal:J.documents.total,stylePreferences:J.stylePreferences.ok?"ok":`error:${J.stylePreferences.error}`},null,2))}var eg0=m(()=>{T5();m6();fT();X6()});async function $y0($,Y,U){let z=Y??S(U.options.corp)??($&&$!=="--corp"?$:void 0);await tg0({corpId:z})}var Yy0=m(()=>{eg0();Z4()});async function ro($,Y,U,z,I){if($==="count"){await x0("seal_approval_rules_list",U,z,{countOnly:!0},j0(I.options));return}if($==="list"){if(G0(I.options.count)){await x0("seal_approval_rules_list",U,z,{countOnly:!0},j0(I.options));return}let Q=s0(I.options.limit),J=s0(I.options.offset);if(G0(I.options.summary)){await x0("seal_approval_rules_list",U,z,{fields:Iv0,limit:Q,offset:J},j0(I.options));return}let K=await M$("seal_approval_rules_list",U,z,{limit:Q,offset:J}),G=j0(I.options);Qv0(K,G.allowFull===!0||Boolean(G.outputFile)),R0(K,G);return}if($==="clear"){let Q=G0(I.options.yes)===!0,J=G0(I.options.dryRun)??G0(I.options["dry-run"])??!Q;if(!Q&&!J)throw w$("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${z.id}--dry-run`);let K=await M$("seal_approval_rules_clear",U,z,{dryRun:J,recode:G0(I.options.recode)});if(!Q&&J&
Line truncated
`).filter(Boolean),Q=I.slice(-Y);return{logFile:U,lines:Q,totalLines:I.length}}async function Bk1($){let Y=Xj($),U=to($),z=pq($);Jy0($.stateDir);let I=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):Qj),Q=$.host??(process.env.HOST?process.env.HOST:Jj);Hj(Y,`${process.pid}
`,{mode:384}),Hj(U,JSON.stringify({pid:process.pid,port:I,host:Q,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),pK(z,`servicestartingonhttp://${Q}:${I} pid=${process.pid}`);let J=null;try{J=await Kj({port:I,host:Q,silent:!0}),pK(z,`service listening pid=${process.pid}`)}catch(G){if(pK(z,`service failed to bind port ${I}: ${G instanceof Error?G.message:String(G)}`),Wj(Y)===process.pid)x9(Y,{force:!0}),x9(U,{force:!0});throw G}let K=()=>{if(J)J.close(),J=null;if(Wj(Y)===process.pid)x9(Y,{force:!0}),x9(U,{force:!0});pK(z,`stopped pid=${process.pid}`)};await new Promise((G)=>{let H=!1,W=()=>{if(H)return;H=!0,K(),process.off("SIGTERM",W),process.off("SIGINT",W),G()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function zy0($){Jy0($.stateDir);let Y=cz($);if(Y.running)return Y;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},z=[...U.args??[],"service","run"];if($.port)z.push("--port",String($.port));if($.host)z.push("--host",String($.host));let I=Ok1(U.command,z,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});I.unref();let Q=Xj($);return Hj(Q,`${I.pid}
`,{flag:"a",mode:384})}var eo=m(()=>{lo()});import{homedir as Tk1}from"node:os";import{join as jk1}from"node:path";async function Yr($,Y,U){let z=U?s0(U.options.port)??s0(U.options.p):void 0,I=U?S(U.options.host)??S(U.options.h):void 0,Q=U?s0(U.options.lines)??s0(U.options.n):void 0,J=await s3($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:$r,version:X1,launcher:Y.launcher,port:z,host:I},{maxLines:Q});if(J!==void 0)R0(J)}var $r;var Ur=m(()=>{z3();eo();m1();Z4();$r=jk1(Tk1(),".config","seal-use")});import{existsSync as Ek1,readFileSync as Ky0}from"node:fs";async function Gy0($,Y,U,z,I){if($==="batch-records"||$==="records"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation batch-records <batchId>");await x0("seal_simulation_batch_records_get",U,z,{batchId:Q,query:S(I.options.query)},j0(I.options));return}if($==="create"||$==="run"){let Q=S(I.options.mode)??S(I.options.sourceSystem)??S(I.options["source-system"])??"hosecloud",J=Q==="material-pack"?"material_pack":Q,K=S(I.options.schemaConfig)??S(I.options["schema-config"]),G=K?JSON.parse(Ky0(K,"utf8")):void 0,H=S(I.options.input),W=H?JSON.parse(Ky0(H,"utf8")):B8(I.json),X=S(I.options.packageId)??S(I.options["package-id"]),Z=i6(I.options.packageIds)??i6(I.options["package-ids"])??(X?[X]:void 0),q=i6(I.options.flowIds)??i6(I.options["flow-ids"])??i6(I.options.documentSn)??i6(I.options["document-sn"]),V=S(I.options.signKey)??S(I.options["sign-key"])??S(I.options.integration),w=G0(I.options.wait)===!0,M=G0(I.options.noWait)??G0(I.options["no-wait"])??(w?!1:!0),F=await M$("seal_simulation_batch_create",U,z,{mode:J,sourceSystem:J,flowIds:q,documentSn:q,rejectNodeName:S(I.options.rejectNode)??S(I.options["reject-node"])??null,thinkingDepthOverride:S(I.options.thinkingDepth)??S(I.options["thinking-depth"]),skipInvoiceGeneration:G0(I.options.skipInvoiceGeneration)??G0(I.options["skip-invoice-generation"]),skipExpenseExtraction:G0(I.options.skipExpenseExtraction)??G0(I.options["skip-expense-extraction"]),disableAttachmentCache:G0(I.options.disableAttachmentCache)??G0(I.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:S(I.options.templateId)??S(I.options["template-id"]),schemaConfig:G,requestIds:i6(I.options.requestIds)??i6(I.options["request-ids"]),workflowTypeId:S(I.options.workflowTypeId)??S(I.options["workflow-type-id"]),flowStatusList:i6(I.options.flowStatusList)?.map(Number)??i6(I.options["flow-status-list"])?.map(Number),businessCodes:i6(I.options.businessCodes)??i6(I.options["business-codes"]),documentType:S(I.options.documentType)??S(I.options["document-type"]),startTime:s0(I.options.startTime)??s0(I.options["start-time"]),endTime:s0(I.options.endTime)??s0(I.options["end-time"]),status:i6(I.options.status),limit:s0(I.options.limit),noWait:M,rawParams:W});if(w&&F&&typeof F==="object"&&"batchId"in F&&typeof F.batchId==="string"){await x0("seal_simulation_batch_wait",U,z,{batchId:F.batchId,timeout:S(I.options.timeout),pollInterval:S(I.options.pollInterval)??S(I.options["poll-interval"])},j0(I.options));return}R0(F,j0(I.options));return}if($==="wait"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await x0("seal_simulation_batch_wait",U,z,{batchId:Q,timeout:S(I.options.timeout),pollInterval:S(I.options.pollInterval)??S(I.options["poll-interval"])},j0(I.options));return}if($==="status"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation status <batchId>");await x0("seal_simulation_batch_status",U,z,{batchId:Q},j0(I.options));return}if($==="clean"||$==="delete"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation clean <batchId>");await x0("seal_simulation_batch_clean",U,z,{batchId:Q},j0(I.options));return}if($==="specifications"){let Q=Y??S(I.options.integration)??S(I.options.signKey)??S(I.options["sign-key"]);await x0("seal_simulation_specifications_list",U,z,{signKey:Q},j0(I.options));return}if($==="approval-definitions"||$==="definitions"){await x0("seal_simulation_feishu_approval_definitions_list",U,z,{},j0(I.options));return}if($==="list"){await x0("seal_simulation_batches_list",U,z,{limit:s0(I.options.limit)},j0(I.options));return}if($==="get"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation get <batchId>");await x0("seal_simulation_batch_get",U,z,{batchId:Q},j0(I.options));return}if($==="templates"){await x0("seal_simulation_templates_get",U,z,{},j0(I.options));return}if($==="integrations"){await x0("seal_simulation_integrations_get",U,z,{},j0(I.options));return}if($==="package-upload"){let Q=Y??S(I.options.file);if(!Q)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!Ek1(Q))throw Error(`Filenotfound:${Q}`);await x0("seal_simulation_material_package_upload",U,z,{filePath:Q},j0(I.o
Line truncated
`);return}if($==="install"||$==="init"||$==="sync"){let z=G0(U.options.local)||G0(U.options.workspace),I=S(U.options.dir)??S(U.options.target)??Y,Q=I?I:z?Zj(process.cwd(),".agents","skills","seal-use"):iz(),J=Og0(Q),K=!z&&!I,G=K?_o():void 0,H=K?So():void 0;R0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files,...G?{antigravity:G}:{},...H?{hosts:H}:{}});return}if($==="status"||$==="get"||!$){let z=iz(),I=Zj(process.cwd(),".agents","skills","seal-use"),Q=vo(),J=go();R0({global:{dir:z,installed:Wy0(Zj(z,"SKILL.md"))},local:{dir:I,installed:Wy0(Zj(I,"SKILL.md"))},antigravity:Q,hosts:J});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}var Zy0=m(()=>{ko();iq();Z4();m1()});async function qy0($,Y){if($==="config"){R0(await bK(Y));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var Vy0=m(()=>{fT();m1()});function zr($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let Y=$.toUpperCase().trim();if(Y==="APPROVE"||Y==="PASS")return"APPROVE";if(Y==="REJECT"||Y==="DENIED")return"REJECT";if(Y==="MANUAL"||Y==="ASSISTED")return"MANUAL";if(Y==="ERROR"||Y==="FAILED")return"ERROR";return Y}async function Ly0($){let{sourceCorp:Y,targetCorp:U,sourceClient:z,targetClient:I,samples:Q=10,dryRun:J=!1,pollIntervalMs:K=2000,timeoutMs:G=45000,snPrefix:H="REG_",fetchFn:W=fetch}=$;if(U.environment!=="test")throw new W4(`重放目标企业「${U.name}」(${U.id})的环境为「${U.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Y.id}<testCorpId>`);let X=await lY(I),q=(Array.isArray(X.features)?X.features:[]).find((d)=>d?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,w=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,M=Q*w;if(V<M)throw new W4(`测试企业「${U.name}」AI审批额度不足:当前剩余${V}点,本次回归抽样${Q}笔需要约${M}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${U.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(V/w))})`);let F=await i4(z,{limit:Q,status:"completed"}),N=Array.isArray(F.records)?F.records:[];if(N.length===0){let d=await i4(z,{limit:Q});N=Array.isArray(d.records)?d.records:[]}if(N.length===0)throw new W4(`在母企业「${Y.name}」(${Y.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(N=N.slice(0,Q),J){let d=N.map((a)=>{let $0=a.sourceDocumentSN??a.id,y=a?.result?.decision??a.aiDecision??a?.decision,p=zr(y),Y0=a?.result?.summary??a.aiSummary;return{sn:$0,sourceRecordId:a.id,prodDecision:p,prodSummary:Y0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M},metrics:{sampleCount:d.length,successCount:d.length,failureCount:0,matchCount:d.length,flipCount:0,concordanceRate:1},flips:[],records:d}}let O=await gp(I,U,$.webhookSelector),D=[];for(let d of N){let a=Date.now(),$0=d.sourceDocumentSN??d.id,y=zr(d?.result?.decision??d.aiDecision??d?.decision),p=d?.result?.summary??d.aiSummary;try{let Y0=await H4(z,d.id),R=`${H}${$0}`,o=hp(Y0,{snPrefix:H,docIdPrefix:H});await Sp(O.incomingDocumentWebhook.url,O.secret,o,W,A6(U.seal));let e=null,O0=Date.now();while(Date.now()-O0<G){await new Promise((X0)=>setTimeout(X0,K));let t=await i4(I,{sourceDocumentSN:R,limit:1});if(t.records&&t.records.length>0){let X0=t.records[0];if(X0.status==="completed"||X0.status==="failed"){e=X0;break}}}if(!e){D.push({sn:$0,sourceRecordId:d.id,prodDecision:y,prodSummary:p,status:"FAILED",error:`测试租户单据审核超时(${Math.round(G/1000)}s未完成)`,durationMs:Date.now()-a});continue}let T0=zr(e?.result?.decision??e.aiDecision??e?.decision??(e.status==="completed"?"APPROVE":"ERROR")),y0=e?.result?.summary??e.aiSummary,v0=y===T0,o0=v0?"MATCHED":"FLIPPED",q1={sn:$0,sourceRecordId:d.id,prodDecision:y,prodSummary:p,testRecordId:e.id,testDecision:T0,testSummary:y0,status:o0,durationMs:Date.now()-a};if(!v0)q1.diff={from:y,to:T0,reasonDiff:y0&&p&&y0!==p?`生产:${p.slice(0,60)}...->测试:${y0.slice(0,60)}...`:void 0};D.push(q1)}catch(Y0){D.push({sn:$0,sourceRecordId:d.id,prodDecision:y,prodSummary:p,status:"FAILED",error:Y0 instanceof Error?Y0.message:String(Y0),durationMs:Date.now()-a})}}let P=D.filter((d)=>d.status==="MATCHED"||d.status==="FLIPPED"),T=D.filter((d)=>d.status==="MATCHED"),A=D.filter((d)=>d.status==="FLIPPED"),j=D.filter((d)=>d.status==="FAILED").length,C=T.length,b=A.length,x=C+b,g=x>0?C/x:0,i=b>0,c=i?"REGRESSIONS_DETECTED":"CLEAN",z0=!i&&j===0,k;try{let d=await lY(I),$0=(Array.isArray(d.features)?d.features:[]).find((y)=>y?.code==="ai-approval");if(typeof $0?.balance==="number")k=$0.balance}catch{}return{ok:!i&&j===0,verdict:c,safeToPublish:z0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M,balanceAfter:k},metrics:{sampleCount:D.length,successCount:P.length,failureCount:j,matchCount:C,flipCount:b,concordanceRate:Number(g.toFixed(4))},flips:A,records:D}}function Fy0($){let{sourceCorp:Y,targetCorp:U,verdict:z,safeToPublish:I,metrics:Q,quota:J,flips:K,records:G}=$,H=z==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":z==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",W=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${Y.name}」->测试靶场「${U.name}」`,`判定:${H}·准许发布:${I?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${Q.sampleCount}|一致通过:${Q.matchCount}|决策翻转:${Q.flipCount}|异常失败:${Q.failureCount}`,`一致率:${(Q.concordanceRate*100).toFixed(1)}%|消耗预估:${J.estimatedRequired}点(余量:${J.balanceBefore}${J.balanceAfter!==void0?` -> ${J.balanceAfter}`:""})`," "+"─".repeat(65)];if(K.length>0){W.push(`⚠️决策翻转清单(${K.length}笔单据在新规则下结果改变):`);for(let X of K)if(W.push(`•单据[${X.sn}]:原生产判定「${X.prodDecision}」➔测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)W.push(`理由差异:${X.diff.reasonDiff}`);W.push(" "+"─".repeat(65)),W.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(z==="CLEAN")W.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100%
Line truncated
`)}var wy0=m(()=>{O8();X6();iZ()});async function Ir($,Y,U){let z=($??Y??"regression").toLowerCase();if(z==="regression"||z==="regress"||z==="matrix"){let I=S(U.options.corp)??(Y&&Y!==z?Y:void 0),Q=M1(I),J=Q,K=Q;if(Q.environment==="test"){K=Q;let O=S(U.options["prod-corp"])??S(U.options.prod)??Q.prodCorpId;if(!O)throw new W4(`测试企业「${Q.name}」(${Q.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${Q.id}`);J=M1(O)}else{J=Q;let O=S(U.options["test-corp"])??S(U.options.test)??Q.testCorpId;if(!O)throw new W4(`生产企业「${Q.name}」(${Q.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Q.id}<testCorpId>`);K=M1(O)}let G=await B1(J),H=await B1(K),W=s0(U.options.samples)??s0(U.options.limit)??s0(U.options.n)??10,X=G0(U.options["dry-run"]),Z=G0(U.options["fail-on-flips"]),q=s0(U.options["poll-interval"])??2000,V=s0(U.options.timeout)??45000,w=S(U.options["sn-prefix"])??"REG_",M=S(U.options.webhook)??S(U.options.selector),F=await Ly0({sourceCorp:J,targetCorp:K,sourceClient:G,targetClient:H,samples:W,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:w,failOnFlips:Z,webhookSelector:M});if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Fy0(F));if(R0(F),Z&&!F.ok)throw new W4(`回归测试发现${F.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new W4(`未知的test子命令:"${z}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}var My0=m(()=>{O8();O4();Z4();m1();m6();wy0()});async function Oy0($,Y,U,z){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await x0($,Y,U,B8(z.json),j0(z.options))}var Ny0=m(()=>{O4();Z4();m1()});function Dy0(){R0(Pq.map(($)=>({name:$.name,description:$.description})))}var Ay0=m(()=>{jq();m1()});function qj($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var By0=m(()=>{iq()});import{existsSync as Ck1,mkdirSync as Rk1,readFileSync as _k1,renameSync as vk1,writeFileSync as hk1}from"node:fs";import{homedir as Sk1}from"node:os";import{dirname as gk1,join as yk1}from"node:path";import{spawn as kk1}from"node:child_process";function Py0($){return $.replace(/\.\d+Z$/,"Z")}function Ty0(){let $=process.env[xk1]?.trim();if($)return $;return uk1}function jy0($=Ty0()){if(!Ck1($))return null;try{let Y=_k1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&typeof U.latestVersion==="string"&&typeof U.checkedAt==="string")return{...U,checkedAt:Py0(U.checkedAt)};return null}catch{return null}}function dq($,Y=Ty0()){try{let U=gk1(Y);Rk1(U,{recursive:!0,mode:448});let z={checkedAt:Py0($.checkedAt??new Date().toISOString()),latestVersion:$.latestVersion,publishedAt:$.publishedAt,releaseUrl:$.releaseUrl},I=`${Y}.tmp.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;hk1(I,JSON.stringify(z,null,2),{mode:384}),vk1(I,Y)}catch{}}function Ey0($,Y=fk1){if(!$||!$.checkedAt)return!0;let U=new Date($.checkedAt).getTime();if(Number.isNaN(U))return!0;return Date.now()-U>Y}function Cy0($){if(process.env.SEAL_DISABLE_BG_UPDATE==="1"||!1||process.env.CI)return!1;if(!$||!$.command)return!1;try{let Y=$.command,U=[...$.args??[],"update","check","--bg-save"];return kk1(Y,U,{detached:!0,stdio:"ignore",env:{...process.env,SEAL_DISABLE_BG_UPDATE:"1"}}).unref(),!0}catch{return!1}}var xk1="SEAL_USE_UPDATE_CACHE_FILE",fk1=86400000,uk1;var Qr=m(()=>{uk1=yk1(Sk1(),".config","seal-use","update-cache.json")});import{chmodSync as bk1,mkdirSync as ik1,readdirSync as ck1,realpathSync as Ry0,renameSync as Jr,rmSync as nk1,unlinkSync as gy0,writeFileSync as _y0}from"node:fs";import{basename as pk1,dirname as dk1,isAbsolute as mk1,join as Fj,relative as lk1}from"node:path";import{spawn as ok1,spawnSync as a3}from"node:child_process";async function ky0($,Y={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:$r,version:X1,launcher:$.launcher},z=Y.repo||process.env[rk1]?.trim()||process.env[sk1]?.trim()||yy0,I=Y.targetVersion?.trim(),Q=I&&I.toLowerCase()!=="latest"?I:void 0;if(Q){let D=Q.replace(/^v/,""),P=by0(D,X1);if(P<0)if(!Wg&&Y.force);else{R0({updated:!1,currentVersion:X1,targetVersion:D,mode:qj()?"binary":"source",message:!Wg?`Cannotdowngradeseal-usefromdevbuildv${X1}toreleasev${D}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${X1}toolderversionv${D}.Updatesmustbeforward-only.`});return}if(P===0&&!Y.force){R0({updated:!1,currentVersion:X1,targetVersion:D,mode:qj()?"binary":"source",message:`seal-useisalreadyatversionv${X1}.Use--forcetoreinstall.`});return}}if(Y.changelogOnly){let D=await Lj(z,Y.limit??10);R0({currentVersion:X1,totalQueried:D.length,releases:D.map((P)=>({version:P.version,tagName:P.tagName,publishedAt:P.publishedAt,author:P.author,releaseNotes:P.notes,releaseUrl:P.htmlUrl,isCurrent:P.version===X1,isNewer:h5(P.version,X1)}))});return}if(!qj()){if(Y.checkOnly){let P=await Lj(z,30),T=P[0],A=T?.version??X1,j=P.find((x)=>x.version===X1),C=h5(A,X1),b=P.filter((x)=>h5(x.version,X1));if(T?.version)dq({latestVersion:T.version,publishedAt:T.publishedAt,releaseUrl:T.htmlUrl});if(Y.bgSave)return;R0({updated:!1,updateAvailable:C,currentVersion:X1,currentVersionPublishedAt:j?.publishedAt,latestVersion:A,latestVersionPublishedAt:T?.publishedAt,behindCount:b.length,pendingReleases:b.map((x)=>({version:x.version,tagName:x.tagName,publishedAt:x.publishedAt,author:x.author,releaseNotes:x.notes,releaseUrl:x.htmlUrl})),releaseNotes:T?.notes??"",releaseUrl:T?.htmlUrl??"",mode:"source",message:"当前运行的是开发版。正式用户请安装正式版后使用 seal-use update。"});return}let D=cz(U).running;if(D)await s3("stop",U);try{Sy0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(P){console.error(`⚠️开发版更新同步失败,继续刷新本地依赖:${PinstanceofError?P.message:String(P)}`)}if(Sy0("bun",["install"],{cwd:$.appRoot}),D)await s3("start",U);R0({updated:!0,serviceRestarted:D,version:X1,mode:"source"});return}if(Yx1())try{await Ux1($,Y,U,z,Q);return}catch(D){console.error(`⚠️Homebrew自动更新失败,回退至原生二进制更新:${DinstanceofError?D.message:String(D)}`)}let J=tk1(),K=ek1(),G=await Lj(z,30),H=Q?G.find((D)=>D.version
Line truncated
`)}catch{}}async function Qx1($,Y,U,z){let I=Kr(),Q=[],J=U?U.startsWith("v")?U:`v${U}`:void 0,K=z||$.split("/").pop()||"";if(I!=="github"){if(J&&K)Q.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${J}/${K}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${J}/${K}`);if($.startsWith("https://git.ying-qing.cn"))Q.push($)}if(I!=="gitea")if(J&&K){let w=`https://github.com/${yy0}/releases/download/${J}/${K}`;if(!process.env.CI)Q.push(`https://ghfast.top/${w}`,`https://gh.ddlc.top/${w}`);Q.push(w)}else if($.includes("github.com")){if(!process.env.CI)Q.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Q.push($)}else Q.push($);let G=Array.from(new Set(Q)),H,W=6000,X=6000,Z=307200,q=1e4,V=180000;for(let w=0;w<G.length;w++){let M=G[w],F=new AbortController,N="",O=(A)=>{N=A;try{F.abort()}catch{}},D=setTimeout(()=>{O("Connection timed out (no response headers within 6s)")},W),P,T;try{Vj(`==> [${w+1}/${G.length}] Downloading via: ${M}`);let A=await fetch(M,{signal:F.signal});if(D)clearTimeout(D),D=void 0;if(!A.ok)throw Error(`HTTP ${A.status} ${A.statusText}`);P=setTimeout(()=>{O("Overall download time exceeded 3 minutes")},V);let j=Number(A.headers.get("content-length"))||0,C=A.body?.getReader();if(!C){let c=Buffer.from(await A.arrayBuffer());if(c.length<1000)throw Error(`Downloaded content is suspiciously small (${c.length} bytes)`);_y0(Y,c),Vj(`✓ Download succeeded (${(c.length/1024/1024).toFixed(1)} MB)`);return}let b=[],x=0,g=0;T=setTimeout(()=>{if(x<Z){let c=(x/1024).toFixed(1);O(`Initial transfer too slow (${c} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let c=C.read(),z0,k=new Promise((y,p)=>{z0=setTimeout(()=>{p(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),d;try{d=await Promise.race([c,k])}finally{if(z0)clearTimeout(z0)}let{done:a,value:$0}=d;if(a)break;if($0){if(b.push($0),x+=$0.length,T&&x>=Z)clearTimeout(T),T=void 0;let y=Date.now();if(y-g>200){g=y;let p=j?Math.round(x/j*100):0,Y0=(x/1048576).toFixed(1),R=j?(j/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${p}% (${Y0} / ${R} MB)...`)}catch{}}}}try{process.stderr.write(`
`);Q(I)})})}var ZE=8787,qE="127.0.0.1";var Gr=m(()=>{Ey0();J3()});async function jy0($){let Y=s0($.options.port)??s0($.options.p),U=h($.options.host)??h($.options.h),I=await VE({port:Y,host:U}),Q=()=>{I.close(()=>{process.exit(0)})};process.on("SIGINT",Q),process.on("SIGTERM",Q),await new Promise(()=>{})}var Cy0=m(()=>{q4();Gr()});async function Ry0($,Y,U,I){if($==="config"||$==="get"){await x0("seal_llm_config_get",Y,U,{},E0(I.options));return}if($==="providers"||$==="list"){await x0("seal_llm_providers_list",Y,U,{},E0(I.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var _y0=m(()=>{O4();l1()});async function vy0($,Y){if($==="config"||$==="json"){Hr();return}let{startServer:U}=await gy0().then(() => hy0);U()}function Hr(){R0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var Sy0=m(()=>{l1()});function yy0($){let Y=HE();R0(Y,{...E0($.options),allowFull:!0})}var ky0=m(()=>{Kr();l1()});async function xy0($,Y,U,I){if($==="available"){await x0("seal_permissions_available_list",Y,U,{},E0(I.options));return}if($==="configs"||$==="list"){await x0("seal_permissions_configs_list",Y,U,{},E0(I.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var fy0=m(()=>{O4();l1()});import{readFileSync as uy0}from"node:fs";async function by0($,Y,U,I,Q,J,K){if(!$||$==="get"){await x0("seal_preference_get",Q,J,{},E0(K.options));return}if($==="decision"){if(Y==="update"||!Y){let z=h(K.options.input),G=z?JSON.parse(uy0(z,"utf8")):E8(K.json);if(!G||Object.keys(G).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await x0("seal_preference_decision_update",Q,J,{...G,dryRun:G0(K.options.dryRun)??G0(K.options["dry-run"])},E0(K.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let z=h(K.options.default)??h(K.options.level)??I;if(z!=="medium"&&z!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await x0("seal_preference_thinking_depth_set",Q,J,{defaultLevel:z,dryRun:G0(K.options.dryRun)??G0(K.options["dry-run"])},E0(K.options));return}if(Y==="policies"){if(U==="list"||!U){await x0("seal_preference_thinking_depth_policies_list",Q,J,{},E0(K.options));return}if(U==="upsert"){let z=h(K.options.input),G=z?JSON.parse(uy0(z,"utf8")):E8(K.json);if(!G||!G.id||!G.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await x0("seal_preference_thinking_depth_policies_upsert",Q,J,{...G,dryRun:G0(K.options.dryRun)??G0(K.options["dry-run"])},E0(K.options));return}if(U==="remove"||U==="delete"){let z=I??h(K.options.id)??h(K.options.policyId);if(!z)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await x0("seal_preference_thinking_depth_policies_remove",Q,J,{policyId:z,dryRun:G0(K.options.dryRun)??G0(K.options["dry-run"])},E0(K.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}var iy0=m(()=>{O4();q4();l1()});async function cy0($={}){let Y=Y$(),U=A4(),I=d2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},i3());console.log(`[probe]corp=${I.id}source=${I.source.type}`);let Q=await nz(I);console.log("[probe] seal enterprise"),console.log(JSON.stringify(Q,null,2));let J=await A1(I),K=await uM(J,{documentLimit:20,stylePreferencesEndpoint:I.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:K.rules.rules.length,hasPendingRuleDeletes:K.rules.hasPendingDeletes,documents:K.documents.articles.length,documentsTotal:K.documents.total,stylePreferences:K.stylePreferences.ok?"ok":`error:${K.stylePreferences.error}`},null,2))}var ny0=m(()=>{l$();f6();pT();H4()});async function dy0($,Y,U){let I=Y??h(U.options.corp)??($&&$!=="--corp"?$:void 0);await cy0({corpId:I})}var py0=m(()=>{ny0();q4()});async function Wr($,Y,U,I,Q){if(!U&&!($==="lint"||$==="linters"||$==="linter-list"||$==="map"))throw Error(`rules${$??""}requiresanauthenticatedenterprise.Run'seal-use corps list'toselectone.`);if($==="count"){await x0("seal_approval_rules_list",U,I,{countOnly:!0},E0(Q.options));return}if($==="list"){if(G0(Q.options.count)){await x0("seal_approval_rules_list",U,I,{countOnly:!0},E0(Q.options));return}let K=s0(Q.options.limit),z=s0(Q.options.offset);if(G0(Q.options.summary)){await x0("seal_approval_rules_list",U,I,{fields:pv0,limit:K,offset:z},E0(Q.options));return}let G=await P$("seal_approval_rules_list",U,I,{limit:K,offset:z}),H=E0(Q.options);mv0(G,H.allowFull===!0||Boolean(H.outputFile)),R0(G,H);return}if($==="clear"){let K=G0(Q.options.yes)===!0,z=G0(Q.options.dryRun)??G0(Q.options["dry-run"])??!K;if(!K&&!z)throw U$("Refusing to clear rules without --ye
Line truncated
`).filter(Boolean),J=Q.slice(-Y);return{logFile:U,lines:J,totalLines:Q.length}}async function cx1($){let Y=ME($),U=qr($),I=sq($);sy0($.stateDir);let Q=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):ZE),J=$.host??(process.env.HOST?process.env.HOST:qE);FE(Y,`${process.pid}
`,{mode:384}),FE(U,JSON.stringify({pid:process.pid,port:Q,host:J,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),lz(I,`servicestartingonhttp://${J}:${Q} pid=${process.pid}`);let K=null;try{K=await VE({port:Q,host:J,silent:!0}),lz(I,`service listening pid=${process.pid}`)}catch(G){if(lz(I,`service failed to bind port ${Q}: ${G instanceof Error?G.message:String(G)}`),wE(Y)===process.pid)u9(Y,{force:!0}),u9(U,{force:!0});throw G}let z=()=>{if(K)K.close(),K=null;if(wE(Y)===process.pid)u9(Y,{force:!0}),u9(U,{force:!0});lz(I,`stopped pid=${process.pid}`)};await new Promise((G)=>{let H=!1,W=()=>{if(H)return;H=!0,z(),process.off("SIGTERM",W),process.off("SIGINT",W),G()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function ly0($){sy0($.stateDir);let Y=nI($);if(Y.running)return Y;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},I=[...U.args??[],"service","run"];if($.port)I.push("--port",String($.port));if($.host)I.push("--host",String($.host));let Q=fx1(U.command,I,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});Q.unref();let J=ME($);return FE(J,`${Q.pid}
`,{flag:"a",mode:384})}var Vr=m(()=>{Gr()});import{homedir as dx1}from"node:os";import{join as px1}from"node:path";async function Fr($,Y,U){let I=U?s0(U.options.port)??s0(U.options.p):void 0,Q=U?h(U.options.host)??h(U.options.h):void 0,J=U?s0(U.options.lines)??s0(U.options.n):void 0,K=await e3($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:Lr,version:X1,launcher:Y.launcher,port:I,host:Q},{maxLines:J});if(K!==void 0)R0(K)}var Lr;var wr=m(()=>{J3();Vr();l1();q4();Lr=px1(dx1(),".config","seal-use")});import{existsSync as mx1,readFileSync as ay0}from"node:fs";async function ty0($,Y,U,I,Q){if($==="batch-records"||$==="records"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation batch-records <batchId>");await x0("seal_simulation_batch_records_get",U,I,{batchId:J,query:h(Q.options.query)},E0(Q.options));return}if($==="create"||$==="run"){let J=h(Q.options.mode)??h(Q.options.sourceSystem)??h(Q.options["source-system"])??"hosecloud",K=J==="material-pack"?"material_pack":J,z=h(Q.options.schemaConfig)??h(Q.options["schema-config"]),G=z?JSON.parse(ay0(z,"utf8")):void 0,H=h(Q.options.input),W=H?JSON.parse(ay0(H,"utf8")):E8(Q.json),X=h(Q.options.packageId)??h(Q.options["package-id"]),Z=n6(Q.options.packageIds)??n6(Q.options["package-ids"])??(X?[X]:void 0),q=n6(Q.options.flowIds)??n6(Q.options["flow-ids"])??n6(Q.options.documentSn)??n6(Q.options["document-sn"]),V=h(Q.options.signKey)??h(Q.options["sign-key"])??h(Q.options.integration),w=G0(Q.options.wait)===!0,M=G0(Q.options.noWait)??G0(Q.options["no-wait"])??(w?!1:!0),F=await P$("seal_simulation_batch_create",U,I,{mode:K,sourceSystem:K,flowIds:q,documentSn:q,rejectNodeName:h(Q.options.rejectNode)??h(Q.options["reject-node"])??null,thinkingDepthOverride:h(Q.options.thinkingDepth)??h(Q.options["thinking-depth"]),skipInvoiceGeneration:G0(Q.options.skipInvoiceGeneration)??G0(Q.options["skip-invoice-generation"]),skipExpenseExtraction:G0(Q.options.skipExpenseExtraction)??G0(Q.options["skip-expense-extraction"]),disableAttachmentCache:G0(Q.options.disableAttachmentCache)??G0(Q.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:h(Q.options.templateId)??h(Q.options["template-id"]),schemaConfig:G,requestIds:n6(Q.options.requestIds)??n6(Q.options["request-ids"]),workflowTypeId:h(Q.options.workflowTypeId)??h(Q.options["workflow-type-id"]),flowStatusList:n6(Q.options.flowStatusList)?.map(Number)??n6(Q.options["flow-status-list"])?.map(Number),businessCodes:n6(Q.options.businessCodes)??n6(Q.options["business-codes"]),documentType:h(Q.options.documentType)??h(Q.options["document-type"]),startTime:s0(Q.options.startTime)??s0(Q.options["start-time"]),endTime:s0(Q.options.endTime)??s0(Q.options["end-time"]),status:n6(Q.options.status),limit:s0(Q.options.limit),noWait:M,rawParams:W});if(w&&F&&typeof F==="object"&&"batchId"in F&&typeof F.batchId==="string"){await x0("seal_simulation_batch_wait",U,I,{batchId:F.batchId,timeout:h(Q.options.timeout),pollInterval:h(Q.options.pollInterval)??h(Q.options["poll-interval"])},E0(Q.options));return}R0(F,E0(Q.options));return}if($==="wait"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await x0("seal_simulation_batch_wait",U,I,{batchId:J,timeout:h(Q.options.timeout),pollInterval:h(Q.options.pollInterval)??h(Q.options["poll-interval"])},E0(Q.options));return}if($==="status"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation status <batchId>");await x0("seal_simulation_batch_status",U,I,{batchId:J},E0(Q.options));return}if($==="clean"||$==="delete"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation clean <batchId>");await x0("seal_simulation_batch_clean",U,I,{batchId:J},E0(Q.options));return}if($==="specifications"){let J=Y??h(Q.options.integration)??h(Q.options.signKey)??h(Q.options["sign-key"]);await x0("seal_simulation_specifications_list",U,I,{signKey:J},E0(Q.options));return}if($==="approval-definitions"||$==="definitions"){await x0("seal_simulation_feishu_approval_definitions_list",U,I,{},E0(Q.options));return}if($==="list"){await x0("seal_simulation_batches_list",U,I,{limit:s0(Q.options.limit)},E0(Q.options));return}if($==="get"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation get <batchId>");await x0("seal_simulation_batch_get",U,I,{batchId:J},E0(Q.options));return}if($==="templates"){await x0("seal_simulation_templates_get",U,I,{},E0(Q.options));return}if($==="integrations"){await x0("seal_simulation_integrations_get",U,I,{},E0(Q.options));return}if($==="package-upload"){let J=Y??h(Q.options.file);if(!J)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!mx1(J))throw Error(`Filenotfound:${J}`);await x0("seal_simulation_material_package_upload",U,I,{filePath:J},E0(Q.o
Line truncated
`);return}if($==="install"||$==="init"||$==="sync"){let I=G0(U.options.local)||G0(U.options.workspace),Q=h(U.options.dir)??h(U.options.target)??Y,J=Q?Q:I?OE(process.cwd(),".agents","skills","seal-use"):cI(),K=Ky0(J),z=!I&&!Q,G=z?mo():void 0,H=z?ro():void 0;R0({installed:!0,targetDir:K.targetDir,fileCount:K.files.length,files:K.files,...G?{antigravity:G}:{},...H?{hosts:H}:{}});return}if($==="status"||$==="get"||!$){let I=cI(),Q=OE(process.cwd(),".agents","skills","seal-use"),J=lo(),K=so();R0({global:{dir:I,installed:$k0(OE(I,"SKILL.md"))},local:{dir:Q,installed:$k0(OE(Q,"SKILL.md"))},antigravity:J,hosts:K});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}var Uk0=m(()=>{to();lq();q4();l1()});async function Ik0($,Y){if($==="config"){R0(await nz(Y));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var Qk0=m(()=>{pT();l1()});function Mr($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let Y=$.toUpperCase().trim();if(Y==="APPROVE"||Y==="PASS")return"APPROVE";if(Y==="REJECT"||Y==="DENIED")return"REJECT";if(Y==="MANUAL"||Y==="ASSISTED")return"MANUAL";if(Y==="ERROR"||Y==="FAILED")return"ERROR";return Y}async function Jk0($){let{sourceCorp:Y,targetCorp:U,sourceClient:I,targetClient:Q,samples:J=10,dryRun:K=!1,pollIntervalMs:z=2000,timeoutMs:G=45000,snPrefix:H="REG_",fetchFn:W=fetch}=$;if(U.environment!=="test")throw new X4(`重放目标企业「${U.name}」(${U.id})的环境为「${U.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Y.id}<testCorpId>`);let X=await oY(Q),q=(Array.isArray(X.features)?X.features:[]).find((p)=>p?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,w=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,M=J*w;if(V<M)throw new X4(`测试企业「${U.name}」AI审批额度不足:当前剩余${V}点,本次回归抽样${J}笔需要约${M}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${U.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(V/w))})`);let F=await x4(I,{limit:J,status:"completed"}),N=Array.isArray(F.records)?F.records:[];if(N.length===0){let p=await x4(I,{limit:J});N=Array.isArray(p.records)?p.records:[]}if(N.length===0)throw new X4(`在母企业「${Y.name}」(${Y.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(N=N.slice(0,J),K){let p=N.map((a)=>{let $0=a.sourceDocumentSN??a.id,y=a?.result?.decision??a.aiDecision??a?.decision,d=Mr(y),Y0=a?.result?.summary??a.aiSummary;return{sn:$0,sourceRecordId:a.id,prodDecision:d,prodSummary:Y0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M},metrics:{sampleCount:p.length,successCount:p.length,failureCount:0,matchCount:p.length,flipCount:0,concordanceRate:1},flips:[],records:p}}let O=await Zp(Q,U,$.webhookSelector),D=[];for(let p of N){let a=Date.now(),$0=p.sourceDocumentSN??p.id,y=Mr(p?.result?.decision??p.aiDecision??p?.decision),d=p?.result?.summary??p.aiSummary;try{let Y0=await G4(I,p.id),R=`${H}${$0}`,o=Wp(Y0,{snPrefix:H,docIdPrefix:H});await Xp(O.incomingDocumentWebhook.url,O.secret,o,W,P6(U.seal));let e=null,O0=Date.now();while(Date.now()-O0<G){await new Promise((X0)=>setTimeout(X0,z));let t=await x4(Q,{sourceDocumentSN:R,limit:1});if(t.records&&t.records.length>0){let X0=t.records[0];if(X0.status==="completed"||X0.status==="failed"){e=X0;break}}}if(!e){D.push({sn:$0,sourceRecordId:p.id,prodDecision:y,prodSummary:d,status:"FAILED",error:`测试租户单据审核超时(${Math.round(G/1000)}s未完成)`,durationMs:Date.now()-a});continue}let T0=Mr(e?.result?.decision??e.aiDecision??e?.decision??(e.status==="completed"?"APPROVE":"ERROR")),y0=e?.result?.summary??e.aiSummary,v0=y===T0,o0=v0?"MATCHED":"FLIPPED",q1={sn:$0,sourceRecordId:p.id,prodDecision:y,prodSummary:d,testRecordId:e.id,testDecision:T0,testSummary:y0,status:o0,durationMs:Date.now()-a};if(!v0)q1.diff={from:y,to:T0,reasonDiff:y0&&d&&y0!==d?`生产:${d.slice(0,60)}...->测试:${y0.slice(0,60)}...`:void 0};D.push(q1)}catch(Y0){D.push({sn:$0,sourceRecordId:p.id,prodDecision:y,prodSummary:d,status:"FAILED",error:Y0 instanceof Error?Y0.message:String(Y0),durationMs:Date.now()-a})}}let P=D.filter((p)=>p.status==="MATCHED"||p.status==="FLIPPED"),T=D.filter((p)=>p.status==="MATCHED"),B=D.filter((p)=>p.status==="FLIPPED"),E=D.filter((p)=>p.status==="FAILED").length,C=T.length,b=B.length,x=C+b,g=x>0?C/x:0,i=b>0,c=i?"REGRESSIONS_DETECTED":"CLEAN",I0=!i&&E===0,k;try{let p=await oY(Q),$0=(Array.isArray(p.features)?p.features:[]).find((y)=>y?.code==="ai-approval");if(typeof $0?.balance==="number")k=$0.balance}catch{}return{ok:!i&&E===0,verdict:c,safeToPublish:I0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M,balanceAfter:k},metrics:{sampleCount:D.length,successCount:P.length,failureCount:E,matchCount:C,flipCount:b,concordanceRate:Number(g.toFixed(4))},flips:B,records:D}}function Kk0($){let{sourceCorp:Y,targetCorp:U,verdict:I,safeToPublish:Q,metrics:J,quota:K,flips:z,records:G}=$,H=I==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":I==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",W=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${Y.name}」->测试靶场「${U.name}」`,`判定:${H}·准许发布:${Q?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${J.sampleCount}|一致通过:${J.matchCount}|决策翻转:${J.flipCount}|异常失败:${J.failureCount}`,`一致率:${(J.concordanceRate*100).toFixed(1)}%|消耗预估:${K.estimatedRequired}点(余量:${K.balanceBefore}${K.balanceAfter!==void0?` -> ${K.balanceAfter}`:""})`," "+"─".repeat(65)];if(z.length>0){W.push(`⚠️决策翻转清单(${z.length}笔单据在新规则下结果改变):`);for(let X of z)if(W.push(`•单据[${X.sn}]:原生产判定「${X.prodDecision}」➔测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)W.push(`理由差异:${X.diff.reasonDiff}`);W.push(" "+"─".repeat(65)),W.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(I==="CLEAN")W.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100%
Line truncated
`)}var zk0=m(()=>{BP();H4();sZ()});async function Or($,Y,U){let I=($??Y??"regression").toLowerCase();if(I==="regression"||I==="regress"||I==="matrix"){let Q=h(U.options.corp)??(Y&&Y!==I?Y:void 0),J=M1(Q),K=J,z=J;if(J.environment==="test"){z=J;let O=h(U.options["prod-corp"])??h(U.options.prod)??J.prodCorpId;if(!O)throw new X4(`测试企业「${J.name}」(${J.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${J.id}`);K=M1(O)}else{K=J;let O=h(U.options["test-corp"])??h(U.options.test)??J.testCorpId;if(!O)throw new X4(`生产企业「${J.name}」(${J.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${J.id}<testCorpId>`);z=M1(O)}let G=await A1(K),H=await A1(z),W=s0(U.options.samples)??s0(U.options.limit)??s0(U.options.n)??10,X=G0(U.options["dry-run"]),Z=G0(U.options["fail-on-flips"]),q=s0(U.options["poll-interval"])??2000,V=s0(U.options.timeout)??45000,w=h(U.options["sn-prefix"])??"REG_",M=h(U.options.webhook)??h(U.options.selector),F=await Jk0({sourceCorp:K,targetCorp:z,sourceClient:G,targetClient:H,samples:W,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:w,failOnFlips:Z,webhookSelector:M});if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Kk0(F));if(R0(F),Z&&!F.ok)throw new X4(`回归测试发现${F.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new X4(`未知的test子命令:"${I}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}var Gk0=m(()=>{J$();O4();q4();l1();f6();zk0()});async function Hk0($,Y,U,I){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await x0($,Y,U,E8(I.json),E0(I.options))}var Wk0=m(()=>{O4();q4();l1()});function Xk0(){R0(vq.map(($)=>({name:$.name,description:$.description})))}var Zk0=m(()=>{Sq();l1()});function NE($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var qk0=m(()=>{lq()});import{existsSync as lx1,mkdirSync as ox1,readFileSync as rx1,renameSync as sx1,writeFileSync as ax1}from"node:fs";import{homedir as tx1}from"node:os";import{dirname as ex1,join as $f1}from"node:path";import{spawn as Yf1}from"node:child_process";function Vk0($){return $.replace(/\.\d+Z$/,"Z")}function Lk0(){let $=process.env[Uf1]?.trim();if($)return $;return Qf1}function Fk0($=Lk0()){if(!lx1($))return null;try{let Y=rx1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&typeof U.latestVersion==="string"&&typeof U.checkedAt==="string")return{...U,checkedAt:Vk0(U.checkedAt)};return null}catch{return null}}function aq($,Y=Lk0()){try{let U=ex1(Y);ox1(U,{recursive:!0,mode:448});let I={checkedAt:Vk0($.checkedAt??new Date().toISOString()),latestVersion:$.latestVersion,publishedAt:$.publishedAt,releaseUrl:$.releaseUrl},Q=`${Y}.tmp.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;ax1(Q,JSON.stringify(I,null,2),{mode:384}),sx1(Q,Y)}catch{}}function wk0($,Y=If1){if(!$||!$.checkedAt)return!0;let U=new Date($.checkedAt).getTime();if(Number.isNaN(U))return!0;return Date.now()-U>Y}function Mk0($){if(process.env.SEAL_DISABLE_BG_UPDATE==="1"||!1||process.env.CI)return!1;if(!$||!$.command)return!1;try{let Y=$.command,U=[...$.args??[],"update","check","--bg-save"];return Yf1(Y,U,{detached:!0,stdio:"ignore",env:{...process.env,SEAL_DISABLE_BG_UPDATE:"1"}}).unref(),!0}catch{return!1}}var Uf1="SEAL_USE_UPDATE_CACHE_FILE",If1=86400000,Qf1;var Nr=m(()=>{Qf1=$f1(tx1(),".config","seal-use","update-cache.json")});import{chmodSync as Jf1,mkdirSync as Kf1,readdirSync as zf1,realpathSync as Ok0,renameSync as Dr,rmSync as Gf1,unlinkSync as Pk0,writeFileSync as Nk0}from"node:fs";import{basename as Hf1,dirname as Wf1,isAbsolute as Xf1,join as AE,relative as Zf1}from"node:path";import{spawn as qf1,spawnSync as $7}from"node:child_process";async function Ek0($,Y={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Lr,version:X1,launcher:$.launcher},I=Y.repo||process.env[Vf1]?.trim()||process.env[Lf1]?.trim()||Tk0,Q=Y.targetVersion?.trim(),J=Q&&Q.toLowerCase()!=="latest"?Q:void 0;if(J){let D=J.replace(/^v/,""),P=_k0(D,X1);if(P<0)if(!wg&&Y.force);else{R0({updated:!1,currentVersion:X1,targetVersion:D,mode:NE()?"binary":"source",message:!wg?`Cannotdowngradeseal-usefromdevbuildv${X1}toreleasev${D}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${X1}toolderversionv${D}.Updatesmustbeforward-only.`});return}if(P===0&&!Y.force){R0({updated:!1,currentVersion:X1,targetVersion:D,mode:NE()?"binary":"source",message:`seal-useisalreadyatversionv${X1}.Use--forcetoreinstall.`});return}}if(Y.changelogOnly){let D=await BE(I,Y.limit??10);R0({currentVersion:X1,totalQueried:D.length,releases:D.map((P)=>({version:P.version,tagName:P.tagName,publishedAt:P.publishedAt,author:P.author,releaseNotes:P.notes,releaseUrl:P.htmlUrl,isCurrent:P.version===X1,isNewer:y5(P.version,X1)}))});return}if(!NE()){if(Y.checkOnly){let P=await BE(I,30),T=P[0],B=T?.version??X1,E=P.find((x)=>x.version===X1),C=y5(B,X1),b=P.filter((x)=>y5(x.version,X1));if(T?.version)aq({latestVersion:T.version,publishedAt:T.publishedAt,releaseUrl:T.htmlUrl});if(Y.bgSave)return;R0({updated:!1,updateAvailable:C,currentVersion:X1,currentVersionPublishedAt:E?.publishedAt,latestVersion:B,latestVersionPublishedAt:T?.publishedAt,behindCount:b.length,pendingReleases:b.map((x)=>({version:x.version,tagName:x.tagName,publishedAt:x.publishedAt,author:x.author,releaseNotes:x.notes,releaseUrl:x.htmlUrl})),releaseNotes:T?.notes??"",releaseUrl:T?.htmlUrl??"",mode:"source",message:"当前运行的是开发版。正式用户请安装正式版后使用 seal-use update。"});return}let D=nI(U).running;if(D)await e3("stop",U);try{Ak0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(P){console.error(`⚠️开发版更新同步失败,继续刷新本地依赖:${PinstanceofError?P.message:String(P)}`)}if(Ak0("bun",["install"],{cwd:$.appRoot}),D)await e3("start",U);R0({updated:!0,serviceRestarted:D,version:X1,mode:"source"});return}if(Nf1())try{await Df1($,Y,U,I,J);return}catch(D){console.error(`⚠️Homebrew自动更新失败,回退至原生二进制更新:${DinstanceofError?D.message:String(D)}`)}let K=wf1(),z=Mf1(),G=await BE(I,30),H=J?G.find((D)=>D.version
Line truncated
`)}catch{}}async function Pf1($,Y,U,I){let Q=Br(),J=[],K=U?U.startsWith("v")?U:`v${U}`:void 0,z=I||$.split("/").pop()||"";if(Q!=="github"){if(K&&z)J.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${K}/${z}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${K}/${z}`);if($.startsWith("https://git.ying-qing.cn"))J.push($)}if(Q!=="gitea")if(K&&z){let w=`https://github.com/${Tk0}/releases/download/${K}/${z}`;if(!process.env.CI)J.push(`https://ghfast.top/${w}`,`https://gh.ddlc.top/${w}`);J.push(w)}else if($.includes("github.com")){if(!process.env.CI)J.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);J.push($)}else J.push($);let G=Array.from(new Set(J)),H,W=6000,X=6000,Z=307200,q=1e4,V=180000;for(let w=0;w<G.length;w++){let M=G[w],F=new AbortController,N="",O=(B)=>{N=B;try{F.abort()}catch{}},D=setTimeout(()=>{O("Connection timed out (no response headers within 6s)")},W),P,T;try{DE(`==> [${w+1}/${G.length}] Downloading via: ${M}`);let B=await fetch(M,{signal:F.signal});if(D)clearTimeout(D),D=void 0;if(!B.ok)throw Error(`HTTP ${B.status} ${B.statusText}`);P=setTimeout(()=>{O("Overall download time exceeded 3 minutes")},V);let E=Number(B.headers.get("content-length"))||0,C=B.body?.getReader();if(!C){let c=Buffer.from(await B.arrayBuffer());if(c.length<1000)throw Error(`Downloaded content is suspiciously small (${c.length} bytes)`);Nk0(Y,c),DE(`✓ Download succeeded (${(c.length/1024/1024).toFixed(1)} MB)`);return}let b=[],x=0,g=0;T=setTimeout(()=>{if(x<Z){let c=(x/1024).toFixed(1);O(`Initial transfer too slow (${c} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let c=C.read(),I0,k=new Promise((y,d)=>{I0=setTimeout(()=>{d(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),p;try{p=await Promise.race([c,k])}finally{if(I0)clearTimeout(I0)}let{done:a,value:$0}=p;if(a)break;if($0){if(b.push($0),x+=$0.length,T&&x>=Z)clearTimeout(T),T=void 0;let y=Date.now();if(y-g>200){g=y;let d=E?Math.round(x/E*100):0,Y0=(x/1048576).toFixed(1),R=E?(E/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${d}% (${Y0} / ${R} MB)...`)}catch{}}}}try{process.stderr.write(`
thrownewError("Auto-login (--auto-login) is only supported for Seal AI audit links (type: seal-result). To generate an auto-login link for Hose document page, please use: seal-use auth hose-link");
}
if(source.type!=="hose"){
thrownewError(
`Auto-login direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use auth link' for authorized access.`
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.