Compare commits

..
1 Commits
Author SHA1 Message Date
gitea e1f7c76d19 Release v0.9.7: Improve agent onboarding
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-01 14:46:18 +08:00
11 changed files with 360 additions and 88 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-home",
"version": "0.9.6",
"version": "0.9.7",
"description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+10
View File
@@ -5,6 +5,16 @@ All notable changes to `seal-home` will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.9.7] - 2026-09-01
### Enhanced
- **Agent-first Enterprise Onboarding**: Added a dedicated first-run workflow that makes Agents discover configured enterprises before asking users for parameters, resolves human enterprise names to internal IDs, and avoids asking users for discoverable `corpId`, `staffId`, or tenant identifiers.
- **Identity and Credential Classification**: Clearly separated Hose/合思-sourced versus Seal-native tenant identity from the way access was obtained: standard Hose app credentials, incoming assistance links, or browser-copied cURL sessions.
- **Browser cURL Guidance and Secret Handling**: Added concrete F12/Network/Fetch-XHR capture instructions, read-only verification guidance, credential redaction rules, and explicit boundaries for raw cURL and assistance-link capabilities not yet supported by the CLI.
- **Simplified Hose Setup Routing**: Updated the standard Hose path to request only `appKey` and `appSecurity` initially, while automatically discovering the domain, enterprise, and administrator candidates.
---
## [0.9.6] - 2026-08-27
### Fixed & Enhanced
+207 -78
View File
@@ -1,82 +1,82 @@
import{createRequire as cj}from"node:module";var vj=Object.create;var{getPrototypeOf:$j,defineProperty:I$,getOwnPropertyNames:Ij}=Object;var gj=Object.prototype.hasOwnProperty;function bj(i){return this[i]}var wj,fj,Z0=(i,n,r)=>{var o=i!=null&&typeof i==="object";if(o){var t=n?wj??=new WeakMap:fj??=new WeakMap,u=t.get(i);if(u)return u}r=i!=null?vj($j(i)):{};let l=n||!i||!i.__esModule?I$(r,"default",{value:i,enumerable:!0}):r;for(let e of Ij(i))if(!gj.call(l,e))I$(l,e,{get:bj.bind(i,e),enumerable:!0});if(o)t.set(i,l);return l};var H=(i,n)=>()=>(n||i((n={exports:{}}).exports,n),n.exports);var Dj=(i)=>i;function Uj(i,n){this[i]=Dj.bind(null,n)}var Fn=(i,n)=>{for(var r in n)I$(i,r,{get:n[r],enumerable:!0,configurable:!0,set:Uj.bind(n,r)})};var M0=cj(import.meta.url);var so=H((S1)=>{Object.defineProperty(S1,"__esModule",{value:!0});S1.regexpCode=S1.getEsmExportName=S1.getProperty=S1.safeStringify=S1.stringify=S1.strConcat=S1.addCodeArg=S1.str=S1._=S1.nil=S1._Code=S1.Name=S1.IDENTIFIER=S1._CodeOrName=void 0;class Fe{}S1._CodeOrName=Fe;S1.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Jr extends Fe{constructor(i){super();if(!S1.IDENTIFIER.test(i))throw Error("CodeGen: name must be a valid identifier");this.str=i}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}S1.Name=Jr;class Dn extends Fe{constructor(i){super();this._items=typeof i==="string"?[i]:i}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let i=this._items[0];return i===""||i==='""'}get str(){var i;return(i=this._str)!==null&&i!==void 0?i:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var i;return(i=this._names)!==null&&i!==void 0?i:this._names=this._items.reduce((n,r)=>{if(r instanceof Jr)n[r.str]=(n[r.str]||0)+1;return n},{})}}S1._Code=Dn;S1.nil=new Dn("");function U1(i,...n){let r=[i[0]],o=0;while(o<n.length)G6(r,n[o]),r.push(i[++o]);return new Dn(r)}S1._=U1;var k6=new Dn("+");function c1(i,...n){let r=[ao(i[0])],o=0;while(o<n.length)r.push(k6),G6(r,n[o]),r.push(k6,ao(i[++o]));return q8(r),new Dn(r)}S1.str=c1;function G6(i,n){if(n instanceof Dn)i.push(...n._items);else if(n instanceof Jr)i.push(n);else i.push(T8(n))}S1.addCodeArg=G6;function q8(i){let n=1;while(n<i.length-1){if(i[n]===k6){let r=_8(i[n-1],i[n+1]);if(r!==void 0){i.splice(n-1,3,r);continue}i[n++]="+"}n++}}function _8(i,n){if(n==='""')return i;if(i==='""')return n;if(typeof i=="string"){if(n instanceof Jr||i[i.length-1]!=='"')return;if(typeof n!="string")return`${i.slice(0,-1)}${n}"`;if(n[0]==='"')return i.slice(0,-1)+n.slice(1);return}if(typeof n=="string"&&n[0]==='"'&&!(i instanceof Jr))return`"${i}${n.slice(1)}`;return}function E8(i,n){return n.emptyStr()?i:i.emptyStr()?n:c1`${i}${n}`}S1.strConcat=E8;function T8(i){return typeof i=="number"||typeof i=="boolean"||i===null?i:ao(Array.isArray(i)?i.join(","):i)}function Z8(i){return new Dn(ao(i))}S1.stringify=Z8;function ao(i){return JSON.stringify(i).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}S1.safeStringify=ao;function M8(i){return typeof i=="string"&&S1.IDENTIFIER.test(i)?new Dn(`.${i}`):U1`[${i}]`}S1.getProperty=M8;function d8(i){if(typeof i=="string"&&S1.IDENTIFIER.test(i))return new Dn(`${i}`);throw Error(`CodeGen: invalid export name: ${i}, use explicit $id name mapping`)}S1.getEsmExportName=d8;function z8(i){return new Dn(i.toString())}S1.regexpCode=z8});var J6=H((L1)=>{Object.defineProperty(L1,"__esModule",{value:!0});L1.ValueScope=L1.ValueScopeName=L1.Scope=L1.varKinds=L1.UsedValueState=void 0;var xi=so();class A1 extends Error{constructor(i){super(`CodeGen: "code" for ${i} not defined`);this.value=i.value}}var Be;(function(i){i[i.Started=0]="Started",i[i.Completed=1]="Completed"})(Be||(L1.UsedValueState=Be={}));L1.varKinds={const:new xi.Name("const"),let:new xi.Name("let"),var:new xi.Name("var")};class W6{constructor({prefixes:i,parent:n}={}){this._names={},this._prefixes=i,this._parent=n}toName(i){return i instanceof xi.Name?i:this.name(i)}name(i){return new xi.Name(this._newName(i))}_newName(i){let n=this._names[i]||this._nameGroup(i);return`${i}${n.index++}`}_nameGroup(i){var n,r;if(((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0?void 0:r.has(i))||this._prefixes&&!this._prefixes.has(i))throw Error(`CodeGen: prefix "${i}" is not allowed in this scope`);return this._names[i]={prefix:i,index:0}}}L1.Scope=W6;class y6 extends xi.Name{constructor(i,n){super(n);this.prefix=i}setValue(i,{property:n,itemIndex:r}){this.value=i,this.scopePath=xi._`.${new xi.Name(n)}[${r}]`}}L1.ValueScopeName=y6;var o9=xi._`\n`;class N1 extends W6{constructor(i){super(i);this._values={},this._scope=i.scope,this.opts={...i,_n:i.lines?o9:xi.nil}}get(){return this._scope}name(i){return new y6(i,this._newName(i))}value(i,n){var r;if(n.ref===void 0)throw Error("CodeGen: ref must be passed in value");let o=this.toName(i),{prefix:t}=o,u=(r=n.key)!==null&&r!==void 0?r:n.ref,l=this._values[t];if(l){let I=l.get(u);if(I)return I}else l=this._values[t]=newLine truncated
`:""},this._extScope=i,this._scope=new Un.Scope({parent:i}),this._nodes=[new Y1]}toString(){return this._root.render(this.opts)}name(i){return this._scope.name(i)}scopeName(i){return this._extScope.name(i)}scopeValue(i,n){let r=this._extScope.value(i,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(i,n){return this._extScope.getValue(i,n)}scopeRefs(i){return this._extScope.scopeRefs(i,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(i,n,r,o){let t=this._scope.toName(n);if(r!==void 0&&o)this._constants[t.str]=r;return this._leafNode(new G1(i,t,r)),t}const(i,n,r){return this._def(Un.varKinds.const,i,n,r)}let(i,n,r){return this._def(Un.varKinds.let,i,n,r)}var(i,n,r){return this._def(Un.varKinds.var,i,n,r)}assign(i,n,r){return this._leafNode(new P6(i,n,r))}add(i,n){return this._leafNode(new j1(i,ai.operators.ADD,n))}code(i){if(typeof i=="function")i();else if(i!==s.nil)this._leafNode(new X1(i));return this}object(...i){let n=["{"];for(let[r,o]of i){if(n.length>1)n.push(",");if(n.push(r),r!==o||this.opts.es5)n.push(":"),(0,s.addCodeArg)(n,o)}return n.push("}"),new s._Code(n)}if(i,n,r){if(this._blockNode(new _n(i)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(i){return this._elseNode(new _n(i))}else(){return this._elseNode(new iu)}endIf(){return this._endBlockNode(_n,iu)}_for(i,n){if(this._blockNode(i),n)this.code(n).endFor();return this}for(i,n){return this._for(new P1(i),n)}forRange(i,n,r,o,t=this.opts.es5?Un.varKinds.var:Un.varKinds.let){let u=this._scope.toName(i);return this._for(new Q1(t,u,n,r),()=>o(u))}forOf(i,n,r,o=Un.varKinds.const){let t=this._scope.toName(i);if(this.opts.es5){let u=n instanceof s.Name?n:this.var("_arr",n);return this.forRange("_i",0,s._`${u}.length`,(l)=>{this.var(t,s._`${u}[${l}]`),r(t)})}return this._for(new X6("of",o,t,n),()=>r(t))}forIn(i,n,r,o=this.opts.es5?Un.varKinds.var:Un.varKinds.const){if(this.opts.ownProperties)return this.forOf(i,s._`Object.keys(${n})`,r);let t=this._scope.toName(i);return this._for(new X6("in",o,t,n),()=>r(t))}endFor(){return this._endBlockNode(Xr)}label(i){return this._leafNode(new W1(i))}break(i){return this._leafNode(new y1(i))}return(i){let n=new qe;if(this._blockNode(n),this.code(i),n.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(qe)}try(i,n,r){if(!n&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new H1;if(this._blockNode(o),this.code(i),n){let t=this.name("e");this._currNode=o.catch=new _e(t),n(t)}if(r)this._currNode=o.finally=new Ee,this.code(r);return this._endBlockNode(_e,Ee)}throw(i){return this._leafNode(new J1(i))}block(i,n){if(this._blockStarts.push(this._nodes.length),i)this.code(i).endBlock(n);return this}endBlock(i){let n=this._blockStarts.pop();if(n===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||i!==void 0&&r!==i)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${i} expected`);return this._nodes.length=n,this}func(i,n=s.nil,r,o){if(this._blockNode(new Ve(i,n,r)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(Ve)}optimize(i=1){while(i-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(i){return this._currNode.nodes.push(i),this}_blockNode(i){this._currNode.nodes.push(i),this._nodes.push(i)}_endBlockNode(i,n){let r=this._currNode;if(r instanceof i||n&&r instanceof n)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${n?`${i.kind}/${n.kind}`:i.kind}"`)}_elseNode(i){let n=this._currNode;if(!(n instanceof _n))throw Error('CodeGen: "else" without "if"');return this._currNode=n.else=i,this}get _root(){return this._nodes[0]}get _currNode(){let i=this._nodes;return i[i.length-1]}set _currNode(i){let n=this._nodes;n[n.length-1]=i}}ai.CodeGen=F1;function Yt(i,n){for(let r in n)i[r]=(i[r]||0)+(n[r]||0);return i}function Te(i,n){return n instanceof s._CodeOrName?Yt(i,n.names):i}function Yr(i,n,r){if(i instanceof s.Name)return o(i);if(!t(i))return i;return new s._Code(i._items.reduce((u,l)=>{if(l instanceof s.Name)l=o(l);if(l instanceof s._Code)u.push(...l._items);else u.push(l);return u},[]));function o(u){let l=r[u.str];if(l===void 0||n[u.str]!==1)return u;return delete n[u.str],l}function t(u){return u instanceof s._Code&&u._items.some((l)=>l instanceof s.Name&&n[l.str]===1&&r[l.str]!==void 0)}}function v9(i,n){for(let r in n)i[r]=(i[r]||0)-(n[r]||0)}function K1(i){return typeof i=="boolean"||typeof i=="number"||i===null?!i:s._`!${Y6(i)}`}ai.not=K1;var $9=B1(ai.operators.AND);function I9(...i){return i.reduce($9)}ai.and=I9;var g9=B1(ai.operators.OR);function b9(...i){return i.reduce(g9)}ai.or=b9;function B1(i){return(n,r)=>n===s.nil?r:r===s.nil?n:s._`${Y6(n)} ${i} ${Y6(r)}`}function Y6(i){return i instanceof s.Name?i:s._`(${i})`}});var ii=H((z1)=>{Object Line truncated
|| (${l} == "string" && ${t} && ${t} == +${t})`).assign(e,z._`+${t}`);return;case"integer":o.elseIf(z._`${l} === "boolean" || ${t} === null
|| (${l} === "string" && ${t} && ${t} == +${t} && !(${t} % 1))`).assign(e,z._`+${t}`);return;case"boolean":o.elseIf(z._`${t} === "false" || ${t} === 0 || ${t} === null`).assign(e,!1).elseIf(z._`${t} === "true" || ${t} === 1`).assign(e,!0);return;case"null":o.elseIf(z._`${t} === "" || ${t} === 0 || ${t} === false`),o.assign(e,null);return;case"array":o.elseIf(z._`${l} === "string" || ${l} === "number"
|| ${l} === "boolean" || ${t} === null`).assign(e,z._`[${t}]`)}}}function jX({gen:i,parentData:n,parentDataProperty:r},o){i.if(z._`${n} !== undefined`,()=>i.assign(z._`${n}[${r}]`,o))}function q6(i,n,r,o=Pr.Correct){let t=o===Pr.Correct?z.operators.EQ:z.operators.NEQ,u;switch(i){case"null":return z._`${n} ${t} null`;case"array":u=z._`Array.isArray(${n})`;break;case"object":u=z._`${n} && typeof ${n} == "object" && !Array.isArray(${n})`;break;case"integer":u=l(z._`!(${n} % 1) && !isNaN(${n})`);break;case"number":u=l();break;default:return z._`typeof ${n} ${t} ${i}`}return o===Pr.Correct?u:(0,z.not)(u);function l(e=z.nil){return(0,z.and)(z._`typeof ${n} == "number"`,e,r?z._`isFinite(${n})`:z.nil)}}bc.checkDataType=q6;function _6(i,n,r,o){if(i.length===1)return q6(i[0],n,r,o);let t,u=(0,$c.toHash)(i);if(u.array&&u.object){let l=z._`typeof ${n} != "object"`;t=u.null?l:z._`!${n} || ${l}`,delete u.null,delete u.array,delete u.object}else t=z.nil;if(u.number)delete u.integer;for(let l in u)t=(0,z.and)(t,q6(l,n,r,o));return t}bc.checkDataTypes=_6;var WX={message:({schema:i})=>`must be ${i}`,params:({schema:i,schemaValue:n})=>typeof i=="string"?z._`{type: ${i}}`:z._`{type: ${n}}`};function E6(i){let n=yX(i);(0,AX.reportError)(n,WX)}bc.reportTypeError=E6;function yX(i){let{gen:n,data:r,schema:o}=i,t=(0,$c.schemaRefOrVal)(i,o,"type");return{gen:n,keyword:"type",data:r,schema:o.type,schemaCode:t,schemaValue:t,parentSchema:o,params:{},it:i}}});var cc=H((Dc)=>{Object.defineProperty(Dc,"__esModule",{value:!0});Dc.assignDefaults=void 0;var Qr=h(),FX=ii();function KX(i,n){let{properties:r,items:o}=i.schema;if(n==="object"&&r)for(let t in r)fc(i,t,r[t].default);else if(n==="array"&&Array.isArray(o))o.forEach((t,u)=>fc(i,u,t.default))}Dc.assignDefaults=KX;function fc(i,n,r){let{gen:o,compositeRule:t,data:u,opts:l}=i;if(r===void 0)return;let e=Qr._`${u}${(0,Qr.getProperty)(n)}`;if(t){(0,FX.checkStrictMode)(i,`default is ignored for: ${e}`);return}let $=Qr._`${e} === undefined`;if(l.useDefaults==="empty")$=Qr._`${$} || ${e} === null || ${e} === ""`;o.if($,Qr._`${e} = ${(0,Qr.stringify)(r)}`)}});var In=H((Ac)=>{Object.defineProperty(Ac,"__esModule",{value:!0});Ac.validateUnion=Ac.validateArray=Ac.usePattern=Ac.callValidateCode=Ac.schemaProperties=Ac.allSchemaProperties=Ac.noPropertyInData=Ac.propertyInData=Ac.isOwnProperty=Ac.hasPropFunc=Ac.reportMissingProp=Ac.checkMissingProp=Ac.checkReportMissingProp=void 0;var ci=h(),T6=ii(),$t=En(),BX=ii();function VX(i,n){let{gen:r,data:o,it:t}=i;r.if(M6(r,o,n,t.opts.ownProperties),()=>{i.setParams({missingProperty:ci._`${n}`},!0),i.error()})}Ac.checkReportMissingProp=VX;function qX({gen:i,data:n,it:{opts:r}},o,t){return(0,ci.or)(...o.map((u)=>(0,ci.and)(M6(i,n,u,r.ownProperties),ci._`${t} = ${u}`)))}Ac.checkMissingProp=qX;function _X(i,n){i.setParams({missingProperty:n},!0),i.error()}Ac.reportMissingProp=_X;function Sc(i){return i.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:ci._`Object.prototype.hasOwnProperty`})}Ac.hasPropFunc=Sc;function Z6(i,n,r){return ci._`${Sc(i)}.call(${n}, ${r})`}Ac.isOwnProperty=Z6;function EX(i,n,r,o){let t=ci._`${n}${(0,ci.getProperty)(r)} !== undefined`;return o?ci._`${t} && ${Z6(i,n,r)}`:t}Ac.propertyInData=EX;function M6(i,n,r,o){let t=ci._`${n}${(0,ci.getProperty)(r)} === undefined`;return o?(0,ci.or)(t,(0,ci.not)(Z6(i,n,r))):t}Ac.noPropertyInData=M6;function Oc(i){return i?Object.keys(i).filter((n)=>n!=="__proto__"):[]}Ac.allSchemaProperties=Oc;function TX(i,n){return Oc(n).filter((r)=>!(0,T6.alwaysValidSchema)(i,n[r]))}Ac.schemaProperties=TX;function ZX({schemaCode:i,data:n,it:{gen:r,topSchemaRef:o,schemaPath:t,errorPath:u},it:l},e,$,I){let g=I?ci._`${i}, ${n}, ${o}${t}`:n,b=[[$t.default.instancePath,(0,ci.strConcat)($t.default.instancePath,u)],[$t.default.parentData,l.parentData],[$t.default.parentDataProperty,l.parentDataProperty],[$t.default.rootData,$t.default.rootData]];if(l.opts.dynamicRef)b.push([$t.default.dynamicAnchors,$t.default.dynamicAnchors]);let w=ci._`${g}, ${r.object(...b)}`;return $!==ci.nil?ci._`${e}.call(${$}, ${w})`:ci._`${e}(${w})`}Ac.callValidateCode=ZX;var MX=ci._`new RegExp`;function dX({gen:i,it:{opts:n}},r){let o=n.unicodeRegExp?"u":"",{regExp:t}=n.code,u=t(r,o);return i.scopeValue("pattern",{key:u.toString(),ref:u,code:ci._`${t.code==="new RegExp"?MX:(0,BX.useFunc)(i,t)}(${r}, ${o})`})}Ac.usePattern=dX;function zX(i){let{gen:n,data:r,keyword:o,it:t}=i,u=n.name("valid");if(t.allErrors){let e=n.let("valid",!0);return l(()=>n.assign(e,!1)),e}return n.var(u,!0),l(()=>n.break()),u;function l(e){let $=n.const("len",ci._`${r}.length`);n.forRange("i",0,$,(I)=>{i.subschema({keyword:o,dataProp:I,dataPropType:T6.Type.Num},u),n.if((0,ci.not)(u),e)})}}Ac.validateArray=zX;function pX(i){let{gen:n,schema:r,keyword:o,it:t}=i;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(($)=>(0,T6.alwaysValidSchema)(t,$))&&!t.opts.unevaluated)return;let l=n.let("valid",!1),e=n.name("_valid");n.block(()=>r. Line truncated
import{createRequire as Sd}from"node:module";var $d=Object.create;var{getPrototypeOf:Id,defineProperty:I$,getOwnPropertyNames:gd}=Object;var bd=Object.prototype.hasOwnProperty;function wd(n){return this[n]}var fd,cd,T4=(n,i,r)=>{var o=n!=null&&typeof n==="object";if(o){var t=i?fd??=new WeakMap:cd??=new WeakMap,u=t.get(n);if(u)return u}r=n!=null?$d(Id(n)):{};let e=i||!n||!n.__esModule?I$(r,"default",{value:n,enumerable:!0}):r;for(let l of gd(n))if(!bd.call(e,l))I$(e,l,{get:wd.bind(n,l),enumerable:!0});if(o)t.set(n,e);return e};var P=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports);var Dd=(n)=>n;function Ud(n,i){this[n]=Dd.bind(null,i)}var Qi=(n,i)=>{for(var r in i)I$(n,r,{get:i[r],enumerable:!0,configurable:!0,set:Ud.bind(i,r)})};var _4=Sd(import.meta.url);var so=P((SU)=>{Object.defineProperty(SU,"__esModule",{value:!0});SU.regexpCode=SU.getEsmExportName=SU.getProperty=SU.safeStringify=SU.stringify=SU.strConcat=SU.addCodeArg=SU.str=SU._=SU.nil=SU._Code=SU.Name=SU.IDENTIFIER=SU._CodeOrName=void 0;class Ql{}SU._CodeOrName=Ql;SU.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Wr extends Ql{constructor(n){super();if(!SU.IDENTIFIER.test(n))throw Error("CodeGen: name must be a valid identifier");this.str=n}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}SU.Name=Wr;class ci extends Ql{constructor(n){super();this._items=typeof n==="string"?[n]:n}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let n=this._items[0];return n===""||n==='""'}get str(){var n;return(n=this._str)!==null&&n!==void 0?n:this._str=this._items.reduce((i,r)=>`${i}${r}`,"")}get names(){var n;return(n=this._names)!==null&&n!==void 0?n:this._names=this._items.reduce((i,r)=>{if(r instanceof Wr)i[r.str]=(i[r.str]||0)+1;return i},{})}}SU._Code=ci;SU.nil=new ci("");function DU(n,...i){let r=[n[0]],o=0;while(o<i.length)k6(r,i[o]),r.push(n[++o]);return new ci(r)}SU._=DU;var y6=new ci("+");function UU(n,...i){let r=[ao(n[0])],o=0;while(o<i.length)r.push(y6),k6(r,i[o]),r.push(y6,ao(n[++o]));return pJ(r),new ci(r)}SU.str=UU;function k6(n,i){if(i instanceof ci)n.push(...i._items);else if(i instanceof Wr)n.push(i);else n.push(TJ(i))}SU.addCodeArg=k6;function pJ(n){let i=1;while(i<n.length-1){if(n[i]===y6){let r=VJ(n[i-1],n[i+1]);if(r!==void 0){n.splice(i-1,3,r);continue}n[i++]="+"}i++}}function VJ(n,i){if(i==='""')return n;if(n==='""')return i;if(typeof n=="string"){if(i instanceof Wr||n[n.length-1]!=='"')return;if(typeof i!="string")return`${n.slice(0,-1)}${i}"`;if(i[0]==='"')return n.slice(0,-1)+i.slice(1);return}if(typeof i=="string"&&i[0]==='"'&&!(n instanceof Wr))return`"${n}${i.slice(1)}`;return}function qJ(n,i){return i.emptyStr()?n:n.emptyStr()?i:UU`${n}${i}`}SU.strConcat=qJ;function TJ(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:ao(Array.isArray(n)?n.join(","):n)}function _J(n){return new ci(ao(n))}SU.stringify=_J;function ao(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}SU.safeStringify=ao;function EJ(n){return typeof n=="string"&&SU.IDENTIFIER.test(n)?new ci(`.${n}`):DU`[${n}]`}SU.getProperty=EJ;function ZJ(n){if(typeof n=="string"&&SU.IDENTIFIER.test(n))return new ci(`${n}`);throw Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}SU.getEsmExportName=ZJ;function MJ(n){return new ci(n.toString())}SU.regexpCode=MJ});var W6=P((LU)=>{Object.defineProperty(LU,"__esModule",{value:!0});LU.ValueScope=LU.ValueScopeName=LU.Scope=LU.varKinds=LU.UsedValueState=void 0;var an=so();class AU extends Error{constructor(n){super(`CodeGen: "code" for ${n} not defined`);this.value=n.value}}var hl;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed"})(hl||(LU.UsedValueState=hl={}));LU.varKinds={const:new an.Name("const"),let:new an.Name("let"),var:new an.Name("var")};class G6{constructor({prefixes:n,parent:i}={}){this._names={},this._prefixes=n,this._parent=i}toName(n){return n instanceof an.Name?n:this.name(n)}name(n){return new an.Name(this._newName(n))}_newName(n){let i=this._names[n]||this._nameGroup(n);return`${n}${i.index++}`}_nameGroup(n){var i,r;if(((r=(i=this._parent)===null||i===void 0?void 0:i._prefixes)===null||r===void 0?void 0:r.has(n))||this._prefixes&&!this._prefixes.has(n))throw Error(`CodeGen: prefix "${n}" is not allowed in this scope`);return this._names[n]={prefix:n,index:0}}}LU.Scope=G6;class j6 extends an.Name{constructor(n,i){super(i);this.prefix=n}setValue(n,{property:i,itemIndex:r}){this.value=n,this.scopePath=an._`.${new an.Name(i)}[${r}]`}}LU.ValueScopeName=j6;var u8=an._`\n`;class NU extends G6{constructor(n){super(n);this._values={},this._scope=n.scope,this.opts={...n,_n:n.lines?u8:an.nil}}get(){return this._scope}name(n){return new j6(n,this._newName(n))}value(n,i){var r;if(i.ref===void 0)throw Error("CodeGen: ref must be passed in value");let o=this.toName(n),{prefix:t}=o,u=(r=i.key)!==null&&r!==void 0?r:i.ref,e=this._values[t];if(e){let I=e.get(u);if(I)return I}else e=this._values[t]=newLine truncated
`:""},this._extScope=n,this._scope=new Di.Scope({parent:n}),this._nodes=[new XU]}toString(){return this._root.render(this.opts)}name(n){return this._scope.name(n)}scopeName(n){return this._extScope.name(n)}scopeValue(n,i){let r=this._extScope.value(n,i);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(n,i){return this._extScope.getValue(n,i)}scopeRefs(n){return this._extScope.scopeRefs(n,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(n,i,r,o){let t=this._scope.toName(i);if(r!==void 0&&o)this._constants[t.str]=r;return this._leafNode(new kU(n,t,r)),t}const(n,i,r){return this._def(Di.varKinds.const,n,i,r)}let(n,i,r){return this._def(Di.varKinds.let,n,i,r)}var(n,i,r){return this._def(Di.varKinds.var,n,i,r)}assign(n,i,r){return this._leafNode(new Y6(n,i,r))}add(n,i){return this._leafNode(new dU(n,sn.operators.ADD,i))}code(n){if(typeof n=="function")n();else if(n!==s.nil)this._leafNode(new JU(n));return this}object(...n){let i=["{"];for(let[r,o]of n){if(i.length>1)i.push(",");if(i.push(r),r!==o||this.opts.es5)i.push(":"),(0,s.addCodeArg)(i,o)}return i.push("}"),new s._Code(i)}if(n,i,r){if(this._blockNode(new pi(n)),i&&r)this.code(i).else().code(r).endIf();else if(i)this.code(i).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(n){return this._elseNode(new pi(n))}else(){return this._elseNode(new nu)}endIf(){return this._endBlockNode(pi,nu)}_for(n,i){if(this._blockNode(n),i)this.code(i).endFor();return this}for(n,i){return this._for(new YU(n),i)}forRange(n,i,r,o,t=this.opts.es5?Di.varKinds.var:Di.varKinds.let){let u=this._scope.toName(n);return this._for(new HU(t,u,i,r),()=>o(u))}forOf(n,i,r,o=Di.varKinds.const){let t=this._scope.toName(n);if(this.opts.es5){let u=i instanceof s.Name?i:this.var("_arr",i);return this.forRange("_i",0,s._`${u}.length`,(e)=>{this.var(t,s._`${u}[${e}]`),r(t)})}return this._for(new J6("of",o,t,i),()=>r(t))}forIn(n,i,r,o=this.opts.es5?Di.varKinds.var:Di.varKinds.const){if(this.opts.ownProperties)return this.forOf(n,s._`Object.keys(${i})`,r);let t=this._scope.toName(n);return this._for(new J6("in",o,t,i),()=>r(t))}endFor(){return this._endBlockNode(Jr)}label(n){return this._leafNode(new GU(n))}break(n){return this._leafNode(new jU(n))}return(n){let i=new Bl;if(this._blockNode(i),this.code(n),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Bl)}try(n,i,r){if(!i&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new PU;if(this._blockNode(o),this.code(n),i){let t=this.name("e");this._currNode=o.catch=new pl(t),i(t)}if(r)this._currNode=o.finally=new Vl,this.code(r);return this._endBlockNode(pl,Vl)}throw(n){return this._leafNode(new WU(n))}block(n,i){if(this._blockStarts.push(this._nodes.length),n)this.code(n).endBlock(i);return this}endBlock(n){let i=this._blockStarts.pop();if(i===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-i;if(r<0||n!==void 0&&r!==n)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${n} expected`);return this._nodes.length=i,this}func(n,i=s.nil,r,o){if(this._blockNode(new Kl(n,i,r)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(Kl)}optimize(n=1){while(n-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(n){return this._currNode.nodes.push(n),this}_blockNode(n){this._currNode.nodes.push(n),this._nodes.push(n)}_endBlockNode(n,i){let r=this._currNode;if(r instanceof n||i&&r instanceof i)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${i?`${n.kind}/${i.kind}`:n.kind}"`)}_elseNode(n){let i=this._currNode;if(!(i instanceof pi))throw Error('CodeGen: "else" without "if"');return this._currNode=i.else=n,this}get _root(){return this._nodes[0]}get _currNode(){let n=this._nodes;return n[n.length-1]}set _currNode(n){let i=this._nodes;i[i.length-1]=n}}sn.CodeGen=QU;function Xt(n,i){for(let r in i)n[r]=(n[r]||0)+(i[r]||0);return n}function ql(n,i){return i instanceof s._CodeOrName?Xt(n,i.names):n}function Xr(n,i,r){if(n instanceof s.Name)return o(n);if(!t(n))return n;return new s._Code(n._items.reduce((u,e)=>{if(e instanceof s.Name)e=o(e);if(e instanceof s._Code)u.push(...e._items);else u.push(e);return u},[]));function o(u){let e=r[u.str];if(e===void 0||i[u.str]!==1)return u;return delete i[u.str],e}function t(u){return u instanceof s._Code&&u._items.some((e)=>e instanceof s.Name&&i[e.str]===1&&r[e.str]!==void 0)}}function $8(n,i){for(let r in i)n[r]=(n[r]||0)-(i[r]||0)}function FU(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:s._`!${X6(n)}`}sn.not=FU;var I8=hU(sn.operators.AND);function g8(...n){return n.reduce(I8)}sn.and=g8;var b8=hU(sn.operators.OR);function w8(...n){return n.reduce(b8)}sn.or=w8;function hU(n){return(i,r)=>i===s.nil?r:r===s.nil?i:s._`${X6(i)} ${n} ${X6(r)}`}function X6(n){return n instanceof s.Name?n:s._`(${n})`}});var nn=P((ZU)=>{Object Line truncated
|| (${e} == "string" && ${t} && ${t} == +${t})`).assign(l,Z._`+${t}`);return;case"integer":o.elseIf(Z._`${e} === "boolean" || ${t} === null
|| (${e} === "string" && ${t} && ${t} == +${t} && !(${t} % 1))`).assign(l,Z._`+${t}`);return;case"boolean":o.elseIf(Z._`${t} === "false" || ${t} === 0 || ${t} === null`).assign(l,!1).elseIf(Z._`${t} === "true" || ${t} === 1`).assign(l,!0);return;case"null":o.elseIf(Z._`${t} === "" || ${t} === 0 || ${t} === false`),o.assign(l,null);return;case"array":o.elseIf(Z._`${e} === "string" || ${e} === "number"
|| ${e} === "boolean" || ${t} === null`).assign(l,Z._`[${t}]`)}}}function GX({gen:n,parentData:i,parentDataProperty:r},o){n.if(Z._`${i} !== undefined`,()=>n.assign(Z._`${i}[${r}]`,o))}function B6(n,i,r,o=Yr.Correct){let t=o===Yr.Correct?Z.operators.EQ:Z.operators.NEQ,u;switch(n){case"null":return Z._`${i} ${t} null`;case"array":u=Z._`Array.isArray(${i})`;break;case"object":u=Z._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":u=e(Z._`!(${i} % 1) && !isNaN(${i})`);break;case"number":u=e();break;default:return Z._`typeof ${i} ${t} ${n}`}return o===Yr.Correct?u:(0,Z.not)(u);function e(l=Z.nil){return(0,Z.and)(Z._`typeof ${i} == "number"`,l,r?Z._`isFinite(${i})`:Z.nil)}}b1.checkDataType=B6;function p6(n,i,r,o){if(n.length===1)return B6(n[0],i,r,o);let t,u=(0,$1.toHash)(n);if(u.array&&u.object){let e=Z._`typeof ${i} != "object"`;t=u.null?e:Z._`!${i} || ${e}`,delete u.null,delete u.array,delete u.object}else t=Z.nil;if(u.number)delete u.integer;for(let e in u)t=(0,Z.and)(t,B6(e,i,r,o));return t}b1.checkDataTypes=p6;var jX={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:i})=>typeof n=="string"?Z._`{type: ${n}}`:Z._`{type: ${i}}`};function V6(n){let i=WX(n);(0,NX.reportError)(i,jX)}b1.reportTypeError=V6;function WX(n){let{gen:i,data:r,schema:o}=n,t=(0,$1.schemaRefOrVal)(n,o,"type");return{gen:i,keyword:"type",data:r,schema:o.type,schemaCode:t,schemaValue:t,parentSchema:o,params:{},it:n}}});var U1=P((c1)=>{Object.defineProperty(c1,"__esModule",{value:!0});c1.assignDefaults=void 0;var Hr=z(),FX=nn();function hX(n,i){let{properties:r,items:o}=n.schema;if(i==="object"&&r)for(let t in r)f1(n,t,r[t].default);else if(i==="array"&&Array.isArray(o))o.forEach((t,u)=>f1(n,u,t.default))}c1.assignDefaults=hX;function f1(n,i,r){let{gen:o,compositeRule:t,data:u,opts:e}=n;if(r===void 0)return;let l=Hr._`${u}${(0,Hr.getProperty)(i)}`;if(t){(0,FX.checkStrictMode)(n,`default is ignored for: ${l}`);return}let $=Hr._`${l} === undefined`;if(e.useDefaults==="empty")$=Hr._`${$} || ${l} === null || ${l} === ""`;o.if($,Hr._`${l} = ${(0,Hr.stringify)(r)}`)}});var Ii=P((A1)=>{Object.defineProperty(A1,"__esModule",{value:!0});A1.validateUnion=A1.validateArray=A1.usePattern=A1.callValidateCode=A1.schemaProperties=A1.allSchemaProperties=A1.noPropertyInData=A1.propertyInData=A1.isOwnProperty=A1.hasPropFunc=A1.reportMissingProp=A1.checkMissingProp=A1.checkReportMissingProp=void 0;var Sn=z(),q6=nn(),$t=Vi(),KX=nn();function BX(n,i){let{gen:r,data:o,it:t}=n;r.if(_6(r,o,i,t.opts.ownProperties),()=>{n.setParams({missingProperty:Sn._`${i}`},!0),n.error()})}A1.checkReportMissingProp=BX;function pX({gen:n,data:i,it:{opts:r}},o,t){return(0,Sn.or)(...o.map((u)=>(0,Sn.and)(_6(n,i,u,r.ownProperties),Sn._`${t} = ${u}`)))}A1.checkMissingProp=pX;function VX(n,i){n.setParams({missingProperty:i},!0),n.error()}A1.reportMissingProp=VX;function S1(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Sn._`Object.prototype.hasOwnProperty`})}A1.hasPropFunc=S1;function T6(n,i,r){return Sn._`${S1(n)}.call(${i}, ${r})`}A1.isOwnProperty=T6;function qX(n,i,r,o){let t=Sn._`${i}${(0,Sn.getProperty)(r)} !== undefined`;return o?Sn._`${t} && ${T6(n,i,r)}`:t}A1.propertyInData=qX;function _6(n,i,r,o){let t=Sn._`${i}${(0,Sn.getProperty)(r)} === undefined`;return o?(0,Sn.or)(t,(0,Sn.not)(T6(n,i,r))):t}A1.noPropertyInData=_6;function O1(n){return n?Object.keys(n).filter((i)=>i!=="__proto__"):[]}A1.allSchemaProperties=O1;function TX(n,i){return O1(i).filter((r)=>!(0,q6.alwaysValidSchema)(n,i[r]))}A1.schemaProperties=TX;function _X({schemaCode:n,data:i,it:{gen:r,topSchemaRef:o,schemaPath:t,errorPath:u},it:e},l,$,I){let g=I?Sn._`${n}, ${i}, ${o}${t}`:i,b=[[$t.default.instancePath,(0,Sn.strConcat)($t.default.instancePath,u)],[$t.default.parentData,e.parentData],[$t.default.parentDataProperty,e.parentDataProperty],[$t.default.rootData,$t.default.rootData]];if(e.opts.dynamicRef)b.push([$t.default.dynamicAnchors,$t.default.dynamicAnchors]);let w=Sn._`${g}, ${r.object(...b)}`;return $!==Sn.nil?Sn._`${l}.call(${$}, ${w})`:Sn._`${l}(${w})`}A1.callValidateCode=_X;var EX=Sn._`new RegExp`;function ZX({gen:n,it:{opts:i}},r){let o=i.unicodeRegExp?"u":"",{regExp:t}=i.code,u=t(r,o);return n.scopeValue("pattern",{key:u.toString(),ref:u,code:Sn._`${t.code==="new RegExp"?EX:(0,KX.useFunc)(n,t)}(${r}, ${o})`})}A1.usePattern=ZX;function MX(n){let{gen:i,data:r,keyword:o,it:t}=n,u=i.name("valid");if(t.allErrors){let l=i.let("valid",!0);return e(()=>i.assign(l,!1)),l}return i.var(u,!0),e(()=>i.break()),u;function e(l){let $=i.const("len",Sn._`${r}.length`);i.forRange("i",0,$,(I)=>{n.subschema({keyword:o,dataProp:I,dataPropType:q6.Type.Num},u),i.if((0,Sn.not)(u),l)})}}A1.validateArray=MX;function zX(n){let{gen:i,schema:r,keyword:o,it:t}=n;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(($)=>(0,q6.alwaysValidSchema)(t,$))&&!t.opts.unevaluated)return;let e=i.let("valid",!1),l=i.name("_valid");i.block(()=>r. Line truncated
missingProperty: ${o},
depsCount: ${n},
deps: ${r}}`};var gQ={keyword:"dependencies",type:"object",schemaType:"object",error:VO.error,code(i){let[n,r]=bQ(i);KO(i,n),BO(i,r)}};function bQ({schema:i}){let n={},r={};for(let o in i){if(o==="__proto__")continue;let t=Array.isArray(i[o])?n:r;t[o]=i[o]}return[n,r]}function KO(i,n=i.schema){let{gen:r,data:o,it:t}=i;if(Object.keys(n).length===0)return;let u=r.let("missing");for(let l in n){let e=n[l];if(e.length===0)continue;let $=(0,Su.propertyInData)(r,o,l,t.opts.ownProperties);if(i.setParams({property:l,depsCount:e.length,deps:e.join(", ")}),t.allErrors)r.if($,()=>{for(let I of e)(0,Su.checkReportMissingProp)(i,I)});else r.if(b4._`${$} && (${(0,Su.checkMissingProp)(i,e,u)})`),(0,Su.reportMissingProp)(i,u),r.else()}}VO.validatePropertyDeps=KO;function BO(i,n=i.schema){let{gen:r,data:o,keyword:t,it:u}=i,l=r.name("valid");for(let e in n){if((0,IQ.alwaysValidSchema)(u,n[e]))continue;r.if((0,Su.propertyInData)(r,o,e,u.opts.ownProperties),()=>{let $=i.subschema({keyword:t,schemaProp:e},l);i.mergeValidEvaluated($,l)},()=>r.var(l,!0)),i.ok(l)}}VO.validateSchemaDeps=BO;VO.default=gQ});var MO=H((ZO)=>{Object.defineProperty(ZO,"__esModule",{value:!0});var TO=h(),DQ=ii(),UQ={message:"property name must be valid",params:({params:i})=>TO._`{propertyName: ${i.propertyName}}`},cQ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:UQ,code(i){let{gen:n,schema:r,data:o,it:t}=i;if((0,DQ.alwaysValidSchema)(t,r))return;let u=n.name("valid");n.forIn("key",o,(l)=>{i.setParams({propertyName:l}),i.subschema({keyword:"propertyNames",data:l,dataTypes:["string"],propertyName:l,compositeRule:!0},u),n.if((0,TO.not)(u),()=>{if(i.error(!0),!t.allErrors)n.break()})}),i.ok(u)}};ZO.default=cQ});var w4=H((dO)=>{Object.defineProperty(dO,"__esModule",{value:!0});var $v=In(),On=h(),OQ=En(),Iv=ii(),AQ={message:"must NOT have additional properties",params:({params:i})=>On._`{additionalProperty: ${i.additionalProperty}}`},NQ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:AQ,code(i){let{gen:n,schema:r,parentSchema:o,data:t,errsCount:u,it:l}=i;if(!u)throw Error("ajv implementation error");let{allErrors:e,opts:$}=l;if(l.props=!0,$.removeAdditional!=="all"&&(0,Iv.alwaysValidSchema)(l,r))return;let I=(0,$v.allSchemaProperties)(o.properties),g=(0,$v.allSchemaProperties)(o.patternProperties);b(),i.ok(On._`${u} === ${OQ.default.errors}`);function b(){n.forIn("key",t,(N)=>{if(!I.length&&!g.length)D(N);else n.if(w(N),()=>D(N))})}function w(N){let L;if(I.length>8){let V=(0,Iv.schemaRefOrVal)(l,o.properties,"properties");L=(0,$v.isOwnProperty)(n,V,N)}else if(I.length)L=(0,On.or)(...I.map((V)=>On._`${N} === ${V}`));else L=On.nil;if(g.length)L=(0,On.or)(L,...g.map((V)=>On._`${(0,$v.usePattern)(i,V)}.test(${N})`));return(0,On.not)(L)}function f(N){n.code(On._`delete ${t}[${N}]`)}function D(N){if($.removeAdditional==="all"||$.removeAdditional&&r===!1){f(N);return}if(r===!1){if(i.setParams({additionalProperty:N}),i.error(),!e)n.break();return}if(typeof r=="object"&&!(0,Iv.alwaysValidSchema)(l,r)){let L=n.name("valid");if($.removeAdditional==="failing")S(N,L,!1),n.if((0,On.not)(L),()=>{i.reset(),f(N)});else if(S(N,L),!e)n.if((0,On.not)(L),()=>n.break())}}function S(N,L,V){let Q={keyword:"additionalProperties",dataProp:N,dataPropType:Iv.Type.Str};if(V===!1)Object.assign(Q,{compositeRule:!0,createErrors:!1,allErrors:!1});i.subschema(Q,L)}}};dO.default=NQ});var CO=H((hO)=>{Object.defineProperty(hO,"__esModule",{value:!0});var kQ=lu(),zO=In(),f4=ii(),pO=w4(),GQ={keyword:"properties",type:"object",schemaType:"object",code(i){let{gen:n,schema:r,parentSchema:o,data:t,it:u}=i;if(u.opts.removeAdditional==="all"&&o.additionalProperties===void 0)pO.default.code(new kQ.KeywordCxt(u,pO.default,"additionalProperties"));let l=(0,zO.allSchemaProperties)(r);for(let b of l)u.definedProperties.add(b);if(u.opts.unevaluated&&l.length&&u.props!==!0)u.props=f4.mergeEvaluated.props(n,(0,f4.toHash)(l),u.props);let e=l.filter((b)=>!(0,f4.alwaysValidSchema)(u,r[b]));if(e.length===0)return;let $=n.name("valid");for(let b of e){if(I(b))g(b);else{if(n.if((0,zO.propertyInData)(n,t,b,u.opts.ownProperties)),g(b),!u.allErrors)n.else().var($,!0);n.endIf()}i.it.definedProperties.add(b),i.ok($)}function I(b){return u.opts.useDefaults&&!u.compositeRule&&r[b].default!==void 0}function g(b){i.subschema({keyword:"properties",schemaProp:b,dataProp:b},$)}}};hO.default=GQ});var sO=H((aO)=>{Object.defineProperty(aO,"__esModule",{value:!0});var mO=In(),gv=h(),RO=ii(),xO=ii(),WQ={keyword:"patternProperties",type:"object",schemaType:"object",code(i){let{gen:n,schema:r,data:o,parentSchema:t,it:u}=i,{opts:l}=u,e=(0,mO.allSchemaProperties)(r),$=e.filter((S)=>(0,RO.alwaysValidSchema)(u,r[S]));if(e.length===0||$.length===e.length&&(!u.opts.unevaluated||u.props===!0))return;let I=l.strictSchema&&!l.allowMatchingProperties&&t.properties,g=n.name("valid");if(u.props!==!0&&!(u.props instanceof gv.Name))u.props=(0,xO. Line truncated
`)}var Ct=(i)=>(n,r,o,t)=>{let u=o?{...o,async:!1}:{async:!1},l=n._zod.run({value:r,issues:[]},u);if(l instanceof Promise)throw new Gn;if(l.issues.length){let e=new(t?.Err??i)(l.issues.map(($)=>Zi($,u,Ai())));throw zu(e,t?.callee),e}return l.value},$o=Ct(mi),mt=(i)=>async(n,r,o,t)=>{let u=o?{...o,async:!0}:{async:!0},l=n._zod.run({value:r,issues:[]},u);if(l instanceof Promise)l=await l;if(l.issues.length){let e=new(t?.Err??i)(l.issues.map(($)=>Zi($,u,Ai())));throw zu(e,t?.callee),e}return l.value},Io=mt(mi),Rt=(i)=>(n,r,o)=>{let t=o?{...o,async:!1}:{async:!1},u=n._zod.run({value:r,issues:[]},t);if(u instanceof Promise)throw new Gn;return u.issues.length?{success:!1,error:new(i??lo)(u.issues.map((l)=>Zi(l,t,Ai())))}:{success:!0,data:u.value}},xt=Rt(mi),at=(i)=>async(n,r,o)=>{let t=o?{...o,async:!0}:{async:!0},u=n._zod.run({value:r,issues:[]},t);if(u instanceof Promise)u=await u;return u.issues.length?{success:!1,error:new i(u.issues.map((l)=>Zi(l,t,Ai())))}:{success:!0,data:u.value}},go=at(mi),pu=(i)=>(n,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Ct(i)(n,r,t)},x0=pu(mi),hu=(i)=>(n,r,o)=>{return Ct(i)(n,r,o)},a0=hu(mi),Cu=(i)=>async(n,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return mt(i)(n,r,t)},s0=Cu(mi),mu=(i)=>async(n,r,o)=>{return mt(i)(n,r,o)},iD=mu(mi),Ru=(i)=>(n,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Rt(i)(n,r,t)},nD=Ru(mi),xu=(i)=>(n,r,o)=>{return Rt(i)(n,r,o)},tD=xu(mi),au=(i)=>async(n,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return at(i)(n,r,t)},rD=au(mi),su=(i)=>async(n,r,o)=>{return at(i)(n,r,o)},oD=su(mi);var on={};Fn(on,{xid:()=>J$,uuid7:()=>hj,uuid6:()=>pj,uuid4:()=>zj,uuid:()=>Gt,uppercase:()=>s$,unicodeEmail:()=>uD,undefined:()=>x$,ulid:()=>y$,time:()=>d$,string:()=>p$,sha512_hex:()=>fW,sha512_base64url:()=>UW,sha512_base64:()=>DW,sha384_hex:()=>gW,sha384_base64url:()=>wW,sha384_base64:()=>bW,sha256_hex:()=>vW,sha256_base64url:()=>IW,sha256_base64:()=>$W,sha1_hex:()=>uW,sha1_base64url:()=>eW,sha1_base64:()=>lW,rfc5322Email:()=>mj,number:()=>bo,null:()=>R$,nanoid:()=>Y$,md5_hex:()=>tW,md5_base64url:()=>oW,md5_base64:()=>rW,mac:()=>V$,lowercase:()=>a$,ksuid:()=>X$,ipv6:()=>B$,ipv4:()=>K$,integer:()=>C$,idnEmail:()=>Rj,httpProtocol:()=>T$,html5Email:()=>Cj,hostname:()=>sj,hex:()=>nW,guid:()=>Q$,extendedDuration:()=>dj,emoji:()=>F$,email:()=>H$,e164:()=>Z$,duration:()=>P$,domain:()=>iW,datetime:()=>z$,date:()=>M$,cuid2:()=>W$,cuid:()=>j$,cidrv6:()=>_$,cidrv4:()=>q$,browserEmail:()=>xj,boolean:()=>m$,bigint:()=>h$,base64url:()=>il,base64:()=>E$});var j$=/^[cC][0-9a-z]{6,}$/,W$=/^[0-9a-z]+$/,y$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,J$=/^[0-9a-vA-V]{20}$/,X$=/^[A-Za-z0-9]{27}$/,Y$=/^[a-zA-Z0-9_-]{21}$/,P$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,dj=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Q$=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Gt=(i)=>{if(!i)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${i}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},zj=Gt(4),pj=Gt(6),hj=Gt(7),H$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Cj=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,mj=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,uD=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Rj=uD,xj=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,aj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function F$(){return new RegExp(aj,"u")}var K$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B$=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,V$=(i)=>{let n=en(i??":");return new RegExp(`^(?:[0-9A-F]{2}${n}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${n}){5}[0-9a-f]{2}$`)},q$=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-Line truncated
`).filter((u)=>u),o=Math.min(...r.map((u)=>u.length-u.trimStart().length)),t=r.map((u)=>u.slice(o)).map((u)=>" ".repeat(this.indent*2)+u);for(let u of t)this.content.push(u)}compile(){let i=Function,n=this?.args,o=[...(this?.content??[""]).map((t)=>` ${t}`)];return new i(...n,o.join(`
`))}}var SI={major:4,minor:4,patch:3};var _=U("$ZodType",(i,n)=>{var r;i??(i={}),i._zod.def=n,i._zod.bag=i._zod.bag||{},i._zod.version=SI;let o=[...i._zod.def.checks??[]];if(i._zod.traits.has("$ZodCheck"))o.unshift(i);for(let t of o)for(let u of t._zod.onattach)u(i);if(o.length===0)(r=i._zod).deferred??(r.deferred=[]),i._zod.deferred?.push(()=>{i._zod.run=i._zod.parse});else{let t=(l,e,$)=>{let I=Rn(l),g;for(let b of e){if(b._zod.def.when){if(L$(l))continue;if(!b._zod.def.when(l))continue}else if(I)continue;let w=l.issues.length,f=b._zod.check(l);if(f instanceof Promise&&$?.async===!1)throw new Gn;if(g||f instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await f,l.issues.length===w)return;if(!I)I=Rn(l,w)});else{if(l.issues.length===w)continue;if(!I)I=Rn(l,w)}}if(g)return g.then(()=>{return l});return l},u=(l,e,$)=>{if(Rn(l))return l.aborted=!0,l;let I=t(e,o,$);if(I instanceof Promise){if($.async===!1)throw new Gn;return I.then((g)=>i._zod.parse(g,$))}return i._zod.parse(I,$)};i._zod.run=(l,e)=>{if(e.skipChecks)return i._zod.parse(l,e);if(e.direction==="backward"){let I=i._zod.parse({value:l.value,issues:[]},{...e,skipChecks:!0});if(I instanceof Promise)return I.then((g)=>{return u(g,l,e)});return u(I,l,e)}let $=i._zod.parse(l,e);if($ instanceof Promise){if(e.async===!1)throw new Gn;return $.then((I)=>t(I,o,e))}return t($,o,e)}}C(i,"~standard",()=>({validate:(t)=>{try{let u=xt(i,t);return u.success?{value:u.data}:{issues:u.error?.issues}}catch(u){return go(i,t).then((l)=>l.success?{value:l.data}:{issues:l.error?.issues})}},vendor:"zod",version:1}))}),jt=U("$ZodString",(i,n)=>{_.init(i,n),i._zod.pattern=[...i?._zod.bag?.patterns??[]].pop()??p$(i._zod.bag),i._zod.parse=(r,o)=>{if(n.coerce)try{r.value=String(r.value)}catch(t){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:i}),r}}),vi=U("$ZodStringFormat",(i,n)=>{st.init(i,n),jt.init(i,n)}),AI=U("$ZodGUID",(i,n)=>{n.pattern??(n.pattern=Q$),vi.init(i,n)}),NI=U("$ZodUUID",(i,n)=>{if(n.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[n.version];if(o===void 0)throw Error(`Invalid UUID version: "${n.version}"`);n.pattern??(n.pattern=Gt(o))}else n.pattern??(n.pattern=Gt());vi.init(i,n)}),LI=U("$ZodEmail",(i,n)=>{n.pattern??(n.pattern=H$),vi.init(i,n)}),kI=U("$ZodURL",(i,n)=>{vi.init(i,n),i._zod.check=(r)=>{try{let o=r.value.trim();if(!n.normalize&&n.protocol?.source===T$.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:i,continue:!n.abort});return}}let t=new URL(o);if(n.hostname){if(n.hostname.lastIndex=0,!n.hostname.test(t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:n.hostname.source,input:r.value,inst:i,continue:!n.abort})}if(n.protocol){if(n.protocol.lastIndex=0,!n.protocol.test(t.protocol.endsWith(":")?t.protocol.slice(0,-1):t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:n.protocol.source,input:r.value,inst:i,continue:!n.abort})}if(n.normalize)r.value=t.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:i,continue:!n.abort})}}}),GI=U("$ZodEmoji",(i,n)=>{n.pattern??(n.pattern=F$()),vi.init(i,n)}),jI=U("$ZodNanoID",(i,n)=>{n.pattern??(n.pattern=Y$),vi.init(i,n)}),WI=U("$ZodCUID",(i,n)=>{n.pattern??(n.pattern=j$),vi.init(i,n)}),yI=U("$ZodCUID2",(i,n)=>{n.pattern??(n.pattern=W$),vi.init(i,n)}),JI=U("$ZodULID",(i,n)=>{n.pattern??(n.pattern=y$),vi.init(i,n)}),XI=U("$ZodXID",(i,n)=>{n.pattern??(n.pattern=J$),vi.init(i,n)}),YI=U("$ZodKSUID",(i,n)=>{n.pattern??(n.pattern=X$),vi.init(i,n)}),PI=U("$ZodISODateTime",(i,n)=>{n.pattern??(n.pattern=z$(n)),vi.init(i,n)}),QI=U("$ZodISODate",(i,n)=>{n.pattern??(n.pattern=M$),vi.init(i,n)}),HI=U("$ZodISOTime",(i,n)=>{n.pattern??(n.pattern=d$(n)),vi.init(i,n)}),FI=U("$ZodISODuration",(i,n)=>{n.pattern??(n.pattern=P$),vi.init(i,n)}),KI=U("$ZodIPv4",(i,n)=>{n.pattern??(n.pattern=K$),vi.init(i,n),i._zod.bag.format="ipv4"}),BI=U("$ZodIPv6",(i,n)=>{n.pattern??(n.pattern=B$),vi.init(i,n),i._zod.bag.format="ipv6",i._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:i,continue:!n.abort})}}}),VI=U("$ZodMAC",(i,n)=>{n.pattern??(n.pattern=V$(n.delimiter)),vi.init(i,n),i._zod.bag.format="mac"}),qI=U("$ZodCIDRv4",(i,n)=>{n.pattern??(n.pattern=q$),vi.init(i,n)}),_I=U("$ZodCIDRv6",(i,n)=>{n.pattern??(n.pattern=_$),vi.init(i,n),i._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[t,u]=o;if(!u)throw Error();let l=Number(u);if(`${l}`!==u)throw Error();if(l<0||l>128)throw Error();new URL(`http://[${t}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:i,continue:!n.abort})}}});function EI(i){if(i==="")return!0;if(/\s/.test(i))return!1;if(i.length%4!==0)return!1;try{return atob(i),!0}catch{return!1}}var Line truncated
if (${y}.issues.length) {
if (${k} in input) {
payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
depsCount: ${i},
deps: ${r}}`};var bP={keyword:"dependencies",type:"object",schemaType:"object",error:KO.error,code(n){let[i,r]=wP(n);FO(n,i),hO(n,r)}};function wP({schema:n}){let i={},r={};for(let o in n){if(o==="__proto__")continue;let t=Array.isArray(n[o])?i:r;t[o]=n[o]}return[i,r]}function FO(n,i=n.schema){let{gen:r,data:o,it:t}=n;if(Object.keys(i).length===0)return;let u=r.let("missing");for(let e in i){let l=i[e];if(l.length===0)continue;let $=(0,Su.propertyInData)(r,o,e,t.opts.ownProperties);if(n.setParams({property:e,depsCount:l.length,deps:l.join(", ")}),t.allErrors)r.if($,()=>{for(let I of l)(0,Su.checkReportMissingProp)(n,I)});else r.if(bc._`${$} && (${(0,Su.checkMissingProp)(n,l,u)})`),(0,Su.reportMissingProp)(n,u),r.else()}}KO.validatePropertyDeps=FO;function hO(n,i=n.schema){let{gen:r,data:o,keyword:t,it:u}=n,e=r.name("valid");for(let l in i){if((0,gP.alwaysValidSchema)(u,i[l]))continue;r.if((0,Su.propertyInData)(r,o,l,u.opts.ownProperties),()=>{let $=n.subschema({keyword:t,schemaProp:l},e);n.mergeValidEvaluated($,e)},()=>r.var(e,!0)),n.ok(e)}}KO.validateSchemaDeps=hO;KO.default=bP});var _O=P((TO)=>{Object.defineProperty(TO,"__esModule",{value:!0});var qO=z(),DP=nn(),UP={message:"property name must be valid",params:({params:n})=>qO._`{propertyName: ${n.propertyName}}`},SP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:UP,code(n){let{gen:i,schema:r,data:o,it:t}=n;if((0,DP.alwaysValidSchema)(t,r))return;let u=i.name("valid");i.forIn("key",o,(e)=>{n.setParams({propertyName:e}),n.subschema({keyword:"propertyNames",data:e,dataTypes:["string"],propertyName:e,compositeRule:!0},u),i.if((0,qO.not)(u),()=>{if(n.error(!0),!t.allErrors)i.break()})}),n.ok(u)}};TO.default=SP});var wc=P((EO)=>{Object.defineProperty(EO,"__esModule",{value:!0});var $v=Ii(),Oi=z(),AP=Vi(),Iv=nn(),NP={message:"must NOT have additional properties",params:({params:n})=>Oi._`{additionalProperty: ${n.additionalProperty}}`},LP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:NP,code(n){let{gen:i,schema:r,parentSchema:o,data:t,errsCount:u,it:e}=n;if(!u)throw Error("ajv implementation error");let{allErrors:l,opts:$}=e;if(e.props=!0,$.removeAdditional!=="all"&&(0,Iv.alwaysValidSchema)(e,r))return;let I=(0,$v.allSchemaProperties)(o.properties),g=(0,$v.allSchemaProperties)(o.patternProperties);b(),n.ok(Oi._`${u} === ${AP.default.errors}`);function b(){i.forIn("key",t,(N)=>{if(!I.length&&!g.length)c(N);else i.if(w(N),()=>c(N))})}function w(N){let L;if(I.length>8){let K=(0,Iv.schemaRefOrVal)(e,o.properties,"properties");L=(0,$v.isOwnProperty)(i,K,N)}else if(I.length)L=(0,Oi.or)(...I.map((K)=>Oi._`${N} === ${K}`));else L=Oi.nil;if(g.length)L=(0,Oi.or)(L,...g.map((K)=>Oi._`${(0,$v.usePattern)(n,K)}.test(${N})`));return(0,Oi.not)(L)}function f(N){i.code(Oi._`delete ${t}[${N}]`)}function c(N){if($.removeAdditional==="all"||$.removeAdditional&&r===!1){f(N);return}if(r===!1){if(n.setParams({additionalProperty:N}),n.error(),!l)i.break();return}if(typeof r=="object"&&!(0,Iv.alwaysValidSchema)(e,r)){let L=i.name("valid");if($.removeAdditional==="failing")S(N,L,!1),i.if((0,Oi.not)(L),()=>{n.reset(),f(N)});else if(S(N,L),!l)i.if((0,Oi.not)(L),()=>i.break())}}function S(N,L,K){let H={keyword:"additionalProperties",dataProp:N,dataPropType:Iv.Type.Str};if(K===!1)Object.assign(H,{compositeRule:!0,createErrors:!1,allErrors:!1});n.subschema(H,L)}}};EO.default=LP});var mO=P((zO)=>{Object.defineProperty(zO,"__esModule",{value:!0});var kP=eu(),ZO=Ii(),fc=nn(),MO=wc(),dP={keyword:"properties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,parentSchema:o,data:t,it:u}=n;if(u.opts.removeAdditional==="all"&&o.additionalProperties===void 0)MO.default.code(new kP.KeywordCxt(u,MO.default,"additionalProperties"));let e=(0,ZO.allSchemaProperties)(r);for(let b of e)u.definedProperties.add(b);if(u.opts.unevaluated&&e.length&&u.props!==!0)u.props=fc.mergeEvaluated.props(i,(0,fc.toHash)(e),u.props);let l=e.filter((b)=>!(0,fc.alwaysValidSchema)(u,r[b]));if(l.length===0)return;let $=i.name("valid");for(let b of l){if(I(b))g(b);else{if(i.if((0,ZO.propertyInData)(i,t,b,u.opts.ownProperties)),g(b),!u.allErrors)i.else().var($,!0);i.endIf()}n.it.definedProperties.add(b),n.ok($)}function I(b){return u.opts.useDefaults&&!u.compositeRule&&r[b].default!==void 0}function g(b){n.subschema({keyword:"properties",schemaProp:b,dataProp:b},$)}}};zO.default=dP});var sO=P((aO)=>{Object.defineProperty(aO,"__esModule",{value:!0});var CO=Ii(),gv=z(),RO=nn(),xO=nn(),jP={keyword:"patternProperties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,data:o,parentSchema:t,it:u}=n,{opts:e}=u,l=(0,CO.allSchemaProperties)(r),$=l.filter((S)=>(0,RO.alwaysValidSchema)(u,r[S]));if(l.length===0||$.length===l.length&&(!u.opts.unevaluated||u.props===!0))return;let I=e.strictSchema&&!e.allowMatchingProperties&&t.properties,g=i.name("valid");if(u.props!==!0&&!(u.props instanceof gv.Name))u.props=(0,xO. Line truncated
`)}var mt=(n)=>(i,r,o,t)=>{let u=o?{...o,async:!1}:{async:!1},e=i._zod.run({value:r,issues:[]},u);if(e instanceof Promise)throw new ki;if(e.issues.length){let l=new(t?.Err??n)(e.issues.map(($)=>_n($,u,Nn())));throw Zu(l,t?.callee),l}return e.value},$o=mt(Rn),Ct=(n)=>async(i,r,o,t)=>{let u=o?{...o,async:!0}:{async:!0},e=i._zod.run({value:r,issues:[]},u);if(e instanceof Promise)e=await e;if(e.issues.length){let l=new(t?.Err??n)(e.issues.map(($)=>_n($,u,Nn())));throw Zu(l,t?.callee),l}return e.value},Io=Ct(Rn),Rt=(n)=>(i,r,o)=>{let t=o?{...o,async:!1}:{async:!1},u=i._zod.run({value:r,issues:[]},t);if(u instanceof Promise)throw new ki;return u.issues.length?{success:!1,error:new(n??eo)(u.issues.map((e)=>_n(e,t,Nn())))}:{success:!0,data:u.value}},xt=Rt(Rn),at=(n)=>async(i,r,o)=>{let t=o?{...o,async:!0}:{async:!0},u=i._zod.run({value:r,issues:[]},t);if(u instanceof Promise)u=await u;return u.issues.length?{success:!1,error:new n(u.issues.map((e)=>_n(e,t,Nn())))}:{success:!0,data:u.value}},go=at(Rn),Mu=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return mt(n)(i,r,t)},x4=Mu(Rn),zu=(n)=>(i,r,o)=>{return mt(n)(i,r,o)},a4=zu(Rn),mu=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Ct(n)(i,r,t)},s4=mu(Rn),Cu=(n)=>async(i,r,o)=>{return Ct(n)(i,r,o)},n0=Cu(Rn),Ru=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Rt(n)(i,r,t)},i0=Ru(Rn),xu=(n)=>(i,r,o)=>{return Rt(n)(i,r,o)},t0=xu(Rn),au=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return at(n)(i,r,t)},r0=au(Rn),su=(n)=>async(i,r,o)=>{return at(n)(i,r,o)},o0=su(Rn);var oi={};Qi(oi,{xid:()=>W$,uuid7:()=>md,uuid6:()=>zd,uuid4:()=>Md,uuid:()=>kt,uppercase:()=>s$,unicodeEmail:()=>u0,undefined:()=>x$,ulid:()=>j$,time:()=>E$,string:()=>M$,sha512_hex:()=>cG,sha512_base64url:()=>UG,sha512_base64:()=>DG,sha384_hex:()=>bG,sha384_base64url:()=>fG,sha384_base64:()=>wG,sha256_hex:()=>$G,sha256_base64url:()=>gG,sha256_base64:()=>IG,sha1_hex:()=>eG,sha1_base64url:()=>vG,sha1_base64:()=>lG,rfc5322Email:()=>Rd,number:()=>bo,null:()=>R$,nanoid:()=>X$,md5_hex:()=>rG,md5_base64url:()=>uG,md5_base64:()=>oG,mac:()=>K$,lowercase:()=>a$,ksuid:()=>J$,ipv6:()=>h$,ipv4:()=>F$,integer:()=>m$,idnEmail:()=>xd,httpProtocol:()=>q$,html5Email:()=>Cd,hostname:()=>nG,hex:()=>tG,guid:()=>H$,extendedDuration:()=>Zd,emoji:()=>Q$,email:()=>P$,e164:()=>T$,duration:()=>Y$,domain:()=>iG,datetime:()=>Z$,date:()=>_$,cuid2:()=>G$,cuid:()=>d$,cidrv6:()=>p$,cidrv4:()=>B$,browserEmail:()=>ad,boolean:()=>C$,bigint:()=>z$,base64url:()=>ne,base64:()=>V$});var d$=/^[cC][0-9a-z]{6,}$/,G$=/^[0-9a-z]+$/,j$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,W$=/^[0-9a-vA-V]{20}$/,J$=/^[A-Za-z0-9]{27}$/,X$=/^[a-zA-Z0-9_-]{21}$/,Y$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Zd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,H$=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,kt=(n)=>{if(!n)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Md=kt(4),zd=kt(6),md=kt(7),P$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Cd=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Rd=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,u0=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,xd=u0,ad=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,sd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Q$(){return new RegExp(sd,"u")}var F$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,h$=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,K$=(n)=>{let i=li(n??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},B$=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-Line truncated
`).filter((u)=>u),o=Math.min(...r.map((u)=>u.length-u.trimStart().length)),t=r.map((u)=>u.slice(o)).map((u)=>" ".repeat(this.indent*2)+u);for(let u of t)this.content.push(u)}compile(){let n=Function,i=this?.args,o=[...(this?.content??[""]).map((t)=>` ${t}`)];return new n(...i,o.join(`
`))}}var SI={major:4,minor:4,patch:3};var p=D("$ZodType",(n,i)=>{var r;n??(n={}),n._zod.def=i,n._zod.bag=n._zod.bag||{},n._zod.version=SI;let o=[...n._zod.def.checks??[]];if(n._zod.traits.has("$ZodCheck"))o.unshift(n);for(let t of o)for(let u of t._zod.onattach)u(n);if(o.length===0)(r=n._zod).deferred??(r.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let t=(e,l,$)=>{let I=Ri(e),g;for(let b of l){if(b._zod.def.when){if(L$(e))continue;if(!b._zod.def.when(e))continue}else if(I)continue;let w=e.issues.length,f=b._zod.check(e);if(f instanceof Promise&&$?.async===!1)throw new ki;if(g||f instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await f,e.issues.length===w)return;if(!I)I=Ri(e,w)});else{if(e.issues.length===w)continue;if(!I)I=Ri(e,w)}}if(g)return g.then(()=>{return e});return e},u=(e,l,$)=>{if(Ri(e))return e.aborted=!0,e;let I=t(l,o,$);if(I instanceof Promise){if($.async===!1)throw new ki;return I.then((g)=>n._zod.parse(g,$))}return n._zod.parse(I,$)};n._zod.run=(e,l)=>{if(l.skipChecks)return n._zod.parse(e,l);if(l.direction==="backward"){let I=n._zod.parse({value:e.value,issues:[]},{...l,skipChecks:!0});if(I instanceof Promise)return I.then((g)=>{return u(g,e,l)});return u(I,e,l)}let $=n._zod.parse(e,l);if($ instanceof Promise){if(l.async===!1)throw new ki;return $.then((I)=>t(I,o,l))}return t($,o,l)}}m(n,"~standard",()=>({validate:(t)=>{try{let u=xt(n,t);return u.success?{value:u.data}:{issues:u.error?.issues}}catch(u){return go(n,t).then((e)=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),dt=D("$ZodString",(n,i)=>{p.init(n,i),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??M$(n._zod.bag),n._zod.parse=(r,o)=>{if(i.coerce)try{r.value=String(r.value)}catch(t){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:n}),r}}),$n=D("$ZodStringFormat",(n,i)=>{st.init(n,i),dt.init(n,i)}),AI=D("$ZodGUID",(n,i)=>{i.pattern??(i.pattern=H$),$n.init(n,i)}),NI=D("$ZodUUID",(n,i)=>{if(i.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[i.version];if(o===void 0)throw Error(`Invalid UUID version: "${i.version}"`);i.pattern??(i.pattern=kt(o))}else i.pattern??(i.pattern=kt());$n.init(n,i)}),LI=D("$ZodEmail",(n,i)=>{i.pattern??(i.pattern=P$),$n.init(n,i)}),yI=D("$ZodURL",(n,i)=>{$n.init(n,i),n._zod.check=(r)=>{try{let o=r.value.trim();if(!i.normalize&&i.protocol?.source===q$.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:n,continue:!i.abort});return}}let t=new URL(o);if(i.hostname){if(i.hostname.lastIndex=0,!i.hostname.test(t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:i.hostname.source,input:r.value,inst:n,continue:!i.abort})}if(i.protocol){if(i.protocol.lastIndex=0,!i.protocol.test(t.protocol.endsWith(":")?t.protocol.slice(0,-1):t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:i.protocol.source,input:r.value,inst:n,continue:!i.abort})}if(i.normalize)r.value=t.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:n,continue:!i.abort})}}}),kI=D("$ZodEmoji",(n,i)=>{i.pattern??(i.pattern=Q$()),$n.init(n,i)}),dI=D("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=X$),$n.init(n,i)}),GI=D("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=d$),$n.init(n,i)}),jI=D("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=G$),$n.init(n,i)}),WI=D("$ZodULID",(n,i)=>{i.pattern??(i.pattern=j$),$n.init(n,i)}),JI=D("$ZodXID",(n,i)=>{i.pattern??(i.pattern=W$),$n.init(n,i)}),XI=D("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=J$),$n.init(n,i)}),YI=D("$ZodISODateTime",(n,i)=>{i.pattern??(i.pattern=Z$(i)),$n.init(n,i)}),HI=D("$ZodISODate",(n,i)=>{i.pattern??(i.pattern=_$),$n.init(n,i)}),PI=D("$ZodISOTime",(n,i)=>{i.pattern??(i.pattern=E$(i)),$n.init(n,i)}),QI=D("$ZodISODuration",(n,i)=>{i.pattern??(i.pattern=Y$),$n.init(n,i)}),FI=D("$ZodIPv4",(n,i)=>{i.pattern??(i.pattern=F$),$n.init(n,i),n._zod.bag.format="ipv4"}),hI=D("$ZodIPv6",(n,i)=>{i.pattern??(i.pattern=h$),$n.init(n,i),n._zod.bag.format="ipv6",n._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:n,continue:!i.abort})}}}),KI=D("$ZodMAC",(n,i)=>{i.pattern??(i.pattern=K$(i.delimiter)),$n.init(n,i),n._zod.bag.format="mac"}),BI=D("$ZodCIDRv4",(n,i)=>{i.pattern??(i.pattern=B$),$n.init(n,i)}),pI=D("$ZodCIDRv6",(n,i)=>{i.pattern??(i.pattern=p$),$n.init(n,i),n._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[t,u]=o;if(!u)throw Error();let e=Number(u);if(`${e}`!==u)throw Error();if(e<0||e>128)throw Error();new URL(`http://[${t}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:n,continue:!i.abort})}}});function VI(n){if(n==="")return!0;if(/\s/.test(n))return!1;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}var Line truncated
if (${j}.issues.length) {
if (${y} in input) {
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
...iss,
path: iss.path ? [${k}, ...iss.path] : [${k}]
path: iss.path ? [${y}, ...iss.path] : [${y}]
})));
}
}
if (${y}.value === undefined) {
if (${k} in input) {
newResult[${k}] = undefined;
if (${j}.value === undefined) {
if (${y} in input) {
newResult[${y}] = undefined;
}
} else {
newResult[${k}] = ${y}.value;
newResult[${y}] = ${j}.value;
}
`);else if(!x)f.write(`
const ${y}_present = ${k} in input;
if (${y}.issues.length) {
payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
const ${j}_present = ${y} in input;
if (${j}.issues.length) {
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
...iss,
path: iss.path ? [${k}, ...iss.path] : [${k}]
path: iss.path ? [${y}, ...iss.path] : [${y}]
})));
}
if (!${y}_present && !${y}.issues.length) {
if (!${j}_present && !${j}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${k}]
path: [${y}]
});
}
if (${y}_present) {
if (${y}.value === undefined) {
newResult[${k}] = undefined;
if (${j}_present) {
if (${j}.value === undefined) {
newResult[${y}] = undefined;
} else {
newResult[${k}] = ${y}.value;
newResult[${y}] = ${j}.value;
}
}
`);else f.write(`
if (${y}.issues.length) {
payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
if (${j}.issues.length) {
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
...iss,
path: iss.path ? [${k}, ...iss.path] : [${k}]
path: iss.path ? [${y}, ...iss.path] : [${y}]
})));
}
if (${y}.value === undefined) {
if (${k} in input) {
newResult[${k}] = undefined;
if (${j}.value === undefined) {
if (${y} in input) {
newResult[${y}] = undefined;
}
} else {
newResult[${k}] = ${y}.value;
newResult[${y}] = ${j}.value;
}
`)}f.write("payload.value = newResult;"),f.write("return payload;");let V=f.compile();return(Q,y)=>V(w,Q,y)},u,l=kt,e=!Nt.jitless,I=e&&U$.value,g=n.catchall,b;i._zod.parse=(w,f)=>{b??(b=o.value);let D=w.value;if(!l(D))return w.issues.push({expected:"object",code:"invalid_type",input:D,inst:i}),w;if(e&&I&&f?.async===!1&&f.jitless!==!0){if(!u)u=t(n.shape);if(w=u(w,f),!g)return w;return JD([],D,w,f,b,i)}return r(w,f)}});function bD(i,n,r,o){for(let u of i)if(u.issues.length===0)return n.value=u.value,n;let t=i.filter((u)=>!Rn(u));if(t.length===1)return n.value=t[0].value,t[0];return n.issues.push({code:"invalid_union",input:n.value,inst:r,errors:i.map((u)=>u.issues.map((l)=>Zi(l,o,Ai())))}),n}var Uo=U("$ZodUnion",(i,n)=>{_.init(i,n),C(i._zod,"optin",()=>n.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),C(i._zod,"optout",()=>n.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),C(i._zod,"values",()=>{if(n.options.every((o)=>o._zod.values))return new Set(n.options.flatMap((o)=>Array.from(o._zod.values)));return}),C(i._zod,"pattern",()=>{if(n.options.every((o)=>o._zod.pattern)){let o=n.options.map((t)=>t._zod.pattern);return new RegExp(`^(${o.map((t)=>to(t.source)).join("|")})$`)}return});let r=n.options.length===1?n.options[0]._zod.run:null;i._zod.parse=(o,t)=>{if(r)return r(o,t);let u=!1,l=[];for(let e of n.options){let $=e._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)l.push($),u=!0;else{if($.issues.length===0)return $;l.push($)}}if(!u)return bD(l,o,i,t);return Promise.all(l).then((e)=>{return bD(e,o,i,t)})}});function wD(i,n,r,o){let t=i.filter((u)=>u.issues.length===0);if(t.length===1)return n.value=t[0].value,n;if(t.length===0)n.issues.push({code:"invalid_union",input:n.value,inst:r,errors:i.map((u)=>u.issues.map((l)=>Zi(l,o,Ai())))});else n.issues.push({code:"invalid_union",input:n.value,inst:r,errors:[],inclusive:!1});return n}var og=U("$ZodXor",(i,n)=>{Uo.init(i,n),n.inclusive=!1;let r=n.options.length===1?n.options[0]._zod.run:null;i._zod.parse=(o,t)=>{if(r)return r(o,t);let u=!1,l=[];for(let e of n.options){let $=e._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)l.push($),u=!0;else l.push($)}if(!u)return wD(l,o,i,t);return Promise.all(l).then((e)=>{return wD(e,o,i,t)})}}),ug=U("$ZodDiscriminatedUnion",(i,n)=>{n.inclusive=!1,Uo.init(i,n);let r=i._zod.parse;C(i._zod,"propValues",()=>{let t={};for(let u of n.options){let l=u._zod.propValues;if(!l||Object.keys(l).length===0)throw Error(`Invalid discriminated union option at index "${n.options.indexOf(u)}"`);for(let[e,$]of Object.entries(l)){if(!t[e])t[e]=new Set;for(let I of $)t[e].add(I)}}return t});let o=pt(()=>{let t=n.options,u=new Map;for(let l of t){let e=l._zod.propValues?.[n.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${n.options.indexOf(l)}"`);for(let $ of e){if(u.has($))throw Error(`Duplicate discriminator value "${String($)}"`);u.set($,l)}}return u});i._zod.parse=(t,u)=>{let l=t.value;if(!kt(l))return t.issues.push({code:"invalid_type",expected:"object",input:l,inst:i}),t;let e=o.value.get(l?.[n.discriminator]);if(e)return e._zod.run(t,u);if(n.unionFallback||u.direction==="backward")return r(t,u);return t.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:n.discriminator,options:Array.from(o.value.keys()),input:l,path:[n.discriminator],inst:i}),t}}),lg=U("$ZodIntersection",(i,n)=>{_.init(i,n),i._zod.parse=(r,o)=>{let t=r.value,u=n.left._zod.run({value:t,issues:[]},o),l=n.right._zod.run({value:t,issues:[]},o);if(u instanceof Promise||l instanceof Promise)return Promise.all([u,l]).then(([$,I])=>{return fD(r,$,I)});return fD(r,u,l)}});function OI(i,n){if(i===n)return{valid:!0,data:i};if(i instanceof Date&&n instanceof Date&&+i===+n)return{valid:!0,data:i};if(mn(i)&&mn(n)){let r=Object.keys(n),o=Object.keys(i).filter((u)=>r.indexOf(u)!==-1),t={...i,...n};for(let u of o){let l=OI(i[u],n[u]);if(!l.valid)return{valid:!1,mergeErrorPath:[u,...l.mergeErrorPath]};t[u]=l.data}return{valid:!0,data:t}}if(Array.isArray(i)&&Array.isArray(n)){if(i.length!==n.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<i.length;o++){let t=i[o],u=n[o],l=OI(t,u);if(!l.valid)return{valid:!1,mergeErrorPath:[o,...l.mergeErrorPath]};r.push(l.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function fD(i,n,r){let o=new Map,t;for(let e of n.issues)if(e.code==="unrecognized_keys"){t??(t=e);for(let $ of e.keys){if(!o.has($))o.set($,{});o.get($).l=!0}}else i.issues.push(e);for(let e of r.issues)if(e.code==="unrecognized_keys")for(let $ of e.keys){if(!o.has($))o.set($,{});o.get($).r=!0}else i.issues.push(e);let u=[...o].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(u.length&&t)i.issues.push({...t,keys:u});if(Rn(i))return i;let l=OI(n.value,r.value);if(!l.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`);return i.value=l.data,i}var Il=U("$ZodTuple",(i,n)=>{_.init(i,n Line truncated
`)}f.write("payload.value = newResult;"),f.write("return payload;");let K=f.compile();return(H,j)=>K(w,H,j)},u,e=yt,l=!Nt.jitless,I=l&&D$.value,g=i.catchall,b;n._zod.parse=(w,f)=>{b??(b=o.value);let c=w.value;if(!e(c))return w.issues.push({expected:"object",code:"invalid_type",input:c,inst:n}),w;if(l&&I&&f?.async===!1&&f.jitless!==!0){if(!u)u=t(i.shape);if(w=u(w,f),!g)return w;return W0([],c,w,f,b,n)}return r(w,f)}});function b0(n,i,r,o){for(let u of n)if(u.issues.length===0)return i.value=u.value,i;let t=n.filter((u)=>!Ri(u));if(t.length===1)return i.value=t[0].value,t[0];return i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((u)=>u.issues.map((e)=>_n(e,o,Nn())))}),i}var Do=D("$ZodUnion",(n,i)=>{p.init(n,i),m(n._zod,"optin",()=>i.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),m(n._zod,"optout",()=>i.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),m(n._zod,"values",()=>{if(i.options.every((o)=>o._zod.values))return new Set(i.options.flatMap((o)=>Array.from(o._zod.values)));return}),m(n._zod,"pattern",()=>{if(i.options.every((o)=>o._zod.pattern)){let o=i.options.map((t)=>t._zod.pattern);return new RegExp(`^(${o.map((t)=>to(t.source)).join("|")})$`)}return});let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let u=!1,e=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)e.push($),u=!0;else{if($.issues.length===0)return $;e.push($)}}if(!u)return b0(e,o,n,t);return Promise.all(e).then((l)=>{return b0(l,o,n,t)})}});function w0(n,i,r,o){let t=n.filter((u)=>u.issues.length===0);if(t.length===1)return i.value=t[0].value,i;if(t.length===0)i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((u)=>u.issues.map((e)=>_n(e,o,Nn())))});else i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:[],inclusive:!1});return i}var og=D("$ZodXor",(n,i)=>{Do.init(n,i),i.inclusive=!1;let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let u=!1,e=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)e.push($),u=!0;else e.push($)}if(!u)return w0(e,o,n,t);return Promise.all(e).then((l)=>{return w0(l,o,n,t)})}}),ug=D("$ZodDiscriminatedUnion",(n,i)=>{i.inclusive=!1,Do.init(n,i);let r=n._zod.parse;m(n._zod,"propValues",()=>{let t={};for(let u of i.options){let e=u._zod.propValues;if(!e||Object.keys(e).length===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(u)}"`);for(let[l,$]of Object.entries(e)){if(!t[l])t[l]=new Set;for(let I of $)t[l].add(I)}}return t});let o=Mt(()=>{let t=i.options,u=new Map;for(let e of t){let l=e._zod.propValues?.[i.discriminator];if(!l||l.size===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(e)}"`);for(let $ of l){if(u.has($))throw Error(`Duplicate discriminator value "${String($)}"`);u.set($,e)}}return u});n._zod.parse=(t,u)=>{let e=t.value;if(!yt(e))return t.issues.push({code:"invalid_type",expected:"object",input:e,inst:n}),t;let l=o.value.get(e?.[i.discriminator]);if(l)return l._zod.run(t,u);if(i.unionFallback||u.direction==="backward")return r(t,u);return t.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:i.discriminator,options:Array.from(o.value.keys()),input:e,path:[i.discriminator],inst:n}),t}}),eg=D("$ZodIntersection",(n,i)=>{p.init(n,i),n._zod.parse=(r,o)=>{let t=r.value,u=i.left._zod.run({value:t,issues:[]},o),e=i.right._zod.run({value:t,issues:[]},o);if(u instanceof Promise||e instanceof Promise)return Promise.all([u,e]).then(([$,I])=>{return f0(r,$,I)});return f0(r,u,e)}});function OI(n,i){if(n===i)return{valid:!0,data:n};if(n instanceof Date&&i instanceof Date&&+n===+i)return{valid:!0,data:n};if(Ci(n)&&Ci(i)){let r=Object.keys(i),o=Object.keys(n).filter((u)=>r.indexOf(u)!==-1),t={...n,...i};for(let u of o){let e=OI(n[u],i[u]);if(!e.valid)return{valid:!1,mergeErrorPath:[u,...e.mergeErrorPath]};t[u]=e.data}return{valid:!0,data:t}}if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<n.length;o++){let t=n[o],u=i[o],e=OI(t,u);if(!e.valid)return{valid:!1,mergeErrorPath:[o,...e.mergeErrorPath]};r.push(e.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function f0(n,i,r){let o=new Map,t;for(let l of i.issues)if(l.code==="unrecognized_keys"){t??(t=l);for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).l=!0}}else n.issues.push(l);for(let l of r.issues)if(l.code==="unrecognized_keys")for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).r=!0}else n.issues.push(l);let u=[...o].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(u.length&&t)n.issues.push({...t,keys:u});if(Ri(n))return n;let e=OI(i.value,r.value);if(!e.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(e.mergeErrorPath)}`);return n.value=e.data,n}var Ie=D("$ZodTuple",(n,i)=>{p.init(n,i Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of i.seen.entries()){let e=l[1];if(n===l[0]){u(l);continue}if(i.external){let I=i.external.registry.get(l[0])?.id;if(n!==l[0]&&I){u(l);continue}}if(i.metadataRegistry.get(l[0])?.id){u(l);continue}if(e.cycle){u(l);continue}if(e.count>1){if(i.reused==="ref"){u(l);continue}}}}function nt(i,n){let r=i.seen.get(n);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(e)=>{let $=i.seen.get(e);if($.ref===null)return;let I=$.def??$.schema,g={...I},b=$.ref;if($.ref=null,b){o(b);let f=i.seen.get(b),D=f.schema;if(D.$ref&&(i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"))I.allOf=I.allOf??[],I.allOf.push(D);else Object.assign(I,D);if(Object.assign(I,g),e._zod.parent===b)for(let N in I){if(N==="$ref"||N==="allOf")continue;if(!(N in g))delete I[N]}if(D.$ref&&f.def)for(let N in I){if(N==="$ref"||N==="allOf")continue;if(N in f.def&&JSON.stringify(I[N])===JSON.stringify(f.def[N]))delete I[N]}}let w=e._zod.parent;if(w&&w!==b){o(w);let f=i.seen.get(w);if(f?.schema.$ref){if(I.$ref=f.schema.$ref,f.def)for(let D in I){if(D==="$ref"||D==="allOf")continue;if(D in f.def&&JSON.stringify(I[D])===JSON.stringify(f.def[D]))delete I[D]}}}i.override({zodSchema:e,jsonSchema:I,path:$.path??[]})};for(let e of[...i.seen.entries()].reverse())o(e[0]);let t={};if(i.target==="draft-2020-12")t.$schema="https://json-schema.org/draft/2020-12/schema";else if(i.target==="draft-07")t.$schema="http://json-schema.org/draft-07/schema#";else if(i.target==="draft-04")t.$schema="http://json-schema.org/draft-04/schema#";else if(i.target==="openapi-3.0");if(i.external?.uri){let e=i.external.registry.get(n)?.id;if(!e)throw Error("Schema is missing an `id` property");t.$id=i.external.uri(e)}Object.assign(t,r.def??r.schema);let u=i.metadataRegistry.get(n)?.id;if(u!==void 0&&t.id===u)delete t.id;let l=i.external?.defs??{};for(let e of i.seen.entries()){let $=e[1];if($.def&&$.defId){if($.def.id===$.defId)delete $.def.id;l[$.defId]=$.def}}if(i.external);else if(Object.keys(l).length>0)if(i.target==="draft-2020-12")t.$defs=l;else t.definitions=l;try{let e=JSON.parse(JSON.stringify(t));return Object.defineProperty(e,"~standard",{value:{...n["~standard"],jsonSchema:{input:fr(n,"input",i.processors),output:fr(n,"output",i.processors)}},enumerable:!1,writable:!1}),e}catch(e){throw Error("Error converting schema to JSON.")}}function di(i,n){let r=n??{seen:new Set};if(r.seen.has(i))return!1;r.seen.add(i);let o=i._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return di(o.element,r);if(o.type==="set")return di(o.valueType,r);if(o.type==="lazy")return di(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return di(o.innerType,r);if(o.type==="intersection")return di(o.left,r)||di(o.right,r);if(o.type==="record"||o.type==="map")return di(o.keyType,r)||di(o.valueType,r);if(o.type==="pipe"){if(i._zod.traits.has("$ZodCodec"))return!0;return di(o.in,r)||di(o.out,r)}if(o.type==="object"){for(let t in o.shape)if(di(o.shape[t],r))return!0;return!1}if(o.type==="union"){for(let t of o.options)if(di(t,r))return!0;return!1}if(o.type==="tuple"){for(let t of o.items)if(di(t,r))return!0;if(o.rest&&di(o.rest,r))return!0;return!1}return!1}var bw=(i,n={})=>(r)=>{let o=sn({...r,processors:n});return ui(i,o),it(o,i),nt(o,i)},fr=(i,n,r={})=>(o)=>{let{libraryOptions:t,target:u}=o??{},l=sn({...t??{},target:u,io:n,processors:r});return ui(i,l),it(l,i),nt(l,i)};var qy={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ww=(i,n,r,o)=>{let t=r;t.type="string";let{minimum:u,maximum:l,format:e,patterns:$,contentEncoding:I}=i._zod.bag;if(typeof u==="number")t.minLength=u;if(typeof l==="number")t.maxLength=l;if(e){if(t.format=qy[e]??e,t.format==="")delete t.format;if(e==="time")delete t.format}if(I)t.contentEncoding=I;if($&&$.size>0){let g=[...$];if(g.length===1)t.pattern=g[0].source;else if(g.length>1)t.allOf=[...g.map((b)=>({...n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))]}},fw=(i,n,r,o)=>{let t=r,{minimum:u,maximum:l,format:e,multipleOf:$,exclusiveMaximum:I,exclusiveMinimum:g}=i._zod.bag;if(typeof e==="string"&&e.includes("int"))t.type="integer";else t.type="number";let b=typeof g==="number"&&g>=(u??Number.NEGATIVE_INFINITY),w=typeof I==="number"&&I<=(l??Number.POSITIVE_INFINITY),f=n.target==="draft-04"||n.target==="openapi-3.0";if(b)if(f)t.minimum=g,t.exclusiveMinimum=!0;else t.exclusiveMinimum=g;else if(typeof u==="number")t.minimum=u;if(w)if(f)t.maximum=I,t.exclusiveMaximum=!0;else t.exclusiveMaximum=I;else if(typeof l==="number")t.maximum=l;if(typeof $==="number")t.multipleOf=$},Dw=(i,n,r,o)=>{r.type="boolean"},Uw=(i,n,r,o)=>{if(n.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},cw=(i,n,r,o)=>{if(n.unrepresentable==="Line truncated
`);if(i===-1)return null;let n=this._buffer.toString("utf8",0,i).replace(/\r$/,"");return this._buffer=this._buffer.subarray(i+1),lF(n)}clear(){this._buffer=void 0}}function lF(i){return u1.parse(JSON.parse(i))}function nN(i){return JSON.stringify(i)+`
`}class P4{constructor(i=tN.stdin,n=tN.stdout){this._stdin=i,this._stdout=n,this._readBuffer=new Y4,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}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 i=this._readBuffer.readMessage();if(i===null)break;this.onmessage?.(i)}catch(i){this.onerror?.(i)}}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(i){return new Promise((n)=>{let r=nN(i);if(this._stdout.write(r))n();else this._stdout.once("drain",n)})}}import{dirname as _0,join as DB}from"node:path";import{fileURLToPath as UB}from"node:url";class Mn extends Error{name="KyError";get isKyError(){return!0}}class tn extends Mn{name="HTTPError";response;request;options;data;constructor(i,n,r){let o=i.status||i.status===0?i.status:"",t=i.statusText??"",u=`${o} ${t}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${n.method} ${n.url}`);this.response=i,this.request=n,this.options=r}}class Nu extends Mn{name="NetworkError";request;constructor(i,n){super(`Request failed due to a network error: ${i.method} ${i.url}`,n);this.request=i}}class Lu extends Error{name="NonError";value;constructor(i){let n="Non-error value was thrown";try{if(typeof i==="string")n=i;else if(i&&typeof i==="object"&&"message"in i&&typeof i.message==="string")n=i.message}catch{}super(n);this.value=i}}class Tr extends Mn{name="ForceRetryError";customDelay;code;customRequest;constructor(i){let n=i?.cause?i.cause instanceof Error?i.cause:new Lu(i.cause):void 0;super(i?.code?`Forced retry: ${i.code}`:"Forced retry",n?{cause:n}:void 0);this.customDelay=i?.delay,this.code=i?.code,this.customRequest=i?.request}}class Q4 extends Error{name="SchemaValidationError";issues;constructor(i){super("Response schema validation failed");this.issues=i}}class Nn extends Mn{name="TimeoutError";request;constructor(i){super(`Request timed out: ${i.method} ${i.url}`);this.request=i}}var H4=(()=>{let i=!1,n=!1,r=typeof globalThis.ReadableStream==="function",o=typeof globalThis.Request==="function";if(r&&o)try{n=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return i=!0,"half"}}).headers.has("Content-Type")}catch(t){if(t instanceof Error&&t.message==="unsupported BodyInit type")return!1;throw t}return i&&!n})(),rN=typeof globalThis.AbortController==="function",Uv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",oN=typeof globalThis.ReadableStream==="function",uN=typeof globalThis.FormData==="function",cv=["get","post","put","patch","head","delete"],eF=()=>{return};eF();var lN={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Zr=2147483647,eN=40,Sv=Symbol("stop");class Ov{options;constructor(i){this.options=i}}var vN=(i)=>new Ov(i),$N={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},IN={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 Av=new TextEncoder,vF=(i)=>{if(!i)return 0;if(i instanceof FormData){let n=0;for(let[r,o]of i)n+=eN,n+=Av.encode(`Content-Disposition: form-data; name="${r}"`).byteLength,n+=typeof o==="string"?Av.encode(o).byteLength:o.size;return n}if(i instanceof Blob)return i.size;if(i instanceof ArrayBuffer||ArrayBuffer.isView(i))return i.byteLength;if(typeof i==="string")return Av.encode(i).byteLength;if(i instanceof URLSearchParams)return Av.encode(i.toString()).byteLength;return 0},gN=(i,n,r)=>{let o,t=0;return i.pipeThrough(new TransformStream({transform(u,l){if(l.enqueue(u),o){t+=o.byteLength;let e=n===0?0:t/n;if(e>=1)e=1-Number.EPSILON;r?.({percent:e,totalBytes:Math.max(n,t),transferredBytes:t},o)}o=u},flush(){if(o)t+=o.byteLength,r?.({percent:1,totalBytes:Math.max(n,t),transferredBytes:t},o)}}))},bN=(i,n)=>{if(!i.body)return i;let r={status:i.status,statusText:i.statusText,headers:i.headers};if(i.status===204)return new Response(null,r);let o=Math.max(0,Number(i.headers.get("content-length"))||0);return new Response(gN(i.body,o,n),r)},wN=(i,n,r)=>{if(!i.body)return i;let o=vF(r??i.body);return new Request(i,{duplex:"half",body:gN(i.body,o,n)})};var Pn=(i)=>i!==null&&typeof i==="object";var $F=Symbol("replaceOption"),F4=(i)=>Pn(i)&&i[$F]===!0?{isReplace:!0,value:i.value}:{isReplace:!1,value:i};var Gu=(...i)=>{for(let n of i)if((!Pn(n)| Line truncated
`,{mode:384}),n}function hr(i,n,r=[]){let o=n.corpId?.trim()||void 0,t=n.stateful?n.defaultCorpId?.trim()||void 0:void 0,u=o??t;if(u){let e=i.find(($)=>$.id===u);if(e)return e;throw Error(`No enterprise config found for ${u}`)}if(!n.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let l=i[0];if(l)return l;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(r.length?r.join(", "):"the configured enterprise directories"))}import{readFileSync as qK}from"node:fs";import{randomBytes as _K}from"node:crypto";import{randomBytes as SL}from"node:crypto";var tK=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),rK=v.object({id:v.string(),tenantId:v.string(),name:v.string(),isAdmin:v.boolean().default(!1),permissions:v.array(v.string()).default([]),providerUserId:v.string().optional(),hosecloudStaff:tK.optional()}),oK=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),uK=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:oK.optional()}),RN=v.object({user:rK,tenant:uK}),lK=v.object({id:v.string(),name:v.string(),email:v.string().nullable().optional(),emailVerified:v.boolean().optional(),image:v.string().nullable().optional(),tenantId:v.string().optional(),provider:v.string().optional(),providerUserId:v.string().optional(),mobile:v.string().nullable().optional(),status:v.string().optional(),permissions:v.array(v.string()).default([]),isAdmin:v.boolean().default(!1),hosecloudStaff:v.unknown().optional()}).passthrough(),eK=v.object({id:v.string(),token:v.string().optional(),expiresAt:v.string(),createdAt:v.string().optional(),updatedAt:v.string().optional(),ipAddress:v.string().optional(),userAgent:v.string().optional(),userId:v.string(),delegationId:v.string().nullable().optional()}).passthrough(),xN=v.object({user:lK,session:eK}),Hv=v.object({id:v.string(),tenantId:v.string().optional(),code:v.number().optional(),description:v.string(),scope:v.string(),strictness:v.string(),status:v.string().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional()}),aN=v.object({rules:v.array(Hv),hasPendingDeletes:v.boolean().default(!1)}),vK=v.object({code:v.string().optional(),description:v.string(),scope:v.string(),strictness:v.string()}),Fv=v.object({id:v.string(),tenantId:v.string().optional(),versionNumber:v.number(),versionName:v.string().nullable().optional(),publishedBy:v.string().nullable().optional(),publishedByName:v.string().nullable().optional(),rules:v.array(vK).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),sN=v.object({version:Fv,rulesCount:v.number()}),Xu=v.object({id:v.string(),tenantId:v.string().optional(),title:v.string(),purpose:v.string().default(""),contentType:v.string().default("policy"),content:v.string(),status:v.string().default("published"),enabled:v.boolean().default(!0),scenarios:v.array(v.string()).default([]),tags:v.array(v.string()).default([]),category:v.string().nullable().optional(),categoryTags:v.array(v.string()).default([]),createdBy:v.string().nullable().optional(),createdByName:v.string().nullable().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional(),updatedBy:v.string().nullable().optional(),updatedByName:v.string().nullable().optional(),isDeleted:v.boolean().default(!1)}),iL=v.object({articles:v.array(Xu),total:v.number().optional()}),$K=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),IK=v.object({type:v.string(),signKey:v.string().optional(),outboundName:v.string().optional(),mode:v.string().optional(),autoApprovalRate:v.number().optional(),apiKey:v.string().optional(),apiSecret:v.string().optional(),apiOrigin:v.string().optional(),corporationId:v.string().optional(),ebotSignKey:v.string().optional(),completionSignKey:v.string().optional(),outboundMessageId:v.string().optional(),completionMessageId:v.string().optional()}).passthrough(),gK=v.enum(["assisted","semi_automatic","fully_automatic"]),mN=v.object({id:v.string(),url:v.string().url()}).passthrough(),Yu=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:gK,incomingDocumentWebhook:mN,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:mN,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),a4=v.object({id:v.string().optional(),tenantId:v.string().optional(),tone:v.string().optional(),language:v.string().optional(),detailLevel:v.string().optional(),outputFormat:v.string().optional(),examples:v.array(v.string()).default([]),prohibitedPhrases:v.array(v.string()).default([]),cus Line truncated
`);return{recordId:i.id,sourceDocumentSN:i.sourceDocumentSN,sourceDocumentId:i.sourceDocumentId,document:Ut({id:n?.id,sn:n?.sn??n?.sourceDocumentSN??i.sourceDocumentSN,title:n?.title??n?.name,template:zv(n,["template.name","templateName","form.name","formName","formTitle"]),amount:Mv(r,["金额","报销金额","付款金额","合计","价税合计"])??zv(n,["amount","totalAmount","expenseAmount"]),expenseType:Mv(r,["费用类型","费用类别","报销类型"]),costCompany:Mv(r,["费用承担公司","承担公司","成本中心","费用归属"]),payee:Mv(r,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:r.slice(0,30)}),invoices:r3(i),attachments:jk(i,{summary:!0}).attachments,aiResult:hv(i),manualResult:Zt(i)?.value,hints:Ut({amountMentions:wk(o,["金额","合计","税率"],8),partyMentions:wk(o,["买方","卖方","甲方","乙方","收款"],8)})}}function jk(i,n={}){let r=[["document",i.document],["result",i.result],["pipelineData",i.pipelineData],["sourceExtendData",i.sourceExtendData]],o=[],t=new Set;for(let[u,l]of r)U0(l,u,o,t);return{recordId:i.id,sourceDocumentSN:i.sourceDocumentSN,sourceDocumentId:i.sourceDocumentId,count:o.length,attachments:n.summary?o.map((u)=>Ut({path:u.path,kind:u.kind,fileName:u.fileName,mimeType:u.mimeType,fileId:u.fileId,sourceField:u.sourceField})):o}}function xK(i){let n=[["result.citedRules",dn(i,"result.citedRules")],["result.matchedRules",dn(i,"result.matchedRules")],["result.ruleResults",dn(i,"result.ruleResults")],["result.rules",dn(i,"result.rules")],["pipelineData.citedRules",dn(i,"pipelineData.citedRules")],["pipelineData.matchedRules",dn(i,"pipelineData.matchedRules")]],r=[],o=new Set;for(let[t,u]of n)(Array.isArray(u)?u:u&&typeof u==="object"?Object.values(u):[]).forEach((e,$)=>{let I=mr(e);if(!I)return;let g=T(I.runtimeRuleId)??T(I.runtimeId)??T(I.id)??T(I.ruleId),b=T(I.ruleCode)??T(I.code)??(g?l3(g):void 0),w=Ut({runtimeRuleId:g,ruleCode:b,versionNumber:n3(I.versionNumber)??i.ruleSetVersionNumber,scope:T(I.scope),strictness:T(I.strictness),appliedAnalysis:I.appliedAnalysis??I.analysis??I.reasoning,checkResult:I.checkResult??I.result??I.decision,findings:I.findings??I.riskPoints??I.evidence,sourcePath:`${t}.${$}`}),f=JSON.stringify(w);if(!o.has(f))o.add(f),r.push(w)});return{recordId:i.id,sourceDocumentSN:i.sourceDocumentSN,sourceDocumentId:i.sourceDocumentId,ruleSetVersionNumber:i.ruleSetVersionNumber,count:r.length,rules:r}}function U0(i,n,r,o){if(Array.isArray(i)){i.forEach((u,l)=>U0(u,`${n}.${l}`,r,o));return}let t=mr(i);if(!t)return;if(aK(t,n)){let u=Ut({path:n,fieldPath:n,kind:sK(n,t),fileName:T(t.fileName)??T(t.filename)??T(t.name)??T(t.originalName),mimeType:T(t.mimeType)??T(t.mimetype)??T(t.contentType),fileId:T(t.fileId)??T(t.id)??T(t.attachmentId),ossPath:T(t.ossPath)??T(t.ossKey)??T(t.key),url:T(t.url)??T(t.signedUrl)??T(t.downloadUrl)??T(t.previewUrl),invoiceId:T(t.invoiceId),sourceField:T(t.fieldName)??T(t.label)}),l=JSON.stringify(u);if(!o.has(l))o.add(l),r.push(u)}for(let[u,l]of Object.entries(t))U0(l,`${n}.${u}`,r,o)}function aK(i,n){let r=Object.keys(i).map((u)=>u.toLowerCase());return/(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(n)&&["filename","fileName","mimeType","mimetype","contentType","fileId","ossPath","signedUrl","downloadUrl","previewUrl","attachmentId"].some((u)=>r.includes(u.toLowerCase()))}function sK(i,n){let r=`${i} ${T(n.type)??""}`.toLowerCase();if(r.includes("invoice")||r.includes("发票"))return"invoice";if(r.includes("receipt"))return"receipt";return"attachment"}function zv(i,n){if(!i)return;for(let r of n){let o=dn(i,r);if(o!==void 0)return o}return}function bk(i,n){if(!i)return 0;for(let r of n){let o=dn(i,r);if(Array.isArray(o))return o.length;if(o&&typeof o==="object")return Object.keys(o).length;if(typeof o==="number")return o}return 0}function dn(i,n){return n.split(".").reduce((r,o)=>{if(r===void 0||r===null)return;if(Array.isArray(r)){let t=Number(o);return Number.isInteger(t)?r[t]:void 0}if(typeof r==="object")return r[o];return},i)}function i3(i,n,r){let o=n.split("."),t=i;for(let u of o.slice(0,-1)){let l=t[u];if(!l||typeof l!=="object"||Array.isArray(l))t[u]={};t=t[u]}t[o[o.length-1]??n]=r}function Ut(i){return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function mr(i){return i&&typeof i==="object"&&!Array.isArray(i)?i:void 0}function n3(i){return typeof i==="number"&&Number.isFinite(i)?i:void 0}function t3(i){let n=[];return c0(i,"document",n),n}function c0(i,n,r){if(Array.isArray(i)){i.forEach((l,e)=>c0(l,`${n}.${e}`,r));return}let o=mr(i);if(!o)return;let t=T(o.label)??T(o.name)??T(o.title)??T(o.fieldName),u=o.value??o.displayValue??o.text??o.content;if(t&&u!==void 0&&typeof u!=="object")r.push(Ut({path:n,label:t,value:u,type:T(o.type)??T(o.fieldType)}));for(let[l,e]of Object.entries(o)){if(l==="attachments")continue;c0(e,`${n}.${l}`,r)}}function Mv(i,n){return i.find((o)=>{let t=T(o.label)??"";return n.some((u)=>t.includes(u)) Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let e of n.seen.entries()){let l=e[1];if(i===e[0]){u(e);continue}if(n.external){let I=n.external.registry.get(e[0])?.id;if(i!==e[0]&&I){u(e);continue}}if(n.metadataRegistry.get(e[0])?.id){u(e);continue}if(l.cycle){u(e);continue}if(l.count>1){if(n.reused==="ref"){u(e);continue}}}}function it(n,i){let r=n.seen.get(i);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(l)=>{let $=n.seen.get(l);if($.ref===null)return;let I=$.def??$.schema,g={...I},b=$.ref;if($.ref=null,b){o(b);let f=n.seen.get(b),c=f.schema;if(c.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0"))I.allOf=I.allOf??[],I.allOf.push(c);else Object.assign(I,c);if(Object.assign(I,g),l._zod.parent===b)for(let N in I){if(N==="$ref"||N==="allOf")continue;if(!(N in g))delete I[N]}if(c.$ref&&f.def)for(let N in I){if(N==="$ref"||N==="allOf")continue;if(N in f.def&&JSON.stringify(I[N])===JSON.stringify(f.def[N]))delete I[N]}}let w=l._zod.parent;if(w&&w!==b){o(w);let f=n.seen.get(w);if(f?.schema.$ref){if(I.$ref=f.schema.$ref,f.def)for(let c in I){if(c==="$ref"||c==="allOf")continue;if(c in f.def&&JSON.stringify(I[c])===JSON.stringify(f.def[c]))delete I[c]}}}n.override({zodSchema:l,jsonSchema:I,path:$.path??[]})};for(let l of[...n.seen.entries()].reverse())o(l[0]);let t={};if(n.target==="draft-2020-12")t.$schema="https://json-schema.org/draft/2020-12/schema";else if(n.target==="draft-07")t.$schema="http://json-schema.org/draft-07/schema#";else if(n.target==="draft-04")t.$schema="http://json-schema.org/draft-04/schema#";else if(n.target==="openapi-3.0");if(n.external?.uri){let l=n.external.registry.get(i)?.id;if(!l)throw Error("Schema is missing an `id` property");t.$id=n.external.uri(l)}Object.assign(t,r.def??r.schema);let u=n.metadataRegistry.get(i)?.id;if(u!==void 0&&t.id===u)delete t.id;let e=n.external?.defs??{};for(let l of n.seen.entries()){let $=l[1];if($.def&&$.defId){if($.def.id===$.defId)delete $.def.id;e[$.defId]=$.def}}if(n.external);else if(Object.keys(e).length>0)if(n.target==="draft-2020-12")t.$defs=e;else t.definitions=e;try{let l=JSON.parse(JSON.stringify(t));return Object.defineProperty(l,"~standard",{value:{...i["~standard"],jsonSchema:{input:fr(i,"input",n.processors),output:fr(i,"output",n.processors)}},enumerable:!1,writable:!1}),l}catch(l){throw Error("Error converting schema to JSON.")}}function Zn(n,i){let r=i??{seen:new Set};if(r.seen.has(n))return!1;r.seen.add(n);let o=n._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Zn(o.element,r);if(o.type==="set")return Zn(o.valueType,r);if(o.type==="lazy")return Zn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Zn(o.innerType,r);if(o.type==="intersection")return Zn(o.left,r)||Zn(o.right,r);if(o.type==="record"||o.type==="map")return Zn(o.keyType,r)||Zn(o.valueType,r);if(o.type==="pipe"){if(n._zod.traits.has("$ZodCodec"))return!0;return Zn(o.in,r)||Zn(o.out,r)}if(o.type==="object"){for(let t in o.shape)if(Zn(o.shape[t],r))return!0;return!1}if(o.type==="union"){for(let t of o.options)if(Zn(t,r))return!0;return!1}if(o.type==="tuple"){for(let t of o.items)if(Zn(t,r))return!0;if(o.rest&&Zn(o.rest,r))return!0;return!1}return!1}var bw=(n,i={})=>(r)=>{let o=si({...r,processors:i});return en(n,o),nt(o,n),it(o,n)},fr=(n,i,r={})=>(o)=>{let{libraryOptions:t,target:u}=o??{},e=si({...t??{},target:u,io:i,processors:r});return en(n,e),nt(e,n),it(e,n)};var pj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ww=(n,i,r,o)=>{let t=r;t.type="string";let{minimum:u,maximum:e,format:l,patterns:$,contentEncoding:I}=n._zod.bag;if(typeof u==="number")t.minLength=u;if(typeof e==="number")t.maxLength=e;if(l){if(t.format=pj[l]??l,t.format==="")delete t.format;if(l==="time")delete t.format}if(I)t.contentEncoding=I;if($&&$.size>0){let g=[...$];if(g.length===1)t.pattern=g[0].source;else if(g.length>1)t.allOf=[...g.map((b)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))]}},fw=(n,i,r,o)=>{let t=r,{minimum:u,maximum:e,format:l,multipleOf:$,exclusiveMaximum:I,exclusiveMinimum:g}=n._zod.bag;if(typeof l==="string"&&l.includes("int"))t.type="integer";else t.type="number";let b=typeof g==="number"&&g>=(u??Number.NEGATIVE_INFINITY),w=typeof I==="number"&&I<=(e??Number.POSITIVE_INFINITY),f=i.target==="draft-04"||i.target==="openapi-3.0";if(b)if(f)t.minimum=g,t.exclusiveMinimum=!0;else t.exclusiveMinimum=g;else if(typeof u==="number")t.minimum=u;if(w)if(f)t.maximum=I,t.exclusiveMaximum=!0;else t.exclusiveMaximum=I;else if(typeof e==="number")t.maximum=e;if(typeof $==="number")t.multipleOf=$},cw=(n,i,r,o)=>{r.type="boolean"},Dw=(n,i,r,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Uw=(n,i,r,o)=>{if(i.unrepresentable==="Line truncated
`);if(n===-1)return null;let i=this._buffer.toString("utf8",0,n).replace(/\r$/,"");return this._buffer=this._buffer.subarray(n+1),lQ(i)}clear(){this._buffer=void 0}}function lQ(n){return uU.parse(JSON.parse(n))}function iN(n){return JSON.stringify(n)+`
`}class Yc{constructor(n=tN.stdin,i=tN.stdout){this._stdin=n,this._stdout=i,this._readBuffer=new Xc,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}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 n=this._readBuffer.readMessage();if(n===null)break;this.onmessage?.(n)}catch(n){this.onerror?.(n)}}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(n){return new Promise((i)=>{let r=iN(n);if(this._stdout.write(r))i();else this._stdout.once("drain",i)})}}import{dirname as p4,join as UK}from"node:path";import{fileURLToPath as SK}from"node:url";class _i extends Error{name="KyError";get isKyError(){return!0}}class ti extends _i{name="HTTPError";response;request;options;data;constructor(n,i,r){let o=n.status||n.status===0?n.status:"",t=n.statusText??"",u=`${o} ${t}`.trim(),e=u?`status code ${u}`:"an unknown error";super(`Request failed with ${e}: ${i.method} ${i.url}`);this.response=n,this.request=i,this.options=r}}class Nu extends _i{name="NetworkError";request;constructor(n,i){super(`Request failed due to a network error: ${n.method} ${n.url}`,i);this.request=n}}class Lu extends Error{name="NonError";value;constructor(n){let i="Non-error value was thrown";try{if(typeof n==="string")i=n;else if(n&&typeof n==="object"&&"message"in n&&typeof n.message==="string")i=n.message}catch{}super(i);this.value=n}}class qr extends _i{name="ForceRetryError";customDelay;code;customRequest;constructor(n){let i=n?.cause?n.cause instanceof Error?n.cause:new Lu(n.cause):void 0;super(n?.code?`Forced retry: ${n.code}`:"Forced retry",i?{cause:i}:void 0);this.customDelay=n?.delay,this.code=n?.code,this.customRequest=n?.request}}class Hc extends Error{name="SchemaValidationError";issues;constructor(n){super("Response schema validation failed");this.issues=n}}class Ni extends _i{name="TimeoutError";request;constructor(n){super(`Request timed out: ${n.method} ${n.url}`);this.request=n}}var Pc=(()=>{let n=!1,i=!1,r=typeof globalThis.ReadableStream==="function",o=typeof globalThis.Request==="function";if(r&&o)try{i=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type")}catch(t){if(t instanceof Error&&t.message==="unsupported BodyInit type")return!1;throw t}return n&&!i})(),rN=typeof globalThis.AbortController==="function",Dv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",oN=typeof globalThis.ReadableStream==="function",uN=typeof globalThis.FormData==="function",Uv=["get","post","put","patch","head","delete"],vQ=()=>{return};vQ();var eN={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Tr=2147483647,lN=40,Sv=Symbol("stop");class Ov{options;constructor(n){this.options=n}}var vN=(n)=>new Ov(n),$N={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},IN={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 Av=new TextEncoder,$Q=(n)=>{if(!n)return 0;if(n instanceof FormData){let i=0;for(let[r,o]of n)i+=lN,i+=Av.encode(`Content-Disposition: form-data; name="${r}"`).byteLength,i+=typeof o==="string"?Av.encode(o).byteLength:o.size;return i}if(n instanceof Blob)return n.size;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return n.byteLength;if(typeof n==="string")return Av.encode(n).byteLength;if(n instanceof URLSearchParams)return Av.encode(n.toString()).byteLength;return 0},gN=(n,i,r)=>{let o,t=0;return n.pipeThrough(new TransformStream({transform(u,e){if(e.enqueue(u),o){t+=o.byteLength;let l=i===0?0:t/i;if(l>=1)l=1-Number.EPSILON;r?.({percent:l,totalBytes:Math.max(i,t),transferredBytes:t},o)}o=u},flush(){if(o)t+=o.byteLength,r?.({percent:1,totalBytes:Math.max(i,t),transferredBytes:t},o)}}))},bN=(n,i)=>{if(!n.body)return n;let r={status:n.status,statusText:n.statusText,headers:n.headers};if(n.status===204)return new Response(null,r);let o=Math.max(0,Number(n.headers.get("content-length"))||0);return new Response(gN(n.body,o,i),r)},wN=(n,i,r)=>{if(!n.body)return n;let o=$Q(r??n.body);return new Request(n,{duplex:"half",body:gN(n.body,o,i)})};var Yi=(n)=>n!==null&&typeof n==="object";var IQ=Symbol("replaceOption"),Qc=(n)=>Yi(n)&&n[IQ]===!0?{isReplace:!0,value:n.value}:{isReplace:!1,value:n};var ku=(...n)=>{for(let i of n)if((!Yi(i)| Line truncated
`,{mode:384}),i}function zr(n,i,r=[]){let o=i.corpId?.trim()||void 0,t=i.stateful?i.defaultCorpId?.trim()||void 0:void 0,u=o??t;if(u){let l=n.find(($)=>$.id===u);if(l)return l;throw Error(`No enterprise config found for ${u}`)}if(!i.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let e=n[0];if(e)return e;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(r.length?r.join(", "):"the configured enterprise directories"))}import{readFileSync as pF}from"node:fs";import{randomBytes as VF}from"node:crypto";import{randomBytes as SL}from"node:crypto";var rF=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),oF=v.object({id:v.string(),tenantId:v.string(),name:v.string(),isAdmin:v.boolean().default(!1),permissions:v.array(v.string()).default([]),providerUserId:v.string().optional(),hosecloudStaff:rF.optional()}),uF=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),eF=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:uF.optional()}),RN=v.object({user:oF,tenant:eF}),lF=v.object({id:v.string(),name:v.string(),email:v.string().nullable().optional(),emailVerified:v.boolean().optional(),image:v.string().nullable().optional(),tenantId:v.string().optional(),provider:v.string().optional(),providerUserId:v.string().optional(),mobile:v.string().nullable().optional(),status:v.string().optional(),permissions:v.array(v.string()).default([]),isAdmin:v.boolean().default(!1),hosecloudStaff:v.unknown().optional()}).passthrough(),vF=v.object({id:v.string(),token:v.string().optional(),expiresAt:v.string(),createdAt:v.string().optional(),updatedAt:v.string().optional(),ipAddress:v.string().optional(),userAgent:v.string().optional(),userId:v.string(),delegationId:v.string().nullable().optional()}).passthrough(),xN=v.object({user:lF,session:vF}),Pv=v.object({id:v.string(),tenantId:v.string().optional(),code:v.number().optional(),description:v.string(),scope:v.string(),strictness:v.string(),status:v.string().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional()}),aN=v.object({rules:v.array(Pv),hasPendingDeletes:v.boolean().default(!1)}),$F=v.object({code:v.string().optional(),description:v.string(),scope:v.string(),strictness:v.string()}),Qv=v.object({id:v.string(),tenantId:v.string().optional(),versionNumber:v.number(),versionName:v.string().nullable().optional(),publishedBy:v.string().nullable().optional(),publishedByName:v.string().nullable().optional(),rules:v.array($F).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),sN=v.object({version:Qv,rulesCount:v.number()}),Ju=v.object({id:v.string(),tenantId:v.string().optional(),title:v.string(),purpose:v.string().default(""),contentType:v.string().default("policy"),content:v.string(),status:v.string().default("published"),enabled:v.boolean().default(!0),scenarios:v.array(v.string()).default([]),tags:v.array(v.string()).default([]),category:v.string().nullable().optional(),categoryTags:v.array(v.string()).default([]),createdBy:v.string().nullable().optional(),createdByName:v.string().nullable().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional(),updatedBy:v.string().nullable().optional(),updatedByName:v.string().nullable().optional(),isDeleted:v.boolean().default(!1)}),nL=v.object({articles:v.array(Ju),total:v.number().optional()}),IF=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),gF=v.object({type:v.string(),signKey:v.string().optional(),outboundName:v.string().optional(),mode:v.string().optional(),autoApprovalRate:v.number().optional(),apiKey:v.string().optional(),apiSecret:v.string().optional(),apiOrigin:v.string().optional(),corporationId:v.string().optional(),ebotSignKey:v.string().optional(),completionSignKey:v.string().optional(),outboundMessageId:v.string().optional(),completionMessageId:v.string().optional()}).passthrough(),bF=v.enum(["assisted","semi_automatic","fully_automatic"]),CN=v.object({id:v.string(),url:v.string().url()}).passthrough(),Xu=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:bF,incomingDocumentWebhook:CN,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:CN,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),ac=v.object({id:v.string().optional(),tenantId:v.string().optional(),tone:v.string().optional(),language:v.string().optional(),detailLevel:v.string().optional(),outputFormat:v.string().optional(),examples:v.array(v.string()).default([]),prohibitedPhrases:v.array(v.string()).default([]),cus Line truncated
`);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,document:Dt({id:i?.id,sn:i?.sn??i?.sourceDocumentSN??n.sourceDocumentSN,title:i?.title??i?.name,template:Zv(i,["template.name","templateName","form.name","formName","formTitle"]),amount:_v(r,["金额","报销金额","付款金额","合计","价税合计"])??Zv(i,["amount","totalAmount","expenseAmount"]),expenseType:_v(r,["费用类型","费用类别","报销类型"]),costCompany:_v(r,["费用承担公司","承担公司","成本中心","费用归属"]),payee:_v(r,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:r.slice(0,30)}),invoices:oh(n),attachments:dy(n,{summary:!0}).attachments,aiResult:zv(n),manualResult:Tt(n)?.value,hints:Dt({amountMentions:wy(o,["金额","合计","税率"],8),partyMentions:wy(o,["买方","卖方","甲方","乙方","收款"],8)})}}function dy(n,i={}){let r=[["document",n.document],["result",n.result],["pipelineData",n.pipelineData],["sourceExtendData",n.sourceExtendData]],o=[],t=new Set;for(let[u,e]of r)D4(e,u,o,t);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,count:o.length,attachments:i.summary?o.map((u)=>Dt({path:u.path,kind:u.kind,fileName:u.fileName,mimeType:u.mimeType,fileId:u.fileId,sourceField:u.sourceField})):o}}function aF(n){let i=[["result.citedRules",Ei(n,"result.citedRules")],["result.matchedRules",Ei(n,"result.matchedRules")],["result.ruleResults",Ei(n,"result.ruleResults")],["result.rules",Ei(n,"result.rules")],["pipelineData.citedRules",Ei(n,"pipelineData.citedRules")],["pipelineData.matchedRules",Ei(n,"pipelineData.matchedRules")]],r=[],o=new Set;for(let[t,u]of i)(Array.isArray(u)?u:u&&typeof u==="object"?Object.values(u):[]).forEach((l,$)=>{let I=Cr(l);if(!I)return;let g=q(I.runtimeRuleId)??q(I.runtimeId)??q(I.id)??q(I.ruleId),b=q(I.ruleCode)??q(I.code)??(g?lh(g):void 0),w=Dt({runtimeRuleId:g,ruleCode:b,versionNumber:th(I.versionNumber)??n.ruleSetVersionNumber,scope:q(I.scope),strictness:q(I.strictness),appliedAnalysis:I.appliedAnalysis??I.analysis??I.reasoning,checkResult:I.checkResult??I.result??I.decision,findings:I.findings??I.riskPoints??I.evidence,sourcePath:`${t}.${$}`}),f=JSON.stringify(w);if(!o.has(f))o.add(f),r.push(w)});return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,ruleSetVersionNumber:n.ruleSetVersionNumber,count:r.length,rules:r}}function D4(n,i,r,o){if(Array.isArray(n)){n.forEach((u,e)=>D4(u,`${i}.${e}`,r,o));return}let t=Cr(n);if(!t)return;if(sF(t,i)){let u=Dt({path:i,fieldPath:i,kind:nh(i,t),fileName:q(t.fileName)??q(t.filename)??q(t.name)??q(t.originalName),mimeType:q(t.mimeType)??q(t.mimetype)??q(t.contentType),fileId:q(t.fileId)??q(t.id)??q(t.attachmentId),ossPath:q(t.ossPath)??q(t.ossKey)??q(t.key),url:q(t.url)??q(t.signedUrl)??q(t.downloadUrl)??q(t.previewUrl),invoiceId:q(t.invoiceId),sourceField:q(t.fieldName)??q(t.label)}),e=JSON.stringify(u);if(!o.has(e))o.add(e),r.push(u)}for(let[u,e]of Object.entries(t))D4(e,`${i}.${u}`,r,o)}function sF(n,i){let r=Object.keys(n).map((u)=>u.toLowerCase());return/(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(i)&&["filename","fileName","mimeType","mimetype","contentType","fileId","ossPath","signedUrl","downloadUrl","previewUrl","attachmentId"].some((u)=>r.includes(u.toLowerCase()))}function nh(n,i){let r=`${n} ${q(i.type)??""}`.toLowerCase();if(r.includes("invoice")||r.includes("发票"))return"invoice";if(r.includes("receipt"))return"receipt";return"attachment"}function Zv(n,i){if(!n)return;for(let r of i){let o=Ei(n,r);if(o!==void 0)return o}return}function by(n,i){if(!n)return 0;for(let r of i){let o=Ei(n,r);if(Array.isArray(o))return o.length;if(o&&typeof o==="object")return Object.keys(o).length;if(typeof o==="number")return o}return 0}function Ei(n,i){return i.split(".").reduce((r,o)=>{if(r===void 0||r===null)return;if(Array.isArray(r)){let t=Number(o);return Number.isInteger(t)?r[t]:void 0}if(typeof r==="object")return r[o];return},n)}function ih(n,i,r){let o=i.split("."),t=n;for(let u of o.slice(0,-1)){let e=t[u];if(!e||typeof e!=="object"||Array.isArray(e))t[u]={};t=t[u]}t[o[o.length-1]??i]=r}function Dt(n){return Object.fromEntries(Object.entries(n).filter(([,i])=>i!==void 0))}function Cr(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function th(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function rh(n){let i=[];return U4(n,"document",i),i}function U4(n,i,r){if(Array.isArray(n)){n.forEach((e,l)=>U4(e,`${i}.${l}`,r));return}let o=Cr(n);if(!o)return;let t=q(o.label)??q(o.name)??q(o.title)??q(o.fieldName),u=o.value??o.displayValue??o.text??o.content;if(t&&u!==void 0&&typeof u!=="object")r.push(Dt({path:i,label:t,value:u,type:q(o.type)??q(o.fieldType)}));for(let[e,l]of Object.entries(o)){if(e==="attachments")continue;U4(l,`${i}.${e}`,r)}}function _v(n,i){return n.find((o)=>{let t=q(o.label)??"";return i.some((u)=>t.includes(u)) Line truncated
`)}
`}function qu(i){return i.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function q(i,n={}){O3(i,n);let r=`${JSON.stringify(i,null,2)}
`;if(n.outputFile){D3(n.outputFile,r),console.log(JSON.stringify({outputFile:n.outputFile,bytes:Buffer.byteLength(r,"utf-8")},null,2));return}console.log(r.trimEnd())}function O3(i,n={}){if(n.allowFull||n.outputFile)return;let r=Buffer.byteLength(JSON.stringify(i),"utf-8");if(r>S3)throw Error(`Output is large (${r} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function qk(i,n){if(n)return;let r=i&&typeof i==="object"?i:{},o=typeof r.count==="number"?r.count:void 0,t=Array.isArray(r.rules)?r.rules.length:void 0,u=Buffer.byteLength(JSON.stringify(i),"utf-8"),l=o??t??0;if(l>U3||u>c3)throw Error(`Rule list is large (${l} rules, ${u} bytes). Use "seal-home rules list --summary" or "seal-home rules count"; pass --full only when you really need full descriptions.`)}function X(i){return{allowFull:p(i.full)===!0,outputFile:c(i.outputFile)??c(i["output-file"])}}function _k(){console.log(`seal-home CLI
`}function Bu(n){return n.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function B(n,i={}){Ah(n,i);let r=`${JSON.stringify(n,null,2)}
`;if(i.outputFile){Dh(i.outputFile,r),console.log(JSON.stringify({outputFile:i.outputFile,bytes:Buffer.byteLength(r,"utf-8")},null,2));return}console.log(r.trimEnd())}function Ah(n,i={}){if(i.allowFull||i.outputFile)return;let r=Buffer.byteLength(JSON.stringify(n),"utf-8");if(r>Oh)throw Error(`Output is large (${r} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function By(n,i){if(i)return;let r=n&&typeof n==="object"?n:{},o=typeof r.count==="number"?r.count:void 0,t=Array.isArray(r.rules)?r.rules.length:void 0,u=Buffer.byteLength(JSON.stringify(n),"utf-8"),e=o??t??0;if(e>Uh||u>Sh)throw Error(`Rule list is large (${e} rules, ${u} bytes). Use "seal-home rules list --summary" or "seal-home rules count"; pass --full only when you really need full descriptions.`)}function J(n){return{allowFull:M(n.full)===!0,outputFile:U(n.outputFile)??U(n["output-file"])}}function py(){console.log(`seal-home CLI
Usage:
seal-home version
@@ -175,18 +175,18 @@ Usage:
seal-home simulation templates [--corp <corpId>]
seal-home simulation integrations [--corp <corpId>]
seal-home simulation package-upload <材料包.zip> [--corp <corpId>]
`)}function ki(i){let n=Qn(),r=bn();return hr(n,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:i},Vt())}function Cv(i=bn()){return{mode:i.stateful?"stateful":"stateless",stateful:i.stateful,...i.stateful&&i.defaultCorpId?{defaultCorpId:i.defaultCorpId}:{},configFile:pr()}}async function Y(i,n,r,o,t={}){q(await Rr(i,n,r,o),t)}async function Rr(i,n,r,o){let t=ct.find((e)=>e.name===i);if(!t)throw Error(`Unknown Seal tool: ${i}`);let u=Object.fromEntries(Object.entries(o).filter(([,e])=>e!==void 0)),l=t.handler;return l(n,u,{corp:r})}async function Ek(i,n,r,o,t){if(i==="summary"){let u=await Rr("seal_approval_runs_summary",r,o,{date:c(t.options.date),timezone:c(t.options.timezone),limit:li(t.options.limit),startDate:c(t.options.startDate),endDate:c(t.options.endDate),status:c(t.options.status),taskMode:c(t.options.taskMode),manualApprovalStatus:c(t.options.manualApprovalStatus),sourceDocumentSN:c(t.options.sourceDocumentSN),sourceDocumentId:c(t.options.sourceDocumentId),humanResult:c(t.options.humanResult),query:c(t.options.query)});if(u?.matched===0&&u?.total>0)console.error(`提示:在 ${u.date} 未匹配到记录(该企业共有 ${u.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-home approval-runs list --limit 10 查看最近记录。`);q(u,X(t.options));return}if(i==="stats"){await Y("seal_approval_runs_stats",r,o,{since:c(t.options.since),dedupeBy:c(t.options.dedupeBy)??c(t.options["dedupe-by"]),status:c(t.options.status),sourceSystem:c(t.options.sourceSystem)??c(t.options["source-system"]),taskMode:c(t.options.taskMode)??c(t.options["task-mode"])},X(t.options));return}if(i==="count"){await Y("seal_approval_runs_count",r,o,{status:c(t.options.status),sourceSystem:c(t.options.sourceSystem)??c(t.options["source-system"]),taskMode:c(t.options.taskMode)??c(t.options["task-mode"]),search:c(t.options.search)??c(t.options.query)},X(t.options));return}if(i==="search"||i==="list"){await Y("seal_approval_runs_search",r,o,{limit:li(t.options.limit),offset:li(t.options.offset),startDate:c(t.options.startDate),endDate:c(t.options.endDate),status:c(t.options.status),taskMode:c(t.options.taskMode),manualApprovalStatus:c(t.options.manualApprovalStatus),sourceDocumentSN:c(t.options.sourceDocumentSN),sourceDocumentId:c(t.options.sourceDocumentId),humanResult:c(t.options.humanResult),query:c(t.options.query),includeBridge:p(t.options.includeBridge)},X(t.options));return}if(i==="bridge"){await Y("seal_approval_run_langfuse_bridge_get",r,o,{recordId:c(t.options.recordId),sourceDocumentSN:c(t.options.sourceDocumentSN),sourceDocumentId:c(t.options.sourceDocumentId),simulationBatchId:c(t.options.simulationBatchId),limit:li(t.options.limit)},X(t.options));return}if(i==="pick"){let u=n??c(t.options.query)??c(t.options.sn);if(!u)throw Error("Usage: seal-home approval-runs pick --sn <documentSN>");await Y("seal_approval_run_pick",r,o,{query:u,sn:c(t.options.sn),batchId:c(t.options.batch)??c(t.options.batchId),latest:p(t.options.latest),fields:c(t.options.fields),limit:li(t.options.limit),includeBridge:p(t.options.includeBridge)},X(t.options));return}if(i==="get"){let u=t.command[2];if(!u)throw Error("Missing approval run recordId");await Y("seal_approval_run_get",r,o,{recordId:u,fields:c(t.options.fields),summary:p(t.options.summary)},X(t.options));return}if(i==="cited-rules"){let u=t.command[2];if(!u)throw Error("Usage: seal-home approval-runs cited-rules <recordId>");await Y("seal_approval_run_cited_rules_get",r,o,{recordId:u},X(t.options));return}if(i==="document-summary"){let u=t.command[2];if(!u)throw Error("Usage: seal-home approval-runs document-summary <recordId>");await Y("seal_approval_run_document_summary_get",r,o,{recordId:u},X(t.options));return}if(i==="attachments"){let u=t.command[2];if(!u)throw Error("Usage: seal-home approval-runs attachments <recordId>");await Y("seal_approval_run_attachments_get",r,o,{recordId:u,summary:p(t.options.summary)},X(t.options));return}if(i==="result"){let u=t.command[2];if(!u)throw Error("Usage: seal-home approval-runs result <recordId> [--summary]");await Y("seal_approval_run_result_get",r,o,{recordId:u,summary:p(t.options.summary)},X(t.options));return}if(i==="url"){await Y("seal_approval_run_url_get",r,o,{recordId:n,sourceDocumentSN:c(t.options.sourceDocumentSN),sourceDocumentId:c(t.options.sourceDocumentId)},X(t.options));return}throw Error(`Unknown approval-runs command: ${i??""}. Run 'seal-home help' for available commands.`)}async function Mk(i,n,r){if(i==="diagnose"){q(await A3(n));return}if(i==="hose-link"){let o=li(r.options.expire)??7200;q(await qN(n,o));return}throw Error(`Unknown auth command: ${i??""}. Run 'seal-home help' for available commands.`)}async function A3(i){if(i.source.type!=="hose"){let D=await Si(i),S=await Cr(D);return{corp:{id:i.id,name:i.name,sourceType:i.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:S.user,tenant:S.tenant}]}}Gv(i.id);let n=i.source,r=n.appKey??n.key,o=n.appSecurity??n.passw Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${yi.length} candidate administrators:
- ${Oi}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!S)if(!g&&u)S=u;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-home corps hose-staffs' to discover available administrators.");let N=Di(i,"id")??w,L=f??w,V=Di(i,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,Q={id:N,name:L,seal:{url:V,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:b,appKey:r,appSecurity:o,corpId:w,staffId:S},auth:{refreshTtl:300}};if(g)Gv(N),await xr(Q);let y=x4();Rk(y,{recursive:!0,mode:448});let k=ak(y,`${G0(N)}.json`);if(mk(k)&&i.overwrite!==!0)throw Error(`Enterprise config already exists: ${k}. Pass "overwrite": true to replace it.`);xk(k,`${JSON.stringify(Q,null,2)}
`,{mode:384}),q({id:N,name:L,corpId:w,domain:b,staffId:S,verified:g,path:k})}async function W3(i){let n=St(i,"token"),r=(Di(i,"sealUrl")??Di(i,"url")??"").replace(/\/+$/,"");if(!r)throw Error("Missing required JSON field: sealUrl");let o=Qk(i,"expiresIn")??2592000,t=i.force===!0||i.verify===!1?!1:!0,u=t?await y3(r,n):void 0,l=u?.user,e=u?.tenant,$=Di(i,"tenantSlug")??Ot(e?.tenantSlug),I=Di(i,"tenantId")??Ot(e?.id),g=Di(i,"tenantName")??Di(i,"name")??Ot(e?.name),b=Di(i,"id")??$??I;if(!b)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let w=Di(i,"staffId")??Ot(l?.providerUserId)??Ot(l?.id)??"seal",f=Di(i,"provider")??Ot(l?.provider)??Ot(e?.providerConfig?.provider),D={id:b,name:g??b,seal:{url:r,tenantSlug:$,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:n,sealUrl:r,expiresIn:o,staffId:w,corpId:$??I??b,tenantId:I,tenantSlug:$,tenantName:g,providerUserId:Ot(l?.providerUserId),provider:f},auth:{refreshTtl:300}},S=x4();Rk(S,{recursive:!0,mode:448});let N=ak(S,`${G0(b)}.json`);if(mk(N)&&i.overwrite!==!0)throw Error(`Enterprise config already exists: ${N}. Pass "overwrite": true to replace it.`);xk(N,`${JSON.stringify(D,null,2)}
`,{mode:384}),q({id:b,name:D.name,tenantId:I,tenantSlug:$,verified:t,path:N})}async function y3(i,n){let r=await J3(`${i}/api/v1/auth/me`,{authorization:`Bearer ${n}`}),o=Rv(r.data);return{user:Rv(o.user??r.user),tenant:Rv(o.tenant??r.tenant)}}async function J3(i,n={}){let r=await fetch(i,{headers:n}),o=await r.text();if(!r.ok)throw Error(`${r.status} ${o}`);let t=JSON.parse(o);return Rv(t)}function Rv(i){return i&&typeof i==="object"&&!Array.isArray(i)?i:{}}function Ot(i){return typeof i==="string"&&i?i:void 0}async function iG(i,n,r,o,t){if(i==="list"){await Y("seal_delegation_list",r,o,{},X(t.options));return}if(i==="create"){let u=c(t.options.note)??(n?[n,...t.command.slice(2)].join(" "):void 0);await Y("seal_delegation_create",r,o,{note:u},X(t.options));return}if(i==="revoke"){let u=n??c(t.options.tokenId);if(!u)throw Error("Usage: seal-home delegation revoke <tokenId>");await Y("seal_delegation_revoke",r,o,{tokenId:u},X(t.options));return}throw Error(`Unknown delegation command: ${i??""}. Run 'seal-home help' for available commands.`)}import{readFileSync as X3}from"node:fs";async function nG(i,n,r,o,t,u){let l=i==="hosecloud"||!i,e=i==="hosecloud"?n:i,$=i==="hosecloud"?r:n;if(!l&&i!=="hosecloud")throw Error(`Unknown deploy target: ${i??""}. Currently supported: hosecloud`);if(e==="requirements"){await Y("seal_deploy_hosecloud_requirements",o,t,{},X(u.options));return}if(e==="list"){await Y("seal_deploy_hosecloud_list",o,t,{},X(u.options));return}if(e==="get"){let I=$??c(u.options.signKey)??c(u.options["sign-key"]);if(!I)throw Error("Usage: seal-home deploy hosecloud get <sign-key>");await Y("seal_deploy_hosecloud_get",o,t,{signKey:I},X(u.options));return}if(e==="status"){await Y("seal_deploy_hosecloud_status",o,t,{},X(u.options));return}if(e==="configure"){let I=c(u.options.input),g=I?JSON.parse(X3(I,"utf8")):rn(u.json);if(!g||Object.keys(g).length===0)throw Error("Usage: seal-home deploy hosecloud configure --json '{...}' or --input <file>");await Y("seal_deploy_hosecloud_configure",o,t,g,X(u.options));return}if(e==="sync"){let I=$??c(u.options.signKey)??c(u.options["sign-key"]);if(!I)throw Error("Usage: seal-home deploy hosecloud sync <sign-key>");await Y("seal_deploy_hosecloud_sync",o,t,{signKey:I},X(u.options));return}throw Error(`Unknown deploy hosecloud action: ${e??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as F3}from"node:http";import{URL as P3}from"node:url";var tG={openapi:"3.1.0",info:{title:"seal-home Wrapped API",version:"0.9.6",description:`Planned HTTP contract for the seal-home wrapped backend API.
`)}function kn(n){let i=Hi(),r=bi();return zr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n},Kt())}function mv(n=bi()){return{mode:n.stateful?"stateful":"stateless",stateful:n.stateful,...n.stateful&&n.defaultCorpId?{defaultCorpId:n.defaultCorpId}:{},configFile:Mr()}}async function X(n,i,r,o,t={}){B(await Rr(n,i,r,o),t)}async function Rr(n,i,r,o){let t=Ut.find((l)=>l.name===n);if(!t)throw Error(`Unknown Seal tool: ${n}`);let u=Object.fromEntries(Object.entries(o).filter(([,l])=>l!==void 0)),e=t.handler;return e(i,u,{corp:r})}async function Vy(n,i,r,o,t){if(n==="summary"){let u=await Rr("seal_approval_runs_summary",r,o,{date:U(t.options.date),timezone:U(t.options.timezone),limit:ln(t.options.limit),startDate:U(t.options.startDate),endDate:U(t.options.endDate),status:U(t.options.status),taskMode:U(t.options.taskMode),manualApprovalStatus:U(t.options.manualApprovalStatus),sourceDocumentSN:U(t.options.sourceDocumentSN),sourceDocumentId:U(t.options.sourceDocumentId),humanResult:U(t.options.humanResult),query:U(t.options.query)});if(u?.matched===0&&u?.total>0)console.error(`提示:在 ${u.date} 未匹配到记录(该企业共有 ${u.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-home approval-runs list --limit 10 查看最近记录。`);B(u,J(t.options));return}if(n==="stats"){await X("seal_approval_runs_stats",r,o,{since:U(t.options.since),dedupeBy:U(t.options.dedupeBy)??U(t.options["dedupe-by"]),status:U(t.options.status),sourceSystem:U(t.options.sourceSystem)??U(t.options["source-system"]),taskMode:U(t.options.taskMode)??U(t.options["task-mode"])},J(t.options));return}if(n==="count"){await X("seal_approval_runs_count",r,o,{status:U(t.options.status),sourceSystem:U(t.options.sourceSystem)??U(t.options["source-system"]),taskMode:U(t.options.taskMode)??U(t.options["task-mode"]),search:U(t.options.search)??U(t.options.query)},J(t.options));return}if(n==="search"||n==="list"){await X("seal_approval_runs_search",r,o,{limit:ln(t.options.limit),offset:ln(t.options.offset),startDate:U(t.options.startDate),endDate:U(t.options.endDate),status:U(t.options.status),taskMode:U(t.options.taskMode),manualApprovalStatus:U(t.options.manualApprovalStatus),sourceDocumentSN:U(t.options.sourceDocumentSN),sourceDocumentId:U(t.options.sourceDocumentId),humanResult:U(t.options.humanResult),query:U(t.options.query),includeBridge:M(t.options.includeBridge)},J(t.options));return}if(n==="bridge"){await X("seal_approval_run_langfuse_bridge_get",r,o,{recordId:U(t.options.recordId),sourceDocumentSN:U(t.options.sourceDocumentSN),sourceDocumentId:U(t.options.sourceDocumentId),simulationBatchId:U(t.options.simulationBatchId),limit:ln(t.options.limit)},J(t.options));return}if(n==="pick"){let u=i??U(t.options.query)??U(t.options.sn);if(!u)throw Error("Usage: seal-home approval-runs pick --sn <documentSN>");await X("seal_approval_run_pick",r,o,{query:u,sn:U(t.options.sn),batchId:U(t.options.batch)??U(t.options.batchId),latest:M(t.options.latest),fields:U(t.options.fields),limit:ln(t.options.limit),includeBridge:M(t.options.includeBridge)},J(t.options));return}if(n==="get"){let u=t.command[2];if(!u)throw Error("Missing approval run recordId");await X("seal_approval_run_get",r,o,{recordId:u,fields:U(t.options.fields),summary:M(t.options.summary)},J(t.options));return}if(n==="cited-rules"){let u=t.command[2];if(!u)throw Error("Usage: seal-home approval-runs cited-rules <recordId>");await X("seal_approval_run_cited_rules_get",r,o,{recordId:u},J(t.options));return}if(n==="document-summary"){let u=t.command[2];if(!u)throw Error("Usage: seal-home approval-runs document-summary <recordId>");await X("seal_approval_run_document_summary_get",r,o,{recordId:u},J(t.options));return}if(n==="attachments"){let u=t.command[2];if(!u)throw Error("Usage: seal-home approval-runs attachments <recordId>");await X("seal_approval_run_attachments_get",r,o,{recordId:u,summary:M(t.options.summary)},J(t.options));return}if(n==="result"){let u=t.command[2];if(!u)throw Error("Usage: seal-home approval-runs result <recordId> [--summary]");await X("seal_approval_run_result_get",r,o,{recordId:u,summary:M(t.options.summary)},J(t.options));return}if(n==="url"){await X("seal_approval_run_url_get",r,o,{recordId:i,sourceDocumentSN:U(t.options.sourceDocumentSN),sourceDocumentId:U(t.options.sourceDocumentId)},J(t.options));return}throw Error(`Unknown approval-runs command: ${n??""}. Run 'seal-home help' for available commands.`)}async function _y(n,i,r){if(n==="diagnose"){B(await Nh(i));return}if(n==="hose-link"){let o=ln(r.options.expire)??7200;B(await BN(i,o));return}throw Error(`Unknown auth command: ${n??""}. Run 'seal-home help' for available commands.`)}async function Nh(n){if(n.source.type!=="hose"){let c=await On(n),S=await mr(c);return{corp:{id:n.id,name:n.name,sourceType:n.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:S.user,tenant:S.tenant}]}}kv(n.id);let i=n.source,r=i.appKey??i.key,o=i.appSecurity??i.passw Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${Wn.length} candidate administrators:
- ${An}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!S)if(!g&&u)S=u;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-home corps hose-staffs' to discover available administrators.");let N=Dn(n,"id")??w,L=f??w,K=Dn(n,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,H={id:N,name:L,seal:{url:K,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:b,appKey:r,appSecurity:o,corpId:w,staffId:S},auth:{refreshTtl:300}};if(g)kv(N),await xr(H);let j=xc();Ry(j,{recursive:!0,mode:448});let y=ay(j,`${k4(N)}.json`);if(Cy(y)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${y}. Pass "overwrite": true to replace it.`);xy(y,`${JSON.stringify(H,null,2)}
`,{mode:384}),B({id:N,name:L,corpId:w,domain:b,staffId:S,verified:g,path:y})}async function jh(n){let i=St(n,"token"),r=(Dn(n,"sealUrl")??Dn(n,"url")??"").replace(/\/+$/,"");if(!r)throw Error("Missing required JSON field: sealUrl");let o=Hy(n,"expiresIn")??2592000,t=n.force===!0||n.verify===!1?!1:!0,u=t?await Wh(r,i):void 0,e=u?.user,l=u?.tenant,$=Dn(n,"tenantSlug")??Ot(l?.tenantSlug),I=Dn(n,"tenantId")??Ot(l?.id),g=Dn(n,"tenantName")??Dn(n,"name")??Ot(l?.name),b=Dn(n,"id")??$??I;if(!b)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let w=Dn(n,"staffId")??Ot(e?.providerUserId)??Ot(e?.id)??"seal",f=Dn(n,"provider")??Ot(e?.provider)??Ot(l?.providerConfig?.provider),c={id:b,name:g??b,seal:{url:r,tenantSlug:$,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:i,sealUrl:r,expiresIn:o,staffId:w,corpId:$??I??b,tenantId:I,tenantSlug:$,tenantName:g,providerUserId:Ot(e?.providerUserId),provider:f},auth:{refreshTtl:300}},S=xc();Ry(S,{recursive:!0,mode:448});let N=ay(S,`${k4(b)}.json`);if(Cy(N)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${N}. Pass "overwrite": true to replace it.`);xy(N,`${JSON.stringify(c,null,2)}
`,{mode:384}),B({id:b,name:c.name,tenantId:I,tenantSlug:$,verified:t,path:N})}async function Wh(n,i){let r=await Jh(`${n}/api/v1/auth/me`,{authorization:`Bearer ${i}`}),o=Rv(r.data);return{user:Rv(o.user??r.user),tenant:Rv(o.tenant??r.tenant)}}async function Jh(n,i={}){let r=await fetch(n,{headers:i}),o=await r.text();if(!r.ok)throw Error(`${r.status} ${o}`);let t=JSON.parse(o);return Rv(t)}function Rv(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:{}}function Ot(n){return typeof n==="string"&&n?n:void 0}async function nk(n,i,r,o,t){if(n==="list"){await X("seal_delegation_list",r,o,{},J(t.options));return}if(n==="create"){let u=U(t.options.note)??(i?[i,...t.command.slice(2)].join(" "):void 0);await X("seal_delegation_create",r,o,{note:u},J(t.options));return}if(n==="revoke"){let u=i??U(t.options.tokenId);if(!u)throw Error("Usage: seal-home delegation revoke <tokenId>");await X("seal_delegation_revoke",r,o,{tokenId:u},J(t.options));return}throw Error(`Unknown delegation command: ${n??""}. Run 'seal-home help' for available commands.`)}import{readFileSync as Xh}from"node:fs";async function ik(n,i,r,o,t,u){let e=n==="hosecloud"||!n,l=n==="hosecloud"?i:n,$=n==="hosecloud"?r:i;if(!e&&n!=="hosecloud")throw Error(`Unknown deploy target: ${n??""}. Currently supported: hosecloud`);if(l==="requirements"){await X("seal_deploy_hosecloud_requirements",o,t,{},J(u.options));return}if(l==="list"){await X("seal_deploy_hosecloud_list",o,t,{},J(u.options));return}if(l==="get"){let I=$??U(u.options.signKey)??U(u.options["sign-key"]);if(!I)throw Error("Usage: seal-home deploy hosecloud get <sign-key>");await X("seal_deploy_hosecloud_get",o,t,{signKey:I},J(u.options));return}if(l==="status"){await X("seal_deploy_hosecloud_status",o,t,{},J(u.options));return}if(l==="configure"){let I=U(u.options.input),g=I?JSON.parse(Xh(I,"utf8")):ri(u.json);if(!g||Object.keys(g).length===0)throw Error("Usage: seal-home deploy hosecloud configure --json '{...}' or --input <file>");await X("seal_deploy_hosecloud_configure",o,t,g,J(u.options));return}if(l==="sync"){let I=$??U(u.options.signKey)??U(u.options["sign-key"]);if(!I)throw Error("Usage: seal-home deploy hosecloud sync <sign-key>");await X("seal_deploy_hosecloud_sync",o,t,{signKey:I},J(u.options));return}throw Error(`Unknown deploy hosecloud action: ${l??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as Fh}from"node:http";import{URL as Hh}from"node:url";var tk={openapi:"3.1.0",info:{title:"seal-home Wrapped API",version:"0.9.7",description:`Planned HTTP contract for the seal-home wrapped backend API.
These endpoints describe the intended stable API for frontend developers and agents once
the HTTP adapter is implemented.
They are not the raw downstream Seal endpoints. seal-home is responsible for enterprise
selection, source authentication, response compaction, and diagnostics-friendly fields.
`},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
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
@@ -210,20 +210,20 @@ selection, source authentication, response compaction, and diagnostics-friendly
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`}async function Xi(i,n,r,o){let t=i.handler;return t(n,r,{corp:o})}async function oG(i,n){if(n.setHeader("Access-Control-Allow-Origin","*"),n.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),n.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),i.method==="OPTIONS"){n.writeHead(204),n.end();return}let r=i.headers.host||"localhost",o=i.headers["x-forwarded-proto"]||"http",t=new P3(i.url||"/",`${o}://${r}`),u=t.pathname.replace(/\/+$/,"")||"/",l=(i.method||"GET").toUpperCase();try{if(l==="GET"&&u==="/"){Ui(n,200,{name:"seal-home",version:R,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(l==="GET"&&u==="/docs"){H3(n,200,rG());return}if(l==="GET"&&(u==="/openapi.json"||u==="/openapi")){let e=xv();Ui(n,200,e);return}if(l==="GET"&&(u==="/health"||u==="/version")){Ui(n,200,{status:"ok",name:"seal-home",version:R,uptimeSeconds:Math.floor(process.uptime()),timestamp:new Date().toISOString()});return}if(l==="GET"&&u==="/api/tools"){Ui(n,200,{count:ct.length,tools:ct.map((e)=>({name:e.name,description:e.description}))});return}if(l==="POST"&&u==="/api/cli"){let e=await sv(i),$=typeof e?.command==="string"?e.command.trim():"";if(!$){av(n,400,"Missing or empty 'command' field in request body");return}let I=Y0($),g=I[0]==="seal-home"||I[0]?.endsWith("/seal-home")?I.slice(1):I,b=await Eu(g),w=void 0;try{if(b.stdout.trim().startsWith("{")||b.stdout.trim().startsWith("["))w=JSON.parse(b.stdout)}catch{}Ui(n,b.isError?400:200,{success:!b.isError,stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,data:w});return}if(l==="POST"&&u.startsWith("/api/tool/")){let e=u.slice(10).trim(),$=Wi(e,{includeMcpAliases:!0});if(!$){av(n,404,`Tool not found: '${e}'`);return}let I=await sv(i)||{},g=hi(i,t,I),b=ki(g),w=await Si(b),f={...I};delete f.corp;let D=await Xi($,w,f,b);Ui(n,200,D);return}if(u.startsWith("/v1/")){if(await Q3(i,n,l,u,t))return}av(n,404,`Cannot ${l} ${u}. Visit /docs for available endpoints.`)}catch(e){let $=e instanceof Error?e.message:String(e);av(n,500,$)}}async function Q3(i,n,r,o,t){let u=Object.fromEntries(t.searchParams.entries());if(r==="GET"&&o==="/v1/corps"){let l=Qn(),e=bn();return Ui(n,200,{count:l.length,mode:e.stateful?"stateful":"stateless",defaultCorpId:e.defaultCorpId,corps:l.map(($)=>({id:$.id,name:$.name,sourceType:$.source.type,sealUrl:$.seal?.url}))}),!0}if(r==="GET"&&o==="/v1/whoami"){let l=hi(i,t,u),e=ki(l),$=await Si(e),I=Wi("seal_whoami"),g=await Xi(I,$,{},e);return Ui(n,200,g),!0}if(r==="GET"&&o==="/v1/session"){let l=hi(i,t,u),e=ki(l),$=await Si(e),I=Wi("seal_session_get"),g=await Xi(I,$,{},e);return Ui(n,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/summary"){let l=hi(i,t,u),e=ki(l),$=await Si(e),I=Wi("seal_approval_runs_summary"),g=await Xi(I,$,u,e);return Ui(n,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/stats"){let l=hi(i,t,u),e=ki(l),$=await Si(e),I=Wi("seal_approval_runs_stats"),g=await Xi(I,$,u,e);return Ui(n,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/pick"){let l=hi(i,t,u),e=ki(l),$=await Si(e),I=Wi("seal_approval_run_pick"),g=await Xi(I,$,u,e);return Ui(n,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/url"){let l=hi(i,t,u),e=ki(l),$=await Si(e),I=Wi("seal_approval_run_url_get"),g=await Xi(I,$,u,e);return Ui(n,200,g),!0}if(o.startsWith("/v1/approval-runs/")){let l=o.slice(18).split("/"),e=l[0],$=l[1];if(e&&!["summary","pick","stats","url","bridge"].includes(e)){let I=hi(i,t,u),g=ki(I),b=await Si(g);if(!$){let w=Wi("seal_approval_run_get"),f=await Xi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}if($==="attachments"){let w=Wi("seal_approval_run_attachments_get"),f=await Xi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}if($==="cited-rules"){let w=Wi("seal_approval_run_cited_rules_get"),f=await Xi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}if($==="document-summary"){let w=Wi("seal_approval_run_document_summary_get"),f=await Xi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}if($==="result"){let w=Wi("seal_approval_run_result_get"),f=await Xi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}}}if(r==="GET"&&o==="/v1/approval-runs"){let l=hi(i,t,u),e=ki(l),$=await Si(e),I=Wi("seal_approval_runs_search"),g=await Xi(I,$,{...u,limit:u.limit?Number(u.limit):void 0,offset:u.offset?Number(u.offset):void 0,includeBridge:u.includeBridge==="true"},e);return Ui(n,200,g),!0}if(r==="GET"&&o==="/v1/approval/rules"){let l=hi(i,t,u),e=ki(l),$=await Si(e),I=Wi("seal_approval_rules_list"),g=await Xi(I,$,u,e);return Ui(n,200,g),!0}if(r==="GET"&&o==="/v1/simulation/batches"){let l=hi(i,t,u),e=ki(l),$=await Si(e),I=Wi("seal_simulation_batches_list"),g=await Xi(I,$,u,e);return Ui(n,200,g),!0}if(r==="POST"&&o==="/v1/simulation/create-batch"){let l=await sv(i)||{},e=hi(i,t,l),$=ki(e),I=await Si($),g=Wi("seal_simulaLine truncated
\uD83D\uDE80 seal-home HTTP Server (v${R}) started`),console.error(` URL: http://${r}:${n}`),console.error(` Docs: http://${r}:${n}/docs`),console.error(` OpenAPI: http://${r}:${n}/openapi.json`),console.error(` CLI Exec: POST http://${r}:${n}/api/cli`),console.error(` REST API: http://${r}:${n}/v1/...
`);t(o)})})}async function lG(i){let n=li(i.options.port)??li(i.options.p),r=c(i.options.host)??c(i.options.h),o=await uG({port:n,host:r}),t=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}async function eG(i,n,r,o){if(i==="config"||i==="get"){await Y("seal_llm_config_get",n,r,{},X(o.options));return}if(i==="providers"||i==="list"){await Y("seal_llm_providers_list",n,r,{},X(o.options));return}throw Error(`Unknown llm command: ${i??""}. Run 'seal-home help' for available commands.`)}async function vG(i,n){if(i==="config"||i==="json"){P0();return}await Q0()}function P0(){q({mcpServers:{"seal-home":{type:"stdio",command:"seal-home",args:["mcp"],env:{SEAL_HOME_MCP_ENABLED:"true"}}}})}function $G(i){let n=xv();q(n,{...X(i.options),allowFull:!0})}async function IG(i,n,r,o){if(i==="available"){await Y("seal_permissions_available_list",n,r,{},X(o.options));return}if(i==="configs"||i==="list"){await Y("seal_permissions_configs_list",n,r,{},X(o.options));return}throw Error(`Unknown permissions command: ${i??""}. Run 'seal-home help' for available commands.`)}import{readFileSync as gG}from"node:fs";async function bG(i,n,r,o,t,u,l){if(!i||i==="get"){await Y("seal_preference_get",t,u,{},X(l.options));return}if(i==="decision"){if(n==="update"||!n){let e=c(l.options.input),$=e?JSON.parse(gG(e,"utf8")):rn(l.json);if(!$||Object.keys($).length===0)throw Error(`Usage: seal-home preference decision update --json '{"explicitApprove":"..."}'`);await Y("seal_preference_decision_update",t,u,$,X(l.options));return}}if(i==="thinking-depth"||i==="thinkingDepth"){if(n==="set"){let e=c(l.options.default)??c(l.options.level)??o;if(e!=="medium"&&e!=="high")throw Error("Usage: seal-home preference thinking-depth set --default <medium|high>");await Y("seal_preference_thinking_depth_set",t,u,{defaultLevel:e},X(l.options));return}if(n==="policies"){if(r==="list"||!r){await Y("seal_preference_thinking_depth_policies_list",t,u,{},X(l.options));return}if(r==="upsert"){let e=c(l.options.input),$=e?JSON.parse(gG(e,"utf8")):rn(l.json);if(!$||!$.id||!$.name)throw Error(`Usage: seal-home preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await Y("seal_preference_thinking_depth_policies_upsert",t,u,$,X(l.options));return}if(r==="remove"||r==="delete"){let e=o??c(l.options.id)??c(l.options.policyId);if(!e)throw Error("Usage: seal-home preference thinking-depth policies remove <policyId>");await Y("seal_preference_thinking_depth_policies_remove",t,u,{policyId:e},X(l.options));return}}}throw Error(`Unknown preference action: ${i??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function wG(i={}){let n=Qn(),r=bn(),o=hr(n,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:i.corpId},Vt());console.log(`[probe] corp=${o.id} source=${o.source.type}`);let t=await xr(o);console.log("[probe] seal enterprise"),console.log(JSON.stringify(t,null,2));let u=await Si(o),l=await Ev(u,{documentLimit:20,stylePreferencesEndpoint:o.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:l.rules.rules.length,hasPendingRuleDeletes:l.rules.hasPendingDeletes,documents:l.documents.articles.length,documentsTotal:l.documents.total,stylePreferences:l.stylePreferences.ok?"ok":`error: ${l.stylePreferences.error}`},null,2))}async function fG(i,n,r){let o=n??c(r.options.corp)??(i&&i!=="--corp"?i:void 0);await wG({corpId:o})}async function DG(i,n,r,o,t){if(i==="count"){await Y("seal_approval_rules_list",r,o,{countOnly:!0},X(t.options));return}if(i==="list"){if(p(t.options.count)){await Y("seal_approval_rules_list",r,o,{countOnly:!0},X(t.options));return}let u=li(t.options.limit),l=li(t.options.offset);if(p(t.options.summary)){await Y("seal_approval_rules_list",r,o,{fields:Vk,limit:u,offset:l},X(t.options));return}let e=await Rr("seal_approval_rules_list",r,o,{limit:u,offset:l});qk(e,p(t.options.full)===!0),q(e);return}if(i==="clear"){let u=p(t.options.yes)===!0,l=p(t.options.dryRun)??p(t.options["dry-run"])??!u;if(!u&&!l)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let e=await Rr("seal_approval_rules_clear",r,o,{dryRun:l,recode:p(t.options.recode)});if(!u&&l&&e&&typeof e==="object"){q({...e,nextCommand:`seal-home rules clear --corp ${o.id} --yes`},X(t.options));return}q(e,X(t.options));return}if(i==="versions"){await Y("seal_approval_rule_versions_list",r,o,{},X(t.options));return}if(i==="version"){let u=n??c(t.options.version);if(!u)throw Error("Usage: seal-home rules version <versionId|versionNumber|latest>");await Y("seal_approval_rule_version_get",r,o,Bu(u),X(t.options));return}if(i==="get"){await Y("seal_approval_rule_get",r,o,{...Bk(c(t.options.version)),code:c(t.options.code),runtimeId:c(t.options.runtimeId)??c(t.options["runtime-id"]),recordId:c(t.options.recordId)??c(t.options["record-id"])},X(t.options)) Line truncated
`,{mode:384}),n$(r,`running pid=${process.pid}`);let o=()=>{if(F0(n)===process.pid)i$(n,{force:!0});n$(r,`stopped pid=${process.pid}`)};await new Promise((t)=>{let u=!1,l=setInterval(()=>{},60000),e=()=>{if(u)return;u=!0,o(),clearInterval(l),process.off("SIGTERM",e),process.off("SIGINT",e),t()};process.once("SIGTERM",e),process.once("SIGINT",e)})}function UG(i){AG(i.stateDir);let n=ar(i);if(n.running)return n;let r=i.launcher??{command:process.execPath,args:[i.entryFile]},o=K3(r.command,[...r.args??[],"service","run"],{cwd:i.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});o.unref();let t=t$(i);return H0(t,`${o.pid}
`,{mode:384}),n$(r$(i),`started pid=${o.pid}`),{started:!0,...ar(i)}}function cG(i,n={}){let r=t$(i),o=F0(r);if(!o||!OG(o,i.appRoot))return i$(r,{force:!0}),n.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(o,"SIGTERM"),i$(r,{force:!0}),n$(r$(i),`stop requested pid=${o}`),n.quiet?void 0:{stopped:!0,pid:o}}function OG(i,n){if(!T3(i))return!1;try{let r=B3("ps",["-p",String(i),"-o","command="],{encoding:"utf8"});return(r.includes(n)||r.includes("seal-home")||r.includes("src/cli.ts"))&&r.includes("service")&&r.includes("run")}catch{return!1}}function T3(i){try{return process.kill(i,0),!0}catch{return!1}}function t$(i){return SG(i.stateDir,"service.pid")}function r$(i){return SG(i.stateDir,"service.log")}function F0(i){if(!V3(i))return;let n=Number(_3(i,"utf8").trim());return Number.isInteger(n)&&n>0?n:void 0}function AG(i){q3(i,{recursive:!0,mode:448})}function n$(i,n){H0(i,`${new Date().toISOString()} ${n}
`,{flag:"a",mode:384})}var K0=M3(Z3(),".config","seal-home");async function NG(i,n){let r=await Mt(i,{appRoot:n.appRoot,entryFile:n.entryFile,stateDir:K0,version:R,launcher:n.launcher});if(r!==void 0)q(r)}import{existsSync as d3,readFileSync as LG}from"node:fs";async function kG(i,n,r,o,t){if(i==="batch-records"||i==="records"){let u=n??c(t.options.batchId)??c(t.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation batch-records <batchId>");await Y("seal_simulation_batch_records_get",r,o,{batchId:u,query:c(t.options.query)},X(t.options));return}if(i==="create"||i==="run"){let u=c(t.options.mode)??c(t.options.sourceSystem)??c(t.options["source-system"])??"hosecloud",l=u==="material-pack"?"material_pack":u,e=c(t.options.schemaConfig)??c(t.options["schema-config"]),$=e?JSON.parse(LG(e,"utf8")):void 0,I=c(t.options.input),g=I?JSON.parse(LG(I,"utf8")):rn(t.json),b=c(t.options.packageId)??c(t.options["package-id"]),w=Ei(t.options.packageIds)??Ei(t.options["package-ids"])??(b?[b]:void 0),f=Ei(t.options.flowIds)??Ei(t.options["flow-ids"])??Ei(t.options.documentSn)??Ei(t.options["document-sn"]),D=c(t.options.signKey)??c(t.options["sign-key"])??c(t.options.integration);await Y("seal_simulation_batch_create",r,o,{mode:l,sourceSystem:l,flowIds:f,documentSn:f,rejectNodeName:c(t.options.rejectNode)??c(t.options["reject-node"])??null,thinkingDepthOverride:c(t.options.thinkingDepth)??c(t.options["thinking-depth"]),skipInvoiceGeneration:p(t.options.skipInvoiceGeneration)??p(t.options["skip-invoice-generation"]),skipExpenseExtraction:p(t.options.skipExpenseExtraction)??p(t.options["skip-expense-extraction"]),disableAttachmentCache:p(t.options.disableAttachmentCache)??p(t.options["disable-attachment-cache"]),signKey:D,packageIds:w,packageId:b,templateId:c(t.options.templateId)??c(t.options["template-id"]),schemaConfig:$,requestIds:Ei(t.options.requestIds)??Ei(t.options["request-ids"]),workflowTypeId:c(t.options.workflowTypeId)??c(t.options["workflow-type-id"]),flowStatusList:Ei(t.options.flowStatusList)?.map(Number)??Ei(t.options["flow-status-list"])?.map(Number),businessCodes:Ei(t.options.businessCodes)??Ei(t.options["business-codes"]),documentType:c(t.options.documentType)??c(t.options["document-type"]),startTime:li(t.options.startTime)??li(t.options["start-time"]),endTime:li(t.options.endTime)??li(t.options["end-time"]),status:Ei(t.options.status),limit:li(t.options.limit),rawParams:g},X(t.options));return}if(i==="wait"){let u=n??c(t.options.batchId)??c(t.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await Y("seal_simulation_batch_wait",r,o,{batchId:u,timeout:c(t.options.timeout),pollInterval:c(t.options.pollInterval)??c(t.options["poll-interval"])},X(t.options));return}if(i==="clean"||i==="delete"){let u=n??c(t.options.batchId)??c(t.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation clean <batchId>");await Y("seal_simulation_batch_clean",r,o,{batchId:u},X(t.options));return}if(i==="specifications"){let u=n??c(t.options.integration)??c(t.options.signKey)??c(t.options["sign-key"]);await Y("seal_simulation_specifications_list",r,o,{signKey:u},X(t.options));return}if(i==="list"){await Y("seal_simulation_batches_list",r,o,{limit:li(t.options.limit)},X(t.options));return}if(i==="get"){let u=n??c(t.options.batchId)??c(t.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation get <batchId>");await Y("seal_simulation_batch_get",r,o,{batchId:u},X(t.options));return}if(i==="templates"){await Y("seal_simulation_templates_get",r,o,{},X(t.options));return}if(i==="integrations"){await Y("seal_simulation_integrations_get",r,o,{},X(t.options));return}if(i==="package-upload"){let u=n??c(t.options.file);if(!u)throw Error("Usage: seal-home simulation package-upload <材料包.zip>");if(!d3(u))throw Error(`File not found: ${u}`);await Y("seal_simulation_material_package_upload",r,o,{filePath:u},X(t.options));return}throw Error(`Unknown simulation command: ${i??""}. Run 'seal-home help' for available commands.`)}import{existsSync as _G}from"node:fs";import{join as o$}from"node:path";import{mkdirSync as FG,writeFileSync as nB}from"node:fs";import{homedir as tB}from"node:os";import{dirname as rB,join as KG}from"node:path";var GG=`---
</html>`}async function Xn(n,i,r,o){let t=n.handler;return t(i,r,{corp:o})}async function ok(n,i){if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),n.method==="OPTIONS"){i.writeHead(204),i.end();return}let r=n.headers.host||"localhost",o=n.headers["x-forwarded-proto"]||"http",t=new Hh(n.url||"/",`${o}://${r}`),u=t.pathname.replace(/\/+$/,"")||"/",e=(n.method||"GET").toUpperCase();try{if(e==="GET"&&u==="/"){Un(i,200,{name:"seal-home",version:R,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(e==="GET"&&u==="/docs"){Qh(i,200,rk());return}if(e==="GET"&&(u==="/openapi.json"||u==="/openapi")){let l=xv();Un(i,200,l);return}if(e==="GET"&&(u==="/health"||u==="/version")){Un(i,200,{status:"ok",name:"seal-home",version:R,uptimeSeconds:Math.floor(process.uptime()),timestamp:new Date().toISOString()});return}if(e==="GET"&&u==="/api/tools"){Un(i,200,{count:Ut.length,tools:Ut.map((l)=>({name:l.name,description:l.description}))});return}if(e==="POST"&&u==="/api/cli"){let l=await sv(n),$=typeof l?.command==="string"?l.command.trim():"";if(!$){av(i,400,"Missing or empty 'command' field in request body");return}let I=X4($),g=I[0]==="seal-home"||I[0]?.endsWith("/seal-home")?I.slice(1):I,b=await Vu(g),w=void 0;try{if(b.stdout.trim().startsWith("{")||b.stdout.trim().startsWith("["))w=JSON.parse(b.stdout)}catch{}Un(i,b.isError?400:200,{success:!b.isError,stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,data:w});return}if(e==="POST"&&u.startsWith("/api/tool/")){let l=u.slice(10).trim(),$=jn(l,{includeMcpAliases:!0});if(!$){av(i,404,`Tool not found: '${l}'`);return}let I=await sv(n)||{},g=mn(n,t,I),b=kn(g),w=await On(b),f={...I};delete f.corp;let c=await Xn($,w,f,b);Un(i,200,c);return}if(u.startsWith("/v1/")){if(await Ph(n,i,e,u,t))return}av(i,404,`Cannot ${e} ${u}. Visit /docs for available endpoints.`)}catch(l){let $=l instanceof Error?l.message:String(l);av(i,500,$)}}async function Ph(n,i,r,o,t){let u=Object.fromEntries(t.searchParams.entries());if(r==="GET"&&o==="/v1/corps"){let e=Hi(),l=bi();return Un(i,200,{count:e.length,mode:l.stateful?"stateful":"stateless",defaultCorpId:l.defaultCorpId,corps:e.map(($)=>({id:$.id,name:$.name,sourceType:$.source.type,sealUrl:$.seal?.url}))}),!0}if(r==="GET"&&o==="/v1/whoami"){let e=mn(n,t,u),l=kn(e),$=await On(l),I=jn("seal_whoami"),g=await Xn(I,$,{},l);return Un(i,200,g),!0}if(r==="GET"&&o==="/v1/session"){let e=mn(n,t,u),l=kn(e),$=await On(l),I=jn("seal_session_get"),g=await Xn(I,$,{},l);return Un(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/summary"){let e=mn(n,t,u),l=kn(e),$=await On(l),I=jn("seal_approval_runs_summary"),g=await Xn(I,$,u,l);return Un(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/stats"){let e=mn(n,t,u),l=kn(e),$=await On(l),I=jn("seal_approval_runs_stats"),g=await Xn(I,$,u,l);return Un(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/pick"){let e=mn(n,t,u),l=kn(e),$=await On(l),I=jn("seal_approval_run_pick"),g=await Xn(I,$,u,l);return Un(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/url"){let e=mn(n,t,u),l=kn(e),$=await On(l),I=jn("seal_approval_run_url_get"),g=await Xn(I,$,u,l);return Un(i,200,g),!0}if(o.startsWith("/v1/approval-runs/")){let e=o.slice(18).split("/"),l=e[0],$=e[1];if(l&&!["summary","pick","stats","url","bridge"].includes(l)){let I=mn(n,t,u),g=kn(I),b=await On(g);if(!$){let w=jn("seal_approval_run_get"),f=await Xn(w,b,{recordId:l,...u},g);return Un(i,200,f),!0}if($==="attachments"){let w=jn("seal_approval_run_attachments_get"),f=await Xn(w,b,{recordId:l,...u},g);return Un(i,200,f),!0}if($==="cited-rules"){let w=jn("seal_approval_run_cited_rules_get"),f=await Xn(w,b,{recordId:l,...u},g);return Un(i,200,f),!0}if($==="document-summary"){let w=jn("seal_approval_run_document_summary_get"),f=await Xn(w,b,{recordId:l,...u},g);return Un(i,200,f),!0}if($==="result"){let w=jn("seal_approval_run_result_get"),f=await Xn(w,b,{recordId:l,...u},g);return Un(i,200,f),!0}}}if(r==="GET"&&o==="/v1/approval-runs"){let e=mn(n,t,u),l=kn(e),$=await On(l),I=jn("seal_approval_runs_search"),g=await Xn(I,$,{...u,limit:u.limit?Number(u.limit):void 0,offset:u.offset?Number(u.offset):void 0,includeBridge:u.includeBridge==="true"},l);return Un(i,200,g),!0}if(r==="GET"&&o==="/v1/approval/rules"){let e=mn(n,t,u),l=kn(e),$=await On(l),I=jn("seal_approval_rules_list"),g=await Xn(I,$,u,l);return Un(i,200,g),!0}if(r==="GET"&&o==="/v1/simulation/batches"){let e=mn(n,t,u),l=kn(e),$=await On(l),I=jn("seal_simulation_batches_list"),g=await Xn(I,$,u,l);return Un(i,200,g),!0}if(r==="POST"&&o==="/v1/simulation/create-batch"){let e=await sv(n)||{},l=mn(n,t,e),$=kn(l),I=await On($),g=jn("seal_simulaLine truncated
\uD83D\uDE80 seal-home HTTP Server (v${R}) started`),console.error(` URL: http://${r}:${i}`),console.error(` Docs: http://${r}:${i}/docs`),console.error(` OpenAPI: http://${r}:${i}/openapi.json`),console.error(` CLI Exec: POST http://${r}:${i}/api/cli`),console.error(` REST API: http://${r}:${i}/v1/...
`);t(o)})})}async function ek(n){let i=ln(n.options.port)??ln(n.options.p),r=U(n.options.host)??U(n.options.h),o=await uk({port:i,host:r}),t=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}async function lk(n,i,r,o){if(n==="config"||n==="get"){await X("seal_llm_config_get",i,r,{},J(o.options));return}if(n==="providers"||n==="list"){await X("seal_llm_providers_list",i,r,{},J(o.options));return}throw Error(`Unknown llm command: ${n??""}. Run 'seal-home help' for available commands.`)}async function vk(n,i){if(n==="config"||n==="json"){Y4();return}await H4()}function Y4(){B({mcpServers:{"seal-home":{type:"stdio",command:"seal-home",args:["mcp"],env:{SEAL_HOME_MCP_ENABLED:"true"}}}})}function $k(n){let i=xv();B(i,{...J(n.options),allowFull:!0})}async function Ik(n,i,r,o){if(n==="available"){await X("seal_permissions_available_list",i,r,{},J(o.options));return}if(n==="configs"||n==="list"){await X("seal_permissions_configs_list",i,r,{},J(o.options));return}throw Error(`Unknown permissions command: ${n??""}. Run 'seal-home help' for available commands.`)}import{readFileSync as gk}from"node:fs";async function bk(n,i,r,o,t,u,e){if(!n||n==="get"){await X("seal_preference_get",t,u,{},J(e.options));return}if(n==="decision"){if(i==="update"||!i){let l=U(e.options.input),$=l?JSON.parse(gk(l,"utf8")):ri(e.json);if(!$||Object.keys($).length===0)throw Error(`Usage: seal-home preference decision update --json '{"explicitApprove":"..."}'`);await X("seal_preference_decision_update",t,u,$,J(e.options));return}}if(n==="thinking-depth"||n==="thinkingDepth"){if(i==="set"){let l=U(e.options.default)??U(e.options.level)??o;if(l!=="medium"&&l!=="high")throw Error("Usage: seal-home preference thinking-depth set --default <medium|high>");await X("seal_preference_thinking_depth_set",t,u,{defaultLevel:l},J(e.options));return}if(i==="policies"){if(r==="list"||!r){await X("seal_preference_thinking_depth_policies_list",t,u,{},J(e.options));return}if(r==="upsert"){let l=U(e.options.input),$=l?JSON.parse(gk(l,"utf8")):ri(e.json);if(!$||!$.id||!$.name)throw Error(`Usage: seal-home preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await X("seal_preference_thinking_depth_policies_upsert",t,u,$,J(e.options));return}if(r==="remove"||r==="delete"){let l=o??U(e.options.id)??U(e.options.policyId);if(!l)throw Error("Usage: seal-home preference thinking-depth policies remove <policyId>");await X("seal_preference_thinking_depth_policies_remove",t,u,{policyId:l},J(e.options));return}}}throw Error(`Unknown preference action: ${n??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function wk(n={}){let i=Hi(),r=bi(),o=zr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n.corpId},Kt());console.log(`[probe] corp=${o.id} source=${o.source.type}`);let t=await xr(o);console.log("[probe] seal enterprise"),console.log(JSON.stringify(t,null,2));let u=await On(o),e=await Vv(u,{documentLimit:20,stylePreferencesEndpoint:o.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:e.rules.rules.length,hasPendingRuleDeletes:e.rules.hasPendingDeletes,documents:e.documents.articles.length,documentsTotal:e.documents.total,stylePreferences:e.stylePreferences.ok?"ok":`error: ${e.stylePreferences.error}`},null,2))}async function fk(n,i,r){let o=i??U(r.options.corp)??(n&&n!=="--corp"?n:void 0);await wk({corpId:o})}async function ck(n,i,r,o,t){if(n==="count"){await X("seal_approval_rules_list",r,o,{countOnly:!0},J(t.options));return}if(n==="list"){if(M(t.options.count)){await X("seal_approval_rules_list",r,o,{countOnly:!0},J(t.options));return}let u=ln(t.options.limit),e=ln(t.options.offset);if(M(t.options.summary)){await X("seal_approval_rules_list",r,o,{fields:Ky,limit:u,offset:e},J(t.options));return}let l=await Rr("seal_approval_rules_list",r,o,{limit:u,offset:e});By(l,M(t.options.full)===!0),B(l);return}if(n==="clear"){let u=M(t.options.yes)===!0,e=M(t.options.dryRun)??M(t.options["dry-run"])??!u;if(!u&&!e)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let l=await Rr("seal_approval_rules_clear",r,o,{dryRun:e,recode:M(t.options.recode)});if(!u&&e&&l&&typeof l==="object"){B({...l,nextCommand:`seal-home rules clear --corp ${o.id} --yes`},J(t.options));return}B(l,J(t.options));return}if(n==="versions"){await X("seal_approval_rule_versions_list",r,o,{},J(t.options));return}if(n==="version"){let u=i??U(t.options.version);if(!u)throw Error("Usage: seal-home rules version <versionId|versionNumber|latest>");await X("seal_approval_rule_version_get",r,o,hu(u),J(t.options));return}if(n==="get"){await X("seal_approval_rule_get",r,o,{...hy(U(t.options.version)),code:U(t.options.code),runtimeId:U(t.options.runtimeId)??U(t.options["runtime-id"]),recordId:U(t.options.recordId)??U(t.options["record-id"])},J(t.options)) Line truncated
`,{mode:384}),i$(r,`running pid=${process.pid}`);let o=()=>{if(Q4(i)===process.pid)n$(i,{force:!0});i$(r,`stopped pid=${process.pid}`)};await new Promise((t)=>{let u=!1,e=setInterval(()=>{},60000),l=()=>{if(u)return;u=!0,o(),clearInterval(e),process.off("SIGTERM",l),process.off("SIGINT",l),t()};process.once("SIGTERM",l),process.once("SIGINT",l)})}function Dk(n){Ak(n.stateDir);let i=ar(n);if(i.running)return i;let r=n.launcher??{command:process.execPath,args:[n.entryFile]},o=hh(r.command,[...r.args??[],"service","run"],{cwd:n.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});o.unref();let t=t$(n);return P4(t,`${o.pid}
`,{mode:384}),i$(r$(n),`started pid=${o.pid}`),{started:!0,...ar(n)}}function Uk(n,i={}){let r=t$(n),o=Q4(r);if(!o||!Ok(o,n.appRoot))return n$(r,{force:!0}),i.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(o,"SIGTERM"),n$(r,{force:!0}),i$(r$(n),`stop requested pid=${o}`),i.quiet?void 0:{stopped:!0,pid:o}}function Ok(n,i){if(!Th(n))return!1;try{let r=Kh("ps",["-p",String(n),"-o","command="],{encoding:"utf8"});return(r.includes(i)||r.includes("seal-home")||r.includes("src/cli.ts"))&&r.includes("service")&&r.includes("run")}catch{return!1}}function Th(n){try{return process.kill(n,0),!0}catch{return!1}}function t$(n){return Sk(n.stateDir,"service.pid")}function r$(n){return Sk(n.stateDir,"service.log")}function Q4(n){if(!Bh(n))return;let i=Number(Vh(n,"utf8").trim());return Number.isInteger(i)&&i>0?i:void 0}function Ak(n){ph(n,{recursive:!0,mode:448})}function i$(n,i){P4(n,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var F4=Eh(_h(),".config","seal-home");async function Nk(n,i){let r=await _t(n,{appRoot:i.appRoot,entryFile:i.entryFile,stateDir:F4,version:R,launcher:i.launcher});if(r!==void 0)B(r)}import{existsSync as Zh,readFileSync as Lk}from"node:fs";async function yk(n,i,r,o,t){if(n==="batch-records"||n==="records"){let u=i??U(t.options.batchId)??U(t.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation batch-records <batchId>");await X("seal_simulation_batch_records_get",r,o,{batchId:u,query:U(t.options.query)},J(t.options));return}if(n==="create"||n==="run"){let u=U(t.options.mode)??U(t.options.sourceSystem)??U(t.options["source-system"])??"hosecloud",e=u==="material-pack"?"material_pack":u,l=U(t.options.schemaConfig)??U(t.options["schema-config"]),$=l?JSON.parse(Lk(l,"utf8")):void 0,I=U(t.options.input),g=I?JSON.parse(Lk(I,"utf8")):ri(t.json),b=U(t.options.packageId)??U(t.options["package-id"]),w=qn(t.options.packageIds)??qn(t.options["package-ids"])??(b?[b]:void 0),f=qn(t.options.flowIds)??qn(t.options["flow-ids"])??qn(t.options.documentSn)??qn(t.options["document-sn"]),c=U(t.options.signKey)??U(t.options["sign-key"])??U(t.options.integration);await X("seal_simulation_batch_create",r,o,{mode:e,sourceSystem:e,flowIds:f,documentSn:f,rejectNodeName:U(t.options.rejectNode)??U(t.options["reject-node"])??null,thinkingDepthOverride:U(t.options.thinkingDepth)??U(t.options["thinking-depth"]),skipInvoiceGeneration:M(t.options.skipInvoiceGeneration)??M(t.options["skip-invoice-generation"]),skipExpenseExtraction:M(t.options.skipExpenseExtraction)??M(t.options["skip-expense-extraction"]),disableAttachmentCache:M(t.options.disableAttachmentCache)??M(t.options["disable-attachment-cache"]),signKey:c,packageIds:w,packageId:b,templateId:U(t.options.templateId)??U(t.options["template-id"]),schemaConfig:$,requestIds:qn(t.options.requestIds)??qn(t.options["request-ids"]),workflowTypeId:U(t.options.workflowTypeId)??U(t.options["workflow-type-id"]),flowStatusList:qn(t.options.flowStatusList)?.map(Number)??qn(t.options["flow-status-list"])?.map(Number),businessCodes:qn(t.options.businessCodes)??qn(t.options["business-codes"]),documentType:U(t.options.documentType)??U(t.options["document-type"]),startTime:ln(t.options.startTime)??ln(t.options["start-time"]),endTime:ln(t.options.endTime)??ln(t.options["end-time"]),status:qn(t.options.status),limit:ln(t.options.limit),rawParams:g},J(t.options));return}if(n==="wait"){let u=i??U(t.options.batchId)??U(t.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await X("seal_simulation_batch_wait",r,o,{batchId:u,timeout:U(t.options.timeout),pollInterval:U(t.options.pollInterval)??U(t.options["poll-interval"])},J(t.options));return}if(n==="clean"||n==="delete"){let u=i??U(t.options.batchId)??U(t.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation clean <batchId>");await X("seal_simulation_batch_clean",r,o,{batchId:u},J(t.options));return}if(n==="specifications"){let u=i??U(t.options.integration)??U(t.options.signKey)??U(t.options["sign-key"]);await X("seal_simulation_specifications_list",r,o,{signKey:u},J(t.options));return}if(n==="list"){await X("seal_simulation_batches_list",r,o,{limit:ln(t.options.limit)},J(t.options));return}if(n==="get"){let u=i??U(t.options.batchId)??U(t.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation get <batchId>");await X("seal_simulation_batch_get",r,o,{batchId:u},J(t.options));return}if(n==="templates"){await X("seal_simulation_templates_get",r,o,{},J(t.options));return}if(n==="integrations"){await X("seal_simulation_integrations_get",r,o,{},J(t.options));return}if(n==="package-upload"){let u=i??U(t.options.file);if(!u)throw Error("Usage: seal-home simulation package-upload <材料包.zip>");if(!Zh(u))throw Error(`File not found: ${u}`);await X("seal_simulation_material_package_upload",r,o,{filePath:u},J(t.options));return}throw Error(`Unknown simulation command: ${n??""}. Run 'seal-home help' for available commands.`)}import{existsSync as Vk}from"node:fs";import{join as o$}from"node:path";import{mkdirSync as Fk,writeFileSync as rK}from"node:fs";import{homedir as oK}from"node:os";import{dirname as uK,join as hk}from"node:path";var kk=`---
name: seal-home
description: "v0.9.6: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
description: "v0.9.7: Use for Seal Home 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.9.6
short-description: Seal tenant and Hose approval automation (v0.9.6)
version: 0.9.7
short-description: Seal tenant and Hose approval automation (v0.9.7)
---
# Seal Home (v0.9.6)
# Seal Home (v0.9.7)
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-home\` 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.
@@ -235,6 +235,11 @@ seal-home tools list
## First Rules
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
- Before asking for enterprise parameters, run \`seal-home corps list\`. If the target is already configured, resolve its human name to the returned \`id\` and pass that value as \`--corp\`; do not ask the user to know \`corpId\`.
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read \`references/enterprise-onboarding.md\` before asking questions or running setup commands.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
- Never ask a normal user for \`corpId\`, \`staffId\`, \`proxyStaffBizId\`, \`tenantId\`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
- Prefer compact commands first: \`pick\`, \`--summary\`, \`--fields\`, \`attachments --summary\`, \`rules count\`, and \`rules list --summary\`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use \`seal-home corps ...\`.
@@ -251,6 +256,7 @@ seal-home tools list
## Route By Intent
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read \`references/enterprise-onboarding.md\`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run \`seal-home 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.
- 模拟测试发布闭环: \`seal-home simulation create --mode hosecloud --flow-ids ... --corp <corpId>\` (合思指定单号) 或 \`--mode material_pack --package-ids ... --schema-config file.json\` (材料包导入), 支持多源系统 \`--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>\`, \`simulation wait <batchId>\` 轮询等待完成, \`simulation clean <batchId>\` 清理数据, \`simulation specifications\` 列出单据模板, \`simulation list\`/\`get\`/\`batch-records\` 查看批次与记录。创建前确认目标环境为测试环境。
@@ -307,21 +313,23 @@ seal-home tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅
## References
- \`references/enterprise-onboarding.md\`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- \`references/approval-run-lightweight.md\`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- \`references/rule-lightweight.md\`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- \`references/customer-feedback-rule-remediation.md\`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- \`references/hose-enterprise-auth.md\`: Hose 企业配置、认证诊断、授权链接。
- \`references/hose-enterprise-init.md\`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
- \`references/approval-attachment-trace.md\`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。
- \`references/cli.md\`: 完整 CLI 命令清单。
## Safety
Rule, document, style preference, and publish actions mutate Seal configuration. Make the target enterprise explicit, show the intended payload, and verify after the write. Never send real \`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 jG=`interface:
`;var dk=`interface:
display_name: "Seal Home"
short_description: "Diagnose approval feedback and publish minimal rule fixes"
default_prompt: "Use $seal-home to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation."
`;var WG=`# Rule Lightweight Queries
`;var Gk=`# Rule Lightweight Queries
Use this reference when the user wants rule counts, compact rule lists, one rule from a historical version, or approval knowledge search without dumping hundreds of rule descriptions.
@@ -426,7 +434,7 @@ Use current search only when the question is about current draft/current knowled
## Output Discipline
If a rule command would return many descriptions or more than about 20 rules, use \`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports.
`;var yG=`# Approval Bad Case Catalog
`;var jk=`# Approval Bad Case Catalog
Use this file only as a comparison catalog after inspecting the current trace. Do not treat any case below as a default diagnosis.
@@ -476,7 +484,7 @@ Important nuance:
- This is a bad-case pattern, not a general rule that every amount-total dispute is caused by \`pre_analysis\`.
- Use it when the current trace shows recognized amounts being excluded downstream or duplicate attachments producing inconsistent conclusions.
`;var JG=`# Seal Home CLI Reference
`;var Wk=`# Seal Home CLI Reference
Run from any directory after installing the global CLI:
@@ -839,7 +847,7 @@ Update style preferences:
- If date-based summaries look wrong, pass \`--timezone Asia/Shanghai\` and an explicit \`--date\`.
- If \`langfuseTraceId\` is missing, use \`langfuseSessionFallback\`.
- If a write operation fails, report the raw JSON error and do not retry with guessed payloads.
`;var XG="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-home approval-runs get <recordId> --corp <corpId> --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-home approval-runs get <recordId> --corp <corpId> --fields metadata\nseal-home approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary\nseal-home approval-runs get <recordId> --corp <corpId> --fields result.summary,result.decision,result.riskPoints\nseal-home approval-runs get <recordId> --corp <corpId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-home approval-runs document-summary <recordId> --corp <corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-home approval-runs cited-rules <recordId> --corp <corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id <recordId> --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\nseal-home approval-runs attachments <recordId> --corp <corpId> --summary\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-home approval-runs result <recordId> --corp <corpId> --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Output Discipline\n\nIf a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.\n";var YG=`# Approval Attachment Trace Investigation
`;var Jk="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-home approval-runs get <recordId> --corp <corpId> --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-home approval-runs get <recordId> --corp <corpId> --fields metadata\nseal-home approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary\nseal-home approval-runs get <recordId> --corp <corpId> --fields result.summary,result.decision,result.riskPoints\nseal-home approval-runs get <recordId> --corp <corpId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-home approval-runs document-summary <recordId> --corp <corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-home approval-runs cited-rules <recordId> --corp <corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id <recordId> --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\nseal-home approval-runs attachments <recordId> --corp <corpId> --summary\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-home approval-runs result <recordId> --corp <corpId> --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Output Discipline\n\nIf a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.\n";var Xk=`# Approval Attachment Trace Investigation
Use this workflow when a customer disputes an AI approval finding about an attachment, invoice, receipt, OCR result, or a UI-highlighted audit result.
@@ -1060,7 +1068,7 @@ Manual image check:
- The customer's objection that they were receipts rather than invoices was reasonable.
However, the final rejection also had an independent rule-37 reason: payment screenshots totaled 699.48 while reimbursement was 700.00.
`;var PG=`# Customer Feedback Rule Remediation
`;var Yk=`# Customer Feedback Rule Remediation
Use this low-freedom workflow when the user provides packaged customer feedback from WeChat, screenshots, rejection notifications, a document number, or expected business behavior and wants diagnosis or an approval-rule change.
@@ -1224,7 +1232,124 @@ Return a compact report containing:
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
`;var QG=`# Hose Enterprise Auth
`;var Hk=`# Enterprise Onboarding
Read 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.
## Start With Discovery
Run this before asking for setup parameters:
\`\`\`bash
seal-home version
seal-home corps list
\`\`\`
- 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\`.
- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.
- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”
Do not open with a JSON template or a list of internal fields.
All 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.
## Keep Two Concepts Separate
Classify both the enterprise identity origin and how the current credential was acquired:
| Enterprise identity origin | Credential material the user may have | Meaning |
| --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose \`appKey\` + \`appSecurity\` | Stable, refreshable standard integration |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |
| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |
| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |
Credential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When \`whoami\` returns provider metadata, preserve it and use it to describe the tenant accurately.
## Parameter Ownership
Ask the user only for information that cannot be discovered safely:
| Field | Owner and behavior |
| --- | --- |
| \`appKey\`, \`appSecurity\` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |
| \`domain\` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |
| Enterprise name and \`corpId\` | Discover from the credential response or Seal \`whoami\`. Do not ask the user to invent or locate them first. |
| 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. |
| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal \`whoami\`. |
| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |
## Route 1: Standard Hose Credentials
This is the preferred durable route for a Hose-sourced tenant. Read \`hose-enterprise-init.md\`, then use:
\`\`\`bash
seal-home corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
\`\`\`
The CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with \`staffName\`, \`staffPhone\`, or the selected \`staffId\` internally. After creation, run:
\`\`\`bash
seal-home auth diagnose --corp <discovered-id>
\`\`\`
Do not ask for \`domain\`, \`corpId\`, or \`proxyStaffBizId\` up front. For a dedicated/private Hose deployment, add \`domain\` only after standard probing reports that it cannot find the enterprise.
## Route 2: Incoming Assistance Link
First distinguish the link by its host and purpose:
- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.
- \`seal-home auth hose-link\` and \`seal-home delegation create\` generate links for an enterprise that is already configured; they do not import a new enterprise from a received link.
The current CLI does not directly import an incoming assistance link. Do not pretend that \`corps add-hose\` or \`corps add-seal\` accepts the raw URL. If a browser tool is available and the user authorized opening the link, open it, confirm the final tenant host, and obtain an authenticated Seal business request. Otherwise explain that the link must be opened in the user's browser, then continue with the browser cURL route below.
Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it.
## Route 3: Browser F12 cURL
When the user needs capture instructions, give these concrete steps:
1. Open the already signed-in Hose or Seal page.
2. Open browser developer tools: \`F12\` on many keyboards, or \`Option+Command+I\` on macOS.
3. Open **Network**, then select **Fetch/XHR**.
4. Refresh the page or perform one ordinary read-only business action.
5. Choose a successful business API request from the relevant tenant, not analytics, static assets, upload, delete, publish, or logout requests.
6. Right-click it and choose **Copy → Copy as cURL**.
7. Send that complete cURL only to the local trusted Agent handling setup.
When receiving cURL:
1. Treat the entire cURL as a secret. Do not echo it, execute it blindly, paste it into another service, or store it in repository files.
2. Parse it as data. Extract the request host, path, \`Authorization\` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3. Classify whether the captured request is to Hose or Seal. A Seal request with \`Authorization: Bearer ...\` can supply \`sealUrl\` and a session token even when the user's identity origin is Hose.
4. Verify with the narrowest read-only identity endpoint available. For a Seal Bearer session, verify \`/api/v1/auth/me\` through \`seal-home corps add-seal\`; use returned provider metadata to retain the actual origin.
5. Persist only the normalized minimum configuration needed by seal-home. Do not preserve the raw cURL, unrelated headers, request body, cookies, or signed URL.
For a verified Seal Bearer captured from cURL, the existing CLI route is:
\`\`\`bash
seal-home corps add-seal --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
\`\`\`
The current CLI has no raw-cURL import command and \`add-seal\` requires a Bearer token. If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
## Verify and Hand Off
After adding an enterprise:
\`\`\`bash
seal-home corps list
seal-home corps current --corp <discovered-id>
seal-home auth diagnose --corp <discovered-id> # Hose source
\`\`\`
Report the human enterprise name, identity provider, credential method, and whether verification succeeded. Do not expose internal IDs unless they help with troubleshooting. Do not perform approval, rule, document, simulation, publishing, or other business mutations just because onboarding succeeded; continue only with the user's requested task and its normal confirmation rules.
If a temporary assistance-link or browser session expires, explain that it must be renewed or recaptured. Recommend standard Hose app credentials when the user needs durable unattended access.
`;var Pk=`# Hose Enterprise Auth
Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links.
@@ -1232,14 +1357,18 @@ Use this reference for Hose/合思 enterprise configuration and user-facing Hose
Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit \`~/.config/seal-home/enterprises/*.json\` unless the CLI fails or the user explicitly asks for low-level config debugging.
For first-time setup or when the user has an assistance link or browser cURL instead of standard application credentials, read \`enterprise-onboarding.md\` first. This reference's \`add-hose\` route is specifically for durable Hose OpenAPI credentials.
\`\`\`bash
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-home corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
seal-home corps list
seal-home corps current --corp <corpId>
seal-home corps switch <corpId>
\`\`\`
\`corps add-hose\` verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at \`corps\` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
\`corps add-hose\` probes standard domains and discovers the enterprise automatically. If it returns multiple administrator candidates, present their names and masked phones for the user to choose, then retry with \`staffName\`, \`staffPhone\`, or the selected \`staffId\`. Do not ask for \`domain\`, \`corpId\`, \`staffId\`, or \`proxyStaffBizId\` before discovery. Ask for a dedicated/private-cloud \`domain\` only after standard probing fails.
The command verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at \`corps\` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
## Diagnose authentication
@@ -1285,7 +1414,7 @@ Important:
- \`seal-home auth diagnose\` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
- **Formatting Requirement**: When returning a Hose authorization link to the user, ALWAYS provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- If the CLI later provides a dedicated command for this, prefer that command.
`;var HG=`# Hose Enterprise Initialization & Automated Discovery
`;var Qk=`# Hose Enterprise Initialization & Automated Discovery
Use this reference for automated Hose/合思 enterprise onboarding, multi-domain probing (including dedicated private cloud domains like 美年大健康), OpenAPI role and staff discovery, and non-TUI safe administrator selection.
@@ -1391,12 +1520,12 @@ seal-home corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var BG={"SKILL.md":GG,"agents/openai.yaml":jG,"references/rule-lightweight.md":WG,"references/approval-bad-cases.md":yG,"references/cli.md":JG,"references/approval-run-lightweight.md":XG,"references/approval-attachment-trace.md":YG,"references/customer-feedback-rule-remediation.md":PG,"references/hose-enterprise-auth.md":QG,"references/hose-enterprise-init.md":HG};function VG(){return BG["SKILL.md"]||""}function Tu(){return KG(tB(),".agents","skills","seal-home")}function B0(i=Tu()){FG(i,{recursive:!0});let n=[];for(let[r,o]of Object.entries(BG)){let t=KG(i,r);FG(rB(t),{recursive:!0}),nB(t,o,"utf8"),n.push(r)}return{targetDir:i,files:n}}function qG(){let i=Tu();return B0(i),{synced:!0,targetDir:i}}function EG(i,n,r){if(i==="dump"||i==="cat"||i==="show"){process.stdout.write(`${VG()}
`);return}if(i==="install"||i==="init"||i==="sync"){let o=p(r.options.local)||p(r.options.workspace),t=c(r.options.dir)??c(r.options.target)??n,u=t?t:o?o$(process.cwd(),".agents","skills","seal-home"):Tu(),l=B0(u);q({installed:!0,targetDir:l.targetDir,fileCount:l.files.length,files:l.files});return}if(i==="status"||i==="get"||!i){let o=Tu(),t=o$(process.cwd(),".agents","skills","seal-home");q({global:{dir:o,installed:_G(o$(o,"SKILL.md"))},local:{dir:t,installed:_G(o$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${i}. Run 'seal-home help' for available commands.`)}async function TG(i,n){if(i==="config"){q(await xr(n));return}throw Error(`Unknown source command: ${i??""}. Run 'seal-home help' for available commands.`)}async function ZG(i,n,r,o){if(!i)throw Error("Usage: seal-home tool <toolName> [--json '{...}']");await Y(i,n,r,rn(o.json),X(o.options))}function MG(){q(ct.map((i)=>({name:i.name,description:i.description})))}import{chmodSync as oB,mkdirSync as uB,renameSync as V0,rmSync as lB,unlinkSync as CG,writeFileSync as dG}from"node:fs";import{dirname as eB,join as zG}from"node:path";import{spawnSync as dt}from"node:child_process";function u$(i=process.execPath,n=import.meta.url){if(n.includes("/$bunfs/")||n.includes("\\$bunfs\\"))return!0;let r=i.toLowerCase().replace(/\\/g,"/");return!r.endsWith("/bun")&&!r.endsWith("/bun.exe")}var mG="yunyingk/seal-home";var vB="SEAL_HOME_GITHUB_REPO";async function RG(i,n={}){let r={appRoot:i.appRoot,entryFile:i.entryFile,stateDir:K0,version:R,launcher:i.launcher},o=n.repo||process.env[vB]?.trim()||mG,t=n.targetVersion?.trim(),u=t&&t.toLowerCase()!=="latest"?t:void 0;if(u){let y=u.replace(/^v/,""),k=xG(y,R);if(k<0){q({updated:!1,currentVersion:R,targetVersion:y,mode:u$()?"binary":"source",message:`Cannot downgrade seal-home from v${R} to older version v${y}. Updates must be forward-only.`});return}if(k===0&&!n.force){q({updated:!1,currentVersion:R,targetVersion:y,mode:u$()?"binary":"source",message:`seal-home is already at version v${R}. Use --force to reinstall.`});return}}if(n.changelogOnly){let y=await q0(o,n.limit??10);q({currentVersion:R,totalQueried:y.length,releases:y.map((k)=>({version:k.version,tagName:k.tagName,publishedAt:k.publishedAt,author:k.author,releaseNotes:k.notes,releaseUrl:k.htmlUrl,isCurrent:k.version===R,isNewer:Zu(k.version,R)}))});return}if(!u$()){if(n.checkOnly){let k=await q0(o,30),Z=k[0],x=Z?.version??R,Gi=k.find((oi)=>oi.version===R),yi=Zu(x,R),Oi=k.filter((oi)=>Zu(oi.version,R));q({updated:!1,updateAvailable:yi,currentVersion:R,currentVersionPublishedAt:Gi?.publishedAt,latestVersion:x,latestVersionPublishedAt:Z?.publishedAt,behindCount:Oi.length,pendingReleases:Oi.map((oi)=>({version:oi.version,tagName:oi.tagName,publishedAt:oi.publishedAt,author:oi.author,releaseNotes:oi.notes,releaseUrl:oi.htmlUrl})),releaseNotes:Z?.notes??"",releaseUrl:Z?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-home update' to git pull & bun install."});return}let y=ar(r).running;if(y)await Mt("stop",r);try{hG("git",["-C",i.appRoot,"pull","--ff-only"])}catch(k){console.error(`git pull skipped: ${k instanceof Error?k.message:String(k)}`)}if(hG("bun",["install"],{cwd:i.appRoot}),y)await Mt("start",r);q({updated:!0,serviceRestarted:y,version:R,mode:"source"});return}let l=$B(),e=IB(),$=await q0(o,30),I=u?$.find((y)=>y.version===u||y.tagName===u||y.tagName===`v${u}`)??await pG(o,u):$[0]??await pG(o);if(!I){q({updated:!1,currentVersion:R,mode:"binary",message:`Failed to query releases from GitHub repository '${o}'`});return}let g=I.version,b=$.find((y)=>y.version===R),w=Zu(g,R),f=w||Boolean(n.force),D=$.filter((y)=>Zu(y.version,R));if(n.checkOnly){q({updated:!1,updateAvailable:w,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:D.length,pendingReleases:D.map((y)=>({version:y.version,tagName:y.tagName,publishedAt:y.publishedAt,author:y.author,releaseNotes:y.notes,releaseUrl:y.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!f){q({updated:!1,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-home is already up to date (v${R})`});return}let S=gB(I.assets,l,e);if(!S)throw Error(`No compatible binary found for ${l}-${e} in release v${g}. Available assets: ${I.assets.map((y)=>y.name).join(", ")}`);let N=ar(r).running;if(N)await Mt("stop",r);let L=process.execPath,V=eB(L),Q=zG(V,`.tmp-update-${Date.now()}`);uB(Q,{recursive:!0});try{let y=zG(Q,S.name);await bB(S.downloadUrl,y,I.tagName,S.name);let k=y;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))k=wB(y,Q,l);else if(S.name.endsWith(".zip"))k=fB(y,Q,l);if(oB(k,493),process.platform==="darwin")try{dt("/usr/bin/codesign",["--remove-signature",k],{stdio:"ignore"}),dt("/usr/bin/codesign",["--force","--sign","-",k],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let x=`${Line truncated
`)}catch{}}async function bB(i,n,r,o){let t=[],u=r?r.startsWith("v")?r:`v${r}`:void 0,l=o||i.split("/").pop()||"";if(u&&l)t.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${u}/${l}`);if(i.startsWith("https://git.ying-qing.cn"))t.push(i);if(u&&l){let D=`https://github.com/${mG}/releases/download/${u}/${l}`;t.push(`https://ghfast.top/${D}`),t.push(`https://gh.ddlc.top/${D}`),t.push(D)}else if(i.includes("github.com"))t.push(`https://ghfast.top/${i}`),t.push(`https://gh.ddlc.top/${i}`),t.push(i);else t.push(i);let e=Array.from(new Set(t)),$,I=6000,g=6000,b=307200,w=1e4,f=180000;for(let D=0;D<e.length;D++){let S=e[D],N=new AbortController,L="",V=(Z)=>{L=Z;try{N.abort()}catch{}},Q=setTimeout(()=>{V("Connection timed out (no response headers within 6s)")},I),y,k;try{l$(`==> [${D+1}/${e.length}] Downloading via: ${S}`);let Z=await fetch(S,{signal:N.signal});if(Q)clearTimeout(Q),Q=void 0;if(!Z.ok)throw Error(`HTTP ${Z.status} ${Z.statusText}`);y=setTimeout(()=>{V("Overall download time exceeded 3 minutes")},f);let x=Number(Z.headers.get("content-length"))||0,Gi=Z.body?.getReader();if(!Gi){let wn=Buffer.from(await Z.arrayBuffer());if(wn.length<1000)throw Error(`Downloaded content is suspiciously small (${wn.length} bytes)`);dG(n,wn),l$(`✓ Download succeeded (${(wn.length/1024/1024).toFixed(1)} MB)`);return}let yi=[],Oi=0,oi=0;k=setTimeout(()=>{if(Oi<b){let wn=(Oi/1024).toFixed(1);V(`Initial transfer too slow (${wn} KB < 300 KB in 6s), switching mirror...`)}},g);while(!0){let wn=Gi.read(),sr,oj=new Promise((v$,$$)=>{sr=setTimeout(()=>{$$(Error("Data transfer stalled (no chunk received for 10s)"))},w)}),T0;try{T0=await Promise.race([wn,oj])}finally{if(sr)clearTimeout(sr)}let{done:uj,value:e$}=T0;if(uj)break;if(e$){if(yi.push(e$),Oi+=e$.length,k&&Oi>=b)clearTimeout(k),k=void 0;let v$=Date.now();if(v$-oi>200){oi=v$;let $$=x?Math.round(Oi/x*100):0,lj=(Oi/1048576).toFixed(1),ej=x?(x/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${$$}% (${lj} / ${ej} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let At=Buffer.concat(yi);if(At.length<1000)throw Error(`Downloaded content is suspiciously small (${At.length} bytes)`);dG(n,At),l$(`✓ Download completed successfully (${(At.length/1024/1024).toFixed(1)} MB)`);return}catch(Z){if(Q)clearTimeout(Q);if(k)clearTimeout(k);if(y)clearTimeout(y);let x=L||(Z instanceof Error?Z.message:String(Z));$=Error(x),l$(`
↳ Mirror failed: ${$.message}`)}finally{if(Q)clearTimeout(Q);if(k)clearTimeout(k);if(y)clearTimeout(y)}}throw Error(`Failed to download asset from all mirrors: ${$?.message}`)}function wB(i,n,r){let o=dt("tar",["-xzf",i,"-C",n],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract tar archive: ${o.stderr.toString()}`);CG(i);let t=r==="windows"?"seal-home.exe":"seal-home",u=dt("find",[n,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),l=u.find((e)=>e.endsWith(`/${t}`)||e.endsWith(t));if(l)return l;return u[0]||i}function fB(i,n,r){let o=dt("unzip",["-q","-o",i,"-d",n],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract zip archive: ${o.stderr.toString()}`);CG(i);let t=r==="windows"?"seal-home.exe":"seal-home",u=dt("find",[n,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),l=u.find((e)=>e.endsWith(`/${t}`)||e.endsWith(t));if(l)return l;return u[0]||i}function xG(i,n){let r=i.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0),o=n.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0);for(let t=0;t<Math.max(r.length,o.length);t++){let u=r[t]??0,l=o[t]??0;if(u>l)return 1;if(u<l)return-1}return 0}function Zu(i,n){return xG(i,n)>0}function hG(i,n,r={}){let o=dt(i,n,{cwd:r.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(o.stdout)console.error(o.stdout.trimEnd());if(o.stderr)console.error(o.stderr.trimEnd());if(o.status!==0)throw Error(`${i} ${n.join(" ")} failed with status ${o.status}`)}async function aG(i,n,r,o,t){if(i==="create"){let u=c(t.options.name)??n,l=c(t.options.phone);if(!u||!l)throw Error("Usage: seal-home users create --name <name> --phone <phone> [--dept <deptId>]");let e=c(t.options.dept)??c(t.options.departmentId);await Y("seal_user_create",r,o,{name:u,phone:l,departmentIds:e?[e]:void 0},X(t.options));return}if(i==="reset-password"){let u=n??c(t.options.userId);if(!u)throw Error("Usage: seal-home users reset-password <userId>");await Y("seal_user_reset_password",r,o,{userId:u},X(t.options));return}if(i==="search"||i==="list"){let u=n??c(t.options.keyword)??c(t.options.query)??"";await Y("seal_user_search",r,o,{keyword:u},X(t.options));return}if(i==="get"){let u=n??c(t.options.userId);if(!u)throw Error("Usage: seal-home users get <userId>");await Y("seal_user_get",r,o,{userId:u},X(t.options));return}if(i==="delete"){let u=n??c(t.options.userId);if(!u)throw Error("Usage: seal-home users delete <userId>");await Y("seal_user_delete",r,o,{userId:u},X(t.options));return}if(i==="activate"){let u=n??c(t.options.userId);if(!u)throw Error("Usage: seal-home users activate <userId>");await Y("seal_user_activate",r,o,{userId:u},X(t.options));return}if(i==="delegation"||i==="impersonate"){let u=n??c(t.options.userId)??c(t.options.phone);if(!u)throw Error("Usage: seal-home users delegation <userIdOrPhone> [--note <note>]");let l=c(t.options.note);await Y("seal_user_delegation_create",r,o,{userIdOrPhone:u,note:l},X(t.options));return}throw Error(`Unknown users command: ${i??""}. Run 'seal-home help' for available commands.`)}async function sG(i,n,r,o,t){if(i==="list"){await Y("seal_webhook_list",r,o,{query:c(t.options.query)??c(t.options.keyword),includeSecret:y0(t.options)},X(t.options));return}if(i==="get"||i==="find"){let u=n??c(t.options.selector)??c(t.options.id);if(!u)throw Error("Usage: seal-home webhook get <idOrName> [--show-secret]");await Y("seal_webhook_get",r,o,{selector:u,includeSecret:y0(t.options)},X(t.options));return}if(i==="add"||i==="create"){let u=c(t.options.name)??n,l=c(t.options.resultUrl)??c(t.options["result-url"])??c(t.options.outgoingResultWebhook)??c(t.options["outgoing-result-webhook"]);if(!u||!l)throw Error("Usage: seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let e=W0(t.options);await Y("seal_webhook_add",r,o,{name:u,mode:j0(c(t.options.mode)),outgoingResultWebhook:l,autoApprovalRate:e,secret:c(t.options.secret)},X(t.options));return}if(i==="update"){let u=n??c(t.options.selector)??c(t.options.id);if(!u)throw Error("Usage: seal-home webhook update <idOrName> [options]");let l=c(t.options.secret),e=p(t.options.rotateSecret)??p(t.options["rotate-secret"]);if(l!==void 0&&e)throw Error("Use either --secret or --rotate-secret, not both");let $=c(t.options.name),I=j0(c(t.options.mode)),g=c(t.options.resultUrl)??c(t.options["result-url"])??c(t.options.outgoingResultWebhook)??c(t.options["outgoing-result-webhook"]),b=W0(t.options);if($===void 0&&I===void 0&&g===void 0&&b===void 0&&l===void 0&&!e)throw Error("Webhook update requires at least one field option");await Y("seal_webhook_update",r,o,{selector:u,name:$,mode:I,outgoingResultWebhook:g,autoApprovalRate:b,secret:l,rotateSecret:e},X(t.options));return}if(i==="delete"){let u=n??c(t.options.selector)??c(t.options.id);if(!u)throw Error("Usage: seal-home webhook delete <idOrName> --yes");if(p(t.options.yes)!==!0)throw Error("Refusing to delete Webhook integration without --yes");await Y("seal_webhook_delete",r,o,{selector:u,confirm:!0},X(t.options));return}throw Error(`Unknown webhook command: ${i??""}. Run 'seal-home help' for available commands.`)}var ij=_0(_0(_0(UB(import.meta.url)))),cB=new Set(["config","service","http","serve","update","tools","corps","tool","source","auth","delegation","users","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","changelog"]),nj=Promise.resolve();function Eu(i,n={}){let r=nj.then(()=>SB(i,n));return nj=r.then(()=>{return},()=>{return}),r}async function SB(i,n){let r=[],o=[],t=console.log,u=console.error,l={appRoot:n.appRoot??ij,entryFile:n.entryFile??DB(n.appRoot??ij,"src","cli.ts"),launcher:n.launcher};console.log=(...e)=>{r.pu Line truncated
`;var Kk={"SKILL.md":kk,"agents/openai.yaml":dk,"references/rule-lightweight.md":Gk,"references/approval-bad-cases.md":jk,"references/cli.md":Wk,"references/approval-run-lightweight.md":Jk,"references/approval-attachment-trace.md":Xk,"references/customer-feedback-rule-remediation.md":Yk,"references/enterprise-onboarding.md":Hk,"references/hose-enterprise-auth.md":Pk,"references/hose-enterprise-init.md":Qk};function Bk(){return Kk["SKILL.md"]||""}function qu(){return hk(oK(),".agents","skills","seal-home")}function h4(n=qu()){Fk(n,{recursive:!0});let i=[];for(let[r,o]of Object.entries(Kk)){let t=hk(n,r);Fk(uK(t),{recursive:!0}),rK(t,o,"utf8"),i.push(r)}return{targetDir:n,files:i}}function pk(){let n=qu();return h4(n),{synced:!0,targetDir:n}}function qk(n,i,r){if(n==="dump"||n==="cat"||n==="show"){process.stdout.write(`${Bk()}
`);return}if(n==="install"||n==="init"||n==="sync"){let o=M(r.options.local)||M(r.options.workspace),t=U(r.options.dir)??U(r.options.target)??i,u=t?t:o?o$(process.cwd(),".agents","skills","seal-home"):qu(),e=h4(u);B({installed:!0,targetDir:e.targetDir,fileCount:e.files.length,files:e.files});return}if(n==="status"||n==="get"||!n){let o=qu(),t=o$(process.cwd(),".agents","skills","seal-home");B({global:{dir:o,installed:Vk(o$(o,"SKILL.md"))},local:{dir:t,installed:Vk(o$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${n}. Run 'seal-home help' for available commands.`)}async function Tk(n,i){if(n==="config"){B(await xr(i));return}throw Error(`Unknown source command: ${n??""}. Run 'seal-home help' for available commands.`)}async function _k(n,i,r,o){if(!n)throw Error("Usage: seal-home tool <toolName> [--json '{...}']");await X(n,i,r,ri(o.json),J(o.options))}function Ek(){B(Ut.map((n)=>({name:n.name,description:n.description})))}import{chmodSync as eK,mkdirSync as lK,renameSync as K4,rmSync as vK,unlinkSync as Ck,writeFileSync as Zk}from"node:fs";import{dirname as $K,join as Mk}from"node:path";import{spawnSync as Et}from"node:child_process";function u$(n=process.execPath,i=import.meta.url){if(i.includes("/$bunfs/")||i.includes("\\$bunfs\\"))return!0;let r=n.toLowerCase().replace(/\\/g,"/");return!r.endsWith("/bun")&&!r.endsWith("/bun.exe")}var Rk="yunyingk/seal-home";var IK="SEAL_HOME_GITHUB_REPO";async function xk(n,i={}){let r={appRoot:n.appRoot,entryFile:n.entryFile,stateDir:F4,version:R,launcher:n.launcher},o=i.repo||process.env[IK]?.trim()||Rk,t=i.targetVersion?.trim(),u=t&&t.toLowerCase()!=="latest"?t:void 0;if(u){let j=u.replace(/^v/,""),y=ak(j,R);if(y<0){B({updated:!1,currentVersion:R,targetVersion:j,mode:u$()?"binary":"source",message:`Cannot downgrade seal-home from v${R} to older version v${j}. Updates must be forward-only.`});return}if(y===0&&!i.force){B({updated:!1,currentVersion:R,targetVersion:j,mode:u$()?"binary":"source",message:`seal-home is already at version v${R}. Use --force to reinstall.`});return}}if(i.changelogOnly){let j=await B4(o,i.limit??10);B({currentVersion:R,totalQueried:j.length,releases:j.map((y)=>({version:y.version,tagName:y.tagName,publishedAt:y.publishedAt,author:y.author,releaseNotes:y.notes,releaseUrl:y.htmlUrl,isCurrent:y.version===R,isNewer:Tu(y.version,R)}))});return}if(!u$()){if(i.checkOnly){let y=await B4(o,30),T=y[0],x=T?.version??R,dn=y.find((un)=>un.version===R),Wn=Tu(x,R),An=y.filter((un)=>Tu(un.version,R));B({updated:!1,updateAvailable:Wn,currentVersion:R,currentVersionPublishedAt:dn?.publishedAt,latestVersion:x,latestVersionPublishedAt:T?.publishedAt,behindCount:An.length,pendingReleases:An.map((un)=>({version:un.version,tagName:un.tagName,publishedAt:un.publishedAt,author:un.author,releaseNotes:un.notes,releaseUrl:un.htmlUrl})),releaseNotes:T?.notes??"",releaseUrl:T?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-home update' to git pull & bun install."});return}let j=ar(r).running;if(j)await _t("stop",r);try{mk("git",["-C",n.appRoot,"pull","--ff-only"])}catch(y){console.error(`git pull skipped: ${y instanceof Error?y.message:String(y)}`)}if(mk("bun",["install"],{cwd:n.appRoot}),j)await _t("start",r);B({updated:!0,serviceRestarted:j,version:R,mode:"source"});return}let e=gK(),l=bK(),$=await B4(o,30),I=u?$.find((j)=>j.version===u||j.tagName===u||j.tagName===`v${u}`)??await zk(o,u):$[0]??await zk(o);if(!I){B({updated:!1,currentVersion:R,mode:"binary",message:`Failed to query releases from GitHub repository '${o}'`});return}let g=I.version,b=$.find((j)=>j.version===R),w=Tu(g,R),f=w||Boolean(i.force),c=$.filter((j)=>Tu(j.version,R));if(i.checkOnly){B({updated:!1,updateAvailable:w,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:c.length,pendingReleases:c.map((j)=>({version:j.version,tagName:j.tagName,publishedAt:j.publishedAt,author:j.author,releaseNotes:j.notes,releaseUrl:j.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!f){B({updated:!1,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-home is already up to date (v${R})`});return}let S=wK(I.assets,e,l);if(!S)throw Error(`No compatible binary found for ${e}-${l} in release v${g}. Available assets: ${I.assets.map((j)=>j.name).join(", ")}`);let N=ar(r).running;if(N)await _t("stop",r);let L=process.execPath,K=$K(L),H=Mk(K,`.tmp-update-${Date.now()}`);lK(H,{recursive:!0});try{let j=Mk(H,S.name);await fK(S.downloadUrl,j,I.tagName,S.name);let y=j;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))y=cK(j,H,e);else if(S.name.endsWith(".zip"))y=DK(j,H,e);if(eK(y,493),process.platform==="darwin")try{Et("/usr/bin/codesign",["--remove-signature",y],{stdio:"ignore"}),Et("/usr/bin/codesign",["--force","--sign","-",y],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let x=`${Line truncated
`)}catch{}}async function fK(n,i,r,o){let t=[],u=r?r.startsWith("v")?r:`v${r}`:void 0,e=o||n.split("/").pop()||"";if(u&&e)t.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${u}/${e}`);if(n.startsWith("https://git.ying-qing.cn"))t.push(n);if(u&&e){let c=`https://github.com/${Rk}/releases/download/${u}/${e}`;t.push(`https://ghfast.top/${c}`),t.push(`https://gh.ddlc.top/${c}`),t.push(c)}else if(n.includes("github.com"))t.push(`https://ghfast.top/${n}`),t.push(`https://gh.ddlc.top/${n}`),t.push(n);else t.push(n);let l=Array.from(new Set(t)),$,I=6000,g=6000,b=307200,w=1e4,f=180000;for(let c=0;c<l.length;c++){let S=l[c],N=new AbortController,L="",K=(T)=>{L=T;try{N.abort()}catch{}},H=setTimeout(()=>{K("Connection timed out (no response headers within 6s)")},I),j,y;try{e$(`==> [${c+1}/${l.length}] Downloading via: ${S}`);let T=await fetch(S,{signal:N.signal});if(H)clearTimeout(H),H=void 0;if(!T.ok)throw Error(`HTTP ${T.status} ${T.statusText}`);j=setTimeout(()=>{K("Overall download time exceeded 3 minutes")},f);let x=Number(T.headers.get("content-length"))||0,dn=T.body?.getReader();if(!dn){let wi=Buffer.from(await T.arrayBuffer());if(wi.length<1000)throw Error(`Downloaded content is suspiciously small (${wi.length} bytes)`);Zk(i,wi),e$(`✓ Download succeeded (${(wi.length/1024/1024).toFixed(1)} MB)`);return}let Wn=[],An=0,un=0;y=setTimeout(()=>{if(An<b){let wi=(An/1024).toFixed(1);K(`Initial transfer too slow (${wi} KB < 300 KB in 6s), switching mirror...`)}},g);while(!0){let wi=dn.read(),sr,ud=new Promise((v$,$$)=>{sr=setTimeout(()=>{$$(Error("Data transfer stalled (no chunk received for 10s)"))},w)}),q4;try{q4=await Promise.race([wi,ud])}finally{if(sr)clearTimeout(sr)}let{done:ed,value:l$}=q4;if(ed)break;if(l$){if(Wn.push(l$),An+=l$.length,y&&An>=b)clearTimeout(y),y=void 0;let v$=Date.now();if(v$-un>200){un=v$;let $$=x?Math.round(An/x*100):0,ld=(An/1048576).toFixed(1),vd=x?(x/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${$$}% (${ld} / ${vd} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let At=Buffer.concat(Wn);if(At.length<1000)throw Error(`Downloaded content is suspiciously small (${At.length} bytes)`);Zk(i,At),e$(`✓ Download completed successfully (${(At.length/1024/1024).toFixed(1)} MB)`);return}catch(T){if(H)clearTimeout(H);if(y)clearTimeout(y);if(j)clearTimeout(j);let x=L||(T instanceof Error?T.message:String(T));$=Error(x),e$(`
↳ Mirror failed: ${$.message}`)}finally{if(H)clearTimeout(H);if(y)clearTimeout(y);if(j)clearTimeout(j)}}throw Error(`Failed to download asset from all mirrors: ${$?.message}`)}function cK(n,i,r){let o=Et("tar",["-xzf",n,"-C",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract tar archive: ${o.stderr.toString()}`);Ck(n);let t=r==="windows"?"seal-home.exe":"seal-home",u=Et("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),e=u.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(e)return e;return u[0]||n}function DK(n,i,r){let o=Et("unzip",["-q","-o",n,"-d",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract zip archive: ${o.stderr.toString()}`);Ck(n);let t=r==="windows"?"seal-home.exe":"seal-home",u=Et("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),e=u.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(e)return e;return u[0]||n}function ak(n,i){let r=n.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0),o=i.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0);for(let t=0;t<Math.max(r.length,o.length);t++){let u=r[t]??0,e=o[t]??0;if(u>e)return 1;if(u<e)return-1}return 0}function Tu(n,i){return ak(n,i)>0}function mk(n,i,r={}){let o=Et(n,i,{cwd:r.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(o.stdout)console.error(o.stdout.trimEnd());if(o.stderr)console.error(o.stderr.trimEnd());if(o.status!==0)throw Error(`${n} ${i.join(" ")} failed with status ${o.status}`)}async function sk(n,i,r,o,t){if(n==="create"){let u=U(t.options.name)??i,e=U(t.options.phone);if(!u||!e)throw Error("Usage: seal-home users create --name <name> --phone <phone> [--dept <deptId>]");let l=U(t.options.dept)??U(t.options.departmentId);await X("seal_user_create",r,o,{name:u,phone:e,departmentIds:l?[l]:void 0},J(t.options));return}if(n==="reset-password"){let u=i??U(t.options.userId);if(!u)throw Error("Usage: seal-home users reset-password <userId>");await X("seal_user_reset_password",r,o,{userId:u},J(t.options));return}if(n==="search"||n==="list"){let u=i??U(t.options.keyword)??U(t.options.query)??"";await X("seal_user_search",r,o,{keyword:u},J(t.options));return}if(n==="get"){let u=i??U(t.options.userId);if(!u)throw Error("Usage: seal-home users get <userId>");await X("seal_user_get",r,o,{userId:u},J(t.options));return}if(n==="delete"){let u=i??U(t.options.userId);if(!u)throw Error("Usage: seal-home users delete <userId>");await X("seal_user_delete",r,o,{userId:u},J(t.options));return}if(n==="activate"){let u=i??U(t.options.userId);if(!u)throw Error("Usage: seal-home users activate <userId>");await X("seal_user_activate",r,o,{userId:u},J(t.options));return}if(n==="delegation"||n==="impersonate"){let u=i??U(t.options.userId)??U(t.options.phone);if(!u)throw Error("Usage: seal-home users delegation <userIdOrPhone> [--note <note>]");let e=U(t.options.note);await X("seal_user_delegation_create",r,o,{userIdOrPhone:u,note:e},J(t.options));return}throw Error(`Unknown users command: ${n??""}. Run 'seal-home help' for available commands.`)}async function nd(n,i,r,o,t){if(n==="list"){await X("seal_webhook_list",r,o,{query:U(t.options.query)??U(t.options.keyword),includeSecret:j4(t.options)},J(t.options));return}if(n==="get"||n==="find"){let u=i??U(t.options.selector)??U(t.options.id);if(!u)throw Error("Usage: seal-home webhook get <idOrName> [--show-secret]");await X("seal_webhook_get",r,o,{selector:u,includeSecret:j4(t.options)},J(t.options));return}if(n==="add"||n==="create"){let u=U(t.options.name)??i,e=U(t.options.resultUrl)??U(t.options["result-url"])??U(t.options.outgoingResultWebhook)??U(t.options["outgoing-result-webhook"]);if(!u||!e)throw Error("Usage: seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let l=G4(t.options);await X("seal_webhook_add",r,o,{name:u,mode:d4(U(t.options.mode)),outgoingResultWebhook:e,autoApprovalRate:l,secret:U(t.options.secret)},J(t.options));return}if(n==="update"){let u=i??U(t.options.selector)??U(t.options.id);if(!u)throw Error("Usage: seal-home webhook update <idOrName> [options]");let e=U(t.options.secret),l=M(t.options.rotateSecret)??M(t.options["rotate-secret"]);if(e!==void 0&&l)throw Error("Use either --secret or --rotate-secret, not both");let $=U(t.options.name),I=d4(U(t.options.mode)),g=U(t.options.resultUrl)??U(t.options["result-url"])??U(t.options.outgoingResultWebhook)??U(t.options["outgoing-result-webhook"]),b=G4(t.options);if($===void 0&&I===void 0&&g===void 0&&b===void 0&&e===void 0&&!l)throw Error("Webhook update requires at least one field option");await X("seal_webhook_update",r,o,{selector:u,name:$,mode:I,outgoingResultWebhook:g,autoApprovalRate:b,secret:e,rotateSecret:l},J(t.options));return}if(n==="delete"){let u=i??U(t.options.selector)??U(t.options.id);if(!u)throw Error("Usage: seal-home webhook delete <idOrName> --yes");if(M(t.options.yes)!==!0)throw Error("Refusing to delete Webhook integration without --yes");await X("seal_webhook_delete",r,o,{selector:u,confirm:!0},J(t.options));return}throw Error(`Unknown webhook command: ${n??""}. Run 'seal-home help' for available commands.`)}var id=p4(p4(p4(SK(import.meta.url)))),OK=new Set(["config","service","http","serve","update","tools","corps","tool","source","auth","delegation","users","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","changelog"]),td=Promise.resolve();function Vu(n,i={}){let r=td.then(()=>AK(n,i));return td=r.then(()=>{return},()=>{return}),r}async function AK(n,i){let r=[],o=[],t=console.log,u=console.error,e={appRoot:i.appRoot??id,entryFile:i.entryFile??UK(i.appRoot??id,"src","cli.ts"),launcher:i.launcher};console.log=(...l)=>{r.pu Line truncated
`)?"":`
`}`);process.exitCode=i.exitCode}var yB=Boolean(M0.main==M0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&tj(process.argv[1])===tj(pn));if(yB)if(process.argv[2]==="--seal-home-cli")await WB();else Q0().catch((i)=>{console.error(i),process.exitCode=1});export{Y0 as tokenizeCommand,Q0 as startServer,kB as resolveMcpEnabled,GB as createServer,LB as SEAL_MCP_ENABLED_ENV,NB as SEAL_CLI_TOOL_NAME};
`}`);process.exitCode=n.exitCode}var JK=Boolean(_4.main==_4.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&rd(process.argv[1])===rd(Mi));if(JK)if(process.argv[2]==="--seal-home-cli")await WK();else H4().catch((n)=>{console.error(n),process.exitCode=1});export{X4 as tokenizeCommand,H4 as startServer,dK as resolveMcpEnabled,GK as createServer,kK as SEAL_MCP_ENABLED_ENV,yK as SEAL_CLI_TOOL_NAME};
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "seal-home Wrapped API",
"version": "0.9.6",
"version": "0.9.7",
"description": "Planned HTTP contract for the seal-home 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-home is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: seal-home Wrapped API
version: 0.9.6
version: 0.9.7
description: |
Planned HTTP contract for the seal-home wrapped backend API.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-home",
"version": "0.9.6",
"version": "0.9.7",
"type": "module",
"module": "src/server.ts",
"bin": {
+12 -4
View File
@@ -1,12 +1,12 @@
---
name: seal-home
description: "v0.9.6: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
description: "v0.9.7: Use for Seal Home 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.9.6
short-description: Seal tenant and Hose approval automation (v0.9.6)
version: 0.9.7
short-description: Seal tenant and Hose approval automation (v0.9.7)
---
# Seal Home (v0.9.6)
# Seal Home (v0.9.7)
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-home` 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.
@@ -18,6 +18,11 @@ seal-home tools list
## First Rules
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
- Before asking for enterprise parameters, run `seal-home corps list`. If the target is already configured, resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`.
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read `references/enterprise-onboarding.md` before asking questions or running setup commands.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
- Never ask a normal user for `corpId`, `staffId`, `proxyStaffBizId`, `tenantId`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use `seal-home corps ...`.
@@ -34,6 +39,7 @@ seal-home tools list
## Route By Intent
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read `references/enterprise-onboarding.md`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-home 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.
- 模拟测试发布闭环: `seal-home simulation create --mode hosecloud --flow-ids ... --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
@@ -90,10 +96,12 @@ seal-home tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅
## References
- `references/enterprise-onboarding.md`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- `references/approval-run-lightweight.md`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- `references/rule-lightweight.md`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- `references/customer-feedback-rule-remediation.md`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- `references/hose-enterprise-auth.md`: Hose 企业配置、认证诊断、授权链接。
- `references/hose-enterprise-init.md`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
- `references/approval-attachment-trace.md`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。
- `references/cli.md`: 完整 CLI 命令清单。
@@ -0,0 +1,117 @@
# Enterprise Onboarding
Read 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.
## Start With Discovery
Run this before asking for setup parameters:
```bash
seal-home version
seal-home corps list
```
- 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`.
- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.
- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”
Do not open with a JSON template or a list of internal fields.
All 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.
## Keep Two Concepts Separate
Classify both the enterprise identity origin and how the current credential was acquired:
| Enterprise identity origin | Credential material the user may have | Meaning |
| --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |
| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |
| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |
Credential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.
## Parameter Ownership
Ask the user only for information that cannot be discovered safely:
| Field | Owner and behavior |
| --- | --- |
| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |
| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |
| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |
| 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. |
| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |
| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |
## Route 1: Standard Hose Credentials
This is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:
```bash
seal-home corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
```
The CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:
```bash
seal-home auth diagnose --corp <discovered-id>
```
Do not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.
## Route 2: Incoming Assistance Link
First distinguish the link by its host and purpose:
- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.
- `seal-home auth hose-link` and `seal-home delegation create` generate links for an enterprise that is already configured; they do not import a new enterprise from a received link.
The current CLI does not directly import an incoming assistance link. Do not pretend that `corps add-hose` or `corps add-seal` accepts the raw URL. If a browser tool is available and the user authorized opening the link, open it, confirm the final tenant host, and obtain an authenticated Seal business request. Otherwise explain that the link must be opened in the user's browser, then continue with the browser cURL route below.
Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it.
## Route 3: Browser F12 cURL
When the user needs capture instructions, give these concrete steps:
1. Open the already signed-in Hose or Seal page.
2. Open browser developer tools: `F12` on many keyboards, or `Option+Command+I` on macOS.
3. Open **Network**, then select **Fetch/XHR**.
4. Refresh the page or perform one ordinary read-only business action.
5. Choose a successful business API request from the relevant tenant, not analytics, static assets, upload, delete, publish, or logout requests.
6. Right-click it and choose **Copy → Copy as cURL**.
7. Send that complete cURL only to the local trusted Agent handling setup.
When receiving cURL:
1. Treat the entire cURL as a secret. Do not echo it, execute it blindly, paste it into another service, or store it in repository files.
2. Parse it as data. Extract the request host, path, `Authorization` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3. Classify whether the captured request is to Hose or Seal. A Seal request with `Authorization: Bearer ...` can supply `sealUrl` and a session token even when the user's identity origin is Hose.
4. Verify with the narrowest read-only identity endpoint available. For a Seal Bearer session, verify `/api/v1/auth/me` through `seal-home corps add-seal`; use returned provider metadata to retain the actual origin.
5. Persist only the normalized minimum configuration needed by seal-home. Do not preserve the raw cURL, unrelated headers, request body, cookies, or signed URL.
For a verified Seal Bearer captured from cURL, the existing CLI route is:
```bash
seal-home corps add-seal --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
```
The current CLI has no raw-cURL import command and `add-seal` requires a Bearer token. If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
## Verify and Hand Off
After adding an enterprise:
```bash
seal-home corps list
seal-home corps current --corp <discovered-id>
seal-home auth diagnose --corp <discovered-id> # Hose source
```
Report the human enterprise name, identity provider, credential method, and whether verification succeeded. Do not expose internal IDs unless they help with troubleshooting. Do not perform approval, rule, document, simulation, publishing, or other business mutations just because onboarding succeeded; continue only with the user's requested task and its normal confirmation rules.
If a temporary assistance-link or browser session expires, explain that it must be renewed or recaptured. Recommend standard Hose app credentials when the user needs durable unattended access.
@@ -6,14 +6,18 @@ Use this reference for Hose/合思 enterprise configuration and user-facing Hose
Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit `~/.config/seal-home/enterprises/*.json` unless the CLI fails or the user explicitly asks for low-level config debugging.
For first-time setup or when the user has an assistance link or browser cURL instead of standard application credentials, read `enterprise-onboarding.md` first. This reference's `add-hose` route is specifically for durable Hose OpenAPI credentials.
```bash
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-home corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
seal-home corps list
seal-home corps current --corp <corpId>
seal-home corps switch <corpId>
```
`corps add-hose` verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at `corps` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
`corps add-hose` probes standard domains and discovers the enterprise automatically. If it returns multiple administrator candidates, present their names and masked phones for the user to choose, then retry with `staffName`, `staffPhone`, or the selected `staffId`. Do not ask for `domain`, `corpId`, `staffId`, or `proxyStaffBizId` before discovery. Ask for a dedicated/private-cloud `domain` only after standard probing fails.
The command verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at `corps` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
## Diagnose authentication
+2
View File
@@ -9,6 +9,7 @@ describe("embedded-skill", () => {
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: seal-home");
expect(EMBEDDED_SKILL_FILES["references/cli.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["references/enterprise-onboarding.md"]).toContain("# Enterprise Onboarding");
expect(getSkillContent()).toContain("name: seal-home");
});
@@ -20,6 +21,7 @@ describe("embedded-skill", () => {
expect(res.files.length).toBeGreaterThan(5);
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "cli.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "enterprise-onboarding.md"))).toBe(true);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
+2
View File
@@ -10,6 +10,7 @@ import refCli from "../../skills/seal-home/references/cli.md" with { type: "text
import refApprovalRunLightweight from "../../skills/seal-home/references/approval-run-lightweight.md" with { type: "text" };
import refApprovalAttachmentTrace from "../../skills/seal-home/references/approval-attachment-trace.md" with { type: "text" };
import refCustomerFeedbackRuleRemediation from "../../skills/seal-home/references/customer-feedback-rule-remediation.md" with { type: "text" };
import refEnterpriseOnboarding from "../../skills/seal-home/references/enterprise-onboarding.md" with { type: "text" };
import refHoseEnterpriseAuth from "../../skills/seal-home/references/hose-enterprise-auth.md" with { type: "text" };
import refHoseEnterpriseInit from "../../skills/seal-home/references/hose-enterprise-init.md" with { type: "text" };
@@ -22,6 +23,7 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
"references/approval-run-lightweight.md": refApprovalRunLightweight,
"references/approval-attachment-trace.md": refApprovalAttachmentTrace,
"references/customer-feedback-rule-remediation.md": refCustomerFeedbackRuleRemediation,
"references/enterprise-onboarding.md": refEnterpriseOnboarding,
"references/hose-enterprise-auth.md": refHoseEnterpriseAuth,
"references/hose-enterprise-init.md": refHoseEnterpriseInit
};