@@ -107,7 +107,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
## Security & Configuration Tips
Never commit real enterprise credentials, Seal tokens, service logs, or local generated state. Use `enterprises/example.hose.json` or `enterprises/example.direct.json` as templates, then place real configs in `enterprises/local.json` or `~/.config/seal-use/enterprises` (with legacy fallback to `~/.config/seal-home/enterprises`). For auth or tenant changes, verify with `bun run probe` or `seal-use auth diagnose`.
Never commit real enterprise credentials, Seal tokens, service logs, or local generated state. Use `enterprises/example.hose.json` or `enterprises/example.seal.json` as templates, then place real configs in `enterprises/local.json` or `~/.config/seal-use/enterprises` (with legacy fallback to `~/.config/seal-home/enterprises`). For auth or tenant changes, verify with `bun run probe` or `seal-use auth diagnose`.
Credential files are written `0600`; a config placed by hand keeps the `0o644` default, so run `seal-use doctor` and act on its `credential_permissions` check before sharing a machine or a backup. See `SECURITY.md` for the trust model (local HTTP adapter, self-update, custom linters).
@@ -9,9 +9,9 @@ Bun + TypeScript CLI and optional local service for pulling Seal enterprise appr
The first provider is Hose/合思: `key`, `password`, `corpId`, `staffId`, and an optional Hose domain. The provider exchanges those credentials for a Seal enterprise session, then the Seal domain tools can read and maintain approval rules, approval documents, and approval style preferences.
Seal-native enterprise pages can be added with a Seal Bearer token. The older `direct` source remains available for existing configs that already provide a Seal Bearer token.
Seal-native enterprise pages can be added with a Seal Bearer token.
An incoming Hose/合思 `thirdparty.html` assistance link can be imported directly; the CLI exchanges its temporary token through Seal SSO, verifies the tenant, and stores a short-lived local Seal session.
An incoming Hose/合思 `thirdparty.html` assistance link can be imported directly; the CLI exchanges its temporary token through Seal SSO, verifies the tenant, and stores the Hose web-session source (`closeToken` plus `staffId`). The Seal Bearer is runtime-only.
For an already-authenticated Seal-native source, use `seal-use corps add-seal` or copy `enterprises/example.seal.json`. Existing `direct` configs remain supported via `enterprises/example.direct.json`.
For an already-authenticated Seal-native source, use `seal-use corps add-seal-bearer` or copy `enterprises/example.seal.json`.
## Public Usage
@@ -79,21 +79,31 @@ Create a user-level Hose enterprise config that works from any directory:
```bash
mkdir -p ~/.config/seal-use/enterprises
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use auth diagnose --corp <corpId>
seal-use tools list
```
`corps add-hose` verifies by default before writing the config. It uses the Hose OpenAPI credential response to derive the corporation ID, then checks provisional auth, Seal SSO, and Seal `whoami`. Pass `"force":true` or `"verify":false` only when you intentionally want to write a config that may fail later.
`corps add-hose-persistent` verifies by default before writing the config. It uses the Hose OpenAPI credential response to derive the corporation ID, then checks provisional auth, Seal SSO, and Seal `whoami`. Pass `"force":true` or `"verify":false` only when you intentionally want to write a config that may fail later. The old `add-hose` spelling remains a compatibility alias.
Create a user-level Seal-native enterprise config from an already signed-in Seal Use page:
```bash
seal-use corps add-seal --json '{"sealUrl":"https://tenant.staging.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-seal-bearer --json '{"sealUrl":"https://tenant.staging.sealai.cc","token":"seal-bearer-token"}'
seal-use auth diagnose --corp tenant
```
`corps add-seal` verifies `/api/v1/auth/me` by default and writes the tenant slug, tenant ID, tenant name, and provider user ID into local config metadata. Pass `"force":true` or `"verify":false` only when writing an offline config intentionally.
`corps add-seal-bearer` verifies `/api/v1/auth/me` by default and writes the tenant slug, tenant ID, tenant name, and provider user ID into local config metadata. Pass `"force":true` or `"verify":false` only when writing an offline config intentionally. The old `add-seal` spelling remains a compatibility alias.
When the Agent receives a cURL copied from an authenticated Hose page, it first attempts to extract durable OpenAPI credentials. If that is not possible, it can import the normalized Hose web session and retain its `closeToken` plus `staffId`; Seal access is exchanged at runtime:
```bash
seal-use corps add-hose-web-session --json '{"baseUrl":"https://wx2.ekuaibao.com","corpId":"...","accessToken":"..."}'
```
The Hose `accessToken` is not a Seal Bearer Token and must not be passed to `add-seal-bearer` directly. `add-hose-web-session` stores it as a Hose `closeToken` together with the Hose `staffId`; Seal Bearer is obtained only as a runtime SSO session. It does not create or persist Hose OpenAPI credentials.
Import a Hose/合思 assistance link when you do not have OpenAPI app credentials:
@@ -101,7 +111,7 @@ Import a Hose/合思 assistance link when you do not have OpenAPI app credential
seal-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home"[--name "企业名称"]
```
The command accepts HTTPS links from the supported Hose domains, verifies the Seal tenant with `/api/v1/auth/me`, and writes a `seal` source with `provider: "hosecloud"`. The incoming token is never printed, but the resulting session is temporary and must be renewed after it expires. Use `--overwrite` to replace an existing config explicitly.
The command accepts HTTPS links from the supported Hose domains, verifies the Seal tenant with `/api/v1/auth/me`, and writes a Hose source with `provider: "hosecloud"`, `closeToken`, and `staffId`. The incoming token is never printed. Use `--overwrite` to replace an existing config explicitly.
To generate a Seal delegation link directly from the same incoming Hose link without saving a config:
import{createRequireasly0}from"node:module";varfy0=Object.create;var{getPrototypeOf:uy0,defineProperty:IT,getOwnPropertyNames:by0}=Object;variy0=Object.prototype.hasOwnProperty;functionny0($){returnthis[$]}varcy0,py0,J6=($,Y,z)=>{varU=$!=null&&typeof$==="object";if(U){varQ=Y?cy0??=newWeakMap:py0??=newWeakMap,J=Q.get($);if(J)returnJ}z=$!=null?fy0(uy0($)):{};letI=Y||!$||!$.__esModule?IT(z,"default",{value:$,enumerable:!0}):z;for(letKofby0($))if(!iy0.call(I,K))IT(I,K,{get:ny0.bind($,K),enumerable:!0});if(U)Q.set($,I);returnI};varE=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);vardy0=($)=>$;functionmy0($,Y){this[$]=dy0.bind(null,Y)}varD8=($,Y)=>{for(varzinY)IT($,z,{get:Y[z],enumerable:!0,configurable:!0,set:my0.bind(Y,z)})};varm=($,Y)=>()=>($&&(Y=$($=0)),Y);varI0=ly0(import.meta.url);varoy0,rq,ry0,sy0,ay0,ty0,C0=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports),Gr=($,Y)=>{letz={};for(varUin$)rq(z,U,{get:$[U],enumerable:!0});if(Y)rq(z,Symbol.toStringTag,{value:"Module"});returnz},ey0=($,Y,z,U)=>{if(Y&&typeofY==="object"||typeofY==="function"){for(varQ=sy0(Y),J=0,I=Q.length,K;J<I;J++)if(K=Q[J],!ty0.call($,K)&&K!==z)rq($,K,{get:((G)=>Y[G]).bind(null,K),enumerable:!(U=ry0(Y,K))||U.enumerable})}return$},sq=($,Y,z)=>(z=$!=null?oy0(ay0($)):{},ey0(Y||!$||!$.__esModule?rq(z,"default",{value:$,enumerable:!0}):z,$));varKT=m(()=>{oy0=Object.create,rq=Object.defineProperty,ry0=Object.getOwnPropertyDescriptor,sy0=Object.getOwnPropertyNames,ay0=Object.getPrototypeOf,ty0=Object.prototype.hasOwnProperty});functionWr($){returntypeof$==="string"&&Hr.has($.replace(/#$/,""))}functionXr($,Y){if(!("$schema"in$)||typeof$.$schema!=="string")return"2020-12";letz=$.$schema.replace(/#$/,"");if($k0.has(z))return"2020-12";if(Hr.has(z))return"2019-09";if(Yk0.has(z)||zk0.has(z))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}`)}var$k0,Hr,Yk0,zk0;varGT=m(()=>{$k0=newSet(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Hr=newSet(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Yk0=newSet(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),zk0=newSet(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});functionW0($,Y,z){functionU(K,G){if(!K._zod)Object.defineProperty(K,"_zod",{value:{def:G,constr:I,traits:newSet},enumerable:!1});if(K._zod.traits.has($))return;K._zod.traits.add($),Y(K,G);letH=I.prototype,W=Object.keys(H);for(letX=0;X<W.length;X++){letZ=W[X];if(!(ZinK))K[Z]=H[Z].bind(K)}}letQ=z?.Parent??Object;classJextendsQ{}Object.defineProperty(J,"name",{value:$});functionI(K){varG;letH=z?.Parent?newJ:this;U(H,K),(G=H._zod).deferred??(G.deferred=[]);for(letWofH._zod.deferred)W();returnH}returnObject.defineProperty(I,"init",{value:U}),Object.defineProperty(I,Symbol.hasInstance,{value:(K)=>{if(z?.Parent&&Kinstanceofz.Parent)return!0;returnK?._zod?.traits?.has($)}}),Object.defineProperty(I,"name",{value:$}),I}functiona4($){if($)Object.assign(jY,$);returnjY}varZr,sK,HT,n5,TY,jY;varEY=m(()=>{sK=Object.freeze({status:"aborted"});HT=Symbol("zod_brand");n5=classn5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};TY=classTYextendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(Zr=globalThis).__zod_globalConfig??(Zr.__zod_globalConfig={});jY=globalThis.__zod_globalConfig});vary0={};D8(y0,{unwrapMessage:()=>aK,uint8ArrayToHex:()=>Ek0,uint8ArrayToBase64url:()=>jk0,uint8ArrayToBase64:()=>Lr,stringifyPrimitive:()=>v0,slugify:()=>ZT,shallowClone:()=>VT,safeExtend:()=>Mk0,required:()=>Ak0,randomString:()=>Zk0,propertyKeyTypes:()=>$G,promiseAllObject:()=>Xk0,primitiveTypes:()=>LT,prefixIssues:()=>f8,pick:()=>Fk0,partial:()=>Dk0,parsedType:()=>S0,optionalKeys:()=>FT,omit:()=>Ok0,objectClone:()=>Gk0,numKeys:()=>qk0,nullish:()=>G7,normalizeParams:()=>u0,mergeDefs:()=>p9,merge:()=>Nk0,jsonStringifyReplacer:()=>dU,joinValues:()=>M0,issue:()=>lU,isPlainObject:()=>W7,isObject:()=>CY,hexToUint8Array:()=>Tk0,getSizableOrigin:()=>YG,getParsedType:()=>Vk0,getLengthableOrigin:()=>zG,getEnumValues:()=>tK,getElementAtPath:()=>Wk0,floatSafeRemainder:()=>XT,finalizeIssue:()=>B8,extend:()=>wk0,explicitlyAborted:()=>MT,escapeRegex:()=>A$,esc:()=>aq,defineLazy:()=>E1,createTransparentProxy:()=>Lk0,cloneDef:()=>Hk0,clone:()=>A8,cleanRegex:()=>eK,cleanEnum:()=>Bk0,captureStackTrace:()=>tq,cached:()=>mU,base64urlToUint8Array:()=>Pk0,base64ToUint8Array:()=>Vr,assignProp:()=>H7,assertNotEqual:()=>Qk0,assertNever:()=>Ik0,assertIs:()=>Jk0,assertEqual:()=>Uk0,assert:()=>Kk0,allowsEval:()=>qT,aborted:()=>X7,NUMBER_FORMAT_RANGES:()=>OT,Class:()=>FrLine truncated
`)}var Or=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,dU,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},UG,u8;var AT=m(()=>{EY();Y1();UG=W0("$ZodError",Or),u8=W0("$ZodError",Or,{Parent:Error})});var oU=($)=>(Y,z,U,Q)=>{let J=U?{...U,async:!1}:{async:!1},I=Y._zod.run({value:z,issues:[]},J);if(I instanceof Promise)throw new n5;if(I.issues.length){let K=new(Q?.Err??$)(I.issues.map((G)=>B8(G,J,a4())));throw tq(K,Q?.callee),K}return I.value},eq,rU=($)=>async(Y,z,U,Q)=>{let J=U?{...U,async:!0}:{async:!0},I=Y._zod.run({value:z,issues:[]},J);if(I instanceof Promise)I=await I;if(I.issues.length){let K=new(Q?.Err??$)(I.issues.map((G)=>B8(G,J,a4())));throw tq(K,Q?.callee),K}return I.value},$V,sU=($)=>(Y,z,U)=>{let Q=U?{...U,async:!1}:{async:!1},J=Y._zod.run({value:z,issues:[]},Q);if(J instanceof Promise)throw new n5;return J.issues.length?{success:!1,error:new($??UG)(J.issues.map((I)=>B8(I,Q,a4())))}:{success:!0,data:J.value}},BT,aU=($)=>async(Y,z,U)=>{let Q=U?{...U,async:!0}:{async:!0},J=Y._zod.run({value:z,issues:[]},Q);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((I)=>B8(I,Q,a4())))}:{success:!0,data:J.value}},PT,YV=($)=>(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return oU($)(Y,z,Q)},Rk0,zV=($)=>(Y,z,U)=>{return oU($)(Y,z,U)},_k0,UV=($)=>async(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return rU($)(Y,z,Q)},vk0,QV=($)=>async(Y,z,U)=>{return rU($)(Y,z,U)},hk0,JV=($)=>(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return sU($)(Y,z,Q)},Sk0,IV=($)=>(Y,z,U)=>{return sU($)(Y,z,U)},gk0,KV=($)=>async(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return aU($)(Y,z,Q)},yk0,GV=($)=>async(Y,z,U)=>{return aU($)(Y,z,U)},kk0;var jT=m(()=>{EY();AT();Y1();eq=oU(u8),$V=rU(u8),BT=sU(u8),PT=aU(u8),Rk0=YV(u8),_k0=zV(u8),vk0=UV(u8),hk0=QV(u8),Sk0=JV(u8),gk0=IV(u8),yk0=KV(u8),kk0=GV(u8)});var z$={};D8(z$,{xid:()=>RT,uuid7:()=>bk0,uuid6:()=>uk0,uuid4:()=>fk0,uuid:()=>RY,uppercase:()=>$E,unicodeEmail:()=>Mr,undefined:()=>tT,ulid:()=>CT,time:()=>dT,string:()=>lT,sha512_hex:()=>Kx0,sha512_base64url:()=>Hx0,sha512_base64:()=>Gx0,sha384_hex:()=>Qx0,sha384_base64url:()=>Ix0,sha384_base64:()=>Jx0,sha256_hex:()=>Yx0,sha256_base64url:()=>Ux0,sha256_base64:()=>zx0,sha1_hex:()=>tk0,sha1_base64url:()=>$x0,sha1_base64:()=>ek0,rfc5322Email:()=>nk0,number:()=>IG,null:()=>aT,nanoid:()=>vT,md5_hex:()=>rk0,md5_base64url:()=>ak0,md5_base64:()=>sk0,mac:()=>fT,lowercase:()=>eT,ksuid:()=>_T,ipv6:()=>xT,ipv4:()=>kT,integer:()=>rT,idnEmail:()=>ck0,httpProtocol:()=>nT,html5Email:()=>ik0,hostname:()=>mk0,hex:()=>ok0,guid:()=>ST,extendedDuration:()=>xk0,emoji:()=>yT,email:()=>gT,e164:()=>cT,duration:()=>hT,domain:()=>lk0,datetime:()=>mT,date:()=>pT,cuid2:()=>ET,cuid:()=>TT,cidrv6:()=>bT,cidrv4:()=>uT,browserEmail:()=>pk0,boolean:()=>sT,bigint:()=>oT,base64url:()=>HV,base64:()=>iT});function yT(){return new RegExp(dk0,"u")}function Dr($){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 dT($){return new RegExp(`^${Dr($)}$`)}function mT($){let Y=Dr({precision:$.precision}),z=["Z"];if($.local)z.push("");if($.offset)z.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let U=`${Y}(?:${z.join("|")})`;return new RegExp(`^${Nr}T(?:${U})$`)}function KG($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function GG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var TT,ET,CT,RT,_T,vT,hT,xk0,ST,RY=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;returnnewRegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},fk0,uk0,bk0,gT,ik0,nk0,Mr,ck0,pk0,dk0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",kT,xT,fT=($)=>{letY=A$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},uT,bT,iT,HV,mk0,lk0,nT,cT,Nr="(?:(?:\\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])))",pT,lT=($)=>{letY=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${Y}$`)},oT,rT,IG,sT,aT,tT,eT,$E,ok0,rk0,sk0,ak0,tk0,ek0,$x0,Yx0,zx0,Ux0,Qx0,Jx0,Ix0,Kx0,Gx0,Hx0;varWV=m(()=>{Y1();TT=/^[cC][0-9a-z]{6,}$/,ET=/^[0-9a-z]+$/,CT=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,RT=/^[0-9a-vA-V]{20}$/,_T=/^[A-Za-z0-9]{27}$/,vT=/^[a-zA-Z0-9_-]{21}$/,hT=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((J)=>J),U=Math.min(...z.map((J)=>J.length-J.trimStart().length)),Q=z.map((J)=>J.slice(U)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of Q)this.content.push(J)}compile(){let $=Function,Y=this?.args,U=[...(this?.content??[""]).map((Q)=>`${Q}`)];return new $(...Y,U.join(`
`))}}var ME;var NE=m(()=>{ME={major:4,minor:4,patch:3}});function nE($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function ur($){if(!HV.test($))return!1;let Y=$.replace(/[-_]/g,(U)=>U==="-"?"+":"/"),z=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return nE(z)}function br($,Y=null){try{let z=$.split(".");if(z.length!==3)return!1;let[U]=z;if(!U)return!1;let Q=JSON.parse(atob(U));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 jr($,Y,z){if($.issues.length)Y.issues.push(...f8(z,$.issues));Y.value[z]=$.value}function wV($,Y,z,U,Q,J){let I=z in U;if($.issues.length){if(Q&&J&&!I)return;Y.issues.push(...f8(z,$.issues))}if(!I&&!Q){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[z]});return}if($.value===void 0){if(I)Y.value[z]=void 0}else Y.value[z]=$.value}function ir($){let Y=Object.keys($.shape);for(let U of Y)if(!$.shape?.[U]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${U}":expectedaZodschema`);let z=FT($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(z)}}function nr($,Y,z,U,Q,J){let I=[],K=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(K.has(Z))continue;if(H==="never"){I.push(Z);continue}let q=G.run({value:Y[Z],issues:[]},U);if(q instanceof Promise)$.push(q.then((V)=>wV(V,z,Z,Y,W,X)));else wV(q,z,Z,Y,W,X)}if(I.length)z.issues.push({code:"unrecognized_keys",keys:I,input:Y,inst:J});if(!$.length)return z;return Promise.all($).then(()=>{return z})}function Tr($,Y,z,U){for(let J of $)if(J.issues.length===0)return Y.value=J.value,Y;let Q=$.filter((J)=>!X7(J));if(Q.length===1)return Y.value=Q[0].value,Q[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:z,errors:$.map((J)=>J.issues.map((I)=>B8(I,U,a4())))}),Y}function Er($,Y,z,U){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:z,errors:$.map((J)=>J.issues.map((I)=>B8(I,U,a4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:z,errors:[],inclusive:!1});return Y}function DE($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(W7($)&&W7(Y)){let z=Object.keys(Y),U=Object.keys($).filter((J)=>z.indexOf(J)!==-1),Q={...$,...Y};for(let J of U){let I=DE($[J],Y[J]);if(!I.valid)return{valid:!1,mergeErrorPath:[J,...I.mergeErrorPath]};Q[J]=I.data}return{valid:!0,data:Q}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let z=[];for(let U=0;U<$.length;U++){let Q=$[U],J=Y[U],I=DE(Q,J);if(!I.valid)return{valid:!1,mergeErrorPath:[U,...I.mergeErrorPath]};z.push(I.data)}return{valid:!0,data:z}}return{valid:!1,mergeErrorPath:[]}}function Cr($,Y,z){let U=new Map,Q;for(let K of Y.issues)if(K.code==="unrecognized_keys"){Q??(Q=K);for(let G of K.keys){if(!U.has(G))U.set(G,{});U.get(G).l=!0}}else $.issues.push(K);for(let K of z.issues)if(K.code==="unrecognized_keys")for(let G of K.keys){if(!U.has(G))U.set(G,{});U.get(G).r=!0}else $.issues.push(K);let J=[...U].filter(([,K])=>K.l&&K.r).map(([K])=>K);if(J.length&&Q)$.issues.push({...Q,keys:J});if(X7($))return $;let I=DE(Y.value,z.value);if(!I.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(I.mergeErrorPath)}`);return $.value=I.data,$}function Rr($,Y){for(let z=$.length-1;z>=0;z--)if($[z]._zod[Y]!=="optional")return z+1;return 0}function _r($,Y,z){if($.issues.length)Y.issues.push(...f8(z,$.issues));Y.value[z]=$.value}function vr($,Y,z,U,Q){for(let J=0;J<z.length;J++){let I=$[J],K=J<U.length;if(I.issues.length){if(!K&&J>=Q){Y.value.length=J;break}Y.issues.push(...f8(J,I.issues))}Y.value[J]=I.value}for(let J=Y.value.length-1;J>=U.length;J--)if(z[J]._zod.optout==="optional"&&Y.value[J]===void 0)Y.value.length=J;else break;return Y}function hr($,Y,z,U,Q,J,I){if($.issues.length)if($G.has(typeof U))z.issues.push(...f8(U,$.issues));else z.issues.push({code:"invalid_key",origin:"map",input:Q,inst:J,issues:$.issues.map((K)=>B8(K,I,a4()))});if(Y.issues.length)if($G.has(typeof U))z.issues.push(...f8(U,Y.issues));else z.issues.push({origin:"map",code:"invalid_element",input:Q,inst:J,key:U,issues:Y.issues.map((K)=>B8(K,I,a4()))});z.value.set($.value,Y.value)}function Sr($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function gr($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function yr($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function kr($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function LV($,Y,z){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa
Line truncated
import{createRequireasAk0}from"node:module";varqk0=Object.create;var{getPrototypeOf:Vk0,defineProperty:Oj,getOwnPropertyNames:Lk0}=Object;varwk0=Object.prototype.hasOwnProperty;functionFk0($){returnthis[$]}varMk0,Ok0,I6=($,U,Y)=>{varz=$!=null&&typeof$==="object";if(z){varI=U?Mk0??=newWeakMap:Ok0??=newWeakMap,Q=I.get($);if(Q)returnQ}Y=$!=null?qk0(Vk0($)):{};letJ=U||!$||!$.__esModule?Oj(Y,"default",{value:$,enumerable:!0}):Y;for(letKofLk0($))if(!wk0.call(J,K))Oj(J,K,{get:Fk0.bind($,K),enumerable:!0});if(z)I.set($,J);returnJ};varE=($,U)=>()=>(U||$((U={exports:{}}).exports,U),U.exports);varNk0=($)=>$;functionDk0($,U){this[$]=Nk0.bind(null,U)}varT8=($,U)=>{for(varYinU)Oj($,Y,{get:U[Y],enumerable:!0,configurable:!0,set:Dk0.bind(U,Y)})};varm=($,U)=>()=>($&&(U=$($=0)),U);varJ0=Ak0(import.meta.url);varBk0,UV,Pk0,Tk0,jk0,Ek0,E0=($,U)=>()=>(U||$((U={exports:{}}).exports,U),U.exports),Nr=($,U)=>{letY={};for(varzin$)UV(Y,z,{get:$[z],enumerable:!0});if(U)UV(Y,Symbol.toStringTag,{value:"Module"});returnY},Ck0=($,U,Y,z)=>{if(U&&typeofU==="object"||typeofU==="function"){for(varI=Tk0(U),Q=0,J=I.length,K;Q<J;Q++)if(K=I[Q],!Ek0.call($,K)&&K!==Y)UV($,K,{get:((G)=>U[G]).bind(null,K),enumerable:!(z=Pk0(U,K))||z.enumerable})}return$},YV=($,U,Y)=>(Y=$!=null?Bk0(jk0($)):{},Ck0(U||!$||!$.__esModule?UV(Y,"default",{value:$,enumerable:!0}):Y,$));varNj=m(()=>{Bk0=Object.create,UV=Object.defineProperty,Pk0=Object.getOwnPropertyDescriptor,Tk0=Object.getOwnPropertyNames,jk0=Object.getPrototypeOf,Ek0=Object.prototype.hasOwnProperty});functionAr($){returntypeof$==="string"&&Dr.has($.replace(/#$/,""))}functionBr($,U){if(!("$schema"in$)||typeof$.$schema!=="string")return"2020-12";letY=$.$schema.replace(/#$/,"");if(Rk0.has(Y))return"2020-12";if(Dr.has(Y))return"2019-09";if(_k0.has(Y)||vk0.has(Y))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; ${U}`)}varRk0,Dr,_k0,vk0;varDj=m(()=>{Rk0=newSet(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Dr=newSet(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),_k0=newSet(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),vk0=newSet(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});functionH0($,U,Y){functionz(K,G){if(!K._zod)Object.defineProperty(K,"_zod",{value:{def:G,constr:J,traits:newSet},enumerable:!1});if(K._zod.traits.has($))return;K._zod.traits.add($),U(K,G);letH=J.prototype,W=Object.keys(H);for(letX=0;X<W.length;X++){letZ=W[X];if(!(ZinK))K[Z]=H[Z].bind(K)}}letI=Y?.Parent??Object;classQextendsI{}Object.defineProperty(Q,"name",{value:$});functionJ(K){varG;letH=Y?.Parent?newQ:this;z(H,K),(G=H._zod).deferred??(G.deferred=[]);for(letWofH._zod.deferred)W();returnH}returnObject.defineProperty(J,"init",{value:z}),Object.defineProperty(J,Symbol.hasInstance,{value:(K)=>{if(Y?.Parent&&KinstanceofY.Parent)return!0;returnK?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}functions4($){if($)Object.assign(TU,$);returnTU}varPr,aK,Aj,d5,jU,TU;varEU=m(()=>{aK=Object.freeze({status:"aborted"});Aj=Symbol("zod_brand");d5=classd5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};jU=classjUextendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(Pr=globalThis).__zod_globalConfig??(Pr.__zod_globalConfig={});TU=globalThis.__zod_globalConfig});vark0={};T8(k0,{unwrapMessage:()=>tK,uint8ArrayToHex:()=>Yx0,uint8ArrayToBase64url:()=>$x0,uint8ArrayToBase64:()=>Er,stringifyPrimitive:()=>_0,slugify:()=>Tj,shallowClone:()=>Ej,safeExtend:()=>ok0,required:()=>ak0,randomString:()=>ik0,propertyKeyTypes:()=>UG,promiseAllObject:()=>bk0,primitiveTypes:()=>Cj,prefixIssues:()=>b8,pick:()=>pk0,partial:()=>sk0,parsedType:()=>S0,optionalKeys:()=>Rj,omit:()=>mk0,objectClone:()=>xk0,numKeys:()=>nk0,nullish:()=>W7,normalizeParams:()=>f0,mergeDefs:()=>l9,merge:()=>rk0,jsonStringifyReplacer:()=>mz,joinValues:()=>M0,issue:()=>oz,isPlainObject:()=>Z7,isObject:()=>CU,hexToUint8Array:()=>Ux0,getSizableOrigin:()=>YG,getParsedType:()=>ck0,getLengthableOrigin:()=>zG,getEnumValues:()=>eK,getElementAtPath:()=>uk0,floatSafeRemainder:()=>Pj,finalizeIssue:()=>E8,extend:()=>lk0,explicitlyAborted:()=>hj,escapeRegex:()=>B$,esc:()=>zV,defineLazy:()=>E1,createTransparentProxy:()=>dk0,cloneDef:()=>fk0,clone:()=>j8,cleanRegex:()=>$G,cleanEnum:()=>tk0,captureStackTrace:()=>IV,cached:()=>lz,base64urlToUint8Array:()=>ek0,base64ToUint8Array:()=>jr,assignProp:()=>X7,assertNotEqual:()=>Sk0,assertNever:()=>yk0,assertIs:()=>gk0,assertEqual:()=>hk0,assert:()=>kk0,allowsEval:()=>jj,aborted:()=>q7,NUMBER_FORMAT_RANGES:()=>_j,Class:()=>CrLine truncated
`)}var Rr=($,U)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:U,enumerable:!1}),$.message=JSON.stringify(U,mz,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},IG,i8;var yj=m(()=>{EU();$1();IG=H0("$ZodError",Rr),i8=H0("$ZodError",Rr,{Parent:Error})});var rz=($)=>(U,Y,z,I)=>{let Q=z?{...z,async:!1}:{async:!1},J=U._zod.run({value:Y,issues:[]},Q);if(J instanceof Promise)throw new d5;if(J.issues.length){let K=new(I?.Err??$)(J.issues.map((G)=>E8(G,Q,s4())));throw IV(K,I?.callee),K}return J.value},QV,sz=($)=>async(U,Y,z,I)=>{let Q=z?{...z,async:!0}:{async:!0},J=U._zod.run({value:Y,issues:[]},Q);if(J instanceof Promise)J=await J;if(J.issues.length){let K=new(I?.Err??$)(J.issues.map((G)=>E8(G,Q,s4())));throw IV(K,I?.callee),K}return J.value},JV,az=($)=>(U,Y,z)=>{let I=z?{...z,async:!1}:{async:!1},Q=U._zod.run({value:Y,issues:[]},I);if(Q instanceof Promise)throw new d5;return Q.issues.length?{success:!1,error:new($??IG)(Q.issues.map((J)=>E8(J,I,s4())))}:{success:!0,data:Q.value}},kj,tz=($)=>async(U,Y,z)=>{let I=z?{...z,async:!0}:{async:!0},Q=U._zod.run({value:Y,issues:[]},I);if(Q instanceof Promise)Q=await Q;return Q.issues.length?{success:!1,error:new $(Q.issues.map((J)=>E8(J,I,s4())))}:{success:!0,data:Q.value}},xj,KV=($)=>(U,Y,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return rz($)(U,Y,I)},Ix0,GV=($)=>(U,Y,z)=>{return rz($)(U,Y,z)},Qx0,HV=($)=>async(U,Y,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return sz($)(U,Y,I)},Jx0,WV=($)=>async(U,Y,z)=>{return sz($)(U,Y,z)},Kx0,XV=($)=>(U,Y,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return az($)(U,Y,I)},Gx0,ZV=($)=>(U,Y,z)=>{return az($)(U,Y,z)},Hx0,qV=($)=>async(U,Y,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return tz($)(U,Y,I)},Wx0,VV=($)=>async(U,Y,z)=>{return tz($)(U,Y,z)},Xx0;var fj=m(()=>{EU();yj();$1();QV=rz(i8),JV=sz(i8),kj=az(i8),xj=tz(i8),Ix0=KV(i8),Qx0=GV(i8),Jx0=HV(i8),Kx0=WV(i8),Gx0=XV(i8),Hx0=ZV(i8),Wx0=qV(i8),Xx0=VV(i8)});var z$={};T8(z$,{xid:()=>nj,uuid7:()=>Lx0,uuid6:()=>Vx0,uuid4:()=>qx0,uuid:()=>RU,uppercase:()=>qE,unicodeEmail:()=>vr,undefined:()=>XE,ulid:()=>ij,time:()=>IE,string:()=>JE,sha512_hex:()=>kx0,sha512_base64url:()=>fx0,sha512_base64:()=>xx0,sha384_hex:()=>Sx0,sha384_base64url:()=>yx0,sha384_base64:()=>gx0,sha256_hex:()=>_x0,sha256_base64url:()=>hx0,sha256_base64:()=>vx0,sha1_hex:()=>Ex0,sha1_base64url:()=>Rx0,sha1_base64:()=>Cx0,rfc5322Email:()=>Fx0,number:()=>KG,null:()=>WE,nanoid:()=>dj,md5_hex:()=>Px0,md5_base64url:()=>jx0,md5_base64:()=>Tx0,mac:()=>aj,lowercase:()=>ZE,ksuid:()=>cj,ipv6:()=>sj,ipv4:()=>rj,integer:()=>GE,idnEmail:()=>Mx0,httpProtocol:()=>UE,html5Email:()=>wx0,hostname:()=>Dx0,hex:()=>Bx0,guid:()=>mj,extendedDuration:()=>Zx0,emoji:()=>oj,email:()=>lj,e164:()=>YE,duration:()=>pj,domain:()=>Ax0,datetime:()=>QE,date:()=>zE,cuid2:()=>bj,cuid:()=>uj,cidrv6:()=>ej,cidrv4:()=>tj,browserEmail:()=>Ox0,boolean:()=>HE,bigint:()=>KE,base64url:()=>LV,base64:()=>$E});function oj(){return new RegExp(Nx0,"u")}function Sr($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function IE($){return new RegExp(`^${Sr($)}$`)}function QE($){let U=Sr({precision:$.precision}),Y=["Z"];if($.local)Y.push("");if($.offset)Y.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let z=`${U}(?:${Y.join("|")})`;return new RegExp(`^${hr}T(?:${z})$`)}function GG($,U){return new RegExp(`^[A-Za-z0-9+/]{${$}}${U}$`)}function HG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var uj,bj,ij,nj,cj,dj,pj,Zx0,mj,RU=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;returnnewRegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},qx0,Vx0,Lx0,lj,wx0,Fx0,vr,Mx0,Ox0,Nx0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rj,sj,aj=($)=>{letU=B$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${U}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${U}){5}[0-9a-f]{2}$`)},tj,ej,$E,LV,Dx0,Ax0,UE,YE,hr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",zE,JE=($)=>{letU=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${U}$`)},KE,GE,KG,HE,WE,XE,ZE,qE,Bx0,Px0,Tx0,jx0,Ex0,Cx0,Rx0,_x0,vx0,hx0,Sx0,gx0,yx0,kx0,xx0,fx0;varwV=m(()=>{$1();uj=/^[cC][0-9a-z]{6,}$/,bj=/^[0-9a-z]+$/,ij=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nj=/^[0-9a-vA-V]{20}$/,cj=/^[A-Za-z0-9]{27}$/,dj=/^[a-zA-Z0-9_-]{21}$/,pj=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((Q)=>Q),z=Math.min(...Y.map((Q)=>Q.length-Q.trimStart().length)),I=Y.map((Q)=>Q.slice(z)).map((Q)=>" ".repeat(this.indent*2)+Q);for(let Q of I)this.content.push(Q)}compile(){let $=Function,U=this?.args,z=[...(this?.content??[""]).map((I)=>`${I}`)];return new $(...U,z.join(`
`))}}var hE;var SE=m(()=>{hE={major:4,minor:4,patch:3}});function UC($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function ar($){if(!LV.test($))return!1;let U=$.replace(/[-_]/g,(z)=>z==="-"?"+":"/"),Y=U.padEnd(Math.ceil(U.length/4)*4,"=");return UC(Y)}function tr($,U=null){try{let Y=$.split(".");if(Y.length!==3)return!1;let[z]=Y;if(!z)return!1;let I=JSON.parse(atob(z));if("typ"in I&&I?.typ!=="JWT")return!1;if(!I.alg)return!1;if(U&&(!("alg"in I)||I.alg!==U))return!1;return!0}catch{return!1}}function xr($,U,Y){if($.issues.length)U.issues.push(...b8(Y,$.issues));U.value[Y]=$.value}function PV($,U,Y,z,I,Q){let J=Y in z;if($.issues.length){if(I&&Q&&!J)return;U.issues.push(...b8(Y,$.issues))}if(!J&&!I){if(!$.issues.length)U.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[Y]});return}if($.value===void 0){if(J)U.value[Y]=void 0}else U.value[Y]=$.value}function er($){let U=Object.keys($.shape);for(let z of U)if(!$.shape?.[z]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${z}":expectedaZodschema`);let Y=Rj($.shape);return{...$,keys:U,keySet:new Set(U),numKeys:U.length,optionalKeys:new Set(Y)}}function $s($,U,Y,z,I,Q){let J=[],K=I.keySet,G=I.catchall._zod,H=G.def.type,W=G.optin==="optional",X=G.optout==="optional";for(let Z in U){if(Z==="__proto__")continue;if(K.has(Z))continue;if(H==="never"){J.push(Z);continue}let q=G.run({value:U[Z],issues:[]},z);if(q instanceof Promise)$.push(q.then((V)=>PV(V,Y,Z,U,W,X)));else PV(q,Y,Z,U,W,X)}if(J.length)Y.issues.push({code:"unrecognized_keys",keys:J,input:U,inst:Q});if(!$.length)return Y;return Promise.all($).then(()=>{return Y})}function fr($,U,Y,z){for(let Q of $)if(Q.issues.length===0)return U.value=Q.value,U;let I=$.filter((Q)=>!q7(Q));if(I.length===1)return U.value=I[0].value,I[0];return U.issues.push({code:"invalid_union",input:U.value,inst:Y,errors:$.map((Q)=>Q.issues.map((J)=>E8(J,z,s4())))}),U}function ur($,U,Y,z){let I=$.filter((Q)=>Q.issues.length===0);if(I.length===1)return U.value=I[0].value,U;if(I.length===0)U.issues.push({code:"invalid_union",input:U.value,inst:Y,errors:$.map((Q)=>Q.issues.map((J)=>E8(J,z,s4())))});else U.issues.push({code:"invalid_union",input:U.value,inst:Y,errors:[],inclusive:!1});return U}function gE($,U){if($===U)return{valid:!0,data:$};if($ instanceof Date&&U instanceof Date&&+$===+U)return{valid:!0,data:$};if(Z7($)&&Z7(U)){let Y=Object.keys(U),z=Object.keys($).filter((Q)=>Y.indexOf(Q)!==-1),I={...$,...U};for(let Q of z){let J=gE($[Q],U[Q]);if(!J.valid)return{valid:!1,mergeErrorPath:[Q,...J.mergeErrorPath]};I[Q]=J.data}return{valid:!0,data:I}}if(Array.isArray($)&&Array.isArray(U)){if($.length!==U.length)return{valid:!1,mergeErrorPath:[]};let Y=[];for(let z=0;z<$.length;z++){let I=$[z],Q=U[z],J=gE(I,Q);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};Y.push(J.data)}return{valid:!0,data:Y}}return{valid:!1,mergeErrorPath:[]}}function br($,U,Y){let z=new Map,I;for(let K of U.issues)if(K.code==="unrecognized_keys"){I??(I=K);for(let G of K.keys){if(!z.has(G))z.set(G,{});z.get(G).l=!0}}else $.issues.push(K);for(let K of Y.issues)if(K.code==="unrecognized_keys")for(let G of K.keys){if(!z.has(G))z.set(G,{});z.get(G).r=!0}else $.issues.push(K);let Q=[...z].filter(([,K])=>K.l&&K.r).map(([K])=>K);if(Q.length&&I)$.issues.push({...I,keys:Q});if(q7($))return $;let J=gE(U.value,Y.value);if(!J.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}function ir($,U){for(let Y=$.length-1;Y>=0;Y--)if($[Y]._zod[U]!=="optional")return Y+1;return 0}function nr($,U,Y){if($.issues.length)U.issues.push(...b8(Y,$.issues));U.value[Y]=$.value}function cr($,U,Y,z,I){for(let Q=0;Q<Y.length;Q++){let J=$[Q],K=Q<z.length;if(J.issues.length){if(!K&&Q>=I){U.value.length=Q;break}U.issues.push(...b8(Q,J.issues))}U.value[Q]=J.value}for(let Q=U.value.length-1;Q>=z.length;Q--)if(Y[Q]._zod.optout==="optional"&&U.value[Q]===void 0)U.value.length=Q;else break;return U}function dr($,U,Y,z,I,Q,J){if($.issues.length)if(UG.has(typeof z))Y.issues.push(...b8(z,$.issues));else Y.issues.push({code:"invalid_key",origin:"map",input:I,inst:Q,issues:$.issues.map((K)=>E8(K,J,s4()))});if(U.issues.length)if(UG.has(typeof z))Y.issues.push(...b8(z,U.issues));else Y.issues.push({origin:"map",code:"invalid_element",input:I,inst:Q,key:z,issues:U.issues.map((K)=>E8(K,J,s4()))});Y.value.set($.value,U.value)}function pr($,U){if($.issues.length)U.issues.push(...$.issues);U.value.add($.value)}function mr($,U){if(U===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function lr($,U){if($.value===void 0)$.value=U.defaultValue;return $}function or($,U){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:U});return $}function DV($,U,Y){if($.issues.length)return $.aborted=!0,$;return U._zod.run({value:$.value,issues:$.issues,fa
Line truncated
@@ -60,108 +60,108 @@ import{createRequire as ly0}from"node:module";var fy0=Object.create;var{getProto
newResult[${P}]=${D}.value;
}
`)}q.write("payload.value = newResult;"),q.write("return payload;");let N=q.compile();return(M,D)=>N(Z,M,D)},J,I=CY,K=!jY.jitless,H=K&&qT.value,W=Y.catchall,X;$._zod.parse=(Z,q)=>{X??(X=U.value);let V=Z.value;if(!I(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(K&&H&&q?.async===!1&&q.jitless!==!0){if(!J)J=Q(Y.shape);if(Z=J(Z,q),!W)return Z;return nr([],V,Z,q,X,$)}return z(Z,q)}});WG=W0("$ZodUnion",($,Y)=>{V1.init($,Y),E1($._zod,"optin",()=>Y.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),E1($._zod,"optout",()=>Y.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),E1($._zod,"values",()=>{if(Y.options.every((U)=>U._zod.values))return new Set(Y.options.flatMap((U)=>Array.from(U._zod.values)));return}),E1($._zod,"pattern",()=>{if(Y.options.every((U)=>U._zod.pattern)){let U=Y.options.map((Q)=>Q._zod.pattern);return new RegExp(`^(${U.map((Q)=>eK(Q.source)).join("|")})$`)}return});let z=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(U,Q)=>{if(z)return z(U,Q);let J=!1,I=[];for(let K of Y.options){let G=K._zod.run({value:U.value,issues:[]},Q);if(G instanceof Promise)I.push(G),J=!0;else{if(G.issues.length===0)return G;I.push(G)}}if(!J)return Tr(I,U,$,Q);return Promise.all(I).then((K)=>{return Tr(K,U,$,Q)})}});IC=W0("$ZodXor",($,Y)=>{WG.init($,Y),Y.inclusive=!1;let z=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(U,Q)=>{if(z)return z(U,Q);let J=!1,I=[];for(let K of Y.options){let G=K._zod.run({value:U.value,issues:[]},Q);if(G instanceof Promise)I.push(G),J=!0;else I.push(G)}if(!J)return Er(I,U,$,Q);return Promise.all(I).then((K)=>{return Er(K,U,$,Q)})}}),KC=W0("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,WG.init($,Y);let z=$._zod.parse;E1($._zod,"propValues",()=>{let Q={};for(let J of Y.options){let I=J._zod.propValues;if(!I||Object.keys(I).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(J)}"`);for(let[K,G]of Object.entries(I)){if(!Q[K])Q[K]=new Set;for(let H of G)Q[K].add(H)}}return Q});let U=mU(()=>{let Q=Y.options,J=new Map;for(let I of Q){let K=I._zod.propValues?.[Y.discriminator];if(!K||K.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(I)}"`);for(let G of K){if(J.has(G))throw Error(`Duplicatediscriminatorvalue"${String(G)}"`);J.set(G,I)}}return J});$._zod.parse=(Q,J)=>{let I=Q.value;if(!CY(I))return Q.issues.push({code:"invalid_type",expected:"object",input:I,inst:$}),Q;let K=U.value.get(I?.[Y.discriminator]);if(K)return K._zod.run(Q,J);if(Y.unionFallback||J.direction==="backward")return z(Q,J);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(U.value.keys()),input:I,path:[Y.discriminator],inst:$}),Q}}),GC=W0("$ZodIntersection",($,Y)=>{V1.init($,Y),$._zod.parse=(z,U)=>{let Q=z.value,J=Y.left._zod.run({value:Q,issues:[]},U),I=Y.right._zod.run({value:Q,issues:[]},U);if(J instanceof Promise||I instanceof Promise)return Promise.all([J,I]).then(([G,H])=>{return Cr(z,G,H)});return Cr(z,J,I)}});DV=W0("$ZodTuple",($,Y)=>{V1.init($,Y);let z=Y.items;$._zod.parse=(U,Q)=>{let J=U.value;if(!Array.isArray(J))return U.issues.push({input:J,inst:$,expected:"tuple",code:"invalid_type"}),U;U.value=[];let I=[],K=Rr(z,"optin"),G=Rr(z,"optout");if(!Y.rest){if(J.length<K)return U.issues.push({code:"too_small",minimum:K,inclusive:!0,input:J,inst:$,origin:"array"}),U;if(J.length>z.length)U.issues.push({code:"too_big",maximum:z.length,inclusive:!0,input:J,inst:$,origin:"array"})}let H=Array(z.length);for(let W=0;W<z.length;W++){let X=z[W]._zod.run({value:J[W],issues:[]},Q);if(X instanceof Promise)I.push(X.then((Z)=>{H[W]=Z}));else H[W]=X}if(Y.rest){let W=z.length-1,X=J.slice(z.length);for(let Z of X){W++;let q=Y.rest._zod.run({value:Z,issues:[]},Q);if(q instanceof Promise)I.push(q.then((V)=>_r(V,U,W)));else _r(q,U,W)}}if(I.length)return Promise.all(I).then(()=>vr(H,U,z,J,G));return vr(H,U,z,J,G)}});HC=W0("$ZodRecord",($,Y)=>{V1.init($,Y),$._zod.parse=(z,U)=>{let Q=z.value;if(!W7(Q))return z.issues.push({expected:"record",code:"invalid_type",input:Q,inst:$}),z;let J=[],I=Y.keyType._zod.values;if(I){z.value={};let K=new Set;for(let H of I)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){K.add(typeof H==="number"?H.toString():H);let W=Y.keyType._zod.run({value:H,issues:[]},U);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length){z.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((q)=>B8(q,U,a4())),input:H,path:[H],inst:$});continue}let X=W.value,Z=Y.valueType._zod.run({value:Q[H],issues:[]},U);if(Z instanceof Promise)J.push(Z.then((q)=>{if(q.issues.length)z.issues.push(...f8(H,q.issues));z.value[X]=q.value}));else{if(Z.issues.length)z.issues.push(...f8(H,Z.issues));z.value[X]=Z.value}}let G;for(let H in Q)if(!K.has(H))G=G??[],G.push(H);if(G&&G.length>0)z.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)},Q,J=CU,K=!TU.jitless,H=K&&jj.value,W=U.catchall,X;$._zod.parse=(Z,q)=>{X??(X=z.value);let V=Z.value;if(!J(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(K&&H&&q?.async===!1&&q.jitless!==!0){if(!Q)Q=I(U.shape);if(Z=Q(Z,q),!W)return Z;return $s([],V,Z,q,X,$)}return Y(Z,q)}});XG=H0("$ZodUnion",($,U)=>{V1.init($,U),E1($._zod,"optin",()=>U.options.some((z)=>z._zod.optin==="optional")?"optional":void 0),E1($._zod,"optout",()=>U.options.some((z)=>z._zod.optout==="optional")?"optional":void 0),E1($._zod,"values",()=>{if(U.options.every((z)=>z._zod.values))return new Set(U.options.flatMap((z)=>Array.from(z._zod.values)));return}),E1($._zod,"pattern",()=>{if(U.options.every((z)=>z._zod.pattern)){let z=U.options.map((I)=>I._zod.pattern);return new RegExp(`^(${z.map((I)=>$G(I.source)).join("|")})$`)}return});let Y=U.options.length===1?U.options[0]._zod.run:null;$._zod.parse=(z,I)=>{if(Y)return Y(z,I);let Q=!1,J=[];for(let K of U.options){let G=K._zod.run({value:z.value,issues:[]},I);if(G instanceof Promise)J.push(G),Q=!0;else{if(G.issues.length===0)return G;J.push(G)}}if(!Q)return fr(J,z,$,I);return Promise.all(J).then((K)=>{return fr(K,z,$,I)})}});OC=H0("$ZodXor",($,U)=>{XG.init($,U),U.inclusive=!1;let Y=U.options.length===1?U.options[0]._zod.run:null;$._zod.parse=(z,I)=>{if(Y)return Y(z,I);let Q=!1,J=[];for(let K of U.options){let G=K._zod.run({value:z.value,issues:[]},I);if(G instanceof Promise)J.push(G),Q=!0;else J.push(G)}if(!Q)return ur(J,z,$,I);return Promise.all(J).then((K)=>{return ur(K,z,$,I)})}}),NC=H0("$ZodDiscriminatedUnion",($,U)=>{U.inclusive=!1,XG.init($,U);let Y=$._zod.parse;E1($._zod,"propValues",()=>{let I={};for(let Q of U.options){let J=Q._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${U.options.indexOf(Q)}"`);for(let[K,G]of Object.entries(J)){if(!I[K])I[K]=new Set;for(let H of G)I[K].add(H)}}return I});let z=lz(()=>{let I=U.options,Q=new Map;for(let J of I){let K=J._zod.propValues?.[U.discriminator];if(!K||K.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${U.options.indexOf(J)}"`);for(let G of K){if(Q.has(G))throw Error(`Duplicatediscriminatorvalue"${String(G)}"`);Q.set(G,J)}}return Q});$._zod.parse=(I,Q)=>{let J=I.value;if(!CU(J))return I.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),I;let K=z.value.get(J?.[U.discriminator]);if(K)return K._zod.run(I,Q);if(U.unionFallback||Q.direction==="backward")return Y(I,Q);return I.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:U.discriminator,options:Array.from(z.value.keys()),input:J,path:[U.discriminator],inst:$}),I}}),DC=H0("$ZodIntersection",($,U)=>{V1.init($,U),$._zod.parse=(Y,z)=>{let I=Y.value,Q=U.left._zod.run({value:I,issues:[]},z),J=U.right._zod.run({value:I,issues:[]},z);if(Q instanceof Promise||J instanceof Promise)return Promise.all([Q,J]).then(([G,H])=>{return br(Y,G,H)});return br(Y,Q,J)}});EV=H0("$ZodTuple",($,U)=>{V1.init($,U);let Y=U.items;$._zod.parse=(z,I)=>{let Q=z.value;if(!Array.isArray(Q))return z.issues.push({input:Q,inst:$,expected:"tuple",code:"invalid_type"}),z;z.value=[];let J=[],K=ir(Y,"optin"),G=ir(Y,"optout");if(!U.rest){if(Q.length<K)return z.issues.push({code:"too_small",minimum:K,inclusive:!0,input:Q,inst:$,origin:"array"}),z;if(Q.length>Y.length)z.issues.push({code:"too_big",maximum:Y.length,inclusive:!0,input:Q,inst:$,origin:"array"})}let H=Array(Y.length);for(let W=0;W<Y.length;W++){let X=Y[W]._zod.run({value:Q[W],issues:[]},I);if(X instanceof Promise)J.push(X.then((Z)=>{H[W]=Z}));else H[W]=X}if(U.rest){let W=Y.length-1,X=Q.slice(Y.length);for(let Z of X){W++;let q=U.rest._zod.run({value:Z,issues:[]},I);if(q instanceof Promise)J.push(q.then((V)=>nr(V,z,W)));else nr(q,z,W)}}if(J.length)return Promise.all(J).then(()=>cr(H,z,Y,Q,G));return cr(H,z,Y,Q,G)}});AC=H0("$ZodRecord",($,U)=>{V1.init($,U),$._zod.parse=(Y,z)=>{let I=Y.value;if(!Z7(I))return Y.issues.push({expected:"record",code:"invalid_type",input:I,inst:$}),Y;let Q=[],J=U.keyType._zod.values;if(J){Y.value={};let K=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){K.add(typeof H==="number"?H.toString():H);let W=U.keyType._zod.run({value:H,issues:[]},z);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length){Y.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((q)=>E8(q,z,s4())),input:H,path:[H],inst:$});continue}let X=W.value,Z=U.valueType._zod.run({value:I[H],issues:[]},z);if(Z instanceof Promise)Q.push(Z.then((q)=>{if(q.issues.length)Y.issues.push(...b8(H,q.issues));Y.value[X]=q.value}));else{if(Z.issues.length)Y.issues.push(...b8(H,Z.issues));Y.value[X]=Z.value}}let G;for(let H in I)if(!K.has(H))G=G??[],G.push(H);if(G&&G.length>0)Y.issues.push({code:"unrec
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letIof$.seen.entries()){letK=I[1];if(Y===I[0]){J(I);continue}if($.external){letH=$.external.registry.get(I[0])?.id;if(Y!==I[0]&&H){J(I);continue}}if($.metadataRegistry.get(I[0])?.id){J(I);continue}if(K.cycle){J(I);continue}if(K.count>1){if($.reused==="ref"){J(I);continue}}}}functionF7($,Y){letz=$.seen.get(Y);if(!z)throwError("Unprocessed schema. This is a bug in Zod.");letU=(K)=>{letG=$.seen.get(K);if(G.ref===null)return;letH=G.def??G.schema,W={...H},X=G.ref;if(G.ref=null,X){U(X);letq=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(V);elseObject.assign(H,V);if(Object.assign(H,W),K._zod.parent===X)for(letwinH){if(w==="$ref"||w==="allOf")continue;if(!(winW))deleteH[w]}if(V.$ref&&q.def)for(letwinH){if(w==="$ref"||w==="allOf")continue;if(winq.def&&JSON.stringify(H[w])===JSON.stringify(q.def[w]))deleteH[w]}}letZ=K._zod.parent;if(Z&&Z!==X){U(Z);letq=$.seen.get(Z);if(q?.schema.$ref){if(H.$ref=q.schema.$ref,q.def)for(letVinH){if(V==="$ref"||V==="allOf")continue;if(Vinq.def&&JSON.stringify(H[V])===JSON.stringify(q.def[V]))deleteH[V]}}}$.override({zodSchema:K,jsonSchema:H,path:G.path??[]})};for(letKof[...$.seen.entries()].reverse())U(K[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){letK=$.external.registry.get(Y)?.id;if(!K)throwError("Schema is missing an `id` property");Q.$id=$.external.uri(K)}Object.assign(Q,z.def??z.schema);letJ=$.metadataRegistry.get(Y)?.id;if(J!==void0&&Q.id===J)deleteQ.id;letI=$.external?.defs??{};for(letKof$.seen.entries()){letG=K[1];if(G.def&&G.defId){if(G.def.id===G.defId)deleteG.def.id;I[G.defId]=G.def}}if($.external);elseif(Object.keys(I).length>0)if($.target==="draft-2020-12")Q.$defs=I;elseQ.definitions=I;try{letK=JSON.parse(JSON.stringify(Q));returnObject.defineProperty(K,"~standard",{value:{...Y["~standard"],jsonSchema:{input:qQ(Y,"input",$.processors),output:qQ(Y,"output",$.processors)}},enumerable:!1,writable:!1}),K}catch(K){throwError("Error converting schema to JSON.")}}functionj8($,Y){letz=Y??{seen:newSet};if(z.seen.has($))return!1;z.seen.add($);letU=$._zod.def;if(U.type==="transform")return!0;if(U.type==="array")returnj8(U.element,z);if(U.type==="set")returnj8(U.valueType,z);if(U.type==="lazy")returnj8(U.getter(),z);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")returnj8(U.innerType,z);if(U.type==="intersection")returnj8(U.left,z)||j8(U.right,z);if(U.type==="record"||U.type==="map")returnj8(U.keyType,z)||j8(U.valueType,z);if(U.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnj8(U.in,z)||j8(U.out,z)}if(U.type==="object"){for(letQinU.shape)if(j8(U.shape[Q],z))return!0;return!1}if(U.type==="union"){for(letQofU.options)if(j8(Q,z))return!0;return!1}if(U.type==="tuple"){for(letQofU.items)if(j8(Q,z))return!0;if(U.rest&&j8(U.rest,z))return!0;return!1}return!1}varM_=($,Y={})=>(z)=>{letU=V7({...z,processors:Y});returnJ4($,U),L7(U,$),F7(U,$)},qQ=($,Y,z={})=>(U)=>{let{libraryOptions:Q,target:J}=U??{},I=V7({...Q??{},target:J,io:Y,processors:z});returnJ4($,I),L7(I,$),F7(I,$)};varNG=m(()=>{OG()});functiongY($,Y){if("_idmap"in$){letU=$,Q=V7({...Y,processors:sV}),J={};for(letGofU._idmap.entries()){let[H,W]=G;J4(W,Q)}letI={},K={registry:U,uri:Y?.uri,defs:J};Q.external=K;for(letGofU._idmap.entries()){let[H,W]=G;L7(Q,W),I[H]=F7(Q,W)}if(Object.keys(J).length>0){letG=Q.target==="draft-2020-12"?"$defs":"definitions";I.__shared={[G]:J}}return{schemas:I}}letz=V7({...Y,processors:sV});returnJ4($,z),L7(z,$),F7(z,$)}varvf0,N_=($,Y,z,U)=>{letQ=z;Q.type="string";let{minimum:J,maximum:I,format:K,patterns:G,contentEncoding:H}=$._zod.bag;if(typeofJ==="number")Q.minLength=J;if(typeofI==="number")Q.maxLength=I;if(K){if(Q.format=vf0[K]??K,Q.format==="")deleteQ.format;if(K==="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}))]}},D_=($,Y,z,U)=>{letQ=z,{minimum:J,maximum:I,format:K,multipleOf:G,exclusiveMaximum:H,exclusiveMinimum:W}=$._zod.bag;if(typeofK==="string"&&K.includes("int"))Q.type="integer";elseQ.type="number";letX=typeofW==="number"&&W>=(J??Number.NEGATIVE_INFINITY),Z=typeofH==="number"&&H<=(I??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 Xb0($){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(!Wb0.test($)){let z=[...$].filter((U)=>!/[A-Za-z0-9._-]/.test(U)).filter((U,Q,J)=>J.indexOf(U)===Q);return Y.push(`Toolnamecontainsinvalidcharacters:${z.map((U)=>`"${U}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function Zb0($,Y){if(Y.length>0){console.warn(`Toolnamevalidationwarningfor"${$}":`);for(let z of Y)console.warn(`-${z}`);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 FS($){let Y=Xb0($);return Zb0($,Y.warnings),Y.isValid}function qb0($){return typeof $==="object"&&$!==null&&"_zod"in $}function Vb0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function Lb0($){if(typeof $!=="object"||$===null)return!1;if(kQ($))return!1;let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return!1;return Object.values($).every((z)=>qb0(z))}function kO($){if($===void 0)return;if(Lb0($))return z0($);if(typeof $==="object"&&$!==null&&!kQ($)&&Object.values($).some((Y)=>Vb0(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(!kQ($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var ph,lf0,B1,L1,of0,kt="2026-07-28",R7,ut,af0,tf0,ef0,nt,ct,Yu0,NO,su1,au1,Pt,th,Ku0,Gu0,gQ,c0,J1,RO,mt,fQ,_O,Xu0=0,Zu0="private",qu0,Du0,AO,zS,rt,tu1,eu1,Eu0,Cu0,US,BO,LH="2026-07-28",tt,vu0,B$=($)=>iG.safeParse($).success,_7=($)=>nG.safeParse($).success,qH=($)=>BQ.safeParse($).success,gO=($)=>PQ.safeParse($).success,t9=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",Rt="x-mcp-header",hu0,Su0,gu0,yu0,TO=-32020,$b1,ku0,_t=!1,mh="draft-2020-12",uu0,pu0,du0,vt,mu0,tu0,Ye=250,eu0,$b0,Je,Ie,Yb0,zb0,Ge=60000,Qb0,Jb0,Ib0,He,ZS,Hb0,Yb1,We=10485760,VS=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??We}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 Xe(Y)}catch(z){if(z instanceof SyntaxError)continue;throw z}}return null}clear(){this._buffer=void 0}},Wb0;var xO=m(()=>{KT();GT();Dt();Hh();ph=Symbol.for("mcp.sdk.errorBrands");lf0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](Y){return yQ(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 yQ(this,Y)}constructor(Y,z,U){super(z);this.code=Y,this.errorUri=U,this.name="OAuthError",oh(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)}},B1=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 yQ(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 yQ(this,$)}constructor($,Y,z){super(Y);this.code=$,this.data=z,this.name="SdkError",oh(this,new.target)}},of0=class extends L1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,Y,z){super($,Y,z);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};R7=[kt];ut=["task","inputRequests","requestState"];tf0=new Set(["const","enum","default","examples"]),ef0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);nt={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},ct={"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},Yu0={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};su1=Object.keys(nt),au1=Object.keys(ct);Pt={ok:!1,reason:"not-in-era"};th={era:"2025-11-25",hasRequestMethod:pt,hasNotificationMethod:dt,validateRequest:($,Y)=>DO(Qu0($),Y),validateResult:($,Y)=>DO(Uu0($),Y),validateNotification:($,Y)=>DO(Ju0($),Y),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Pt,validateInputResponse:()=>Pt,samplingResultVariant:($,Y)=>{let z=bt();return DO($?z.CreateMessageResultWithToolsSchema:z.CreateMessageResultSchema,Y)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,Y){let z=ft($),U=z.structuredContent;if(U===void 0)return z;let Q=typeof U!=="object"||U===null||Array.isArray(U),J=Y!==void 0&&it(Y);if(!Q&&!J)return z;return{...z,structuredContent:{result:U}}},decodeResult($,Y){if(dh(Y)&&"resultType"in Y){let z={...Y};return delete z.resultType,{kind:"complete",result:Tt(z)}}return{kind:"complete",result:Tt(Y)}},encodeResult($,Y){if($!=="tools/list")return Y;l
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letJof$.seen.entries()){letK=J[1];if(U===J[0]){Q(J);continue}if($.external){letH=$.external.registry.get(J[0])?.id;if(U!==J[0]&&H){Q(J);continue}}if($.metadataRegistry.get(J[0])?.id){Q(J);continue}if(K.cycle){Q(J);continue}if(K.count>1){if($.reused==="ref"){Q(J);continue}}}}functionM7($,U){letY=$.seen.get(U);if(!Y)throwError("Unprocessed schema. This is a bug in Zod.");letz=(K)=>{letG=$.seen.get(K);if(G.ref===null)return;letH=G.def??G.schema,W={...H},X=G.ref;if(G.ref=null,X){z(X);letq=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(V);elseObject.assign(H,V);if(Object.assign(H,W),K._zod.parent===X)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(!(MinW))deleteH[M]}if(V.$ref&&q.def)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(Minq.def&&JSON.stringify(H[M])===JSON.stringify(q.def[M]))deleteH[M]}}letZ=K._zod.parent;if(Z&&Z!==X){z(Z);letq=$.seen.get(Z);if(q?.schema.$ref){if(H.$ref=q.schema.$ref,q.def)for(letVinH){if(V==="$ref"||V==="allOf")continue;if(Vinq.def&&JSON.stringify(H[V])===JSON.stringify(q.def[V]))deleteH[V]}}}$.override({zodSchema:K,jsonSchema:H,path:G.path??[]})};for(letKof[...$.seen.entries()].reverse())z(K[0]);letI={};if($.target==="draft-2020-12")I.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")I.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")I.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letK=$.external.registry.get(U)?.id;if(!K)throwError("Schema is missing an `id` property");I.$id=$.external.uri(K)}Object.assign(I,Y.def??Y.schema);letQ=$.metadataRegistry.get(U)?.id;if(Q!==void0&&I.id===Q)deleteI.id;letJ=$.external?.defs??{};for(letKof$.seen.entries()){letG=K[1];if(G.def&&G.defId){if(G.def.id===G.defId)deleteG.def.id;J[G.defId]=G.def}}if($.external);elseif(Object.keys(J).length>0)if($.target==="draft-2020-12")I.$defs=J;elseI.definitions=J;try{letK=JSON.parse(JSON.stringify(I));returnObject.defineProperty(K,"~standard",{value:{...U["~standard"],jsonSchema:{input:VI(U,"input",$.processors),output:VI(U,"output",$.processors)}},enumerable:!1,writable:!1}),K}catch(K){throwError("Error converting schema to JSON.")}}functionR8($,U){letY=U??{seen:newSet};if(Y.seen.has($))return!1;Y.seen.add($);letz=$._zod.def;if(z.type==="transform")return!0;if(z.type==="array")returnR8(z.element,Y);if(z.type==="set")returnR8(z.valueType,Y);if(z.type==="lazy")returnR8(z.getter(),Y);if(z.type==="promise"||z.type==="optional"||z.type==="nonoptional"||z.type==="nullable"||z.type==="readonly"||z.type==="default"||z.type==="prefault")returnR8(z.innerType,Y);if(z.type==="intersection")returnR8(z.left,Y)||R8(z.right,Y);if(z.type==="record"||z.type==="map")returnR8(z.keyType,Y)||R8(z.valueType,Y);if(z.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnR8(z.in,Y)||R8(z.out,Y)}if(z.type==="object"){for(letIinz.shape)if(R8(z.shape[I],Y))return!0;return!1}if(z.type==="union"){for(letIofz.options)if(R8(I,Y))return!0;return!1}if(z.type==="tuple"){for(letIofz.items)if(R8(I,Y))return!0;if(z.rest&&R8(z.rest,Y))return!0;return!1}return!1}varh_=($,U={})=>(Y)=>{letz=w7({...Y,processors:U});returnK4($,z),F7(z,$),M7(z,$)},VI=($,U,Y={})=>(z)=>{let{libraryOptions:I,target:Q}=z??{},J=w7({...I??{},target:Q,io:U,processors:Y});returnK4($,J),F7(J,$),M7(J,$)};varDG=m(()=>{MG()});functiongU($,U){if("_idmap"in$){letz=$,I=w7({...U,processors:YL}),Q={};for(letGofz._idmap.entries()){let[H,W]=G;K4(W,I)}letJ={},K={registry:z,uri:U?.uri,defs:Q};I.external=K;for(letGofz._idmap.entries()){let[H,W]=G;F7(I,W),J[H]=M7(I,W)}if(Object.keys(Q).length>0){letG=I.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[G]:Q}}return{schemas:J}}letY=w7({...U,processors:YL});returnK4($,Y),F7(Y,$),M7(Y,$)}varJu0,S_=($,U,Y,z)=>{letI=Y;I.type="string";let{minimum:Q,maximum:J,format:K,patterns:G,contentEncoding:H}=$._zod.bag;if(typeofQ==="number")I.minLength=Q;if(typeofJ==="number")I.maxLength=J;if(K){if(I.format=Ju0[K]??K,I.format==="")deleteI.format;if(K==="time")deleteI.format}if(H)I.contentEncoding=H;if(G&&G.size>0){letW=[...G];if(W.length===1)I.pattern=W[0].source;elseif(W.length>1)I.allOf=[...W.map((X)=>({...U.target==="draft-07"||U.target==="draft-04"||U.target==="openapi-3.0"?{type:"string"}:{},pattern:X.source}))]}},g_=($,U,Y,z)=>{letI=Y,{minimum:Q,maximum:J,format:K,multipleOf:G,exclusiveMaximum:H,exclusiveMinimum:W}=$._zod.bag;if(typeofK==="string"&&K.includes("int"))I.type="integer";elseI.type="number";letX=typeofW==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),Z=typeofH==="number"&&H<=(J??Number.POSITIVE_INFINITY),q=U.target==="draft-04"||U.target==="openapi-3.0";if(X)if(q)I.minimum=W,I.exclusiveMinimum=!0;elseI.exclusiveMinimuLine truncated
`}function bb0($){let U=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Toolnameexceedsmaximumlengthof128characters(current:${$.length})`]};if($.includes(" "))U.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))U.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))U.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))U.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!ub0.test($)){let Y=[...$].filter((z)=>!/[A-Za-z0-9._-]/.test(z)).filter((z,I,Q)=>Q.indexOf(z)===I);return U.push(`Toolnamecontainsinvalidcharacters:${Y.map((z)=>`"${z}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:U}}return{isValid:!0,warnings:U}}function ib0($,U){if(U.length>0){console.warn(`Toolnamevalidationwarningfor"${$}":`);for(let Y of U)console.warn(`-${Y}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function RS($){let U=bb0($);return ib0($,U.warnings),U.isValid}function nb0($){return typeof $==="object"&&$!==null&&"_zod"in $}function cb0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function db0($){if(typeof $!=="object"||$===null)return!1;if(xI($))return!1;let U=Object.getPrototypeOf($);if(U!==Object.prototype&&U!==null)return!1;return Object.values($).every((Y)=>nb0(Y))}function nF($){if($===void 0)return;if(db0($))return Y0($);if(typeof $==="object"&&$!==null&&!xI($)&&Object.values($).some((U)=>cb0(U)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!xI($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var zS,Au0,T1,L1,Bu0,ot="2026-07-28",v7,at,ju0,Eu0,Cu0,$e,Ue,_u0,jF,Cb1,Rb1,kt,XS,ku0,xu0,yI,i0,I1,yF,Ie,uI,kF,bu0=0,iu0="private",nu0,su0,CF,LS,Ke,_b1,vb1,Yb0,zb0,wS,RF,wH="2026-07-28",We,Jb0,P$=($)=>nG.safeParse($).success,h7=($)=>cG.safeParse($).success,VH=($)=>PI.safeParse($).success,bF=($)=>TI.safeParse($).success,U3=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",it="x-mcp-header",Kb0,Gb0,Hb0,Wb0,hF=-32020,hb1,Xb0,nt=!1,QS="draft-2020-12",Vb0,Ob0,Nb0,ct,Db0,Eb0,qe=250,Cb0,Rb0,Fe,Me,_b0,vb0,Ne=60000,Sb0,gb0,yb0,De,TS,fb0,Sb1,Ae=10485760,ES=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??Ae}append($){if((this._buffer?.length??0)+$.length>this._maxBufferSize)throw this.clear(),Error(`ReadBufferexceededmaximumsizeof${this._maxBufferSize}bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){while(this._buffer){let $=this._buffer.indexOf(`
`);if($===-1)return null;let U=this._buffer.toString("utf8",0,$).replace(/\r$/,"");this._buffer=this._buffer.subarray($+1);try{return Be(U)}catch(Y){if(Y instanceof SyntaxError)continue;throw Y}}return null}clear(){this._buffer=void 0}},ub0;var cF=m(()=>{Nj();Dj();St();Ah();zS=Symbol.for("mcp.sdk.errorBrands");Au0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](U){return kI(this,U)}static isInstance(U){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return kI(this,U)}constructor(U,Y,z){super(Y);this.code=U,this.errorUri=z,this.name="OAuthError",KS(this,new.target)}toResponseObject(){let U={error:this.code,error_description:this.message};if(this.errorUri)U.error_uri=this.errorUri;return U}static fromResponse(U){return new $(U.error,U.error_description??U.error,U.error_uri)}},T1=function($){return $.NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$}({}),L1=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return kI(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return kI(this,$)}constructor($,U,Y){super(U);this.code=$,this.data=Y,this.name="SdkError",KS(this,new.target)}},Bu0=class extends L1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,U,Y){super($,U,Y);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};v7=[ot];at=["task","inputRequests","requestState"];Eu0=new Set(["const","enum","default","examples"]),Cu0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);$e={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ue={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},_u0={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};Cb1=Object.keys($e),Rb1=Object.keys(Ue);kt={ok:!1,reason:"not-in-era"};XS={era:"2025-11-25",hasRequestMethod:Ye,hasNotificationMethod:ze,validateRequest:($,U)=>EF(Su0($),U),validateResult:($,U)=>EF(hu0($),U),validateNotification:($,U)=>EF(gu0($),U),hasInputRequestMethod:()=>!1,validateInputRequest:()=>kt,validateInputResponse:()=>kt,samplingResultVariant:($,U)=>{let Y=tt();return EF($?Y.CreateMessageResultWithToolsSchema:Y.CreateMessageResultSchema,U)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,U){let Y=st($),z=Y.structuredContent;if(z===void 0)return Y;let I=typeof z!=="object"||z===null||Array.isArray(z),Q=U!==void 0&&et(U);if(!I&&!Q)return Y;return{...Y,structuredContent:{result:z}}},decodeResult($,U){if(IS(U)&&"resultType"in U){let Y={...U};return delete Y.resultType,{kind:"complete",result:ft(Y)}}return{kind:"complete",result:ft(U)}},encodeResult($,U){if($!=="tools/list")return U;l
Line truncated
*content-type
*Copyright(c)2015DouglasChristopherWilson
*MITLicensed
*/Hb0=C0(($)=>{var Y=/;*([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,z=/\\([\u000b\u0020-\u00ff])/g,U=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;$.parse=Q;function Q(K){if(!K)throw TypeError("argument string is required");var G=typeof K==="object"?J(K):K;if(typeof G!=="string")throw TypeError("argument string is required to be a string");var H=G.indexOf(";"),W=H!==-1?G.slice(0,H).trim():G.trim();if(!U.test(W))throw TypeError("invalid media type");var X=new I(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(z,"$1")}X.parameters[Z]=V}if(H!==G.length)throw TypeError("invalid parameter format")}return X}function J(K){var G;if(typeof K.getHeader==="function")G=K.getHeader("content-type");else if(typeof K.headers==="object")G=K.headers&&K.headers["content-type"];if(typeof G!=="string")throw TypeError("content-type header is missing from object");return G}function I(K){this.parameters=Object.create(null),this.type=K}}),Yb1=sq(Hb0(),1);Wb0=/^[A-Za-z0-9._-]{1,128}$/});function OS($){let Y=new $({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return vi0(Y),Y}var fO,Ze,F1,v1,Q5,bO,Fb0,qe,Ve,uO,Ob0,J5,wb0,Mb0,Le,Nb0,iO,uQ,OH,bQ,nO,Db0,Fe,Ab0,Bb0,Pb0,wS,jb0,MS,Oe,Tb0,Eb0,Cb0,Rb0,_b0,vb0,hb0,Sb0,NS,gb0,yb0,kb0,we,Me,Ne,xb0,fb0,ub0,DS,bb0,De,ib0,nb0,cb0,pb0,db0,mb0,lb0,ob0,Ae,rb0,Be,Pe,je,sb0,AS,ab0,Te,Ee,Ce,tb0,eb0,Re,$i0,Yi0,zi0,_e,Ui0,Qi0,ve,Ji0,Ii0,Ki0,Gi0,Hi0,Wi0,Xi0,Zi0,qi0,Vi0,Li0,Fi0,Oi0,wi0,Mi0,Ni0,Di0,Ai0,Bi0,Pi0,ji0,Ti0,Ei0,he,Ci0,Ri0,_i0,vi0,cO=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor($){this._userAjv=$!==void 0,this._ajv=$}get ajv(){return this._ajv??=OS(Ri0.Ajv2020)}_engineFor($){if(this._userAjv)return this.ajv;let Y=Xr($,"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??=OS(Ci0.Ajv2019);return this._ajvDraft7??=OS(he.Ajv)}getValidator($){let Y=this._engineFor($),z="$id"in $&&typeof $.$id==="string"?Y.getSchema($.$id)??Y.compile($):Y.compile($);return(U)=>{return z(U)?{valid:!0,data:U,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:Y.errorsText(z.errors)}}}},qb1;var Se=m(()=>{KT();GT();fO=C0(($)=>{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 z=class extends Y{constructor(O){super();if(!$.IDENTIFIER.test(O))throw Error("CodeGen: name must be a valid identifier");this.str=O}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};$.Name=z;var U=class extends Y{constructor(O){super();this._items=typeof O==="string"?[O]:O}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let O=this._items[0];return O===""||O==='""'}get str(){var O;return(O=this._str)!==null&&O!==void 0?O:this._str=this._items.reduce((N,M)=>`${N}${M}`,"")}get names(){var O;return(O=this._names)!==null&&O!==void 0?O:this._names=this._items.reduce((N,M)=>{if(M instanceof z)N[M.str]=(N[M.str]||0)+1;return N},{})}};$._Code=U,$.nil=new U("");function Q(O,...N){let M=[O[0]],D=0;while(D<N.length)K(M,N[D]),M.push(O[++D]);return new U(M)}$._=Q;let J=new U("+");function I(O,...N){let M=[q(O[0])],D=0;while(D<N.length)M.push(J),K(M,N[D]),M.push(J,q(O[++D]));return G(M),new U(M)}$.str=I;function K(O,N){if(N instanceof U)O.push(...N._items);else if(N instanceof z)O.push(N);else O.push(X(N))}$.addCodeArg=K;function G(O){let N=1;while(N<O.length-1){if(O[N]===J){let M=H(O[N-1],O[N+1]);if(M!==void 0){O.splice(N-1,3,M);continue}O[N++]="+"}N++}}function H(O,N){if(N==='""')return O;if(O==='""')return N;if(typeof O=="string"){if(N instanceof z||O[O.length-1]!=='"')return;if(typeof N!="string")return`${O.slice(0,-1)}${N}"`;if(N[0]==='"')return O.slice(0,-1)+N.slice(1);return}if(typeof N=="string"&&N[0]==='"'&&!(O instanceof z))return`"${O}${N.slice(1)}`}function W(O,N){return N.emptyStr()?O:O.emptyStr()?N:I`${O}${N}`}$.strConcat=W;function X(O){return typeof O=="number"||typeof O=="boolean"||O===null?O:q(Array.isArray(O)?O.join(","):O)}function Z(O){return new U(q(O))}$.stringify=Z;function q(O){return JSON.stringify(O).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$.safeStringify=q;function V(O){return typeof O=="string"&&$.IDENTIFIER.test(O)?new U(`.${O}`):Q`[${O}]`}$.getProperty=V;function F(O){if(typeof O=="string"&&$.IDENTIFIER.test(O))returnnewU(`${O}`);throwError(`CodeGen: invalid export name: ${O}, use explicit $id name mapping`)}$.getEsmExportName=F;functionw(O){returnnewU(O.toStringLine truncated
deps:${W}}`};let Q={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[H,W]=J(G);I(G,H),K(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 I(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 F=H[V];if(F.length===0)continue;let w=(0,U.propertyInData)(W,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:F.length,deps:F.join(", ")}),Z.allErrors)W.if(w,()=>{for(let O of F)(0,U.checkReportMissingProp)(G,O)});else W.if(Y._`${w}&&(${(0,U.checkMissingProp)(G,F,q)})`),(0,U.reportMissingProp)(G,q),W.else()}}$.validatePropertyDeps=I;function K(G,H=G.schema){let{gen:W,data:X,keyword:Z,it:q}=G,V=W.name("valid");for(let F in H){if((0,z.alwaysValidSchema)(q,H[F]))continue;W.if((0,U.propertyInData)(W,X,F,q.opts.ownProperties),()=>{let w=G.subschema({keyword:Z,schemaProp:F},V);G.mergeValidEvaluated(w,V)},()=>W.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=K,$.default=Q}),bb0=C0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=F1(),z=v1(),U={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:I,data:K,it:G}=Q;if((0,z.alwaysValidSchema)(G,I))return;let H=J.name("valid");J.forIn("key",K,(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=U}),De=C0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=J5(),z=F1(),U=Q5(),Q=v1(),J={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:I})=>z._`{additionalProperty:${I.additionalProperty}}`},code(I){let{gen:K,schema:G,parentSchema:H,data:W,errsCount:X,it:Z}=I;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 F=(0,Y.allSchemaProperties)(H.properties),w=(0,Y.allSchemaProperties)(H.patternProperties);O(),I.ok(z._`${X}===${U.default.errors}`);function O(){K.forIn("key",W,(j)=>{if(!F.length&&!w.length)D(j);else K.if(N(j),()=>D(j))})}function N(j){let A;if(F.length>8){let T=(0,Q.schemaRefOrVal)(Z,H.properties,"properties");A=(0,Y.isOwnProperty)(K,T,j)}else if(F.length)A=(0,z.or)(...F.map((T)=>z._`${j}===${T}`));else A=z.nil;if(w.length)A=(0,z.or)(A,...w.map((T)=>z._`${(0,Y.usePattern)(I,T)}.test(${j})`));return(0,z.not)(A)}function M(j){K.code(z._`delete${W}[${j}]`)}function D(j){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){M(j);return}if(G===!1){if(I.setParams({additionalProperty:j}),I.error(),!q)K.break();return}if(typeof G=="object"&&!(0,Q.alwaysValidSchema)(Z,G)){let A=K.name("valid");if(V.removeAdditional==="failing")P(j,A,!1),K.if((0,z.not)(A),()=>{I.reset(),M(j)});else if(P(j,A),!q)K.if((0,z.not)(A),()=>K.break())}}function P(j,A,T){let C={keyword:"additionalProperties",dataProp:j,dataPropType:Q.Type.Str};if(T===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});I.subschema(C,A)}}};$.default=J}),ib0=C0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=uQ(),z=J5(),U=v1(),Q=De(),J={keyword:"properties",type:"object",schemaType:"object",code(I){let{gen:K,schema:G,parentSchema:H,data:W,it:X}=I;if(X.opts.removeAdditional==="all"&&H.additionalProperties===void 0)Q.default.code(new Y.KeywordCxt(X,Q.default,"additionalProperties"));let Z=(0,z.allSchemaProperties)(G);for(let O of Z)X.definedProperties.add(O);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=U.mergeEvaluated.props(K,(0,U.toHash)(Z),X.props);let q=Z.filter((O)=>!(0,U.alwaysValidSchema)(X,G[O]));if(q.length===0)return;let V=K.name("valid");for(let O of q){if(F(O))w(O);else{if(K.if((0,z.propertyInData)(K,W,O,X.opts.ownProperties)),w(O),!X.allErrors)K.else().var(V,!0);K.endIf()}I.it.definedProperties.add(O),I.ok(V)}function F(O){return X.opts.useDefaults&&!X.compositeRule&&G[O].default!==void 0}function w(O){I.subschema({keyword:"properties",schemaProp:O,dataProp:O},V)}}};$.default=J}),nb0=C0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=J5(),z=F1(),U=v1(),Q=v1(),J={keyword:"patternProperties",type:"object",schemaType:"object",code(I){let{gen:K,schema:G,data:H,parentSchema:W,it:X}=I,{opts:Z}=X,q=(0,Y.allSchemaProperties)(G),V=q.filter((P)=>(0,U.alwaysValidSchema)(X,G[P]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let F=Z.strictSchema&&!Z.allowMatchingProperties&&W.properties,w=K.name("valid");if(X.props!==!0&&!(X.props instanceof z.Name))X.props=(0,Q.evaluatedPropsToName)(K,X.props);let{props:O}=X;N();function N(){for(let P of q){if(F)M(P);if(X.allErrors)
Line truncated
`)}openNode($,Y){let z=this.tos,U=this._xml;if(z&&this.open)U.push(">");this._stack.push($),U.push("<"),U.push($),gk(U,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)Q70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");gk(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(U70.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,z){if(this.openNode($,Y),z!==void 0)this.writeText(z);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("")}}yk.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};J70.exports=yk});var kk=E((ot0)=>{var I70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function lt0($){if(typeof $==="string")return $;if(I70)return I70.decode($);return $.toString()}ot0.bufferToString=lt0});var X70=E((G70)=>{Object.defineProperty(G70,"__esModule",{value:!0});G70.CHAR=`
`,$=this.i;break;case V01:{let{entityReturnState:z}=this,U=this.entity+Y.slice($,this.prevI);this.state=z;let Q;if(U==="")this.fail("empty entity name."),Q="&;";else Q=this.parseEntity(U),this.entity="";if(z!==R8||this.textHandler!==void 0)this.text+=Q;break $}case k4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(hW($))this.state=H01,this.unget(),this.xmlDeclPossible=!1;else switch($){case YN:this.state=Z01,this.xmlDeclPossible=!1;break;case g70:this.state=ee0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case r6:this.state=Q01;break;default:this.fail("disallowed character in tag name"),this.state=R8,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=mk,this.openWakaBang="";break;case"--":this.state=dk,this.openWakaBang="";break;case"DOCTYPE":if(this.state=nk,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($N))this.state=$01}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===$N)this.state=Y01,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=dk}sCommentEnded(){let $=this.getCodeNorm();if($!==j6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=dk;else this.state=R8}sCData(){if(this.captureToChar(vJ))this.state=z01}sCDataEnding(){let $=this.getCodeNorm();if($===vJ)this.state=U01;else this.text+=`]${String.fromCodePoint($)}`,this.state=mk}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case j6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=R8;break}case vJ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=mk}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=E70;else if($===r6||d8($))this.fail("processing instruction without a target."),this.state=$===r6?eM:lk;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 z=this.getCodeNorm();if(z===k4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(z)){this.piTarget+=$.slice(Y,this.prevI);let U=z===r6;if(U||d8(z))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=U?qz:C70}else this.state=U?eM:lk;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(z);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===r6)this.state=eM;else if(!d8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(r6))this.state=eM}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===j6){let{piTarget:z}=this;if(z.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:z,body:this.text}),this.piTarget=this.text="",this.state=R8}else if(Y===r6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=lk;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===r6){this.state=qz;return}if($!==k4)this.state=J01,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(O01);if($===r6){this.state=qz,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(d8($)||$===_J))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=$===_J?R70:I01}sXMLDeclEq(){let $=this.getCodeNorm();if($===r6){this.state=qz,this.fail("XML declaration is incomplete.");return}if(d8($))return;if($!==_J)this.fail("value required.");this.state=R70}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===r6){this.state=qz,this.fail("XML declaration is incomplete.");return}if(d8($))return;if(!zN($))this.fail("value must be quoted."),this.q=S70;else this.q=$;this.state=K01}sXMLDeclValue(){let $=this.captureTo([this.q,r6]);if($===r6){this.state=qz,this.text="",this.fail("XML declaration is incomplete.");return}if($===k4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let z=Y;if(this.xmlDecl.version=z,!/^1\.[0-9]+$/.test(z))this.fail("ver
Line truncated
deps:${W}}`};let I={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[H,W]=Q(G);J(G,H),K(G,W)}};function Q({schema:G}){let H={},W={};for(let X in G){if(X==="__proto__")continue;let Z=Array.isArray(G[X])?H:W;Z[X]=G[X]}return[H,W]}function J(G,H=G.schema){let{gen:W,data:X,it:Z}=G;if(Object.keys(H).length===0)return;let q=W.let("missing");for(let V in H){let F=H[V];if(F.length===0)continue;let M=(0,z.propertyInData)(W,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:F.length,deps:F.join(", ")}),Z.allErrors)W.if(M,()=>{for(let w of F)(0,z.checkReportMissingProp)(G,w)});else W.if(U._`${M}&&(${(0,z.checkMissingProp)(G,F,q)})`),(0,z.reportMissingProp)(G,q),W.else()}}$.validatePropertyDeps=J;function K(G,H=G.schema){let{gen:W,data:X,keyword:Z,it:q}=G,V=W.name("valid");for(let F in H){if((0,Y.alwaysValidSchema)(q,H[F]))continue;W.if((0,z.propertyInData)(W,X,F,q.opts.ownProperties),()=>{let M=G.subschema({keyword:Z,schemaProp:F},V);G.mergeValidEvaluated(M,V)},()=>W.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=K,$.default=I}),Li0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let U=w1(),Y=v1(),z={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:I})=>U._`{propertyName:${I.propertyName}}`},code(I){let{gen:Q,schema:J,data:K,it:G}=I;if((0,Y.alwaysValidSchema)(G,J))return;let H=Q.name("valid");Q.forIn("key",K,(W)=>{I.setParams({propertyName:W}),I.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},H),Q.if((0,U.not)(H),()=>{if(I.error(!0),!G.allErrors)Q.break()})}),I.ok(H)}};$.default=z}),Se=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let U=G5(),Y=w1(),z=K5(),I=v1(),Q={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:J})=>Y._`{additionalProperty:${J.additionalProperty}}`},code(J){let{gen:K,schema:G,parentSchema:H,data:W,errsCount:X,it:Z}=J;if(!X)throw Error("ajv implementation error");let{allErrors:q,opts:V}=Z;if(Z.props=!0,V.removeAdditional!=="all"&&(0,I.alwaysValidSchema)(Z,G))return;let F=(0,U.allSchemaProperties)(H.properties),M=(0,U.allSchemaProperties)(H.patternProperties);w(),J.ok(Y._`${X}===${z.default.errors}`);function w(){K.forIn("key",W,(T)=>{if(!F.length&&!M.length)D(T);else K.if(N(T),()=>D(T))})}function N(T){let A;if(F.length>8){let j=(0,I.schemaRefOrVal)(Z,H.properties,"properties");A=(0,U.isOwnProperty)(K,j,T)}else if(F.length)A=(0,Y.or)(...F.map((j)=>Y._`${T}===${j}`));else A=Y.nil;if(M.length)A=(0,Y.or)(A,...M.map((j)=>Y._`${(0,U.usePattern)(J,j)}.test(${T})`));return(0,Y.not)(A)}function O(T){K.code(Y._`delete${W}[${T}]`)}function D(T){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){O(T);return}if(G===!1){if(J.setParams({additionalProperty:T}),J.error(),!q)K.break();return}if(typeof G=="object"&&!(0,I.alwaysValidSchema)(Z,G)){let A=K.name("valid");if(V.removeAdditional==="failing")P(T,A,!1),K.if((0,Y.not)(A),()=>{J.reset(),O(T)});else if(P(T,A),!q)K.if((0,Y.not)(A),()=>K.break())}}function P(T,A,j){let C={keyword:"additionalProperties",dataProp:T,dataPropType:I.Type.Str};if(j===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});J.subschema(C,A)}}};$.default=Q}),wi0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let U=bI(),Y=G5(),z=v1(),I=Se(),Q={keyword:"properties",type:"object",schemaType:"object",code(J){let{gen:K,schema:G,parentSchema:H,data:W,it:X}=J;if(X.opts.removeAdditional==="all"&&H.additionalProperties===void 0)I.default.code(new U.KeywordCxt(X,I.default,"additionalProperties"));let Z=(0,Y.allSchemaProperties)(G);for(let w of Z)X.definedProperties.add(w);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=z.mergeEvaluated.props(K,(0,z.toHash)(Z),X.props);let q=Z.filter((w)=>!(0,z.alwaysValidSchema)(X,G[w]));if(q.length===0)return;let V=K.name("valid");for(let w of q){if(F(w))M(w);else{if(K.if((0,Y.propertyInData)(K,W,w,X.opts.ownProperties)),M(w),!X.allErrors)K.else().var(V,!0);K.endIf()}J.it.definedProperties.add(w),J.ok(V)}function F(w){return X.opts.useDefaults&&!X.compositeRule&&G[w].default!==void 0}function M(w){J.subschema({keyword:"properties",schemaProp:w,dataProp:w},V)}}};$.default=Q}),Fi0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let U=G5(),Y=w1(),z=v1(),I=v1(),Q={keyword:"patternProperties",type:"object",schemaType:"object",code(J){let{gen:K,schema:G,data:H,parentSchema:W,it:X}=J,{opts:Z}=X,q=(0,U.allSchemaProperties)(G),V=q.filter((P)=>(0,z.alwaysValidSchema)(X,G[P]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let F=Z.strictSchema&&!Z.allowMatchingProperties&&W.properties,M=K.name("valid");if(X.props!==!0&&!(X.props instanceof Y.Name))X.props=(0,I.evaluatedPropsToName)(K,X.props);let{props:w}=X;N();function N(){for(let P of q){if(F)O(P);if(X.allErrors)
Line truncated
`)}openNode($,U){let Y=this.tos,z=this._xml;if(Y&&this.open)z.push(">");this._stack.push($),z.push("<"),z.push($),ok(z,U),this.leaf=!0,this.open=!0}addAttribute($,U){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(U!==void 0)L70(this._xml,$,U)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");ok(this._xml,$)}writeText($){let U=this._xml;if(this.open)U.push(">"),this.open=!1;this.leaf=!1,U.push(V70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),U=this._xml;if(this.leaf)U.push("/>");else U.push("</"),U.push($),U.push(">");this.open=!1,this.leaf=!1}leafNode($,U,Y){if(this.openNode($,U),Y!==void 0)this.writeText(Y);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}rk.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};w70.exports=rk});var sk=E((Ae0)=>{var F70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function De0($){if(typeof $==="string")return $;if(F70)return F70.decode($);return $.toString()}Ae0.bufferToString=De0});var A70=E((O70)=>{Object.defineProperty(O70,"__esModule",{value:!0});O70.CHAR=`
`,$=this.i;break;case n01:{let{entityReturnState:Y}=this,z=this.entity+U.slice($,this.prevI);this.state=Y;let I;if(z==="")this.fail("empty entity name."),I="&;";else I=this.parseEntity(z),this.entity="";if(Y!==h8||this.textHandler!==void 0)this.text+=I;break $}case x4:this.entity+=U.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(gW($))this.state=x01,this.unget(),this.xmlDeclPossible=!1;else switch($){case KN:this.state=b01,this.xmlDeclPossible=!1;break;case p70:this.state=E01,this.openWakaBang="",this.xmlDeclPossible=!1;break;case s6:this.state=h01;break;default:this.fail("disallowed character in tag name"),this.state=h8,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=Jx,this.openWakaBang="";break;case"--":this.state=Qx,this.openWakaBang="";break;case"DOCTYPE":if(this.state=Yx,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar(JN))this.state=C01}sCommentEnding(){var $;let U=this.getCodeNorm();if(U===JN)this.state=R01,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(U)}`,this.state=Qx}sCommentEnded(){let $=this.getCodeNorm();if($!==T6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Qx;else this.state=h8}sCData(){if(this.captureToChar(hQ))this.state=_01}sCDataEnding(){let $=this.getCodeNorm();if($===hQ)this.state=v01;else this.text+=`]${String.fromCodePoint($)}`,this.state=Jx}sCDataEnding2(){var $;let U=this.getCodeNorm();switch(U){case T6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=h8;break}case hQ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(U)}`,this.state=Jx}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=f70;else if($===s6||m8($))this.fail("processing instruction without a target."),this.state=$===s6?QN:Kx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=f70}sPIRest(){let{chunk:$,i:U}=this;while(!0){let Y=this.getCodeNorm();if(Y===x4){this.piTarget+=$.slice(U);return}if(!this.nameCheck(Y)){this.piTarget+=$.slice(U,this.prevI);let z=Y===s6;if(z||m8(Y))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=z?qY:u70}else this.state=z?QN:Kx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(Y);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===s6)this.state=QN;else if(!m8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(s6))this.state=QN}sPIEnding(){var $;let U=this.getCodeNorm();if(U===T6){let{piTarget:Y}=this;if(Y.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:Y,body:this.text}),this.piTarget=this.text="",this.state=h8}else if(U===s6)this.text+="?";else this.text+=`?${String.fromCodePoint(U)}`,this.state=Kx;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===s6){this.state=qY;return}if($!==x4)this.state=S01,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(p01);if($===s6){this.state=qY,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(m8($)||$===vQ))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expectedthename${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expectedoneof${this.xmlDeclExpects.join(", ")}`)}this.state=$===vQ?b70:g01}sXMLDeclEq(){let $=this.getCodeNorm();if($===s6){this.state=qY,this.fail("XML declaration is incomplete.");return}if(m8($))return;if($!==vQ)this.fail("value required.");this.state=b70}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===s6){this.state=qY,this.fail("XML declaration is incomplete.");return}if(m8($))return;if(!GN($))this.fail("value must be quoted."),this.q=d70;else this.q=$;this.state=y01}sXMLDeclValue(){let $=this.captureTo([this.q,s6]);if($===s6){this.state=qY,this.text="",this.fail("XML declaration is incomplete.");return}if($===x4)return;let U=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let Y=U;if(this.xmlDecl.version=Y,!/^1\.[0-9]+$/.test(Y))this.fail("ver
Line truncated
See:https://github.com/isaacs/node-glob/issues/167`);return new T6($,Y).found}function T6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See:https://github.com/isaacs/node-glob/issues/167`);return new j6($,U).found}function j6($,U){if(!$)throw Error("must provide pattern");if(typeof U==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
`+q0[B0-1];break}}}var A1="a promise was created in a "+v+"handler "+X0+"but was not returned from it, see http://goo.gl/rRqMUw"+J0;u._warn(A1,!0,B)}}function y(Q0,B){var v=Q0+" is deprecated and will be removed in a future version.";if(B)v+=" Use "+B+" instead.";return r(v)}function r(Q0,B,v){if(!A0.warnings)return;var u=new Q(Q0),a;if(B)v._attachExtraTrace(u);else if(A0.longStackTraces&&(a=$._peekContext()))a.attachExtraTrace(u);else{var X0=f0(u);u.stack=X0.message+`
`+Z0[A0-1];break}}}var A1="a promise was created in a "+h+"handler "+W0+"but was not returned from it, see http://goo.gl/rRqMUw"+Q0;u._warn(A1,!0,B)}}function R(I0,B){var h=I0+" is deprecated and will be removed in a future version.";if(B)h+=" Use "+B+" instead.";return o(h)}function o(I0,B,h){if(!D0.warnings)return;var u=new I(I0),s;if(B)h._attachExtraTrace(u);else if(D0.longStackTraces&&(s=$._peekContext()))s.attachExtraTrace(u);else{var W0=o0(u);u.stack=W0.message+`
`)));return}}O=O._target();var N=O._bitField;if((N&50397184)===0)this._yieldedPromise=O,O._proxy(this,null);else if((N&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,O._value());else if((N&16777216)!==0)$._async.invoke(this._promiseRejected,this,O._reason());else this._promiseCancelled()}},$.coroutine=function(V,F){if(typeof V!=="function")throw new K(`generatorFunctionmustbeafunction
`)));return}}w=w._target();var N=w._bitField;if((N&50397184)===0)this._yieldedPromise=w,w._proxy(this,null);else if((N&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,w._value());else if((N&16777216)!==0)$._async.invoke(this._promiseRejected,this,w._reason());else this._promiseCancelled()}},$.coroutine=function(V,F){if(typeof V!=="function")throw new K(`generatorFunctionmustbeafunction
Seehttp://goo.gl/MqrFmX
`);var w=Object(F).yieldHandler,O=q,N=Error().stack;return function(){var M=V.apply(this,arguments),D=new O(void 0,void 0,w,N),P=D.promise();return D._generator=M,D._promiseFulfilled(void 0),P}},$.coroutine.addYieldHandler=function(V){if(typeof V!=="function")throw new K("expecting a function but got "+G.classString(V));X.push(V)},$.spawn=function(V){if(J.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return Y(`generatorFunctionmustbeafunction
`);var M=Object(F).yieldHandler,w=q,N=Error().stack;return function(){var O=V.apply(this,arguments),D=new w(void 0,void 0,M,N),P=D.promise();return D._generator=O,D._promiseFulfilled(void 0),P}},$.coroutine.addYieldHandler=function(V){if(typeof V!=="function")throw new K("expecting a function but got "+G.classString(V));X.push(V)},$.spawn=function(V){if(Q.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return U(`generatorFunctionmustbeafunction
`)},Y=function(){return new S.PromiseInspection(this._target())},z=function(x){return S.reject(new X(x))};function U(){}var Q={},J=O4(),I;if(J.isNode)I=function(){var x=process.domain;if(x===void 0)x=null;return x};else I=function(){return null};J.notEnumerableProp(S,"_getDomain",I);var K=az(),G=oF0(),H=new G;K.defineProperty(S,"_async",{value:H});var W=E3(),X=S.TypeError=W.TypeError;S.RangeError=W.RangeError;var Z=S.CancellationError=W.CancellationError;S.TimeoutError=W.TimeoutError,S.OperationalError=W.OperationalError,S.RejectionError=W.OperationalError,S.AggregateError=W.AggregateError;var q=function(){},V={},F={},w=eF0()(S,q),O=YO0()(S,q,w,z,U),N=UO0()(S),M=N.create,D=JO0()(S,N),P=D.CapturedTrace,j=KO0()(S,w),A=HO0()(F),T=Mn(),C=J.errorObj,b=J.tryCatch;function k(x,d){if(typeof d!=="function")throw new X("expecting a function but got "+J.classString(d));if(x.constructor!==S)throw new X(`thepromiseconstructorcannotbeinvokeddirectly
`)},U=function(){return new g.PromiseInspection(this._target())},Y=function(k){return g.reject(new X(k))};function z(){}var I={},Q=F4(),J;if(Q.isNode)J=function(){var k=process.domain;if(k===void 0)k=null;return k};else J=function(){return null};Q.notEnumerableProp(g,"_getDomain",J);var K=aY(),G=QF0(),H=new G;K.defineProperty(g,"_async",{value:H});var W=_3(),X=g.TypeError=W.TypeError;g.RangeError=W.RangeError;var Z=g.CancellationError=W.CancellationError;g.TimeoutError=W.TimeoutError,g.OperationalError=W.OperationalError,g.RejectionError=W.OperationalError,g.AggregateError=W.AggregateError;var q=function(){},V={},F={},M=WF0()(g,q),w=ZF0()(g,q,M,Y,z),N=VF0()(g),O=N.create,D=wF0()(g,N),P=D.CapturedTrace,T=MF0()(g,M),A=NF0()(F),j=Sn(),C=Q.errorObj,b=Q.tryCatch;function x(k,p){if(typeof p!=="function")throw new X("expecting a function but got "+Q.classString(p));if(k.constructor!==g)throw new X(`thepromiseconstructorcannotbeinvokeddirectly
Seehttp://goo.gl/MqrFmX
`)}function S(x){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,x!==q)k(this,x),this._resolveFromExecutor(x);this._promiseCreated(),this._fireEvent("promiseCreated",this)}S.prototype.toString=function(){return"[object Promise]"},S.prototype.caught=S.prototype.catch=function(x){var d=arguments.length;if(d>1){var t=Array(d-1),e=0,g;for(g=0;g<d-1;++g){var p=arguments[g];if(J.isObject(p))t[e++]=p;else return z("expecting an object but got A catch statement predicate "+J.classString(p))}return t.length=e,x=arguments[g],this.then(void 0,A(t,x,this))}return this.then(void 0,x)},S.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},S.prototype.then=function(x,d){if(D.warnings()&&arguments.length>0&&typeof x!=="function"&&typeof d!=="function"){var t=".then() only accepts functions but was passed: "+J.classString(x);if(arguments.length>1)t+=", "+J.classString(d);this._warn(t)}return this._then(x,d,void 0,void 0,void 0)},S.prototype.done=function(x,d){var t=this._then(x,d,void 0,void 0,void 0);t._setIsFinal()},S.prototype.spread=function(x){if(typeof x!=="function")return z("expecting a function but got "+J.classString(x));return this.all()._then(x,void 0,void 0,V,void 0)},S.prototype.toJSON=function(){var x={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())x.fulfillmentValue=this.value(),x.isFulfilled=!0;else if(this.isRejected())x.rejectionReason=this.reason(),x.isRejected=!0;return x},S.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new O(this).promise()},S.prototype.error=function(x){return this.caught(J.originatesFromRejection,x)},S.getNewLibraryCopy=Dn.exports,S.is=function(x){return x instanceof S},S.fromNode=S.fromCallback=function(x){var d=new S(q);d._captureStackTrace();var t=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,e=b(x)(T(d,t));if(e===C)d._rejectCallback(e.e,!0);if(!d._isFateSealed())d._setAsyncGuaranteed();return d},S.all=function(x){return new O(x).promise()},S.cast=function(x){var d=w(x);if(!(d instanceof S))d=new S(q),d._captureStackTrace(),d._setFulfilled(),d._rejectionHandler0=x;return d},S.resolve=S.fulfilled=S.cast,S.reject=S.rejected=function(x){var d=new S(q);return d._captureStackTrace(),d._rejectCallback(x,!0),d},S.setScheduler=function(x){if(typeof x!=="function")throw new X("expecting a function but got "+J.classString(x));return H.setScheduler(x)},S.prototype._then=function(x,d,t,e,g){var p=g!==void 0,Y0=p?g:new S(q),y=this._target(),r=y._bitField;if(!p){if(Y0._propagateFrom(this,3),Y0._captureStackTrace(),e===void 0&&(this._bitField&2097152)!==0)if((r&50397184)!==0)e=this._boundValue();else e=y===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,Y0)}var $0=I();if((r&50397184)!==0){var N0,T0,_0=y._settlePromiseCtx;if((r&33554432)!==0)T0=y._rejectionHandler0,N0=x;else if((r&16777216)!==0)T0=y._fulfillmentHandler0,N0=d,y._unsetRejectionIsUnhandled();else _0=y._settlePromiseLateCancellationObserver,T0=new Z("late cancellation observer"),y._attachExtraTrace(T0),N0=d;H.invoke(_0,y,{handler:$0===null?N0:typeof N0==="function"&&J.domainBind($0,N0),promise:Y0,receiver:e,value:T0})}else y._addCallbacks(x,d,Y0,e,$0);return Y0},S.prototype._length=function(){return this._bitField&65535},S.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},S.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},S.prototype._setLength=function(x){this._bitField=this._bitField&-65536|x&65535},S.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},S.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},S.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},S.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},S.prototype._isFinal=function(){return(this._bitField&4194304)>0},S.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},S.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},S.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},S.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},S.prototype._receiverAt=function(x){var d=x===0?this._receiver0:this[x*4-4+3];if(d===Q)return;else if(d===void 0&&this._isBound())return this._boundValue();return d},S.prototype._promiseAt=function(x){return this[x*4-4+2]},S.prototype._fulfillmentHandlerAt=function(x){return this[x*4-4+0]},S.prototype._rejectionHandlerAt=function(x){return this[x*4-4+1]},S.prototype._boundValue=function(){},S.prototype._migrateCallback0=function(x){var{_bitField:d,_fulfillmentHandler0:t,_
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(Q.isObject(d))a[$0++]=d;else return Y("expecting an object but got A catch statement predicate "+Q.classString(d))}return a.length=$0,k=arguments[y],this.then(void 0,A(a,k,this))}return this.then(void 0,k)},g.prototype.reflect=function(){return this._then(U,U,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: "+Q.classString(k);if(arguments.length>1)a+=", "+Q.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 Y("expecting a function but got "+Q.classString(k));return this.all()._then(k,void 0,void 0,V,void 0)},g.prototype.toJSON=function(){var k={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())k.fulfillmentValue=this.value(),k.isFulfilled=!0;else if(this.isRejected())k.rejectionReason=this.reason(),k.isRejected=!0;return k},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new w(this).promise()},g.prototype.error=function(k){return this.caught(Q.originatesFromRejection,k)},g.getNewLibraryCopy=yn.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)(j(p,a));if($0===C)p._rejectCallback($0.e,!0);if(!p._isFateSealed())p._setAsyncGuaranteed();return p},g.all=function(k){return new w(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 "+Q.classString(k));return H.setScheduler(k)},g.prototype._then=function(k,p,a,$0,y){var d=y!==void 0,U0=d?y:new g(q),R=this._target(),o=R._bitField;if(!d){if(U0._propagateFrom(this,3),U0._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,U0)}var e=J();if((o&50397184)!==0){var O0,T0,y0=R._settlePromiseCtx;if((o&33554432)!==0)T0=R._rejectionHandler0,O0=k;else if((o&16777216)!==0)T0=R._fulfillmentHandler0,O0=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"&&Q.domainBind(e,O0),promise:U0,receiver:$0,value:T0})}else R._addCallbacks(k,p,U0,$0,e);return U0},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===I)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 Vp($){let Y=hA0();for(let z of Y){if(!L$(z))continue;for(let U of dB(z).filter((Q)=>Q.endsWith(".json")).filter((Q)=>!Q.startsWith("example."))){let Q=P9(z,U);try{let J=lB(Q,"utf-8"),I=JSON.parse(J);if(I&&typeof I==="object"&&I.id===$)return Q}catch{}}}return}function y3($,Y){let z=Vp($);if(!z)throw Error(`Enterpriseconfignotfound:${$}`);let Q={...JSON.parse(lB(z,"utf-8")),...Y};for(let I of Object.keys(Y))if(Y[I]===void 0)delete Q[I];let J=Wp.parse(Q);return TA0(z,`${JSON.stringify(J,null,2)}
`,"utf-8"),J}var Zp="SEAL_USE_ENTERPRISES_DIR",EA0="SEAL_HOME_ENTERPRISES_DIR",CA0="SEAL_USE_USER_ENTERPRISES_DIR",RA0="SEAL_HOME_USER_ENTERPRISES_DIR",_A0="SEAL_USE_CONFIG_FILE",vA0="SEAL_HOME_CONFIG_FILE",YK,mB,pB,PA0;var k3=m(()=>{Xp();YK=P9(oB(),".config","seal-use","enterprises"),mB=P9(oB(),".config","seal-home","enterprises"),pB=P9(oB(),".config","seal-use","config.json"),PA0=P9(oB(),".config","seal-home","config.json")});function n2($,Y,z=[]){let U=Y.corpId?.trim()||void 0,Q=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,J=U??Q;if(J){let K=$.find((W)=>W.id===J);if(K)return K;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 I=$[0];if(I)return I;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(z.length?z.join(", "):"the configured enterprise directories"))}import{existsSync as Lp,mkdirSync as wD1,readFileSync as MD1,renameSync as ND1,unlinkSync as DD1,writeFileSync as AD1}from"node:fs";import{homedir as BD1}from"node:os";import{dirname as PD1,join as jD1}from"node:path";function vZ(){let $=process.env[TD1]?.trim();if($)return $;return ED1}function SA0($=new Date){return $.toISOString().slice(0,10)}function gA0($=Fp,Y=new Date){let z=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(z).toISOString().slice(0,10)}function yA0($=vZ()){if(!Lp($))return{};try{let Y=MD1($,"utf-8"),z=JSON.parse(Y);if(z&&typeof z==="object"&&!Array.isArray(z))return z;return{}}catch{return{}}}function CD1($,Y){let z={};for(let[U,Q]of Object.entries($)){if(!Q||typeof Q!=="object")continue;let J={},I=!1;for(let[K,G]of Object.entries(Q))if(typeof G==="number"&&G>0&&K>=Y)J[K]=G,I=!0;if(I)z[U]=J}return z}function RD1($,Y=vZ()){let z=PD1(Y);if(!Lp(z))wD1(z,{recursive:!0,mode:448});let U=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{AD1(U,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),ND1(U,Y)}catch(Q){try{if(Lp(U))DD1(U)}catch{}throw Q}}function kA0($,Y=new Date){if(!$||typeof $!=="string")return;try{let z=vZ(),U=yA0(z),Q=SA0(Y),J=gA0(Fp,Y),I=CD1(U,J);I[$]=I[$]||{},I[$][Q]=(I[$][Q]??0)+1,RD1(I,z)}catch{}}function _D1($,Y=Fp,z=new Date){let U=new Map;try{let Q=yA0(),J=gA0(Y,z),I=SA0(z),K=$??Object.keys(Q);for(let G of K){let H=Q[G];if(!H){U.set(G,0);continue}let W=0;for(let[X,Z]of Object.entries(H))if(X>=J&&X<=I&&typeof Z==="number")W+=Z;U.set(G,W)}}catch{if($)for(let Q of $)U.set(Q,0)}return U}function xA0($,Y,z){let U=z??_D1($.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 I=U.get(Q.id)??0,K=U.get(J.id)??0;if(I!==K)return K-I;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 TD1="SEAL_USE_USAGE_FILE",ED1,Fp=7;var rB=m(()=>{ED1=jD1(BD1(),".config","seal-use","usage.json")});function vD1($,Y){return $.map((z)=>z.trim()).filter(Boolean).map((z)=>Y?z:z.toLowerCase())}function hD1($,Y){return Y?$:$.toLowerCase()}function SD1($,Y,z,U){let Q=hD1($,U),J=Y.filter((I)=>Q.includes(I));if(z==="all"&&J.length!==Y.length)return[];return J}function gD1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function yD1($,Y){if(Y.fields&&!Y.fields.has($.field))return[];let z=gD1($.value),U=[];return z.forEach((Q,J)=>{let I=SD1(Q,Y.keywords,Y.matchMode,Y.caseSensitive);if(I.length===0)return;let K=Math.max(0,J-Y.contextLines),G=Math.min(z.length,J+Y.contextLines+1),H={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:J+1,matchedKeywords:I,matchedText:sB(Q,Y.maxChars),context:{before:Y.snippetOnly?[]:z.slice(K,J).map((W)=>sB(W,Y.maxChars)),line:sB(Q,Y.maxChars),after:Y.snippetOnly?[]:z.slice(J+1,G).map((W)=>sB(W,Y.maxChars))},metadata:$.metadata};if(Y.snippetOnly)H.context={before:[],line:H.context.line,after:[]};U.push(H)}),U}function sB($,Y){if(!Y||$.length<=Y)return $;return`${$.slice(0,Math.max(0,Y))}...`}function kD1($){return[{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"description",value:$.description,metadata:{scope:$.scope,strictness:$.strictness,status:$.status}},{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"scope",value:$.scope,metadata:{strictness:$.strictness,status:$.status}}]}function uA0($){return $.rules.flatMap((Y,z)=>{let U=`${$.id}:${Y.description.slice(0,32)}`,Q={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:Y.scope,strictness:Y.strictness,code:"code"in Y?Y.code:void 0,index:z};return[{area:"rules",entityType:"rule",entityId:U,title:`${$.versionName}/${Y.scope}`,field:"hi
Line truncated
`)}function pA0($){return{id:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt}}function dA0($,Y){let z=new Map;for(let U of $.rules){let Q=hZ(U),J=Y==="stable-id"?lA0(Q):SZ(Q.code??Q.ruleCode);if(!J)throw Error(`Ruleversion${$.versionNumber}containsarulewithouta${Y==="stable-id"?"stable rule ID":"code"}.`);if(z.has(J))throw Error(`Ruleversion${$.versionNumber}containsduplicate${Y==="stable-id"?"stable rule ID":"code"}:${J}`);z.set(J,Q)}return z}function dD1($,Y,z){if(z!=="auto")return z;if([...$.rules,...Y.rules].every((J)=>Boolean(lA0(J))))return"stable-id";if([...$.rules,...Y.rules].every((J)=>Boolean(SZ(hZ(J).code??hZ(J).ruleCode))))return"code";throw Error("Rule snapshots have neither a complete stable-ID mapping nor a complete code mapping.")}function oA0($,Y,z={}){let U=dD1($,Y,z.identityMode??"auto"),Q=dA0($,U),J=dA0(Y,U),I=[...new Set([...Q.keys(),...J.keys()])],K=[],G={added:0,removed:0,modified:0,unchanged:0},H=pA0($),W=pA0(Y);for(let Z of I){let q=Q.get(Z),V=J.get(Z),F=q?VU(q,U):void 0,w=V?VU(V,U):void 0,O=!q?"added":!V?"removed":JSON.stringify(F)!==JSON.stringify(w)?"modified":"unchanged";if(G[O]+=1,O==="unchanged"&&!z.includeUnchanged)continue;let N=O==="modified"?[...new Set([...Object.keys(F??{}),...Object.keys(w??{})])].filter((M)=>JSON.stringify(F?.[M])!==JSON.stringify(w?.[M])):void 0;K.push({status:O,ruleId:Z,identityMode:U,...q?{before:q}:{},...V?{after:V}:{},...N?.length?{changedFields:N}:{},...O!=="unchanged"?{diff:pD1(Z,H,W,q,V,U)}:{}})}let X={from:H,to:W,identityMode:U,counts:G,changes:K,unifiedDiff:K.filter((Z)=>Z.diff).map((Z)=>Z.diff).join(`
`)};if(U==="code"){let Z=I.filter((P)=>Q.has(P)&&J.has(P)).length,q=I.filter((P)=>Q.has(P)&&J.has(P)&&JSON.stringify(VU(Q.get(P),"code"))===JSON.stringify(VU(J.get(P),"code"))).length,V=Q.size,F=J.size,w=Math.min(V,F)?Z/Math.min(V,F):1,O=new Map;for(let[P,j]of Q)O.set(JSON.stringify(VU(j,"code")),P);let N=0;for(let[P,j]of J){let A=O.get(JSON.stringify(VU(j,"code")));if(A&&A!==P)N+=1}let D=(Math.min(V,F)?q/Math.min(V,F):1)>=0.5?"high":q>0||N>0?"ambiguous":"low";X.codeStats={oldCount:V,newCount:F,sameCodeCount:Z,sameCodeUnchanged:q,sameBodyDifferentCode:N,overlapRatio:w,confidence:D,warning:"Published snapshots do not carry stable IDs; code matching can report reorderings as remove/add or modified rules."}}return X}function wp($,Y=20000,z=!1){if(z||$.unifiedDiff.length<=Y)return{...$,truncation:{truncated:!1,maxChars:Y,omittedChars:0,hint:"Use --full only when the complete diff is required."}};let U=$.unifiedDiff.length-Y,Q=`
...[difftruncated:${U}charactersomitted;rerunwith--fullforthecompletediff]`,J=$.changes.map(({before:I,after:K,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:U,hint:"Use --full for the complete diff."}}}var mA0,nD1;var rA0=m(()=>{mA0=["id","ruleId","stableId"],nD1=new Set([...mA0,"runtimeRuleId","runtimeId","tenantId","createdAt","updatedAt","versionId","versionNumber"])});import{existsSync as mD1,mkdirSync as lD1,readFileSync as oD1,renameSync as rD1,writeFileSync as sD1}from"node:fs";import{homedir as aD1}from"node:os";import{join as sA0}from"node:path";function gZ($){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 aB($){return JSON.stringify([$.description??"",$.scope??"",$.strictness??""])}function aA0(){return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim()||sA0(aD1(),".config","seal-use","rule-version-snapshots")}function tD1($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function tA0($,Y){return sA0(aA0(),`${tD1($)}-v${Y}.json`)}function yZ($,Y,z){let U=new Map,Q=new Map;for(let W of z){let X=gZ(W.code);if(X)U.set(X,[...U.get(X)??[],W]);let Z=aB(W);Q.set(Z,[...Q.get(Z)??[],W])}let J=[];for(let W of Y.rules??[]){let X=gZ(W.code),Z=X?U.get(X)??[]:[],q=Q.get(aB(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 I={corpId:$,versionId:Y.id,versionNumber:Y.versionNumber,capturedAt:new Date().toISOString(),rules:J},K=aA0();lD1(K,{recursive:!0,mode:448});let G=tA0($,Y.versionNumber),H=`${G}.${process.pid}.tmp`;return sD1(H,`${JSON.stringify(I,null,2)}
`,{mode:384}),U}function Td($){let U=dA0();for(let Y of U){if(!w$(Y))continue;for(let z of tB(Y).filter((I)=>I.endsWith(".json")).filter((I)=>!I.startsWith("example."))){let I=j9(Y,z);try{let Q=$P(I,"utf-8"),J=JSON.parse(Q);if(J&&typeof J==="object"&&J.id===$)return I}catch{}}}return}function E9($,U){let Y=Td($);if(!Y)throw Error(`Enterpriseconfignotfound:${$}`);let I={...JSON.parse($P(Y,"utf-8")),...U};for(let J of Object.keys(U))if(U[J]===void 0)delete I[J];let Q=hZ.parse(I);return fA0(Y,`${JSON.stringify(Q,null,2)}
`,"utf-8"),Q}var Pd="SEAL_USE_ENTERPRISES_DIR",uA0="SEAL_HOME_ENTERPRISES_DIR",bA0="SEAL_USE_USER_ENTERPRISES_DIR",iA0="SEAL_HOME_USER_ENTERPRISES_DIR",nA0="SEAL_USE_CONFIG_FILE",cA0="SEAL_HOME_CONFIG_FILE",YK,eB,aB,kA0;var T5=m(()=>{sB();YK=j9(UP(),".config","seal-use","enterprises"),eB=j9(UP(),".config","seal-home","enterprises"),aB=j9(UP(),".config","seal-use","config.json"),kA0=j9(UP(),".config","seal-home","config.json")});function c2($,U,Y=[]){let z=U.corpId?.trim()||void 0,I=U.stateful?U.defaultCorpId?.trim()||void 0:void 0,Q=z??I;if(Q){let K=$.find((W)=>W.id===Q);if(K)return K;let G=$.find((W)=>W.id.toLowerCase()===Q.toLowerCase());if(G)return G;let H=$.find((W)=>W.name.toLowerCase()===Q.toLowerCase());if(H)return H;throw Error(`Noenterpriseconfigfoundfor${Q}`)}if(!U.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-useconfigmodestateful` to enable a default enterprise.");let J=$[0];if(J)return J;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(Y.length?Y.join(", "):"the configured enterprise directories"))}import{existsSync as jd,mkdirSync as pD1,readFileSync as mD1,renameSync as lD1,unlinkSync as oD1,writeFileSync as rD1}from"node:fs";import{homedir as sD1}from"node:os";import{dirname as aD1,join as tD1}from"node:path";function gZ(){let $=process.env[eD1]?.trim();if($)return $;return $A1}function mA0($=new Date){return $.toISOString().slice(0,10)}function lA0($=Ed,U=new Date){let Y=U.getTime()-Math.max(0,$-1)*86400000;return new Date(Y).toISOString().slice(0,10)}function oA0($=gZ()){if(!jd($))return{};try{let U=mD1($,"utf-8"),Y=JSON.parse(U);if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y;return{}}catch{return{}}}function UA1($,U){let Y={};for(let[z,I]of Object.entries($)){if(!I||typeof I!=="object")continue;let Q={},J=!1;for(let[K,G]of Object.entries(I))if(typeof G==="number"&&G>0&&K>=U)Q[K]=G,J=!0;if(J)Y[z]=Q}return Y}function YA1($,U=gZ()){let Y=aD1(U);if(!jd(Y))pD1(Y,{recursive:!0,mode:448});let z=`${U}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{rD1(z,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),lD1(z,U)}catch(I){try{if(jd(z))oD1(z)}catch{}throw I}}function rA0($,U=new Date){if(!$||typeof $!=="string")return;try{let Y=gZ(),z=oA0(Y),I=mA0(U),Q=lA0(Ed,U),J=UA1(z,Q);J[$]=J[$]||{},J[$][I]=(J[$][I]??0)+1,YA1(J,Y)}catch{}}function zA1($,U=Ed,Y=new Date){let z=new Map;try{let I=oA0(),Q=lA0(U,Y),J=mA0(Y),K=$??Object.keys(I);for(let G of K){let H=I[G];if(!H){z.set(G,0);continue}let W=0;for(let[X,Z]of Object.entries(H))if(X>=Q&&X<=J&&typeof Z==="number")W+=Z;z.set(G,W)}}catch{if($)for(let I of $)z.set(I,0)}return z}function sA0($,U,Y){let z=Y??zA1($.map((I)=>I.id));return[...$].sort((I,Q)=>{if(U){if(I.id===U&&Q.id!==U)return-1;if(Q.id===U&&I.id!==U)return 1}let J=z.get(I.id)??0,K=z.get(Q.id)??0;if(J!==K)return K-J;let G=I.name??I.id,H=Q.name??Q.id,W=G.localeCompare(H,"zh-CN");if(W!==0)return W;return I.id.localeCompare(Q.id)})}var eD1="SEAL_USE_USAGE_FILE",$A1,Ed=7;var YP=m(()=>{$A1=tD1(sD1(),".config","seal-use","usage.json")});function IA1($,U){return $.map((Y)=>Y.trim()).filter(Boolean).map((Y)=>U?Y:Y.toLowerCase())}function QA1($,U){return U?$:$.toLowerCase()}function JA1($,U,Y,z){let I=QA1($,z),Q=U.filter((J)=>I.includes(J));if(Y==="all"&&Q.length!==U.length)return[];return Q}function KA1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function GA1($,U){if(U.fields&&!U.fields.has($.field))return[];let Y=KA1($.value),z=[];return Y.forEach((I,Q)=>{let J=JA1(I,U.keywords,U.matchMode,U.caseSensitive);if(J.length===0)return;let K=Math.max(0,Q-U.contextLines),G=Math.min(Y.length,Q+U.contextLines+1),H={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Q+1,matchedKeywords:J,matchedText:zP(I,U.maxChars),context:{before:U.snippetOnly?[]:Y.slice(K,Q).map((W)=>zP(W,U.maxChars)),line:zP(I,U.maxChars),after:U.snippetOnly?[]:Y.slice(Q+1,G).map((W)=>zP(W,U.maxChars))},metadata:$.metadata};if(U.snippetOnly)H.context={before:[],line:H.context.line,after:[]};z.push(H)}),z}function zP($,U){if(!U||$.length<=U)return $;return`${$.slice(0,Math.max(0,U))}...`}function HA1($){return[{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"description",value:$.description,metadata:{scope:$.scope,strictness:$.strictness,status:$.status}},{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"scope",value:$.scope,metadata:{strictness:$.strictness,status:$.status}}]}function tA0($){return $.rules.flatMap((U,Y)=>{let z=`${$.id}:${U.description.slice(0,32)}`,I={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:U.scope,strictness:U.strictness,code:"code"in U?U.code:void 0,index:Y};return[{area:"rules",entityType:"rule",entityId:z,title:`${$.versionName}/${U.scope}`,field:"hi
Line truncated
`)}function zB0($){return{id:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt}}function IB0($,U){let Y=new Map;for(let z of $.rules){let I=yZ(z),Q=U==="stable-id"?JB0(I):kZ(I.code??I.ruleCode);if(!Q)throw Error(`Ruleversion${$.versionNumber}containsarulewithouta${U==="stable-id"?"stable rule ID":"code"}.`);if(Y.has(Q))throw Error(`Ruleversion${$.versionNumber}containsduplicate${U==="stable-id"?"stable rule ID":"code"}:${Q}`);Y.set(Q,I)}return Y}function MA1($,U,Y){if(Y!=="auto")return Y;if([...$.rules,...U.rules].every((Q)=>Boolean(JB0(Q))))return"stable-id";if([...$.rules,...U.rules].every((Q)=>Boolean(kZ(yZ(Q).code??yZ(Q).ruleCode))))return"code";throw Error("Rule snapshots have neither a complete stable-ID mapping nor a complete code mapping.")}function KB0($,U,Y={}){let z=MA1($,U,Y.identityMode??"auto"),I=IB0($,z),Q=IB0(U,z),J=[...new Set([...I.keys(),...Q.keys()])],K=[],G={added:0,removed:0,modified:0,unchanged:0},H=zB0($),W=zB0(U);for(let Z of J){let q=I.get(Z),V=Q.get(Z),F=q?Vz(q,z):void 0,M=V?Vz(V,z):void 0,w=!q?"added":!V?"removed":JSON.stringify(F)!==JSON.stringify(M)?"modified":"unchanged";if(G[w]+=1,w==="unchanged"&&!Y.includeUnchanged)continue;let N=w==="modified"?[...new Set([...Object.keys(F??{}),...Object.keys(M??{})])].filter((O)=>JSON.stringify(F?.[O])!==JSON.stringify(M?.[O])):void 0;K.push({status:w,ruleId:Z,identityMode:z,...q?{before:q}:{},...V?{after:V}:{},...N?.length?{changedFields:N}:{},...w!=="unchanged"?{diff:FA1(Z,H,W,q,V,z)}:{}})}let X={from:H,to:W,identityMode:z,counts:G,changes:K,unifiedDiff:K.filter((Z)=>Z.diff).map((Z)=>Z.diff).join(`
`)};if(z==="code"){let Z=J.filter((P)=>I.has(P)&&Q.has(P)).length,q=J.filter((P)=>I.has(P)&&Q.has(P)&&JSON.stringify(Vz(I.get(P),"code"))===JSON.stringify(Vz(Q.get(P),"code"))).length,V=I.size,F=Q.size,M=Math.min(V,F)?Z/Math.min(V,F):1,w=new Map;for(let[P,T]of I)w.set(JSON.stringify(Vz(T,"code")),P);let N=0;for(let[P,T]of Q){let A=w.get(JSON.stringify(Vz(T,"code")));if(A&&A!==P)N+=1}let D=(Math.min(V,F)?q/Math.min(V,F):1)>=0.5?"high":q>0||N>0?"ambiguous":"low";X.codeStats={oldCount:V,newCount:F,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($,U=20000,Y=!1){if(Y||$.unifiedDiff.length<=U)return{...$,truncation:{truncated:!1,maxChars:U,omittedChars:0,hint:"Use --full only when the complete diff is required."}};let z=$.unifiedDiff.length-U,I=`
...[difftruncated:${z}charactersomitted;rerunwith--fullforthecompletediff]`,Q=$.changes.map(({before:J,after:K,diff:G,...H})=>({...H,...G?{diff:G.length>U?`${G.slice(0,U)}${I}`:G}:{}}));return{...$,changes:Q,unifiedDiff:`${$.unifiedDiff.slice(0,U)}${I}`,truncation:{truncated:!0,maxChars:U,omittedChars:z,hint:"Use --full for the complete diff."}}}var QB0,LA1;var GB0=m(()=>{QB0=["id","ruleId","stableId"],LA1=new Set([...QB0,"runtimeRuleId","runtimeId","tenantId","createdAt","updatedAt","versionId","versionNumber"])});import{existsSync as OA1,mkdirSync as NA1,readFileSync as DA1,renameSync as AA1,writeFileSync as BA1}from"node:fs";import{homedir as PA1}from"node:os";import{join as HB0}from"node:path";function xZ($){if($===void 0||$===null)return;let U=String($).trim().toLowerCase().replace(/^rule[-_:]?/,"").replace(/^#/,"");if(!U)return;return/^\d+$/.test(U)?String(Number(U)):U}function IP($){return JSON.stringify([$.description??"",$.scope??"",$.strictness??""])}function WB0(){return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim()||HB0(PA1(),".config","seal-use","rule-version-snapshots")}function TA1($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function XB0($,U){return HB0(WB0(),`${TA1($)}-v${U}.json`)}function fZ($,U,Y){let z=new Map,I=new Map;for(let W of Y){let X=xZ(W.code);if(X)z.set(X,[...z.get(X)??[],W]);let Z=IP(W);I.set(Z,[...I.get(Z)??[],W])}let Q=[];for(let W of U.rules??[]){let X=xZ(W.code),Z=X?z.get(X)??[]:[],q=I.get(IP(W))??[],V=Z.length===1?Z[0]:q.length===1?q[0]:void 0;if(!V)continue;Q.push({stableId:V.id,...W.code!==void 0?{code:W.code}:{},description:W.description,scope:W.scope,strictness:W.strictness})}let J={corpId:$,versionId:U.id,versionNumber:U.versionNumber,capturedAt:new Date().toISOString(),rules:Q},K=WB0();NA1(K,{recursive:!0,mode:448});let G=XB0($,U.versionNumber),H=`${G}.${process.pid}.tmp`;return BA1(H,`${JSON.stringify(J,null,2)}
@@ -881,68 +881,65 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
}
exportdefaultlintRule;
`}});import{existsSync as LU,mkdirSync as NA1,readFileSync as DA1,readdirSync as KB0,rmSync as AA1,unlinkSync as BA1,writeFileSync as PA1}from"node:fs";import{homedir as jA1}from"node:os";import{isAbsolute as TA1,join as b6,resolve as EA1}from"node:path";import{pathToFileURL as JB0}from"node:url";function GB0($=n$){let Y=[],z=[];try{if(!LU($))NA1($,{recursive:!0});let U=Object.keys(Ep);for(let[J,I]of Object.entries(Ep)){let K=b6($,J),G=!0;if(LU(K))try{if(DA1(K,"utf8")===I)G=!1}catch{G=!0}if(G)PA1(K,I,"utf8");Y.push(J)}let Q=KB0($,{withFileTypes:!0});for(let J of Q)if(!U.includes(J.name)){let I=b6($,J.name);try{if(J.isDirectory())AA1(I,{recursive:!0,force:!0});else BA1(I);z.push(J.name)}catch{}}}catch{}return{synced:Y,pruned:z}}function HB0($={syncOfficial:!0}){if($.syncOfficial!==!1)GB0();let Y=[{name:"builtin",type:"builtin",path:b6(n$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:b6(n$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:b6(n$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],z=[i$,YP];for(let U of z)if(LU(U))try{let Q=KB0(U,{withFileTypes:!0});for(let J of Q){if(J.isDirectory())continue;let I=J.name;if(I.endsWith(".ts")||I.endsWith(".js")||I.endsWith(".mjs")){let K=I.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((G)=>G.name===K))Y.push({name:K,type:"custom",path:b6(U,I),description:`用户自定义规则校验器(${I})`})}}}catch{}return Y}function RA1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:b6(n$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:b6(n$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(Y==="hlab"||Y==="hlab-sop"||Y==="hlab-rules"||Y==="hlab-standard"||Y==="official/hlab"||Y==="official/hlab.ts")return{path:b6(n$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(TA1(Y)||Y.startsWith("./")||Y.startsWith("../")){let U=EA1(Y);if(LU(U))return{path:U};for(let Q of[".ts",".js",".mjs"])if(LU(`${U}${Q}`))return{path:`${U}${Q}`}}let z=[b6(i$,`${Y}.ts`),b6(i$,`${Y}.js`),b6(i$,`${Y}.mjs`),b6(YP,`${Y}.ts`),b6(YP,`${Y}.js`),b6(YP,`${Y}.mjs`)];for(let U of z)if(LU(U))return{path:U};return{}}async function Rp($){GB0();let Y=RA1($??"builtin");if(Y.isOfficial){let U=Y.officialKind==="strict"?UB0:Y.officialKind==="hlab"?QB0:UK,Q=Y.officialKind==="builtin"?"builtin":"official",J=Y.path;if(J&&LU(J))try{let K=await import(JB0(J).href),G=K.default??K.lintRule??K.linter??K.lint;if(typeof G==="function")return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:IB0(G,U)}}catch{}return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:U}}let z=Y.path;if(!z)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:UK};try{let Q=await import(JB0(z).href),J=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof J!=="function")return console.error(`⚠️[linter]自定义校验器"${z}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:UK};return{name:$??"custom",type:"custom",filePath:z,linter:IB0(J,UK)}}catch(U){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${z}"失败(语法错误或依赖缺失:${U?.message??U}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:UK}}}functionIB0($,Y){returnasync(z,U)=>{try{letQ=await$(z,U);if(Q&&typeofQ==="object"&&typeofQ.score==="number"&&Array.isArray(Q.issues))returnQ;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),Y(z,U)}catch(Q){returnconsole.error("⚠️[linter]自定义校验器执行异常:",Q),Y(z,U)}}}vari$,CA1="official",n$,YP;var_p=m(()=>{Pp();Tp();Cp();jp();i$=b6(jA1(),".config","seal-use","linters"),n$=b6(i$,CA1),YP=b6(process.cwd(),"linters")});asyncfunctionvp($,Y,z){letU=awaitY.linter($,z);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:U.score,passed:U.passed,issues:U.issues,description:$.description}}asyncfunctionWB0($,Y,z,U){letQ=U?.minScore??0,J=U?.level??"all",I=[],K=0;for(letqof$){letV=awaitvp(q,Y,z);K+=V.score;letF=V.issues;if(J==="error")F=V.issues.filter((O)=>O.level==="error");elseif(J==="warning")F=V.issues.filter((O)=>O.level==="warning"||O.level==="error");letw=F.every((O)=>O.level!=="error");if(U?.summary){if(F.length>0)I.push({...V,passed:w,issues:F})}elseI.push({...V,passed:w,issues:F})}letG=$.length,H=G===0?100:Math.round(K/G),W=I.filter((q)=>q.issues.length>0).length,X=G-Line truncated
`}});import{existsSync as Lz,mkdirSync as lA1,readFileSync as oA1,readdirSync as NB0,rmSync as rA1,unlinkSync as sA1,writeFileSync as aA1}from"node:fs";import{homedir as tA1}from"node:os";import{isAbsolute as eA1,join as b6,resolve as $B1}from"node:path";import{pathToFileURL as MB0}from"node:url";function DB0($=d$){let U=[],Y=[];try{if(!Lz($))lA1($,{recursive:!0});let z=Object.keys(fd);for(let[Q,J]of Object.entries(fd)){let K=b6($,Q),G=!0;if(Lz(K))try{if(oA1(K,"utf8")===J)G=!1}catch{G=!0}if(G)aA1(K,J,"utf8");U.push(Q)}let I=NB0($,{withFileTypes:!0});for(let Q of I)if(!z.includes(Q.name)){let J=b6($,Q.name);try{if(Q.isDirectory())rA1(J,{recursive:!0,force:!0});else sA1(J);Y.push(Q.name)}catch{}}}catch{}return{synced:U,pruned:Y}}function AB0($={syncOfficial:!0}){if($.syncOfficial!==!1)DB0();let U=[{name:"builtin",type:"builtin",path:b6(d$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:b6(d$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:b6(d$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],Y=[c$,GP];for(let z of Y)if(Lz(z))try{let I=NB0(z,{withFileTypes:!0});for(let Q of I){if(Q.isDirectory())continue;let J=Q.name;if(J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")){let K=J.replace(/\.(ts|js|mjs)$/,"");if(!U.some((G)=>G.name===K))U.push({name:K,type:"custom",path:b6(z,J),description:`用户自定义规则校验器(${J})`})}}}catch{}return U}function YB1($){let U=($||"").trim();if(!U||U==="builtin"||U==="default"||U==="official/builtin"||U==="official/builtin.ts")return{path:b6(d$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(U==="strict"||U==="official/strict"||U==="official/strict.ts")return{path:b6(d$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(U==="hlab"||U==="hlab-sop"||U==="hlab-rules"||U==="hlab-standard"||U==="official/hlab"||U==="official/hlab.ts")return{path:b6(d$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(eA1(U)||U.startsWith("./")||U.startsWith("../")){let z=$B1(U);if(Lz(z))return{path:z};for(let I of[".ts",".js",".mjs"])if(Lz(`${z}${I}`))return{path:`${z}${I}`}}let Y=[b6(c$,`${U}.ts`),b6(c$,`${U}.js`),b6(c$,`${U}.mjs`),b6(GP,`${U}.ts`),b6(GP,`${U}.js`),b6(GP,`${U}.mjs`)];for(let z of Y)if(Lz(z))return{path:z};return{}}async function bd($){DB0();let U=YB1($??"builtin");if(U.isOfficial){let z=U.officialKind==="strict"?wB0:U.officialKind==="hlab"?FB0:IK,I=U.officialKind==="builtin"?"builtin":"official",Q=U.path;if(Q&&Lz(Q))try{let K=await import(MB0(Q).href),G=K.default??K.lintRule??K.linter??K.lint;if(typeof G==="function")return{name:U.officialKind??"builtin",type:I,filePath:Q,linter:OB0(G,z)}}catch{}return{name:U.officialKind??"builtin",type:I,filePath:Q,linter:z}}let Y=U.path;if(!Y)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK};try{let I=await import(MB0(Y).href),Q=I.default??I.lintRule??I.linter??I.lint;if(typeof Q!=="function")return console.error(`⚠️[linter]自定义校验器"${Y}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK};return{name:$??"custom",type:"custom",filePath:Y,linter:OB0(Q,IK)}}catch(z){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${Y}"失败(语法错误或依赖缺失:${z?.message??z}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK}}}functionOB0($,U){returnasync(Y,z)=>{try{letI=await$(Y,z);if(I&&typeofI==="object"&&typeofI.score==="number"&&Array.isArray(I.issues))returnI;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),U(Y,z)}catch(I){returnconsole.error("⚠️[linter]自定义校验器执行异常:",I),U(Y,z)}}}varc$,UB1="official",d$,GP;varid=m(()=>{yd();xd();ud();kd();c$=b6(tA1(),".config","seal-use","linters"),d$=b6(c$,UB1),GP=b6(process.cwd(),"linters")});asyncfunctionnd($,U,Y){letz=awaitU.linter($,Y);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:z.score,passed:z.passed,issues:z.issues,description:$.description}}asyncfunctionBB0($,U,Y,z){letI=z?.minScore??0,Q=z?.level??"all",J=[],K=0;for(letqof$){letV=awaitnd(q,U,Y);K+=V.score;letF=V.issues;if(Q==="error")F=V.issues.filter((w)=>w.level==="error");elseif(Q==="warning")F=V.issues.filter((w)=>w.level==="warning"||w.level==="error");letM=F.every((w)=>w.level!=="error");if(z?.summary){if(F.length>0)J.push({...V,passed:M,issues:F})}elseJ.push({...V,passed:M,issues:F})}letG=$.length,H=G===0?100:Math.round(K/G),W=J.filter((q)=>q.issues.length>0).length,X=G-Line truncated
`),U=await Promise.all(M.map((D)=>H4($,D.id)))}let Q=new Map,J=0;for(let O of U){let N=O.document,M=O.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??O.documentId??O.id,D=`${z.docIdPrefix??""}${M}${z.docIdSuffix??""}`,P=[];if(z.includeAttachments!==!1){let A=i2(O,{summary:!1}).attachments,T=new Set;for(let C of A){let b=C.ossSignedUrl??C.url;if(!b)continue;let k=C.fileName??C.fileId??"attachment",S=Kp(k),i=S,n=S.lastIndexOf("."),U0=n>0?S.slice(0,n):S,x=n>0?S.slice(n):"",d=1;while(T.has(i.toLowerCase()))i=`${U0}_${d}${x}`,d++;T.add(i.toLowerCase());try{process.stderr.write(`⬇下载单据「${D}」附件:${k}...
`),await new Promise((O,N)=>{let M=QS1(V),D=new Bl({zlib:{level:9}});M.on("close",()=>O()),D.on("error",(P)=>N(P)),D.pipe(M),D.append(Buffer.from(F),{name:"信息表.xlsx"});for(let P of Q.values())for(let j of P)D.append(j.buffer,{name:j.zipPath});D.finalize()});let w=IS1(V);return{filePath:V,corpId:Y.id,corpName:Y.name,recordCount:U.length,attachmentCount:J,fileSizeBytes:w.size,exportedAt:new Date().toISOString(),nextAction:`seal-usewebhookresource-packpush${V}--corp<targetCorpId>`}}var L_0;var Pl=m(()=>{q_0();B6();nB();L_0=J6(CZ(),1)});import{readFileSync as XS1}from"node:fs";function ZS1($){let Y=new URL($),z=Y.pathname.match(/\/webhook\/([^/]+)/);if(!z)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:z[1]}}function qS1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function VS1($,Y){if(!$.length)return;let z=new Set($.map((J)=>{let I=J.fileName.split("/")[0],K=I.indexOf("@");return K>=0?I.slice(0,K):I}).filter((J)=>J!=="信息表.xlsx")),U=[];for(let J of Y){let I=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))&&!z.has(I))U.push(`Excel 会议编号「${I}」声明了附件,但在 ZIP 中找不到对应的根目录「${I}/」或「${I}@.../」。`)}let Q=new Set(Y.map((J)=>J.document.documentId));for(let J of z)if(!Q.has(J))U.push(`ZIP 根目录对应的编号「${J}」在信息表中找不到对应的会议编号。`);if(U.length)throw new B5(U)}async function F_0($,Y,z){let U=[],Q=$;if(qS1($,Y)){U=await TP0($),CP0(U,z);let G=U.find((H)=>H.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");Q=await Pd($,G)}let J=await yP0(Q);VS1(U,J);let I=kP0(U,J),K=J.map((G)=>G.document);return{entries:U,parsed:J,plans:I,documents:K,fileBuffer:$}}async function kU($,Y,z){let U=await F_0($,Y,z),Q=U.parsed.map((J,I)=>_d(J.document,U.plans[I],new Map));return{warnings:[],documents:Q,attachmentPlan:U.plans}}async function Zj($,Y,z){let U=await F_0($,Y,z.materialPackFilePolicy),{baseUrl:Q,webhookId:J}=ZS1(z.webhookUrl),I=[];for(let K=0;K<U.parsed.length;K+=1){let G=U.parsed[K],H=U.plans[K],W=new Map,X=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let V of X)for(let F of V.paths){if(W.has(F))continue;let w=U.entries.find((j)=>j.fileName===F);if(!w)continue;process.stderr.write(`⬆ 上传附件: ${F}
`),z=await Promise.all(O.map((D)=>H4($,D.id)))}let I=new Map,Q=0;for(let w of z){let N=w.document,O=w.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??w.documentId??w.id,D=`${Y.docIdPrefix??""}${O}${Y.docIdSuffix??""}`,P=[];if(Y.includeAttachments!==!1){let A=n2(w,{summary:!1}).attachments,j=new Set;for(let C of A){let b=C.ossSignedUrl??C.url;if(!b)continue;let x=C.fileName??C.fileId??"attachment",g=Dd(x),i=g,n=g.lastIndexOf("."),z0=n>0?g.slice(0,n):g,k=n>0?g.slice(n):"",p=1;while(j.has(i.toLowerCase()))i=`${z0}_${p}${k}`,p++;j.add(i.toLowerCase());try{process.stderr.write(`⬇下载单据「${D}」附件:${x}...
`),await new Promise((w,N)=>{let O=vS1(V),D=new gl({zlib:{level:9}});O.on("close",()=>w()),D.on("error",(P)=>N(P)),D.pipe(O),D.append(Buffer.from(F),{name:"信息表.xlsx"});for(let P of I.values())for(let T of P)D.append(T.buffer,{name:T.zipPath});D.finalize()});let M=SS1(V);return{filePath:V,corpId:U.id,corpName:U.name,recordCount:z.length,attachmentCount:Q,fileSizeBytes:M.size,exportedAt:new Date().toISOString(),nextAction:`seal-usewebhookresource-packpush${V}--corp<targetCorpId>`}}var C_0;var yl=m(()=>{j_0();X6();oB();C_0=I6(_Z(),1)});import{readFileSync as fS1}from"node:fs";function uS1($){let U=new URL($),Y=U.pathname.match(/\/webhook\/([^/]+)/);if(!Y)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${U.protocol}//${U.host}`,webhookId:Y[1]}}function bS1($,U){return U.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!U.toLowerCase().endsWith(".xlsx")}function iS1($,U){if(!$.length)return;let Y=new Set($.map((Q)=>{let J=Q.fileName.split("/")[0],K=J.indexOf("@");return K>=0?J.slice(0,K):J}).filter((Q)=>Q!=="信息表.xlsx")),z=[];for(let Q of U){let J=Q.document.documentId;if((Q.documentAttachments.length>0||Object.values(Q.expenseAttachments).some((G)=>G.length>0)||Object.values(Q.personAttachments).some((G)=>G.length>0))&&!Y.has(J))z.push(`Excel 会议编号「${J}」声明了附件,但在 ZIP 中找不到对应的根目录「${J}/」或「${J}@.../」。`)}let I=new Set(U.map((Q)=>Q.document.documentId));for(let Q of Y)if(!I.has(Q))z.push(`ZIP 根目录对应的编号「${Q}」在信息表中找不到对应的会议编号。`);if(z.length)throw new j5(z)}async function R_0($,U,Y){let z=[],I=$;if(bS1($,U)){z=await uP0($),iP0(z,Y);let G=z.find((H)=>H.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");I=await yp($,G)}let Q=await oP0(I);iS1(z,Q);let J=rP0(z,Q),K=Q.map((G)=>G.document);return{entries:z,parsed:Q,plans:J,documents:K,fileBuffer:$}}async function kz($,U,Y){let z=await R_0($,U,Y),I=z.parsed.map((Q,J)=>ip(Q.document,z.plans[J],new Map));return{warnings:[],documents:I,attachmentPlan:z.plans}}async function OT($,U,Y){let z=await R_0($,U,Y.materialPackFilePolicy),{baseUrl:I,webhookId:Q}=uS1(Y.webhookUrl),J=[];for(let K=0;K<z.parsed.length;K+=1){let G=z.parsed[K],H=z.plans[K],W=new Map,X=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let V of X)for(let F of V.paths){if(W.has(F))continue;let M=z.entries.find((T)=>T.fileName===F);if(!M)continue;process.stderr.write(`⬆ 上传附件: ${F}
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:W?I:Z?V:G,type:X,mode:Z?"auto_login":"direct",sealResultUrl:G,hoseDocumentUrl:I,documentUrl:I,ssoUrl:V,expiresIn:Z?q:void 0,identity:F,warning:w,hoseDomain:J.type==="hose"?pS1(J.domain):void 0,recordId:Q.id,sourceDocumentSN:Q.sourceDocumentSN,sourceDocumentId:Q.sourceDocumentId,sourceSystem:Q.sourceSystem,missing:{hoseDocumentUrl:!I?"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,z)=>{let U=Y.sn??Y.query;if(!U)throw Error("query or sn is required");let Q=await dS1($,{query:U,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)=>H4($,X.id))),I=A_0(Y.fields),K=J.map((X)=>iS1(X,I)),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:U,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:Q.total,scanned:Q.scanned,matched:K.length,records:K,next:{getSummary:`seal-useapproval-runsget<recordId>--summary--corp${z.corp.id}`,getRuleVersion:`seal-userulesversion${H}--corp${z.corp.id}`,searchRuleVersion:`seal-usetoolseal_approval_search--corp${z.corp.id}--json'{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${W}}'`,getVersionContext:`seal-usetoolseal_approval_context_get--corp${z.corp.id}--json'{${W}}'`},...Y.includeBridge?{bridge:wj(J)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:L.object({batchId:L.string().describe("simulation batch ID"),query:L.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,Y)=>{let z=yl(await Wg($,Y.batchId),Y.query);return{batchId:Y.batchId,count:z.length,records:z.map(fU),bridge:wj(z)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:L.object({mode:L.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:L.array(L.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:L.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:L.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:L.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:L.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:L.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:L.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:L.array(L.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:L.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:L.record(L.string(),L.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:L.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:L.record(L.string(),L.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,Y)=>{let z=Y.mode??"hosecloud",U=Y.signKey;if(z==="hosecloud"&&!U){if(U=(await Zg($)).find((K)=>K.signKey)?.signKey,!U)throw Error("
Line truncated
`)}function Yg1($){let Y=[];if(Y.push(`seal-use${$.area}-${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");let z=new Map;for(let Q of $.commands){let J=Q.group??"",I=z.get(J)??[];I.push(Q),z.set(J,I)}let U=[...$.groupOrder??[],...[...z.keys()].filter((Q)=>!$.groupOrder?.includes(Q))];for(let Q of U){let J=z.get(Q);if(!J)continue;if(Q)Y.push(""),Y.push(`${Q}:`);for(let I of J)for(let K of I.usage)Y.push(`${K}`)}if($.commands.some((Q)=>Q.name))Y.push(""),Y.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return Y.join(`
`)}function i_0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of n_0)for(let z of Y.commands)for(let U of z.usage)$.push(`${U}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var n_0;var nl=m(()=>{F$();n_0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",groupOrder:["企业接入","发现与选择","企业配置","测试配对与验证","Hose 专属能力"],commands:[{name:"list",group:"发现与选择",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],group:"发现与选择",summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],group:"发现与选择",summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",group:"发现与选择",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",group:"发现与选择",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",group:"企业配置",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"rename",group:"企业配置",summary:"Rename an enterprise display name",usage:["seal-use corps rename <corpId> --name <newName>"],options:[{flag:"--name <newName>",description:"New human-readable enterprise name (required)"}],description:"Safely updates the display name of a configured enterprise without modifying underlying files manually."},{name:"bind-test",group:"测试配对与验证",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",group:"测试配对与验证",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",group:"测试配对与验证",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new versi
Line truncated
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:W?J:Z?V:G,type:X,mode:Z?"auto_login":"direct",sealResultUrl:G,hoseDocumentUrl:J,documentUrl:J,ssoUrl:V,expiresIn:Z?q:void 0,identity:F,warning:M,hoseDomain:Q.type==="hose"?Fg1(Q.domain):void 0,recordId:I.id,sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId,sourceSystem:I.sourceSystem,missing:{hoseDocumentUrl:!J?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:L.object({query:L.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:L.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:L.string().optional().describe("模拟批次 ID"),latest:L.boolean().optional().describe("只返回最新一条匹配记录"),fields:L.union([L.string(),L.array(L.string())]).optional().describe("限制返回字段"),limit:L.number().int().positive().max(100).optional(),maxScan:L.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:L.boolean().optional()}),handler:async($,U,Y)=>{let z=U.sn??U.query;if(!z)throw Error("query or sn is required");let I=await Mg1($,{query:z,sn:U.sn,batchId:U.batchId,latest:U.latest,limit:U.latest?1:U.limit??20,maxScan:U.maxScan??1000}),Q=await Promise.all(I.records.map((X)=>H4($,X.id))),J=y_0(U.fields),K=Q.map((X)=>Vg1(X,J)),G=Q.find((X)=>X.ruleSetVersionNumber!==void 0)?.ruleSetVersionNumber,H=G===void 0?"latest":String(G),W=G===void 0?'"latestRuleVersion":true':`"ruleVersionNumber":${G}`;return{query:z,sourceDocumentSN:U.sn,simulationBatchId:U.batchId,latest:U.latest??!1,total:I.total,scanned:I.scanned,matched:K.length,records:K,next:{getSummary:`seal-useapproval-runsget<recordId>--summary--corp${Y.corp.id}`,getRuleVersion:`seal-userulesversion${H}--corp${Y.corp.id}`,searchRuleVersion:`seal-usetoolseal_approval_search--corp${Y.corp.id}--json'{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${W}}'`,getVersionContext:`seal-usetoolseal_approval_context_get--corp${Y.corp.id}--json'{${W}}'`},...U.includeBridge?{bridge:TT(Q)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:L.object({batchId:L.string().describe("simulation batch ID"),query:L.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,U)=>{let Y=ml(await Pg($,U.batchId),U.query);return{batchId:U.batchId,count:Y.length,records:Y.map(fz),bridge:TT(Y)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:L.object({mode:L.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:L.array(L.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:L.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:L.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:L.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:L.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:L.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:L.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:L.array(L.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:L.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:L.record(L.string(),L.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:L.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:L.record(L.string(),L.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,U)=>{let Y=U.mode??"hosecloud",z=U.signKey;if(Y==="hosecloud"&&!z){if(z=(await jg($)).find((K)=>K.signKey)?.signKey,!z)throw Error("
Line truncated
`)}function Rg1($){let U=[];if(U.push(`seal-use${$.area}-${$.title}`),$.description)U.push($.description);U.push(""),U.push("Usage:");let Y=new Map;for(let I of $.commands){let Q=I.group??"",J=Y.get(Q)??[];J.push(I),Y.set(Q,J)}let z=[...$.groupOrder??[],...[...Y.keys()].filter((I)=>!$.groupOrder?.includes(I))];for(let I of z){let Q=Y.get(I);if(!Q)continue;if(I)U.push(""),U.push(`${I}:`);for(let J of Q)for(let K of J.usage)U.push(`${K}`)}if($.commands.some((I)=>I.name))U.push(""),U.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return U.join(`
`)}function $v0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let U of Uv0)for(let Y of U.commands)for(let z of Y.usage)$.push(`${z}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var Uv0;var el=m(()=>{O8();Uv0=[{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(U.outputFile){_g1(U.outputFile,Y),console.log(JSON.stringify({outputFile:U.outputFile,bytes:Buffer.byteLength(Y,"utf-8")},null,2));return}console.log(Y.trimEnd())}function gg1($,U={}){if(U.allowFull||U.outputFile)return;let Y=Buffer.byteLength(JSON.stringify($),"utf-8");if(Y>Sg1)throw new JP(`Outputislarge(${Y}bytes).Use--summary,--fields,--count,or--output-file;pass--fullonlywhenyoureallyneedthefullresponse.`)}function Qv0($,U){if(U)return;let Y=$&&typeof $==="object"?$:{},z=typeof Y.count==="number"?Y.count:void 0,I=Array.isArray(Y.rules)?Y.rules.length:void 0,Q=Buffer.byteLength(JSON.stringify($),"utf-8"),J=z??I??0;if(J>vg1||Q>hg1)throw new JP(`Rulelistislarge(${J}rules,${Q}bytes).Use"seal-use rules list --summary","seal-use rules count",or--output-file;pass--fullonlywhenyoureallyneedfulldescriptions.`,"seal-use rules list --summary")}function j0($){return{allowFull:G0($.full)===!0,outputFile:S($.outputFile)??S($["output-file"])}}function Jv0($=[]){console.log(zv0($))}var vg1=100,hg1=120000,Iv0,Sg1=200000;var m1=m(()=>{Z4();O8();el();Iv0=["code","status","strictness","scope","updatedAt"]});var Uo={};T8(Uo,{selectCorp:()=>M1,runToolResult:()=>M$,runTool:()=>x0,globalConfigSummary:()=>t2});function M1($){let U=t8(),Y=v4(),z=c2(U,{stateful:Y.stateful,defaultCorpId:Y.defaultCorpId,corpId:$},x3());return rA0(z.id),z}function t2($=v4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:Zz()}}async function x0($,U,Y,z,I={}){R0(await M$($,U,Y,z),I)}async function M$($,U,Y,z){let I=Pq.find((K)=>K.name===$);if(!I)throw Error(`UnknownSealtool:${$}`);let Q=Object.fromEntries(Object.entries(z).filter(([,K])=>K!==void 0)),J=I.handler;return J(U,Q,{corp:Y})}var O4=m(()=>{T5();YP();jq();m1()});import{existsSync as Kv0}from"node:fs";async function Gv0($,U){if(!Kv0($))throw Error(`Filenotfound:${$}`);let Y=xz($);console.log(JSON.stringify(await kz(Y.fileBuffer,Y.fileName,U),null,2))}async function gT($,U,Y,z,I){if($==="ready"||$==="status"){let Q=U??S(I.options.file)??S(I.options.input),J=await NT(Y,z,{filePath:Q,webhook:S(I.options.webhook)??S(I.options.selector)});if(console.error(`[webhook-ready]企业环境:${J.corp.name}(${J.corp.id})[${J.stateMode}]`),J.corp.tenant?.name)console.error(`[webhook-ready]租户信息:${J.corp.tenant.name}(${J.corp.tenant.id})`);console.error(`[webhook-ready]凭证状态:${J.authStatus==="ok"?"OK":`异常 (${J.authError})`}`),console.error(`[webhook-ready]Webhook通道:${J.activeWebhooks.length}个可用`);for(let K of J.activeWebhooks){let G=K.isDefault?" [默认通道]":"";console.error(`-${K.name}(${K.id})mode=${K.mode}${G}`)}if(J.materialPack)console.error(`[webhook-ready]材料包预检:${J.materialPack.valid?`通过 (${J.materialPack.documentCount} 单)`:`失败 (${J.materialPack.errors?.join("; ")})`}`);if(J.ready)console.error(`\uD83D\uDFE2${J.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${J.nextAction}`);else console.error(`\uD83D\uDD34准备阶段未通过:${J.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${J.nextAction}`);console.log(JSON.stringify(J,null,2));return}if($==="replay"){let Q=U??S(I.options.recordId)??S(I.options["record-id"])??S(I.options.id),J=S(I.options.recordIds)??S(I.options["record-ids"]),K=J?J.split(",").map((n)=>n.trim()).filter(Boolean):void 0,G=S(I.options.sn)??S(I.options.documentSn)??S(I.options["document-sn"]),H=S(I.options.sns)??S(I.options["document-sns"]),W=H?H.split(",").map((n)=>n.trim()).filter(Boolean):void 0,X=s0(I.options.limit),Z=S(I.options.status),q=S(I.options.startDate)??S(I.options["start-date"]),V=S(I.options.endDate)??S(I.options["end-date"]);if(!Q&&!K&&!G&&!W&&X===void 0)throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let F=S(I.options.sourceCorp)??S(I.options["source-corp"])??S(I.options.prodCorp)??S(I.options["prod-corp"]),M=S(I.options.targetCorp)??S(I.options["target-corp"])??S(I.options.testCorp)??S(I.options["test-corp"]),w=G0(I.options.force)===!0,{sourceCorp:N,targetCorp:O}=KP({sourceCorpId:F,targetCorpId:M,activeCorp:z,force:w},M1),D=N.id===z.id?Y:await B1(N),P=O.id===z.id?Y:await B1(O),T=S(I.options.webhook)??S(I.options.selector),A=S(I.options.snSuffix)??S(I.options["sn-suffix"]),j=S(I.options.snPrefix)??S(I.options["sn-prefix"]),C=S(I.options.docIdSuffix)??S(I.options["doc-id-suffix"]),b=S(I.options.docIdPrefix)??S(I.options["doc-id-prefix"]),x=G0(I.options.dryRun)??G0(I.options["dry-run"]),i=await zK({query:{recordId:Q,recordIds:K,sn:G,sns:W,limit:X,status:Z,startDate:q,endDate:V},sourceClient:D,targetClient:P,sourceCorp:N,targetCorp:O,webhookSelector:T,snPrefix:j,snSuffix:A,docIdPrefix:b,docIdSuffix:C,dr
Line truncated
or:seal-usecorpsbind-test<testCorpId>--corp<prodCorpId>[--confirm][--force]`);let Q=M1(z),J=M1(I);if(Q.id===J.id)throw h4(`Cannotbindenterprise'${Q.id}'toitself.`);if(Q.prodCorpId&&Q.prodCorpId!==J.id)throw h4(`Cannotuse'${Q.id}'asaproductionenterprisebecauseitisalreadyregisteredasatestenterprisefor'${Q.prodCorpId}'.Multi-tierchainingisnotpermitted.`);if(J.testCorpId&&J.testCorpId!==Q.id)throw h4(`Cannotbind'${J.id}'asatestenterprisebecauseitalreadyhasaboundtestenterprise'${J.testCorpId}'.Multi-tierchainingisnotpermitted.`);let K=G0(Y.options.force)===!0;if(Q.testCorpId&&Q.testCorpId!==J.id||J.prodCorpId&&J.prodCorpId!==Q.id){if(!K)throw F$(`Enterprisebindingconflict:productionenterprise'${Q.id}'isboundto'${Q.testCorpId??"none"}',andtestenterprise'${J.id}'isboundto'${J.prodCorpId??"none"}'.Overwritinganexistingbindingrequires--forceand--confirm.`,`seal-usecorpsbind-test${Q.id}${J.id}--confirm--force`)}if(!(G0(Y.options.confirm)===!0||G0(Y.options.yes)===!0)){let X=K?" --force":"";throw F$(`Refusingtobindtestenterprise'${J.name}'(${J.id})toproductionenterprise'${Q.name}'(${Q.id})without--confirm.Enterprisebindingestablishes1-to-1syncpairingandmarks'${J.id}'asatestenvironment.`,`seal-usecorpsbind-test${Q.id}${J.id}--confirm${X}`)}if(Q.testCorpId&&Q.testCorpId!==J.id)try{E9(Q.testCorpId,{prodCorpId:void 0})}catch{}if(J.prodCorpId&&J.prodCorpId!==Q.id)try{E9(J.prodCorpId,{testCorpId:void 0})}catch{}let H=E9(Q.id,{environment:"production",testCorpId:J.id}),W=E9(J.id,{environment:"test",prodCorpId:Q.id});return R0({success:!0,productionEnterprise:{id:H.id,name:H.name,environment:H.environment,testCorpId:H.testCorpId},testEnterprise:{id:W.id,name:W.name,environment:W.environment,prodCorpId:W.prodCorpId}}),!0}if($==="unbind-test"){let z=U??S(Y.options.corp),I=M1(z);if(!I.testCorpId&&!I.prodCorpId)return R0({unbound:!1,message:`Enterprise'${I.name}'(${I.id})doesnothaveanactivetestenterprisebinding.`}),!0;let Q=I.testCorpId?I.id:I.prodCorpId,J=I.testCorpId?I.testCorpId:I.id;if(!(G0(Y.options.confirm)===!0||G0(Y.options.yes)===!0))throw F$(`Refusingtounbindproductionenterprise'${Q}'andtestenterprise'${J}'without--confirm.`,`seal-usecorpsunbind-test${I.id}--confirm`);E9(Q,{testCorpId:void 0});try{E9(J,{prodCorpId:void 0})}catch{}return R0({success:!0,unboundProduction:Q,unboundTest:J}),!0}return!1}var Vv0=m(()=>{T5();O4();O8();Z4();m1()});function yT($){let U;try{U=new URL($.trim())}catch{throw Error("Invalid Seal delegate link: expected a valid HTTPS URL")}if(U.protocol!=="https:")throw Error("Invalid Seal delegate link: expected HTTPS");let Y=U.hostname.toLowerCase();if(!Y.endsWith(Lv0))throw Error(`InvalidSealdelegatelink:expectedhostendingin${Lv0},got${Y}`);let z=U.pathname.replace(/\/+$/,"");if(z!==wv0)throw Error(`InvalidSealdelegatelink:expectedpath${wv0},got${z}`);let I=U.searchParams.get("token");if(!I)throw Error("Invalid Seal delegate link: token query parameter is required");return{sealUrl:U.origin,delegateToken:I}}async function Fv0($){let U=typeof $==="string"?yT($):$;return(await B6(U.sealUrl,void 0).post("api/v1/delegation/preview",{json:{token:U.delegateToken}}).json()).data}async function Mv0($){let U=typeof $==="string"?yT($):$,Y=U.sealUrl,z=B6(Y,void 0),I=await z.post("api/v1/delegation/consume",{json:{token:U.delegateToken}}),Q=I.headers.get("set-cookie")??"",J=typeof I.headers.getSetCookie==="function"?I.headers.getSetCookie():[Q],K="";for(let M of J)if(M&&M.includes("session_token=")){K=(M.split(";")[0]??"").trim();break}let G;try{G=await z.get("api/auth/get-session",{headers:K?{cookie:K}:{}}).json()}catch{}let H=G?.session?.token;if(!H&&K){let M=K.match(/session_token=([^.;]+)/);if(M?.[1])H=decodeURIComponent(M[1])}if(!H)throw Error("Seal delegate exchange did not return a session token");let W=86400;if(G?.session?.expiresAt){let M=new Date(G.session.expiresAt).getTime();if(Number.isFinite(M)){let w=Math.floor((M-Date.now())/1000);if(w>0)W=w}}let Z=await B6(Y,H).get("api/v1/auth/me").json(),q=Z.data&&typeof Z.data==="object"?Z.data:Z,V=q.user??G?.user??{},F=q.tenant??{};return{sealUrl:Y,token:H,expiresIn:W,user:V,tenant:F}}function kT($){let U=[],Y=0,z="";try{let J=new URL($.trim()),K=J.hostname.toLowerCase(),G=J.pathname.replace(/\/+$/,"");if(K.endsWith(".ekuaibao.com")||K.endsWith(".hosecloud.com")||K==="ekuaibao.com"||K==="hosecloud.com")Y+=40,z="host is Hose domain";if(G==="/web/thirdparty.html")Y+=40,z+="; path is /web/thirdparty.html";if(J.searchParams.has("accessToken"))Y+=10,z+="; has accessToken";if(J.searchParams.has("ekbCorpId"))Y+=10,z+="; has ekbCorpId"}catch{Y=0}if(Y>0)U.push({kind:"hose",score:Y,reason:z});let I=0,Q="";try{let J=new URL($.trim()),K=J.hostname.toLowerCase(),G=J.pathname.replace(/\/+$/,"");if(K.endsWith(".sealai.cc"))I+=40,Q="host ends with .sealai.cc";if(G==="/delegate")I+=40,Q+="; path is /delegate";if(
Line truncated
`,{mode:384}),{config:Y,path:I}}var Io=m(()=>{T5();sB()});function Qo($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function xT($){let U=new Date($);if(Number.isNaN(U.getTime()))return $;return Qo(U.getTime())}function $5($){return typeof $==="string"&&$?$:void 0}function bg1($){return{headers:Ad.parse($.headers),cookies:Bd.parse($.cookies)}}async function ig1($,U,Y={}){let z=await Z8(B6($,U,Y));return{user:z.user??{},tenant:z.tenant??{}}}async function Ov0($){let U=$.sealUrl.replace(/\/+$/,""),Y=$.expiresIn??2592000,z=$.force===!0||$.verify===!1?!1:!0,I=bg1($),Q=z?await ig1(U,$.token,A6(I)):void 0,J=Dv0($,{token:$.token,sealUrl:U,expiresIn:Y,expiresAt:$.expiresAt,verify:z,remote:Q,custom:I}),K=$.tenantId??$5(Q?.tenant.id),G=$.tenantSlug??$5(Q?.tenant.tenantSlug);return{...J,verified:z,tenantId:K,tenantSlug:G}}function Nv0($){let U=$5($.session.tenant.tenantSlug),Y=$5($.session.tenant.id),z=U??Y??"seal-delegate";return{...Dv0({id:z,corpId:z,name:$.name,provider:"seal",overwrite:$.overwrite},{token:$.session.token,sealUrl:$.session.sealUrl,expiresIn:$.session.expiresIn,verify:!0,remote:{user:$.session.user,tenant:$.session.tenant}}),tenantId:Y,tenantSlug:U}}function Dv0($,U){let Y=U.remote?.user,z=U.remote?.tenant,I=$.tenantSlug??$5(z?.tenantSlug),Q=$.tenantId??$5(z?.id),J=$.tenantName??$5(z?.name),K=$.id??I??Q;if(!K)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let G=U.expiresAt?xT(U.expiresAt):Qo(Date.now()+U.expiresIn*1000),H=$.staffId??$5(Y?.providerUserId)??$5(Y?.id)??"seal",W=$.provider??$5(Y?.provider)??$5(z?.providerConfig?.provider),X=$.corpId??I??Q??K,Z={id:K,name:$.name??J??K,environment:"production",seal:{url:U.sealUrl,tenantSlug:I,headers:U.custom?.headers,cookies:U.custom?.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:U.token,sealUrl:U.sealUrl,expiresIn:U.expiresIn,expiresAt:G,staffId:H,corpId:X,tenantId:Q,tenantSlug:I,tenantName:J,providerUserId:$5(Y?.providerUserId),provider:W},auth:{refreshTtl:300}};return _q(Z,{overwrite:$.overwrite===!0})}var Jo=m(()=>{Io();sB();m6();X6()});async function bK($){let[U,Y]=await Promise.all([J10($),B1($)]),z=await Z8(Y);return{...U,tenantId:z.tenant.id,tenantSlug:z.tenant.tenantSlug??U.tenantSlug,tenantName:z.tenant.name,raw:{...typeof U.raw==="object"&&U.raw!==null?U.raw:{},user:{id:z.user.id,name:z.user.name,isAdmin:z.user.isAdmin,providerUserId:z.user.providerUserId,hosecloudStaff:z.user.hosecloudStaff},tenant:z.tenant}}}var fT=m(()=>{m6();Gg();X6()});async function Av0($){let U=await rI($.appKey,$.appSecurity,$.domain),Y=await wM(U.domain,U.openapiToken).catch(()=>[]);return{...U,roleCount:Y.reduce((z,I)=>z+I.roleDefs.length,0),roleGroups:Y.map((z)=>({id:z.id,name:z.name,roleDefs:z.roleDefs.map((I)=>({id:I.id,name:I.name,sourceType:I.sourceType}))}))}}async function Bv0($){let U=await rI($.appKey,$.appSecurity,$.domain),Y=$.role??$.roleDefId??"admin",z=await wM(U.domain,U.openapiToken),I,Q;for(let G of z){for(let H of G.roleDefs)if(H.id===Y||H.id===`${U.corpId}:${Y}`){I=H.id,Q=H.name;break}if(I)break}if(!I&&(Y==="admin"||Y==="主管理员"))for(let G of z){for(let H of G.roleDefs)if(H.id.endsWith(":admin")||H.name==="主管理员"){I=H.id,Q=H.name;break}if(I)break}if(!I)for(let G of z){for(let H of G.roleDefs)if(H.name.toLowerCase().includes(Y.toLowerCase())){I=H.id,Q=H.name;break}if(I)break}if(!I)throw Error(`Rolenotfoundmatchingquery:'${Y}'.Run'seal-use corps probe-hose'toviewallavailableroles.`);let J=await Ig(U.domain,U.openapiToken,I),K=await Qg(U.domain,U.openapiToken,J.staffs);return{domain:U.domain,corpId:U.corpId,corpName:U.corpName??U.corpId,roleId:I,roleName:Q,staffs:K}}async function vq($){let U=$.domain,Y=$.staffId??$.proxyStaffBizId,z=$.force===!0,I=z||$.verify===!1?!1:!0,Q=U,J=$.corpId??$.corporationId,K=$.name,G;if(!Q||!J||!Y){let V=await rI($.appKey,$.appSecurity,U);Q=V.domain,J=J??V.corpId,K=K??V.corpName,G=V.openapiToken}let H=Y;if(!H&&G&&Q){let V=$.role??"admin",F=await wM(Q,G).catch(()=>[]),M;for(let w of F){for(let N of w.roleDefs)if(N.id.endsWith(`:${V}`)||N.name===V||N.id===V){M=N.id;break}if(M)break}if(!M)M=F.find((w)=>w.roleDefs.some((N)=>N.id.endsWith(":admin")))?.roleDefs.find((w)=>w.id.endsWith(":admin"))?.id;if(M){let w=await Ig(Q,G,M).catch(()=>({staffs:[]})),N=await Qg(Q,G,w.staffs).catch(()=>[]);if($.staffName||$.staffPhone){let O=N.filter((D)=>{if($.staffName&&D.name!==$.staffName&&!D.name.includes($.staffName))return!1;if($.staffPhone&&(!D.cellphone||!D.cellphone.includes($.staffPhone)))return!1;return!0});if(O.length===1&&O[0])H=O[0].id;else if(O.length>1)throw Error(`Multiplestaffmembersmatched'${$.staffName??$.staffPhone}':${O.map((D)=>`${D.name}(${D.id})`).join(", ")}.PleasespecifyexactstaffId.`);else throw Error(`Nostaffmemberfoundmatching'${$.staffName??$.staffPhone}'underrole${M}.Run'seal-use corps hose-staffs'toviewcandidates.`)}else if(!z){let O=N.map(
Line truncated
`+"\uD83D\uDCA1 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。",z);if(Y.keyId||Y.appKey){let I=$.find((Q)=>Y.keyId&&Q.id===Y.keyId||Y.appKey&&Q.appKey===Y.appKey);if(!I)throw new bz(`指定的合思密钥不存在,请从上述候选列表中选择正确的appKey或keyId。
Run'seal-use corps bind-test ${Q.id} <testCorpId> --confirm'firsttoestablishaverified1-to-1association.`);let J=T1(Q.testCorpId);if(J.environment!=="test")throw Error(`Targetenterprise'${J.name}'(${J.id})ismarkedas'${J.environment}',NOT'test'.Abortingsynctoprotectnon-testenvironments.`);let I=await P1(Q),K=await P1(J),[G,H,W,X,Z,q,V,F]=await Promise.all([o1(I,Q.seal.endpoints.approvalStylePreferences),o1(K,J.seal.endpoints.approvalStylePreferences),X6(I),X6(K),c8(I),c8(K),Ch0(I),Ch0(K)]),w=(V.articles||[]).filter((G0)=>!G0.isDeleted),O=(F.articles||[]).filter((G0)=>!G0.isDeleted),N=new Map(O.map((G0)=>[G0.title.trim(),G0])),M=[],D=[],P=new Set(w.map((G0)=>G0.title.trim()));for(let G0 of w){let f0=G0.title.trim(),e0=N.get(f0);if(!e0)M.push(G0);else{let s=e0.content!==G0.content,H0=(e0.purpose??"")!==(G0.purpose??""),F0=e0.enabled!==G0.enabled,b0=e0.contentType!==G0.contentType,i0=(e0.status??"")!==(G0.status??""),n0=JSON.stringify([...e0.scenarios??[]].sort())!==JSON.stringify([...G0.scenarios??[]].sort()),w1=JSON.stringify([...e0.tags??[]].sort())!==JSON.stringify([...G0.tags??[]].sort());if(s||H0||F0||b0||i0||n0||w1)D.push({testId:e0.id,prodDoc:G0,reasons:[...s?["content"]:[],...H0?["purpose"]:[],...F0?["enabled"]:[],...b0?["contentType"]:[],...i0?["status"]:[],...n0?["scenarios"]:[],...w1?["tags"]:[]]})}}let j=O.filter((G0)=>!P.has(G0.title.trim())),T=[...Z].sort((G0,f0)=>f0.versionNumber-G0.versionNumber)[0],C=T?.versionNumber,k=([...q].sort((G0,f0)=>f0.versionNumber-G0.versionNumber)[0]?.versionNumber??0)+1,S=Th0(Q.name,C,q),n=h(z.options["version-name"])??h(z.options.versionName)??Eh0(Q.name,C,S,k),U0={...H,tone:G.tone,language:G.language,detailLevel:G.detailLevel,outputFormat:G.outputFormat,examples:G.examples??[],prohibitedPhrases:G.prohibitedPhrases??[],customInstructions:G.customInstructions,decisionPreferences:G.decisionPreferences,thinkingDepthPreference:G.thinkingDepthPreference};if(Z0(z.options["dry-run"])===!0||Z0(z.options.dryRun)===!0){x0({dryRun:!0,source:{id:Q.id,name:Q.name,environment:Q.environment,latestPublishedVersion:T?{versionNumber:T.versionNumber,versionName:T.versionName}:null,documentsCount:w.length},target:{id:J.id,name:J.name,environment:J.environment},versionMappingPlan:{sourceProdVersionNumber:C??null,sourceProdVersionName:T?.versionName??null,targetTestExpectedVersionNumber:k,targetTestPublishVersionName:n,iteration:S},preferencesDiff:{decisionPreferences:{before:H.decisionPreferences,after:G.decisionPreferences},thinkingDepthPreference:{before:H.thinkingDepthPreference,after:G.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:W.rules.length,targetExistingDraftRuleCount:X.rules.length,toDeleteCount:X.rules.length,toCreateCount:W.rules.length,rulesToSync:W.rules.map((G0,f0)=>({index:f0+1,sourceRuleId:G0.id,sourceRuleCode:G0.code??f0+1,expectedTargetCode:`rule-${f0+1}`,description:G0.description,scope:G0.scope,strictness:G0.strictness}))},documentsPlan:{sourceDocumentCount:w.length,targetExistingDocumentCount:O.length,toCreateCount:M.length,toCreate:M.map((G0)=>({title:G0.title,purpose:G0.purpose,contentType:G0.contentType,scenarios:G0.scenarios})),toUpdateCount:D.length,toUpdate:D.map((G0)=>({targetDocumentId:G0.testId,title:G0.prodDoc.title,reasons:G0.reasons})),toDeleteCount:j.length,toDelete:j.map((G0)=>({targetDocumentId:G0.id,title:G0.title}))},publishingPlan:{targetCorpId:J.id,publishVersionName:n,publishTarget:"test"},hosecloudSyncPlan:(()=>{if(Q.source.type!=="hose")return{sourceType:Q.source.type,skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let G0=(G.integrations??[]).filter((s)=>s.type==="hosecloud"),f0=new Set,e0=G0.filter((s)=>{let H0=s.corporationId??Q.id;if(f0.has(H0))return!1;return f0.add(H0),!0});return{sourceType:"hose",outboundName:yh0(Q.name),targetMode:"assisted",integrationsCount:e0.length,integrations:e0.map((s)=>({corporationId:s.corporationId,apiOrigin:s.apiOrigin,customApiUrl:s.customApiUrl}))}})(),productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(Z0(z.options.yes)===!0||Z0(z.options.confirm)===!0))throw A5(`Refusingtooverwritetestenterprise'${J.name}'(${J.id})withpreferences,${W.rules.length}draftrules,and${w.length}knowledgedocumentsfromproductionenterprise'${Q.name}'(${Q.id})without--yes.Thiswillreplacetestdraftrules,synchronizeknowledgedocuments,andpublishanewversiononthetestenterprise.`,`seal-usecorpssync-test${Q.id}--yes`);await s5(K,U0,J.seal.endpoints.approvalStylePreferences);let t=[];for(let G0 of j)await Bw(K,G0.id),t.push({id:G0.id,title:G0.title});let e=[];for(let G0 of D)await Aw(K,G0.testId,{title:G0.prodDoc.title,purpose:G0.prodDoc.purpose,content:G0.prodDoc.content,contentType:G0.prodDoc.contentType,status:G0.prodDoc.status,enabled:G0.prodDoc.enabled,scenarios:G0.prodDoc.scenarios&&G0.prodDoc.scenarios.length>0?G0.prodDoc.scenarios:["audit"],tags:G0.prodDoc.tags}),e.push({id:G0.testId,title
Line truncated
Run'seal-use corps bind-test ${Q.id} <testCorpId> --confirm'firsttoestablishaverified1-to-1association,
oradd'--force'(oruse'seal-use webhook replay <recordId> --force')ifyouexplicitlyintendtoreplaydirectlywithinproduction.`);G=Q}else if(G=T1(Q.testCorpId),G.environment!=="test"&&!J)throw Error(`Targetenterprise'${G.name}'(${G.id})ismarkedas'${G.environment}',NOT'test'.Abortingreplaytoprotectnon-testenvironments(use--forcetooverride).`);if(!I&&!K)throw A5("Refusing to replay approval records without --confirm. Use --dry-run to preview the payload without sending it.",`seal-usecorpsreplay-test${U??"<prodCorpId>"}--confirm`);let H=h(z.options.recordId)??h(z.options["record-id"])??h(z.options.id),W=h(z.options.recordIds)??h(z.options["record-ids"]),X=W?W.split(",").map((S)=>S.trim()).filter(Boolean):void 0,Z=h(z.options.sn)??h(z.options.documentSn)??h(z.options["document-sn"]),q=h(z.options.sns)??h(z.options["document-sns"]),V=q?q.split(",").map((S)=>S.trim()).filter(Boolean):void 0,F=s0(z.options.limit)??(!H&&!X&&!Z&&!V?1:void 0),w=h(z.options.status),O=h(z.options.startDate)??h(z.options["start-date"]),N=h(z.options.endDate)??h(z.options["end-date"]),M=await P1(Q),D=Q.id===G.id?M:await P1(G),P=h(z.options.webhook)??h(z.options.selector),j=h(z.options.snSuffix)??h(z.options["sn-suffix"]),A=h(z.options.snPrefix)??h(z.options["sn-prefix"]),T=h(z.options.docIdSuffix)??h(z.options["doc-id-suffix"]),C=h(z.options.docIdPrefix)??h(z.options["doc-id-prefix"]),b={recordId:H,recordIds:X,sn:Z,sns:V,limit:F,status:w,startDate:O,endDate:N};console.error(`[corps-replay-test]正式企业「${Q.name}」(${Q.id})->测试企业「${G.name}」(${G.id})`);let k=await zK({query:b,sourceClient:M,targetClient:D,sourceCorp:Q,targetCorp:G,webhookSelector:P,snPrefix:A,snSuffix:j,docIdPrefix:C,docIdSuffix:T,dryRun:I});if(I){console.error(`[corps-replay-test]预览模式:已成功从${Q.name}提取单据并转换为WebhookPayload(未实际推送)。`),console.log(JSON.stringify(k,null,2));return}if(k.success)if(k.totalCount===1&&k.replayedDocument)console.error(`\uD83D\uDFE2成功重放单据「${k.replayedDocument.documentSN}」至${G.name}(${k.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDFE2成功重放${k.successCount}条单据(来自「${Q.name}」)至「${G.name}」(${k.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDD34单据重放部分或全部失败(成功${k.successCount}条,失败${k.failureCount}条)至「${G.name}」`);if(console.error(`\uD83D\uDC49Nextaction:seal-useapproval-runslist--corp${G.id}--limit${k.totalCount}`),console.log(JSON.stringify(k,null,2)),!k.success)throw new L4(`Approvalrecordreplayfailed:${k.failureCount}record(s)failed.`,1);return}if($==="switch"){let U=Y;if(!U)throw Error("Usage: seal-use corps switch <corpId>");let Q=v4();if(!Q.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-useconfigmodestateful` first.");let J=T1(U);qU({...Q,stateful:!0,defaultCorpId:J.id}),x0({current:!0,id:J.id,name:J.name});return}if($==="probe-hose"){await fg1(k8(z.json));return}if($==="hose-staffs"){await ug1(k8(z.json));return}if($==="add-hose"){let Q={...k8(z.json),...z.options.staffName?{staffName:h(z.options.staffName)}:{},...z.options["staff-name"]?{staffName:h(z.options["staff-name"])}:{},...z.options.staffPhone?{staffPhone:h(z.options.staffPhone)}:{},...z.options["staff-phone"]?{staffPhone:h(z.options["staff-phone"])}:{},...z.options.name?{name:h(z.options.name)}:{},...z.options.domain?{domain:h(z.options.domain)}:{},...z.options.corpId?{corpId:h(z.options.corpId)}:{},...z.options["corp-id"]?{corpId:h(z.options["corp-id"])}:{},...z.options.appKey?{appKey:h(z.options.appKey)}:{},...z.options["app-key"]?{appKey:h(z.options["app-key"])}:{},...z.options.appSecurity?{appSecurity:h(z.options.appSecurity)}:{},...z.options["app-security"]?{appSecurity:h(z.options["app-security"])}:{},...z.options.force!==void 0?{force:Z0(z.options.force)}:{},...z.options.overwrite!==void 0?{overwrite:Z0(z.options.overwrite)}:{}};await Go(Q);return}if($==="add-seal"){let Q={...k8(z.json),...z.options.name?{name:h(z.options.name)}:{},...z.options.token?{token:h(z.options.token)}:{},...z.options.sealUrl?{sealUrl:h(z.options.sealUrl)}:{},...z.options.url?{sealUrl:h(z.options.url)}:{},...z.options.force!==void 0?{force:Z0(z.options.force)}:{},...z.options.overwrite!==void 0?{overwrite:Z0(z.options.overwrite)}:{}};await bg1(Q);return}if($==="add-link"){let U=Y??h(z.options.link)??h(z.options.url);if(!U)throw Error("Usage: seal-use corps add-link <url> [--name <customName>] [--as-hose] [--overwrite]");let Q=Z0(z.options["dry-run"])===!0||Z0(z.options.dryRun)===!0;if(Z0(z.options["as-hose"])===!0||Z0(z.options.hose)===!0){if(ml(U)[0]?.kind==="seal-delegate")throw Error("Option --as-hose cannot be used with a Seal native delegate link. Seal delegate links directly authenticate to Seal.");await ng1(U,h(z.options.name),Z0(z.options.overwrite)===!0,Z0(z.options.force
Line truncated
`);x0({provider:"hose",capability:"privilege-elevation",corpId:z.corpId,corpName:z.corpName??z.corpId,baseUrl:z.baseUrl,staffId:z.staffId,keyCount:z.keys.length,keys:z.keys.map((Q)=>({id:Q.id,name:Q.name||"-",appKey:Q.appKey,appSecurity:U?Q.appSecurity:Ww(Q.appSecurity),active:Q.active,createTime:Q.createTime,updateTime:Q.updateTime}))})}async function Ho($,Y){let z=T1($),U=Y.reveal===!0;if(z.source.type!=="hose")throw new L4(`【合思子域专享能力】当前企业「${z.name}」(id:${z.id})为原生Seal(${z.source.type})租户,非合思(Hose/合思云/易快报)渠道企业。
`);R0({provider:"hose",capability:"privilege-elevation",corpId:z.corpId,corpName:z.corpName??z.corpId,baseUrl:z.baseUrl,staffId:z.staffId,keyCount:z.keys.length,keys:z.keys.map((Q)=>Rv0(Q,I))})}async function nT($,U){let Y=M1($),z=U.reveal===!0;if(Y.source.type!=="hose")throw new W4(`【合思子域专享能力】当前企业「${Y.name}」(id:${Y.id})为原生Seal(${Y.source.type})租户,非合思(Hose/合思云/易快报)渠道企业。
`);x0({provider:"hose",capability:"privilege-elevation",corpId:z.id,corpName:z.name,domain:z.source.domain,staffId:z.source.staffId,appKey:Q??"-",appSecurity:J?U?J:Ww(J):"-",active:!0})}function Ko($,Y){let{token:z,sealUrl:U,expiresIn:Q,verify:J,remote:I}=Y,K=Y.custom??kh0($),G=I?.user,H=I?.tenant,W=X4($,"tenantSlug")??e2(H?.tenantSlug),X=X4($,"tenantId")??e2(H?.id),Z=X4($,"tenantName")??e2(H?.name),q=X4($,"id")??W??X;if(!q)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let V=X4($,"staffId")??e2(G?.providerUserId)??e2(G?.id)??"seal",F=X4($,"provider")??e2(G?.provider)??e2(H?.providerConfig?.provider),w=X4($,"corpId")??W??X??q,O={id:q,name:X4($,"name")??Z??q,environment:"production",seal:{url:U,tenantSlug:W,headers:K.headers,cookies:K.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:z,sealUrl:U,expiresIn:Q,staffId:V,corpId:w,tenantId:X,tenantSlug:W,tenantName:Z,providerUserId:e2(G?.providerUserId),provider:F},auth:{refreshTtl:300}},N=qp();_h0(N,{recursive:!0,mode:448});let M=hh0(N,`${Pj(q)}.json`);if(Rh0(M)&&$.overwrite!==!0)throw Error(`Enterpriseconfigalreadyexists:${M}.Pass"overwrite":truetoreplaceit.`);vh0(M,`${JSON.stringify(O,null,2)}
`,{mode:384}),x0({id:q,name:O.name,tenantId:X,tenantSlug:W,verified:J,path:M})}async function cg1($,Y,z={}){let U=y6($,Y,z),Q=await T8(U);return{user:Q.user??{},tenant:Q.tenant??{}}}function e2($){return typeof $==="string"&&$?$:void 0}var Wo=m(()=>{g7();Qv0();CH();i8();k3();Nh0();rB();Xp();B6();B6();Jo();Np();fZ();fj();f4();F$();A4();K4()});var bh0={};D8(bh0,{handleAuthExtractKeysCommand:()=>qo,handleAuthCommand:()=>ij,formatBeijingIso:()=>Zo});async function qo($,Y){let z=$??h(Y.options.link)??h(Y.options.url);if(!z)throw Error("Usage: seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");let U=Z0(Y.options.reveal)===!0||Z0(Y.options.r)===!0||Z0(Y.options.plain)===!0,Q=Z0(Y.options.save)===!0||Z0(Y.options.add)===!0;await uj(z,{reveal:U,save:Q,name:h(Y.options.name),overwrite:Z0(Y.options.overwrite)===!0,force:Z0(Y.options.force)===!0,appKey:h(Y.options["app-key"])??h(Y.options.appKey),keyId:h(Y.options["key-id"])??h(Y.options.keyId)})}async function ij($,Y,z){if($==="check"||$==="diagnose"||$==="status"||$==="test"||$==="doctor"){x0(await pg1(Y));return}if($==="seal-link"||$==="link"||$==="hose-link"&&Y?.source?.type==="seal"){let U=z.command[2]?.toLowerCase(),Q=h(z.options["from-link"])??(U==="from-link"?z.command[3]:void 0);if(Q){let X=h(z.options.note),Z=await Jw(Q),q=y6(Z.sealUrl,Z.token),V=await T8(q);Iw(Z.corpId,V.tenant);let F=await aQ(q,{note:X});x0({tenant:{id:V.tenant.id,name:V.tenant.name,tenantSlug:V.tenant.tenantSlug,corpId:Z.corpId},user:{id:V.user.id,name:V.user.name,providerUserId:V.user.providerUserId,isAdmin:V.user.isAdmin},delegation:F,expiresIn:Z.expiresIn});return}let J=await P1(Y);if(U==="list"){await k0("seal_delegation_list",J,Y,{},E0(z.options));return}if(U==="revoke"){let X=z.command[3]??h(z.options.tokenId)??h(z.options.id);if(!X)throw Error("Usage: seal-use auth link revoke <tokenId>");await k0("seal_delegation_revoke",J,Y,{tokenId:X},E0(z.options));return}let I=h(z.options.note)??"CLI generated provisional access link",K=await O$("seal_delegation_create",J,Y,{note:I});if($==="hose-link")console.error(`\uD83D\uDC49提示:企业「${Y.name}」源类型为Seal原生测试环境,已自动为您生成委托免登直达链接。`);let G=K,H="staffName"in Y.source&&typeof Y.source.staffName==="string"?Y.source.staffName:void 0,W=Zo(Date.now()+86400000);x0({id:G.id,corpId:Y.source.corpId??Y.id,corpName:Y.name,staffId:Y.source.staffId,...H?{staffName:H}:{},link:G.link,expiresAt:W,token:G.token});return}if($==="hose-link"){let U=z.options.expire,Q=U!==void 0?s0(U):7200;if(Q===void 0||Q<=0)throw Error(`Invalid--expire:${String(U)}.Mustbeapositivenumberofseconds(e.g.--expire7200or--expire86400).`);let J=Z0(z.options.force)===!0||Z0(z.options.refresh)===!0||Z0(z.options.f)===!0,I=await m00(Y,Q,{force:J}),K="staffName"in Y.source&&typeof Y.source.staffName==="string"?Y.source.staffName:void 0,G=Zo(Date.now()+Q*1000);x0({corpId:Y.source.corpId??Y.id,corpName:Y.name,staffId:Y.source.staffId,...K?{staffName:K}:{},link:I.url,expiresAt:G,token:I.token});return}if($==="keys"||$==="hose-keys"){let U=Z0(z.options.reveal)===!0||Z0(z.options.r)===!0||Z0(z.options.plain)===!0;await Ho(Y.id,{reveal:U});return}throw Error(`Unknownauthcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function pg1($){if($.source.type!=="hose"){let F=await P1($),w=await T8(F);return{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:w.user,tenant:w.tenant}]}}Qw($.id);let Y=$.source,z=Y.appKey??Y.key,U=Y.appSecurity??Y.password,Q=($.seal.url??Y.sealUrl??`https://${Y.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/,""),J=Y.staffId.includes(":")?Y.staffId:`${Y.corpId}:${Y.staffId}`,I=[];if(!z||!U)return{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:!1,stages:[{name:"hose.openapi",ok:!1,error:"Hose source requires appKey/key and appSecurity/password"}]};let K=await bj("hose.openapi",async()=>{let F=await fh0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1/auth/getAccessToken`,{appKey:z,appSecurity:U}),w=o3(F.value),O=n6(w.accessToken)??n6(F.accessToken)??n6(F.token);if(!O)throw Error("Hose login did not return an access token");return{token:O,public:{corporationId:n6(w.corporationId)??n6(o3(w.corporation).id),expireTime:vq(w.expireTime)}}});I.push(K.public);let G=K.private?.token,H=G?await bj("hose.provisional",async()=>{let F=await fh0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=${encodeURIComponent(G)}`,{uid:J,pageType:"home",expireDate:7200}),w=n6(o3(F.value).message);if(!w)throw Error("Hose CloseAPI did not return a provisional auth URL");let O=new URL(w).searchParams.get("accessToken");if(!O)throw Error("Hose provisional auth URL did not include accessToken");return{token:O,public:{uid:J,enterpriseUrl:Tq(w)}}}):Xo("hose.provisional");I.push(H.public);let W=A6($.seal),X=H.private?.token,Z=X?await bj("seal
Line truncated
`);R0({provider:"hose",capability:"privilege-elevation",corpId:Y.id,corpName:Y.name,domain:Y.source.domain,staffId:Y.source.staffId,appKey:I??"-",appSecurity:Q?z?Q:_H(Q):"-",active:!0})}var yv0=m(()=>{E$();zo();Jo();Tv0();bT();_v0();O8();O4();Z4();m1();iT()});var xv0,fv0,cT,kv0,o4;var U5=m(()=>{xv0=/^[\uD800-\uDBFF]$/,fv0=/^[\uDC00-\uDFFF]$/,cT=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;(function($){$[$.Unknown=0.0000000000001]="Unknown",$[$.Rule=0.000000000001]="Rule",$[$.DICT=0.00000002]="DICT",$[$.Surname=1]="Surname",$[$.Custom=1]="Custom"})(kv0||(kv0={}));o4={Normal:1,Surname:10,Custom:100}});function e2($){var U;return $.length-(((U=$.match(cT))===null||U===void 0?void 0:U.length)||0)}function O$($){if(cT.lastIndex=0,!cT.test($))return $.split("");let U=[],Y=0;while(Y<$.length){let z=$[Y];if(xv0.test(z)&&fv0.test($[Y+1]))U.push($.substring(Y,Y+2)),Y+=2;else U.push(z),Y+=1}return U}class iK{constructor(){this.NumberDICT=[],this.StringDICT=new Map}get($){if($.length>1)return this.StringDICT.get($);else{let U=$.charCodeAt(0);return this.NumberDICT[U]}}set($,U){if($.length>1)this.StringDICT.set($,U);else{let Y=$.charCodeAt(0);this.NumberDICT[Y]=U}}clear(){this.NumberDICT=[],this.StringDICT.clear()}}var k9=m(()=>{U5()});function pg1(){let $={零一:"líng yī",〇一:"líng yī",十一:"shí yī",一十:"yī shí",第一:"dì yī",一十一:"yī shí yī"};for(let U in uv0)for(let Y in bv0){let z=`${U}${Y}`,I=`${uv0[U]}${bv0[Y]}`;$[z]=I}return $}var nv0,cv0,dv0,pv0,mv0,uv0,bv0,iv0,lv0,Go,ov0,rv0;var Ho=m(()=>{U5();k9();nv0=["zh","ch","sh","z","c","s","b","p","m","f","d","t","n","l","g","k","h","j","q","x","r","y","w",""],cv0=["j","q","x"],dv0=["uān","uán","uǎn","uàn","uan","uē","ué","uě","uè","ue","ūn","ún","ǔn","ùn","un","ū","ú","ǔ","ù","u"],pv0={uān:"üān",uán:"üán",uǎn:"üǎn",uàn:"üàn",uan:"üan",uē:"üē",ué:"üé",uě:"üě",uè:"üè",ue:"üe",ūn:"ǖn",ún:"ǘn",ǔn:"ǚn",ùn:"ǜn",un:"ün",ū:"ǖ",ú:"ǘ",ǔ:"ǚ",ù:"ǜ",u:"ü"},mv0=["ia","ian","iang","iao","ie","iu","iong","ua","uai","uan","uang","ue","ui","uo","üan","üe","van","ve"],uv0={一:"yì",二:"èr",三:"sān",四:"sì",五:"wǔ",六:"liù",七:"qī",八:"bā",九:"jiǔ",十:"shí",百:"bǎi",千:"qiān",万:"wàn",亿:"yì",单:"dān",两:"liǎng",双:"shuāng",多:"duō",几:"jǐ",十一:"shí yī",零一:"líng yī",第一:"dì yī",一十:"yī shí",一十一:"yī shí yī"},bv0={重:"chóng",行:"háng",斗:"dǒu",更:"gēng"};iv0=pg1(),lv0=Object.keys(iv0).map(($)=>({zh:$,pinyin:iv0[$],probability:0.000000000001,length:e2($),priority:o4.Normal,dict:Symbol("rule")})),Go={不:{bú:[4]},一:{yí:[4],yì:[1,2,3]}},ov0={不:["的","而","之","后","也","还","地"],一:["的","而","之","后","也","还","是"]},rv0=Object.keys(Go)});var sv0,_5;var dT=m(()=>{k9();sv0={"bǎng páng pāng":["膀"],líng:["〇","伶","凌","刢","囹","坽","夌","姈","婈","孁","岺","彾","掕","昤","朎","柃","棂","櫺","欞","泠","淩","澪","灵","燯","爧","狑","玲","琌","瓴","皊","砱","祾","秢","竛","笭","紷","綾","绫","羐","羚","翎","聆","舲","苓","菱","蓤","蔆","蕶","蛉","衑","裬","詅","跉","軨","輘","酃","醽","鈴","錂","铃","閝","陵","零","霊","霗","霛","霝","靈","駖","魿","鯪","鲮","鴒","鸰","鹷","麢","齡","齢","龄","龗","㥄"],yī:["一","乊","伊","依","医","吚","咿","噫","壱","壹","夁","嫛","嬄","弌","揖","撎","檹","毉","洢","渏","漪","瑿","畩","祎","禕","稦","繄","蛜","衤","譩","辷","郼","醫","銥","铱","鷖","鹥","黟","黳"],"dīng zhēng":["丁"],"kǎo qiǎo yú":["丂"],qī:["七","倛","僛","凄","嘁","墄","娸","悽","慼","慽","戚","捿","柒","桤","桼","棲","榿","欺","沏","淒","漆","紪","緀","萋","褄","諆","迉","郪","鏚","霋","魌","鶈"],shàng:["丄","尙","尚","恦","緔","绱"],xià:["丅","下","乤","圷","夏","夓","懗","梺","疜","睱","罅","鎼","鏬"],hǎn:["丆","喊","浫","罕","豃","㘎"],"wàn mò":["万"],zhàng:["丈","仗","墇","嶂","帐","帳","幛","扙","杖","涱","痮","瘬","瘴","瞕","粀","胀","脹","賬","账","障"],sān:["三","厁","叁","弎","毵","毶","毿","犙","鬖"],"shàng shǎng shang":["上"],"qí jī":["丌","其","奇"],"bù fǒu":["不"],"yǔ yù yú":["与"],miǎn:["丏","偭","免","冕","勉","勔","喕","娩","愐","汅","沔","湎","睌","緬","缅","腼","葂","靦","鮸","\uD867\uDF83"],gài:["丐","乢","匃","匄","戤","概","槩","槪","溉","漑","瓂","葢","鈣","钙","\uD872\uDFBF"],chǒu:["丑","丒","侴","吜","杽","瞅","矁","醜","魗"],zhuān:["专","叀","嫥","専","專","瑼","甎","砖","磗","磚","蟤","諯","鄟","顓","颛","鱄","䏝"],"qiě jū":["且"],pī:["丕","伓","伾","噼","坯","岯","憵","批","披","炋","狉","狓","砒","磇","礔","礕","秛","秠","耚","豾","邳","鈚","鉟","銔","錃","錍","霹","駓","髬","魾","\uD873\uDCF5"],shì:["世","丗","亊","事","仕","侍","冟","势","勢"
Line truncated
`+`\uD83D\uDC49查看全部请添加:seal-usecorpslist--all
`+"\uD83D\uDC49 检索指定企业请使用: seal-use corps search <keyword>")}return R0(w.map((N)=>({id:N.id,name:N.name,environment:N.environment??"production",sourceType:N.source.type,provider:N.source.provider??N.source.type,staffId:N.source.staffId,testCorpId:N.testCorpId,prodCorpId:N.prodCorpId,current:N.id===H}))),!0}if($==="get"||$==="show"){let z=U??S(Y.options.corp);if(!z)throw h4("Usage: seal-use corps get <corpId>");let I=M1(z),Q=Td(I.id),J=hv0(I);return R0({id:I.id,name:I.name,environment:I.environment??"production",configFile:Q,seal:{url:J,tenantSlug:I.seal.tenantSlug??I.source.tenantSlug,customHeaderNames:I.seal.headers?Object.keys(I.seal.headers):[],customCookieNames:I.seal.cookies?Object.keys(I.seal.cookies):[],endpoints:I.seal.endpoints},source:Sv0(I.source),relations:{testCorpId:I.testCorpId,prodCorpId:I.prodCorpId},auth:{refreshTtl:I.auth.refreshTtl}}),!0}if($==="current"){let z=M1(S(Y.options.corp));return R0({id:z.id,name:z.name,environment:z.environment??"production",sourceType:z.source.type,provider:z.source.provider??z.source.type,staffId:z.source.staffId,testCorpId:z.testCorpId,prodCorpId:z.prodCorpId}),!0}if($==="mark"||$==="mark-test"||$==="mark-prod"){let z=U??S(Y.options.corp);if(!z)throw h4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");let I=M1(z),Q=$==="mark-test"?"test":$==="mark-prod"?"production":S(Y.options.env)??S(Y.options.environment);if(Q!=="production"&&Q!=="test")throw h4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");if(!(G0(Y.options.confirm)===!0||G0(Y.options.yes)===!0))throw F$(`Refusingtochangeenvironmenttagofenterprise'${I.name}'(${I.id})to'${Q}'without--confirm.Markingalterssynchronizationsafetyguards.`,`seal-usecorpsmark${I.id}--env${Q}--confirm`);let K=E9(I.id,{environment:Q});return R0({id:K.id,name:K.name,environment:K.environment,testCorpId:K.testCorpId,prodCorpId:K.prodCorpId}),!0}if($==="rename"){let z=U??S(Y.options.corp)??S(Y.options.id),I=S(Y.options.name)??S(Y.options.to)??(Y.command[3]&&!Y.command[3].startsWith("-")?Y.command[3]:void 0);if(!z||!I)throw Error("Usage: seal-use corps rename <corpId> --name <newName>");let Q=M1(z),J=E9(Q.id,{name:I});return R0({success:!0,id:J.id,name:J.name,previousName:Q.name}),!0}if($==="switch"){let z=U;if(!z)throw Error("Usage: seal-use corps switch <corpId>");let I=v4();if(!I.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-useconfigmodestateful` first.");let Q=M1(z);return qz({...I,stateful:!0,defaultCorpId:Q.id}),R0({current:!0,id:Q.id,name:Q.name}),!0}return!1}var eh0=m(()=>{T5();ah0();YP();O4();O8();Z4();m1();iT()});import{existsSync as Vy1,mkdirSync as Ly1,readFileSync as wy1,writeFileSync as $S0}from"node:fs";import{homedir as Fy1}from"node:os";import{join as sT}from"node:path";function US0(){let $=process.env.SEAL_USE_MAPPINGS_DIR?.trim();if($)return $;return sT(Fy1(),".config","seal-use","mappings")}function YS0($){let U=US0();Ly1(U,{recursive:!0,mode:448});let Y=sT(U,`${$.target.id}-v${$.target.publishedVersionNumber}.json`),z=sT(U,`${$.target.id}-latest.json`),I=JSON.stringify($,null,2);return $S0(Y,I,{encoding:"utf-8",mode:384}),$S0(z,I,{encoding:"utf-8",mode:384}),Y}function zS0($,U){let Y=US0(),z;if(!U||U==="latest")z=`${$}-latest.json`;else{let Q=String(U).replace(/^v/i,"");z=`${$}-v${Q}.json`}let I=sT(Y,z);if(!Vy1(I))return null;try{let Q=wy1(I,"utf-8");return JSON.parse(Q)}catch{return null}}function IS0($,U){if(!U)return $;let Y=U.trim().toLowerCase();return $.filter((z)=>{return String(z.sourceRuleCode).toLowerCase()===Y||String(z.targetRuleCode).toLowerCase()===Y||z.sourceRuleId.toLowerCase()===Y||z.targetRuleId.toLowerCase()===Y||`#${z.sourceRuleCode}`.toLowerCase()===Y||`#${z.targetRuleCode}`.toLowerCase()===Y})}function QS0($,U,Y){let z=0,I=U!==void 0?new RegExp(`\\[Prodv${U}\\s*·\\s*#(\\d+)(?:[^\\]]*)\\]`):/\[Prod draft\s*·\s*#(\d+)(?:[^\]]*)\]/;for(let J of Y){if(!J.versionName)continue;let K=J.versionName.match(I);if(K&&K[1]){let G=parseInt(K[1],10);if(!isNaN(G)&&G>z)z=G}}if(z>0)return z+1;if(!Y.some((J)=>J.versionName&&/\[Prod v\d+/.test(J.versionName))){let J=Y.filter((K)=>K.versionName&&K.versionName.includes(`Syncfrom${$}`)).length;if(J>0)return J+1}return 1}function JS0($,U,Y,z){let I=U!==void 0?`Prodv${U}`:"Prod draft",Q=z!==void 0?`->Testv${z}`:"";return`Syncfrom${$}[${I}·#${Y}${Q}]`}var No=()=>{};import{randomBytes as My1}from"node:crypto";async function aT($,U,Y={}){let z=await B1($),I=await B1(U),[Q,J,K,G,H,W,X,Z]=await Promise.all([r1(z,$.seal.endpoints.approvalStylePreferences),r1(I,U.seal.endpoints.approvalStylePreferences),W6(z),W6(I),d8(z),d8(I),KS0(z),KS0(I)]),q=(X.articles||[]).filter((R)=>!R.isDeleted),V=(Z.articles||[]).filter((R)=>!R.isDeleted),F=new Map(V.map((R)=>[R.title.trim(),R])),M=[],w=[],N=new Set(q.map((R)=>R.title.trim()));for(let R of q){let o=R.title.trim(),e=F.get(o);if(!e){M.push(R);continue}let O0=[["co
Line truncated
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,F=Z.apiOrigin??"production";console.error(`•"${q}"(signKey:${V},环境:${F})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${V}--corp${Q.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let F=V.outboundName??"SealAI 审批",w=V.signKey,O=V.apiOrigin??"production";console.error(`•"${F}"(signKey:${w},环境:${O})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${w}--corp${Q.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,F=Z.apiOrigin??"production";console.error(`•"${q}"(signKey:${V},环境:${F})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${V}--corp${I.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let F=V.outboundName??"SealAI 审批",M=V.signKey,w=V.apiOrigin??"production";console.error(`•"${F}"(signKey:${M},环境:${w})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${M}--corp${I.id}
description:"v0.10.37: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
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 JS0=()=>{};var GS0="# 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 hS0=()=>{};var yS0="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--batch<batchId>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest--fieldsrecordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-useapproval-runsget<recordId>--corp<corpId>--summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsmetadata\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.fields,result.summary\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsresult.summary,result.decision,result.riskPoints\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runsget<recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-useapproval-runsdocument-summary<recordId>--corp<corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-useapproval-runscited-rules<recordId>--corp<corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rulesget--record-id<recordId>--runtime-idrule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\n#查看附件列表摘要(包含文件名、类型、大小及直链可用性)\nseal-useapproval-runsattachments<recordId>--corp<corpId>--summary\n\n#下载全部附件到本地目录(优先使用ossSignedUrl签名直链)\nseal-useapproval-runsattachmentsdownload<recordId>--all--out-dir./downloads--corp<corpId>\n\n#按名称或fileId过滤下载单个附件\nseal-useapproval-runsattachmentsdownload<recordId>--name发票--corp<corpId>\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-useapproval-runsresult<recordId>--corp<corpId>--summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Approval Run Web Links & Auto-Login Links\n\nUse this when the user asks for a link to an approval run or wants to open the run directly in their browser:\n\n```bash\n#默认推荐:生成SealAI审核详情直达链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)\nseal-useapproval-runslink<recordId>--corp<corpId>\nseal-useapproval-runslink--sn<sourceDocumentSN>--corp<corpId>\n\n#生成合思主系统原始单据页面链接\nseal-useapproval-runslink<recordId>--typehose-document--corp<corpId>\n\n#仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带合思单次临时票据的免登直达链接\nseal-useapproval-runslink<recordId>--auto-login[--expire7200]--corp<corpId>\n```\n\n### 返回字段说明与语义规范\n- `sealResultUrl`: Seal AI 单据智能审核结果页\n- `hoseDocumentUrl`: 合思费控主系统原始报销/借款单详情页\n- `type`: 链接类型,默认为 `seal_result`,指定时可为 `hose_document`\n- `mode`: 鉴权模式,`direct`(原生直接打开)或 `auto_login`(免密换票)\n\n### 免登链接安全与声明规范\n当向用户返回 `--auto-login` 链接时
Line truncated
|Hose/合思-sourcedSealtenant|Hose\`appKey\` + \`appSecurity\` | 【最高·永久】自动签名/续期 | Stable, refreshable standard integration; unlocks full OpenAPI and \`deploy hosecloud sync\`. |
|Hose/合思-sourcedSealtenant|Hoseauthorization/assistancelink(\`thirdparty.html\`) | 【两极分化】普通导入→短效;提权→永久 | Temporary session that can be **elevated** to permanent \`appKey\`/\`appSecurity\` with \`extract-keys --save\` or \`add-link --as-hose\`. |
|Hose/合思-sourcedSealtenant|Hoseauthorization/assistancelink(\`thirdparty.html\`) | 【两极分化】普通导入→短效;提权→永久 | Temporary session that can be **elevated** to permanent \`appKey\`/\`appSecurity\` with \`extract-keys --save\` or \`add-link --elevate-hose\`. |
|Hose/合思-sourcedSealtenant|cURLcopiedfromanauthenticated**Hoseadmin**page|【两极分化】普通导入→短效;提权→永久|**Samesessionscopeasanassistancelink.**IftheuserisaHoseadministrator,thiscarriesthesamewebsessioncredentials(\`accesstoken\`, \`corpid\`, cookies) and can equally invoke \`/api/innerapi/v1/key\` to extract permanent \`appKey\`/\`appSecurity\`. |
|Seal-nativetenant|SealURL+BearerToken,orcURLcopiedfromanauthenticatedSealpage|【短效会话快照】|Bothnormalizeto\`add-seal-bearer\`; the cURL is only a transport format for the same Seal Bearer credential. |
**同等凭据原则(EqualCredentialScopePrinciple)**:AHoseassistancelinkandabrowsercURLfromanauthenticatedHoseadminsessionarebothHosewebfrontendsessions—theycarrythesameunderlying\`accessToken\`/\`accesstoken\` and \`corpid\`. The **only** structural difference is delivery format. When a Hose administrator sends you a cURL, treat it with the same privilege elevation potential as an assistance link. Do not downgrade it to a plain Seal session import without first attempting key extraction.
Credentialshapealonedoesnotdefineidentityorigin.Inparticular,aHose-sourcedusereventuallyreceivesaSealBearersessionafterSSO.When\`whoami\` returns provider metadata, preserve it and use it to describe the tenant accurately.
###Tokenboundary
TheHoseweb-session\`accesstoken\` and the Seal Bearer Token are different credentials and are not interchangeable:
-\`corps add-seal-bearer\` accepts the Seal Bearer Token together with \`sealUrl\`.
-AHosecURL's\`accesstoken\` is used first for Hose key extraction. If no permanent OpenAPI key can be extracted, call \`add-hose-web-session\`; it stores the Hose \`closeToken\` and \`staffId\`, then exchanges the Hose session through Seal SSO only when a Seal session is needed.
-NeverpassaHose\`accesstoken\` directly as the \`token\` field of \`add-seal-bearer\`.
Thesavedconfigmakesthelifecyclevisible:durableHosecredentialsuse\`source.type: "hose"\` with \`appKey/appSecurity\`; Hose Web Session credentials also use \`source.type: "hose"\`, but carry \`closeToken\` and \`staffId\` instead. If the Hose session material provides an expiry, it is stored as \`expiresIn\` (seconds) and \`expiresAt\` in UTC second precision, such as \`2026-09-22T05:30:00Z\`. The Seal Bearer obtained through SSO is a runtime cache, not the enterprise source type.
TheCLIprobesthestandarddomains,discoversthecorporation,anddiscoversadministratorcandidates.Ifitreturnsmultiplecandidates,showonlyusefulidentifyinginformationandaskwhichpersonshouldbeused;retrywith\`staffName\`, \`staffPhone\`, or the selected \`staffId\` internally. After creation, run:
@@ -1728,8 +1756,8 @@ Do not ask for \`domain\`, \`corpId\`, or \`proxyStaffBizId\` up front. For a de
-**Seal-NativeDelegationLink(默认第一公民)**:\`https://<tenant>.sealai.cc/delegate?token=...\` grants delegated access directly on a Seal tenant. Running \`seal-use corps add-link <url>\` automatically exchanges the delegation token via \`/api/v1/delegation/consume\`, receives the session, retrieves tenant and user info via \`/api/v1/auth/me\`, and registers a native Seal enterprise (\`provider: "seal"\`). Supports \`--dry-run\` to preview metadata without mutating local config.
-**Hose/合思AssistanceLink**:\`https://<domain>/web/thirdparty.html?...\` opens an upstream Hose session and continues through Seal SSO. Running standard \`seal-use corps add-link <url>\`exchanges that temporary token for a short-lived Seal Bearer token.
-**HoseSubdomainBoundary(合思子域专属提权)**:\`seal-use\` primarily manages Seal tenants. Tenants sourced from the Hose ecosystem have an upstream Hose enterprise backing them. A received Hose assistance link contains only a temporary session \`accessToken\`. To elevate to permanent Hose OpenAPI developer credentials, use \`corps hose-extract-keys <url> --save\` or \`corps add-link <url> --as-hose\`. (Note: \`--as-hose\` cannot be used on Seal-native delegation links).
-**Hose/合思AssistanceLink**:\`https://<domain>/web/thirdparty.html?...\` opens an upstream Hose session and continues through Seal SSO. Running standard \`seal-use corps add-link <url>\`verifies the tenant and stores the Hose \`closeToken\` plus \`staffId\`; the Seal Bearer is runtime-only.
-**HoseSubdomainBoundary(合思子域专属提权)**:\`seal-use\` primarily manages Seal tenants. Tenants sourced from the Hose ecosystem have an upstream Hose enterprise backing them. A received Hose assistance link contains only a temporary session \`accessToken\`. To elevate to permanent Hose OpenAPI developer credentials, use \`corps hose-extract-keys <url> --save\` or \`corps add-link <url> --elevate-hose\`. (Note: \`--elevate-hose\` cannot be used on Seal-native delegation links; \`--as-hose\` remains a deprecated compatibility alias).
-**Multi-KeyDisambiguation(多套密钥明确抉择)**:IftheHoseenterpriseownsmultipleapplicationkeys,theCLIwillnotguessorsilentlypickthefirstkey.Instead,itterminateswithaninformativecandidatelistandrequirestheusertospecify\`--app-key <key>\` or \`--key-id <id>\`. If only one key exists, it is selected automatically.
-**Non-HoseTenantsBlocked**:Calling\`keys\` on native Seal enterprises (\`corp.source.type !== "hose"\`) is strictly rejected with exit code 2, explaining that this capability belongs exclusively to the Hose ecosystem.
@@ -1740,7 +1768,7 @@ First distinguish the link by its host, purpose, and identity origin:
@@ -1758,7 +1786,7 @@ seal-use corps hose-keys <corpId> [--reveal]
seal-useauthhose-keys--corp<corpId>[--reveal]
\`\`\`
Whenusingstandard\`add-link\` with a Seal delegate link, it consumes the token directly against the Seal tenant and persists the verified Seal session. When using standard \`add-link\` with a Hose link (without \`--as-hose\`), it exchanges the temporary Hose token at the target Seal tenant and stores the short-lived Seal session. When \`--as-hose\` is used on a Hose link, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration.
Whenusingstandard\`add-link\` with a Seal delegate link, it consumes the token directly against the Seal tenant and persists the verified Seal session. When using standard \`add-link\` with a Hose link (without \`--elevate-hose\`), it stores the Hose web-session source (\`closeToken\` plus \`staffId\`) and uses the temporary Seal Bearer only at runtime. When \`--elevate-hose\` is used on a Hose link, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration. The legacy \`--as-hose\` alias remains accepted for compatibility.
2.Extract:therequesthostname(determines\`baseUrl\`), \`accesstoken\` header (session token), \`corpid\` header or cookie, and any other Hose session headers.
3.**Privilegeelevationpath(preferred)**:Useextracted\`accesstoken\`, \`corpid\`, and \`baseUrl\` to call \`/api/innerapi/v1/key\`, exactly as \`corps hose-extract-keys\` does for assistance links. This retrieves permanent \`appKey\`/\`appSecurity\` to register a durable Hose enterprise configuration — do not skip this step just because the input is a cURL instead of a URL.
4.**Fallbackshort-termpath**:Ifthesessionuserisnotanadministratorandthekeyinterfacereturnsnokeys,passthenormalizedHosesessionto\`corps add-hose-web-session\`; it saves the Hose \`closeToken\` and \`staffId\`, then uses the Seal SSO bridge only when a Seal session is needed.
@@ -1926,16 +1956,16 @@ Use this reference for Hose/合思 enterprise configuration and user-facing Hose
UsetheCLIfornormalenterprisesetup.Donotinspectsourcecodeorhand-edit\`~/.config/seal-use/enterprises/*.json\` unless the CLI fails or the user explicitly asks for low-level config debugging.
Forfirst-timesetuporwhentheuserhasanassistancelinkorbrowsercURLinsteadofstandardapplicationcredentials,read\`enterprise-onboarding.md\` first. This reference's \`add-hose\` route is specifically for durable Hose OpenAPI credentials.
Forfirst-timesetuporwhentheuserhasanassistancelinkorbrowsercURLinsteadofstandardapplicationcredentials,read\`enterprise-onboarding.md\` first. This reference's \`add-hose-persistent\` route is specifically for durable Hose OpenAPI credentials.
\`corps add-hose\` probes standard domains and discovers the enterprise automatically. If it returns multiple administrator candidates, present their names and masked phones for the user to choose, then retry with \`staffName\`, \`staffPhone\`, or the selected \`staffId\`. Do not ask for \`domain\`, \`corpId\`, \`staffId\`, or \`proxyStaffBizId\` before discovery. Ask for a dedicated/private-cloud \`domain\` only after standard probing fails.
\`corps add-hose-persistent\` probes standard domains and discovers the enterprise automatically. If it returns multiple administrator candidates, present their names and masked phones for the user to choose, then retry with \`staffName\`, \`staffPhone\`, or the selected \`staffId\`. Do not ask for \`domain\`, \`corpId\`, \`staffId\`, or \`proxyStaffBizId\` before discovery. Ask for a dedicated/private-cloud \`domain\` only after standard probing fails. The old \`add-hose\` spelling remains a compatibility alias.
Thecommandverifiesbydefaultandwritestheenterpriseconfig.Iftheusersaysnottooperatebusinesslogic,stopat\`corps\` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
@@ -1987,7 +2017,7 @@ Important:
3.BOTHacodeblock(\`\`\`\`text ... \`\`\`\`) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
-**DedicatedCLICommand**:Use\`seal-use auth hose-link --corp <corpId> [--expire <seconds>] [--force]\`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports \`--expire\` (default 7200, e.g. 86400 for 1 day).
-**SealAIPlatformDirectLink**:Use\`seal-use auth link --corp <corpId> [--note <note>]\`. This generates a 24-hour provisional delegation link for the Seal AI audit platform (\`https://*.sealai.cc\`).
@@ -2302,7 +2332,7 @@ Use current search only when the question is about current draft/current knowled
##OutputDiscipline
Ifarulecommandwouldreturnmanydescriptionsormorethanabout20rules,use\`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports.
`;var BS0=()=>{};var TS0="# Seal Approval Rule Linter & Quality Validation\n\nUse this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.\n\n## Key Principles\n\n- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled:false`) to avoid unsolicited noise during standard operations.\n- **Doctor Visibility**: `seal-usedoctor` audits the rule linter configuration state and active linter name in its health checks, and surfaces a one-click hint (`seal-useconfiglintenable`) when disabled.\n- **Explicit Triggering**: `seal-useruleslint` always runs regardless of global configuration.\n- **Draft Hook**: When `seal-useconfiglintenable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.\n- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.\n\n## CLI Commands\n\n### 1. Lint Current Draft Rules (Whole-RuleSet Scan)\n\n```bash\nseal-useruleslint--corp<corpId>\n```\n\n### 2. Lint Specific Historical Version or Single Rule\n\n```bash\n#Lintrulesinpublishedversion16\nseal-useruleslint--version16--corp<corpId>\n\n#Lintaspecificrulebycode(#0038)\nseal-useruleslint--code'#0038'--corp<corpId>\n\n#Summarymode(onlyshowruleswithissues)\nseal-useruleslint--summary--corp<corpId>\n```\n\n### 3. Quality Gate for CI / Release\n\n```bash\n#Ifoverallscoreisbelow85,terminateswithexitcode1\nseal-useruleslint--min-score85--levelerror--corp<corpId>\n```\n\n### 4. Configure Global Linter Settings\n\n```bash\n#Checkstatus\nseal-useconfiglintstatus\n\n#Enableautolintonruleupdates\nseal-useconfiglintenable--linterbuiltin--min-score80\n\n#Disableautolint\nseal-useconfiglintdisable\n```\n\n## Official Linters\n\n| Linter Name | Scope & Purpose | Aliases |\n| :--- | :--- | :--- |\n| `builtin` | Seal 官方标准校验器:拦截过短描述、主观模糊词与悬空例外条款。 | `default`, `official/builtin` |\n| `strict` | Seal 官方严格风控校验器:强校验字数、刚性定量约束、凭证依据与具体审批人角色。 | `official/strict` |\n| `hlab` | 合思实验室 (HLab) 结构化规则校验器:SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判。 | `hlab-sop`, `hlab-rules`, `hlab-standard`, `official/hlab` |\n\n```bash\n#Inspectavailablelinters\nseal-useruleslinters\n\n#LintrulesusingHLabSOPstandard\nseal-useruleslint--linterhlab--corp<corpId>\n\n#LintlocalruleworkspaceofflinewithHLabstandard\nseal-useruleslint--linterhlab--file./rules.local.json\n```\n\n## Built-In Detection Rules (`builtin`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |\n| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |\n| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |\n\n## HLab SOP Detection Rules (`hlab`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `MISSING_CHECK_METHOD` | `error` | Missing `**检查方法**` section in rule description. | Add `**检查方法**:` specifying fields, vouchers, and normalization logic. |\n| `MISSING_EVAL_STANDARD` | `error` | Missing `**判定标准**` section in rule description. | Add `**判定标准**:` with standard branches. |\n| `INCOMPLETE_TERNARY_BRANCH` | `error` | Incomplete ternary branch under evaluation criteria (missing `PASS`, `FAIL`, or `证据不足`). | Provide complete ternary closure: `-PASS:`, `-FAIL:`, `-证据不足:`. |\n| `INSUFFICIENT_WITHOUT_MANUAL_REVIEW` | `warning` | `证据不足` branch does not specify escalating to `人工复核`. | Add `转人工复核` at the end of `证据不足` branch. |\n| `DISPOSAL_ACTION_LEAK` | `warning` | Contains whole-bill workflow disposal actions (`驳回单据`, `直接驳回`, `进行提醒`, `退回单据`). | Decouple disposal actions from rule text; rely on rule strictness or platform workflow. |\n| `SCOPE_FALSE_SKIP_PRONE` | `warning` | Scope contains material upload conditions (`若上传了`, `若提供了`, `附件需上传`). | Keep scope pure to business triggers; handle missing materials explicitly in FAIL branch to prevent silent SKIP. |\n| `RISK_SUPPRESSION` | `erroLine truncated
`;var sS0=()=>{};var eS0="# Seal Approval Rule Linter & Quality Validation\n\nUse this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.\n\n## Key Principles\n\n- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled:false`) to avoid unsolicited noise during standard operations.\n- **Doctor Visibility**: `seal-usedoctor` audits the rule linter configuration state and active linter name in its health checks, and surfaces a one-click hint (`seal-useconfiglintenable`) when disabled.\n- **Explicit Triggering**: `seal-useruleslint` always runs regardless of global configuration.\n- **Draft Hook**: When `seal-useconfiglintenable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.\n- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.\n\n## CLI Commands\n\n### 1. Lint Current Draft Rules (Whole-RuleSet Scan)\n\n```bash\nseal-useruleslint--corp<corpId>\n```\n\n### 2. Lint Specific Historical Version or Single Rule\n\n```bash\n#Lintrulesinpublishedversion16\nseal-useruleslint--version16--corp<corpId>\n\n#Lintaspecificrulebycode(#0038)\nseal-useruleslint--code'#0038'--corp<corpId>\n\n#Summarymode(onlyshowruleswithissues)\nseal-useruleslint--summary--corp<corpId>\n```\n\n### 3. Quality Gate for CI / Release\n\n```bash\n#Ifoverallscoreisbelow85,terminateswithexitcode1\nseal-useruleslint--min-score85--levelerror--corp<corpId>\n```\n\n### 4. Configure Global Linter Settings\n\n```bash\n#Checkstatus\nseal-useconfiglintstatus\n\n#Enableautolintonruleupdates\nseal-useconfiglintenable--linterbuiltin--min-score80\n\n#Disableautolint\nseal-useconfiglintdisable\n```\n\n## Official Linters\n\n| Linter Name | Scope & Purpose | Aliases |\n| :--- | :--- | :--- |\n| `builtin` | Seal 官方标准校验器:拦截过短描述、主观模糊词与悬空例外条款。 | `default`, `official/builtin` |\n| `strict` | Seal 官方严格风控校验器:强校验字数、刚性定量约束、凭证依据与具体审批人角色。 | `official/strict` |\n| `hlab` | 合思实验室 (HLab) 结构化规则校验器:SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判。 | `hlab-sop`, `hlab-rules`, `hlab-standard`, `official/hlab` |\n\n```bash\n#Inspectavailablelinters\nseal-useruleslinters\n\n#LintrulesusingHLabSOPstandard\nseal-useruleslint--linterhlab--corp<corpId>\n\n#LintlocalruleworkspaceofflinewithHLabstandard\nseal-useruleslint--linterhlab--file./rules.local.json\n```\n\n## Built-In Detection Rules (`builtin`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |\n| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |\n| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |\n\n## HLab SOP Detection Rules (`hlab`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `MISSING_CHECK_METHOD` | `error` | Missing `**检查方法**` section in rule description. | Add `**检查方法**:` specifying fields, vouchers, and normalization logic. |\n| `MISSING_EVAL_STANDARD` | `error` | Missing `**判定标准**` section in rule description. | Add `**判定标准**:` with standard branches. |\n| `INCOMPLETE_TERNARY_BRANCH` | `error` | Incomplete ternary branch under evaluation criteria (missing `PASS`, `FAIL`, or `证据不足`). | Provide complete ternary closure: `-PASS:`, `-FAIL:`, `-证据不足:`. |\n| `INSUFFICIENT_WITHOUT_MANUAL_REVIEW` | `warning` | `证据不足` branch does not specify escalating to `人工复核`. | Add `转人工复核` at the end of `证据不足` branch. |\n| `DISPOSAL_ACTION_LEAK` | `warning` | Contains whole-bill workflow disposal actions (`驳回单据`, `直接驳回`, `进行提醒`, `退回单据`). | Decouple disposal actions from rule text; rely on rule strictness or platform workflow. |\n| `SCOPE_FALSE_SKIP_PRONE` | `warning` | Scope contains material upload conditions (`若上传了`, `若提供了`, `附件需上传`). | Keep scope pure to business triggers; handle missing materials explicitly in FAIL branch to prevent silent SKIP. |\n| `RISK_SUPPRESSION` | `erroLine truncated
`;var ES0=()=>{};var Wy1="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:U,configured:!0,configPath:z,targetDir:Y,action:"prepended"}}function Mo($){let Y=$?.targetSkillsDir??hS0(),z=$?.configFile??SS0(),U=gS0(),Q=!1;if(hq(z))try{let J=JSON.parse(vS0(z,"utf8"));if(Array.isArray(J?.entries))Q=J.entries.some((I)=>I?.path===Y)}catch{}return{detected:U,configured:Q,configPath:z,targetDir:Y}}var No=()=>{};import{cpSync as wy1,existsSync as nK,lstatSync as kS0,mkdirSync as My1,realpathSync as $Y,rmSync as Ny1,symlinkSync as Dy1,unlinkSync as yS0}from"node:fs";import{homedir as xS0}from"node:os";import{dirname as fS0,join as YY}from"node:path";function Ay1($,Y){let z=Y?.baseHomeDir??xS0(),U=YY(z,$.rootDirName),Q=Y?.sourceSkillDir??YY(z,".agents","skills","seal-use"),J=fS0(Q),I=YY(U,"skills"),K=YY(I,"seal-use");if(!nK(U))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"skipped_not_detected"};if(nK(I)&&nK(J))try{if($Y(I)===$Y(J))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:I}}catch{}My1(I,{recursive:!0});let G;try{G=kS0(K)}catch{G=void 0}let H=!1;if(G)if(G.isSymbolicLink()){try{if($Y(K)===$Y(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"already_linked",targetPath:K}}catch{}try{yS0(K)}catch{}}else if(G.isDirectory())Ny1(K,{recursive:!0,force:!0}),H=!0;else yS0(K);let W=process.platform==="win32"?"junction":"dir";try{return Dy1(Q,K,W),{id:$.id,name:$.name,detected:!0,configured:!0,mode:H?"replaced_real_dir":"linked",targetPath:K}}catch{try{return wy1(Q,K,{recursive:!0}),{id:$.id,name:$.name,detected:!0,configured:!0,mode:"fallback_copied",targetPath:K}}catch(X){return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"error",targetPath:K,error:X?.message||String(X)}}}}function By1($,Y){let z=Y?.baseHomeDir??xS0(),U=YY(z,$.rootDirName),Q=Y?.sourceSkillDir??YY(z,".agents","skills","seal-use"),J=fS0(Q),I=YY(U,"skills"),K=YY(I,"seal-use");if(!nK(U))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"not_detected"};if(nK(I)&&nK(J))try{if($Y(I)===$Y(J))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:I}}catch{}let G;try{G=kS0(K)}catch{G=void 0}if(G){if(G.isSymbolicLink())try{if($Y(K)===$Y(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"single_symlinked",targetPath:K}}catch{}else if(G.isDirectory())return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"real_directory",targetPath:K}}return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"not_configured",targetPath:K}}function Do($){return uS0.map((Y)=>Ay1(Y,$))}function Ao($){return uS0.map((Y)=>By1(Y,$))}var uS0;var Bo=m(()=>{uS0=[{id:"workbuddy",name:"WorkBuddy",rootDirName:".workbuddy"},{id:"claude",name:"Claude",rootDirName:".claude"},{id:"qoder",name:"Qoder",rootDirName:".qoder"}]});var Po=m(()=>{No();Bo();No();Bo()});import{existsSync as Py1,mkdirSync as jo,readFileSync as jy1,rmSync as Ty1,writeFileSync as bS0}from"node:fs";import{homedir as nS0}from"node:os";import{dirname as iS0,join as gq}from"node:path";function To(){return cS0["SKILL.md"]||""}function pS0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function dS0($=gq(bU(),"SKILL.md")){try{return pS0(jy1($,"utf8"))}catch{return}}function bU(){return gq(nS0(),".agents","skills","seal-use")}function Cy1(){return gq(nS0(),".agents","skills","seal-home")}function Ry1(){let $=Cy1();if(Py1($))try{return Ty1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function mS0($=bU()){Ry1(),jo($,{recursive:!0});let Y=[];for(let[z,U]of Object.entries(cS0)){let Q=gq($,z);jo(iS0(Q),{recursive:!0}),bS0(Q,U,"utf8"),Y.push(z)}for(let[z,U]of Object.entries(Ey1)){let Q=gq($,z);jo(iS0(Q),{recursive:!0}),bS0(Q,U),Y.push(z)}return{targetDir:$,files:Y}}var cS0,Ey1,xY4;var yq=m(()=>{Lo();Lo();Po();cS0=RS0,Ey1=Object.fromEntries(Object.entries(_S0).map(([$,Y])=>[$,Buffer.from(Y,"base64")]));xY4=pS0(To())});function lS0(){return`#SealUse系统架构与运行规范白皮书
`;var $g0=()=>{};var iy1="iVBORw0KGgoAAAANSUhEUgAADVgAAAdwCAYAAACUWcTmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWKADAAQAAAABAAAHcAAAAAD4n9OGAABAAElEQVR4AeydB4AdVfX/z246pNAD0hK6dOki0rsU+dMJJVIFRYoUFUFAQUCqgHSkxx8gTRCpFkB6CU06SQi9BEhC+u7/fu7b83J3dt7bt33f5nuStzNz5947M583c+fOvPO9p6Y+mMlEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4kUDsHHrMOWQREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQigd7jxo8TChEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYIwkogtUc+bXroEVABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABCBQUx9MKERABERABERABERABERABERABERABERABERABERABERABERABESgqwiMHz/eBgwY0FWb13ZFQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQATmcAKKYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwn0npMPXscuAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj2RwP8+n26vfjbd3vpyho2fPN0+mjLTJs+qs/qaOhvYp8YWGtDLFh/U25YZ3NdWnr+/rTDvgJ6IQcckAhURqKkPVlFOZRIBERABERABERABERABERABERABERABERABERABERABERABERCBDiAwfvx4GzBAP9p2AFpVKQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiMIcR+GhSnT347lT713tT7eOpM4OYqj5+LEzNEFdZ+MyKU5Zr4jLp9fat/r1ss28NtM0WG2KLzN1nDiOnw53TCUhgNaefATp+ERABERABERABERABERABERABERABERABERABERABERABEehiAhJYdfEXoM2LgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhUPYFJ08z+7+Updsc7U8OxFARURKqyIKAqCKnqbVYQUdU2CK7iOiuIr4oirLBcgxArfHZZcrDttcwCNnefXlXPRgcgApUQkMCqEkrKIwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0GEEJLDqMLSqWAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4g8MR7M+2Cp6fY5JmFSFQhRlUQStUVBVUsF0VUCKiSSFZEsKqLkawa5yH/oN5mP195qK0/dPAcQFGHOKcTkMBqTj8DdPwiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0MUEJLDq4i+gCzY/ZcqUuNUBAwZ0wda1SREQAREQAREQAREQAREQAREQAREQAREQAREQARHoHAKd8S501AszbNT/psXIUwWhVDi2IK6qj5GriGRVEE4RlSoVWlUayYry+w2fx0Yst1DnQNNWRKCLCAQ9oUwEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKCaCFz035n20JgZ1stqQowqs9qaWmJVBR1VbRBZkdLLakN0qiCzCtMGgVXMURfW1YQsTHsFEdasMC0UCSWjOIvcbte++6V9MX2mHb7ytzypS6e/+93v7H//+1/uPuy888727W9/O35yMyhRBEoQ4NyXiYAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiECPIXDbbbfZiBEjGh0PP7aSxif90dXzks68G3k8P2VTYznNm67TvAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BoGLHp1lD74zM6qh6kK4qprwqW+YMl9TR1pYHcRWtUFHhZaqLi6TFsJbhflCOYRVtbG818H6+KGOhnr+9v4ku/DlDzrj0Mpug/fz6Xv+bOa//vWvxkcmAi0loAhWLSWm/CIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAt2WAD+sdvQPp/xwy0cjYHbb00A7JgIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAI9msCo5+rt4XdDVKoaIlfVxChVHHCMPtXoyIO4KuSoy0ayqifOFeWJUxVqSCJZfW/hwfbox1/FuqiKHF4zIqt5+39qey+zYEztij/pbwC8p0/NhVc+TddpXgSaIyCBVXOEtF4EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKBqCLz66qudtq/8iPvrX/+607aX3VBniMluvPHG7Ga1LAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUIJAzT+vi2vqN9m3RA4li0DbCTw5xuyWl+qMIFQWIk8Rpqo+Cq1YDlKokL7m4v2D7IrFOgurwvqwoiaEsIpyKebNHv9wki+FdERaSKlq7fytlrEj73vLHvvoq7gNUkM4q1BPKBTque7tCbbUoH62/tDBrOkyQ1yVfUf/u9/9rmx0qy7b2VZu2H8H4FhXXHFF+3//7/+1siYVq4RATX2wSjIqjwiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BIHx48fbgAEDOqLqHlun/6ja0QfYUQKrKVOmxF3X997R36DqFwEREAEREAEREAEREAEREAEREAEREAER6EwCs074btxcr9Me78zNalvdmEB7vwudNM3ssFvNJs2oi0KqWUE0FQVUUUiF6KreLtx5QVtt0X5lqYz+cIodevfYkKcg1KpHfBXKHvadobbvdxay0R9NsgPveyOsD3KTWiQniLjCNHyYDgqhfq7bcCmbu0+vsttpy0rEUlgqLErfje+8885NBEepwMrXE83Ko16ldbVl3zqjbHqsvj0EZdmoXb5O07YTUASrtjNUDSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQqQQ6M1JXpx5YD96Yj3sZR3ntwcdZyaHNmDHDPv74Y1t00UULo95WUqiL8syaNct69eo4J5EuOqwu3Szff58+fZrsg66RJkiU0MkEGJ4YhzSZCHQmAdpEjHtNbW0Ydb4djHvX9OnTNYBBA0ucWfv169dufNvhK+oxVUydOtXq6upsrrnm6jHHpAMRAREQAREQgbYS8OhV1FN/1VFWc8B5ba2yWJ6+45gxY+ytt96y/v3729JLL22LLbZYbj+H9y4u6ilWUGJm7rnntgUXXDCu/frrr+2LL74okbNxMv3XJZZYonFia5fGjLaad0e3tnSx3JwSNezmZ2ts8vQQTSr8C9KoOA2Sp8ChJvyttQPXG9SsuMqh1VEslIviqTBdf5G5o7iK1NUWHmg/XW1Ru/iF960+aK8QVbE1j2SFwOumtz6zg749lOztbqlQygVSCIuYL2cIqDwPoirepfsy5ZgnLRv5qlydXbUu73cAjqka9h1mCMSw1kbdamv5uPEW/pHAqoXAlF0EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEuppA+oNwR0WZ6upj7Enbf+ONN+yUU06Jh3Tsscfa6quv3pMOLx7Lhx9+aMcff3yc33vvvW3LLbfMPcZbbrnF7rjjjrjuF7/4ha2yyiq5+dLEyZMn24QJE2zhhRe23r1720svvWTnn39+zPLLX/7SlllmmTR77jyORb/61a/iuv3339++973v5eZLE99++2076aSTbNlll7UtttiiojJp+WqZHz16dBQ84XziNnPmTPv00099sUVTHLMGDx6cW2bcuHHRAWSzzTazHXfc0eaZZ56Y7/HHH7eLLroozh933HG21FJL2Zlnnmm77LJLm6+Xb775xr766qvc/ckmzjvvvNFJLZveluWzzz7b3nrzTVty2DDjfG2JTZs2ze677z7bZpttGonSvvzyy4od5bLb4zqqJqHnxxNmWcHZK3skLV/u16fG5huUL2B5cPRUO
Line truncated
`,"utf8"),{detected:z,configured:!0,configPath:Y,targetDir:U,action:"prepended"}}function vo($){let U=$?.targetSkillsDir??Qg0(),Y=$?.configFile??Jg0(),z=Kg0(),I=!1;if(fq(Y))try{let Q=JSON.parse(Ig0(Y,"utf8"));if(Array.isArray(Q?.entries))I=Q.entries.some((J)=>J?.path===U)}catch{}return{detected:z,configured:I,configPath:Y,targetDir:U}}var ho=()=>{};import{cpSync as ry1,existsSync as cK,lstatSync as Hg0,mkdirSync as sy1,realpathSync as $U,rmSync as ay1,symlinkSync as ty1,unlinkSync as Gg0}from"node:fs";import{homedir as Wg0}from"node:os";import{dirname as Xg0,join as UU}from"node:path";function ey1($,U){let Y=U?.baseHomeDir??Wg0(),z=UU(Y,$.rootDirName),I=U?.sourceSkillDir??UU(Y,".agents","skills","seal-use"),Q=Xg0(I),J=UU(z,"skills"),K=UU(J,"seal-use");if(!cK(z))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"skipped_not_detected"};if(cK(J)&&cK(Q))try{if($U(J)===$U(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:J}}catch{}sy1(J,{recursive:!0});let G;try{G=Hg0(K)}catch{G=void 0}let H=!1;if(G)if(G.isSymbolicLink()){try{if($U(K)===$U(I))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"already_linked",targetPath:K}}catch{}try{Gg0(K)}catch{}}else if(G.isDirectory())ay1(K,{recursive:!0,force:!0}),H=!0;else Gg0(K);let W=process.platform==="win32"?"junction":"dir";try{return ty1(I,K,W),{id:$.id,name:$.name,detected:!0,configured:!0,mode:H?"replaced_real_dir":"linked",targetPath:K}}catch{try{return ry1(I,K,{recursive:!0}),{id:$.id,name:$.name,detected:!0,configured:!0,mode:"fallback_copied",targetPath:K}}catch(X){return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"error",targetPath:K,error:X?.message||String(X)}}}}function $k1($,U){let Y=U?.baseHomeDir??Wg0(),z=UU(Y,$.rootDirName),I=U?.sourceSkillDir??UU(Y,".agents","skills","seal-use"),Q=Xg0(I),J=UU(z,"skills"),K=UU(J,"seal-use");if(!cK(z))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"not_detected"};if(cK(J)&&cK(Q))try{if($U(J)===$U(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:J}}catch{}let G;try{G=Hg0(K)}catch{G=void 0}if(G){if(G.isSymbolicLink())try{if($U(K)===$U(I))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"single_symlinked",targetPath:K}}catch{}else if(G.isDirectory())return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"real_directory",targetPath:K}}return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"not_configured",targetPath:K}}function So($){return Zg0.map((U)=>ey1(U,$))}function go($){return Zg0.map((U)=>$k1(U,$))}var Zg0;var yo=m(()=>{Zg0=[{id:"workbuddy",name:"WorkBuddy",rootDirName:".workbuddy"},{id:"claude",name:"Claude",rootDirName:".claude"},{id:"qoder",name:"Qoder",rootDirName:".qoder"}]});var ko=m(()=>{ho();yo();ho();yo()});import{existsSync as Uk1,mkdirSync as xo,readFileSync as Yk1,rmSync as zk1,writeFileSync as qg0}from"node:fs";import{homedir as Lg0}from"node:os";import{dirname as Vg0,join as bq}from"node:path";function fo(){return wg0["SKILL.md"]||""}function Fg0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function Mg0($=bq(iz(),"SKILL.md")){try{return Fg0(Yk1($,"utf8"))}catch{return}}function iz(){return bq(Lg0(),".agents","skills","seal-use")}function Qk1(){return bq(Lg0(),".agents","skills","seal-home")}function Jk1(){let $=Qk1();if(Uk1($))try{return zk1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Og0($=iz()){Jk1(),xo($,{recursive:!0});let U=[];for(let[Y,z]of Object.entries(wg0)){let I=bq($,Y);xo(Vg0(I),{recursive:!0}),qg0(I,z,"utf8"),U.push(Y)}for(let[Y,z]of Object.entries(Ik1)){let I=bq($,Y);xo(Vg0(I),{recursive:!0}),qg0(I,z),U.push(Y)}return{targetDir:$,files:U}}var wg0,Ik1,Oz4;var iq=m(()=>{Eo();Eo();ko();wg0=Yg0,Ik1=Object.fromEntries(Object.entries(zg0).map(([$,U])=>[$,Buffer.from(U,"base64")]));Oz4=Fg0(fo())});function Ng0(){return`#SealUse系统架构与运行规范白皮书
`)}var $g0=m(()=>{B6()});async function Yg0($,Y,z){let U=($??Y??"").toLowerCase();if(U==="guide"||U==="doc"||U==="knowledge"||U==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(lS0());return}if(U==="paths"||U==="dirs"||U==="directories"){let I=vo();x0(I.directories);return}if(U==="auth"){let{selectCorp:I}=await Promise.resolve().then(() => (f4(),pl)),{stringOption:K}=await Promise.resolve().then(() => (A4(),il)),{handleAuthCommand:G}=await Promise.resolve().then(() => (Vo(),bh0)),H=K(z.options.corp)??(Y&&Y!==U?Y:void 0)??(z.command[2]&&z.command[2]!==U?z.command[2]:void 0),W=I(H);await G("check",W,z);return}if(U==="tenant"||U==="corp"||U==="enterprise"){let{selectCorp:I}=await Promise.resolve().then(() => (f4(),pl)),{createSealClient:K}=await Promise.resolve().then(() => (i8(),t00)),{stringOption:G}=await Promise.resolve().then(() => (A4(),il)),{diagnoseTenantContract:H,formatTenantDoctorDashboard:W}=await Promise.resolve().then(() => ($g0(),eS0)),X=G(z.options.corp)??(Y&&Y!==U?Y:void 0)??(z.command[2]&&z.command[2]!==U?z.command[2]:void 0),Z=I(X),q=await K(Z),V=await H(q,Z);if(!(Z0(z.options.quiet)||Z0(z.options.silent)))console.error(W(V));x0(V);return}let Q=vo();if(!(Z0(z.options.quiet)||Z0(z.options.silent)))console.error(aS0(Q));x0(Q)}var zg0=m(()=>{tS0();_o();A4();K4()});var Qg0;var Ug0=m(()=>{Qg0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.37",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","direct","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","direct","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 sta
Line truncated
`)}var Eg0=m(()=>{X6()});async function Cg0($,U,Y){let z=($??U??"").toLowerCase();if(z==="guide"||z==="doc"||z==="knowledge"||z==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(Ng0());return}if(z==="paths"||z==="dirs"||z==="directories"){let J=co();R0(J.directories);return}if(z==="auth"){let{selectCorp:J}=await Promise.resolve().then(() => (O4(),Uo)),{stringOption:K}=await Promise.resolve().then(() => (Z4(),tl)),{handleAuthCommand:G}=await Promise.resolve().then(() => (jo(),qS0)),H=K(Y.options.corp)??(U&&U!==z?U:void 0)??(Y.command[2]&&Y.command[2]!==z?Y.command[2]:void 0),W=J(H);await G("check",W,Y);return}if(z==="tenant"||z==="corp"||z==="enterprise"){let{selectCorp:J}=await Promise.resolve().then(() => (O4(),Uo)),{createSealClient:K}=await Promise.resolve().then(() => (m6(),H10)),{stringOption:G}=await Promise.resolve().then(() => (Z4(),tl)),{diagnoseTenantContract:H,formatTenantDoctorDashboard:W}=await Promise.resolve().then(() => (Eg0(),jg0)),X=G(Y.options.corp)??(U&&U!==z?U:void 0)??(Y.command[2]&&Y.command[2]!==z?Y.command[2]:void 0),Z=J(X),q=await K(Z),V=await H(q,Z);if(!(G0(Y.options.quiet)||G0(Y.options.silent)))console.error(W(V));R0(V);return}let I=co();if(!(G0(Y.options.quiet)||G0(Y.options.silent)))console.error(Pg0(I));R0(I)}var Rg0=m(()=>{Tg0();no();Z4();m1()});var vg0;var _g0=m(()=>{vg0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.37",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","direct","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"},t
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(U)})})}var mj=8787,lj="127.0.0.1";var go=m(()=>{Hg0();$3()});async function Wg0($){let Y=s0($.options.port)??s0($.options.p),z=h($.options.host)??h($.options.h),U=await oj({port:Y,host:z}),Q=()=>{U.close(()=>{process.exit(0)})};process.on("SIGINT",Q),process.on("SIGTERM",Q),await new Promise(()=>{})}var Xg0=m(()=>{A4();go()});async function Zg0($,Y,z,U){if($==="config"||$==="get"){await k0("seal_llm_config_get",Y,z,{},E0(U.options));return}if($==="providers"||$==="list"){await k0("seal_llm_providers_list",Y,z,{},E0(U.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var qg0=m(()=>{f4();K4()});async function Vg0($,Y){if($==="config"||$==="json"){yo();return}let{startServer:z}=await Og0().then(() => Fg0);z()}function yo(){x0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var Lg0=m(()=>{K4()});function wg0($){let Y=cj();x0(Y,{...E0($.options),allowFull:!0})}var Mg0=m(()=>{ho();K4()});async function Ng0($,Y,z,U){if($==="available"){await k0("seal_permissions_available_list",Y,z,{},E0(U.options));return}if($==="configs"||$==="list"){await k0("seal_permissions_configs_list",Y,z,{},E0(U.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var Dg0=m(()=>{f4();K4()});import{readFileSync as Ag0}from"node:fs";async function Bg0($,Y,z,U,Q,J,I){if(!$||$==="get"){await k0("seal_preference_get",Q,J,{},E0(I.options));return}if($==="decision"){if(Y==="update"||!Y){let K=h(I.options.input),G=K?JSON.parse(Ag0(K,"utf8")):k8(I.json);if(!G||Object.keys(G).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await k0("seal_preference_decision_update",Q,J,{...G,dryRun:Z0(I.options.dryRun)??Z0(I.options["dry-run"])},E0(I.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let K=h(I.options.default)??h(I.options.level)??U;if(K!=="medium"&&K!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await k0("seal_preference_thinking_depth_set",Q,J,{defaultLevel:K,dryRun:Z0(I.options.dryRun)??Z0(I.options["dry-run"])},E0(I.options));return}if(Y==="policies"){if(z==="list"||!z){await k0("seal_preference_thinking_depth_policies_list",Q,J,{},E0(I.options));return}if(z==="upsert"){let K=h(I.options.input),G=K?JSON.parse(Ag0(K,"utf8")):k8(I.json);if(!G||!G.id||!G.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await k0("seal_preference_thinking_depth_policies_upsert",Q,J,{...G,dryRun:Z0(I.options.dryRun)??Z0(I.options["dry-run"])},E0(I.options));return}if(z==="remove"||z==="delete"){let K=U??h(I.options.id)??h(I.options.policyId);if(!K)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await k0("seal_preference_thinking_depth_policies_remove",Q,J,{policyId:K,dryRun:Z0(I.options.dryRun)??Z0(I.options["dry-run"])},E0(I.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}var Pg0=m(()=>{f4();A4();K4()});async function jg0($={}){let Y=a8(),z=v4(),U=n2(Y,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$.corpId},g3());console.log(`[probe]corp=${U.id}source=${U.source.type}`);let Q=await iK(U);console.log("[probe] seal enterprise"),console.log(JSON.stringify(Q,null,2));let J=await P1(U),I=await Ew(J,{documentLimit:20,stylePreferencesEndpoint:U.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:I.rules.rules.length,hasPendingRuleDeletes:I.rules.hasPendingDeletes,documents:I.documents.articles.length,documentsTotal:I.documents.total,stylePreferences:I.stylePreferences.ok?"ok":`error:${I.stylePreferences.error}`},null,2))}var Tg0=m(()=>{k3();i8();fj();B6()});async function Eg0($,Y,z){let U=Y??h(z.options.corp)??($&&$!=="--corp"?$:void 0);await jg0({corpId:U})}var Cg0=m(()=>{Tg0();A4()});async function ko($,Y,z,U,Q){if($==="count"){await k0("seal_approval_rules_list",z,U,{countOnly:!0},E0(Q.options));return}if($==="list"){if(Z0(Q.options.count)){await k0("seal_approval_rules_list",z,U,{countOnly:!0},E0(Q.options));return}let J=s0(Q.options.limit),I=s0(Q.options.offset);if(Z0(Q.options.summary)){await k0("seal_approval_rules_list",z,U,{fields:d_0,limit:J,offset:I},E0(Q.options));return}let K=await O$("seal_approval_rules_list",z,U,{limit:J,offset:I}),G=E0(Q.options);m_0(K,G.allowFull===!0||Boolean(G.outputFile)),x0(K,G);return}if($==="clear"){let J=Z0(Q.options.yes)===!0,I=Z0(Q.options.dryRun)??Z0(Q.options["dry-run"])??!J;if(!J&&!I)throw A5("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${U.id}--dry-run`);let K=await O$("seal_approval_rules_clear",z,U,{dryRun:I,recode:Z0(Q.options.recode)});if(!J&&I&
Line truncated
`).filter(Boolean),J=Q.slice(-Y);return{logFile:z,lines:J,totalLines:Q.length}}async function my1($){let Y=tj($),z=uo($),U=fq($);Sg0($.stateDir);let Q=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):mj),J=$.host??(process.env.HOST?process.env.HOST:lj);sj(Y,`${process.pid}
`,{mode:384}),sj(z,JSON.stringify({pid:process.pid,port:Q,host:J,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),cK(U,`servicestartingonhttp://${J}:${Q} pid=${process.pid}`);let I=null;try{I=await oj({port:Q,host:J,silent:!0}),cK(U,`service listening pid=${process.pid}`)}catch(G){if(cK(U,`service failed to bind port ${Q}: ${G instanceof Error?G.message:String(G)}`),aj(Y)===process.pid)g9(Y,{force:!0}),g9(z,{force:!0});throw G}let K=()=>{if(I)I.close(),I=null;if(aj(Y)===process.pid)g9(Y,{force:!0}),g9(z,{force:!0});cK(U,`stopped pid=${process.pid}`)};await new Promise((G)=>{let H=!1,W=()=>{if(H)return;H=!0,K(),process.off("SIGTERM",W),process.off("SIGINT",W),G()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function _g0($){Sg0($.stateDir);let Y=iU($);if(Y.running)return Y;let z=$.launcher??{command:process.execPath,args:[$.entryFile]},U=[...z.args??[],"service","run"];if($.port)U.push("--port",String($.port));if($.host)U.push("--host",String($.host));let Q=ny1(z.command,U,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});Q.unref();let J=tj($);return sj(J,`${Q.pid}
`,{flag:"a",mode:384})}var bo=m(()=>{go()});import{homedir as oy1}from"node:os";import{join as ry1}from"node:path";async function no($,Y,z){let U=z?s0(z.options.port)??s0(z.options.p):void 0,Q=z?h(z.options.host)??h(z.options.h):void 0,J=z?s0(z.options.lines)??s0(z.options.n):void 0,I=await r3($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:io,version:Z1,launcher:Y.launcher,port:U,host:Q},{maxLines:J});if(I!==void 0)x0(I)}var io;var co=m(()=>{$3();bo();K4();A4();io=ry1(oy1(),".config","seal-use")});import{existsSync as sy1,readFileSync as gg0}from"node:fs";async function yg0($,Y,z,U,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 k0("seal_simulation_batch_records_get",z,U,{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",I=J==="material-pack"?"material_pack":J,K=h(Q.options.schemaConfig)??h(Q.options["schema-config"]),G=K?JSON.parse(gg0(K,"utf8")):void 0,H=h(Q.options.input),W=H?JSON.parse(gg0(H,"utf8")):k8(Q.json),X=h(Q.options.packageId)??h(Q.options["package-id"]),Z=i6(Q.options.packageIds)??i6(Q.options["package-ids"])??(X?[X]:void 0),q=i6(Q.options.flowIds)??i6(Q.options["flow-ids"])??i6(Q.options.documentSn)??i6(Q.options["document-sn"]),V=h(Q.options.signKey)??h(Q.options["sign-key"])??h(Q.options.integration),F=Z0(Q.options.wait)===!0,w=Z0(Q.options.noWait)??Z0(Q.options["no-wait"])??(F?!1:!0),O=await O$("seal_simulation_batch_create",z,U,{mode:I,sourceSystem:I,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:Z0(Q.options.skipInvoiceGeneration)??Z0(Q.options["skip-invoice-generation"]),skipExpenseExtraction:Z0(Q.options.skipExpenseExtraction)??Z0(Q.options["skip-expense-extraction"]),disableAttachmentCache:Z0(Q.options.disableAttachmentCache)??Z0(Q.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:h(Q.options.templateId)??h(Q.options["template-id"]),schemaConfig:G,requestIds:i6(Q.options.requestIds)??i6(Q.options["request-ids"]),workflowTypeId:h(Q.options.workflowTypeId)??h(Q.options["workflow-type-id"]),flowStatusList:i6(Q.options.flowStatusList)?.map(Number)??i6(Q.options["flow-status-list"])?.map(Number),businessCodes:i6(Q.options.businessCodes)??i6(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:i6(Q.options.status),limit:s0(Q.options.limit),noWait:w,rawParams:W});if(F&&O&&typeof O==="object"&&"batchId"in O&&typeof O.batchId==="string"){await k0("seal_simulation_batch_wait",z,U,{batchId:O.batchId,timeout:h(Q.options.timeout),pollInterval:h(Q.options.pollInterval)??h(Q.options["poll-interval"])},E0(Q.options));return}x0(O,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 k0("seal_simulation_batch_wait",z,U,{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 k0("seal_simulation_batch_status",z,U,{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 k0("seal_simulation_batch_clean",z,U,{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 k0("seal_simulation_specifications_list",z,U,{signKey:J},E0(Q.options));return}if($==="approval-definitions"||$==="definitions"){await k0("seal_simulation_feishu_approval_definitions_list",z,U,{},E0(Q.options));return}if($==="list"){await k0("seal_simulation_batches_list",z,U,{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 k0("seal_simulation_batch_get",z,U,{batchId:J},E0(Q.options));return}if($==="templates"){await k0("seal_simulation_templates_get",z,U,{},E0(Q.options));return}if($==="integrations"){await k0("seal_simulation_integrations_get",z,U,{},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(!sy1(J))throw Error(`Filenotfound:${J}`);await k0("seal_simulation_material_package_upload",z,U,{filePath:J},E0(Q.o
Line truncated
`);return}if($==="install"||$==="init"||$==="sync"){let U=Z0(z.options.local)||Z0(z.options.workspace),Q=h(z.options.dir)??h(z.options.target)??Y,J=Q?Q:U?ej(process.cwd(),".agents","skills","seal-use"):bU(),I=mS0(J),K=!U&&!Q,G=K?wo():void 0,H=K?Do():void 0;x0({installed:!0,targetDir:I.targetDir,fileCount:I.files.length,files:I.files,...G?{antigravity:G}:{},...H?{hosts:H}:{}});return}if($==="status"||$==="get"||!$){let U=bU(),Q=ej(process.cwd(),".agents","skills","seal-use"),J=Mo(),I=Ao();x0({global:{dir:U,installed:xg0(ej(U,"SKILL.md"))},local:{dir:Q,installed:xg0(ej(Q,"SKILL.md"))},antigravity:J,hosts:I});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}var ug0=m(()=>{Po();yq();A4();K4()});async function bg0($,Y){if($==="config"){x0(await iK(Y));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var ig0=m(()=>{fj();K4()});function po($){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 ng0($){let{sourceCorp:Y,targetCorp:z,sourceClient:U,targetClient:Q,samples:J=10,dryRun:I=!1,pollIntervalMs:K=2000,timeoutMs:G=45000,snPrefix:H="REG_",fetchFn:W=fetch}=$;if(z.environment!=="test")throw new L4(`重放目标企业「${z.name}」(${z.id})的环境为「${z.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Y.id}<testCorpId>`);let X=await lY(Q),q=(Array.isArray(X.features)?X.features:[]).find((d)=>d?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,F=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,w=J*F;if(V<w)throw new L4(`测试企业「${z.name}」AI审批额度不足:当前剩余${V}点,本次回归抽样${J}笔需要约${w}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${z.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(V/F))})`);let O=await i4(U,{limit:J,status:"completed"}),N=Array.isArray(O.records)?O.records:[];if(N.length===0){let d=await i4(U,{limit:J});N=Array.isArray(d.records)?d.records:[]}if(N.length===0)throw new L4(`在母企业「${Y.name}」(${Y.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(N=N.slice(0,J),I){let d=N.map((t)=>{let e=t.sourceDocumentSN??t.id,g=t?.result?.decision??t.aiDecision??t?.decision,p=po(g),Y0=t?.result?.summary??t.aiSummary;return{sn:e,sourceRecordId:t.id,prodDecision:p,prodSummary:Y0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:F,estimatedRequired:w},metrics:{sampleCount:d.length,successCount:d.length,failureCount:0,matchCount:d.length,flipCount:0,concordanceRate:1},flips:[],records:d}}let M=await Bp(Q,z,$.webhookSelector),D=[];for(let d of N){let t=Date.now(),e=d.sourceDocumentSN??d.id,g=po(d?.result?.decision??d.aiDecision??d?.decision),p=d?.result?.summary??d.aiSummary;try{let Y0=await H4(U,d.id),y=`${H}${e}`,r=Dp(Y0,{snPrefix:H,docIdPrefix:H});await Ap(M.incomingDocumentWebhook.url,M.secret,r,W,A6(z.seal));let $0=null,N0=Date.now();while(Date.now()-N0<G){await new Promise((H0)=>setTimeout(H0,K));let s=await i4(Q,{sourceDocumentSN:y,limit:1});if(s.records&&s.records.length>0){let H0=s.records[0];if(H0.status==="completed"||H0.status==="failed"){$0=H0;break}}}if(!$0){D.push({sn:e,sourceRecordId:d.id,prodDecision:g,prodSummary:p,status:"FAILED",error:`测试租户单据审核超时(${Math.round(G/1000)}s未完成)`,durationMs:Date.now()-t});continue}let T0=po($0?.result?.decision??$0.aiDecision??$0?.decision??($0.status==="completed"?"APPROVE":"ERROR")),_0=$0?.result?.summary??$0.aiSummary,G0=g===T0,f0=G0?"MATCHED":"FLIPPED",e0={sn:e,sourceRecordId:d.id,prodDecision:g,prodSummary:p,testRecordId:$0.id,testDecision:T0,testSummary:_0,status:f0,durationMs:Date.now()-t};if(!G0)e0.diff={from:g,to:T0,reasonDiff:_0&&p&&_0!==p?`生产:${p.slice(0,60)}...->测试:${_0.slice(0,60)}...`:void 0};D.push(e0)}catch(Y0){D.push({sn:e,sourceRecordId:d.id,prodDecision:g,prodSummary:p,status:"FAILED",error:Y0 instanceof Error?Y0.message:String(Y0),durationMs:Date.now()-t})}}let P=D.filter((d)=>d.status==="MATCHED"||d.status==="FLIPPED"),j=D.filter((d)=>d.status==="MATCHED"),A=D.filter((d)=>d.status==="FLIPPED"),T=D.filter((d)=>d.status==="FAILED").length,C=j.length,b=A.length,k=C+b,S=k>0?C/k:0,i=b>0,n=i?"REGRESSIONS_DETECTED":"CLEAN",U0=!i&&T===0,x;try{let d=await lY(Q),e=(Array.isArray(d.features)?d.features:[]).find((g)=>g?.code==="ai-approval");if(typeof e?.balance==="number")x=e.balance}catch{}return{ok:!i&&T===0,verdict:n,safeToPublish:U0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:F,estimatedRequired:w,balanceAfter:x},metrics:{sampleCount:D.length,successCount:P.length,failureCount:T,matchCount:C,flipCount:b,concordanceRate:Number(S.toFixed(4))},flips:A,records:D}}function cg0($){let{sourceCorp:Y,targetCorp:z,verdict:U,safeToPublish:Q,metrics:J,quota:I,flips:K,records:G}=$,H=U==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":U==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",W=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${Y.name}」->测试靶场「${z.name}」`,`判定:${H}·准许发布:${Q?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${J.sampleCount}|一致通过:${J.matchCount}|决策翻转:${J.flipCount}|异常失败:${J.failureCount}`,`一致率:${(J.concordanceRate*100).toFixed(1)}%|消耗预估:${I.estimatedRequired}点(余量:${I.balanceBefore}${I.balanceAfter!==void0?` -> ${I.balanceAfter}`:""})`," "+"─".repeat(65)];if(K.length>0){W.push(`⚠️决策翻转清单(${K.length}笔单据在新规则下结果改变):`);for(let X of K)if(W.push(`•单据[${X.sn}]:原生产判定「${X.prodDecision}」➔测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)W.push(`理由差异:${X.diff.reasonDiff}`);W.push(" "+"─".repeat(65)),W.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(U==="CLEAN")W.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100%
Line truncated
`)}var pg0=m(()=>{F$();B6();fZ()});async function mo($,Y,z){let U=($??Y??"regression").toLowerCase();if(U==="regression"||U==="regress"||U==="matrix"){let Q=h(z.options.corp)??(Y&&Y!==U?Y:void 0),J=T1(Q),I=J,K=J;if(J.environment==="test"){K=J;let M=h(z.options["prod-corp"])??h(z.options.prod)??J.prodCorpId;if(!M)throw new L4(`测试企业「${J.name}」(${J.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${J.id}`);I=T1(M)}else{I=J;let M=h(z.options["test-corp"])??h(z.options.test)??J.testCorpId;if(!M)throw new L4(`生产企业「${J.name}」(${J.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${J.id}<testCorpId>`);K=T1(M)}let G=await P1(I),H=await P1(K),W=s0(z.options.samples)??s0(z.options.limit)??s0(z.options.n)??10,X=Z0(z.options["dry-run"]),Z=Z0(z.options["fail-on-flips"]),q=s0(z.options["poll-interval"])??2000,V=s0(z.options.timeout)??45000,F=h(z.options["sn-prefix"])??"REG_",w=h(z.options.webhook)??h(z.options.selector),O=await ng0({sourceCorp:I,targetCorp:K,sourceClient:G,targetClient:H,samples:W,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:F,failOnFlips:Z,webhookSelector:w});if(!(Z0(z.options.quiet)||Z0(z.options.silent)))console.error(cg0(O));if(x0(O),Z&&!O.ok)throw new L4(`回归测试发现${O.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new L4(`未知的test子命令:"${U}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}var dg0=m(()=>{F$();f4();A4();K4();i8();pg0()});async function mg0($,Y,z,U){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await k0($,Y,z,k8(U.json),E0(U.options))}var lg0=m(()=>{f4();A4();K4()});function og0(){x0(Dq.map(($)=>({name:$.name,description:$.description})))}var rg0=m(()=>{Bq();K4()});function $T($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let z=$.toLowerCase().replace(/\\/g,"/");return!z.endsWith("/bun")&&!z.endsWith("/bun.exe")&&!z.endsWith("/node")&&!z.endsWith("/node.exe")}var sg0=m(()=>{yq()});import{existsSync as ay1,mkdirSync as ty1,readFileSync as ey1,renameSync as $k1,writeFileSync as Yk1}from"node:fs";import{homedir as zk1}from"node:os";import{dirname as Uk1,join as Qk1}from"node:path";import{spawn as Jk1}from"node:child_process";function ag0(){let $=process.env[Ik1]?.trim();if($)return $;return Gk1}function tg0($=ag0()){if(!ay1($))return null;try{let Y=ey1($,"utf-8"),z=JSON.parse(Y);if(z&&typeof z==="object"&&typeof z.latestVersion==="string"&&typeof z.checkedAt==="string")return z;return null}catch{return null}}function uq($,Y=ag0()){try{let z=Uk1(Y);ty1(z,{recursive:!0,mode:448});let U={checkedAt:$.checkedAt??new Date().toISOString(),latestVersion:$.latestVersion,publishedAt:$.publishedAt,releaseUrl:$.releaseUrl},Q=`${Y}.tmp.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;Yk1(Q,JSON.stringify(U,null,2),{mode:384}),$k1(Q,Y)}catch{}}function eg0($,Y=Kk1){if(!$||!$.checkedAt)return!0;let z=new Date($.checkedAt).getTime();if(Number.isNaN(z))return!0;return Date.now()-z>Y}function $y0($){if(process.env.SEAL_DISABLE_BG_UPDATE==="1"||!1||process.env.CI)return!1;if(!$||!$.command)return!1;try{let Y=$.command,z=[...$.args??[],"update","check","--bg-save"];return Jk1(Y,z,{detached:!0,stdio:"ignore",env:{...process.env,SEAL_DISABLE_BG_UPDATE:"1"}}).unref(),!0}catch{return!1}}var Ik1="SEAL_USE_UPDATE_CACHE_FILE",Kk1=86400000,Gk1;var lo=m(()=>{Gk1=Qk1(zk1(),".config","seal-use","update-cache.json")});import{chmodSync as Hk1,mkdirSync as Wk1,readdirSync as Xk1,realpathSync as Yy0,renameSync as oo,rmSync as Zk1,unlinkSync as Jy0,writeFileSync as zy0}from"node:fs";import{basename as qk1,dirname as Vk1,isAbsolute as Lk1,join as UT,relative as Fk1}from"node:path";import{spawnSync as _5}from"node:child_process";async function Ky0($,Y={}){let z={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:io,version:Z1,launcher:$.launcher},U=Y.repo||process.env[Ok1]?.trim()||process.env[wk1]?.trim()||Iy0,Q=Y.targetVersion?.trim(),J=Q&&Q.toLowerCase()!=="latest"?Q:void 0;if(J){let D=J.replace(/^v/,""),P=Xy0(D,Z1);if(P<0)if(!sS&&Y.force);else{x0({updated:!1,currentVersion:Z1,targetVersion:D,mode:$T()?"binary":"source",message:!sS?`Cannotdowngradeseal-usefromdevbuildv${Z1}toreleasev${D}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${Z1}toolderversionv${D}.Updatesmustbeforward-only.`});return}if(P===0&&!Y.force){x0({updated:!1,currentVersion:Z1,targetVersion:D,mode:$T()?"binary":"source",message:`seal-useisalreadyatversionv${Z1}.Use--forcetoreinstall.`});return}}if(Y.changelogOnly){let D=await zT(U,Y.limit??10);x0({currentVersion:Z1,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===Z1,isNewer:R5(P.version,Z1)}))});return}if(!$T()){if(Y.checkOnly){let P=await zT(U,30),j=P[0],A=j?.version??Z1,T=P.find((k)=>k.version===Z1),C=R5(A,Z1),b=P.filter((k)=>R5(k.version,Z1));if(j?.version)uq({latestVersion:j.version,publishedAt:j.publishedAt,releaseUrl:j.htmlUrl});if(Y.bgSave)return;x0({updated:!1,updateAvailable:C,currentVersion:Z1,currentVersionPublishedAt:T?.publishedAt,latestVersion:A,latestVersionPublishedAt:j?.publishedAt,behindCount:b.length,pendingReleases:b.map((k)=>({version:k.version,tagName:k.tagName,publishedAt:k.publishedAt,author:k.author,releaseNotes:k.notes,releaseUrl:k.htmlUrl})),releaseNotes:j?.notes??"",releaseUrl:j?.htmlUrl??"",mode:"source",message:"当前运行的是开发版。正式用户请安装正式版后使用 seal-use update。"});return}let D=iU(z).running;if(D)await r3("stop",z);try{Qy0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(P){console.error(`⚠️开发版更新同步失败,继续刷新本地依赖:${PinstanceofError?P.message:String(P)}`)}if(Qy0("bun",["install"],{cwd:$.appRoot}),D)await r3("start",z);x0({updated:!0,serviceRestarted:D,version:Z1,mode:"source"});return}if(Bk1())try{await Pk1($,Y,z,U,J);return}catch(D){console.error(`⚠️Homebrew自动更新失败,回退至原生二进制更新:${DinstanceofError?D.message:String(D)}`)}let I=Nk1(),K=Dk1(),G=await zT(U,30),H=J?G.find((D)=>D.version===J||D.tagName===J||D.tagName===`v${J}`)??await QT(U,J):G[0]??await QT(U);if(!H){x0({updated:!1,
Line truncated
`)}catch{}}async function Ek1($,Y,z,U){let Q=ro(),J=[],I=z?z.startsWith("v")?z:`v${z}`:void 0,K=U||$.split("/").pop()||"";if(Q!=="github"){if(I&&K)J.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${I}/${K}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${I}/${K}`);if($.startsWith("https://git.ying-qing.cn"))J.push($)}if(Q!=="gitea")if(I&&K){let F=`https://github.com/${Iy0}/releases/download/${I}/${K}`;if(!process.env.CI)J.push(`https://ghfast.top/${F}`,`https://gh.ddlc.top/${F}`);J.push(F)}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 F=0;F<G.length;F++){let w=G[F],O=new AbortController,N="",M=(A)=>{N=A;try{O.abort()}catch{}},D=setTimeout(()=>{M("Connection timed out (no response headers within 6s)")},W),P,j;try{YT(`==> [${F+1}/${G.length}] Downloading via: ${w}`);let A=await fetch(w,{signal:O.signal});if(D)clearTimeout(D),D=void 0;if(!A.ok)throw Error(`HTTP ${A.status} ${A.statusText}`);P=setTimeout(()=>{M("Overall download time exceeded 3 minutes")},V);let T=Number(A.headers.get("content-length"))||0,C=A.body?.getReader();if(!C){let n=Buffer.from(await A.arrayBuffer());if(n.length<1000)throw Error(`Downloaded content is suspiciously small (${n.length} bytes)`);zy0(Y,n),YT(`✓ Download succeeded (${(n.length/1024/1024).toFixed(1)} MB)`);return}let b=[],k=0,S=0;j=setTimeout(()=>{if(k<Z){let n=(k/1024).toFixed(1);M(`Initial transfer too slow (${n} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let n=C.read(),U0,x=new Promise((g,p)=>{U0=setTimeout(()=>{p(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),d;try{d=await Promise.race([n,x])}finally{if(U0)clearTimeout(U0)}let{done:t,value:e}=d;if(t)break;if(e){if(b.push(e),k+=e.length,j&&k>=Z)clearTimeout(j),j=void 0;let g=Date.now();if(g-S>200){S=g;let p=T?Math.round(k/T*100):0,Y0=(k/1048576).toFixed(1),y=T?(T/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${p}% (${Y0} / ${y} MB)...`)}catch{}}}}try{process.stderr.write(`
`);I(z)})})}var Qj=8787,Jj="127.0.0.1";var lo=m(()=>{kg0();z3()});async function xg0($){let U=s0($.options.port)??s0($.options.p),Y=S($.options.host)??S($.options.h),z=await Kj({port:U,host:Y}),I=()=>{z.close(()=>{process.exit(0)})};process.on("SIGINT",I),process.on("SIGTERM",I),await new Promise(()=>{})}var fg0=m(()=>{Z4();lo()});async function ug0($,U,Y,z){if($==="config"||$==="get"){await x0("seal_llm_config_get",U,Y,{},j0(z.options));return}if($==="providers"||$==="list"){await x0("seal_llm_providers_list",U,Y,{},j0(z.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var bg0=m(()=>{O4();m1()});async function ig0($,U){if($==="config"||$==="json"){oo();return}let{startServer:Y}=await dg0().then(() => cg0);Y()}function oo(){R0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var ng0=m(()=>{m1()});function pg0($){let U=Yj();R0(U,{...j0($.options),allowFull:!0})}var mg0=m(()=>{po();m1()});async function lg0($,U,Y,z){if($==="available"){await x0("seal_permissions_available_list",U,Y,{},j0(z.options));return}if($==="configs"||$==="list"){await x0("seal_permissions_configs_list",U,Y,{},j0(z.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var og0=m(()=>{O4();m1()});import{readFileSync as rg0}from"node:fs";async function sg0($,U,Y,z,I,Q,J){if(!$||$==="get"){await x0("seal_preference_get",I,Q,{},j0(J.options));return}if($==="decision"){if(U==="update"||!U){let K=S(J.options.input),G=K?JSON.parse(rg0(K,"utf8")):B8(J.json);if(!G||Object.keys(G).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await x0("seal_preference_decision_update",I,Q,{...G,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(U==="set"){let K=S(J.options.default)??S(J.options.level)??z;if(K!=="medium"&&K!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await x0("seal_preference_thinking_depth_set",I,Q,{defaultLevel:K,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}if(U==="policies"){if(Y==="list"||!Y){await x0("seal_preference_thinking_depth_policies_list",I,Q,{},j0(J.options));return}if(Y==="upsert"){let K=S(J.options.input),G=K?JSON.parse(rg0(K,"utf8")):B8(J.json);if(!G||!G.id||!G.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await x0("seal_preference_thinking_depth_policies_upsert",I,Q,{...G,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}if(Y==="remove"||Y==="delete"){let K=z??S(J.options.id)??S(J.options.policyId);if(!K)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await x0("seal_preference_thinking_depth_policies_remove",I,Q,{policyId:K,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}var ag0=m(()=>{O4();Z4();m1()});async function tg0($={}){let U=t8(),Y=v4(),z=c2(U,{stateful:Y.stateful,defaultCorpId:Y.defaultCorpId,corpId:$.corpId},x3());console.log(`[probe]corp=${z.id}source=${z.source.type}`);let I=await bK(z);console.log("[probe] seal enterprise"),console.log(JSON.stringify(I,null,2));let Q=await B1(z),J=await SM(Q,{documentLimit:20,stylePreferencesEndpoint:z.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:J.rules.rules.length,hasPendingRuleDeletes:J.rules.hasPendingDeletes,documents:J.documents.articles.length,documentsTotal:J.documents.total,stylePreferences:J.stylePreferences.ok?"ok":`error:${J.stylePreferences.error}`},null,2))}var eg0=m(()=>{T5();m6();fT();X6()});async function $y0($,U,Y){let z=U??S(Y.options.corp)??($&&$!=="--corp"?$:void 0);await tg0({corpId:z})}var Uy0=m(()=>{eg0();Z4()});async function ro($,U,Y,z,I){if($==="count"){await x0("seal_approval_rules_list",Y,z,{countOnly:!0},j0(I.options));return}if($==="list"){if(G0(I.options.count)){await x0("seal_approval_rules_list",Y,z,{countOnly:!0},j0(I.options));return}let Q=s0(I.options.limit),J=s0(I.options.offset);if(G0(I.options.summary)){await x0("seal_approval_rules_list",Y,z,{fields:Iv0,limit:Q,offset:J},j0(I.options));return}let K=await M$("seal_approval_rules_list",Y,z,{limit:Q,offset:J}),G=j0(I.options);Qv0(K,G.allowFull===!0||Boolean(G.outputFile)),R0(K,G);return}if($==="clear"){let Q=G0(I.options.yes)===!0,J=G0(I.options.dryRun)??G0(I.options["dry-run"])??!Q;if(!Q&&!J)throw F$("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${z.id}--dry-run`);let K=await M$("seal_approval_rules_clear",Y,z,{dryRun:J,recode:G0(I.options.recode)});if(!Q&&J&
Line truncated
`).filter(Boolean),Q=I.slice(-U);return{logFile:Y,lines:Q,totalLines:I.length}}async function Bk1($){let U=Xj($),Y=to($),z=dq($);Jy0($.stateDir);let I=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):Qj),Q=$.host??(process.env.HOST?process.env.HOST:Jj);Hj(U,`${process.pid}
`,{mode:384}),Hj(Y,JSON.stringify({pid:process.pid,port:I,host:Q,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),dK(z,`servicestartingonhttp://${Q}:${I} pid=${process.pid}`);let J=null;try{J=await Kj({port:I,host:Q,silent:!0}),dK(z,`service listening pid=${process.pid}`)}catch(G){if(dK(z,`service failed to bind port ${I}: ${G instanceof Error?G.message:String(G)}`),Wj(U)===process.pid)x9(U,{force:!0}),x9(Y,{force:!0});throw G}let K=()=>{if(J)J.close(),J=null;if(Wj(U)===process.pid)x9(U,{force:!0}),x9(Y,{force:!0});dK(z,`stopped pid=${process.pid}`)};await new Promise((G)=>{let H=!1,W=()=>{if(H)return;H=!0,K(),process.off("SIGTERM",W),process.off("SIGINT",W),G()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function zy0($){Jy0($.stateDir);let U=nz($);if(U.running)return U;let Y=$.launcher??{command:process.execPath,args:[$.entryFile]},z=[...Y.args??[],"service","run"];if($.port)z.push("--port",String($.port));if($.host)z.push("--host",String($.host));let I=Ok1(Y.command,z,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});I.unref();let Q=Xj($);return Hj(Q,`${I.pid}
`,{flag:"a",mode:384})}var eo=m(()=>{lo()});import{homedir as Tk1}from"node:os";import{join as jk1}from"node:path";async function Ur($,U,Y){let z=Y?s0(Y.options.port)??s0(Y.options.p):void 0,I=Y?S(Y.options.host)??S(Y.options.h):void 0,Q=Y?s0(Y.options.lines)??s0(Y.options.n):void 0,J=await s3($,{appRoot:U.appRoot,entryFile:U.entryFile,stateDir:$r,version:X1,launcher:U.launcher,port:z,host:I},{maxLines:Q});if(J!==void 0)R0(J)}var $r;var Yr=m(()=>{z3();eo();m1();Z4();$r=jk1(Tk1(),".config","seal-use")});import{existsSync as Ek1,readFileSync as Ky0}from"node:fs";async function Gy0($,U,Y,z,I){if($==="batch-records"||$==="records"){let Q=U??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation batch-records <batchId>");await x0("seal_simulation_batch_records_get",Y,z,{batchId:Q,query:S(I.options.query)},j0(I.options));return}if($==="create"||$==="run"){let Q=S(I.options.mode)??S(I.options.sourceSystem)??S(I.options["source-system"])??"hosecloud",J=Q==="material-pack"?"material_pack":Q,K=S(I.options.schemaConfig)??S(I.options["schema-config"]),G=K?JSON.parse(Ky0(K,"utf8")):void 0,H=S(I.options.input),W=H?JSON.parse(Ky0(H,"utf8")):B8(I.json),X=S(I.options.packageId)??S(I.options["package-id"]),Z=i6(I.options.packageIds)??i6(I.options["package-ids"])??(X?[X]:void 0),q=i6(I.options.flowIds)??i6(I.options["flow-ids"])??i6(I.options.documentSn)??i6(I.options["document-sn"]),V=S(I.options.signKey)??S(I.options["sign-key"])??S(I.options.integration),F=G0(I.options.wait)===!0,M=G0(I.options.noWait)??G0(I.options["no-wait"])??(F?!1:!0),w=await M$("seal_simulation_batch_create",Y,z,{mode:J,sourceSystem:J,flowIds:q,documentSn:q,rejectNodeName:S(I.options.rejectNode)??S(I.options["reject-node"])??null,thinkingDepthOverride:S(I.options.thinkingDepth)??S(I.options["thinking-depth"]),skipInvoiceGeneration:G0(I.options.skipInvoiceGeneration)??G0(I.options["skip-invoice-generation"]),skipExpenseExtraction:G0(I.options.skipExpenseExtraction)??G0(I.options["skip-expense-extraction"]),disableAttachmentCache:G0(I.options.disableAttachmentCache)??G0(I.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:S(I.options.templateId)??S(I.options["template-id"]),schemaConfig:G,requestIds:i6(I.options.requestIds)??i6(I.options["request-ids"]),workflowTypeId:S(I.options.workflowTypeId)??S(I.options["workflow-type-id"]),flowStatusList:i6(I.options.flowStatusList)?.map(Number)??i6(I.options["flow-status-list"])?.map(Number),businessCodes:i6(I.options.businessCodes)??i6(I.options["business-codes"]),documentType:S(I.options.documentType)??S(I.options["document-type"]),startTime:s0(I.options.startTime)??s0(I.options["start-time"]),endTime:s0(I.options.endTime)??s0(I.options["end-time"]),status:i6(I.options.status),limit:s0(I.options.limit),noWait:M,rawParams:W});if(F&&w&&typeof w==="object"&&"batchId"in w&&typeof w.batchId==="string"){await x0("seal_simulation_batch_wait",Y,z,{batchId:w.batchId,timeout:S(I.options.timeout),pollInterval:S(I.options.pollInterval)??S(I.options["poll-interval"])},j0(I.options));return}R0(w,j0(I.options));return}if($==="wait"){let Q=U??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await x0("seal_simulation_batch_wait",Y,z,{batchId:Q,timeout:S(I.options.timeout),pollInterval:S(I.options.pollInterval)??S(I.options["poll-interval"])},j0(I.options));return}if($==="status"){let Q=U??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation status <batchId>");await x0("seal_simulation_batch_status",Y,z,{batchId:Q},j0(I.options));return}if($==="clean"||$==="delete"){let Q=U??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation clean <batchId>");await x0("seal_simulation_batch_clean",Y,z,{batchId:Q},j0(I.options));return}if($==="specifications"){let Q=U??S(I.options.integration)??S(I.options.signKey)??S(I.options["sign-key"]);await x0("seal_simulation_specifications_list",Y,z,{signKey:Q},j0(I.options));return}if($==="approval-definitions"||$==="definitions"){await x0("seal_simulation_feishu_approval_definitions_list",Y,z,{},j0(I.options));return}if($==="list"){await x0("seal_simulation_batches_list",Y,z,{limit:s0(I.options.limit)},j0(I.options));return}if($==="get"){let Q=U??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation get <batchId>");await x0("seal_simulation_batch_get",Y,z,{batchId:Q},j0(I.options));return}if($==="templates"){await x0("seal_simulation_templates_get",Y,z,{},j0(I.options));return}if($==="integrations"){await x0("seal_simulation_integrations_get",Y,z,{},j0(I.options));return}if($==="package-upload"){let Q=U??S(I.options.file);if(!Q)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!Ek1(Q))throw Error(`Filenotfound:${Q}`);await x0("seal_simulation_material_package_upload",Y,z,{filePath:Q},j0(I.o
Line truncated
`);return}if($==="install"||$==="init"||$==="sync"){let z=G0(Y.options.local)||G0(Y.options.workspace),I=S(Y.options.dir)??S(Y.options.target)??U,Q=I?I:z?Zj(process.cwd(),".agents","skills","seal-use"):iz(),J=Og0(Q),K=!z&&!I,G=K?_o():void 0,H=K?So():void 0;R0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files,...G?{antigravity:G}:{},...H?{hosts:H}:{}});return}if($==="status"||$==="get"||!$){let z=iz(),I=Zj(process.cwd(),".agents","skills","seal-use"),Q=vo(),J=go();R0({global:{dir:z,installed:Wy0(Zj(z,"SKILL.md"))},local:{dir:I,installed:Wy0(Zj(I,"SKILL.md"))},antigravity:Q,hosts:J});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}var Zy0=m(()=>{ko();iq();Z4();m1()});async function qy0($,U){if($==="config"){R0(await bK(U));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var Vy0=m(()=>{fT();m1()});function zr($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let U=$.toUpperCase().trim();if(U==="APPROVE"||U==="PASS")return"APPROVE";if(U==="REJECT"||U==="DENIED")return"REJECT";if(U==="MANUAL"||U==="ASSISTED")return"MANUAL";if(U==="ERROR"||U==="FAILED")return"ERROR";return U}async function Ly0($){let{sourceCorp:U,targetCorp:Y,sourceClient:z,targetClient:I,samples:Q=10,dryRun:J=!1,pollIntervalMs:K=2000,timeoutMs:G=45000,snPrefix:H="REG_",fetchFn:W=fetch}=$;if(Y.environment!=="test")throw new W4(`重放目标企业「${Y.name}」(${Y.id})的环境为「${Y.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${U.id}<testCorpId>`);let X=await lU(I),q=(Array.isArray(X.features)?X.features:[]).find((p)=>p?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,F=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,M=Q*F;if(V<M)throw new W4(`测试企业「${Y.name}」AI审批额度不足:当前剩余${V}点,本次回归抽样${Q}笔需要约${M}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${Y.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(V/F))})`);let w=await i4(z,{limit:Q,status:"completed"}),N=Array.isArray(w.records)?w.records:[];if(N.length===0){let p=await i4(z,{limit:Q});N=Array.isArray(p.records)?p.records:[]}if(N.length===0)throw new W4(`在母企业「${U.name}」(${U.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(N=N.slice(0,Q),J){let p=N.map((a)=>{let $0=a.sourceDocumentSN??a.id,y=a?.result?.decision??a.aiDecision??a?.decision,d=zr(y),U0=a?.result?.summary??a.aiSummary;return{sn:$0,sourceRecordId:a.id,prodDecision:d,prodSummary:U0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:U.id,name:U.name,environment:U.environment??"production"},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:F,estimatedRequired:M},metrics:{sampleCount:p.length,successCount:p.length,failureCount:0,matchCount:p.length,flipCount:0,concordanceRate:1},flips:[],records:p}}let O=await gd(I,Y,$.webhookSelector),D=[];for(let p of N){let a=Date.now(),$0=p.sourceDocumentSN??p.id,y=zr(p?.result?.decision??p.aiDecision??p?.decision),d=p?.result?.summary??p.aiSummary;try{let U0=await H4(z,p.id),R=`${H}${$0}`,o=hd(U0,{snPrefix:H,docIdPrefix:H});await Sd(O.incomingDocumentWebhook.url,O.secret,o,W,A6(Y.seal));let e=null,O0=Date.now();while(Date.now()-O0<G){await new Promise((X0)=>setTimeout(X0,K));let t=await i4(I,{sourceDocumentSN:R,limit:1});if(t.records&&t.records.length>0){let X0=t.records[0];if(X0.status==="completed"||X0.status==="failed"){e=X0;break}}}if(!e){D.push({sn:$0,sourceRecordId:p.id,prodDecision:y,prodSummary:d,status:"FAILED",error:`测试租户单据审核超时(${Math.round(G/1000)}s未完成)`,durationMs:Date.now()-a});continue}let T0=zr(e?.result?.decision??e.aiDecision??e?.decision??(e.status==="completed"?"APPROVE":"ERROR")),y0=e?.result?.summary??e.aiSummary,v0=y===T0,o0=v0?"MATCHED":"FLIPPED",q1={sn:$0,sourceRecordId: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(U0){D.push({sn:$0,sourceRecordId:p.id,prodDecision:y,prodSummary:d,status:"FAILED",error:U0 instanceof Error?U0.message:String(U0),durationMs:Date.now()-a})}}let P=D.filter((p)=>p.status==="MATCHED"||p.status==="FLIPPED"),T=D.filter((p)=>p.status==="MATCHED"),A=D.filter((p)=>p.status==="FLIPPED"),j=D.filter((p)=>p.status==="FAILED").length,C=T.length,b=A.length,x=C+b,g=x>0?C/x:0,i=b>0,n=i?"REGRESSIONS_DETECTED":"CLEAN",z0=!i&&j===0,k;try{let p=await lU(I),$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&&j===0,verdict:n,safeToPublish:z0,timestamp:new Date().toISOString(),sourceCorp:{id:U.id,name:U.name,environment:U.environment??"production"},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:F,estimatedRequired:M,balanceAfter:k},metrics:{sampleCount:D.length,successCount:P.length,failureCount:j,matchCount:C,flipCount:b,concordanceRate:Number(g.toFixed(4))},flips:A,records:D}}function wy0($){let{sourceCorp:U,targetCorp:Y,verdict:z,safeToPublish:I,metrics:Q,quota:J,flips:K,records:G}=$,H=z==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":z==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",W=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${U.name}」->测试靶场「${Y.name}」`,`判定:${H}·准许发布:${I?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${Q.sampleCount}|一致通过:${Q.matchCount}|决策翻转:${Q.flipCount}|异常失败:${Q.failureCount}`,`一致率:${(Q.concordanceRate*100).toFixed(1)}%|消耗预估:${J.estimatedRequired}点(余量:${J.balanceBefore}${J.balanceAfter!==void0?` -> ${J.balanceAfter}`:""})`," "+"─".repeat(65)];if(K.length>0){W.push(`⚠️决策翻转清单(${K.length}笔单据在新规则下结果改变):`);for(let X of K)if(W.push(`•单据[${X.sn}]:原生产判定「${X.prodDecision}」➔测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)W.push(`理由差异:${X.diff.reasonDiff}`);W.push(" "+"─".repeat(65)),W.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(z==="CLEAN")W.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100%
Line truncated
`)}var Fy0=m(()=>{O8();X6();iZ()});async function Ir($,U,Y){let z=($??U??"regression").toLowerCase();if(z==="regression"||z==="regress"||z==="matrix"){let I=S(Y.options.corp)??(U&&U!==z?U:void 0),Q=M1(I),J=Q,K=Q;if(Q.environment==="test"){K=Q;let O=S(Y.options["prod-corp"])??S(Y.options.prod)??Q.prodCorpId;if(!O)throw new W4(`测试企业「${Q.name}」(${Q.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${Q.id}`);J=M1(O)}else{J=Q;let O=S(Y.options["test-corp"])??S(Y.options.test)??Q.testCorpId;if(!O)throw new W4(`生产企业「${Q.name}」(${Q.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Q.id}<testCorpId>`);K=M1(O)}let G=await B1(J),H=await B1(K),W=s0(Y.options.samples)??s0(Y.options.limit)??s0(Y.options.n)??10,X=G0(Y.options["dry-run"]),Z=G0(Y.options["fail-on-flips"]),q=s0(Y.options["poll-interval"])??2000,V=s0(Y.options.timeout)??45000,F=S(Y.options["sn-prefix"])??"REG_",M=S(Y.options.webhook)??S(Y.options.selector),w=await Ly0({sourceCorp:J,targetCorp:K,sourceClient:G,targetClient:H,samples:W,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:F,failOnFlips:Z,webhookSelector:M});if(!(G0(Y.options.quiet)||G0(Y.options.silent)))console.error(wy0(w));if(R0(w),Z&&!w.ok)throw new W4(`回归测试发现${w.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new W4(`未知的test子命令:"${z}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}var My0=m(()=>{O8();O4();Z4();m1();m6();Fy0()});async function Oy0($,U,Y,z){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await x0($,U,Y,B8(z.json),j0(z.options))}var Ny0=m(()=>{O4();Z4();m1()});function Dy0(){R0(Pq.map(($)=>({name:$.name,description:$.description})))}var Ay0=m(()=>{jq();m1()});function qj($=process.execPath,U=import.meta.url){if(U.includes("/$bunfs/")||U.includes("\\$bunfs\\"))return!0;let Y=$.toLowerCase().replace(/\\/g,"/");return!Y.endsWith("/bun")&&!Y.endsWith("/bun.exe")&&!Y.endsWith("/node")&&!Y.endsWith("/node.exe")}var By0=m(()=>{iq()});import{existsSync as Ck1,mkdirSync as Rk1,readFileSync as _k1,renameSync as vk1,writeFileSync as hk1}from"node:fs";import{homedir as Sk1}from"node:os";import{dirname as gk1,join as yk1}from"node:path";import{spawn as kk1}from"node:child_process";function Py0($){return $.replace(/\.\d+Z$/,"Z")}function Ty0(){let $=process.env[xk1]?.trim();if($)return $;return uk1}function jy0($=Ty0()){if(!Ck1($))return null;try{let U=_k1($,"utf-8"),Y=JSON.parse(U);if(Y&&typeof Y==="object"&&typeof Y.latestVersion==="string"&&typeof Y.checkedAt==="string")return{...Y,checkedAt:Py0(Y.checkedAt)};return null}catch{return null}}function pq($,U=Ty0()){try{let Y=gk1(U);Rk1(Y,{recursive:!0,mode:448});let z={checkedAt:Py0($.checkedAt??new Date().toISOString()),latestVersion:$.latestVersion,publishedAt:$.publishedAt,releaseUrl:$.releaseUrl},I=`${U}.tmp.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;hk1(I,JSON.stringify(z,null,2),{mode:384}),vk1(I,U)}catch{}}function Ey0($,U=fk1){if(!$||!$.checkedAt)return!0;let Y=new Date($.checkedAt).getTime();if(Number.isNaN(Y))return!0;return Date.now()-Y>U}function Cy0($){if(process.env.SEAL_DISABLE_BG_UPDATE==="1"||!1||process.env.CI)return!1;if(!$||!$.command)return!1;try{let U=$.command,Y=[...$.args??[],"update","check","--bg-save"];return kk1(U,Y,{detached:!0,stdio:"ignore",env:{...process.env,SEAL_DISABLE_BG_UPDATE:"1"}}).unref(),!0}catch{return!1}}var xk1="SEAL_USE_UPDATE_CACHE_FILE",fk1=86400000,uk1;var Qr=m(()=>{uk1=yk1(Sk1(),".config","seal-use","update-cache.json")});import{chmodSync as bk1,mkdirSync as ik1,readdirSync as nk1,realpathSync as Ry0,renameSync as Jr,rmSync as ck1,unlinkSync as gy0,writeFileSync as _y0}from"node:fs";import{basename as dk1,dirname as pk1,isAbsolute as mk1,join as wj,relative as lk1}from"node:path";import{spawn as ok1,spawnSync as a3}from"node:child_process";async function ky0($,U={}){let Y={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:$r,version:X1,launcher:$.launcher},z=U.repo||process.env[rk1]?.trim()||process.env[sk1]?.trim()||yy0,I=U.targetVersion?.trim(),Q=I&&I.toLowerCase()!=="latest"?I:void 0;if(Q){let D=Q.replace(/^v/,""),P=by0(D,X1);if(P<0)if(!Wg&&U.force);else{R0({updated:!1,currentVersion:X1,targetVersion:D,mode:qj()?"binary":"source",message:!Wg?`Cannotdowngradeseal-usefromdevbuildv${X1}toreleasev${D}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${X1}toolderversionv${D}.Updatesmustbeforward-only.`});return}if(P===0&&!U.force){R0({updated:!1,currentVersion:X1,targetVersion:D,mode:qj()?"binary":"source",message:`seal-useisalreadyatversionv${X1}.Use--forcetoreinstall.`});return}}if(U.changelogOnly){let D=await Lj(z,U.limit??10);R0({currentVersion:X1,totalQueried:D.length,releases:D.map((P)=>({version:P.version,tagName:P.tagName,publishedAt:P.publishedAt,author:P.author,releaseNotes:P.notes,releaseUrl:P.htmlUrl,isCurrent:P.version===X1,isNewer:h5(P.version,X1)}))});return}if(!qj()){if(U.checkOnly){let P=await Lj(z,30),T=P[0],A=T?.version??X1,j=P.find((x)=>x.version===X1),C=h5(A,X1),b=P.filter((x)=>h5(x.version,X1));if(T?.version)pq({latestVersion:T.version,publishedAt:T.publishedAt,releaseUrl:T.htmlUrl});if(U.bgSave)return;R0({updated:!1,updateAvailable:C,currentVersion:X1,currentVersionPublishedAt:j?.publishedAt,latestVersion:A,latestVersionPublishedAt:T?.publishedAt,behindCount:b.length,pendingReleases:b.map((x)=>({version:x.version,tagName:x.tagName,publishedAt:x.publishedAt,author:x.author,releaseNotes:x.notes,releaseUrl:x.htmlUrl})),releaseNotes:T?.notes??"",releaseUrl:T?.htmlUrl??"",mode:"source",message:"当前运行的是开发版。正式用户请安装正式版后使用 seal-use update。"});return}let D=nz(Y).running;if(D)await s3("stop",Y);try{Sy0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(P){console.error(`⚠️开发版更新同步失败,继续刷新本地依赖:${PinstanceofError?P.message:String(P)}`)}if(Sy0("bun",["install"],{cwd:$.appRoot}),D)await s3("start",Y);R0({updated:!0,serviceRestarted:D,version:X1,mode:"source"});return}if(Ux1())try{await Yx1($,U,Y,z,Q);return}catch(D){console.error(`⚠️Homebrew自动更新失败,回退至原生二进制更新:${DinstanceofError?D.message:String(D)}`)}let J=tk1(),K=ek1(),G=await Lj(z,30),H=Q?G.find((D)=>D.version
Line truncated
`)}catch{}}async function Qx1($,U,Y,z){let I=Kr(),Q=[],J=Y?Y.startsWith("v")?Y:`v${Y}`:void 0,K=z||$.split("/").pop()||"";if(I!=="github"){if(J&&K)Q.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${J}/${K}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${J}/${K}`);if($.startsWith("https://git.ying-qing.cn"))Q.push($)}if(I!=="gitea")if(J&&K){let F=`https://github.com/${yy0}/releases/download/${J}/${K}`;if(!process.env.CI)Q.push(`https://ghfast.top/${F}`,`https://gh.ddlc.top/${F}`);Q.push(F)}else if($.includes("github.com")){if(!process.env.CI)Q.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Q.push($)}else Q.push($);let G=Array.from(new Set(Q)),H,W=6000,X=6000,Z=307200,q=1e4,V=180000;for(let F=0;F<G.length;F++){let M=G[F],w=new AbortController,N="",O=(A)=>{N=A;try{w.abort()}catch{}},D=setTimeout(()=>{O("Connection timed out (no response headers within 6s)")},W),P,T;try{Vj(`==> [${F+1}/${G.length}] Downloading via: ${M}`);let A=await fetch(M,{signal:w.signal});if(D)clearTimeout(D),D=void 0;if(!A.ok)throw Error(`HTTP ${A.status} ${A.statusText}`);P=setTimeout(()=>{O("Overall download time exceeded 3 minutes")},V);let j=Number(A.headers.get("content-length"))||0,C=A.body?.getReader();if(!C){let n=Buffer.from(await A.arrayBuffer());if(n.length<1000)throw Error(`Downloaded content is suspiciously small (${n.length} bytes)`);_y0(U,n),Vj(`✓ Download succeeded (${(n.length/1024/1024).toFixed(1)} MB)`);return}let b=[],x=0,g=0;T=setTimeout(()=>{if(x<Z){let n=(x/1024).toFixed(1);O(`Initial transfer too slow (${n} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let n=C.read(),z0,k=new Promise((y,d)=>{z0=setTimeout(()=>{d(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),p;try{p=await Promise.race([n,k])}finally{if(z0)clearTimeout(z0)}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=j?Math.round(x/j*100):0,U0=(x/1048576).toFixed(1),R=j?(j/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${d}% (${U0} / ${R} MB)...`)}catch{}}}}try{process.stderr.write(`
seal-use corps sync-test [<prodCorpId>][--dry-run][--yes][--version-name <name>]
seal-use corps replay-test [<prodCorpId>][--record-id <id>][--sn <sn>][--limit <n>][--status <status>][--webhook <idOrName>][--sn-suffix <str>][--dry-run][--confirm|--yes][--force]
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <url> [--name <customName>][--as-hose][--app-key <key>][--key-id <id>][--overwrite][--dry-run]
seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal-bearer --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <url> [--name <customName>][--elevate-hose][--app-key <key>][--key-id <id>][--overwrite][--dry-run]
seal-use corps probe-hose --json '{"appKey":"...","appSecurity":"...","domain":"https://..."}'
seal-use corps hose-staffs --json '{"appKey":"...","appSecurity":"...","role":"admin"}'
seal-use corps hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal][--save][--name <customName>][--app-key <key>][--key-id <id>][--overwrite]
@@ -212,9 +212,12 @@ Enterprise and tenant management (`corps` is the enterprise-context entry point)
Use the command groups in this order for normal work: **enterprise onboarding** → **discovery and selection** → **environment configuration** → **test pairing and verification**. Hose probing, staff discovery, key extraction, and key inspection are secondary capabilities for Hose-sourced enterprises.
-`seal-use corps add-link <url> [--name <name>] [--as-hose] [--app-key <key>] [--key-id <id>] [--overwrite] [--dry-run]` is the preferred onboarding entry point: it auto-detects a Seal native delegate link or a Hose assistance link. Native Seal links are registered as native Seal enterprises; Hose links can remain short-lived or use `--as-hose` for durable Hose credentials. `--dry-run` never writes local config.
-`seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"..."}'` registers a native Seal enterprise directly.
-`seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"..."}'` registers a Hose enterprise from durable OpenAPI credentials.
-`seal-use corps add-link <url> [--name <name>] [--elevate-hose] [--app-key <key>] [--key-id <id>] [--overwrite] [--dry-run]` is the preferred onboarding entry point: it auto-detects a Seal native delegate link or a Hose assistance link. Native Seal links are registered as native Seal enterprises; Hose links can remain short-lived or use `--elevate-hose` for durable Hose credentials. The legacy `--as-hose` alias remains accepted for compatibility.`--dry-run` never writes local config.
-`seal-use corps add-seal-bearer --json '{"sealUrl":"https://tenant.sealai.cc","token":"..."}'` registers a native Seal enterprise directly from a Seal Bearer Token. The old `add-seal` spelling remains a compatibility alias.
-`seal-use corps add-hose-web-session --json '{"baseUrl":"https://wx2.ekuaibao.com","corpId":"...","staffId":"...","accessToken":"..."}'` imports a normalized Hose web session (for example, parsed from a Hose admin cURL), saving the Hose `closeToken` and personnel ID. Seal Bearer is exchanged only at runtime; this command does not create or save OpenAPI `appKey/appSecurity` credentials.
-`seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"..."}'` registers and persists a Hose enterprise from durable OpenAPI credentials. The old `add-hose` spelling remains a compatibility alias.
Durable Hose configs are identified by `source.type: "hose"` plus `appKey/appSecurity`; Hose Web Session configs use the same source type with `closeToken + staffId`. When the session material includes an expiry, it is recorded as `expiresIn` (TTL seconds) and `expiresAt` (UTC without milliseconds, for example `2026-09-22T05:30:00Z`).
-`seal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--strict] [--corp <corpId>]` (defaults to displaying the top 10 most frequently used enterprises in the last 7 days; sorting is automatic and query results keep relevance order)
-`seal-use corps search <query> [--env <production|test>] [--strict]` (intelligent soft search by default: case-insensitive, Chinese homophones, front/back nasal vowels, flat/retroflex consonants, initials, typo/missing letter tolerance; pass `--strict` for exact substring match)
-`seal-use corps get <corpId>` (rich enterprise attributes with sensitive secrets safely redacted)
@@ -350,14 +353,14 @@ Approval runs, simulations, and Langfuse bridge:
Add and verify a Hose enterprise:
```bash
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use auth check --corp <corpId>
```
Force-write a Hose config without verification:
```bash
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId","force":true}'
seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId","force":true}'
@@ -39,16 +39,25 @@ Classify both the enterprise identity origin and how the current credential was
| Enterprise identity origin | Credential material the user may have | 权限等级与时效 | Meaning |
| --- | --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | 【最高·永久】自动签名/续期 | Stable, refreshable standard integration; unlocks full OpenAPI and `deploy hosecloud sync`. |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link (`thirdparty.html`) | 【两极分化】普通导入→短效;提权→永久 | Temporary session that can be **elevated** to permanent `appKey`/`appSecurity` with `extract-keys --save` or `add-link --as-hose`. |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link (`thirdparty.html`) | 【两极分化】普通导入→短效;提权→永久 | Temporary session that can be **elevated** to permanent `appKey`/`appSecurity` with `extract-keys --save` or `add-link --elevate-hose`. |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated **Hose admin** page | 【两极分化】普通导入→短效;提权→永久 | **Same session scope as an assistance link.** If the user is a Hose administrator, this carries the same web session credentials (`accesstoken`, `corpid`, cookies) and can equally invoke `/api/innerapi/v1/key` to extract permanent `appKey`/`appSecurity`. |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Seal page | 【短效会话快照】 | Snapshot with Seal Bearer token; can set up temporary Seal session access. |
| Seal-native tenant | Seal assistance/delegation link | 【临时·可撤销】 | Temporary delegated access to a Seal tenant. |
| Seal-native tenant | cURL copied from an authenticated Seal page | 【短效会话快照】 | Snapshot containing the Seal host and session authentication. |
| Seal-native tenant | Seal URL + Bearer Token, or cURL copied from an authenticated Seal page | 【短效会话快照】 | Both normalize to `add-seal-bearer`; the cURL is only a transport format for the same Seal Bearer credential. |
**同等凭据原则(Equal Credential Scope Principle)**: A Hose assistance link and a browser cURL from an authenticated Hose admin session are both Hose web frontend sessions — they carry the same underlying `accessToken`/`accesstoken` and `corpid`. The **only** structural difference is delivery format. When a Hose administrator sends you a cURL, treat it with the same privilege elevation potential as an assistance link. Do not downgrade it to a plain Seal session import without first attempting key extraction.
Credential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.
### Token boundary
The Hose web-session `accesstoken` and the Seal Bearer Token are different credentials and are not interchangeable:
-`corps add-seal-bearer` accepts the Seal Bearer Token together with `sealUrl`.
- A Hose cURL's `accesstoken` is used first for Hose key extraction. If no permanent OpenAPI key can be extracted, call `add-hose-web-session`; it stores the Hose `closeToken` and `staffId`, then exchanges the Hose session through Seal SSO only when a Seal session is needed.
- Never pass a Hose `accesstoken` directly as the `token` field of `add-seal-bearer`.
The saved config makes the lifecycle visible: durable Hose credentials use `source.type: "hose"` with `appKey/appSecurity`; Hose Web Session credentials also use `source.type: "hose"`, but carry `closeToken` and `staffId` instead. If the Hose session material provides an expiry, it is stored as `expiresIn` (seconds) and `expiresAt` in UTC second precision, such as `2026-09-22T05:30:00Z`. The Seal Bearer obtained through SSO is a runtime cache, not the enterprise source type.
## Parameter Ownership
Ask the user only for information that cannot be discovered safely:
@@ -67,7 +76,7 @@ Ask the user only for information that cannot be discovered safely:
This is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:
```bash
seal-use corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
seal-use corps add-hose-persistent --json '{"appKey":"...","appSecurity":"..."}'
```
The CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:
@@ -83,8 +92,8 @@ Do not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicate
First distinguish the link by its host, purpose, and identity origin:
- **Seal-Native Delegation Link (默认第一公民)**: `https://<tenant>.sealai.cc/delegate?token=...` grants delegated access directly on a Seal tenant. Running `seal-use corps add-link <url>` automatically exchanges the delegation token via `/api/v1/delegation/consume`, receives the session, retrieves tenant and user info via `/api/v1/auth/me`, and registers a native Seal enterprise (`provider: "seal"`). Supports `--dry-run` to preview metadata without mutating local config.
- **Hose/合思 Assistance Link**: `https://<domain>/web/thirdparty.html?...` opens an upstream Hose session and continues through Seal SSO. Running standard `seal-use corps add-link <url>`exchanges that temporary token for a short-lived Seal Bearer token.
- **Hose Subdomain Boundary (合思子域专属提权)**: `seal-use` primarily manages Seal tenants. Tenants sourced from the Hose ecosystem have an upstream Hose enterprise backing them. A received Hose assistance link contains only a temporary session `accessToken`. To elevate to permanent Hose OpenAPI developer credentials, use `corps hose-extract-keys <url> --save` or `corps add-link <url> --as-hose`. (Note: `--as-hose` cannot be used on Seal-native delegation links).
- **Hose/合思 Assistance Link**: `https://<domain>/web/thirdparty.html?...` opens an upstream Hose session and continues through Seal SSO. Running standard `seal-use corps add-link <url>`verifies the tenant and stores the Hose `closeToken` plus `staffId`; the Seal Bearer is runtime-only.
- **Hose Subdomain Boundary (合思子域专属提权)**: `seal-use` primarily manages Seal tenants. Tenants sourced from the Hose ecosystem have an upstream Hose enterprise backing them. A received Hose assistance link contains only a temporary session `accessToken`. To elevate to permanent Hose OpenAPI developer credentials, use `corps hose-extract-keys <url> --save` or `corps add-link <url> --elevate-hose`. (Note: `--elevate-hose` cannot be used on Seal-native delegation links; `--as-hose` remains a deprecated compatibility alias).
- **Multi-Key Disambiguation (多套密钥明确抉择)**: If the Hose enterprise owns multiple application keys, the CLI will not guess or silently pick the first key. Instead, it terminates with an informative candidate list and requires the user to specify `--app-key <key>` or `--key-id <id>`. If only one key exists, it is selected automatically.
- **Non-Hose Tenants Blocked**: Calling `keys` on native Seal enterprises (`corp.source.type !== "hose"`) is strictly rejected with exit code 2, explaining that this capability belongs exclusively to the Hose ecosystem.
@@ -95,7 +104,7 @@ First distinguish the link by its host, purpose, and identity origin:
seal-use corps add-link "https://<tenant>.sealai.cc/delegate?token=..."[--name "企业名称"][--dry-run]
# 2. 接入合思协助链接并提权为标准持久化合思企业配置:
seal-use corps add-link "<url>" --as-hose [--name "企业名称"]
seal-use corps add-link "<url>" --elevate-hose [--name "企业名称"]
# 或通过 extract-keys 提取保存:
seal-use corps hose-extract-keys "<url>" --save [--name "企业名称"]
@@ -113,7 +122,7 @@ seal-use corps hose-keys <corpId> [--reveal]
When using standard `add-link` with a Seal delegate link, it consumes the token directly against the Seal tenant and persists the verified Seal session. When using standard `add-link` with a Hose link (without `--as-hose`), it exchanges the temporary Hose token at the target Seal tenant and stores the short-lived Seal session. When `--as-hose` is used on a Hose link, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration.
When using standard `add-link` with a Seal delegate link, it consumes the token directly against the Seal tenant and persists the verified Seal session. When using standard `add-link` with a Hose link (without `--elevate-hose`), it stores the Hose web-session source (`closeToken` plus `staffId`) and uses the temporary Seal Bearer only at runtime. When `--elevate-hose` is used on a Hose link, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration. The legacy `--as-hose` alias remains accepted for compatibility.
Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it.
@@ -140,7 +149,7 @@ This is functionally equivalent to a Hose assistance link. Both carry the same u
1. Treat the entire cURL as a secret. Do not echo it, execute it blindly, paste it into another service, or store it in repository files.
2. Extract: the request hostname (determines `baseUrl`), `accesstoken` header (session token), `corpid` header or cookie, and any other Hose session headers.
3.**Privilege elevation path (preferred)**: Use extracted `accesstoken`, `corpid`, and `baseUrl` to call `/api/innerapi/v1/key`, exactly as `corps hose-extract-keys` does for assistance links. This retrieves permanent `appKey`/`appSecurity` to register a durable Hose enterprise configuration — do not skip this step just because the input is a cURL instead of a URL.
4.**Fallback short-term path**: If the session user is not an administrator and the key interface returns no keys, fall back to the Seal SSO bridge to register a temporary Seal session.
4.**Fallback short-term path**: If the session user is not an administrator and the key interface returns no keys, pass the normalized Hose session to `corps add-hose-web-session`; it saves the Hose `closeToken` and `staffId`, then uses the Seal SSO bridge only when a Seal session is needed.
5. If key extraction succeeds, inform the user that credentials have been permanently elevated; if it fails, explain the limitation and suggest the administrator copy a dedicated cURL or provide an assistance link or `appKey`/`appSecurity`.
```
@@ -155,11 +164,11 @@ This is functionally equivalent to a Hose assistance link. Both carry the same u
1. Treat the entire cURL as a secret.
2. Parse it as data. Extract the request host, path, `Authorization: Bearer ...` header, and provider/tenant hints.
3. Verify with `/api/v1/auth/me` through `seal-use corps add-seal`; use returned provider metadata to retain the actual origin.
3. Verify with `/api/v1/auth/me` through `seal-use corps add-seal-bearer`; use returned provider metadata to retain the actual origin.
4. Persist only the normalized minimum configuration needed by seal-use.
```bash
seal-use corps add-seal --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
seal-use corps add-seal-bearer --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
```
If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
@@ -6,16 +6,16 @@ Use this reference for Hose/合思 enterprise configuration and user-facing Hose
Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit `~/.config/seal-use/enterprises/*.json` unless the CLI fails or the user explicitly asks for low-level config debugging.
For first-time setup or when the user has an assistance link or browser cURL instead of standard application credentials, read `enterprise-onboarding.md` first. This reference's `add-hose` route is specifically for durable Hose OpenAPI credentials.
For first-time setup or when the user has an assistance link or browser cURL instead of standard application credentials, read `enterprise-onboarding.md` first. This reference's `add-hose-persistent` route is specifically for durable Hose OpenAPI credentials.
```bash
seal-use corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
seal-use corps add-hose-persistent --json '{"appKey":"...","appSecurity":"..."}'
seal-use corps list
seal-use corps current --corp <corpId>
seal-use corps switch <corpId>
```
`corps add-hose` probes standard domains and discovers the enterprise automatically. If it returns multiple administrator candidates, present their names and masked phones for the user to choose, then retry with `staffName`, `staffPhone`, or the selected `staffId`. Do not ask for `domain`, `corpId`, `staffId`, or `proxyStaffBizId` before discovery. Ask for a dedicated/private-cloud `domain` only after standard probing fails.
`corps add-hose-persistent` probes standard domains and discovers the enterprise automatically. If it returns multiple administrator candidates, present their names and masked phones for the user to choose, then retry with `staffName`, `staffPhone`, or the selected `staffId`. Do not ask for `domain`, `corpId`, `staffId`, or `proxyStaffBizId` before discovery. Ask for a dedicated/private-cloud `domain` only after standard probing fails. The old `add-hose` spelling remains a compatibility alias.
The command verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at `corps` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
`Cannot use '${prodCorp.id}' as a production enterprise because it is already registered as a test enterprise for '${prodCorp.prodCorpId}'. Multi-tier chaining is not permitted.`
`Cannot bind '${testCorp.id}' as a test enterprise because it already has a bound test enterprise '${testCorp.testCorpId}'. Multi-tier chaining is not permitted.`
`Enterprise binding conflict: production enterprise '${prodCorp.id}' is bound to '${prodCorp.testCorpId??"none"}', and test enterprise '${testCorp.id}' is bound to '${testCorp.prodCorpId??"none"}'. Overwriting an existing binding requires --force and --confirm.`,
`seal-use corps bind-test ${prodCorp.id}${testCorp.id} --confirm --force`
`Refusing to bind test enterprise '${testCorp.name}' (${testCorp.id}) to production enterprise '${prodCorp.name}' (${prodCorp.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${testCorp.id}' as a test environment.`,
`seal-use corps bind-test ${prodCorp.id}${testCorp.id} --confirm${forceFlag}`
`Refusing to change environment tag of enterprise '${corp.name}' (${corp.id}) to '${targetEnv}' without --confirm. Marking alters synchronization safety guards.`,
`seal-use corps mark ${corp.id} --env ${targetEnv} --confirm`
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n`+
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`
);
}
consttestCorp=selectCorp(prodCorp.testCorpId);
if(testCorp.environment!=="test"){
thrownewError(
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting sync to protect non-test environments.`
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences, ${preview.rulesPlan.sourceDraftRuleCount} draft rules, and ${preview.documentsPlan.sourceDocumentCount} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n`+
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association,\n`+
`or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`
);
}
testCorp=prodCorp;
}else{
testCorp=selectCorp(prodCorp.testCorpId);
if(testCorp.environment!=="test"&&!force){
thrownewError(
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`
);
}
}
if(!dryRun&&!confirmed){
throwconfirmationRequired(
"Refusing to replay approval records without --confirm. Use --dry-run to preview the payload without sending it.",
`seal-use corps replay-test ${targetCorpId??"<prodCorpId>"} --confirm`
description:"Pulls production approval records from the production enterprise and replays them into the bound test enterprise's Webhook channel for rule verification."
},
{
name:"add-hose",
name:"add-hose-persistent",
aliases:["add-hose"],
group:"企业接入",
summary:"Add a Hose/Ekuaibao enterprise configuration",
usage:["seal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'"]
summary:"Add a durable Hose/Ekuaibao enterprise configuration",
usage:["seal-use corps add-hose-persistent --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'"],
summary:"Add a native Seal enterprise configuration",
usage:["seal-use corps add-seal --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'"]
summary:"Add a native Seal enterprise from a Bearer session",
usage:["seal-use corps add-seal-bearer --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'"],
description:"使用 Seal Bearer Token 接入原生 Seal 企业;旧命令 add-seal 仍可用,但仅作为兼容别名。"
},
{
name:"add-hose-web-session",
group:"企业接入",
summary:"Import a temporary Hose web session and exchange it for a Seal session",
usage:["seal-use corps add-hose-web-session --json '{\"baseUrl\":\"https://wx2.ekuaibao.com\",\"corpId\":\"...\",\"staffId\":\"...\",\"accessToken\":\"...\"}'"],
options:[
{flag:"--name <name>",description:"Optional custom name for the enterprise"},
{flag:"--domain <url>",description:"Hose web-session base URL (alias: --base-url)"},
thrownewError(`No staff member found matching '${input.staffName??input.staffPhone}' under role ${targetRoleId}. Run 'seal-use corps hose-staffs' to view candidates.`);
if(prodCorp.source.type!=="hose")return{sourceType: prodCorp.source.type,skipped: true,reason:"prod source is not hose; no hosecloud credentials available"};
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.