@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.10.19] - 2026-09-13
### Added & Enhanced
- **Smart Insights Full Suite & Multi-Sheet Excel Export**:
- Implemented complete Smart Insights analytics suite: `seal-use analytics risks` (risk tag frequency and interception trends), `seal-use analytics performance` (Sankey review throughput, adoption rates, avg duration), `seal-use analytics analyze` (on-demand rule/document risk diagnosis), and `seal-use analytics insight` (overview metrics).
- Added multi-sheet Excel export CLI `seal-use analytics export` (aliases: `report`, `download`) and MCP tool `seal_insight_export`. Generates styled `.xlsx` reports with 3 dedicated sheets (`审核效能与决策流向`, `Top 风险标签分析`, `风险单据穿透明细`), supporting `--downloads` to system downloads directory and custom `--out` paths.
- **Rule Linter Directory Restructuring & Official Isolation**:
- Structured `~/.config/seal-use/linters/` for custom user linters while isolating official linters in `~/.config/seal-use/linters/official/`.
- Added plaintext sync mechanism (`syncOfficialLinters`): writes human- and Agent-readable TypeScript source files (`builtin.ts` and `strict.ts`) with types and JSDoc, overwrites user modifications unconditionally, and prunes rogue files in `official/`.
- Added `strict.ts` linter: enforces quantitative boundaries (amounts, days, strict limits), catches vague expressions, errors on hanging exceptions without required notes/attachments, and enforces concrete approver roles.
- Added CLI `seal-use rules linters` to inspect available linters and updated `seal-use doctor paths` with `officialLintersDir`.
- **Unified Seal Backend HTTP Client & Enterprise Context Injection**:
- Enhanced `createSealClientForUrl` in `src/core/http/factory.ts` with optional Bearer token support, allowing pre-auth endpoints (SSO exchange, OAuth2 session, whoami) to use the unified client without sending invalid Authorization headers.
- Unified all outbound Seal backend HTTP calls across `auth.ts`, `corps.ts`, `hose.ts`, `api.ts`, `webhook-replay.ts`, and `material-pack/service.ts`, ensuring enterprise custom headers (`corp.seal.headers`) and gateway cookies (`corp.seal.cookies`) are consistently injected.
import{createRequireasVO0}from"node:module";varUO0=Object.create;var{getPrototypeOf:YO0,defineProperty:FO,getOwnPropertyNames:JO0}=Object;varQO0=Object.prototype.hasOwnProperty;functionwO0($){returnthis[$]}varKO0,HO0,jI=($,I,q)=>{varz=$!=null&&typeof$==="object";if(z){varU=I?KO0??=newWeakMap:HO0??=newWeakMap,Y=U.get($);if(Y)returnY}q=$!=null?UO0(YO0($)):{};letJ=I||!$||!$.__esModule?FO(q,"default",{value:$,enumerable:!0}):q;for(letQofJO0($))if(!QO0.call(J,Q))FO(J,Q,{get:wO0.bind($,Q),enumerable:!0});if(z)U.set($,J);returnJ};varF=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);varGO0=($)=>$;functionWO0($,I){this[$]=GO0.bind(null,I)}varU5=($,I)=>{for(varqinI)FO($,q,{get:I[q],enumerable:!0,configurable:!0,set:WO0.bind(I,q)})};vart=VO0(import.meta.url);vartY=F((cn)=>{Object.defineProperty(cn,"__esModule",{value:!0});cn.regexpCode=cn.getEsmExportName=cn.getProperty=cn.safeStringify=cn.stringify=cn.strConcat=cn.addCodeArg=cn.str=cn._=cn.nil=cn._Code=cn.Name=cn.IDENTIFIER=cn._CodeOrName=void0;classeH{}cn._CodeOrName=eH;cn.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;classGqextendseH{constructor($){super();if(!cn.IDENTIFIER.test($))throwError("CodeGen: name must be a valid identifier");this.str=$}toString(){returnthis.str}emptyStr(){return!1}getnames(){return{[this.str]:1}}}cn.Name=Gq;classa$extendseH{constructor($){super();this._items=typeof$==="string"?[$]:$}toString(){returnthis.str}emptyStr(){if(this._items.length>1)return!1;let$=this._items[0];return$===""||$==='""'}getstr(){var$;return($=this._str)!==null&&$!==void0?$:this._str=this._items.reduce((I,q)=>`${I}${q}`,"")}getnames(){var$;return($=this._names)!==null&&$!==void0?$:this._names=this._items.reduce((I,q)=>{if(qinstanceofGq)I[q.str]=(I[q.str]||0)+1;returnI},{})}}cn._Code=a$;cn.nil=newa$("");functionbn($,...I){letq=[$[0]],z=0;while(z<I.length)_T(q,I[z]),q.push($[++z]);returnnewa$(q)}cn._=bn;varCT=newa$("+");functionpn($,...I){letq=[rY($[0])],z=0;while(z<I.length)q.push(CT),_T(q,I[z]),q.push(CT,rY($[++z]));returnSA0(q),newa$(q)}cn.str=pn;function_T($,I){if(Iinstanceofa$)$.push(...I._items);elseif(IinstanceofGq)$.push(I);else$.push(xA0(I))}cn.addCodeArg=_T;functionSA0($){letI=1;while(I<$.length-1){if($[I]===CT){letq=uA0($[I-1],$[I+1]);if(q!==void0){$.splice(I-1,3,q);continue}$[I++]="+"}I++}}functionuA0($,I){if(I==='""')return$;if($==='""')returnI;if(typeof$=="string"){if(IinstanceofGq||$[$.length-1]!=='"')return;if(typeofI!="string")return`${$.slice(0,-1)}${I}"`;if(I[0]==='"')return$.slice(0,-1)+I.slice(1);return}if(typeofI=="string"&&I[0]==='"'&&!($instanceofGq))return`"${$}${I.slice(1)}`;return}functionyA0($,I){returnI.emptyStr()?$:$.emptyStr()?I:pn`${$}${I}`}cn.strConcat=yA0;functionxA0($){returntypeof$=="number"||typeof$=="boolean"||$===null?$:rY(Array.isArray($)?$.join(","):$)}functionkA0($){returnnewa$(rY($))}cn.stringify=kA0;functionrY($){returnJSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}cn.safeStringify=rY;functionfA0($){returntypeof$=="string"&&cn.IDENTIFIER.test($)?newa$(`.${$}`):bn`[${$}]`}cn.getProperty=fA0;functionnA0($){if(typeof$=="string"&&cn.IDENTIFIER.test($))returnnewa$(`${$}`);throwError(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}cn.getEsmExportName=nA0;functionbA0($){returnnewa$($.toString())}cn.regexpCode=bA0});varyT=F((on)=>{Object.defineProperty(on,"__esModule",{value:!0});on.ValueScope=on.ValueScopeName=on.Scope=on.varKinds=on.UsedValueState=void0;vard6=tY();classmnextendsError{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}varIG;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(IG||(on.UsedValueState=IG={}));on.varKinds={const:newd6.Name("const"),let:newd6.Name("let"),var:newd6.Name("var")};classST{constructor({prefixes:$,parent:I}={}){this._names={},this._prefixes=$,this._parent=I}toName($){return$instanceofd6.Name?$:this.name($)}name($){returnnewd6.Name(this._newName($))}_newName($){letI=this._names[$]||this._nameGroup($);return`${$}${I.index++}`}_nameGroup($){varI,q;if(((q=(I=this._parent)===null||I===void0?void0:I._prefixes)===null||q===void0?void0:q.has($))||this._prefixes&&!this._prefixes.has($))throwError(`CodeGen: prefix "${$}" is not allowed in this scope`);returnthis._names[$]={prefix:$,index:0}}}on.Scope=ST;classuTextendsd6.Name{constructor($,I){super(I);this.prefix=$}setValue($,{property:I,itemIndex:q}){this.value=$,this.scopePath=d6._`.${newd6.Name(I)}[${q}]`}}on.ValueScopeName=uT;var$P0=d6._`\n`;classlnextendsST{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?$P0:d6.nil}}get(){returnthis._scope}name($){returnnewuT($,this._newName($))}value($,I){varq;if(I.ref===void0)throwError("CodeGen: ref must be passed in value");letz=this.toName($),{prefix:U}=z,Y=(q=I.key)!==null&&q!==void0?q:I.ref,J=this._values[U];if(J){letK=J.get(Y);if(Line truncated
import{createRequireasCO0}from"node:module";varPO0=Object.create;var{getPrototypeOf:TO0,defineProperty:hO,getOwnPropertyNames:EO0}=Object;varBO0=Object.prototype.hasOwnProperty;functionjO0($){returnthis[$]}varvO0,RO0,b7=($,I,z)=>{varq=$!=null&&typeof$==="object";if(q){varU=I?vO0??=newWeakMap:RO0??=newWeakMap,Y=U.get($);if(Y)returnY}z=$!=null?PO0(TO0($)):{};letJ=I||!$||!$.__esModule?hO(z,"default",{value:$,enumerable:!0}):z;for(letQofEO0($))if(!BO0.call(J,Q))hO(J,Q,{get:jO0.bind($,Q),enumerable:!0});if(q)U.set($,J);returnJ};varF=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);vargO0=($)=>$;function_O0($,I){this[$]=gO0.bind(null,I)}varw5=($,I)=>{for(varzinI)hO($,z,{get:I[z],enumerable:!0,configurable:!0,set:_O0.bind(I,z)})};vart=CO0(import.meta.url);varIJ=F(($n)=>{Object.defineProperty($n,"__esModule",{value:!0});$n.regexpCode=$n.getEsmExportName=$n.getProperty=$n.safeStringify=$n.stringify=$n.strConcat=$n.addCodeArg=$n.str=$n._=$n.nil=$n._Code=$n.Name=$n.IDENTIFIER=$n._CodeOrName=void0;classUH{}$n._CodeOrName=UH;$n.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;classXzextendsUH{constructor($){super();if(!$n.IDENTIFIER.test($))throwError("CodeGen: name must be a valid identifier");this.str=$}toString(){returnthis.str}emptyStr(){return!1}getnames(){return{[this.str]:1}}}$n.Name=Xz;classI8extendsUH{constructor($){super();this._items=typeof$==="string"?[$]:$}toString(){returnthis.str}emptyStr(){if(this._items.length>1)return!1;let$=this._items[0];return$===""||$==='""'}getstr(){var$;return($=this._str)!==null&&$!==void0?$:this._str=this._items.reduce((I,z)=>`${I}${z}`,"")}getnames(){var$;return($=this._names)!==null&&$!==void0?$:this._names=this._items.reduce((I,z)=>{if(zinstanceofXz)I[z.str]=(I[z.str]||0)+1;returnI},{})}}$n._Code=I8;$n.nil=newI8("");functionsb($,...I){letz=[$[0]],q=0;while(q<I.length)mT(z,I[q]),z.push($[++q]);returnnewI8(z)}$n._=sb;vardT=newI8("+");functioneb($,...I){letz=[$J($[0])],q=0;while(q<I.length)z.push(dT),mT(z,I[q]),z.push(dT,$J($[++q]));returneA0(z),newI8(z)}$n.str=eb;functionmT($,I){if(IinstanceofI8)$.push(...I._items);elseif(IinstanceofXz)$.push(I);else$.push(zP0(I))}$n.addCodeArg=mT;functioneA0($){letI=1;while(I<$.length-1){if($[I]===dT){letz=$P0($[I-1],$[I+1]);if(z!==void0){$.splice(I-1,3,z);continue}$[I++]="+"}I++}}function$P0($,I){if(I==='""')return$;if($==='""')returnI;if(typeof$=="string"){if(IinstanceofXz||$[$.length-1]!=='"')return;if(typeofI!="string")return`${$.slice(0,-1)}${I}"`;if(I[0]==='"')return$.slice(0,-1)+I.slice(1);return}if(typeofI=="string"&&I[0]==='"'&&!($instanceofXz))return`"${$}${I.slice(1)}`;return}functionIP0($,I){returnI.emptyStr()?$:$.emptyStr()?I:eb`${$}${I}`}$n.strConcat=IP0;functionzP0($){returntypeof$=="number"||typeof$=="boolean"||$===null?$:$J(Array.isArray($)?$.join(","):$)}functionqP0($){returnnewI8($J($))}$n.stringify=qP0;function$J($){returnJSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$n.safeStringify=$J;functionUP0($){returntypeof$=="string"&&$n.IDENTIFIER.test($)?newI8(`.${$}`):sb`[${$}]`}$n.getProperty=UP0;functionYP0($){if(typeof$=="string"&&$n.IDENTIFIER.test($))returnnewI8(`${$}`);throwError(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}$n.getEsmExportName=YP0;functionJP0($){returnnewI8($.toString())}$n.regexpCode=JP0});vartT=F((Un)=>{Object.defineProperty(Un,"__esModule",{value:!0});Un.ValueScope=Un.ValueScopeName=Un.Scope=Un.varKinds=Un.UsedValueState=void0;varo6=IJ();classznextendsError{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}varJH;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(JH||(Un.UsedValueState=JH={}));Un.varKinds={const:newo6.Name("const"),let:newo6.Name("let"),var:newo6.Name("var")};classoT{constructor({prefixes:$,parent:I}={}){this._names={},this._prefixes=$,this._parent=I}toName($){return$instanceofo6.Name?$:this.name($)}name($){returnnewo6.Name(this._newName($))}_newName($){letI=this._names[$]||this._nameGroup($);return`${$}${I.index++}`}_nameGroup($){varI,z;if(((z=(I=this._parent)===null||I===void0?void0:I._prefixes)===null||z===void0?void0:z.has($))||this._prefixes&&!this._prefixes.has($))throwError(`CodeGen: prefix "${$}" is not allowed in this scope`);returnthis._names[$]={prefix:$,index:0}}}Un.Scope=oT;classrTextendso6.Name{constructor($,I){super(I);this.prefix=$}setValue($,{property:I,itemIndex:z}){this.value=$,this.scopePath=o6._`.${newo6.Name(I)}[${z}]`}}Un.ValueScopeName=rT;varFP0=o6._`\n`;classqnextendsoT{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?FP0:o6.nil}}get(){returnthis._scope}name($){returnnewrT($,this._newName($))}value($,I){varz;if(I.ref===void0)throwError("CodeGen: ref must be passed in value");letq=this.toName($),{prefix:U}=q,Y=(z=I.key)!==null&&z!==void0?z:I.ref,J=this._values[U];if(J){letw=J.get(Y);if(Line truncated
deps:${q}}`};var Qv0={keyword:"dependencies",type:"object",schemaType:"object",error:Kc.error,code($){let[I,q]=wv0($);Qc($,I),wc($,q)}};function wv0({schema:$}){let I={},q={};for(let z in $){if(z==="__proto__")continue;let U=Array.isArray($[z])?I:q;U[z]=$[z]}return[I,q]}function Qc($,I=$.schema){let{gen:q,data:z,it:U}=$;if(Object.keys(I).length===0)return;let Y=q.let("missing");for(let J in I){let Q=I[J];if(Q.length===0)continue;let w=(0,XJ.propertyInData)(q,z,J,U.opts.ownProperties);if($.setParams({property:J,depsCount:Q.length,deps:Q.join(", ")}),U.allErrors)q.if(w,()=>{for(let K of Q)(0,XJ.checkReportMissingProp)($,K)});else q.if(NE._`${w}&&(${(0,XJ.checkMissingProp)($,Q,Y)})`),(0,XJ.reportMissingProp)($,Y),q.else()}}Kc.validatePropertyDeps=Qc;function wc($,I=$.schema){let{gen:q,data:z,keyword:U,it:Y}=$,J=q.name("valid");for(let Q in I){if((0,Jv0.alwaysValidSchema)(Y,I[Q]))continue;q.if((0,XJ.propertyInData)(q,z,Q,Y.opts.ownProperties),()=>{let w=$.subschema({keyword:U,schemaProp:Q},J);$.mergeValidEvaluated(w,J)},()=>q.var(J,!0)),$.ok(J)}}Kc.validateSchemaDeps=wc;Kc.default=Qv0});var Xc=F((Zc)=>{Object.defineProperty(Zc,"__esModule",{value:!0});var Vc=a0(),Gv0=Z1(),Wv0={message:"property name must be valid",params:({params:$})=>Vc._`{propertyName:${$.propertyName}}`},Vv0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Wv0,code($){let{gen:I,schema:q,data:z,it:U}=$;if((0,Gv0.alwaysValidSchema)(U,q))return;let Y=I.name("valid");I.forIn("key",z,(J)=>{$.setParams({propertyName:J}),$.subschema({keyword:"propertyNames",data:J,dataTypes:["string"],propertyName:J,compositeRule:!0},Y),I.if((0,Vc.not)(Y),()=>{if($.error(!0),!U.allErrors)I.break()})}),$.ok(Y)}};Zc.default=Vv0});var ME=F((Lc)=>{Object.defineProperty(Lc,"__esModule",{value:!0});var gG=v$(),I8=a0(),Xv0=H5(),vG=Z1(),Lv0={message:"must NOT have additional properties",params:({params:$})=>I8._`{additionalProperty:${$.additionalProperty}}`},Dv0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Lv0,code($){let{gen:I,schema:q,parentSchema:z,data:U,errsCount:Y,it:J}=$;if(!Y)throw Error("ajv implementation error");let{allErrors:Q,opts:w}=J;if(J.props=!0,w.removeAdditional!=="all"&&(0,vG.alwaysValidSchema)(J,q))return;let K=(0,gG.allSchemaProperties)(z.properties),H=(0,gG.allSchemaProperties)(z.patternProperties);G(),$.ok(I8._`${Y}===${Xv0.default.errors}`);function G(){I.forIn("key",U,(D)=>{if(!K.length&&!H.length)X(D);else I.if(W(D),()=>X(D))})}function W(D){let O;if(K.length>8){let P=(0,vG.schemaRefOrVal)(J,z.properties,"properties");O=(0,gG.isOwnProperty)(I,P,D)}else if(K.length)O=(0,I8.or)(...K.map((P)=>I8._`${D}===${P}`));else O=I8.nil;if(H.length)O=(0,I8.or)(O,...H.map((P)=>I8._`${(0,gG.usePattern)($,P)}.test(${D})`));return(0,I8.not)(O)}function V(D){I.code(I8._`delete${U}[${D}]`)}function X(D){if(w.removeAdditional==="all"||w.removeAdditional&&q===!1){V(D);return}if(q===!1){if($.setParams({additionalProperty:D}),$.error(),!Q)I.break();return}if(typeof q=="object"&&!(0,vG.alwaysValidSchema)(J,q)){let O=I.name("valid");if(w.removeAdditional==="failing")L(D,O,!1),I.if((0,I8.not)(O),()=>{$.reset(),V(D)});else if(L(D,O),!Q)I.if((0,I8.not)(O),()=>I.break())}}function L(D,O,P){let T={keyword:"additionalProperties",dataProp:D,dataPropType:vG.Type.Str};if(P===!1)Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(T,O)}}};Lc.default=Dv0});var Nc=F((Fc)=>{Object.defineProperty(Fc,"__esModule",{value:!0});var Fv0=zJ(),Dc=v$(),AE=Z1(),Oc=ME(),Nv0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:I,schema:q,parentSchema:z,data:U,it:Y}=$;if(Y.opts.removeAdditional==="all"&&z.additionalProperties===void 0)Oc.default.code(new Fv0.KeywordCxt(Y,Oc.default,"additionalProperties"));let J=(0,Dc.allSchemaProperties)(q);for(let G of J)Y.definedProperties.add(G);if(Y.opts.unevaluated&&J.length&&Y.props!==!0)Y.props=AE.mergeEvaluated.props(I,(0,AE.toHash)(J),Y.props);let Q=J.filter((G)=>!(0,AE.alwaysValidSchema)(Y,q[G]));if(Q.length===0)return;let w=I.name("valid");for(let G of Q){if(K(G))H(G);else{if(I.if((0,Dc.propertyInData)(I,U,G,Y.opts.ownProperties)),H(G),!Y.allErrors)I.else().var(w,!0);I.endIf()}$.it.definedProperties.add(G),$.ok(w)}function K(G){return Y.opts.useDefaults&&!Y.compositeRule&&q[G].default!==void 0}function H(G){$.subschema({keyword:"properties",schemaProp:G,dataProp:G},w)}}};Fc.default=Nv0});var Ec=F((Tc)=>{Object.defineProperty(Tc,"__esModule",{value:!0});var Mc=v$(),RG=a0(),Ac=Z1(),Pc=Z1(),Av0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:q,data:z,parentSchema:U,it:Y}=$,{opts:J}=Y,Q=(0,Mc.allSchemaProperties)(q),w=Q.filter((L)=>(0,Ac.alwaysValidSchema)(Y,q[L]));if(Q.length===0||w.length===Q.length&&(!Y.opts.unevaluated||Y.props===!0))return;let K=J.strictSchema&&!J.allowMatchingProperties&&U.properties,H=I.name("valid");if(Y.props!==!0&&!(Y.props instanceo
Line truncated
`)}openNode($,I){let q=this.tos,z=this._xml;if(q&&this.open)z.push(">");this._stack.push($),z.push("<"),z.push($),ng(z,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)M00(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");ng(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(N00.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,q){if(this.openNode($,I),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("")}}bg.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};A00.exports=bg});var ig=F((qi0)=>{var P00=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function Ii0($){if(typeof $==="string")return $;if(P00)return P00.decode($);return $.toString()}qi0.bufferToString=Ii0});var g00=F((E00)=>{Object.defineProperty(E00,"__esModule",{value:!0});E00.CHAR=`
`,$=this.i;break;case Ap0:{let{entityReturnState:q}=this,z=this.entity+I.slice($,this.prevI);this.state=q;let U;if(z==="")this.fail("empty entity name."),U="&;";else U=this.parseEntity(z),this.entity="";if(q!==S6||this.textHandler!==void 0)this.text+=U;break $}case w4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(RQ($))this.state=Dp0,this.unget(),this.xmlDeclPossible=!1;else switch($){case xV:this.state=Np0,this.xmlDeclPossible=!1;break;case a00:this.state=Qp0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case U6:this.state=Wp0;break;default:this.fail("disallowed character in tag name"),this.state=S6,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=sg,this.openWakaBang="";break;case"--":this.state=ag,this.openWakaBang="";break;case"DOCTYPE":if(this.state=og,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(yV))this.state=wp0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===yV)this.state=Kp0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=ag}sCommentEnded(){let $=this.getCodeNorm();if($!==y4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=ag;else this.state=S6}sCData(){if(this.captureToChar(Gz))this.state=Hp0}sCDataEnding(){let $=this.getCodeNorm();if($===Gz)this.state=Gp0;else this.text+=`]${String.fromCodePoint($)}`,this.state=sg}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case y4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=S6;break}case Gz:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=sg}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=c00;else if($===U6||t6($))this.fail("processing instruction without a target."),this.state=$===U6?uV:eg;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=c00}sPIRest(){let{chunk:$,i:I}=this;while(!0){let q=this.getCodeNorm();if(q===w4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(q)){this.piTarget+=$.slice(I,this.prevI);let z=q===U6;if(z||t6(q))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=z?D3:d00}else this.state=z?uV:eg;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($===U6)this.state=uV;else if(!t6($))this.text=String.fromCodePoint($)}else if(this.captureToChar(U6))this.state=uV}sPIEnding(){var $;let I=this.getCodeNorm();if(I===y4){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=S6}else if(I===U6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=eg;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===U6){this.state=D3;return}if($!==w4)this.state=Vp0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(Ep0);if($===U6){this.state=D3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(t6($)||$===Hz))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=$===Hz?m00:Zp0}sXMLDeclEq(){let $=this.getCodeNorm();if($===U6){this.state=D3,this.fail("XML declaration is incomplete.");return}if(t6($))return;if($!==Hz)this.fail("value required.");this.state=m00}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===U6){this.state=D3,this.fail("XML declaration is incomplete.");return}if(t6($))return;if(!kV($))this.fail("value must be quoted."),this.q=t00;else this.q=$;this.state=Xp0}sXMLDeclValue(){let $=this.captureTo([this.q,U6]);if($===U6){this.state=D3,this.text="",this.fail("XML declaration is incomplete.");return}if($===w4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let q=I;if(this.xmlDecl.version=q,!/^1\.[0-9]+$/.test(q))this.fail("ver
Line truncated
`;$=this.i;break;case w4:if(q!==void 0)this.text+=I.slice($);break $;default:if(!t6(U))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($,I){var q;let{prefix:z,local:U}=this.qname($),Y={name:$,prefix:z,local:U,value:I};if(this.attribList.push(Y),(q=this.attributeHandler)===null||q===void 0||q.call(this,Y),z==="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,Yv(this,U,J)}else if($==="xmlns"){let J=I.trim();this.topNS[""]=J,Yv(this,"",J)}}pushAttribPlain($,I){var q;let z={name:$,value:I};this.attribList.push(z),(q=this.attributeHandler)===null||q===void 0||q.call(this,z)}end(){var $,I;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:q}=this;while(q.length>0){let U=q.pop();this.fail(`unclosedtag:${U.name}`)}if(this.state!==p00&&this.state!==S6)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,(I=this.endHandler)===null||I===void 0||I.call(this),this._init(),this}resolve($){var I,q;let z=this.topNS[$];if(z!==void 0)return z;let{tags:U}=this;for(let Y=U.length-1;Y>=0;Y--)if(z=U[Y].ns[$],z!==void 0)return z;if(z=this.ns[$],z!==void 0)return z;return(q=(I=this.opt).resolvePrefix)===null||q===void 0?void 0:q.call(I,$)}qname($){let I=$.indexOf(":");if(I===-1)return{prefix:"",local:$};let q=$.slice(I+1),z=$.slice(0,I);if(z===""||q===""||q.includes(":"))this.fail(`malformedname:${$}.`);return{prefix:z,local:q}}processAttribsNS(){var $;let{attribList:I}=this,q=this.tag;{let{prefix:Y,local:J}=this.qname(q.name);q.prefix=Y,q.local=J;let Q=q.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)}.`),q.uri=Y}}if(I.length===0)return;let{attributes:z}=q,U=new Set;for(let Y of I){let{name:J,prefix:Q,local:w}=Y,K,H;if(Q==="")K=J==="xmlns"?Wz:"",H=J;else{if(K=this.resolve(Q),K===void 0)this.fail(`unboundnamespaceprefix:${JSON.stringify(Q)}.`),K=Q;H=`{${K}}${w}`}if(U.has(H))this.fail(`duplicateattribute:${H}.`);U.add(H),Y.uri=K,z[J]=Y}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,I=this.tag.attributes;for(let{name:q,value:z}of $){if(I[q]!==void 0)this.fail(`duplicateattribute:${q}.`);I[q]=z}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:I}=this,q=this.tag;q.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,q),I.push(q),this.state=S6,this.name=""}openSelfClosingTag(){var $,I,q;this.processAttribs();let{tags:z}=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=(q=z[z.length-1])!==null&&q!==void 0?q:null)===null)this.closedRoot=!0;this.state=S6,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=S6,this.name="",I===""){this.fail("weird empty close tag."),this.text+="</>";return}let q=this.closeTagHandler,z=$.length;while(z-- >0){let U=this.tag=$.pop();if(this.topNS=U.ns,q===null||q===void 0||q(U),U.name===I)break;this.fail("unexpected close tag.")}if(z===0)this.closedRoot=!0;else if(z<0)this.fail(`unmatchedclosingtag:${I}.`),this.text+=`</${I}>`}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 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)}}w10.SaxesParser=Q10});varhQ=F((EB1,H10)=>{var{SaxesParser:_p0}=K10(),{PassThrough:hp0}=O6(),{bufferToString:Sp0}=ig();H10.exports=asyncfunction*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(newhp0);letI=new_p0,q;I.on("error",(U)=>{q=U});letz=[];I.on("opentag",(U)=>z.push({eventType:"opentag",value:U})),I.on("text",(U)=>z.push({eventType:"text",value:U})),I.on("closetag",(U)=>z.push({eventType:"closetag",value:U}));forawait(letUof$){if(I.write(Sp0(U)),q)throwq;yieldz,z=[]}}});varL0=F((BB1,G10)=>{varup0=hQ(),yp0=z6();classZz{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($instanceofZz)$.reset();elseif($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}asyncparse($){forawait(letIof$)for(let{eventType:q,value:z}ofI)if(q==="opentag")this.parseOpen(z);elseif(q==="text")this.parseText(z);elseif(q==="closetag"){if(!this.parseClose(z.name))returnthLine truncated
`)}openNode($,I){let z=this.tos,q=this._xml;if(z&&this.open)q.push(">");this._stack.push($),q.push("<"),q.push($),IR(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)S00(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");IR(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(h00.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("")}}zR.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};y00.exports=zR});var qR=F((Mi0)=>{var u00=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function Ni0($){if(typeof $==="string")return $;if(u00)return u00.decode($);return $.toString()}Mi0.bufferToString=Ni0});var n00=F((k00)=>{Object.defineProperty(k00,"__esModule",{value:!0});k00.CHAR=`
`,$=this.i;break;case np0:{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!==x6||this.textHandler!==void 0)this.text+=U;break $}case w4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(yQ($))this.state=up0,this.unget(),this.xmlDeclPossible=!1;else switch($){case mV:this.state=fp0,this.xmlDeclPossible=!1;break;case G10:this.state=Bp0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case Y6:this.state=_p0;break;default:this.fail("disallowed character in tag name"),this.state=x6,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=VR,this.openWakaBang="";break;case"--":this.state=WR,this.openWakaBang="";break;case"DOCTYPE":if(this.state=wR,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(dV))this.state=jp0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===dV)this.state=vp0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=WR}sCommentEnded(){let $=this.getCodeNorm();if($!==u4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=WR;else this.state=x6}sCData(){if(this.captureToChar(Xq))this.state=Rp0}sCDataEnding(){let $=this.getCodeNorm();if($===Xq)this.state=gp0;else this.text+=`]${String.fromCodePoint($)}`,this.state=VR}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case u4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=x6;break}case Xq:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=VR}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=q10;else if($===Y6||z$($))this.fail("processing instruction without a target."),this.state=$===Y6?cV:ZR;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=q10}sPIRest(){let{chunk:$,i:I}=this;while(!0){let z=this.getCodeNorm();if(z===w4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(z)){this.piTarget+=$.slice(I,this.prevI);let q=z===Y6;if(q||z$(z))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=q?P3:U10}else this.state=q?cV:ZR;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($===Y6)this.state=cV;else if(!z$($))this.text=String.fromCodePoint($)}else if(this.captureToChar(Y6))this.state=cV}sPIEnding(){var $;let I=this.getCodeNorm();if(I===u4){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=x6}else if(I===Y6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=ZR;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===Y6){this.state=P3;return}if($!==w4)this.state=Cp0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(cp0);if($===Y6){this.state=P3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(z$($)||$===Zq))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=$===Zq?Y10:hp0}sXMLDeclEq(){let $=this.getCodeNorm();if($===Y6){this.state=P3,this.fail("XML declaration is incomplete.");return}if(z$($))return;if($!==Zq)this.fail("value required.");this.state=Y10}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===Y6){this.state=P3,this.fail("XML declaration is incomplete.");return}if(z$($))return;if(!lV($))this.fail("value must be quoted."),this.q=w10;else this.q=$;this.state=Sp0}sXMLDeclValue(){let $=this.captureTo([this.q,Y6]);if($===Y6){this.state=P3,this.text="",this.fail("XML declaration is incomplete.");return}if($===w4)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 w4:if(z!==void 0)this.text+=I.slice($);break $;default:if(!z$(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,NR(this,U,J)}else if($==="xmlns"){let J=I.trim();this.topNS[""]=J,NR(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!==z10&&this.state!==x6)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,w,G;if(Q==="")w=J==="xmlns"?Lq:"",G=J;else{if(w=this.resolve(Q),w===void 0)this.fail(`unboundnamespaceprefix:${JSON.stringify(Q)}.`),w=Q;G=`{${w}}${K}`}if(U.has(G))this.fail(`duplicateattribute:${G}.`);U.add(G),Y.uri=w,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=x6,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=x6,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=x6,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)}}M10.SaxesParser=N10});varkQ=F((Vj1,P10)=>{var{SaxesParser:ap0}=A10(),{PassThrough:sp0}=F6(),{bufferToString:ep0}=qR();P10.exports=asyncfunction*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(newsp0);letI=newap0,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(ep0(U)),z)throwz;yieldq,q=[]}}});varD0=F((Zj1,T10)=>{var$c0=kQ(),Ic0=U6();classOq{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($instanceofOq)$.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
See:https://github.com/isaacs/node-glob/issues/167`);return new x4($,I).found}function x4($,I){if(!$)throw Error("must provide pattern");if(typeof I==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
`+e[H0-1];break}}}var w1="a promise was created in a "+M+"handler "+s+"but was not returned from it, see http://goo.gl/rRqMUw"+m;R._warn(w1,!0,N)}}function v0(a,N){var M=a+" is deprecated and will be removed in a future version.";if(N)M+=" Use "+N+" instead.";return Q1(M)}function Q1(a,N,M){if(!j0.warnings)return;var R=new U(a),y;if(N)M._attachExtraTrace(R);else if(j0.longStackTraces&&(y=$._peekContext()))y.attachExtraTrace(R);else{var s=z1(R);R.stack=s.message+`
`+e[G0-1];break}}}var K1="a promise was created in a "+A+"handler "+s+"but was not returned from it, see http://goo.gl/rRqMUw"+m;S._warn(K1,!0,N)}}function R0(a,N){var A=a+" is deprecated and will be removed in a future version.";if(N)A+=" Use "+N+" instead.";return Q1(A)}function Q1(a,N,A){if(!j0.warnings)return;var S=new U(a),n;if(N)A._attachExtraTrace(S);else if(j0.longStackTraces&&(n=$._peekContext()))n.attachExtraTrace(S);else{var s=q1(S);S.stack=s.message+`
`)));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(X,L){if(typeof X!=="function")throw new Q(`generatorFunctionmustbeafunction
`)));return}}O=O._target();var T=O._bitField;if((T&50397184)===0)this._yieldedPromise=O,O._proxy(this,null);else if((T&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,O._value());else if((T&16777216)!==0)$._async.invoke(this._promiseRejected,this,O._reason());else this._promiseCancelled()}},$.coroutine=function(X,L){if(typeof X!=="function")throw new Q(`generatorFunctionmustbeafunction
Seehttp://goo.gl/MqrFmX
`);var D=Object(L).yieldHandler,O=V,P=Error().stack;return function(){var T=X.apply(this,arguments),A=new O(void 0,void 0,D,P),g=A.promise();return A._generator=T,A._promiseFulfilled(void 0),g}},$.coroutine.addYieldHandler=function(X){if(typeof X!=="function")throw new Q("expecting a function but got "+w.classString(X));G.push(X)},$.spawn=function(X){if(Y.deprecated("Promise.spawn()","Promise.coroutine()"),typeof X!=="function")return I(`generatorFunctionmustbeafunction
`);var D=Object(L).yieldHandler,O=Z,T=Error().stack;return function(){var P=X.apply(this,arguments),M=new O(void 0,void 0,D,T),v=M.promise();return M._generator=P,M._promiseFulfilled(void 0),v}},$.coroutine.addYieldHandler=function(X){if(typeof X!=="function")throw new Q("expecting a function but got "+K.classString(X));H.push(X)},$.spawn=function(X){if(Y.deprecated("Promise.spawn()","Promise.coroutine()"),typeof X!=="function")return I(`generatorFunctionmustbeafunction
`)},I=function(){return new h.PromiseInspection(this._target())},q=function(B){return h.reject(new G(B))};function z(){}var U={},Y=d1(),J;if(Y.isNode)J=function(){var B=process.domain;if(B===void 0)B=null;return B};else J=function(){return null};Y.notEnumerableProp(h,"_getDomain",J);var Q=t3(),w=H20(),K=new w;Q.defineProperty(h,"_async",{value:K});var H=b5(),G=h.TypeError=H.TypeError;h.RangeError=H.RangeError;var W=h.CancellationError=H.CancellationError;h.TimeoutError=H.TimeoutError,h.OperationalError=H.OperationalError,h.RejectionError=H.OperationalError,h.AggregateError=H.AggregateError;var V=function(){},X={},L={},D=X20()(h,V),O=D20()(h,V,D,q,z),P=F20()(h),T=P.create,A=M20()(h,P),g=A.CapturedTrace,k=P20()(h,D),S=E20()(L),f=YS(),v=Y.errorObj,p=Y.tryCatch;function i(B,x){if(typeof x!=="function")throw new G("expecting a function but got "+Y.classString(x));if(B.constructor!==h)throw new G(`thepromiseconstructorcannotbeinvokeddirectly
`)},I=function(){return new g.PromiseInspection(this._target())},z=function(R){return g.reject(new H(R))};function q(){}var U={},Y=d1(),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(g,"_getDomain",J);var Q=zI(),K=P20(),w=new K;Q.defineProperty(g,"_async",{value:w});var G=m5(),H=g.TypeError=G.TypeError;g.RangeError=G.RangeError;var W=g.CancellationError=G.CancellationError;g.TimeoutError=G.TimeoutError,g.OperationalError=G.OperationalError,g.RejectionError=G.OperationalError,g.AggregateError=G.AggregateError;var Z=function(){},X={},L={},D=v20()(g,Z),O=g20()(g,Z,D,z,q),T=C20()(g),P=T.create,M=S20()(g,T),v=M.CapturedTrace,u=u20()(g,D),h=k20()(L),x=NS(),B=Y.errorObj,k=Y.tryCatch;function b(R,i){if(typeof i!=="function")throw new H("expecting a function but got "+Y.classString(i));if(R.constructor!==g)throw new H(`thepromiseconstructorcannotbeinvokeddirectly
Seehttp://goo.gl/MqrFmX
`)}function h(B){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,B!==V)i(this,B),this._resolveFromExecutor(B);this._promiseCreated(),this._fireEvent("promiseCreated",this)}h.prototype.toString=function(){return"[object Promise]"},h.prototype.caught=h.prototype.catch=function(B){var x=arguments.length;if(x>1){var c=Array(x-1),r=0,U0;for(U0=0;U0<x-1;++U0){var G0=arguments[U0];if(Y.isObject(G0))c[r++]=G0;else return q("expecting an object but got A catch statement predicate "+Y.classString(G0))}return c.length=r,B=arguments[U0],this.then(void 0,S(c,B,this))}return this.then(void 0,B)},h.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},h.prototype.then=function(B,x){if(A.warnings()&&arguments.length>0&&typeof B!=="function"&&typeof x!=="function"){var c=".then() only accepts functions but was passed: "+Y.classString(B);if(arguments.length>1)c+=", "+Y.classString(x);this._warn(c)}return this._then(B,x,void 0,void 0,void 0)},h.prototype.done=function(B,x){var c=this._then(B,x,void 0,void 0,void 0);c._setIsFinal()},h.prototype.spread=function(B){if(typeof B!=="function")return q("expecting a function but got "+Y.classString(B));return this.all()._then(B,void 0,void 0,X,void 0)},h.prototype.toJSON=function(){var B={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())B.fulfillmentValue=this.value(),B.isFulfilled=!0;else if(this.isRejected())B.rejectionReason=this.reason(),B.isRejected=!0;return B},h.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new O(this).promise()},h.prototype.error=function(B){return this.caught(Y.originatesFromRejection,B)},h.getNewLibraryCopy=QS.exports,h.is=function(B){return B instanceof h},h.fromNode=h.fromCallback=function(B){var x=new h(V);x._captureStackTrace();var c=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=p(B)(f(x,c));if(r===v)x._rejectCallback(r.e,!0);if(!x._isFateSealed())x._setAsyncGuaranteed();return x},h.all=function(B){return new O(B).promise()},h.cast=function(B){var x=D(B);if(!(x instanceof h))x=new h(V),x._captureStackTrace(),x._setFulfilled(),x._rejectionHandler0=B;return x},h.resolve=h.fulfilled=h.cast,h.reject=h.rejected=function(B){var x=new h(V);return x._captureStackTrace(),x._rejectCallback(B,!0),x},h.setScheduler=function(B){if(typeof B!=="function")throw new G("expecting a function but got "+Y.classString(B));return K.setScheduler(B)},h.prototype._then=function(B,x,c,r,U0){var G0=U0!==void 0,A0=G0?U0:new h(V),v0=this._target(),Q1=v0._bitField;if(!G0){if(A0._propagateFrom(this,3),A0._captureStackTrace(),r===void 0&&(this._bitField&2097152)!==0)if((Q1&50397184)!==0)r=this._boundValue();else r=v0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,A0)}var k0=J();if((Q1&50397184)!==0){var q1,M0,Y0=v0._settlePromiseCtx;if((Q1&33554432)!==0)M0=v0._rejectionHandler0,q1=B;else if((Q1&16777216)!==0)M0=v0._fulfillmentHandler0,q1=x,v0._unsetRejectionIsUnhandled();else Y0=v0._settlePromiseLateCancellationObserver,M0=new W("late cancellation observer"),v0._attachExtraTrace(M0),q1=x;K.invoke(Y0,v0,{handler:k0===null?q1:typeof q1==="function"&&Y.domainBind(k0,q1),promise:A0,receiver:r,value:M0})}else v0._addCallbacks(B,x,A0,r,k0);return A0},h.prototype._length=function(){return this._bitField&65535},h.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},h.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},h.prototype._setLength=function(B){this._bitField=this._bitField&-65536|B&65535},h.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},h.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},h.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},h.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},h.prototype._isFinal=function(){return(this._bitField&4194304)>0},h.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},h.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},h.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},h.prototype._setAsyncGuaranteed=function(){if(K.hasCustomScheduler())return;this._bitField=this._bitField|134217728},h.prototype._receiverAt=function(B){var x=B===0?this._receiver0:this[B*4-4+3];if(x===U)return;else if(x===void 0&&this._isBound())return this._boundValue();return x},h.prototype._promiseAt=function(B){return this[B*4-4+2]},h.prototype._fulfillmentHandlerAt=function(B){return this[B*4-4+0]},h.prototype._rejectionHandlerAt=function(B){return this[B*4-4+1]},h.prototype._boundValue=function(){},h.prototype._migrateCallback0=function(B){var{_bit
Line truncated
`)}function g(R){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,R!==Z)b(this,R),this._resolveFromExecutor(R);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(R){var i=arguments.length;if(i>1){var c=Array(i-1),r=0,U0;for(U0=0;U0<i-1;++U0){var H0=arguments[U0];if(Y.isObject(H0))c[r++]=H0;else return z("expecting an object but got A catch statement predicate "+Y.classString(H0))}return c.length=r,R=arguments[U0],this.then(void 0,h(c,R,this))}return this.then(void 0,R)},g.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},g.prototype.then=function(R,i){if(M.warnings()&&arguments.length>0&&typeof R!=="function"&&typeof i!=="function"){var c=".then() only accepts functions but was passed: "+Y.classString(R);if(arguments.length>1)c+=", "+Y.classString(i);this._warn(c)}return this._then(R,i,void 0,void 0,void 0)},g.prototype.done=function(R,i){var c=this._then(R,i,void 0,void 0,void 0);c._setIsFinal()},g.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,X,void 0)},g.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},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(R){return this.caught(Y.originatesFromRejection,R)},g.getNewLibraryCopy=AS.exports,g.is=function(R){return R instanceof g},g.fromNode=g.fromCallback=function(R){var i=new g(Z);i._captureStackTrace();var c=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=k(R)(x(i,c));if(r===B)i._rejectCallback(r.e,!0);if(!i._isFateSealed())i._setAsyncGuaranteed();return i},g.all=function(R){return new O(R).promise()},g.cast=function(R){var i=D(R);if(!(i instanceof g))i=new g(Z),i._captureStackTrace(),i._setFulfilled(),i._rejectionHandler0=R;return i},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(R){var i=new g(Z);return i._captureStackTrace(),i._rejectCallback(R,!0),i},g.setScheduler=function(R){if(typeof R!=="function")throw new H("expecting a function but got "+Y.classString(R));return w.setScheduler(R)},g.prototype._then=function(R,i,c,r,U0){var H0=U0!==void 0,A0=H0?U0:new g(Z),R0=this._target(),Q1=R0._bitField;if(!H0){if(A0._propagateFrom(this,3),A0._captureStackTrace(),r===void 0&&(this._bitField&2097152)!==0)if((Q1&50397184)!==0)r=this._boundValue();else r=R0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,A0)}var f0=J();if((Q1&50397184)!==0){var z1,M0,Y0=R0._settlePromiseCtx;if((Q1&33554432)!==0)M0=R0._rejectionHandler0,z1=R;else if((Q1&16777216)!==0)M0=R0._fulfillmentHandler0,z1=i,R0._unsetRejectionIsUnhandled();else Y0=R0._settlePromiseLateCancellationObserver,M0=new W("late cancellation observer"),R0._attachExtraTrace(M0),z1=i;w.invoke(Y0,R0,{handler:f0===null?z1:typeof z1==="function"&&Y.domainBind(f0,z1),promise:A0,receiver:r,value:M0})}else R0._addCallbacks(R,i,A0,r,f0);return A0},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(R){this._bitField=this._bitField&-65536|R&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(w.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(R){var i=R===0?this._receiver0:this[R*4-4+3];if(i===U)return;else if(i===void 0&&this._isBound())return this._boundValue();return i},g.prototype._promiseAt=function(R){return this[R*4-4+2]},g.prototype._fulfillmentHandlerAt=function(R){return this[R*4-4+0]},g.prototype._rejectionHandlerAt=function(R){return this[R*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(R){var{_bit
Line truncated
`).filter((Y)=>Y),z=Math.min(...q.map((Y)=>Y.length-Y.trimStart().length)),U=q.map((Y)=>Y.slice(z)).map((Y)=>" ".repeat(this.indent*2)+Y);for(let Y of U)this.content.push(Y)}compile(){let $=Function,I=this?.args,z=[...(this?.content??[""]).map((U)=>`${U}`)];return new $(...I,z.join(`
`))}}var jF={major:4,minor:4,patch:3};var p0=o("$ZodType",($,I)=>{var q;$??($={}),$._zod.def=I,$._zod.bag=$._zod.bag||{},$._zod.version=jF;let z=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))z.unshift($);for(let U of z)for(let Y of U._zod.onattach)Y($);if(z.length===0)(q=$._zod).deferred??(q.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let U=(J,Q,w)=>{let K=Q9(J),H;for(let G of Q){if(G._zod.def.when){if(CO(J))continue;if(!G._zod.def.when(J))continue}else if(K)continue;let W=J.issues.length,V=G._zod.check(J);if(V instanceof Promise&&w?.async===!1)throw new O8;if(H||V instanceof Promise)H=(H??Promise.resolve()).then(async()=>{if(await V,J.issues.length===W)return;if(!K)K=Q9(J,W)});else{if(J.issues.length===W)continue;if(!K)K=Q9(J,W)}}if(H)return H.then(()=>{return J});return J},Y=(J,Q,w)=>{if(Q9(J))return J.aborted=!0,J;let K=U(Q,z,w);if(K instanceof Promise){if(w.async===!1)throw new O8;return K.then((H)=>$._zod.parse(H,w))}return $._zod.parse(K,w)};$._zod.run=(J,Q)=>{if(Q.skipChecks)return $._zod.parse(J,Q);if(Q.direction==="backward"){let K=$._zod.parse({value:J.value,issues:[]},{...Q,skipChecks:!0});if(K instanceof Promise)return K.then((H)=>{return Y(H,J,Q)});return Y(K,J,Q)}let w=$._zod.parse(J,Q);if(w instanceof Promise){if(Q.async===!1)throw new O8;return w.then((K)=>U(K,z,Q))}return U(w,z,Q)}}$1($,"~standard",()=>({validate:(U)=>{try{let Y=SI($,U);return Y.success?{value:Y.data}:{issues:Y.error?.issues}}catch(Y){return KY($,U).then((J)=>J.success?{value:J.data}:{issues:J.error?.issues})}},vendor:"zod",version:1}))}),k7=o("$ZodString",($,I)=>{p0.init($,I),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??IF($._zod.bag),$._zod.parse=(q,z)=>{if(I.coerce)try{q.value=String(q.value)}catch(U){}if(typeof q.value==="string")return q;return q.issues.push({expected:"string",code:"invalid_type",input:q.value,inst:$}),q}}),x1=o("$ZodStringFormat",($,I)=>{yI.init($,I),k7.init($,I)}),vF=o("$ZodGUID",($,I)=>{I.pattern??(I.pattern=bO),x1.init($,I)}),RF=o("$ZodUUID",($,I)=>{if(I.version){let z={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[I.version];if(z===void 0)throw Error(`InvalidUUIDversion:"${I.version}"`);I.pattern??(I.pattern=x7(z))}else I.pattern??(I.pattern=x7());x1.init($,I)}),CF=o("$ZodEmail",($,I)=>{I.pattern??(I.pattern=iO),x1.init($,I)}),_F=o("$ZodURL",($,I)=>{x1.init($,I),$._zod.check=(q)=>{try{let z=q.value.trim();if(!I.normalize&&I.protocol?.source===tO.source){if(!/^https?:\/\//i.test(z)){q.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:q.value,inst:$,continue:!I.abort});return}}let U=new URL(z);if(I.hostname){if(I.hostname.lastIndex=0,!I.hostname.test(U.hostname))q.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:I.hostname.source,input:q.value,inst:$,continue:!I.abort})}if(I.protocol){if(I.protocol.lastIndex=0,!I.protocol.test(U.protocol.endsWith(":")?U.protocol.slice(0,-1):U.protocol))q.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:I.protocol.source,input:q.value,inst:$,continue:!I.abort})}if(I.normalize)q.value=U.href;else q.value=z;return}catch(z){q.issues.push({code:"invalid_format",format:"url",input:q.value,inst:$,continue:!I.abort})}}}),hF=o("$ZodEmoji",($,I)=>{I.pattern??(I.pattern=pO()),x1.init($,I)}),SF=o("$ZodNanoID",($,I)=>{I.pattern??(I.pattern=fO),x1.init($,I)}),uF=o("$ZodCUID",($,I)=>{I.pattern??(I.pattern=SO),x1.init($,I)}),yF=o("$ZodCUID2",($,I)=>{I.pattern??(I.pattern=uO),x1.init($,I)}),xF=o("$ZodULID",($,I)=>{I.pattern??(I.pattern=yO),x1.init($,I)}),kF=o("$ZodXID",($,I)=>{I.pattern??(I.pattern=xO),x1.init($,I)}),fF=o("$ZodKSUID",($,I)=>{I.pattern??(I.pattern=kO),x1.init($,I)}),nF=o("$ZodISODateTime",($,I)=>{I.pattern??(I.pattern=$F(I)),x1.init($,I)}),bF=o("$ZodISODate",($,I)=>{I.pattern??(I.pattern=sO),x1.init($,I)}),iF=o("$ZodISOTime",($,I)=>{I.pattern??(I.pattern=eO(I)),x1.init($,I)}),pF=o("$ZodISODuration",($,I)=>{I.pattern??(I.pattern=nO),x1.init($,I)}),cF=o("$ZodIPv4",($,I)=>{I.pattern??(I.pattern=cO),x1.init($,I),$._zod.bag.format="ipv4"}),dF=o("$ZodIPv6",($,I)=>{I.pattern??(I.pattern=dO),x1.init($,I),$._zod.bag.format="ipv6",$._zod.check=(q)=>{try{new URL(`http://[${q.value}]`)}catch{q.issues.push({code:"invalid_format",format:"ipv6",input:q.value,inst:$,continue:!I.abort})}}}),mF=o("$ZodMAC",($,I)=>{I.pattern??(I.pattern=mO(I.delimiter)),x1.init($,I),$._zod.bag.format="mac"}),lF=o("$ZodCIDRv4",($,I)=>{I.pattern??(I.pattern=lO),x1.init($,I)}),oF=o("$ZodCIDRv6",($,I)=>{I.pattern??(I.pattern=oO),x1.init($,I),$._zod.check=(q)=>{let z=q.value.split("/");try{if(z.length!==2)throw Error();let[U,Y]=z;if(!Y)throw Error();let J=Number(Y);if(`${J}`!==Y)throw Error();if(J<0||J>128)throw Error();new URL(`http://[${U}]`)}catch{q.issues.push({code:"invalid_format",format:"cidrv6",input:q.value,inst:$,continue:!I.abort})}}});function rF($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}
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 nF={major:4,minor:4,patch:3};var p0=o("$ZodType",($,I)=>{var z;$??($={}),$._zod.def=I,$._zod.bag=$._zod.bag||{},$._zod.version=nF;let q=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))q.unshift($);for(let U of q)for(let Y of U._zod.onattach)Y($);if(q.length===0)(z=$._zod).deferred??(z.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let U=(J,Q,K)=>{let w=V9(J),G;for(let H of Q){if(H._zod.def.when){if(dO(J))continue;if(!H._zod.def.when(J))continue}else if(w)continue;let W=J.issues.length,Z=H._zod.check(J);if(Z instanceof Promise&&K?.async===!1)throw new A8;if(G||Z instanceof Promise)G=(G??Promise.resolve()).then(async()=>{if(await Z,J.issues.length===W)return;if(!w)w=V9(J,W)});else{if(J.issues.length===W)continue;if(!w)w=V9(J,W)}}if(G)return G.then(()=>{return J});return J},Y=(J,Q,K)=>{if(V9(J))return J.aborted=!0,J;let w=U(Q,q,K);if(w instanceof Promise){if(K.async===!1)throw new A8;return w.then((G)=>$._zod.parse(G,K))}return $._zod.parse(w,K)};$._zod.run=(J,Q)=>{if(Q.skipChecks)return $._zod.parse(J,Q);if(Q.direction==="backward"){let w=$._zod.parse({value:J.value,issues:[]},{...Q,skipChecks:!0});if(w instanceof Promise)return w.then((G)=>{return Y(G,J,Q)});return Y(w,J,Q)}let K=$._zod.parse(J,Q);if(K instanceof Promise){if(Q.async===!1)throw new A8;return K.then((w)=>U(w,q,Q))}return U(K,q,Q)}}$1($,"~standard",()=>({validate:(U)=>{try{let Y=kI($,U);return Y.success?{value:Y.data}:{issues:Y.error?.issues}}catch(Y){return ZY($,U).then((J)=>J.success?{value:J.data}:{issues:J.error?.issues})}},vendor:"zod",version:1}))}),d7=o("$ZodString",($,I)=>{p0.init($,I),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??XF($._zod.bag),$._zod.parse=(z,q)=>{if(I.coerce)try{z.value=String(z.value)}catch(U){}if(typeof z.value==="string")return z;return z.issues.push({expected:"string",code:"invalid_type",input:z.value,inst:$}),z}}),x1=o("$ZodStringFormat",($,I)=>{bI.init($,I),d7.init($,I)}),pF=o("$ZodGUID",($,I)=>{I.pattern??(I.pattern=IF),x1.init($,I)}),cF=o("$ZodUUID",($,I)=>{if(I.version){let q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[I.version];if(q===void 0)throw Error(`InvalidUUIDversion:"${I.version}"`);I.pattern??(I.pattern=c7(q))}else I.pattern??(I.pattern=c7());x1.init($,I)}),dF=o("$ZodEmail",($,I)=>{I.pattern??(I.pattern=zF),x1.init($,I)}),mF=o("$ZodURL",($,I)=>{x1.init($,I),$._zod.check=(z)=>{try{let q=z.value.trim();if(!I.normalize&&I.protocol?.source===GF.source){if(!/^https?:\/\//i.test(q)){z.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:z.value,inst:$,continue:!I.abort});return}}let U=new URL(q);if(I.hostname){if(I.hostname.lastIndex=0,!I.hostname.test(U.hostname))z.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:I.hostname.source,input:z.value,inst:$,continue:!I.abort})}if(I.protocol){if(I.protocol.lastIndex=0,!I.protocol.test(U.protocol.endsWith(":")?U.protocol.slice(0,-1):U.protocol))z.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:I.protocol.source,input:z.value,inst:$,continue:!I.abort})}if(I.normalize)z.value=U.href;else z.value=q;return}catch(q){z.issues.push({code:"invalid_format",format:"url",input:z.value,inst:$,continue:!I.abort})}}}),lF=o("$ZodEmoji",($,I)=>{I.pattern??(I.pattern=qF()),x1.init($,I)}),oF=o("$ZodNanoID",($,I)=>{I.pattern??(I.pattern=eO),x1.init($,I)}),rF=o("$ZodCUID",($,I)=>{I.pattern??(I.pattern=oO),x1.init($,I)}),tF=o("$ZodCUID2",($,I)=>{I.pattern??(I.pattern=rO),x1.init($,I)}),aF=o("$ZodULID",($,I)=>{I.pattern??(I.pattern=tO),x1.init($,I)}),sF=o("$ZodXID",($,I)=>{I.pattern??(I.pattern=aO),x1.init($,I)}),eF=o("$ZodKSUID",($,I)=>{I.pattern??(I.pattern=sO),x1.init($,I)}),$N=o("$ZodISODateTime",($,I)=>{I.pattern??(I.pattern=ZF(I)),x1.init($,I)}),IN=o("$ZodISODate",($,I)=>{I.pattern??(I.pattern=WF),x1.init($,I)}),zN=o("$ZodISOTime",($,I)=>{I.pattern??(I.pattern=VF(I)),x1.init($,I)}),qN=o("$ZodISODuration",($,I)=>{I.pattern??(I.pattern=$F),x1.init($,I)}),UN=o("$ZodIPv4",($,I)=>{I.pattern??(I.pattern=UF),x1.init($,I),$._zod.bag.format="ipv4"}),YN=o("$ZodIPv6",($,I)=>{I.pattern??(I.pattern=YF),x1.init($,I),$._zod.bag.format="ipv6",$._zod.check=(z)=>{try{new URL(`http://[${z.value}]`)}catch{z.issues.push({code:"invalid_format",format:"ipv6",input:z.value,inst:$,continue:!I.abort})}}}),JN=o("$ZodMAC",($,I)=>{I.pattern??(I.pattern=JF(I.delimiter)),x1.init($,I),$._zod.bag.format="mac"}),QN=o("$ZodCIDRv4",($,I)=>{I.pattern??(I.pattern=QF),x1.init($,I)}),KN=o("$ZodCIDRv6",($,I)=>{I.pattern??(I.pattern=KF),x1.init($,I),$._zod.check=(z)=>{let q=z.value.split("/");try{if(q.length!==2)throw Error();let[U,Y]=q;if(!Y)throw Error();let J=Number(Y);if(`${J}`!==Y)throw Error();if(J<0||J>128)throw Error();new URL(`http://[${U}]`)}catch{z.issues.push({code:"invalid_format",format:"cidrv6",input:z.value,inst:$,continue:!I.abort})}}});function wN($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}
Line truncated
`)}V.write("payload.value = newResult;"),V.write("return payload;");let P=V.compile();return(T,A)=>P(W,T,A)},Y,J=y7,Q=!S7.jitless,K=Q&&EO.value,H=I.catchall,G;$._zod.parse=(W,V)=>{G??(G=z.value);let X=W.value;if(!J(X))return W.issues.push({expected:"object",code:"invalid_type",input:X,inst:$}),W;if(Q&&K&&V?.async===!1&&V.jitless!==!0){if(!Y)Y=U(I.shape);if(W=Y(W,V),!H)return W;return sk([],X,W,V,G,$)}return q(W,V)}});function yk($,I,q,z){for(let Y of $)if(Y.issues.length===0)return I.value=Y.value,I;let U=$.filter((Y)=>!Q9(Y));if(U.length===1)return I.value=U[0].value,U[0];return I.issues.push({code:"invalid_union",input:I.value,inst:q,errors:$.map((Y)=>Y.issues.map((J)=>B6(J,z,L4())))}),I}var ZY=o("$ZodUnion",($,I)=>{p0.init($,I),$1($._zod,"optin",()=>I.options.some((z)=>z._zod.optin==="optional")?"optional":void 0),$1($._zod,"optout",()=>I.options.some((z)=>z._zod.optout==="optional")?"optional":void 0),$1($._zod,"values",()=>{if(I.options.every((z)=>z._zod.values))return new Set(I.options.flatMap((z)=>Array.from(z._zod.values)));return}),$1($._zod,"pattern",()=>{if(I.options.every((z)=>z._zod.pattern)){let z=I.options.map((U)=>U._zod.pattern);return new RegExp(`^(${z.map((U)=>$Y(U.source)).join("|")})$`)}return});let q=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(z,U)=>{if(q)return q(z,U);let Y=!1,J=[];for(let Q of I.options){let w=Q._zod.run({value:z.value,issues:[]},U);if(w instanceof Promise)J.push(w),Y=!0;else{if(w.issues.length===0)return w;J.push(w)}}if(!Y)return yk(J,z,$,U);return Promise.all(J).then((Q)=>{return yk(Q,z,$,U)})}});function xk($,I,q,z){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:q,errors:$.map((Y)=>Y.issues.map((J)=>B6(J,z,L4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:q,errors:[],inclusive:!1});return I}var VN=o("$ZodXor",($,I)=>{ZY.init($,I),I.inclusive=!1;let q=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(z,U)=>{if(q)return q(z,U);let Y=!1,J=[];for(let Q of I.options){let w=Q._zod.run({value:z.value,issues:[]},U);if(w instanceof Promise)J.push(w),Y=!0;else J.push(w)}if(!Y)return xk(J,z,$,U);return Promise.all(J).then((Q)=>{return xk(Q,z,$,U)})}}),ZN=o("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,ZY.init($,I);let q=$._zod.parse;$1($._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,w]of Object.entries(J)){if(!U[Q])U[Q]=new Set;for(let K of w)U[Q].add(K)}}return U});let z=vI(()=>{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 w of Q){if(Y.has(w))throw Error(`Duplicatediscriminatorvalue"${String(w)}"`);Y.set(w,J)}}return Y});$._zod.parse=(U,Y)=>{let J=U.value;if(!y7(J))return U.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),U;let Q=z.value.get(J?.[I.discriminator]);if(Q)return Q._zod.run(U,Y);if(I.unionFallback||Y.direction==="backward")return q(U,Y);return U.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(z.value.keys()),input:J,path:[I.discriminator],inst:$}),U}}),XN=o("$ZodIntersection",($,I)=>{p0.init($,I),$._zod.parse=(q,z)=>{let U=q.value,Y=I.left._zod.run({value:U,issues:[]},z),J=I.right._zod.run({value:U,issues:[]},z);if(Y instanceof Promise||J instanceof Promise)return Promise.all([Y,J]).then(([w,K])=>{return kk(q,w,K)});return kk(q,Y,J)}});function gF($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if(J9($)&&J9(I)){let q=Object.keys(I),z=Object.keys($).filter((Y)=>q.indexOf(Y)!==-1),U={...$,...I};for(let Y of z){let J=gF($[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 q=[];for(let z=0;z<$.length;z++){let U=$[z],Y=I[z],J=gF(U,Y);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};q.push(J.data)}return{valid:!0,data:q}}return{valid:!1,mergeErrorPath:[]}}function kk($,I,q){let z=new Map,U;for(let Q of I.issues)if(Q.code==="unrecognized_keys"){U??(U=Q);for(let w of Q.keys){if(!z.has(w))z.set(w,{});z.get(w).l=!0}}else $.issues.push(Q);for(let Q of q.issues)if(Q.code==="unrecognized_keys")for(let w of Q.keys){if(!z.has(w))z.set(w,{});z.get(w).r=!0}else $.issues.push(Q);let Y=[...z].filter(([,Q])=>Q.l&&Q.r).map(([Q])=>Q);if(Y.length&&U)$.issues.push({...U,keys:Y});if(Q9($))return $;let J=gF(I.value,q.value);if(!J.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}var vK=o("$ZodTuple",($,I)=>{p0.
Line truncated
`)}Z.write("payload.value = newResult;"),Z.write("return payload;");let T=Z.compile();return(P,M)=>T(W,P,M)},Y,J=p7,Q=!n7.jitless,w=Q&&fO.value,G=I.catchall,H;$._zod.parse=(W,Z)=>{H??(H=q.value);let X=W.value;if(!J(X))return W.issues.push({expected:"object",code:"invalid_type",input:X,inst:$}),W;if(Q&&w&&Z?.async===!1&&Z.jitless!==!0){if(!Y)Y=U(I.shape);if(W=Y(W,Z),!G)return W;return wf([],X,W,Z,H,$)}return z(W,Z)}});function lk($,I,z,q){for(let Y of $)if(Y.issues.length===0)return I.value=Y.value,I;let U=$.filter((Y)=>!V9(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)=>R6(J,q,D4())))}),I}var FY=o("$ZodUnion",($,I)=>{p0.init($,I),$1($._zod,"optin",()=>I.options.some((q)=>q._zod.optin==="optional")?"optional":void 0),$1($._zod,"optout",()=>I.options.some((q)=>q._zod.optout==="optional")?"optional":void 0),$1($._zod,"values",()=>{if(I.options.every((q)=>q._zod.values))return new Set(I.options.flatMap((q)=>Array.from(q._zod.values)));return}),$1($._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)=>YY(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 lk(J,q,$,U);return Promise.all(J).then((Q)=>{return lk(Q,q,$,U)})}});function ok($,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)=>R6(J,q,D4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:[],inclusive:!1});return I}var jN=o("$ZodXor",($,I)=>{FY.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 ok(J,q,$,U);return Promise.all(J).then((Q)=>{return ok(Q,q,$,U)})}}),vN=o("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,FY.init($,I);let z=$._zod.parse;$1($._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 w of K)U[Q].add(w)}}return U});let q=hI(()=>{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(!p7(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}}),RN=o("$ZodIntersection",($,I)=>{p0.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,w])=>{return rk(z,K,w)});return rk(z,Y,J)}});function iF($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if(W9($)&&W9(I)){let z=Object.keys(I),q=Object.keys($).filter((Y)=>z.indexOf(Y)!==-1),U={...$,...I};for(let Y of q){let J=iF($[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=iF(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 rk($,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(V9($))return $;let J=iF(I.value,z.value);if(!J.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}var Sw=o("$ZodTuple",($,I)=>{p0.
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){letK=$.external.registry.get(J[0])?.id;if(I!==J[0]&&K){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}}}}functionW9($,I){letq=$.seen.get(I);if(!q)throwError("Unprocessed schema. This is a bug in Zod.");letz=(Q)=>{letw=$.seen.get(Q);if(w.ref===null)return;letK=w.def??w.schema,H={...K},G=w.ref;if(w.ref=null,G){z(G);letV=$.seen.get(G),X=V.schema;if(X.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))K.allOf=K.allOf??[],K.allOf.push(X);elseObject.assign(K,X);if(Object.assign(K,H),Q._zod.parent===G)for(letDinK){if(D==="$ref"||D==="allOf")continue;if(!(DinH))deleteK[D]}if(X.$ref&&V.def)for(letDinK){if(D==="$ref"||D==="allOf")continue;if(DinV.def&&JSON.stringify(K[D])===JSON.stringify(V.def[D]))deleteK[D]}}letW=Q._zod.parent;if(W&&W!==G){z(W);letV=$.seen.get(W);if(V?.schema.$ref){if(K.$ref=V.schema.$ref,V.def)for(letXinK){if(X==="$ref"||X==="allOf")continue;if(XinV.def&&JSON.stringify(K[X])===JSON.stringify(V.def[X]))deleteK[X]}}}$.override({zodSchema:Q,jsonSchema:K,path:w.path??[]})};for(letQof[...$.seen.entries()].reverse())z(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,q.def??q.schema);letY=$.metadataRegistry.get(I)?.id;if(Y!==void0&&U.id===Y)deleteU.id;letJ=$.external?.defs??{};for(letQof$.seen.entries()){letw=Q[1];if(w.def&&w.defId){if(w.def.id===w.defId)deletew.def.id;J[w.defId]=w.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:aI(I,"input",$.processors),output:aI(I,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throwError("Error converting schema to JSON.")}}functiong6($,I){letq=I??{seen:newSet};if(q.seen.has($))return!1;q.seen.add($);letz=$._zod.def;if(z.type==="transform")return!0;if(z.type==="array")returng6(z.element,q);if(z.type==="set")returng6(z.valueType,q);if(z.type==="lazy")returng6(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")returng6(z.innerType,q);if(z.type==="intersection")returng6(z.left,q)||g6(z.right,q);if(z.type==="record"||z.type==="map")returng6(z.keyType,q)||g6(z.valueType,q);if(z.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returng6(z.in,q)||g6(z.out,q)}if(z.type==="object"){for(letUinz.shape)if(g6(z.shape[U],q))return!0;return!1}if(z.type==="union"){for(letUofz.options)if(g6(U,q))return!0;return!1}if(z.type==="tuple"){for(letUofz.items)if(g6(U,q))return!0;if(z.rest&&g6(z.rest,q))return!0;return!1}return!1}varMA=($,I={})=>(q)=>{letz=H9({...q,processors:I});returnh1($,z),G9(z,$),W9(z,$)},aI=($,I,q={})=>(z)=>{let{libraryOptions:U,target:Y}=z??{},J=H9({...U??{},target:Y,io:I,processors:q});returnh1($,J),G9(J,$),W9(J,$)};varSN0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},AA=($,I,q,z)=>{letU=q;U.type="string";let{minimum:Y,maximum:J,format:Q,patterns:w,contentEncoding:K}=$._zod.bag;if(typeofY==="number")U.minLength=Y;if(typeofJ==="number")U.maxLength=J;if(Q){if(U.format=SN0[Q]??Q,U.format==="")deleteU.format;if(Q==="time")deleteU.format}if(K)U.contentEncoding=K;if(w&&w.size>0){letH=[...w];if(H.length===1)U.pattern=H[0].source;elseif(H.length>1)U.allOf=[...H.map((G)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:G.source}))]}},PA=($,I,q,z)=>{letU=q,{minimum:Y,maximum:J,format:Q,multipleOf:w,exclusiveMaximum:K,exclusiveMinimum:H}=$._zod.bag;if(typeofQ==="string"&&Q.includes("int"))U.type="integer";elseU.type="number";letG=typeofH==="number"&&H>=(Y??Number.NEGATIVE_INFINITY),W=typeofK==="number"&&K<=(J??Number.POSITIVE_INFINITY),V=I.target==="draft-04"||I.target==="openapi-3.0";if(G)if(V)U.minimum=H,U.exclusiveMinimum=!0;elseU.exclusiveMinimum=H;elseif(typeofY==="number")U.minimum=Y;if(W)if(V)U.maximum=K,U.exclusiveMaximum=!0;elseU.exclusiveMaximum=K;elseif(typeofJ==="number")U.maximum=J;if(typeofw==="number")U.multipleOf=w},TA=($,I,q,z)=>{q.type="boolean"},EA=($,I,q,z)=>{if(I.unrepresentable==="throw")throwError("BigInt cannot be represented in JSON Schema")},BA=($,I,q,z)=>{if(I.unrepresentable==Line truncated
`)}return{warnings:[],results:J}}function DI($){return{fileBuffer:GH1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}import{existsSync as XH1}from"node:fs";async function SD($,I,q={}){let U=K4().stateful?"stateful":"stateless",Y="ok",J,Q,w;try{let A=await H$($);w={id:A.user.id,name:A.user.name,isAdmin:A.user.isAdmin},Q={id:A.tenant.id,name:A.tenant.name,tenantSlug:A.tenant.tenantSlug,corporationName:A.tenant.hoseCorpConfig?.corporationName}}catch(A){Y="error",J=A instanceof Error?A.message:String(A)}let K=[];if(Y==="ok")try{K=await X5($,I.seal.endpoints.approvalStylePreferences)}catch(A){Y="error",J=`读取Webhook配置失败:${AinstanceofError?A.message:String(A)}`}let H=K.length===1,G=K.map((A)=>({id:A.id,name:A.name,mode:A.mode,incomingDocumentWebhookUrl:A.incomingDocumentWebhook.url,outgoingResultWebhookUrl:A.outgoingResultWebhook,autoApprovalRate:A.autoApprovalRate,...H?{isDefault:!0}:{}})),W=H?{id:K[0].id,name:K[0].name,mode:K[0].mode}:null,V=q.webhook?j9(K,q.webhook):H?K[0]:void 0,X;if(q.filePath)if(!XH1(q.filePath))X={valid:!1,filePath:q.filePath,fileName:q.filePath.split(/[\\/]/).pop()??q.filePath,documentCount:0,errors:[`文件不存在:${q.filePath}`]};else try{let A=DI(q.filePath),g=await LI(A.fileBuffer,A.fileName,V?.materialPackFilePolicy);X={valid:!0,filePath:q.filePath,fileName:A.fileName,documentCount:g.documents.length,warnings:g.warnings}}catch(A){X={valid:!1,filePath:q.filePath,fileName:q.filePath.split(/[\\/]/).pop()??q.filePath,documentCount:0,errors:[A instanceof Error?A.message:String(A)]}}let L=X?X.valid:!0,D=Y==="ok"&&G.length>0&&L,O=U==="stateful"?"":`--corp${I.id}`,P="",T="";if(Y!=="ok")T=`凭证鉴权异常:${J}`,P=`seal-useauthdiagnose${O}`;else if(G.length===0)T="当前企业尚未配置任何 Webhook 集成通道",P=`seal-usewebhookadd--name"默认入站通道"--result-url"https://your-domain.com/callback"${O}`;else if(X&&!X.valid)T=`材料包预检失败:${X.errors?.join("; ")}`,P=`seal-usewebhookmaterial-packpreview${X.filePath}${O}`;else{T=H?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到${G.length}个Webhook通道,等待载入`;let A=X?.filePath??"<材料包.zip>",g=H?"":`--webhook${W?W.id:"<webhookIdOrName>"}`;P=`seal-usewebhookmaterial-packpush${A}${g}${O}`}return{ready:D,corp:{id:I.id,name:I.name,sourceType:I.source.type,tenant:Q,user:w},stateMode:U,authStatus:Y,authError:J,activeWebhooks:G,defaultWebhook:W,materialPack:X,statusMessage:T,nextAction:P}}var jw=[{name:"seal_whoami",description:"查询当前 Seal 用户身份及租户信息",parameters:Z.object({}),handler:async($)=>H$($)},{name:"seal_session_get",description:"查询当前 Seal Bearer session、用户和过期时间",parameters:Z.object({}),handler:async($)=>Il($)},{name:"seal_delegation_list",description:"查询当前 Seal 租户下的授权链接 (Delegation) 列表",parameters:Z.object({}),handler:async($)=>Tl($)},{name:"seal_delegation_create",description:"创建新的 Seal 授权链接 (Delegation)",parameters:Z.object({note:Z.string().optional().describe("授权链接的备注或说明信息")}),handler:async($,I)=>_q($,I)},{name:"seal_delegation_revoke",description:"撤销/废除指定的 Seal 授权链接 (Delegation)",parameters:Z.object({tokenId:Z.string().describe("授权链接 ID (delegation record ID)")}),handler:async($,I)=>El($,I.tokenId)},{name:"seal_user_create",description:"创建本地 Seal 用户,生成并返回初始随机密码",parameters:Z.object({name:Z.string().describe("用户姓名"),phone:Z.string().describe("手机号码 (例如 13300001111 或 +8613300001111)"),permissions:Z.array(Z.string()).optional().describe("权限列表,默认为 []"),departmentIds:Z.array(Z.string()).optional().describe("关联部门 ID 数组")}),handler:async($,I)=>Bl($,I)},{name:"seal_user_reset_password",description:"重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",parameters:Z.object({userId:Z.string().describe("用户 ID (_id)")}),handler:async($,I)=>FB($,I.userId)},{name:"seal_user_get",description:"获取指定 Seal 用户的详细信息",parameters:Z.object({userId:Z.string().describe("用户 ID (_id)")}),handler:async($,I)=>zW($,I.userId)},{name:"seal_user_search",description:"按姓名、手机号或邮箱搜索 Seal 成员用户列表",parameters:Z.object({keyword:Z.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")}),handler:async($,I)=>UW($,I.keyword??"")},{name:"seal_user_delete",description:"删除指定 Seal 本地用户",parameters:Z.object({userId:Z.string().describe("用户 ID (_id)")}),handler:async($,I)=>xl($,I.userId)},{name:"seal_user_activate",description:"启用/激活已离职的 Seal 用户账号",parameters:Z.object({userId:Z.string().describe("用户 ID (_id)")}),handler:async($,I)=>NB($,I.userId)},{name:"seal_user_delegation_create",description:"为指定 S
Line truncated
`+`•身份主体:${O}${P}
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){letw=$.external.registry.get(J[0])?.id;if(I!==J[0]&&w){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}}}}functionO9($,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;letw=K.def??K.schema,G={...w},H=K.ref;if(K.ref=null,H){q(H);letZ=$.seen.get(H),X=Z.schema;if(X.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))w.allOf=w.allOf??[],w.allOf.push(X);elseObject.assign(w,X);if(Object.assign(w,G),Q._zod.parent===H)for(letDinw){if(D==="$ref"||D==="allOf")continue;if(!(DinG))deletew[D]}if(X.$ref&&Z.def)for(letDinw){if(D==="$ref"||D==="allOf")continue;if(DinZ.def&&JSON.stringify(w[D])===JSON.stringify(Z.def[D]))deletew[D]}}letW=Q._zod.parent;if(W&&W!==H){q(W);letZ=$.seen.get(W);if(Z?.schema.$ref){if(w.$ref=Z.schema.$ref,Z.def)for(letXinw){if(X==="$ref"||X==="allOf")continue;if(XinZ.def&&JSON.stringify(w[X])===JSON.stringify(Z.def[X]))deletew[X]}}}$.override({zodSchema:Q,jsonSchema:w,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:Iz(I,"input",$.processors),output:Iz(I,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throwError("Error converting schema to JSON.")}}function_6($,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")return_6(q.element,z);if(q.type==="set")return_6(q.valueType,z);if(q.type==="lazy")return_6(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")return_6(q.innerType,z);if(q.type==="intersection")return_6(q.left,z)||_6(q.right,z);if(q.type==="record"||q.type==="map")return_6(q.keyType,z)||_6(q.valueType,z);if(q.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return_6(q.in,z)||_6(q.out,z)}if(q.type==="object"){for(letUinq.shape)if(_6(q.shape[U],z))return!0;return!1}if(q.type==="union"){for(letUofq.options)if(_6(U,z))return!0;return!1}if(q.type==="tuple"){for(letUofq.items)if(_6(U,z))return!0;if(q.rest&&_6(q.rest,z))return!0;return!1}return!1}varyA=($,I={})=>(z)=>{letq=L9({...z,processors:I});returnS1($,q),D9(q,$),O9(q,$)},Iz=($,I,z={})=>(q)=>{let{libraryOptions:U,target:Y}=q??{},J=L9({...U??{},target:Y,io:I,processors:z});returnS1($,J),D9(J,$),O9(J,$)};vareN0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},uA=($,I,z,q)=>{letU=z;U.type="string";let{minimum:Y,maximum:J,format:Q,patterns:K,contentEncoding:w}=$._zod.bag;if(typeofY==="number")U.minLength=Y;if(typeofJ==="number")U.maxLength=J;if(Q){if(U.format=eN0[Q]??Q,U.format==="")deleteU.format;if(Q==="time")deleteU.format}if(w)U.contentEncoding=w;if(K&&K.size>0){letG=[...K];if(G.length===1)U.pattern=G[0].source;elseif(G.length>1)U.allOf=[...G.map((H)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:H.source}))]}},xA=($,I,z,q)=>{letU=z,{minimum:Y,maximum:J,format:Q,multipleOf:K,exclusiveMaximum:w,exclusiveMinimum:G}=$._zod.bag;if(typeofQ==="string"&&Q.includes("int"))U.type="integer";elseU.type="number";letH=typeofG==="number"&&G>=(Y??Number.NEGATIVE_INFINITY),W=typeofw==="number"&&w<=(J??Number.POSITIVE_INFINITY),Z=I.target==="draft-04"||I.target==="openapi-3.0";if(H)if(Z)U.minimum=G,U.exclusiveMinimum=!0;elseU.exclusiveMinimum=G;elseif(typeofY==="number")U.minimum=Y;if(W)if(Z)U.maximum=w,U.exclusiveMaximum=!0;elseU.exclusiveMaximum=w;elseif(typeofJ==="number")U.maximum=J;if(typeofK==="number")U.multipleOf=K},kA=($,I,z,q)=>{z.type="boolean"},fA=($,I,z,q)=>{if(I.unrepresentable==="throw")throwError("BigInt cannot be represented in JSON Schema")},bA=($,I,z,q)=>{if(I.unrepresentable==Line truncated
`};import{existsSync as OI,mkdirSync as mK1,readFileSync as lK1,readdirSync as IV0,rmSync as oK1,unlinkSync as rK1,writeFileSync as tK1}from"node:fs";import{homedir as aK1}from"node:os";import{isAbsolute as sK1,join as E6,resolve as eK1}from"node:path";import{pathToFileURL as eW0}from"node:url";var r$=E6(aK1(),".config","seal-use","linters"),$w1="official",U5=E6(r$,$w1),BD=E6(process.cwd(),"linters");function zV0($=U5){let I=[],z=[];try{if(!OI($))mK1($,{recursive:!0});let q=Object.keys($u);for(let[Y,J]of Object.entries($u)){let Q=E6($,Y),K=!0;if(OI(Q))try{if(lK1(Q,"utf8")===J)K=!1}catch{K=!0}if(K)tK1(Q,J,"utf8");I.push(Y)}let U=IV0($,{withFileTypes:!0});for(let Y of U)if(!q.includes(Y.name)){let J=E6($,Y.name);try{if(Y.isDirectory())oK1(J,{recursive:!0,force:!0});else rK1(J);z.push(Y.name)}catch{}}}catch{}return{synced:I,pruned:z}}function qV0($={syncOfficial:!0}){if($.syncOfficial!==!1)zV0();let I=[{name:"builtin",type:"builtin",path:E6(U5,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:E6(U5,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"}],z=[r$,BD];for(let q of z)if(OI(q))try{let U=IV0(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:E6(q,J),description:`用户自定义规则校验器(${J})`})}}}catch{}return I}function Iw1($){let I=($||"").trim();if(!I||I==="builtin"||I==="default"||I==="official/builtin"||I==="official/builtin.ts")return{path:E6(U5,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(I==="strict"||I==="official/strict"||I==="official/strict.ts")return{path:E6(U5,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(sK1(I)||I.startsWith("./")||I.startsWith("../")){let q=eK1(I);if(OI(q))return{path:q};for(let U of[".ts",".js",".mjs"])if(OI(`${q}${U}`))return{path:`${q}${U}`}}let z=[E6(r$,`${I}.ts`),E6(r$,`${I}.js`),E6(r$,`${I}.mjs`),E6(BD,`${I}.ts`),E6(BD,`${I}.js`),E6(BD,`${I}.mjs`)];for(let q of z)if(OI(q))return{path:q};return{}}async function Iu($){zV0();let I=Iw1($??"builtin");if(I.isOfficial){let q=I.officialKind==="strict"?sW0:SU,U=I.officialKind==="strict"?"official":"builtin",Y=I.path;if(Y&&OI(Y))try{let Q=await import(eW0(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:$V0(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:SU};try{let U=await import(eW0(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:SU};return{name:$??"custom",type:"custom",filePath:z,linter:$V0(Y,SU)}}catch(q){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${z}"失败(语法错误或依赖缺失:${q?.message??q}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:SU}}}function$V0($,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)}}}asyncfunctionzu($,I,z){letq=awaitI.linter($,z);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:q.score,passed:q.passed,issues:q.issues,description:$.description}}asyncfunctionUV0($,I,z,q){letU=q?.minScore??0,Y=q?.level??"all",J=[],Q=0;for(letZof$){letX=awaitzu(Z,I,z);Q+=X.score;letL=X.issues;if(Y==="error")L=X.issues.filter((O)=>O.level==="error");elseif(Y==="warning")L=X.issues.filter((O)=>O.level==="warning"||O.level==="error");letD=L.every((O)=>O.level!=="error");if(q?.summary){if(L.length>0)J.push({...X,passed:D,issues:L})}elseJ.push({...X,passed:D,issues:L})}letK=$.length,w=K===0?100:Math.round(Q/K),G=J.filter((Z)=>Z.issues.length>0).length,H=K-G,W=w>=U&&J.every((Z)=>Z.passed);return{linter:I.name,linterType:I.type,totalRules:K,healthyCount:H,issueCount:G,overallScore:w,passed:W,issues:J}}import{existsSyncaszw1,readFileSyncasqw1,writeFileSyncasUw1,mkdirSyncasYw1}from"node:fs";import{dirnameasJw1,resolveasJV0}from"node:path";functionQw1($){letI;try{I=JSON.parse($)}catch(z){throwError(`本地规则文件JSON解析失败:${zinstanceofError?z.message:String(z)}`)}iLine truncated
`)}function rH1($){let I=[];if(I.push(`seal-use${$.area}-${$.title}`),$.description)I.push($.description);I.push(""),I.push("Usage:");for(let q of $.commands)for(let z of q.usage)I.push(`${z}`);if($.commands.some((q)=>q.name))I.push(""),I.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return I.join(`
`)}function SZ0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let I of uZ0)for(let q of I.commands)for(let z of q.usage)$.push(`${z}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:I.sso?G:w,sealResultUrl:w,ssoUrl:G,type:I.sso?"sso_link":"deep_link",expiresIn:I.sso?Z:void 0,identity:H,warning:W,enterpriseAssistUrl:J,enterpriseUrl:J,hoseDomain:Y.type==="hose"?PH1(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 TH1($,{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)=>P4($,Q.id))),Y=yZ0(I.fields),J=U.map((Q)=>NH1(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:eD(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=Jx(await gB($,I.batchId),I.query);return{batchId:I.batchId,count:z.length,records:z.map(PI),bridge:eD(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 CB($)).find((Q)=>Q.signKey)?.signKey,!q)throw Error("未找到合思集成 signKey, 请通过 signKey
Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:cU({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:zO(I,["template.name","templateName","form.name","formName","formTitle"]),amount:sD(z,["金额","报销金额","付款金额","合计","价税合计"])??zO(I,["amount","totalAmount","expenseAmount"]),expenseType:sD(z,["费用类型","费用类别","报销类型"]),costCompany:sD(z,["费用承担公司","承担公司","成本中心","费用归属"]),payee:sD(z,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:z.slice(0,30)}),invoices:LH1($),attachments:_U($,{summary:!0}).attachments,aiResult:UO($),manualResult:TI($)?.value,hints:cU({amountMentions:xZ0(q,["金额","合计","税率"],8),partyMentions:xZ0(q,["买方","卖方","甲方","乙方","收款"],8)})}}function WH1($){let I=[["result.citedRules",U9($,"result.citedRules")],["result.matchedRules",U9($,"result.matchedRules")],["result.ruleResults",U9($,"result.ruleResults")],["result.rules",U9($,"result.rules")],["pipelineData.citedRules",U9($,"pipelineData.citedRules")],["pipelineData.matchedRules",U9($,"pipelineData.matchedRules")]],z=[],q=new Set;for(let[U,Y]of I)(Array.isArray(Y)?Y:Y&&typeof Y==="object"?Object.values(Y):[]).forEach((Q,K)=>{let w=hK(Q);if(!w)return;let G=J4(w.runtimeRuleId)??J4(w.runtimeId)??J4(w.id)??J4(w.ruleId),H=J4(w.ruleCode)??J4(w.code)??(G?FH1(G):void 0),W=cU({runtimeRuleId:G,ruleCode:H,versionNumber:ZH1(w.versionNumber)??$.ruleSetVersionNumber,scope:J4(w.scope),strictness:J4(w.strictness),appliedAnalysis:w.appliedAnalysis??w.analysis??w.reasoning,checkResult:w.checkResult??w.result??w.decision,findings:w.findings??w.riskPoints??w.evidence,sourcePath:`${U}.${K}`}),Z=JSON.stringify(W);if(!q.has(Z))q.add(Z),z.push(W)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:z.length,rules:z}}function zO($,I){if(!$)return;for(let z of I){let q=U9($,z);if(q!==void 0)return q}return}function uZ0($,I){if(!$)return 0;for(let z of I){let q=U9($,z);if(Array.isArray(q))return q.length;if(q&&typeof q==="object")return Object.keys(q).length;if(typeof q==="number")return q}return 0}function U9($,I){return I.split(".").reduce((z,q)=>{if(z===void 0||z===null)return;if(Array.isArray(z)){let U=Number(q);return Number.isInteger(U)?z[U]:void 0}if(typeof z==="object")return z[q];return},$)}function VH1($,I,z){let q=I.split("."),U=$;for(let Y of q.slice(0,-1)){let J=U[Y];if(!J||typeof J!=="object"||Array.isArray(J))U[Y]={};U=U[Y]}U[q[q.length-1]??I]=z}function cU($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function hK($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function ZH1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function XH1($){let I=[];return $x($,"document",I),I}function $x($,I,z){if(Array.isArray($)){$.forEach((J,Q)=>$x(J,`${I}.${Q}`,z));return}let q=hK($);if(!q)return;let U=J4(q.label)??J4(q.name)??J4(q.title)??J4(q.fieldName),Y=q.value??q.displayValue??q.text??q.content;if(U&&Y!==void 0&&typeof Y!=="object")z.push(cU({path:I,label:U,value:Y,type:J4(q.type)??J4(q.fieldType)}));for(let[J,Q]of Object.entries(q)){if(J==="attachments")continue;$x(Q,`${I}.${J}`,z)}}function sD($,I){return $.find((q)=>{let U=J4(q.label)??"";return I.some((Y)=>U.includes(Y))})?.value}function LH1($){let I=[];return qO($.result,"result",I),qO($.document,"document",I),I.slice(0,20)}function qO($,I,z){if(Array.isArray($)){$.forEach((U,Y)=>qO(U,`${I}.${Y}`,z));return}let q=hK($);if(!q)return;if(/invoice|发票/i.test(I))z.push(cU({path:I,fileName:J4(q.fileName)??J4(q.filename)??J4(q.name),buyer:q.buyer??q.buyerName??q.purchaserName,seller:q.seller??q.sellerName,amount:q.amount??q.totalAmount??q.total,taxRate:q.taxRate,category:q.category??q.type}));for(let[U,Y]of Object.entries(q))qO(Y,`${I}.${U}`,z)}function xZ0($,I,z){return $.split(/\r?\n/).filter((q)=>I.some((U)=>q.includes(U))).slice(0,z)}function eD($){return $.map((I)=>{let z=PI(I);return{recordId:z.id,tenantId:z.tenantId,agentId:z.agentId,sourceDocumentSN:z.sourceDocumentSN,sourceDocumentId:z.sourceDocumentId,simulationBatchId:z.simulationBatchId,langfuseTraceId:z.langfuseTraceId,langfuseSessionFallback:z.langfuseSessionFallback,ruleSetVersionNumber:z.ruleSetVersionNumber,ruleSetPublishedAt:z.ruleSetPublishedAt,ruleSetPublishedByName:z.ruleSetPublishedByName,resolution:z.langfuseTraceId?"trace":z.langfuseSessionFallback?"session-fallback":"unresolved"}})}function su($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function DH1($,I){if(I.recordId&&!I.versionId&&!I.versionNumber&&!I.latest){let z=await P4($,I.recordId);if(!z.ruleSetVersionNumber)throw Er
Line truncated
`)}function CH1($){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 YX0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let I of JX0)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(`
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let W of G){let V=W.outboundName??"SealAI 审批",X=W.signKey,L=W.apiOrigin??"production";console.error(`•"${V}"(signKey:${X},环境:${L})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${X}--corp${U.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let W of H){let Z=W.outboundName??"SealAI 审批",X=W.signKey,L=W.apiOrigin??"production";console.error(`•"${Z}"(signKey:${X},环境:${L})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${X}--corp${U.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let X of W){let L=X.outboundName??"SealAI 审批",D=X.signKey,O=X.apiOrigin??"production";console.error(`•"${L}"(signKey:${D},环境:${O})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${D}--corp${U.id}
`);throw new r$("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,W.length===1?`seal-usedeployhosecloudsync${W[0].signKey}--corp${U.id}`:void 0)}await F0("seal_deploy_hosecloud_sync",z,U,{signKey:K},W0(Y.options));return}throw Error(`Unknowndeployhosecloudaction:${Q??""}.Available:requirements,list,get,status,configure,sync.`)}import{accessSync as UW1,constants as YW1,existsSync as M$,readdirSync as JW1}from"node:fs";import{homedir as QW1}from"node:os";import{join as $9}from"node:path";import{existsSync as Hx,mkdirSync as SL0,rmSync as IW1,writeFileSync as qW1}from"node:fs";import{homedir as uL0}from"node:os";import{dirname as zW1,join as Gx}from"node:path";var PL0=`---
`);throw new w$("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,W.length===1?`seal-usedeployhosecloudsync${W[0].signKey}--corp${U.id}`:void 0)}await F0("seal_deploy_hosecloud_sync",q,U,{signKey:w},W0(Y.options));return}throw Error(`Unknowndeployhosecloudaction:${Q??""}.Available:requirements,list,get,status,configure,sync.`)}import{accessSync as fW1,constants as bW1,existsSync as B6,readdirSync as nW1}from"node:fs";import{homedir as iW1}from"node:os";import{join as J9}from"node:path";import{existsSync as Ax,mkdirSync as eL0,rmSync as uW1,writeFileSync as xW1}from"node:fs";import{homedir as $D0}from"node:os";import{dirname as kW1,join as Px}from"node:path";var iL0=`---
name:seal-use
description:"v0.10.18: 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.19: 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.
@@ -422,6 +747,7 @@ seal-use corps list
-Inthedefaultstatelessmode,everyenterprisecommandrequires\`--corp <corpId>\`. In stateful mode, omitting \`--corp\` uses the configured default enterprise and is unsafe for an explicitly named enterprise.
-Foranexplicitlynamedenterprise,resolveitdirectlywith\`seal-use corps search <name>\` (or \`seal-use corps get <corpId>\` if given an exact ID) rather than dumping all enterprises with \`seal-use corps list\`. Then pass its exact \`corpId\` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link.
-User-facingSealtenantassistancelink(Seal协助/Seal授权/委托):resolvethenamedenterprisefirst,thenrun\`seal-use delegation create --corp <corpId> --note '<enterprise>'\`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (\`\`\`\`text ... \`\`\`\`) AND a hyperlink.
-Packagedcustomerfeedback→approval-ruleremediation:read\`references/customer-feedback-rule-remediation.md\`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
-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 TL0=`interface:
`;var pL0=`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."
@@ -653,7 +979,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 jL0="# 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-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-useopenapi\nseal-usedoctor[--quiet]\nseal-usedoctorguide\nseal-usedoctorpaths\nseal-useprobe[<corpId>]\nseal-usetoolslist\nseal-usecorpslist[query][--env<production|test>][--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-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]\nseal-usedelegationlist[--corp<corpId>]\nseal-usedelegationcreate[--note<note>][--from-link<url>][--corp<corpId>]\nseal-usedelegationrevoke<tokenId>[--corp<corpId>]\nseal-useuserscreate--name<name>--phone<phone>[--dept<deptId>][--corp<corpId>]\nseal-useuserssearch<keyword>[--corp<corpId>]\nseal-useusersdelegation<userIdOrPhone|name>[--note<note>][--corp<corpId>]\nseal-useusersactivate<userId>[--corp<corpId>]\nseal-useusersreseLine truncated
`;var mL0="# 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-useopenapi\nseal-usedoctor[--quiet]\nseal-usedoctorguide\nseal-usedoctorpaths\nseal-useprobe[<corpId>]\nseal-usetoolslist\nseal-usecorpslist[query][--env<production|test>][--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-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]\nseal-usedelegationlist[--corp<corpId>]\nseal-usedelegationcreate[--note<note>][--from-link<url>][--corp<corpId>]\nseal-usedelegationrevoke<tokenId>[--corp<corpId>]\nseal-useuserscreate--name<name>--phone<phone>[--dept<deptId>][--corpLine truncated
-\`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.
`)}async function pL0($,I,q){let z=($??I??"").toLowerCase();if(z==="guide"||z==="doc"||z==="knowledge"||z==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(nL0());return}if(z==="paths"||z==="dirs"||z==="directories"){let J=Ox();E0(J.directories);return}let U=Ox();if(!(O0(q.options.quiet)||O0(q.options.silent)))console.error(iL0(U));E0(U)}import{createServer as WW1}from"node:http";import{URL as KW1}from"node:url";var cL0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.18",description:`PlannedHTTPcontractfortheseal-usewrappedbackendAPI.
`)}async function KD0($,I,z){let q=($??I??"").toLowerCase();if(q==="guide"||q==="doc"||q==="knowledge"||q==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(YD0());return}if(q==="paths"||q==="dirs"||q==="directories"){let J=Rx();T0(J.directories);return}let U=Rx();if(!(V0(z.options.quiet)||V0(z.options.silent)))console.error(QD0(U));T0(U)}import{createServer as lW1}from"node:http";import{URL as cW1}from"node:url";var wD0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.19",description:`PlannedHTTPcontractfortheseal-usewrappedbackendAPI.
`},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(z)})})}async function lL0($){let I=i0($.options.port)??i0($.options.p),q=C($.options.host)??C($.options.h),z=await YO({port:I,host:q}),U=()=>{z.close(()=>{process.exit(0)})};process.on("SIGINT",U),process.on("SIGTERM",U),await new Promise(()=>{})}async function oL0($,I,q,z){if($==="config"||$==="get"){await F0("seal_llm_config_get",I,q,{},W0(z.options));return}if($==="providers"||$==="list"){await F0("seal_llm_providers_list",I,q,{},W0(z.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function rL0($,I){if($==="config"||$==="json"){Nx();return}await Mx()}function Nx(){E0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function tL0($){let I=$O();E0(I,{...W0($.options),allowFull:!0})}async function aL0($,I,q,z){if($==="available"){await F0("seal_permissions_available_list",I,q,{},W0(z.options));return}if($==="configs"||$==="list"){await F0("seal_permissions_configs_list",I,q,{},W0(z.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{readFileSync as sL0}from"node:fs";async function eL0($,I,q,z,U,Y,J){if(!$||$==="get"){await F0("seal_preference_get",U,Y,{},W0(J.options));return}if($==="decision"){if(I==="update"||!I){let Q=C(J.options.input),w=Q?JSON.parse(sL0(Q,"utf8")):z$(J.json);if(!w||Object.keys(w).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await F0("seal_preference_decision_update",U,Y,{...w,dryRun:O0(J.options.dryRun)??O0(J.options["dry-run"])},W0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let Q=C(J.options.default)??C(J.options.level)??z;if(Q!=="medium"&&Q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await F0("seal_preference_thinking_depth_set",U,Y,{defaultLevel:Q,dryRun:O0(J.options.dryRun)??O0(J.options["dry-run"])},W0(J.options));return}if(I==="policies"){if(q==="list"||!q){await F0("seal_preference_thinking_depth_policies_list",U,Y,{},W0(J.options));return}if(q==="upsert"){let Q=C(J.options.input),w=Q?JSON.parse(sL0(Q,"utf8")):z$(J.json);if(!w||!w.id||!w.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await F0("seal_preference_thinking_depth_policies_upsert",U,Y,{...w,dryRun:O0(J.options.dryRun)??O0(J.options["dry-run"])},W0(J.options));return}if(q==="remove"||q==="delete"){let Q=z??C(J.options.id)??C(J.options.policyId);if(!Q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await F0("seal_preference_thinking_depth_policies_remove",U,Y,{policyId:Q,dryRun:O0(J.options.dryRun)??O0(J.options["dry-run"])},W0(J.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}async function $D0($={}){let I=c$(),q=K4(),z=vU(I,{stateful:q.stateful,defaultCorpId:q.defaultCorpId,corpId:$.corpId},HI());console.log(`[probe]corp=${z.id}source=${z.source.type}`);let U=await iU(z);console.log("[probe] seal enterprise"),console.log(JSON.stringify(U,null,2));let Y=await y1(z),J=await WW(Y,{documentLimit:20,stylePreferencesEndpoint:z.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:J.rules.rules.length,hasPendingRuleDeletes:J.rules.hasPendingDeletes,documents:J.documents.articles.length,documentsTotal:J.documents.total,stylePreferences:J.stylePreferences.ok?"ok":`error:${J.stylePreferences.error}`},null,2))}async function ID0($,I,q){let z=I??C(q.options.corp)??($&&$!=="--corp"?$:void 0);await $D0({corpId:z})}async function Ax($,I,q,z,U){if($==="count"){await F0("seal_approval_rules_list",q,z,{countOnly:!0},W0(U.options));return}if($==="list"){if(O0(U.options.count)){await F0("seal_approval_rules_list",q,z,{countOnly:!0},W0(U.options));return}let Y=i0(U.options.limit),J=i0(U.options.offset);if(O0(U.options.summary)){await F0("seal_approval_rules_list",q,z,{fields:kZ0,limit:Y,offset:J},W0(U.options));return}let Q=await MI("seal_approval_rules_list",q,z,{limit:Y,offset:J});fZ0(Q,O0(U.options.full)===!0),E0(Q);return}if($==="clear"){let Y=O0(U.options.yes)===!0,J=O0(U.options.dryRun)??O0(U.options["dry-run"])??!Y;if(!Y&&!J)throw q5("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${z.id}--dry-run`);let Q=await MI("seal_approval_rules_clear",q,z,{dryRun:J,recode:O0(U.options.recode)});if(!Y&&J&&Q&&typeof Q==="object"){E0({...Q,nextCommand:`seal-userulesclear--corp${z.id}--yes`},W0(U.options));return}E0(Q,W0(U.options));return}if($==="versions"){await F0("seal_approval_rule_versions_list",q,z,{},W0(U.options));return}if($==="version"){let Y=I??C(U.options.version);if(!Y)throw Error("Usage: seal-use rules version <versionId|versionNumber|l
Line truncated
`).filter(Boolean),Y=U.slice(-I);return{logFile:q,lines:Y,totalLines:U.length}}async function DW1($){let I=KO($),q=Ex($),z=fw($);YD0($.stateDir);let U=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):zO),Y=$.host??(process.env.HOST?process.env.HOST:UO);QO(I,`${process.pid}
`,{mode:384}),QO(q,JSON.stringify({pid:process.pid,port:U,host:Y,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),pU(z,`servicestartingonhttp://${Y}:${U} pid=${process.pid}`);let J=null;try{J=await YO({port:U,host:Y,silent:!0}),pU(z,`service listening pid=${process.pid}`)}catch(w){if(pU(z,`service failed to bind port ${U}: ${w instanceof Error?w.message:String(w)}`),wO(I)===process.pid)z5(I,{force:!0}),z5(q,{force:!0});throw w}let Q=()=>{if(J)J.close(),J=null;if(wO(I)===process.pid)z5(I,{force:!0}),z5(q,{force:!0});pU(z,`stopped pid=${process.pid}`)};await new Promise((w)=>{let K=!1,H=()=>{if(K)return;K=!0,Q(),process.off("SIGTERM",H),process.off("SIGINT",H),w()};process.once("SIGTERM",H),process.once("SIGINT",H)})}function qD0($){YD0($.stateDir);let I=cU($);if(I.running)return I;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 U=VW1(q.command,z,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});U.unref();let Y=KO($);return QO(Y,`${U.pid}
`,{flag:"a",mode:384})}var Bx=NW1(FW1(),".config","seal-use");async function jx($,I,q){let z=q?i0(q.options.port)??i0(q.options.p):void 0,U=q?C(q.options.host)??C(q.options.h):void 0,Y=q?i0(q.options.lines)??i0(q.options.n):void 0,J=await PI($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:Bx,version:s0,launcher:I.launcher,port:z,host:U},{maxLines:Y});if(J!==void 0)E0(J)}import{existsSync as MW1,readFileSync as JD0}from"node:fs";async function QD0($,I,q,z,U){if($==="batch-records"||$==="records"){let Y=I??C(U.options.batchId)??C(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation batch-records <batchId>");await F0("seal_simulation_batch_records_get",q,z,{batchId:Y,query:C(U.options.query)},W0(U.options));return}if($==="create"||$==="run"){let Y=C(U.options.mode)??C(U.options.sourceSystem)??C(U.options["source-system"])??"hosecloud",J=Y==="material-pack"?"material_pack":Y,Q=C(U.options.schemaConfig)??C(U.options["schema-config"]),w=Q?JSON.parse(JD0(Q,"utf8")):void 0,K=C(U.options.input),H=K?JSON.parse(JD0(K,"utf8")):z$(U.json),G=C(U.options.packageId)??C(U.options["package-id"]),W=V6(U.options.packageIds)??V6(U.options["package-ids"])??(G?[G]:void 0),V=V6(U.options.flowIds)??V6(U.options["flow-ids"])??V6(U.options.documentSn)??V6(U.options["document-sn"]),X=C(U.options.signKey)??C(U.options["sign-key"])??C(U.options.integration),L=O0(U.options.noWait)??O0(U.options["no-wait"]);await F0("seal_simulation_batch_create",q,z,{mode:J,sourceSystem:J,flowIds:V,documentSn:V,rejectNodeName:C(U.options.rejectNode)??C(U.options["reject-node"])??null,thinkingDepthOverride:C(U.options.thinkingDepth)??C(U.options["thinking-depth"]),skipInvoiceGeneration:O0(U.options.skipInvoiceGeneration)??O0(U.options["skip-invoice-generation"]),skipExpenseExtraction:O0(U.options.skipExpenseExtraction)??O0(U.options["skip-expense-extraction"]),disableAttachmentCache:O0(U.options.disableAttachmentCache)??O0(U.options["disable-attachment-cache"]),signKey:X,packageIds:W,packageId:G,templateId:C(U.options.templateId)??C(U.options["template-id"]),schemaConfig:w,requestIds:V6(U.options.requestIds)??V6(U.options["request-ids"]),workflowTypeId:C(U.options.workflowTypeId)??C(U.options["workflow-type-id"]),flowStatusList:V6(U.options.flowStatusList)?.map(Number)??V6(U.options["flow-status-list"])?.map(Number),businessCodes:V6(U.options.businessCodes)??V6(U.options["business-codes"]),documentType:C(U.options.documentType)??C(U.options["document-type"]),startTime:i0(U.options.startTime)??i0(U.options["start-time"]),endTime:i0(U.options.endTime)??i0(U.options["end-time"]),status:V6(U.options.status),limit:i0(U.options.limit),noWait:L,rawParams:H},W0(U.options));return}if($==="wait"){let Y=I??C(U.options.batchId)??C(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await F0("seal_simulation_batch_wait",q,z,{batchId:Y,timeout:C(U.options.timeout),pollInterval:C(U.options.pollInterval)??C(U.options["poll-interval"])},W0(U.options));return}if($==="status"){let Y=I??C(U.options.batchId)??C(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation status <batchId>");await F0("seal_simulation_batch_status",q,z,{batchId:Y},W0(U.options));return}if($==="clean"||$==="delete"){let Y=I??C(U.options.batchId)??C(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation clean <batchId>");await F0("seal_simulation_batch_clean",q,z,{batchId:Y},W0(U.options));return}if($==="specifications"){let Y=I??C(U.options.integration)??C(U.options.signKey)??C(U.options["sign-key"]);await F0("seal_simulation_specifications_list",q,z,{signKey:Y},W0(U.options));return}if($==="approval-definitions"||$==="definitions"){await F0("seal_simulation_feishu_approval_definitions_list",q,z,{},W0(U.options));return}if($==="list"){await F0("seal_simulation_batches_list",q,z,{limit:i0(U.options.limit)},W0(U.options));return}if($==="get"){let Y=I??C(U.options.batchId)??C(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation get <batchId>");await F0("seal_simulation_batch_get",q,z,{batchId:Y},W0(U.options));return}if($==="templates"){await F0("seal_simulation_templates_get",q,z,{},W0(U.options));return}if($==="integrations"){await F0("seal_simulation_integrations_get",q,z,{},W0(U.options));return}if($==="package-upload"){let Y=I??C(U.options.file);if(!Y)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!MW1(Y))throw Error(`Filenotfound:${Y}`);await F0("seal_simulation_material_package_upload",q,z,{filePath:Y},W0(U.options));return}throw Error(`Unknownsimulationcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{existsSync as wD0}from"node:fs";import{join as HO}from"node:path";function KD0($,I,q){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${xL0()}
`);return}if($==="install"||$==="init"||$==="sync"){let z=O0(q.options.local)||O0(q.options.workspace),U=C(q.options.dir)??C(q.options.target)??I,Y=U?U:z?HO(process.cwd(),".agents","skills","seal-use"):AI(),J=Wx(Y);E0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files});return}if($==="status"||$==="get"||!$){let z=AI(),U=HO(process.cwd(),".agents","skills","seal-use");E0({global:{dir:z,installed:wD0(HO(z,"SKILL.md"))},local:{dir:U,installed:wD0(HO(U,"SKILL.md"))}});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}async function HD0($,I){if($==="config"){E0(await iU(I));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function GD0($,I,q,z){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await F0($,I,q,z$(z.json),W0(z.options))}function WD0(){E0(jw.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as AW1,mkdirSync as PW1,renameSync as gx,rmSync as TW1,unlinkSync as DD0,writeFileSync as VD0}from"node:fs";import{dirname as EW1,join as ZD0}from"node:path";import{spawnSync as TI}from"node:child_process";function GO($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let q=$.toLowerCase().replace(/\\/g,"/");return!q.endsWith("/bun")&&!q.endsWith("/bun.exe")&&!q.endsWith("/node")&&!q.endsWith("/node.exe")}var OD0="yunyingk/seal-use",bw="yunyingk/seal-home";var BW1="SEAL_USE_GITHUB_REPO",jW1="SEAL_HOME_GITHUB_REPO";async function FD0($,I={}){let q={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Bx,version:s0,launcher:$.launcher},z=I.repo||process.env[BW1]?.trim()||process.env[jW1]?.trim()||OD0,U=I.targetVersion?.trim(),Y=U&&U.toLowerCase()!=="latest"?U:void 0;if(Y){let A=Y.replace(/^v/,""),g=ND0(A,s0);if(g<0)if(!zB&&I.force);else{E0({updated:!1,currentVersion:s0,targetVersion:A,mode:GO()?"binary":"source",message:!zB?`Cannotdowngradeseal-usefromdevbuildv${s0}toreleasev${A}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${s0}toolderversionv${A}.Updatesmustbeforward-only.`});return}if(g===0&&!I.force){E0({updated:!1,currentVersion:s0,targetVersion:A,mode:GO()?"binary":"source",message:`seal-useisalreadyatversionv${s0}.Use--forcetoreinstall.`});return}}if(I.changelogOnly){let A=await vx(z,I.limit??10);E0({currentVersion:s0,totalQueried:A.length,releases:A.map((g)=>({version:g.version,tagName:g.tagName,publishedAt:g.publishedAt,author:g.author,releaseNotes:g.notes,releaseUrl:g.htmlUrl,isCurrent:g.version===s0,isNewer:nw(g.version,s0)}))});return}if(!GO()){if(I.checkOnly){let g=await vx(z,30),k=g[0],S=k?.version??s0,f=g.find((i)=>i.version===s0),v=nw(S,s0),p=g.filter((i)=>nw(i.version,s0));E0({updated:!1,updateAvailable:v,currentVersion:s0,currentVersionPublishedAt:f?.publishedAt,latestVersion:S,latestVersionPublishedAt:k?.publishedAt,behindCount:p.length,pendingReleases:p.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=cU(q).running;if(A)await PI("stop",q);try{LD0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(g){console.error(`gitpullskipped:${ginstanceofError?g.message:String(g)}`)}if(LD0("bun",["install"],{cwd:$.appRoot}),A)await PI("start",q);E0({updated:!0,serviceRestarted:A,version:s0,mode:"source"});return}let J=gW1(),Q=vW1(),w=await vx(z,30),K=Y?w.find((A)=>A.version===Y||A.tagName===Y||A.tagName===`v${Y}`)??await XD0(z,Y):w[0]??await XD0(z);if(!K){E0({updated:!1,currentVersion:s0,mode:"binary",message:`Failedtoqueryreleasesfromrepository'${z}'`});return}let H=K.version,G=w.find((A)=>A.version===s0),W=nw(H,s0),V=W||Boolean(I.force),X=w.filter((A)=>nw(A.version,s0));if(I.checkOnly){E0({updated:!1,updateAvailable:W,currentVersion:s0,currentVersionPublishedAt:G?.publishedAt,latestVersion:H,latestVersionPublishedAt:K.publishedAt,behindCount:X.length,pendingReleases:X.map((A)=>({version:A.version,tagName:A.tagName,publishedAt:A.publishedAt,author:A.author,releaseNotes:A.notes,releaseUrl:A.htmlUrl})),releaseNotes:K.notes,releaseUrl:K.htmlUrl,mode:"binary"});return}if(!V){E0({updated:!1,currentVersion:s0,currentVersionPublishedAt:G?.publishedAt,latestVersion:H,latestVersionPublishedAt:K.publishedAt,mode:"binary",message:`seal-useisalreadyuptodate(v${s0})`});return}let L=RW1(K.assets,J,Q);if(!L)throw Error(`Nocompatiblebinaryfoundfor${J}-${Q}inreleasev${H}.Availableassets:${K.assets.map((A)=>A.name).join(", ")}`);let D=cU(q).running;if(D)await PI("stop",q);let O=process.execPath,P=EW1(O),T=ZD0(P,`.tmp-update-${Date.now()}`);PW1(T,{recursive:!0});try{let A=ZD0(T,L.name);await CW1(L.downloadUrl,A,K.tagName,L.name);let g=A;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))g=_W1
Line truncated
`)}catch{}}async function CW1($,I,q,z){let U=Rx(),Y=[],J=q?q.startsWith("v")?q:`v${q}`:void 0,Q=z||$.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/${OD0}/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 w=Array.from(new Set(Y)),K,H=6000,G=6000,W=307200,V=1e4,X=180000;for(let L=0;L<w.length;L++){let D=w[L],O=new AbortController,P="",T=(S)=>{P=S;try{O.abort()}catch{}},A=setTimeout(()=>{T("Connection timed out (no response headers within 6s)")},H),g,k;try{WO(`==> [${L+1}/${w.length}] Downloading via: ${D}`);let S=await fetch(D,{signal:O.signal});if(A)clearTimeout(A),A=void 0;if(!S.ok)throw Error(`HTTP ${S.status} ${S.statusText}`);g=setTimeout(()=>{T("Overall download time exceeded 3 minutes")},X);let f=Number(S.headers.get("content-length"))||0,v=S.body?.getReader();if(!v){let b=Buffer.from(await S.arrayBuffer());if(b.length<1000)throw Error(`Downloaded content is suspiciously small (${b.length} bytes)`);VD0(I,b),WO(`✓ Download succeeded (${(b.length/1024/1024).toFixed(1)} MB)`);return}let p=[],i=0,h=0;k=setTimeout(()=>{if(i<W){let b=(i/1024).toFixed(1);T(`Initial transfer too slow (${b} KB < 300 KB in 6s), switching mirror...`)}},G);while(!0){let b=v.read(),q0,B=new Promise((U0,G0)=>{q0=setTimeout(()=>{G0(Error("Data transfer stalled (no chunk received for 10s)"))},V)}),x;try{x=await Promise.race([b,B])}finally{if(q0)clearTimeout(q0)}let{done:c,value:r}=x;if(c)break;if(r){if(p.push(r),i+=r.length,k&&i>=W)clearTimeout(k),k=void 0;let U0=Date.now();if(U0-h>200){h=U0;let G0=f?Math.round(i/f*100):0,A0=(i/1048576).toFixed(1),v0=f?(f/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${G0}% (${A0} / ${v0} MB)...`)}catch{}}}}try{process.stderr.write(`
`);U(q)})})}async function WD0($){let I=y0($.options.port)??y0($.options.p),z=j($.options.host)??j($.options.h),q=await FO({port:I,host:z}),U=()=>{q.close(()=>{process.exit(0)})};process.on("SIGINT",U),process.on("SIGTERM",U),await new Promise(()=>{})}async function VD0($,I,z,q){if($==="config"||$==="get"){await F0("seal_llm_config_get",I,z,{},W0(q.options));return}if($==="providers"||$==="list"){await F0("seal_llm_providers_list",I,z,{},W0(q.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function ZD0($,I){if($==="config"||$==="json"){_x();return}await Cx()}function _x(){T0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function XD0($){let I=ZO();T0(I,{...W0($.options),allowFull:!0})}async function LD0($,I,z,q){if($==="available"){await F0("seal_permissions_available_list",I,z,{},W0(q.options));return}if($==="configs"||$==="list"){await F0("seal_permissions_configs_list",I,z,{},W0(q.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{readFileSync as DD0}from"node:fs";async function OD0($,I,z,q,U,Y,J){if(!$||$==="get"){await F0("seal_preference_get",U,Y,{},W0(J.options));return}if($==="decision"){if(I==="update"||!I){let Q=j(J.options.input),K=Q?JSON.parse(DD0(Q,"utf8")):H$(J.json);if(!K||Object.keys(K).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await F0("seal_preference_decision_update",U,Y,{...K,dryRun:V0(J.options.dryRun)??V0(J.options["dry-run"])},W0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let Q=j(J.options.default)??j(J.options.level)??q;if(Q!=="medium"&&Q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await F0("seal_preference_thinking_depth_set",U,Y,{defaultLevel:Q,dryRun:V0(J.options.dryRun)??V0(J.options["dry-run"])},W0(J.options));return}if(I==="policies"){if(z==="list"||!z){await F0("seal_preference_thinking_depth_policies_list",U,Y,{},W0(J.options));return}if(z==="upsert"){let Q=j(J.options.input),K=Q?JSON.parse(DD0(Q,"utf8")):H$(J.json);if(!K||!K.id||!K.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await F0("seal_preference_thinking_depth_policies_upsert",U,Y,{...K,dryRun:V0(J.options.dryRun)??V0(J.options["dry-run"])},W0(J.options));return}if(z==="remove"||z==="delete"){let Q=q??j(J.options.id)??j(J.options.policyId);if(!Q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await F0("seal_preference_thinking_depth_policies_remove",U,Y,{policyId:Q,dryRun:V0(J.options.dryRun)??V0(J.options["dry-run"])},W0(J.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}async function FD0($={}){let I=K$(),z=Y4(),q=C7(I,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$.corpId},e5());console.log(`[probe]corp=${q.id}source=${q.source.type}`);let U=await lU(q);console.log("[probe] seal enterprise"),console.log(JSON.stringify(U,null,2));let Y=await H1(q),J=await OW(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))}async function ND0($,I,z){let q=I??j(z.options.corp)??($&&$!=="--corp"?$:void 0);await FD0({corpId:q})}async function hx($,I,z,q,U){if($==="count"){await F0("seal_approval_rules_list",z,q,{countOnly:!0},W0(U.options));return}if($==="list"){if(V0(U.options.count)){await F0("seal_approval_rules_list",z,q,{countOnly:!0},W0(U.options));return}let Y=y0(U.options.limit),J=y0(U.options.offset);if(V0(U.options.summary)){await F0("seal_approval_rules_list",z,q,{fields:wX0,limit:Y,offset:J},W0(U.options));return}let Q=await BI("seal_approval_rules_list",z,q,{limit:Y,offset:J});GX0(Q,V0(U.options.full)===!0),T0(Q);return}if($==="clear"){let Y=V0(U.options.yes)===!0,J=V0(U.options.dryRun)??V0(U.options["dry-run"])??!Y;if(!Y&&!J)throw q5("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${q.id}--dry-run`);let Q=await BI("seal_approval_rules_clear",z,q,{dryRun:J,recode:V0(U.options.recode)});if(!Y&&J&&Q&&typeof Q==="object"){T0({...Q,nextCommand:`seal-userulesclear--corp${q.id}--yes`},W0(U.options));return}T0(Q,W0(U.options));return}if($==="versions"){await F0("seal_approval_rule_versions_list",z,q,{},W0(U.options));return}if($==="version"){let Y=I??j(U.options.version);if(!Y)throw Error("Usage: seal-use rules version <versionId|versionNumber|l
Line truncated
`).filter(Boolean),Y=U.slice(-I);return{logFile:z,lines:Y,totalLines:U.length}}async function sW1($){let I=PO($),z=ux($),q=cK($);TD0($.stateDir);let U=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):DO),Y=$.host??(process.env.HOST?process.env.HOST:OO);MO(I,`${process.pid}
`,{mode:384}),MO(z,JSON.stringify({pid:process.pid,port:U,host:Y,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),oU(q,`servicestartingonhttp://${Y}:${U} pid=${process.pid}`);let J=null;try{J=await FO({port:U,host:Y,silent:!0}),oU(q,`service listening pid=${process.pid}`)}catch(K){if(oU(q,`service failed to bind port ${U}: ${K instanceof Error?K.message:String(K)}`),AO(I)===process.pid)K5(I,{force:!0}),K5(z,{force:!0});throw K}let Q=()=>{if(J)J.close(),J=null;if(AO(I)===process.pid)K5(I,{force:!0}),K5(z,{force:!0});oU(q,`stopped pid=${process.pid}`)};await new Promise((K)=>{let w=!1,G=()=>{if(w)return;w=!0,Q(),process.off("SIGTERM",G),process.off("SIGINT",G),K()};process.once("SIGTERM",G),process.once("SIGINT",G)})}function MD0($){TD0($.stateDir);let I=rU($);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=oW1(z.command,q,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});U.unref();let Y=PO($);return MO(Y,`${U.pid}
`,{flag:"a",mode:384})}var xx=IV1($V1(),".config","seal-use");async function kx($,I,z){let q=z?y0(z.options.port)??y0(z.options.p):void 0,U=z?j(z.options.host)??j(z.options.h):void 0,Y=z?y0(z.options.lines)??y0(z.options.n):void 0,J=await vI($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:xx,version:e0,launcher:I.launcher,port:q,host:U},{maxLines:Y});if(J!==void 0)T0(J)}import{existsSync as zV1,readFileSync as ED0}from"node:fs";async function BD0($,I,z,q,U){if($==="batch-records"||$==="records"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation batch-records <batchId>");await F0("seal_simulation_batch_records_get",z,q,{batchId:Y,query:j(U.options.query)},W0(U.options));return}if($==="create"||$==="run"){let Y=j(U.options.mode)??j(U.options.sourceSystem)??j(U.options["source-system"])??"hosecloud",J=Y==="material-pack"?"material_pack":Y,Q=j(U.options.schemaConfig)??j(U.options["schema-config"]),K=Q?JSON.parse(ED0(Q,"utf8")):void 0,w=j(U.options.input),G=w?JSON.parse(ED0(w,"utf8")):H$(U.json),H=j(U.options.packageId)??j(U.options["package-id"]),W=Z6(U.options.packageIds)??Z6(U.options["package-ids"])??(H?[H]:void 0),Z=Z6(U.options.flowIds)??Z6(U.options["flow-ids"])??Z6(U.options.documentSn)??Z6(U.options["document-sn"]),X=j(U.options.signKey)??j(U.options["sign-key"])??j(U.options.integration),L=V0(U.options.noWait)??V0(U.options["no-wait"]);await F0("seal_simulation_batch_create",z,q,{mode:J,sourceSystem:J,flowIds:Z,documentSn:Z,rejectNodeName:j(U.options.rejectNode)??j(U.options["reject-node"])??null,thinkingDepthOverride:j(U.options.thinkingDepth)??j(U.options["thinking-depth"]),skipInvoiceGeneration:V0(U.options.skipInvoiceGeneration)??V0(U.options["skip-invoice-generation"]),skipExpenseExtraction:V0(U.options.skipExpenseExtraction)??V0(U.options["skip-expense-extraction"]),disableAttachmentCache:V0(U.options.disableAttachmentCache)??V0(U.options["disable-attachment-cache"]),signKey:X,packageIds:W,packageId:H,templateId:j(U.options.templateId)??j(U.options["template-id"]),schemaConfig:K,requestIds:Z6(U.options.requestIds)??Z6(U.options["request-ids"]),workflowTypeId:j(U.options.workflowTypeId)??j(U.options["workflow-type-id"]),flowStatusList:Z6(U.options.flowStatusList)?.map(Number)??Z6(U.options["flow-status-list"])?.map(Number),businessCodes:Z6(U.options.businessCodes)??Z6(U.options["business-codes"]),documentType:j(U.options.documentType)??j(U.options["document-type"]),startTime:y0(U.options.startTime)??y0(U.options["start-time"]),endTime:y0(U.options.endTime)??y0(U.options["end-time"]),status:Z6(U.options.status),limit:y0(U.options.limit),noWait:L,rawParams:G},W0(U.options));return}if($==="wait"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await F0("seal_simulation_batch_wait",z,q,{batchId:Y,timeout:j(U.options.timeout),pollInterval:j(U.options.pollInterval)??j(U.options["poll-interval"])},W0(U.options));return}if($==="status"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation status <batchId>");await F0("seal_simulation_batch_status",z,q,{batchId:Y},W0(U.options));return}if($==="clean"||$==="delete"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation clean <batchId>");await F0("seal_simulation_batch_clean",z,q,{batchId:Y},W0(U.options));return}if($==="specifications"){let Y=I??j(U.options.integration)??j(U.options.signKey)??j(U.options["sign-key"]);await F0("seal_simulation_specifications_list",z,q,{signKey:Y},W0(U.options));return}if($==="approval-definitions"||$==="definitions"){await F0("seal_simulation_feishu_approval_definitions_list",z,q,{},W0(U.options));return}if($==="list"){await F0("seal_simulation_batches_list",z,q,{limit:y0(U.options.limit)},W0(U.options));return}if($==="get"){let Y=I??j(U.options.batchId)??j(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation get <batchId>");await F0("seal_simulation_batch_get",z,q,{batchId:Y},W0(U.options));return}if($==="templates"){await F0("seal_simulation_templates_get",z,q,{},W0(U.options));return}if($==="integrations"){await F0("seal_simulation_integrations_get",z,q,{},W0(U.options));return}if($==="package-upload"){let Y=I??j(U.options.file);if(!Y)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!zV1(Y))throw Error(`Filenotfound:${Y}`);await F0("seal_simulation_material_package_upload",z,q,{filePath:Y},W0(U.options));return}throw Error(`Unknownsimulationcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{existsSync as jD0}from"node:fs";import{join as TO}from"node:path";function vD0($,I,z){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${zD0()}
`);return}if($==="install"||$==="init"||$==="sync"){let q=V0(z.options.local)||V0(z.options.workspace),U=j(z.options.dir)??j(z.options.target)??I,Y=U?U:q?TO(process.cwd(),".agents","skills","seal-use"):jI(),J=Tx(Y);T0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files});return}if($==="status"||$==="get"||!$){let q=jI(),U=TO(process.cwd(),".agents","skills","seal-use");T0({global:{dir:q,installed:jD0(TO(q,"SKILL.md"))},local:{dir:U,installed:jD0(TO(U,"SKILL.md"))}});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}async function RD0($,I){if($==="config"){T0(await lU(I));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function gD0($,I,z,q){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await F0($,I,z,H$(q.json),W0(q.options))}function _D0(){T0(CK.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as qV1,mkdirSync as UV1,renameSync as fx,rmSync as YV1,unlinkSync as uD0,writeFileSync as CD0}from"node:fs";import{dirname as JV1,join as hD0}from"node:path";import{spawnSync as RI}from"node:child_process";function EO($=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")}var xD0="yunyingk/seal-use",mK="yunyingk/seal-home";var QV1="SEAL_USE_GITHUB_REPO",KV1="SEAL_HOME_GITHUB_REPO";async function kD0($,I={}){let z={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:xx,version:e0,launcher:$.launcher},q=I.repo||process.env[QV1]?.trim()||process.env[KV1]?.trim()||xD0,U=I.targetVersion?.trim(),Y=U&&U.toLowerCase()!=="latest"?U:void 0;if(Y){let M=Y.replace(/^v/,""),v=fD0(M,e0);if(v<0)if(!DB&&I.force);else{T0({updated:!1,currentVersion:e0,targetVersion:M,mode:EO()?"binary":"source",message:!DB?`Cannotdowngradeseal-usefromdevbuildv${e0}toreleasev${M}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${e0}toolderversionv${M}.Updatesmustbeforward-only.`});return}if(v===0&&!I.force){T0({updated:!1,currentVersion:e0,targetVersion:M,mode:EO()?"binary":"source",message:`seal-useisalreadyatversionv${e0}.Use--forcetoreinstall.`});return}}if(I.changelogOnly){let M=await bx(q,I.limit??10);T0({currentVersion:e0,totalQueried:M.length,releases:M.map((v)=>({version:v.version,tagName:v.tagName,publishedAt:v.publishedAt,author:v.author,releaseNotes:v.notes,releaseUrl:v.htmlUrl,isCurrent:v.version===e0,isNewer:dK(v.version,e0)}))});return}if(!EO()){if(I.checkOnly){let v=await bx(q,30),u=v[0],h=u?.version??e0,x=v.find((b)=>b.version===e0),B=dK(h,e0),k=v.filter((b)=>dK(b.version,e0));T0({updated:!1,updateAvailable:B,currentVersion:e0,currentVersionPublishedAt:x?.publishedAt,latestVersion:h,latestVersionPublishedAt:u?.publishedAt,behindCount:k.length,pendingReleases:k.map((b)=>({version:b.version,tagName:b.tagName,publishedAt:b.publishedAt,author:b.author,releaseNotes:b.notes,releaseUrl:b.htmlUrl})),releaseNotes:u?.notes??"",releaseUrl:u?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let M=rU(z).running;if(M)await vI("stop",z);try{yD0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(v){console.error(`gitpullskipped:${vinstanceofError?v.message:String(v)}`)}if(yD0("bun",["install"],{cwd:$.appRoot}),M)await vI("start",z);T0({updated:!0,serviceRestarted:M,version:e0,mode:"source"});return}let J=wV1(),Q=GV1(),K=await bx(q,30),w=Y?K.find((M)=>M.version===Y||M.tagName===Y||M.tagName===`v${Y}`)??await SD0(q,Y):K[0]??await SD0(q);if(!w){T0({updated:!1,currentVersion:e0,mode:"binary",message:`Failedtoqueryreleasesfromrepository'${q}'`});return}let G=w.version,H=K.find((M)=>M.version===e0),W=dK(G,e0),Z=W||Boolean(I.force),X=K.filter((M)=>dK(M.version,e0));if(I.checkOnly){T0({updated:!1,updateAvailable:W,currentVersion:e0,currentVersionPublishedAt:H?.publishedAt,latestVersion:G,latestVersionPublishedAt:w.publishedAt,behindCount:X.length,pendingReleases:X.map((M)=>({version:M.version,tagName:M.tagName,publishedAt:M.publishedAt,author:M.author,releaseNotes:M.notes,releaseUrl:M.htmlUrl})),releaseNotes:w.notes,releaseUrl:w.htmlUrl,mode:"binary"});return}if(!Z){T0({updated:!1,currentVersion:e0,currentVersionPublishedAt:H?.publishedAt,latestVersion:G,latestVersionPublishedAt:w.publishedAt,mode:"binary",message:`seal-useisalreadyuptodate(v${e0})`});return}let L=HV1(w.assets,J,Q);if(!L)throw Error(`Nocompatiblebinaryfoundfor${J}-${Q}inreleasev${G}.Availableassets:${w.assets.map((M)=>M.name).join(", ")}`);let D=rU(z).running;if(D)await vI("stop",z);let O=process.execPath,T=JV1(O),P=hD0(T,`.tmp-update-${Date.now()}`);UV1(P,{recursive:!0});try{let M=hD0(P,L.name);await WV1(L.downloadUrl,M,w.tagName,L.name);let v=M;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))v=VV1
Line truncated
`)}catch{}}async function WV1($,I,z,q){let U=nx(),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/${xD0}/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)),w,G=6000,H=6000,W=307200,Z=1e4,X=180000;for(let L=0;L<K.length;L++){let D=K[L],O=new AbortController,T="",P=(h)=>{T=h;try{O.abort()}catch{}},M=setTimeout(()=>{P("Connection timed out (no response headers within 6s)")},G),v,u;try{BO(`==> [${L+1}/${K.length}] Downloading via: ${D}`);let h=await fetch(D,{signal:O.signal});if(M)clearTimeout(M),M=void 0;if(!h.ok)throw Error(`HTTP ${h.status} ${h.statusText}`);v=setTimeout(()=>{P("Overall download time exceeded 3 minutes")},X);let x=Number(h.headers.get("content-length"))||0,B=h.body?.getReader();if(!B){let p=Buffer.from(await h.arrayBuffer());if(p.length<1000)throw Error(`Downloaded content is suspiciously small (${p.length} bytes)`);CD0(I,p),BO(`✓ Download succeeded (${(p.length/1024/1024).toFixed(1)} MB)`);return}let k=[],b=0,g=0;u=setTimeout(()=>{if(b<W){let p=(b/1024).toFixed(1);P(`Initial transfer too slow (${p} KB < 300 KB in 6s), switching mirror...`)}},H);while(!0){let p=B.read(),z0,R=new Promise((U0,H0)=>{z0=setTimeout(()=>{H0(Error("Data transfer stalled (no chunk received for 10s)"))},Z)}),i;try{i=await Promise.race([p,R])}finally{if(z0)clearTimeout(z0)}let{done:c,value:r}=i;if(c)break;if(r){if(k.push(r),b+=r.length,u&&b>=W)clearTimeout(u),u=void 0;let U0=Date.now();if(U0-g>200){g=U0;let H0=x?Math.round(b/x*100):0,A0=(b/1048576).toFixed(1),R0=x?(x/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${H0}% (${A0} / ${R0} 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.18: 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.19: 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.18
short-description:Seal tenant and Hose approval automation (v0.10.18)
version:0.10.19
short-description:Seal tenant and Hose approval automation (v0.10.19)
---
# Seal Use (v0.10.18)
# Seal Use (v0.10.19)
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.
@@ -71,6 +71,7 @@ seal-use corps list
- In the default stateless mode, every enterprise command requires `--corp <corpId>`. In stateful mode, omitting `--corp` uses the configured default enterprise and is unsafe for an explicitly named enterprise.
- For an explicitly named enterprise, resolve it directly with `seal-use corps search <name>` (or `seal-use corps get <corpId>` if given an exact ID) rather than dumping all enterprises with `seal-use corps list`. Then pass its exact `corpId` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link.
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp <corpId> --note '<enterprise>'`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
- Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
- 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 service <start|stop|restart|status|logs> [--port 8787][--host 127.0.0.1][--lines 50]
@@ -82,6 +83,7 @@ seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm][--force]
seal-use corps unbind-test [<corpId>][--confirm]
seal-use corps sync-test [<prodCorpId>][--dry-run][--yes][--version-name <name>]
seal-use corps replay-test [<prodCorpId>][--record-id <id>][--sn <sn>][--limit <n>][--status <status>][--webhook <idOrName>][--sn-suffix <str>][--dry-run][--force]
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>][--overwrite]
-`seal-use source config --corp <corpId>` resolves the live source-system configuration without changing it.
@@ -213,6 +223,12 @@ Test Enterprise Binding & Staging Synchronization:
- **Semantic Version Naming**: Defaults to `Sync from <ProdCorp> [Prod v<N> · #<Iteration>]` tracking production baseline version and test draft iteration without redundant date strings.
- **Rule Mapping & Local Snapshot**: Returns `versionMapping` and `ruleMapping` in CLI stdout and saves persistent snapshot to `~/.config/seal-use/mappings/<testCorpId>-v<N>.json` and `<testCorpId>-latest.json`.
-`--dry-run` previews the full preference diff, version mapping plan, and rule sync plan without sending mutations. Execution requires `--yes`.
- **Approval Run Replay to Test Enterprise (`corps replay-test`)**:
- Automatically identifies the bound test enterprise for `<prodCorpId>` (or current corp).
- Fetches original approval records from the production enterprise (`--record-id`, `--sn`, or batch via `--limit` / `--status`).
- Cleans and normalizes payload structure, appends customizable suffix (default `-REPLAY-TEST`) to avoid collision.
- Automatically provisions `(Seal测-回放通道)` with `assisted` mode on the test enterprise if no webhook integration exists.
- Replays documents safely to the test enterprise webhook endpoint. Targeting production is blocked by default; if the enterprise has no bound test corp or target is production, `--force` can be specified to allow direct replay.
-`seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: `~/.config/seal-use/linters` and `official/`)
-`seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound.
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n`+
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association,\n`+
`or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`
);
}
testCorp=prodCorp;
}else{
testCorp=selectCorp(prodCorp.testCorpId);
if(testCorp.environment!=="test"&&!force){
thrownewError(
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`
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",
{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>",description:"Filter records by status (e.g. completed, failed, rejected)"},
{flag:"--webhook <idOrName>",description:"Target Webhook integration on test enterprise"},
{flag:"--sn-suffix <str>",description:"Optional suffix appended to documentSN"},
{flag:"--dry-run",description:"Preview payload without sending"}
],
description:"Pulls production approval records from the production enterprise and replays them into the bound test enterprise's Webhook channel for rule verification."
},
{
name:"add-hose",
summary:"Add a Hose/Ekuaibao enterprise configuration",
{flag:"<recordId>",description:"Approval run record ID to replay"},
{flag:"--sn <sn>",description:"Lookup approval record by source document SN if recordId not given"},
{flag:"--limit <n>",description:"Batch replay latest N records from source enterprise"},
{flag:"--status <status>",description:"Filter records by status (e.g. completed, failed, rejected)"},
{flag:"--webhook <idOrName>",description:"Target Webhook integration (auto-locks if only one exists)"},
{flag:"--source-corp <corpId>",description:"Source enterprise where the approval record resides (default: active)"},
{flag:"--source-corp <corpId>",description:"Source enterprise where records reside (alias: --prod-corp)"},
{flag:"--target-corp <corpId>",description:"Target enterprise where records are pushed (alias: --test-corp)"},
{flag:"--sn-suffix <str>",description:"Optional suffix appended to documentSN and documentId"},
{flag:"--sn-prefix <str>",description:"Optional prefix prepended to documentSN and documentId"},
{flag:"--dry-run",description:"Generate and output Webhook payload JSON without sending HTTP request"}
{flag:"--dry-run",description:"Generate and output Webhook payload JSON without sending HTTP request"},
{flag:"--force",description:"Allow replaying to a production enterprise"}
],
description:"Extracts structured form fields from any historical approval record (Webhook or Hose source), sanitizes field types, and pushes a new document to the target Webhook channel."
description:"Extracts structured form fields from historical approval records (Webhook or Hose source), sanitizes field types, and pushes documents to the target Webhook channel. Automatically infers 1-to-1 bound test/production enterprise pairs."
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.