| `10` | **Confirmation Required** | Mutating command invoked without `--confirm` or `--yes` |
| `11` | **Authentication Missing / Invalid** | Upstream HTTP 401/403, or an expired/missing/invalid `token`/`bearer`/`session` (classified in `classifyCliError`) |
| `12` | **Output Protection** | Response exceeds the size limit (`PayloadTooLargeError` from `printer.ts`); use `--summary`/`--fields`/`--count`/`--output-file`, or `--full` when the full payload is genuinely required |
**Rule**: Never call `process.exit()` deep in domain functions. Throw structured errors and let `src/cli/runner.ts` handle error classification, stream routing, and exit code assignment.
@@ -42,6 +42,8 @@ Prefer small domain functions over broad utility modules.
-`1`: Upstream API failure or domain business block.
-`2`: Parameter validation failure, unknown subcommand, or invalid JSON.
-`10`: Safety gate block requiring user confirmation (`--confirm` / `--yes`).
-`11`: Missing or invalid authentication (HTTP 401/403, or an expired/missing/invalid `token`/`bearer`/`session`).
-`12`: Output protection — response exceeds the size limit; use `--summary`/`--fields`/`--count`/`--output-file` (or `--full` when the full payload is genuinely required).
- Never call `process.exit()` deep in domain functions; throw structured errors and let `src/cli/runner.ts` handle stream routing and exit code assignment.
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
import{createRequireasVx0}from"node:module";varJx0=Object.create;var{getPrototypeOf:Kx0,defineProperty:EE,getOwnPropertyNames:zx0}=Object;varGx0=Object.prototype.hasOwnProperty;functionHx0($){returnthis[$]}varWx0,Xx0,K6=($,Y,U)=>{varI=$!=null&&typeof$==="object";if(I){varQ=Y?Wx0??=newWeakMap:Xx0??=newWeakMap,J=Q.get($);if(J)returnJ}U=$!=null?Jx0(Kx0($)):{};letK=Y||!$||!$.__esModule?EE(U,"default",{value:$,enumerable:!0}):U;for(letzofzx0($))if(!Gx0.call(K,z))EE(K,z,{get:Hx0.bind($,z),enumerable:!0});if(I)Q.set($,K);returnK};varj=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);varZx0=($)=>$;functionqx0($,Y){this[$]=Zx0.bind(null,Y)}varZ8=($,Y)=>{for(varUinY)EE($,U,{get:Y[U],enumerable:!0,configurable:!0,set:qx0.bind(Y,U)})};varm=($,Y)=>()=>($&&(Y=$($=0)),Y);varK0=Vx0(import.meta.url);varLx0,zV,Fx0,wx0,Mx0,Ox0,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},Nx0=($,Y,U,I)=>{if(Y&&typeofY==="object"||typeofY==="function"){for(varQ=wx0(Y),J=0,K=Q.length,z;J<K;J++)if(z=Q[J],!Ox0.call($,z)&&z!==U)zV($,z,{get:((G)=>Y[G]).bind(null,z),enumerable:!(I=Fx0(Y,z))||I.enumerable})}return$},GV=($,Y,U)=>(U=$!=null?Lx0(Mx0($)):{},Nx0(Y||!$||!$.__esModule?zV(U,"default",{value:$,enumerable:!0}):U,$));varjE=m(()=>{Lx0=Object.create,zV=Object.defineProperty,Fx0=Object.getOwnPropertyDescriptor,wx0=Object.getOwnPropertyNames,Mx0=Object.getPrototypeOf,Ox0=Object.prototype.hasOwnProperty});functionxr($){returntypeof$==="string"&&kr.has($.replace(/#$/,""))}functionfr($,Y){if(!("$schema"in$)||typeof$.$schema!=="string")return"2020-12";letU=$.$schema.replace(/#$/,"");if(Dx0.has(U))return"2020-12";if(kr.has(U))return"2019-09";if(Bx0.has(U)||Ax0.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}`)}varDx0,kr,Bx0,Ax0;varCE=m(()=>{Dx0=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"]),Bx0=newSet(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Ax0=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:()=>ox0,uint8ArrayToBase64url:()=>mx0,uint8ArrayToBase64:()=>cr,stringifyPrimitive:()=>_0,slugify:()=>SE,shallowClone:()=>gE,safeExtend:()=>bx0,required:()=>nx0,randomString:()=>hx0,propertyKeyTypes:()=>QG,promiseAllObject:()=>Sx0,primitiveTypes:()=>yE,prefixIssues:()=>n8,pick:()=>xx0,partial:()=>cx0,parsedType:()=>h0,optionalKeys:()=>kE,omit:()=>fx0,objectClone:()=>Rx0,numKeys:()=>gx0,nullish:()=>q7,normalizeParams:()=>f0,mergeDefs:()=>r9,merge:()=>ix0,jsonStringifyReplacer:()=>lI,joinValues:()=>M0,issue:()=>rI,isPlainObject:()=>L7,isObject:()=>RY,hexToUint8Array:()=>lx0,getSizableOrigin:()=>JG,getParsedType:()=>yx0,getLengthableOrigin:()=>KG,getEnumValues:()=>UG,getElementAtPath:()=>vx0,floatSafeRemainder:()=>vE,finalizeIssue:()=>R8,extend:()=>ux0,explicitlyAborted:()=>uE,escapeRegex:()=>R$,esc:()=>HV,defineLazy:()=>j1,createTransparentProxy:()=>kx0,cloneDef:()=>_x0,clone:()=>C8,cleanRegex:()=>IG,cleanEnum:()=>dx0,captureStackTrace:()=>WV,cached:()=>oI,base64urlToUint8Array:()=>px0,base64ToUint8Array:()=>ir,assignProp:()=>V7,assertNotEqual:()=>Tx0,assertNever:()=>jx0,assertIs:()=>Ex0,assertEqual:()=>Px0,assert:()=>Cx0,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)},sx0,VV=($)=>(Y,U,I)=>{return sI($)(Y,U,I)},ax0,LV=($)=>async(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return aI($)(Y,U,Q)},tx0,FV=($)=>async(Y,U,I)=>{return aI($)(Y,U,I)},ex0,wV=($)=>(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return tI($)(Y,U,Q)},$f0,MV=($)=>(Y,U,I)=>{return tI($)(Y,U,I)},Yf0,OV=($)=>async(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return eI($)(Y,U,Q)},Uf0,NV=($)=>async(Y,U,I)=>{return eI($)(Y,U,I)},If0;var pE=m(()=>{CY();cE();$1();XV=sI(d8),ZV=aI(d8),nE=tI(d8),dE=eI(d8),sx0=qV(d8),ax0=VV(d8),tx0=LV(d8),ex0=FV(d8),$f0=wV(d8),Yf0=MV(d8),Uf0=OV(d8),If0=NV(d8)});var G$={};Z8(G$,{xid:()=>rE,uuid7:()=>zf0,uuid6:()=>Kf0,uuid4:()=>Jf0,uuid:()=>_Y,uppercase:()=>Nj,unicodeEmail:()=>mr,undefined:()=>Mj,ulid:()=>oE,time:()=>Xj,string:()=>qj,sha512_hex:()=>Cf0,sha512_base64url:()=>_f0,sha512_base64:()=>Rf0,sha384_hex:()=>Tf0,sha384_base64url:()=>jf0,sha384_base64:()=>Ef0,sha256_hex:()=>Bf0,sha256_base64url:()=>Pf0,sha256_base64:()=>Af0,sha1_hex:()=>Of0,sha1_base64url:()=>Df0,sha1_base64:()=>Nf0,rfc5322Email:()=>Hf0,number:()=>WG,null:()=>wj,nanoid:()=>aE,md5_hex:()=>Ff0,md5_base64url:()=>Mf0,md5_base64:()=>wf0,mac:()=>Qj,lowercase:()=>Oj,ksuid:()=>sE,ipv6:()=>Ij,ipv4:()=>Uj,integer:()=>Lj,idnEmail:()=>Wf0,httpProtocol:()=>Gj,html5Email:()=>Gf0,hostname:()=>qf0,hex:()=>Lf0,guid:()=>eE,extendedDuration:()=>Qf0,emoji:()=>Yj,email:()=>$j,e164:()=>Hj,duration:()=>tE,domain:()=>Vf0,datetime:()=>Zj,date:()=>Wj,cuid2:()=>lE,cuid:()=>mE,cidrv6:()=>Kj,cidrv4:()=>Jj,browserEmail:()=>Xf0,boolean:()=>Fj,bigint:()=>Vj,base64url:()=>DV,base64:()=>zj});function Yj(){return new RegExp(Zf0,"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,Qf0,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})$`)},Jf0,Kf0,zf0,$j,Gf0,Hf0,mr,Wf0,Xf0,Zf0="^(\\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,qf0,Vf0,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,Lf0,Ff0,wf0,Mf0,Of0,Nf0,Df0,Bf0,Af0,Pf0,Tf0,Ef0,jf0,Cf0,Rf0,_f0;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
if(${D}.issues.length){
@@ -60,66 +60,66 @@ import{createRequire as Zx0}from"node:module";var Ix0=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)},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
`)}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(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
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,$)}vartu0,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=tu0[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 Si0($){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(!vi0.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 hi0($,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=Si0($);return hi0($,Y.warnings),Y.isValid}function gi0($){return typeof $==="object"&&$!==null&&"_zod"in $}function yi0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function ki0($){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)=>gi0(U))}function ow($){if($===void 0)return;if(ki0($))return U0($);if(typeof $==="object"&&$!==null&&!fQ($)&&Object.values($).some((Y)=>yi0(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,Vb0,T1,L1,Lb0,He="2026-07-28",g7,Ze,Mb0,Ob0,Nb0,Le,Fe,Bb0,Sw,si1,ai1,at,Mh,Cb0,Rb0,kQ,i0,Q1,iw,Oe,bQ,cw,Sb0=0,hb0="private",gb0,cb0,gw,Bh,Be,ti1,ei1,ob0,rb0,Ah,yw,OH="2026-07-28",Te,tb0,_$=($)=>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",eb0,$i0,Yi0,Ui0,fw=-32020,$c1,Ii0,Ie=!1,Zh="draft-2020-12",Ki0,Xi0,Zi0,Qe,qi0,Oi0,Ce=250,Ni0,Di0,Se,he,Bi0,Ai0,ye=60000,Ti0,Ei0,ji0,ke,Sh,_i0,Yc1,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}},vi0;var rw=m(()=>{jE();CE();ot();RS();Wh=Symbol.for("mcp.sdk.errorBrands");Vb0=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)}},Lb0=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"];Ob0=new Set(["const","enum","default","examples"]),Nb0=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},Bb0={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};si1=Object.keys(Le),ai1=Object.keys(Fe);at={ok:!1,reason:"not-in-era"};Mh={era:"2025-11-25",hasRequestMethod:we,hasNotificationMethod:Me,validateRequest:($,Y)=>hw(Tb0($),Y),validateResult:($,Y)=>hw(Pb0($),Y),validateNotification:($,Y)=>hw(Eb0($),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
*/Ci0=j0(($)=>{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,I=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;$.parse=Q;function Q(z){if(!z)throw TypeError("argument string is required");var G=typeof z==="object"?J(z):z;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(!I.test(W))throw TypeError("invalid media type");var X=new K(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 J(z){var G;if(typeof z.getHeader==="function")G=z.getHeader("content-type");else if(typeof z.headers==="object")G=z.headers&&z.headers["content-type"];if(typeof G!=="string")throw TypeError("content-type header is missing from object");return G}function K(z){this.parameters=Object.create(null),this.type=z}}),ti1=GV(Ci0(),1);Ri0=/^[A-Za-z0-9._-]{1,128}$/});function xh($){let Y=new $({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return sc0(Y),Y}var sw,ue,F1,v1,X5,tw,yi0,be,ie,aw,ki0,Z5,xi0,fi0,ce,ui0,ew,iQ,DH,cQ,$M,bi0,ne,ii0,ci0,ni0,fh,di0,uh,de,pi0,mi0,li0,oi0,ri0,si0,ai0,ti0,bh,ei0,$c0,Yc0,pe,me,le,Uc0,Ic0,Qc0,ih,Jc0,oe,Kc0,zc0,Gc0,Hc0,Wc0,Xc0,Zc0,qc0,re,Vc0,se,ae,te,Lc0,ch,Fc0,ee,$00,Y00,wc0,Mc0,U00,Oc0,Nc0,Dc0,I00,Bc0,Ac0,Q00,Pc0,Tc0,Ec0,jc0,Cc0,Rc0,_c0,vc0,Sc0,hc0,gc0,yc0,kc0,xc0,fc0,uc0,bc0,ic0,cc0,nc0,dc0,pc0,mc0,J00,lc0,oc0,rc0,sc0,YM=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor($){this._userAjv=$!==void 0,this._ajv=$}get ajv(){return this._ajv??=xh(oc0.Ajv2020)}_engineFor($){if(this._userAjv)return this.ajv;let Y=fr($,"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??=xh(lc0.Ajv2019);return this._ajvDraft7??=xh(J00.Ajv)}getValidator($){let Y=this._engineFor($),U="$id"in $&&typeof $.$id==="string"?Y.getSchema($.$id)??Y.compile($):Y.compile($);return(I)=>{return U(I)?{valid:!0,data:I,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:Y.errorsText(U.errors)}}}},Wc1;var K00=m(()=>{jE();CE();sw=j0(($)=>{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 I=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=I,$.nil=new I("");function Q(F,...N){let O=[F[0]],D=0;while(D<N.length)z(O,N[D]),O.push(F[++D]);return new I(O)}$._=Q;let J=new I("+");function K(F,...N){let O=[q(F[0])],D=0;while(D<N.length)O.push(J),z(O,N[D]),O.push(J,q(F[++D]));return G(O),new I(O)}$.str=K;function z(F,N){if(N instanceof I)F.push(...N._items);else if(N instanceof U)F.push(N);else F.push(X(N))}$.addCodeArg=z;function G(F){let N=1;while(N<F.length-1){if(F[N]===J){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:K`${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 I(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 I(`.${F}`):Q`[${F}]`}$.getProperty=V;function w(F){if(typeof F=="string"&&$.IDENTIFIER.test(F))returnnewI(`${F}`);throwError(`CodeGen: invalid export name: ${F}, use explicit $id name mapping`)}$.getEsmExportName=w;functionM(F){returnnewI(F.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=`
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}),zc0=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}),Gc0=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}),Hc0=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((V01)=>{var S70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function q01($){if(typeof $==="string")return $;if(S70)return S70.decode($);return $.toString()}V01.bufferToString=q01});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
`,$=this.i;break;case g11:{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=R11,this.unget(),this.xmlDeclPossible=!1;else switch($){case LN:this.state=S11,this.xmlDeclPossible=!1;break;case K20:this.state=O11,this.openWakaBang="",this.xmlDeclPossible=!1;break;case t6:this.state=P11;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=N11}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===VN)this.state=D11,($=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=B11}sCDataEnding(){let $=this.getCodeNorm();if($===hJ)this.state=A11;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=T11,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(x11);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:E11}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=j11}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 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
`);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 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 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
`)}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 _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 iA1($,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=iA1($,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:bA1(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)}
...[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,fA1;var lA0=m(()=>{dA0=["id","ruleId","stableId"],fA1=new Set([...dA0,"runtimeRuleId","runtimeId","tenantId","createdAt","updatedAt","versionId","versionNumber"])});import{existsSync as cA1,mkdirSync as nA1,readFileSync as dA1,renameSync as pA1,writeFileSync as mA1}from"node:fs";import{homedir as lA1}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(lA1(),".config","seal-use","rule-version-snapshots")}function oA1($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function sA0($,Y){return oA0(rA0(),`${oA1($)}-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();nA1(z,{recursive:!0,mode:448});let G=sA0($,Y.versionNumber),H=`${G}.${process.pid}.tmp`;return mA1(H,`${JSON.stringify(K,null,2)}
@@ -881,44 +881,44 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
}
exportdefaultlintRule;
`}});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
`}});import{homedir as WP1}from"node:os";import{join as Ip}from"node:path";var XP1,B$,A$;var Qp=m(()=>{XP1=Ip(WP1(),".config","seal-use"),B$=Ip(XP1,"linters"),A$=Ip(B$,"official")});import{existsSync as MI,mkdirSync as ZP1,readFileSync as qP1,readdirSync as IP0,rmSync as VP1,unlinkSync as LP1,writeFileSync as FP1}from"node:fs";import{isAbsolute as wP1,join as B8,resolve as MP1}from"node:path";import{pathToFileURL as YP0}from"node:url";function QP0($=A$){let Y=[],U=[];try{if(!MI($))ZP1($,{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(qP1(z,"utf8")===K)G=!1}catch{G=!0}if(G)FP1(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())VP1(K,{recursive:!0,force:!0});else LP1(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 OP1($){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(wP1(Y)||Y.startsWith("./")||Y.startsWith("../")){let I=MP1(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=OP1($??"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 W$4,X$4,EP1,Z$4,jP1,q$4,V$4,qP0,L$4,F$4,VP0,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,b$4,i$4,c$4,Hp,CP1,RP1,LP0,_P1,n$4,d$4,p$4,m$4,l$4,o$4,FP0,r$4,s$4,vP1,wP0,a$4,t$4,e$4,$54,Y54,U54,I54,Q54,J54,K54,z54,G54,H54,W54,X54,Z54,q54,V54,MP0;var OP0=m(()=>{z6();H4();l$();bA0();lA0();ad();zp();ZP0();o$();({presentWebhookIntegration:W$4,getConfiguredSealBaseUrl:X$4,projectApprovalRules:EP1,pickRuleFields:Z$4,buildRulePushPlan:jP1,rulesHaveSameContent:q$4,ruleChangedFields:V$4,normalizeRuleStrictness:qP0,parseDurationMs:L$4,redactIntegrationSecrets:F$4,mutationPreview:VP0,redactPreviewValue:w$4,buildSimulationBatchParams:M$4,summarizeSimulationBatch:O$4,summarizeApprovalRun:N$4,summarizeApprovalRuns:D$4,parseFieldPaths:B$4,pickRunFields:A$4,approvalRunMetadata:P$4,summarizeApprovalRunDetail:T$4,summarizeApprovalRunResult:E$4,summarizeApprovalRunDocument:j$4,extractCitedRules:C$4,firstPath:R$4,countPathCandidates:_$4,getPath:v$4,setPath:S$4,compactObject:h$4,asRecord:g$4,numberFromUnknown:y$4,flattenDocumentFields:k$4,collectDocumentFields:x$4,firstByLabel:f$4,collectInvoiceSummary:u$4,collectInvoiceObjects:b$4,findKeywordLines:i$4,summarizeRunBridge:c$4,summarizeRuleVersion:Hp,resolveRuleVersionForLookup:CP1,findRuleInVersion:RP1,normalizeRuleCode:LP0,runtimeRuleIndex:_P1,runtimeRuleIdToCode:n$4,formatRuleCode:d$4,pickApprovalRunCandidate:p$4,resolveApprovalRunForUrl:m$4,resolveSealBaseUrl:l$4,normalizeUrl:o$4,stringFromUnknown:FP0,pickApprovalRuns:r$4,timestampOf:s$4,resolveRuleVersion:vP1,resolveRuleVersionSelector:wP0,filterRuns:a$4,scalarIncludes:t$4,objectContainsScalar:e$4,filterRunsByHumanResult:$54,withApprovalRunFilters:Y54,resolveManualApprovalStatus:U54,prepareApprovalRuns:I54,approvalRunAliases:Q54,extractHumanResult:J54,findHumanResultValue:K54,isHumanResultKey:z54,stringifyHumanResultValue:G54,matchesRunLookup:H54,countBy:W54,localDateKey:X54,formatLocalDateTime:Z54,toDate:q54,localParts:V54}=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 EP1(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
`),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}
`),await new Promise((F,N)=>{let O=Ky1(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=Gy1(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 qy1}from"node:fs";function Vy1($){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 Ly1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function Fy1($,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(Ly1($,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);Fy1(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}=Vy1(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?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(`
`+"• 安全边界:该凭证绝不包含且无法访问合思 (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"?Cy1(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 _y1($,{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)=>Ty1(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)=>yy1(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 ty1($){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
`)}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){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
`;if(Y.outputFile){ey1(Y.outputFile,U),console.log(JSON.stringify({outputFile:Y.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function Ik1($,Y={}){if(Y.allowFull||Y.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>Uk1)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>$k1||J>Yk1)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 $k1=100,Yk1=120000,pv0,Uk1=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 Hk1($){return{headers:jd.parse($.headers),cookies:Cd.parse($.cookies)}}async function Wk1($,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=Hk1($),J=I?await Wk1(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: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${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
`);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 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
`;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
`;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
A**Webhookresourcepack**(webhook资源包/资源包,CLI:\`resource-pack\`, alias: \`pack\`, legacy alias: \`material-pack\`) is a ZIP file that bundles an Excel information sheet (\`信息表.xlsx\`) with attachments organised by document ID. It is designed for exporting online approval runs and transferring them offline across environments or teams to be replayed via inbound Webhooks.
>**Note**:ThisisdistinctfromSealbackend'snativesimulation"材料包"(\`simulation material_pack\` / \`/api/v1/material-packages/upload\`). Calling this standard "Webhook 资源包" avoids confusion.
-Therootdirectoryname**mustequal**the\`documentId\` **OR** start with \`documentId@\` (the \`@\` separates an optional annotation ignored during matching).
-\`信息表.xlsx\` at the ZIP root is the only file not associated with any document directory.
|费用明细表(has\`报销金额\` column) | Per-row entries in \`mingxi_list\` |
|劳务明细(has\`姓名\` column) | Per-person entries in \`daoshi_list\` |
###Strictbidirectionalvalidation
Beforepushingorpreviewing,thesystemenforces:
1.**Excel→ZIP**:Everypathdeclaredinan\`[附件]\` column cell **must** exist as a ZIP entry. Error: \`Excel 声明的附件路径在 ZIP 中不存在: <path>\`
2.**ZIP→Excel**:EveryZIPfile(excluding\`信息表.xlsx\`) **must** be declared in exactly one \`[附件]\` column. Error: \`ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>\`
3.**DocumentDirectoryScopeIsolation**:Allattachmentsdeclaredforadocument\`DOC_X\` **must** reside in its own root directory (\`DOC_X/\` or \`DOC_X@annotation/\`). Cross-document references are strictly forbidden. Error: \`单据「X」声明了跨单据或非本单据目录的附件路径: <path>。附件必须位于该单据自己的根目录...\`
4.**StrictDeclarationUniqueness**:AgivenZIPfilepath**cannot**bedeclaredmorethanonceacrosstheentireresourcepack(evenwithinthesamedocumentacrossmultiplerowsorfields).Ifthesamelogicaldocumentisneededinmultipleplaces,separatefilesmustbeplacedindistinctpaths.Error:\`附件路径「<path>」被重复声明了 N 次...\`
5.**Attachmentfilepolicy**:Everyattachmentexcepttheroot\`信息表.xlsx\` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: \`附件文件过小...\` / \`附件文件过大...\` / \`附件后缀不在白名单中...\`
6.**documentId↔ZIProot**:Every\`documentId\` in the Excel main sheet that declares attachments must have a matching ZIP root dir (exact match or \`documentId@annotation\`), and every ZIP root dir must match a declared \`documentId\`. Errors: \`Excel 会议编号「X」在 ZIP 中找不到对应的根目录...\` / \`ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号\`
\`null\` or an omitted \`maxFileSizeBytes\` means no per-file upper bound. Values are bytes; a file smaller than the minimum or larger than the maximum fails. Extensions are normalized case-insensitively and may be written with or without the leading dot. The root \`信息表.xlsx\` remains exempt from attachment policy checks.
Thesavedconfigurationisreturnedby\`webhook get\`/\`webhook list\` under \`materialPackFilePolicy\`. The root \`信息表.xlsx\` is always allowed as the material-pack manifest and is not subject to the attachment policy.
3.Ifconfigurationchangeisauthorized,readthecurrentpolicywith\`webhook get\`/\`webhook list\`, update only the necessary fields, and verify the returned configuration.
4.Retrytheoriginal\`material-pack push\`; it will load the latest saved policy before any upload begins.
Thesameloopisavailablethroughtheinternaltoolregistry:readwith\`seal-use tool seal_webhook_get\`/\`seal_webhook_list\`, update with \`seal-use tool seal_webhook_update\` and its \`materialPackFilePolicy\` patch, then retry \`seal-use tool seal_webhook_material_pack\` in \`push\` mode. Over MCP these run through \`seal_cli\` (reads) or \`seal_cli_write\` (the update and push, which need user confirmation); no separate \`seal_webhook_*\` MCP tool exists. Set \`maxFileSizeBytes\` to \`null\` to clear the upper bound. \`allowedExtensions\` is a complete replacement list, so include existing allowed suffixes when adding one.
Thedirectlocal\`material-pack preview\` command and the tool-registry preview use the default or temporary policy. They do not automatically read a selected Webhook's persisted policy. Use \`webhook ready --file --webhook <idOrName>\` or the actual push path when validating against the saved inbound policy.
###Errormessagesreference
|Errormessage|Meaning|Fix|
|---|---|---|
|\`Excel 声明的附件路径在 ZIP 中不存在: <path>\` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |
|\`ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>\` | ZIP contains a file not referenced by any \`[附件]\` column | Add an \`[附件]\` column entry or remove the file from ZIP |
|\`单据「X」声明了跨单据或非本单据目录的附件路径: <path>\` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |
|\`附件路径「<path>」被重复声明了 N 次\` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |
|\`Excel 会议编号「X」在 ZIP 中找不到对应的根目录\` | No ZIP root dir matches documentId \`X\` | Rename the ZIP folder to match the documentId |
|\`ZIP 根目录对应的编号「X」在信息表中找不到\` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |
|\`ZIP 根目录缺少信息表.xlsx\` | No \`信息表.xlsx\` found at ZIP root | Add the Excel file to the ZIP root |
|\`附件文件过小\` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower \`--min-file-size\` |
|\`附件文件过大\` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise \`--max-file-size\` |
|\`附件后缀不在白名单中\` | Attachment extension is not allowed by the Webhook policy | Add the extension with \`--allowed-extensions\` or convert the file |
|\`附件上传失败 <status>\` | Network/server error during file upload | Check webhook URL, secret, and server availability |
`;var ng0=()=>{};var Xx1="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系统架构与运行规范白皮书
`,"utf8"),{detected:I,configured:!0,configPath:U,targetDir:Y,action:"prepended"}}function lo($){let Y=$?.targetSkillsDir??og0(),U=$?.configFile??rg0(),I=sg0(),Q=!1;if(dq(U))try{let J=JSON.parse(lg0(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 Ox1,existsSync as mz,lstatSync as tg0,mkdirSync as Nx1,realpathSync as YY,rmSync as Dx1,symlinkSync as Bx1,unlinkSync as ag0}from"node:fs";import{homedir as eg0}from"node:os";import{dirname as $y0,join as UY}from"node:path";function Ax1($,Y){let U=Y?.baseHomeDir??eg0(),I=UY(U,$.rootDirName),Q=Y?.sourceSkillDir??UY(U,".agents","skills","seal-use"),J=$y0(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{}Nx1(K,{recursive:!0});let G;try{G=tg0(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{ag0(z)}catch{}}else if(G.isDirectory())Dx1(z,{recursive:!0,force:!0}),H=!0;else ag0(z);let W=process.platform==="win32"?"junction":"dir";try{return Bx1(Q,z,W),{id:$.id,name:$.name,detected:!0,configured:!0,mode:H?"replaced_real_dir":"linked",targetPath:z}}catch{try{return Ox1(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 Px1($,Y){let U=Y?.baseHomeDir??eg0(),I=UY(U,$.rootDirName),Q=Y?.sourceSkillDir??UY(U,".agents","skills","seal-use"),J=$y0(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=tg0(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 Yy0.map((Y)=>Ax1(Y,$))}function so($){return Yy0.map((Y)=>Px1(Y,$))}var Yy0;var ao=m(()=>{Yy0=[{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 Tx1,mkdirSync as eo,readFileSync as Ex1,rmSync as jx1,writeFileSync as Uy0}from"node:fs";import{homedir as Qy0}from"node:os";import{dirname as Iy0,join as mq}from"node:path";function $r(){return Jy0["SKILL.md"]||""}function Ky0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function zy0($=mq(cI(),"SKILL.md")){try{return Ky0(Ex1($,"utf8"))}catch{return}}function cI(){return mq(Qy0(),".agents","skills","seal-use")}function Rx1(){return mq(Qy0(),".agents","skills","seal-home")}function _x1(){let $=Rx1();if(Tx1($))try{return jx1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Gy0($=cI()){_x1(),eo($,{recursive:!0});let Y=[];for(let[U,I]of Object.entries(Jy0)){let Q=mq($,U);eo(Iy0(Q),{recursive:!0}),Uy0(Q,I,"utf8"),Y.push(U)}for(let[U,I]of Object.entries(Cx1)){let Q=mq($,U);eo(Iy0(Q),{recursive:!0}),Uy0(Q,I),Y.push(U)}return{targetDir:$,files:Y}}var Jy0,Cx1,cZ4;var lq=m(()=>{co();co();to();Jy0=pg0,Cx1=Object.fromEntries(Object.entries(mg0).map(([$,Y])=>[$,Buffer.from(Y,"base64")]));cZ4=Ky0($r())});function Hy0(){return`#SealUse系统架构与运行规范白皮书
`)}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
`)}var wy0=m(()=>{H4()});var My0={};Z8(My0,{formatTenantDoctorDashboard:()=>Fy0,diagnoseTenantContract:()=>Ly0});var Oy0=m(()=>{wy0()});async function Ny0($,Y,U){let I=($??Y??"").toLowerCase();if(I==="guide"||I==="doc"||I==="knowledge"||I==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(Hy0());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(() => (Oy0(),My0)),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(qy0(Q));R0(Q)}var Dy0=m(()=>{Vy0();Qr();q4();l1()});var Ay0;var By0=m(()=>{Ay0={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
`);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}」,非测试环境!
`);Q(I)})})}var ZE=8787,qE="127.0.0.1";var Gr=m(()=>{Cy0();J3()});async function Ry0($){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 _y0=m(()=>{q4();Gr()});async function vy0($,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 Sy0=m(()=>{O4();l1()});async function hy0($,Y){if($==="config"||$==="json"){Hr();return}let{startServer:U}=await ky0().then(() => yy0);U()}function Hr(){R0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var gy0=m(()=>{l1()});function xy0($){let Y=HE();R0(Y,{...E0($.options),allowFull:!0})}var fy0=m(()=>{Kr();l1()});async function uy0($,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 by0=m(()=>{O4();l1()});import{readFileSync as iy0}from"node:fs";async function cy0($,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(iy0(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(iy0(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 ny0=m(()=>{O4();q4();l1()});async function dy0($={}){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 py0=m(()=>{l$();f6();pT();H4()});async function my0($,Y,U){let I=Y??h(U.options.corp)??($&&$!=="--corp"?$:void 0);await dy0({corpId:I})}var ly0=m(()=>{py0();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 px1($){let Y=ME($),U=qr($),I=sq($);ty0($.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 ry0($){ty0($.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=ix1(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 lx1}from"node:os";import{join as ox1}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=ox1(lx1(),".config","seal-use")});import{existsSync as rx1,readFileSync as ey0}from"node:fs";async function $k0($,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(ey0(z,"utf8")):void 0,H=h(Q.options.input),W=H?JSON.parse(ey0(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(!rx1(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=Gy0(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:Uk0(OE(I,"SKILL.md"))},local:{dir:Q,installed:Uk0(OE(Q,"SKILL.md"))},antigravity:J,hosts:K});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}var Qk0=m(()=>{to();lq();q4();l1()});async function Jk0($,Y){if($==="config"){R0(await nz(Y));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var Kk0=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 zk0($){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})未绑定生产母企业,无法拉取历史样本。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",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 Gk0($){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 Hk0=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(`
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(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 zk0({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(Gk0(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 Wk0=m(()=>{J$();O4();q4();l1();f6();Hk0()});async function Xk0($,Y,U,I){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await x0($,Y,U,E8(I.json),E0(I.options))}var Zk0=m(()=>{O4();q4();l1()});function qk0(){R0(vq.map(($)=>({name:$.name,description:$.description})))}var Vk0=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 Lk0=m(()=>{lq()});import{existsSync as sx1,mkdirSync as ax1,readFileSync as tx1,renameSync as ex1,writeFileSync as $f1}from"node:fs";import{homedir as Yf1}from"node:os";import{dirname as Uf1,join as If1}from"node:path";import{spawn as Qf1}from"node:child_process";function Fk0($){return $.replace(/\.\d+Z$/,"Z")}function wk0(){let $=process.env[Jf1]?.trim();if($)return $;return zf1}function Mk0($=wk0()){if(!sx1($))return null;try{let Y=tx1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&typeof U.latestVersion==="string"&&typeof U.checkedAt==="string")return{...U,checkedAt:Fk0(U.checkedAt)};return null}catch{return null}}function aq($,Y=wk0()){try{let U=Uf1(Y);ax1(U,{recursive:!0,mode:448});let I={checkedAt:Fk0($.checkedAt??new Date().toISOString()),latestVersion:$.latestVersion,publishedAt:$.publishedAt,releaseUrl:$.releaseUrl},Q=`${Y}.tmp.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;$f1(Q,JSON.stringify(I,null,2),{mode:384}),ex1(Q,Y)}catch{}}function Ok0($,Y=Kf1){if(!$||!$.checkedAt)return!0;let U=new Date($.checkedAt).getTime();if(Number.isNaN(U))return!0;return Date.now()-U>Y}function Nk0($){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 Qf1(Y,U,{detached:!0,stdio:"ignore",env:{...process.env,SEAL_DISABLE_BG_UPDATE:"1"}}).unref(),!0}catch{return!1}}var Jf1="SEAL_USE_UPDATE_CACHE_FILE",Kf1=86400000,zf1;var Nr=m(()=>{zf1=If1(Yf1(),".config","seal-use","update-cache.json")});import{chmodSync as Gf1,mkdirSync as Hf1,readdirSync as Wf1,realpathSync as Dk0,renameSync as Dr,rmSync as Xf1,unlinkSync as Ek0,writeFileSync as Bk0}from"node:fs";import{basename as Zf1,dirname as qf1,isAbsolute as Vf1,join as AE,relative as Lf1}from"node:path";import{spawn as Ff1,spawnSync as $7}from"node:child_process";async function Ck0($,Y={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Lr,version:X1,launcher:$.launcher},I=Y.repo||process.env[wf1]?.trim()||process.env[Mf1]?.trim()||jk0,Q=Y.targetVersion?.trim(),J=Q&&Q.toLowerCase()!=="latest"?Q:void 0;if(J){let D=J.replace(/^v/,""),P=Sk0(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{Tk0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(P){console.error(`⚠️开发版更新同步失败,继续刷新本地依赖:${PinstanceofError?P.message:String(P)}`)}if(Tk0("bun",["install"],{cwd:$.appRoot}),D)await e3("start",U);R0({updated:!0,serviceRestarted:D,version:X1,mode:"source"});return}if(Af1())try{await Pf1($,Y,U,I,J);return}catch(D){console.error(`⚠️Homebrew自动更新失败,回退至原生二进制更新:${DinstanceofError?D.message:String(D)}`)}let K=Nf1(),z=Df1(),G=await BE(I,30),H=J?G.find((D)=>D.version
Line truncated
`)}catch{}}async function jf1($,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/${jk0}/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)`);Bk0(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(`
A **Webhook resource pack** (webhook 资源包 / 资源包, CLI: `resource-pack`, alias: `pack`, legacy alias: `material-pack`) is a ZIP file that bundles an Excel information sheet (`信息表.xlsx`) with attachments organised by document ID. It is designed for exporting online approval runs and transferring them offline across environments or teams to be replayed via inbound Webhooks.
> **Note**: This is distinct from Seal backend's native simulation "材料包" (`simulation material_pack` / `/api/v1/material-packages/upload`). Calling this standard "Webhook 资源包" avoids confusion.
### ZIP structure convention
```
资源包.zip
├── 信息表.xlsx ← must exist at ZIP root
├── BX20260826003/ ← root dir name = documentId (or documentId@annotation)
│ ├── 合同协议/
│ │ └── 采购合同.pdf
│ └── 支付凭证/
│ └── 支付宝交易明细.pdf
└── BX20260826004@重新提交v2/ ← @annotation is stripped when matching documentId
└── 发票/
└── 增值税专用发票.pdf
```
- The root directory name **must equal** the `documentId`**OR** start with `documentId@` (the `@` separates an optional annotation ignored during matching).
-`信息表.xlsx` at the ZIP root is the only file not associated with any document directory.
- Documents without attachments do not require a directory entry in the ZIP.
### Excel column convention
| Column type | Naming | Purpose |
|---|---|---|
| Regular column | Any header (e.g. `会议编号`, `总金额`, `报销事由`) | Standard document fields |
| Attachment column | Header starts with `[附件]` (e.g. `[附件]合同协议`, `[附件]发票`) | Declares attached files for this row |
- The `[附件]` prefix is stripped to produce the field `label` sent to Seal.
- The cell value contains full ZIP-relative path(s) to the declared files (multiple paths separated by newline, comma, or semicolon).
- Example: column `[附件]合同协议`, cell value `BX20260826003/合同协议/采购合同.pdf`
Before pushing or previewing, the system enforces:
1.**Excel → ZIP**: Every path declared in an `[附件]` column cell **must** exist as a ZIP entry. Error: `Excel 声明的附件路径在 ZIP 中不存在: <path>`
2.**ZIP → Excel**: Every ZIP file (excluding `信息表.xlsx`) **must** be declared in exactly one `[附件]` column. Error: `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>`
3.**Document Directory Scope Isolation**: All attachments declared for a document `DOC_X`**must** reside in its own root directory (`DOC_X/` or `DOC_X@annotation/`). Cross-document references are strictly forbidden. Error: `单据「X」声明了跨单据或非本单据目录的附件路径: <path>。附件必须位于该单据自己的根目录...`
4.**Strict Declaration Uniqueness**: A given ZIP file path **cannot** be declared more than once across the entire resource pack (even within the same document across multiple rows or fields). If the same logical document is needed in multiple places, separate files must be placed in distinct paths. Error: `附件路径「<path>」被重复声明了 N 次...`
5.**Attachment file policy**: Every attachment except the root `信息表.xlsx` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: `附件文件过小...` / `附件文件过大...` / `附件后缀不在白名单中...`
6.**documentId ↔ ZIP root**: Every `documentId` in the Excel main sheet that declares attachments must have a matching ZIP root dir (exact match or `documentId@annotation`), and every ZIP root dir must match a declared `documentId`. Errors: `Excel 会议编号「X」在 ZIP 中找不到对应的根目录...` / `ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号`
All validation errors are collected and reported together in a single `MaterialPackValidationError`.
### CLI usage
```bash
# Export online approval records to a local Webhook resource pack ZIP
# When there is exactly one webhook channel, --webhook can be omitted (auto-locked)
```
### Attachment file policy configuration
The policy is stored per inbound Webhook integration and is applied before any attachment upload or document push. A failed check stops the entire material-pack flow. The policy is intentionally mutable: after an authorized configuration change, retrying the same push reads the saved policy again.
`null` or an omitted `maxFileSizeBytes` means no per-file upper bound. Values are bytes; a file smaller than the minimum or larger than the maximum fails. Extensions are normalized case-insensitively and may be written with or without the leading dot. The root `信息表.xlsx` remains exempt from attachment policy checks.
```bash
# New Webhook: use the default 500-byte minimum and default extension whitelist
The saved configuration is returned by `webhook get`/`webhook list` under `materialPackFilePolicy`. The root `信息表.xlsx` is always allowed as the material-pack manifest and is not subject to the attachment policy.
### Failure recovery loop
When a push fails because of the attachment policy, the error is actionable and should be handled as a two-channel recovery loop:
1. Error channel: read `附件文件过小`, `附件文件过大`, or `附件后缀不在白名单中`, including the attachment path and the configured boundary.
2. Resolution channel: ask whether the user wants to replace/compress the file or explicitly allow the format/size by changing the target Webhook policy.
3. If configuration change is authorized, read the current policy with `webhook get`/`webhook list`, update only the necessary fields, and verify the returned configuration.
4. Retry the original `material-pack push`; it will load the latest saved policy before any upload begins.
The same loop is available through the internal tool registry: read with `seal-use tool seal_webhook_get`/`seal_webhook_list`, update with `seal-use tool seal_webhook_update` and its `materialPackFilePolicy` patch, then retry `seal-use tool seal_webhook_material_pack` in `push` mode. Over MCP these run through `seal_cli` (reads) or `seal_cli_write` (the update and push, which need user confirmation); no separate `seal_webhook_*` MCP tool exists. Set `maxFileSizeBytes` to `null` to clear the upper bound. `allowedExtensions` is a complete replacement list, so include existing allowed suffixes when adding one.
If the assistant lacks permission to update the Webhook or the user does not authorize relaxing the rule, report the block rather than bypassing validation. Since validation happens before the upload loop, a failed attempt does not leave a partially pushed material pack.
The direct local `material-pack preview` command and the tool-registry preview use the default or temporary policy. They do not automatically read a selected Webhook's persisted policy. Use `webhook ready --file --webhook <idOrName>` or the actual push path when validating against the saved inbound policy.
### Error messages reference
| Error message | Meaning | Fix |
|---|---|---|
| `Excel 声明的附件路径在 ZIP 中不存在: <path>` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |
| `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>` | ZIP contains a file not referenced by any `[附件]` column | Add an `[附件]` column entry or remove the file from ZIP |
| `单据「X」声明了跨单据或非本单据目录的附件路径: <path>` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |
| `附件路径「<path>」被重复声明了 N 次` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |
| `Excel 会议编号「X」在 ZIP 中找不到对应的根目录` | No ZIP root dir matches documentId `X` | Rename the ZIP folder to match the documentId |
| `ZIP 根目录对应的编号「X」在信息表中找不到` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |
| `ZIP 根目录缺少信息表.xlsx` | No `信息表.xlsx` found at ZIP root | Add the Excel file to the ZIP root |
| `附件文件过小` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower `--min-file-size` |
| `附件文件过大` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise `--max-file-size` |
| `附件后缀不在白名单中` | Attachment extension is not allowed by the Webhook policy | Add the extension with `--allowed-extensions` or convert the file |
| `附件上传失败 <status>` | Network/server error during file upload | Check webhook URL, secret, and server availability |
A **Webhook resource pack** (webhook 资源包 / 资源包, CLI: `resource-pack`, alias: `pack`, legacy alias: `material-pack`) is a ZIP file that bundles an Excel information sheet (`信息表.xlsx`) with attachments organised by document ID. It is designed for exporting online approval runs and transferring them offline across environments or teams to be replayed via inbound Webhooks.
> **Note**: This is distinct from Seal backend's native simulation "材料包" (`simulation material_pack` / `/api/v1/material-packages/upload`). Calling this standard "Webhook 资源包" avoids confusion.
### ZIP structure convention
```
资源包.zip
├── 信息表.xlsx ← must exist at ZIP root
├── BX20260826003/ ← root dir name = documentId (or documentId@annotation)
│ ├── 合同协议/
│ │ └── 采购合同.pdf
│ └── 支付凭证/
│ └── 支付宝交易明细.pdf
└── BX20260826004@重新提交v2/ ← @annotation is stripped when matching documentId
└── 发票/
└── 增值税专用发票.pdf
```
- The root directory name **must equal** the `documentId`**OR** start with `documentId@` (the `@` separates an optional annotation ignored during matching).
-`信息表.xlsx` at the ZIP root is the only file not associated with any document directory.
- Documents without attachments do not require a directory entry in the ZIP.
### Excel column convention
| Column type | Naming | Purpose |
|---|---|---|
| Regular column | Any header (e.g. `会议编号`, `总金额`, `报销事由`) | Standard document fields |
| Attachment column | Header starts with `[附件]` (e.g. `[附件]合同协议`, `[附件]发票`) | Declares attached files for this row |
- The `[附件]` prefix is stripped to produce the field `label` sent to Seal.
- The cell value contains full ZIP-relative path(s) to the declared files (multiple paths separated by newline, comma, or semicolon).
- Example: column `[附件]合同协议`, cell value `BX20260826003/合同协议/采购合同.pdf`
Before pushing or previewing, the system enforces:
1.**Excel → ZIP**: Every path declared in an `[附件]` column cell **must** exist as a ZIP entry. Error: `Excel 声明的附件路径在 ZIP 中不存在: <path>`
2.**ZIP → Excel**: Every ZIP file (excluding `信息表.xlsx`) **must** be declared in exactly one `[附件]` column. Error: `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>`
3.**Document Directory Scope Isolation**: All attachments declared for a document `DOC_X`**must** reside in its own root directory (`DOC_X/` or `DOC_X@annotation/`). Cross-document references are strictly forbidden. Error: `单据「X」声明了跨单据或非本单据目录的附件路径: <path>。附件必须位于该单据自己的根目录...`
4.**Strict Declaration Uniqueness**: A given ZIP file path **cannot** be declared more than once across the entire resource pack (even within the same document across multiple rows or fields). If the same logical document is needed in multiple places, separate files must be placed in distinct paths. Error: `附件路径「<path>」被重复声明了 N 次...`
5.**Attachment file policy**: Every attachment except the root `信息表.xlsx` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: `附件文件过小...` / `附件文件过大...` / `附件后缀不在白名单中...`
6.**documentId ↔ ZIP root**: Every `documentId` in the Excel main sheet that declares attachments must have a matching ZIP root dir (exact match or `documentId@annotation`), and every ZIP root dir must match a declared `documentId`. Errors: `Excel 会议编号「X」在 ZIP 中找不到对应的根目录...` / `ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号`
All validation errors are collected and reported together in a single `MaterialPackValidationError`.
### CLI usage
```bash
# Export online approval records to a local Webhook resource pack ZIP
# When there is exactly one webhook channel, --webhook can be omitted (auto-locked)
```
### Attachment file policy configuration
The policy is stored per inbound Webhook integration and is applied before any attachment upload or document push. A failed check stops the entire material-pack flow. The policy is intentionally mutable: after an authorized configuration change, retrying the same push reads the saved policy again.
`null` or an omitted `maxFileSizeBytes` means no per-file upper bound. Values are bytes; a file smaller than the minimum or larger than the maximum fails. Extensions are normalized case-insensitively and may be written with or without the leading dot. The root `信息表.xlsx` remains exempt from attachment policy checks.
```bash
# New Webhook: use the default 500-byte minimum and default extension whitelist
The saved configuration is returned by `webhook get`/`webhook list` under `materialPackFilePolicy`. The root `信息表.xlsx` is always allowed as the material-pack manifest and is not subject to the attachment policy.
### Failure recovery loop
When a push fails because of the attachment policy, the error is actionable and should be handled as a two-channel recovery loop:
1. Error channel: read `附件文件过小`, `附件文件过大`, or `附件后缀不在白名单中`, including the attachment path and the configured boundary.
2. Resolution channel: ask whether the user wants to replace/compress the file or explicitly allow the format/size by changing the target Webhook policy.
3. If configuration change is authorized, read the current policy with `webhook get`/`webhook list`, update only the necessary fields, and verify the returned configuration.
4. Retry the original `material-pack push`; it will load the latest saved policy before any upload begins.
The same loop is available through the internal tool registry: read with `seal-use tool seal_webhook_get`/`seal_webhook_list`, update with `seal-use tool seal_webhook_update` and its `materialPackFilePolicy` patch, then retry `seal-use tool seal_webhook_material_pack` in `push` mode. Over MCP these run through `seal_cli` (reads) or `seal_cli_write` (the update and push, which need user confirmation); no separate `seal_webhook_*` MCP tool exists. Set `maxFileSizeBytes` to `null` to clear the upper bound. `allowedExtensions` is a complete replacement list, so include existing allowed suffixes when adding one.
If the assistant lacks permission to update the Webhook or the user does not authorize relaxing the rule, report the block rather than bypassing validation. Since validation happens before the upload loop, a failed attempt does not leave a partially pushed material pack.
The direct local `material-pack preview` command and the tool-registry preview use the default or temporary policy. They do not automatically read a selected Webhook's persisted policy. Use `webhook ready --file --webhook <idOrName>` or the actual push path when validating against the saved inbound policy.
### Error messages reference
| Error message | Meaning | Fix |
|---|---|---|
| `Excel 声明的附件路径在 ZIP 中不存在: <path>` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |
| `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>` | ZIP contains a file not referenced by any `[附件]` column | Add an `[附件]` column entry or remove the file from ZIP |
| `单据「X」声明了跨单据或非本单据目录的附件路径: <path>` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |
| `附件路径「<path>」被重复声明了 N 次` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |
| `Excel 会议编号「X」在 ZIP 中找不到对应的根目录` | No ZIP root dir matches documentId `X` | Rename the ZIP folder to match the documentId |
| `ZIP 根目录对应的编号「X」在信息表中找不到` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |
| `ZIP 根目录缺少信息表.xlsx` | No `信息表.xlsx` found at ZIP root | Add the Excel file to the ZIP root |
| `附件文件过小` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower `--min-file-size` |
| `附件文件过大` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise `--max-file-size` |
| `附件后缀不在白名单中` | Attachment extension is not allowed by the Webhook policy | Add the extension with `--allowed-extensions` or convert the file |
| `附件上传失败 <status>` | Network/server error during file upload | Check webhook URL, secret, and server availability |
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.