- **Isolation Rule**: If the main working directory contains uncommitted changes or another branch is actively being edited, NEVER switch branches or stash in the shared repository. Instead, use an isolated worktree for release operations:
```bash
git worktree add -b codex/release-vX.Y.Z /tmp/seal-use-release main
cd /tmp/seal-use-release
# Execute bump, commit, push, PR, merge, tag here
# When finished, remove the worktree:
git worktree remove /tmp/seal-use-release
```
- Do not tag or push `main` directly. Create a release branch, commit the version bump, push it, open a PR to `main`, wait for the required CI check, and merge the PR first.
- After the PR is merged, fast-forward the local `main`, then synchronize `home/main` before creating the tag:
- Implemented extracting permanent OpenAPI developer credentials (`appKey` and `appSecurity`) from incoming Hose/Ekuaibao assistance links (`thirdparty.html`) via internal session key interfaces (`GET /api/innerapi/v1/key`).
- Added `seal-use corps extract-keys <url>` (alias: `seal-use auth extract-keys`) with `--reveal` (`-r`) for explicit unmasking and `--save` to upgrade short-lived session links into durable standard Hose enterprise configurations.
- Added `--as-hose` option to `seal-use corps add-link` to automatically elevate privileges to standard Hose configuration upon link import.
- Explicitly defined the Hose capability boundary: `seal-use` is the primary smart approval platform; Hose is an upstream integrated ecosystem.
- Calling key extraction or `keys` on native Seal enterprises (`corp.source.type !== "hose"`) is strictly rejected with exit code 2 and explicit subdomain boundary explanations.
- **Multi-Key Disambiguation Guardrails**:
- Enforced interactive disambiguation when an enterprise has multiple OpenAPI keys configured instead of guessing or silently picking the first key.
- Emits candidate key lists with application names, appKeys, keyIds, and active status to `stderr`, requiring explicit selection via `--app-key <key>` or `--key-id <id>`. Single-key enterprises are safely auto-selected.
- Fully documented that a Hose assistance link and a browser cURL from an authenticated Hose admin session are both Hose web frontend sessions with identical privilege scope — the structural difference is delivery format only.
- Updated `SKILL.md` First Rules and `enterprise-onboarding.md` Route 3 with explicit guidance: when a Hose administrator provides a browser cURL, attempt privilege elevation first (extract `accesstoken`+`corpid`+`baseUrl` → call `/api/innerapi/v1/key`), not a downgraded short-term session import.
- Added Route 3a/3b/3c classification in `enterprise-onboarding.md` and a privilege comparison table (F12 session vs. elevated OpenAPI credentials).
- Added opt-in `--with-flow` flag to `seal-use approval-runs export` to enrich reports with **E人工行为** and **E人工意见** columns from native Hose/Ekuaibao approval timelines.
- **Rejection Formatting (样式 2-B 三行展开式)**: Cleanly structures rejections with explicit reject target nodes, staff names with roles, and resubmission routing (`↳ 驳回至: ...` / `↳ 重新提交后由...继续审批`).
- **Mid-Flow Modification Detection**: Identifies mid-flow edits (`已支付 (中途修改)` / `审批通过 (中途修改)`), hoists modification events to top (`✏️: 修改了单据`) for instant fact visibility while strictly preserving genuine approval-flow chronological sequence numbers.
- **Action Emojis**: Visual distinction across approval actions (`✏️` 修改、`🤖` 自动同意、`❌` 驳回、`💰` 支付、`💬` 附言、`↩️` 撤回、`🔀` 转审),while normal approvals maintain a clean text format (`: 同意`).
- **Targeted Document SN Export Filter (`--sn` / `--sns`)**:
- Supported `--sn <SN1,SN2>` or `--sns` option for `seal-use approval-runs export` to filter specific documents by single or comma-separated document SNs.
- Direct indexed lookup via Seal backend `search: sn`, bypassing full pagination scans and reducing export runtimes from 30+ seconds to ~1.5 seconds.
- Smart time windowing: searches across full history without artificial 1-day truncation when start/end dates are omitted, and dynamically computes filename date interval from retrieved records.
- **Strict Clean Export Filenames with Forced Minute Timestamp**:
- Enforced a standard format `${safeCorpName}_审核记录_${dateTag}_${countTag}_${YYYYMMDD_HHmm}.xlsx`.
- Filename timestamp suffix accurate to the minute prevents accidental overwrites and ambiguity.
- Eradicated document SN numbers from the output filename to maintain a concise, standard pattern regardless of export batch size.
- **CLI Help, Guidance & Diagnostics Channel**:
- Enhanced `seal-use approval-runs export --help` with complete option table.
- Added next-step command suggestions (`👉 查看导出文件: open "..."`) and flow enrichment hints to `stderr`.
- Synchronized `skills/seal-use/SKILL.md` and CLI documentation references.
import{createRequireasHS0}from"node:module";var$S0=Object.create;var{getPrototypeOf:IS0,defineProperty:QP,getOwnPropertyNames:zS0}=Object;varqS0=Object.prototype.hasOwnProperty;functionUS0($){returnthis[$]}varYS0,JS0,j4=($,I,z)=>{varq=$!=null&&typeof$==="object";if(q){varU=I?YS0??=newWeakMap:JS0??=newWeakMap,Y=U.get($);if(Y)returnY}z=$!=null?$S0(IS0($)):{};letJ=I||!$||!$.__esModule?QP(z,"default",{value:$,enumerable:!0}):z;for(letQofzS0($))if(!qS0.call(J,Q))QP(J,Q,{get:US0.bind($,Q),enumerable:!0});if(q)U.set($,J);returnJ};varM=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);varQS0=($)=>$;functionKS0($,I){this[$]=QS0.bind(null,I)}varo8=($,I)=>{for(varzinI)QP($,z,{get:I[z],enumerable:!0,configurable:!0,set:KS0.bind(I,z)})};vare=($,I)=>()=>($&&(I=$($=0)),I);vard=HS0(import.meta.url);functiont($,I,z){functionq(Q,K){if(!Q._zod)Object.defineProperty(Q,"_zod",{value:{def:K,constr:J,traits:newSet},enumerable:!1});if(Q._zod.traits.has($))return;Q._zod.traits.add($),I(Q,K);letH=J.prototype,G=Object.keys(H);for(letZ=0;Z<G.length;Z++){letW=G[Z];if(!(WinQ))Q[W]=H[W].bind(Q)}}letU=z?.Parent??Object;classYextendsU{}Object.defineProperty(Y,"name",{value:$});functionJ(Q){varK;letH=z?.Parent?newY:this;q(H,Q),(K=H._zod).deferred??(K.deferred=[]);for(letGofH._zod.deferred)G();returnH}returnObject.defineProperty(J,"init",{value:q}),Object.defineProperty(J,Symbol.hasInstance,{value:(Q)=>{if(z?.Parent&&Qinstanceofz.Parent)return!0;returnQ?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}functionf4($){if($)Object.assign(H2,$);returnH2}varqm,KP,HP,O5,G2,H2;varZ2=e(()=>{KP=Object.freeze({status:"aborted"});HP=Symbol("zod_brand");O5=classO5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};G2=classG2extendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(qm=globalThis).__zod_globalConfig??(qm.__zod_globalConfig={});H2=globalThis.__zod_globalConfig});varM0={};o8(M0,{unwrapMessage:()=>EJ,uint8ArrayToHex:()=>SS0,uint8ArrayToBase64url:()=>hS0,uint8ArrayToBase64:()=>Jm,stringifyPrimitive:()=>w0,slugify:()=>WP,shallowClone:()=>VP,safeExtend:()=>ES0,required:()=>_S0,randomString:()=>MS0,propertyKeyTypes:()=>_J,promiseAllObject:()=>FS0,primitiveTypes:()=>wP,prefixIssues:()=>E8,pick:()=>PS0,partial:()=>CS0,parsedType:()=>O0,optionalKeys:()=>LP,omit:()=>BS0,objectClone:()=>wS0,numKeys:()=>NS0,nullish:()=>L3,normalizeParams:()=>A0,mergeDefs:()=>H9,merge:()=>jS0,jsonStringifyReplacer:()=>Bz,joinValues:()=>Y0,issue:()=>Ez,isPlainObject:()=>F3,isObject:()=>W2,hexToUint8Array:()=>gS0,getSizableOrigin:()=>RJ,getParsedType:()=>DS0,getLengthableOrigin:()=>vJ,getEnumValues:()=>jJ,getElementAtPath:()=>OS0,floatSafeRemainder:()=>ZP,finalizeIssue:()=>K8,extend:()=>TS0,explicitlyAborted:()=>MP,escapeRegex:()=>w$,esc:()=>TW,defineLazy:()=>J1,createTransparentProxy:()=>AS0,cloneDef:()=>LS0,clone:()=>Q8,cleanRegex:()=>CJ,cleanEnum:()=>RS0,captureStackTrace:()=>EW,cached:()=>Tz,base64urlToUint8Array:()=>vS0,base64ToUint8Array:()=>Ym,assignProp:()=>O3,assertNotEqual:()=>ZS0,assertNever:()=>XS0,assertIs:()=>WS0,assertEqual:()=>GS0,assert:()=>VS0,allowsEval:()=>XP,aborted:()=>M3,NUMBER_FORMAT_RANGES:()=>OP,Class:()=>Qm,BIGINT_FORMAT_RANGES:()=>FP});functionGS0($){return$}functionZS0($){return$}functionWS0($){}functionXS0($){throwError("Unexpected value in exhaustive check")}functionVS0($){}functionjJ($){letI=Object.values($).filter((q)=>typeofq==="number");returnObject.entries($).filter(([q,U])=>I.indexOf(+q)===-1).map(([q,U])=>U)}functionY0($,I="|"){return$.map((z)=>w0(z)).join(I)}functionBz($,I){if(typeofI==="bigint")returnI.toString();returnI}functionTz($){return{getvalue(){{letz=$();returnObject.defineProperty(this,"value",{value:z}),z}throwError("cached value already set")}}}functionL3($){return$===null||$===void0}functionCJ($){letI=$.startsWith("^")?1:0,z=$.endsWith("$")?$.length-1:$.length;return$.slice(I,z)}functionZP($,I){letz=$/I,q=Math.round(z),U=Number.EPSILON*Math.max(Math.abs(z),1);if(Math.abs(z-q)<U)return0;returnz-q}functionJ1($,I,z){letq=void0;Object.defineProperty($,I,{get(){if(q===Um)return;if(q===void0)q=Um,q=z();returnq},set(U){Object.defineProperty($,I,{value:U})},configurable:!0})}functionwS0($){returnObject.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}functionO3($,I,z){Object.defineProperty($,I,{value:z,writable:!0,enumerable:!0,configurable:!0})}functionH9(...$){letI={};for(letzof$){letq=Object.getOwnPropertyDescriptors(z);Object.assign(I,q)}returnObject.defineProperties({},I)}functionLS0($){returnH9($._zod.def)}functionOS0($,I){if(!I)return$;returnI.reduce((z,q)=>z?.[q],$)}functionFS0($){letI=Object.keys($),z=I.map((q)=>$[q]);returnPromise.all(z).then((q)=>{letU={};for(letY=0;Y<I.length;Y++)U[I[Y]]=q[Y];returnU})}functionMS0($=10){letz=""Line truncated
`)}var Km=($,I)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:I,enumerable:!1}),$.message=JSON.stringify(I,Bz,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},hJ,j8;var AP=e(()=>{Z2();h0();hJ=t("$ZodError",Km),j8=t("$ZodError",Km,{Parent:Error})});var jz=($)=>(I,z,q,U)=>{let Y=q?{...q,async:!1}:{async:!1},J=I._zod.run({value:z,issues:[]},Y);if(J instanceof Promise)throw new O5;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>K8(K,Y,f4())));throw EW(Q,U?.callee),Q}return J.value},yJ,Cz=($)=>async(I,z,q,U)=>{let Y=q?{...q,async:!0}:{async:!0},J=I._zod.run({value:z,issues:[]},Y);if(J instanceof Promise)J=await J;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>K8(K,Y,f4())));throw EW(Q,U?.callee),Q}return J.value},xJ,_z=($)=>(I,z,q)=>{let U=q?{...q,async:!1}:{async:!1},Y=I._zod.run({value:z,issues:[]},U);if(Y instanceof Promise)throw new O5;return Y.issues.length?{success:!1,error:new($??hJ)(Y.issues.map((J)=>K8(J,U,f4())))}:{success:!0,data:Y.value}},Rz,vz=($)=>async(I,z,q)=>{let U=q?{...q,async:!0}:{async:!0},Y=I._zod.run({value:z,issues:[]},U);if(Y instanceof Promise)Y=await Y;return Y.issues.length?{success:!1,error:new $(Y.issues.map((J)=>K8(J,U,f4())))}:{success:!0,data:Y.value}},uJ,jW=($)=>(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return jz($)(I,z,U)},Gm,CW=($)=>(I,z,q)=>{return jz($)(I,z,q)},Zm,_W=($)=>async(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return Cz($)(I,z,U)},Wm,RW=($)=>async(I,z,q)=>{return Cz($)(I,z,q)},Xm,vW=($)=>(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return _z($)(I,z,U)},Vm,hW=($)=>(I,z,q)=>{return _z($)(I,z,q)},wm,gW=($)=>async(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return vz($)(I,z,U)},Lm,SW=($)=>async(I,z,q)=>{return vz($)(I,z,q)},Om;var PP=e(()=>{Z2();AP();h0();yJ=jz(j8),xJ=Cz(j8),Rz=_z(j8),uJ=vz(j8),Gm=jW(j8),Zm=CW(j8),Wm=_W(j8),Xm=RW(j8),Vm=vW(j8),wm=hW(j8),Lm=gW(j8),Om=SW(j8)});var r8={};o8(r8,{xid:()=>jP,uuid7:()=>fS0,uuid6:()=>kS0,uuid4:()=>uS0,uuid:()=>X2,uppercase:()=>aP,unicodeEmail:()=>Fm,undefined:()=>sP,ulid:()=>EP,time:()=>cP,string:()=>dP,sha512_hex:()=>Jy0,sha512_base64url:()=>Ky0,sha512_base64:()=>Qy0,sha384_hex:()=>qy0,sha384_base64url:()=>Yy0,sha384_base64:()=>Uy0,sha256_hex:()=>$y0,sha256_base64url:()=>zy0,sha256_base64:()=>Iy0,sha1_hex:()=>tS0,sha1_base64url:()=>eS0,sha1_base64:()=>aS0,rfc5322Email:()=>iS0,number:()=>kJ,null:()=>rP,nanoid:()=>_P,md5_hex:()=>oS0,md5_base64url:()=>sS0,md5_base64:()=>rS0,mac:()=>xP,lowercase:()=>tP,ksuid:()=>CP,ipv6:()=>yP,ipv4:()=>SP,integer:()=>lP,idnEmail:()=>nS0,httpProtocol:()=>bP,html5Email:()=>bS0,hostname:()=>dS0,hex:()=>lS0,guid:()=>vP,extendedDuration:()=>xS0,emoji:()=>gP,email:()=>hP,e164:()=>iP,duration:()=>RP,domain:()=>mS0,datetime:()=>pP,date:()=>nP,cuid2:()=>TP,cuid:()=>BP,cidrv6:()=>kP,cidrv4:()=>uP,browserEmail:()=>cS0,boolean:()=>oP,bigint:()=>mP,base64url:()=>yW,base64:()=>fP});function gP(){return new RegExp(pS0,"u")}function Nm($){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 cP($){return new RegExp(`^${Nm($)}$`)}function pP($){let I=Nm({precision:$.precision}),z=["Z"];if($.local)z.push("");if($.offset)z.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let q=`${I}(?:${z.join("|")})`;return new RegExp(`^${Mm}T(?:${q})$`)}function fJ($,I){return new RegExp(`^[A-Za-z0-9+/]{${$}}${I}$`)}function bJ($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var BP,TP,EP,jP,CP,_P,RP,xS0,vP,X2=($)=>{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})$`)},uS0,kS0,fS0,hP,bS0,iS0,Fm,nS0,cS0,pS0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",SP,yP,xP=($)=>{letI=w$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${I}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${I}){5}[0-9a-f]{2}$`)},uP,kP,fP,yW,dS0,mS0,bP,iP,Mm="(?:(?:\\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])))",nP,dP=($)=>{letI=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${I}$`)},mP,lP,kJ,oP,rP,sP,tP,aP,lS0,oS0,rS0,sS0,tS0,aS0,eS0,$y0,Iy0,zy0,qy0,Uy0,Yy0,Jy0,Qy0,Ky0;varxW=e(()=>{h0();BP=/^[cC][0-9a-z]{6,}$/,TP=/^[0-9a-z]+$/,EP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jP=/^[0-9a-vA-V]{20}$/,CP=/^[A-Za-z0-9]{27}$/,_P=/^[a-zA-Z0-9_-]{21}$/,RP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?Line truncated
`).filter((Y)=>Y),q=Math.min(...z.map((Y)=>Y.length-Y.trimStart().length)),U=z.map((Y)=>Y.slice(q)).map((Y)=>" ".repeat(this.indent*2)+Y);for(let Y of U)this.content.push(Y)}compile(){let $=Function,I=this?.args,q=[...(this?.content??[""]).map((U)=>`${U}`)];return new $(...I,q.join(`
`))}}var OB;var FB=e(()=>{OB={major:4,minor:4,patch:3}});function bB($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function km($){if(!yW.test($))return!1;let I=$.replace(/[-_]/g,(q)=>q==="-"?"+":"/"),z=I.padEnd(Math.ceil(I.length/4)*4,"=");return bB(z)}function fm($,I=null){try{let z=$.split(".");if(z.length!==3)return!1;let[q]=z;if(!q)return!1;let U=JSON.parse(atob(q));if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if(I&&(!("alg"in U)||U.alg!==I))return!1;return!0}catch{return!1}}function Bm($,I,z){if($.issues.length)I.issues.push(...E8(z,$.issues));I.value[z]=$.value}function pW($,I,z,q,U,Y){let J=z in q;if($.issues.length){if(U&&Y&&!J)return;I.issues.push(...E8(z,$.issues))}if(!J&&!U){if(!$.issues.length)I.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[z]});return}if($.value===void 0){if(J)I.value[z]=void 0}else I.value[z]=$.value}function bm($){let I=Object.keys($.shape);for(let q of I)if(!$.shape?.[q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${q}":expectedaZodschema`);let z=LP($.shape);return{...$,keys:I,keySet:new Set(I),numKeys:I.length,optionalKeys:new Set(z)}}function im($,I,z,q,U,Y){let J=[],Q=U.keySet,K=U.catchall._zod,H=K.def.type,G=K.optin==="optional",Z=K.optout==="optional";for(let W in I){if(W==="__proto__")continue;if(Q.has(W))continue;if(H==="never"){J.push(W);continue}let X=K.run({value:I[W],issues:[]},q);if(X instanceof Promise)$.push(X.then((w)=>pW(w,z,W,I,G,Z)));else pW(X,z,W,I,G,Z)}if(J.length)z.issues.push({code:"unrecognized_keys",keys:J,input:I,inst:Y});if(!$.length)return z;return Promise.all($).then(()=>{return z})}function Tm($,I,z,q){for(let Y of $)if(Y.issues.length===0)return I.value=Y.value,I;let U=$.filter((Y)=>!M3(Y));if(U.length===1)return I.value=U[0].value,U[0];return I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:$.map((Y)=>Y.issues.map((J)=>K8(J,q,f4())))}),I}function Em($,I,z,q){let U=$.filter((Y)=>Y.issues.length===0);if(U.length===1)return I.value=U[0].value,I;if(U.length===0)I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:$.map((Y)=>Y.issues.map((J)=>K8(J,q,f4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:[],inclusive:!1});return I}function MB($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if(F3($)&&F3(I)){let z=Object.keys(I),q=Object.keys($).filter((Y)=>z.indexOf(Y)!==-1),U={...$,...I};for(let Y of q){let J=MB($[Y],I[Y]);if(!J.valid)return{valid:!1,mergeErrorPath:[Y,...J.mergeErrorPath]};U[Y]=J.data}return{valid:!0,data:U}}if(Array.isArray($)&&Array.isArray(I)){if($.length!==I.length)return{valid:!1,mergeErrorPath:[]};let z=[];for(let q=0;q<$.length;q++){let U=$[q],Y=I[q],J=MB(U,Y);if(!J.valid)return{valid:!1,mergeErrorPath:[q,...J.mergeErrorPath]};z.push(J.data)}return{valid:!0,data:z}}return{valid:!1,mergeErrorPath:[]}}function jm($,I,z){let q=new Map,U;for(let Q of I.issues)if(Q.code==="unrecognized_keys"){U??(U=Q);for(let K of Q.keys){if(!q.has(K))q.set(K,{});q.get(K).l=!0}}else $.issues.push(Q);for(let Q of z.issues)if(Q.code==="unrecognized_keys")for(let K of Q.keys){if(!q.has(K))q.set(K,{});q.get(K).r=!0}else $.issues.push(Q);let Y=[...q].filter(([,Q])=>Q.l&&Q.r).map(([Q])=>Q);if(Y.length&&U)$.issues.push({...U,keys:Y});if(M3($))return $;let J=MB(I.value,z.value);if(!J.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}function Cm($,I){for(let z=$.length-1;z>=0;z--)if($[z]._zod[I]!=="optional")return z+1;return 0}function _m($,I,z){if($.issues.length)I.issues.push(...E8(z,$.issues));I.value[z]=$.value}function Rm($,I,z,q,U){for(let Y=0;Y<z.length;Y++){let J=$[Y],Q=Y<q.length;if(J.issues.length){if(!Q&&Y>=U){I.value.length=Y;break}I.issues.push(...E8(Y,J.issues))}I.value[Y]=J.value}for(let Y=I.value.length-1;Y>=q.length;Y--)if(z[Y]._zod.optout==="optional"&&I.value[Y]===void 0)I.value.length=Y;else break;return I}function vm($,I,z,q,U,Y,J){if($.issues.length)if(_J.has(typeof q))z.issues.push(...E8(q,$.issues));else z.issues.push({code:"invalid_key",origin:"map",input:U,inst:Y,issues:$.issues.map((Q)=>K8(Q,J,f4()))});if(I.issues.length)if(_J.has(typeof q))z.issues.push(...E8(q,I.issues));else z.issues.push({origin:"map",code:"invalid_element",input:U,inst:Y,key:q,issues:I.issues.map((Q)=>K8(Q,J,f4()))});z.value.set($.value,I.value)}function hm($,I){if($.issues.length)I.issues.push(...$.issues);I.value.add($.value)}function gm($,I){if(I===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function Sm($,I){if($.value===void 0)$.value=I.defaultValue;return $}function ym($,I){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:I});return $}function iW($,I,z){if($.issues.length)return $.aborted=!0,$;return I._zod.run({value:$.value,issues:$.issues,fa
Line truncated
import{createRequireasUy0}from"node:module";varsS0=Object.create;var{getPrototypeOf:tS0,defineProperty:DA,getOwnPropertyNames:aS0}=Object;vareS0=Object.prototype.hasOwnProperty;function$y0($){returnthis[$]}varYy0,qy0,y4=($,Y,q)=>{varz=$!=null&&typeof$==="object";if(z){varJ=Y?Yy0??=newWeakMap:qy0??=newWeakMap,U=J.get($);if(U)returnU}q=$!=null?sS0(tS0($)):{};letI=Y||!$||!$.__esModule?DA(q,"default",{value:$,enumerable:!0}):q;for(letQofaS0($))if(!eS0.call(I,Q))DA(I,Q,{get:$y0.bind($,Q),enumerable:!0});if(z)J.set($,I);returnI};varM=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);varzy0=($)=>$;functionJy0($,Y){this[$]=zy0.bind(null,Y)}var$$=($,Y)=>{for(varqinY)DA($,q,{get:Y[q],enumerable:!0,configurable:!0,set:Jy0.bind(Y,q)})};vare=($,Y)=>()=>($&&(Y=$($=0)),Y);varm=Uy0(import.meta.url);functiona($,Y,q){functionz(Q,K){if(!Q._zod)Object.defineProperty(Q,"_zod",{value:{def:K,constr:I,traits:newSet},enumerable:!1});if(Q._zod.traits.has($))return;Q._zod.traits.add($),Y(Q,K);letG=I.prototype,H=Object.keys(G);for(letZ=0;Z<H.length;Z++){letV=H[Z];if(!(VinQ))Q[V]=G[V].bind(Q)}}letJ=q?.Parent??Object;classUextendsJ{}Object.defineProperty(U,"name",{value:$});functionI(Q){varK;letG=q?.Parent?newU:this;z(G,Q),(K=G._zod).deferred??(K.deferred=[]);for(letHofG._zod.deferred)H();returnG}returnObject.defineProperty(I,"init",{value:z}),Object.defineProperty(I,Symbol.hasInstance,{value:(Q)=>{if(q?.Parent&&Qinstanceofq.Parent)return!0;returnQ?._zod?.traits?.has($)}}),Object.defineProperty(I,"name",{value:$}),I}functionm4($){if($)Object.assign(L2,$);returnL2}vargm,PA,AA,T5,w2,L2;varF2=e(()=>{PA=Object.freeze({status:"aborted"});AA=Symbol("zod_brand");T5=classT5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};w2=classw2extendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(gm=globalThis).__zod_globalConfig??(gm.__zod_globalConfig={});L2=globalThis.__zod_globalConfig});varP0={};$$(P0,{unwrapMessage:()=>kI,uint8ArrayToHex:()=>Cy0,uint8ArrayToBase64url:()=>_y0,uint8ArrayToBase64:()=>xm,stringifyPrimitive:()=>O0,slugify:()=>EA,shallowClone:()=>_A,safeExtend:()=>Py0,required:()=>Ty0,randomString:()=>Ly0,propertyKeyTypes:()=>bI,promiseAllObject:()=>Vy0,primitiveTypes:()=>RA,prefixIssues:()=>h8,pick:()=>My0,partial:()=>By0,parsedType:()=>N0,optionalKeys:()=>CA,omit:()=>Ny0,objectClone:()=>Zy0,numKeys:()=>wy0,nullish:()=>B3,normalizeParams:()=>B0,mergeDefs:()=>O9,merge:()=>Ay0,jsonStringifyReplacer:()=>Cq,joinValues:()=>I0,issue:()=>hq,isPlainObject:()=>E3,isObject:()=>O2,hexToUint8Array:()=>Ry0,getSizableOrigin:()=>iI,getParsedType:()=>Fy0,getLengthableOrigin:()=>nI,getEnumValues:()=>uI,getElementAtPath:()=>Xy0,floatSafeRemainder:()=>TA,finalizeIssue:()=>L8,extend:()=>Dy0,explicitlyAborted:()=>gA,escapeRegex:()=>O$,esc:()=>xW,defineLazy:()=>G1,createTransparentProxy:()=>Oy0,cloneDef:()=>Wy0,clone:()=>V8,cleanRegex:()=>fI,cleanEnum:()=>Ey0,captureStackTrace:()=>kW,cached:()=>vq,base64urlToUint8Array:()=>jy0,base64ToUint8Array:()=>ym,assignProp:()=>T3,assertNotEqual:()=>Qy0,assertNever:()=>Gy0,assertIs:()=>Ky0,assertEqual:()=>Iy0,assert:()=>Hy0,allowsEval:()=>jA,aborted:()=>j3,NUMBER_FORMAT_RANGES:()=>vA,Class:()=>km,BIGINT_FORMAT_RANGES:()=>hA});functionIy0($){return$}functionQy0($){return$}functionKy0($){}functionGy0($){throwError("Unexpected value in exhaustive check")}functionHy0($){}functionuI($){letY=Object.values($).filter((z)=>typeofz==="number");returnObject.entries($).filter(([z,J])=>Y.indexOf(+z)===-1).map(([z,J])=>J)}functionI0($,Y="|"){return$.map((q)=>O0(q)).join(Y)}functionCq($,Y){if(typeofY==="bigint")returnY.toString();returnY}functionvq($){return{getvalue(){{letq=$();returnObject.defineProperty(this,"value",{value:q}),q}throwError("cached value already set")}}}functionB3($){return$===null||$===void0}functionfI($){letY=$.startsWith("^")?1:0,q=$.endsWith("$")?$.length-1:$.length;return$.slice(Y,q)}functionTA($,Y){letq=$/Y,z=Math.round(q),J=Number.EPSILON*Math.max(Math.abs(q),1);if(Math.abs(q-z)<J)return0;returnq-z}functionG1($,Y,q){letz=void0;Object.defineProperty($,Y,{get(){if(z===Sm)return;if(z===void0)z=Sm,z=q();returnz},set(J){Object.defineProperty($,Y,{value:J})},configurable:!0})}functionZy0($){returnObject.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}functionT3($,Y,q){Object.defineProperty($,Y,{value:q,writable:!0,enumerable:!0,configurable:!0})}functionO9(...$){letY={};for(letqof$){letz=Object.getOwnPropertyDescriptors(q);Object.assign(Y,z)}returnObject.defineProperties({},Y)}functionWy0($){returnO9($._zod.def)}functionXy0($,Y){if(!Y)return$;returnY.reduce((q,z)=>q?.[z],$)}functionVy0($){letY=Object.keys($),q=Y.map((z)=>$[z]);returnPromise.all(q).then((z)=>{letJ={};for(letU=0;U<Y.length;U++)J[Y[U]]=z[U];returnJ})}functionLy0($=10){letq=""Line truncated
`)}var um=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,Cq,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},cI,g8;var xA=e(()=>{F2();y0();cI=a("$ZodError",um),g8=a("$ZodError",um,{Parent:Error})});var gq=($)=>(Y,q,z,J)=>{let U=z?{...z,async:!1}:{async:!1},I=Y._zod.run({value:q,issues:[]},U);if(I instanceof Promise)throw new T5;if(I.issues.length){let Q=new(J?.Err??$)(I.issues.map((K)=>L8(K,U,m4())));throw kW(Q,J?.callee),Q}return I.value},mI,Sq=($)=>async(Y,q,z,J)=>{let U=z?{...z,async:!0}:{async:!0},I=Y._zod.run({value:q,issues:[]},U);if(I instanceof Promise)I=await I;if(I.issues.length){let Q=new(J?.Err??$)(I.issues.map((K)=>L8(K,U,m4())));throw kW(Q,J?.callee),Q}return I.value},lI,yq=($)=>(Y,q,z)=>{let J=z?{...z,async:!1}:{async:!1},U=Y._zod.run({value:q,issues:[]},J);if(U instanceof Promise)throw new T5;return U.issues.length?{success:!1,error:new($??cI)(U.issues.map((I)=>L8(I,J,m4())))}:{success:!0,data:U.value}},xq,kq=($)=>async(Y,q,z)=>{let J=z?{...z,async:!0}:{async:!0},U=Y._zod.run({value:q,issues:[]},J);if(U instanceof Promise)U=await U;return U.issues.length?{success:!1,error:new $(U.issues.map((I)=>L8(I,J,m4())))}:{success:!0,data:U.value}},oI,uW=($)=>(Y,q,z)=>{let J=z?{...z,direction:"backward"}:{direction:"backward"};return gq($)(Y,q,J)},bm,fW=($)=>(Y,q,z)=>{return gq($)(Y,q,z)},im,bW=($)=>async(Y,q,z)=>{let J=z?{...z,direction:"backward"}:{direction:"backward"};return Sq($)(Y,q,J)},nm,iW=($)=>async(Y,q,z)=>{return Sq($)(Y,q,z)},cm,nW=($)=>(Y,q,z)=>{let J=z?{...z,direction:"backward"}:{direction:"backward"};return yq($)(Y,q,J)},pm,cW=($)=>(Y,q,z)=>{return yq($)(Y,q,z)},dm,pW=($)=>async(Y,q,z)=>{let J=z?{...z,direction:"backward"}:{direction:"backward"};return kq($)(Y,q,J)},mm,dW=($)=>async(Y,q,z)=>{return kq($)(Y,q,z)},lm;var kA=e(()=>{F2();xA();y0();mI=gq(g8),lI=Sq(g8),xq=yq(g8),oI=kq(g8),bm=uW(g8),im=fW(g8),nm=bW(g8),cm=iW(g8),pm=nW(g8),dm=cW(g8),mm=pW(g8),lm=dW(g8)});var Y$={};$$(Y$,{xid:()=>iA,uuid7:()=>yy0,uuid6:()=>Sy0,uuid4:()=>gy0,uuid:()=>M2,uppercase:()=>WB,unicodeEmail:()=>om,undefined:()=>HB,ulid:()=>bA,time:()=>zB,string:()=>UB,sha512_hex:()=>qx0,sha512_base64url:()=>Jx0,sha512_base64:()=>zx0,sha384_hex:()=>ey0,sha384_base64url:()=>Yx0,sha384_base64:()=>$x0,sha256_hex:()=>sy0,sha256_base64url:()=>ay0,sha256_base64:()=>ty0,sha1_hex:()=>ly0,sha1_base64url:()=>ry0,sha1_base64:()=>oy0,rfc5322Email:()=>ky0,number:()=>rI,null:()=>GB,nanoid:()=>cA,md5_hex:()=>py0,md5_base64url:()=>my0,md5_base64:()=>dy0,mac:()=>sA,lowercase:()=>ZB,ksuid:()=>nA,ipv6:()=>rA,ipv4:()=>oA,integer:()=>QB,idnEmail:()=>uy0,httpProtocol:()=>$B,html5Email:()=>xy0,hostname:()=>iy0,hex:()=>cy0,guid:()=>dA,extendedDuration:()=>hy0,emoji:()=>lA,email:()=>mA,e164:()=>YB,duration:()=>pA,domain:()=>ny0,datetime:()=>JB,date:()=>qB,cuid2:()=>fA,cuid:()=>uA,cidrv6:()=>aA,cidrv4:()=>tA,browserEmail:()=>fy0,boolean:()=>KB,bigint:()=>IB,base64url:()=>mW,base64:()=>eA});function lA(){return new RegExp(by0,"u")}function sm($){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 zB($){return new RegExp(`^${sm($)}$`)}function JB($){let Y=sm({precision:$.precision}),q=["Z"];if($.local)q.push("");if($.offset)q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let z=`${Y}(?:${q.join("|")})`;return new RegExp(`^${rm}T(?:${z})$`)}function sI($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function tI($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var uA,fA,bA,iA,nA,cA,pA,hy0,dA,M2=($)=>{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})$`)},gy0,Sy0,yy0,mA,xy0,ky0,om,uy0,fy0,by0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",oA,rA,sA=($)=>{letY=O$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},tA,aA,eA,mW,iy0,ny0,$B,YB,rm="(?:(?:\\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])))",qB,UB=($)=>{letY=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${Y}$`)},IB,QB,rI,KB,GB,HB,ZB,WB,cy0,py0,dy0,my0,ly0,oy0,ry0,sy0,ty0,ay0,ey0,$x0,Yx0,qx0,zx0,Jx0;varlW=e(()=>{y0();uA=/^[cC][0-9a-z]{6,}$/,fA=/^[0-9a-z]+$/,bA=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,iA=/^[0-9a-vA-V]{20}$/,nA=/^[A-Za-z0-9]{27}$/,cA=/^[a-zA-Z0-9_-]{21}$/,pA=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?Line truncated
`).filter((U)=>U),z=Math.min(...q.map((U)=>U.length-U.trimStart().length)),J=q.map((U)=>U.slice(z)).map((U)=>" ".repeat(this.indent*2)+U);for(let U of J)this.content.push(U)}compile(){let $=Function,Y=this?.args,z=[...(this?.content??[""]).map((J)=>`${J}`)];return new $(...Y,z.join(`
`))}}var vB;var hB=e(()=>{vB={major:4,minor:4,patch:3}});function $T($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function Vl($){if(!mW.test($))return!1;let Y=$.replace(/[-_]/g,(z)=>z==="-"?"+":"/"),q=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return $T(q)}function Ll($,Y=null){try{let q=$.split(".");if(q.length!==3)return!1;let[z]=q;if(!z)return!1;let J=JSON.parse(atob(z));if("typ"in J&&J?.typ!=="JWT")return!1;if(!J.alg)return!1;if(Y&&(!("alg"in J)||J.alg!==Y))return!1;return!0}catch{return!1}}function $l($,Y,q){if($.issues.length)Y.issues.push(...h8(q,$.issues));Y.value[q]=$.value}function YX($,Y,q,z,J,U){let I=q in z;if($.issues.length){if(J&&U&&!I)return;Y.issues.push(...h8(q,$.issues))}if(!I&&!J){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[q]});return}if($.value===void 0){if(I)Y.value[q]=void 0}else Y.value[q]=$.value}function wl($){let Y=Object.keys($.shape);for(let z of Y)if(!$.shape?.[z]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${z}":expectedaZodschema`);let q=CA($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(q)}}function Fl($,Y,q,z,J,U){let I=[],Q=J.keySet,K=J.catchall._zod,G=K.def.type,H=K.optin==="optional",Z=K.optout==="optional";for(let V in Y){if(V==="__proto__")continue;if(Q.has(V))continue;if(G==="never"){I.push(V);continue}let X=K.run({value:Y[V],issues:[]},z);if(X instanceof Promise)$.push(X.then((L)=>YX(L,q,V,Y,H,Z)));else YX(X,q,V,Y,H,Z)}if(I.length)q.issues.push({code:"unrecognized_keys",keys:I,input:Y,inst:U});if(!$.length)return q;return Promise.all($).then(()=>{return q})}function Yl($,Y,q,z){for(let U of $)if(U.issues.length===0)return Y.value=U.value,Y;let J=$.filter((U)=>!j3(U));if(J.length===1)return Y.value=J[0].value,J[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:q,errors:$.map((U)=>U.issues.map((I)=>L8(I,z,m4())))}),Y}function ql($,Y,q,z){let J=$.filter((U)=>U.issues.length===0);if(J.length===1)return Y.value=J[0].value,Y;if(J.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:q,errors:$.map((U)=>U.issues.map((I)=>L8(I,z,m4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:q,errors:[],inclusive:!1});return Y}function gB($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(E3($)&&E3(Y)){let q=Object.keys(Y),z=Object.keys($).filter((U)=>q.indexOf(U)!==-1),J={...$,...Y};for(let U of z){let I=gB($[U],Y[U]);if(!I.valid)return{valid:!1,mergeErrorPath:[U,...I.mergeErrorPath]};J[U]=I.data}return{valid:!0,data:J}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let q=[];for(let z=0;z<$.length;z++){let J=$[z],U=Y[z],I=gB(J,U);if(!I.valid)return{valid:!1,mergeErrorPath:[z,...I.mergeErrorPath]};q.push(I.data)}return{valid:!0,data:q}}return{valid:!1,mergeErrorPath:[]}}function zl($,Y,q){let z=new Map,J;for(let Q of Y.issues)if(Q.code==="unrecognized_keys"){J??(J=Q);for(let K of Q.keys){if(!z.has(K))z.set(K,{});z.get(K).l=!0}}else $.issues.push(Q);for(let Q of q.issues)if(Q.code==="unrecognized_keys")for(let K of Q.keys){if(!z.has(K))z.set(K,{});z.get(K).r=!0}else $.issues.push(Q);let U=[...z].filter(([,Q])=>Q.l&&Q.r).map(([Q])=>Q);if(U.length&&J)$.issues.push({...J,keys:U});if(j3($))return $;let I=gB(Y.value,q.value);if(!I.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(I.mergeErrorPath)}`);return $.value=I.data,$}function Jl($,Y){for(let q=$.length-1;q>=0;q--)if($[q]._zod[Y]!=="optional")return q+1;return 0}function Ul($,Y,q){if($.issues.length)Y.issues.push(...h8(q,$.issues));Y.value[q]=$.value}function Il($,Y,q,z,J){for(let U=0;U<q.length;U++){let I=$[U],Q=U<z.length;if(I.issues.length){if(!Q&&U>=J){Y.value.length=U;break}Y.issues.push(...h8(U,I.issues))}Y.value[U]=I.value}for(let U=Y.value.length-1;U>=z.length;U--)if(q[U]._zod.optout==="optional"&&Y.value[U]===void 0)Y.value.length=U;else break;return Y}function Ql($,Y,q,z,J,U,I){if($.issues.length)if(bI.has(typeof z))q.issues.push(...h8(z,$.issues));else q.issues.push({code:"invalid_key",origin:"map",input:J,inst:U,issues:$.issues.map((Q)=>L8(Q,I,m4()))});if(Y.issues.length)if(bI.has(typeof z))q.issues.push(...h8(z,Y.issues));else q.issues.push({origin:"map",code:"invalid_element",input:J,inst:U,key:z,issues:Y.issues.map((Q)=>L8(Q,I,m4()))});q.value.set($.value,Y.value)}function Kl($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function Gl($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function Hl($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function Zl($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function aW($,Y,q){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa
Line truncated
`)}X.write("payload.value = newResult;"),X.write("return payload;");let D=X.compile();return(P,A)=>D(W,P,A)},Y,J=W2,Q=!H2.jitless,H=Q&&XP.value,G=I.catchall,Z;$._zod.parse=(W,X)=>{Z??(Z=q.value);let w=W.value;if(!J(w))return W.issues.push({expected:"object",code:"invalid_type",input:w,inst:$}),W;if(Q&&H&&X?.async===!1&&X.jitless!==!0){if(!Y)Y=U(I.shape);if(W=Y(W,X),!G)return W;return im([],w,W,X,Z,$)}return z(W,X)}});nJ=t("$ZodUnion",($,I)=>{m0.init($,I),J1($._zod,"optin",()=>I.options.some((q)=>q._zod.optin==="optional")?"optional":void 0),J1($._zod,"optout",()=>I.options.some((q)=>q._zod.optout==="optional")?"optional":void 0),J1($._zod,"values",()=>{if(I.options.every((q)=>q._zod.values))return new Set(I.options.flatMap((q)=>Array.from(q._zod.values)));return}),J1($._zod,"pattern",()=>{if(I.options.every((q)=>q._zod.pattern)){let q=I.options.map((U)=>U._zod.pattern);return new RegExp(`^(${q.map((U)=>CJ(U.source)).join("|")})$`)}return});let z=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(q,U)=>{if(z)return z(q,U);let Y=!1,J=[];for(let Q of I.options){let K=Q._zod.run({value:q.value,issues:[]},U);if(K instanceof Promise)J.push(K),Y=!0;else{if(K.issues.length===0)return K;J.push(K)}}if(!Y)return Tm(J,q,$,U);return Promise.all(J).then((Q)=>{return Tm(Q,q,$,U)})}});UT=t("$ZodXor",($,I)=>{nJ.init($,I),I.inclusive=!1;let z=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(q,U)=>{if(z)return z(q,U);let Y=!1,J=[];for(let Q of I.options){let K=Q._zod.run({value:q.value,issues:[]},U);if(K instanceof Promise)J.push(K),Y=!0;else J.push(K)}if(!Y)return Em(J,q,$,U);return Promise.all(J).then((Q)=>{return Em(Q,q,$,U)})}}),YT=t("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,nJ.init($,I);let z=$._zod.parse;J1($._zod,"propValues",()=>{let U={};for(let Y of I.options){let J=Y._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${I.options.indexOf(Y)}"`);for(let[Q,K]of Object.entries(J)){if(!U[Q])U[Q]=new Set;for(let H of K)U[Q].add(H)}}return U});let q=Tz(()=>{let U=I.options,Y=new Map;for(let J of U){let Q=J._zod.propValues?.[I.discriminator];if(!Q||Q.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${I.options.indexOf(J)}"`);for(let K of Q){if(Y.has(K))throw Error(`Duplicatediscriminatorvalue"${String(K)}"`);Y.set(K,J)}}return Y});$._zod.parse=(U,Y)=>{let J=U.value;if(!W2(J))return U.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),U;let Q=q.value.get(J?.[I.discriminator]);if(Q)return Q._zod.run(U,Y);if(I.unionFallback||Y.direction==="backward")return z(U,Y);return U.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(q.value.keys()),input:J,path:[I.discriminator],inst:$}),U}}),JT=t("$ZodIntersection",($,I)=>{m0.init($,I),$._zod.parse=(z,q)=>{let U=z.value,Y=I.left._zod.run({value:U,issues:[]},q),J=I.right._zod.run({value:U,issues:[]},q);if(Y instanceof Promise||J instanceof Promise)return Promise.all([Y,J]).then(([K,H])=>{return jm(z,K,H)});return jm(z,Y,J)}});lW=t("$ZodTuple",($,I)=>{m0.init($,I);let z=I.items;$._zod.parse=(q,U)=>{let Y=q.value;if(!Array.isArray(Y))return q.issues.push({input:Y,inst:$,expected:"tuple",code:"invalid_type"}),q;q.value=[];let J=[],Q=Cm(z,"optin"),K=Cm(z,"optout");if(!I.rest){if(Y.length<Q)return q.issues.push({code:"too_small",minimum:Q,inclusive:!0,input:Y,inst:$,origin:"array"}),q;if(Y.length>z.length)q.issues.push({code:"too_big",maximum:z.length,inclusive:!0,input:Y,inst:$,origin:"array"})}let H=Array(z.length);for(let G=0;G<z.length;G++){let Z=z[G]._zod.run({value:Y[G],issues:[]},U);if(Z instanceof Promise)J.push(Z.then((W)=>{H[G]=W}));else H[G]=Z}if(I.rest){let G=z.length-1,Z=Y.slice(z.length);for(let W of Z){G++;let X=I.rest._zod.run({value:W,issues:[]},U);if(X instanceof Promise)J.push(X.then((w)=>_m(w,q,G)));else _m(X,q,G)}}if(J.length)return Promise.all(J).then(()=>Rm(H,q,z,Y,K));return Rm(H,q,z,Y,K)}});QT=t("$ZodRecord",($,I)=>{m0.init($,I),$._zod.parse=(z,q)=>{let U=z.value;if(!F3(U))return z.issues.push({expected:"record",code:"invalid_type",input:U,inst:$}),z;let Y=[],J=I.keyType._zod.values;if(J){z.value={};let Q=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){Q.add(typeof H==="number"?H.toString():H);let G=I.keyType._zod.run({value:H,issues:[]},q);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(G.issues.length){z.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((X)=>K8(X,q,f4())),input:H,path:[H],inst:$});continue}let Z=G.value,W=I.valueType._zod.run({value:U[H],issues:[]},q);if(W instanceof Promise)Y.push(W.then((X)=>{if(X.issues.length)z.issues.push(...E8(H,X.issues));z.value[Z]=X.value}));else{if(W.issues.length)z.issues.push(...E8(H,W.issues));z.value[Z]=W.value}}let K;for(let H in U)if(!Q.has(H))K=K??[],K.push(H);if(K&&K.length>0)z.issues.push({code:"unrecognize
Line truncated
`)}X.write("payload.value = newResult;"),X.write("return payload;");let P=X.compile();return(B,A)=>P(V,B,A)},U,I=O2,Q=!L2.jitless,G=Q&&jA.value,H=Y.catchall,Z;$._zod.parse=(V,X)=>{Z??(Z=z.value);let L=V.value;if(!I(L))return V.issues.push({expected:"object",code:"invalid_type",input:L,inst:$}),V;if(Q&&G&&X?.async===!1&&X.jitless!==!0){if(!U)U=J(Y.shape);if(V=U(V,X),!H)return V;return Fl([],L,V,X,Z,$)}return q(V,X)}});eI=a("$ZodUnion",($,Y)=>{s0.init($,Y),G1($._zod,"optin",()=>Y.options.some((z)=>z._zod.optin==="optional")?"optional":void 0),G1($._zod,"optout",()=>Y.options.some((z)=>z._zod.optout==="optional")?"optional":void 0),G1($._zod,"values",()=>{if(Y.options.every((z)=>z._zod.values))return new Set(Y.options.flatMap((z)=>Array.from(z._zod.values)));return}),G1($._zod,"pattern",()=>{if(Y.options.every((z)=>z._zod.pattern)){let z=Y.options.map((J)=>J._zod.pattern);return new RegExp(`^(${z.map((J)=>fI(J.source)).join("|")})$`)}return});let q=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,J)=>{if(q)return q(z,J);let U=!1,I=[];for(let Q of Y.options){let K=Q._zod.run({value:z.value,issues:[]},J);if(K instanceof Promise)I.push(K),U=!0;else{if(K.issues.length===0)return K;I.push(K)}}if(!U)return Yl(I,z,$,J);return Promise.all(I).then((Q)=>{return Yl(Q,z,$,J)})}});OT=a("$ZodXor",($,Y)=>{eI.init($,Y),Y.inclusive=!1;let q=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,J)=>{if(q)return q(z,J);let U=!1,I=[];for(let Q of Y.options){let K=Q._zod.run({value:z.value,issues:[]},J);if(K instanceof Promise)I.push(K),U=!0;else I.push(K)}if(!U)return ql(I,z,$,J);return Promise.all(I).then((Q)=>{return ql(Q,z,$,J)})}}),MT=a("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,eI.init($,Y);let q=$._zod.parse;G1($._zod,"propValues",()=>{let J={};for(let U of Y.options){let I=U._zod.propValues;if(!I||Object.keys(I).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(U)}"`);for(let[Q,K]of Object.entries(I)){if(!J[Q])J[Q]=new Set;for(let G of K)J[Q].add(G)}}return J});let z=vq(()=>{let J=Y.options,U=new Map;for(let I of J){let Q=I._zod.propValues?.[Y.discriminator];if(!Q||Q.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(I)}"`);for(let K of Q){if(U.has(K))throw Error(`Duplicatediscriminatorvalue"${String(K)}"`);U.set(K,I)}}return U});$._zod.parse=(J,U)=>{let I=J.value;if(!O2(I))return J.issues.push({code:"invalid_type",expected:"object",input:I,inst:$}),J;let Q=z.value.get(I?.[Y.discriminator]);if(Q)return Q._zod.run(J,U);if(Y.unionFallback||U.direction==="backward")return q(J,U);return J.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(z.value.keys()),input:I,path:[Y.discriminator],inst:$}),J}}),NT=a("$ZodIntersection",($,Y)=>{s0.init($,Y),$._zod.parse=(q,z)=>{let J=q.value,U=Y.left._zod.run({value:J,issues:[]},z),I=Y.right._zod.run({value:J,issues:[]},z);if(U instanceof Promise||I instanceof Promise)return Promise.all([U,I]).then(([K,G])=>{return zl(q,K,G)});return zl(q,U,I)}});JX=a("$ZodTuple",($,Y)=>{s0.init($,Y);let q=Y.items;$._zod.parse=(z,J)=>{let U=z.value;if(!Array.isArray(U))return z.issues.push({input:U,inst:$,expected:"tuple",code:"invalid_type"}),z;z.value=[];let I=[],Q=Jl(q,"optin"),K=Jl(q,"optout");if(!Y.rest){if(U.length<Q)return z.issues.push({code:"too_small",minimum:Q,inclusive:!0,input:U,inst:$,origin:"array"}),z;if(U.length>q.length)z.issues.push({code:"too_big",maximum:q.length,inclusive:!0,input:U,inst:$,origin:"array"})}let G=Array(q.length);for(let H=0;H<q.length;H++){let Z=q[H]._zod.run({value:U[H],issues:[]},J);if(Z instanceof Promise)I.push(Z.then((V)=>{G[H]=V}));else G[H]=Z}if(Y.rest){let H=q.length-1,Z=U.slice(q.length);for(let V of Z){H++;let X=Y.rest._zod.run({value:V,issues:[]},J);if(X instanceof Promise)I.push(X.then((L)=>Ul(L,z,H)));else Ul(X,z,H)}}if(I.length)return Promise.all(I).then(()=>Il(G,z,q,U,K));return Il(G,z,q,U,K)}});DT=a("$ZodRecord",($,Y)=>{s0.init($,Y),$._zod.parse=(q,z)=>{let J=q.value;if(!E3(J))return q.issues.push({expected:"record",code:"invalid_type",input:J,inst:$}),q;let U=[],I=Y.keyType._zod.values;if(I){q.value={};let Q=new Set;for(let G of I)if(typeof G==="string"||typeof G==="number"||typeof G==="symbol"){Q.add(typeof G==="number"?G.toString():G);let H=Y.keyType._zod.run({value:G,issues:[]},z);if(H instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(H.issues.length){q.issues.push({code:"invalid_key",origin:"record",issues:H.issues.map((X)=>L8(X,z,m4())),input:G,path:[G],inst:$});continue}let Z=H.value,V=Y.valueType._zod.run({value:J[G],issues:[]},z);if(V instanceof Promise)U.push(V.then((X)=>{if(X.issues.length)q.issues.push(...h8(G,X.issues));q.value[Z]=X.value}));else{if(V.issues.length)q.issues.push(...h8(G,V.issues));q.value[Z]=V.value}}let K;for(let G in J)if(!Q.has(G))K=K??[],K.push(G);if(K&&K.length>0)q.issues.push({code:"unrecognize
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letJof$.seen.entries()){letQ=J[1];if(I===J[0]){Y(J);continue}if($.external){letH=$.external.registry.get(J[0])?.id;if(I!==J[0]&&H){Y(J);continue}}if($.metadataRegistry.get(J[0])?.id){Y(J);continue}if(Q.cycle){Y(J);continue}if(Q.count>1){if($.reused==="ref"){Y(J);continue}}}}functionB3($,I){letz=$.seen.get(I);if(!z)throwError("Unprocessed schema. This is a bug in Zod.");letq=(Q)=>{letK=$.seen.get(Q);if(K.ref===null)return;letH=K.def??K.schema,G={...H},Z=K.ref;if(K.ref=null,Z){q(Z);letX=$.seen.get(Z),w=X.schema;if(w.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(w);elseObject.assign(H,w);if(Object.assign(H,G),Q._zod.parent===Z)for(letOinH){if(O==="$ref"||O==="allOf")continue;if(!(OinG))deleteH[O]}if(w.$ref&&X.def)for(letOinH){if(O==="$ref"||O==="allOf")continue;if(OinX.def&&JSON.stringify(H[O])===JSON.stringify(X.def[O]))deleteH[O]}}letW=Q._zod.parent;if(W&&W!==Z){q(W);letX=$.seen.get(W);if(X?.schema.$ref){if(H.$ref=X.schema.$ref,X.def)for(letwinH){if(w==="$ref"||w==="allOf")continue;if(winX.def&&JSON.stringify(H[w])===JSON.stringify(X.def[w]))deleteH[w]}}}$.override({zodSchema:Q,jsonSchema:H,path:K.path??[]})};for(letQof[...$.seen.entries()].reverse())q(Q[0]);letU={};if($.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")U.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")U.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letQ=$.external.registry.get(I)?.id;if(!Q)throwError("Schema is missing an `id` property");U.$id=$.external.uri(Q)}Object.assign(U,z.def??z.schema);letY=$.metadataRegistry.get(I)?.id;if(Y!==void0&&U.id===Y)deleteU.id;letJ=$.external?.defs??{};for(letQof$.seen.entries()){letK=Q[1];if(K.def&&K.defId){if(K.def.id===K.defId)deleteK.def.id;J[K.defId]=K.def}}if($.external);elseif(Object.keys(J).length>0)if($.target==="draft-2020-12")U.$defs=J;elseU.definitions=J;try{letQ=JSON.parse(JSON.stringify(U));returnObject.defineProperty(Q,"~standard",{value:{...I["~standard"],jsonSchema:{input:lz(I,"input",$.processors),output:lz(I,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throwError("Error converting schema to JSON.")}}functionG8($,I){letz=I??{seen:newSet};if(z.seen.has($))return!1;z.seen.add($);letq=$._zod.def;if(q.type==="transform")return!0;if(q.type==="array")returnG8(q.element,z);if(q.type==="set")returnG8(q.valueType,z);if(q.type==="lazy")returnG8(q.getter(),z);if(q.type==="promise"||q.type==="optional"||q.type==="nonoptional"||q.type==="nullable"||q.type==="readonly"||q.type==="default"||q.type==="prefault")returnG8(q.innerType,z);if(q.type==="intersection")returnG8(q.left,z)||G8(q.right,z);if(q.type==="record"||q.type==="map")returnG8(q.keyType,z)||G8(q.valueType,z);if(q.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnG8(q.in,z)||G8(q.out,z)}if(q.type==="object"){for(letUinq.shape)if(G8(q.shape[U],z))return!0;return!1}if(q.type==="union"){for(letUofq.options)if(G8(U,z))return!0;return!1}if(q.type==="tuple"){for(letUofq.items)if(G8(U,z))return!0;if(q.rest&&G8(q.rest,z))return!0;return!1}return!1}varOj=($,I={})=>(z)=>{letq=A3({...z,processors:I});returnc1($,q),P3(q,$),B3(q,$)},lz=($,I,z={})=>(q)=>{let{libraryOptions:U,target:Y}=q??{},J=A3({...U??{},target:Y,io:I,processors:z});returnc1($,J),P3(J,$),B3(J,$)};varaJ=e(()=>{rJ()});functionTX($,I){if("_idmap"in$){letq=$,U=A3({...I,processors:AX}),Y={};for(letKofq._idmap.entries()){let[H,G]=K;c1(G,U)}letJ={},Q={registry:q,uri:I?.uri,defs:Y};U.external=Q;for(letKofq._idmap.entries()){let[H,G]=K;P3(U,G),J[H]=B3(U,G)}if(Object.keys(Y).length>0){letK=U.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[K]:Y}}return{schemas:J}}letz=A3({...I,processors:AX});returnc1($,z),P3(z,$),B3(z,$)}varRx0,Fj=($,I,z,q)=>{letU=z;U.type="string";let{minimum:Y,maximum:J,format:Q,patterns:K,contentEncoding:H}=$._zod.bag;if(typeofY==="number")U.minLength=Y;if(typeofJ==="number")U.maxLength=J;if(Q){if(U.format=Rx0[Q]??Q,U.format==="")deleteU.format;if(Q==="time")deleteU.format}if(H)U.contentEncoding=H;if(K&&K.size>0){letG=[...K];if(G.length===1)U.pattern=G[0].source;elseif(G.length>1)U.allOf=[...G.map((Z)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:Z.source}))]}},Mj=($,I,z,q)=>{letU=z,{minimum:Y,maximum:J,format:Q,multipleOf:K,exclusiveMaximum:H,exclusiveMinimum:G}=$._zod.bag;if(typeofQ==="string"&&Q.includes("int"))U.type="integer";elseU.type="number";letZ=typeofG==="number"&&G>=(Y??Number.NEGATIVE_INFINITY),W=typeofH==="number"&&H<=(J??Number.POSITIVE_INFINITY),X=I.target==="draft-04"||I.target==="openapi-3.0";if(Z)if(X)U.minimum=G,U.exclusiveMinimum=!0;elseU.exclusiveMinimuLine truncated
`)}openNode($,I){let z=this.tos,q=this._xml;if(z&&this.open)q.push(">");this._stack.push($),q.push("<"),q.push($),pg(q,I),this.leaf=!0,this.open=!0}addAttribute($,I){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(I!==void 0)D70(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");pg(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(N70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),I=this._xml;if(this.leaf)I.push("/>");else I.push("</"),I.push($),I.push(">");this.open=!1,this.leaf=!1}leafNode($,I,z){if(this.openNode($,I),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("")}}dg.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};A70.exports=dg});var mg=M((t61)=>{var P70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function s61($){if(typeof $==="string")return $;if(P70)return P70.decode($);return $.toString()}t61.bufferToString=s61});var C70=M((T70)=>{Object.defineProperty(T70,"__esModule",{value:!0});T70.CHAR=`
`,$=this.i;break;case O$1:{let{entityReturnState:z}=this,q=this.entity+I.slice($,this.prevI);this.state=z;let U;if(q==="")this.fail("empty entity name."),U="&;";else U=this.parseEntity(q),this.entity="";if(z!==L8||this.textHandler!==void 0)this.text+=U;break $}case B4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(ZH($))this.state=W$1,this.unget(),this.xmlDeclPossible=!1;else switch($){case GO:this.state=w$1,this.xmlDeclPossible=!1;break;case t70:this.state=z$1,this.openWakaBang="",this.xmlDeclPossible=!1;break;case x6:this.state=Q$1;break;default:this.fail("disallowed character in tag name"),this.state=L8,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=zS,this.openWakaBang="";break;case"--":this.state=IS,this.openWakaBang="";break;case"DOCTYPE":if(this.state=ag,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(HO))this.state=q$1}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===HO)this.state=U$1,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=IS}sCommentEnded(){let $=this.getCodeNorm();if($!==G6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=IS;else this.state=L8}sCData(){if(this.captureToChar(HU))this.state=Y$1}sCDataEnding(){let $=this.getCodeNorm();if($===HU)this.state=J$1;else this.text+=`]${String.fromCodePoint($)}`,this.state=zS}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case G6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=L8;break}case HU:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=zS}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=p70;else if($===x6||u8($))this.fail("processing instruction without a target."),this.state=$===x6?KO:qS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=p70}sPIRest(){let{chunk:$,i:I}=this;while(!0){let z=this.getCodeNorm();if(z===B4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(z)){this.piTarget+=$.slice(I,this.prevI);let q=z===x6;if(q||u8(z))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=q?o2:d70}else this.state=q?KO:qS;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($===x6)this.state=KO;else if(!u8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(x6))this.state=KO}sPIEnding(){var $;let I=this.getCodeNorm();if(I===G6){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=L8}else if(I===x6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=qS;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===x6){this.state=o2;return}if($!==B4)this.state=K$1,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(N$1);if($===x6){this.state=o2,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(u8($)||$===KU))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=$===KU?m70:H$1}sXMLDeclEq(){let $=this.getCodeNorm();if($===x6){this.state=o2,this.fail("XML declaration is incomplete.");return}if(u8($))return;if($!==KU)this.fail("value required.");this.state=m70}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===x6){this.state=o2,this.fail("XML declaration is incomplete.");return}if(u8($))return;if(!ZO($))this.fail("value must be quoted."),this.q=s70;else this.q=$;this.state=G$1}sXMLDeclValue(){let $=this.captureTo([this.q,x6]);if($===x6){this.state=o2,this.text="",this.fail("XML declaration is incomplete.");return}if($===B4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let z=I;if(this.xmlDecl.version=z,!/^1\.[0-9]+$/.test(z))this.fail("ver
Line truncated
`;$=this.i;break;case B4:if(z!==void 0)this.text+=I.slice($);break $;default:if(!u8(U))q=!0}}if(!q)return;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}pushAttribNS($,I){var z;let{prefix:q,local:U}=this.qname($),Y={name:$,prefix:q,local:U,value:I};if(this.attribList.push(Y),(z=this.attributeHandler)===null||z===void 0||z.call(this,Y),q==="xmlns"){let J=I.trim();if(this.currentXMLVersion==="1.0"&&J==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[U]=J,HS(this,U,J)}else if($==="xmlns"){let J=I.trim();this.topNS[""]=J,HS(this,"",J)}}pushAttribPlain($,I){var z;let q={name:$,value:I};this.attribList.push(q),(z=this.attributeHandler)===null||z===void 0||z.call(this,q)}end(){var $,I;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:z}=this;while(z.length>0){let U=z.pop();this.fail(`unclosedtag:${U.name}`)}if(this.state!==c70&&this.state!==L8)this.fail("unexpected end.");let{text:q}=this;if(q.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,q),this.text="";return this._closed=!0,(I=this.endHandler)===null||I===void 0||I.call(this),this._init(),this}resolve($){var I,z;let q=this.topNS[$];if(q!==void 0)return q;let{tags:U}=this;for(let Y=U.length-1;Y>=0;Y--)if(q=U[Y].ns[$],q!==void 0)return q;if(q=this.ns[$],q!==void 0)return q;return(z=(I=this.opt).resolvePrefix)===null||z===void 0?void 0:z.call(I,$)}qname($){let I=$.indexOf(":");if(I===-1)return{prefix:"",local:$};let z=$.slice(I+1),q=$.slice(0,I);if(q===""||z===""||z.includes(":"))this.fail(`malformedname:${$}.`);return{prefix:q,local:z}}processAttribsNS(){var $;let{attribList:I}=this,z=this.tag;{let{prefix:Y,local:J}=this.qname(z.name);z.prefix=Y,z.local=J;let Q=z.uri=($=this.resolve(Y))!==null&&$!==void 0?$:"";if(Y!==""){if(Y==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(Q==="")this.fail(`unboundnamespaceprefix:${JSON.stringify(Y)}.`),z.uri=Y}}if(I.length===0)return;let{attributes:q}=z,U=new Set;for(let Y of I){let{name:J,prefix:Q,local:K}=Y,H,G;if(Q==="")H=J==="xmlns"?GU:"",G=J;else{if(H=this.resolve(Q),H===void 0)this.fail(`unboundnamespaceprefix:${JSON.stringify(Q)}.`),H=Q;G=`{${H}}${K}`}if(U.has(G))this.fail(`duplicateattribute:${G}.`);U.add(G),Y.uri=H,q[J]=Y}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,I=this.tag.attributes;for(let{name:z,value:q}of $){if(I[z]!==void 0)this.fail(`duplicateattribute:${z}.`);I[z]=q}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:I}=this,z=this.tag;z.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,z),I.push(z),this.state=L8,this.name=""}openSelfClosingTag(){var $,I,z;this.processAttribs();let{tags:q}=this,U=this.tag;if(U.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,U),(I=this.closeTagHandler)===null||I===void 0||I.call(this,U),(this.tag=(z=q[q.length-1])!==null&&z!==void 0?z:null)===null)this.closedRoot=!0;this.state=L8,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=L8,this.name="",I===""){this.fail("weird empty close tag."),this.text+="</>";return}let z=this.closeTagHandler,q=$.length;while(q-- >0){let U=this.tag=$.pop();if(this.topNS=U.ns,z===null||z===void 0||z(U),U.name===I)break;this.fail("unexpected close tag.")}if(q===0)this.closedRoot=!0;else if(q<0)this.fail(`unmatchedclosingtag:${I}.`),this.text+=`</${I}>`}parseEntity($){if($[0]!=="#"){let z=this.ENTITIES[$];if(z!==void 0)return z;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let I=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))I=parseInt($.slice(2),16);elseif(/^#[0-9]+$/.test($))I=parseInt($.slice(1),10);if(!this.isChar(I))returnthis.fail("malformed character entity."),`&${$};`;returnString.fromCodePoint(I)}}K20.SaxesParser=Q20});varVH=M((le1,G20)=>{var{SaxesParser:j$1}=H20(),{PassThrough:C$1}=w8(),{bufferToString:_$1}=mg();G20.exports=asyncfunction*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(newC$1);letI=newj$1,z;I.on("error",(U)=>{z=U});letq=[];I.on("opentag",(U)=>q.push({eventType:"opentag",value:U})),I.on("text",(U)=>q.push({eventType:"text",value:U})),I.on("closetag",(U)=>q.push({eventType:"closetag",value:U}));forawait(letUof$){if(I.write(_$1(U)),z)throwz;yieldq,q=[]}}});varF0=M((oe1,Z20)=>{varR$1=VH(),v$1=y6();classWU{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($instanceofWU)$.reset();elseif($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}asyncparse($){forawait(letIof$)for(let{eventType:z,value:q}ofI)if(z==="opentag")this.parseOpen(q);elseif(z==="text")this.parseText(q);elseif(z==="closetag"){if(!this.parseClose(q.name))returnthLine truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letIof$.seen.entries()){letQ=I[1];if(Y===I[0]){U(I);continue}if($.external){letG=$.external.registry.get(I[0])?.id;if(Y!==I[0]&&G){U(I);continue}}if($.metadataRegistry.get(I[0])?.id){U(I);continue}if(Q.cycle){U(I);continue}if(Q.count>1){if($.reused==="ref"){U(I);continue}}}}functionh3($,Y){letq=$.seen.get(Y);if(!q)throwError("Unprocessed schema. This is a bug in Zod.");letz=(Q)=>{letK=$.seen.get(Q);if(K.ref===null)return;letG=K.def??K.schema,H={...G},Z=K.ref;if(K.ref=null,Z){z(Z);letX=$.seen.get(Z),L=X.schema;if(L.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))G.allOf=G.allOf??[],G.allOf.push(L);elseObject.assign(G,L);if(Object.assign(G,H),Q._zod.parent===Z)for(letFinG){if(F==="$ref"||F==="allOf")continue;if(!(FinH))deleteG[F]}if(L.$ref&&X.def)for(letFinG){if(F==="$ref"||F==="allOf")continue;if(FinX.def&&JSON.stringify(G[F])===JSON.stringify(X.def[F]))deleteG[F]}}letV=Q._zod.parent;if(V&&V!==Z){z(V);letX=$.seen.get(V);if(X?.schema.$ref){if(G.$ref=X.schema.$ref,X.def)for(letLinG){if(L==="$ref"||L==="allOf")continue;if(LinX.def&&JSON.stringify(G[L])===JSON.stringify(X.def[L]))deleteG[L]}}}$.override({zodSchema:Q,jsonSchema:G,path:K.path??[]})};for(letQof[...$.seen.entries()].reverse())z(Q[0]);letJ={};if($.target==="draft-2020-12")J.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")J.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")J.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letQ=$.external.registry.get(Y)?.id;if(!Q)throwError("Schema is missing an `id` property");J.$id=$.external.uri(Q)}Object.assign(J,q.def??q.schema);letU=$.metadataRegistry.get(Y)?.id;if(U!==void0&&J.id===U)deleteJ.id;letI=$.external?.defs??{};for(letQof$.seen.entries()){letK=Q[1];if(K.def&&K.defId){if(K.def.id===K.defId)deleteK.def.id;I[K.defId]=K.def}}if($.external);elseif(Object.keys(I).length>0)if($.target==="draft-2020-12")J.$defs=I;elseJ.definitions=I;try{letQ=JSON.parse(JSON.stringify(J));returnObject.defineProperty(Q,"~standard",{value:{...Y["~standard"],jsonSchema:{input:eq(Y,"input",$.processors),output:eq(Y,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throwError("Error converting schema to JSON.")}}functionF8($,Y){letq=Y??{seen:newSet};if(q.seen.has($))return!1;q.seen.add($);letz=$._zod.def;if(z.type==="transform")return!0;if(z.type==="array")returnF8(z.element,q);if(z.type==="set")returnF8(z.valueType,q);if(z.type==="lazy")returnF8(z.getter(),q);if(z.type==="promise"||z.type==="optional"||z.type==="nonoptional"||z.type==="nullable"||z.type==="readonly"||z.type==="default"||z.type==="prefault")returnF8(z.innerType,q);if(z.type==="intersection")returnF8(z.left,q)||F8(z.right,q);if(z.type==="record"||z.type==="map")returnF8(z.keyType,q)||F8(z.valueType,q);if(z.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnF8(z.in,q)||F8(z.out,q)}if(z.type==="object"){for(letJinz.shape)if(F8(z.shape[J],q))return!0;return!1}if(z.type==="union"){for(letJofz.options)if(F8(J,q))return!0;return!1}if(z.type==="tuple"){for(letJofz.items)if(F8(J,q))return!0;if(z.rest&&F8(z.rest,q))return!0;return!1}return!1}varvj=($,Y={})=>(q)=>{letz=C3({...q,processors:Y});returns1($,z),v3(z,$),h3(z,$)},eq=($,Y,q={})=>(z)=>{let{libraryOptions:J,target:U}=z??{},I=C3({...J??{},target:U,io:Y,processors:q});returns1($,I),v3(I,$),h3(I,$)};varGQ=e(()=>{IQ()});functionxX($,Y){if("_idmap"in$){letz=$,J=C3({...Y,processors:gX}),U={};for(letKofz._idmap.entries()){let[G,H]=K;s1(H,J)}letI={},Q={registry:z,uri:Y?.uri,defs:U};J.external=Q;for(letKofz._idmap.entries()){let[G,H]=K;v3(J,H),I[G]=h3(J,H)}if(Object.keys(U).length>0){letK=J.target==="draft-2020-12"?"$defs":"definitions";I.__shared={[K]:U}}return{schemas:I}}letq=C3({...Y,processors:gX});returns1($,q),v3(q,$),h3(q,$)}varEk0,hj=($,Y,q,z)=>{letJ=q;J.type="string";let{minimum:U,maximum:I,format:Q,patterns:K,contentEncoding:G}=$._zod.bag;if(typeofU==="number")J.minLength=U;if(typeofI==="number")J.maxLength=I;if(Q){if(J.format=Ek0[Q]??Q,J.format==="")deleteJ.format;if(Q==="time")deleteJ.format}if(G)J.contentEncoding=G;if(K&&K.size>0){letH=[...K];if(H.length===1)J.pattern=H[0].source;elseif(H.length>1)J.allOf=[...H.map((Z)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:Z.source}))]}},gj=($,Y,q,z)=>{letJ=q,{minimum:U,maximum:I,format:Q,multipleOf:K,exclusiveMaximum:G,exclusiveMinimum:H}=$._zod.bag;if(typeofQ==="string"&&Q.includes("int"))J.type="integer";elseJ.type="number";letZ=typeofH==="number"&&H>=(U??Number.NEGATIVE_INFINITY),V=typeofG==="number"&&G<=(I??Number.POSITIVE_INFINITY),X=Y.target==="draft-04"||Y.target==="openapi-3.0";if(Z)if(X)J.minimum=H,J.exclusiveMinimum=!0;elseJ.exclusiveMinimuLine truncated
deps:${q}}`};var ed0={keyword:"dependencies",type:"object",schemaType:"object",error:_e.error,code($){let[Y,q]=$m0($);Ee($,Y),je($,q)}};function $m0({schema:$}){let Y={},q={};for(let z in $){if(z==="__proto__")continue;let J=Array.isArray($[z])?Y:q;J[z]=$[z]}return[Y,q]}function Ee($,Y=$.schema){let{gen:q,data:z,it:J}=$;if(Object.keys(Y).length===0)return;let U=q.let("missing");for(let I in Y){let Q=Y[I];if(Q.length===0)continue;let K=(0,UK.propertyInData)(q,z,I,J.opts.ownProperties);if($.setParams({property:I,depsCount:Q.length,deps:Q.join(", ")}),J.allErrors)q.if(K,()=>{for(let G of Q)(0,UK.checkReportMissingProp)($,G)});else q.if(gC._`${K}&&(${(0,UK.checkMissingProp)($,Q,U)})`),(0,UK.reportMissingProp)($,U),q.else()}}_e.validatePropertyDeps=Ee;function je($,Y=$.schema){let{gen:q,data:z,keyword:J,it:U}=$,I=q.name("valid");for(let Q in Y){if((0,ad0.alwaysValidSchema)(U,Y[Q]))continue;q.if((0,UK.propertyInData)(q,z,Q,U.opts.ownProperties),()=>{let K=$.subschema({keyword:J,schemaProp:Q},I);$.mergeValidEvaluated(K,I)},()=>q.var(I,!0)),$.ok(I)}}_e.validateSchemaDeps=je;_e.default=ed0});var Se=M((ge)=>{Object.defineProperty(ge,"__esModule",{value:!0});var he=I1(),zm0=j1(),Jm0={message:"property name must be valid",params:({params:$})=>he._`{propertyName:${$.propertyName}}`},Um0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Jm0,code($){let{gen:Y,schema:q,data:z,it:J}=$;if((0,zm0.alwaysValidSchema)(J,q))return;let U=Y.name("valid");Y.forIn("key",z,(I)=>{$.setParams({propertyName:I}),$.subschema({keyword:"propertyNames",data:I,dataTypes:["string"],propertyName:I,compositeRule:!0},U),Y.if((0,he.not)(U),()=>{if($.error(!0),!J.allErrors)Y.break()})}),$.ok(U)}};ge.default=Um0});var SC=M((ye)=>{Object.defineProperty(ye,"__esModule",{value:!0});var JL=D$(),q5=I1(),Qm0=A9(),UL=j1(),Km0={message:"must NOT have additional properties",params:({params:$})=>q5._`{additionalProperty:${$.additionalProperty}}`},Gm0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Km0,code($){let{gen:Y,schema:q,parentSchema:z,data:J,errsCount:U,it:I}=$;if(!U)throw Error("ajv implementation error");let{allErrors:Q,opts:K}=I;if(I.props=!0,K.removeAdditional!=="all"&&(0,UL.alwaysValidSchema)(I,q))return;let G=(0,JL.allSchemaProperties)(z.properties),H=(0,JL.allSchemaProperties)(z.patternProperties);Z(),$.ok(q5._`${U}===${Qm0.default.errors}`);function Z(){Y.forIn("key",J,(F)=>{if(!G.length&&!H.length)L(F);else Y.if(V(F),()=>L(F))})}function V(F){let O;if(G.length>8){let P=(0,UL.schemaRefOrVal)(I,z.properties,"properties");O=(0,JL.isOwnProperty)(Y,P,F)}else if(G.length)O=(0,q5.or)(...G.map((P)=>q5._`${F}===${P}`));else O=q5.nil;if(H.length)O=(0,q5.or)(O,...H.map((P)=>q5._`${(0,JL.usePattern)($,P)}.test(${F})`));return(0,q5.not)(O)}function X(F){Y.code(q5._`delete${J}[${F}]`)}function L(F){if(K.removeAdditional==="all"||K.removeAdditional&&q===!1){X(F);return}if(q===!1){if($.setParams({additionalProperty:F}),$.error(),!Q)Y.break();return}if(typeof q=="object"&&!(0,UL.alwaysValidSchema)(I,q)){let O=Y.name("valid");if(K.removeAdditional==="failing")w(F,O,!1),Y.if((0,q5.not)(O),()=>{$.reset(),X(F)});else if(w(F,O),!Q)Y.if((0,q5.not)(O),()=>Y.break())}}function w(F,O,P){let B={keyword:"additionalProperties",dataProp:F,dataPropType:UL.Type.Str};if(P===!1)Object.assign(B,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(B,O)}}};ye.default=Gm0});var fe=M((ue)=>{Object.defineProperty(ue,"__esModule",{value:!0});var Zm0=lQ(),xe=D$(),yC=j1(),ke=SC(),Wm0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:Y,schema:q,parentSchema:z,data:J,it:U}=$;if(U.opts.removeAdditional==="all"&&z.additionalProperties===void 0)ke.default.code(new Zm0.KeywordCxt(U,ke.default,"additionalProperties"));let I=(0,xe.allSchemaProperties)(q);for(let Z of I)U.definedProperties.add(Z);if(U.opts.unevaluated&&I.length&&U.props!==!0)U.props=yC.mergeEvaluated.props(Y,(0,yC.toHash)(I),U.props);let Q=I.filter((Z)=>!(0,yC.alwaysValidSchema)(U,q[Z]));if(Q.length===0)return;let K=Y.name("valid");for(let Z of Q){if(G(Z))H(Z);else{if(Y.if((0,xe.propertyInData)(Y,J,Z,U.opts.ownProperties)),H(Z),!U.allErrors)Y.else().var(K,!0);Y.endIf()}$.it.definedProperties.add(Z),$.ok(K)}function G(Z){return U.opts.useDefaults&&!U.compositeRule&&q[Z].default!==void 0}function H(Z){$.subschema({keyword:"properties",schemaProp:Z,dataProp:Z},K)}}};ue.default=Wm0});var pe=M((ce)=>{Object.defineProperty(ce,"__esModule",{value:!0});var be=D$(),IL=I1(),ie=j1(),ne=j1(),Vm0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:Y,schema:q,data:z,parentSchema:J,it:U}=$,{opts:I}=U,Q=(0,be.allSchemaProperties)(q),K=Q.filter((w)=>(0,ie.alwaysValidSchema)(U,q[w]));if(Q.length===0||K.length===Q.length&&(!U.opts.unevaluated||U.props===!0))return;let G=I.strictSchema&&!I.allowMatchingProperties&&J.properties,H=Y.name("valid");if(U.props!==!0&&!(U.props instanceo
Line truncated
`)}openNode($,Y){let q=this.tos,z=this._xml;if(q&&this.open)z.push(">");this._stack.push($),z.push("<"),z.push($),QS(z,Y),this.leaf=!0,this.open=!0}addAttribute($,Y){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(Y!==void 0)a70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");QS(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(t70.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,q){if(this.openNode($,Y),q!==void 0)this.writeText(q);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("")}}KS.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};e70.exports=KS});var GS=M((m81)=>{var $20=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function d81($){if(typeof $==="string")return $;if($20)return $20.decode($);return $.toString()}m81.bufferToString=d81});var U20=M((q20)=>{Object.defineProperty(q20,"__esModule",{value:!0});q20.CHAR=`
`,$=this.i;break;case W51:{let{entityReturnState:q}=this,z=this.entity+Y.slice($,this.prevI);this.state=q;let J;if(z==="")this.fail("empty entity name."),J="&;";else J=this.parseEntity(z),this.entity="";if(q!==A8||this.textHandler!==void 0)this.text+=J;break $}case h4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(DG($))this.state=Q51,this.unget(),this.xmlDeclPossible=!1;else switch($){case MF:this.state=H51,this.xmlDeclPossible=!1;break;case _20:this.state=t$1,this.openWakaBang="",this.xmlDeclPossible=!1;break;case p6:this.state=q51;break;default:this.fail("disallowed character in tag name"),this.state=A8,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=MS,this.openWakaBang="";break;case"--":this.state=OS,this.openWakaBang="";break;case"DOCTYPE":if(this.state=LS,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(OF))this.state=a$1}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===OF)this.state=e$1,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=OS}sCommentEnded(){let $=this.getCodeNorm();if($!==O6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=OS;else this.state=A8}sCData(){if(this.captureToChar(FJ))this.state=$51}sCDataEnding(){let $=this.getCodeNorm();if($===FJ)this.state=Y51;else this.text+=`]${String.fromCodePoint($)}`,this.state=MS}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case O6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=A8;break}case FJ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=MS}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=D20;else if($===p6||c8($))this.fail("processing instruction without a target."),this.state=$===p6?FF:NS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=D20}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let q=this.getCodeNorm();if(q===h4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(q)){this.piTarget+=$.slice(Y,this.prevI);let z=q===p6;if(z||c8(q))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=z?e2:P20}else this.state=z?FF:NS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(q);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===p6)this.state=FF;else if(!c8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(p6))this.state=FF}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===O6){let{piTarget:q}=this;if(q.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:q,body:this.text}),this.piTarget=this.text="",this.state=A8}else if(Y===p6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=NS;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===p6){this.state=e2;return}if($!==h4)this.state=z51,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(L51);if($===p6){this.state=e2,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(c8($)||$===wJ))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=$===wJ?A20:J51}sXMLDeclEq(){let $=this.getCodeNorm();if($===p6){this.state=e2,this.fail("XML declaration is incomplete.");return}if(c8($))return;if($!==wJ)this.fail("value required.");this.state=A20}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===p6){this.state=e2,this.fail("XML declaration is incomplete.");return}if(c8($))return;if(!NF($))this.fail("value must be quoted."),this.q=j20;else this.q=$;this.state=U51}sXMLDeclValue(){let $=this.captureTo([this.q,p6]);if($===p6){this.state=e2,this.text="",this.fail("XML declaration is incomplete.");return}if($===h4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let q=Y;if(this.xmlDecl.version=q,!/^1\.[0-9]+$/.test(q))this.fail("ver
Line truncated
`;$=this.i;break;case h4:if(q!==void 0)this.text+=Y.slice($);break $;default:if(!c8(J))z=!0}}if(!z)return;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}pushAttribNS($,Y){var q;let{prefix:z,local:J}=this.qname($),U={name:$,prefix:z,local:J,value:Y};if(this.attribList.push(U),(q=this.attributeHandler)===null||q===void 0||q.call(this,U),z==="xmlns"){let I=Y.trim();if(this.currentXMLVersion==="1.0"&&I==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[J]=I,ES(this,J,I)}else if($==="xmlns"){let I=Y.trim();this.topNS[""]=I,ES(this,"",I)}}pushAttribPlain($,Y){var q;let z={name:$,value:Y};this.attribList.push(z),(q=this.attributeHandler)===null||q===void 0||q.call(this,z)}end(){var $,Y;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:q}=this;while(q.length>0){let J=q.pop();this.fail(`unclosedtag:${J.name}`)}if(this.state!==N20&&this.state!==A8)this.fail("unexpected end.");let{text:z}=this;if(z.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,z),this.text="";return this._closed=!0,(Y=this.endHandler)===null||Y===void 0||Y.call(this),this._init(),this}resolve($){var Y,q;let z=this.topNS[$];if(z!==void 0)return z;let{tags:J}=this;for(let U=J.length-1;U>=0;U--)if(z=J[U].ns[$],z!==void 0)return z;if(z=this.ns[$],z!==void 0)return z;return(q=(Y=this.opt).resolvePrefix)===null||q===void 0?void 0:q.call(Y,$)}qname($){let Y=$.indexOf(":");if(Y===-1)return{prefix:"",local:$};let q=$.slice(Y+1),z=$.slice(0,Y);if(z===""||q===""||q.includes(":"))this.fail(`malformedname:${$}.`);return{prefix:z,local:q}}processAttribsNS(){var $;let{attribList:Y}=this,q=this.tag;{let{prefix:U,local:I}=this.qname(q.name);q.prefix=U,q.local=I;let Q=q.uri=($=this.resolve(U))!==null&&$!==void 0?$:"";if(U!==""){if(U==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(Q==="")this.fail(`unboundnamespaceprefix:${JSON.stringify(U)}.`),q.uri=U}}if(Y.length===0)return;let{attributes:z}=q,J=new Set;for(let U of Y){let{name:I,prefix:Q,local:K}=U,G,H;if(Q==="")G=I==="xmlns"?OJ:"",H=I;else{if(G=this.resolve(Q),G===void 0)this.fail(`unboundnamespaceprefix:${JSON.stringify(Q)}.`),G=Q;H=`{${G}}${K}`}if(J.has(H))this.fail(`duplicateattribute:${H}.`);J.add(H),U.uri=G,z[I]=U}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,Y=this.tag.attributes;for(let{name:q,value:z}of $){if(Y[q]!==void 0)this.fail(`duplicateattribute:${q}.`);Y[q]=z}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:Y}=this,q=this.tag;q.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,q),Y.push(q),this.state=A8,this.name=""}openSelfClosingTag(){var $,Y,q;this.processAttribs();let{tags:z}=this,J=this.tag;if(J.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,J),(Y=this.closeTagHandler)===null||Y===void 0||Y.call(this,J),(this.tag=(q=z[z.length-1])!==null&&q!==void 0?q:null)===null)this.closedRoot=!0;this.state=A8,this.name=""}closeTag(){let{tags:$,name:Y}=this;if(this.state=A8,this.name="",Y===""){this.fail("weird empty close tag."),this.text+="</>";return}let q=this.closeTagHandler,z=$.length;while(z-- >0){let J=this.tag=$.pop();if(this.topNS=J.ns,q===null||q===void 0||q(J),J.name===Y)break;this.fail("unexpected close tag.")}if(z===0)this.closedRoot=!0;else if(z<0)this.fail(`unmatchedclosingtag:${Y}.`),this.text+=`</${Y}>`}parseEntity($){if($[0]!=="#"){let q=this.ENTITIES[$];if(q!==void 0)return q;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let Y=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))Y=parseInt($.slice(2),16);elseif(/^#[0-9]+$/.test($))Y=parseInt($.slice(1),10);if(!this.isChar(Y))returnthis.fail("malformed character entity."),`&${$};`;returnString.fromCodePoint(Y)}}f20.SaxesParser=u20});varBG=M((D14,i20)=>{var{SaxesParser:P51}=b20(),{PassThrough:A51}=P8(),{bufferToString:B51}=GS();i20.exports=asyncfunction*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(newA51);letY=newP51,q;Y.on("error",(J)=>{q=J});letz=[];Y.on("opentag",(J)=>z.push({eventType:"opentag",value:J})),Y.on("text",(J)=>z.push({eventType:"text",value:J})),Y.on("closetag",(J)=>z.push({eventType:"closetag",value:J}));forawait(letJof$){if(Y.write(B51(J)),q)throwq;yieldz,z=[]}}});varD0=M((P14,n20)=>{varT51=BG(),E51=c6();classNJ{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,Y){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($instanceofNJ)$.reset();elseif($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}asyncparse($){forawait(letYof$)for(let{eventType:q,value:z}ofY)if(q==="opentag")this.parseOpen(z);elseif(q==="text")this.parseText(z);elseif(q==="closetag"){if(!this.parseClose(z.name))returnthLine truncated
See:https://github.com/isaacs/node-glob/issues/167`);return new Z6($,I).found}function Z6($,I){if(!$)throw Error("must provide pattern");if(typeof I==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See:https://github.com/isaacs/node-glob/issues/167`);return new M6($,Y).found}function M6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
`+z0[W0-1];break}}}var O1="a promise was created in a "+B+"handler "+I0+"but was not returned from it, see http://goo.gl/rRqMUw"+r;S._warn(O1,!0,N)}}function _0(a,N){var B=a+" is deprecated and will be removed in a future version.";if(N)B+=" Use "+N+" instead.";return Y1(B)}function Y1(a,N,B){if(!C0.warnings)return;var S=new U(a),n;if(N)B._attachExtraTrace(S);else if(C0.longStackTraces&&(n=$._peekContext()))n.attachExtraTrace(S);else{var I0=k0(S);S.stack=I0.message+`
`+z0[V0-1];break}}}var D1="a promise was created in a "+D+"handler "+Y0+"but was not returned from it, see http://goo.gl/rRqMUw"+r;h._warn(D1,!0,N)}}function L0(o,N){var D=o+" is deprecated and will be removed in a future version.";if(N)D+=" Use "+N+" instead.";return T0(D)}function T0(o,N,D){if(!w0.warnings)return;var h=new J(o),x;if(N)D._attachExtraTrace(h);else if(w0.longStackTraces&&(x=$._peekContext()))x.attachExtraTrace(h);else{var Y0=f0(h);h.stack=Y0.message+`
`)));return}}F=F._target();var D=F._bitField;if((D&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((D&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((D&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(w,L){if(typeof w!=="function")throw new Q(`generatorFunctionmustbeafunction
`)));return}}O=O._target();var P=O._bitField;if((P&50397184)===0)this._yieldedPromise=O,O._proxy(this,null);else if((P&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,O._value());else if((P&16777216)!==0)$._async.invoke(this._promiseRejected,this,O._reason());else this._promiseCancelled()}},$.coroutine=function(L,w){if(typeof L!=="function")throw new Q(`generatorFunctionmustbeafunction
Seehttp://goo.gl/MqrFmX
`);var O=Object(L).yieldHandler,F=X,D=Error().stack;return function(){var P=w.apply(this,arguments),A=new F(void 0,void 0,O,D),T=A.promise();return A._generator=P,A._promiseFulfilled(void 0),T}},$.coroutine.addYieldHandler=function(w){if(typeof w!=="function")throw new Q("expecting a function but got "+K.classString(w));Z.push(w)},$.spawn=function(w){if(Y.deprecated("Promise.spawn()","Promise.coroutine()"),typeof w!=="function")return I(`generatorFunctionmustbeafunction
`);var F=Object(w).yieldHandler,O=X,P=Error().stack;return function(){var B=L.apply(this,arguments),A=new O(void 0,void 0,F,P),E=A.promise();return A._generator=B,A._promiseFulfilled(void 0),E}},$.coroutine.addYieldHandler=function(L){if(typeof L!=="function")throw new Q("expecting a function but got "+K.classString(L));Z.push(L)},$.spawn=function(L){if(U.deprecated("Promise.spawn()","Promise.coroutine()"),typeof L!=="function")return Y(`generatorFunctionmustbeafunction
`)},I=function(){return new v.PromiseInspection(this._target())},z=function(R){return v.reject(new Z(R))};function q(){}var U={},Y=q4(),J;if(Y.isNode)J=function(){var R=process.domain;if(R===void 0)R=null;return R};else J=function(){return null};Y.notEnumerableProp(v,"_getDomain",J);var Q=hI(),K=ZO0(),H=new K;Q.defineProperty(v,"_async",{value:H});var G=d9(),Z=v.TypeError=G.TypeError;v.RangeError=G.RangeError;var W=v.CancellationError=G.CancellationError;v.TimeoutError=G.TimeoutError,v.OperationalError=G.OperationalError,v.RejectionError=G.OperationalError,v.AggregateError=G.AggregateError;var X=function(){},w={},L={},O=LO0()(v,X),F=FO0()(v,X,O,z,q),D=NO0()(v),P=D.create,A=AO0()(v,D),T=A.CapturedTrace,k=BO0()(v,O),h=EO0()(L),f=Cf(),C=Y.errorObj,b=Y.tryCatch;function i(R,u){if(typeof u!=="function")throw new Z("expecting a function but got "+Y.classString(u));if(R.constructor!==v)throw new Z(`thepromiseconstructorcannotbeinvokeddirectly
`)},Y=function(){return new g.PromiseInspection(this._target())},q=function(j){return g.reject(new Z(j))};function z(){}var J={},U=H4(),I;if(U.isNode)I=function(){var j=process.domain;if(j===void 0)j=null;return j};else I=function(){return null};U.notEnumerableProp(g,"_getDomain",I);var Q=kY(),K=nF0(),G=new K;Q.defineProperty(g,"_async",{value:G});var H=$3(),Z=g.TypeError=H.TypeError;g.RangeError=H.RangeError;var V=g.CancellationError=H.CancellationError;g.TimeoutError=H.TimeoutError,g.OperationalError=H.OperationalError,g.RejectionError=H.OperationalError,g.AggregateError=H.AggregateError;var X=function(){},L={},w={},F=lF0()(g,X),O=rF0()(g,X,F,q,z),P=tF0()(g),B=P.create,A=eF0()(g,P),E=A.CapturedTrace,y=YO0()(g,F),v=zO0()(w),k=mf(),C=U.errorObj,c=U.tryCatch;function n(j,u){if(typeof u!=="function")throw new Z("expecting a function but got "+U.classString(u));if(j.constructor!==g)throw new Z(`thepromiseconstructorcannotbeinvokeddirectly
Seehttp://goo.gl/MqrFmX
`)}function v(R){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,R!==X)i(this,R),this._resolveFromExecutor(R);this._promiseCreated(),this._fireEvent("promiseCreated",this)}v.prototype.toString=function(){return"[object Promise]"},v.prototype.caught=v.prototype.catch=function(R){var u=arguments.length;if(u>1){var p=Array(u-1),s=0,U0;for(U0=0;U0<u-1;++U0){var H0=arguments[U0];if(Y.isObject(H0))p[s++]=H0;else return z("expecting an object but got A catch statement predicate "+Y.classString(H0))}return p.length=s,R=arguments[U0],this.then(void 0,h(p,R,this))}return this.then(void 0,R)},v.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},v.prototype.then=function(R,u){if(A.warnings()&&arguments.length>0&&typeof R!=="function"&&typeof u!=="function"){var p=".then() only accepts functions but was passed: "+Y.classString(R);if(arguments.length>1)p+=", "+Y.classString(u);this._warn(p)}return this._then(R,u,void 0,void 0,void 0)},v.prototype.done=function(R,u){var p=this._then(R,u,void 0,void 0,void 0);p._setIsFinal()},v.prototype.spread=function(R){if(typeof R!=="function")return z("expecting a function but got "+Y.classString(R));return this.all()._then(R,void 0,void 0,w,void 0)},v.prototype.toJSON=function(){var R={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())R.fulfillmentValue=this.value(),R.isFulfilled=!0;else if(this.isRejected())R.rejectionReason=this.reason(),R.isRejected=!0;return R},v.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},v.prototype.error=function(R){return this.caught(Y.originatesFromRejection,R)},v.getNewLibraryCopy=Rf.exports,v.is=function(R){return R instanceof v},v.fromNode=v.fromCallback=function(R){var u=new v(X);u._captureStackTrace();var p=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,s=b(R)(f(u,p));if(s===C)u._rejectCallback(s.e,!0);if(!u._isFateSealed())u._setAsyncGuaranteed();return u},v.all=function(R){return new F(R).promise()},v.cast=function(R){var u=O(R);if(!(u instanceof v))u=new v(X),u._captureStackTrace(),u._setFulfilled(),u._rejectionHandler0=R;return u},v.resolve=v.fulfilled=v.cast,v.reject=v.rejected=function(R){var u=new v(X);return u._captureStackTrace(),u._rejectCallback(R,!0),u},v.setScheduler=function(R){if(typeof R!=="function")throw new Z("expecting a function but got "+Y.classString(R));return H.setScheduler(R)},v.prototype._then=function(R,u,p,s,U0){var H0=U0!==void 0,D0=H0?U0:new v(X),_0=this._target(),Y1=_0._bitField;if(!H0){if(D0._propagateFrom(this,3),D0._captureStackTrace(),s===void 0&&(this._bitField&2097152)!==0)if((Y1&50397184)!==0)s=this._boundValue();else s=_0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,D0)}var u0=J();if((Y1&50397184)!==0){var r0,I1,o=_0._settlePromiseCtx;if((Y1&33554432)!==0)I1=_0._rejectionHandler0,r0=R;else if((Y1&16777216)!==0)I1=_0._fulfillmentHandler0,r0=u,_0._unsetRejectionIsUnhandled();else o=_0._settlePromiseLateCancellationObserver,I1=new W("late cancellation observer"),_0._attachExtraTrace(I1),r0=u;H.invoke(o,_0,{handler:u0===null?r0:typeof r0==="function"&&Y.domainBind(u0,r0),promise:D0,receiver:s,value:I1})}else _0._addCallbacks(R,u,D0,s,u0);return D0},v.prototype._length=function(){return this._bitField&65535},v.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},v.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},v.prototype._setLength=function(R){this._bitField=this._bitField&-65536|R&65535},v.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},v.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},v.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},v.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},v.prototype._isFinal=function(){return(this._bitField&4194304)>0},v.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},v.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},v.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},v.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},v.prototype._receiverAt=function(R){var u=R===0?this._receiver0:this[R*4-4+3];if(u===U)return;else if(u===void 0&&this._isBound())return this._boundValue();return u},v.prototype._promiseAt=function(R){return this[R*4-4+2]},v.prototype._fulfillmentHandlerAt=function(R){return this[R*4-4+0]},v.prototype._rejectionHandlerAt=function(R){return this[R*4-4+1]},v.prototype._boundValue=function(){},v.prototype._migrateCallback0=function(R){var{_bitFie
Line truncated
`)}function g(j){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,j!==X)n(this,j),this._resolveFromExecutor(j);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(j){var u=arguments.length;if(u>1){var p=Array(u-1),d=0,q0;for(q0=0;q0<u-1;++q0){var t=arguments[q0];if(U.isObject(t))p[d++]=t;else return q("expecting an object but got A catch statement predicate "+U.classString(t))}return p.length=d,j=arguments[q0],this.then(void 0,v(p,j,this))}return this.then(void 0,j)},g.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},g.prototype.then=function(j,u){if(A.warnings()&&arguments.length>0&&typeof j!=="function"&&typeof u!=="function"){var p=".then() only accepts functions but was passed: "+U.classString(j);if(arguments.length>1)p+=", "+U.classString(u);this._warn(p)}return this._then(j,u,void 0,void 0,void 0)},g.prototype.done=function(j,u){var p=this._then(j,u,void 0,void 0,void 0);p._setIsFinal()},g.prototype.spread=function(j){if(typeof j!=="function")return q("expecting a function but got "+U.classString(j));return this.all()._then(j,void 0,void 0,L,void 0)},g.prototype.toJSON=function(){var j={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())j.fulfillmentValue=this.value(),j.isFulfilled=!0;else if(this.isRejected())j.rejectionReason=this.reason(),j.isRejected=!0;return j},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new O(this).promise()},g.prototype.error=function(j){return this.caught(U.originatesFromRejection,j)},g.getNewLibraryCopy=of.exports,g.is=function(j){return j instanceof g},g.fromNode=g.fromCallback=function(j){var u=new g(X);u._captureStackTrace();var p=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,d=c(j)(k(u,p));if(d===C)u._rejectCallback(d.e,!0);if(!u._isFateSealed())u._setAsyncGuaranteed();return u},g.all=function(j){return new O(j).promise()},g.cast=function(j){var u=F(j);if(!(u instanceof g))u=new g(X),u._captureStackTrace(),u._setFulfilled(),u._rejectionHandler0=j;return u},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(j){var u=new g(X);return u._captureStackTrace(),u._rejectCallback(j,!0),u},g.setScheduler=function(j){if(typeof j!=="function")throw new Z("expecting a function but got "+U.classString(j));return G.setScheduler(j)},g.prototype._then=function(j,u,p,d,q0){var t=q0!==void 0,H0=t?q0:new g(X),L0=this._target(),T0=L0._bitField;if(!t){if(H0._propagateFrom(this,3),H0._captureStackTrace(),d===void 0&&(this._bitField&2097152)!==0)if((T0&50397184)!==0)d=this._boundValue();else d=L0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,H0)}var C0=I();if((T0&50397184)!==0){var j0,i0,K0=L0._settlePromiseCtx;if((T0&33554432)!==0)i0=L0._rejectionHandler0,j0=j;else if((T0&16777216)!==0)i0=L0._fulfillmentHandler0,j0=u,L0._unsetRejectionIsUnhandled();else K0=L0._settlePromiseLateCancellationObserver,i0=new V("late cancellation observer"),L0._attachExtraTrace(i0),j0=u;G.invoke(K0,L0,{handler:C0===null?j0:typeof j0==="function"&&U.domainBind(C0,j0),promise:H0,receiver:d,value:i0})}else L0._addCallbacks(j,u,H0,d,C0);return H0},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(j){this._bitField=this._bitField&-65536|j&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(G.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(j){var u=j===0?this._receiver0:this[j*4-4+3];if(u===J)return;else if(u===void 0&&this._isBound())return this._boundValue();return u},g.prototype._promiseAt=function(j){return this[j*4-4+2]},g.prototype._fulfillmentHandlerAt=function(j){return this[j*4-4+0]},g.prototype._rejectionHandlerAt=function(j){return this[j*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(j){var{_bitField:u
Line truncated
↳${L}`,operator:U}}function QA0($){if(!$)return[];let Y=$.pending||[],q=String($.rawState||"").toUpperCase(),z=String($.state||"").toUpperCase(),J=[];if(Y.length>0)for(let U of Y){let I=U.approver?.name||U.approver?.id||"待定",Q=(U.name||$.currentNode||"").trim(),K=Q?`${Q}(${I})`:I,H=U.type?.toUpperCase()==="PAYING"||Q.includes("支付")||q==="PAYING"||z==="支付中"?"待支付":"待审批";J.push(`${K}:${H}`)}else if($.currentNode?.trim()){let I=$.currentNode.includes("支付")||q==="PAYING"||z==="支付中"?"待支付":"待审批";J.push(`${$.currentNode.trim()}:${I}`)}return J}function tY($,Y){let q=new Map;if(!$||$.length===0)return q;if(!Y){for(let X of $){let w=(X.result||{}).decision||X.aiDecision||"-";q.set(X.id,{recordId:X.id,sourceDocumentSN:X.sourceDocumentSN,taskMode:X.taskMode,aiDecision:IA0(typeof w==="string"?w:"-"),aiAction:"-",eHumanAction:"-",eHumanComment:"-",auditDrift:!1})}return q}let z=[...$].sort((X,L)=>(Number(X.createdAt)||0)-(Number(L.createdAt)||0)),J=Y.history||[],U=String(Y.rawState||"").toUpperCase(),I=String(Y.state||"").toUpperCase(),Q=U==="DRAFT"||U==="REVOKED"||U==="CANCELED"||U==="CANCELLED"||I==="草稿"||I==="已撤回"||I==="已取消",K=U==="REJECTED"||U==="TERMINATED"||I==="审批驳回"||I==="已驳回",G=!Q&&!K&&(U==="PAID"||I==="已支付"||J.some((X)=>!X.isEbot&&(X.rawAction==="freeflow.pay"||X.action==="支付成功"||X.action==="支付完成"))),H=!Q&&!K&&!G&&(U==="PAYING"||I==="支付中"||(Y.pending||[]).some((X)=>X.isCurrent&&(X.type?.toUpperCase()==="PAYING"||X.name?.includes("支付")))||Y.currentNode?.includes("支付")===!0),V=G||!Q&&!K&&!H&&(U==="COMPLETED"||U==="APPROVED"||I==="已完成"||I==="审批通过");for(let X=0;X<z.length;X++){let L=z[X];if(!L)continue;let w=Number(L.createdAt)||0,F=L.document||{},O=L.manualApprovalRecord||L.result?.manualApprovalRecord||F.manualApprovalRecord||{},P=typeof L.sourceExtendData?.nodeId==="string"?String(L.sourceExtendData.nodeId):void 0,B=typeof O.nodeId==="string"?String(O.nodeId):void 0,A=B?decodeURIComponent(B).replace(/^hcnode_/,"").replace(/_r\d+$/,""):void 0,E=P||A,y=E?J.find((w0)=>w0.nodeId&&(w0.nodeId===E||E.includes(w0.nodeId))):void 0,v=y?.time??w,k=z[X+1],C=k?Number(k.createdAt)||1/0:1/0,c=X===z.length-1,n=J.find((w0)=>(w0.time??0)>v+5000&&w0.isEbot&&(w0.nodeName?.includes("智能")||w0.nodeName?.includes("AI")||w0.action?.includes("智能")||w0.comment?.includes("AI")||w0.comment?.includes("approval-result"))&&!w0.nodeName?.includes("费用标准检查")&&!w0.nodeName?.includes("标准检查")&&!w0.nodeName?.includes("预算"));if(n){if(c=!1,(n.time??1/0)<C)C=n.time}let g=L.result||{},b=g.decision||L.aiDecision||"-",i=typeof b==="string"?b:"-",$0=i.toUpperCase(),j=$0==="REJECT"||$0==="驳回",u=$0==="APPROVE"||$0==="通过",p=$0==="EXEMPT_APPROVE"||$0==="免审通过"||$0==="备注通过",d=L.taskMode||L.finalExecutionMode||"",t=String(d).toLowerCase().includes("auto")||L.finalExecutionMode==="automatic"||d==="automatic"||d==="fully_automatic",H0="-";if(u||p)H0="添加评论";else if(j)H0=t?"驳回":"添加评论";else if($0==="REVIEW"||$0==="转交复核")H0="转交复核";let L0=typeof O.status==="object"&&O.status!==null?String(O.status.type||O.status.label||"").toUpperCase():"",T0=typeof O.status==="object"&&O.status!==null?String(O.status.sourceStatus||""):"",C0=F.manualApprovalStatus||g.manualApprovalStatus||L.manualApprovalStatus,j0=typeof C0==="string"?C0.toUpperCase():"",i0=j0==="CANCELLED"||j0==="CANCELED"||j0==="已取消"||j0==="已撤回"||j0==="REVOKED"||L0==="CANCELLED"||L0==="CANCELED"||T0.includes("撤回")||T0.includes("取消"),K0=j0==="APPROVED"||j0==="已支付/审批完成"||j0==="已通过"||j0==="已完成"||j0==="已支付"||L0==="APPROVED",f0=!(T0.includes("补偿")||T0.includes("已支付"))&&(j0==="TERMINATED"||j0==="REJECTED"||j0==="REJECT"||j0==="已驳回"||j0==="被驳回"||L0==="TERMINATED"||L0==="REJECTED"||L0==="已驳回"||L0==="被驳回"),c0=y?1000:60000,C1=J.filter((w0)=>{let o=w0.time??0;return o>=v-c0&&o<C}),a0="-",r1="-",F1=!1,b1,$1,J6=u||p,a8=J.filter((w0)=>(w0.time??0)>v+5000),U6=a8.some((w0)=>w0.rawAction==="freeflow.retract"||w0.action==="单据撤回"),e8=a8.some((w0)=>w0.rawAction==="freeflow.submit"||w0.action==="提交送审");if(J6&&c&&(U6||e8))F1=!0,b1="AI通过后单据发生撤回/修改重提,后续未经AI复审";if(t&&j)a0="无操作",r1="-";else{let w0=C1.filter((D)=>(D.time??0)>=v-1000&&!D.isEbot&&D.rawAction!=="freeflow.submit"&&D.action!=="提交送审"&&!((D.rawAction==="freeflow.comment"||D.action==="发表评论")&&!D.comment)&&!((D.rawAction==="freeflow.print"||D.action==="打印提醒")&&!D.comment)&&!(D.rawAction==="freeflow.carbonCopy"||D.rawAction==="freeflow.cc"||D.action==="抄送通知")),o=w0.find((D)=>D.rawAction==="freeflow.retract"||D.action==="单据撤回"),N=w0.find((D)=>D.rawAction==="freeflow.reject"||D.action==="审批驳回");if(!c)if(N||!Y&&f0){a0="审批驳回",F1=!1,b1=void 0;let D=Ei(N,void 0,O,J,Y);
Line truncated
`,{mode:384}),Y}function bi($){let Y=EA0();for(let q of Y){if(!X$(q))continue;for(let z of GD(q).filter((J)=>J.endsWith(".json")).filter((J)=>!J.startsWith("example."))){let J=Q9(q,z);try{let U=ZD(J,"utf-8"),I=JSON.parse(U);if(I&&typeof I==="object"&&I.id===$)return J}catch{}}}return}function e7($,Y){let q=bi($);if(!q)throw Error(`Enterpriseconfignotfound:${$}`);let J={...JSON.parse(ZD(q,"utf-8")),...Y};for(let I of Object.keys(Y))if(Y[I]===void 0)delete J[I];let U=xi.parse(J);return NA0(q,`${JSON.stringify(U,null,2)}
`,"utf-8"),U}var ui="SEAL_USE_ENTERPRISES_DIR",DA0="SEAL_HOME_ENTERPRISES_DIR",PA0="SEAL_USE_USER_ENTERPRISES_DIR",AA0="SEAL_HOME_USER_ENTERPRISES_DIR",BA0="SEAL_USE_CONFIG_FILE",TA0="SEAL_HOME_CONFIG_FILE",iU,HD,KD,OA0;var K3=e(()=>{ki();iU=Q9(WD(),".config","seal-use","enterprises"),HD=Q9(WD(),".config","seal-home","enterprises"),KD=Q9(WD(),".config","seal-use","config.json"),OA0=Q9(WD(),".config","seal-home","config.json")});function $2($,Y,q=[]){let z=Y.corpId?.trim()||void 0,J=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,U=z??J;if(U){let Q=$.find((H)=>H.id===U);if(Q)return Q;let K=$.find((H)=>H.id.toLowerCase()===U.toLowerCase());if(K)return K;let G=$.find((H)=>H.name.toLowerCase()===U.toLowerCase());if(G)return G;throw Error(`Noenterpriseconfigfoundfor${U}`)}if(!Y.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-homeconfigmodestateful` 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: "+(q.length?q.join(", "):"the configured enterprise directories"))}import{existsSync as ii,mkdirSync as Lj1,readFileSync as wj1,renameSync as Fj1,unlinkSync as Oj1,writeFileSync as Mj1}from"node:fs";import{homedir as Nj1}from"node:os";import{dirname as Dj1,join as Pj1}from"node:path";function ci(){let $=process.env[Aj1]?.trim();if($)return $;return Bj1}function jA0($=new Date){return $.toISOString().slice(0,10)}function _A0($=ni,Y=new Date){let q=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(q).toISOString().slice(0,10)}function RA0($=ci()){if(!ii($))return{};try{let Y=wj1($,"utf-8"),q=JSON.parse(Y);if(q&&typeof q==="object"&&!Array.isArray(q))return q;return{}}catch{return{}}}function Tj1($,Y){let q={};for(let[z,J]of Object.entries($)){if(!J||typeof J!=="object")continue;let U={},I=!1;for(let[Q,K]of Object.entries(J))if(typeof K==="number"&&K>0&&Q>=Y)U[Q]=K,I=!0;if(I)q[z]=U}return q}function Ej1($,Y=ci()){let q=Dj1(Y);if(!ii(q))Lj1(q,{recursive:!0,mode:448});let z=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{Mj1(z,JSON.stringify($,null,2),"utf-8"),Fj1(z,Y)}catch(J){try{if(ii(z))Oj1(z)}catch{}throw J}}function CA0($,Y=new Date){if(!$||typeof $!=="string")return;try{let q=ci(),z=RA0(q),J=jA0(Y),U=_A0(ni,Y),I=Tj1(z,U);I[$]=I[$]||{},I[$][J]=(I[$][J]??0)+1,Ej1(I,q)}catch{}}function jj1($,Y=ni,q=new Date){let z=new Map;try{let J=RA0(),U=_A0(Y,q),I=jA0(q),Q=$??Object.keys(J);for(let K of Q){let G=J[K];if(!G){z.set(K,0);continue}let H=0;for(let[Z,V]of Object.entries(G))if(Z>=U&&Z<=I&&typeof V==="number")H+=V;z.set(K,H)}}catch{if($)for(let J of $)z.set(J,0)}return z}function vA0($,Y,q){let z=q??jj1($.map((J)=>J.id));return[...$].sort((J,U)=>{if(Y){if(J.id===Y&&U.id!==Y)return-1;if(U.id===Y&&J.id!==Y)return 1}let I=z.get(J.id)??0,Q=z.get(U.id)??0;if(I!==Q)return Q-I;let K=J.name??J.id,G=U.name??U.id,H=K.localeCompare(G,"zh-CN");if(H!==0)return H;return J.id.localeCompare(U.id)})}var Aj1="SEAL_USE_USAGE_FILE",Bj1,ni=7;var pi=e(()=>{Bj1=Pj1(Nj1(),".config","seal-use","usage.json")});function _j1($,Y){return $.map((q)=>q.trim()).filter(Boolean).map((q)=>Y?q:q.toLowerCase())}function Rj1($,Y){return Y?$:$.toLowerCase()}function Cj1($,Y,q,z){let J=Rj1($,z),U=Y.filter((I)=>J.includes(I));if(q==="all"&&U.length!==Y.length)return[];return U}function vj1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function hj1($,Y){if(Y.fields&&!Y.fields.has($.field))return[];let q=vj1($.value),z=[];return q.forEach((J,U)=>{let I=Cj1(J,Y.keywords,Y.matchMode,Y.caseSensitive);if(I.length===0)return;let Q=Math.max(0,U-Y.contextLines),K=Math.min(q.length,U+Y.contextLines+1),G={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:U+1,matchedKeywords:I,matchedText:XD(J,Y.maxChars),context:{before:Y.snippetOnly?[]:q.slice(Q,U).map((H)=>XD(H,Y.maxChars)),line:XD(J,Y.maxChars),after:Y.snippetOnly?[]:q.slice(U+1,K).map((H)=>XD(H,Y.maxChars))},metadata:$.metadata};if(Y.snippetOnly)G.context={before:[],line:G.context.line,after:[]};z.push(G)}),z}function XD($,Y){if(!Y||$.length<=Y)return $;return`${$.slice(0,Math.max(0,Y))}...`}function gj1($){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 gA0($){return $.rules.flatMap((Y,q)=>{let z=`${$.id}:${Y.description.slice(0,32)}`,J={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:q};return[{area:"rules",entityType:"rule",entityId:z,title:`${$.versionName}/${Y.scope}`,field:"history.description",
Line truncated
@@ -866,55 +870,65 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
}
exportdefaultlintRule;
`}});import{existsSync as oI,mkdirSync as vE1,readFileSync as hE1,readdirSync as tA0,rmSync as gE1,unlinkSync as SE1,writeFileSync as yE1}from"node:fs";import{homedir as xE1}from"node:os";import{isAbsolute as uE1,join as A6,resolve as kE1}from"node:path";import{pathToFileURL as rA0}from"node:url";function aA0($=x$){let I=[],z=[];try{if(!oI($))vE1($,{recursive:!0});let q=Object.keys(Pi);for(let[Y,J]of Object.entries(Pi)){let Q=A6($,Y),K=!0;if(oI(Q))try{if(hE1(Q,"utf8")===J)K=!1}catch{K=!0}if(K)yE1(Q,J,"utf8");I.push(Y)}let U=tA0($,{withFileTypes:!0});for(let Y of U)if(!q.includes(Y.name)){let J=A6($,Y.name);try{if(Y.isDirectory())gE1(J,{recursive:!0,force:!0});else SE1(J);z.push(Y.name)}catch{}}}catch{}return{synced:I,pruned:z}}function eA0($={syncOfficial:!0}){if($.syncOfficial!==!1)aA0();let I=[{name:"builtin",type:"builtin",path:A6(x$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:A6(x$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:A6(x$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],z=[y$,YD];for(let q of z)if(oI(q))try{let U=tA0(q,{withFileTypes:!0});for(let Y of U){if(Y.isDirectory())continue;let J=Y.name;if(J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")){let Q=J.replace(/\.(ts|js|mjs)$/,"");if(!I.some((K)=>K.name===Q))I.push({name:Q,type:"custom",path:A6(q,J),description:`用户自定义规则校验器(${J})`})}}}catch{}return I}function bE1($){let I=($||"").trim();if(!I||I==="builtin"||I==="default"||I==="official/builtin"||I==="official/builtin.ts")return{path:A6(x$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(I==="strict"||I==="official/strict"||I==="official/strict.ts")return{path:A6(x$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(I==="hlab"||I==="hlab-sop"||I==="hlab-rules"||I==="hlab-standard"||I==="official/hlab"||I==="official/hlab.ts")return{path:A6(x$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(uE1(I)||I.startsWith("./")||I.startsWith("../")){let q=kE1(I);if(oI(q))return{path:q};for(let U of[".ts",".js",".mjs"])if(oI(`${q}${U}`))return{path:`${q}${U}`}}let z=[A6(y$,`${I}.ts`),A6(y$,`${I}.js`),A6(y$,`${I}.mjs`),A6(YD,`${I}.ts`),A6(YD,`${I}.js`),A6(YD,`${I}.mjs`)];for(let q of z)if(oI(q))return{path:q};return{}}async function Ti($){aA0();let I=bE1($??"builtin");if(I.isOfficial){let q=I.officialKind==="strict"?lA0:I.officialKind==="hlab"?oA0:hY,U=I.officialKind==="builtin"?"builtin":"official",Y=I.path;if(Y&&oI(Y))try{let Q=await import(rA0(Y).href),K=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof K==="function")return{name:I.officialKind??"builtin",type:U,filePath:Y,linter:sA0(K,q)}}catch{}return{name:I.officialKind??"builtin",type:U,filePath:Y,linter:q}}let z=I.path;if(!z)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:hY};try{let U=await import(rA0(z).href),Y=U.default??U.lintRule??U.linter??U.lint;if(typeof Y!=="function")return console.error(`⚠️[linter]自定义校验器"${z}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:hY};return{name:$??"custom",type:"custom",filePath:z,linter:sA0(Y,hY)}}catch(q){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${z}"失败(语法错误或依赖缺失:${q?.message??q}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:hY}}}functionsA0($,I){returnasync(z,q)=>{try{letU=await$(z,q);if(U&&typeofU==="object"&&typeofU.score==="number"&&Array.isArray(U.issues))returnU;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),I(z,q)}catch(U){returnconsole.error("⚠️[linter]自定义校验器执行异常:",U),I(z,q)}}}vary$,fE1="official",x$,YD;varEi=e(()=>{Ni();Ai();Bi();Di();y$=A6(xE1(),".config","seal-use","linters"),x$=A6(y$,fE1),YD=A6(process.cwd(),"linters")});asyncfunctionji($,I,z){letq=awaitI.linter($,z);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:q.score,passed:q.passed,issues:q.issues,description:$.description}}asyncfunction$P0($,I,z,q){letU=q?.minScore??0,Y=q?.level??"all",J=[],Q=0;for(letXof$){letw=awaitji(X,I,z);Q+=w.score;letL=w.issues;if(Y==="error")L=w.issues.filter((F)=>F.level==="error");elseif(Y==="warning")L=w.issues.filter((F)=>F.level==="warning"||F.level==="error");letO=L.every((F)=>F.level!=="error");if(q?.summary){if(L.length>0)J.push({...w,passed:O,issues:L})}elseJ.push({...w,passed:O,issues:L})}letK=$.length,H=K===0?100:Math.round(Q/K),G=J.filter((X)=>X.issues.length>0).length,Z=K-Line truncated
`}});import{existsSync as $q,mkdirSync as U_1,readFileSync as I_1,readdirSync as dA0,rmSync as Q_1,unlinkSync as K_1,writeFileSync as G_1}from"node:fs";import{homedir as H_1}from"node:os";import{isAbsolute as Z_1,join as C6,resolve as W_1}from"node:path";import{pathToFileURL as cA0}from"node:url";function mA0($=i$){let Y=[],q=[];try{if(!$q($))U_1($,{recursive:!0});let z=Object.keys(ti);for(let[U,I]of Object.entries(ti)){let Q=C6($,U),K=!0;if($q(Q))try{if(I_1(Q,"utf8")===I)K=!1}catch{K=!0}if(K)G_1(Q,I,"utf8");Y.push(U)}let J=dA0($,{withFileTypes:!0});for(let U of J)if(!z.includes(U.name)){let I=C6($,U.name);try{if(U.isDirectory())Q_1(I,{recursive:!0,force:!0});else K_1(I);q.push(U.name)}catch{}}}catch{}return{synced:Y,pruned:q}}function lA0($={syncOfficial:!0}){if($.syncOfficial!==!1)mA0();let Y=[{name:"builtin",type:"builtin",path:C6(i$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:C6(i$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:C6(i$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],q=[b$,OD];for(let z of q)if($q(z))try{let J=dA0(z,{withFileTypes:!0});for(let U of J){if(U.isDirectory())continue;let I=U.name;if(I.endsWith(".ts")||I.endsWith(".js")||I.endsWith(".mjs")){let Q=I.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((K)=>K.name===Q))Y.push({name:Q,type:"custom",path:C6(z,I),description:`用户自定义规则校验器(${I})`})}}}catch{}return Y}function V_1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:C6(i$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:C6(i$,"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:C6(i$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(Z_1(Y)||Y.startsWith("./")||Y.startsWith("../")){let z=W_1(Y);if($q(z))return{path:z};for(let J of[".ts",".js",".mjs"])if($q(`${z}${J}`))return{path:`${z}${J}`}}let q=[C6(b$,`${Y}.ts`),C6(b$,`${Y}.js`),C6(b$,`${Y}.mjs`),C6(OD,`${Y}.ts`),C6(OD,`${Y}.js`),C6(OD,`${Y}.mjs`)];for(let z of q)if($q(z))return{path:z};return{}}async function ei($){mA0();let Y=V_1($??"builtin");if(Y.isOfficial){let z=Y.officialKind==="strict"?iA0:Y.officialKind==="hlab"?nA0:cU,J=Y.officialKind==="builtin"?"builtin":"official",U=Y.path;if(U&&$q(U))try{let Q=await import(cA0(U).href),K=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof K==="function")return{name:Y.officialKind??"builtin",type:J,filePath:U,linter:pA0(K,z)}}catch{}return{name:Y.officialKind??"builtin",type:J,filePath:U,linter:z}}let q=Y.path;if(!q)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cU};try{let J=await import(cA0(q).href),U=J.default??J.lintRule??J.linter??J.lint;if(typeof U!=="function")return console.error(`⚠️[linter]自定义校验器"${q}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cU};return{name:$??"custom",type:"custom",filePath:q,linter:pA0(U,cU)}}catch(z){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${q}"失败(语法错误或依赖缺失:${z?.message??z}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cU}}}functionpA0($,Y){returnasync(q,z)=>{try{letJ=await$(q,z);if(J&&typeofJ==="object"&&typeofJ.score==="number"&&Array.isArray(J.issues))returnJ;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),Y(q,z)}catch(J){returnconsole.error("⚠️[linter]自定义校验器执行异常:",J),Y(q,z)}}}varb$,X_1="official",i$,OD;var$n=e(()=>{oi();si();ai();ri();b$=C6(H_1(),".config","seal-use","linters"),i$=C6(b$,X_1),OD=C6(process.cwd(),"linters")});asyncfunctionYn($,Y,q){letz=awaitY.linter($,q);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:z.score,passed:z.passed,issues:z.issues,description:$.description}}asyncfunctionoA0($,Y,q,z){letJ=z?.minScore??0,U=z?.level??"all",I=[],Q=0;for(letXof$){letL=awaitYn(X,Y,q);Q+=L.score;letw=L.issues;if(U==="error")w=L.issues.filter((O)=>O.level==="error");elseif(U==="warning")w=L.issues.filter((O)=>O.level==="warning"||O.level==="error");letF=w.every((O)=>O.level!=="error");if(z?.summary){if(w.length>0)I.push({...L,passed:F,issues:w})}elseI.push({...L,passed:F,issues:w})}letK=$.length,G=K===0?100:Math.round(Q/K),H=I.filter((X)=>X.issues.length>0).length,Z=K-Line truncated
`),q=await Promise.all(P.map((A)=>z4($,A.id)))}let U=new Map,Y=0;for(let F of q){let D=F.document,P=F.sourceDocumentId??(typeof D?.id==="string"?D.id:void 0)??(typeof D?.sourceDocumentId==="string"?D.sourceDocumentId:void 0)??F.documentId??F.id,A=`${z.docIdPrefix??""}${P}${z.docIdSuffix??""}`,T=[];if(z.includeAttachments!==!1){let h=d7(F,{summary:!1}).attachments,f=new Set;for(let C of h){let b=C.ossSignedUrl??C.url;if(!b)continue;let i=C.fileName??C.fileId??"attachment",v=Yi(i),y=v,c=v.lastIndexOf("."),$0=c>0?v.slice(0,c):v,R=c>0?v.slice(c):"",u=1;while(f.has(y.toLowerCase()))y=`${$0}_${u}${R}`,u++;f.add(y.toLowerCase());try{process.stderr.write(`⬇下载单据「${A}」附件:${i}...
`),await new Promise((F,D)=>{let P=wu1(w),A=new Np({zlib:{level:9}});P.on("close",()=>F()),A.on("error",(T)=>D(T)),A.pipe(P),A.append(Buffer.from(L),{name:"信息表.xlsx"});for(let T of U.values())for(let k of T)A.append(k.buffer,{name:k.zipPath});A.finalize()});let O=Ou1(w);return{filePath:w,corpId:I.id,corpName:I.name,recordCount:q.length,attachmentCount:Y,fileSizeBytes:O.size,exportedAt:new Date().toISOString(),nextAction:`seal-usewebhookresource-packpush${w}--corp<targetCorpId>`}}var YR0;var Dp=e(()=>{qR0();e4();lN();YR0=j4(QZ(),1)});import{readFileSync as Au1}from"node:fs";function Pu1($){let I=new URL($),z=I.pathname.match(/\/webhook\/([^/]+)/);if(!z)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${I.protocol}//${I.host}`,webhookId:z[1]}}function Bu1($,I){return I.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!I.toLowerCase().endsWith(".xlsx")}function Tu1($,I){if(!$.length)return;let z=new Set($.map((Y)=>{let J=Y.fileName.split("/")[0],Q=J.indexOf("@");return Q>=0?J.slice(0,Q):J}).filter((Y)=>Y!=="信息表.xlsx")),q=[];for(let Y of I){let J=Y.document.documentId;if((Y.documentAttachments.length>0||Object.values(Y.expenseAttachments).some((K)=>K.length>0)||Object.values(Y.personAttachments).some((K)=>K.length>0))&&!z.has(J))q.push(`Excel 会议编号「${J}」声明了附件,但在 ZIP 中找不到对应的根目录「${J}/」或「${J}@.../」。`)}let U=new Set(I.map((Y)=>Y.document.documentId));for(let Y of z)if(!U.has(Y))q.push(`ZIP 根目录对应的编号「${Y}」在信息表中找不到对应的会议编号。`);if(q.length)throw new W5(q)}async function JR0($,I,z){let q=[],U=$;if(Bu1($,I)){q=await LB0($),FB0(q,z);let K=q.find((H)=>H.fileName==="信息表.xlsx");if(!K)throw Error("ZIP 根目录缺少信息表.xlsx");U=await Nn($,K)}let Y=await TB0(U);Tu1(q,Y);let J=EB0(q,Y),Q=Y.map((K)=>K.document);return{entries:q,parsed:Y,plans:J,documents:Q,fileBuffer:$}}async function wz($,I,z){let q=await JR0($,I,z),U=q.parsed.map((Y,J)=>En(Y.document,q.plans[J],new Map));return{warnings:[],documents:U,attachmentPlan:q.plans}}async function LA($,I,z){let q=await JR0($,I,z.materialPackFilePolicy),{baseUrl:U,webhookId:Y}=Pu1(z.webhookUrl),J=[];for(let Q=0;Q<q.parsed.length;Q+=1){let K=q.parsed[Q],H=q.plans[Q],G=new Map,Z=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let w of Z)for(let L of w.paths){if(G.has(L))continue;let O=q.entries.find((k)=>k.fileName===L);if(!O)continue;process.stderr.write(`⬆ 上传附件: ${L}
`),z=await Promise.all(B.map((A)=>e1($,A.id)))}let J=new Map,U=0;for(let O of z){let P=O.document,B=O.sourceDocumentId??(typeof P?.id==="string"?P.id:void 0)??(typeof P?.sourceDocumentId==="string"?P.sourceDocumentId:void 0)??O.documentId??O.id,A=`${q.docIdPrefix??""}${B}${q.docIdSuffix??""}`,E=[];if(q.includeAttachments!==!1){let v=a7(O,{summary:!1}).attachments,k=new Set;for(let C of v){let c=C.ossSignedUrl??C.url;if(!c)continue;let n=C.fileName??C.fileId??"attachment",g=gi(n),b=g,i=g.lastIndexOf("."),$0=i>0?g.slice(0,i):g,j=i>0?g.slice(i):"",u=1;while(k.has(b.toLowerCase()))b=`${$0}_${u}${j}`,u++;k.add(b.toLowerCase());try{process.stderr.write(`⬇下载单据「${A}」附件:${n}...
`),await new Promise((O,P)=>{let B=cu1(L),A=new op({zlib:{level:9}});B.on("close",()=>O()),A.on("error",(E)=>P(E)),A.pipe(B),A.append(Buffer.from(w),{name:"信息表.xlsx"});for(let E of J.values())for(let y of E)A.append(y.buffer,{name:y.zipPath});A.finalize()});let F=du1(L);return{filePath:L,corpId:Y.id,corpName:Y.name,recordCount:z.length,attachmentCount:U,fileSizeBytes:F.size,exportedAt:new Date().toISOString(),nextAction:`seal-usewebhookresource-packpush${L}--corp<targetCorpId>`}}var eC0;var rp=e(()=>{tC0();I6();ID();eC0=y4(FZ(),1)});import{readFileSync as su1}from"node:fs";function tu1($){let Y=new URL($),q=Y.pathname.match(/\/webhook\/([^/]+)/);if(!q)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:q[1]}}function au1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function eu1($,Y){if(!$.length)return;let q=new Set($.map((U)=>{let I=U.fileName.split("/")[0],Q=I.indexOf("@");return Q>=0?I.slice(0,Q):I}).filter((U)=>U!=="信息表.xlsx")),z=[];for(let U of Y){let I=U.document.documentId;if((U.documentAttachments.length>0||Object.values(U.expenseAttachments).some((K)=>K.length>0)||Object.values(U.personAttachments).some((K)=>K.length>0))&&!q.has(I))z.push(`Excel 会议编号「${I}」声明了附件,但在 ZIP 中找不到对应的根目录「${I}/」或「${I}@.../」。`)}let J=new Set(Y.map((U)=>U.document.documentId));for(let U of q)if(!J.has(U))z.push(`ZIP 根目录对应的编号「${U}」在信息表中找不到对应的会议编号。`);if(z.length)throw new N5(z)}async function $v0($,Y,q){let z=[],J=$;if(au1($,Y)){z=await HT0($),WT0(z,q);let K=z.find((G)=>G.fileName==="信息表.xlsx");if(!K)throw Error("ZIP 根目录缺少信息表.xlsx");J=await rn($,K)}let U=await MT0(J);eu1(z,U);let I=NT0(z,U),Q=U.map((K)=>K.document);return{entries:z,parsed:U,plans:I,documents:Q,fileBuffer:$}}async function Dq($,Y,q){let z=await $v0($,Y,q),J=z.parsed.map((U,I)=>Yc(U.document,z.plans[I],new Map));return{warnings:[],documents:J,attachmentPlan:z.plans}}async function RP($,Y,q){let z=await $v0($,Y,q.materialPackFilePolicy),{baseUrl:J,webhookId:U}=tu1(q.webhookUrl),I=[];for(let Q=0;Q<z.parsed.length;Q+=1){let K=z.parsed[Q],G=z.plans[Q],H=new Map,Z=[...G.categoryFields,...Object.values(G.personAttachments).flat(),...Object.values(G.expenseAttachments).flat()];for(let L of Z)for(let w of L.paths){if(H.has(w))continue;let F=z.entries.find((y)=>y.fileName===w);if(!F)continue;process.stderr.write(`⬆ 上传附件: ${w}
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:I.sso?G:H,sealResultUrl:H,ssoUrl:G,type:I.sso?"sso_link":"deep_link",expiresIn:I.sso?X:void 0,identity:Z,warning:W,enterpriseAssistUrl:J,enterpriseUrl:J,hoseDomain:Y.type==="hose"?$k1(Y.domain):void 0,documentUrl:Q,recordId:U?.id,sourceDocumentSN:U?.sourceDocumentSN,sourceDocumentId:U?.sourceDocumentId,sourceSystem:U?.sourceSystem,missing:{enterpriseAssistUrl:J?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:q&&!Q?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:V.object({query:V.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:V.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:V.string().optional().describe("模拟批次 ID"),latest:V.boolean().optional().describe("只返回最新一条匹配记录"),fields:V.union([V.string(),V.array(V.string())]).optional().describe("限制返回字段"),limit:V.number().int().positive().max(100).optional(),maxScan:V.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:V.boolean().optional()}),handler:async($,I)=>{let z=I.sn??I.query;if(!z)throw Error("query or sn is required");let q=await Ik1($,{query:z,sn:I.sn,batchId:I.batchId,latest:I.latest,limit:I.latest?1:I.limit??20,maxScan:I.maxScan??1000}),U=await Promise.all(q.records.map((Q)=>z4($,Q.id))),Y=WR0(I.fields),J=U.map((Q)=>tu1(Q,Y));return{query:z,sourceDocumentSN:I.sn,simulationBatchId:I.batchId,latest:I.latest??!1,total:q.total,scanned:q.scanned,matched:J.length,records:J,next:{getSummary:"seal-home approval-runs get <recordId> --summary",getRuleVersion:"seal-home rules version <ruleSetVersionNumber>",searchRuleVersion:`seal-hometoolseal_approval_search--json'{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","ruleVersionNumber":14}'`,getVersionContext:`seal-hometoolseal_approval_context_get--json'{"ruleVersionNumber":14}'`},...I.includeBridge?{bridge:AA(U)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:V.object({batchId:V.string().describe("simulation batch ID"),query:V.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,I)=>{let z=gp(await Nv($,I.batchId),I.query);return{batchId:I.batchId,count:z.length,records:z.map(Oz),bridge:AA(z)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:V.object({mode:V.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:V.array(V.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:V.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:V.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:V.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:V.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:V.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:V.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:V.array(V.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:V.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:V.record(V.string(),V.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:V.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:V.record(V.string(),V.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,I)=>{let z=I.mode??"hosecloud",q=I.signKey;if(z==="hosecloud"&&!q){if(q=(await Av($)).find((Q)=>Q.signKey)?.signKey,!q)throw Error("未找到合思集成 signKey, 请通过 signKey
Line truncated
`)}function Zk1($){let I=[];if(I.push(`seal-use${$.area}-${$.title}`),$.description)I.push($.description);I.push(""),I.push("Usage:");for(let z of $.commands)for(let q of z.usage)I.push(`${q}`);if($.commands.some((z)=>z.name))I.push(""),I.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return I.join(`
`)}function vR0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let I of hR0)for(let z of I.commands)for(let q of z.usage)$.push(`${q}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var hR0;var bp=e(()=>{H$();hR0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",commands:[{name:"list",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"],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"],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",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",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:"bind-test",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",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",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 version on the test enterprise. Production rules remain safe in draft state."},{name:"replay-test",summary:"Replay approval records from production enterprise to bound test enterprise via Webhook",usage:["seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"],options:[{flag:"<prodCorpId>",description:"Production enterprise ID (default: active enterprise)"},{flag:"--record-id <id>",description:"Replay a specific approval run ID"},{flag:"--sn <sn>",description:"Replay a specific document SN"},{flag:"--limit <n>",description:"Batch replay latest N records from production (default: 1)"},{flag:"--status <status>",descripti
Line truncated
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:Y.sso?H:G,sealResultUrl:G,ssoUrl:H,type:Y.sso?"sso_link":"deep_link",expiresIn:Y.sso?X:void 0,identity:Z,warning:V,enterpriseAssistUrl:I,enterpriseUrl:I,hoseDomain:U.type==="hose"?_f1(U.domain):void 0,documentUrl:Q,recordId:J?.id,sourceDocumentSN:J?.sourceDocumentSN,sourceDocumentId:J?.sourceDocumentId,sourceSystem:J?.sourceSystem,missing:{enterpriseAssistUrl:I?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:z&&!Q?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:W.object({query:W.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:W.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:W.string().optional().describe("模拟批次 ID"),latest:W.boolean().optional().describe("只返回最新一条匹配记录"),fields:W.union([W.string(),W.array(W.string())]).optional().describe("限制返回字段"),limit:W.number().int().positive().max(100).optional(),maxScan:W.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:W.boolean().optional()}),handler:async($,Y)=>{let q=Y.sn??Y.query;if(!q)throw Error("query or sn is required");let z=await Rf1($,{query:q,sn:Y.sn,batchId:Y.batchId,latest:Y.latest,limit:Y.latest?1:Y.limit??20,maxScan:Y.maxScan??1000}),J=await Promise.all(z.records.map((Q)=>e1($,Q.id))),U=Iv0(Y.fields),I=J.map((Q)=>Tf1(Q,U));return{query:q,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:z.total,scanned:z.scanned,matched:I.length,records:I,next:{getSummary:"seal-home approval-runs get <recordId> --summary",getRuleVersion:"seal-home rules version <ruleSetVersionNumber>",searchRuleVersion:`seal-hometoolseal_approval_search--json'{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","ruleVersionNumber":14}'`,getVersionContext:`seal-hometoolseal_approval_context_get--json'{"ruleVersionNumber":14}'`},...Y.includeBridge?{bridge:yP(J)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:W.object({batchId:W.string().describe("simulation batch ID"),query:W.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,Y)=>{let q=Qd(await kv($,Y.batchId),Y.query);return{batchId:Y.batchId,count:q.length,records:q.map(Aq),bridge:yP(q)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:W.object({mode:W.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:W.array(W.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:W.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:W.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:W.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:W.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:W.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:W.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:W.array(W.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:W.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:W.record(W.string(),W.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:W.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:W.record(W.string(),W.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,Y)=>{let q=Y.mode??"hosecloud",z=Y.signKey;if(q==="hosecloud"&&!z){if(z=(await fv($)).find((Q)=>Q.signKey)?.signKey,!z)throw Error("未找到合思集成 signKey, 请通过 signKey
Line truncated
`)}function ff1($){let Y=[];if(Y.push(`seal-use${$.area}-${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");for(let q of $.commands)for(let z of q.usage)Y.push(`${z}`);if($.commands.some((q)=>q.name))Y.push(""),Y.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return Y.join(`
`)}function Tv0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of Ev0)for(let q of Y.commands)for(let z of q.usage)$.push(`${z}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var Ev0;var Vd=e(()=>{V$();Ev0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",commands:[{name:"list",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"],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"],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",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",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:"bind-test",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",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",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 version on the test enterprise. Production rules remain safe in draft state."},{name:"replay-test",summary:"Replay approval records from production enterprise to bound test enterprise via Webhook",usage:["seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"],options:[{flag:"<prodCorpId>",description:"Production enterprise ID (default: active enterprise)"},{flag:"--record-id <id>",description:"Replay a specific approval run ID"},{flag:"--sn <sn>",description:"Replay a specific document SN"},{flag:"--limit <n>",description:"Batch replay latest N records from production (default: 1)"},{flag:"--status <status>",descripti
Line truncated
`}class kR{constructor($=O00.stdin,I=O00.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new uR,this._started=!1,this._ondata=(z)=>{this._readBuffer.append(z),this.processReadBuffer()},this._onerror=(z)=>{this.onerror?.(z)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((I)=>{let z=L00($);if(this._stdout.write(z))I();else this._stdout.once("drain",I)})}}S8();import{dirname as Nd,join as sf1}from"node:path";import{fileURLToPath as tf1}from"node:url";import{spawnSync as O10}from"node:child_process";var JK={name:"seal-use",version:"0.10.22",type:"module",module:"src/server.ts",bin:{"seal-use":"src/cli.ts","seal-home":"src/cli.ts"},scripts:{dev:"bun run --watch src/server.ts",start:"bun run src/server.ts",probe:"bun run src/probe.ts",cli:"bun run src/cli.ts",check:"tsc --noEmit","build:binary":"node scripts/build-binary.mjs","build:plugin":"node scripts/build-plugin.mjs",bump:"bun run scripts/bump-version.ts","dev:override":"bun run scripts/dev-override.ts","dev:link":"bun run scripts/dev-override.ts","openapi:bundle":"bun run scripts/bundle-openapi.ts","openapi:raw":"bun run scripts/generate-raw-openapi.ts",test:"bun test"},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0",archiver:"^8.0.0",exceljs:"^4.4.0","iconv-lite":"^0.7.3",ky:"^2.0.2","pinyin-pro":"^3.29.3",yauzl:"^3.4.0",zod:"^4.4.3"},devDependencies:{"@types/archiver":"^8.0.0","@types/bun":"^1.3.14","@types/yauzl":"^3.4.0","bun-types":"^1.3.14",typescript:"^5.9.3",yaml:"^2.9.0"}};function il0($,I=JK.version){let z=$.trim();if(!z)return null;let q=z.endsWith("-dirty"),U=q?z.slice(0,-6):z,Y=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);if(Y&&Y[1]&&Y[2]&&Y[3])return{baseVersion:Y[1],commitsAhead:Number.parseInt(Y[2],10),commit:Y[3],dirty:q,describe:z};let J=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/);if(J&&J[1])return{baseVersion:J[1],commitsAhead:0,commit:"",dirty:q,describe:z};let Q=U.match(/^([0-9a-f]{7,40})$/);if(Q&&Q[1])return{baseVersion:I,commitsAhead:0,commit:Q[1],dirty:q,describe:z};return null}function nl0($,I,z,q){let Y=z?`+g${z}${q?".dirty":""}`:q?"+dirty":"";return`${$}-dev.${I}${Y}`}function cl0($){let I=$?.env,z=I?.SEAL_BUILD_VERSION??process.env.SEAL_BUILD_VERSION,q=I?.SEAL_BUILD_IS_RELEASE??process.env.SEAL_BUILD_IS_RELEASE,U=I?.SEAL_BUILD_CHANNEL??process.env.SEAL_BUILD_CHANNEL,Y=I?.SEAL_BUILD_GIT_BASE??process.env.SEAL_BUILD_GIT_BASE,J=I?.SEAL_BUILD_GIT_COMMITS_AHEAD??process.env.SEAL_BUILD_GIT_COMMITS_AHEAD,Q=I?.SEAL_BUILD_GIT_COMMIT??process.env.SEAL_BUILD_GIT_COMMIT,K=I?.SEAL_BUILD_GIT_DIRTY??process.env.SEAL_BUILD_GIT_DIRTY,H=I?.SEAL_BUILD_GIT_DESCRIBE??process.env.SEAL_BUILD_GIT_DESCRIBE,G=I?.SEAL_FORCE_RELEASE??process.env.SEAL_FORCE_RELEASE,Z=$?.cwd;if(z){let W=q==="true",w={name:"seal-use",version:z,channel:U||(W?"release":"dev"),isRelease:W};if(Y)w.git={baseVersion:Y,commitsAhead:Number.parseInt(J||"0",10),commit:Q||"",dirty:K==="true",describe:H||z};return w}if(q==="true"||G==="1")return{name:"seal-use",version:JK.version,channel:"release",isRelease:!0};try{let W=O10("git",["describe","--tags","--long","--dirty","--always"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(W.status===0&&W.stdout){let X=il0(W.stdout.trim(),JK.version);if(X){if(!X.commit){let L=O10("git",["rev-parse","--short","HEAD"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(L.status===0&&L.stdout)X.commit=L.stdout.trim()}return{name:"seal-use",version:nl0(X.baseVersion,X.commitsAhead,X.commit,X.dirty),channel:"dev",isRelease:!1,git:X}}}}catch{}return{name:"seal-use",version:`${JK.version}-dev.0+local`,channel:"dev",isRelease:!1}}var QK=cl0(),q1=QK.version,Jv=QK.isRelease,gs1=QK.channel;e4();dN();lN();x4();D4();n1();S8();x4();e4();e4();GZ();Pp();D4();n1();H$();import{existsSync as fR0}from"node:fs";async function bR0($,I){if(!fR0($))throw Error(`Filenotfound:${$}`);let z=Lz($);console.log(JSON.stringify(await wz(z.fileBuffer,z.fileName,I),null,2))}async function gA($,I,z,q,U){if($==="ready"||$==="status"){let Y=I??E(U.options.file)??E(U.options.input),J=await OA(z,q,{filePath:Y,webhook:E(U.options.webhook)??E(U.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.erro
Line truncated
`}class aC{constructor($=l00.stdin,Y=l00.stdout){this._stdin=$,this._stdout=Y,this._readBuffer=new tC,this._started=!1,this._ondata=(q)=>{this._readBuffer.append(q),this.processReadBuffer()},this._onerror=(q)=>{this.onerror?.(q)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((Y)=>{let q=m00($);if(this._stdout.write(q))Y();else this._stdout.once("drain",Y)})}}b8();import{dirname as sd,join as Bi1}from"node:path";import{fileURLToPath as Ti1}from"node:url";import{spawnSync as o10}from"node:child_process";var wK={name:"seal-use",version:"0.10.24",type:"module",module:"src/server.ts",bin:{"seal-use":"src/cli.ts","seal-home":"src/cli.ts"},scripts:{dev:"bun run --watch src/server.ts",start:"bun run src/server.ts",probe:"bun run src/probe.ts",cli:"bun run src/cli.ts",check:"tsc --noEmit","build:binary":"node scripts/build-binary.mjs","build:plugin":"node scripts/build-plugin.mjs",bump:"bun run scripts/bump-version.ts","dev:override":"bun run scripts/dev-override.ts","dev:link":"bun run scripts/dev-override.ts","openapi:bundle":"bun run scripts/bundle-openapi.ts","openapi:raw":"bun run scripts/generate-raw-openapi.ts",test:"bun test"},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0",archiver:"^8.0.0",exceljs:"^4.4.0","iconv-lite":"^0.7.3",ky:"^2.0.2","pinyin-pro":"^3.29.3",yauzl:"^3.4.0",zod:"^4.4.3"},devDependencies:{"@types/archiver":"^8.0.0","@types/bun":"^1.3.14","@types/yauzl":"^3.4.0","bun-types":"^1.3.14",typescript:"^5.9.3",yaml:"^2.9.0"}};function xo0($,Y=wK.version){let q=$.trim();if(!q)return null;let z=q.endsWith("-dirty"),J=z?q.slice(0,-6):q,U=J.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);if(U&&U[1]&&U[2]&&U[3])return{baseVersion:U[1],commitsAhead:Number.parseInt(U[2],10),commit:U[3],dirty:z,describe:q};let I=J.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/);if(I&&I[1])return{baseVersion:I[1],commitsAhead:0,commit:"",dirty:z,describe:q};let Q=J.match(/^([0-9a-f]{7,40})$/);if(Q&&Q[1])return{baseVersion:Y,commitsAhead:0,commit:Q[1],dirty:z,describe:q};return null}function ko0($,Y,q,z){let U=q?`+g${q}${z?".dirty":""}`:z?"+dirty":"";return`${$}-dev.${Y}${U}`}function uo0($){let Y=$?.env,q=Y?.SEAL_BUILD_VERSION??process.env.SEAL_BUILD_VERSION,z=Y?.SEAL_BUILD_IS_RELEASE??process.env.SEAL_BUILD_IS_RELEASE,J=Y?.SEAL_BUILD_CHANNEL??process.env.SEAL_BUILD_CHANNEL,U=Y?.SEAL_BUILD_GIT_BASE??process.env.SEAL_BUILD_GIT_BASE,I=Y?.SEAL_BUILD_GIT_COMMITS_AHEAD??process.env.SEAL_BUILD_GIT_COMMITS_AHEAD,Q=Y?.SEAL_BUILD_GIT_COMMIT??process.env.SEAL_BUILD_GIT_COMMIT,K=Y?.SEAL_BUILD_GIT_DIRTY??process.env.SEAL_BUILD_GIT_DIRTY,G=Y?.SEAL_BUILD_GIT_DESCRIBE??process.env.SEAL_BUILD_GIT_DESCRIBE,H=Y?.SEAL_FORCE_RELEASE??process.env.SEAL_FORCE_RELEASE,Z=$?.cwd;if(q){let V=z==="true",L={name:"seal-use",version:q,channel:J||(V?"release":"dev"),isRelease:V};if(U)L.git={baseVersion:U,commitsAhead:Number.parseInt(I||"0",10),commit:Q||"",dirty:K==="true",describe:G||q};return L}if(z==="true"||H==="1")return{name:"seal-use",version:wK.version,channel:"release",isRelease:!0};try{let V=o10("git",["describe","--tags","--long","--dirty","--always"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(V.status===0&&V.stdout){let X=xo0(V.stdout.trim(),wK.version);if(X){if(!X.commit){let w=o10("git",["rev-parse","--short","HEAD"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(w.status===0&&w.stdout)X.commit=w.stdout.trim()}return{name:"seal-use",version:ko0(X.baseVersion,X.commitsAhead,X.commit,X.dirty),channel:"dev",isRelease:!1,git:X}}}}catch{}return{name:"seal-use",version:`${wK.version}-dev.0+local`,channel:"dev",isRelease:!1}}var FK=uo0(),Q1=FK.version,Av=FK.isRelease,Qa1=FK.channel;I6();JD();ID();p4();R4();o1();b8();p4();I6();I6();DZ();tp();R4();o1();V$();import{existsSync as gv0}from"node:fs";async function Sv0($,Y){if(!gv0($))throw Error(`Filenotfound:${$}`);let q=Pq($);console.log(JSON.stringify(await Dq(q.fileBuffer,q.fileName,Y),null,2))}async function mP($,Y,q,z,J){if($==="ready"||$==="status"){let U=Y??T(J.options.file)??T(J.options.input),I=await CP(q,z,{filePath:U,webhook:T(J.options.webhook)??T(J.options.selector)});if(console.error(`[webhook-ready]企业环境:${I.corp.name}(${I.corp.id})[${I.stateMode}]`),I.corp.tenant?.name)console.error(`[webhook-ready]租户信息:${I.corp.tenant.name}(${I.corp.tenant.id})`);console.error(`[webhook-ready]凭证状态:${I.authStatus==="ok"?"OK":`异常 (${I.authError})`}`),console.erro
Line truncated
`+`\uD83D\uDC49查看全部请添加:seal-usecorpslist--all
`+"\uD83D\uDC49 检索指定企业请使用: seal-use corps search <keyword>")}P0(F.map((D)=>({id:D.id,name:D.name,environment:D.environment??"production",sourceType:D.source.type,provider:D.source.provider??D.source.type,staffId:D.source.staffId,testCorpId:D.testCorpId,prodCorpId:D.prodCorpId,current:D.id===H})));return}if($==="get"||$==="show"){let q=I??E(z.options.corp);if(!q)throw g4("Usage: seal-use corps get <corpId>");let U=W1(q),Y=Wi(U.id),J=ok1(U);P0({id:U.id,name:U.name,environment:U.environment??"production",configFile:Y,seal:{url:J,tenantSlug:U.seal.tenantSlug??U.source.tenantSlug,customHeaderNames:U.seal.headers?Object.keys(U.seal.headers):[],customCookieNames:U.seal.cookies?Object.keys(U.seal.cookies):[],endpoints:U.seal.endpoints},source:rk1(U.source),relations:{testCorpId:U.testCorpId,prodCorpId:U.prodCorpId},auth:{refreshTtl:U.auth.refreshTtl}});return}if($==="current"){let q=W1(E(z.options.corp));P0({id:q.id,name:q.name,environment:q.environment??"production",sourceType:q.source.type,provider:q.source.provider??q.source.type,staffId:q.source.staffId,testCorpId:q.testCorpId,prodCorpId:q.prodCorpId});return}if($==="mark"||$==="mark-test"||$==="mark-prod"){let q=I??E(z.options.corp);if(!q)throw g4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");let U=W1(q),Y=$==="mark-test"?"test":$==="mark-prod"?"production":E(z.options.env)??E(z.options.environment);if(Y!=="production"&&Y!=="test")throw g4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");if(!(X0(z.options.confirm)===!0||X0(z.options.yes)===!0))throw e5(`Refusingtochangeenvironmenttagofenterprise'${U.name}'(${U.id})to'${Y}'without--confirm.Markingalterssynchronizationsafetyguards.`,`seal-usecorpsmark${U.id}--env${Y}--confirm`);let Q=m7(U.id,{environment:Y});P0({id:Q.id,name:Q.name,environment:Q.environment,testCorpId:Q.testCorpId,prodCorpId:Q.prodCorpId});return}if($==="bind-test"){let q,U;if(I&&z.command[3])q=I,U=z.command[3];else if(I){let Z=E(z.options.corp),W=E(z.options["test-corp"])??E(z.options.testCorp);if(Z)q=Z,U=I;else if(W)q=I,U=W}if(!q||!U)throw g4(`Usage:seal-usecorpsbind-test<prodCorpId><testCorpId>[--confirm][--force]
Run'seal-use corps bind-test ${U.id} <testCorpId> --confirm'firsttoestablishaverified1-to-1association.`);let Y=W1(U.testCorpId);if(Y.environment!=="test")throw Error(`Targetenterprise'${Y.name}'(${Y.id})ismarkedas'${Y.environment}',NOT'test'.Abortingsynctoprotectnon-testenvironments.`);let J=await K1(U),Q=await K1(Y),[K,H,G,Z,W,X,w,L]=await Promise.all([v1(J,U.seal.endpoints.approvalStylePreferences).catch(()=>({})),v1(Q,Y.seal.endpoints.approvalStylePreferences).catch(()=>({})),h6(J),h6(Q),N$(J).catch(()=>[]),N$(Q).catch(()=>[]),f3(J,{limit:100}).catch(()=>({articles:[]})),f3(Q,{limit:100}).catch(()=>({articles:[]}))]),O=(w.articles||[]).filter((o)=>!o.isDeleted),F=(L.articles||[]).filter((o)=>!o.isDeleted),D=new Map(F.map((o)=>[o.title.trim(),o])),P=[],A=[],T=new Set(O.map((o)=>o.title.trim()));for(let o of O){let E0=o.title.trim(),k0=D.get(E0);if(!k0)P.push(o);else{let L1=k0.content!==o.content,k4=(k0.purpose??"")!==(o.purpose??""),t4=k0.enabled!==o.enabled,Z$=k0.contentType!==o.contentType,T8=(k0.status??"")!==(o.status??""),J8=JSON.stringify([...k0.scenarios??[]].sort())!==JSON.stringify([...o.scenarios??[]].sort()),W$=JSON.stringify([...k0.tags??[]].sort())!==JSON.stringify([...o.tags??[]].sort());if(L1||k4||t4||Z$||T8||J8||W$)A.push({testId:k0.id,prodDoc:o,reasons:[...L1?["content"]:[],...k4?["purpose"]:[],...t4?["enabled"]:[],...Z$?["contentType"]:[],...T8?["status"]:[],...J8?["scenarios"]:[],...W$?["tags"]:[]]})}}let k=F.filter((o)=>!T.has(o.title.trim())),f=[...W].sort((o,E0)=>E0.versionNumber-o.versionNumber)[0],C=f?.versionNumber,i=([...X].sort((o,E0)=>E0.versionNumber-o.versionNumber)[0]?.versionNumber??0)+1,v=zh0(U.name,C,X),c=E(z.options["version-name"])??E(z.options.versionName)??qh0(U.name,C,v,i),$0={...H,tone:K.tone,language:K.language,detailLevel:K.detailLevel,outputFormat:K.outputFormat,examples:K.examples??[],prohibitedPhrases:K.prohibitedPhrases??[],customInstructions:K.customInstructions,decisionPreferences:K.decisionPreferences,thinkingDepthPreference:K.thinkingDepthPreference};if(X0(z.options["dry-run"])===!0||X0(z.options.dryRun)===!0){P0({dryRun:!0,source:{id:U.id,name:U.name,environment:U.environment,latestPublishedVersion:f?{versionNumber:f.versionNumber,versionName:f.versionName}:null,documentsCount:O.length},target:{id:Y.id,name:Y.name,environment:Y.environment},versionMappingPlan:{sourceProdVersionNumber:C??null,sourceProdVersionName:f?.versionName??null,targetTestExpectedVersionNumber:i,targetTestPublishVersionName:c,iteration:v},preferencesDiff:{decisionPreferences:{before:H.decisionPreferences,after:K.decisionPreferences},thinkingDepthPreference:{before:H.thinkingDepthPreference,after:K.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:G.rules.length,targetExistingDraftRuleCount:Z.rules.length,toDeleteCount:Z.rules.length,toCreateCount:G.rules.length,rulesToSync:G.rules.map((o,E0)=>({index:E0+1,sourceRuleId:o.id,sourceRuleCode:o.code??E0+1,expectedTargetCode:`rule-${E0+1}`,description:o.description,scope:o.scope,strictness:o.strictness}))},documentsPlan:{sourceDocumentCount:O.length,targetExistingDocumentCount:F.length,toCreateCount:P.length,toCreate:P.map((o)=>({title:o.title,purpose:o.purpose,contentType:o.contentType,scenarios:o.scenarios})),toUpdateCount:A.length,toUpdate:A.map((o)=>({targetDocumentId:o.testId,title:o.prodDoc.title,reasons:o.reasons})),toDeleteCount:k.length,toDelete:k.map((o)=>({targetDocumentId:o.id,title:o.title}))},publishingPlan:{targetCorpId:Y.id,publishVersionName:c,publishTarget:"test"},hosecloudSyncPlan:(()=>{if(U.source.type!=="hose")return{sourceType:U.source.type,skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let o=(K.integrations??[]).filter((L1)=>L1.type==="hosecloud"),E0=new Set,k0=o.filter((L1)=>{let k4=L1.corporationId??U.id;if(E0.has(k4))return!1;return E0.add(k4),!0});return{sourceType:"hose",outboundName:Hh0(U.name),targetMode:"assisted",integrationsCount:k0.length,integrations:k0.map((L1)=>({corporationId:L1.corporationId,apiOrigin:L1.apiOrigin,customApiUrl:L1.customApiUrl}))}})(),productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(X0(z.options.yes)===!0||X0(z.options.confirm)===!0))throw e5(`Refusingtooverwritetestenterprise'${Y.name}'(${Y.id})withpreferences,${G.rules.length}draftrules,and${O.length}knowledgedocumentsfromproductionenterprise'${U.name}'(${U.id})without--yes.Thiswillreplacetestdraftrules,synchronizeknowledgedocuments,andpublishanewversiononthetestenterprise.`,`seal-usecorpssync-test${U.id}--yes`);await T5(Q,$0,Y.seal.endpoints.approvalStylePreferences);let p=[];for(let o of k)await hw(Q,o.id),p.push({id:o.id,title:o.title});let s=[];for(let o of A)await vw(Q,o.testId,{title:o.prodDoc.title,purpose:o.prodDoc.purpose,content:o.prodDoc.content,contentType:o.prodDoc.contentType,status:o.prodDoc.status,enabled:o.prodDoc.enabled,scenarios:o.prodDoc.scenarios&&o.prodDoc.scenarios.le
Line truncated
Run'seal-use corps bind-test ${U.id} <testCorpId> --confirm'firsttoestablishaverified1-to-1association,
oradd'--force'(oruse'seal-use webhook replay <recordId> --force')ifyouexplicitlyintendtoreplaydirectlywithinproduction.`);J=U}else if(J=W1(U.testCorpId),J.environment!=="test"&&!Y)throw Error(`Targetenterprise'${J.name}'(${J.id})ismarkedas'${J.environment}',NOT'test'.Abortingreplaytoprotectnon-testenvironments(use--forcetooverride).`);let Q=E(z.options.recordId)??E(z.options["record-id"])??E(z.options.id),K=E(z.options.recordIds)??E(z.options["record-ids"]),H=K?K.split(",").map((i)=>i.trim()).filter(Boolean):void 0,G=E(z.options.sn)??E(z.options.documentSn)??E(z.options["document-sn"]),Z=E(z.options.sns)??E(z.options["document-sns"]),W=Z?Z.split(",").map((i)=>i.trim()).filter(Boolean):void 0,X=R0(z.options.limit)??(!Q&&!H&&!G&&!W?1:void 0),w=E(z.options.status),L=E(z.options.startDate)??E(z.options["start-date"]),O=E(z.options.endDate)??E(z.options["end-date"]),F=await K1(U),D=U.id===J.id?F:await K1(J),P=E(z.options.webhook)??E(z.options.selector),A=E(z.options.snSuffix)??E(z.options["sn-suffix"]),T=E(z.options.snPrefix)??E(z.options["sn-prefix"]),k=E(z.options.docIdSuffix)??E(z.options["doc-id-suffix"]),h=E(z.options.docIdPrefix)??E(z.options["doc-id-prefix"]),f=X0(z.options.dryRun)??X0(z.options["dry-run"]),C={recordId:Q,recordIds:H,sn:G,sns:W,limit:X,status:w,startDate:L,endDate:O};console.error(`[corps-replay-test]正式企业「${U.name}」(${U.id})->测试企业「${J.name}」(${J.id})`);let b=await vY({query:C,sourceClient:F,targetClient:D,sourceCorp:U,targetCorp:J,webhookSelector:P,snPrefix:T,snSuffix:A,docIdPrefix:h,docIdSuffix:k,dryRun:f});if(f){console.error(`[corps-replay-test]预览模式:已成功从${U.name}提取单据并转换为WebhookPayload(未实际推送)。`),console.log(JSON.stringify(b,null,2));return}if(b.success)if(b.totalCount===1&&b.replayedDocument)console.error(`\uD83D\uDFE2成功重放单据「${b.replayedDocument.documentSN}」至${J.name}(${b.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDFE2成功重放${b.successCount}条单据(来自「${U.name}」)至「${J.name}」(${b.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDD34单据重放部分或全部失败(成功${b.successCount}条,失败${b.failureCount}条)至「${J.name}」`);if(console.error(`\uD83D\uDC49Nextaction:seal-useapproval-runslist--corp${J.id}--limit${b.totalCount}`),console.log(JSON.stringify(b,null,2)),!b.success)process.exitCode=1;return}if($==="switch"){let q=I;if(!q)throw Error("Usage: seal-use corps switch <corpId>");let U=O4();if(!U.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-useconfigmodestateful` first.");let Y=W1(q);lI({...U,stateful:!0,defaultCorpId:Y.id}),P0({current:!0,id:Y.id,name:Y.name});return}if($==="probe-hose"){await tk1(P8(z.json));return}if($==="hose-staffs"){await ak1(P8(z.json));return}if($==="add-hose"){await ek1(P8(z.json));return}if($==="add-seal"){await $f1(P8(z.json));return}if($==="add-link"){let q=I??E(z.options.link)??E(z.options.url);if(!q)throw Error("Usage: seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]");await If1(q,E(z.options.name),X0(z.options.overwrite)===!0);return}throw Error(`Unknowncorpscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}function Hh0($){return[...$].slice(0,6).join("")+"(Seal测)"}async function sk1($,I,z,q){if($.source.type!=="hose")return{skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let U=($.source.appKey??$.source.key)?.trim(),Y=($.source.appSecurity??$.source.password)?.trim();if(!U||!Y)return{skipped:!0,reason:"prod hose source missing appKey/appSecurity (or key/password)"};let[J,Q]=await Promise.all([v1(z,$.seal.endpoints.approvalStylePreferences).catch(()=>({})),v1(q,I.seal.endpoints.approvalStylePreferences).catch(()=>({}))]),K=(J.integrations??[]).filter((D)=>D.type==="hosecloud");if(K.length===0)return{skipped:!0,reason:"prod Seal enterprise has no hosecloud integrations configured"};let H=new Set,G=[];for(let D of K){let P=D.corporationId??$.id;if(!H.has(P))H.add(P),G.push(D)}let Z=Q.integrations??[],W=new Map(Z.filter((D)=>D.type==="hosecloud").map((D)=>[D.corporationId,D])),X=Hh0($.name),w=[],L=G.map((D)=>{let P=W.get(D.corporationId),A=P?.signKey??lk1(6).toString("hex");return w.push({signKey:A,outboundName:X,corporationId:D.corporationId,action:P?"updated":"created"}),{type:"hosecloud",signKey:A,outboundName:X,mode:"assisted",apiKey:U,apiSecret:Y,apiOrigin:D.apiOrigin,...D.customApiUrl?{customApiUrl:D.customApiUrl}:{},corporationId:D.corporationId}}),O=Z.filter((D)=>D.type!=="hosecloud"),F={...Q,integrations:[...O,...L]};return await T5(q,F,I.seal.endpoints.approvalStylePreferences),{skipped:!1,synced:w}}async function tk1($){let I=G3($,"appKey"),z=G3($,"appSecurity"),q=l1($,"domain"),U=await Eq(I,z,q),Y=await Mw(U.domain,U.openapiToken).catch(()=>[])
Line truncated
`+"\uD83D\uDC49 检索指定企业请使用: seal-use corps search <keyword>")}E0(O.map((P)=>({id:P.id,name:P.name,environment:P.environment??"production",sourceType:P.source.type,provider:P.source.provider??P.source.type,staffId:P.source.staffId,testCorpId:P.testCorpId,prodCorpId:P.prodCorpId,current:P.id===G})));return}if($==="get"||$==="show"){let z=Y??T(q.options.corp);if(!z)throw i4("Usage: seal-use corps get <corpId>");let J=W1(z),U=bi(J.id),I=Ob1(J);E0({id:J.id,name:J.name,environment:J.environment??"production",configFile:U,seal:{url:I,tenantSlug:J.seal.tenantSlug??J.source.tenantSlug,customHeaderNames:J.seal.headers?Object.keys(J.seal.headers):[],customCookieNames:J.seal.cookies?Object.keys(J.seal.cookies):[],endpoints:J.seal.endpoints},source:Mb1(J.source),relations:{testCorpId:J.testCorpId,prodCorpId:J.prodCorpId},auth:{refreshTtl:J.auth.refreshTtl}});return}if($==="current"){let z=W1(T(q.options.corp));E0({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});return}if($==="mark"||$==="mark-test"||$==="mark-prod"){let z=Y??T(q.options.corp);if(!z)throw i4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");let J=W1(z),U=$==="mark-test"?"test":$==="mark-prod"?"production":T(q.options.env)??T(q.options.environment);if(U!=="production"&&U!=="test")throw i4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");if(!(J0(q.options.confirm)===!0||J0(q.options.yes)===!0))throw K9(`Refusingtochangeenvironmenttagofenterprise'${J.name}'(${J.id})to'${U}'without--confirm.Markingalterssynchronizationsafetyguards.`,`seal-usecorpsmark${J.id}--env${U}--confirm`);let Q=e7(J.id,{environment:U});E0({id:Q.id,name:Q.name,environment:Q.environment,testCorpId:Q.testCorpId,prodCorpId:Q.prodCorpId});return}if($==="bind-test"){let z,J;if(Y&&q.command[3])z=Y,J=q.command[3];else if(Y){let Z=T(q.options.corp),V=T(q.options["test-corp"])??T(q.options.testCorp);if(Z)z=Z,J=Y;else if(V)z=Y,J=V}if(!z||!J)throw i4(`Usage:seal-usecorpsbind-test<prodCorpId><testCorpId>[--confirm][--force]
❌未找到指定的合思OpenAPI密钥(${q.appKey??q.keyId})。`),console.error(`ℹ️该合思企业当前存在以下${$.length}套候选密钥:`);for(let U of $){let I=U.active?"\uD83D\uDFE2 启用":"⚪ 停用";console.error(`•"${U.name||"未命名应用"}"(appKey:${U.appKey},keyId:${U.id},状态:${I})`)}throw new Z4("指定的合思密钥不存在,请从上述候选列表中选择正确的 appKey 或 keyId。",2,`${z}--app-key${$[0].appKey}`)}return J}if($.length===1)return $[0];console.error(`
`);E0({provider:"hose",capability:"privilege-elevation",corpId:q.corpId,corpName:q.corpName??q.corpId,baseUrl:q.baseUrl,staffId:q.staffId,keyCount:q.keys.length,keys:q.keys.map((J)=>({id:J.id,name:J.name||"-",appKey:J.appKey,appSecurity:z?J.appSecurity:Mv(J.appSecurity),active:J.active,createTime:J.createTime,updateTime:J.updateTime}))})}async function Ed($,Y){let q=W1($),z=Y.reveal===!0;if(q.source.type!=="hose")throw new Z4(`【合思子域专享能力】当前企业「${q.name}」(id:${q.id})为原生Seal(${q.source.type})租户,非合思(Hose/合思云/易快报)渠道企业。
`);E0({provider:"hose",capability:"privilege-elevation",corpId:q.id,corpName:q.name,domain:q.source.domain,staffId:q.source.staffId,appKey:J??"-",appSecurity:U?z?U:Mv(U):"-",active:!0})}function ah0($,Y){let{token:q,sealUrl:z,expiresIn:J,verify:U,remote:I}=Y,Q=Y.custom??sh0($),K=I?.user,G=I?.tenant,H=Y4($,"tenantSlug")??W2(G?.tenantSlug),Z=Y4($,"tenantId")??W2(G?.id),V=Y4($,"tenantName")??W2(G?.name),X=Y4($,"id")??H??Z;if(!X)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let L=Y4($,"staffId")??W2(K?.providerUserId)??W2(K?.id)??"seal",w=Y4($,"provider")??W2(K?.provider)??W2(G?.providerConfig?.provider),F=Y4($,"corpId")??H??Z??X,O={id:X,name:Y4($,"name")??V??X,environment:"production",seal:{url:z,tenantSlug:H,headers:Q.headers,cookies:Q.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:q,sealUrl:z,expiresIn:J,staffId:L,corpId:F,tenantId:Z,tenantSlug:H,tenantName:V,providerUserId:W2(K?.providerUserId),provider:w},auth:{refreshTtl:300}},P=fi();dh0(P,{recursive:!0,mode:448});let B=lh0(P,`${nP(X)}.json`);if(ph0(B)&&$.overwrite!==!0)throw Error(`Enterpriseconfigalreadyexists:${B}.Pass"overwrite":truetoreplaceit.`);mh0(B,`${JSON.stringify(O,null,2)}
`,{mode:384}),E0({id:X,name:O.name,tenantId:Z,tenantSlug:H,verified:U,path:B})}async function Eb1($,Y,q={}){let z=N8($,Y,q),J=await z8(z);return{user:J.user??{},tenant:J.tenant??{}}}function W2($){return typeof $==="string"&&$?$:void 0}async function $g0($,Y){let q=$??T(Y.options.link)??T(Y.options.url);if(!q)throw Error("Usage: seal-use auth extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");let z=J0(Y.options.reveal)===!0||J0(Y.options.r)===!0||J0(Y.options.plain)===!0,J=J0(Y.options.save)===!0||J0(Y.options.add)===!0;await eP(q,{reveal:z,save:J,name:T(Y.options.name),overwrite:J0(Y.options.overwrite)===!0,force:J0(Y.options.force)===!0,appKey:T(Y.options["app-key"])??T(Y.options.appKey),keyId:T(Y.options["key-id"])??T(Y.options.keyId)})}async function Yg0($,Y,q){if($==="diagnose"){E0(await jb1(Y));return}if($==="hose-link"){let z=g0(q.options.expire)??7200;E0(await jL(Y,z));return}if($==="keys"){let z=J0(q.options.reveal)===!0||J0(q.options.r)===!0||J0(q.options.plain)===!0;await Ed(Y.id,{reveal:z});return}throw Error(`Unknownauthcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function jb1($){if($.source.type!=="hose"){let w=await Z1($),F=await z8(w);return{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:F.user,tenant:F.tenant}]}}AL($.id);let Y=$.source,q=Y.appKey??Y.key,z=Y.appSecurity??Y.password,J=($.seal.url??Y.sealUrl??`https://${Y.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/,""),U=Y.staffId.includes(":")?Y.staffId:`${Y.corpId}:${Y.staffId}`,I=[];if(!q||!z)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 Q=await $A("hose.openapi",async()=>{let w=await eh0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1/auth/getAccessToken`,{appKey:q,appSecurity:z}),F=N3(w.value),O=h6(F.accessToken)??h6(w.accessToken)??h6(w.token);if(!O)throw Error("Hose login did not return an access token");return{token:O,public:{corporationId:h6(F.corporationId)??h6(N3(F.corporation).id),expireTime:HW(F.expireTime)}}});I.push(Q.public);let K=Q.private?.token,G=K?await $A("hose.provisional",async()=>{let w=await eh0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=${encodeURIComponent(K)}`,{uid:U,pageType:"home",expireDate:7200}),F=h6(N3(w.value).message);if(!F)throw Error("Hose CloseAPI did not return a provisional auth URL");let O=new URL(F).searchParams.get("accessToken");if(!O)throw Error("Hose provisional auth URL did not include accessToken");return{token:O,public:{uid:U,enterpriseUrl:UW(F)}}}):jd("hose.provisional");I.push(G.public);let H=w6($.seal),Z=G.private?.token,V=Z?await $A("seal.sso",async()=>{let F=await N8(J,void 0,H).get(`api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(Z)}&returnToken=1`).json(),O=N3(F.data),P=h6(F.token)??h6(F.accessToken)??h6(O.token)??h6(O.accessToken);if(!P)throw Error("Seal SSO did not return a bearer token");return{token:P,public:{sealUrl:J,expiresIn:HW(F.expiresIn)??HW(F.expires_in)??HW(O.expiresIn)??HW(O.expires_in)}}}):jd("seal.sso");I.push(V.public);let X=V.private?.token,L=X?await $A("seal.whoami",async()=>{let F=await N8(J,X,H).get("api/v1/auth/me").json(),O=N3(F.data),P=N3(O.user??F.user),B=N3(O.tenant??F.tenant);return{public:{user:{id:h6(P.id),name:h6(P.name),isAdmin:Rb1(P.isAdmin),providerUserId:h6(P.providerUserId)},tenant:{id:h6(B.id),name:h6(B.name),tenantSlug:h6(B.tenantSlug),hoseCorpConfig:Cb1(B.hoseCorpConfig)}}}}):jd("seal.whoami");return I.push(L.public),{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:I.every((w)=>w.ok===!0),stages:I}}async function $A($,Y){try{let q=await Y();return{public:{name:$,ok:!0,...qg0(q.public)},private:q.token?{token:q.token}:void 0}}catch(q){return{public:{name:$,ok:!1,error:UW(q instanceof Error?q.message:String(q))}}}}function jd($){return{public:{name:$,ok:!1,skipped:!0}}}async function eh0($,Y){let q=await fetch($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Y)});return _b1(q)}async function _b1($){let Y=await $.text();if(!$.ok)throw Error(`${$.status} ${Y}`);let q=JSON.parse(Y);return N3(q)}function N3($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function h6($){return typeof $==="string"&&$?$:void 0}function HW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Rb1($){return typeof $==="boolean"?$:void 0}function Cb1($){let Y=N3($);return qg0({corporationId:h6(Y.corporationId),corporationName:h6(Y.corporationName)})}function qg0($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))}p4();o1();async function zg0($,Y,q,z){if($==="status"||$==="get"){await A0("seal_billing_status_get",Y,q,{},F0(z.options));return}if($==="plans"){await A0("seal_billing_plans_list",Y,q,{},F0(z.options));return}if($==="features"){await A0("seal_billing_features
Line truncated
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let W of Z){let X=W.outboundName??"SealAI 审批",w=W.signKey,L=W.apiOrigin??"production";console.error(`•"${X}"(signKey:${w},环境:${L})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${w}--corp${U.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let w of W){let L=w.outboundName??"SealAI 审批",O=w.signKey,F=w.apiOrigin??"production";console.error(`•"${L}"(signKey:${O},环境:${F})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${O}--corp${U.id}
`);throw new h4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,W.length===1?`seal-usedeployhosecloudsync${W[0].signKey}--corp${U.id}`:void 0)}await N0("seal_deploy_hosecloud_sync",q,U,{signKey:H},V0(Y.options));return}throw Error(`Unknowndeployhosecloudaction:${Q??""}.Available:requirements,list,get,status,configure,sync.`)}Ei();import{accessSync as Ff1,constants as Mf1,existsSync as Y8,readdirSync as Nf1}from"node:fs";import{homedir as Df1}from"node:os";import{join as W3}from"node:path";e9();import{existsSync as ap,mkdirSync as Eh0,rmSync as wf1,writeFileSync as Lf1}from"node:fs";import{homedir as jh0}from"node:os";import{dirname as Of1,join as ep}from"node:path";var wh0=`---
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let X=V.outboundName??"SealAI 审批",L=V.signKey,w=V.apiOrigin??"production";console.error(`•"${X}"(signKey:${L},环境:${w})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${L}--corp${J.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let L of V){let w=L.outboundName??"SealAI 审批",F=L.signKey,O=L.apiOrigin??"production";console.error(`•"${w}"(signKey:${F},环境:${O})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${F}--corp${J.id}
`);throw new Z4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,V.length===1?`seal-usedeployhosecloudsync${V[0].signKey}--corp${J.id}`:void 0)}await A0("seal_deploy_hosecloud_sync",z,J,{signKey:G},F0(U.options));return}throw Error(`Unknowndeployhosecloudaction:${Q??""}.Available:requirements,list,get,status,configure,sync.`)}$n();import{accessSync as mb1,constants as lb1,existsSync as X8,readdirSync as ob1}from"node:fs";import{homedir as rb1}from"node:os";import{join as D3}from"node:path";K3();import{existsSync as _d,mkdirSync as Pg0,rmSync as cb1,writeFileSync as pb1}from"node:fs";import{homedir as Ag0}from"node:os";import{dirname as db1,join as Rd}from"node:path";var Zg0=`---
name:seal-use
description:"v0.10.22: 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."
description:"v0.10.24: 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."
Usethe\`seal_cli\` MCP tool when it is available; pass the command string as its \`command\` argument. If MCP is unavailable, fall back to the global \`seal-use\` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -974,8 +988,8 @@ seal-use corps list
-TreatCLI/MCPastheAgent's execution channel, not the user'sinterface.Translatenatural-languageintentintocommandsyourself;neverasktheusertocomposeCLIsyntax,JSONpayloads,placeholdervalues,orinternalIDs.
-Beforeaskingforenterpriseparameters,resolvethetargetenterprise:whenanenterpriseisnamed,hinted,orkeyword-identifiable,ALWAYSrun\`seal-use corps search <keyword>\` (or \`seal-use corps get <corpId>\` if an exact ID is known) — DO NOT dump the entire enterprise catalog with \`seal-use corps list\` when the target is already known. Only run \`seal-use corps list\` (or \`corps list --env <test|production>\`) for initial discovery when zero enterprise context is known. Resolve its human name to the returned \`id\` and pass that value as \`--corp\`; do not ask the user to know \`corpId\`. Use \`seal-use corps get <corpId>\` to inspect rich enterprise attributes (URLs, tenant slugs, staff IDs, environment relations, and config file locations) with sensitive secrets safely redacted.
-Ifnoenterpriseisconfigured,theuserisinstallingforthefirsttime,ortheuserprovidescredentials,anassistancelink,orabrowser-copiedcURL,read\`references/enterprise-onboarding.md\` before asking questions or running setup commands.
-WhentheuserprovidesaHose/合思\`thirdparty.html\` assistance link, use \`seal-use corps add-link <url> [--name ...]\`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
-WhentheuserprovidesaHose/合思\`thirdparty.html\` assistance link, use \`seal-use corps add-link <url> [--name ...]\` for temporary session access, or elevate privileges to permanent developer credentials using \`seal-use corps extract-keys <url> --save\` (or \`seal-use corps add-link <url> --as-hose\`). This Hose-exclusive capability extracts \`appKey\`/\`appSecurity\`. If the enterprise has multiple keys, specify \`--app-key <key>\` or \`--key-id <id>\`.
-Keepenterpriseidentityoriginseparatefromcredentialacquisition.AHose/合思-sourcedSealtenantcanbeaccessedwithstandardHoseappcredentials,anassistancelink,oracapturedwebsession;receivingaSealBearertokendoesnotbyitselfprovethetenantisSeal-native.Callingkeyextractionor\`keys\` on native Seal enterprises is strictly blocked.
-Neveraskanormaluserfor\`corpId\`, \`staffId\`, \`proxyStaffBizId\`, \`tenantId\`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
-Prefercompactcommandsfirst:\`pick\`, \`--summary\`, \`--fields\`, \`attachments --summary\`, \`rules count\`, and \`rules list --summary\`.
-User-facing合思authorizationlink(合思/易快报授权):\`seal-use auth hose-link --corp <corpId> --expire 7200\`; read \`references/hose-enterprise-auth.md\`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (\`\`\`\`text ... \`\`\`\`) AND a hyperlink.
Rule,document,stylepreference,andpublishactionsmutateSealconfiguration.Makethetargetenterpriseexplicit,showtheintendedpayload,andverifyafterthewrite.Neversendreal\`enterprises/*.json\` files, tokens, signed URLs, or full raw documents to GitHub, tickets, logs, or chat unless the user explicitly requests a safe export.
`;var Lh0=`interface:
`;var Wg0=`interface:
display_name:"Seal Use"
short_description:"Diagnose approval feedback and publish minimal rule fixes"
default_prompt:"Use $seal-use to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation."
@@ -1240,7 +1258,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 Mh0="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use<command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise the user-level `~/.config/seal-use/enterprises`directoryisloaded.Aconfigured\n`testEnterprisesDir`isloadedfirstfortest-tenantworkflows.Thecurrentworkingdirectory's\n`./enterprises`directoryisnotloadedimplicitly.\n-Set`SEAL_USE_ENTERPRISES_DIR`touseoneexplicitdirectoryinstead.Legacy\n`~/.config/seal-home/enterprises`filesaremigratedtotheprimarydirectorywhenpossible.\n\nEnterpriseselectionisstatelessbydefault.Commandsthataccessanenterpriserequire\n`--corp<corpId>`unlessstatefulmodeisexplicitlyenabled:\n\n```bash\nseal-useconfigmodestateful--corp<corpId>\nseal-usecorpsswitch<corpId>\nseal-useconfigmodestateless\n```\n\nTheglobalmodeisstoredin`~/.config/seal-use/config.json`;set`SEAL_USE_CONFIG_FILE`to\noverridethatpath.Thelegacy`current-corp`fileisnotread.\n\n##Stream&ExitCodeContract\n\n-**`stdout`**:Pure,deterministicJSONformachine/Agentparsing.\n-**`stderr`**:Diagnostics,probinglogs,and**Next-StepCommandSuggestions**withthestableprefix`👉Nextaction:seal-use...`.\n-**`ExitCode`**:`0`onsuccess;`1`runtime/upstreamfailure,`2`usage/argumenterror,`10`explicitdestructive-operationconfirmationrequired,`11`missing/invalidauthentication,and`12`outputprotectionrequiringacompact/file/queryalternative.\n\n##Top-LevelCommands\n\n```bash\nseal-useversion\nseal-useconfigpaths\nseal-useconfigget\nseal-useconfigmode<stateful|stateless>[--corp<corpId>]\nseal-useconfigtest-dir[<path>|--clear]\nseal-useconfiglint<enable|disable|status>[--linter<name>][--min-score<score>]\nseal-userulescount[--corp<corpId>]\nseal-useruleslist[--summary][--count][--limit20][--offset0][--corp<corpId>]\nseal-userulesclear[--corp<corpId>][--dry-run|--yes]\nseal-userulesversions[--corp<corpId>]\nseal-userulesversion<versionId|versionNumber|latest>[--corp<corpId>]\nseal-userulesget--corp<corpId>--version<number|latest>--code'#0038'\nseal-userulesget--corp<corpId>--record-id<recordId>--runtime-idrule-205\nseal-userulessearch<keyword>[--version<versionId|versionNumber|latest>][--maxResults20][--corp<corpId>]\nseal-userulespull[--corp<corpId>][--version<id|num|latest>][--out<file>]\nseal-useruleslint[--file<path>][--corp<corpId>][--linter<name|path>][--version<num>][--code<code>][--min-score<score>][--summary]\nseal-useruleslinters[--corp<corpId>]\nseal-userulespush[--file<path>][--corp<corpId>][--publish][--version-name<name>][--dry-run|--yes]\nseal-userulesmap[--corp<corpId>][--version<id|num|latest>][--code<code>]\nseal-useservice<start|stop|restart|status|logs>[--port8787][--host127.0.0.1][--lines50]\nseal-usehttp[--port8787][--host127.0.0.1]\nseal-useserve[--port8787]\nseal-useupdate[--check][--force][--version<v>]\nseal-useupdatecheck\nseal-useupdatechangelog[--limit<n>]\nseal-usechangelog[--limit<n>]\nseal-usemcp\nseal-usemcpconfig\nseal-usemcp-config\nseal-useskilldump\nseal-useskillinstall[--dir<path>|--local]\nseal-useskillstatus\nseal-usedoctor[--quiet]\nseal-usedoctortenant[--corp<corpId>][--quiet]\nseal-usedoctorguide\nseal-usedoctorpaths\nseal-usetestregression[--corp<corpId>][--samples<N>][--dry-run][--fail-on-flips]\nseal-useprobe[<corpId>]\nseal-usetoolslist\nseal-usecorpslist[query][--env<production|test>][--limit<n>][--all][--sort<usage|name|id>][--strict][--corp<corpId>]\nseal-usecorpssearch<query>[--env<production|test>][--strict]\nseal-usecorpsget<corpId>\nseal-usecorpscurrent[--corp<corpId>]\nseal-usecorpsswitch<corpId>\nseal-usecorpsmark<corpId>--env<production|test>[--confirm]\nseal-usecorpsbind-test<prodCorpId><testCorpId>[--confirm][--force]\nseal-usecorpsunbind-test[<corpId>][--confirm]\nseal-usecorpssync-test[<prodCorpId>][--dry-run][--yes][--version-name<name>]\nseal-usecorpsreplay-test[<prodCorpId>][--record-id<id>][--sn<sn>][--limit<n>][--status<status>][--webhook<idOrName>][--sn-suffix<str>][--dry-run][--force]\nseal-usecorpsregression[--corp<corpId>][--samples<N>][--dry-run][--fail-on-flips]\nseal-usecorpsadd-hose--json'{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-usecorpsadd-seal--json'{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-usecorpsadd-link<https://.../web/thirdparty.html?...>[--name<customName>][--overwrite]\nseal-useauthdiagnose[--corp<corpId>]\nseal-useauthhose-link[--corp<corpId>][--expire7200]Line truncated
`;var Lg0="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use<command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise the user-level `~/.config/seal-use/enterprises`directoryisloaded.Aconfigured\n`testEnterprisesDir`isloadedfirstfortest-tenantworkflows.Thecurrentworkingdirectory's\n`./enterprises`directoryisnotloadedimplicitly.\n-Set`SEAL_USE_ENTERPRISES_DIR`touseoneexplicitdirectoryinstead.Legacy\n`~/.config/seal-home/enterprises`filesaremigratedtotheprimarydirectorywhenpossible.\n\nEnterpriseselectionisstatelessbydefault.Commandsthataccessanenterpriserequire\n`--corp<corpId>`unlessstatefulmodeisexplicitlyenabled:\n\n```bash\nseal-useconfigmodestateful--corp<corpId>\nseal-usecorpsswitch<corpId>\nseal-useconfigmodestateless\n```\n\nTheglobalmodeisstoredin`~/.config/seal-use/config.json`;set`SEAL_USE_CONFIG_FILE`to\noverridethatpath.Thelegacy`current-corp`fileisnotread.\n\n##Stream&ExitCodeContract\n\n-**`stdout`**:Pure,deterministicJSONformachine/Agentparsing.\n-**`stderr`**:Diagnostics,probinglogs,and**Next-StepCommandSuggestions**withthestableprefix`👉Nextaction:seal-use...`.\n-**`ExitCode`**:`0`onsuccess;`1`runtime/upstreamfailure,`2`usage/argumenterror,`10`explicitdestructive-operationconfirmationrequired,`11`missing/invalidauthentication,and`12`outputprotectionrequiringacompact/file/queryalternative.\n\n##Top-LevelCommands\n\n```bash\nseal-useversion\nseal-useconfigpaths\nseal-useconfigget\nseal-useconfigmode<stateful|stateless>[--corp<corpId>]\nseal-useconfigtest-dir[<path>|--clear]\nseal-useconfiglint<enable|disable|status>[--linter<name>][--min-score<score>]\nseal-userulescount[--corp<corpId>]\nseal-useruleslist[--summary][--count][--limit20][--offset0][--corp<corpId>]\nseal-userulesclear[--corp<corpId>][--dry-run|--yes]\nseal-userulesversions[--corp<corpId>]\nseal-userulesversion<versionId|versionNumber|latest>[--corp<corpId>]\nseal-userulesget--corp<corpId>--version<number|latest>--code'#0038'\nseal-userulesget--corp<corpId>--record-id<recordId>--runtime-idrule-205\nseal-userulessearch<keyword>[--version<versionId|versionNumber|latest>][--maxResults20][--corp<corpId>]\nseal-userulespull[--corp<corpId>][--version<id|num|latest>][--out<file>]\nseal-useruleslint[--file<path>][--corp<corpId>][--linter<name|path>][--version<num>][--code<code>][--min-score<score>][--summary]\nseal-useruleslinters[--corp<corpId>]\nseal-userulespush[--file<path>][--corp<corpId>][--publish][--version-name<name>][--dry-run|--yes]\nseal-userulesmap[--corp<corpId>][--version<id|num|latest>][--code<code>]\nseal-useservice<start|stop|restart|status|logs>[--port8787][--host127.0.0.1][--lines50]\nseal-usehttp[--port8787][--host127.0.0.1]\nseal-useserve[--port8787]\nseal-useupdate[--check][--force][--version<v>]\nseal-useupdatecheck\nseal-useupdatechangelog[--limit<n>]\nseal-usechangelog[--limit<n>]\nseal-usemcp\nseal-usemcpconfig\nseal-usemcp-config\nseal-useskilldump\nseal-useskillinstall[--dir<path>|--local]\nseal-useskillstatus\nseal-usedoctor[--quiet]\nseal-usedoctortenant[--corp<corpId>][--quiet]\nseal-usedoctorguide\nseal-usedoctorpaths\nseal-usetestregression[--corp<corpId>][--samples<N>][--dry-run][--fail-on-flips]\nseal-useprobe[<corpId>]\nseal-usetoolslist\nseal-usecorpslist[query][--env<production|test>][--limit<n>][--all][--sort<usage|name|id>][--strict][--corp<corpId>]\nseal-usecorpssearch<query>[--env<production|test>][--strict]\nseal-usecorpsget<corpId>\nseal-usecorpscurrent[--corp<corpId>]\nseal-usecorpsswitch<corpId>\nseal-usecorpsmark<corpId>--env<production|test>[--confirm]\nseal-usecorpsbind-test<prodCorpId><testCorpId>[--confirm][--force]\nseal-usecorpsunbind-test[<corpId>][--confirm]\nseal-usecorpssync-test[<prodCorpId>][--dry-run][--yes][--version-name<name>]\nseal-usecorpsreplay-test[<prodCorpId>][--record-id<id>][--sn<sn>][--limit<n>][--status<status>][--webhook<idOrName>][--sn-suffix<str>][--dry-run][--force]\nseal-usecorpsregression[--corp<corpId>][--samples<N>][--dry-run][--fail-on-flips]\nseal-usecorpsadd-hose--json'{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-usecorpsadd-seal--json'{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-usecorpsadd-link<https://.../web/thirdparty.html?...>[--name<customName>][--as-hose][--app-key<key>][--key-id<id>][--overwrite]\nseal-usecorpsextract-keys<https://.../web/thirdparLine truncated
Donotaskfor\`domain\`, \`corpId\`, or \`proxyStaffBizId\` up front. For a dedicated/private Hose deployment, add \`domain\` only after standard probing reports that it cannot find the enterprise.
-\`seal-use auth hose-link\` and \`seal-use delegation create\` generate links for an enterprise that is already configured. \`seal-use corps add-link <url>\` imports a received Hose/合思 \`thirdparty.html\` assistance link and verifies the resulting Seal tenant.
-A**Hose/合思authorization/assistancelink**(\`https://<domain>/web/thirdparty.html?...\`) opens an upstream Hose session and may continue through Seal SSO. It is not a Seal delegation link.
-**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\`. If you run standard \`corps add-link\`, it exchanges that temporary token for a short-lived Seal Bearer token—sufficient for basic Seal inspection, but it will expire and cannot call any Hose OpenAPI.
-**PrivilegeElevation(权限等级提升)**:Toelevatefromashort-livedsessiontokentopermanent,durableHoseOpenAPIdevelopercredentials,use\`corps extract-keys <url> --save\` or \`corps add-link <url> --as-hose\`. This leverages Hose's internal key interface (\`GET /api/innerapi/v1/key\`) using the session token to retrieve the enterprise's OpenAPI \`appKey\` and \`appSecurity\`. Once saved, the enterprise is upgraded to a standard Hose configuration with full OpenAPI support (e.g. \`corps sync-hosecloud\`).
-**Multi-KeyDisambiguation(多套密钥明确抉择)**:Iftheenterpriseownsmultipleapplicationkeys,theCLI**willnot**guessorsilentlypickthefirstkey.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.
UsethedirectimportroutewhentheincominglinkisanHTTPS\`thirdparty.html\` URL from a supported \`ekuaibao.com\` or \`hosecloud.com\` domain:
Thecommandparses\`accessToken\`and\`ekbCorpId\`, exchanges the temporary Hose token at the target Seal tenant, verifies \`/api/v1/auth/me\`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use \`--overwrite\` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use \`seal-use delegation create --from-link <url> [--note ...]\`.
Whenusingstandard\`add-link\`(without\`--as-hose\`), it exchanges the temporary Hose token at the target Seal tenant, verifies \`/api/v1/auth/me\`, and stores only the normalized short-lived Seal session. When \`--as-hose\` or \`extract-keys --save\` is used, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration.
-\`seal-use auth diagnose\` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
-**FormattingRequirement**:WhenreturningaHoseauthorizationlinktotheuser,ALWAYSprovideBOTHacodeblock(\`\`\`\`text ... \`\`\`\`) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
`)}D4();n1();async function uh0($,I,z){let q=($??I??"").toLowerCase();if(q==="guide"||q==="doc"||q==="knowledge"||q==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`)}R4();o1();async function gg0($,Y,q){let z=($??Y??"").toLowerCase();if(z==="guide"||z==="doc"||z==="knowledge"||z==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],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",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",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",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",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 in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{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:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{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."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{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."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{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:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{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."}],responses:{"2
Line truncated
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],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",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",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",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",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 in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{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:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{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."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{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."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{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:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{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."}],responses:{"2
Line truncated
`);U(q)})})}async function ih0($){let I=R0($.options.port)??R0($.options.p),z=E($.options.host)??E($.options.h),q=await lA({port:I,host:z}),U=()=>{q.close(()=>{process.exit(0)})};process.on("SIGINT",U),process.on("SIGTERM",U),await new Promise(()=>{})}x4();n1();async function nh0($,I,z,q){if($==="config"||$==="get"){await N0("seal_llm_config_get",I,z,{},V0(q.options));return}if($==="providers"||$==="list"){await N0("seal_llm_providers_list",I,z,{},V0(q.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}n1();async function ch0($,I){if($==="config"||$==="json"){Qd();return}await Kd()}function Qd(){P0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}n1();function ph0($){let I=nA();P0(I,{...V0($.options),allowFull:!0})}x4();n1();async function dh0($,I,z,q){if($==="available"){await N0("seal_permissions_available_list",I,z,{},V0(q.options));return}if($==="configs"||$==="list"){await N0("seal_permissions_configs_list",I,z,{},V0(q.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}x4();D4();n1();import{readFileSync as mh0}from"node:fs";async function lh0($,I,z,q,U,Y,J){if(!$||$==="get"){await N0("seal_preference_get",U,Y,{},V0(J.options));return}if($==="decision"){if(I==="update"||!I){let Q=E(J.options.input),K=Q?JSON.parse(mh0(Q,"utf8")):P8(J.json);if(!K||Object.keys(K).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await N0("seal_preference_decision_update",U,Y,{...K,dryRun:X0(J.options.dryRun)??X0(J.options["dry-run"])},V0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let Q=E(J.options.default)??E(J.options.level)??q;if(Q!=="medium"&&Q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await N0("seal_preference_thinking_depth_set",U,Y,{defaultLevel:Q,dryRun:X0(J.options.dryRun)??X0(J.options["dry-run"])},V0(J.options));return}if(I==="policies"){if(z==="list"||!z){await N0("seal_preference_thinking_depth_policies_list",U,Y,{},V0(J.options));return}if(z==="upsert"){let Q=E(J.options.input),K=Q?JSON.parse(mh0(Q,"utf8")):P8(J.json);if(!K||!K.id||!K.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await N0("seal_preference_thinking_depth_policies_upsert",U,Y,{...K,dryRun:X0(J.options.dryRun)??X0(J.options["dry-run"])},V0(J.options));return}if(z==="remove"||z==="delete"){let Q=q??E(J.options.id)??E(J.options.policyId);if(!Q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await N0("seal_preference_thinking_depth_policies_remove",U,Y,{policyId:Q,dryRun:X0(J.options.dryRun)??X0(J.options["dry-run"])},V0(J.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}e9();S8();e4();async function oh0($={}){let I=c8(),z=O4(),q=l7(I,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$.corpId},a9());console.log(`[probe]corp=${q.id}source=${q.source.type}`);let U=await LJ(q);console.log("[probe] seal enterprise"),console.log(JSON.stringify(U,null,2));let Y=await K1(q),J=await xw(Y,{documentLimit:20,stylePreferencesEndpoint:q.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))}D4();async function rh0($,I,z){let q=I??E(z.options.corp)??($&&$!=="--corp"?$:void 0);await oh0({corpId:q})}Ci();x4();H$();D4();n1();async function Hd($,I,z,q,U){if($==="count"){await N0("seal_approval_rules_list",z,q,{countOnly:!0},V0(U.options));return}if($==="list"){if(X0(U.options.count)){await N0("seal_approval_rules_list",z,q,{countOnly:!0},V0(U.options));return}let Y=R0(U.options.limit),J=R0(U.options.offset);if(X0(U.options.summary)){await N0("seal_approval_rules_list",z,q,{fields:yR0,limit:Y,offset:J},V0(U.options));return}let Q=await q2("seal_approval_rules_list",z,q,{limit:Y,offset:J});xR0(Q,X0(U.options.full)===!0),P0(Q);return}if($==="clear"){let Y=X0(U.options.yes)===!0,J=X0(U.options.dryRun)??X0(U.options["dry-run"])??!Y;if(!Y&&!J)throw e5("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${q.id}--dry-run`);let Q=await q2("seal_approval_rules_clear",z,q,{dryRun:J,recode:X0(U.options.recode)});if(!Y&&J&&Q&&typeof Q==="object"){P0({...Q,nextCommand:`seal-userulesclear--corp${q.id}--yes`},V0(U.options));return}P0(Q,V0(U.options));return}if($==="versions"){await N0("seal_approval_rule_versions_list",z,q,{},V0(U.options));return}if($==="version"){let Y=I??E(U.op
Line truncated
`).filter(Boolean),Y=U.slice(-I);return{logFile:z,lines:Y,totalLines:U.length}}async function gf1($){let I=tA($),z=Wd($),q=IW($);eh0($.stateDir);let U=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):dA),Y=$.host??(process.env.HOST?process.env.HOST:mA);rA(I,`${process.pid}
`,{mode:384}),rA(z,JSON.stringify({pid:process.pid,port:U,host:Y,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),OJ(q,`servicestartingonhttp://${Y}:${U} pid=${process.pid}`);let J=null;try{J=await lA({port:U,host:Y,silent:!0}),OJ(q,`service listening pid=${process.pid}`)}catch(K){if(OJ(q,`service failed to bind port ${U}: ${K instanceof Error?K.message:String(K)}`),sA(I)===process.pid)K9(I,{force:!0}),K9(z,{force:!0});throw K}let Q=()=>{if(J)J.close(),J=null;if(sA(I)===process.pid)K9(I,{force:!0}),K9(z,{force:!0});OJ(q,`stopped pid=${process.pid}`)};await new Promise((K)=>{let H=!1,G=()=>{if(H)return;H=!0,Q(),process.off("SIGTERM",G),process.off("SIGINT",G),K()};process.once("SIGTERM",G),process.once("SIGINT",G)})}function sh0($){eh0($.stateDir);let I=FJ($);if(I.running)return I;let z=$.launcher??{command:process.execPath,args:[$.entryFile]},q=[...z.args??[],"service","run"];if($.port)q.push("--port",String($.port));if($.host)q.push("--host",String($.host));let U=_f1(z.command,q,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});U.unref();let Y=tA($);return rA(Y,`${U.pid}
`,{flag:"a",mode:384})}n1();D4();var Xd=xf1(yf1(),".config","seal-use");async function Vd($,I,z){let q=z?R0(z.options.port)??R0(z.options.p):void 0,U=z?E(z.options.host)??E(z.options.h):void 0,Y=z?R0(z.options.lines)??R0(z.options.n):void 0,J=await Nz($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:Xd,version:q1,launcher:I.launcher,port:q,host:U},{maxLines:Y});if(J!==void 0)P0(J)}x4();D4();n1();import{existsSync as uf1,readFileSync as $g0}from"node:fs";async function Ig0($,I,z,q,U){if($==="batch-records"||$==="records"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation batch-records <batchId>");await N0("seal_simulation_batch_records_get",z,q,{batchId:Y,query:E(U.options.query)},V0(U.options));return}if($==="create"||$==="run"){let Y=E(U.options.mode)??E(U.options.sourceSystem)??E(U.options["source-system"])??"hosecloud",J=Y==="material-pack"?"material_pack":Y,Q=E(U.options.schemaConfig)??E(U.options["schema-config"]),K=Q?JSON.parse($g0(Q,"utf8")):void 0,H=E(U.options.input),G=H?JSON.parse($g0(H,"utf8")):P8(U.json),Z=E(U.options.packageId)??E(U.options["package-id"]),W=P6(U.options.packageIds)??P6(U.options["package-ids"])??(Z?[Z]:void 0),X=P6(U.options.flowIds)??P6(U.options["flow-ids"])??P6(U.options.documentSn)??P6(U.options["document-sn"]),w=E(U.options.signKey)??E(U.options["sign-key"])??E(U.options.integration),L=X0(U.options.noWait)??X0(U.options["no-wait"]);await N0("seal_simulation_batch_create",z,q,{mode:J,sourceSystem:J,flowIds:X,documentSn:X,rejectNodeName:E(U.options.rejectNode)??E(U.options["reject-node"])??null,thinkingDepthOverride:E(U.options.thinkingDepth)??E(U.options["thinking-depth"]),skipInvoiceGeneration:X0(U.options.skipInvoiceGeneration)??X0(U.options["skip-invoice-generation"]),skipExpenseExtraction:X0(U.options.skipExpenseExtraction)??X0(U.options["skip-expense-extraction"]),disableAttachmentCache:X0(U.options.disableAttachmentCache)??X0(U.options["disable-attachment-cache"]),signKey:w,packageIds:W,packageId:Z,templateId:E(U.options.templateId)??E(U.options["template-id"]),schemaConfig:K,requestIds:P6(U.options.requestIds)??P6(U.options["request-ids"]),workflowTypeId:E(U.options.workflowTypeId)??E(U.options["workflow-type-id"]),flowStatusList:P6(U.options.flowStatusList)?.map(Number)??P6(U.options["flow-status-list"])?.map(Number),businessCodes:P6(U.options.businessCodes)??P6(U.options["business-codes"]),documentType:E(U.options.documentType)??E(U.options["document-type"]),startTime:R0(U.options.startTime)??R0(U.options["start-time"]),endTime:R0(U.options.endTime)??R0(U.options["end-time"]),status:P6(U.options.status),limit:R0(U.options.limit),noWait:L,rawParams:G},V0(U.options));return}if($==="wait"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await N0("seal_simulation_batch_wait",z,q,{batchId:Y,timeout:E(U.options.timeout),pollInterval:E(U.options.pollInterval)??E(U.options["poll-interval"])},V0(U.options));return}if($==="status"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation status <batchId>");await N0("seal_simulation_batch_status",z,q,{batchId:Y},V0(U.options));return}if($==="clean"||$==="delete"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation clean <batchId>");await N0("seal_simulation_batch_clean",z,q,{batchId:Y},V0(U.options));return}if($==="specifications"){let Y=I??E(U.options.integration)??E(U.options.signKey)??E(U.options["sign-key"]);await N0("seal_simulation_specifications_list",z,q,{signKey:Y},V0(U.options));return}if($==="approval-definitions"||$==="definitions"){await N0("seal_simulation_feishu_approval_definitions_list",z,q,{},V0(U.options));return}if($==="list"){await N0("seal_simulation_batches_list",z,q,{limit:R0(U.options.limit)},V0(U.options));return}if($==="get"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation get <batchId>");await N0("seal_simulation_batch_get",z,q,{batchId:Y},V0(U.options));return}if($==="templates"){await N0("seal_simulation_templates_get",z,q,{},V0(U.options));return}if($==="integrations"){await N0("seal_simulation_integrations_get",z,q,{},V0(U.options));return}if($==="package-upload"){let Y=I??E(U.options.file);if(!Y)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!uf1(Y))throw Error(`Filenotfound:${Y}`);await N0("seal_simulation_material_package_upload",z,q,{filePath:Y},V0(U.options));return}throw Error(`Unknownsimulationcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{existsSync as zg0}from"node:fs";import{join as aA}from"node:path";D4();n1();function qg0($,I,z){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${_h0()}
`);return}if($==="install"||$==="init"||$==="sync"){let q=X0(z.options.local)||X0(z.options.workspace),U=E(z.options.dir)??E(z.options.target)??I,Y=U?U:q?aA(process.cwd(),".agents","skills","seal-use"):Mz(),J=$d(Y);P0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files});return}if($==="status"||$==="get"||!$){let q=Mz(),U=aA(process.cwd(),".agents","skills","seal-use");P0({global:{dir:q,installed:zg0(aA(q,"SKILL.md"))},local:{dir:U,installed:zg0(aA(U,"SKILL.md"))}});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}n1();async function Ug0($,I){if($==="config"){P0(await LJ(I));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}H$();x4();D4();n1();S8();H$();e4();GZ();function wd($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let I=$.toUpperCase().trim();if(I==="APPROVE"||I==="PASS")return"APPROVE";if(I==="REJECT"||I==="DENIED")return"REJECT";if(I==="MANUAL"||I==="ASSISTED")return"MANUAL";if(I==="ERROR"||I==="FAILED")return"ERROR";return I}async function Yg0($){let{sourceCorp:I,targetCorp:z,sourceClient:q,targetClient:U,samples:Y=10,dryRun:J=!1,pollIntervalMs:Q=2000,timeoutMs:K=45000,snPrefix:H="REG_",fetchFn:G=fetch}=$;if(z.environment!=="test")throw new h4(`重放目标企业「${z.name}」(${z.id})的环境为「${z.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${I.id}<testCorpId>`);let Z=await C2(U),X=(Array.isArray(Z.features)?Z.features:[]).find((u)=>u?.code==="ai-approval"),w=typeof X?.balance==="number"?X.balance:0,L=typeof X?.deductionAmount==="number"&&X.deductionAmount>0?X.deductionAmount:120,O=Y*L;if(w<O)throw new h4(`测试企业「${z.name}」AI审批额度不足:当前剩余${w}点,本次回归抽样${Y}笔需要约${O}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${z.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(w/L))})`);let F=await a4(q,{limit:Y,status:"completed"}),D=Array.isArray(F.records)?F.records:[];if(D.length===0){let u=await a4(q,{limit:Y});D=Array.isArray(u.records)?u.records:[]}if(D.length===0)throw new h4(`在母企业「${I.name}」(${I.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(D=D.slice(0,Y),J){let u=D.map((p)=>{let s=p.sourceDocumentSN??p.id,U0=p?.result?.decision??p.aiDecision??p?.decision,H0=wd(U0),D0=p?.result?.summary??p.aiSummary;return{sn:s,sourceRecordId:p.id,prodDecision:H0,prodSummary:D0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:I.id,name:I.name,environment:I.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:w,deductionAmount:L,estimatedRequired:O},metrics:{sampleCount:u.length,successCount:u.length,failureCount:0,matchCount:u.length,flipCount:0,concordanceRate:1},flips:[],records:u}}let P=await Mi(U,z),A=[];for(let u of D){let p=Date.now(),s=u.sourceDocumentSN??u.id,U0=wd(u?.result?.decision??u.aiDecision??u?.decision),H0=u?.result?.summary??u.aiSummary;try{let D0=await z4(q,u.id),_0=`${H}${s}`,Y1=Oi(D0,{snPrefix:H,docIdPrefix:H});await Fi(P.incomingDocumentWebhook.url,P.secret,Y1,G,K6(z.seal));let u0=null,r0=Date.now();while(Date.now()-r0<K){await new Promise((t4)=>setTimeout(t4,Q));let k4=await a4(U,{sourceDocumentSN:_0,limit:1});if(k4.records&&k4.records.length>0){let t4=k4.records[0];if(t4.status==="completed"||t4.status==="failed"){u0=t4;break}}}if(!u0){A.push({sn:s,sourceRecordId:u.id,prodDecision:U0,prodSummary:H0,status:"FAILED",error:`测试租户单据审核超时(${Math.round(K/1000)}s未完成)`,durationMs:Date.now()-p});continue}let I1=wd(u0?.result?.decision??u0.aiDecision??u0?.decision??(u0.status==="completed"?"APPROVE":"ERROR")),o=u0?.result?.summary??u0.aiSummary,E0=U0===I1,k0=E0?"MATCHED":"FLIPPED",L1={sn:s,sourceRecordId:u.id,prodDecision:U0,prodSummary:H0,testRecordId:u0.id,testDecision:I1,testSummary:o,status:k0,durationMs:Date.now()-p};if(!E0)L1.diff={from:U0,to:I1,reasonDiff:o&&H0&&o!==H0?`生产:${H0.slice(0,60)}...->测试:${o.slice(0,60)}...`:void 0};A.push(L1)}catch(D0){A.push({sn:s,sourceRecordId:u.id,prodDecision:U0,prodSummary:H0,status:"FAILED",error:D0 instanceof Error?D0.message:String(D0),durationMs:Date.now()-p})}}let T=A.filter((u)=>u.status==="MATCHED"||u.status==="FLIPPED"),k=A.filter((u)=>u.status==="MATCHED"),h=A.filter((u)=>u.status==="FLIPPED"),f=A.filter((u)=>u.status==="FAILED").length,C=k.length,b=h.length,i=C+b,v=i>0?C/i:0,y=b>0,c=y?"REGRESSIONS_DETECTED":"CLEAN",$0=!y&&f===0,R;try{let u=await C2(U),s=(Array.isArray(u.features)?u.features:[]).find((U0)=>U0?.code==="ai-approval");if(typeof s?.balance==="number")R=s.balance}catch{}return{ok:!y&&f===0,verdict:c,safeToPublish:$0,timestamp:new Date().toISOString(),sourceCorp:{id:I.id,name:I.name,environment:I.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:w,deductionAmount:L,estimatedRequired:O,balanceAfter:R},metrics:{sampleCount:A.length,successCount:T.length,failureCount:f,matchCount:C,flipCount:b,concordanceRate:Number(v.toFixed(4))},flips:h,records:A}}function Jg0($){let{sourceCorp:I,targetCorp:z,verdict:q,safeToPublish:U,metrics:Y,quota:J,flips:Q,records:K}=$,H=q==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":q==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",G=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${I.name}」->测试靶场「${z.name}」`,`判定:${H}·准许发布:${U?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${Y.sampleCount}|一致通过:${Y.matchCount}|决策翻转:${Y.flipCount}|异常失败:${Y.failureCount}`,`一致率:${(Y.concordanceRate*100).toFixed(1)}%|消耗预估:${J.estimatedRequired}点(余量:${J.balanceBefore}${J.balanceAfter!==void0?` -> ${J.balanceAfter}`:""})`," "+"─".repeat(65)];if(Q.length>0){G.push(`⚠️决策翻转清单(${Q.length}笔单据在新规则下结果改变):`);for(let Z of Q)if(G.push(`•单据[${Z.sn}]:原生产判定「${Z.prodDecision}」➔测试新判定「${Z.testDecision}」`),Z.diff?.reasonDiff)G.push(`理由差异:${Z.diff.reasonDiff}`);G.push(" "+"─".repeat(65)),G.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(q==="CLEAN")G.push(" ✓ 全部样本在新规则下的审核决策与生产历史 1
Line truncated
`)}async function Ld($,I,z){let q=($??I??"regression").toLowerCase();if(q==="regression"||q==="regress"||q==="matrix"){let U=E(z.options.corp)??(I&&I!==q?I:void 0),Y=W1(U),J=Y,Q=Y;if(Y.environment==="test"){Q=Y;let D=E(z.options["prod-corp"])??E(z.options.prod)??Y.prodCorpId;if(!D)throw new h4(`测试企业「${Y.name}」(${Y.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${Y.id}`);J=W1(D)}else{J=Y;let D=E(z.options["test-corp"])??E(z.options.test)??Y.testCorpId;if(!D)throw new h4(`生产企业「${Y.name}」(${Y.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Y.id}<testCorpId>`);Q=W1(D)}let K=await K1(J),H=await K1(Q),G=R0(z.options.samples)??R0(z.options.limit)??R0(z.options.n)??10,Z=X0(z.options["dry-run"]),W=X0(z.options["fail-on-flips"]),X=R0(z.options["poll-interval"])??2000,w=R0(z.options.timeout)??45000,L=E(z.options["sn-prefix"])??"REG_",O=await Yg0({sourceCorp:J,targetCorp:Q,sourceClient:K,targetClient:H,samples:G,dryRun:Z,pollIntervalMs:X,timeoutMs:w,snPrefix:L,failOnFlips:W});if(!(X0(z.options.quiet)||X0(z.options.silent)))console.error(Jg0(O));if(P0(O),W&&!O.ok)throw new h4(`回归测试发现${O.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new h4(`未知的test子命令:"${q}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}x4();D4();n1();async function Qg0($,I,z,q){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await N0($,I,z,P8(q.json),V0(q.options))}CA();n1();function Kg0(){P0(dZ.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as kf1,mkdirSync as ff1,renameSync as Od,rmSync as bf1,unlinkSync as Xg0,writeFileSync as Hg0}from"node:fs";import{dirname as if1,join as Gg0}from"node:path";import{spawnSync as Dz}from"node:child_process";function eA($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let z=$.toLowerCase().replace(/\\/g,"/");return!z.endsWith("/bun")&&!z.endsWith("/bun.exe")&&!z.endsWith("/node")&&!z.endsWith("/node.exe")}n1();var Vg0="yunyingk/seal-use",qW="yunyingk/seal-home";var nf1="SEAL_USE_GITHUB_REPO",cf1="SEAL_HOME_GITHUB_REPO";async function wg0($,I={}){let z={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Xd,version:q1,launcher:$.launcher},q=I.repo||process.env[nf1]?.trim()||process.env[cf1]?.trim()||Vg0,U=I.targetVersion?.trim(),Y=U&&U.toLowerCase()!=="latest"?U:void 0;if(Y){let A=Y.replace(/^v/,""),T=Lg0(A,q1);if(T<0)if(!Jv&&I.force);else{P0({updated:!1,currentVersion:q1,targetVersion:A,mode:eA()?"binary":"source",message:!Jv?`Cannotdowngradeseal-usefromdevbuildv${q1}toreleasev${A}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${q1}toolderversionv${A}.Updatesmustbeforward-only.`});return}if(T===0&&!I.force){P0({updated:!1,currentVersion:q1,targetVersion:A,mode:eA()?"binary":"source",message:`seal-useisalreadyatversionv${q1}.Use--forcetoreinstall.`});return}}if(I.changelogOnly){let A=await Fd(q,I.limit??10);P0({currentVersion:q1,totalQueried:A.length,releases:A.map((T)=>({version:T.version,tagName:T.tagName,publishedAt:T.publishedAt,author:T.author,releaseNotes:T.notes,releaseUrl:T.htmlUrl,isCurrent:T.version===q1,isNewer:zW(T.version,q1)}))});return}if(!eA()){if(I.checkOnly){let T=await Fd(q,30),k=T[0],h=k?.version??q1,f=T.find((i)=>i.version===q1),C=zW(h,q1),b=T.filter((i)=>zW(i.version,q1));P0({updated:!1,updateAvailable:C,currentVersion:q1,currentVersionPublishedAt:f?.publishedAt,latestVersion:h,latestVersionPublishedAt:k?.publishedAt,behindCount:b.length,pendingReleases:b.map((i)=>({version:i.version,tagName:i.tagName,publishedAt:i.publishedAt,author:i.author,releaseNotes:i.notes,releaseUrl:i.htmlUrl})),releaseNotes:k?.notes??"",releaseUrl:k?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let A=FJ(z).running;if(A)await Nz("stop",z);try{Wg0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(T){console.error(`gitpullskipped:${TinstanceofError?T.message:String(T)}`)}if(Wg0("bun",["install"],{cwd:$.appRoot}),A)await Nz("start",z);P0({updated:!0,serviceRestarted:A,version:q1,mode:"source"});return}let J=pf1(),Q=df1(),K=await Fd(q,30),H=Y?K.find((A)=>A.version===Y||A.tagName===Y||A.tagName===`v${Y}`)??await Zg0(q,Y):K[0]??await Zg0(q);if(!H){P0({updated:!1,currentVersion:q1,mode:"binary",message:`Failedtoqueryreleasesfromrepository'${q}'`});return}let G=H.version,Z=K.find((A)=>A.version===q1),W=zW(G,q1),X=W||Boolean(I.force),w=K.filter((A)=>zW(A.version,q1));if(I.checkOnly){P0({updated:!1,updateAvailable:W,currentVersion:q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:G,latestVersionPublishedAt:H.publishedAt,behindCount:w.length,pendingReleases:w.map((A)=>({version:A.version,tagName:A.tagName,publishedAt:A.publishedAt,author:A.author,releaseNotes:A.notes,releaseUrl:A.htmlUrl})),releaseNotes:H.notes,releaseUrl:H.htmlUrl,mode:"binary"});return}if(!X){P0({updated:!1,currentVersion:q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:G,latestVersionPublishedAt:H.publishedAt,mode:"binary",message:`seal-useisalreadyuptodate(v${q1})`});return}let L=mf1(H.assets,J,Q);if(!L)throw Error(`Nocompatiblebinaryfoundfor${J}-${Q}inreleasev${G}.Availableassets:${H.assets.map((A)=>A.name).join(", ")}`);let O=FJ(z).running;if(O)await Nz("stop",z);let F=process.execPath,D=if1(F),P=Gg0(D,`.tmp-update-${Date.now()}`);ff1(P,{recursive:!0});try{let A=Gg0(P,L.name);await lf1(L.downloadUrl,A,H.tagName,L.name);let T=A;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))T=of1(A,P,J);else if(L.name.endsWith(".zip"))T=rf1(A,P,J);if(kf1(T,493),process.platform==="darwin")try{Dz("/usr/bin/codesign",["--remove-signature",T],{stdio:"ignore"}),Dz("/usr/bin/codesign",["--force","--sign","-",T],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let h=`${F}.old.${Date.now()}`;try{Od(F,h)}catch{}Od(T,F)}else Od(T,F);if(O)await Nz("start",z);let k=Id();P0({updated:!0,fromVersion:q1,toVersion:G,serviceRestarted:O,skillSynced:k.synced?k.targetDir:!1,mode:"binary"})}finally{try{bf1(P,{recursive:!0,force:!0})}catch{}}}function pf1(){if(process.platform==="darwin")retur
Line truncated
`)}catch{}}async function lf1($,I,z,q){let U=Md(),Y=[],J=z?z.startsWith("v")?z:`v${z}`:void 0,Q=q||$.split("/").pop()||"";if(U!=="github"){if(J&&Q)Y.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${J}/${Q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${J}/${Q}`);if($.startsWith("https://git.ying-qing.cn"))Y.push($)}if(U!=="gitea")if(J&&Q){let L=`https://github.com/${Vg0}/releases/download/${J}/${Q}`;if(!process.env.CI)Y.push(`https://ghfast.top/${L}`,`https://gh.ddlc.top/${L}`);Y.push(L)}else if($.includes("github.com")){if(!process.env.CI)Y.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Y.push($)}else Y.push($);let K=Array.from(new Set(Y)),H,G=6000,Z=6000,W=307200,X=1e4,w=180000;for(let L=0;L<K.length;L++){let O=K[L],F=new AbortController,D="",P=(h)=>{D=h;try{F.abort()}catch{}},A=setTimeout(()=>{P("Connection timed out (no response headers within 6s)")},G),T,k;try{$P(`==> [${L+1}/${K.length}] Downloading via: ${O}`);let h=await fetch(O,{signal:F.signal});if(A)clearTimeout(A),A=void 0;if(!h.ok)throw Error(`HTTP ${h.status} ${h.statusText}`);T=setTimeout(()=>{P("Overall download time exceeded 3 minutes")},w);let f=Number(h.headers.get("content-length"))||0,C=h.body?.getReader();if(!C){let c=Buffer.from(await h.arrayBuffer());if(c.length<1000)throw Error(`Downloaded content is suspiciously small (${c.length} bytes)`);Hg0(I,c),$P(`✓ Download succeeded (${(c.length/1024/1024).toFixed(1)} MB)`);return}let b=[],i=0,v=0;k=setTimeout(()=>{if(i<W){let c=(i/1024).toFixed(1);P(`Initial transfer too slow (${c} KB < 300 KB in 6s), switching mirror...`)}},Z);while(!0){let c=C.read(),$0,R=new Promise((U0,H0)=>{$0=setTimeout(()=>{H0(Error("Data transfer stalled (no chunk received for 10s)"))},X)}),u;try{u=await Promise.race([c,R])}finally{if($0)clearTimeout($0)}let{done:p,value:s}=u;if(p)break;if(s){if(b.push(s),i+=s.length,k&&i>=W)clearTimeout(k),k=void 0;let U0=Date.now();if(U0-v>200){v=U0;let H0=f?Math.round(i/f*100):0,D0=(i/1048576).toFixed(1),_0=f?(f/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${H0}% (${D0} / ${_0} MB)...`)}catch{}}}}try{process.stderr.write(`
`);J(z)})})}async function kg0($){let Y=g0($.options.port)??g0($.options.p),q=T($.options.host)??T($.options.h),z=await QA({port:Y,host:q}),J=()=>{z.close(()=>{process.exit(0)})};process.on("SIGINT",J),process.on("SIGTERM",J),await new Promise(()=>{})}p4();o1();async function ug0($,Y,q,z){if($==="config"||$==="get"){await A0("seal_llm_config_get",Y,q,{},F0(z.options));return}if($==="providers"||$==="list"){await A0("seal_llm_providers_list",Y,q,{},F0(z.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}o1();async function fg0($,Y){if($==="config"||$==="json"){kd();return}await ud()}function kd(){E0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}o1();function bg0($){let Y=qA();E0(Y,{...F0($.options),allowFull:!0})}p4();o1();async function ig0($,Y,q,z){if($==="available"){await A0("seal_permissions_available_list",Y,q,{},F0(z.options));return}if($==="configs"||$==="list"){await A0("seal_permissions_configs_list",Y,q,{},F0(z.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}p4();R4();o1();import{readFileSync as ng0}from"node:fs";async function cg0($,Y,q,z,J,U,I){if(!$||$==="get"){await A0("seal_preference_get",J,U,{},F0(I.options));return}if($==="decision"){if(Y==="update"||!Y){let Q=T(I.options.input),K=Q?JSON.parse(ng0(Q,"utf8")):C8(I.json);if(!K||Object.keys(K).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await A0("seal_preference_decision_update",J,U,{...K,dryRun:J0(I.options.dryRun)??J0(I.options["dry-run"])},F0(I.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let Q=T(I.options.default)??T(I.options.level)??z;if(Q!=="medium"&&Q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await A0("seal_preference_thinking_depth_set",J,U,{defaultLevel:Q,dryRun:J0(I.options.dryRun)??J0(I.options["dry-run"])},F0(I.options));return}if(Y==="policies"){if(q==="list"||!q){await A0("seal_preference_thinking_depth_policies_list",J,U,{},F0(I.options));return}if(q==="upsert"){let Q=T(I.options.input),K=Q?JSON.parse(ng0(Q,"utf8")):C8(I.json);if(!K||!K.id||!K.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await A0("seal_preference_thinking_depth_policies_upsert",J,U,{...K,dryRun:J0(I.options.dryRun)??J0(I.options["dry-run"])},F0(I.options));return}if(q==="remove"||q==="delete"){let Q=z??T(I.options.id)??T(I.options.policyId);if(!Q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await A0("seal_preference_thinking_depth_policies_remove",J,U,{policyId:Q,dryRun:J0(I.options.dryRun)??J0(I.options["dry-run"])},F0(I.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}K3();b8();I6();async function pg0($={}){let Y=r8(),q=T4(),z=$2(Y,{stateful:q.stateful,defaultCorpId:q.defaultCorpId,corpId:$.corpId},Q3());console.log(`[probe]corp=${z.id}source=${z.source.type}`);let J=await jI(z);console.log("[probe] seal enterprise"),console.log(JSON.stringify(J,null,2));let U=await Z1(z),I=await dL(U,{documentLimit:20,stylePreferencesEndpoint:z.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))}R4();async function dg0($,Y,q){let z=Y??T(q.options.corp)??($&&$!=="--corp"?$:void 0);await pg0({corpId:z})}qn();p4();V$();R4();o1();async function fd($,Y,q,z,J){if($==="count"){await A0("seal_approval_rules_list",q,z,{countOnly:!0},F0(J.options));return}if($==="list"){if(J0(J.options.count)){await A0("seal_approval_rules_list",q,z,{countOnly:!0},F0(J.options));return}let U=g0(J.options.limit),I=g0(J.options.offset);if(J0(J.options.summary)){await A0("seal_approval_rules_list",q,z,{fields:Rv0,limit:U,offset:I},F0(J.options));return}let Q=await H2("seal_approval_rules_list",q,z,{limit:U,offset:I});Cv0(Q,J0(J.options.full)===!0),E0(Q);return}if($==="clear"){let U=J0(J.options.yes)===!0,I=J0(J.options.dryRun)??J0(J.options["dry-run"])??!U;if(!U&&!I)throw K9("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${z.id}--dry-run`);let Q=await H2("seal_approval_rules_clear",q,z,{dryRun:I,recode:J0(J.options.recode)});if(!U&&I&&Q&&typeof Q==="object"){E0({...Q,nextCommand:`seal-userulesclear--corp${z.id}--yes`},F0(J.options));return}E0(Q,F0(J.options));return}if($==="versions"){await A0("seal_approval_rule_versions_list",q,z,{},F0(J.options));return}if($==="version"){let U=Y??T(J.op
Line truncated
`).filter(Boolean),U=J.slice(-Y);return{logFile:q,lines:U,totalLines:J.length}}async function Qi1($){let Y=ZA($),q=nd($),z=WW($);rg0($.stateDir);let J=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):UA),U=$.host??(process.env.HOST?process.env.HOST:IA);GA(Y,`${process.pid}
`,{mode:384}),GA(q,JSON.stringify({pid:process.pid,port:J,host:U,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),_I(z,`servicestartingonhttp://${U}:${J} pid=${process.pid}`);let I=null;try{I=await QA({port:J,host:U,silent:!0}),_I(z,`service listening pid=${process.pid}`)}catch(K){if(_I(z,`service failed to bind port ${J}: ${K instanceof Error?K.message:String(K)}`),HA(Y)===process.pid)F9(Y,{force:!0}),F9(q,{force:!0});throw K}let Q=()=>{if(I)I.close(),I=null;if(HA(Y)===process.pid)F9(Y,{force:!0}),F9(q,{force:!0});_I(z,`stopped pid=${process.pid}`)};await new Promise((K)=>{let G=!1,H=()=>{if(G)return;G=!0,Q(),process.off("SIGTERM",H),process.off("SIGINT",H),K()};process.once("SIGTERM",H),process.once("SIGINT",H)})}function mg0($){rg0($.stateDir);let Y=RI($);if(Y.running)return Y;let q=$.launcher??{command:process.execPath,args:[$.entryFile]},z=[...q.args??[],"service","run"];if($.port)z.push("--port",String($.port));if($.host)z.push("--host",String($.host));let J=zi1(q.command,z,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});J.unref();let U=ZA($);return GA(U,`${J.pid}
`,{flag:"a",mode:384})}o1();R4();var cd=Hi1(Gi1(),".config","seal-use");async function pd($,Y,q){let z=q?g0(q.options.port)??g0(q.options.p):void 0,J=q?T(q.options.host)??T(q.options.h):void 0,U=q?g0(q.options.lines)??g0(q.options.n):void 0,I=await Eq($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:cd,version:Q1,launcher:Y.launcher,port:z,host:J},{maxLines:U});if(I!==void 0)E0(I)}p4();R4();o1();import{existsSync as Zi1,readFileSync as sg0}from"node:fs";async function tg0($,Y,q,z,J){if($==="batch-records"||$==="records"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation batch-records <batchId>");await A0("seal_simulation_batch_records_get",q,z,{batchId:U,query:T(J.options.query)},F0(J.options));return}if($==="create"||$==="run"){let U=T(J.options.mode)??T(J.options.sourceSystem)??T(J.options["source-system"])??"hosecloud",I=U==="material-pack"?"material_pack":U,Q=T(J.options.schemaConfig)??T(J.options["schema-config"]),K=Q?JSON.parse(sg0(Q,"utf8")):void 0,G=T(J.options.input),H=G?JSON.parse(sg0(G,"utf8")):C8(J.json),Z=T(J.options.packageId)??T(J.options["package-id"]),V=v6(J.options.packageIds)??v6(J.options["package-ids"])??(Z?[Z]:void 0),X=v6(J.options.flowIds)??v6(J.options["flow-ids"])??v6(J.options.documentSn)??v6(J.options["document-sn"]),L=T(J.options.signKey)??T(J.options["sign-key"])??T(J.options.integration),w=J0(J.options.noWait)??J0(J.options["no-wait"]);await A0("seal_simulation_batch_create",q,z,{mode:I,sourceSystem:I,flowIds:X,documentSn:X,rejectNodeName:T(J.options.rejectNode)??T(J.options["reject-node"])??null,thinkingDepthOverride:T(J.options.thinkingDepth)??T(J.options["thinking-depth"]),skipInvoiceGeneration:J0(J.options.skipInvoiceGeneration)??J0(J.options["skip-invoice-generation"]),skipExpenseExtraction:J0(J.options.skipExpenseExtraction)??J0(J.options["skip-expense-extraction"]),disableAttachmentCache:J0(J.options.disableAttachmentCache)??J0(J.options["disable-attachment-cache"]),signKey:L,packageIds:V,packageId:Z,templateId:T(J.options.templateId)??T(J.options["template-id"]),schemaConfig:K,requestIds:v6(J.options.requestIds)??v6(J.options["request-ids"]),workflowTypeId:T(J.options.workflowTypeId)??T(J.options["workflow-type-id"]),flowStatusList:v6(J.options.flowStatusList)?.map(Number)??v6(J.options["flow-status-list"])?.map(Number),businessCodes:v6(J.options.businessCodes)??v6(J.options["business-codes"]),documentType:T(J.options.documentType)??T(J.options["document-type"]),startTime:g0(J.options.startTime)??g0(J.options["start-time"]),endTime:g0(J.options.endTime)??g0(J.options["end-time"]),status:v6(J.options.status),limit:g0(J.options.limit),noWait:w,rawParams:H},F0(J.options));return}if($==="wait"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await A0("seal_simulation_batch_wait",q,z,{batchId:U,timeout:T(J.options.timeout),pollInterval:T(J.options.pollInterval)??T(J.options["poll-interval"])},F0(J.options));return}if($==="status"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation status <batchId>");await A0("seal_simulation_batch_status",q,z,{batchId:U},F0(J.options));return}if($==="clean"||$==="delete"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation clean <batchId>");await A0("seal_simulation_batch_clean",q,z,{batchId:U},F0(J.options));return}if($==="specifications"){let U=Y??T(J.options.integration)??T(J.options.signKey)??T(J.options["sign-key"]);await A0("seal_simulation_specifications_list",q,z,{signKey:U},F0(J.options));return}if($==="approval-definitions"||$==="definitions"){await A0("seal_simulation_feishu_approval_definitions_list",q,z,{},F0(J.options));return}if($==="list"){await A0("seal_simulation_batches_list",q,z,{limit:g0(J.options.limit)},F0(J.options));return}if($==="get"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation get <batchId>");await A0("seal_simulation_batch_get",q,z,{batchId:U},F0(J.options));return}if($==="templates"){await A0("seal_simulation_templates_get",q,z,{},F0(J.options));return}if($==="integrations"){await A0("seal_simulation_integrations_get",q,z,{},F0(J.options));return}if($==="package-upload"){let U=Y??T(J.options.file);if(!U)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!Zi1(U))throw Error(`Filenotfound:${U}`);await A0("seal_simulation_material_package_upload",q,z,{filePath:U},F0(J.options));return}throw Error(`Unknownsimulationcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{existsSync as ag0}from"node:fs";import{join as WA}from"node:path";R4();o1();function eg0($,Y,q){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${Tg0()}
`);return}if($==="install"||$==="init"||$==="sync"){let z=J0(q.options.local)||J0(q.options.workspace),J=T(q.options.dir)??T(q.options.target)??Y,U=J?J:z?WA(process.cwd(),".agents","skills","seal-use"):Tq(),I=Cd(U);E0({installed:!0,targetDir:I.targetDir,fileCount:I.files.length,files:I.files});return}if($==="status"||$==="get"||!$){let z=Tq(),J=WA(process.cwd(),".agents","skills","seal-use");E0({global:{dir:z,installed:ag0(WA(z,"SKILL.md"))},local:{dir:J,installed:ag0(WA(J,"SKILL.md"))}});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}o1();async function $S0($,Y){if($==="config"){E0(await jI(Y));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}V$();p4();R4();o1();b8();V$();I6();DZ();function dd($){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 YS0($){let{sourceCorp:Y,targetCorp:q,sourceClient:z,targetClient:J,samples:U=10,dryRun:I=!1,pollIntervalMs:Q=2000,timeoutMs:K=45000,snPrefix:G="REG_",fetchFn:H=fetch}=$;if(q.environment!=="test")throw new Z4(`重放目标企业「${q.name}」(${q.id})的环境为「${q.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Y.id}<testCorpId>`);let Z=await g2(J),X=(Array.isArray(Z.features)?Z.features:[]).find((u)=>u?.code==="ai-approval"),L=typeof X?.balance==="number"?X.balance:0,w=typeof X?.deductionAmount==="number"&&X.deductionAmount>0?X.deductionAmount:120,F=U*w;if(L<F)throw new Z4(`测试企业「${q.name}」AI审批额度不足:当前剩余${L}点,本次回归抽样${U}笔需要约${F}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${q.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(L/w))})`);let O=await x4(z,{limit:U,status:"completed"}),P=Array.isArray(O.records)?O.records:[];if(P.length===0){let u=await x4(z,{limit:U});P=Array.isArray(u.records)?u.records:[]}if(P.length===0)throw new Z4(`在母企业「${Y.name}」(${Y.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(P=P.slice(0,U),I){let u=P.map((p)=>{let d=p.sourceDocumentSN??p.id,q0=p?.result?.decision??p.aiDecision??p?.decision,t=dd(q0),H0=p?.result?.summary??p.aiSummary;return{sn:d,sourceRecordId:p.id,prodDecision:t,prodSummary:H0,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:q.id,name:q.name,environment:q.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:L,deductionAmount:w,estimatedRequired:F},metrics:{sampleCount:u.length,successCount:u.length,failureCount:0,matchCount:u.length,flipCount:0,concordanceRate:1},flips:[],records:u}}let B=await li(J,q),A=[];for(let u of P){let p=Date.now(),d=u.sourceDocumentSN??u.id,q0=dd(u?.result?.decision??u.aiDecision??u?.decision),t=u?.result?.summary??u.aiSummary;try{let H0=await e1(z,u.id),L0=`${G}${d}`,T0=di(H0,{snPrefix:G,docIdPrefix:G});await mi(B.incomingDocumentWebhook.url,B.secret,T0,H,w6(q.seal));let C0=null,j0=Date.now();while(Date.now()-j0<K){await new Promise((a0)=>setTimeout(a0,Q));let C1=await x4(J,{sourceDocumentSN:L0,limit:1});if(C1.records&&C1.records.length>0){let a0=C1.records[0];if(a0.status==="completed"||a0.status==="failed"){C0=a0;break}}}if(!C0){A.push({sn:d,sourceRecordId:u.id,prodDecision:q0,prodSummary:t,status:"FAILED",error:`测试租户单据审核超时(${Math.round(K/1000)}s未完成)`,durationMs:Date.now()-p});continue}let i0=dd(C0?.result?.decision??C0.aiDecision??C0?.decision??(C0.status==="completed"?"APPROVE":"ERROR")),K0=C0?.result?.summary??C0.aiSummary,v0=q0===i0,f0=v0?"MATCHED":"FLIPPED",c0={sn:d,sourceRecordId:u.id,prodDecision:q0,prodSummary:t,testRecordId:C0.id,testDecision:i0,testSummary:K0,status:f0,durationMs:Date.now()-p};if(!v0)c0.diff={from:q0,to:i0,reasonDiff:K0&&t&&K0!==t?`生产:${t.slice(0,60)}...->测试:${K0.slice(0,60)}...`:void 0};A.push(c0)}catch(H0){A.push({sn:d,sourceRecordId:u.id,prodDecision:q0,prodSummary:t,status:"FAILED",error:H0 instanceof Error?H0.message:String(H0),durationMs:Date.now()-p})}}let E=A.filter((u)=>u.status==="MATCHED"||u.status==="FLIPPED"),y=A.filter((u)=>u.status==="MATCHED"),v=A.filter((u)=>u.status==="FLIPPED"),k=A.filter((u)=>u.status==="FAILED").length,C=y.length,c=v.length,n=C+c,g=n>0?C/n:0,b=c>0,i=b?"REGRESSIONS_DETECTED":"CLEAN",$0=!b&&k===0,j;try{let u=await g2(J),d=(Array.isArray(u.features)?u.features:[]).find((q0)=>q0?.code==="ai-approval");if(typeof d?.balance==="number")j=d.balance}catch{}return{ok:!b&&k===0,verdict:i,safeToPublish:$0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:q.id,name:q.name,environment:q.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:L,deductionAmount:w,estimatedRequired:F,balanceAfter:j},metrics:{sampleCount:A.length,successCount:E.length,failureCount:k,matchCount:C,flipCount:c,concordanceRate:Number(g.toFixed(4))},flips:v,records:A}}function qS0($){let{sourceCorp:Y,targetCorp:q,verdict:z,safeToPublish:J,metrics:U,quota:I,flips:Q,records:K}=$,G=z==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":z==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",H=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${Y.name}」->测试靶场「${q.name}」`,`判定:${G}·准许发布:${J?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${U.sampleCount}|一致通过:${U.matchCount}|决策翻转:${U.flipCount}|异常失败:${U.failureCount}`,`一致率:${(U.concordanceRate*100).toFixed(1)}%|消耗预估:${I.estimatedRequired}点(余量:${I.balanceBefore}${I.balanceAfter!==void0?` -> ${I.balanceAfter}`:""})`," "+"─".repeat(65)];if(Q.length>0){H.push(`⚠️决策翻转清单(${Q.length}笔单据在新规则下结果改变):`);for(let Z of Q)if(H.push(`•单据[${Z.sn}]:原生产判定「${Z.prodDecision}」➔测试新判定「${Z.testDecision}」`),Z.diff?.reasonDiff)H.push(`理由差异:${Z.diff.reasonDiff}`);H.push(" "+"─".repeat(65)),H.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(z==="CLEAN")H.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100%
Line truncated
`)}async function md($,Y,q){let z=($??Y??"regression").toLowerCase();if(z==="regression"||z==="regress"||z==="matrix"){let J=T(q.options.corp)??(Y&&Y!==z?Y:void 0),U=W1(J),I=U,Q=U;if(U.environment==="test"){Q=U;let P=T(q.options["prod-corp"])??T(q.options.prod)??U.prodCorpId;if(!P)throw new Z4(`测试企业「${U.name}」(${U.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${U.id}`);I=W1(P)}else{I=U;let P=T(q.options["test-corp"])??T(q.options.test)??U.testCorpId;if(!P)throw new Z4(`生产企业「${U.name}」(${U.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${U.id}<testCorpId>`);Q=W1(P)}let K=await Z1(I),G=await Z1(Q),H=g0(q.options.samples)??g0(q.options.limit)??g0(q.options.n)??10,Z=J0(q.options["dry-run"]),V=J0(q.options["fail-on-flips"]),X=g0(q.options["poll-interval"])??2000,L=g0(q.options.timeout)??45000,w=T(q.options["sn-prefix"])??"REG_",F=await YS0({sourceCorp:I,targetCorp:Q,sourceClient:K,targetClient:G,samples:H,dryRun:Z,pollIntervalMs:X,timeoutMs:L,snPrefix:w,failOnFlips:V});if(!(J0(q.options.quiet)||J0(q.options.silent)))console.error(qS0(F));if(E0(F),V&&!F.ok)throw new Z4(`回归测试发现${F.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new Z4(`未知的test子命令:"${z}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}p4();R4();o1();async function zS0($,Y,q,z){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await A0($,Y,q,C8(z.json),F0(z.options))}iP();o1();function JS0(){E0(qW.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as Wi1,mkdirSync as Xi1,renameSync as ld,rmSync as Vi1,unlinkSync as GS0,writeFileSync as US0}from"node:fs";import{dirname as Li1,join as IS0}from"node:path";import{spawnSync as jq}from"node:child_process";function XA($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let q=$.toLowerCase().replace(/\\/g,"/");return!q.endsWith("/bun")&&!q.endsWith("/bun.exe")&&!q.endsWith("/node")&&!q.endsWith("/node.exe")}o1();var HS0="yunyingk/seal-use",VW="yunyingk/seal-home";var wi1="SEAL_USE_GITHUB_REPO",Fi1="SEAL_HOME_GITHUB_REPO";async function ZS0($,Y={}){let q={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:cd,version:Q1,launcher:$.launcher},z=Y.repo||process.env[wi1]?.trim()||process.env[Fi1]?.trim()||HS0,J=Y.targetVersion?.trim(),U=J&&J.toLowerCase()!=="latest"?J:void 0;if(U){let A=U.replace(/^v/,""),E=WS0(A,Q1);if(E<0)if(!Av&&Y.force);else{E0({updated:!1,currentVersion:Q1,targetVersion:A,mode:XA()?"binary":"source",message:!Av?`Cannotdowngradeseal-usefromdevbuildv${Q1}toreleasev${A}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${Q1}toolderversionv${A}.Updatesmustbeforward-only.`});return}if(E===0&&!Y.force){E0({updated:!1,currentVersion:Q1,targetVersion:A,mode:XA()?"binary":"source",message:`seal-useisalreadyatversionv${Q1}.Use--forcetoreinstall.`});return}}if(Y.changelogOnly){let A=await od(z,Y.limit??10);E0({currentVersion:Q1,totalQueried:A.length,releases:A.map((E)=>({version:E.version,tagName:E.tagName,publishedAt:E.publishedAt,author:E.author,releaseNotes:E.notes,releaseUrl:E.htmlUrl,isCurrent:E.version===Q1,isNewer:XW(E.version,Q1)}))});return}if(!XA()){if(Y.checkOnly){let E=await od(z,30),y=E[0],v=y?.version??Q1,k=E.find((n)=>n.version===Q1),C=XW(v,Q1),c=E.filter((n)=>XW(n.version,Q1));E0({updated:!1,updateAvailable:C,currentVersion:Q1,currentVersionPublishedAt:k?.publishedAt,latestVersion:v,latestVersionPublishedAt:y?.publishedAt,behindCount:c.length,pendingReleases:c.map((n)=>({version:n.version,tagName:n.tagName,publishedAt:n.publishedAt,author:n.author,releaseNotes:n.notes,releaseUrl:n.htmlUrl})),releaseNotes:y?.notes??"",releaseUrl:y?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let A=RI(q).running;if(A)await Eq("stop",q);try{KS0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(E){console.error(`gitpullskipped:${EinstanceofError?E.message:String(E)}`)}if(KS0("bun",["install"],{cwd:$.appRoot}),A)await Eq("start",q);E0({updated:!0,serviceRestarted:A,version:Q1,mode:"source"});return}let I=Oi1(),Q=Mi1(),K=await od(z,30),G=U?K.find((A)=>A.version===U||A.tagName===U||A.tagName===`v${U}`)??await QS0(z,U):K[0]??await QS0(z);if(!G){E0({updated:!1,currentVersion:Q1,mode:"binary",message:`Failedtoqueryreleasesfromrepository'${z}'`});return}let H=G.version,Z=K.find((A)=>A.version===Q1),V=XW(H,Q1),X=V||Boolean(Y.force),L=K.filter((A)=>XW(A.version,Q1));if(Y.checkOnly){E0({updated:!1,updateAvailable:V,currentVersion:Q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:H,latestVersionPublishedAt:G.publishedAt,behindCount:L.length,pendingReleases:L.map((A)=>({version:A.version,tagName:A.tagName,publishedAt:A.publishedAt,author:A.author,releaseNotes:A.notes,releaseUrl:A.htmlUrl})),releaseNotes:G.notes,releaseUrl:G.htmlUrl,mode:"binary"});return}if(!X){E0({updated:!1,currentVersion:Q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:H,latestVersionPublishedAt:G.publishedAt,mode:"binary",message:`seal-useisalreadyuptodate(v${Q1})`});return}let w=Ni1(G.assets,I,Q);if(!w)throw Error(`Nocompatiblebinaryfoundfor${I}-${Q}inreleasev${H}.Availableassets:${G.assets.map((A)=>A.name).join(", ")}`);let F=RI(q).running;if(F)await Eq("stop",q);let O=process.execPath,P=Li1(O),B=IS0(P,`.tmp-update-${Date.now()}`);Xi1(B,{recursive:!0});try{let A=IS0(B,w.name);await Di1(w.downloadUrl,A,G.tagName,w.name);let E=A;if(w.name.endsWith(".tar.gz")||w.name.endsWith(".tgz"))E=Pi1(A,B,I);else if(w.name.endsWith(".zip"))E=Ai1(A,B,I);if(Wi1(E,493),process.platform==="darwin")try{jq("/usr/bin/codesign",["--remove-signature",E],{stdio:"ignore"}),jq("/usr/bin/codesign",["--force","--sign","-",E],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let v=`${O}.old.${Date.now()}`;try{ld(O,v)}catch{}ld(E,O)}else ld(E,O);if(F)await Eq("start",q);let y=vd();E0({updated:!0,fromVersion:Q1,toVersion:H,serviceRestarted:F,skillSynced:y.synced?y.targetDir:!1,mode:"binary"})}finally{try{Vi1(B,{recursive:!0,force:!0})}catch{}}}function Oi1(){if(process.platform==="darwin")retur
Line truncated
`)}catch{}}async function Di1($,Y,q,z){let J=rd(),U=[],I=q?q.startsWith("v")?q:`v${q}`:void 0,Q=z||$.split("/").pop()||"";if(J!=="github"){if(I&&Q)U.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${I}/${Q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${I}/${Q}`);if($.startsWith("https://git.ying-qing.cn"))U.push($)}if(J!=="gitea")if(I&&Q){let w=`https://github.com/${HS0}/releases/download/${I}/${Q}`;if(!process.env.CI)U.push(`https://ghfast.top/${w}`,`https://gh.ddlc.top/${w}`);U.push(w)}else if($.includes("github.com")){if(!process.env.CI)U.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);U.push($)}else U.push($);let K=Array.from(new Set(U)),G,H=6000,Z=6000,V=307200,X=1e4,L=180000;for(let w=0;w<K.length;w++){let F=K[w],O=new AbortController,P="",B=(v)=>{P=v;try{O.abort()}catch{}},A=setTimeout(()=>{B("Connection timed out (no response headers within 6s)")},H),E,y;try{VA(`==> [${w+1}/${K.length}] Downloading via: ${F}`);let v=await fetch(F,{signal:O.signal});if(A)clearTimeout(A),A=void 0;if(!v.ok)throw Error(`HTTP ${v.status} ${v.statusText}`);E=setTimeout(()=>{B("Overall download time exceeded 3 minutes")},L);let k=Number(v.headers.get("content-length"))||0,C=v.body?.getReader();if(!C){let i=Buffer.from(await v.arrayBuffer());if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);US0(Y,i),VA(`✓ Download succeeded (${(i.length/1024/1024).toFixed(1)} MB)`);return}let c=[],n=0,g=0;y=setTimeout(()=>{if(n<V){let i=(n/1024).toFixed(1);B(`Initial transfer too slow (${i} KB < 300 KB in 6s), switching mirror...`)}},Z);while(!0){let i=C.read(),$0,j=new Promise((q0,t)=>{$0=setTimeout(()=>{t(Error("Data transfer stalled (no chunk received for 10s)"))},X)}),u;try{u=await Promise.race([i,j])}finally{if($0)clearTimeout($0)}let{done:p,value:d}=u;if(p)break;if(d){if(c.push(d),n+=d.length,y&&n>=V)clearTimeout(y),y=void 0;let q0=Date.now();if(q0-g>200){g=q0;let t=k?Math.round(n/k*100):0,H0=(n/1048576).toFixed(1),L0=k?(k/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${t}% (${H0} / ${L0} MB)...`)}catch{}}}}try{process.stderr.write(`
"description":"Planned HTTP contract for the seal-use wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-use is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
description:"v0.10.22: 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."
description:"v0.10.24: 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."
metadata:
version:0.10.22
short-description:Seal tenant and Hose approval automation (v0.10.22)
version:0.10.24
short-description:Seal tenant and Hose approval automation (v0.10.24)
---
# Seal Use (v0.10.22)
# Seal Use (v0.10.24)
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-use` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -43,8 +43,9 @@ seal-use corps list
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
- Before asking for enterprise parameters, resolve the target enterprise: when an enterprise is named, hinted, or keyword-identifiable, ALWAYS run `seal-use corps search <keyword>` (or `seal-use corps get <corpId>` if an exact ID is known) — DO NOT dump the entire enterprise catalog with `seal-use corps list` when the target is already known. Only run `seal-use corps list` (or `corps list --env <test|production>`) for initial discovery when zero enterprise context is known. Resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`. Use `seal-use corps get <corpId>` to inspect rich enterprise attributes (URLs, tenant slugs, staff IDs, environment relations, and config file locations) with sensitive secrets safely redacted.
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read `references/enterprise-onboarding.md` before asking questions or running setup commands.
- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link <url> [--name ...]`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
-Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link <url> [--name ...]` for temporary session access, or elevate privileges to permanent developer credentials using `seal-use corps extract-keys <url> --save` (or `seal-use corps add-link <url> --as-hose`). This Hose-exclusive capability extracts `appKey`/`appSecurity`. If the enterprise has multiple keys, specify `--app-key <key>` or `--key-id <id>`.
-**同等凭据原则(Equal Credential Scope Principle)**: A Hose assistance link and a cURL copied from an authenticated **Hose admin** page are both Hose web frontend sessions — structurally different in format only, carrying the same `accesstoken`/`corpid` web session credentials. **When a Hose administrator provides a browser cURL, do NOT silently downgrade it to a plain short-lived session import.** Attempt privilege elevation first by extracting `accesstoken`+`corpid`+`baseUrl` from the cURL and invoking the Hose key interface (`/api/innerapi/v1/key`) to retrieve permanent `appKey`/`appSecurity`. Only fall back to temporary session import if the user is not a Hose administrator or the key interface returns no keys.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native. Calling key extraction or `keys` on native Seal enterprises is strictly blocked.
- Never ask a normal user for `corpId`, `staffId`, `proxyStaffBizId`, `tenantId`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
- User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp <corpId> --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
seal-use corps regression [--corp <corpId>][--samples <N>][--dry-run][--fail-on-flips]
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 <https://.../web/thirdparty.html?...> [--name <customName>][--overwrite]
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>][--as-hose][--app-key <key>][--key-id <id>][--overwrite]
seal-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal][--save][--name <customName>][--app-key <key>][--key-id <id>][--overwrite]
seal-use corps keys [<url> | <corpId>][--reveal][--save][--app-key <key>][--key-id <id>]
@@ -203,7 +210,10 @@ Enterprise and tenant management:
-`seal-use corps get <corpId>` (rich enterprise attributes with sensitive secrets safely redacted)
-`seal-use corps current [--corp <corpId>]`
-`seal-use corps switch <corpId>`
-`seal-use auth diagnose --corp <corpId>`
-`seal-use corps extract-keys <url> [--reveal] [--save] [--name <name>] [--app-key <key>] [--key-id <id>] [--overwrite]` extracts OpenAPI keys (`appKey` and `appSecurity`) from a Hose assistance link (`thirdparty.html`). **Hose Subdomain Privilege Elevation**: elevates a short-lived session token to permanent Hose OpenAPI developer credentials. If `--save` is specified, registers the enterprise as a durable Hose tenant. If the enterprise has multiple keys, execution halts and candidates are listed unless `--app-key` or `--key-id` is passed.
-`seal-use corps add-link <url> [--name <name>] [--as-hose] [--app-key <key>] [--key-id <id>] [--overwrite]` imports a Hose assistance link. Without `--as-hose`, creates a temporary Seal Bearer session. With `--as-hose`, elevates permissions by extracting Hose OpenAPI developer keys and saving a durable Hose enterprise configuration.
-`seal-use corps keys [<url> | <corpId>] [--reveal] [--save]` reads/displays OpenAPI keys for a Hose assistance link or configured Hose enterprise (masked by default, `--reveal` displays plaintext). Rejects non-Hose/native-Seal tenants with exit code 2.
-`seal-use auth extract-keys <url>` and `seal-use auth keys [--corp <corpId>]` provide auth-domain aliases for key extraction and inspection.
@@ -34,13 +34,16 @@ All command examples in this reference are for the Agent to run. Do not hand the
Classify both the enterprise identity origin and how the current credential was acquired:
| Enterprise identity origin | Credential material the user may have | Meaning |
| --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |
| 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 |
| 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 `corps sync-hosecloud`. |
| 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 | 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. |
**同等凭据原则(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.
Do not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.
First distinguish the link by its host and purpose:
First distinguish the link by its host, purpose, and identity origin:
- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.
-`seal-use auth hose-link` and `seal-use delegation create` generate links for an enterprise that is already configured. `seal-use corps add-link <url>` imports a received Hose/合思 `thirdparty.html` assistance link and verifies the resulting Seal tenant.
- A **Hose/合思 authorization/assistance link** (`https://<domain>/web/thirdparty.html?...`) opens an upstream Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A **Seal-native assistance/delegation link** grants temporary delegated access on a Seal tenant. It is not a Hose credential and cannot be elevated to Hose OpenAPI credentials.
-**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`. If you run standard `corps add-link`, it exchanges that temporary token for a short-lived Seal Bearer token—sufficient for basic Seal inspection, but it will expire and cannot call any Hose OpenAPI.
- **Privilege Elevation (权限等级提升)**: To elevate from a short-lived session token to permanent, durable Hose OpenAPI developer credentials, use `corps extract-keys <url> --save` or `corps add-link <url> --as-hose`. This leverages Hose's internal key interface (`GET /api/innerapi/v1/key`) using the session token to retrieve the enterprise's OpenAPI `appKey` and `appSecurity`. Once saved, the enterprise is upgraded to a standard Hose configuration with full OpenAPI support (e.g. `corps sync-hosecloud`).
- **Multi-Key Disambiguation (多套密钥明确抉择)**: If the 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.
Use the direct import route when the incoming link is an HTTPS `thirdparty.html` URL from a supported `ekuaibao.com` or `hosecloud.com` domain:
### Command Usage
```bash
seal-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home"[--name "企业名称"]
# 1. 提取密钥并脱敏查看(合思子域能力):
seal-use corps extract-keys "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..."
# 2. 显式完整查看密钥明文(--reveal / -r):
seal-use corps extract-keys "<url>" --reveal
# 3. 提权保存为标准持久化合思企业配置:
seal-use corps extract-keys "<url>" --save [--name "企业名称"][--overwrite]
# 或简写为:
seal-use corps add-link "<url>" --as-hose [--name "企业名称"]
# 4. 多套密钥存在时,显式指定具体应用密钥:
seal-use corps extract-keys "<url>" --save --app-key "ekb_app_..."
# 或按 key ID 选取:
seal-use corps extract-keys "<url>" --save --key-id "key_id_..."
# 5. 查看已配置合思企业当前使用的应用密钥:
seal-use corps keys <corpId> [--reveal]
seal-use auth keys --corp <corpId> [--reveal]
```
The command parses `accessToken` and `ekbCorpId`, exchanges the temporary Hose token at the target Seal tenant, verifies `/api/v1/auth/me`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use `--overwrite` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use `seal-use delegation create --from-link <url> [--note ...]`.
When using standard `add-link` (without `--as-hose`), it exchanges the temporary Hose token at the target Seal tenant, verifies `/api/v1/auth/me`, and stores only the normalized short-lived Seal session. When `--as-hose` or `extract-keys --save` is used, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration.
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.
@@ -103,21 +127,51 @@ When the user needs capture instructions, give these concrete steps:
6. Right-click it and choose **Copy → Copy as cURL**.
7. Send that complete cURL only to the local trusted Agent handling setup.
When receiving cURL:
When receiving cURL, immediately classify its origin before deciding on an action path:
### 3a. cURL from an authenticated Hose page (合思/易快报 后台)
This is functionally equivalent to a Hose assistance link. Both carry the same underlying web session credentials (`accesstoken`, `corpid`/`ekbCorpId`, and cookies). The structural difference is only in delivery format.
**Always attempt privilege elevation first when the session user is or may be a Hose administrator:**
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. Parse it as data. Extract the request host, path, `Authorization` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3.Classify whether the captured request is to Hose or Seal. A Seal request with `Authorization: Bearer ...` can supply `sealUrl` and a session token even when the user's identity origin is Hose.
4.Verify with the narrowest read-only identity endpoint available. For a Seal Bearer session, verify `/api/v1/auth/me` through `seal-use corps add-seal`; use returned provider metadata to retain the actual origin.
5.Persist only the normalized minimum configuration needed by seal-use. Do not preserve the raw cURL, unrelated headers, request body, cookies, or signed URL.
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 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.
5.If key extraction succeeds, inform the user that credentials have been permanently elevated; if it fails, explain the limitation and suggest theadministrator copy a dedicated cURL or provide an assistance link or `appKey`/`appSecurity`.
For a verified Seal Bearer captured from cURL, the existing CLI route is:
### 3b. cURL from an authenticated Seal page (Seal 后台)
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.
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>"}'
```
The current CLI has no raw-cURL import command and `add-seal` requires a Bearer token. 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.
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.
summary:"Export approval run audit records to Excel workbook. Add --with-flow to include E人工行为 / E人工意见 columns (requires Hose Open API; adds ~30s for large batches).",
{flag:"--sn, --sns <SNs>",description:"Target specific document SNs (comma-separated, e.g. B26002307,B26002144); fast indexed search bypassing full pagination"},
{flag:"--with-flow",description:"Enrich export with Hose human actions and opinions in E人工行为 / E人工意见 columns (rejection 2-B, mid-flow modifications, action emojis)"},
{flag:"--start <date>",description:"Filter records by start date (YYYY-MM-DD or ms timestamp)"},
{flag:"--end <date>",description:"Filter records by end date (YYYY-MM-DD or ms timestamp)"},
{flag:"--force",description:"Force export when time range exceeds 180 days"},
{flag:"--status <status>",description:"Filter by system status (e.g. completed, processing)"},
{flag:"--manual-status <status>",description:"Filter by manual approval status (e.g. APPROVED, TERMINATED)"},
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.