Compare commits

...
4 Commits
Author SHA1 Message Date
yunyingk 1299d70777 Merge pull request #31 from yunyingk/codex/release-v0.10.5
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.5: Intelligent HoseCloud sync discovery, actionable guidance, and --auto support (Fixes #26)
2026-09-03 11:42:54 +08:00
gitea 0a3c984018 Release v0.10.5: Intelligent HoseCloud sync discovery, actionable guidance, and --auto support (Fixes #26) 2026-09-03 11:41:56 +08:00
yunyingk 923184e623 Merge pull request #29 from yunyingk/codex/release-v0.10.4
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.4: Built-in rule linter, dynamic TS plugin loader with fault-tolerant fallback, and default-disabled global config
2026-09-03 11:31:50 +08:00
gitea 1cf35dfd78 Release v0.10.4: Built-in rule linter, dynamic TS plugin loader with fault-tolerant fallback, and default-disabled global config 2026-09-03 11:30:52 +08:00
25 changed files with 1000 additions and 87 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.3",
"version": "0.10.5",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+19
View File
@@ -5,6 +5,25 @@ All notable changes to `seal-use` 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.10.5] - 2026-09-03
### Added & Enhanced
- **Intelligent HoseCloud Sync Discovery & Actionable Guidance (Issue #26)**: In `seal-use deploy hosecloud sync` and `deploy hosecloud get`, when `<sign-key>` is omitted, the CLI dynamically discovers all active HoseCloud integration configs for the tenant and renders structured cards on `stderr` with 1-click copy commands (e.g. `👉 同步命令: seal-use deploy hosecloud sync <signKey> --corp <corpId>`).
- **Single-Config Fast Track (`--auto`)**: Added `--auto` (and `--yes`) flag to `deploy hosecloud sync`. When a tenant has exactly one configured HoseCloud integration, `--auto` automatically locks and syncs without requiring manual `signKey` extraction.
- **Enhanced Empty State & Diagnostic Hints**: If a tenant has zero HoseCloud integrations configured, clearly prompts the user with next-step configuration command `seal-use deploy hosecloud configure ...`.
- **Updated Reference Documentation**: Updated `skills/seal-use/references/hose-enterprise-deploy.md` and CLI references with `--auto` and dynamic discovery patterns.
## [0.10.4] - 2026-09-03
### Added & Enhanced
- **Built-in Approval Rule Linter & Quality Validation Engine**: Introduced a pure TypeScript/heuristic rule quality validator (`seal-use rules lint` & `seal_approval_rules_lint`). Detects subjective fuzzy words (`原则上`, `尽量`, `适当`, `酌情`), hanging exception clauses lacking evidence keywords (`除非/特殊情况` 未指明 `备注/附件/截图` 凭证来源), and short invalid descriptions.
- **Plugin-as-Code Dynamic TS Linter Loader**: Supports loading custom enterprise TypeScript linter plugins dynamically from `~/.config/seal-use/linters/*.ts` or explicit paths (`--linter <name|path>`).
- **Fault-Tolerant Automatic Fallback (Anti-Crash Guarantee)**: If a user's custom `.ts` linter file contains syntax errors, throws runtime exceptions, or is missing, the engine automatically catches errors, logs diagnostic warnings to `stderr`, and seamlessly falls back to the built-in heuristic linter without failing or blocking CLI execution.
- **Global Config & Default-Disabled Policy**: Added `lint: { enabled: false, activeLinter: "builtin", minScore: 0 }` to global configuration (`~/.config/seal-use/config.json`). Linter is **disabled by default** to avoid unsolicited noise; can be enabled via `seal-use config lint enable`.
- **Real-time Diagnostic Hook on Rule Updates**: When linting is enabled, `seal_approval_rule_update` automatically inspects modified descriptions and outputs structured warnings on `stderr` while keeping clean machine JSON on `stdout`.
- **Comprehensive Scenarios & Gatekeeping**: `seal-use rules lint` supports full draft scanning, historical version review (`--version <num>`), rule filtering (`--code <code>`), summary mode (`--summary`), and quality gate scoring (`--min-score <score>`) with non-zero exit codes.
- **Dedicated Reference Documentation**: Added `skills/seal-use/references/rule-lint.md` and updated SKILL router.
## [0.10.3] - 2026-09-02
### Added & Enhanced
+71 -61
View File
@@ -1,37 +1,37 @@
import{createRequire as _y}from"node:module";var Qy=Object.create;var{getPrototypeOf:Py,defineProperty:O$,getOwnPropertyNames:Fy}=Object;var Ky=Object.prototype.hasOwnProperty;function By(n){return this[n]}var Ey,Ty,t0=(n,i,r)=>{var o=n!=null&&typeof n==="object";if(o){var t=i?Ey??=new WeakMap:Ty??=new WeakMap,u=t.get(n);if(u)return u}r=n!=null?Qy(Py(n)):{};let e=i||!n||!n.__esModule?O$(r,"default",{value:n,enumerable:!0}):r;for(let l of Fy(n))if(!Ky.call(e,l))O$(e,l,{get:By.bind(n,l),enumerable:!0});if(o)t.set(n,e);return e};var Y=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports);var Vy=(n)=>n;function qy(n,i){this[n]=Vy.bind(null,i)}var Pi=(n,i)=>{for(var r in i)O$(n,r,{get:i[r],enumerable:!0,configurable:!0,set:qy.bind(i,r)})};var r0=_y(import.meta.url);var nu=Y((YD)=>{Object.defineProperty(YD,"__esModule",{value:!0});YD.regexpCode=YD.getEsmExportName=YD.getProperty=YD.safeStringify=YD.stringify=YD.strConcat=YD.addCodeArg=YD.str=YD._=YD.nil=YD._Code=YD.Name=YD.IDENTIFIER=YD._CodeOrName=void 0;class Tl{}YD._CodeOrName=Tl;YD.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class jr extends Tl{constructor(n){super();if(!YD.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}}}YD.Name=jr;class fi extends Tl{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 jr)i[r.str]=(i[r.str]||0)+1;return i},{})}}YD._Code=fi;YD.nil=new fi("");function XD(n,...i){let r=[n[0]],o=0;while(o<i.length)Qc(r,i[o]),r.push(n[++o]);return new fi(r)}YD._=XD;var pc=new fi("+");function HD(n,...i){let r=[so(n[0])],o=0;while(o<i.length)r.push(pc),Qc(r,i[o]),r.push(pc,so(n[++o]));return IX(r),new fi(r)}YD.str=HD;function Qc(n,i){if(i instanceof fi)n.push(...i._items);else if(i instanceof jr)n.push(i);else n.push(wX(i))}YD.addCodeArg=Qc;function IX(n){let i=1;while(i<n.length-1){if(n[i]===pc){let r=gX(n[i-1],n[i+1]);if(r!==void 0){n.splice(i-1,3,r);continue}n[i++]="+"}i++}}function gX(n,i){if(i==='""')return n;if(n==='""')return i;if(typeof n=="string"){if(i instanceof jr||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 jr))return`"${n}${i.slice(1)}`;return}function bX(n,i){return i.emptyStr()?n:n.emptyStr()?i:HD`${n}${i}`}YD.strConcat=bX;function wX(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:so(Array.isArray(n)?n.join(","):n)}function fX(n){return new fi(so(n))}YD.stringify=fX;function so(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}YD.safeStringify=so;function cX(n){return typeof n=="string"&&YD.IDENTIFIER.test(n)?new fi(`.${n}`):XD`[${n}]`}YD.getProperty=cX;function UX(n){if(typeof n=="string"&&YD.IDENTIFIER.test(n))return new fi(`${n}`);throw Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}YD.getEsmExportName=UX;function DX(n){return new fi(n.toString())}YD.regexpCode=DX});var Bc=Y((FD)=>{Object.defineProperty(FD,"__esModule",{value:!0});FD.ValueScope=FD.ValueScopeName=FD.Scope=FD.varKinds=FD.UsedValueState=void 0;var an=nu();class QD extends Error{constructor(n){super(`CodeGen: "code" for ${n} not defined`);this.value=n.value}}var ql;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed"})(ql||(FD.UsedValueState=ql={}));FD.varKinds={const:new an.Name("const"),let:new an.Name("let"),var:new an.Name("var")};class Fc{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}}}FD.Scope=Fc;class Kc 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}]`}}FD.ValueScopeName=Kc;var XX=an._`\n`;class PD extends Fc{constructor(n){super(n);this._values={},this._scope=n.scope,this.opts={...n,_n:n.lines?XX:an.nil}}get(){return this._scope}name(n){return new Kc(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 ci.Scope({parent:n}),this._nodes=[new ZD]}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 BD(n,t,r)),t}const(n,i,r){return this._def(ci.varKinds.const,n,i,r)}let(n,i,r){return this._def(ci.varKinds.let,n,i,r)}var(n,i,r){return this._def(ci.varKinds.var,n,i,r)}assign(n,i,r){return this._leafNode(new Vc(n,i,r))}add(n,i){return this._leafNode(new ED(n,sn.operators.ADD,i))}code(n){if(typeof n=="function")n();else if(n!==s.nil)this._leafNode(new _D(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 Ti(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 Ti(n))}else(){return this._elseNode(new iu)}endIf(){return this._endBlockNode(Ti,iu)}_for(n,i){if(this._blockNode(n),i)this.code(i).endFor();return this}for(n,i){return this._for(new MD(n),i)}forRange(n,i,r,o,t=this.opts.es5?ci.varKinds.var:ci.varKinds.let){let u=this._scope.toName(n);return this._for(new zD(t,u,i,r),()=>o(u))}forOf(n,i,r,o=ci.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 Ec("of",o,t,i),()=>r(t))}forIn(n,i,r,o=this.opts.es5?ci.varKinds.var:ci.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 Ec("in",o,t,i),()=>r(t))}endFor(){return this._endBlockNode(Jr)}label(n){return this._leafNode(new TD(n))}break(n){return this._leafNode(new VD(n))}return(n){let i=new Zl;if(this._blockNode(i),this.code(n),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Zl)}try(n,i,r){if(!i&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new CD;if(this._blockNode(o),this.code(n),i){let t=this.name("e");this._currNode=o.catch=new Ml(t),i(t)}if(r)this._currNode=o.finally=new zl,this.code(r);return this._endBlockNode(Ml,zl)}throw(n){return this._leafNode(new qD(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 _l(n,i,r)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(_l)}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 Ti))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=RD;function Xt(n,i){for(let r in i)n[r]=(n[r]||0)+(i[r]||0);return n}function Cl(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 QX(n,i){for(let r in i)n[r]=(n[r]||0)-(i[r]||0)}function hD(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:s._`!${Tc(n)}`}sn.not=hD;var PX=mD(sn.operators.AND);function FX(...n){return n.reduce(PX)}sn.and=FX;var KX=mD(sn.operators.OR);function BX(...n){return n.reduce(KX)}sn.or=BX;function mD(n){return(i,r)=>i===s.nil?r:r===s.nil?i:s._`${Tc(i)} ${n} ${Tc(r)}`}function Tc(n){return n instanceof s.Name?n:s._`(${n})`}});var tn=Y((u1)=>{Object Line truncated
import{createRequire as sN}from"node:module";var ZN=Object.create;var{getPrototypeOf:MN,defineProperty:O$,getOwnPropertyNames:zN}=Object;var CN=Object.prototype.hasOwnProperty;function RN(n){return this[n]}var hN,mN,$4=(n,i,r)=>{var o=n!=null&&typeof n==="object";if(o){var t=i?hN??=new WeakMap:mN??=new WeakMap,u=t.get(n);if(u)return u}r=n!=null?ZN(MN(n)):{};let e=i||!n||!n.__esModule?O$(r,"default",{value:n,enumerable:!0}):r;for(let l of zN(n))if(!CN.call(e,l))O$(e,l,{get:RN.bind(n,l),enumerable:!0});if(o)t.set(n,e);return e};var H=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports);var xN=(n)=>n;function aN(n,i){this[n]=xN.bind(null,i)}var Fi=(n,i)=>{for(var r in i)O$(n,r,{get:i[r],enumerable:!0,configurable:!0,set:aN.bind(i,r)})};var I4=sN(import.meta.url);var ru=H((ED)=>{Object.defineProperty(ED,"__esModule",{value:!0});ED.regexpCode=ED.getEsmExportName=ED.getProperty=ED.safeStringify=ED.stringify=ED.strConcat=ED.addCodeArg=ED.str=ED._=ED.nil=ED._Code=ED.Name=ED.IDENTIFIER=ED._CodeOrName=void 0;class Zl{}ED._CodeOrName=Zl;ED.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Jr extends Zl{constructor(n){super();if(!ED.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}}}ED.Name=Jr;class wi extends Zl{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 Jr)i[r.str]=(i[r.str]||0)+1;return i},{})}}ED._Code=wi;ED.nil=new wi("");function PD(n,...i){let r=[n[0]],o=0;while(o<i.length)Kc(r,i[o]),r.push(n[++o]);return new wi(r)}ED._=PD;var Fc=new wi("+");function BD(n,...i){let r=[tu(n[0])],o=0;while(o<i.length)r.push(Fc),Kc(r,i[o]),r.push(Fc,tu(n[++o]));return dJ(r),new wi(r)}ED.str=BD;function Kc(n,i){if(i instanceof wi)n.push(...i._items);else if(i instanceof Jr)n.push(i);else n.push(yJ(i))}ED.addCodeArg=Kc;function dJ(n){let i=1;while(i<n.length-1){if(n[i]===Fc){let r=kJ(n[i-1],n[i+1]);if(r!==void 0){n.splice(i-1,3,r);continue}n[i++]="+"}i++}}function kJ(n,i){if(i==='""')return n;if(n==='""')return i;if(typeof n=="string"){if(i instanceof Jr||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 Jr))return`"${n}${i.slice(1)}`;return}function OJ(n,i){return i.emptyStr()?n:n.emptyStr()?i:BD`${n}${i}`}ED.strConcat=OJ;function yJ(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:tu(Array.isArray(n)?n.join(","):n)}function LJ(n){return new wi(tu(n))}ED.stringify=LJ;function tu(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ED.safeStringify=tu;function NJ(n){return typeof n=="string"&&ED.IDENTIFIER.test(n)?new wi(`.${n}`):PD`[${n}]`}ED.getProperty=NJ;function GJ(n){if(typeof n=="string"&&ED.IDENTIFIER.test(n))return new wi(`${n}`);throw Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}ED.getEsmExportName=GJ;function WJ(n){return new wi(n.toString())}ED.regexpCode=WJ});var Tc=H((qD)=>{Object.defineProperty(qD,"__esModule",{value:!0});qD.ValueScope=qD.ValueScopeName=qD.Scope=qD.varKinds=qD.UsedValueState=void 0;var sn=ru();class VD extends Error{constructor(n){super(`CodeGen: "code" for ${n} not defined`);this.value=n.value}}var zl;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed"})(zl||(qD.UsedValueState=zl={}));qD.varKinds={const:new sn.Name("const"),let:new sn.Name("let"),var:new sn.Name("var")};class Bc{constructor({prefixes:n,parent:i}={}){this._names={},this._prefixes=n,this._parent=i}toName(n){return n instanceof sn.Name?n:this.name(n)}name(n){return new sn.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}}}qD.Scope=Bc;class Ec extends sn.Name{constructor(n,i){super(i);this.prefix=n}setValue(n,{property:i,itemIndex:r}){this.value=n,this.scopePath=sn._`.${new sn.Name(i)}[${r}]`}}qD.ValueScopeName=Ec;var TJ=sn._`\n`;class _D extends Bc{constructor(n){super(n);this._values={},this._scope=n.scope,this.opts={...n,_n:n.lines?TJ:sn.nil}}get(){return this._scope}name(n){return new Ec(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 ci.Scope({parent:n}),this._nodes=[new xD]}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 MD(n,t,r)),t}const(n,i,r){return this._def(ci.varKinds.const,n,i,r)}let(n,i,r){return this._def(ci.varKinds.let,n,i,r)}var(n,i,r){return this._def(ci.varKinds.var,n,i,r)}assign(n,i,r){return this._leafNode(new qc(n,i,r))}add(n,i){return this._leafNode(new zD(n,ni.operators.ADD,i))}code(n){if(typeof n=="function")n();else if(n!==s.nil)this._leafNode(new mD(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 Ti(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 Ti(n))}else(){return this._elseNode(new ou)}endIf(){return this._endBlockNode(Ti,ou)}_for(n,i){if(this._blockNode(n),i)this.code(i).endFor();return this}for(n,i){return this._for(new aD(n),i)}forRange(n,i,r,o,t=this.opts.es5?ci.varKinds.var:ci.varKinds.let){let u=this._scope.toName(n);return this._for(new sD(t,u,i,r),()=>o(u))}forOf(n,i,r,o=ci.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 Vc("of",o,t,i),()=>r(t))}forIn(n,i,r,o=this.opts.es5?ci.varKinds.var:ci.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 Vc("in",o,t,i),()=>r(t))}endFor(){return this._endBlockNode(Xr)}label(n){return this._leafNode(new CD(n))}break(n){return this._leafNode(new RD(n))}return(n){let i=new Rl;if(this._blockNode(i),this.code(n),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Rl)}try(n,i,r){if(!i&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new n1;if(this._blockNode(o),this.code(n),i){let t=this.name("e");this._currNode=o.catch=new hl(t),i(t)}if(r)this._currNode=o.finally=new ml,this.code(r);return this._endBlockNode(hl,ml)}throw(n){return this._leafNode(new hD(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 Cl(n,i,r)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(Cl)}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 Ti))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}}ni.CodeGen=i1;function Yt(n,i){for(let r in i)n[r]=(n[r]||0)+(i[r]||0);return n}function xl(n,i){return i instanceof s._CodeOrName?Yt(n,i.names):n}function Hr(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 ZJ(n,i){for(let r in i)n[r]=(n[r]||0)-(i[r]||0)}function t1(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:s._`!${_c(n)}`}ni.not=t1;var MJ=r1(ni.operators.AND);function zJ(...n){return n.reduce(MJ)}ni.and=zJ;var CJ=r1(ni.operators.OR);function RJ(...n){return n.reduce(CJ)}ni.or=RJ;function r1(n){return(i,r)=>i===s.nil?r:r===s.nil?i:s._`${_c(i)} ${n} ${_c(r)}`}function _c(n){return n instanceof s.Name?n:s._`(${n})`}});var tn=H((b1)=>{Object Line truncated
|| (${e} == "string" && ${t} && ${t} == +${t})`).assign(l,C._`+${t}`);return;case"integer":o.elseIf(C._`${e} === "boolean" || ${t} === null
|| (${e} === "string" && ${t} && ${t} == +${t} && !(${t} % 1))`).assign(l,C._`+${t}`);return;case"boolean":o.elseIf(C._`${t} === "false" || ${t} === 0 || ${t} === null`).assign(l,!1).elseIf(C._`${t} === "true" || ${t} === 1`).assign(l,!0);return;case"null":o.elseIf(C._`${t} === "" || ${t} === 0 || ${t} === false`),o.assign(l,null);return;case"array":o.elseIf(C._`${e} === "string" || ${e} === "number"
|| ${e} === "boolean" || ${t} === null`).assign(l,C._`[${t}]`)}}}function x8({gen:n,parentData:i,parentDataProperty:r},o){n.if(C._`${i} !== undefined`,()=>n.assign(C._`${i}[${r}]`,o))}function Rc(n,i,r,o=Hr.Correct){let t=o===Hr.Correct?C.operators.EQ:C.operators.NEQ,u;switch(n){case"null":return C._`${i} ${t} null`;case"array":u=C._`Array.isArray(${i})`;break;case"object":u=C._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":u=e(C._`!(${i} % 1) && !isNaN(${i})`);break;case"number":u=e();break;default:return C._`typeof ${i} ${t} ${n}`}return o===Hr.Correct?u:(0,C.not)(u);function e(l=C.nil){return(0,C.and)(C._`typeof ${i} == "number"`,l,r?C._`isFinite(${i})`:C.nil)}}G1.checkDataType=Rc;function hc(n,i,r,o){if(n.length===1)return Rc(n[0],i,r,o);let t,u=(0,N1.toHash)(n);if(u.array&&u.object){let e=C._`typeof ${i} != "object"`;t=u.null?e:C._`!${i} || ${e}`,delete u.null,delete u.array,delete u.object}else t=C.nil;if(u.number)delete u.integer;for(let e in u)t=(0,C.and)(t,Rc(e,i,r,o));return t}G1.checkDataTypes=hc;var a8={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:i})=>typeof n=="string"?C._`{type: ${n}}`:C._`{type: ${i}}`};function mc(n){let i=s8(n);(0,z8.reportError)(i,a8)}G1.reportTypeError=mc;function s8(n){let{gen:i,data:r,schema:o}=n,t=(0,N1.schemaRefOrVal)(n,o,"type");return{gen:i,keyword:"type",data:r,schema:o.type,schemaCode:t,schemaValue:t,parentSchema:o,params:{},it:n}}});var H1=Y((J1)=>{Object.defineProperty(J1,"__esModule",{value:!0});J1.assignDefaults=void 0;var Yr=R(),e9=tn();function l9(n,i){let{properties:r,items:o}=n.schema;if(i==="object"&&r)for(let t in r)j1(n,t,r[t].default);else if(i==="array"&&Array.isArray(o))o.forEach((t,u)=>j1(n,u,t.default))}J1.assignDefaults=l9;function j1(n,i,r){let{gen:o,compositeRule:t,data:u,opts:e}=n;if(r===void 0)return;let l=Yr._`${u}${(0,Yr.getProperty)(i)}`;if(t){(0,e9.checkStrictMode)(n,`default is ignored for: ${l}`);return}let $=Yr._`${l} === undefined`;if(e.useDefaults==="empty")$=Yr._`${$} || ${l} === null || ${l} === ""`;o.if($,Yr._`${l} = ${(0,Yr.stringify)(r)}`)}});var Ii=Y((Q1)=>{Object.defineProperty(Q1,"__esModule",{value:!0});Q1.validateUnion=Q1.validateArray=Q1.usePattern=Q1.callValidateCode=Q1.schemaProperties=Q1.allSchemaProperties=Q1.noPropertyInData=Q1.propertyInData=Q1.isOwnProperty=Q1.hasPropFunc=Q1.reportMissingProp=Q1.checkMissingProp=Q1.checkReportMissingProp=void 0;var Dn=R(),xc=tn(),gt=Vi(),v9=tn();function $9(n,i){let{gen:r,data:o,it:t}=n;r.if(sc(r,o,i,t.opts.ownProperties),()=>{n.setParams({missingProperty:Dn._`${i}`},!0),n.error()})}Q1.checkReportMissingProp=$9;function I9({gen:n,data:i,it:{opts:r}},o,t){return(0,Dn.or)(...o.map((u)=>(0,Dn.and)(sc(n,i,u,r.ownProperties),Dn._`${t} = ${u}`)))}Q1.checkMissingProp=I9;function g9(n,i){n.setParams({missingProperty:i},!0),n.error()}Q1.reportMissingProp=g9;function Y1(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Dn._`Object.prototype.hasOwnProperty`})}Q1.hasPropFunc=Y1;function ac(n,i,r){return Dn._`${Y1(n)}.call(${i}, ${r})`}Q1.isOwnProperty=ac;function b9(n,i,r,o){let t=Dn._`${i}${(0,Dn.getProperty)(r)} !== undefined`;return o?Dn._`${t} && ${ac(n,i,r)}`:t}Q1.propertyInData=b9;function sc(n,i,r,o){let t=Dn._`${i}${(0,Dn.getProperty)(r)} === undefined`;return o?(0,Dn.or)(t,(0,Dn.not)(ac(n,i,r))):t}Q1.noPropertyInData=sc;function p1(n){return n?Object.keys(n).filter((i)=>i!=="__proto__"):[]}Q1.allSchemaProperties=p1;function w9(n,i){return p1(i).filter((r)=>!(0,xc.alwaysValidSchema)(n,i[r]))}Q1.schemaProperties=w9;function f9({schemaCode:n,data:i,it:{gen:r,topSchemaRef:o,schemaPath:t,errorPath:u},it:e},l,$,I){let g=I?Dn._`${n}, ${i}, ${o}${t}`:i,b=[[gt.default.instancePath,(0,Dn.strConcat)(gt.default.instancePath,u)],[gt.default.parentData,e.parentData],[gt.default.parentDataProperty,e.parentDataProperty],[gt.default.rootData,gt.default.rootData]];if(e.opts.dynamicRef)b.push([gt.default.dynamicAnchors,gt.default.dynamicAnchors]);let w=Dn._`${g}, ${r.object(...b)}`;return $!==Dn.nil?Dn._`${l}.call(${$}, ${w})`:Dn._`${l}(${w})`}Q1.callValidateCode=f9;var c9=Dn._`new RegExp`;function U9({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:Dn._`${t.code==="new RegExp"?c9:(0,v9.useFunc)(n,t)}(${r}, ${o})`})}Q1.usePattern=U9;function D9(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",Dn._`${r}.length`);i.forRange("i",0,$,(I)=>{n.subschema({keyword:o,dataProp:I,dataPropType:xc.Type.Num},u),i.if((0,Dn.not)(u),l)})}}Q1.validateArray=D9;function S9(n){let{gen:i,schema:r,keyword:o,it:t}=n;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(($)=>(0,xc.alwaysValidSchema)(t,$))&&!t.opts.unevaluated)return;let e=i.let("valid",!1),l=i.name("_valid");i.block(()=>r. Line truncated
|| ${e} === "boolean" || ${t} === null`).assign(l,C._`[${t}]`)}}}function l8({gen:n,parentData:i,parentDataProperty:r},o){n.if(C._`${i} !== undefined`,()=>n.assign(C._`${i}[${r}]`,o))}function mc(n,i,r,o=Yr.Correct){let t=o===Yr.Correct?C.operators.EQ:C.operators.NEQ,u;switch(n){case"null":return C._`${i} ${t} null`;case"array":u=C._`Array.isArray(${i})`;break;case"object":u=C._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":u=e(C._`!(${i} % 1) && !isNaN(${i})`);break;case"number":u=e();break;default:return C._`typeof ${i} ${t} ${n}`}return o===Yr.Correct?u:(0,C.not)(u);function e(l=C.nil){return(0,C.and)(C._`typeof ${i} == "number"`,l,r?C._`isFinite(${i})`:C.nil)}}Y1.checkDataType=mc;function xc(n,i,r,o){if(n.length===1)return mc(n[0],i,r,o);let t,u=(0,J1.toHash)(n);if(u.array&&u.object){let e=C._`typeof ${i} != "object"`;t=u.null?e:C._`!${i} || ${e}`,delete u.null,delete u.array,delete u.object}else t=C.nil;if(u.number)delete u.integer;for(let e in u)t=(0,C.and)(t,mc(e,i,r,o));return t}Y1.checkDataTypes=xc;var v8={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:i})=>typeof n=="string"?C._`{type: ${n}}`:C._`{type: ${i}}`};function ac(n){let i=$8(n);(0,t8.reportError)(i,v8)}Y1.reportTypeError=ac;function $8(n){let{gen:i,data:r,schema:o}=n,t=(0,J1.schemaRefOrVal)(n,o,"type");return{gen:i,keyword:"type",data:r,schema:o.type,schemaCode:t,schemaValue:t,parentSchema:o,params:{},it:n}}});var B1=H((K1)=>{Object.defineProperty(K1,"__esModule",{value:!0});K1.assignDefaults=void 0;var Qr=R(),U8=tn();function D8(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))}K1.assignDefaults=D8;function F1(n,i,r){let{gen:o,compositeRule:t,data:u,opts:e}=n;if(r===void 0)return;let l=Qr._`${u}${(0,Qr.getProperty)(i)}`;if(t){(0,U8.checkStrictMode)(n,`default is ignored for: ${l}`);return}let $=Qr._`${l} === undefined`;if(e.useDefaults==="empty")$=Qr._`${$} || ${l} === null || ${l} === ""`;o.if($,Qr._`${l} = ${(0,Qr.stringify)(r)}`)}});var gi=H((V1)=>{Object.defineProperty(V1,"__esModule",{value:!0});V1.validateUnion=V1.validateArray=V1.usePattern=V1.callValidateCode=V1.schemaProperties=V1.allSchemaProperties=V1.noPropertyInData=V1.propertyInData=V1.isOwnProperty=V1.hasPropFunc=V1.reportMissingProp=V1.checkMissingProp=V1.checkReportMissingProp=void 0;var Dn=R(),sc=tn(),gt=Vi(),S8=tn();function A8(n,i){let{gen:r,data:o,it:t}=n;r.if(i6(r,o,i,t.opts.ownProperties),()=>{n.setParams({missingProperty:Dn._`${i}`},!0),n.error()})}V1.checkReportMissingProp=A8;function d8({gen:n,data:i,it:{opts:r}},o,t){return(0,Dn.or)(...o.map((u)=>(0,Dn.and)(i6(n,i,u,r.ownProperties),Dn._`${t} = ${u}`)))}V1.checkMissingProp=d8;function k8(n,i){n.setParams({missingProperty:i},!0),n.error()}V1.reportMissingProp=k8;function E1(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Dn._`Object.prototype.hasOwnProperty`})}V1.hasPropFunc=E1;function n6(n,i,r){return Dn._`${E1(n)}.call(${i}, ${r})`}V1.isOwnProperty=n6;function O8(n,i,r,o){let t=Dn._`${i}${(0,Dn.getProperty)(r)} !== undefined`;return o?Dn._`${t} && ${n6(n,i,r)}`:t}V1.propertyInData=O8;function i6(n,i,r,o){let t=Dn._`${i}${(0,Dn.getProperty)(r)} === undefined`;return o?(0,Dn.or)(t,(0,Dn.not)(n6(n,i,r))):t}V1.noPropertyInData=i6;function T1(n){return n?Object.keys(n).filter((i)=>i!=="__proto__"):[]}V1.allSchemaProperties=T1;function y8(n,i){return T1(i).filter((r)=>!(0,sc.alwaysValidSchema)(n,i[r]))}V1.schemaProperties=y8;function L8({schemaCode:n,data:i,it:{gen:r,topSchemaRef:o,schemaPath:t,errorPath:u},it:e},l,$,I){let g=I?Dn._`${n}, ${i}, ${o}${t}`:i,b=[[gt.default.instancePath,(0,Dn.strConcat)(gt.default.instancePath,u)],[gt.default.parentData,e.parentData],[gt.default.parentDataProperty,e.parentDataProperty],[gt.default.rootData,gt.default.rootData]];if(e.opts.dynamicRef)b.push([gt.default.dynamicAnchors,gt.default.dynamicAnchors]);let f=Dn._`${g}, ${r.object(...b)}`;return $!==Dn.nil?Dn._`${l}.call(${$}, ${f})`:Dn._`${l}(${f})`}V1.callValidateCode=L8;var N8=Dn._`new RegExp`;function G8({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:Dn._`${t.code==="new RegExp"?N8:(0,S8.useFunc)(n,t)}(${r}, ${o})`})}V1.usePattern=G8;function W8(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",Dn._`${r}.length`);i.forRange("i",0,$,(I)=>{n.subschema({keyword:o,dataProp:I,dataPropType:sc.Type.Num},u),i.if((0,Dn.not)(u),l)})}}V1.validateArray=W8;function p8(n){let{gen:i,schema:r,keyword:o,it:t}=n;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(($)=>(0,sc.alwaysValidSchema)(t,$))&&!t.opts.unevaluated)return;let e=i.let("valid",!1),l=i.name("_valid");i.block(()=>r. Line truncated
missingProperty: ${o},
depsCount: ${i},
deps: ${r}}`};var K7={keyword:"dependencies",type:"object",schemaType:"object",error:xA.error,code(n){let[i,r]=B7(n);hA(n,i),mA(n,r)}};function B7({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 hA(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,Au.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,Au.checkReportMissingProp)(n,I)});else r.if(k6._`${$} && (${(0,Au.checkMissingProp)(n,l,u)})`),(0,Au.reportMissingProp)(n,u),r.else()}}xA.validatePropertyDeps=hA;function mA(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,F7.alwaysValidSchema)(u,i[l]))continue;r.if((0,Au.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)}}xA.validateSchemaDeps=mA;xA.default=K7});var rO=Y((tO)=>{Object.defineProperty(tO,"__esModule",{value:!0});var iO=R(),V7=tn(),q7={message:"property name must be valid",params:({params:n})=>iO._`{propertyName: ${n.propertyName}}`},_7={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:q7,code(n){let{gen:i,schema:r,data:o,it:t}=n;if((0,V7.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,iO.not)(u),()=>{if(n.error(!0),!t.allErrors)i.break()})}),n.ok(u)}};tO.default=_7});var N6=Y((oO)=>{Object.defineProperty(oO,"__esModule",{value:!0});var cv=Ii(),Si=R(),M7=Vi(),Uv=tn(),z7={message:"must NOT have additional properties",params:({params:n})=>Si._`{additionalProperty: ${n.additionalProperty}}`},C7={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:z7,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,Uv.alwaysValidSchema)(e,r))return;let I=(0,cv.allSchemaProperties)(o.properties),g=(0,cv.allSchemaProperties)(o.patternProperties);b(),n.ok(Si._`${u} === ${M7.default.errors}`);function b(){i.forIn("key",t,(d)=>{if(!I.length&&!g.length)c(d);else i.if(w(d),()=>c(d))})}function w(d){let k;if(I.length>8){let P=(0,Uv.schemaRefOrVal)(e,o.properties,"properties");k=(0,cv.isOwnProperty)(i,P,d)}else if(I.length)k=(0,Si.or)(...I.map((P)=>Si._`${d} === ${P}`));else k=Si.nil;if(g.length)k=(0,Si.or)(k,...g.map((P)=>Si._`${(0,cv.usePattern)(n,P)}.test(${d})`));return(0,Si.not)(k)}function f(d){i.code(Si._`delete ${t}[${d}]`)}function c(d){if($.removeAdditional==="all"||$.removeAdditional&&r===!1){f(d);return}if(r===!1){if(n.setParams({additionalProperty:d}),n.error(),!l)i.break();return}if(typeof r=="object"&&!(0,Uv.alwaysValidSchema)(e,r)){let k=i.name("valid");if($.removeAdditional==="failing")S(d,k,!1),i.if((0,Si.not)(k),()=>{n.reset(),f(d)});else if(S(d,k),!l)i.if((0,Si.not)(k),()=>i.break())}}function S(d,k,P){let Q={keyword:"additionalProperties",dataProp:d,dataPropType:Uv.Type.Str};if(P===!1)Object.assign(Q,{compositeRule:!0,createErrors:!1,allErrors:!1});n.subschema(Q,k)}}};oO.default=C7});var vO=Y((lO)=>{Object.defineProperty(lO,"__esModule",{value:!0});var h7=lu(),uO=Ii(),L6=tn(),eO=N6(),m7={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)eO.default.code(new h7.KeywordCxt(u,eO.default,"additionalProperties"));let e=(0,uO.allSchemaProperties)(r);for(let b of e)u.definedProperties.add(b);if(u.opts.unevaluated&&e.length&&u.props!==!0)u.props=L6.mergeEvaluated.props(i,(0,L6.toHash)(e),u.props);let l=e.filter((b)=>!(0,L6.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,uO.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},$)}}};lO.default=m7});var wO=Y((bO)=>{Object.defineProperty(bO,"__esModule",{value:!0});var $O=Ii(),Dv=R(),IO=tn(),gO=tn(),a7={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,$O.allSchemaProperties)(r),$=l.filter((S)=>(0,IO.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 Dv.Name))u.props=(0,gO. Line truncated
`)}var Rt=(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 Li;if(e.issues.length){let l=new(t?.Err??n)(e.issues.map(($)=>_n($,u,dn())));throw xu(l,t?.callee),l}return e.value},Io=Rt(mn),ht=(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,dn())));throw xu(l,t?.callee),l}return e.value},go=ht(mn),mt=(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 Li;return u.issues.length?{success:!1,error:new(n??lo)(u.issues.map((e)=>_n(e,t,dn())))}:{success:!0,data:u.value}},xt=mt(mn),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,dn())))}:{success:!0,data:u.value}},bo=at(mn),au=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Rt(n)(i,r,t)},g0=au(mn),su=(n)=>(i,r,o)=>{return Rt(n)(i,r,o)},b0=su(mn),ne=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return ht(n)(i,r,t)},w0=ne(mn),ie=(n)=>async(i,r,o)=>{return ht(n)(i,r,o)},f0=ie(mn),te=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return mt(n)(i,r,t)},c0=te(mn),re=(n)=>(i,r,o)=>{return mt(n)(i,r,o)},U0=re(mn),oe=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return at(n)(i,r,t)},D0=oe(mn),ue=(n)=>async(i,r,o)=>{return at(n)(i,r,o)},S0=ue(mn);var oi={};Pi(oi,{xid:()=>B$,uuid7:()=>AG,uuid6:()=>SG,uuid4:()=>DG,uuid:()=>Lt,uppercase:()=>$I,unicodeEmail:()=>A0,undefined:()=>lI,ulid:()=>K$,time:()=>nI,string:()=>tI,sha512_hex:()=>TG,sha512_base64url:()=>qG,sha512_base64:()=>VG,sha384_hex:()=>KG,sha384_base64url:()=>EG,sha384_base64:()=>BG,sha256_hex:()=>QG,sha256_base64url:()=>FG,sha256_base64:()=>PG,sha1_hex:()=>HG,sha1_base64url:()=>pG,sha1_base64:()=>YG,rfc5322Email:()=>dG,number:()=>wo,null:()=>eI,nanoid:()=>T$,md5_hex:()=>jG,md5_base64url:()=>XG,md5_base64:()=>JG,mac:()=>C$,lowercase:()=>vI,ksuid:()=>E$,ipv6:()=>z$,ipv4:()=>M$,integer:()=>oI,idnEmail:()=>kG,httpProtocol:()=>x$,html5Email:()=>OG,hostname:()=>yG,hex:()=>WG,guid:()=>q$,extendedDuration:()=>UG,emoji:()=>Z$,email:()=>_$,e164:()=>a$,duration:()=>V$,domain:()=>GG,datetime:()=>iI,date:()=>s$,cuid2:()=>F$,cuid:()=>P$,cidrv6:()=>h$,cidrv4:()=>R$,browserEmail:()=>NG,boolean:()=>uI,bigint:()=>rI,base64url:()=>ee,base64:()=>m$});var P$=/^[cC][0-9a-z]{6,}$/,F$=/^[0-9a-z]+$/,K$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,B$=/^[0-9a-vA-V]{20}$/,E$=/^[A-Za-z0-9]{27}$/,T$=/^[a-zA-Z0-9_-]{21}$/,V$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,UG=/^[-+]?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})$/,Lt=(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})$`)},DG=Lt(4),SG=Lt(6),AG=Lt(7),_$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,OG=/^[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])?)*$/,dG=/^(([^<>()\[\]\\.,;:\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,}))$/,A0=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,kG=A0,NG=/^[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])?)*$/,LG="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Z$(){return new RegExp(LG,"u")}var M$=/^(?:(?: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])$/,z$=/^(([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}|:))$/,C$=(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}$`)},R$=/^((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
deps: ${r}}`};var C5={keyword:"dependencies",type:"object",schemaType:"object",error:od.error,code(n){let[i,r]=R5(n);td(n,i),rd(n,r)}};function R5({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 td(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,Ou.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,Ou.checkReportMissingProp)(n,I)});else r.if(L6._`${$} && (${(0,Ou.checkMissingProp)(n,l,u)})`),(0,Ou.reportMissingProp)(n,u),r.else()}}od.validatePropertyDeps=td;function rd(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,z5.alwaysValidSchema)(u,i[l]))continue;r.if((0,Ou.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)}}od.validateSchemaDeps=rd;od.default=C5});var Id=H(($d)=>{Object.defineProperty($d,"__esModule",{value:!0});var vd=R(),x5=tn(),a5={message:"property name must be valid",params:({params:n})=>vd._`{propertyName: ${n.propertyName}}`},s5={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:a5,code(n){let{gen:i,schema:r,data:o,it:t}=n;if((0,x5.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,vd.not)(u),()=>{if(n.error(!0),!t.allErrors)i.break()})}),n.ok(u)}};$d.default=s5});var N6=H((gd)=>{Object.defineProperty(gd,"__esModule",{value:!0});var Av=gi(),Si=R(),i7=Vi(),dv=tn(),t7={message:"must NOT have additional properties",params:({params:n})=>Si._`{additionalProperty: ${n.additionalProperty}}`},r7={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:t7,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,dv.alwaysValidSchema)(e,r))return;let I=(0,Av.allSchemaProperties)(o.properties),g=(0,Av.allSchemaProperties)(o.patternProperties);b(),n.ok(Si._`${u} === ${i7.default.errors}`);function b(){i.forIn("key",t,(k)=>{if(!I.length&&!g.length)c(k);else i.if(f(k),()=>c(k))})}function f(k){let O;if(I.length>8){let F=(0,dv.schemaRefOrVal)(e,o.properties,"properties");O=(0,Av.isOwnProperty)(i,F,k)}else if(I.length)O=(0,Si.or)(...I.map((F)=>Si._`${k} === ${F}`));else O=Si.nil;if(g.length)O=(0,Si.or)(O,...g.map((F)=>Si._`${(0,Av.usePattern)(n,F)}.test(${k})`));return(0,Si.not)(O)}function w(k){i.code(Si._`delete ${t}[${k}]`)}function c(k){if($.removeAdditional==="all"||$.removeAdditional&&r===!1){w(k);return}if(r===!1){if(n.setParams({additionalProperty:k}),n.error(),!l)i.break();return}if(typeof r=="object"&&!(0,dv.alwaysValidSchema)(e,r)){let O=i.name("valid");if($.removeAdditional==="failing")S(k,O,!1),i.if((0,Si.not)(O),()=>{n.reset(),w(k)});else if(S(k,O),!l)i.if((0,Si.not)(O),()=>i.break())}}function S(k,O,F){let Q={keyword:"additionalProperties",dataProp:k,dataPropType:dv.Type.Str};if(F===!1)Object.assign(Q,{compositeRule:!0,createErrors:!1,allErrors:!1});n.subschema(Q,O)}}};gd.default=r7});var cd=H((wd)=>{Object.defineProperty(wd,"__esModule",{value:!0});var u7=Iu(),bd=gi(),G6=tn(),fd=N6(),e7={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)fd.default.code(new u7.KeywordCxt(u,fd.default,"additionalProperties"));let e=(0,bd.allSchemaProperties)(r);for(let b of e)u.definedProperties.add(b);if(u.opts.unevaluated&&e.length&&u.props!==!0)u.props=G6.mergeEvaluated.props(i,(0,G6.toHash)(e),u.props);let l=e.filter((b)=>!(0,G6.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,bd.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},$)}}};wd.default=e7});var dd=H((Ad)=>{Object.defineProperty(Ad,"__esModule",{value:!0});var Ud=gi(),kv=R(),Dd=tn(),Sd=tn(),v7={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,Ud.allSchemaProperties)(r),$=l.filter((S)=>(0,Dd.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 kv.Name))u.props=(0,Sd. 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 Li;if(e.issues.length){let l=new(t?.Err??n)(e.issues.map(($)=>Zn($,u,On())));throw ie(l,t?.callee),l}return e.value},fo=mt(xn),xt=(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(($)=>Zn($,u,On())));throw ie(l,t?.callee),l}return e.value},wo=xt(xn),at=(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 Li;return u.issues.length?{success:!1,error:new(n??Io)(u.issues.map((e)=>Zn(e,t,On())))}:{success:!0,data:u.value}},st=at(xn),nr=(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)=>Zn(e,t,On())))}:{success:!0,data:u.value}},co=nr(xn),te=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return mt(n)(i,r,t)},S4=te(xn),re=(n)=>(i,r,o)=>{return mt(n)(i,r,o)},A4=re(xn),oe=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return xt(n)(i,r,t)},d4=oe(xn),ue=(n)=>async(i,r,o)=>{return xt(n)(i,r,o)},k4=ue(xn),ee=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return at(n)(i,r,t)},O4=ee(xn),le=(n)=>(i,r,o)=>{return at(n)(i,r,o)},y4=le(xn),ve=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return nr(n)(i,r,t)},L4=ve(xn),$e=(n)=>async(i,r,o)=>{return nr(n)(i,r,o)},N4=$e(xn);var ui={};Fi(ui,{xid:()=>T$,uuid7:()=>jG,uuid6:()=>pG,uuid4:()=>WG,uuid:()=>Wt,uppercase:()=>gI,unicodeEmail:()=>G4,undefined:()=>$I,ulid:()=>E$,time:()=>tI,string:()=>oI,sha512_hex:()=>mG,sha512_base64url:()=>aG,sha512_base64:()=>xG,sha384_hex:()=>CG,sha384_base64url:()=>hG,sha384_base64:()=>RG,sha256_hex:()=>ZG,sha256_base64url:()=>zG,sha256_base64:()=>MG,sha1_hex:()=>VG,sha1_base64url:()=>qG,sha1_base64:()=>_G,rfc5322Email:()=>XG,number:()=>Uo,null:()=>vI,nanoid:()=>_$,md5_hex:()=>BG,md5_base64url:()=>TG,md5_base64:()=>EG,mac:()=>h$,lowercase:()=>II,ksuid:()=>V$,ipv6:()=>R$,ipv4:()=>C$,integer:()=>eI,idnEmail:()=>HG,httpProtocol:()=>s$,html5Email:()=>JG,hostname:()=>FG,hex:()=>PG,guid:()=>Z$,extendedDuration:()=>GG,emoji:()=>z$,email:()=>M$,e164:()=>nI,duration:()=>q$,domain:()=>KG,datetime:()=>rI,date:()=>iI,cuid2:()=>B$,cuid:()=>P$,cidrv6:()=>x$,cidrv4:()=>m$,browserEmail:()=>YG,boolean:()=>lI,bigint:()=>uI,base64url:()=>Ie,base64:()=>a$});var P$=/^[cC][0-9a-z]{6,}$/,B$=/^[0-9a-z]+$/,E$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,T$=/^[0-9a-vA-V]{20}$/,V$=/^[A-Za-z0-9]{27}$/,_$=/^[a-zA-Z0-9_-]{21}$/,q$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,GG=/^[-+]?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)?)??$/,Z$=/^([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})$/,Wt=(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})$`)},WG=Wt(4),pG=Wt(6),jG=Wt(7),M$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,JG=/^[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])?)*$/,XG=/^(([^<>()\[\]\\.,;:\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,}))$/,G4=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,HG=G4,YG=/^[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])?)*$/,QG="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function z$(){return new RegExp(QG,"u")}var C$=/^(?:(?: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])$/,R$=/^(([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}|:))$/,h$=(n)=>{let i=vi(n??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},m$=/^((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 jI={major:4,minor:4,patch:3};var E=U("$ZodType",(n,i)=>{var r;n??(n={}),n._zod.def=i,n._zod.bag=n._zod.bag||{},n._zod.version=jI;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=ai(e),g;for(let b of l){if(b._zod.def.when){if(Y$(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 Li;if(g||f instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await f,e.issues.length===w)return;if(!I)I=ai(e,w)});else{if(e.issues.length===w)continue;if(!I)I=ai(e,w)}}if(g)return g.then(()=>{return e});return e},u=(e,l,$)=>{if(ai(e))return e.aborted=!0,e;let I=t(l,o,$);if(I instanceof Promise){if($.async===!1)throw new Li;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 Li;return $.then((I)=>t(I,o,l))}return t($,o,l)}}h(n,"~standard",()=>({validate:(t)=>{try{let u=xt(n,t);return u.success?{value:u.data}:{issues:u.error?.issues}}catch(u){return bo(n,t).then((e)=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),yt=U("$ZodString",(n,i)=>{E.init(n,i),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??tI(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=U("$ZodStringFormat",(n,i)=>{st.init(n,i),yt.init(n,i)}),XI=U("$ZodGUID",(n,i)=>{i.pattern??(i.pattern=q$),$n.init(n,i)}),HI=U("$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=Lt(o))}else i.pattern??(i.pattern=Lt());$n.init(n,i)}),YI=U("$ZodEmail",(n,i)=>{i.pattern??(i.pattern=_$),$n.init(n,i)}),pI=U("$ZodURL",(n,i)=>{$n.init(n,i),n._zod.check=(r)=>{try{let o=r.value.trim();if(!i.normalize&&i.protocol?.source===x$.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})}}}),QI=U("$ZodEmoji",(n,i)=>{i.pattern??(i.pattern=Z$()),$n.init(n,i)}),PI=U("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=T$),$n.init(n,i)}),FI=U("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=P$),$n.init(n,i)}),KI=U("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=F$),$n.init(n,i)}),BI=U("$ZodULID",(n,i)=>{i.pattern??(i.pattern=K$),$n.init(n,i)}),EI=U("$ZodXID",(n,i)=>{i.pattern??(i.pattern=B$),$n.init(n,i)}),TI=U("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=E$),$n.init(n,i)}),VI=U("$ZodISODateTime",(n,i)=>{i.pattern??(i.pattern=iI(i)),$n.init(n,i)}),qI=U("$ZodISODate",(n,i)=>{i.pattern??(i.pattern=s$),$n.init(n,i)}),_I=U("$ZodISOTime",(n,i)=>{i.pattern??(i.pattern=nI(i)),$n.init(n,i)}),ZI=U("$ZodISODuration",(n,i)=>{i.pattern??(i.pattern=V$),$n.init(n,i)}),MI=U("$ZodIPv4",(n,i)=>{i.pattern??(i.pattern=M$),$n.init(n,i),n._zod.bag.format="ipv4"}),zI=U("$ZodIPv6",(n,i)=>{i.pattern??(i.pattern=z$),$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})}}}),CI=U("$ZodMAC",(n,i)=>{i.pattern??(i.pattern=C$(i.delimiter)),$n.init(n,i),n._zod.bag.format="mac"}),RI=U("$ZodCIDRv4",(n,i)=>{i.pattern??(i.pattern=R$),$n.init(n,i)}),hI=U("$ZodCIDRv6",(n,i)=>{i.pattern??(i.pattern=h$),$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 mI(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
`))}}var JI={major:4,minor:4,patch:3};var T=D("$ZodType",(n,i)=>{var r;n??(n={}),n._zod.def=i,n._zod.bag=n._zod.bag||{},n._zod.version=JI;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=ai(e),g;for(let b of l){if(b._zod.def.when){if(Q$(e))continue;if(!b._zod.def.when(e))continue}else if(I)continue;let f=e.issues.length,w=b._zod.check(e);if(w instanceof Promise&&$?.async===!1)throw new Li;if(g||w instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await w,e.issues.length===f)return;if(!I)I=ai(e,f)});else{if(e.issues.length===f)continue;if(!I)I=ai(e,f)}}if(g)return g.then(()=>{return e});return e},u=(e,l,$)=>{if(ai(e))return e.aborted=!0,e;let I=t(l,o,$);if(I instanceof Promise){if($.async===!1)throw new Li;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 Li;return $.then((I)=>t(I,o,l))}return t($,o,l)}}h(n,"~standard",()=>({validate:(t)=>{try{let u=st(n,t);return u.success?{value:u.data}:{issues:u.error?.issues}}catch(u){return co(n,t).then((e)=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),pt=D("$ZodString",(n,i)=>{T.init(n,i),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??oI(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)=>{ir.init(n,i),pt.init(n,i)}),HI=D("$ZodGUID",(n,i)=>{i.pattern??(i.pattern=Z$),$n.init(n,i)}),YI=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=Wt(o))}else i.pattern??(i.pattern=Wt());$n.init(n,i)}),QI=D("$ZodEmail",(n,i)=>{i.pattern??(i.pattern=M$),$n.init(n,i)}),FI=D("$ZodURL",(n,i)=>{$n.init(n,i),n._zod.check=(r)=>{try{let o=r.value.trim();if(!i.normalize&&i.protocol?.source===s$.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=z$()),$n.init(n,i)}),PI=D("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=_$),$n.init(n,i)}),BI=D("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=P$),$n.init(n,i)}),EI=D("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=B$),$n.init(n,i)}),TI=D("$ZodULID",(n,i)=>{i.pattern??(i.pattern=E$),$n.init(n,i)}),VI=D("$ZodXID",(n,i)=>{i.pattern??(i.pattern=T$),$n.init(n,i)}),_I=D("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=V$),$n.init(n,i)}),qI=D("$ZodISODateTime",(n,i)=>{i.pattern??(i.pattern=rI(i)),$n.init(n,i)}),ZI=D("$ZodISODate",(n,i)=>{i.pattern??(i.pattern=iI),$n.init(n,i)}),MI=D("$ZodISOTime",(n,i)=>{i.pattern??(i.pattern=tI(i)),$n.init(n,i)}),zI=D("$ZodISODuration",(n,i)=>{i.pattern??(i.pattern=q$),$n.init(n,i)}),CI=D("$ZodIPv4",(n,i)=>{i.pattern??(i.pattern=C$),$n.init(n,i),n._zod.bag.format="ipv4"}),RI=D("$ZodIPv6",(n,i)=>{i.pattern??(i.pattern=R$),$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})}}}),hI=D("$ZodMAC",(n,i)=>{i.pattern??(i.pattern=h$(i.delimiter)),$n.init(n,i),n._zod.bag.format="mac"}),mI=D("$ZodCIDRv4",(n,i)=>{i.pattern??(i.pattern=m$),$n.init(n,i)}),xI=D("$ZodCIDRv6",(n,i)=>{i.pattern??(i.pattern=x$),$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 aI(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 (${W}.issues.length) {
if (${N} in input) {
if (${y} in input) {
payload.issues = payload.issues.concat(${W}.issues.map(iss => ({
...iss,
path: iss.path ? [${N}, ...iss.path] : [${N}]
path: iss.path ? [${y}, ...iss.path] : [${y}]
})));
}
}
if (${W}.value === undefined) {
if (${N} in input) {
newResult[${N}] = undefined;
if (${y} in input) {
newResult[${y}] = undefined;
}
} else {
newResult[${N}] = ${W}.value;
newResult[${y}] = ${W}.value;
}
`);else if(!q)f.write(`
const ${W}_present = ${N} in input;
`);else if(!q)w.write(`
const ${W}_present = ${y} in input;
if (${W}.issues.length) {
payload.issues = payload.issues.concat(${W}.issues.map(iss => ({
...iss,
path: iss.path ? [${N}, ...iss.path] : [${N}]
path: iss.path ? [${y}, ...iss.path] : [${y}]
})));
}
if (!${W}_present && !${W}.issues.length) {
@@ -39,44 +39,44 @@ import{createRequire as _y}from"node:module";var Qy=Object.create;var{getPrototy
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${N}]
path: [${y}]
});
}
if (${W}_present) {
if (${W}.value === undefined) {
newResult[${N}] = undefined;
newResult[${y}] = undefined;
} else {
newResult[${N}] = ${W}.value;
newResult[${y}] = ${W}.value;
}
}
`);else f.write(`
`);else w.write(`
if (${W}.issues.length) {
payload.issues = payload.issues.concat(${W}.issues.map(iss => ({
...iss,
path: iss.path ? [${N}, ...iss.path] : [${N}]
path: iss.path ? [${y}, ...iss.path] : [${y}]
})));
}
if (${W}.value === undefined) {
if (${N} in input) {
newResult[${N}] = undefined;
if (${y} in input) {
newResult[${y}] = undefined;
}
} else {
newResult[${N}] = ${W}.value;
newResult[${y}] = ${W}.value;
}
`)}f.write("payload.value = newResult;"),f.write("return payload;");let P=f.compile();return(Q,W)=>P(w,Q,W)},u,e=Nt,l=!dt.jitless,I=l&&G$.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 q0([],c,w,f,b,n)}return r(w,f)}});function G0(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)=>!ai(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,dn())))}),i}var Do=U("$ZodUnion",(n,i)=>{E.init(n,i),h(n._zod,"optin",()=>i.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),h(n._zod,"optout",()=>i.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),h(n._zod,"values",()=>{if(i.options.every((o)=>o._zod.values))return new Set(i.options.flatMap((o)=>Array.from(o._zod.values)));return}),h(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)=>ro(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 G0(e,o,n,t);return Promise.all(e).then((l)=>{return G0(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,dn())))});else i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:[],inclusive:!1});return i}var fg=U("$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)})}}),cg=U("$ZodDiscriminatedUnion",(n,i)=>{i.inclusive=!1,Do.init(n,i);let r=n._zod.parse;h(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=zt(()=>{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(!Nt(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}}),Ug=U("$ZodIntersection",(n,i)=>{E.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 j0(r,$,I)});return j0(r,u,e)}});function JI(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(xi(n)&&xi(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=JI(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=JI(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 j0(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(ai(n))return n;let e=JI(i.value,r.value);if(!e.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(e.mergeErrorPath)}`);return n.value=e.data,n}var Ue=U("$ZodTuple",(n,i)=>{E.init(n,i Line truncated
`)}w.write("payload.value = newResult;"),w.write("return payload;");let F=w.compile();return(Q,W)=>F(f,Q,W)},u,e=Gt,l=!Lt.jitless,I=l&&p$.value,g=i.catchall,b;n._zod.parse=(f,w)=>{b??(b=o.value);let c=f.value;if(!e(c))return f.issues.push({expected:"object",code:"invalid_type",input:c,inst:n}),f;if(l&&I&&w?.async===!1&&w.jitless!==!0){if(!u)u=t(i.shape);if(f=u(f,w),!g)return f;return h4([],c,f,w,b,n)}return r(f,w)}});function Y4(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)=>!ai(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)=>Zn(e,o,On())))}),i}var ko=D("$ZodUnion",(n,i)=>{T.init(n,i),h(n._zod,"optin",()=>i.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),h(n._zod,"optout",()=>i.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),h(n._zod,"values",()=>{if(i.options.every((o)=>o._zod.values))return new Set(i.options.flatMap((o)=>Array.from(o._zod.values)));return}),h(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)=>eo(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 Y4(e,o,n,t);return Promise.all(e).then((l)=>{return Y4(l,o,n,t)})}});function Q4(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)=>Zn(e,o,On())))});else i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:[],inclusive:!1});return i}var Ug=D("$ZodXor",(n,i)=>{ko.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 Q4(e,o,n,t);return Promise.all(e).then((l)=>{return Q4(l,o,n,t)})}}),Dg=D("$ZodDiscriminatedUnion",(n,i)=>{i.inclusive=!1,ko.init(n,i);let r=n._zod.parse;h(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=Rt(()=>{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(!Gt(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}}),Sg=D("$ZodIntersection",(n,i)=>{T.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 F4(r,$,I)});return F4(r,u,e)}});function XI(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(xi(n)&&xi(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=XI(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=XI(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 F4(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(ai(n))return n;let e=XI(i.value,r.value);if(!e.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(e.mergeErrorPath)}`);return n.value=e.data,n}var de=D("$ZodTuple",(n,i)=>{T.init(n,i 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 rt(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 d in I){if(d==="$ref"||d==="allOf")continue;if(!(d in g))delete I[d]}if(c.$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]}}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 Mn(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 Mn(o.element,r);if(o.type==="set")return Mn(o.valueType,r);if(o.type==="lazy")return Mn(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 Mn(o.innerType,r);if(o.type==="intersection")return Mn(o.left,r)||Mn(o.right,r);if(o.type==="record"||o.type==="map")return Mn(o.keyType,r)||Mn(o.valueType,r);if(o.type==="pipe"){if(n._zod.traits.has("$ZodCodec"))return!0;return Mn(o.in,r)||Mn(o.out,r)}if(o.type==="object"){for(let t in o.shape)if(Mn(o.shape[t],r))return!0;return!1}if(o.type==="union"){for(let t of o.options)if(Mn(t,r))return!0;return!1}if(o.type==="tuple"){for(let t of o.items)if(Mn(t,r))return!0;if(o.rest&&Mn(o.rest,r))return!0;return!1}return!1}var kw=(n,i={})=>(r)=>{let o=it({...r,processors:i});return en(n,o),tt(o,n),rt(o,n)},fr=(n,i,r={})=>(o)=>{let{libraryOptions:t,target:u}=o??{},e=it({...t??{},target:u,io:i,processors:r});return en(n,e),tt(e,n),rt(e,n)};var Ij={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Nw=(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=Ij[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}))]}},Lw=(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=$},yw=(n,i,r,o)=>{r.type="boolean"},Gw=(n,i,r,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Ww=(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),YQ(i)}clear(){this._buffer=void 0}}function YQ(n){return AD.parse(JSON.parse(n))}function cd(n){return JSON.stringify(n)+`
`}class V6{constructor(n=Ud.stdin,i=Ud.stdout){this._stdin=n,this._stdout=i,this._readBuffer=new T6,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=cd(n);if(this._stdout.write(r))i();else this._stdout.once("drain",i)})}}import{dirname as s4,join as MK}from"node:path";import{fileURLToPath as zK}from"node:url";class Zi extends Error{name="KyError";get isKyError(){return!0}}class ti extends Zi{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 ku extends Zi{name="NetworkError";request;constructor(n,i){super(`Request failed due to a network error: ${n.method} ${n.url}`,i);this.request=n}}class Nu 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 Vr extends Zi{name="ForceRetryError";customDelay;code;customRequest;constructor(n){let i=n?.cause?n.cause instanceof Error?n.cause:new Nu(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 q6 extends Error{name="SchemaValidationError";issues;constructor(n){super("Response schema validation failed");this.issues=n}}class Oi extends Zi{name="TimeoutError";request;constructor(n){super(`Request timed out: ${n.method} ${n.url}`);this.request=n}}var _6=(()=>{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})(),Dd=typeof globalThis.AbortController==="function",kv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",Sd=typeof globalThis.ReadableStream==="function",Ad=typeof globalThis.FormData==="function",Nv=["get","post","put","patch","head","delete"],pQ=()=>{return};pQ();var Od={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},qr=2147483647,dd=40,Lv=Symbol("stop");class yv{options;constructor(n){this.options=n}}var kd=(n)=>new yv(n),Nd={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},Ld={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 Gv=new TextEncoder,QQ=(n)=>{if(!n)return 0;if(n instanceof FormData){let i=0;for(let[r,o]of n)i+=dd,i+=Gv.encode(`Content-Disposition: form-data; name="${r}"`).byteLength,i+=typeof o==="string"?Gv.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 Gv.encode(n).byteLength;if(n instanceof URLSearchParams)return Gv.encode(n.toString()).byteLength;return 0},yd=(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)}}))},Gd=(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(yd(n.body,o,i),r)},Wd=(n,i,r)=>{if(!n.body)return n;let o=QQ(r??n.body);return new Request(n,{duplex:"half",body:yd(n.body,o,i)})};var Hi=(n)=>n!==null&&typeof n==="object";var PQ=Symbol("replaceOption"),Z6=(n)=>Hi(n)&&n[PQ]===!0?{isReplace:!0,value:n.value}:{isReplace:!1,value:n};var yu=(...n)=>{for(let i of n)if((!Hi(i)| Line truncated
`,{mode:384}),i}function Rr(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 gF}from"node:fs";import{randomBytes as bF}from"node:crypto";import{randomBytes as Tk}from"node:crypto";var JP=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),XP=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:JP.optional()}),HP=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),YP=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:HP.optional()}),Sk=v.object({user:XP,tenant:YP}),pP=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(),QP=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(),Ak=v.object({user:pP,session:QP}),_v=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()}),Ok=v.object({rules:v.array(_v),hasPendingDeletes:v.boolean().default(!1)}),PP=v.object({code:v.string().optional(),description:v.string(),scope:v.string(),strictness:v.string()}),Zv=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(PP).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),dk=v.object({version:Zv,rulesCount:v.number()}),pu=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)}),kk=v.object({articles:v.array(pu),total:v.number().optional()}),FP=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),KP=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(),BP=v.enum(["assisted","semi_automatic","fully_automatic"]),Dk=v.object({id:v.string(),url:v.string().url()}).passthrough(),Qu=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:BP,incomingDocumentWebhook:Dk,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:Dk,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),v4=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:n$(i,["template.name","templateName","form.name","formName","formTitle"]),amount:av(r,["金额","报销金额","付款金额","合计","价税合计"])??n$(i,["amount","totalAmount","expenseAmount"]),expenseType:av(r,["费用类型","费用类别","报销类型"]),costCompany:av(r,["费用承担公司","承担公司","成本中心","费用归属"]),payee:av(r,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:r.slice(0,30)}),invoices:XF(n),attachments:CN(n,{summary:!0}).attachments,aiResult:t$(n),manualResult:qt(n)?.value,hints:Dt({amountMentions:PN(o,["金额","合计","税率"],8),partyMentions:PN(o,["买方","卖方","甲方","乙方","收款"],8)})}}function CN(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)G4(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 LF(n){let i=[["result.citedRules",zi(n,"result.citedRules")],["result.matchedRules",zi(n,"result.matchedRules")],["result.ruleResults",zi(n,"result.ruleResults")],["result.rules",zi(n,"result.rules")],["pipelineData.citedRules",zi(n,"pipelineData.citedRules")],["pipelineData.matchedRules",zi(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=mr(l);if(!I)return;let g=V(I.runtimeRuleId)??V(I.runtimeId)??V(I.id)??V(I.ruleId),b=V(I.ruleCode)??V(I.code)??(g?pF(g):void 0),w=Dt({runtimeRuleId:g,ruleCode:b,versionNumber:jF(I.versionNumber)??n.ruleSetVersionNumber,scope:V(I.scope),strictness:V(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 G4(n,i,r,o){if(Array.isArray(n)){n.forEach((u,e)=>G4(u,`${i}.${e}`,r,o));return}let t=mr(n);if(!t)return;if(yF(t,i)){let u=Dt({path:i,fieldPath:i,kind:GF(i,t),fileName:V(t.fileName)??V(t.filename)??V(t.name)??V(t.originalName),mimeType:V(t.mimeType)??V(t.mimetype)??V(t.contentType),fileId:V(t.fileId)??V(t.id)??V(t.attachmentId),ossPath:V(t.ossPath)??V(t.ossKey)??V(t.key),url:V(t.url)??V(t.signedUrl)??V(t.downloadUrl)??V(t.previewUrl),invoiceId:V(t.invoiceId),sourceField:V(t.fieldName)??V(t.label)}),e=JSON.stringify(u);if(!o.has(e))o.add(e),r.push(u)}for(let[u,e]of Object.entries(t))G4(e,`${i}.${u}`,r,o)}function yF(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 GF(n,i){let r=`${n} ${V(i.type)??""}`.toLowerCase();if(r.includes("invoice")||r.includes("发票"))return"invoice";if(r.includes("receipt"))return"receipt";return"attachment"}function n$(n,i){if(!n)return;for(let r of i){let o=zi(n,r);if(o!==void 0)return o}return}function QN(n,i){if(!n)return 0;for(let r of i){let o=zi(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 zi(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 WF(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 mr(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function jF(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function JF(n){let i=[];return W4(n,"document",i),i}function W4(n,i,r){if(Array.isArray(n)){n.forEach((e,l)=>W4(e,`${i}.${l}`,r));return}let o=mr(n);if(!o)return;let t=V(o.label)??V(o.name)??V(o.title)??V(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:V(o.type)??V(o.fieldType)}));for(let[e,l]of Object.entries(o)){if(e==="attachments")continue;W4(l,`${i}.${e}`,r)}}function av(n,i){return n.find((o)=>{let t=V(o.label)??"";return i.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 rt(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 w=n.seen.get(b),c=w.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 k in I){if(k==="$ref"||k==="allOf")continue;if(!(k in g))delete I[k]}if(c.$ref&&w.def)for(let k in I){if(k==="$ref"||k==="allOf")continue;if(k in w.def&&JSON.stringify(I[k])===JSON.stringify(w.def[k]))delete I[k]}}let f=l._zod.parent;if(f&&f!==b){o(f);let w=n.seen.get(f);if(w?.schema.$ref){if(I.$ref=w.schema.$ref,w.def)for(let c in I){if(c==="$ref"||c==="allOf")continue;if(c in w.def&&JSON.stringify(I[c])===JSON.stringify(w.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:Ur(i,"input",n.processors),output:Ur(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 Nf=(n,i={})=>(r)=>{let o=it({...r,processors:i});return ln(n,o),tt(o,n),rt(o,n)},Ur=(n,i,r={})=>(o)=>{let{libraryOptions:t,target:u}=o??{},e=it({...t??{},target:u,io:i,processors:r});return ln(n,e),tt(e,n),rt(e,n)};var dp={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Gf=(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=dp[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}))]}},Wf=(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),f=typeof I==="number"&&I<=(e??Number.POSITIVE_INFINITY),w=i.target==="draft-04"||i.target==="openapi-3.0";if(b)if(w)t.minimum=g,t.exclusiveMinimum=!0;else t.exclusiveMinimum=g;else if(typeof u==="number")t.minimum=u;if(f)if(w)t.maximum=I,t.exclusiveMaximum=!0;else t.exclusiveMaximum=I;else if(typeof e==="number")t.maximum=e;if(typeof $==="number")t.multipleOf=$},pf=(n,i,r,o)=>{r.type="boolean"},jf=(n,i,r,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Jf=(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),_Q(i)}clear(){this._buffer=void 0}}function _Q(n){return GD.parse(JSON.parse(n))}function Ok(n){return JSON.stringify(n)+`
`}class q6{constructor(n=yk.stdin,i=yk.stdout){this._stdin=n,this._stdout=i,this._readBuffer=new _6,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=Ok(n);if(this._stdout.write(r))i();else this._stdout.once("drain",i)})}}import{dirname as e4,join as IB}from"node:path";import{fileURLToPath as gB}from"node:url";class Zi extends Error{name="KyError";get isKyError(){return!0}}class ri extends Zi{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 Zi{name="NetworkError";request;constructor(n,i){super(`Request failed due to a network error: ${n.method} ${n.url}`,i);this.request=n}}class Gu 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 Zi{name="ForceRetryError";customDelay;code;customRequest;constructor(n){let i=n?.cause?n.cause instanceof Error?n.cause:new Gu(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 Z6 extends Error{name="SchemaValidationError";issues;constructor(n){super("Response schema validation failed");this.issues=n}}class di extends Zi{name="TimeoutError";request;constructor(n){super(`Request timed out: ${n.method} ${n.url}`);this.request=n}}var M6=(()=>{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})(),Lk=typeof globalThis.AbortController==="function",Gv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",Nk=typeof globalThis.ReadableStream==="function",Gk=typeof globalThis.FormData==="function",Wv=["get","post","put","patch","head","delete"],qQ=()=>{return};qQ();var Wk={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Zr=2147483647,pk=40,pv=Symbol("stop");class jv{options;constructor(n){this.options=n}}var jk=(n)=>new jv(n),Jk={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},Xk={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 Jv=new TextEncoder,ZQ=(n)=>{if(!n)return 0;if(n instanceof FormData){let i=0;for(let[r,o]of n)i+=pk,i+=Jv.encode(`Content-Disposition: form-data; name="${r}"`).byteLength,i+=typeof o==="string"?Jv.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 Jv.encode(n).byteLength;if(n instanceof URLSearchParams)return Jv.encode(n.toString()).byteLength;return 0},Hk=(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)}}))},Yk=(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(Hk(n.body,o,i),r)},Qk=(n,i,r)=>{if(!n.body)return n;let o=ZQ(r??n.body);return new Request(n,{duplex:"half",body:Hk(n.body,o,i)})};var Xi=(n)=>n!==null&&typeof n==="object";var MQ=Symbol("replaceOption"),z6=(n)=>Xi(n)&&n[MQ]===!0?{isReplace:!0,value:n.value}:{isReplace:!1,value:n};var pu=(...n)=>{for(let i of n)if((!Xi(i)| Line truncated
`,{mode:384}),i}function xr(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 JK}from"node:fs";import{randomBytes as XK}from"node:crypto";import{randomBytes as CO}from"node:crypto";var TF=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),VF=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:TF.optional()}),_F=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),qF=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:_F.optional()}),NO=v.object({user:VF,tenant:qF}),ZF=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(),MF=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(),GO=v.object({user:ZF,session:MF}),zv=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()}),WO=v.object({rules:v.array(zv),hasPendingDeletes:v.boolean().default(!1)}),zF=v.object({code:v.string().optional(),description:v.string(),scope:v.string(),strictness:v.string()}),Cv=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(zF).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),pO=v.object({version:Cv,rulesCount:v.number()}),Ku=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)}),jO=v.object({articles:v.array(Ku),total:v.number().optional()}),CF=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),RF=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(),hF=v.enum(["assisted","semi_automatic","fully_automatic"]),LO=v.object({id:v.string(),url:v.string().url()}).passthrough(),Pu=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:hF,incomingDocumentWebhook:LO,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:LO,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),I0=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:r$(i,["template.name","templateName","form.name","formName","formTitle"]),amount:i$(r,["金额","报销金额","付款金额","合计","价税合计"])??r$(i,["amount","totalAmount","expenseAmount"]),expenseType:i$(r,["费用类型","费用类别","报销类型"]),costCompany:i$(r,["费用承担公司","承担公司","成本中心","费用归属"]),payee:i$(r,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:r.slice(0,30)}),invoices:hK(n),attachments:rL(n,{summary:!0}).attachments,aiResult:u$(n),manualResult:Zt(n)?.value,hints:dt({amountMentions:My(o,["金额","合计","税率"],8),partyMentions:My(o,["买方","卖方","甲方","乙方","收款"],8)})}}function rL(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)Y0(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 qK(n){let i=[["result.citedRules",zi(n,"result.citedRules")],["result.matchedRules",zi(n,"result.matchedRules")],["result.ruleResults",zi(n,"result.ruleResults")],["result.rules",zi(n,"result.rules")],["pipelineData.citedRules",zi(n,"pipelineData.citedRules")],["pipelineData.matchedRules",zi(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=sr(l);if(!I)return;let g=_(I.runtimeRuleId)??_(I.runtimeId)??_(I.id)??_(I.ruleId),b=_(I.ruleCode)??_(I.code)??(g?aK(g):void 0),f=dt({runtimeRuleId:g,ruleCode:b,versionNumber:CK(I.versionNumber)??n.ruleSetVersionNumber,scope:_(I.scope),strictness:_(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}.${$}`}),w=JSON.stringify(f);if(!o.has(w))o.add(w),r.push(f)});return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,ruleSetVersionNumber:n.ruleSetVersionNumber,count:r.length,rules:r}}function Y0(n,i,r,o){if(Array.isArray(n)){n.forEach((u,e)=>Y0(u,`${i}.${e}`,r,o));return}let t=sr(n);if(!t)return;if(ZK(t,i)){let u=dt({path:i,fieldPath:i,kind:MK(i,t),fileName:_(t.fileName)??_(t.filename)??_(t.name)??_(t.originalName),mimeType:_(t.mimeType)??_(t.mimetype)??_(t.contentType),fileId:_(t.fileId)??_(t.id)??_(t.attachmentId),ossPath:_(t.ossPath)??_(t.ossKey)??_(t.key),url:_(t.url)??_(t.signedUrl)??_(t.downloadUrl)??_(t.previewUrl),invoiceId:_(t.invoiceId),sourceField:_(t.fieldName)??_(t.label)}),e=JSON.stringify(u);if(!o.has(e))o.add(e),r.push(u)}for(let[u,e]of Object.entries(t))Y0(e,`${i}.${u}`,r,o)}function ZK(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 MK(n,i){let r=`${n} ${_(i.type)??""}`.toLowerCase();if(r.includes("invoice")||r.includes("发票"))return"invoice";if(r.includes("receipt"))return"receipt";return"attachment"}function r$(n,i){if(!n)return;for(let r of i){let o=zi(n,r);if(o!==void 0)return o}return}function Zy(n,i){if(!n)return 0;for(let r of i){let o=zi(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 zi(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 zK(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 sr(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function CK(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function RK(n){let i=[];return Q0(n,"document",i),i}function Q0(n,i,r){if(Array.isArray(n)){n.forEach((e,l)=>Q0(e,`${i}.${l}`,r));return}let o=sr(n);if(!o)return;let t=_(o.label)??_(o.name)??_(o.title)??_(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:_(o.type)??_(o.fieldType)}));for(let[e,l]of Object.entries(o)){if(e==="attachments")continue;Q0(l,`${i}.${e}`,r)}}function i$(n,i){return n.find((o)=>{let t=_(o.label)??"";return i.some((u)=>t.includes(u)) Line truncated
`)}
`}function _u(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={}){zF(n,i);let r=`${JSON.stringify(n,null,2)}
`;if(i.outputFile){qF(i.outputFile,r),console.log(JSON.stringify({outputFile:i.outputFile,bytes:Buffer.byteLength(r,"utf-8")},null,2));return}console.log(r.trimEnd())}function zF(n,i={}){if(i.allowFull||i.outputFile)return;let r=Buffer.byteLength(JSON.stringify(n),"utf-8");if(r>MF)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 eL(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>_F||u>ZF)throw Error(`Rule list is large (${e} rules, ${u} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`)}function J(n){return{allowFull:_(n.full)===!0,outputFile:D(n.outputFile)??D(n["output-file"])}}function lL(){console.log(`seal-use CLI
`}function zu(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={}){gP(n,i);let r=`${JSON.stringify(n,null,2)}
`;if(i.outputFile){lP(i.outputFile,r),console.log(JSON.stringify({outputFile:i.outputFile,bytes:Buffer.byteLength(r,"utf-8")},null,2));return}console.log(r.trimEnd())}function gP(n,i={}){if(i.allowFull||i.outputFile)return;let r=Buffer.byteLength(JSON.stringify(n),"utf-8");if(r>IP)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 UL(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>vP||u>$P)throw Error(`Rule list is large (${e} rules, ${u} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`)}function j(n){return{allowFull:E(n.full)===!0,outputFile:U(n.outputFile)??U(n["output-file"])}}function DL(){console.log(`seal-use CLI
Usage:
seal-use version
@@ -176,12 +176,12 @@ Usage:
seal-use simulation templates [--corp <corpId>]
seal-use simulation integrations [--corp <corpId>]
seal-use simulation package-upload <材料包.zip> [--corp <corpId>]
`)}function Ln(n){let i=Yi(),r=bi();return Rr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n},Kt())}function r$(n=bi()){return{mode:n.stateful?"stateful":"stateless",stateful:n.stateful,...n.stateful&&n.defaultCorpId?{defaultCorpId:n.defaultCorpId}:{},configFile:Yu()}}async function X(n,i,r,o,t={}){B(await xr(n,i,r,o),t)}async function xr(n,i,r,o){let t=Tu.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 vL(n,i,r,o,t){if(n==="summary"){let u=await xr("seal_approval_runs_summary",r,o,{date:D(t.options.date),timezone:D(t.options.timezone),limit:ln(t.options.limit),startDate:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query)});if(u?.matched===0&&u?.total>0)console.error(`提示:在 ${u.date} 未匹配到记录(该企业共有 ${u.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-use approval-runs list --limit 10 查看最近记录。`);B(u,J(t.options));return}if(n==="stats"){await X("seal_approval_runs_stats",r,o,{since:D(t.options.since),dedupeBy:D(t.options.dedupeBy)??D(t.options["dedupe-by"]),status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"])},J(t.options));return}if(n==="count"){await X("seal_approval_runs_count",r,o,{status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"]),search:D(t.options.search)??D(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:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query),includeBridge:_(t.options.includeBridge)},J(t.options));return}if(n==="bridge"){await X("seal_approval_run_langfuse_bridge_get",r,o,{recordId:D(t.options.recordId),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),simulationBatchId:D(t.options.simulationBatchId),limit:ln(t.options.limit)},J(t.options));return}if(n==="pick"){let u=i??D(t.options.query)??D(t.options.sn);if(!u)throw Error("Usage: seal-use approval-runs pick --sn <documentSN>");await X("seal_approval_run_pick",r,o,{query:u,sn:D(t.options.sn),batchId:D(t.options.batch)??D(t.options.batchId),latest:_(t.options.latest),fields:D(t.options.fields),limit:ln(t.options.limit),includeBridge:_(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:D(t.options.fields),summary:_(t.options.summary)},J(t.options));return}if(n==="cited-rules"){let u=t.command[2];if(!u)throw Error("Usage: seal-use 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-use 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-use approval-runs attachments <recordId>");await X("seal_approval_run_attachments_get",r,o,{recordId:u,summary:_(t.options.summary)},J(t.options));return}if(n==="result"){let u=t.command[2];if(!u)throw Error("Usage: seal-use approval-runs result <recordId> [--summary]");await X("seal_approval_run_result_get",r,o,{recordId:u,summary:_(t.options.summary)},J(t.options));return}if(n==="url"){await X("seal_approval_run_url_get",r,o,{recordId:i,sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId)},J(t.options));return}throw Error(`Unknown approval-runs command: ${n??""}. Run 'seal-use help' for available commands.`)}async function gL(n,i,r){if(n==="diagnose"){B(await CF(i));return}if(n==="hose-link"){let o=ln(r.options.expire)??7200;B(await ik(i,o));return}throw Error(`Unknown auth command: ${n??""}. Run 'seal-use help' for available commands.`)}async function CF(n){if(n.source.type!=="hose"){let c=await On(n),S=await Qi(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}]}}Hv(n.id);let i=n.source,r=i.appKey??i.key,o=i.appSecurity??i.password,t=(n Line truncated
`)}function Nn(n){let i=Hi(),r=Vn();return xr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n},Tt())}function Cu(n=Vn()){return{mode:n.stateful?"stateful":"stateless",stateful:n.stateful,...n.stateful&&n.defaultCorpId?{defaultCorpId:n.defaultCorpId}:{},lint:n.lint,configFile:mr()}}async function J(n,i,r,o,t={}){B(await no(n,i,r,o),t)}async function no(n,i,r,o){let t=qu.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 SL(n,i,r,o,t){if(n==="summary"){let u=await no("seal_approval_runs_summary",r,o,{date:U(t.options.date),timezone:U(t.options.timezone),limit:en(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-use approval-runs list --limit 10 查看最近记录。`);B(u,j(t.options));return}if(n==="stats"){await J("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 J("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 J("seal_approval_runs_search",r,o,{limit:en(t.options.limit),offset:en(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:E(t.options.includeBridge)},j(t.options));return}if(n==="bridge"){await J("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:en(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-use approval-runs pick --sn <documentSN>");await J("seal_approval_run_pick",r,o,{query:u,sn:U(t.options.sn),batchId:U(t.options.batch)??U(t.options.batchId),latest:E(t.options.latest),fields:U(t.options.fields),limit:en(t.options.limit),includeBridge:E(t.options.includeBridge)},j(t.options));return}if(n==="get"){let u=t.command[2];if(!u)throw Error("Missing approval run recordId");await J("seal_approval_run_get",r,o,{recordId:u,fields:U(t.options.fields),summary:E(t.options.summary)},j(t.options));return}if(n==="cited-rules"){let u=t.command[2];if(!u)throw Error("Usage: seal-use approval-runs cited-rules <recordId>");await J("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-use approval-runs document-summary <recordId>");await J("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-use approval-runs attachments <recordId>");await J("seal_approval_run_attachments_get",r,o,{recordId:u,summary:E(t.options.summary)},j(t.options));return}if(n==="result"){let u=t.command[2];if(!u)throw Error("Usage: seal-use approval-runs result <recordId> [--summary]");await J("seal_approval_run_result_get",r,o,{recordId:u,summary:E(t.options.summary)},j(t.options));return}if(n==="url"){await J("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-use help' for available commands.`)}async function kL(n,i,r){if(n==="diagnose"){B(await bP(i));return}if(n==="hose-link"){let o=en(r.options.expire)??7200;B(await vO(i,o));return}throw Error(`Unknown auth command: ${n??""}. Run 'seal-use help' for available commands.`)}async function bP(n){if(n.source.type!=="hose"){let c=await dn(n),S=await Qi(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}]}}Fv(n.id);let i=n.source,r=i.appKey??i.key,o=i.appSecurity??i.p Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${Wn.length} candidate administrators:
- ${jn}
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-use corps hose-staffs' to discover available administrators.");let d=Un(n,"id")??w,k=f??w,P=Un(n,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,Q={id:d,name:k,seal:{url:P,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)Hv(d),await ar(Q);let W=l4();SL(W,{recursive:!0,mode:448});let N=OL(W,`${Q4(d)}.json`);if(DL(N)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${N}. Pass "overwrite": true to replace it.`);AL(N,`${JSON.stringify(Q,null,2)}
`,{mode:384}),B({id:d,name:k,corpId:w,domain:b,staffId:S,verified:g,path:N})}async function sF(n){let i=St(n,"token"),r=(Un(n,"sealUrl")??Un(n,"url")??"").replace(/\/+$/,"");if(!r)throw Error("Missing required JSON field: sealUrl");let o=nL(n,"expiresIn")??2592000,t=n.force===!0||n.verify===!1?!1:!0,u=t?await iK(r,i):void 0;kL(n,{token:i,sealUrl:r,expiresIn:o,verify:t,remote:u})}async function nK(n,i,r){let o=await Yv(n),t=Xu(o.sealUrl,o.token),u=await Qi(t),e={user:u.user,tenant:u.tenant};pv(o.corpId,e.tenant),kL({id:o.corpId,corpId:o.corpId,name:i,provider:"hosecloud",overwrite:r},{token:o.token,sealUrl:o.sealUrl,expiresIn:o.expiresIn,verify:!0,remote:e})}function kL(n,i){let{token:r,sealUrl:o,expiresIn:t,verify:u,remote:e}=i,l=e?.user,$=e?.tenant,I=Un(n,"tenantSlug")??At($?.tenantSlug),g=Un(n,"tenantId")??At($?.id),b=Un(n,"tenantName")??At($?.name),w=Un(n,"id")??I??g;if(!w)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let f=Un(n,"staffId")??At(l?.providerUserId)??At(l?.id)??"seal",c=Un(n,"provider")??At(l?.provider)??At($?.providerConfig?.provider),S=Un(n,"corpId")??I??g??w,d={id:w,name:Un(n,"name")??b??w,seal:{url:o,tenantSlug:I,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:r,sealUrl:o,expiresIn:t,staffId:f,corpId:S,tenantId:g,tenantSlug:I,tenantName:b,providerUserId:At(l?.providerUserId),provider:c},auth:{refreshTtl:300}},k=l4();SL(k,{recursive:!0,mode:448});let P=OL(k,`${Q4(w)}.json`);if(DL(P)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${P}. Pass "overwrite": true to replace it.`);AL(P,`${JSON.stringify(d,null,2)}
`,{mode:384}),B({id:w,name:d.name,tenantId:g,tenantSlug:I,verified:u,path:P})}async function iK(n,i){let r=await tK(`${n}/api/v1/auth/me`,{authorization:`Bearer ${i}`}),o=u$(r.data);return{user:u$(o.user??r.user),tenant:u$(o.tenant??r.tenant)}}async function tK(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 u$(t)}function u$(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:{}}function At(n){return typeof n==="string"&&n?n:void 0}async function NL(n,i){let r=await Yv(n),o=Xu(r.sealUrl,r.token),t=await Qi(o);pv(r.corpId,t.tenant);let u=await hr(o,{note:i});B({tenant:{id:t.tenant.id,name:t.tenant.name,tenantSlug:t.tenant.tenantSlug,corpId:r.corpId},user:{id:t.user.id,name:t.user.name,providerUserId:t.user.providerUserId,isAdmin:t.user.isAdmin},delegation:u,expiresIn:r.expiresIn})}async function LL(n,i,r,o,t){if(n==="list"){await X("seal_delegation_list",r,o,{},J(t.options));return}if(n==="create"){let u=D(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??D(t.options.tokenId);if(!u)throw Error("Usage: seal-use delegation revoke <tokenId>");await X("seal_delegation_revoke",r,o,{tokenId:u},J(t.options));return}throw Error(`Unknown delegation command: ${n??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as rK}from"node:fs";async function yL(n,i,r,o,t,u){if(!n||n==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
- ${pn}
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-use corps hose-staffs' to discover available administrators.");let k=Un(n,"id")??f,O=w??f,F=Un(n,"sealUrl")??`https://${f.toLowerCase()}.sealai.cc`,Q={id:k,name:O,seal:{url:F,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:b,appKey:r,appSecurity:o,corpId:f,staffId:S},auth:{refreshTtl:300}};if(g)Fv(k),await io(Q);let W=$0();pL(W,{recursive:!0,mode:448});let y=JL(W,`${V0(k)}.json`);if(WL(y)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${y}. Pass "overwrite": true to replace it.`);jL(y,`${JSON.stringify(Q,null,2)}
`,{mode:384}),B({id:k,name:O,corpId:f,domain:b,staffId:S,verified:g,path:y})}async function SP(n){let i=kt(n,"token"),r=(Un(n,"sealUrl")??Un(n,"url")??"").replace(/\/+$/,"");if(!r)throw Error("Missing required JSON field: sealUrl");let o=IL(n,"expiresIn")??2592000,t=n.force===!0||n.verify===!1?!1:!0,u=t?await dP(r,i):void 0;HL(n,{token:i,sealUrl:r,expiresIn:o,verify:t,remote:u})}async function AP(n,i,r){let o=await Kv(n),t=Yu(o.sealUrl,o.token),u=await Qi(t),e={user:u.user,tenant:u.tenant};Pv(o.corpId,e.tenant),HL({id:o.corpId,corpId:o.corpId,name:i,provider:"hosecloud",overwrite:r},{token:o.token,sealUrl:o.sealUrl,expiresIn:o.expiresIn,verify:!0,remote:e})}function HL(n,i){let{token:r,sealUrl:o,expiresIn:t,verify:u,remote:e}=i,l=e?.user,$=e?.tenant,I=Un(n,"tenantSlug")??Ot($?.tenantSlug),g=Un(n,"tenantId")??Ot($?.id),b=Un(n,"tenantName")??Ot($?.name),f=Un(n,"id")??I??g;if(!f)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let w=Un(n,"staffId")??Ot(l?.providerUserId)??Ot(l?.id)??"seal",c=Un(n,"provider")??Ot(l?.provider)??Ot($?.providerConfig?.provider),S=Un(n,"corpId")??I??g??f,k={id:f,name:Un(n,"name")??b??f,seal:{url:o,tenantSlug:I,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:r,sealUrl:o,expiresIn:t,staffId:w,corpId:S,tenantId:g,tenantSlug:I,tenantName:b,providerUserId:Ot(l?.providerUserId),provider:c},auth:{refreshTtl:300}},O=$0();pL(O,{recursive:!0,mode:448});let F=JL(O,`${V0(f)}.json`);if(WL(F)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${F}. Pass "overwrite": true to replace it.`);jL(F,`${JSON.stringify(k,null,2)}
`,{mode:384}),B({id:f,name:k.name,tenantId:g,tenantSlug:I,verified:u,path:F})}async function dP(n,i){let r=await kP(`${n}/api/v1/auth/me`,{authorization:`Bearer ${i}`}),o=l$(r.data);return{user:l$(o.user??r.user),tenant:l$(o.tenant??r.tenant)}}async function kP(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 l$(t)}function l$(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:{}}function Ot(n){return typeof n==="string"&&n?n:void 0}async function YL(n,i){let r=await Kv(n),o=Yu(r.sealUrl,r.token),t=await Qi(o);Pv(r.corpId,t.tenant);let u=await ar(o,{note:i});B({tenant:{id:t.tenant.id,name:t.tenant.name,tenantSlug:t.tenant.tenantSlug,corpId:r.corpId},user:{id:t.user.id,name:t.user.name,providerUserId:t.user.providerUserId,isAdmin:t.user.isAdmin},delegation:u,expiresIn:r.expiresIn})}async function QL(n,i,r,o,t){if(n==="list"){await J("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 J("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-use delegation revoke <tokenId>");await J("seal_delegation_revoke",r,o,{tokenId:u},j(t.options));return}throw Error(`Unknown delegation command: ${n??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as OP}from"node:fs";async function FL(n,i,r,o,t,u){if(!n||n==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
`+`支持的审批系统与发布目标:
`+` • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>
@@ -189,13 +189,20 @@ Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an a
`+` • feishu (飞书审批): 建议使用 Webhook 模式对接
`+` • weaver (泛微 OA): 建议使用 Webhook 模式对接
`+` • helios (汇联易): 建议使用 Webhook 模式对接
`+" • maycur (每刻报销): 建议使用 Webhook 模式对接");if(n==="webhook"||n==="webhooks")throw Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");if(n==="feishu"||n==="lark")throw Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");if(n==="weaver")throw Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");if(n==="maycur"||n==="helios"){let I=n==="maycur"?"每刻报销":"汇联易";throw Error(`${I}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${I}' --result-url <url> --corp <corpId>`)}let e=n==="hosecloud",l=n==="hosecloud"?i:n,$=n==="hosecloud"?r:i;if(!e)throw Error(`未知的发布目标系统: ${n}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);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=$??D(u.options.signKey)??D(u.options["sign-key"]);if(!I)throw Error("Usage: seal-use 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=D(u.options.input),g=I?JSON.parse(rK(I,"utf8")):ri(u.json);if(!g||Object.keys(g).length===0)throw Error("Usage: seal-use 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=$??D(u.options.signKey)??D(u.options["sign-key"]);if(!I)throw Error("Usage: seal-use 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 vK}from"node:http";import{URL as uK}from"node:url";var GL={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.3",description:`Planned HTTP contract for the seal-use wrapped backend API.
`+" • maycur (每刻报销): 建议使用 Webhook 模式对接");if(n==="webhook"||n==="webhooks")throw Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");if(n==="feishu"||n==="lark")throw Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");if(n==="weaver")throw Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");if(n==="maycur"||n==="helios"){let I=n==="maycur"?"每刻报销":"汇联易";throw Error(`${I}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${I}' --result-url <url> --corp <corpId>`)}let e=n==="hosecloud",l=n==="hosecloud"?i:n,$=n==="hosecloud"?r:i;if(!e)throw Error(`未知的发布目标系统: ${n}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(l==="requirements"){await J("seal_deploy_hosecloud_requirements",o,t,{},j(u.options));return}if(l==="list"){await J("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){let b=((await kn(o)).integrations??[]).filter((f)=>f.type==="hosecloud");if(b.length===0)throw Error(`当前企业 (${t.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${t.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${t.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let f of b){let w=f.outboundName??"SealAI 审批",c=f.signKey,S=f.apiOrigin??"production";console.error(` • "${w}" (signKey: ${c}, 环境: ${S})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${c} --corp ${t.id}
`)}throw Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。")}await J("seal_deploy_hosecloud_get",o,t,{signKey:I},j(u.options));return}if(l==="status"){await J("seal_deploy_hosecloud_status",o,t,{},j(u.options));return}if(l==="configure"){let I=U(u.options.input),g=I?JSON.parse(OP(I,"utf8")):oi(u.json);if(!g||Object.keys(g).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await J("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"]),g=E(u.options.auto)??E(u.options.yes);if(!I){let f=((await kn(o)).integrations??[]).filter((w)=>w.type==="hosecloud");if(f.length===0)throw Error(`当前企业 (${t.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${t.id}`);if(f.length===1&&g){let w=f[0].signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${w})`),await J("seal_deploy_hosecloud_sync",o,t,{signKey:w},j(u.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${t.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let w of f){let c=w.outboundName??"SealAI 审批",S=w.signKey,k=w.apiOrigin??"production";console.error(` • "${c}" (signKey: ${S}, 环境: ${k})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${S} --corp ${t.id}
`)}if(f.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${t.id}
`);throw Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。")}await J("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 WP}from"node:http";import{URL as LP}from"node:url";var KL={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.5",description:`Planned HTTP contract for the seal-use 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-use 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" />
@@ -219,20 +226,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 Xn(n,i,r,o){let t=n.handler;return t(i,r,{corp:o})}async function jL(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 uK(n.url||"/",`${o}://${r}`),u=t.pathname.replace(/\/+$/,"")||"/",e=(n.method||"GET").toUpperCase();try{if(e==="GET"&&u==="/"){Sn(i,200,{name:"seal-use",version:x,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"){lK(i,200,WL());return}if(e==="GET"&&u==="/openapi.json"){Sn(i,200,e$());return}if(e==="GET"&&u==="/health"){Sn(i,200,{status:"ok",version:x,name:"seal-use",timestamp:new Date().toISOString()});return}if(e==="POST"&&u==="/api/cli"){let l=await v$(n),$=(typeof l?.command==="string"?l.command:"").trim();if(!$){l$(i,400,"Missing 'command' property in request body");return}let I=T4($),g=I[0]==="seal-use"||I[0]==="seal-home"||I[0]?.endsWith("/seal-use")||I[0]?.endsWith("/seal-home")?I.slice(1):I,b=await Mu(g),w=void 0;try{if(b.stdout.trim().startsWith("{")||b.stdout.trim().startsWith("["))w=JSON.parse(b.stdout)}catch{}Sn(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(),$=Gn(l,{includeMcpAliases:!0});if(!$){l$(i,404,`Tool not found: '${l}'`);return}let I=await v$(n)||{},g=Rn(n,t,I),b=Ln(g),w=await On(b),f={...I};delete f.corp;let c=await Xn($,w,f,b);Sn(i,200,c);return}if(u.startsWith("/v1/")){if(await eK(n,i,e,u,t))return}l$(i,404,`Cannot ${e} ${u}. Visit /docs for available endpoints.`)}catch(l){let $=l instanceof Error?l.message:String(l);l$(i,500,$)}}async function eK(n,i,r,o,t){let u=Object.fromEntries(t.searchParams.entries());if(r==="GET"&&o==="/v1/corps"){let e=Yi(),l=bi();return Sn(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=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_whoami"),g=await Xn(I,$,{},l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/session"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_session_get"),g=await Xn(I,$,{},l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/summary"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_runs_summary"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/stats"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_runs_stats"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/pick"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_run_pick"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/url"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_run_url_get"),g=await Xn(I,$,u,l);return Sn(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=Rn(n,t,u),g=Ln(I),b=await On(g);if(!$){let w=Gn("seal_approval_run_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="attachments"){let w=Gn("seal_approval_run_attachments_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="cited-rules"){let w=Gn("seal_approval_run_cited_rules_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="document-summary"){let w=Gn("seal_approval_run_document_summary_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="result"){let w=Gn("seal_approval_run_result_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}}}if(r==="GET"&&o==="/v1/approval-runs"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("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 Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval/rules"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_rules_list"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/simulation/batches"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_simulation_batches_list"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="POST"&&o==="/v1/simulation/create-batch"){let e=await v$(n)||{},l=Rn(n,t,e),$=Ln(l),I=await On($),g=Gn("seal_simulation_batch_create"),b=await Xn(g,I,e,$);return Sn(i,200,b),!0}if(r==="GET"&&o.startsWith("/v1/simulation/batch/")){let l=o.slice(21).split("/")[0];if(l){let $=Rn(n,t,u),I=LnLine truncated
</html>`}async function Jn(n,i,r,o){let t=n.handler;return t(i,r,{corp:o})}async function BL(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 LP(n.url||"/",`${o}://${r}`),u=t.pathname.replace(/\/+$/,"")||"/",e=(n.method||"GET").toUpperCase();try{if(e==="GET"&&u==="/"){Sn(i,200,{name:"seal-use",version:x,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"){GP(i,200,PL());return}if(e==="GET"&&u==="/openapi.json"){Sn(i,200,v$());return}if(e==="GET"&&u==="/health"){Sn(i,200,{status:"ok",version:x,name:"seal-use",timestamp:new Date().toISOString()});return}if(e==="POST"&&u==="/api/cli"){let l=await I$(n),$=(typeof l?.command==="string"?l.command:"").trim();if(!$){$$(i,400,"Missing 'command' property in request body");return}let I=C0($),g=I[0]==="seal-use"||I[0]==="seal-home"||I[0]?.endsWith("/seal-use")||I[0]?.endsWith("/seal-home")?I.slice(1):I,b=await hu(g),f=void 0;try{if(b.stdout.trim().startsWith("{")||b.stdout.trim().startsWith("["))f=JSON.parse(b.stdout)}catch{}Sn(i,b.isError?400:200,{success:!b.isError,stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,data:f});return}if(e==="POST"&&u.startsWith("/api/tool/")){let l=u.slice(10).trim(),$=Gn(l,{includeMcpAliases:!0});if(!$){$$(i,404,`Tool not found: '${l}'`);return}let I=await I$(n)||{},g=hn(n,t,I),b=Nn(g),f=await dn(b),w={...I};delete w.corp;let c=await Jn($,f,w,b);Sn(i,200,c);return}if(u.startsWith("/v1/")){if(await NP(n,i,e,u,t))return}$$(i,404,`Cannot ${e} ${u}. Visit /docs for available endpoints.`)}catch(l){let $=l instanceof Error?l.message:String(l);$$(i,500,$)}}async function NP(n,i,r,o,t){let u=Object.fromEntries(t.searchParams.entries());if(r==="GET"&&o==="/v1/corps"){let e=Hi(),l=Vn();return Sn(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=hn(n,t,u),l=Nn(e),$=await dn(l),I=Gn("seal_whoami"),g=await Jn(I,$,{},l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/session"){let e=hn(n,t,u),l=Nn(e),$=await dn(l),I=Gn("seal_session_get"),g=await Jn(I,$,{},l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/summary"){let e=hn(n,t,u),l=Nn(e),$=await dn(l),I=Gn("seal_approval_runs_summary"),g=await Jn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/stats"){let e=hn(n,t,u),l=Nn(e),$=await dn(l),I=Gn("seal_approval_runs_stats"),g=await Jn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/pick"){let e=hn(n,t,u),l=Nn(e),$=await dn(l),I=Gn("seal_approval_run_pick"),g=await Jn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/url"){let e=hn(n,t,u),l=Nn(e),$=await dn(l),I=Gn("seal_approval_run_url_get"),g=await Jn(I,$,u,l);return Sn(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=hn(n,t,u),g=Nn(I),b=await dn(g);if(!$){let f=Gn("seal_approval_run_get"),w=await Jn(f,b,{recordId:l,...u},g);return Sn(i,200,w),!0}if($==="attachments"){let f=Gn("seal_approval_run_attachments_get"),w=await Jn(f,b,{recordId:l,...u},g);return Sn(i,200,w),!0}if($==="cited-rules"){let f=Gn("seal_approval_run_cited_rules_get"),w=await Jn(f,b,{recordId:l,...u},g);return Sn(i,200,w),!0}if($==="document-summary"){let f=Gn("seal_approval_run_document_summary_get"),w=await Jn(f,b,{recordId:l,...u},g);return Sn(i,200,w),!0}if($==="result"){let f=Gn("seal_approval_run_result_get"),w=await Jn(f,b,{recordId:l,...u},g);return Sn(i,200,w),!0}}}if(r==="GET"&&o==="/v1/approval-runs"){let e=hn(n,t,u),l=Nn(e),$=await dn(l),I=Gn("seal_approval_runs_search"),g=await Jn(I,$,{...u,limit:u.limit?Number(u.limit):void 0,offset:u.offset?Number(u.offset):void 0,includeBridge:u.includeBridge==="true"},l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval/rules"){let e=hn(n,t,u),l=Nn(e),$=await dn(l),I=Gn("seal_approval_rules_list"),g=await Jn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/simulation/batches"){let e=hn(n,t,u),l=Nn(e),$=await dn(l),I=Gn("seal_simulation_batches_list"),g=await Jn(I,$,u,l);return Sn(i,200,g),!0}if(r==="POST"&&o==="/v1/simulation/create-batch"){let e=await I$(n)||{},l=hn(n,t,e),$=Nn(l),I=await dn($),g=Gn("seal_simulation_batch_create"),b=await Jn(g,I,e,$);return Sn(i,200,b),!0}if(r==="GET"&&o.startsWith("/v1/simulation/batch/")){let l=o.slice(21).split("/")[0];if(l){let $=hn(n,t,u),I=NnLine truncated
\uD83D\uDE80 seal-use HTTP Server (v${x}) 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 XL(n){let i=ln(n.options.port)??ln(n.options.p),r=D(n.options.host)??D(n.options.h),o=await JL({port:i,host:r}),t=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}async function HL(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-use help' for available commands.`)}async function YL(n,i){if(n==="config"||n==="json"){V4();return}await q4()}function V4(){B({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function pL(n){let i=e$();B(i,{...J(n.options),allowFull:!0})}async function QL(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-use help' for available commands.`)}import{readFileSync as PL}from"node:fs";async function FL(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=D(e.options.input),$=l?JSON.parse(PL(l,"utf8")):ri(e.json);if(!$||Object.keys($).length===0)throw Error(`Usage: seal-use 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=D(e.options.default)??D(e.options.level)??o;if(l!=="medium"&&l!=="high")throw Error("Usage: seal-use 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=D(e.options.input),$=l?JSON.parse(PL(l,"utf8")):ri(e.json);if(!$||!$.id||!$.name)throw Error(`Usage: seal-use 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??D(e.options.id)??D(e.options.policyId);if(!l)throw Error("Usage: seal-use 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 KL(n={}){let i=Yi(),r=bi(),o=Rr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n.corpId},Kt());console.log(`[probe] corp=${o.id} source=${o.source.type}`);let t=await ar(o);console.log("[probe] seal enterprise"),console.log(JSON.stringify(t,null,2));let u=await On(o),e=await hv(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 BL(n,i,r){let o=i??D(r.options.corp)??(n&&n!=="--corp"?n:void 0);await KL({corpId:o})}async function EL(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(_(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(_(t.options.summary)){await X("seal_approval_rules_list",r,o,{fields:uL,limit:u,offset:e},J(t.options));return}let l=await xr("seal_approval_rules_list",r,o,{limit:u,offset:e});eL(l,_(t.options.full)===!0),B(l);return}if(n==="clear"){let u=_(t.options.yes)===!0,e=_(t.options.dryRun)??_(t.options["dry-run"])??!u;if(!u&&!e)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let l=await xr("seal_approval_rules_clear",r,o,{dryRun:e,recode:_(t.options.recode)});if(!u&&e&&l&&typeof l==="object"){B({...l,nextCommand:`seal-use 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??D(t.options.version);if(!u)throw Error("Usage: seal-use rules version <versionId|versionNumber|latest>");await X("seal_approval_rule_version_get",r,o,Vu(u),J(t.options));return}if(n==="get"){await X("seal_approval_rule_get",r,o,{...oL(D(t.options.version)),code:D(t.options.code),runtimeId:D(t.options.runtimeId)??D(t.options["runtime-id"]),recordId:D(t.options.recordId)??D(t.options["record-id"])},J(t.options));return}if( Line truncated
`,{mode:384}),I$(r,`running pid=${process.pid}`);let o=()=>{if(Z4(i)===process.pid)$$(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 TL(n){ZL(n.stateDir);let i=sr(n);if(i.running)return i;let r=n.launcher??{command:process.execPath,args:[n.entryFile]},o=$K(r.command,[...r.args??[],"service","run"],{cwd:n.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});o.unref();let t=g$(n);return _4(t,`${o.pid}
`,{mode:384}),I$(b$(n),`started pid=${o.pid}`),{started:!0,...sr(n)}}function VL(n,i={}){let r=g$(n),o=Z4(r);if(!o||!_L(o,n.appRoot))return $$(r,{force:!0}),i.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(o,"SIGTERM"),$$(r,{force:!0}),I$(b$(n),`stop requested pid=${o}`),i.quiet?void 0:{stopped:!0,pid:o}}function _L(n,i){if(!cK(n))return!1;try{let r=IK("ps",["-p",String(n),"-o","command="],{encoding:"utf8"});return(r.includes(i)||r.includes("seal-use")||r.includes("src/cli.ts"))&&r.includes("service")&&r.includes("run")}catch{return!1}}function cK(n){try{return process.kill(n,0),!0}catch{return!1}}function g$(n){return qL(n.stateDir,"service.pid")}function b$(n){return qL(n.stateDir,"service.log")}function Z4(n){if(!gK(n))return;let i=Number(wK(n,"utf8").trim());return Number.isInteger(i)&&i>0?i:void 0}function ZL(n){bK(n,{recursive:!0,mode:448})}function I$(n,i){_4(n,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var M4=DK(UK(),".config","seal-use");async function ML(n,i){let r=await _t(n,{appRoot:i.appRoot,entryFile:i.entryFile,stateDir:M4,version:x,launcher:i.launcher});if(r!==void 0)B(r)}import{existsSync as SK,readFileSync as zL}from"node:fs";async function CL(n,i,r,o,t){if(n==="batch-records"||n==="records"){let u=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!u)throw Error("Usage: seal-use simulation batch-records <batchId>");await X("seal_simulation_batch_records_get",r,o,{batchId:u,query:D(t.options.query)},J(t.options));return}if(n==="create"||n==="run"){let u=D(t.options.mode)??D(t.options.sourceSystem)??D(t.options["source-system"])??"hosecloud",e=u==="material-pack"?"material_pack":u,l=D(t.options.schemaConfig)??D(t.options["schema-config"]),$=l?JSON.parse(zL(l,"utf8")):void 0,I=D(t.options.input),g=I?JSON.parse(zL(I,"utf8")):ri(t.json),b=D(t.options.packageId)??D(t.options["package-id"]),w=Vn(t.options.packageIds)??Vn(t.options["package-ids"])??(b?[b]:void 0),f=Vn(t.options.flowIds)??Vn(t.options["flow-ids"])??Vn(t.options.documentSn)??Vn(t.options["document-sn"]),c=D(t.options.signKey)??D(t.options["sign-key"])??D(t.options.integration);await X("seal_simulation_batch_create",r,o,{mode:e,sourceSystem:e,flowIds:f,documentSn:f,rejectNodeName:D(t.options.rejectNode)??D(t.options["reject-node"])??null,thinkingDepthOverride:D(t.options.thinkingDepth)??D(t.options["thinking-depth"]),skipInvoiceGeneration:_(t.options.skipInvoiceGeneration)??_(t.options["skip-invoice-generation"]),skipExpenseExtraction:_(t.options.skipExpenseExtraction)??_(t.options["skip-expense-extraction"]),disableAttachmentCache:_(t.options.disableAttachmentCache)??_(t.options["disable-attachment-cache"]),signKey:c,packageIds:w,packageId:b,templateId:D(t.options.templateId)??D(t.options["template-id"]),schemaConfig:$,requestIds:Vn(t.options.requestIds)??Vn(t.options["request-ids"]),workflowTypeId:D(t.options.workflowTypeId)??D(t.options["workflow-type-id"]),flowStatusList:Vn(t.options.flowStatusList)?.map(Number)??Vn(t.options["flow-status-list"])?.map(Number),businessCodes:Vn(t.options.businessCodes)??Vn(t.options["business-codes"]),documentType:D(t.options.documentType)??D(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:Vn(t.options.status),limit:ln(t.options.limit),rawParams:g},J(t.options));return}if(n==="wait"){let u=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!u)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await X("seal_simulation_batch_wait",r,o,{batchId:u,timeout:D(t.options.timeout),pollInterval:D(t.options.pollInterval)??D(t.options["poll-interval"])},J(t.options));return}if(n==="clean"||n==="delete"){let u=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!u)throw Error("Usage: seal-use simulation clean <batchId>");await X("seal_simulation_batch_clean",r,o,{batchId:u},J(t.options));return}if(n==="specifications"){let u=i??D(t.options.integration)??D(t.options.signKey)??D(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??D(t.options.batchId)??D(t.options["batch-id"]);if(!u)throw Error("Usage: seal-use 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??D(t.options.file);if(!u)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!SK(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-use help' for available commands.`)}import{existsSync as gy}from"node:fs";import{join as w$}from"node:path";import{existsSync as z4,mkdirSync as uy,rmSync as XK,writeFileSync as HK}from"node:fs";import{homedir as ey}from"node:os";import{dirname as YK,join as C4}from"node:path";var RL=`---
`);t(o)})})}async function TL(n){let i=en(n.options.port)??en(n.options.p),r=U(n.options.host)??U(n.options.h),o=await EL({port:i,host:r}),t=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}async function VL(n,i,r,o){if(n==="config"||n==="get"){await J("seal_llm_config_get",i,r,{},j(o.options));return}if(n==="providers"||n==="list"){await J("seal_llm_providers_list",i,r,{},j(o.options));return}throw Error(`Unknown llm command: ${n??""}. Run 'seal-use help' for available commands.`)}async function _L(n,i){if(n==="config"||n==="json"){R0();return}await h0()}function R0(){B({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function qL(n){let i=v$();B(i,{...j(n.options),allowFull:!0})}async function ZL(n,i,r,o){if(n==="available"){await J("seal_permissions_available_list",i,r,{},j(o.options));return}if(n==="configs"||n==="list"){await J("seal_permissions_configs_list",i,r,{},j(o.options));return}throw Error(`Unknown permissions command: ${n??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as ML}from"node:fs";async function zL(n,i,r,o,t,u,e){if(!n||n==="get"){await J("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(ML(l,"utf8")):oi(e.json);if(!$||Object.keys($).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await J("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-use preference thinking-depth set --default <medium|high>");await J("seal_preference_thinking_depth_set",t,u,{defaultLevel:l},j(e.options));return}if(i==="policies"){if(r==="list"||!r){await J("seal_preference_thinking_depth_policies_list",t,u,{},j(e.options));return}if(r==="upsert"){let l=U(e.options.input),$=l?JSON.parse(ML(l,"utf8")):oi(e.json);if(!$||!$.id||!$.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await J("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-use preference thinking-depth policies remove <policyId>");await J("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 CL(n={}){let i=Hi(),r=Vn(),o=xr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n.corpId},Tt());console.log(`[probe] corp=${o.id} source=${o.source.type}`);let t=await io(o);console.log("[probe] seal enterprise"),console.log(JSON.stringify(t,null,2));let u=await dn(o),e=await av(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 RL(n,i,r){let o=i??U(r.options.corp)??(n&&n!=="--corp"?n:void 0);await CL({corpId:o})}async function hL(n,i,r,o,t){if(n==="count"){await J("seal_approval_rules_list",r,o,{countOnly:!0},j(t.options));return}if(n==="list"){if(E(t.options.count)){await J("seal_approval_rules_list",r,o,{countOnly:!0},j(t.options));return}let u=en(t.options.limit),e=en(t.options.offset);if(E(t.options.summary)){await J("seal_approval_rules_list",r,o,{fields:cL,limit:u,offset:e},j(t.options));return}let l=await no("seal_approval_rules_list",r,o,{limit:u,offset:e});UL(l,E(t.options.full)===!0),B(l);return}if(n==="clear"){let u=E(t.options.yes)===!0,e=E(t.options.dryRun)??E(t.options["dry-run"])??!u;if(!u&&!e)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let l=await no("seal_approval_rules_clear",r,o,{dryRun:e,recode:E(t.options.recode)});if(!u&&e&&l&&typeof l==="object"){B({...l,nextCommand:`seal-use rules clear --corp ${o.id} --yes`},j(t.options));return}B(l,j(t.options));return}if(n==="versions"){await J("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-use rules version <versionId|versionNumber|latest>");await J("seal_approval_rule_version_get",r,o,Zu(u),j(t.options));return}if(n==="get"){await J("seal_approval_rule_get",r,o,{...wL(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));return}if( Line truncated
`,{mode:384}),b$(r,`running pid=${process.pid}`);let o=()=>{if(x0(i)===process.pid)g$(i,{force:!0});b$(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 mL(n){nN(n.stateDir);let i=to(n);if(i.running)return i;let r=n.launcher??{command:process.execPath,args:[n.entryFile]},o=pP(r.command,[...r.args??[],"service","run"],{cwd:n.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});o.unref();let t=f$(n);return m0(t,`${o.pid}
`,{mode:384}),b$(w$(n),`started pid=${o.pid}`),{started:!0,...to(n)}}function xL(n,i={}){let r=f$(n),o=x0(r);if(!o||!sL(o,n.appRoot))return g$(r,{force:!0}),i.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(o,"SIGTERM"),g$(r,{force:!0}),b$(w$(n),`stop requested pid=${o}`),i.quiet?void 0:{stopped:!0,pid:o}}function sL(n,i){if(!QP(n))return!1;try{let r=jP("ps",["-p",String(n),"-o","command="],{encoding:"utf8"});return(r.includes(i)||r.includes("seal-use")||r.includes("src/cli.ts"))&&r.includes("service")&&r.includes("run")}catch{return!1}}function QP(n){try{return process.kill(n,0),!0}catch{return!1}}function f$(n){return aL(n.stateDir,"service.pid")}function w$(n){return aL(n.stateDir,"service.log")}function x0(n){if(!JP(n))return;let i=Number(HP(n,"utf8").trim());return Number.isInteger(i)&&i>0?i:void 0}function nN(n){XP(n,{recursive:!0,mode:448})}function b$(n,i){m0(n,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var a0=KP(FP(),".config","seal-use");async function iN(n,i){let r=await Mt(n,{appRoot:i.appRoot,entryFile:i.entryFile,stateDir:a0,version:x,launcher:i.launcher});if(r!==void 0)B(r)}import{existsSync as PP,readFileSync as tN}from"node:fs";async function rN(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-use simulation batch-records <batchId>");await J("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(tN(l,"utf8")):void 0,I=U(t.options.input),g=I?JSON.parse(tN(I,"utf8")):oi(t.json),b=U(t.options.packageId)??U(t.options["package-id"]),f=_n(t.options.packageIds)??_n(t.options["package-ids"])??(b?[b]:void 0),w=_n(t.options.flowIds)??_n(t.options["flow-ids"])??_n(t.options.documentSn)??_n(t.options["document-sn"]),c=U(t.options.signKey)??U(t.options["sign-key"])??U(t.options.integration);await J("seal_simulation_batch_create",r,o,{mode:e,sourceSystem:e,flowIds:w,documentSn:w,rejectNodeName:U(t.options.rejectNode)??U(t.options["reject-node"])??null,thinkingDepthOverride:U(t.options.thinkingDepth)??U(t.options["thinking-depth"]),skipInvoiceGeneration:E(t.options.skipInvoiceGeneration)??E(t.options["skip-invoice-generation"]),skipExpenseExtraction:E(t.options.skipExpenseExtraction)??E(t.options["skip-expense-extraction"]),disableAttachmentCache:E(t.options.disableAttachmentCache)??E(t.options["disable-attachment-cache"]),signKey:c,packageIds:f,packageId:b,templateId:U(t.options.templateId)??U(t.options["template-id"]),schemaConfig:$,requestIds:_n(t.options.requestIds)??_n(t.options["request-ids"]),workflowTypeId:U(t.options.workflowTypeId)??U(t.options["workflow-type-id"]),flowStatusList:_n(t.options.flowStatusList)?.map(Number)??_n(t.options["flow-status-list"])?.map(Number),businessCodes:_n(t.options.businessCodes)??_n(t.options["business-codes"]),documentType:U(t.options.documentType)??U(t.options["document-type"]),startTime:en(t.options.startTime)??en(t.options["start-time"]),endTime:en(t.options.endTime)??en(t.options["end-time"]),status:_n(t.options.status),limit:en(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-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await J("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-use simulation clean <batchId>");await J("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 J("seal_simulation_specifications_list",r,o,{signKey:u},j(t.options));return}if(n==="list"){await J("seal_simulation_batches_list",r,o,{limit:en(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-use simulation get <batchId>");await J("seal_simulation_batch_get",r,o,{batchId:u},j(t.options));return}if(n==="templates"){await J("seal_simulation_templates_get",r,o,{},j(t.options));return}if(n==="integrations"){await J("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-use simulation package-upload <材料包.zip>");if(!PP(u))throw Error(`File not found: ${u}`);await J("seal_simulation_material_package_upload",r,o,{filePath:u},j(t.options));return}throw Error(`Unknown simulation command: ${n??""}. Run 'seal-use help' for available commands.`)}import{existsSync as kN}from"node:fs";import{join as c$}from"node:path";import{existsSync as s0,mkdirSync as cN,rmSync as hP,writeFileSync as mP}from"node:fs";import{homedir as UN}from"node:os";import{dirname as xP,join as n4}from"node:path";var oN=`---
name: seal-use
description: "v0.10.3: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.10.5: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.10.3
short-description: Seal tenant and Hose approval automation (v0.10.3)
version: 0.10.5
short-description: Seal tenant and Hose approval automation (v0.10.5)
---
# Seal Use (v0.10.3)
# Seal Use (v0.10.5)
Use the \`seal_cli\` MCP tool when it is available; pass the command string as its \`command\` argument. If MCP is unavailable, fall back to the global \`seal-use\` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -293,6 +300,7 @@ seal-use corps list
- Billing & Feature Quotas: \`seal-use billing status --corp <corpId>\`, \`seal-use billing plans --corp <corpId>\`, \`seal-use billing features --corp <corpId>\`.
- Webhook 审批回调管理: \`seal-use webhook <list|get|add|update|delete> --corp <corpId>\`.
- HTTP REST API & Docs Server: \`seal-use http [--port 8787] [--host 127.0.0.1]\` (提供 \`/docs\` 交互文档、\`/openapi.json\`、\`POST /api/cli\` 与 \`/v1/*\` REST API)。
- 审批规则质量校验 (Linter): \`seal-use rules lint [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary] --corp <corpId>\`; read \`references/rule-lint.md\`. 全局配置默认关闭 (\`config lint <enable|disable>\`)。
- Full CLI inventory: read \`references/cli.md\`.
## High-Value Commands
@@ -308,6 +316,7 @@ seal-use approval-runs attachments <recordId> --corp <corpId> --summary
seal-use approval-runs result <recordId> --corp <corpId> --summary
seal-use rules count --corp <corpId>
seal-use rules list --corp <corpId> --summary
seal-use rules lint --corp <corpId> --summary
seal-use rules clear --corp <corpId> --dry-run
seal-use rules clear --corp <corpId> --yes
seal-use rules get --corp <corpId> --version 16 --code '#0038'
@@ -338,6 +347,7 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
- \`references/enterprise-onboarding.md\`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- \`references/approval-run-lightweight.md\`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- \`references/rule-lightweight.md\`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- \`references/rule-lint.md\`: 规则质量检查器(Linter)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
- \`references/customer-feedback-rule-remediation.md\`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- \`references/hose-enterprise-auth.md\`: Hose 企业配置、认证诊断、授权链接。
- \`references/hose-enterprise-init.md\`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
@@ -348,11 +358,11 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
## 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 hL=`interface:
`;var uN=`interface:
display_name: "Seal Use"
short_description: "Diagnose approval feedback and publish minimal rule fixes"
default_prompt: "Use $seal-use to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation."
`;var mL=`# Rule Lightweight Queries
`;var eN=`# 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.
@@ -457,7 +467,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 xL=`# Approval Bad Case Catalog
`;var lN=`# 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.
@@ -507,7 +517,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 aL="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use <command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged.\n- User-level configs override same-ID local configs.\n\nEnterprise selection is stateless by default. Commands that access an enterprise require\n`--corp <corpId>` unless stateful mode is explicitly enabled:\n\n```bash\nseal-use config mode stateful --corp <corpId>\nseal-use corps switch <corpId>\nseal-use config mode stateless\n```\n\nThe global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to\noverride that path. The legacy `current-corp` file is not read.\n\n## Stream & Exit Code Contract\n\n- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.\n- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).\n- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.\n\n## Top-Level Commands\n\n```bash\nseal-use version\nseal-use config paths\nseal-use config get\nseal-use config mode <stateful|stateless> [--corp <corpId>]\nseal-use service <start|stop|restart|status>\nseal-use http [--port 8787] [--host 127.0.0.1]\nseal-use serve [--port 8787]\nseal-use update\nseal-use tools list\nseal-use corps list [--corp <corpId>]\nseal-use corps current [--corp <corpId>]\nseal-use corps switch <corpId>\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use corps add-seal --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]\nseal-use auth diagnose [--corp <corpId>]\nseal-use auth hose-link [--corp <corpId>] [--expire 7200]\nseal-use delegation list [--corp <corpId>]\nseal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]\nseal-use delegation revoke <tokenId> [--corp <corpId>]\nseal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]\nseal-use users reset-password <userId> [--corp <corpId>]\nseal-use users get <userId> [--corp <corpId>]\nseal-use users delete <userId> [--corp <corpId>]\nseal-use llm config [--corp <corpId>]\nseal-use llm providers [--corp <corpId>]\nseal-use permissions available [--corp <corpId>]\nseal-use permissions configs [--corp <corpId>]\nseal-use billing status [--corp <corpId>]\nseal-use billing plans [--corp <corpId>]\nseal-use billing features [--corp <corpId>]\nseal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]\nseal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]\nseal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]\nseal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]\nseal-use webhook delete <idOrName> --yes [--corp <corpId>]\nseal-use deploy hosecloud requirements [--corp <corpId>]\nseal-use deploy hosecloud list [--corp <corpId>]\nseal-use deploy hosecloud get <sign-key> [--corp <corpId>]\nseal-use deploy hosecloud status [--corp <corpId>]\nseal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]\nseal-use deploy hosecloud sync <sign-key> [--corp <corpId>]\nseal-use preference get [--corp <corpId>]\nseal-use preference decision update --json '{\"explicitApprove\":\"...\"}' [--corp <corpId>]\nseal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]\nseal-use preference thinking-depth policies list [--corp <corpId>]\nseal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]\nseal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]\nseal-use source config [--corp <corpId>]\nseal-use tool <toolName> [--corp <corpId>] [--json '{\"key\":\"value\"}']\nseal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]\nseal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]\nseal-use approval-runs count --corp <corpId> [--status APPROVED]\nseal-use approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]\nseal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summary] [--output-file file.json]\nseal-use approval-runs attachments <recordId> --corp <corpId>\nseal-use approval-runs result <recordId> --corp <corpId> [--summary]\nseal-use approval-runs url --corp <corpId>\nseal-use approval-runLine truncated
`;var vN="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use <command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged.\n- User-level configs override same-ID local configs.\n\nEnterprise selection is stateless by default. Commands that access an enterprise require\n`--corp <corpId>` unless stateful mode is explicitly enabled:\n\n```bash\nseal-use config mode stateful --corp <corpId>\nseal-use corps switch <corpId>\nseal-use config mode stateless\n```\n\nThe global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to\noverride that path. The legacy `current-corp` file is not read.\n\n## Stream & Exit Code Contract\n\n- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.\n- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).\n- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.\n\n## Top-Level Commands\n\n```bash\nseal-use version\nseal-use config paths\nseal-use config get\nseal-use config mode <stateful|stateless> [--corp <corpId>]\nseal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]\nseal-use rules lint [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]\nseal-use service <start|stop|restart|status>\nseal-use http [--port 8787] [--host 127.0.0.1]\nseal-use serve [--port 8787]\nseal-use update\nseal-use tools list\nseal-use corps list [--corp <corpId>]\nseal-use corps current [--corp <corpId>]\nseal-use corps switch <corpId>\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use corps add-seal --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]\nseal-use auth diagnose [--corp <corpId>]\nseal-use auth hose-link [--corp <corpId>] [--expire 7200]\nseal-use delegation list [--corp <corpId>]\nseal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]\nseal-use delegation revoke <tokenId> [--corp <corpId>]\nseal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]\nseal-use users reset-password <userId> [--corp <corpId>]\nseal-use users get <userId> [--corp <corpId>]\nseal-use users delete <userId> [--corp <corpId>]\nseal-use llm config [--corp <corpId>]\nseal-use llm providers [--corp <corpId>]\nseal-use permissions available [--corp <corpId>]\nseal-use permissions configs [--corp <corpId>]\nseal-use billing status [--corp <corpId>]\nseal-use billing plans [--corp <corpId>]\nseal-use billing features [--corp <corpId>]\nseal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]\nseal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]\nseal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]\nseal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]\nseal-use webhook delete <idOrName> --yes [--corp <corpId>]\nseal-use deploy hosecloud requirements [--corp <corpId>]\nseal-use deploy hosecloud list [--corp <corpId>]\nseal-use deploy hosecloud get [<sign-key>] [--corp <corpId>]\nseal-use deploy hosecloud status [--corp <corpId>]\nseal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]\nseal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]\nseal-use preference get [--corp <corpId>]\nseal-use preference decision update --json '{\"explicitApprove\":\"...\"}' [--corp <corpId>]\nseal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]\nseal-use preference thinking-depth policies list [--corp <corpId>]\nseal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]\nseal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]\nseal-use source config [--corp <corpId>]\nseal-use tool <toolName> [--corp <corpId>] [--json '{\"key\":\"value\"}']\nseal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]\nseal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]\nseal-use approval-runs count --corp <corpId> [--status APPROVED]\nseal-use approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]\nseal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summaLine truncated
Use this workflow when a customer disputes an AI approval finding about an attachment, invoice, receipt, OCR result, or a UI-highlighted audit result.
@@ -728,7 +738,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 iy=`# Customer Feedback Rule Remediation
`;var gN=`# 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.
@@ -892,7 +902,7 @@ Return a compact report containing:
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
`;var ty="# Enterprise Onboarding\n\nRead this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.\n\n## Start With Discovery\n\nRun this before asking for setup parameters (if `seal-use` is not installed, first run `curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash`):\n\n```bash\nseal-use version\nseal-use corps list\n```\n\n- If `seal-use` is not installed on the system, run the curl install script above to install it.\n- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.\n- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.\n- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”\n\nDo not open with a JSON template or a list of internal fields.\n\nAll command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.\n\n## Keep Two Concepts Separate\n\nClassify both the enterprise identity origin and how the current credential was acquired:\n\n| Enterprise identity origin | Credential material the user may have | Meaning |\n| --- | --- | --- |\n| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |\n| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |\n| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |\n| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |\n| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |\n\nCredential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.\n\n## Parameter Ownership\n\nAsk the user only for information that cannot be discovered safely:\n\n| Field | Owner and behavior |\n| --- | --- |\n| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |\n| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |\n| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |\n| Administrator and `staffId` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |\n| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |\n| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |\n\n## Route 1: Standard Hose Credentials\n\nThis is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:\n\n```bash\nseal-use corps add-hose --json '{\"appKey\":\"...\",\"appSecurity\":\"...\"}'\n```\n\nThe CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:\n\n```bash\nseal-use auth diagnose --corp <discovered-id>\n```\n\nDo not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.\n\n## Route 2: Incoming Assistance Link\n\nFirst distinguish the link by its host and purpose:\n\n- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.\n- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.\n- `seal-use auth hose-link` and `seal-use delegation create` generate Line truncated
`;var bN="# Enterprise Onboarding\n\nRead this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.\n\n## Start With Discovery\n\nRun this before asking for setup parameters (if `seal-use` is not installed, first run `curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash`):\n\n```bash\nseal-use version\nseal-use corps list\n```\n\n- If `seal-use` is not installed on the system, run the curl install script above to install it.\n- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.\n- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.\n- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”\n\nDo not open with a JSON template or a list of internal fields.\n\nAll command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.\n\n## Keep Two Concepts Separate\n\nClassify both the enterprise identity origin and how the current credential was acquired:\n\n| Enterprise identity origin | Credential material the user may have | Meaning |\n| --- | --- | --- |\n| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |\n| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |\n| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |\n| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |\n| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |\n\nCredential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.\n\n## Parameter Ownership\n\nAsk the user only for information that cannot be discovered safely:\n\n| Field | Owner and behavior |\n| --- | --- |\n| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |\n| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |\n| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |\n| Administrator and `staffId` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |\n| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |\n| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |\n\n## Route 1: Standard Hose Credentials\n\nThis is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:\n\n```bash\nseal-use corps add-hose --json '{\"appKey\":\"...\",\"appSecurity\":\"...\"}'\n```\n\nThe CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:\n\n```bash\nseal-use auth diagnose --corp <discovered-id>\n```\n\nDo not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.\n\n## Route 2: Incoming Assistance Link\n\nFirst distinguish the link by its host and purpose:\n\n- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.\n- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.\n- `seal-use auth hose-link` and `seal-use delegation create` generate Line truncated
Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links.
@@ -957,7 +967,7 @@ Important:
- \`seal-use auth diagnose\` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
- **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 oy=`# Hose Enterprise Initialization & Automated Discovery
`;var wN=`# 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.
@@ -1063,12 +1073,12 @@ seal-use corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var ly={"SKILL.md":RL,"agents/openai.yaml":hL,"references/rule-lightweight.md":mL,"references/approval-bad-cases.md":xL,"references/cli.md":aL,"references/approval-run-lightweight.md":sL,"references/approval-attachment-trace.md":ny,"references/customer-feedback-rule-remediation.md":iy,"references/enterprise-onboarding.md":ty,"references/hose-enterprise-auth.md":ry,"references/hose-enterprise-init.md":oy};function vy(){return ly["SKILL.md"]||""}function zu(){return C4(ey(),".agents","skills","seal-use")}function $y(){return C4(ey(),".agents","skills","seal-home")}function Iy(){let n=$y();if(z4(n))try{return XK(n,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function R4(n=zu()){Iy(),uy(n,{recursive:!0});let i=[];for(let[r,o]of Object.entries(ly)){let t=C4(n,r);uy(YK(t),{recursive:!0}),HK(t,o,"utf8"),i.push(r)}return{targetDir:n,files:i}}function h4(){let n=$y(),i=zu(),r=z4(n),o=z4(i);if(r||o)return Iy(),R4(i),{synced:!0,targetDir:i};return{synced:!1}}function by(n,i,r){if(n==="dump"||n==="cat"||n==="show"){process.stdout.write(`${vy()}
`);return}if(n==="install"||n==="init"||n==="sync"){let o=_(r.options.local)||_(r.options.workspace),t=D(r.options.dir)??D(r.options.target)??i,u=t?t:o?w$(process.cwd(),".agents","skills","seal-use"):zu(),e=R4(u);B({installed:!0,targetDir:e.targetDir,fileCount:e.files.length,files:e.files});return}if(n==="status"||n==="get"||!n){let o=zu(),t=w$(process.cwd(),".agents","skills","seal-use");B({global:{dir:o,installed:gy(w$(o,"SKILL.md"))},local:{dir:t,installed:gy(w$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${n}. Run 'seal-use help' for available commands.`)}async function wy(n,i){if(n==="config"){B(await ar(i));return}throw Error(`Unknown source command: ${n??""}. Run 'seal-use help' for available commands.`)}async function fy(n,i,r,o){if(!n)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await X(n,i,r,ri(o.json),J(o.options))}function cy(){B(Tu.map((n)=>({name:n.name,description:n.description})))}import{chmodSync as pK,mkdirSync as QK,renameSync as m4,rmSync as PK,unlinkSync as Oy,writeFileSync as Uy}from"node:fs";import{dirname as FK,join as Dy}from"node:path";import{spawnSync as Zt}from"node:child_process";function f$(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")&&!r.endsWith("/node")&&!r.endsWith("/node.exe")}var dy="yunyingk/seal-use",Ru="yunyingk/seal-home";var KK="SEAL_USE_GITHUB_REPO",BK="SEAL_HOME_GITHUB_REPO";async function ky(n,i={}){let r={appRoot:n.appRoot,entryFile:n.entryFile,stateDir:M4,version:x,launcher:n.launcher},o=i.repo||process.env[KK]?.trim()||process.env[BK]?.trim()||dy,t=i.targetVersion?.trim(),u=t&&t.toLowerCase()!=="latest"?t:void 0;if(u){let W=u.replace(/^v/,""),N=Ny(W,x);if(N<0){B({updated:!1,currentVersion:x,targetVersion:W,mode:f$()?"binary":"source",message:`Cannot downgrade seal-use from v${x} to older version v${W}. Updates must be forward-only.`});return}if(N===0&&!i.force){B({updated:!1,currentVersion:x,targetVersion:W,mode:f$()?"binary":"source",message:`seal-use is already at version v${x}. Use --force to reinstall.`});return}}if(i.changelogOnly){let W=await x4(o,i.limit??10);B({currentVersion:x,totalQueried:W.length,releases:W.map((N)=>({version:N.version,tagName:N.tagName,publishedAt:N.publishedAt,author:N.author,releaseNotes:N.notes,releaseUrl:N.htmlUrl,isCurrent:N.version===x,isNewer:Cu(N.version,x)}))});return}if(!f$()){if(i.checkOnly){let N=await x4(o,30),M=N[0],q=M?.version??x,An=N.find((nn)=>nn.version===x),Wn=Cu(q,x),jn=N.filter((nn)=>Cu(nn.version,x));B({updated:!1,updateAvailable:Wn,currentVersion:x,currentVersionPublishedAt:An?.publishedAt,latestVersion:q,latestVersionPublishedAt:M?.publishedAt,behindCount:jn.length,pendingReleases:jn.map((nn)=>({version:nn.version,tagName:nn.tagName,publishedAt:nn.publishedAt,author:nn.author,releaseNotes:nn.notes,releaseUrl:nn.htmlUrl})),releaseNotes:M?.notes??"",releaseUrl:M?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let W=sr(r).running;if(W)await _t("stop",r);try{Ay("git",["-C",n.appRoot,"pull","--ff-only"])}catch(N){console.error(`git pull skipped: ${N instanceof Error?N.message:String(N)}`)}if(Ay("bun",["install"],{cwd:n.appRoot}),W)await _t("start",r);B({updated:!0,serviceRestarted:W,version:x,mode:"source"});return}let e=EK(),l=TK(),$=await x4(o,30),I=u?$.find((W)=>W.version===u||W.tagName===u||W.tagName===`v${u}`)??await Sy(o,u):$[0]??await Sy(o);if(!I){B({updated:!1,currentVersion:x,mode:"binary",message:`Failed to query releases from repository '${o}'`});return}let g=I.version,b=$.find((W)=>W.version===x),w=Cu(g,x),f=w||Boolean(i.force),c=$.filter((W)=>Cu(W.version,x));if(i.checkOnly){B({updated:!1,updateAvailable:w,currentVersion:x,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:c.length,pendingReleases:c.map((W)=>({version:W.version,tagName:W.tagName,publishedAt:W.publishedAt,author:W.author,releaseNotes:W.notes,releaseUrl:W.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!f){B({updated:!1,currentVersion:x,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-use is already up to date (v${x})`});return}let S=VK(I.assets,e,l);if(!S)throw Error(`No compatible binary found for ${e}-${l} in release v${g}. Available assets: ${I.assets.map((W)=>W.name).join(", ")}`);let d=sr(r).running;if(d)await _t("stop",r);let k=process.execPath,P=FK(k),Q=Dy(P,`.tmp-update-${Date.now()}`);QK(Q,{recursive:!0});try{let W=Dy(Q,S.name);await qK(S.downloadUrl,W,I.tagName,S.name);let N=W;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))N=_K(W,Q,e);else if(S.name.endsWith(".zip"))N=ZK(W,Q,e);if(pK(N,493),process.platform==="darwin")try{Zt("/usr/bin/codesign",["--remove-signature",N],{stdio:"ignore"}),Zt("/usr/ Line truncated
`)}catch{}}async function qK(n,i,r,o){let t=a4(),u=[],e=r?r.startsWith("v")?r:`v${r}`:void 0,l=o||n.split("/").pop()||"";if(t!=="github"){if(e&&l)u.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${e}/${l}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${e}/${l}`);if(n.startsWith("https://git.ying-qing.cn"))u.push(n)}if(t!=="gitea")if(e&&l){let S=`https://github.com/${dy}/releases/download/${e}/${l}`;if(!process.env.CI)u.push(`https://ghfast.top/${S}`,`https://gh.ddlc.top/${S}`);u.push(S)}else if(n.includes("github.com")){if(!process.env.CI)u.push(`https://ghfast.top/${n}`,`https://gh.ddlc.top/${n}`);u.push(n)}else u.push(n);let $=Array.from(new Set(u)),I,g=6000,b=6000,w=307200,f=1e4,c=180000;for(let S=0;S<$.length;S++){let d=$[S],k=new AbortController,P="",Q=(q)=>{P=q;try{k.abort()}catch{}},W=setTimeout(()=>{Q("Connection timed out (no response headers within 6s)")},g),N,M;try{c$(`==> [${S+1}/${$.length}] Downloading via: ${d}`);let q=await fetch(d,{signal:k.signal});if(W)clearTimeout(W),W=void 0;if(!q.ok)throw Error(`HTTP ${q.status} ${q.statusText}`);N=setTimeout(()=>{Q("Overall download time exceeded 3 minutes")},c);let An=Number(q.headers.get("content-length"))||0,Wn=q.body?.getReader();if(!Wn){let Ni=Buffer.from(await q.arrayBuffer());if(Ni.length<1000)throw Error(`Downloaded content is suspiciously small (${Ni.length} bytes)`);Uy(i,Ni),c$(`✓ Download succeeded (${(Ni.length/1024/1024).toFixed(1)} MB)`);return}let jn=[],nn=0,no=0;M=setTimeout(()=>{if(nn<w){let Ni=(nn/1024).toFixed(1);Q(`Initial transfer too slow (${Ni} KB < 300 KB in 6s), switching mirror...`)}},b);while(!0){let Ni=Wn.read(),U$,Xy=new Promise((S$,A$)=>{U$=setTimeout(()=>{A$(Error("Data transfer stalled (no chunk received for 10s)"))},f)}),i0;try{i0=await Promise.race([Ni,Xy])}finally{if(U$)clearTimeout(U$)}let{done:Hy,value:D$}=i0;if(Hy)break;if(D$){if(jn.push(D$),nn+=D$.length,M&&nn>=w)clearTimeout(M),M=void 0;let S$=Date.now();if(S$-no>200){no=S$;let A$=An?Math.round(nn/An*100):0,Yy=(nn/1048576).toFixed(1),py=An?(An/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${A$}% (${Yy} / ${py} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let Ot=Buffer.concat(jn);if(Ot.length<1000)throw Error(`Downloaded content is suspiciously small (${Ot.length} bytes)`);Uy(i,Ot),c$(`✓ Download completed successfully (${(Ot.length/1024/1024).toFixed(1)} MB)`);return}catch(q){if(W)clearTimeout(W);if(M)clearTimeout(M);if(N)clearTimeout(N);let An=P||(q instanceof Error?q.message:String(q));I=Error(An),c$(`
↳ Mirror failed: ${I.message}`)}finally{if(W)clearTimeout(W);if(M)clearTimeout(M);if(N)clearTimeout(N)}}throw Error(`Failed to download asset from all mirrors: ${I?.message}`)}function _K(n,i,r){let o=Zt("tar",["-xzf",n,"-C",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract tar archive: ${o.stderr.toString()}`);Oy(n);let t=r==="windows"?"seal-use.exe":"seal-use",u=Zt("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 ZK(n,i,r){let o=Zt("unzip",["-q","-o",n,"-d",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract zip archive: ${o.stderr.toString()}`);Oy(n);let t=r==="windows"?"seal-use.exe":"seal-use",u=Zt("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 Ny(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 Cu(n,i){return Ny(n,i)>0}function Ay(n,i,r={}){let o=Zt(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 Ly(n,i,r,o,t){if(n==="create"){let u=D(t.options.name)??i,e=D(t.options.phone);if(!u||!e)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let l=D(t.options.dept)??D(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??D(t.options.userId);if(!u)throw Error("Usage: seal-use 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??D(t.options.keyword)??D(t.options.query)??"";await X("seal_user_search",r,o,{keyword:u},J(t.options));return}if(n==="get"){let u=i??D(t.options.userId);if(!u)throw Error("Usage: seal-use users get <userId>");await X("seal_user_get",r,o,{userId:u},J(t.options));return}if(n==="delete"){let u=i??D(t.options.userId);if(!u)throw Error("Usage: seal-use users delete <userId>");await X("seal_user_delete",r,o,{userId:u},J(t.options));return}if(n==="activate"){let u=i??D(t.options.userId);if(!u)throw Error("Usage: seal-use users activate <userId>");await X("seal_user_activate",r,o,{userId:u},J(t.options));return}if(n==="delegation"||n==="impersonate"){let u=i??D(t.options.userId)??D(t.options.phone);if(!u)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let e=D(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-use help' for available commands.`)}async function yy(n,i,r,o,t){if(n==="list"){await X("seal_webhook_list",r,o,{query:D(t.options.query)??D(t.options.keyword),includeSecret:K4(t.options)},J(t.options));return}if(n==="get"||n==="find"){let u=i??D(t.options.selector)??D(t.options.id);if(!u)throw Error("Usage: seal-use webhook get <idOrName> [--show-secret]");await X("seal_webhook_get",r,o,{selector:u,includeSecret:K4(t.options)},J(t.options));return}if(n==="add"||n==="create"){let u=D(t.options.name)??i,e=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]);if(!u||!e)throw Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let l=F4(t.options);await X("seal_webhook_add",r,o,{name:u,mode:P4(D(t.options.mode)),outgoingResultWebhook:e,autoApprovalRate:l,secret:D(t.options.secret)},J(t.options));return}if(n==="update"){let u=i??D(t.options.selector)??D(t.options.id);if(!u)throw Error("Usage: seal-use webhook update <idOrName> [options]");let e=D(t.options.secret),l=_(t.options.rotateSecret)??_(t.options["rotate-secret"]);if(e!==void 0&&l)throw Error("Use either --secret or --rotate-secret, not both");let $=D(t.options.name),I=P4(D(t.options.mode)),g=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]),b=F4(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??D(t.options.selector)??D(t.options.id);if(!u)throw Error("Usage: seal-use webhook delete <idOrName> --yes");if(_(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-use help' for available commands.`)}var Gy=s4(s4(s4(zK(import.meta.url)))),CK=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"]),Wy=Promise.resolve();function Mu(n,i={}){let r=Wy.then(()=>RK(n,i));return Wy=r.then(()=>{return},()=>{return}),r}async function RK(n,i){let r=[],o=[],t=console.log,u=console.error,e={appRoot:i.appRoot??Gy,entryFile:i.entryFile??MK(i.appRoot??Gy,"src","cli.ts"),launcher:i.launcher};console.log=(...l)=>{r.push(B4(l))},c Line truncated
`;var DN={"SKILL.md":oN,"agents/openai.yaml":uN,"references/rule-lightweight.md":eN,"references/approval-bad-cases.md":lN,"references/cli.md":vN,"references/approval-run-lightweight.md":$N,"references/approval-attachment-trace.md":IN,"references/customer-feedback-rule-remediation.md":gN,"references/enterprise-onboarding.md":bN,"references/hose-enterprise-auth.md":fN,"references/hose-enterprise-init.md":wN};function SN(){return DN["SKILL.md"]||""}function mu(){return n4(UN(),".agents","skills","seal-use")}function AN(){return n4(UN(),".agents","skills","seal-home")}function dN(){let n=AN();if(s0(n))try{return hP(n,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function i4(n=mu()){dN(),cN(n,{recursive:!0});let i=[];for(let[r,o]of Object.entries(DN)){let t=n4(n,r);cN(xP(t),{recursive:!0}),mP(t,o,"utf8"),i.push(r)}return{targetDir:n,files:i}}function t4(){let n=AN(),i=mu(),r=s0(n),o=s0(i);if(r||o)return dN(),i4(i),{synced:!0,targetDir:i};return{synced:!1}}function ON(n,i,r){if(n==="dump"||n==="cat"||n==="show"){process.stdout.write(`${SN()}
`);return}if(n==="install"||n==="init"||n==="sync"){let o=E(r.options.local)||E(r.options.workspace),t=U(r.options.dir)??U(r.options.target)??i,u=t?t:o?c$(process.cwd(),".agents","skills","seal-use"):mu(),e=i4(u);B({installed:!0,targetDir:e.targetDir,fileCount:e.files.length,files:e.files});return}if(n==="status"||n==="get"||!n){let o=mu(),t=c$(process.cwd(),".agents","skills","seal-use");B({global:{dir:o,installed:kN(c$(o,"SKILL.md"))},local:{dir:t,installed:kN(c$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${n}. Run 'seal-use help' for available commands.`)}async function yN(n,i){if(n==="config"){B(await io(i));return}throw Error(`Unknown source command: ${n??""}. Run 'seal-use help' for available commands.`)}async function LN(n,i,r,o){if(!n)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await J(n,i,r,oi(o.json),j(o.options))}function NN(){B(qu.map((n)=>({name:n.name,description:n.description})))}import{chmodSync as aP,mkdirSync as sP,renameSync as r4,rmSync as nB,unlinkSync as JN,writeFileSync as GN}from"node:fs";import{dirname as iB,join as WN}from"node:path";import{spawnSync as zt}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")&&!r.endsWith("/node")&&!r.endsWith("/node.exe")}var XN="yunyingk/seal-use",au="yunyingk/seal-home";var tB="SEAL_USE_GITHUB_REPO",rB="SEAL_HOME_GITHUB_REPO";async function HN(n,i={}){let r={appRoot:n.appRoot,entryFile:n.entryFile,stateDir:a0,version:x,launcher:n.launcher},o=i.repo||process.env[tB]?.trim()||process.env[rB]?.trim()||XN,t=i.targetVersion?.trim(),u=t&&t.toLowerCase()!=="latest"?t:void 0;if(u){let W=u.replace(/^v/,""),y=YN(W,x);if(y<0){B({updated:!1,currentVersion:x,targetVersion:W,mode:U$()?"binary":"source",message:`Cannot downgrade seal-use from v${x} to older version v${W}. Updates must be forward-only.`});return}if(y===0&&!i.force){B({updated:!1,currentVersion:x,targetVersion:W,mode:U$()?"binary":"source",message:`seal-use is already at version v${x}. Use --force to reinstall.`});return}}if(i.changelogOnly){let W=await o4(o,i.limit??10);B({currentVersion:x,totalQueried:W.length,releases:W.map((y)=>({version:y.version,tagName:y.tagName,publishedAt:y.publishedAt,author:y.author,releaseNotes:y.notes,releaseUrl:y.htmlUrl,isCurrent:y.version===x,isNewer:xu(y.version,x)}))});return}if(!U$()){if(i.checkOnly){let y=await o4(o,30),M=y[0],q=M?.version??x,An=y.find((nn)=>nn.version===x),Wn=xu(q,x),pn=y.filter((nn)=>xu(nn.version,x));B({updated:!1,updateAvailable:Wn,currentVersion:x,currentVersionPublishedAt:An?.publishedAt,latestVersion:q,latestVersionPublishedAt:M?.publishedAt,behindCount:pn.length,pendingReleases:pn.map((nn)=>({version:nn.version,tagName:nn.tagName,publishedAt:nn.publishedAt,author:nn.author,releaseNotes:nn.notes,releaseUrl:nn.htmlUrl})),releaseNotes:M?.notes??"",releaseUrl:M?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let W=to(r).running;if(W)await Mt("stop",r);try{jN("git",["-C",n.appRoot,"pull","--ff-only"])}catch(y){console.error(`git pull skipped: ${y instanceof Error?y.message:String(y)}`)}if(jN("bun",["install"],{cwd:n.appRoot}),W)await Mt("start",r);B({updated:!0,serviceRestarted:W,version:x,mode:"source"});return}let e=oB(),l=uB(),$=await o4(o,30),I=u?$.find((W)=>W.version===u||W.tagName===u||W.tagName===`v${u}`)??await pN(o,u):$[0]??await pN(o);if(!I){B({updated:!1,currentVersion:x,mode:"binary",message:`Failed to query releases from repository '${o}'`});return}let g=I.version,b=$.find((W)=>W.version===x),f=xu(g,x),w=f||Boolean(i.force),c=$.filter((W)=>xu(W.version,x));if(i.checkOnly){B({updated:!1,updateAvailable:f,currentVersion:x,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:c.length,pendingReleases:c.map((W)=>({version:W.version,tagName:W.tagName,publishedAt:W.publishedAt,author:W.author,releaseNotes:W.notes,releaseUrl:W.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!w){B({updated:!1,currentVersion:x,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-use is already up to date (v${x})`});return}let S=eB(I.assets,e,l);if(!S)throw Error(`No compatible binary found for ${e}-${l} in release v${g}. Available assets: ${I.assets.map((W)=>W.name).join(", ")}`);let k=to(r).running;if(k)await Mt("stop",r);let O=process.execPath,F=iB(O),Q=WN(F,`.tmp-update-${Date.now()}`);sP(Q,{recursive:!0});try{let W=WN(Q,S.name);await lB(S.downloadUrl,W,I.tagName,S.name);let y=W;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))y=vB(W,Q,e);else if(S.name.endsWith(".zip"))y=$B(W,Q,e);if(aP(y,493),process.platform==="darwin")try{zt("/usr/bin/codesign",["--remove-signature",y],{stdio:"ignore"}),zt("/usr/ Line truncated
`)}catch{}}async function lB(n,i,r,o){let t=u4(),u=[],e=r?r.startsWith("v")?r:`v${r}`:void 0,l=o||n.split("/").pop()||"";if(t!=="github"){if(e&&l)u.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${e}/${l}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${e}/${l}`);if(n.startsWith("https://git.ying-qing.cn"))u.push(n)}if(t!=="gitea")if(e&&l){let S=`https://github.com/${XN}/releases/download/${e}/${l}`;if(!process.env.CI)u.push(`https://ghfast.top/${S}`,`https://gh.ddlc.top/${S}`);u.push(S)}else if(n.includes("github.com")){if(!process.env.CI)u.push(`https://ghfast.top/${n}`,`https://gh.ddlc.top/${n}`);u.push(n)}else u.push(n);let $=Array.from(new Set(u)),I,g=6000,b=6000,f=307200,w=1e4,c=180000;for(let S=0;S<$.length;S++){let k=$[S],O=new AbortController,F="",Q=(q)=>{F=q;try{O.abort()}catch{}},W=setTimeout(()=>{Q("Connection timed out (no response headers within 6s)")},g),y,M;try{D$(`==> [${S+1}/${$.length}] Downloading via: ${k}`);let q=await fetch(k,{signal:O.signal});if(W)clearTimeout(W),W=void 0;if(!q.ok)throw Error(`HTTP ${q.status} ${q.statusText}`);y=setTimeout(()=>{Q("Overall download time exceeded 3 minutes")},c);let An=Number(q.headers.get("content-length"))||0,Wn=q.body?.getReader();if(!Wn){let yi=Buffer.from(await q.arrayBuffer());if(yi.length<1000)throw Error(`Downloaded content is suspiciously small (${yi.length} bytes)`);GN(i,yi),D$(`✓ Download succeeded (${(yi.length/1024/1024).toFixed(1)} MB)`);return}let pn=[],nn=0,ro=0;M=setTimeout(()=>{if(nn<f){let yi=(nn/1024).toFixed(1);Q(`Initial transfer too slow (${yi} KB < 300 KB in 6s), switching mirror...`)}},b);while(!0){let yi=Wn.read(),S$,TN=new Promise((d$,k$)=>{S$=setTimeout(()=>{k$(Error("Data transfer stalled (no chunk received for 10s)"))},w)}),v4;try{v4=await Promise.race([yi,TN])}finally{if(S$)clearTimeout(S$)}let{done:VN,value:A$}=v4;if(VN)break;if(A$){if(pn.push(A$),nn+=A$.length,M&&nn>=f)clearTimeout(M),M=void 0;let d$=Date.now();if(d$-ro>200){ro=d$;let k$=An?Math.round(nn/An*100):0,_N=(nn/1048576).toFixed(1),qN=An?(An/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${k$}% (${_N} / ${qN} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let yt=Buffer.concat(pn);if(yt.length<1000)throw Error(`Downloaded content is suspiciously small (${yt.length} bytes)`);GN(i,yt),D$(`✓ Download completed successfully (${(yt.length/1024/1024).toFixed(1)} MB)`);return}catch(q){if(W)clearTimeout(W);if(M)clearTimeout(M);if(y)clearTimeout(y);let An=F||(q instanceof Error?q.message:String(q));I=Error(An),D$(`
↳ Mirror failed: ${I.message}`)}finally{if(W)clearTimeout(W);if(M)clearTimeout(M);if(y)clearTimeout(y)}}throw Error(`Failed to download asset from all mirrors: ${I?.message}`)}function vB(n,i,r){let o=zt("tar",["-xzf",n,"-C",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract tar archive: ${o.stderr.toString()}`);JN(n);let t=r==="windows"?"seal-use.exe":"seal-use",u=zt("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 $B(n,i,r){let o=zt("unzip",["-q","-o",n,"-d",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract zip archive: ${o.stderr.toString()}`);JN(n);let t=r==="windows"?"seal-use.exe":"seal-use",u=zt("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 YN(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 xu(n,i){return YN(n,i)>0}function jN(n,i,r={}){let o=zt(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 QN(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-use users create --name <name> --phone <phone> [--dept <deptId>]");let l=U(t.options.dept)??U(t.options.departmentId);await J("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-use users reset-password <userId>");await J("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 J("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-use users get <userId>");await J("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-use users delete <userId>");await J("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-use users activate <userId>");await J("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-use users delegation <userIdOrPhone> [--note <note>]");let e=U(t.options.note);await J("seal_user_delegation_create",r,o,{userIdOrPhone:u,note:e},j(t.options));return}throw Error(`Unknown users command: ${n??""}. Run 'seal-use help' for available commands.`)}async function FN(n,i,r,o,t){if(n==="list"){await J("seal_webhook_list",r,o,{query:U(t.options.query)??U(t.options.keyword),includeSecret:Z0(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-use webhook get <idOrName> [--show-secret]");await J("seal_webhook_get",r,o,{selector:u,includeSecret:Z0(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-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let l=q0(t.options);await J("seal_webhook_add",r,o,{name:u,mode:_0(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-use webhook update <idOrName> [options]");let e=U(t.options.secret),l=E(t.options.rotateSecret)??E(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=_0(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=q0(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 J("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-use webhook delete <idOrName> --yes");if(E(t.options.yes)!==!0)throw Error("Refusing to delete Webhook integration without --yes");await J("seal_webhook_delete",r,o,{selector:u,confirm:!0},j(t.options));return}throw Error(`Unknown webhook command: ${n??""}. Run 'seal-use help' for available commands.`)}var KN=e4(e4(e4(gB(import.meta.url)))),bB=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"]),PN=Promise.resolve();function hu(n,i={}){let r=PN.then(()=>fB(n,i));return PN=r.then(()=>{return},()=>{return}),r}async function fB(n,i){let r=[],o=[],t=console.log,u=console.error,e={appRoot:i.appRoot??KN,entryFile:i.entryFile??IB(i.appRoot??KN,"src","cli.ts"),launcher:i.launcher};console.log=(...l)=>{r.push(M0(l))},c Line truncated
`)?"":`
`}`);process.exitCode=n.exitCode}var o3=Boolean(r0.main==r0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&jy(process.argv[1])===jy(Ri));if(o3)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await r3();else q4().catch((n)=>{console.error(n),process.exitCode=1});export{T4 as tokenizeCommand,q4 as startServer,n3 as resolveMcpEnabled,i3 as createServer,aK as SEAL_MCP_ENABLED_ENV,xK as SEAL_CLI_TOOL_NAME,sK as LEGACY_SEAL_MCP_ENABLED_ENV};
`}`);process.exitCode=n.exitCode}var yB=Boolean(I4.main==I4.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&BN(process.argv[1])===BN(Ri));if(yB)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await OB();else h0().catch((n)=>{console.error(n),process.exitCode=1});export{C0 as tokenizeCommand,h0 as startServer,AB as resolveMcpEnabled,dB as createServer,DB as SEAL_MCP_ENABLED_ENV,UB as SEAL_CLI_TOOL_NAME,SB as LEGACY_SEAL_MCP_ENABLED_ENV};
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "seal-use Wrapped API",
"version": "0.10.3",
"version": "0.10.5",
"description": "Planned HTTP contract for the seal-use wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-use is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: seal-use Wrapped API
version: 0.10.3
version: 0.10.5
description: |
Planned HTTP contract for the seal-use wrapped backend API.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.3",
"version": "0.10.5",
"type": "module",
"module": "src/server.ts",
"bin": {
+7 -4
View File
@@ -1,12 +1,12 @@
---
name: seal-use
description: "v0.10.3: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.10.5: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.10.3
short-description: Seal tenant and Hose approval automation (v0.10.3)
version: 0.10.5
short-description: Seal tenant and Hose approval automation (v0.10.5)
---
# Seal Use (v0.10.3)
# Seal Use (v0.10.5)
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-use` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -67,6 +67,7 @@ seal-use corps list
- Billing & Feature Quotas: `seal-use billing status --corp <corpId>`, `seal-use billing plans --corp <corpId>`, `seal-use billing features --corp <corpId>`.
- Webhook 审批回调管理: `seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
- HTTP REST API & Docs Server: `seal-use http [--port 8787] [--host 127.0.0.1]` (提供 `/docs` 交互文档、`/openapi.json`、`POST /api/cli` 与 `/v1/*` REST API)。
- 审批规则质量校验 (Linter): `seal-use rules lint [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary] --corp <corpId>`; read `references/rule-lint.md`. 全局配置默认关闭 (`config lint <enable|disable>`)。
- Full CLI inventory: read `references/cli.md`.
## High-Value Commands
@@ -82,6 +83,7 @@ seal-use approval-runs attachments <recordId> --corp <corpId> --summary
seal-use approval-runs result <recordId> --corp <corpId> --summary
seal-use rules count --corp <corpId>
seal-use rules list --corp <corpId> --summary
seal-use rules lint --corp <corpId> --summary
seal-use rules clear --corp <corpId> --dry-run
seal-use rules clear --corp <corpId> --yes
seal-use rules get --corp <corpId> --version 16 --code '#0038'
@@ -112,6 +114,7 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
- `references/enterprise-onboarding.md`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- `references/approval-run-lightweight.md`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- `references/rule-lightweight.md`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- `references/rule-lint.md`: 规则质量检查器(Linter)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
- `references/customer-feedback-rule-remediation.md`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- `references/hose-enterprise-auth.md`: Hose 企业配置、认证诊断、授权链接。
- `references/hose-enterprise-init.md`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
+6 -2
View File
@@ -37,6 +37,8 @@ seal-use version
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]
seal-use rules lint [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]
seal-use service <start|stop|restart|status>
seal-use http [--port 8787] [--host 127.0.0.1]
seal-use serve [--port 8787]
@@ -71,10 +73,10 @@ seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
seal-use deploy hosecloud get [<sign-key>] [--corp <corpId>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]
seal-use preference get [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]
@@ -133,8 +135,10 @@ Approval rule maintenance:
- `seal-use rules count [--corp <corpId>]`
- `seal-use rules list --summary [--corp <corpId>]`
- `seal-use rules lint [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]`
- `seal-use rules clear [--corp <corpId>] [--dry-run|--yes]`
- `seal_approval_rules_list`
- `seal_approval_rules_lint`
- `seal_approval_rules_clear`
- `seal_approval_rule_create`
- `seal_approval_rule_update`
@@ -69,8 +69,12 @@ seal-use deploy hosecloud configure --corp <corpId> --json '{
# 5. 一键同步发布到合思审批流
seal-use deploy hosecloud sync <signKey> --corp <corpId>
# 6. 查看单项配置详情
seal-use deploy hosecloud get <signKey> --corp <corpId>
# 5.1 单配置企业一键自动同步 (--auto)
# 若企业内仅存在 1 个合思配置卡片,可直接传入 --auto 自动锁定执行,免去查询复制 signKey:
seal-use deploy hosecloud sync --auto --corp <corpId>
# 6. 查看单项配置详情(未传 signKey 时自动列出当前企业候选列表与查看命令)
seal-use deploy hosecloud get [<signKey>] --corp <corpId>
# 7. 检查发布与多平台集成状态
seal-use deploy hosecloud status --corp <corpId>
+90
View File
@@ -0,0 +1,90 @@
# Seal Approval Rule Linter & Quality Validation
Use this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.
## Key Principles
- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled: false`) to avoid unsolicited noise during standard operations.
- **Explicit Triggering**: `seal-use rules lint` always runs regardless of global configuration.
- **Draft Hook**: When `seal-use config lint enable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.
- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.
## CLI Commands
### 1. Lint Current Draft Rules (Whole-RuleSet Scan)
```bash
seal-use rules lint --corp <corpId>
```
### 2. Lint Specific Historical Version or Single Rule
```bash
# Lint rules in published version 16
seal-use rules lint --version 16 --corp <corpId>
# Lint a specific rule by code (#0038)
seal-use rules lint --code '#0038' --corp <corpId>
# Summary mode (only show rules with issues)
seal-use rules lint --summary --corp <corpId>
```
### 3. Quality Gate for CI / Release
```bash
# If overall score is below 85, terminates with exit code 1
seal-use rules lint --min-score 85 --level error --corp <corpId>
```
### 4. Configure Global Linter Settings
```bash
# Check status
seal-use config lint status
# Enable auto lint on rule updates
seal-use config lint enable --linter builtin --min-score 80
# Disable auto lint
seal-use config lint disable
```
## Built-In Detection Rules
| Code | Level | Description | Recommendation |
| :--- | :---: | :--- | :--- |
| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |
| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |
| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |
## Custom TS Linters (Plugin-as-Code)
Place custom TypeScript linter functions in `~/.config/seal-use/linters/<name>.ts` or `./linters/<name>.ts`:
```typescript
// ~/.config/seal-use/linters/finance-strict.ts
export default function customLinter(rule: { description: string }) {
const issues = [];
if (rule.description.includes("商务舱") && !rule.description.includes("副总裁")) {
issues.push({
level: "error",
code: "FLIGHT_CABIN_RESTRICTION",
snippet: "商务舱",
message: "乘坐商务舱必须限定副总裁及以上级别",
suggestion: "补充限制: '仅副总裁及以上职级允许报销商务舱'"
});
}
return {
score: issues.length === 0 ? 100 : 60,
passed: issues.length === 0,
issues
};
}
```
Run with custom linter:
```bash
seal-use rules lint --linter finance-strict --corp <corpId>
```
+39 -1
View File
@@ -45,6 +45,7 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
: previousConfig.defaultCorpId
: undefined;
const config = saveGlobalConfig({
...previousConfig,
stateful,
...(defaultCorpId ? { defaultCorpId } : {})
});
@@ -52,5 +53,42 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
if (action === "lint") {
const subAction = maybeName ?? stringOption(args.options.state) ?? stringOption(args.options.enable);
const previousConfig = loadGlobalConfig();
const currentLint = previousConfig.lint ?? { enabled: false, activeLinter: "builtin", minScore: 0 };
if (!subAction || subAction === "status" || subAction === "get") {
printJson({ lint: currentLint, configFile: resolveGlobalConfigFile() });
return;
}
let enabled = currentLint.enabled;
if (subAction === "enable" || subAction === "on" || subAction === "true") {
enabled = true;
} else if (subAction === "disable" || subAction === "off" || subAction === "false") {
enabled = false;
}
const activeLinter = stringOption(args.options.linter) ?? currentLint.activeLinter;
const minScore = args.options.minScore !== undefined || args.options["min-score"] !== undefined
? Number(args.options.minScore ?? args.options["min-score"])
: currentLint.minScore;
const nextLint = {
enabled,
activeLinter,
minScore: isNaN(minScore) ? 0 : Math.max(0, Math.min(100, minScore))
};
const config = saveGlobalConfig({
...previousConfig,
lint: nextLint
});
printJson(globalConfigSummary(config));
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint. Run 'seal-use help' for available commands.`);
}
+60 -3
View File
@@ -2,9 +2,10 @@ import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { jsonObject, stringOption } from "../parser.js";
import { booleanOption, jsonObject, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import * as api from "../../domains/seal/api.js";
export async function handleDeployCommand(
systemOrAction: string | undefined,
@@ -64,7 +65,26 @@ export async function handleDeployCommand(
if (action === "get") {
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
if (!signKey) throw new Error("Usage: seal-use deploy hosecloud get <sign-key>");
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
if (hoseConfigs.length === 0) {
throw new Error(
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
`👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${corp.id}`
);
}
console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${corp.id}]\n`);
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
for (const item of hoseConfigs) {
const name = (item as any).outboundName ?? "SealAI 审批";
const key = item.signKey;
const origin = (item as any).apiOrigin ?? "production";
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。");
}
await runTool("seal_deploy_hosecloud_get", client, corp, { signKey }, outputOptions(args.options));
return;
}
@@ -88,7 +108,44 @@ export async function handleDeployCommand(
if (action === "sync") {
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
if (!signKey) throw new Error("Usage: seal-use deploy hosecloud sync <sign-key>");
const autoOpt = booleanOption(args.options.auto) ?? booleanOption(args.options.yes);
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
if (hoseConfigs.length === 0) {
throw new Error(
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
`👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${corp.id}`
);
}
const firstHose = hoseConfigs[0];
if (firstHose && hoseConfigs.length === 1 && autoOpt) {
const singleKey = firstHose.signKey;
console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${singleKey})`);
await runTool("seal_deploy_hosecloud_sync", client, corp, { signKey: singleKey }, outputOptions(args.options));
return;
}
console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${corp.id}]\n`);
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
for (const item of hoseConfigs) {
const name = (item as any).outboundName ?? "SealAI 审批";
const key = item.signKey;
const origin = (item as any).apiOrigin ?? "production";
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 同步命令: seal-use deploy hosecloud sync ${key} --corp ${corp.id}\n`);
}
if (hoseConfigs.length === 1) {
console.error(`💡 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。");
}
await runTool("seal_deploy_hosecloud_sync", client, corp, { signKey }, outputOptions(args.options));
return;
}
+20 -1
View File
@@ -140,5 +140,24 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
if (action === "lint") {
await runTool(
"seal_approval_rules_lint",
client,
corp,
{
linter: stringOption(args.options.linter),
version: stringOption(args.options.version),
code: stringOption(args.options.code),
ruleId: stringOption(args.options.rule) ?? maybeName,
minScore: numberOption(args.options.minScore) ?? numberOption(args.options["min-score"]),
level: stringOption(args.options.level),
summary: booleanOption(args.options.summary)
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint. Run 'seal-use help' for available commands.`);
}
+1
View File
@@ -27,6 +27,7 @@ export function globalConfigSummary(config: GlobalConfig = loadGlobalConfig()) {
...(config.stateful && config.defaultCorpId
? { defaultCorpId: config.defaultCorpId }
: {}),
lint: config.lint,
configFile: resolveGlobalConfigFile()
};
}
+23 -3
View File
@@ -104,7 +104,14 @@ describe("loadCorpConfigs", () => {
test("defaults global config to stateless", () => {
process.env.SEAL_USE_CONFIG_FILE = join(makeTempDir(), "config.json");
expect(loadGlobalConfig()).toEqual({ stateful: false });
expect(loadGlobalConfig()).toEqual({
stateful: false,
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
test("saves and loads the global state mode", () => {
@@ -113,10 +120,23 @@ describe("loadCorpConfigs", () => {
expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a" })).toEqual({
stateful: true,
defaultCorpId: "corp-a"
defaultCorpId: "corp-a",
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
expect(resolveGlobalConfigFile()).toBe(file);
expect(loadGlobalConfig()).toEqual({ stateful: true, defaultCorpId: "corp-a" });
expect(loadGlobalConfig()).toEqual({
stateful: true,
defaultCorpId: "corp-a",
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
});
+2 -2
View File
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "enterprises";
const CONFIG_ENV = "SEAL_USE_ENTERPRISES_DIR";
@@ -101,7 +101,7 @@ export function loadGlobalConfig(): GlobalConfig {
return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
}
export function saveGlobalConfig(config: GlobalConfig): GlobalConfig {
export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig {
const normalized = GlobalConfigSchema.parse(config);
const configured = (process.env[GLOBAL_CONFIG_ENV] ?? process.env[LEGACY_GLOBAL_CONFIG_ENV])?.trim();
const file = configured || PRIMARY_GLOBAL_CONFIG_FILE;
+14 -2
View File
@@ -82,7 +82,14 @@ describe("CorpConfigSchema", () => {
describe("GlobalConfigSchema", () => {
test("defaults to stateless mode", () => {
expect(GlobalConfigSchema.parse({})).toEqual({ stateful: false });
expect(GlobalConfigSchema.parse({})).toEqual({
stateful: false,
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
test("accepts a stateful default enterprise", () => {
@@ -91,7 +98,12 @@ describe("GlobalConfigSchema", () => {
defaultCorpId: "corp-a"
})).toEqual({
stateful: true,
defaultCorpId: "corp-a"
defaultCorpId: "corp-a",
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
});
+14 -1
View File
@@ -84,9 +84,20 @@ export const CorpConfigSchema = z.object({
auth: CorpAuthConfigSchema
});
export const GlobalLintConfigSchema = z.object({
enabled: z.boolean().default(false),
activeLinter: z.string().default("builtin"),
minScore: z.number().min(0).max(100).default(0)
}).default({
enabled: false,
activeLinter: "builtin",
minScore: 0
});
export const GlobalConfigSchema = z.object({
stateful: z.boolean().default(false),
defaultCorpId: z.string().min(1).optional()
defaultCorpId: z.string().min(1).optional(),
lint: GlobalLintConfigSchema
});
export type HoseSealSource = z.infer<typeof HoseSealSourceSchema>;
@@ -95,4 +106,6 @@ export type NativeSealSource = z.infer<typeof NativeSealSourceSchema>;
export type SealSource = z.infer<typeof SealSourceSchema>;
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
export type GlobalLintConfig = z.infer<typeof GlobalLintConfigSchema>;
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
export type GlobalConfigInput = z.input<typeof GlobalConfigSchema>;
+89
View File
@@ -0,0 +1,89 @@
import type { RuleLintIssue, RuleLintResult, RuleLintTarget } from "./types.js";
export const BUILTIN_VAGUE_WORDS = [
"原则上",
"尽量",
"适当",
"酌情",
"一般情况下",
"尽可能",
"合理控制",
"视情况",
"视具体情况"
];
export const BUILTIN_EXCEPTION_TRIGGERS = [
"除非",
"特殊情况",
"特殊原因",
"经批准",
"经审批",
"经领导同意",
"除外",
"例外"
];
export const BUILTIN_EVIDENCE_KEYWORDS = [
"备注",
"说明",
"附件",
"证明",
"邮件",
"截图",
"凭证",
"审批",
"单据",
"发票"
];
export function builtinRuleLinter(rule: RuleLintTarget): RuleLintResult {
const text = (rule.description || "").trim();
const issues: RuleLintIssue[] = [];
// 1. 规则过短检查
if (text.length < 5) {
issues.push({
level: "error",
code: "TOO_SHORT",
message: "规则描述过于简短(少于 5 个字),大模型难以形成明确的判定逻辑",
suggestion: "请补充具体的费用类型、核验条件与限制标准"
});
}
// 2. 主观模糊词拦截
for (const word of BUILTIN_VAGUE_WORDS) {
if (text.includes(word)) {
issues.push({
level: "error",
code: "VAGUE_WORD",
snippet: word,
message: `包含主观模糊词 "${word}",容易导致大模型判定标准产生波动与幻觉`,
suggestion: `建议移除 "${word}",改为具体的金额上限、枚举范围或刚性判定条件`
});
}
}
// 3. 悬空例外条款检测
const matchedTrigger = BUILTIN_EXCEPTION_TRIGGERS.find((trigger) => text.includes(trigger));
const hasEvidence = BUILTIN_EVIDENCE_KEYWORDS.some((kw) => text.includes(kw));
if (matchedTrigger && !hasEvidence) {
issues.push({
level: "warning",
code: "HANGING_EXCEPTION",
snippet: matchedTrigger,
message: `包含例外条款 "${matchedTrigger}",但未指定 AI 从何处核验该例外成立的依据`,
suggestion: `建议补充明确的凭据来源(例如:"需在【单据备注】中说明原因" 或 "需在【附件】中上传审批截图")`
});
}
const errorCount = issues.filter((i) => i.level === "error").length;
const warningCount = issues.filter((i) => i.level === "warning").length;
const score = Math.max(0, 100 - errorCount * 25 - warningCount * 10);
return {
score,
passed: errorCount === 0,
issues
};
}
+4
View File
@@ -0,0 +1,4 @@
export * from "./types.js";
export * from "./builtin.js";
export * from "./loader.js";
export * from "./service.js";
+112
View File
@@ -0,0 +1,112 @@
import { describe, expect, test } from "bun:test";
import { builtinRuleLinter } from "./builtin.js";
import { loadRuleLinter } from "./loader.js";
import { lintRuleBatch, lintSingleRule } from "./service.js";
import { writeFileSync, unlinkSync, mkdirSync, existsSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
describe("Rule Linter", () => {
test("builtinRuleLinter detects short text, vague words, and hanging exceptions", () => {
// 1. 过短文本
const shortResult = builtinRuleLinter({ description: "测试" });
expect(shortResult.passed).toBe(false);
expect(shortResult.issues.some((i) => i.code === "TOO_SHORT")).toBe(true);
// 2. 主观模糊词
const vagueResult = builtinRuleLinter({
description: "原则上差旅住宿费尽量控制在500元以内"
});
expect(vagueResult.passed).toBe(false);
expect(vagueResult.issues.filter((i) => i.code === "VAGUE_WORD").length).toBe(2);
expect(vagueResult.score).toBeLessThanOrEqual(50);
// 3. 悬空例外条款(无证据说明)
const exceptionResult = builtinRuleLinter({
description: "差旅住宿费单日不得超过500元,特殊情况除外"
});
expect(exceptionResult.issues.some((i) => i.code === "HANGING_EXCEPTION")).toBe(true);
// 4. 完美高质量规则
const cleanResult = builtinRuleLinter({
description: "差旅住宿费每日不可超过500元。若因特殊情况超标,必须在【单据备注】中说明原因并在【附件】中提供总监审批邮件截图。"
});
expect(cleanResult.passed).toBe(true);
expect(cleanResult.score).toBe(100);
expect(cleanResult.issues.length).toBe(0);
});
test("loadRuleLinter returns builtin linter for default or non-existent files safely", async () => {
const builtinLoaded = await loadRuleLinter("builtin");
expect(builtinLoaded.type).toBe("builtin");
// 不存在的文件安全降级至 builtin,不抛错崩溃
const nonExistent = await loadRuleLinter("/tmp/non-existent-linter-xyz.ts");
expect(nonExistent.type).toBe("builtin");
const res = await nonExistent.linter({ description: "原则上不能超标" });
expect(res.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true);
});
test("loadRuleLinter safely executes custom TS/JS linter and catches runtime exceptions", async () => {
const testDir = join(tmpdir(), "seal-use-linter-test");
if (!existsSync(testDir)) mkdirSync(testDir, { recursive: true });
// 1. 有效的自定义校验器
const customTsPath = join(testDir, "custom-valid.ts");
writeFileSync(
customTsPath,
`export default function customLinter(rule) {
if (rule.description.includes("商务舱")) {
return { score: 40, passed: false, issues: [{ level: "error", code: "CUSTOM_FLIGHT", message: "禁止报销商务舱" }] };
}
return { score: 100, passed: true, issues: [] };
}`
);
const loadedCustom = await loadRuleLinter(customTsPath);
expect(loadedCustom.type).toBe("custom");
const customRes = await loadedCustom.linter({ description: "报销商务舱机票一张" });
expect(customRes.passed).toBe(false);
expect(customRes.issues[0]?.code).toBe("CUSTOM_FLIGHT");
// 2. 运行时崩溃的自定义校验器(安全捕获并降级)
const crashingTsPath = join(testDir, "custom-crash.ts");
writeFileSync(
customTsPath,
`export default function crashLinter() {
throw new Error("Intentional Crash");
}`
);
const loadedCrash = await loadRuleLinter(crashingTsPath);
const crashFallbackRes = await loadedCrash.linter({ description: "原则上不能超标" });
// 应当安全降级运行 builtin,返回模糊词拦截结果
expect(crashFallbackRes.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true);
// 清理临时文件
try {
unlinkSync(customTsPath);
} catch {}
});
test("lintRuleBatch computes overall summary, score average, and filters by level", async () => {
const loaded = await loadRuleLinter("builtin");
const rules = [
{ id: "1", code: "#0001", name: "清晰规则", description: "差旅住宿费每日不可超过500元,超标需在【单据备注】中说明并附【审批截图】。" },
{ id: "2", code: "#0002", name: "模糊规则", description: "原则上差旅住宿费尽量控制在500元以内" },
{ id: "3", code: "#0003", name: "悬空例外", description: "差旅住宿费单日不得超过500元,特殊情况除外" }
];
const batchRes = await lintRuleBatch(rules, loaded, undefined, { level: "all" });
expect(batchRes.totalRules).toBe(3);
expect(batchRes.healthyCount).toBe(1);
expect(batchRes.issueCount).toBe(2);
expect(batchRes.overallScore).toBeLessThan(100);
expect(batchRes.passed).toBe(false);
// 摘要模式:只返回有问题的规则
const summaryRes = await lintRuleBatch(rules, loaded, undefined, { summary: true });
expect(summaryRes.issues.length).toBe(2);
expect(summaryRes.issues.map((i) => i.ruleCode)).toEqual(["#0002", "#0003"]);
});
});
+146
View File
@@ -0,0 +1,146 @@
import { existsSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { isAbsolute, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { builtinRuleLinter } from "./builtin.js";
import type { RuleLintContext, RuleLintResult, RuleLintTarget, RuleLinterFn } from "./types.js";
export const PRIMARY_LINTERS_DIR = join(homedir(), ".config", "seal-use", "linters");
export const LOCAL_LINTERS_DIR = join(process.cwd(), "linters");
export interface LoadedLinter {
name: string;
type: "builtin" | "custom";
filePath?: string;
linter: RuleLinterFn;
}
export function listAvailableLinters(): Array<{ name: string; type: "builtin" | "custom"; path?: string }> {
const list: Array<{ name: string; type: "builtin" | "custom"; path?: string }> = [
{ name: "builtin", type: "builtin" }
];
const searchDirs = [PRIMARY_LINTERS_DIR, LOCAL_LINTERS_DIR];
for (const dir of searchDirs) {
if (existsSync(dir)) {
try {
const files = readdirSync(dir);
for (const file of files) {
if (file.endsWith(".ts") || file.endsWith(".js") || file.endsWith(".mjs")) {
const baseName = file.replace(/\.(ts|js|mjs)$/, "");
if (!list.some((item) => item.name === baseName)) {
list.push({
name: baseName,
type: "custom",
path: join(dir, file)
});
}
}
}
} catch {
// 忽略目录读取异常
}
}
}
return list;
}
export function resolveLinterPath(nameOrPath: string): string | undefined {
if (!nameOrPath || nameOrPath === "builtin") {
return undefined;
}
// 1. 绝对路径或显式相对路径
if (isAbsolute(nameOrPath) || nameOrPath.startsWith("./") || nameOrPath.startsWith("../")) {
const absPath = resolve(nameOrPath);
if (existsSync(absPath)) return absPath;
for (const ext of [".ts", ".js", ".mjs"]) {
if (existsSync(`${absPath}${ext}`)) return `${absPath}${ext}`;
}
}
// 2. 搜索预设目录
const candidates = [
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.ts`),
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.js`),
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.mjs`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.ts`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.js`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.mjs`)
];
for (const path of candidates) {
if (existsSync(path)) return path;
}
return undefined;
}
export async function loadRuleLinter(nameOrPath?: string): Promise<LoadedLinter> {
if (!nameOrPath || nameOrPath === "builtin") {
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
const resolvedPath = resolveLinterPath(nameOrPath);
if (!resolvedPath) {
console.error(`⚠️ [linter] 未找到自定义校验器 "${nameOrPath}",已自动安全降级至内置校验器。`);
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
try {
const fileUrl = pathToFileURL(resolvedPath).href;
const mod = await import(fileUrl);
const candidateFn = mod.default ?? mod.lintRule ?? mod.linter ?? mod.lint;
if (typeof candidateFn !== "function") {
console.error(
`⚠️ [linter] 自定义校验器 "${resolvedPath}" 未导出标准函数 (default / lintRule),已安全降级至内置校验器。`
);
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
// 执行期安全包装器:捕获用户自定义函数在运行期间可能抛出的任何未捕获异常
const safeLinter: RuleLinterFn = async (rule: RuleLintTarget, context?: RuleLintContext): Promise<RuleLintResult> => {
try {
const result = await candidateFn(rule, context);
if (result && typeof result === "object" && typeof result.score === "number" && Array.isArray(result.issues)) {
return result;
}
console.error(`⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。`);
return builtinRuleLinter(rule);
} catch (runtimeErr) {
console.error(`⚠️ [linter] 自定义校验器执行异常:`, runtimeErr);
return builtinRuleLinter(rule);
}
};
return {
name: nameOrPath,
type: "custom",
filePath: resolvedPath,
linter: safeLinter
};
} catch (err: any) {
console.error(
`⚠️ [linter] 加载自定义校验器脚本 "${resolvedPath}" 失败(语法错误或依赖缺失: ${err?.message ?? err}),已自动安全降级至内置校验器。`
);
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
}
+94
View File
@@ -0,0 +1,94 @@
import type { LoadedLinter } from "./loader.js";
import type {
RuleLintBatchResult,
RuleLintContext,
RuleLintItemResult,
RuleLintResult,
RuleLintTarget
} from "./types.js";
export interface LintServiceOptions {
level?: "all" | "error" | "warning";
minScore?: number;
summary?: boolean;
}
export async function lintSingleRule(
rule: RuleLintTarget,
loadedLinter: LoadedLinter,
context?: RuleLintContext
): Promise<RuleLintItemResult> {
const result = await loadedLinter.linter(rule, context);
return {
ruleId: rule.id,
ruleCode: rule.code,
ruleName: rule.name,
score: result.score,
passed: result.passed,
issues: result.issues,
description: rule.description
};
}
export async function lintRuleBatch(
rules: RuleLintTarget[],
loadedLinter: LoadedLinter,
context?: RuleLintContext,
options?: LintServiceOptions
): Promise<RuleLintBatchResult> {
const minScoreThreshold = options?.minScore ?? 0;
const levelFilter = options?.level ?? "all";
const itemResults: RuleLintItemResult[] = [];
let totalScoreSum = 0;
for (const rule of rules) {
const rawItem = await lintSingleRule(rule, loadedLinter, context);
totalScoreSum += rawItem.score;
// 根据 level 进行过滤
let filteredIssues = rawItem.issues;
if (levelFilter === "error") {
filteredIssues = rawItem.issues.filter((i) => i.level === "error");
} else if (levelFilter === "warning") {
filteredIssues = rawItem.issues.filter((i) => i.level === "warning" || i.level === "error");
}
const itemPassed = filteredIssues.every((i) => i.level !== "error");
if (options?.summary) {
// 总结模式:只记录有问题的规则项
if (filteredIssues.length > 0) {
itemResults.push({
...rawItem,
passed: itemPassed,
issues: filteredIssues
});
}
} else {
itemResults.push({
...rawItem,
passed: itemPassed,
issues: filteredIssues
});
}
}
const totalRules = rules.length;
const overallScore = totalRules === 0 ? 100 : Math.round(totalScoreSum / totalRules);
const issueCount = itemResults.filter((r) => r.issues.length > 0).length;
const healthyCount = totalRules - issueCount;
const passed = overallScore >= minScoreThreshold && itemResults.every((r) => r.passed);
return {
linter: loadedLinter.name,
linterType: loadedLinter.type,
totalRules,
healthyCount,
issueCount,
overallScore,
passed,
issues: itemResults
};
}
+61
View File
@@ -0,0 +1,61 @@
import { z } from "zod";
export const RuleLintIssueSchema = z.object({
level: z.enum(["error", "warning", "info"]),
code: z.string(),
message: z.string(),
snippet: z.string().optional(),
suggestion: z.string().optional()
});
export const RuleLintResultSchema = z.object({
score: z.number().min(0).max(100),
passed: z.boolean(),
issues: z.array(RuleLintIssueSchema)
});
export const RuleLintItemResultSchema = z.object({
ruleId: z.string().optional(),
ruleCode: z.string().optional(),
ruleName: z.string().optional(),
score: z.number().min(0).max(100),
passed: z.boolean(),
issues: z.array(RuleLintIssueSchema),
description: z.string().optional()
});
export const RuleLintBatchResultSchema = z.object({
linter: z.string(),
linterType: z.enum(["builtin", "custom"]),
totalRules: z.number(),
healthyCount: z.number(),
issueCount: z.number(),
overallScore: z.number().min(0).max(100),
passed: z.boolean(),
issues: z.array(RuleLintItemResultSchema)
});
export type RuleLintIssue = z.infer<typeof RuleLintIssueSchema>;
export type RuleLintResult = z.infer<typeof RuleLintResultSchema>;
export type RuleLintItemResult = z.infer<typeof RuleLintItemResultSchema>;
export type RuleLintBatchResult = z.infer<typeof RuleLintBatchResultSchema>;
export interface RuleLintTarget {
id?: string;
code?: string;
name?: string;
description: string;
scope?: string;
strictness?: string;
}
export interface RuleLintContext {
corpId?: string;
versionNumber?: number;
allRules?: RuleLintTarget[];
}
export type RuleLinterFn = (
rule: RuleLintTarget,
context?: RuleLintContext
) => Promise<RuleLintResult> | RuleLintResult;
+118 -1
View File
@@ -5,8 +5,10 @@ import { randomBytes } from "node:crypto";
import * as api from "./api.js";
import { defaultSealUrl, getHoseEnterpriseUrl, probeHoseDomain } from "../../core/auth/hose.js";
import { CorpConfig } from "../../core/config/types.js";
import { loadGlobalConfig } from "../../core/config/loader.js";
import { createSealClientForToken } from "../../core/http/factory.js";
import { searchApprovalContent } from "./search.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "./linter/index.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
@@ -315,7 +317,30 @@ export const sealTools = [
params: { ruleId: string; description?: string; scope?: string; strictness?: string }
) => {
const { ruleId, ...rest } = params;
return api.updateApprovalRule(client, ruleId, rest);
const result = await api.updateApprovalRule(client, ruleId, rest);
if (params.description) {
try {
const globalConfig = loadGlobalConfig();
if (globalConfig.lint?.enabled) {
const loaded = await loadRuleLinter(globalConfig.lint.activeLinter);
const lintResult = await lintSingleRule({ id: ruleId, description: params.description }, loaded);
if (lintResult.issues.length > 0) {
console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${lintResult.score}/100 (发现 ${lintResult.issues.length} 处潜在风险):`);
for (const issue of lintResult.issues) {
console.error(` • [${issue.level.toUpperCase()}] ${issue.message}${issue.snippet ? ` ("${issue.snippet}")` : ""}`);
if (issue.suggestion) {
console.error(` 👉 建议: ${issue.suggestion}`);
}
}
}
}
} catch {
// 容错降级:质检异常绝不阻断规则更新
}
}
return result;
}
},
{
@@ -412,6 +437,96 @@ export const sealTools = [
return rule;
}
},
{
name: "seal_approval_rules_lint",
description: "对 Seal 草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",
parameters: z.object({
linter: z.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),
version: z.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),
code: z.string().optional().describe("按规则展示编号过滤(如 #0038)"),
ruleId: z.string().optional().describe("按规则 ID 过滤"),
minScore: z.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),
level: z.enum(["all", "error", "warning"]).default("all").describe("问题报告等级过滤"),
summary: z.boolean().optional().describe("为 true 时仅返回存在瑕疵/扣分的规则")
}),
handler: async (
client: KyInstance,
params: {
linter?: string;
version?: string;
code?: string;
ruleId?: string;
minScore?: number;
level?: "all" | "error" | "warning";
summary?: boolean;
},
context: ToolContext
) => {
let targets: RuleLintTarget[] = [];
let versionNumber: number | undefined;
if (params.version) {
const versions = await api.listApprovalRuleVersions(client);
const versionNumberParsed = Number(params.version);
const version = isNaN(versionNumberParsed)
? params.version === "latest"
? versions[0]
: versions.find((v) => v.id === params.version)
: versions.find((v) => v.versionNumber === versionNumberParsed);
if (!version) {
throw new Error(`未找到指定的规则版本: ${params.version}`);
}
versionNumber = version.versionNumber;
targets = (version.rules ?? []).map((r, idx) => ({
id: (r as any).id ?? (r as any).runtimeId,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: (r as any).scope,
strictness: (r as any).strictness
}));
} else {
const draftData = await api.listApprovalRules(client);
targets = (draftData.rules ?? []).map((r, idx) => ({
id: r.id,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: r.scope,
strictness: r.strictness
}));
}
if (params.code) {
targets = targets.filter(
(r) => r.code === params.code || r.code?.replace(/[#\s]/g, "") === params.code?.replace(/[#\s]/g, "")
);
}
if (params.ruleId) {
targets = targets.filter((r) => r.id === params.ruleId || r.code === params.ruleId);
}
const globalConfig = loadGlobalConfig();
const linterNameOrPath = params.linter ?? globalConfig.lint?.activeLinter ?? "builtin";
const loadedLinter = await loadRuleLinter(linterNameOrPath);
const batchResult = await lintRuleBatch(
targets,
loadedLinter,
{ corpId: context.corp.id, versionNumber, allRules: targets },
{ minScore: params.minScore, level: params.level, summary: params.summary }
);
if (params.minScore && batchResult.overallScore < params.minScore) {
throw new Error(
`[Linter 质量门禁未通过] 综合评分 ${batchResult.overallScore} 低于要求的最低分 ${params.minScore} 分 (共发现 ${batchResult.issueCount} 条问题规则)。`
);
}
return batchResult;
}
},
{
name: "seal_approval_documents_list",
description: "列出 Seal 审批知识文档",
@@ -1740,6 +1855,7 @@ const sealActionNames = [
"seal_approval_rule_versions_list",
"seal_approval_rule_version_get",
"seal_approval_rule_get",
"seal_approval_rules_lint",
"seal_approval_rule_version_publish",
"seal_approval_documents_list",
"seal_approval_document_get",
@@ -1797,6 +1913,7 @@ const sealActionAliases: Record<string, (typeof sealActionNames)[number]> = {
"rule.versions.list": "seal_approval_rule_versions_list",
"rule.version.get": "seal_approval_rule_version_get",
"rule.get": "seal_approval_rule_get",
"rule.lint": "seal_approval_rules_lint",
"rule.publish": "seal_approval_rule_version_publish",
"doc.list": "seal_approval_documents_list",
"doc.get": "seal_approval_document_get",