@@ -21,6 +21,7 @@ Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in
-`bun run openapi:bundle`: rebuild `dist/openapi.json`.
-`bun run build:binary`: compile the standalone `seal-use` binary to `dist/bin/seal-use` (gitignored).
-`bun run build:plugin`: bundle the MCP server to `dist/mcp/server.js` (tracked, used by `.mcp.json`).
-`bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the Mac global command (`/opt/homebrew/bin/seal-use`), and sync the local Agent Skill.
- Extended `seal-use corps sync-test` to synchronize knowledge articles (`api/v1/knowledge/articles`) alongside rules and preferences.
- Natural key matching by title: creates missing documents, updates changed documents, and physically deletes redundant test documents (`DELETE /api/v1/knowledge/articles/:id`) to prevent stale background knowledge from distorting audit simulation.
- Aligned approval style preferences endpoint updates to use `POST` (`api/v1/agent/ai-approval/config`) matching Seal backend contract.
- **Local Dev Binary Override & Git-Aware Versioning**:
- Added `bun run dev:override` to compile host binaries with Git dev version metadata, macOS code sign, atomically override `/opt/homebrew/bin/seal-use`, and sync agent skills.
- CLI version output reports active channel (`dev` vs `release`), commits ahead, dirty state, and commit hash.
import{createRequireasZL0}from"node:module";varJL0=Object.create;var{getPrototypeOf:QL0,defineProperty:lD,getOwnPropertyNames:KL0}=Object;varqL0=Object.prototype.hasOwnProperty;functionHL0($){returnthis[$]}varGL0,WL0,OI=($,I,U)=>{varY=$!=null&&typeof$==="object";if(Y){varJ=I?GL0??=newWeakMap:WL0??=newWeakMap,Q=J.get($);if(Q)returnQ}U=$!=null?JL0(QL0($)):{};letK=I||!$||!$.__esModule?lD(U,"default",{value:$,enumerable:!0}):U;for(letqofKL0($))if(!qL0.call(K,q))lD(K,q,{get:HL0.bind($,q),enumerable:!0});if(Y)J.set($,K);returnK};varO=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);varwL0=($)=>$;functionVL0($,I){this[$]=wL0.bind(null,I)}vars8=($,I)=>{for(varUinI)lD($,U,{get:I[U],enumerable:!0,configurable:!0,set:VL0.bind(I,U)})};varr=ZL0(import.meta.url);varkQ=O((Ui)=>{Object.defineProperty(Ui,"__esModule",{value:!0});Ui.regexpCode=Ui.getEsmExportName=Ui.getProperty=Ui.safeStringify=Ui.stringify=Ui.strConcat=Ui.addCodeArg=Ui.str=Ui._=Ui.nil=Ui._Code=Ui.Name=Ui.IDENTIFIER=Ui._CodeOrName=void0;classkW{}Ui._CodeOrName=kW;Ui.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;classUUextendskW{constructor($){super();if(!Ui.IDENTIFIER.test($))throwError("CodeGen: name must be a valid identifier");this.str=$}toString(){returnthis.str}emptyStr(){return!1}getnames(){return{[this.str]:1}}}Ui.Name=UU;classn$extendskW{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,U)=>`${I}${U}`,"")}getnames(){var$;return($=this._names)!==null&&$!==void0?$:this._names=this._items.reduce((I,U)=>{if(UinstanceofUU)I[U.str]=(I[U.str]||0)+1;returnI},{})}}Ui._Code=n$;Ui.nil=newn$("");function$i($,...I){letU=[$[0]],Y=0;while(Y<I.length)KT(U,I[Y]),U.push($[++Y]);returnnewn$(U)}Ui._=$i;varQT=newn$("+");functionIi($,...I){letU=[xQ($[0])],Y=0;while(Y<I.length)U.push(QT),KT(U,I[Y]),U.push(QT,xQ($[++Y]));returnyN0(U),newn$(U)}Ui.str=Ii;functionKT($,I){if(Iinstanceofn$)$.push(...I._items);elseif(IinstanceofUU)$.push(I);else$.push(xN0(I))}Ui.addCodeArg=KT;functionyN0($){letI=1;while(I<$.length-1){if($[I]===QT){letU=hN0($[I-1],$[I+1]);if(U!==void0){$.splice(I-1,3,U);continue}$[I++]="+"}I++}}functionhN0($,I){if(I==='""')return$;if($==='""')returnI;if(typeof$=="string"){if(IinstanceofUU||$[$.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]==='"'&&!($instanceofUU))return`"${$}${I.slice(1)}`;return}functionuN0($,I){returnI.emptyStr()?$:$.emptyStr()?I:Ii`${$}${I}`}Ui.strConcat=uN0;functionxN0($){returntypeof$=="number"||typeof$=="boolean"||$===null?$:xQ(Array.isArray($)?$.join(","):$)}functionkN0($){returnnewn$(xQ($))}Ui.stringify=kN0;functionxQ($){returnJSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ui.safeStringify=xQ;functionfN0($){returntypeof$=="string"&&Ui.IDENTIFIER.test($)?newn$(`.${$}`):$i`[${$}]`}Ui.getProperty=fN0;functioniN0($){if(typeof$=="string"&&Ui.IDENTIFIER.test($))returnnewn$(`${$}`);throwError(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}Ui.getEsmExportName=iN0;functionbN0($){returnnewn$($.toString())}Ui.regexpCode=bN0});varWT=O((Ki)=>{Object.defineProperty(Ki,"__esModule",{value:!0});Ki.ValueScope=Ki.ValueScopeName=Ki.Scope=Ki.varKinds=Ki.UsedValueState=void0;vari6=kQ();classJiextendsError{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}variW;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(iW||(Ki.UsedValueState=iW={}));Ki.varKinds={const:newi6.Name("const"),let:newi6.Name("let"),var:newi6.Name("var")};classHT{constructor({prefixes:$,parent:I}={}){this._names={},this._prefixes=$,this._parent=I}toName($){return$instanceofi6.Name?$:this.name($)}name($){returnnewi6.Name(this._newName($))}_newName($){letI=this._names[$]||this._nameGroup($);return`${$}${I.index++}`}_nameGroup($){varI,U;if(((U=(I=this._parent)===null||I===void0?void0:I._prefixes)===null||U===void0?void0:U.has($))||this._prefixes&&!this._prefixes.has($))throwError(`CodeGen: prefix "${$}" is not allowed in this scope`);returnthis._names[$]={prefix:$,index:0}}}Ki.Scope=HT;classGTextendsi6.Name{constructor($,I){super(I);this.prefix=$}setValue($,{property:I,itemIndex:U}){this.value=$,this.scopePath=i6._`.${newi6.Name(I)}[${U}]`}}Ki.ValueScopeName=GT;var$M0=i6._`\n`;classQiextendsHT{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?$M0:i6.nil}}get(){returnthis._scope}name($){returnnewGT($,this._newName($))}value($,I){varU;if(I.ref===void0)throwError("CodeGen: ref must be passed in value");letY=this.toName($),{prefix:J}=Y,Q=(U=I.key)!==null&&U!==void0?U:I.ref,K=this._values[J];if(K){letG=K.get(Q);if(Line truncated
import{createRequireasEL0}from"node:module";varLL0=Object.create;var{getPrototypeOf:DL0,defineProperty:eD,getOwnPropertyNames:FL0}=Object;varOL0=Object.prototype.hasOwnProperty;functionNL0($){returnthis[$]}varML0,AL0,OI=($,I,U)=>{varY=$!=null&&typeof$==="object";if(Y){varJ=I?ML0??=newWeakMap:AL0??=newWeakMap,Q=J.get($);if(Q)returnQ}U=$!=null?LL0(DL0($)):{};letK=I||!$||!$.__esModule?eD(U,"default",{value:$,enumerable:!0}):U;for(letqofFL0($))if(!OL0.call(K,q))eD(K,q,{get:NL0.bind($,q),enumerable:!0});if(Y)J.set($,K);returnK};varF=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);varPL0=($)=>$;functionTL0($,I){this[$]=PL0.bind(null,I)}vare8=($,I)=>{for(varUinI)eD($,U,{get:I[U],enumerable:!0,configurable:!0,set:TL0.bind(I,U)})};vara=EL0(import.meta.url);varfQ=F((Hi)=>{Object.defineProperty(Hi,"__esModule",{value:!0});Hi.regexpCode=Hi.getEsmExportName=Hi.getProperty=Hi.safeStringify=Hi.stringify=Hi.strConcat=Hi.addCodeArg=Hi.str=Hi._=Hi.nil=Hi._Code=Hi.Name=Hi.IDENTIFIER=Hi._CodeOrName=void0;classiW{}Hi._CodeOrName=iW;Hi.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;classYUextendsiW{constructor($){super();if(!Hi.IDENTIFIER.test($))throwError("CodeGen: name must be a valid identifier");this.str=$}toString(){returnthis.str}emptyStr(){return!1}getnames(){return{[this.str]:1}}}Hi.Name=YU;classc$extendsiW{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,U)=>`${I}${U}`,"")}getnames(){var$;return($=this._names)!==null&&$!==void0?$:this._names=this._items.reduce((I,U)=>{if(UinstanceofYU)I[U.str]=(I[U.str]||0)+1;returnI},{})}}Hi._Code=c$;Hi.nil=newc$("");functionKi($,...I){letU=[$[0]],Y=0;while(Y<I.length)VT(U,I[Y]),U.push($[++Y]);returnnewc$(U)}Hi._=Ki;varwT=newc$("+");functionqi($,...I){letU=[kQ($[0])],Y=0;while(Y<I.length)U.push(wT),VT(U,I[Y]),U.push(wT,kQ($[++Y]));returnmN0(U),newc$(U)}Hi.str=qi;functionVT($,I){if(Iinstanceofc$)$.push(...I._items);elseif(IinstanceofYU)$.push(I);else$.push(rN0(I))}Hi.addCodeArg=VT;functionmN0($){letI=1;while(I<$.length-1){if($[I]===wT){letU=lN0($[I-1],$[I+1]);if(U!==void0){$.splice(I-1,3,U);continue}$[I++]="+"}I++}}functionlN0($,I){if(I==='""')return$;if($==='""')returnI;if(typeof$=="string"){if(IinstanceofYU||$[$.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]==='"'&&!($instanceofYU))return`"${$}${I.slice(1)}`;return}functionoN0($,I){returnI.emptyStr()?$:$.emptyStr()?I:qi`${$}${I}`}Hi.strConcat=oN0;functionrN0($){returntypeof$=="number"||typeof$=="boolean"||$===null?$:kQ(Array.isArray($)?$.join(","):$)}functiontN0($){returnnewc$(kQ($))}Hi.stringify=tN0;functionkQ($){returnJSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Hi.safeStringify=kQ;functionaN0($){returntypeof$=="string"&&Hi.IDENTIFIER.test($)?newc$(`.${$}`):Ki`[${$}]`}Hi.getProperty=aN0;functionsN0($){if(typeof$=="string"&&Hi.IDENTIFIER.test($))returnnewc$(`${$}`);throwError(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}Hi.getEsmExportName=sN0;functioneN0($){returnnewc$($.toString())}Hi.regexpCode=eN0});varLT=F((Vi)=>{Object.defineProperty(Vi,"__esModule",{value:!0});Vi.ValueScope=Vi.ValueScopeName=Vi.Scope=Vi.varKinds=Vi.UsedValueState=void0;varc6=fQ();classWiextendsError{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}varnW;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(nW||(Vi.UsedValueState=nW={}));Vi.varKinds={const:newc6.Name("const"),let:newc6.Name("let"),var:newc6.Name("var")};classzT{constructor({prefixes:$,parent:I}={}){this._names={},this._prefixes=$,this._parent=I}toName($){return$instanceofc6.Name?$:this.name($)}name($){returnnewc6.Name(this._newName($))}_newName($){letI=this._names[$]||this._nameGroup($);return`${$}${I.index++}`}_nameGroup($){varI,U;if(((U=(I=this._parent)===null||I===void0?void0:I._prefixes)===null||U===void0?void0:U.has($))||this._prefixes&&!this._prefixes.has($))throwError(`CodeGen: prefix "${$}" is not allowed in this scope`);returnthis._names[$]={prefix:$,index:0}}}Vi.Scope=zT;classXTextendsc6.Name{constructor($,I){super(I);this.prefix=$}setValue($,{property:I,itemIndex:U}){this.value=$,this.scopePath=c6._`.${newc6.Name(I)}[${U}]`}}Vi.ValueScopeName=XT;varVM0=c6._`\n`;classwiextendszT{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?VM0:c6.nil}}get(){returnthis._scope}name($){returnnewXT($,this._newName($))}value($,I){varU;if(I.ref===void0)throwError("CodeGen: ref must be passed in value");letY=this.toName($),{prefix:J}=Y,Q=(U=I.key)!==null&&U!==void0?U:I.ref,K=this._values[J];if(K){letG=K.get(Q);if(Line truncated
deps:${U}}`};var qv0={keyword:"dependencies",type:"object",schemaType:"object",error:Ap.error,code($){let[I,U]=Hv0($);Np($,I),Mp($,U)}};function Hv0({schema:$}){let I={},U={};for(let Y in $){if(Y==="__proto__")continue;let J=Array.isArray($[Y])?I:U;J[Y]=$[Y]}return[I,U]}function Np($,I=$.schema){let{gen:U,data:Y,it:J}=$;if(Object.keys(I).length===0)return;let Q=U.let("missing");for(let K in I){let q=I[K];if(q.length===0)continue;let H=(0,Y2.propertyInData)(U,Y,K,J.opts.ownProperties);if($.setParams({property:K,depsCount:q.length,deps:q.join(", ")}),J.allErrors)U.if(H,()=>{for(let G of q)(0,Y2.checkReportMissingProp)($,G)});else U.if(oT._`${H}&&(${(0,Y2.checkMissingProp)($,q,Q)})`),(0,Y2.reportMissingProp)($,Q),U.else()}}Ap.validatePropertyDeps=Np;function Mp($,I=$.schema){let{gen:U,data:Y,keyword:J,it:Q}=$,K=U.name("valid");for(let q in I){if((0,Kv0.alwaysValidSchema)(Q,I[q]))continue;U.if((0,Y2.propertyInData)(U,Y,q,Q.opts.ownProperties),()=>{let H=$.subschema({keyword:J,schemaProp:q},K);$.mergeValidEvaluated(H,K)},()=>U.var(K,!0)),$.ok(K)}}Ap.validateSchemaDeps=Mp;Ap.default=qv0});var Rp=O((vp)=>{Object.defineProperty(vp,"__esModule",{value:!0});var Bp=s0(),wv0=V1(),Vv0={message:"property name must be valid",params:({params:$})=>Bp._`{propertyName:${$.propertyName}}`},Zv0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Vv0,code($){let{gen:I,schema:U,data:Y,it:J}=$;if((0,wv0.alwaysValidSchema)(J,U))return;let Q=I.name("valid");I.forIn("key",Y,(K)=>{$.setParams({propertyName:K}),$.subschema({keyword:"propertyNames",data:K,dataTypes:["string"],propertyName:K,compositeRule:!0},Q),I.if((0,Bp.not)(Q),()=>{if($.error(!0),!J.allErrors)I.break()})}),$.ok(Q)}};vp.default=Zv0});var rT=O((Cp)=>{Object.defineProperty(Cp,"__esModule",{value:!0});var Zw=M$(),m$=s0(),Xv0=J5(),zw=V1(),Lv0={message:"must NOT have additional properties",params:({params:$})=>m$._`{additionalProperty:${$.additionalProperty}}`},Dv0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Lv0,code($){let{gen:I,schema:U,parentSchema:Y,data:J,errsCount:Q,it:K}=$;if(!Q)throw Error("ajv implementation error");let{allErrors:q,opts:H}=K;if(K.props=!0,H.removeAdditional!=="all"&&(0,zw.alwaysValidSchema)(K,U))return;let G=(0,Zw.allSchemaProperties)(Y.properties),W=(0,Zw.allSchemaProperties)(Y.patternProperties);w(),$.ok(m$._`${Q}===${Xv0.default.errors}`);function w(){I.forIn("key",J,(D)=>{if(!G.length&&!W.length)X(D);else I.if(V(D),()=>X(D))})}function V(D){let F;if(G.length>8){let E=(0,zw.schemaRefOrVal)(K,Y.properties,"properties");F=(0,Zw.isOwnProperty)(I,E,D)}else if(G.length)F=(0,m$.or)(...G.map((E)=>m$._`${D}===${E}`));else F=m$.nil;if(W.length)F=(0,m$.or)(F,...W.map((E)=>m$._`${(0,Zw.usePattern)($,E)}.test(${D})`));return(0,m$.not)(F)}function Z(D){I.code(m$._`delete${J}[${D}]`)}function X(D){if(H.removeAdditional==="all"||H.removeAdditional&&U===!1){Z(D);return}if(U===!1){if($.setParams({additionalProperty:D}),$.error(),!q)I.break();return}if(typeof U=="object"&&!(0,zw.alwaysValidSchema)(K,U)){let F=I.name("valid");if(H.removeAdditional==="failing")L(D,F,!1),I.if((0,m$.not)(F),()=>{$.reset(),Z(D)});else if(L(D,F),!q)I.if((0,m$.not)(F),()=>I.break())}}function L(D,F,E){let T={keyword:"additionalProperties",dataProp:D,dataPropType:zw.Type.Str};if(E===!1)Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(T,F)}}};Cp.default=Dv0});var Sp=O((gp)=>{Object.defineProperty(gp,"__esModule",{value:!0});var Fv0=dQ(),jp=M$(),tT=V1(),_p=rT(),Nv0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:I,schema:U,parentSchema:Y,data:J,it:Q}=$;if(Q.opts.removeAdditional==="all"&&Y.additionalProperties===void 0)_p.default.code(new Fv0.KeywordCxt(Q,_p.default,"additionalProperties"));let K=(0,jp.allSchemaProperties)(U);for(let w of K)Q.definedProperties.add(w);if(Q.opts.unevaluated&&K.length&&Q.props!==!0)Q.props=tT.mergeEvaluated.props(I,(0,tT.toHash)(K),Q.props);let q=K.filter((w)=>!(0,tT.alwaysValidSchema)(Q,U[w]));if(q.length===0)return;let H=I.name("valid");for(let w of q){if(G(w))W(w);else{if(I.if((0,jp.propertyInData)(I,J,w,Q.opts.ownProperties)),W(w),!Q.allErrors)I.else().var(H,!0);I.endIf()}$.it.definedProperties.add(w),$.ok(H)}function G(w){return Q.opts.useDefaults&&!Q.compositeRule&&U[w].default!==void 0}function W(w){$.subschema({keyword:"properties",schemaProp:w,dataProp:w},H)}}};gp.default=Nv0});var kp=O((xp)=>{Object.defineProperty(xp,"__esModule",{value:!0});var yp=M$(),Xw=s0(),hp=V1(),up=V1(),Av0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:U,data:Y,parentSchema:J,it:Q}=$,{opts:K}=Q,q=(0,yp.allSchemaProperties)(U),H=q.filter((L)=>(0,hp.alwaysValidSchema)(Q,U[L]));if(q.length===0||H.length===q.length&&(!Q.opts.unevaluated||Q.props===!0))return;let G=K.strictSchema&&!K.allowMatchingProperties&&J.properties,W=I.name("valid");if(Q.props!==!0&&!(Q.props instanceo
Line truncated
`)}openNode($,I){let U=this.tos,Y=this._xml;if(U&&this.open)Y.push(">");this._stack.push($),Y.push("<"),Y.push($),ZR(Y,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)xe(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");ZR(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(ue.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,U){if(this.openNode($,I),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}zR.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};ke.exports=zR});var XR=O((ef0)=>{var fe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function sf0($){if(typeof $==="string")return $;if(fe)return fe.decode($);return $.toString()}ef0.bufferToString=sf0});var ce=O((be)=>{Object.defineProperty(be,"__esModule",{value:!0});be.CHAR=`
`,$=this.i;break;case Fb0:{let{entityReturnState:U}=this,Y=this.entity+I.slice($,this.prevI);this.state=U;let J;if(Y==="")this.fail("empty entity name."),J="&;";else J=this.parseEntity(Y),this.entity="";if(U!==_6||this.textHandler!==void 0)this.text+=J;break $}case K4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(FK($))this.state=zb0,this.unget(),this.xmlDeclPossible=!1;else switch($){case OZ:this.state=Db0,this.xmlDeclPossible=!1;break;case Z00:this.state=Jb0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case U6:this.state=Gb0;break;default:this.fail("disallowed character in tag name"),this.state=_6,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=ER,this.openWakaBang="";break;case"--":this.state=TR,this.openWakaBang="";break;case"DOCTYPE":if(this.state=MR,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(DZ))this.state=Qb0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===DZ)this.state=Kb0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=TR}sCommentEnded(){let $=this.getCodeNorm();if($!==y4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=TR;else this.state=_6}sCData(){if(this.captureToChar(IY))this.state=qb0}sCDataEnding(){let $=this.getCodeNorm();if($===IY)this.state=Hb0;else this.text+=`]${String.fromCodePoint($)}`,this.state=ER}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case y4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=_6;break}case IY:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=ER}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=K00;else if($===U6||d6($))this.fail("processing instruction without a target."),this.state=$===U6?LZ:BR;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=K00}sPIRest(){let{chunk:$,i:I}=this;while(!0){let U=this.getCodeNorm();if(U===K4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(I,this.prevI);let Y=U===U6;if(Y||d6(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=Y?G3:q00}else this.state=Y?LZ:BR;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===U6)this.state=LZ;else if(!d6($))this.text=String.fromCodePoint($)}else if(this.captureToChar(U6))this.state=LZ}sPIEnding(){var $;let I=this.getCodeNorm();if(I===y4){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=_6}else if(I===U6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=BR;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===U6){this.state=G3;return}if($!==K4)this.state=Wb0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(Ab0);if($===U6){this.state=G3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(d6($)||$===$Y))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=$===$Y?H00:wb0}sXMLDeclEq(){let $=this.getCodeNorm();if($===U6){this.state=G3,this.fail("XML declaration is incomplete.");return}if(d6($))return;if($!==$Y)this.fail("value required.");this.state=H00}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===U6){this.state=G3,this.fail("XML declaration is incomplete.");return}if(d6($))return;if(!FZ($))this.fail("value must be quoted."),this.q=V00;else this.q=$;this.state=Vb0}sXMLDeclValue(){let $=this.captureTo([this.q,U6]);if($===U6){this.state=G3,this.text="",this.fail("XML declaration is incomplete.");return}if($===K4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=I;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("ver
Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(I)}set headers($){this._headers=$}shouldQuote($,I){let U=I?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(er0.default(U))return U;if(Array.isArray(U))return U[$];if(this._headers!==null)return U[this._headers[$]];return!1}format($,I,U){let Y=`${$t0.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:J}=this;if(J.quote!==""){if(Y.indexOf(J.quote)!==-1)return this.quoteField(Y.replace(this.REPLACE_REGEXP,J.escapedQuote))}if(Y.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(I,U))return this.quoteField(Y);return Y}quoteField($){let{quote:I}=this.formatterOptions;return`${I}${$}${I}`}}LY.FieldFormatter=s90});var qj=O((e90)=>{Object.defineProperty(e90,"__esModule",{value:!0});e90.isSyncTransform=void 0;e90.isSyncTransform=($)=>$.length===1});var U70=O((DY)=>{var I70=DY&&DY.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(DY,"__esModule",{value:!0});DY.RowFormatter=void 0;var Ut0=I70(eZ()),Yt0=I70(p90()),Jt0=Kj(),Qt0=qj();class A3{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new Jt0.FieldFormatter($),this.headers=$.headers,this.shouldWriteHeaders=$.shouldWriteHeaders,this.hasWrittenHeaders=!1,this.headers!==null)this.fieldFormatter.headers=this.headers;if($.transform)this.rowTransform=$.transform}static isRowHashArray($){if(Array.isArray($))return Array.isArray($[0])&&$[0].length===2;return!1}static isRowArray($){return Array.isArray($)&&!this.isRowHashArray($)}static gatherHeaders($){if(A3.isRowHashArray($))return $.map((I)=>I[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(Qt0.isSyncTransform($))return(I,U)=>{let Y=null;try{Y=$(I)}catch(J){return U(J)}return U(null,Y)};return(I,U)=>{$(I,U)}}set rowTransform($){if(!Ut0.default($))throw TypeError("The transform should be a function");this._rowTransform=A3.createTransform($)}format($,I){this.callTransformer($,(U,Y)=>{if(U)return I(U);if(!$)return I(null);let J=[];if(Y){let{shouldFormatColumns:Q,headers:K}=this.checkHeaders(Y);if(this.shouldWriteHeaders&&K&&!this.hasWrittenHeaders)J.push(this.formatColumns(K,!0)),this.hasWrittenHeaders=!0;if(Q){let q=this.gatherColumns(Y);J.push(this.formatColumns(q,!1))}}return I(null,J)})}finish($){let I=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));I.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)I.push(this.formatterOptions.rowDelimiter);return $(null,I)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let I=A3.gatherHeaders($);if(this.headers=I,this.fieldFormatter.headers=I,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!Yt0.default(I,$),headers:I}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((I)=>$[I]);if(A3.isRowHashArray($))return this.headers.map((I,U)=>{let Y=$[U];if(Y)return Y[1];return""});if(A3.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((I,U)=>$[U])}callTransformer($,I){if(!this._rowTransform)return I(null,$);return this._rowTransform($,I)}formatColumns($,I){let U=$.map((J,Q)=>this.fieldFormatter.format(J,Q,I)).join(this.formatterOptions.delimiter),{rowCount:Y}=this;if(this.rowCount+=1,Y)return[this.formatterOptions.rowDelimiter,U].join("");return U}}DY.RowFormatter=A3});var Y70=O((Vz)=>{Object.defineProperty(Vz,"__esModule",{value:!0});Vz.FieldFormatter=Vz.RowFormatter=void 0;var Kt0=U70();Object.defineProperty(Vz,"RowFormatter",{enumerable:!0,get:function(){return Kt0.RowFormatter}});var qt0=Kj();Object.defineProperty(Vz,"FieldFormatter",{enumerable:!0,get:function(){return qt0.FieldFormatter}})});var Hj=O((Q70)=>{Object.defineProperty(Q70,"__esModule",{value:!0});Q70.CsvFormatterStream=void 0;var Gt0=r("stream"),Wt0=Y70();class J70 extends Gt0.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new Wt0.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,I,U){let Y=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(J,Q)=>{if(J)return Y=!0,U(J);if(Q)Q.forEach((K)=>{this.push(Buffer.from(K,"utf8"))});return Y=!0,U()})}catch(J){if(Y)throw J;U(J)}}_flush($){this.rowFormatter.finish((I,U)=>{if(I)return $(I);if(U)U.forEach((Y)=>{this.push(Buffer.from(Y,"utf8"))});return $()})}}Q70.CsvFormatterStream=J70});var H70=O((N1)=>{var q70=N1&&N1.__createBinding||(Object.create?function($,I,U,Y){if(Y===void 0)Y=U;Object.defineProperty($,Y,{enumerable:!0,get:function(){return I[U]}})}:function($,I,U,Y){if(Y===void 0)Y=U;$[Y]=I[U]}),wt0=N1&&N1.__setModuleDefault||(Object.create?function($,I){Ob
Line truncated
deps:${U}}`};var Ov0={keyword:"dependencies",type:"object",schemaType:"object",error:Rp.error,code($){let[I,U]=Nv0($);Bp($,I),vp($,U)}};function Nv0({schema:$}){let I={},U={};for(let Y in $){if(Y==="__proto__")continue;let J=Array.isArray($[Y])?I:U;J[Y]=$[Y]}return[I,U]}function Bp($,I=$.schema){let{gen:U,data:Y,it:J}=$;if(Object.keys(I).length===0)return;let Q=U.let("missing");for(let K in I){let q=I[K];if(q.length===0)continue;let H=(0,J2.propertyInData)(U,Y,K,J.opts.ownProperties);if($.setParams({property:K,depsCount:q.length,deps:q.join(", ")}),J.allErrors)U.if(H,()=>{for(let G of q)(0,J2.checkReportMissingProp)($,G)});else U.if($E._`${H}&&(${(0,J2.checkMissingProp)($,q,Q)})`),(0,J2.reportMissingProp)($,Q),U.else()}}Rp.validatePropertyDeps=Bp;function vp($,I=$.schema){let{gen:U,data:Y,keyword:J,it:Q}=$,K=U.name("valid");for(let q in I){if((0,Fv0.alwaysValidSchema)(Q,I[q]))continue;U.if((0,J2.propertyInData)(U,Y,q,Q.opts.ownProperties),()=>{let H=$.subschema({keyword:J,schemaProp:q},K);$.mergeValidEvaluated(H,K)},()=>U.var(K,!0)),$.ok(K)}}Rp.validateSchemaDeps=vp;Rp.default=Ov0});var yp=F((gp)=>{Object.defineProperty(gp,"__esModule",{value:!0});var Sp=a0(),Pv0=Z1(),Tv0={message:"property name must be valid",params:({params:$})=>Sp._`{propertyName:${$.propertyName}}`},Ev0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Tv0,code($){let{gen:I,schema:U,data:Y,it:J}=$;if((0,Pv0.alwaysValidSchema)(J,U))return;let Q=I.name("valid");I.forIn("key",Y,(K)=>{$.setParams({propertyName:K}),$.subschema({keyword:"propertyNames",data:K,dataTypes:["string"],propertyName:K,compositeRule:!0},Q),I.if((0,Sp.not)(Q),()=>{if($.error(!0),!J.allErrors)I.break()})}),$.ok(Q)}};gp.default=Ev0});var IE=F((hp)=>{Object.defineProperty(hp,"__esModule",{value:!0});var Xw=T$(),o$=a0(),vv0=Q5(),Lw=Z1(),Rv0={message:"must NOT have additional properties",params:({params:$})=>o$._`{additionalProperty:${$.additionalProperty}}`},Cv0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Rv0,code($){let{gen:I,schema:U,parentSchema:Y,data:J,errsCount:Q,it:K}=$;if(!Q)throw Error("ajv implementation error");let{allErrors:q,opts:H}=K;if(K.props=!0,H.removeAdditional!=="all"&&(0,Lw.alwaysValidSchema)(K,U))return;let G=(0,Xw.allSchemaProperties)(Y.properties),W=(0,Xw.allSchemaProperties)(Y.patternProperties);w(),$.ok(o$._`${Q}===${vv0.default.errors}`);function w(){I.forIn("key",J,(D)=>{if(!G.length&&!W.length)X(D);else I.if(V(D),()=>X(D))})}function V(D){let O;if(G.length>8){let E=(0,Lw.schemaRefOrVal)(K,Y.properties,"properties");O=(0,Xw.isOwnProperty)(I,E,D)}else if(G.length)O=(0,o$.or)(...G.map((E)=>o$._`${D}===${E}`));else O=o$.nil;if(W.length)O=(0,o$.or)(O,...W.map((E)=>o$._`${(0,Xw.usePattern)($,E)}.test(${D})`));return(0,o$.not)(O)}function Z(D){I.code(o$._`delete${J}[${D}]`)}function X(D){if(H.removeAdditional==="all"||H.removeAdditional&&U===!1){Z(D);return}if(U===!1){if($.setParams({additionalProperty:D}),$.error(),!q)I.break();return}if(typeof U=="object"&&!(0,Lw.alwaysValidSchema)(K,U)){let O=I.name("valid");if(H.removeAdditional==="failing")L(D,O,!1),I.if((0,o$.not)(O),()=>{$.reset(),Z(D)});else if(L(D,O),!q)I.if((0,o$.not)(O),()=>I.break())}}function L(D,O,E){let T={keyword:"additionalProperties",dataProp:D,dataPropType:Lw.Type.Str};if(E===!1)Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(T,O)}}};hp.default=Cv0});var fp=F((kp)=>{Object.defineProperty(kp,"__esModule",{value:!0});var _v0=mQ(),up=T$(),UE=Z1(),xp=IE(),Sv0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:I,schema:U,parentSchema:Y,data:J,it:Q}=$;if(Q.opts.removeAdditional==="all"&&Y.additionalProperties===void 0)xp.default.code(new _v0.KeywordCxt(Q,xp.default,"additionalProperties"));let K=(0,up.allSchemaProperties)(U);for(let w of K)Q.definedProperties.add(w);if(Q.opts.unevaluated&&K.length&&Q.props!==!0)Q.props=UE.mergeEvaluated.props(I,(0,UE.toHash)(K),Q.props);let q=K.filter((w)=>!(0,UE.alwaysValidSchema)(Q,U[w]));if(q.length===0)return;let H=I.name("valid");for(let w of q){if(G(w))W(w);else{if(I.if((0,up.propertyInData)(I,J,w,Q.opts.ownProperties)),W(w),!Q.allErrors)I.else().var(H,!0);I.endIf()}$.it.definedProperties.add(w),$.ok(H)}function G(w){return Q.opts.useDefaults&&!Q.compositeRule&&U[w].default!==void 0}function W(w){$.subschema({keyword:"properties",schemaProp:w,dataProp:w},H)}}};kp.default=Sv0});var cp=F((pp)=>{Object.defineProperty(pp,"__esModule",{value:!0});var ip=T$(),Dw=a0(),bp=Z1(),np=Z1(),yv0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:U,data:Y,parentSchema:J,it:Q}=$,{opts:K}=Q,q=(0,ip.allSchemaProperties)(U),H=q.filter((L)=>(0,bp.alwaysValidSchema)(Q,U[L]));if(q.length===0||H.length===q.length&&(!Q.opts.unevaluated||Q.props===!0))return;let G=K.strictSchema&&!K.allowMatchingProperties&&J.properties,W=I.name("valid");if(Q.props!==!0&&!(Q.props instanceo
Line truncated
`)}openNode($,I){let U=this.tos,Y=this._xml;if(U&&this.open)Y.push(">");this._stack.push($),Y.push("<"),Y.push($),OR(Y,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)ne(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");OR(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(be.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,U){if(this.openNode($,I),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}NR.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};pe.exports=NR});var MR=F((zi0)=>{var ce=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function Zi0($){if(typeof $==="string")return $;if(ce)return ce.decode($);return $.toString()}zi0.bufferToString=Zi0});var re=F((me)=>{Object.defineProperty(me,"__esModule",{value:!0});me.CHAR=`
`,$=this.i;break;case yb0:{let{entityReturnState:U}=this,Y=this.entity+I.slice($,this.prevI);this.state=U;let J;if(Y==="")this.fail("empty entity name."),J="&;";else J=this.parseEntity(Y),this.entity="";if(U!==g6||this.textHandler!==void 0)this.text+=J;break $}case q4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(MK($))this.state=Cb0,this.unget(),this.xmlDeclPossible=!1;else switch($){case PZ:this.state=Sb0,this.xmlDeclPossible=!1;break;case F00:this.state=Ob0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case U6:this.state=Tb0;break;default:this.fail("disallowed character in tag name"),this.state=g6,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=_R,this.openWakaBang="";break;case"--":this.state=jR,this.openWakaBang="";break;case"DOCTYPE":if(this.state=vR,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(AZ))this.state=Nb0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===AZ)this.state=Mb0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=jR}sCommentEnded(){let $=this.getCodeNorm();if($!==y4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=jR;else this.state=g6}sCData(){if(this.captureToChar(UY))this.state=Ab0}sCDataEnding(){let $=this.getCodeNorm();if($===UY)this.state=Pb0;else this.text+=`]${String.fromCodePoint($)}`,this.state=_R}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case y4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=g6;break}case UY:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=_R}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=w00;else if($===U6||r6($))this.fail("processing instruction without a target."),this.state=$===U6?MZ:SR;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=w00}sPIRest(){let{chunk:$,i:I}=this;while(!0){let U=this.getCodeNorm();if(U===q4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(I,this.prevI);let Y=U===U6;if(Y||r6(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=Y?W3:V00}else this.state=Y?MZ:SR;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===U6)this.state=MZ;else if(!r6($))this.text=String.fromCodePoint($)}else if(this.captureToChar(U6))this.state=MZ}sPIEnding(){var $;let I=this.getCodeNorm();if(I===y4){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=g6}else if(I===U6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=SR;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===U6){this.state=W3;return}if($!==q4)this.state=Eb0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(xb0);if($===U6){this.state=W3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(r6($)||$===IY))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=$===IY?Z00:Bb0}sXMLDeclEq(){let $=this.getCodeNorm();if($===U6){this.state=W3,this.fail("XML declaration is incomplete.");return}if(r6($))return;if($!==IY)this.fail("value required.");this.state=Z00}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===U6){this.state=W3,this.fail("XML declaration is incomplete.");return}if(r6($))return;if(!TZ($))this.fail("value must be quoted."),this.q=D00;else this.q=$;this.state=vb0}sXMLDeclValue(){let $=this.captureTo([this.q,U6]);if($===U6){this.state=W3,this.text="",this.fail("XML declaration is incomplete.");return}if($===q4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=I;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("ver
Line truncated
See:https://github.com/isaacs/node-glob/issues/167`);return new h4($,I).found}function h4($,I){if(!$)throw Error("must provide pattern");if(typeof I==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
`+e[G0-1];break}}}var Q1="a promise was created in a "+M+"handler "+s+"but was not returned from it, see http://goo.gl/rRqMUw"+m;j._warn(Q1,!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 L1(M)}function L1(a,N,M){if(!E0.warnings)return;var j=new J(a),u;if(N)M._attachExtraTrace(j);else if(E0.longStackTraces&&(u=$._peekContext()))u.attachExtraTrace(j);else{var s=q4(j);j.stack=s.message+`
`+$0[W0-1];break}}}var q1="a promise was created in a "+M+"handler "+e+"but was not returned from it, see http://goo.gl/rRqMUw"+m;j._warn(q1,!0,N)}}function R0(s,N){var M=s+" is deprecated and will be removed in a future version.";if(N)M+=" Use "+N+" instead.";return K1(M)}function K1(s,N,M){if(!v0.warnings)return;var j=new J(s),u;if(N)M._attachExtraTrace(j);else if(v0.longStackTraces&&(u=$._peekContext()))u.attachExtraTrace(j);else{var e=g1(j);j.stack=e.message+`
`)));return}}F=F._target();var E=F._bitField;if((E&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((E&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((E&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(X,L){if(typeof X!=="function")throw new q(`generatorFunctionmustbeafunction
`)));return}}O=O._target();var E=O._bitField;if((E&50397184)===0)this._yieldedPromise=O,O._proxy(this,null);else if((E&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,O._value());else if((E&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,F=Z,E=Error().stack;return function(){var T=X.apply(this,arguments),A=new F(void 0,void 0,D,E),R=A.promise();return A._generator=T,A._promiseFulfilled(void 0),R}},$.coroutine.addYieldHandler=function(X){if(typeof X!=="function")throw new q("expecting a function but got "+H.classString(X));w.push(X)},$.spawn=function(X){if(Q.deprecated("Promise.spawn()","Promise.coroutine()"),typeof X!=="function")return I(`generatorFunctionmustbeafunction
`);var D=Object(L).yieldHandler,O=Z,E=Error().stack;return function(){var T=X.apply(this,arguments),A=new O(void 0,void 0,D,E),R=A.promise();return A._generator=T,A._promiseFulfilled(void 0),R}},$.coroutine.addYieldHandler=function(X){if(typeof X!=="function")throw new q("expecting a function but got "+H.classString(X));w.push(X)},$.spawn=function(X){if(Q.deprecated("Promise.spawn()","Promise.coroutine()"),typeof X!=="function")return I(`generatorFunctionmustbeafunction
`)},I=function(){return new g.PromiseInspection(this._target())},U=function(B){return g.reject(new w(B))};function Y(){}var J={},Q=p1(),K;if(Q.isNode)K=function(){var B=process.domain;if(B===void 0)B=null;return B};else K=function(){return null};Q.notEnumerableProp(g,"_getDomain",K);var q=n3(),H=BK0(),G=new H;q.defineProperty(g,"_async",{value:G});var W=u5(),w=g.TypeError=W.TypeError;g.RangeError=W.RangeError;var V=g.CancellationError=W.CancellationError;g.TimeoutError=W.TimeoutError,g.OperationalError=W.OperationalError,g.RejectionError=W.OperationalError,g.AggregateError=W.AggregateError;var Z=function(){},X={},L={},D=_K0()(g,Z),F=SK0()(g,Z,D,U,Y),E=hK0()(g),T=E.create,A=xK0()(g,E),R=A.CapturedTrace,k=fK0()(g,D),S=bK0()(L),i=gS(),C=Q.errorObj,p=Q.tryCatch;function n(B,x){if(typeof x!=="function")throw new w("expecting a function but got "+Q.classString(x));if(B.constructor!==g)throw new w(`thepromiseconstructorcannotbeinvokeddirectly
`)},I=function(){return new S.PromiseInspection(this._target())},U=function(B){return S.reject(new w(B))};function Y(){}var J={},Q=c1(),K;if(Q.isNode)K=function(){var B=process.domain;if(B===void 0)B=null;return B};else K=function(){return null};Q.notEnumerableProp(S,"_getDomain",K);var q=p3(),H=_K0(),G=new H;q.defineProperty(S,"_async",{value:G});var W=u5(),w=S.TypeError=W.TypeError;S.RangeError=W.RangeError;var V=S.CancellationError=W.CancellationError;S.TimeoutError=W.TimeoutError,S.OperationalError=W.OperationalError,S.RejectionError=W.OperationalError,S.AggregateError=W.AggregateError;var Z=function(){},X={},L={},D=uK0()(S,Z),O=kK0()(S,Z,D,U,Y),E=iK0()(S),T=E.create,A=nK0()(S,E),R=A.CapturedTrace,k=cK0()(S,D),g=mK0()(L),f=kg(),C=Q.errorObj,p=Q.tryCatch;function n(B,x){if(typeof x!=="function")throw new w("expecting a function but got "+Q.classString(x));if(B.constructor!==S)throw new w(`thepromiseconstructorcannotbeinvokeddirectly
Seehttp://goo.gl/MqrFmX
`)}function g(B){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,B!==Z)n(this,B),this._resolveFromExecutor(B);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(B){var x=arguments.length;if(x>1){var d=Array(x-1),t=0,K0;for(K0=0;K0<x-1;++K0){var W0=arguments[K0];if(Q.isObject(W0))d[t++]=W0;else return U("expecting an object but got A catch statement predicate "+Q.classString(W0))}return d.length=t,B=arguments[K0],this.then(void 0,S(d,B,this))}return this.then(void 0,B)},g.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},g.prototype.then=function(B,x){if(A.warnings()&&arguments.length>0&&typeof B!=="function"&&typeof x!=="function"){var d=".then() only accepts functions but was passed: "+Q.classString(B);if(arguments.length>1)d+=", "+Q.classString(x);this._warn(d)}return this._then(B,x,void 0,void 0,void 0)},g.prototype.done=function(B,x){var d=this._then(B,x,void 0,void 0,void 0);d._setIsFinal()},g.prototype.spread=function(B){if(typeof B!=="function")return U("expecting a function but got "+Q.classString(B));return this.all()._then(B,void 0,void 0,X,void 0)},g.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},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},g.prototype.error=function(B){return this.caught(Q.originatesFromRejection,B)},g.getNewLibraryCopy=yS.exports,g.is=function(B){return B instanceof g},g.fromNode=g.fromCallback=function(B){var x=new g(Z);x._captureStackTrace();var d=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,t=p(B)(i(x,d));if(t===C)x._rejectCallback(t.e,!0);if(!x._isFateSealed())x._setAsyncGuaranteed();return x},g.all=function(B){return new F(B).promise()},g.cast=function(B){var x=D(B);if(!(x instanceof g))x=new g(Z),x._captureStackTrace(),x._setFulfilled(),x._rejectionHandler0=B;return x},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(B){var x=new g(Z);return x._captureStackTrace(),x._rejectCallback(B,!0),x},g.setScheduler=function(B){if(typeof B!=="function")throw new w("expecting a function but got "+Q.classString(B));return G.setScheduler(B)},g.prototype._then=function(B,x,d,t,K0){var W0=K0!==void 0,A0=W0?K0:new g(Z),v0=this._target(),L1=v0._bitField;if(!W0){if(A0._propagateFrom(this,3),A0._captureStackTrace(),t===void 0&&(this._bitField&2097152)!==0)if((L1&50397184)!==0)t=this._boundValue();else t=v0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,A0)}var f0=K();if((L1&50397184)!==0){var G1,N0,S0=v0._settlePromiseCtx;if((L1&33554432)!==0)N0=v0._rejectionHandler0,G1=B;else if((L1&16777216)!==0)N0=v0._fulfillmentHandler0,G1=x,v0._unsetRejectionIsUnhandled();else S0=v0._settlePromiseLateCancellationObserver,N0=new V("late cancellation observer"),v0._attachExtraTrace(N0),G1=x;G.invoke(S0,v0,{handler:f0===null?G1:typeof G1==="function"&&Q.domainBind(f0,G1),promise:A0,receiver:t,value:N0})}else v0._addCallbacks(B,x,A0,t,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(B){this._bitField=this._bitField&-65536|B&65535},g.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},g.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},g.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},g.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},g.prototype._isFinal=function(){return(this._bitField&4194304)>0},g.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},g.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},g.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},g.prototype._setAsyncGuaranteed=function(){if(G.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(B){var x=B===0?this._receiver0:this[B*4-4+3];if(x===J)return;else if(x===void 0&&this._isBound())return this._boundValue();return x},g.prototype._promiseAt=function(B){return this[B*4-4+2]},g.prototype._fulfillmentHandlerAt=function(B){return this[B*4-4+0]},g.prototype._rejectionHandlerAt=function(B){return this[B*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(B){var{_bit
Line truncated
`)}function S(B){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,B!==Z)n(this,B),this._resolveFromExecutor(B);this._promiseCreated(),this._fireEvent("promiseCreated",this)}S.prototype.toString=function(){return"[object Promise]"},S.prototype.caught=S.prototype.catch=function(B){var x=arguments.length;if(x>1){var c=Array(x-1),r=0,Q0;for(Q0=0;Q0<x-1;++Q0){var w0=arguments[Q0];if(Q.isObject(w0))c[r++]=w0;else return U("expecting an object but got A catch statement predicate "+Q.classString(w0))}return c.length=r,B=arguments[Q0],this.then(void 0,g(c,B,this))}return this.then(void 0,B)},S.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},S.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: "+Q.classString(B);if(arguments.length>1)c+=", "+Q.classString(x);this._warn(c)}return this._then(B,x,void 0,void 0,void 0)},S.prototype.done=function(B,x){var c=this._then(B,x,void 0,void 0,void 0);c._setIsFinal()},S.prototype.spread=function(B){if(typeof B!=="function")return U("expecting a function but got "+Q.classString(B));return this.all()._then(B,void 0,void 0,X,void 0)},S.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},S.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new O(this).promise()},S.prototype.error=function(B){return this.caught(Q.originatesFromRejection,B)},S.getNewLibraryCopy=ig.exports,S.is=function(B){return B instanceof S},S.fromNode=S.fromCallback=function(B){var x=new S(Z);x._captureStackTrace();var c=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=p(B)(f(x,c));if(r===C)x._rejectCallback(r.e,!0);if(!x._isFateSealed())x._setAsyncGuaranteed();return x},S.all=function(B){return new O(B).promise()},S.cast=function(B){var x=D(B);if(!(x instanceof S))x=new S(Z),x._captureStackTrace(),x._setFulfilled(),x._rejectionHandler0=B;return x},S.resolve=S.fulfilled=S.cast,S.reject=S.rejected=function(B){var x=new S(Z);return x._captureStackTrace(),x._rejectCallback(B,!0),x},S.setScheduler=function(B){if(typeof B!=="function")throw new w("expecting a function but got "+Q.classString(B));return G.setScheduler(B)},S.prototype._then=function(B,x,c,r,Q0){var w0=Q0!==void 0,M0=w0?Q0:new S(Z),R0=this._target(),K1=R0._bitField;if(!w0){if(M0._propagateFrom(this,3),M0._captureStackTrace(),r===void 0&&(this._bitField&2097152)!==0)if((K1&50397184)!==0)r=this._boundValue();else r=R0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,M0)}var k0=K();if((K1&50397184)!==0){var I1,t,T0=R0._settlePromiseCtx;if((K1&33554432)!==0)t=R0._rejectionHandler0,I1=B;else if((K1&16777216)!==0)t=R0._fulfillmentHandler0,I1=x,R0._unsetRejectionIsUnhandled();else T0=R0._settlePromiseLateCancellationObserver,t=new V("late cancellation observer"),R0._attachExtraTrace(t),I1=x;G.invoke(T0,R0,{handler:k0===null?I1:typeof I1==="function"&&Q.domainBind(k0,I1),promise:M0,receiver:r,value:t})}else R0._addCallbacks(B,x,M0,r,k0);return M0},S.prototype._length=function(){return this._bitField&65535},S.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},S.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},S.prototype._setLength=function(B){this._bitField=this._bitField&-65536|B&65535},S.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},S.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},S.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},S.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},S.prototype._isFinal=function(){return(this._bitField&4194304)>0},S.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},S.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},S.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},S.prototype._setAsyncGuaranteed=function(){if(G.hasCustomScheduler())return;this._bitField=this._bitField|134217728},S.prototype._receiverAt=function(B){var x=B===0?this._receiver0:this[B*4-4+3];if(x===J)return;else if(x===void 0&&this._isBound())return this._boundValue();return x},S.prototype._promiseAt=function(B){return this[B*4-4+2]},S.prototype._fulfillmentHandlerAt=function(B){return this[B*4-4+0]},S.prototype._rejectionHandlerAt=function(B){return this[B*4-4+1]},S.prototype._boundValue=function(){},S.prototype._migrateCallback0=function(B){var{_bitField:
Line truncated
`).filter((Q)=>Q),Y=Math.min(...U.map((Q)=>Q.length-Q.trimStart().length)),J=U.map((Q)=>Q.slice(Y)).map((Q)=>" ".repeat(this.indent*2)+Q);for(let Q of J)this.content.push(Q)}compile(){let $=Function,I=this?.args,Y=[...(this?.content??[""]).map((J)=>`${J}`)];return new $(...I,Y.join(`
`))}}var IF={major:4,minor:4,patch:3};var b0=o("$ZodType",($,I)=>{var U;$??($={}),$._zod.def=I,$._zod.bag=$._zod.bag||{},$._zod.version=IF;let Y=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))Y.unshift($);for(let J of Y)for(let Q of J._zod.onattach)Q($);if(Y.length===0)(U=$._zod).deferred??(U.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let J=(K,q,H)=>{let G=I9(K),W;for(let w of q){if(w._zod.def.when){if(QO(K))continue;if(!w._zod.def.when(K))continue}else if(G)continue;let V=K.issues.length,Z=w._zod.check(K);if(Z instanceof Promise&&H?.async===!1)throw new H8;if(W||Z instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await Z,K.issues.length===V)return;if(!G)G=I9(K,V)});else{if(K.issues.length===V)continue;if(!G)G=I9(K,V)}}if(W)return W.then(()=>{return K});return K},Q=(K,q,H)=>{if(I9(K))return K.aborted=!0,K;let G=J(q,Y,H);if(G instanceof Promise){if(H.async===!1)throw new H8;return G.then((W)=>$._zod.parse(W,H))}return $._zod.parse(G,H)};$._zod.run=(K,q)=>{if(q.skipChecks)return $._zod.parse(K,q);if(q.direction==="backward"){let G=$._zod.parse({value:K.value,issues:[]},{...q,skipChecks:!0});if(G instanceof Promise)return G.then((W)=>{return Q(W,K,q)});return Q(G,K,q)}let H=$._zod.parse(K,q);if(H instanceof Promise){if(q.async===!1)throw new H8;return H.then((G)=>J(G,Y,q))}return J(H,Y,q)}}e0($,"~standard",()=>({validate:(J)=>{try{let Q=EI($,J);return Q.success?{value:Q.data}:{issues:Q.error?.issues}}catch(Q){return aJ($,J).then((K)=>K.success?{value:K.data}:{issues:K.error?.issues})}},vendor:"zod",version:1}))}),j7=o("$ZodString",($,I)=>{b0.init($,I),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??CO($._zod.bag),$._zod.parse=(U,Y)=>{if(I.coerce)try{U.value=String(U.value)}catch(J){}if(typeof U.value==="string")return U;return U.issues.push({expected:"string",code:"invalid_type",input:U.value,inst:$}),U}}),S1=o("$ZodStringFormat",($,I)=>{vI.init($,I),j7.init($,I)}),YF=o("$ZodGUID",($,I)=>{I.pattern??(I.pattern=XO),S1.init($,I)}),JF=o("$ZodUUID",($,I)=>{if(I.version){let Y={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[I.version];if(Y===void 0)throw Error(`InvalidUUIDversion:"${I.version}"`);I.pattern??(I.pattern=C7(Y))}else I.pattern??(I.pattern=C7());S1.init($,I)}),QF=o("$ZodEmail",($,I)=>{I.pattern??(I.pattern=LO),S1.init($,I)}),KF=o("$ZodURL",($,I)=>{S1.init($,I),$._zod.check=(U)=>{try{let Y=U.value.trim();if(!I.normalize&&I.protocol?.source===TO.source){if(!/^https?:\/\//i.test(Y)){U.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:U.value,inst:$,continue:!I.abort});return}}let J=new URL(Y);if(I.hostname){if(I.hostname.lastIndex=0,!I.hostname.test(J.hostname))U.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:I.hostname.source,input:U.value,inst:$,continue:!I.abort})}if(I.protocol){if(I.protocol.lastIndex=0,!I.protocol.test(J.protocol.endsWith(":")?J.protocol.slice(0,-1):J.protocol))U.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:I.protocol.source,input:U.value,inst:$,continue:!I.abort})}if(I.normalize)U.value=J.href;else U.value=Y;return}catch(Y){U.issues.push({code:"invalid_format",format:"url",input:U.value,inst:$,continue:!I.abort})}}}),qF=o("$ZodEmoji",($,I)=>{I.pattern??(I.pattern=DO()),S1.init($,I)}),HF=o("$ZodNanoID",($,I)=>{I.pattern??(I.pattern=ZO),S1.init($,I)}),GF=o("$ZodCUID",($,I)=>{I.pattern??(I.pattern=HO),S1.init($,I)}),WF=o("$ZodCUID2",($,I)=>{I.pattern??(I.pattern=GO),S1.init($,I)}),wF=o("$ZodULID",($,I)=>{I.pattern??(I.pattern=WO),S1.init($,I)}),VF=o("$ZodXID",($,I)=>{I.pattern??(I.pattern=wO),S1.init($,I)}),ZF=o("$ZodKSUID",($,I)=>{I.pattern??(I.pattern=VO),S1.init($,I)}),zF=o("$ZodISODateTime",($,I)=>{I.pattern??(I.pattern=RO(I)),S1.init($,I)}),XF=o("$ZodISODate",($,I)=>{I.pattern??(I.pattern=BO),S1.init($,I)}),LF=o("$ZodISOTime",($,I)=>{I.pattern??(I.pattern=vO(I)),S1.init($,I)}),DF=o("$ZodISODuration",($,I)=>{I.pattern??(I.pattern=zO),S1.init($,I)}),OF=o("$ZodIPv4",($,I)=>{I.pattern??(I.pattern=OO),S1.init($,I),$._zod.bag.format="ipv4"}),FF=o("$ZodIPv6",($,I)=>{I.pattern??(I.pattern=FO),S1.init($,I),$._zod.bag.format="ipv6",$._zod.check=(U)=>{try{new URL(`http://[${U.value}]`)}catch{U.issues.push({code:"invalid_format",format:"ipv6",input:U.value,inst:$,continue:!I.abort})}}}),NF=o("$ZodMAC",($,I)=>{I.pattern??(I.pattern=NO(I.delimiter)),S1.init($,I),$._zod.bag.format="mac"}),MF=o("$ZodCIDRv4",($,I)=>{I.pattern??(I.pattern=MO),S1.init($,I)}),AF=o("$ZodCIDRv6",($,I)=>{I.pattern??(I.pattern=AO),S1.init($,I),$._zod.check=(U)=>{let Y=U.value.split("/");try{if(Y.length!==2)throw Error();let[J,Q]=Y;if(!Q)throw Error();let K=Number(Q);if(`${K}`!==Q)throw Error();if(K<0||K>128)throw Error();new URL(`http://[${J}]`)}catch{U.issues.push({code:"invalid_format",format:"cidrv6",input:U.value,inst:$,continue:!I.abort})}}});function PF($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}
Line truncated
`))}}var qO={major:4,minor:4,patch:3};var n0=o("$ZodType",($,I)=>{var U;$??($={}),$._zod.def=I,$._zod.bag=$._zod.bag||{},$._zod.version=qO;let Y=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))Y.unshift($);for(let J of Y)for(let Q of J._zod.onattach)Q($);if(Y.length===0)(U=$._zod).deferred??(U.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let J=(K,q,H)=>{let G=I9(K),W;for(let w of q){if(w._zod.def.when){if(wF(K))continue;if(!w._zod.def.when(K))continue}else if(G)continue;let V=K.issues.length,Z=w._zod.check(K);if(Z instanceof Promise&&H?.async===!1)throw new W8;if(W||Z instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await Z,K.issues.length===V)return;if(!G)G=I9(K,V)});else{if(K.issues.length===V)continue;if(!G)G=I9(K,V)}}if(W)return W.then(()=>{return K});return K},Q=(K,q,H)=>{if(I9(K))return K.aborted=!0,K;let G=J(q,Y,H);if(G instanceof Promise){if(H.async===!1)throw new W8;return G.then((W)=>$._zod.parse(W,H))}return $._zod.parse(G,H)};$._zod.run=(K,q)=>{if(q.skipChecks)return $._zod.parse(K,q);if(q.direction==="backward"){let G=$._zod.parse({value:K.value,issues:[]},{...q,skipChecks:!0});if(G instanceof Promise)return G.then((W)=>{return Q(W,K,q)});return Q(G,K,q)}let H=$._zod.parse(K,q);if(H instanceof Promise){if(q.async===!1)throw new W8;return H.then((G)=>J(G,Y,q))}return J(H,Y,q)}}e0($,"~standard",()=>({validate:(J)=>{try{let Q=BI($,J);return Q.success?{value:Q.data}:{issues:Q.error?.issues}}catch(Q){return sJ($,J).then((K)=>K.success?{value:K.data}:{issues:K.error?.issues})}},vendor:"zod",version:1}))}),_7=o("$ZodString",($,I)=>{n0.init($,I),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??hF($._zod.bag),$._zod.parse=(U,Y)=>{if(I.coerce)try{U.value=String(U.value)}catch(J){}if(typeof U.value==="string")return U;return U.issues.push({expected:"string",code:"invalid_type",input:U.value,inst:$}),U}}),y1=o("$ZodStringFormat",($,I)=>{RI.init($,I),_7.init($,I)}),GO=o("$ZodGUID",($,I)=>{I.pattern??(I.pattern=MF),y1.init($,I)}),WO=o("$ZodUUID",($,I)=>{if(I.version){let Y={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[I.version];if(Y===void 0)throw Error(`InvalidUUIDversion:"${I.version}"`);I.pattern??(I.pattern=j7(Y))}else I.pattern??(I.pattern=j7());y1.init($,I)}),wO=o("$ZodEmail",($,I)=>{I.pattern??(I.pattern=AF),y1.init($,I)}),VO=o("$ZodURL",($,I)=>{y1.init($,I),$._zod.check=(U)=>{try{let Y=U.value.trim();if(!I.normalize&&I.protocol?.source===jF.source){if(!/^https?:\/\//i.test(Y)){U.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:U.value,inst:$,continue:!I.abort});return}}let J=new URL(Y);if(I.hostname){if(I.hostname.lastIndex=0,!I.hostname.test(J.hostname))U.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:I.hostname.source,input:U.value,inst:$,continue:!I.abort})}if(I.protocol){if(I.protocol.lastIndex=0,!I.protocol.test(J.protocol.endsWith(":")?J.protocol.slice(0,-1):J.protocol))U.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:I.protocol.source,input:U.value,inst:$,continue:!I.abort})}if(I.normalize)U.value=J.href;else U.value=Y;return}catch(Y){U.issues.push({code:"invalid_format",format:"url",input:U.value,inst:$,continue:!I.abort})}}}),ZO=o("$ZodEmoji",($,I)=>{I.pattern??(I.pattern=PF()),y1.init($,I)}),zO=o("$ZodNanoID",($,I)=>{I.pattern??(I.pattern=OF),y1.init($,I)}),XO=o("$ZodCUID",($,I)=>{I.pattern??(I.pattern=zF),y1.init($,I)}),LO=o("$ZodCUID2",($,I)=>{I.pattern??(I.pattern=XF),y1.init($,I)}),DO=o("$ZodULID",($,I)=>{I.pattern??(I.pattern=LF),y1.init($,I)}),FO=o("$ZodXID",($,I)=>{I.pattern??(I.pattern=DF),y1.init($,I)}),OO=o("$ZodKSUID",($,I)=>{I.pattern??(I.pattern=FF),y1.init($,I)}),NO=o("$ZodISODateTime",($,I)=>{I.pattern??(I.pattern=yF(I)),y1.init($,I)}),MO=o("$ZodISODate",($,I)=>{I.pattern??(I.pattern=SF),y1.init($,I)}),AO=o("$ZodISOTime",($,I)=>{I.pattern??(I.pattern=gF(I)),y1.init($,I)}),PO=o("$ZodISODuration",($,I)=>{I.pattern??(I.pattern=NF),y1.init($,I)}),TO=o("$ZodIPv4",($,I)=>{I.pattern??(I.pattern=TF),y1.init($,I),$._zod.bag.format="ipv4"}),EO=o("$ZodIPv6",($,I)=>{I.pattern??(I.pattern=EF),y1.init($,I),$._zod.bag.format="ipv6",$._zod.check=(U)=>{try{new URL(`http://[${U.value}]`)}catch{U.issues.push({code:"invalid_format",format:"ipv6",input:U.value,inst:$,continue:!I.abort})}}}),BO=o("$ZodMAC",($,I)=>{I.pattern??(I.pattern=BF(I.delimiter)),y1.init($,I),$._zod.bag.format="mac"}),vO=o("$ZodCIDRv4",($,I)=>{I.pattern??(I.pattern=vF),y1.init($,I)}),RO=o("$ZodCIDRv6",($,I)=>{I.pattern??(I.pattern=RF),y1.init($,I),$._zod.check=(U)=>{let Y=U.value.split("/");try{if(Y.length!==2)throw Error();let[J,Q]=Y;if(!Q)throw Error();let K=Number(Q);if(`${K}`!==Q)throw Error();if(K<0||K>128)throw Error();new URL(`http://[${J}]`)}catch{U.issues.push({code:"invalid_format",format:"cidrv6",input:U.value,inst:$,continue:!I.abort})}}});function CO($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}
Line truncated
`)}Z.write("payload.value = newResult;"),Z.write("return payload;");let E=Z.compile();return(T,A)=>E(V,T,A)},Q,K=R7,q=!B7.jitless,G=q&&eD.value,W=I.catchall,w;$._zod.parse=(V,Z)=>{w??(w=Y.value);let X=V.value;if(!K(X))return V.issues.push({expected:"object",code:"invalid_type",input:X,inst:$}),V;if(q&&G&&Z?.async===!1&&Z.jitless!==!0){if(!Q)Q=J(I.shape);if(V=Q(V,Z),!W)return V;return wk([],X,V,Z,w,$)}return U(V,Z)}});function rx($,I,U,Y){for(let Q of $)if(Q.issues.length===0)return I.value=Q.value,I;let J=$.filter((Q)=>!I9(Q));if(J.length===1)return I.value=J[0].value,J[0];return I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:$.map((Q)=>Q.issues.map((K)=>P6(K,Y,Z4())))}),I}var UQ=o("$ZodUnion",($,I)=>{b0.init($,I),e0($._zod,"optin",()=>I.options.some((Y)=>Y._zod.optin==="optional")?"optional":void 0),e0($._zod,"optout",()=>I.options.some((Y)=>Y._zod.optout==="optional")?"optional":void 0),e0($._zod,"values",()=>{if(I.options.every((Y)=>Y._zod.values))return new Set(I.options.flatMap((Y)=>Array.from(Y._zod.values)));return}),e0($._zod,"pattern",()=>{if(I.options.every((Y)=>Y._zod.pattern)){let Y=I.options.map((J)=>J._zod.pattern);return new RegExp(`^(${Y.map((J)=>nJ(J.source)).join("|")})$`)}return});let U=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(Y,J)=>{if(U)return U(Y,J);let Q=!1,K=[];for(let q of I.options){let H=q._zod.run({value:Y.value,issues:[]},J);if(H instanceof Promise)K.push(H),Q=!0;else{if(H.issues.length===0)return H;K.push(H)}}if(!Q)return rx(K,Y,$,J);return Promise.all(K).then((q)=>{return rx(q,Y,$,J)})}});function tx($,I,U,Y){let J=$.filter((Q)=>Q.issues.length===0);if(J.length===1)return I.value=J[0].value,I;if(J.length===0)I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:$.map((Q)=>Q.issues.map((K)=>P6(K,Y,Z4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:[],inclusive:!1});return I}var bF=o("$ZodXor",($,I)=>{UQ.init($,I),I.inclusive=!1;let U=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(Y,J)=>{if(U)return U(Y,J);let Q=!1,K=[];for(let q of I.options){let H=q._zod.run({value:Y.value,issues:[]},J);if(H instanceof Promise)K.push(H),Q=!0;else K.push(H)}if(!Q)return tx(K,Y,$,J);return Promise.all(K).then((q)=>{return tx(q,Y,$,J)})}}),nF=o("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,UQ.init($,I);let U=$._zod.parse;e0($._zod,"propValues",()=>{let J={};for(let Q of I.options){let K=Q._zod.propValues;if(!K||Object.keys(K).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${I.options.indexOf(Q)}"`);for(let[q,H]of Object.entries(K)){if(!J[q])J[q]=new Set;for(let G of H)J[q].add(G)}}return J});let Y=NI(()=>{let J=I.options,Q=new Map;for(let K of J){let q=K._zod.propValues?.[I.discriminator];if(!q||q.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${I.options.indexOf(K)}"`);for(let H of q){if(Q.has(H))throw Error(`Duplicatediscriminatorvalue"${String(H)}"`);Q.set(H,K)}}return Q});$._zod.parse=(J,Q)=>{let K=J.value;if(!R7(K))return J.issues.push({code:"invalid_type",expected:"object",input:K,inst:$}),J;let q=Y.value.get(K?.[I.discriminator]);if(q)return q._zod.run(J,Q);if(I.unionFallback||Q.direction==="backward")return U(J,Q);return J.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(Y.value.keys()),input:K,path:[I.discriminator],inst:$}),J}}),pF=o("$ZodIntersection",($,I)=>{b0.init($,I),$._zod.parse=(U,Y)=>{let J=U.value,Q=I.left._zod.run({value:J,issues:[]},Y),K=I.right._zod.run({value:J,issues:[]},Y);if(Q instanceof Promise||K instanceof Promise)return Promise.all([Q,K]).then(([H,G])=>{return ax(U,H,G)});return ax(U,Q,K)}});function UF($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if($9($)&&$9(I)){let U=Object.keys(I),Y=Object.keys($).filter((Q)=>U.indexOf(Q)!==-1),J={...$,...I};for(let Q of Y){let K=UF($[Q],I[Q]);if(!K.valid)return{valid:!1,mergeErrorPath:[Q,...K.mergeErrorPath]};J[Q]=K.data}return{valid:!0,data:J}}if(Array.isArray($)&&Array.isArray(I)){if($.length!==I.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let Y=0;Y<$.length;Y++){let J=$[Y],Q=I[Y],K=UF(J,Q);if(!K.valid)return{valid:!1,mergeErrorPath:[Y,...K.mergeErrorPath]};U.push(K.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function ax($,I,U){let Y=new Map,J;for(let q of I.issues)if(q.code==="unrecognized_keys"){J??(J=q);for(let H of q.keys){if(!Y.has(H))Y.set(H,{});Y.get(H).l=!0}}else $.issues.push(q);for(let q of U.issues)if(q.code==="unrecognized_keys")for(let H of q.keys){if(!Y.has(H))Y.set(H,{});Y.get(H).r=!0}else $.issues.push(q);let Q=[...Y].filter(([,q])=>q.l&&q.r).map(([q])=>q);if(Q.length&&J)$.issues.push({...J,keys:Q});if(I9($))return $;let K=UF(I.value,U.value);if(!K.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(K.mergeErrorPath)}`);return $.value=K.data,$}var zG=o("$ZodTuple",($,I)=>{b0.
Line truncated
`)}Z.write("payload.value = newResult;"),Z.write("return payload;");let E=Z.compile();return(T,A)=>E(V,T,A)},Q,K=C7,q=!v7.jitless,G=q&&QF.value,W=I.catchall,w;$._zod.parse=(V,Z)=>{w??(w=Y.value);let X=V.value;if(!K(X))return V.issues.push({expected:"object",code:"invalid_type",input:X,inst:$}),V;if(q&&G&&Z?.async===!1&&Z.jitless!==!0){if(!Q)Q=J(I.shape);if(V=Q(V,Z),!W)return V;return Dk([],X,V,Z,w,$)}return U(V,Z)}});function Ik($,I,U,Y){for(let Q of $)if(Q.issues.length===0)return I.value=Q.value,I;let J=$.filter((Q)=>!I9(Q));if(J.length===1)return I.value=J[0].value,J[0];return I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:$.map((Q)=>Q.issues.map((K)=>E6(K,Y,z4())))}),I}var YQ=o("$ZodUnion",($,I)=>{n0.init($,I),e0($._zod,"optin",()=>I.options.some((Y)=>Y._zod.optin==="optional")?"optional":void 0),e0($._zod,"optout",()=>I.options.some((Y)=>Y._zod.optout==="optional")?"optional":void 0),e0($._zod,"values",()=>{if(I.options.every((Y)=>Y._zod.values))return new Set(I.options.flatMap((Y)=>Array.from(Y._zod.values)));return}),e0($._zod,"pattern",()=>{if(I.options.every((Y)=>Y._zod.pattern)){let Y=I.options.map((J)=>J._zod.pattern);return new RegExp(`^(${Y.map((J)=>pJ(J.source)).join("|")})$`)}return});let U=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(Y,J)=>{if(U)return U(Y,J);let Q=!1,K=[];for(let q of I.options){let H=q._zod.run({value:Y.value,issues:[]},J);if(H instanceof Promise)K.push(H),Q=!0;else{if(H.issues.length===0)return H;K.push(H)}}if(!Q)return Ik(K,Y,$,J);return Promise.all(K).then((q)=>{return Ik(q,Y,$,J)})}});function Uk($,I,U,Y){let J=$.filter((Q)=>Q.issues.length===0);if(J.length===1)return I.value=J[0].value,I;if(J.length===0)I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:$.map((Q)=>Q.issues.map((K)=>E6(K,Y,z4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:[],inclusive:!1});return I}var lO=o("$ZodXor",($,I)=>{YQ.init($,I),I.inclusive=!1;let U=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(Y,J)=>{if(U)return U(Y,J);let Q=!1,K=[];for(let q of I.options){let H=q._zod.run({value:Y.value,issues:[]},J);if(H instanceof Promise)K.push(H),Q=!0;else K.push(H)}if(!Q)return Uk(K,Y,$,J);return Promise.all(K).then((q)=>{return Uk(q,Y,$,J)})}}),oO=o("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,YQ.init($,I);let U=$._zod.parse;e0($._zod,"propValues",()=>{let J={};for(let Q of I.options){let K=Q._zod.propValues;if(!K||Object.keys(K).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${I.options.indexOf(Q)}"`);for(let[q,H]of Object.entries(K)){if(!J[q])J[q]=new Set;for(let G of H)J[q].add(G)}}return J});let Y=MI(()=>{let J=I.options,Q=new Map;for(let K of J){let q=K._zod.propValues?.[I.discriminator];if(!q||q.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${I.options.indexOf(K)}"`);for(let H of q){if(Q.has(H))throw Error(`Duplicatediscriminatorvalue"${String(H)}"`);Q.set(H,K)}}return Q});$._zod.parse=(J,Q)=>{let K=J.value;if(!C7(K))return J.issues.push({code:"invalid_type",expected:"object",input:K,inst:$}),J;let q=Y.value.get(K?.[I.discriminator]);if(q)return q._zod.run(J,Q);if(I.unionFallback||Q.direction==="backward")return U(J,Q);return J.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(Y.value.keys()),input:K,path:[I.discriminator],inst:$}),J}}),rO=o("$ZodIntersection",($,I)=>{n0.init($,I),$._zod.parse=(U,Y)=>{let J=U.value,Q=I.left._zod.run({value:J,issues:[]},Y),K=I.right._zod.run({value:J,issues:[]},Y);if(Q instanceof Promise||K instanceof Promise)return Promise.all([Q,K]).then(([H,G])=>{return Yk(U,H,G)});return Yk(U,Q,K)}});function HO($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if($9($)&&$9(I)){let U=Object.keys(I),Y=Object.keys($).filter((Q)=>U.indexOf(Q)!==-1),J={...$,...I};for(let Q of Y){let K=HO($[Q],I[Q]);if(!K.valid)return{valid:!1,mergeErrorPath:[Q,...K.mergeErrorPath]};J[Q]=K.data}return{valid:!0,data:J}}if(Array.isArray($)&&Array.isArray(I)){if($.length!==I.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let Y=0;Y<$.length;Y++){let J=$[Y],Q=I[Y],K=HO(J,Q);if(!K.valid)return{valid:!1,mergeErrorPath:[Y,...K.mergeErrorPath]};U.push(K.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function Yk($,I,U){let Y=new Map,J;for(let q of I.issues)if(q.code==="unrecognized_keys"){J??(J=q);for(let H of q.keys){if(!Y.has(H))Y.set(H,{});Y.get(H).l=!0}}else $.issues.push(q);for(let q of U.issues)if(q.code==="unrecognized_keys")for(let H of q.keys){if(!Y.has(H))Y.set(H,{});Y.get(H).r=!0}else $.issues.push(q);let Q=[...Y].filter(([,q])=>q.l&&q.r).map(([q])=>q);if(Q.length&&J)$.issues.push({...J,keys:Q});if(I9($))return $;let K=HO(I.value,U.value);if(!K.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(K.mergeErrorPath)}`);return $.value=K.data,$}var LG=o("$ZodTuple",($,I)=>{n0.
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letKof$.seen.entries()){letq=K[1];if(I===K[0]){Q(K);continue}if($.external){letG=$.external.registry.get(K[0])?.id;if(I!==K[0]&&G){Q(K);continue}}if($.metadataRegistry.get(K[0])?.id){Q(K);continue}if(q.cycle){Q(K);continue}if(q.count>1){if($.reused==="ref"){Q(K);continue}}}}functionK9($,I){letU=$.seen.get(I);if(!U)throwError("Unprocessed schema. This is a bug in Zod.");letY=(q)=>{letH=$.seen.get(q);if(H.ref===null)return;letG=H.def??H.schema,W={...G},w=H.ref;if(H.ref=null,w){Y(w);letZ=$.seen.get(w),X=Z.schema;if(X.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))G.allOf=G.allOf??[],G.allOf.push(X);elseObject.assign(G,X);if(Object.assign(G,W),q._zod.parent===w)for(letDinG){if(D==="$ref"||D==="allOf")continue;if(!(DinW))deleteG[D]}if(X.$ref&&Z.def)for(letDinG){if(D==="$ref"||D==="allOf")continue;if(DinZ.def&&JSON.stringify(G[D])===JSON.stringify(Z.def[D]))deleteG[D]}}letV=q._zod.parent;if(V&&V!==w){Y(V);letZ=$.seen.get(V);if(Z?.schema.$ref){if(G.$ref=Z.schema.$ref,Z.def)for(letXinG){if(X==="$ref"||X==="allOf")continue;if(XinZ.def&&JSON.stringify(G[X])===JSON.stringify(Z.def[X]))deleteG[X]}}}$.override({zodSchema:q,jsonSchema:G,path:H.path??[]})};for(letqof[...$.seen.entries()].reverse())Y(q[0]);letJ={};if($.target==="draft-2020-12")J.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")J.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")J.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letq=$.external.registry.get(I)?.id;if(!q)throwError("Schema is missing an `id` property");J.$id=$.external.uri(q)}Object.assign(J,U.def??U.schema);letQ=$.metadataRegistry.get(I)?.id;if(Q!==void0&&J.id===Q)deleteJ.id;letK=$.external?.defs??{};for(letqof$.seen.entries()){letH=q[1];if(H.def&&H.defId){if(H.def.id===H.defId)deleteH.def.id;K[H.defId]=H.def}}if($.external);elseif(Object.keys(K).length>0)if($.target==="draft-2020-12")J.$defs=K;elseJ.definitions=K;try{letq=JSON.parse(JSON.stringify(J));returnObject.defineProperty(q,"~standard",{value:{...I["~standard"],jsonSchema:{input:nI(I,"input",$.processors),output:nI(I,"output",$.processors)}},enumerable:!1,writable:!1}),q}catch(q){throwError("Error converting schema to JSON.")}}functionE6($,I){letU=I??{seen:newSet};if(U.seen.has($))return!1;U.seen.add($);letY=$._zod.def;if(Y.type==="transform")return!0;if(Y.type==="array")returnE6(Y.element,U);if(Y.type==="set")returnE6(Y.valueType,U);if(Y.type==="lazy")returnE6(Y.getter(),U);if(Y.type==="promise"||Y.type==="optional"||Y.type==="nonoptional"||Y.type==="nullable"||Y.type==="readonly"||Y.type==="default"||Y.type==="prefault")returnE6(Y.innerType,U);if(Y.type==="intersection")returnE6(Y.left,U)||E6(Y.right,U);if(Y.type==="record"||Y.type==="map")returnE6(Y.keyType,U)||E6(Y.valueType,U);if(Y.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnE6(Y.in,U)||E6(Y.out,U)}if(Y.type==="object"){for(letJinY.shape)if(E6(Y.shape[J],U))return!0;return!1}if(Y.type==="union"){for(letJofY.options)if(E6(J,U))return!0;return!1}if(Y.type==="tuple"){for(letJofY.items)if(E6(J,U))return!0;if(Y.rest&&E6(Y.rest,U))return!0;return!1}return!1}varrM=($,I={})=>(U)=>{letY=J9({...U,processors:I});returnC1($,Y),Q9(Y,$),K9(Y,$)},nI=($,I,U={})=>(Y)=>{let{libraryOptions:J,target:Q}=Y??{},K=J9({...J??{},target:Q,io:I,processors:U});returnC1($,K),Q9(K,$),K9(K,$)};varyO0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},tM=($,I,U,Y)=>{letJ=U;J.type="string";let{minimum:Q,maximum:K,format:q,patterns:H,contentEncoding:G}=$._zod.bag;if(typeofQ==="number")J.minLength=Q;if(typeofK==="number")J.maxLength=K;if(q){if(J.format=yO0[q]??q,J.format==="")deleteJ.format;if(q==="time")deleteJ.format}if(G)J.contentEncoding=G;if(H&&H.size>0){letW=[...H];if(W.length===1)J.pattern=W[0].source;elseif(W.length>1)J.allOf=[...W.map((w)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:w.source}))]}},aM=($,I,U,Y)=>{letJ=U,{minimum:Q,maximum:K,format:q,multipleOf:H,exclusiveMaximum:G,exclusiveMinimum:W}=$._zod.bag;if(typeofq==="string"&&q.includes("int"))J.type="integer";elseJ.type="number";letw=typeofW==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),V=typeofG==="number"&&G<=(K??Number.POSITIVE_INFINITY),Z=I.target==="draft-04"||I.target==="openapi-3.0";if(w)if(Z)J.minimum=W,J.exclusiveMinimum=!0;elseJ.exclusiveMinimum=W;elseif(typeofQ==="number")J.minimum=Q;if(V)if(Z)J.maximum=G,J.exclusiveMaximum=!0;elseJ.exclusiveMaximum=G;elseif(typeofK==="number")J.maximum=K;if(typeofH==="number")J.multipleOf=H},sM=($,I,U,Y)=>{U.type="boolean"},eM=($,I,U,Y)=>{if(I.unrepresentable==="throw")throwError("BigInt cannot be represented in JSON Schema")},$A=($,I,U,Y)=>{if(I.unrepresentable==Line truncated
`}class ZE{constructor($=bc.stdin,I=bc.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new VE,this._started=!1,this._ondata=(U)=>{this._readBuffer.append(U),this.processReadBuffer()},this._onerror=(U)=>{this.onerror?.(U)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((I)=>{let U=ic($);if(this._stdout.write(U))I();else this._stdout.once("drain",I)})}}import{dirname as cu,join as tG1}from"node:path";import{fileURLToPath as aG1}from"node:url";class q5 extends Error{name="KyError";get isKyError(){return!0}}class J$ extends q5{name="HTTPError";response;request;options;data;constructor($,I,U){let Y=$.status||$.status===0?$.status:"",J=$.statusText??"",Q=`${Y}${J}`.trim(),K=Q?`statuscode${Q}`:"an unknown error";super(`Requestfailedwith${K}:${I.method}${I.url}`);this.response=$,this.request=I,this.options=U}}class K2 extends q5{name="NetworkError";request;constructor($,I){super(`Requestfailedduetoanetworkerror:${$.method}${$.url}`,I);this.request=$}}class q2 extends Error{name="NonError";value;constructor($){let I="Non-error value was thrown";try{if(typeof $==="string")I=$;else if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string")I=$.message}catch{}super(I);this.value=$}}class XU extends q5{name="ForceRetryError";customDelay;code;customRequest;constructor($){let I=$?.cause?$.cause instanceof Error?$.cause:new q2($.cause):void 0;super($?.code?`Forcedretry:${$.code}`:"Forced retry",I?{cause:I}:void 0);this.customDelay=$?.delay,this.code=$?.code,this.customRequest=$?.request}}class zE extends Error{name="SchemaValidationError";issues;constructor($){super("Response schema validation failed");this.issues=$}}class o$ extends q5{name="TimeoutError";request;constructor($){super(`Requesttimedout:${$.method}${$.url}`);this.request=$}}var XE=(()=>{let $=!1,I=!1,U=typeof globalThis.ReadableStream==="function",Y=typeof globalThis.Request==="function";if(U&&Y)try{I=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return $=!0,"half"}}).headers.has("Content-Type")}catch(J){if(J instanceof Error&&J.message==="unsupported BodyInit type")return!1;throw J}return $&&!I})(),nc=typeof globalThis.AbortController==="function",Nw=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",pc=typeof globalThis.ReadableStream==="function",cc=typeof globalThis.FormData==="function",Mw=["get","post","put","patch","head","delete"],YC0=()=>{return};YC0();var dc={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},LU=2147483647,mc=40,Aw=Symbol("stop");class Pw{options;constructor($){this.options=$}}var lc=($)=>new Pw($),oc={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},rc={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var Tw=new TextEncoder,JC0=($)=>{if(!$)return 0;if($ instanceof FormData){let I=0;for(let[U,Y]of $)I+=mc,I+=Tw.encode(`Content-Disposition:form-data;name="${U}"`).byteLength,I+=typeof Y==="string"?Tw.encode(Y).byteLength:Y.size;return I}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return Tw.encode($).byteLength;if($ instanceof URLSearchParams)return Tw.encode($.toString()).byteLength;return 0},tc=($,I,U)=>{let Y,J=0;return $.pipeThrough(new TransformStream({transform(Q,K){if(K.enqueue(Q),Y){J+=Y.byteLength;let q=I===0?0:J/I;if(q>=1)q=1-Number.EPSILON;U?.({percent:q,totalBytes:Math.max(I,J),transferredBytes:J},Y)}Y=Q},flush(){if(Y)J+=Y.byteLength,U?.({percent:1,totalBytes:Math.max(I,J),transferredBytes:J},Y)}}))},ac=($,I)=>{if(!$.body)return $;let U={status:$.status,statusText:$.statusText,headers:$.headers};if($.status===204)return new Response(null,U);let Y=Math.max(0,Number($.headers.get("content-length"))||0);return new Response(tc($.body,Y,I),U)},sc=($,I,U)=>{if(!$.body)return $;let Y=JC0(U??$.body);return new Request($,{duplex:"half",body:tc($.body,Y,I)})};var X8=($)=>$!==null&&typeof $==="object";var QC0=Symbol("replaceOption"),LE=($)=>X8($)&&$[QC0]===!0?{isReplace:!0,value:$.value}:{isReplace:!1,value:$};var G2=(...$)=>{for(let I of $)if(
Line truncated
`,{mode:384}),I}function r21($){let I=lw0();for(let U of I){if(!Z$(U))continue;for(let Y of pL(U).filter((J)=>J.endsWith(".json")).filter((J)=>!J.startsWith("example."))){let J=n8(U,Y);try{let Q=dL(J,"utf-8"),K=JSON.parse(Q);if(K&&typeof K==="object"&&K.id===$)return J}catch{}}}return}function O7($,I){let U=r21($);if(!U)throw Error(`Enterpriseconfignotfound:${$}`);let J={...JSON.parse(dL(U,"utf-8")),...I};for(let K of Object.keys(I))if(I[K]===void 0)delete J[K];let Q=Gh.parse(J);return bw0(U,`${JSON.stringify(Q,null,2)}
`,"utf-8"),Q}function FJ($,I,U=[]){let Y=I.corpId?.trim()||void 0,J=I.stateful?I.defaultCorpId?.trim()||void 0:void 0,Q=Y??J;if(Q){let q=$.find((H)=>H.id===Q);if(q)return q;throw Error(`Noenterpriseconfigfoundfor${Q}`)}if(!I.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-homeconfigmodestateful` to enable a default enterprise.");let K=$[0];if(K)return K;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{readFileSync as zH1}from"node:fs";import{randomBytes as XH1}from"node:crypto";var tw0=300000,ow0=new Map;function t21($,I){return $.map((U)=>U.trim()).filter(Boolean).map((U)=>I?U:U.toLowerCase())}function a21($,I){return I?$:$.toLowerCase()}function s21($,I,U,Y){let J=a21($,Y),Q=I.filter((K)=>J.includes(K));if(U==="all"&&Q.length!==I.length)return[];return Q}function e21($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function $K1($,I){if(I.fields&&!I.fields.has($.field))return[];let U=e21($.value),Y=[];return U.forEach((J,Q)=>{let K=s21(J,I.keywords,I.matchMode,I.caseSensitive);if(K.length===0)return;let q=Math.max(0,Q-I.contextLines),H=Math.min(U.length,Q+I.contextLines+1),G={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Q+1,matchedKeywords:K,matchedText:lL(J,I.maxChars),context:{before:I.snippetOnly?[]:U.slice(q,Q).map((W)=>lL(W,I.maxChars)),line:lL(J,I.maxChars),after:I.snippetOnly?[]:U.slice(Q+1,H).map((W)=>lL(W,I.maxChars))},metadata:$.metadata};if(I.snippetOnly)G.context={before:[],line:G.context.line,after:[]};Y.push(G)}),Y}function lL($,I){if(!I||$.length<=I)return $;return`${$.slice(0,Math.max(0,I))}...`}function IK1($){return[{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"description",value:$.description,metadata:{scope:$.scope,strictness:$.strictness,status:$.status}},{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"scope",value:$.scope,metadata:{strictness:$.strictness,status:$.status}}]}function rw0($){return $.rules.flatMap((I,U)=>{let Y=`${$.id}:${I.description.slice(0,32)}`,J={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:I.scope,strictness:I.strictness,code:"code"in I?I.code:void 0,index:U};return[{area:"rules",entityType:"rule",entityId:Y,title:`${$.versionName}/${I.scope}`,field:"history.description",value:I.description,metadata:J},{area:"rules",entityType:"rule",entityId:Y,title:`${$.versionName}/${I.scope}`,field:"history.scope",value:I.scope,metadata:J}]})}function UK1($){return[{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"title",value:$.title,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}},{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"purpose",value:$.purpose,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}},{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"content",value:$.content,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}}]}function YK1($){let I=[];if($.decisionPreferences)for(let[U,Y]of Object.entries($.decisionPreferences))I.push({area:"preferences",entityType:"preference",field:`decisionPreferences.${U}`,value:Y,metadata:{integrationSystem:$.integrationSystem}});return $.integrations.forEach((U,Y)=>{I.push({area:"preferences",entityType:"integration",title:U.outboundName,field:`integrations[${Y}]`,value:U,metadata:{type:U.type,outboundName:U.outboundName,mode:U.mode,corporationId:U.corporationId}})}),I}async function JK1($,I,U){let Y=U.ruleVersionScope??"current",J=[I.id,`ruleVersionScope=${Y}`,`ruleVersionId=${U.ruleVersionId??""}`,`ruleVersionNumber=${U.ruleVersionNumber??""}`,`latestRuleVersion=${U.latestRuleVersion??!1}`,`documentLimit=${U.documentLimit??100}`].join("|"),Q=ow0.get(J);if(!U.refresh&&Q&&Date.now()<Q.expiresAt)return Q;let[K,q,H]=await Promise.all([QK1($,{scope:Y,versionId:U.ruleVersionId,versionNumber:U.ruleVersionNumber,latest:U.latestRuleVersion}),A2($,{limit:U.documentLimit??100}),g1($,I.seal.endpoints.approvalStylePreferences)]),G=Date.now(),W={entries:[...K,...q.articles.flatMap(UK1),...YK1(H)],fetchedAt:G,expiresAt:G+tw0};return ow0.set(J,W),W}async function QK1($,I){if(I.scope==="current")return(await C6($)).rules.flatMap(IK1);if(I.scope==="version"){let Y=await KK1($,I);return rw0(Y)}return(await G5($)).flatMap(rw0)}async function KK1($,I){if(I.versionId)return N2($,I.versionId);let U=await G5($),Y=I.versionNumber?U.find((J)=>J.versionNumber===I.versionNumber):U[0];if(!Y)throw Error(I.versionNumber?`Ruleversionnotfound:${I.versionNumber}`:"No rule versions found");return Y}async function aw0($,I,U){let Y=U.matchMode??"any",J=U.caseSensitive??!1,Q=U.contextLines??3,K=new Set(U.areas??["rules","documents","preferences"]),q=U
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letKof$.seen.entries()){letq=K[1];if(I===K[0]){Q(K);continue}if($.external){letG=$.external.registry.get(K[0])?.id;if(I!==K[0]&&G){Q(K);continue}}if($.metadataRegistry.get(K[0])?.id){Q(K);continue}if(q.cycle){Q(K);continue}if(q.count>1){if($.reused==="ref"){Q(K);continue}}}}functionK9($,I){letU=$.seen.get(I);if(!U)throwError("Unprocessed schema. This is a bug in Zod.");letY=(q)=>{letH=$.seen.get(q);if(H.ref===null)return;letG=H.def??H.schema,W={...G},w=H.ref;if(H.ref=null,w){Y(w);letZ=$.seen.get(w),X=Z.schema;if(X.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))G.allOf=G.allOf??[],G.allOf.push(X);elseObject.assign(G,X);if(Object.assign(G,W),q._zod.parent===w)for(letDinG){if(D==="$ref"||D==="allOf")continue;if(!(DinW))deleteG[D]}if(X.$ref&&Z.def)for(letDinG){if(D==="$ref"||D==="allOf")continue;if(DinZ.def&&JSON.stringify(G[D])===JSON.stringify(Z.def[D]))deleteG[D]}}letV=q._zod.parent;if(V&&V!==w){Y(V);letZ=$.seen.get(V);if(Z?.schema.$ref){if(G.$ref=Z.schema.$ref,Z.def)for(letXinG){if(X==="$ref"||X==="allOf")continue;if(XinZ.def&&JSON.stringify(G[X])===JSON.stringify(Z.def[X]))deleteG[X]}}}$.override({zodSchema:q,jsonSchema:G,path:H.path??[]})};for(letqof[...$.seen.entries()].reverse())Y(q[0]);letJ={};if($.target==="draft-2020-12")J.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")J.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")J.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letq=$.external.registry.get(I)?.id;if(!q)throwError("Schema is missing an `id` property");J.$id=$.external.uri(q)}Object.assign(J,U.def??U.schema);letQ=$.metadataRegistry.get(I)?.id;if(Q!==void0&&J.id===Q)deleteJ.id;letK=$.external?.defs??{};for(letqof$.seen.entries()){letH=q[1];if(H.def&&H.defId){if(H.def.id===H.defId)deleteH.def.id;K[H.defId]=H.def}}if($.external);elseif(Object.keys(K).length>0)if($.target==="draft-2020-12")J.$defs=K;elseJ.definitions=K;try{letq=JSON.parse(JSON.stringify(J));returnObject.defineProperty(q,"~standard",{value:{...I["~standard"],jsonSchema:{input:pI(I,"input",$.processors),output:pI(I,"output",$.processors)}},enumerable:!1,writable:!1}),q}catch(q){throwError("Error converting schema to JSON.")}}functionv6($,I){letU=I??{seen:newSet};if(U.seen.has($))return!1;U.seen.add($);letY=$._zod.def;if(Y.type==="transform")return!0;if(Y.type==="array")returnv6(Y.element,U);if(Y.type==="set")returnv6(Y.valueType,U);if(Y.type==="lazy")returnv6(Y.getter(),U);if(Y.type==="promise"||Y.type==="optional"||Y.type==="nonoptional"||Y.type==="nullable"||Y.type==="readonly"||Y.type==="default"||Y.type==="prefault")returnv6(Y.innerType,U);if(Y.type==="intersection")returnv6(Y.left,U)||v6(Y.right,U);if(Y.type==="record"||Y.type==="map")returnv6(Y.keyType,U)||v6(Y.valueType,U);if(Y.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnv6(Y.in,U)||v6(Y.out,U)}if(Y.type==="object"){for(letJinY.shape)if(v6(Y.shape[J],U))return!0;return!1}if(Y.type==="union"){for(letJofY.options)if(v6(J,U))return!0;return!1}if(Y.type==="tuple"){for(letJofY.items)if(v6(J,U))return!0;if(Y.rest&&v6(Y.rest,U))return!0;return!1}return!1}varIA=($,I={})=>(U)=>{letY=J9({...U,processors:I});returnC1($,Y),Q9(Y,$),K9(Y,$)},pI=($,I,U={})=>(Y)=>{let{libraryOptions:J,target:Q}=Y??{},K=J9({...J??{},target:Q,io:I,processors:U});returnC1($,K),Q9(K,$),K9(K,$)};varmF0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},UA=($,I,U,Y)=>{letJ=U;J.type="string";let{minimum:Q,maximum:K,format:q,patterns:H,contentEncoding:G}=$._zod.bag;if(typeofQ==="number")J.minLength=Q;if(typeofK==="number")J.maxLength=K;if(q){if(J.format=mF0[q]??q,J.format==="")deleteJ.format;if(q==="time")deleteJ.format}if(G)J.contentEncoding=G;if(H&&H.size>0){letW=[...H];if(W.length===1)J.pattern=W[0].source;elseif(W.length>1)J.allOf=[...W.map((w)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:w.source}))]}},YA=($,I,U,Y)=>{letJ=U,{minimum:Q,maximum:K,format:q,multipleOf:H,exclusiveMaximum:G,exclusiveMinimum:W}=$._zod.bag;if(typeofq==="string"&&q.includes("int"))J.type="integer";elseJ.type="number";letw=typeofW==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),V=typeofG==="number"&&G<=(K??Number.POSITIVE_INFINITY),Z=I.target==="draft-04"||I.target==="openapi-3.0";if(w)if(Z)J.minimum=W,J.exclusiveMinimum=!0;elseJ.exclusiveMinimum=W;elseif(typeofQ==="number")J.minimum=Q;if(V)if(Z)J.maximum=G,J.exclusiveMaximum=!0;elseJ.exclusiveMaximum=G;elseif(typeofK==="number")J.maximum=K;if(typeofH==="number")J.multipleOf=H},JA=($,I,U,Y)=>{U.type="boolean"},QA=($,I,U,Y)=>{if(I.unrepresentable==="throw")throwError("BigInt cannot be represented in JSON Schema")},KA=($,I,U,Y)=>{if(I.unrepresentable==Line truncated
`}class OE{constructor($=lc.stdin,I=lc.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new FE,this._started=!1,this._ondata=(U)=>{this._readBuffer.append(U),this.processReadBuffer()},this._onerror=(U)=>{this.onerror?.(U)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((I)=>{let U=mc($);if(this._stdout.write(U))I();else this._stdout.once("drain",I)})}}import{dirname as tu,join as XW1}from"node:path";import{fileURLToPath as LW1}from"node:url";class H5 extends Error{name="KyError";get isKyError(){return!0}}class H$ extends H5{name="HTTPError";response;request;options;data;constructor($,I,U){let Y=$.status||$.status===0?$.status:"",J=$.statusText??"",Q=`${Y}${J}`.trim(),K=Q?`statuscode${Q}`:"an unknown error";super(`Requestfailedwith${K}:${I.method}${I.url}`);this.response=$,this.request=I,this.options=U}}class q2 extends H5{name="NetworkError";request;constructor($,I){super(`Requestfailedduetoanetworkerror:${$.method}${$.url}`,I);this.request=$}}class H2 extends Error{name="NonError";value;constructor($){let I="Non-error value was thrown";try{if(typeof $==="string")I=$;else if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string")I=$.message}catch{}super(I);this.value=$}}class LU extends H5{name="ForceRetryError";customDelay;code;customRequest;constructor($){let I=$?.cause?$.cause instanceof Error?$.cause:new H2($.cause):void 0;super($?.code?`Forcedretry:${$.code}`:"Forced retry",I?{cause:I}:void 0);this.customDelay=$?.delay,this.code=$?.code,this.customRequest=$?.request}}class NE extends Error{name="SchemaValidationError";issues;constructor($){super("Response schema validation failed");this.issues=$}}class t$ extends H5{name="TimeoutError";request;constructor($){super(`Requesttimedout:${$.method}${$.url}`);this.request=$}}var ME=(()=>{let $=!1,I=!1,U=typeof globalThis.ReadableStream==="function",Y=typeof globalThis.Request==="function";if(U&&Y)try{I=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return $=!0,"half"}}).headers.has("Content-Type")}catch(J){if(J instanceof Error&&J.message==="unsupported BodyInit type")return!1;throw J}return $&&!I})(),oc=typeof globalThis.AbortController==="function",Aw=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",rc=typeof globalThis.ReadableStream==="function",tc=typeof globalThis.FormData==="function",Pw=["get","post","put","patch","head","delete"],XC0=()=>{return};XC0();var ac={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},DU=2147483647,sc=40,Tw=Symbol("stop");class Ew{options;constructor($){this.options=$}}var ec=($)=>new Ew($),$d={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},Id={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var Bw=new TextEncoder,LC0=($)=>{if(!$)return 0;if($ instanceof FormData){let I=0;for(let[U,Y]of $)I+=sc,I+=Bw.encode(`Content-Disposition:form-data;name="${U}"`).byteLength,I+=typeof Y==="string"?Bw.encode(Y).byteLength:Y.size;return I}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return Bw.encode($).byteLength;if($ instanceof URLSearchParams)return Bw.encode($.toString()).byteLength;return 0},Ud=($,I,U)=>{let Y,J=0;return $.pipeThrough(new TransformStream({transform(Q,K){if(K.enqueue(Q),Y){J+=Y.byteLength;let q=I===0?0:J/I;if(q>=1)q=1-Number.EPSILON;U?.({percent:q,totalBytes:Math.max(I,J),transferredBytes:J},Y)}Y=Q},flush(){if(Y)J+=Y.byteLength,U?.({percent:1,totalBytes:Math.max(I,J),transferredBytes:J},Y)}}))},Yd=($,I)=>{if(!$.body)return $;let U={status:$.status,statusText:$.statusText,headers:$.headers};if($.status===204)return new Response(null,U);let Y=Math.max(0,Number($.headers.get("content-length"))||0);return new Response(Ud($.body,Y,I),U)},Jd=($,I,U)=>{if(!$.body)return $;let Y=LC0(U??$.body);return new Request($,{duplex:"half",body:Ud($.body,Y,I)})};var D8=($)=>$!==null&&typeof $==="object";var DC0=Symbol("replaceOption"),AE=($)=>D8($)&&$[DC0]===!0?{isReplace:!0,value:$.value}:{isReplace:!1,value:$};var W2=(...$)=>{for(let I of $)if(
Line truncated
`,{mode:384}),I}function WK1($){let I=sw0();for(let U of I){if(!D$(U))continue;for(let Y of oL(U).filter((J)=>J.endsWith(".json")).filter((J)=>!J.startsWith("example."))){let J=c8(U,Y);try{let Q=tL(J,"utf-8"),K=JSON.parse(Q);if(K&&typeof K==="object"&&K.id===$)return J}catch{}}}return}function O7($,I){let U=WK1($);if(!U)throw Error(`Enterpriseconfignotfound:${$}`);let J={...JSON.parse(tL(U,"utf-8")),...I};for(let K of Object.keys(I))if(I[K]===void 0)delete J[K];let Q=Xh.parse(J);return mw0(U,`${JSON.stringify(Q,null,2)}
`,"utf-8"),Q}function NJ($,I,U=[]){let Y=I.corpId?.trim()||void 0,J=I.stateful?I.defaultCorpId?.trim()||void 0:void 0,Q=Y??J;if(Q){let q=$.find((H)=>H.id===Q);if(q)return q;throw Error(`Noenterpriseconfigfoundfor${Q}`)}if(!I.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-homeconfigmodestateful` to enable a default enterprise.");let K=$[0];if(K)return K;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{readFileSync as CH1}from"node:fs";import{randomBytes as jH1}from"node:crypto";var IV0=300000,ew0=new Map;function wK1($,I){return $.map((U)=>U.trim()).filter(Boolean).map((U)=>I?U:U.toLowerCase())}function VK1($,I){return I?$:$.toLowerCase()}function ZK1($,I,U,Y){let J=VK1($,Y),Q=I.filter((K)=>J.includes(K));if(U==="all"&&Q.length!==I.length)return[];return Q}function zK1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function XK1($,I){if(I.fields&&!I.fields.has($.field))return[];let U=zK1($.value),Y=[];return U.forEach((J,Q)=>{let K=ZK1(J,I.keywords,I.matchMode,I.caseSensitive);if(K.length===0)return;let q=Math.max(0,Q-I.contextLines),H=Math.min(U.length,Q+I.contextLines+1),G={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Q+1,matchedKeywords:K,matchedText:sL(J,I.maxChars),context:{before:I.snippetOnly?[]:U.slice(q,Q).map((W)=>sL(W,I.maxChars)),line:sL(J,I.maxChars),after:I.snippetOnly?[]:U.slice(Q+1,H).map((W)=>sL(W,I.maxChars))},metadata:$.metadata};if(I.snippetOnly)G.context={before:[],line:G.context.line,after:[]};Y.push(G)}),Y}function sL($,I){if(!I||$.length<=I)return $;return`${$.slice(0,Math.max(0,I))}...`}function LK1($){return[{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"description",value:$.description,metadata:{scope:$.scope,strictness:$.strictness,status:$.status}},{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"scope",value:$.scope,metadata:{strictness:$.strictness,status:$.status}}]}function $V0($){return $.rules.flatMap((I,U)=>{let Y=`${$.id}:${I.description.slice(0,32)}`,J={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:I.scope,strictness:I.strictness,code:"code"in I?I.code:void 0,index:U};return[{area:"rules",entityType:"rule",entityId:Y,title:`${$.versionName}/${I.scope}`,field:"history.description",value:I.description,metadata:J},{area:"rules",entityType:"rule",entityId:Y,title:`${$.versionName}/${I.scope}`,field:"history.scope",value:I.scope,metadata:J}]})}function DK1($){return[{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"title",value:$.title,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}},{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"purpose",value:$.purpose,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}},{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"content",value:$.content,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}}]}function FK1($){let I=[];if($.decisionPreferences)for(let[U,Y]of Object.entries($.decisionPreferences))I.push({area:"preferences",entityType:"preference",field:`decisionPreferences.${U}`,value:Y,metadata:{integrationSystem:$.integrationSystem}});return $.integrations.forEach((U,Y)=>{I.push({area:"preferences",entityType:"integration",title:U.outboundName,field:`integrations[${Y}]`,value:U,metadata:{type:U.type,outboundName:U.outboundName,mode:U.mode,corporationId:U.corporationId}})}),I}async function OK1($,I,U){let Y=U.ruleVersionScope??"current",J=[I.id,`ruleVersionScope=${Y}`,`ruleVersionId=${U.ruleVersionId??""}`,`ruleVersionNumber=${U.ruleVersionNumber??""}`,`latestRuleVersion=${U.latestRuleVersion??!1}`,`documentLimit=${U.documentLimit??100}`].join("|"),Q=ew0.get(J);if(!U.refresh&&Q&&Date.now()<Q.expiresAt)return Q;let[K,q,H]=await Promise.all([NK1($,{scope:Y,versionId:U.ruleVersionId,versionNumber:U.ruleVersionNumber,latest:U.latestRuleVersion}),O9($,{limit:U.documentLimit??100}),j1($,I.seal.endpoints.approvalStylePreferences)]),G=Date.now(),W={entries:[...K,...q.articles.flatMap(DK1),...FK1(H)],fetchedAt:G,expiresAt:G+IV0};return ew0.set(J,W),W}async function NK1($,I){if(I.scope==="current")return(await _6($)).rules.flatMap(LK1);if(I.scope==="version"){let Y=await MK1($,I);return $V0(Y)}return(await v$($)).flatMap($V0)}async function MK1($,I){if(I.versionId)return P2($,I.versionId);let U=await v$($),Y=I.versionNumber?U.find((J)=>J.versionNumber===I.versionNumber):U[0];if(!Y)throw Error(I.versionNumber?`Ruleversionnotfound:${I.versionNumber}`:"No rule versions found");return Y}async function UV0($,I,U){let Y=U.matchMode??"any",J=U.caseSensitive??!1,Q=U.contextLines??3,K=new Set(U.areas??["rules","documents","preferences"]),q=U
Line truncated
`)}return{warnings:[],results:K}}function GI($){return{fileBuffer:GH1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}import{existsSync as ZH1}from"node:fs";async function XD($,I,U={}){let J=D4().stateful?"stateful":"stateless",Q="ok",K,q,H;try{let A=await P$($);H={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){Q="error",K=A instanceof Error?A.message:String(A)}let G=[];if(Q==="ok")try{G=await F9($,I.seal.endpoints.approvalStylePreferences)}catch(A){Q="error",K=`读取Webhook配置失败:${AinstanceofError?A.message:String(A)}`}let W=G.length===1,w=G.map((A)=>({id:A.id,name:A.name,mode:A.mode,incomingDocumentWebhookUrl:A.incomingDocumentWebhook.url,outgoingResultWebhookUrl:A.outgoingResultWebhook,autoApprovalRate:A.autoApprovalRate,...W?{isDefault:!0}:{}})),V=W?{id:G[0].id,name:G[0].name,mode:G[0].mode}:null,Z=U.webhook?N9(G,U.webhook):W?G[0]:void 0,X;if(U.filePath)if(!ZH1(U.filePath))X={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[`文件不存在:${U.filePath}`]};else try{let A=GI(U.filePath),R=await HI(A.fileBuffer,A.fileName,Z?.materialPackFilePolicy);X={valid:!0,filePath:U.filePath,fileName:A.fileName,documentCount:R.documents.length,warnings:R.warnings}}catch(A){X={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[A instanceof Error?A.message:String(A)]}}let L=X?X.valid:!0,D=Q==="ok"&&w.length>0&&L,F=J==="stateful"?"":`--corp${I.id}`,E="",T="";if(Q!=="ok")T=`凭证鉴权异常:${K}`,E=`seal-useauthdiagnose${F}`;else if(w.length===0)T="当前企业尚未配置任何 Webhook 集成通道",E=`seal-usewebhookadd--name"默认入站通道"--result-url"https://your-domain.com/callback"${F}`;else if(X&&!X.valid)T=`材料包预检失败:${X.errors?.join("; ")}`,E=`seal-usewebhookmaterial-packpreview${X.filePath}${F}`;else{T=W?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到${w.length}个Webhook通道,等待载入`;let A=X?.filePath??"<材料包.zip>",R=W?"":`--webhook${V?V.id:"<webhookIdOrName>"}`;E=`seal-usewebhookmaterial-packpush${A}${R}${F}`}return{ready:D,corp:{id:I.id,name:I.name,sourceType:I.source.type,tenant:q,user:H},stateMode:J,authStatus:Q,authError:K,activeWebhooks:w,defaultWebhook:V,materialPack:X,statusMessage:T,nextAction:E}}var XH=[{name:"seal_whoami",description:"查询当前 Seal 用户身份及租户信息",parameters:z.object({}),handler:async($)=>P$($)},{name:"seal_session_get",description:"查询当前 Seal Bearer session、用户和过期时间",parameters:z.object({}),handler:async($)=>Xm($)},{name:"seal_delegation_list",description:"查询当前 Seal 租户下的授权链接 (Delegation) 列表",parameters:z.object({}),handler:async($)=>im($)},{name:"seal_delegation_create",description:"创建新的 Seal 授权链接 (Delegation)",parameters:z.object({note:z.string().optional().describe("授权链接的备注或说明信息")}),handler:async($,I)=>AU($,I)},{name:"seal_delegation_revoke",description:"撤销/废除指定的 Seal 授权链接 (Delegation)",parameters:z.object({tokenId:z.string().describe("授权链接 ID (delegation record ID)")}),handler:async($,I)=>bm($,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)=>nm($,I)},{name:"seal_user_reset_password",description:"重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>mE($,I.userId)},{name:"seal_user_get",description:"获取指定 Seal 用户的详细信息",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>bw($,I.userId)},{name:"seal_user_search",description:"按姓名、手机号或邮箱搜索 Seal 成员用户列表",parameters:z.object({keyword:z.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")}),handler:async($,I)=>nw($,I.keyword??"")},{name:"seal_user_delete",description:"删除指定 Seal 本地用户",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>em($,I.userId)},{name:"seal_user_activate",description:"启用/激活已离职的 Seal 用户账号",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>lE($,I.userId)},{name:"seal_user_delegation_create",description:"为指定 S
Line truncated
`)}function lH1($){let I=[];if(I.push(`seal-use${$.area}-${$.title}`),$.description)I.push($.description);I.push(""),I.push("Usage:");for(let U of $.commands)for(let Y of U.usage)I.push(`${Y}`);return I.push(""),I.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`),I.join(`
`)}return{warnings:[],results:K}}function WI($){return{fileBuffer:TH1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}import{existsSync as RH1}from"node:fs";async function ND($,I,U={}){let J=F4().stateful?"stateful":"stateless",Q="ok",K,q,H;try{let A=await B$($);H={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){Q="error",K=A instanceof Error?A.message:String(A)}let G=[];if(Q==="ok")try{G=await N9($,I.seal.endpoints.approvalStylePreferences)}catch(A){Q="error",K=`读取Webhook配置失败:${AinstanceofError?A.message:String(A)}`}let W=G.length===1,w=G.map((A)=>({id:A.id,name:A.name,mode:A.mode,incomingDocumentWebhookUrl:A.incomingDocumentWebhook.url,outgoingResultWebhookUrl:A.outgoingResultWebhook,autoApprovalRate:A.autoApprovalRate,...W?{isDefault:!0}:{}})),V=W?{id:G[0].id,name:G[0].name,mode:G[0].mode}:null,Z=U.webhook?M9(G,U.webhook):W?G[0]:void 0,X;if(U.filePath)if(!RH1(U.filePath))X={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[`文件不存在:${U.filePath}`]};else try{let A=WI(U.filePath),R=await GI(A.fileBuffer,A.fileName,Z?.materialPackFilePolicy);X={valid:!0,filePath:U.filePath,fileName:A.fileName,documentCount:R.documents.length,warnings:R.warnings}}catch(A){X={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[A instanceof Error?A.message:String(A)]}}let L=X?X.valid:!0,D=Q==="ok"&&w.length>0&&L,O=J==="stateful"?"":`--corp${I.id}`,E="",T="";if(Q!=="ok")T=`凭证鉴权异常:${K}`,E=`seal-useauthdiagnose${O}`;else if(w.length===0)T="当前企业尚未配置任何 Webhook 集成通道",E=`seal-usewebhookadd--name"默认入站通道"--result-url"https://your-domain.com/callback"${O}`;else if(X&&!X.valid)T=`材料包预检失败:${X.errors?.join("; ")}`,E=`seal-usewebhookmaterial-packpreview${X.filePath}${O}`;else{T=W?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到${w.length}个Webhook通道,等待载入`;let A=X?.filePath??"<材料包.zip>",R=W?"":`--webhook${V?V.id:"<webhookIdOrName>"}`;E=`seal-usewebhookmaterial-packpush${A}${R}${O}`}return{ready:D,corp:{id:I.id,name:I.name,sourceType:I.source.type,tenant:q,user:H},stateMode:J,authStatus:Q,authError:K,activeWebhooks:w,defaultWebhook:V,materialPack:X,statusMessage:T,nextAction:E}}var DH=[{name:"seal_whoami",description:"查询当前 Seal 用户身份及租户信息",parameters:z.object({}),handler:async($)=>B$($)},{name:"seal_session_get",description:"查询当前 Seal Bearer session、用户和过期时间",parameters:z.object({}),handler:async($)=>Am($)},{name:"seal_delegation_list",description:"查询当前 Seal 租户下的授权链接 (Delegation) 列表",parameters:z.object({}),handler:async($)=>dm($)},{name:"seal_delegation_create",description:"创建新的 Seal 授权链接 (Delegation)",parameters:z.object({note:z.string().optional().describe("授权链接的备注或说明信息")}),handler:async($,I)=>PU($,I)},{name:"seal_delegation_revoke",description:"撤销/废除指定的 Seal 授权链接 (Delegation)",parameters:z.object({tokenId:z.string().describe("授权链接 ID (delegation record ID)")}),handler:async($,I)=>mm($,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)=>lm($,I)},{name:"seal_user_reset_password",description:"重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>sE($,I.userId)},{name:"seal_user_get",description:"获取指定 Seal 用户的详细信息",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>pw($,I.userId)},{name:"seal_user_search",description:"按姓名、手机号或邮箱搜索 Seal 成员用户列表",parameters:z.object({keyword:z.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")}),handler:async($,I)=>cw($,I.keyword??"")},{name:"seal_user_delete",description:"删除指定 Seal 本地用户",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>Jl($,I.userId)},{name:"seal_user_activate",description:"启用/激活已离职的 Seal 用户账号",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>eE($,I.userId)},{name:"seal_user_delegation_create",description:"为指定 S
Line truncated
`)}function HG1($){let I=[];if(I.push(`seal-use${$.area}-${$.title}`),$.description)I.push($.description);I.push(""),I.push("Usage:");for(let U of $.commands)for(let Y of U.usage)I.push(`${Y}`);return I.push(""),I.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`),I.join(`
Run'seal-use corps bind-test ${J.id} <testCorpId> --confirm'firsttoestablishaverified1-to-1association.`);let Q=k1(J.testCorpId);if(Q.environment!=="test")throw Error(`Targetenterprise'${Q.name}'(${Q.id})ismarkedas'${Q.environment}',NOT'test'.Abortingsynctoprotectnon-testenvironments.`);let K=await n1(J),q=await n1(Q),H=await g1(K,J.seal.endpoints.approvalStylePreferences),G=await g1(q,Q.seal.endpoints.approvalStylePreferences),W=await C6(K),w=await C6(q),V={...G,tone:H.tone,language:H.language,detailLevel:H.detailLevel,outputFormat:H.outputFormat,examples:H.examples??[],prohibitedPhrases:H.prohibitedPhrases??[],customInstructions:H.customInstructions,decisionPreferences:H.decisionPreferences,thinkingDepthPreference:H.thinkingDepthPreference},Z=h(U.options["version-name"])??h(U.options.versionName),X=new Date().toISOString().slice(0,10),L=Z??`Syncfrom${J.name}(${X})`;if(F0(U.options["dry-run"])===!0||F0(U.options.dryRun)===!0){B0({dryRun:!0,source:{id:J.id,name:J.name,environment:J.environment},target:{id:Q.id,name:Q.name,environment:Q.environment},preferencesDiff:{decisionPreferences:{before:G.decisionPreferences,after:H.decisionPreferences},thinkingDepthPreference:{before:G.thinkingDepthPreference,after:H.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:W.rules.length,targetExistingDraftRuleCount:w.rules.length,toDeleteCount:w.rules.length,toCreateCount:W.rules.length,rulesToSync:W.rules.map((A,R)=>({index:R+1,description:A.description,scope:A.scope,strictness:A.strictness}))},publishingPlan:{targetCorpId:Q.id,publishVersionName:L,publishTarget:"test"},productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(F0(U.options.yes)===!0||F0(U.options.confirm)===!0))throw o8(`Refusingtooverwritetestenterprise'${Q.name}'(${Q.id})withpreferencesand${W.rules.length}draftrulesfromproductionenterprise'${J.name}'(${J.id})without--yes.Thiswillreplacetestdraftrulesandpublishanewversiononthetestenterprise.`,`seal-usecorpssync-test${J.id}--yes`);await W5(q,V,Q.seal.endpoints.approvalStylePreferences);for(let A of w.rules)await PU(q,A.id);let E=[];for(let A of W.rules){let R=await F2(q,{description:A.description,scope:A.scope,strictness:A.strictness});E.push(R)}await cw(q).catch(()=>{return});let T=await M2(q,L);B0({success:!0,syncedAt:new Date().toISOString(),source:{id:J.id,name:J.name,environment:J.environment,draftRulesCount:W.rules.length},target:{id:Q.id,name:Q.name,environment:Q.environment,deletedDraftRulesCount:w.rules.length,createdDraftRulesCount:E.length,publishedVersion:{id:T.version.id,versionNumber:T.version.versionNumber,versionName:T.version.versionName,rulesCount:T.rulesCount}},productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if($==="switch"){let Y=I;if(!Y)throw Error("Usage: seal-use corps switch <corpId>");let J=D4();if(!J.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-useconfigmodestateful` first.");let Q=k1(Y);JI({...J,stateful:!0,defaultCorpId:Q.id}),B0({current:!0,id:Q.id,name:Q.name});return}if($==="probe-hose"){await UG1(s6(U.json));return}if($==="hose-staffs"){await YG1(s6(U.json));return}if($==="add-hose"){await JG1(s6(U.json));return}if($==="add-seal"){await QG1(s6(U.json));return}if($==="add-link"){let Y=I??h(U.options.link)??h(U.options.url);if(!Y)throw Error("Usage: seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]");await KG1(Y,h(U.options.name),F0(U.options.overwrite)===!0);return}throw Error(`Unknowncorpscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function UG1($){let I=M7($,"appKey"),U=M7($,"appSecurity"),Y=c1($,"domain"),J=await NU(I,U,Y),Q=await yw(J.domain,J.openapiToken).catch(()=>[]),K=Q.reduce((q,H)=>q+H.roleDefs.length,0);B0({domain:J.domain,corpId:J.corpId,name:J.corpName??J.corpId,roleCount:K,roleGroups:Q.map((q)=>({id:q.id,name:q.name,roleDefs:q.roleDefs.map((H)=>({id:H.id,name:H.name,sourceType:H.sourceType}))}))})}async function YG1($){let I=M7($,"appKey"),U=M7($,"appSecurity"),Y=c1($,"domain"),J=c1($,"role")??c1($,"roleDefId")??"admin",Q=await NU(I,U,Y),K=await yw(Q.domain,Q.openapiToken),q,H;for(let w of K){for(let V of w.roleDefs)if(V.id===J||V.id===`${Q.corpId}:${J}`){q=V.id,H=V.name;break}if(q)break}if(!q&&(J==="admin"||J==="主管理员"))for(let w of K){for(let V of w.roleDefs)if(V.id.endsWith(":admin")||V.name==="主管理员"){q=V.id,H=V.name;break}if(q)break}if(!q)for(let w of K){for(let V of w.roleDefs)if(V.name.toLowerCase().includes(J.toLowerCase())){q=V.id,H=V.name;break}if(q)break}if(!q)throw Error(`Rolenotfoundmatchingquery:'${J}'.Run'seal-use corps probe-hose'toviewallavailableroles.`);let G=await RE(Q.domain,Q.openapiToken,q),W=await CE(Q.domain,Q.openapiToken,G.staffs);B0({domain:Q.domain,corpId:Q.corpId,corpName:Q.corpName??Q.corpId,roleId:q,roleName:H,count:W.length,staffs:W.map((w)=>(
Line truncated
Run'seal-use corps bind-test ${J.id} <testCorpId> --confirm'firsttoestablishaverified1-to-1association.`);let Q=f1(J.testCorpId);if(Q.environment!=="test")throw Error(`Targetenterprise'${Q.name}'(${Q.id})ismarkedas'${Q.environment}',NOT'test'.Abortingsynctoprotectnon-testenvironments.`);let K=await p1(J),q=await p1(Q),[H,G,W,w,V,Z,X,L]=await Promise.all([j1(K,J.seal.endpoints.approvalStylePreferences).catch(()=>({})),j1(q,Q.seal.endpoints.approvalStylePreferences).catch(()=>({})),_6(K),_6(q),v$(K).catch(()=>[]),v$(q).catch(()=>[]),O9(K,{limit:100}).catch(()=>({articles:[]})),O9(q,{limit:100}).catch(()=>({articles:[]}))]),D=(X.articles||[]).filter((t)=>!t.isDeleted),O=(L.articles||[]).filter((t)=>!t.isDeleted),E=new Map(O.map((t)=>[t.title.trim(),t])),T=[],A=[],R=new Set(D.map((t)=>t.title.trim()));for(let t of D){let T0=t.title.trim(),y0=E.get(T0);if(!y0)T.push(t);else{let g1=y0.content!==t.content,Z4=(y0.purpose??"")!==(t.purpose??""),A6=y0.enabled!==t.enabled,f6=y0.contentType!==t.contentType,F$=(y0.status??"")!==(t.status??""),i6=JSON.stringify([...y0.scenarios??[]].sort())!==JSON.stringify([...t.scenarios??[]].sort()),P6=JSON.stringify([...y0.tags??[]].sort())!==JSON.stringify([...t.tags??[]].sort());if(g1||Z4||A6||f6||F$||i6||P6)A.push({testId:y0.id,prodDoc:t,reasons:[...g1?["content"]:[],...Z4?["purpose"]:[],...A6?["enabled"]:[],...f6?["contentType"]:[],...F$?["status"]:[],...i6?["scenarios"]:[],...P6?["tags"]:[]]})}}let k=O.filter((t)=>!R.has(t.title.trim())),f=[...V].sort((t,T0)=>T0.versionNumber-t.versionNumber)[0],C=f?.versionNumber,n=([...Z].sort((t,T0)=>T0.versionNumber-t.versionNumber)[0]?.versionNumber??0)+1,S=Tz0(J.name,C,Z),b=h(U.options["version-name"])??h(U.options.versionName)??Ez0(J.name,C,S,n),Y0={...G,tone:H.tone,language:H.language,detailLevel:H.detailLevel,outputFormat:H.outputFormat,examples:H.examples??[],prohibitedPhrases:H.prohibitedPhrases??[],customInstructions:H.customInstructions,decisionPreferences:H.decisionPreferences,thinkingDepthPreference:H.thinkingDepthPreference};if(N0(U.options["dry-run"])===!0||N0(U.options.dryRun)===!0){B0({dryRun:!0,source:{id:J.id,name:J.name,environment:J.environment,latestPublishedVersion:f?{versionNumber:f.versionNumber,versionName:f.versionName}:null,documentsCount:D.length},target:{id:Q.id,name:Q.name,environment:Q.environment},versionMappingPlan:{sourceProdVersionNumber:C??null,sourceProdVersionName:f?.versionName??null,targetTestExpectedVersionNumber:n,targetTestPublishVersionName:b,iteration:S},preferencesDiff:{decisionPreferences:{before:G.decisionPreferences,after:H.decisionPreferences},thinkingDepthPreference:{before:G.thinkingDepthPreference,after:H.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:W.rules.length,targetExistingDraftRuleCount:w.rules.length,toDeleteCount:w.rules.length,toCreateCount:W.rules.length,rulesToSync:W.rules.map((t,T0)=>({index:T0+1,sourceRuleId:t.id,sourceRuleCode:t.code??T0+1,expectedTargetCode:`rule-${T0+1}`,description:t.description,scope:t.scope,strictness:t.strictness}))},documentsPlan:{sourceDocumentCount:D.length,targetExistingDocumentCount:O.length,toCreateCount:T.length,toCreate:T.map((t)=>({title:t.title,purpose:t.purpose,contentType:t.contentType,scenarios:t.scenarios})),toUpdateCount:A.length,toUpdate:A.map((t)=>({targetDocumentId:t.testId,title:t.prodDoc.title,reasons:t.reasons})),toDeleteCount:k.length,toDelete:k.map((t)=>({targetDocumentId:t.id,title:t.title}))},publishingPlan:{targetCorpId:Q.id,publishVersionName:b,publishTarget:"test"},productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(N0(U.options.yes)===!0||N0(U.options.confirm)===!0))throw t8(`Refusingtooverwritetestenterprise'${Q.name}'(${Q.id})withpreferences,${W.rules.length}draftrules,and${D.length}knowledgedocumentsfromproductionenterprise'${J.name}'(${J.id})without--yes.Thiswillreplacetestdraftrules,synchronizeknowledgedocuments,andpublishanewversiononthetestenterprise.`,`seal-usecorpssync-test${J.id}--yes`);await W5(q,Y0,Q.seal.endpoints.approvalStylePreferences);let c=[];for(let t of k)await rw(q,t.id),c.push({id:t.id,title:t.title});let r=[];for(let t of A)await ow(q,t.testId,{title:t.prodDoc.title,purpose:t.prodDoc.purpose,content:t.prodDoc.content,contentType:t.prodDoc.contentType,status:t.prodDoc.status,enabled:t.prodDoc.enabled,scenarios:t.prodDoc.scenarios&&t.prodDoc.scenarios.length>0?t.prodDoc.scenarios:["audit"],tags:t.prodDoc.tags}),r.push({id:t.testId,title:t.prodDoc.title,reasons:t.reasons});let Q0=[];for(let t of T){let T0=await lw(q,{title:t.title,purpose:t.purpose,content:t.content,contentType:t.contentType,status:t.status,enabled:t.enabled,scenarios:t.scenarios&&t.scenarios.length>0?t.scenarios:["audit"],tags:t.tags});Q0.push({id:T0.id,title:T0.title})}for(let t of w.rules)await TU(q,t.id);let w0=[];for(let t of W.rules){let T0=await A2(q,{description:t.description,scope:t.scope,strictness:t.strictness});w0.pu
Line truncated
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of w){let Z=V.outboundName??"SealAI 审批",X=V.signKey,L=V.apiOrigin??"production";console.error(`•"${Z}"(signKey:${X},环境:${L})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${X}--corp${J.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let X of V){let L=X.outboundName??"SealAI 审批",D=X.signKey,F=X.apiOrigin??"production";console.error(`•"${L}"(signKey:${D},环境:${F})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${D}--corp${J.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let X of V){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${J.id}
`},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
`);J(Y)})})}async function vz0($){let I=d0($.options.port)??d0($.options.p),U=h($.options.host)??h($.options.h),Y=await SD({port:I,host:U}),J=()=>{Y.close(()=>{process.exit(0)})};process.on("SIGINT",J),process.on("SIGTERM",J),await new Promise(()=>{})}async function Rz0($,I,U,Y){if($==="config"||$==="get"){await D0("seal_llm_config_get",I,U,{},w0(Y.options));return}if($==="providers"||$==="list"){await D0("seal_llm_providers_list",I,U,{},w0(Y.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function Cz0($,I){if($==="config"||$==="json"){Cu();return}await ju()}function Cu(){B0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function jz0($){let I=RD();B0(I,{...w0($.options),allowFull:!0})}async function _z0($,I,U,Y){if($==="available"){await D0("seal_permissions_available_list",I,U,{},w0(Y.options));return}if($==="configs"||$==="list"){await D0("seal_permissions_configs_list",I,U,{},w0(Y.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{readFileSync as gz0}from"node:fs";async function Sz0($,I,U,Y,J,Q,K){if(!$||$==="get"){await D0("seal_preference_get",J,Q,{},w0(K.options));return}if($==="decision"){if(I==="update"||!I){let q=h(K.options.input),H=q?JSON.parse(gz0(q,"utf8")):s6(K.json);if(!H||Object.keys(H).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await D0("seal_preference_decision_update",J,Q,{...H,dryRun:F0(K.options.dryRun)??F0(K.options["dry-run"])},w0(K.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let q=h(K.options.default)??h(K.options.level)??Y;if(q!=="medium"&&q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await D0("seal_preference_thinking_depth_set",J,Q,{defaultLevel:q,dryRun:F0(K.options.dryRun)??F0(K.options["dry-run"])},w0(K.options));return}if(I==="policies"){if(U==="list"||!U){await D0("seal_preference_thinking_depth_policies_list",J,Q,{},w0(K.options));return}if(U==="upsert"){let q=h(K.options.input),H=q?JSON.parse(gz0(q,"utf8")):s6(K.json);if(!H||!H.id||!H.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await D0("seal_preference_thinking_depth_policies_upsert",J,Q,{...H,dryRun:F0(K.options.dryRun)??F0(K.options["dry-run"])},w0(K.options));return}if(U==="remove"||U==="delete"){let q=Y??h(K.options.id)??h(K.options.policyId);if(!q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await D0("seal_preference_thinking_depth_policies_remove",J,Q,{policyId:q,dryRun:F0(K.options.dryRun)??F0(K.options["dry-run"])},w0(K.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}async function yz0($={}){let I=p8(),U=D4(),Y=FJ(I,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},UI());console.log(`[probe]corp=${Y.id}source=${Y.source.type}`);let J=await jJ(Y);console.log("[probe] seal enterprise"),console.log(JSON.stringify(J,null,2));let Q=await n1(Y),K=await lw(Q,{documentLimit:20,stylePreferencesEndpoint:Y.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:K.rules.rules.length,hasPendingRuleDeletes:K.rules.hasPendingDeletes,documents:K.documents.articles.length,documentsTotal:K.documents.total,stylePreferences:K.stylePreferences.ok?"ok":`error:${K.stylePreferences.error}`},null,2))}async function hz0($,I,U){let Y=I??h(U.options.corp)??($&&$!=="--corp"?$:void 0);await yz0({corpId:Y})}async function _u($,I,U,Y,J){if($==="count"){await D0("seal_approval_rules_list",U,Y,{countOnly:!0},w0(J.options));return}if($==="list"){if(F0(J.options.count)){await D0("seal_approval_rules_list",U,Y,{countOnly:!0},w0(J.options));return}let Q=d0(J.options.limit),K=d0(J.options.offset);if(F0(J.options.summary)){await D0("seal_approval_rules_list",U,Y,{fields:eZ0,limit:Q,offset:K},w0(J.options));return}let q=await ZI("seal_approval_rules_list",U,Y,{limit:Q,offset:K});$z0(q,F0(J.options.full)===!0),B0(q);return}if($==="clear"){let Q=F0(J.options.yes)===!0,K=F0(J.options.dryRun)??F0(J.options["dry-run"])??!Q;if(!Q&&!K)throw o8("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${Y.id}--dry-run`);let q=await ZI("seal_approval_rules_clear",U,Y,{dryRun:K,recode:F0(J.options.recode)});if(!Q&&K&&q&&typeof q==="object"){B0({...q,nextCommand:`seal-userulesclear--corp${Y.id}--yes`},w0(J.options));return}B0(q,w0(J.options));return}if($==="versions"){await D0("seal_approval_rule_versions_list",U,Y,{},w0(J.options));return}if($==="version"){let Q=I??h(J.options.version);if(!Q)throw Error("Usage: seal-use rules version <versionId|versionNumber|l
Line truncated
`).filter(Boolean),Q=J.slice(-I);return{logFile:U,lines:Q,totalLines:J.length}}async function FG1($){let I=xD($),U=yu($),Y=PH($);fz0($.stateDir);let J=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):_D),Q=$.host??(process.env.HOST?process.env.HOST:gD);hD(I,`${process.pid}
`,{mode:384}),hD(U,JSON.stringify({pid:process.pid,port:J,host:Q,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),_J(Y,`servicestartingonhttp://${Q}:${J} pid=${process.pid}`);let K=null;try{K=await SD({port:J,host:Q,silent:!0}),_J(Y,`service listening pid=${process.pid}`)}catch(H){if(_J(Y,`service failed to bind port ${J}: ${H instanceof Error?H.message:String(H)}`),uD(I)===process.pid)r8(I,{force:!0}),r8(U,{force:!0});throw H}let q=()=>{if(K)K.close(),K=null;if(uD(I)===process.pid)r8(I,{force:!0}),r8(U,{force:!0});_J(Y,`stopped pid=${process.pid}`)};await new Promise((H)=>{let G=!1,W=()=>{if(G)return;G=!0,q(),process.off("SIGTERM",W),process.off("SIGINT",W),H()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function uz0($){fz0($.stateDir);let I=gJ($);if(I.running)return I;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},Y=[...U.args??[],"service","run"];if($.port)Y.push("--port",String($.port));if($.host)Y.push("--host",String($.host));let J=XG1(U.command,Y,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});J.unref();let Q=xD($);return hD(Q,`${J.pid}
`);J(Y)})})}async function fz0($){let I=m0($.options.port)??m0($.options.p),U=h($.options.host)??h($.options.h),Y=await fD({port:I,host:U}),J=()=>{Y.close(()=>{process.exit(0)})};process.on("SIGINT",J),process.on("SIGTERM",J),await new Promise(()=>{})}async function iz0($,I,U,Y){if($==="config"||$==="get"){await F0("seal_llm_config_get",I,U,{},V0(Y.options));return}if($==="providers"||$==="list"){await F0("seal_llm_providers_list",I,U,{},V0(Y.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function bz0($,I){if($==="config"||$==="json"){hu();return}await uu()}function hu(){B0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function nz0($){let I=yD();B0(I,{...V0($.options),allowFull:!0})}async function pz0($,I,U,Y){if($==="available"){await F0("seal_permissions_available_list",I,U,{},V0(Y.options));return}if($==="configs"||$==="list"){await F0("seal_permissions_configs_list",I,U,{},V0(Y.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{readFileSync as cz0}from"node:fs";async function dz0($,I,U,Y,J,Q,K){if(!$||$==="get"){await F0("seal_preference_get",J,Q,{},V0(K.options));return}if($==="decision"){if(I==="update"||!I){let q=h(K.options.input),H=q?JSON.parse(cz0(q,"utf8")):U$(K.json);if(!H||Object.keys(H).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await F0("seal_preference_decision_update",J,Q,{...H,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let q=h(K.options.default)??h(K.options.level)??Y;if(q!=="medium"&&q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await F0("seal_preference_thinking_depth_set",J,Q,{defaultLevel:q,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}if(I==="policies"){if(U==="list"||!U){await F0("seal_preference_thinking_depth_policies_list",J,Q,{},V0(K.options));return}if(U==="upsert"){let q=h(K.options.input),H=q?JSON.parse(cz0(q,"utf8")):U$(K.json);if(!H||!H.id||!H.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await F0("seal_preference_thinking_depth_policies_upsert",J,Q,{...H,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}if(U==="remove"||U==="delete"){let q=Y??h(K.options.id)??h(K.options.policyId);if(!q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await F0("seal_preference_thinking_depth_policies_remove",J,Q,{policyId:q,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}async function mz0($={}){let I=d8(),U=F4(),Y=NJ(I,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},YI());console.log(`[probe]corp=${Y.id}source=${Y.source.type}`);let J=await _J(Y);console.log("[probe] seal enterprise"),console.log(JSON.stringify(J,null,2));let Q=await p1(Y),K=await sw(Q,{documentLimit:20,stylePreferencesEndpoint:Y.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:K.rules.rules.length,hasPendingRuleDeletes:K.rules.hasPendingDeletes,documents:K.documents.articles.length,documentsTotal:K.documents.total,stylePreferences:K.stylePreferences.ok?"ok":`error:${K.stylePreferences.error}`},null,2))}async function lz0($,I,U){let Y=I??h(U.options.corp)??($&&$!=="--corp"?$:void 0);await mz0({corpId:Y})}async function xu($,I,U,Y,J){if($==="count"){await F0("seal_approval_rules_list",U,Y,{countOnly:!0},V0(J.options));return}if($==="list"){if(N0(J.options.count)){await F0("seal_approval_rules_list",U,Y,{countOnly:!0},V0(J.options));return}let Q=m0(J.options.limit),K=m0(J.options.offset);if(N0(J.options.summary)){await F0("seal_approval_rules_list",U,Y,{fields:Jz0,limit:Q,offset:K},V0(J.options));return}let q=await zI("seal_approval_rules_list",U,Y,{limit:Q,offset:K});Qz0(q,N0(J.options.full)===!0),B0(q);return}if($==="clear"){let Q=N0(J.options.yes)===!0,K=N0(J.options.dryRun)??N0(J.options["dry-run"])??!Q;if(!Q&&!K)throw t8("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${Y.id}--dry-run`);let q=await zI("seal_approval_rules_clear",U,Y,{dryRun:K,recode:N0(J.options.recode)});if(!Q&&K&&q&&typeof q==="object"){B0({...q,nextCommand:`seal-userulesclear--corp${Y.id}--yes`},V0(J.options));return}B0(q,V0(J.options));return}if($==="versions"){await F0("seal_approval_rule_versions_list",U,Y,{},V0(J.options));return}if($==="version"){let Q=I??h(J.options.version);if(!Q)throw Error("Usage: seal-use rules version <versionId|versionNumber|l
Line truncated
`).filter(Boolean),Q=J.slice(-I);return{logFile:U,lines:Q,totalLines:J.length}}async function kG1($){let I=pD($),U=iu($),Y=EH($);az0($.stateDir);let J=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):xD),Q=$.host??(process.env.HOST?process.env.HOST:kD);bD(I,`${process.pid}
`,{mode:384}),bD(U,JSON.stringify({pid:process.pid,port:J,host:Q,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),SJ(Y,`servicestartingonhttp://${Q}:${J} pid=${process.pid}`);let K=null;try{K=await fD({port:J,host:Q,silent:!0}),SJ(Y,`service listening pid=${process.pid}`)}catch(H){if(SJ(Y,`service failed to bind port ${J}: ${H instanceof Error?H.message:String(H)}`),nD(I)===process.pid)a8(I,{force:!0}),a8(U,{force:!0});throw H}let q=()=>{if(K)K.close(),K=null;if(nD(I)===process.pid)a8(I,{force:!0}),a8(U,{force:!0});SJ(Y,`stopped pid=${process.pid}`)};await new Promise((H)=>{let G=!1,W=()=>{if(G)return;G=!0,q(),process.off("SIGTERM",W),process.off("SIGINT",W),H()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function oz0($){az0($.stateDir);let I=gJ($);if(I.running)return I;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},Y=[...U.args??[],"service","run"];if($.port)Y.push("--port",String($.port));if($.host)Y.push("--host",String($.host));let J=yG1(U.command,Y,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});J.unref();let Q=pD($);return bD(Q,`${J.pid}
`,{flag:"a",mode:384})}var bu=bG1(iG1(),".config","seal-use");async function nu($,I,U){let Y=U?m0(U.options.port)??m0(U.options.p):void 0,J=U?h(U.options.host)??h(U.options.h):void 0,Q=U?m0(U.options.lines)??m0(U.options.n):void 0,K=await XI($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:bu,version:U1,launcher:I.launcher,port:Y,host:J},{maxLines:Q});if(K!==void 0)B0(K)}import{existsSync as nG1,readFileSync as sz0}from"node:fs";async function ez0($,I,U,Y,J){if($==="batch-records"||$==="records"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation batch-records <batchId>");await F0("seal_simulation_batch_records_get",U,Y,{batchId:Q,query:h(J.options.query)},V0(J.options));return}if($==="create"||$==="run"){let Q=h(J.options.mode)??h(J.options.sourceSystem)??h(J.options["source-system"])??"hosecloud",K=Q==="material-pack"?"material_pack":Q,q=h(J.options.schemaConfig)??h(J.options["schema-config"]),H=q?JSON.parse(sz0(q,"utf8")):void 0,G=h(J.options.input),W=G?JSON.parse(sz0(G,"utf8")):U$(J.json),w=h(J.options.packageId)??h(J.options["package-id"]),V=w6(J.options.packageIds)??w6(J.options["package-ids"])??(w?[w]:void 0),Z=w6(J.options.flowIds)??w6(J.options["flow-ids"])??w6(J.options.documentSn)??w6(J.options["document-sn"]),X=h(J.options.signKey)??h(J.options["sign-key"])??h(J.options.integration),L=N0(J.options.noWait)??N0(J.options["no-wait"]);await F0("seal_simulation_batch_create",U,Y,{mode:K,sourceSystem:K,flowIds:Z,documentSn:Z,rejectNodeName:h(J.options.rejectNode)??h(J.options["reject-node"])??null,thinkingDepthOverride:h(J.options.thinkingDepth)??h(J.options["thinking-depth"]),skipInvoiceGeneration:N0(J.options.skipInvoiceGeneration)??N0(J.options["skip-invoice-generation"]),skipExpenseExtraction:N0(J.options.skipExpenseExtraction)??N0(J.options["skip-expense-extraction"]),disableAttachmentCache:N0(J.options.disableAttachmentCache)??N0(J.options["disable-attachment-cache"]),signKey:X,packageIds:V,packageId:w,templateId:h(J.options.templateId)??h(J.options["template-id"]),schemaConfig:H,requestIds:w6(J.options.requestIds)??w6(J.options["request-ids"]),workflowTypeId:h(J.options.workflowTypeId)??h(J.options["workflow-type-id"]),flowStatusList:w6(J.options.flowStatusList)?.map(Number)??w6(J.options["flow-status-list"])?.map(Number),businessCodes:w6(J.options.businessCodes)??w6(J.options["business-codes"]),documentType:h(J.options.documentType)??h(J.options["document-type"]),startTime:m0(J.options.startTime)??m0(J.options["start-time"]),endTime:m0(J.options.endTime)??m0(J.options["end-time"]),status:w6(J.options.status),limit:m0(J.options.limit),noWait:L,rawParams:W},V0(J.options));return}if($==="wait"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await F0("seal_simulation_batch_wait",U,Y,{batchId:Q,timeout:h(J.options.timeout),pollInterval:h(J.options.pollInterval)??h(J.options["poll-interval"])},V0(J.options));return}if($==="status"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation status <batchId>");await F0("seal_simulation_batch_status",U,Y,{batchId:Q},V0(J.options));return}if($==="clean"||$==="delete"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation clean <batchId>");await F0("seal_simulation_batch_clean",U,Y,{batchId:Q},V0(J.options));return}if($==="specifications"){let Q=I??h(J.options.integration)??h(J.options.signKey)??h(J.options["sign-key"]);await F0("seal_simulation_specifications_list",U,Y,{signKey:Q},V0(J.options));return}if($==="approval-definitions"||$==="definitions"){await F0("seal_simulation_feishu_approval_definitions_list",U,Y,{},V0(J.options));return}if($==="list"){await F0("seal_simulation_batches_list",U,Y,{limit:m0(J.options.limit)},V0(J.options));return}if($==="get"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation get <batchId>");await F0("seal_simulation_batch_get",U,Y,{batchId:Q},V0(J.options));return}if($==="templates"){await F0("seal_simulation_templates_get",U,Y,{},V0(J.options));return}if($==="integrations"){await F0("seal_simulation_integrations_get",U,Y,{},V0(J.options));return}if($==="package-upload"){let Q=I??h(J.options.file);if(!Q)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!nG1(Q))throw Error(`Filenotfound:${Q}`);await F0("seal_simulation_material_package_upload",U,Y,{filePath:Q},V0(J.options));return}throw Error(`Unknownsimulationcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{existsSync as DX0}from"node:fs";import{join as cD}from"node:path";import{existsSync as pu,mkdirSync as wX0,rmSync as $W1,writeFileSync as IW1}from"node:fs";import{homedir as VX0}from"node:os";import{dirname as UW1,join as cu}from"node:path";var $X0=`---
name:seal-use
description:"v0.10.15: 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.16: 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.
@@ -559,7 +559,7 @@ seal-use corps list
-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.
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 pz0=`interface:
`;var IX0=`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."
@@ -761,7 +761,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 mz0="# 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 `./enterprises` and `~/.config/seal-use/enterprises`aremerged.\n-User-levelconfigsoverridesame-IDlocalconfigs.\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-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-useservice<start|stop|restart|status|logs>[--port8787][--host127.0.0.1][--lines50]\nseal-usehttp[--port8787][--host127.0.0.1]\nseal-useserve[--port8787]\nseal-useupdate\nseal-usetoolslist\nseal-usecorpslist[--corp<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-useusersreset-password<userId>[--corp<corpId>]\nseal-useusersget<userId>[--corp<corpId>]\nseal-useusersdelete<userId>[--corp<corpId>]\nseal-usecontactsdepartments[<departmentId>][--corp<corpId>]\nseal-usecontactschildren<departmentId>[--corp<corpId>]\nseal-usecontactsusers<departmentId>[--corp<corpId>]\nseal-usecontactssync-time[--corp<corpId>]\nseal-usedataexpenses--corp<corpId>[--search<text>][--start-date<ISO|ms>][--end-date<ISO|ms>][--offset<n>][--limit<n>]\nseal-usedatainvoices--corp<corpId>[--search<text>][--start-date<ISO|ms>][--end-date<ISO|ms>][--offset<n>][--limit<n>]\nseal-usellmconfig[--corp<corpId>]\nseal-usellmproviders[--corp<corpId>]\nseal-usepermissionsavailable[--corp<corpId>]\nseal-usepermissionsconfigs[--corp<corpId>]\nseal-usebillingstatus[--corp<corpId>]\nseal-usebillingplans[--corp<corpId>]\nseal-usebillingfeatures[--corp<corpId>]\nseal-usewebhooklist[--query<text>][--show-secret][--corp<corpId>]\nseal-usewebhookget|find<idOrName>[--show-secret][--corp<corpId>]\nseal-usewebhookadd--name<name>--result-url<url>[--modeassisted|semi_automatic|fully_automatic][--auto-approval-rate60][--secret<secret>][--min-file-size<bytes>][--max-file-size<bytes>][--allowed-extensions<.pdf,.xlsx,...>][--dry-run][--corp<corpId>]\nseal-usewebhookupdate<idOrName>[--name<name>][--result-url<url>][--modeassisted|semi_automatic|fully_automatic][--auto-approval-rate60][--secret<secret>|--rotate-secret][--min-file-size<bytes>][--max-file-size<bytes>][--allowed-extensions<.pdf,.xlsx,...>][--clear-max-file-size][--dry-run][--cLine truncated
`;var JX0="# 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 `./enterprises` and `~/.config/seal-use/enterprises`aremerged.\n-User-levelconfigsoverridesame-IDlocalconfigs.\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-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-useservice<start|stop|restart|status|logs>[--port8787][--host127.0.0.1][--lines50]\nseal-usehttp[--port8787][--host127.0.0.1]\nseal-useserve[--port8787]\nseal-useupdate\nseal-usetoolslist\nseal-usecorpslist[--corp<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-useusersreset-password<userId>[--corp<corpId>]\nseal-useusersget<userId>[--corp<corpId>]\nseal-useusersdelete<userId>[--corp<corpId>]\nseal-usecontactsdepartments[<departmentId>][--corp<corpId>]\nseal-usecontactschildren<departmentId>[--corp<corpId>]\nseal-usecontactsusers<departmentId>[--corp<corpId>]\nseal-usecontactssync-time[--corp<corpId>]\nseal-usedataexpenses--corp<corpId>[--search<text>][--start-date<ISO|ms>][--end-date<ISO|ms>][--offset<n>][--limit<n>]\nseal-usedatainvoices--corp<corpId>[--search<text>][--start-date<ISO|ms>][--end-date<ISO|ms>][--offset<n>][--limit<n>]\nseal-usellmconfig[--corp<corpId>]\nseal-usellmproviders[--corp<corpId>]\nseal-usepermissionsavailable[--corp<corpId>]\nseal-usepermissionsconfigs[--corp<corpId>]\nseal-usebillingstatus[--corp<corpId>]\nseal-usebillingplans[--corp<corpId>]\nseal-usebillingfeatures[--corp<corpId>]\nseal-usewebhooklist[--query<text>][--show-secret][--corp<corpId>]\nseal-usewebhookget|find<idOrName>[--show-secret][--corp<corpId>]\nseal-usewebhookadd--name<name>--result-url<url>[--modeassisted|semi_automatic|fully_automatic][--auto-approval-rate60][--secret<secret>][--min-file-size<bytes>][--max-file-size<bytes>][--allowed-extensions<.pdf,.xlsx,...>][--dry-run][--corp<corpId>]\nseal-usewebhookupdate<idOrName>[--name<name>][--result-url<url>][--modeassisted|semi_automatic|fully_automatic][--auto-approval-rate60][--secret<secret>|--rotate-secret][--min-file-size<bytes>][--max-file-size<bytes>][--allowed-extensions<.pdf,.xlsx,...>][--clear-max-file-size][--dry-run][--cLine truncated
@@ -1198,7 +1198,7 @@ Return a compact report containing:
-Newversionnumberandversionname,ifpublished
-Verificationresult
-Whetheraregressionrerunwasperformed
`;var tz0="# Enterprise Onboarding\n\nRead this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.\n\n## Start With Discovery\n\nRun this before asking for setup parameters (if `seal-use` is not installed, first run `curl-fsSLhttps://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash`):\n\n```bash\nseal-use version\nseal-use corps list\n```\n\n- If `seal-use` is not installed on the system, run the curl install script above to install it.\n- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.\n- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.\n- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”\n\nDo not open with a JSON template or a list of internal fields.\n\nAll command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.\n\n## Keep Two Concepts Separate\n\nClassify both the enterprise identity origin and how the current credential was acquired:\n\n| Enterprise identity origin | Credential material the user may have | Meaning |\n| --- | --- | --- |\n| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |\n| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |\n| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |\n| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |\n| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |\n\nCredential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.\n\n## Parameter Ownership\n\nAsk the user only for information that cannot be discovered safely:\n\n| Field | Owner and behavior |\n| --- | --- |\n| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |\n| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |\n| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |\n| Administrator and `staffId` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |\n| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |\n| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |\n\n## Route 1: Standard Hose Credentials\n\nThis is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:\n\n```bash\nseal-use corps add-hose --json '{\"appKey\":\"...\",\"appSecurity\":\"...\"}'\n```\n\nThe CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:\n\n```bash\nseal-use auth diagnose --corp <discovered-id>\n```\n\nDo not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.\n\n## Route 2: Incoming Assistance Link\n\nFirst distinguish the link by its host and purpose:\n\n- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.\n- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.\n- `seal-use auth hose-link` and `seal-use delegation create` generat
Line truncated
`;var HX0="# Enterprise Onboarding\n\nRead this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.\n\n## Start With Discovery\n\nRun this before asking for setup parameters (if `seal-use` is not installed, first run `curl-fsSLhttps://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash`):\n\n```bash\nseal-use version\nseal-use corps list\n```\n\n- If `seal-use` is not installed on the system, run the curl install script above to install it.\n- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.\n- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.\n- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”\n\nDo not open with a JSON template or a list of internal fields.\n\nAll command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.\n\n## Keep Two Concepts Separate\n\nClassify both the enterprise identity origin and how the current credential was acquired:\n\n| Enterprise identity origin | Credential material the user may have | Meaning |\n| --- | --- | --- |\n| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |\n| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |\n| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |\n| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |\n| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |\n\nCredential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.\n\n## Parameter Ownership\n\nAsk the user only for information that cannot be discovered safely:\n\n| Field | Owner and behavior |\n| --- | --- |\n| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |\n| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |\n| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |\n| Administrator and `staffId` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |\n| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |\n| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |\n\n## Route 1: Standard Hose Credentials\n\nThis is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:\n\n```bash\nseal-use corps add-hose --json '{\"appKey\":\"...\",\"appSecurity\":\"...\"}'\n```\n\nThe CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:\n\n```bash\nseal-use auth diagnose --corp <discovered-id>\n```\n\nDo not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.\n\n## Route 2: Incoming Assistance Link\n\nFirst distinguish the link by its host and purpose:\n\n- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.\n- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.\n- `seal-use auth hose-link` and `seal-use delegation create` generat
Line 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.
`);return}if($==="install"||$==="init"||$==="sync"){let Y=F0(U.options.local)||F0(U.options.workspace),J=h(U.options.dir)??h(U.options.target)??I,Q=J?J:Y?kD(process.cwd(),".agents","skills","seal-use"):TH(),K=fu(Q);B0({installed:!0,targetDir:K.targetDir,fileCount:K.files.length,files:K.files});return}if($==="status"||$==="get"||!$){let Y=TH(),J=kD(process.cwd(),".agents","skills","seal-use");B0({global:{dir:Y,installed:QX0(kD(Y,"SKILL.md"))},local:{dir:J,installed:QX0(kD(J,"SKILL.md"))}});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}async function qX0($,I){if($==="config"){B0(await jJ(I));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function HX0($,I,U,Y){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await D0($,I,U,s6(Y.json),w0(Y.options))}function GX0(){B0(XH.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as kG1,mkdirSync as fG1,renameSync as bu,rmSync as iG1,unlinkSync as zX0,writeFileSync as WX0}from"node:fs";import{dirname as bG1,join as wX0}from"node:path";import{spawnSync as XI}from"node:child_process";function fD($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var XX0="yunyingk/seal-use",BH="yunyingk/seal-home";var nG1="SEAL_USE_GITHUB_REPO",pG1="SEAL_HOME_GITHUB_REPO";async function LX0($,I={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:hu,version:I1,launcher:$.launcher},Y=I.repo||process.env[nG1]?.trim()||process.env[pG1]?.trim()||XX0,J=I.targetVersion?.trim(),Q=J&&J.toLowerCase()!=="latest"?J:void 0;if(Q){let A=Q.replace(/^v/,""),R=DX0(A,I1);if(R<0){B0({updated:!1,currentVersion:I1,targetVersion:A,mode:fD()?"binary":"source",message:`Cannotdowngradeseal-usefromv${I1}toolderversionv${A}.Updatesmustbeforward-only.`});return}if(R===0&&!I.force){B0({updated:!1,currentVersion:I1,targetVersion:A,mode:fD()?"binary":"source",message:`seal-useisalreadyatversionv${I1}.Use--forcetoreinstall.`});return}}if(I.changelogOnly){let A=await nu(Y,I.limit??10);B0({currentVersion:I1,totalQueried:A.length,releases:A.map((R)=>({version:R.version,tagName:R.tagName,publishedAt:R.publishedAt,author:R.author,releaseNotes:R.notes,releaseUrl:R.htmlUrl,isCurrent:R.version===I1,isNewer:EH(R.version,I1)}))});return}if(!fD()){if(I.checkOnly){let R=await nu(Y,30),k=R[0],S=k?.version??I1,i=R.find((n)=>n.version===I1),C=EH(S,I1),p=R.filter((n)=>EH(n.version,I1));B0({updated:!1,updateAvailable:C,currentVersion:I1,currentVersionPublishedAt:i?.publishedAt,latestVersion:S,latestVersionPublishedAt:k?.publishedAt,behindCount:p.length,pendingReleases:p.map((n)=>({version:n.version,tagName:n.tagName,publishedAt:n.publishedAt,author:n.author,releaseNotes:n.notes,releaseUrl:n.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=gJ(U).running;if(A)await zI("stop",U);try{ZX0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(R){console.error(`gitpullskipped:${RinstanceofError?R.message:String(R)}`)}if(ZX0("bun",["install"],{cwd:$.appRoot}),A)await zI("start",U);B0({updated:!0,serviceRestarted:A,version:I1,mode:"source"});return}let K=cG1(),q=dG1(),H=await nu(Y,30),G=Q?H.find((A)=>A.version===Q||A.tagName===Q||A.tagName===`v${Q}`)??await VX0(Y,Q):H[0]??await VX0(Y);if(!G){B0({updated:!1,currentVersion:I1,mode:"binary",message:`Failedtoqueryreleasesfromrepository'${Y}'`});return}let W=G.version,w=H.find((A)=>A.version===I1),V=EH(W,I1),Z=V||Boolean(I.force),X=H.filter((A)=>EH(A.version,I1));if(I.checkOnly){B0({updated:!1,updateAvailable:V,currentVersion:I1,currentVersionPublishedAt:w?.publishedAt,latestVersion:W,latestVersionPublishedAt:G.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:G.notes,releaseUrl:G.htmlUrl,mode:"binary"});return}if(!Z){B0({updated:!1,currentVersion:I1,currentVersionPublishedAt:w?.publishedAt,latestVersion:W,latestVersionPublishedAt:G.publishedAt,mode:"binary",message:`seal-useisalreadyuptodate(v${I1})`});return}let L=mG1(G.assets,K,q);if(!L)throw Error(`Nocompatiblebinaryfoundfor${K}-${q}inreleasev${W}.Availableassets:${G.assets.map((A)=>A.name).join(", ")}`);let D=gJ(U).running;if(D)await zI("stop",U);let F=process.execPath,E=bG1(F),T=wX0(E,`.tmp-update-${Date.now()}`);fG1(T,{recursive:!0});try{let A=wX0(T,L.name);await lG1(L.downloadUrl,A,G.tagName,L.name);let R=A;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))R=oG1(A,T,K);else if(L.name.endsWith(".zip"))R=rG1(A,T,K);if(kG1(R,493),process.platform==="darwin")try{XI("/usr/bin/codesig
Line truncated
`)}catch{}}async function lG1($,I,U,Y){let J=pu(),Q=[],K=U?U.startsWith("v")?U:`v${U}`:void 0,q=Y||$.split("/").pop()||"";if(J!=="github"){if(K&&q)Q.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${K}/${q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${K}/${q}`);if($.startsWith("https://git.ying-qing.cn"))Q.push($)}if(J!=="gitea")if(K&&q){let L=`https://github.com/${XX0}/releases/download/${K}/${q}`;if(!process.env.CI)Q.push(`https://ghfast.top/${L}`,`https://gh.ddlc.top/${L}`);Q.push(L)}else if($.includes("github.com")){if(!process.env.CI)Q.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Q.push($)}else Q.push($);let H=Array.from(new Set(Q)),G,W=6000,w=6000,V=307200,Z=1e4,X=180000;for(let L=0;L<H.length;L++){let D=H[L],F=new AbortController,E="",T=(S)=>{E=S;try{F.abort()}catch{}},A=setTimeout(()=>{T("Connection timed out (no response headers within 6s)")},W),R,k;try{iD(`==> [${L+1}/${H.length}] Downloading via: ${D}`);let S=await fetch(D,{signal:F.signal});if(A)clearTimeout(A),A=void 0;if(!S.ok)throw Error(`HTTP ${S.status} ${S.statusText}`);R=setTimeout(()=>{T("Overall download time exceeded 3 minutes")},X);let i=Number(S.headers.get("content-length"))||0,C=S.body?.getReader();if(!C){let b=Buffer.from(await S.arrayBuffer());if(b.length<1000)throw Error(`Downloaded content is suspiciously small (${b.length} bytes)`);WX0(I,b),iD(`✓ Download succeeded (${(b.length/1024/1024).toFixed(1)} MB)`);return}let p=[],n=0,g=0;k=setTimeout(()=>{if(n<V){let b=(n/1024).toFixed(1);T(`Initial transfer too slow (${b} KB < 300 KB in 6s), switching mirror...`)}},w);while(!0){let b=C.read(),Y0,B=new Promise((K0,W0)=>{Y0=setTimeout(()=>{W0(Error("Data transfer stalled (no chunk received for 10s)"))},Z)}),x;try{x=await Promise.race([b,B])}finally{if(Y0)clearTimeout(Y0)}let{done:d,value:t}=x;if(d)break;if(t){if(p.push(t),n+=t.length,k&&n>=V)clearTimeout(k),k=void 0;let K0=Date.now();if(K0-g>200){g=K0;let W0=i?Math.round(n/i*100):0,A0=(n/1048576).toFixed(1),v0=i?(i/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${W0}% (${A0} / ${v0} MB)...`)}catch{}}}}try{process.stderr.write(`
`);return}if($==="install"||$==="init"||$==="sync"){let Y=N0(U.options.local)||N0(U.options.workspace),J=h(U.options.dir)??h(U.options.target)??I,Q=J?J:Y?cD(process.cwd(),".agents","skills","seal-use"):BH(),K=du(Q);B0({installed:!0,targetDir:K.targetDir,fileCount:K.files.length,files:K.files});return}if($==="status"||$==="get"||!$){let Y=BH(),J=cD(process.cwd(),".agents","skills","seal-use");B0({global:{dir:Y,installed:DX0(cD(Y,"SKILL.md"))},local:{dir:J,installed:DX0(cD(J,"SKILL.md"))}});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}async function OX0($,I){if($==="config"){B0(await _J(I));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function NX0($,I,U,Y){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await F0($,I,U,U$(Y.json),V0(Y.options))}function MX0(){B0(DH.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as YW1,mkdirSync as JW1,renameSync as lu,rmSync as QW1,unlinkSync as BX0,writeFileSync as AX0}from"node:fs";import{dirname as KW1,join as PX0}from"node:path";import{spawnSync as LI}from"node:child_process";function dD($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var vX0="yunyingk/seal-use",RH="yunyingk/seal-home";var qW1="SEAL_USE_GITHUB_REPO",HW1="SEAL_HOME_GITHUB_REPO";async function RX0($,I={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:bu,version:U1,launcher:$.launcher},Y=I.repo||process.env[qW1]?.trim()||process.env[HW1]?.trim()||vX0,J=I.targetVersion?.trim(),Q=J&&J.toLowerCase()!=="latest"?J:void 0;if(Q){let A=Q.replace(/^v/,""),R=CX0(A,U1);if(R<0)if(!uE&&I.force);else{B0({updated:!1,currentVersion:U1,targetVersion:A,mode:dD()?"binary":"source",message:!uE?`Cannotdowngradeseal-usefromdevbuildv${U1}toreleasev${A}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${U1}toolderversionv${A}.Updatesmustbeforward-only.`});return}if(R===0&&!I.force){B0({updated:!1,currentVersion:U1,targetVersion:A,mode:dD()?"binary":"source",message:`seal-useisalreadyatversionv${U1}.Use--forcetoreinstall.`});return}}if(I.changelogOnly){let A=await ou(Y,I.limit??10);B0({currentVersion:U1,totalQueried:A.length,releases:A.map((R)=>({version:R.version,tagName:R.tagName,publishedAt:R.publishedAt,author:R.author,releaseNotes:R.notes,releaseUrl:R.htmlUrl,isCurrent:R.version===U1,isNewer:vH(R.version,U1)}))});return}if(!dD()){if(I.checkOnly){let R=await ou(Y,30),k=R[0],g=k?.version??U1,f=R.find((n)=>n.version===U1),C=vH(g,U1),p=R.filter((n)=>vH(n.version,U1));B0({updated:!1,updateAvailable:C,currentVersion:U1,currentVersionPublishedAt:f?.publishedAt,latestVersion:g,latestVersionPublishedAt:k?.publishedAt,behindCount:p.length,pendingReleases:p.map((n)=>({version:n.version,tagName:n.tagName,publishedAt:n.publishedAt,author:n.author,releaseNotes:n.notes,releaseUrl:n.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=gJ(U).running;if(A)await XI("stop",U);try{EX0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(R){console.error(`gitpullskipped:${RinstanceofError?R.message:String(R)}`)}if(EX0("bun",["install"],{cwd:$.appRoot}),A)await XI("start",U);B0({updated:!0,serviceRestarted:A,version:U1,mode:"source"});return}let K=GW1(),q=WW1(),H=await ou(Y,30),G=Q?H.find((A)=>A.version===Q||A.tagName===Q||A.tagName===`v${Q}`)??await TX0(Y,Q):H[0]??await TX0(Y);if(!G){B0({updated:!1,currentVersion:U1,mode:"binary",message:`Failedtoqueryreleasesfromrepository'${Y}'`});return}let W=G.version,w=H.find((A)=>A.version===U1),V=vH(W,U1),Z=V||Boolean(I.force),X=H.filter((A)=>vH(A.version,U1));if(I.checkOnly){B0({updated:!1,updateAvailable:V,currentVersion:U1,currentVersionPublishedAt:w?.publishedAt,latestVersion:W,latestVersionPublishedAt:G.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:G.notes,releaseUrl:G.htmlUrl,mode:"binary"});return}if(!Z){B0({updated:!1,currentVersion:U1,currentVersionPublishedAt:w?.publishedAt,latestVersion:W,latestVersionPublishedAt:G.publishedAt,mode:"binary",message:`seal-useisalreadyuptodate(v${U1})`});return}let L=wW1(G.assets,K,q);if(!L)throw Error(`Nocompatiblebinaryfoundfor${K}-${q}inreleasev${W}.Availableassets:${G.assets.map((A)=>A.name).join(", ")}`);let D=gJ(U).running;if(D)await XI("stop",U);let O=process.execPath,E=KW1(O),T=PX0(E,`.tmp-update-${Date.now()}`);JW1(T,{recursive:!0});try{let A=PX0(T,L.name);await VW1(L.downloadUrl,A,G.tagName,L.name);let R=A;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))R=ZW1
Line truncated
`)}catch{}}async function VW1($,I,U,Y){let J=ru(),Q=[],K=U?U.startsWith("v")?U:`v${U}`:void 0,q=Y||$.split("/").pop()||"";if(J!=="github"){if(K&&q)Q.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${K}/${q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${K}/${q}`);if($.startsWith("https://git.ying-qing.cn"))Q.push($)}if(J!=="gitea")if(K&&q){let L=`https://github.com/${vX0}/releases/download/${K}/${q}`;if(!process.env.CI)Q.push(`https://ghfast.top/${L}`,`https://gh.ddlc.top/${L}`);Q.push(L)}else if($.includes("github.com")){if(!process.env.CI)Q.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Q.push($)}else Q.push($);let H=Array.from(new Set(Q)),G,W=6000,w=6000,V=307200,Z=1e4,X=180000;for(let L=0;L<H.length;L++){let D=H[L],O=new AbortController,E="",T=(g)=>{E=g;try{O.abort()}catch{}},A=setTimeout(()=>{T("Connection timed out (no response headers within 6s)")},W),R,k;try{mD(`==> [${L+1}/${H.length}] Downloading via: ${D}`);let g=await fetch(D,{signal:O.signal});if(A)clearTimeout(A),A=void 0;if(!g.ok)throw Error(`HTTP ${g.status} ${g.statusText}`);R=setTimeout(()=>{T("Overall download time exceeded 3 minutes")},X);let f=Number(g.headers.get("content-length"))||0,C=g.body?.getReader();if(!C){let b=Buffer.from(await g.arrayBuffer());if(b.length<1000)throw Error(`Downloaded content is suspiciously small (${b.length} bytes)`);AX0(I,b),mD(`✓ Download succeeded (${(b.length/1024/1024).toFixed(1)} MB)`);return}let p=[],n=0,S=0;k=setTimeout(()=>{if(n<V){let b=(n/1024).toFixed(1);T(`Initial transfer too slow (${b} KB < 300 KB in 6s), switching mirror...`)}},w);while(!0){let b=C.read(),Y0,B=new Promise((Q0,w0)=>{Y0=setTimeout(()=>{w0(Error("Data transfer stalled (no chunk received for 10s)"))},Z)}),x;try{x=await Promise.race([b,B])}finally{if(Y0)clearTimeout(Y0)}let{done:c,value:r}=x;if(c)break;if(r){if(p.push(r),n+=r.length,k&&n>=V)clearTimeout(k),k=void 0;let Q0=Date.now();if(Q0-S>200){S=Q0;let w0=f?Math.round(n/f*100):0,M0=(n/1048576).toFixed(1),R0=f?(f/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${w0}% (${M0} / ${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.15: 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.16: 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.15
short-description:Seal tenant and Hose approval automation (v0.10.15)
version:0.10.16
short-description:Seal tenant and Hose approval automation (v0.10.16)
---
# Seal Use (v0.10.15)
# Seal Use (v0.10.16)
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.
@@ -57,7 +57,7 @@ seal-use corps list
- 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.
- In the **Production Enterprise**: Rules remain strictly in **draft state** without publishing any live version.
- In the **Test Enterprise**: Style preferences (`decisionPreferences`, `thinkingDepthPreference`) are updated to match production, test draft rules are cleared and populated with production draft rules, recoded, and immediately **published as a new official version** in the test tenant (`--version-name <name>`).
-`--dry-run` previews the full preference diff and rule sync plan without sending mutations. Execution requires `--yes`.
-**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 rule maintenance:
-`seal-use rules count [--corp <corpId>]`
-`seal-use rules list --summary [--corp <corpId>]`
-`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.
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences and${prodRules.rules.length} draft rules from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules and publish a new version on the test enterprise.`,
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences,${prodRules.rules.length} draft rules, and ${prodDocs.length} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,
error:`No local rule mapping found for enterprise '${corp.name}' (${corp.id}) ${vText}. Run 'seal-use corps sync-test <prodCorp> --yes' to synchronize and generate mapping snapshots.`,
// Fall back below if git is not installed or error occurs
}
// 4. Default fallback when git is not available
return{
name:"seal-use",
version:`${packageJson.version}-dev.0+local`,
channel:"dev",
isRelease: false
};
}
exportconstVERSION_INFO=resolveVersionInfo();
exportconstVERSION=VERSION_INFO.version;
exportconstIS_RELEASE=VERSION_INFO.isRelease;
exportconstCHANNEL=VERSION_INFO.channel;
Reference in new issue
Block a user
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.