Compare commits

...
12 Commits
Author SHA1 Message Date
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
yunyingk cdab1e2009 Merge pull request #25 from yunyingk/codex/release-v0.10.3
🧪 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.3: Hose deployment auto platform probing, alias support, multi-target routing, and stderr next-step guidance
2026-09-02 18:19:48 +08:00
gitea 3e06c0f266 Release v0.10.3: Auto platform probing for Hose deployment, alias support, multi-target routing, and stderr next-step guidance 2026-09-02 18:18:54 +08:00
yunyingk f31afd2d92 Merge pull request #24 from yunyingk/codex/update-gitea-repo-in-workflow
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
ci(release): update GITEA_REPO to gitea/seal-use
2026-09-02 16:41:17 +08:00
gitea e3e49d729e ci(release): update GITEA_REPO to gitea/seal-use 2026-09-02 16:40:25 +08:00
yunyingk 8166ec7d3d Merge pull request #23 from yunyingk/codex/release-v0.10.2
🧪 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.2: add agent self-bootstrap guide to SKILL.md and CI mirror isolation
2026-09-02 16:36:58 +08:00
gitea afa039142f Release v0.10.2: add agent self-bootstrap guide to SKILL.md and CI mirror isolation 2026-09-02 16:36:17 +08:00
yunyingk 3c30210bcd Merge pull request #22 from yunyingk/codex/skill-install-instructions
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
docs(skill): add explicit bootstrap & installation guide to SKILL.md
2026-09-02 16:35:49 +08:00
gitea 79e17513ee docs(skill): add explicit bootstrap & installation guide to SKILL.md 2026-09-02 16:35:00 +08:00
yunyingk 46c85181a3 Merge pull request #21 from yunyingk/codex/ci-bypass-gitea-mirror
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
feat(update): block gitea in CI and support SEAL_USE_MIRROR routing
2026-09-02 16:33:00 +08:00
gitea df8c8c8280 feat(update): block gitea in CI and support SEAL_USE_MIRROR routing 2026-09-02 16:32:19 +08:00
31 changed files with 1380 additions and 649 deletions

No files matched your search

+1 -1
View File
@@ -101,7 +101,7 @@ jobs:
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_HOST: "https://git.ying-qing.cn"
GITEA_REPO: "gitea/seal-home"
GITEA_REPO: "gitea/seal-use"
run: |
if [ -z "$GITEA_TOKEN" ]; then
echo "::notice::GITEA_TOKEN secret not configured, skipping Gitea upload."
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.1",
"version": "0.10.4",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+10 -1
View File
@@ -26,7 +26,16 @@ Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in
Use TypeScript ES modules with explicit `.js` import extensions for local files. Validate external data with Zod or narrow types before use. Follow existing style: two-space indentation, double quotes, omitted trailing semicolons, `camelCase` variables/functions, `PascalCase` classes/types, and lowercase hyphenated filenames such as `token-store.ts`.
Prefer small domain functions over broad utility modules. Keep CLI output JSON on stdout and diagnostics/errors on stderr.
Prefer small domain functions over broad utility modules.
## CLI & Agent Harness Protocol Guidelines
- **Machine Channel (`stdout`)**: CLI commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
- **Guidance & Diagnostic Channel (`stderr`)**: Use `stderr` for runtime logs, network probing status, self-healing notifications, and explicit **Next-Step Command Suggestions** (e.g. `👉 Next action: seal-use deploy hosecloud sync <signKey>`).
- **Exit Code Contract**:
- Successful executions MUST terminate with exit code `0`.
- Any parameter validation failure, upstream API error, or business block MUST result in a non-zero exit code (e.g. `1`), allowing the Agent Harness to reliably detect failures and trigger automated error remediation.
- Never call `process.exit()` deep in domain functions; throw structured errors and let `src/cli/runner.ts` handle stream routing and exit code assignment.
## Testing Guidelines
+24
View File
@@ -5,6 +5,30 @@ 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.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
- **Auto Platform Probing for HoseCloud Deployment**: In `deploy hosecloud configure` (`seal_deploy_hosecloud_configure`), automatically probes 6 standard Hose SaaS platform domains (Standard, DingTalk, WeChat Work, Feishu, CloudHub, DingTalk Enterprise) using `probeHoseDomain` when `customApiUrl` is omitted. Eliminates manual platform guessing and prevents authentication failures (`请检查 API 平台和凭证配置是否正确`).
- **Standardized Business Terminology**: Aligned all CLI and tool descriptions with Seal AI product semantics: `Seal AI 智能审核发布到合思费控` (replacing raw backend jargon like "合思出站消息").
- **Dedicated Reference Documentation**: Added `skills/seal-use/references/hose-enterprise-deploy.md` covering end-to-end deployment, auto platform detection, 3-step publishing, and EBot node integration.
## [0.10.2] - 2026-09-02
### Added & Enhanced
- **Agent Skill Self-Bootstrap & Auto-Installation**: Embedded direct 1-line installation scripts into `skills/seal-use/SKILL.md` and onboarding references. Third-party AI Agents can now automatically self-install and bootstrap `seal-use` when missing without human intervention.
- **CI / Mirror Routing Isolation**: Added intelligent mirror mode resolver (`SEAL_USE_MIRROR=github|gitea|auto`). Automatically bypasses Gitea in CI environments to ensure 100% offline, deterministic, and fast (<20s) test execution.
## [0.10.1] - 2026-09-02
### Changed & Infrastructure
+101 -564
View File
@@ -1,82 +1,82 @@
import{createRequire as qy}from"node:module";var Yy=Object.create;var{getPrototypeOf:Py,defineProperty:A$,getOwnPropertyNames:py}=Object;var Qy=Object.prototype.hasOwnProperty;function Fy(n){return this[n]}var Ky,By,n0=(n,i,r)=>{var o=n!=null&&typeof n==="object";if(o){var t=i?Ky??=new WeakMap:By??=new WeakMap,u=t.get(n);if(u)return u}r=n!=null?Yy(Py(n)):{};let e=i||!n||!n.__esModule?A$(r,"default",{value:n,enumerable:!0}):r;for(let l of py(n))if(!Qy.call(e,l))A$(e,l,{get:Fy.bind(n,l),enumerable:!0});if(o)t.set(n,e);return e};var P=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports);var Ty=(n)=>n;function Vy(n,i){this[n]=Ty.bind(null,i)}var Qi=(n,i)=>{for(var r in i)A$(n,r,{get:i[r],enumerable:!0,configurable:!0,set:Vy.bind(i,r)})};var i0=qy(import.meta.url);var nu=P((XD)=>{Object.defineProperty(XD,"__esModule",{value:!0});XD.regexpCode=XD.getEsmExportName=XD.getProperty=XD.safeStringify=XD.stringify=XD.strConcat=XD.addCodeArg=XD.str=XD._=XD.nil=XD._Code=XD.Name=XD.IDENTIFIER=XD._CodeOrName=void 0;class Tl{}XD._CodeOrName=Tl;XD.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Wr extends Tl{constructor(n){super();if(!XD.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}}}XD.Name=Wr;class ci 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 Wr)i[r.str]=(i[r.str]||0)+1;return i},{})}}XD._Code=ci;XD.nil=new ci("");function WD(n,...i){let r=[n[0]],o=0;while(o<i.length)Pc(r,i[o]),r.push(n[++o]);return new ci(r)}XD._=WD;var Yc=new ci("+");function JD(n,...i){let r=[so(n[0])],o=0;while(o<i.length)r.push(Yc),Pc(r,i[o]),r.push(Yc,so(n[++o]));return vX(r),new ci(r)}XD.str=JD;function Pc(n,i){if(i instanceof ci)n.push(...i._items);else if(i instanceof Wr)n.push(i);else n.push(gX(i))}XD.addCodeArg=Pc;function vX(n){let i=1;while(i<n.length-1){if(n[i]===Yc){let r=$X(n[i-1],n[i+1]);if(r!==void 0){n.splice(i-1,3,r);continue}n[i++]="+"}i++}}function $X(n,i){if(i==='""')return n;if(n==='""')return i;if(typeof n=="string"){if(i instanceof Wr||n[n.length-1]!=='"')return;if(typeof i!="string")return`${n.slice(0,-1)}${i}"`;if(i[0]==='"')return n.slice(0,-1)+i.slice(1);return}if(typeof i=="string"&&i[0]==='"'&&!(n instanceof Wr))return`"${n}${i.slice(1)}`;return}function IX(n,i){return i.emptyStr()?n:n.emptyStr()?i:JD`${n}${i}`}XD.strConcat=IX;function gX(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:so(Array.isArray(n)?n.join(","):n)}function bX(n){return new ci(so(n))}XD.stringify=bX;function so(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}XD.safeStringify=so;function wX(n){return typeof n=="string"&&XD.IDENTIFIER.test(n)?new ci(`.${n}`):WD`[${n}]`}XD.getProperty=wX;function fX(n){if(typeof n=="string"&&XD.IDENTIFIER.test(n))return new ci(`${n}`);throw Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}XD.getEsmExportName=fX;function cX(n){return new ci(n.toString())}XD.regexpCode=cX});var Kc=P((pD)=>{Object.defineProperty(pD,"__esModule",{value:!0});pD.ValueScope=pD.ValueScopeName=pD.Scope=pD.varKinds=pD.UsedValueState=void 0;var an=nu();class YD 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||(pD.UsedValueState=ql={}));pD.varKinds={const:new an.Name("const"),let:new an.Name("let"),var:new an.Name("var")};class Qc{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}}}pD.Scope=Qc;class Fc 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}]`}}pD.ValueScopeName=Fc;var WX=an._`\n`;class PD extends Qc{constructor(n){super(n);this._values={},this._scope=n.scope,this.opts={...n,_n:n.lines?WX:an.nil}}get(){return this._scope}name(n){return new Fc(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 Ui.Scope({parent:n}),this._nodes=[new ED]}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 FD(n,t,r)),t}const(n,i,r){return this._def(Ui.varKinds.const,n,i,r)}let(n,i,r){return this._def(Ui.varKinds.let,n,i,r)}var(n,i,r){return this._def(Ui.varKinds.var,n,i,r)}assign(n,i,r){return this._leafNode(new Vc(n,i,r))}add(n,i){return this._leafNode(new KD(n,sn.operators.ADD,i))}code(n){if(typeof n=="function")n();else if(n!==s.nil)this._leafNode(new qD(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 Vi(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 Vi(n))}else(){return this._elseNode(new iu)}endIf(){return this._endBlockNode(Vi,iu)}_for(n,i){if(this._blockNode(n),i)this.code(i).endFor();return this}for(n,i){return this._for(new _D(n),i)}forRange(n,i,r,o,t=this.opts.es5?Ui.varKinds.var:Ui.varKinds.let){let u=this._scope.toName(n);return this._for(new ZD(t,u,i,r),()=>o(u))}forOf(n,i,r,o=Ui.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 Bc("of",o,t,i),()=>r(t))}forIn(n,i,r,o=this.opts.es5?Ui.varKinds.var:Ui.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 Bc("in",o,t,i),()=>r(t))}endFor(){return this._endBlockNode(Jr)}label(n){return this._leafNode(new BD(n))}break(n){return this._leafNode(new TD(n))}return(n){let i=new _l;if(this._blockNode(i),this.code(n),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(_l)}try(n,i,r){if(!i&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new MD;if(this._blockNode(o),this.code(n),i){let t=this.name("e");this._currNode=o.catch=new Zl(t),i(t)}if(r)this._currNode=o.finally=new Ml,this.code(r);return this._endBlockNode(Zl,Ml)}throw(n){return this._leafNode(new VD(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 El(n,i,r)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(El)}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 Vi))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=zD;function Xt(n,i){for(let r in i)n[r]=(n[r]||0)+(i[r]||0);return n}function zl(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 YX(n,i){for(let r in i)n[r]=(n[r]||0)-(i[r]||0)}function CD(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:s._`!${Tc(n)}`}sn.not=CD;var PX=RD(sn.operators.AND);function pX(...n){return n.reduce(PX)}sn.and=pX;var QX=RD(sn.operators.OR);function FX(...n){return n.reduce(QX)}sn.or=FX;function RD(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 nn=P((r1)=>{Object Line truncated
|| (${e} == "string" && ${t} && ${t} == +${t})`).assign(l,z._`+${t}`);return;case"integer":o.elseIf(z._`${e} === "boolean" || ${t} === null
|| (${e} === "string" && ${t} && ${t} == +${t} && !(${t} % 1))`).assign(l,z._`+${t}`);return;case"boolean":o.elseIf(z._`${t} === "false" || ${t} === 0 || ${t} === null`).assign(l,!1).elseIf(z._`${t} === "true" || ${t} === 1`).assign(l,!0);return;case"null":o.elseIf(z._`${t} === "" || ${t} === 0 || ${t} === false`),o.assign(l,null);return;case"array":o.elseIf(z._`${e} === "string" || ${e} === "number"
|| ${e} === "boolean" || ${t} === null`).assign(l,z._`[${t}]`)}}}function h8({gen:n,parentData:i,parentDataProperty:r},o){n.if(z._`${i} !== undefined`,()=>n.assign(z._`${i}[${r}]`,o))}function Cc(n,i,r,o=Hr.Correct){let t=o===Hr.Correct?z.operators.EQ:z.operators.NEQ,u;switch(n){case"null":return z._`${i} ${t} null`;case"array":u=z._`Array.isArray(${i})`;break;case"object":u=z._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":u=e(z._`!(${i} % 1) && !isNaN(${i})`);break;case"number":u=e();break;default:return z._`typeof ${i} ${t} ${n}`}return o===Hr.Correct?u:(0,z.not)(u);function e(l=z.nil){return(0,z.and)(z._`typeof ${i} == "number"`,l,r?z._`isFinite(${i})`:z.nil)}}L1.checkDataType=Cc;function Rc(n,i,r,o){if(n.length===1)return Cc(n[0],i,r,o);let t,u=(0,k1.toHash)(n);if(u.array&&u.object){let e=z._`typeof ${i} != "object"`;t=u.null?e:z._`!${i} || ${e}`,delete u.null,delete u.array,delete u.object}else t=z.nil;if(u.number)delete u.integer;for(let e in u)t=(0,z.and)(t,Cc(e,i,r,o));return t}L1.checkDataTypes=Rc;var m8={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:i})=>typeof n=="string"?z._`{type: ${n}}`:z._`{type: ${i}}`};function hc(n){let i=x8(n);(0,Z8.reportError)(i,m8)}L1.reportTypeError=hc;function x8(n){let{gen:i,data:r,schema:o}=n,t=(0,k1.schemaRefOrVal)(n,o,"type");return{gen:i,keyword:"type",data:r,schema:o.type,schemaCode:t,schemaValue:t,parentSchema:o,params:{},it:n}}});var J1=P((G1)=>{Object.defineProperty(G1,"__esModule",{value:!0});G1.assignDefaults=void 0;var Yr=C(),o9=nn();function u9(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))}G1.assignDefaults=u9;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,o9.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=P((Y1)=>{Object.defineProperty(Y1,"__esModule",{value:!0});Y1.validateUnion=Y1.validateArray=Y1.usePattern=Y1.callValidateCode=Y1.schemaProperties=Y1.allSchemaProperties=Y1.noPropertyInData=Y1.propertyInData=Y1.isOwnProperty=Y1.hasPropFunc=Y1.reportMissingProp=Y1.checkMissingProp=Y1.checkReportMissingProp=void 0;var Dn=C(),mc=nn(),gt=qi(),e9=nn();function l9(n,i){let{gen:r,data:o,it:t}=n;r.if(ac(r,o,i,t.opts.ownProperties),()=>{n.setParams({missingProperty:Dn._`${i}`},!0),n.error()})}Y1.checkReportMissingProp=l9;function v9({gen:n,data:i,it:{opts:r}},o,t){return(0,Dn.or)(...o.map((u)=>(0,Dn.and)(ac(n,i,u,r.ownProperties),Dn._`${t} = ${u}`)))}Y1.checkMissingProp=v9;function $9(n,i){n.setParams({missingProperty:i},!0),n.error()}Y1.reportMissingProp=$9;function X1(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Dn._`Object.prototype.hasOwnProperty`})}Y1.hasPropFunc=X1;function xc(n,i,r){return Dn._`${X1(n)}.call(${i}, ${r})`}Y1.isOwnProperty=xc;function I9(n,i,r,o){let t=Dn._`${i}${(0,Dn.getProperty)(r)} !== undefined`;return o?Dn._`${t} && ${xc(n,i,r)}`:t}Y1.propertyInData=I9;function ac(n,i,r,o){let t=Dn._`${i}${(0,Dn.getProperty)(r)} === undefined`;return o?(0,Dn.or)(t,(0,Dn.not)(xc(n,i,r))):t}Y1.noPropertyInData=ac;function H1(n){return n?Object.keys(n).filter((i)=>i!=="__proto__"):[]}Y1.allSchemaProperties=H1;function g9(n,i){return H1(i).filter((r)=>!(0,mc.alwaysValidSchema)(n,i[r]))}Y1.schemaProperties=g9;function b9({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})`}Y1.callValidateCode=b9;var w9=Dn._`new RegExp`;function f9({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"?w9:(0,e9.useFunc)(n,t)}(${r}, ${o})`})}Y1.usePattern=f9;function c9(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:mc.Type.Num},u),i.if((0,Dn.not)(u),l)})}}Y1.validateArray=c9;function U9(n){let{gen:i,schema:r,keyword:o,it:t}=n;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(($)=>(0,mc.alwaysValidSchema)(t,$))&&!t.opts.unevaluated)return;let e=i.let("valid",!1),l=i.name("_valid");i.block(()=>r. Line truncated
import{createRequire as ay}from"node:module";var _y=Object.create;var{getPrototypeOf:Zy,defineProperty:O$,getOwnPropertyNames:My}=Object;var zy=Object.prototype.hasOwnProperty;function Cy(n){return this[n]}var Ry,hy,$0=(n,i,r)=>{var o=n!=null&&typeof n==="object";if(o){var t=i?Ry??=new WeakMap:hy??=new WeakMap,u=t.get(n);if(u)return u}r=n!=null?_y(Zy(n)):{};let e=i||!n||!n.__esModule?O$(r,"default",{value:n,enumerable:!0}):r;for(let l of My(n))if(!zy.call(e,l))O$(e,l,{get:Cy.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 my=(n)=>n;function xy(n,i){this[n]=my.bind(null,i)}var Fi=(n,i)=>{for(var r in i)O$(n,r,{get:i[r],enumerable:!0,configurable:!0,set:xy.bind(i,r)})};var I0=ay(import.meta.url);var ru=H((TD)=>{Object.defineProperty(TD,"__esModule",{value:!0});TD.regexpCode=TD.getEsmExportName=TD.getProperty=TD.safeStringify=TD.stringify=TD.strConcat=TD.addCodeArg=TD.str=TD._=TD.nil=TD._Code=TD.Name=TD.IDENTIFIER=TD._CodeOrName=void 0;class Zl{}TD._CodeOrName=Zl;TD.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Jr extends Zl{constructor(n){super();if(!TD.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}}}TD.Name=Jr;class fi 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},{})}}TD._Code=fi;TD.nil=new fi("");function BD(n,...i){let r=[n[0]],o=0;while(o<i.length)Kc(r,i[o]),r.push(n[++o]);return new fi(r)}TD._=BD;var Fc=new fi("+");function PD(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 AJ(r),new fi(r)}TD.str=PD;function Kc(n,i){if(i instanceof fi)n.push(...i._items);else if(i instanceof Jr)n.push(i);else n.push(OJ(i))}TD.addCodeArg=Kc;function AJ(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 dJ(n,i){return i.emptyStr()?n:n.emptyStr()?i:PD`${n}${i}`}TD.strConcat=dJ;function OJ(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:tu(Array.isArray(n)?n.join(","):n)}function LJ(n){return new fi(tu(n))}TD.stringify=LJ;function tu(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}TD.safeStringify=tu;function NJ(n){return typeof n=="string"&&TD.IDENTIFIER.test(n)?new fi(`.${n}`):BD`[${n}]`}TD.getProperty=NJ;function yJ(n){if(typeof n=="string"&&TD.IDENTIFIER.test(n))return new fi(`${n}`);throw Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}TD.getEsmExportName=yJ;function GJ(n){return new fi(n.toString())}TD.regexpCode=GJ});var Ec=H((_D)=>{Object.defineProperty(_D,"__esModule",{value:!0});_D.ValueScope=_D.ValueScopeName=_D.Scope=_D.varKinds=_D.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||(_D.UsedValueState=zl={}));_D.varKinds={const:new sn.Name("const"),let:new sn.Name("let"),var:new sn.Name("var")};class Pc{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}}}_D.Scope=Pc;class Tc 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}]`}}_D.ValueScopeName=Tc;var TJ=sn._`\n`;class qD extends Pc{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 Tc(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 _c(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 Ei(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 Ei(n))}else(){return this._elseNode(new ou)}endIf(){return this._endBlockNode(Ei,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 Ei))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 _J(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._`!${qc(n)}`}ni.not=t1;var ZJ=r1(ni.operators.AND);function MJ(...n){return n.reduce(ZJ)}ni.and=MJ;var zJ=r1(ni.operators.OR);function CJ(...n){return n.reduce(zJ)}ni.or=CJ;function r1(n){return(i,r)=>i===s.nil?r:r===s.nil?i:s._`${qc(i)} ${n} ${qc(r)}`}function qc(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 e8({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 l8={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=v8(n);(0,i8.reportError)(i,l8)}Y1.reportTypeError=ac;function v8(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 P1=H((K1)=>{Object.defineProperty(K1,"__esModule",{value:!0});K1.assignDefaults=void 0;var Qr=R(),c8=tn();function U8(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=U8;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,c8.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(),D8=tn();function S8(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=S8;function A8({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=A8;function k8(n,i){n.setParams({missingProperty:i},!0),n.error()}V1.reportMissingProp=k8;function T1(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Dn._`Object.prototype.hasOwnProperty`})}V1.hasPropFunc=T1;function n6(n,i,r){return Dn._`${T1(n)}.call(${i}, ${r})`}V1.isOwnProperty=n6;function d8(n,i,r,o){let t=Dn._`${i}${(0,Dn.getProperty)(r)} !== undefined`;return o?Dn._`${t} && ${n6(n,i,r)}`:t}V1.propertyInData=d8;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 E1(n){return n?Object.keys(n).filter((i)=>i!=="__proto__"):[]}V1.allSchemaProperties=E1;function O8(n,i){return E1(i).filter((r)=>!(0,sc.alwaysValidSchema)(n,i[r]))}V1.schemaProperties=O8;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 w=Dn._`${g}, ${r.object(...b)}`;return $!==Dn.nil?Dn._`${l}.call(${$}, ${w})`:Dn._`${l}(${w})`}V1.callValidateCode=L8;var N8=Dn._`new RegExp`;function y8({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,D8.useFunc)(n,t)}(${r}, ${o})`})}V1.usePattern=y8;function G8(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=G8;function W8(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 QP={keyword:"dependencies",type:"object",schemaType:"object",error:hA.error,code(n){let[i,r]=FP(n);CA(n,i),RA(n,r)}};function FP({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 CA(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()}}hA.validatePropertyDeps=CA;function RA(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,pP.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)}}hA.validateSchemaDeps=RA;hA.default=QP});var iO=P((nO)=>{Object.defineProperty(nO,"__esModule",{value:!0});var sA=C(),TP=nn(),VP={message:"property name must be valid",params:({params:n})=>sA._`{propertyName: ${n.propertyName}}`},qP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:VP,code(n){let{gen:i,schema:r,data:o,it:t}=n;if((0,TP.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,sA.not)(u),()=>{if(n.error(!0),!t.allErrors)i.break()})}),n.ok(u)}};nO.default=qP});var d6=P((tO)=>{Object.defineProperty(tO,"__esModule",{value:!0});var fv=Ii(),Ai=C(),_P=qi(),cv=nn(),ZP={message:"must NOT have additional properties",params:({params:n})=>Ai._`{additionalProperty: ${n.additionalProperty}}`},MP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ZP,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,cv.alwaysValidSchema)(e,r))return;let I=(0,fv.allSchemaProperties)(o.properties),g=(0,fv.allSchemaProperties)(o.patternProperties);b(),n.ok(Ai._`${u} === ${_P.default.errors}`);function b(){i.forIn("key",t,(k)=>{if(!I.length&&!g.length)c(k);else i.if(w(k),()=>c(k))})}function w(k){let d;if(I.length>8){let Q=(0,cv.schemaRefOrVal)(e,o.properties,"properties");d=(0,fv.isOwnProperty)(i,Q,k)}else if(I.length)d=(0,Ai.or)(...I.map((Q)=>Ai._`${k} === ${Q}`));else d=Ai.nil;if(g.length)d=(0,Ai.or)(d,...g.map((Q)=>Ai._`${(0,fv.usePattern)(n,Q)}.test(${k})`));return(0,Ai.not)(d)}function f(k){i.code(Ai._`delete ${t}[${k}]`)}function c(k){if($.removeAdditional==="all"||$.removeAdditional&&r===!1){f(k);return}if(r===!1){if(n.setParams({additionalProperty:k}),n.error(),!l)i.break();return}if(typeof r=="object"&&!(0,cv.alwaysValidSchema)(e,r)){let d=i.name("valid");if($.removeAdditional==="failing")S(k,d,!1),i.if((0,Ai.not)(d),()=>{n.reset(),f(k)});else if(S(k,d),!l)i.if((0,Ai.not)(d),()=>i.break())}}function S(k,d,Q){let Y={keyword:"additionalProperties",dataProp:k,dataPropType:cv.Type.Str};if(Q===!1)Object.assign(Y,{compositeRule:!0,createErrors:!1,allErrors:!1});n.subschema(Y,d)}}};tO.default=MP});var eO=P((uO)=>{Object.defineProperty(uO,"__esModule",{value:!0});var CP=lu(),rO=Ii(),N6=nn(),oO=d6(),RP={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)oO.default.code(new CP.KeywordCxt(u,oO.default,"additionalProperties"));let e=(0,rO.allSchemaProperties)(r);for(let b of e)u.definedProperties.add(b);if(u.opts.unevaluated&&e.length&&u.props!==!0)u.props=N6.mergeEvaluated.props(i,(0,N6.toHash)(e),u.props);let l=e.filter((b)=>!(0,N6.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,rO.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},$)}}};uO.default=RP});var gO=P((IO)=>{Object.defineProperty(IO,"__esModule",{value:!0});var lO=Ii(),Uv=C(),vO=nn(),$O=nn(),mP={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,lO.allSchemaProperties)(r),$=l.filter((S)=>(0,vO.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 Uv.Name))u.props=(0,$O. 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,kn())));throw mu(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,kn())));throw mu(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,kn())))}:{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,kn())))}:{success:!0,data:u.value}},bo=at(mn),xu=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Rt(n)(i,r,t)},$0=xu(mn),au=(n)=>(i,r,o)=>{return Rt(n)(i,r,o)},I0=au(mn),su=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return ht(n)(i,r,t)},g0=su(mn),ne=(n)=>async(i,r,o)=>{return ht(n)(i,r,o)},b0=ne(mn),ie=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return mt(n)(i,r,t)},w0=ie(mn),te=(n)=>(i,r,o)=>{return mt(n)(i,r,o)},f0=te(mn),re=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return at(n)(i,r,t)},c0=re(mn),oe=(n)=>async(i,r,o)=>{return at(n)(i,r,o)},U0=oe(mn);var oi={};Qi(oi,{xid:()=>K$,uuid7:()=>Dj,uuid6:()=>Uj,uuid4:()=>cj,uuid:()=>Lt,uppercase:()=>vI,unicodeEmail:()=>D0,undefined:()=>eI,ulid:()=>F$,time:()=>s$,string:()=>iI,sha512_hex:()=>Bj,sha512_base64url:()=>Vj,sha512_base64:()=>Tj,sha384_hex:()=>Qj,sha384_base64url:()=>Kj,sha384_base64:()=>Fj,sha256_hex:()=>Yj,sha256_base64url:()=>pj,sha256_base64:()=>Pj,sha1_hex:()=>Jj,sha1_base64url:()=>Hj,sha1_base64:()=>Xj,rfc5322Email:()=>Aj,number:()=>wo,null:()=>uI,nanoid:()=>T$,md5_hex:()=>jj,md5_base64url:()=>Wj,md5_base64:()=>Gj,mac:()=>z$,lowercase:()=>lI,ksuid:()=>B$,ipv6:()=>M$,ipv4:()=>Z$,integer:()=>rI,idnEmail:()=>Oj,httpProtocol:()=>m$,html5Email:()=>Sj,hostname:()=>Nj,hex:()=>yj,guid:()=>q$,extendedDuration:()=>fj,emoji:()=>_$,email:()=>E$,e164:()=>x$,duration:()=>V$,domain:()=>Lj,datetime:()=>nI,date:()=>a$,cuid2:()=>Q$,cuid:()=>p$,cidrv6:()=>R$,cidrv4:()=>C$,browserEmail:()=>kj,boolean:()=>oI,bigint:()=>tI,base64url:()=>ue,base64:()=>h$});var p$=/^[cC][0-9a-z]{6,}$/,Q$=/^[0-9a-z]+$/,F$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,K$=/^[0-9a-vA-V]{20}$/,B$=/^[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)?)?)$/,fj=/^[-+]?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})$`)},cj=Lt(4),Uj=Lt(6),Dj=Lt(7),E$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Sj=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Aj=/^(([^<>()\[\]\\.,;:\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,}))$/,D0=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Oj=D0,kj=/^[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])?)*$/,dj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function _$(){return new RegExp(dj,"u")}var Z$=/^(?:(?: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])$/,M$=/^(([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}|:))$/,z$=(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}$`)},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-Line truncated
deps: ${r}}`};var z7={keyword:"dependencies",type:"object",schemaType:"object",error:ok.error,code(n){let[i,r]=C7(n);tk(n,i),rk(n,r)}};function C7({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 tk(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(N6._`${$} && (${(0,Ou.checkMissingProp)(n,l,u)})`),(0,Ou.reportMissingProp)(n,u),r.else()}}ok.validatePropertyDeps=tk;function rk(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,M7.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)}}ok.validateSchemaDeps=rk;ok.default=z7});var Ik=H(($k)=>{Object.defineProperty($k,"__esModule",{value:!0});var vk=R(),m7=tn(),x7={message:"property name must be valid",params:({params:n})=>vk._`{propertyName: ${n.propertyName}}`},a7={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:x7,code(n){let{gen:i,schema:r,data:o,it:t}=n;if((0,m7.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,vk.not)(u),()=>{if(n.error(!0),!t.allErrors)i.break()})}),n.ok(u)}};$k.default=a7});var y6=H((gk)=>{Object.defineProperty(gk,"__esModule",{value:!0});var Av=gi(),Si=R(),n5=Vi(),kv=tn(),i5={message:"must NOT have additional properties",params:({params:n})=>Si._`{additionalProperty: ${n.additionalProperty}}`},t5={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:i5,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,kv.alwaysValidSchema)(e,r))return;let I=(0,Av.allSchemaProperties)(o.properties),g=(0,Av.allSchemaProperties)(o.patternProperties);b(),n.ok(Si._`${u} === ${n5.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 O;if(I.length>8){let F=(0,kv.schemaRefOrVal)(e,o.properties,"properties");O=(0,Av.isOwnProperty)(i,F,d)}else if(I.length)O=(0,Si.or)(...I.map((F)=>Si._`${d} === ${F}`));else O=Si.nil;if(g.length)O=(0,Si.or)(O,...g.map((F)=>Si._`${(0,Av.usePattern)(n,F)}.test(${d})`));return(0,Si.not)(O)}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,kv.alwaysValidSchema)(e,r)){let O=i.name("valid");if($.removeAdditional==="failing")S(d,O,!1),i.if((0,Si.not)(O),()=>{n.reset(),f(d)});else if(S(d,O),!l)i.if((0,Si.not)(O),()=>i.break())}}function S(d,O,F){let Q={keyword:"additionalProperties",dataProp:d,dataPropType:kv.Type.Str};if(F===!1)Object.assign(Q,{compositeRule:!0,createErrors:!1,allErrors:!1});n.subschema(Q,O)}}};gk.default=t5});var ck=H((fk)=>{Object.defineProperty(fk,"__esModule",{value:!0});var o5=Iu(),bk=gi(),G6=tn(),wk=y6(),u5={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)wk.default.code(new o5.KeywordCxt(u,wk.default,"additionalProperties"));let e=(0,bk.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,bk.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},$)}}};fk.default=u5});var kk=H((Ak)=>{Object.defineProperty(Ak,"__esModule",{value:!0});var Uk=gi(),dv=R(),Dk=tn(),Sk=tn(),l5={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,Uk.allSchemaProperties)(r),$=l.filter((S)=>(0,Dk.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,Sk. 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 Ni;if(e.issues.length){let l=new(t?.Err??n)(e.issues.map(($)=>Zn($,u,dn())));throw ie(l,t?.callee),l}return e.value},wo=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,dn())));throw ie(l,t?.callee),l}return e.value},fo=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 Ni;return u.issues.length?{success:!1,error:new(n??Io)(u.issues.map((e)=>Zn(e,t,dn())))}:{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,dn())))}:{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)},S0=te(xn),re=(n)=>(i,r,o)=>{return mt(n)(i,r,o)},A0=re(xn),oe=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return xt(n)(i,r,t)},k0=oe(xn),ue=(n)=>async(i,r,o)=>{return xt(n)(i,r,o)},d0=ue(xn),ee=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return at(n)(i,r,t)},O0=ee(xn),le=(n)=>(i,r,o)=>{return at(n)(i,r,o)},L0=le(xn),ve=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return nr(n)(i,r,t)},N0=ve(xn),$e=(n)=>async(i,r,o)=>{return nr(n)(i,r,o)},y0=$e(xn);var ui={};Fi(ui,{xid:()=>E$,uuid7:()=>jG,uuid6:()=>WG,uuid4:()=>GG,uuid:()=>Wt,uppercase:()=>gI,unicodeEmail:()=>G0,undefined:()=>$I,ulid:()=>T$,time:()=>tI,string:()=>oI,sha512_hex:()=>hG,sha512_base64url:()=>xG,sha512_base64:()=>mG,sha384_hex:()=>zG,sha384_base64url:()=>RG,sha384_base64:()=>CG,sha256_hex:()=>_G,sha256_base64url:()=>MG,sha256_base64:()=>ZG,sha1_hex:()=>EG,sha1_base64url:()=>qG,sha1_base64:()=>VG,rfc5322Email:()=>JG,number:()=>Uo,null:()=>vI,nanoid:()=>q$,md5_hex:()=>BG,md5_base64url:()=>TG,md5_base64:()=>PG,mac:()=>h$,lowercase:()=>II,ksuid:()=>V$,ipv6:()=>R$,ipv4:()=>C$,integer:()=>eI,idnEmail:()=>XG,httpProtocol:()=>s$,html5Email:()=>pG,hostname:()=>QG,hex:()=>KG,guid:()=>Z$,extendedDuration:()=>yG,emoji:()=>z$,email:()=>M$,e164:()=>nI,duration:()=>_$,domain:()=>FG,datetime:()=>rI,date:()=>iI,cuid2:()=>P$,cuid:()=>B$,cidrv6:()=>x$,cidrv4:()=>m$,browserEmail:()=>HG,boolean:()=>lI,bigint:()=>uI,base64url:()=>Ie,base64:()=>a$});var B$=/^[cC][0-9a-z]{6,}$/,P$=/^[0-9a-z]+$/,T$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,E$=/^[0-9a-vA-V]{20}$/,V$=/^[A-Za-z0-9]{27}$/,q$=/^[a-zA-Z0-9_-]{21}$/,_$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,yG=/^[-+]?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})$`)},GG=Wt(4),WG=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,}$/,pG=/^[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])?)*$/,JG=/^(([^<>()\[\]\\.,;:\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,}))$/,G0=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,XG=G0,HG=/^[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])?)*$/,YG="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function z$(){return new RegExp(YG,"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 GI={major:4,minor:4,patch:3};var T=U("$ZodType",(n,i)=>{var r;n??(n={}),n._zod.def=i,n._zod.bag=n._zod.bag||{},n._zod.version=GI;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(H$(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)}}R(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)=>{T.init(n,i),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??iI(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)}),JI=U("$ZodGUID",(n,i)=>{i.pattern??(i.pattern=q$),$n.init(n,i)}),XI=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)}),HI=U("$ZodEmail",(n,i)=>{i.pattern??(i.pattern=E$),$n.init(n,i)}),YI=U("$ZodURL",(n,i)=>{$n.init(n,i),n._zod.check=(r)=>{try{let o=r.value.trim();if(!i.normalize&&i.protocol?.source===m$.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})}}}),PI=U("$ZodEmoji",(n,i)=>{i.pattern??(i.pattern=_$()),$n.init(n,i)}),pI=U("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=T$),$n.init(n,i)}),QI=U("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=p$),$n.init(n,i)}),FI=U("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=Q$),$n.init(n,i)}),KI=U("$ZodULID",(n,i)=>{i.pattern??(i.pattern=F$),$n.init(n,i)}),BI=U("$ZodXID",(n,i)=>{i.pattern??(i.pattern=K$),$n.init(n,i)}),TI=U("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=B$),$n.init(n,i)}),VI=U("$ZodISODateTime",(n,i)=>{i.pattern??(i.pattern=nI(i)),$n.init(n,i)}),qI=U("$ZodISODate",(n,i)=>{i.pattern??(i.pattern=a$),$n.init(n,i)}),EI=U("$ZodISOTime",(n,i)=>{i.pattern??(i.pattern=s$(i)),$n.init(n,i)}),_I=U("$ZodISODuration",(n,i)=>{i.pattern??(i.pattern=V$),$n.init(n,i)}),ZI=U("$ZodIPv4",(n,i)=>{i.pattern??(i.pattern=Z$),$n.init(n,i),n._zod.bag.format="ipv4"}),MI=U("$ZodIPv6",(n,i)=>{i.pattern??(i.pattern=M$),$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})}}}),zI=U("$ZodMAC",(n,i)=>{i.pattern??(i.pattern=z$(i.delimiter)),$n.init(n,i),n._zod.bag.format="mac"}),CI=U("$ZodCIDRv4",(n,i)=>{i.pattern??(i.pattern=C$),$n.init(n,i)}),RI=U("$ZodCIDRv6",(n,i)=>{i.pattern??(i.pattern=R$),$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 hI(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 (${G}.issues.length) {
if (${N} in input) {
payload.issues = payload.issues.concat(${G}.issues.map(iss => ({
`))}}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 w=e.issues.length,f=b._zod.check(e);if(f instanceof Promise&&$?.async===!1)throw new Ni;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 Ni;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 Ni;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}))}),jt=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),jt.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)}),BI=D("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=q$),$n.init(n,i)}),PI=D("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=B$),$n.init(n,i)}),TI=D("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=P$),$n.init(n,i)}),EI=D("$ZodULID",(n,i)=>{i.pattern??(i.pattern=T$),$n.init(n,i)}),VI=D("$ZodXID",(n,i)=>{i.pattern??(i.pattern=E$),$n.init(n,i)}),qI=D("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=V$),$n.init(n,i)}),_I=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=_$),$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 (${L} in input) {
payload.issues = payload.issues.concat(${W}.issues.map(iss => ({
...iss,
path: iss.path ? [${N}, ...iss.path] : [${N}]
path: iss.path ? [${L}, ...iss.path] : [${L}]
})));
}
}
if (${G}.value === undefined) {
if (${N} in input) {
newResult[${N}] = undefined;
if (${W}.value === undefined) {
if (${L} in input) {
newResult[${L}] = undefined;
}
} else {
newResult[${N}] = ${G}.value;
newResult[${L}] = ${W}.value;
}
`);else if(!x)f.write(`
const ${G}_present = ${N} in input;
if (${G}.issues.length) {
payload.issues = payload.issues.concat(${G}.issues.map(iss => ({
`);else if(!q)f.write(`
const ${W}_present = ${L} 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 ? [${L}, ...iss.path] : [${L}]
})));
}
if (!${G}_present && !${G}.issues.length) {
if (!${W}_present && !${W}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${N}]
path: [${L}]
});
}
if (${G}_present) {
if (${G}.value === undefined) {
newResult[${N}] = undefined;
if (${W}_present) {
if (${W}.value === undefined) {
newResult[${L}] = undefined;
} else {
newResult[${N}] = ${G}.value;
newResult[${L}] = ${W}.value;
}
}
`);else f.write(`
if (${G}.issues.length) {
payload.issues = payload.issues.concat(${G}.issues.map(iss => ({
if (${W}.issues.length) {
payload.issues = payload.issues.concat(${W}.issues.map(iss => ({
...iss,
path: iss.path ? [${N}, ...iss.path] : [${N}]
path: iss.path ? [${L}, ...iss.path] : [${L}]
})));
}
if (${G}.value === undefined) {
if (${N} in input) {
newResult[${N}] = undefined;
if (${W}.value === undefined) {
if (${L} in input) {
newResult[${L}] = undefined;
}
} else {
newResult[${N}] = ${G}.value;
newResult[${L}] = ${W}.value;
}
`)}f.write("payload.value = newResult;"),f.write("return payload;");let Q=f.compile();return(Y,G)=>Q(w,Y,G)},u,e=Nt,l=!kt.jitless,I=l&&y$.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 V0([],c,w,f,b,n)}return r(w,f)}});function L0(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,kn())))}),i}var Do=U("$ZodUnion",(n,i)=>{T.init(n,i),R(n._zod,"optin",()=>i.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),R(n._zod,"optout",()=>i.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),R(n._zod,"values",()=>{if(i.options.every((o)=>o._zod.values))return new Set(i.options.flatMap((o)=>Array.from(o._zod.values)));return}),R(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 L0(e,o,n,t);return Promise.all(e).then((l)=>{return L0(l,o,n,t)})}});function y0(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,kn())))});else i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:[],inclusive:!1});return i}var wg=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 y0(e,o,n,t);return Promise.all(e).then((l)=>{return y0(l,o,n,t)})}}),fg=U("$ZodDiscriminatedUnion",(n,i)=>{i.inclusive=!1,Do.init(n,i);let r=n._zod.parse;R(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}}),cg=U("$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 j0(r,$,I)});return j0(r,u,e)}});function WI(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=WI(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=WI(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=WI(i.value,r.value);if(!e.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(e.mergeErrorPath)}`);return n.value=e.data,n}var ce=U("$ZodTuple",(n,i)=>{T.init(n,i Line truncated
`)}f.write("payload.value = newResult;"),f.write("return payload;");let F=f.compile();return(Q,W)=>F(w,Q,W)},u,e=Gt,l=!Nt.jitless,I=l&&j$.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 h0([],c,w,f,b,n)}return r(w,f)}});function Y0(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,dn())))}),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 Y0(e,o,n,t);return Promise.all(e).then((l)=>{return Y0(l,o,n,t)})}});function Q0(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,dn())))});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 Q0(e,o,n,t);return Promise.all(e).then((l)=>{return Q0(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 F0(r,$,I)});return F0(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 F0(n,i,r){let o=new Map,t;for(let l of i.issues)if(l.code==="unrecognized_keys"){t??(t=l);for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).l=!0}}else n.issues.push(l);for(let l of r.issues)if(l.code==="unrecognized_keys")for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).r=!0}else n.issues.push(l);let u=[...o].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(u.length&&t)n.issues.push({...t,keys:u});if(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 ke=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 k in I){if(k==="$ref"||k==="allOf")continue;if(!(k in g))delete I[k]}if(c.$ref&&f.def)for(let k in I){if(k==="$ref"||k==="allOf")continue;if(k in f.def&&JSON.stringify(I[k])===JSON.stringify(f.def[k]))delete I[k]}}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 vW={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dw=(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=vW[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}))]}},Nw=(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=$},Lw=(n,i,r,o)=>{r.type="boolean"},yw=(n,i,r,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},jw=(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),Xp(i)}clear(){this._buffer=void 0}}function Xp(n){return DD.parse(JSON.parse(n))}function wk(n){return JSON.stringify(n)+`
`}class V6{constructor(n=fk.stdin,i=fk.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=wk(n);if(this._stdout.write(r))i();else this._stdout.once("drain",i)})}}import{dirname as x4,join as _K}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 du 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 qr 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 ki extends Zi{name="TimeoutError";request;constructor(n){super(`Request timed out: ${n.method} ${n.url}`);this.request=n}}var E6=(()=>{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})(),ck=typeof globalThis.AbortController==="function",kv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",Uk=typeof globalThis.ReadableStream==="function",Dk=typeof globalThis.FormData==="function",dv=["get","post","put","patch","head","delete"],Hp=()=>{return};Hp();var Sk={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Er=2147483647,Ak=40,Nv=Symbol("stop");class Lv{options;constructor(n){this.options=n}}var Ok=(n)=>new Lv(n),kk={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},dk={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 yv=new TextEncoder,Yp=(n)=>{if(!n)return 0;if(n instanceof FormData){let i=0;for(let[r,o]of n)i+=Ak,i+=yv.encode(`Content-Disposition: form-data; name="${r}"`).byteLength,i+=typeof o==="string"?yv.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 yv.encode(n).byteLength;if(n instanceof URLSearchParams)return yv.encode(n.toString()).byteLength;return 0},Nk=(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)}}))},Lk=(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(Nk(n.body,o,i),r)},yk=(n,i,r)=>{if(!n.body)return n;let o=Yp(r??n.body);return new Request(n,{duplex:"half",body:Nk(n.body,o,i)})};var Hi=(n)=>n!==null&&typeof n==="object";var Pp=Symbol("replaceOption"),_6=(n)=>Hi(n)&&n[Pp]===!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 Cr(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 $F}from"node:fs";import{randomBytes as IF}from"node:crypto";import{randomBytes as Bd}from"node:crypto";var GQ=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),WQ=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:GQ.optional()}),JQ=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),XQ=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:JQ.optional()}),Ud=v.object({user:WQ,tenant:XQ}),HQ=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(),YQ=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(),Dd=v.object({user:HQ,session:YQ}),_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()}),Sd=v.object({rules:v.array(_v),hasPendingDeletes:v.boolean().default(!1)}),PQ=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(PQ).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),Ad=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)}),Od=v.object({articles:v.array(Pu),total:v.number().optional()}),pQ=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),QQ=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(),FQ=v.enum(["assisted","semi_automatic","fully_automatic"]),cd=v.object({id:v.string(),url:v.string().url()}).passthrough(),pu=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:FQ,incomingDocumentWebhook:cd,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:cd,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),l4=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:WF(n),attachments:MN(n,{summary:!0}).attachments,aiResult:t$(n),manualResult:Et(n)?.value,hints:Dt({amountMentions:PN(o,["金额","合计","税率"],8),partyMentions:PN(o,["买方","卖方","甲方","乙方","收款"],8)})}}function MN(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)y4(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 dF(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=hr(l);if(!I)return;let g=q(I.runtimeRuleId)??q(I.runtimeId)??q(I.id)??q(I.ruleId),b=q(I.ruleCode)??q(I.code)??(g?HF(g):void 0),w=Dt({runtimeRuleId:g,ruleCode:b,versionNumber:jF(I.versionNumber)??n.ruleSetVersionNumber,scope:q(I.scope),strictness:q(I.strictness),appliedAnalysis:I.appliedAnalysis??I.analysis??I.reasoning,checkResult:I.checkResult??I.result??I.decision,findings:I.findings??I.riskPoints??I.evidence,sourcePath:`${t}.${$}`}),f=JSON.stringify(w);if(!o.has(f))o.add(f),r.push(w)});return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,ruleSetVersionNumber:n.ruleSetVersionNumber,count:r.length,rules:r}}function y4(n,i,r,o){if(Array.isArray(n)){n.forEach((u,e)=>y4(u,`${i}.${e}`,r,o));return}let t=hr(n);if(!t)return;if(NF(t,i)){let u=Dt({path:i,fieldPath:i,kind:LF(i,t),fileName:q(t.fileName)??q(t.filename)??q(t.name)??q(t.originalName),mimeType:q(t.mimeType)??q(t.mimetype)??q(t.contentType),fileId:q(t.fileId)??q(t.id)??q(t.attachmentId),ossPath:q(t.ossPath)??q(t.ossKey)??q(t.key),url:q(t.url)??q(t.signedUrl)??q(t.downloadUrl)??q(t.previewUrl),invoiceId:q(t.invoiceId),sourceField:q(t.fieldName)??q(t.label)}),e=JSON.stringify(u);if(!o.has(e))o.add(e),r.push(u)}for(let[u,e]of Object.entries(t))y4(e,`${i}.${u}`,r,o)}function NF(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 LF(n,i){let r=`${n} ${q(i.type)??""}`.toLowerCase();if(r.includes("invoice")||r.includes("发票"))return"invoice";if(r.includes("receipt"))return"receipt";return"attachment"}function n$(n,i){if(!n)return;for(let r of i){let o=zi(n,r);if(o!==void 0)return o}return}function YN(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 yF(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 hr(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 GF(n){let i=[];return j4(n,"document",i),i}function j4(n,i,r){if(Array.isArray(n)){n.forEach((e,l)=>j4(e,`${i}.${l}`,r));return}let o=hr(n);if(!o)return;let t=q(o.label)??q(o.name)??q(o.title)??q(o.fieldName),u=o.value??o.displayValue??o.text??o.content;if(t&&u!==void 0&&typeof u!=="object")r.push(Dt({path:i,label:t,value:u,type:q(o.type)??q(o.fieldType)}));for(let[e,l]of Object.entries(o)){if(e==="attachments")continue;j4(l,`${i}.${e}`,r)}}function av(n,i){return n.find((o)=>{let t=q(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 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: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 Nw=(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 Aj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yw=(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=Aj[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}))]}},Gw=(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=$},Ww=(n,i,r,o)=>{r.type="boolean"},jw=(n,i,r,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},pw=(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),VQ(i)}clear(){this._buffer=void 0}}function VQ(n){return GD.parse(JSON.parse(n))}function Od(n){return JSON.stringify(n)+`
`}class _6{constructor(n=Ld.stdin,i=Ld.stdout){this._stdin=n,this._stdout=i,this._readBuffer=new q6,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=Od(n);if(this._stdout.write(r))i();else this._stdout.once("drain",i)})}}import{dirname as e0,join as IP}from"node:path";import{fileURLToPath as gP}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 yu 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 _r 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 ki 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})(),Nd=typeof globalThis.AbortController==="function",Gv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",yd=typeof globalThis.ReadableStream==="function",Gd=typeof globalThis.FormData==="function",Wv=["get","post","put","patch","head","delete"],qQ=()=>{return};qQ();var Wd={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Zr=2147483647,jd=40,jv=Symbol("stop");class pv{options;constructor(n){this.options=n}}var pd=(n)=>new pv(n),Jd={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},Xd={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,_Q=(n)=>{if(!n)return 0;if(n instanceof FormData){let i=0;for(let[r,o]of n)i+=jd,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},Hd=(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)}}))},Yd=(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(Hd(n.body,o,i),r)},Qd=(n,i,r)=>{if(!n.body)return n;let o=_Q(r??n.body);return new Request(n,{duplex:"half",body:Hd(n.body,o,i)})};var Xi=(n)=>n!==null&&typeof n==="object";var ZQ=Symbol("replaceOption"),z6=(n)=>Xi(n)&&n[ZQ]===!0?{isReplace:!0,value:n.value}:{isReplace:!1,value:n};var ju=(...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()}),EF=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()}),VF=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:VF.optional()}),yO=v.object({user:EF,tenant:qF}),_F=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(),ZF=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:_F,session:ZF}),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)}),MF=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(MF).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),jO=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)}),pO=v.object({articles:v.array(Ku),total:v.number().optional()}),zF=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),CF=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(),RF=v.enum(["assisted","semi_automatic","fully_automatic"]),NO=v.object({id:v.string(),url:v.string().url()}).passthrough(),Bu=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:RF,incomingDocumentWebhook:NO,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:NO,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),I4=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:kt({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:tN(n,{summary:!0}).attachments,aiResult:u$(n),manualResult:Zt(n)?.value,hints:kt({amountMentions:ZL(o,["金额","合计","税率"],8),partyMentions:ZL(o,["买方","卖方","甲方","乙方","收款"],8)})}}function tN(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)Y4(e,u,o,t);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,count:o.length,attachments:i.summary?o.map((u)=>kt({path:u.path,kind:u.kind,fileName:u.fileName,mimeType:u.mimeType,fileId:u.fileId,sourceField:u.sourceField})):o}}function _K(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=V(I.runtimeRuleId)??V(I.runtimeId)??V(I.id)??V(I.ruleId),b=V(I.ruleCode)??V(I.code)??(g?aK(g):void 0),w=kt({runtimeRuleId:g,ruleCode:b,versionNumber:CK(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 Y4(n,i,r,o){if(Array.isArray(n)){n.forEach((u,e)=>Y4(u,`${i}.${e}`,r,o));return}let t=sr(n);if(!t)return;if(ZK(t,i)){let u=kt({path:i,fieldPath:i,kind:MK(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))Y4(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} ${V(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 _L(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 kt(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 Q4(n,"document",i),i}function Q4(n,i,r){if(Array.isArray(n)){n.forEach((e,l)=>Q4(e,`${i}.${l}`,r));return}let o=sr(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(kt({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;Q4(l,`${i}.${e}`,r)}}function i$(n,i){return n.find((o)=>{let t=V(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){VF(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>_F)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 oL(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>qF||u>EF)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 uL(){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 P(n,i={}){gB(n,i);let r=`${JSON.stringify(n,null,2)}
`;if(i.outputFile){lB(i.outputFile,r),console.log(JSON.stringify({outputFile:i.outputFile,bytes:Buffer.byteLength(r,"utf-8")},null,2));return}console.log(r.trimEnd())}function gB(n,i={}){if(i.allowFull||i.outputFile)return;let r=Buffer.byteLength(JSON.stringify(n),"utf-8");if(r>IB)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 cN(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>vB||u>$B)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 p(n){return{allowFull:_(n.full)===!0,outputFile:U(n.outputFile)??U(n["output-file"])}}function UN(){console.log(`seal-use CLI
Usage:
seal-use version
@@ -176,23 +176,31 @@ 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 Cr(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 mr(n,i,r,o),t)}async function mr(n,i,r,o){let t=Vu.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 eL(n,i,r,o,t){if(n==="summary"){let u=await mr("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 $L(n,i,r){if(n==="diagnose"){B(await MF(i));return}if(n==="hose-link"){let o=ln(r.options.expire)??7200;B(await sk(i,o));return}throw Error(`Unknown auth command: ${n??""}. Run 'seal-use help' for available commands.`)}async function MF(n){if(n.source.type!=="hose"){let c=await An(n),S=await pi(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}]}}Xv(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},Et())}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={}){P(await no(n,i,r,o),t)}async function no(n,i,r,o){let t=_u.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 DN(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 查看最近记录。`);P(u,p(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"])},p(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)},p(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:_(t.options.includeBridge)},p(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)},p(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:_(t.options.latest),fields:U(t.options.fields),limit:en(t.options.limit),includeBridge:_(t.options.includeBridge)},p(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:_(t.options.summary)},p(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},p(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},p(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:_(t.options.summary)},p(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:_(t.options.summary)},p(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)},p(t.options));return}throw Error(`Unknown approval-runs command: ${n??""}. Run 'seal-use help' for available commands.`)}async function kN(n,i,r){if(n==="diagnose"){P(await bB(i));return}if(n==="hose-link"){let o=en(r.options.expire)??7200;P(await vO(i,o));return}throw Error(`Unknown auth command: ${n??""}. Run 'seal-use help' for available commands.`)}async function bB(n){if(n.source.type!=="hose"){let c=await kn(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:
- ${On}
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")??w,d=f??w,Q=Un(n,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,Y={id:k,name:d,seal:{url:Q,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)Xv(k),await xr(Y);let G=e4();UL(G,{recursive:!0,mode:448});let N=SL(G,`${P4(k)}.json`);if(cL(N)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${N}. Pass "overwrite": true to replace it.`);DL(N,`${JSON.stringify(Y,null,2)}
`,{mode:384}),B({id:k,name:d,corpId:w,domain:b,staffId:S,verified:g,path:N})}async function xF(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=aN(n,"expiresIn")??2592000,t=n.force===!0||n.verify===!1?!1:!0,u=t?await sF(r,i):void 0;OL(n,{token:i,sealUrl:r,expiresIn:o,verify:t,remote:u})}async function aF(n,i,r){let o=await Hv(n),t=Xu(o.sealUrl,o.token),u=await pi(t),e={user:u.user,tenant:u.tenant};Yv(o.corpId,e.tenant),OL({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 OL(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,k={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}},d=e4();UL(d,{recursive:!0,mode:448});let Q=SL(d,`${P4(w)}.json`);if(cL(Q)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${Q}. Pass "overwrite": true to replace it.`);DL(Q,`${JSON.stringify(k,null,2)}
`,{mode:384}),B({id:w,name:k.name,tenantId:g,tenantSlug:I,verified:u,path:Q})}async function sF(n,i){let r=await nK(`${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 nK(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 kL(n,i){let r=await Hv(n),o=Xu(r.sealUrl,r.token),t=await pi(o);Yv(r.corpId,t.tenant);let u=await Rr(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 dL(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 iK}from"node:fs";async function NL(n,i,r,o,t,u){let e=n==="hosecloud"||!n,l=n==="hosecloud"?i:n,$=n==="hosecloud"?r:i;if(!e&&n!=="hosecloud")throw Error(`Unknown deploy target: ${n??""}. Currently supported: hosecloud`);if(l==="requirements"){await X("seal_deploy_hosecloud_requirements",o,t,{},J(u.options));return}if(l==="list"){await X("seal_deploy_hosecloud_list",o,t,{},J(u.options));return}if(l==="get"){let I=$??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(iK(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 eK}from"node:http";import{URL as rK}from"node:url";var LL={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.1",description:`Planned HTTP contract for the seal-use wrapped backend API.
- ${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,O=f??w,F=Un(n,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,Q={id:d,name:O,seal:{url:F,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)Fv(d),await io(Q);let W=$4();WN(W,{recursive:!0,mode:448});let L=pN(W,`${V4(d)}.json`);if(GN(L)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${L}. Pass "overwrite": true to replace it.`);jN(L,`${JSON.stringify(Q,null,2)}
`,{mode:384}),P({id:d,name:O,corpId:w,domain:b,staffId:S,verified:g,path:L})}async function SB(n){let i=dt(n,"token"),r=(Un(n,"sealUrl")??Un(n,"url")??"").replace(/\/+$/,"");if(!r)throw Error("Missing required JSON field: sealUrl");let o=$N(n,"expiresIn")??2592000,t=n.force===!0||n.verify===!1?!1:!0,u=t?await kB(r,i):void 0;XN(n,{token:i,sealUrl:r,expiresIn:o,verify:t,remote:u})}async function AB(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};Bv(o.corpId,e.tenant),XN({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 XN(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),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")??Ot(l?.providerUserId)??Ot(l?.id)??"seal",c=Un(n,"provider")??Ot(l?.provider)??Ot($?.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:Ot(l?.providerUserId),provider:c},auth:{refreshTtl:300}},O=$4();WN(O,{recursive:!0,mode:448});let F=pN(O,`${V4(w)}.json`);if(GN(F)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${F}. Pass "overwrite": true to replace it.`);jN(F,`${JSON.stringify(d,null,2)}
`,{mode:384}),P({id:w,name:d.name,tenantId:g,tenantSlug:I,verified:u,path:F})}async function kB(n,i){let r=await dB(`${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 dB(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 HN(n,i){let r=await Kv(n),o=Yu(r.sealUrl,r.token),t=await Qi(o);Bv(r.corpId,t.tenant);let u=await ar(o,{note:i});P({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 YN(n,i,r,o,t){if(n==="list"){await J("seal_delegation_list",r,o,{},p(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},p(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},p(t.options));return}throw Error(`Unknown delegation command: ${n??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as OB}from"node:fs";async function QN(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>
`+` • webhook (通用审批流回调): seal-use webhook <list|get|add|update|delete> --corp <corpId>
`+` • 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 J("seal_deploy_hosecloud_requirements",o,t,{},p(u.options));return}if(l==="list"){await J("seal_deploy_hosecloud_list",o,t,{},p(u.options));return}if(l==="get"){let I=$??U(u.options.signKey)??U(u.options["sign-key"]);if(!I)throw Error("Usage: seal-use deploy hosecloud get <sign-key>");await J("seal_deploy_hosecloud_get",o,t,{signKey:I},p(u.options));return}if(l==="status"){await J("seal_deploy_hosecloud_status",o,t,{},p(u.options));return}if(l==="configure"){let I=U(u.options.input),g=I?JSON.parse(OB(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,p(u.options));return}if(l==="sync"){let I=$??U(u.options.signKey)??U(u.options["sign-key"]);if(!I)throw Error("Usage: seal-use deploy hosecloud sync <sign-key>");await J("seal_deploy_hosecloud_sync",o,t,{signKey:I},p(u.options));return}throw Error(`Unknown deploy hosecloud action: ${l??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as WB}from"node:http";import{URL as NB}from"node:url";var FN={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.4",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" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Seal Home API Docs (v${m})</title>
<title>Seal Home API Docs (v${x})</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>\uD83E\uDDAD</text></svg>" />
<style>
body {
@@ -211,27 +219,39 @@ 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 rK(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:m,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"){uK(i,200,yL());return}if(e==="GET"&&u==="/openapi.json"){Sn(i,200,e$());return}if(e==="GET"&&u==="/health"){Sn(i,200,{status:"ok",version:m,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 An(b),f={...I};delete f.corp;let c=await Xn($,w,f,b);Sn(i,200,c);return}if(u.startsWith("/v1/")){if(await oK(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 oK(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 An(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 An(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 An(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 An(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 An(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 An(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 An(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 An(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 An(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 An(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 An($),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
\uD83D\uDE80 seal-use HTTP Server (v${m}) 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 WL(n){let i=ln(n.options.port)??ln(n.options.p),r=D(n.options.host)??D(n.options.h),o=await GL({port:i,host:r}),t=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}async function JL(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 XL(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 HL(n){let i=e$();B(i,{...J(n.options),allowFull:!0})}async function YL(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 pL(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 QL(n={}){let i=Yi(),r=bi(),o=Cr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n.corpId},Kt());console.log(`[probe] corp=${o.id} source=${o.source.type}`);let t=await xr(o);console.log("[probe] seal enterprise"),console.log(JSON.stringify(t,null,2));let u=await An(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 FL(n,i,r){let o=i??D(r.options.corp)??(n&&n!=="--corp"?n:void 0);await QL({corpId:o})}async function KL(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:rL,limit:u,offset:e},J(t.options));return}let l=await mr("seal_approval_rules_list",r,o,{limit:u,offset:e});oL(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 mr("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,qu(u),J(t.options));return}if(n==="get"){await X("seal_approval_rule_get",r,o,{...tL(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(_4(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 BL(n){EL(n.stateDir);let i=ar(n);if(i.running)return i;let r=n.launcher??{command:process.execPath,args:[n.entryFile]},o=lK(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 E4(t,`${o.pid}
`,{mode:384}),I$(b$(n),`started pid=${o.pid}`),{started:!0,...ar(n)}}function TL(n,i={}){let r=g$(n),o=_4(r);if(!o||!qL(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 qL(n,i){if(!wK(n))return!1;try{let r=vK("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 wK(n){try{return process.kill(n,0),!0}catch{return!1}}function g$(n){return VL(n.stateDir,"service.pid")}function b$(n){return VL(n.stateDir,"service.log")}function _4(n){if(!$K(n))return;let i=Number(gK(n,"utf8").trim());return Number.isInteger(i)&&i>0?i:void 0}function EL(n){IK(n,{recursive:!0,mode:448})}function I$(n,i){E4(n,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var Z4=cK(fK(),".config","seal-use");async function _L(n,i){let r=await _t(n,{appRoot:i.appRoot,entryFile:i.entryFile,stateDir:Z4,version:m,launcher:i.launcher});if(r!==void 0)B(r)}import{existsSync as UK,readFileSync as ZL}from"node:fs";async function ML(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=qn(t.options.packageIds)??qn(t.options["package-ids"])??(b?[b]:void 0),f=qn(t.options.flowIds)??qn(t.options["flow-ids"])??qn(t.options.documentSn)??qn(t.options["document-sn"]),c=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:qn(t.options.requestIds)??qn(t.options["request-ids"]),workflowTypeId:D(t.options.workflowTypeId)??D(t.options["workflow-type-id"]),flowStatusList:qn(t.options.flowStatusList)?.map(Number)??qn(t.options["flow-status-list"])?.map(Number),businessCodes:qn(t.options.businessCodes)??qn(t.options["business-codes"]),documentType: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:qn(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(!UK(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 $y}from"node:fs";import{join as w$}from"node:path";import{existsSync as M4,mkdirSync as ry,rmSync as WK,writeFileSync as JK}from"node:fs";import{homedir as oy}from"node:os";import{dirname as XK,join as z4}from"node:path";var zL=`---
</html>`}async function Jn(n,i,r,o){let t=n.handler;return t(i,r,{corp:o})}async function BN(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 NB(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"){GB(i,200,KN());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=C4($),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),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(!$){$$(i,404,`Tool not found: '${l}'`);return}let I=await I$(n)||{},g=hn(n,t,I),b=Nn(g),w=await kn(b),f={...I};delete f.corp;let c=await Jn($,w,f,b);Sn(i,200,c);return}if(u.startsWith("/v1/")){if(await yB(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 yB(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 kn(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 kn(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 kn(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 kn(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 kn(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 kn(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 kn(g);if(!$){let w=Gn("seal_approval_run_get"),f=await Jn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="attachments"){let w=Gn("seal_approval_run_attachments_get"),f=await Jn(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 Jn(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 Jn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="result"){let w=Gn("seal_approval_run_result_get"),f=await Jn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}}}if(r==="GET"&&o==="/v1/approval-runs"){let e=hn(n,t,u),l=Nn(e),$=await kn(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 kn(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 kn(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 kn($),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 TN(n){let i=en(n.options.port)??en(n.options.p),r=U(n.options.host)??U(n.options.h),o=await PN({port:i,host:r}),t=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}async function EN(n,i,r,o){if(n==="config"||n==="get"){await J("seal_llm_config_get",i,r,{},p(o.options));return}if(n==="providers"||n==="list"){await J("seal_llm_providers_list",i,r,{},p(o.options));return}throw Error(`Unknown llm command: ${n??""}. Run 'seal-use help' for available commands.`)}async function VN(n,i){if(n==="config"||n==="json"){R4();return}await h4()}function R4(){P({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function qN(n){let i=v$();P(i,{...p(n.options),allowFull:!0})}async function _N(n,i,r,o){if(n==="available"){await J("seal_permissions_available_list",i,r,{},p(o.options));return}if(n==="configs"||n==="list"){await J("seal_permissions_configs_list",i,r,{},p(o.options));return}throw Error(`Unknown permissions command: ${n??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as ZN}from"node:fs";async function MN(n,i,r,o,t,u,e){if(!n||n==="get"){await J("seal_preference_get",t,u,{},p(e.options));return}if(n==="decision"){if(i==="update"||!i){let l=U(e.options.input),$=l?JSON.parse(ZN(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,$,p(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},p(e.options));return}if(i==="policies"){if(r==="list"||!r){await J("seal_preference_thinking_depth_policies_list",t,u,{},p(e.options));return}if(r==="upsert"){let l=U(e.options.input),$=l?JSON.parse(ZN(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,$,p(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},p(e.options));return}}}throw Error(`Unknown preference action: ${n??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function zN(n={}){let i=Hi(),r=Vn(),o=xr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n.corpId},Et());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 kn(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 CN(n,i,r){let o=i??U(r.options.corp)??(n&&n!=="--corp"?n:void 0);await zN({corpId:o})}async function RN(n,i,r,o,t){if(n==="count"){await J("seal_approval_rules_list",r,o,{countOnly:!0},p(t.options));return}if(n==="list"){if(_(t.options.count)){await J("seal_approval_rules_list",r,o,{countOnly:!0},p(t.options));return}let u=en(t.options.limit),e=en(t.options.offset);if(_(t.options.summary)){await J("seal_approval_rules_list",r,o,{fields:fN,limit:u,offset:e},p(t.options));return}let l=await no("seal_approval_rules_list",r,o,{limit:u,offset:e});cN(l,_(t.options.full)===!0),P(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 no("seal_approval_rules_clear",r,o,{dryRun:e,recode:_(t.options.recode)});if(!u&&e&&l&&typeof l==="object"){P({...l,nextCommand:`seal-use rules clear --corp ${o.id} --yes`},p(t.options));return}P(l,p(t.options));return}if(n==="versions"){await J("seal_approval_rule_versions_list",r,o,{},p(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),p(t.options));return}if(n==="get"){await J("seal_approval_rule_get",r,o,{...wN(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"])},p(t.options));return}if( Line truncated
`,{mode:384}),b$(r,`running pid=${process.pid}`);let o=()=>{if(x4(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 hN(n){sN(n.stateDir);let i=to(n);if(i.running)return i;let r=n.launcher??{command:process.execPath,args:[n.entryFile]},o=jB(r.command,[...r.args??[],"service","run"],{cwd:n.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});o.unref();let t=w$(n);return m4(t,`${o.pid}
`,{mode:384}),b$(f$(n),`started pid=${o.pid}`),{started:!0,...to(n)}}function mN(n,i={}){let r=w$(n),o=x4(r);if(!o||!aN(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$(f$(n),`stop requested pid=${o}`),i.quiet?void 0:{stopped:!0,pid:o}}function aN(n,i){if(!QB(n))return!1;try{let r=pB("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 QB(n){try{return process.kill(n,0),!0}catch{return!1}}function w$(n){return xN(n.stateDir,"service.pid")}function f$(n){return xN(n.stateDir,"service.log")}function x4(n){if(!JB(n))return;let i=Number(HB(n,"utf8").trim());return Number.isInteger(i)&&i>0?i:void 0}function sN(n){XB(n,{recursive:!0,mode:448})}function b$(n,i){m4(n,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var a4=KB(FB(),".config","seal-use");async function ny(n,i){let r=await Mt(n,{appRoot:i.appRoot,entryFile:i.entryFile,stateDir:a4,version:x,launcher:i.launcher});if(r!==void 0)P(r)}import{existsSync as BB,readFileSync as iy}from"node:fs";async function ty(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)},p(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(iy(l,"utf8")):void 0,I=U(t.options.input),g=I?JSON.parse(iy(I,"utf8")):oi(t.json),b=U(t.options.packageId)??U(t.options["package-id"]),w=qn(t.options.packageIds)??qn(t.options["package-ids"])??(b?[b]:void 0),f=qn(t.options.flowIds)??qn(t.options["flow-ids"])??qn(t.options.documentSn)??qn(t.options["document-sn"]),c=U(t.options.signKey)??U(t.options["sign-key"])??U(t.options.integration);await J("seal_simulation_batch_create",r,o,{mode:e,sourceSystem:e,flowIds:f,documentSn:f,rejectNodeName:U(t.options.rejectNode)??U(t.options["reject-node"])??null,thinkingDepthOverride:U(t.options.thinkingDepth)??U(t.options["thinking-depth"]),skipInvoiceGeneration:_(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:U(t.options.templateId)??U(t.options["template-id"]),schemaConfig:$,requestIds:qn(t.options.requestIds)??qn(t.options["request-ids"]),workflowTypeId:U(t.options.workflowTypeId)??U(t.options["workflow-type-id"]),flowStatusList:qn(t.options.flowStatusList)?.map(Number)??qn(t.options["flow-status-list"])?.map(Number),businessCodes:qn(t.options.businessCodes)??qn(t.options["business-codes"]),documentType:U(t.options.documentType)??U(t.options["document-type"]),startTime:en(t.options.startTime)??en(t.options["start-time"]),endTime:en(t.options.endTime)??en(t.options["end-time"]),status:qn(t.options.status),limit:en(t.options.limit),rawParams:g},p(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"])},p(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},p(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},p(t.options));return}if(n==="list"){await J("seal_simulation_batches_list",r,o,{limit:en(t.options.limit)},p(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},p(t.options));return}if(n==="templates"){await J("seal_simulation_templates_get",r,o,{},p(t.options));return}if(n==="integrations"){await J("seal_simulation_integrations_get",r,o,{},p(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(!BB(u))throw Error(`File not found: ${u}`);await J("seal_simulation_material_package_upload",r,o,{filePath:u},p(t.options));return}throw Error(`Unknown simulation command: ${n??""}. Run 'seal-use help' for available commands.`)}import{existsSync as ky}from"node:fs";import{join as c$}from"node:path";import{existsSync as s4,mkdirSync as fy,rmSync as hB,writeFileSync as mB}from"node:fs";import{homedir as cy}from"node:os";import{dirname as xB,join as n0}from"node:path";var ry=`---
name: seal-use
description: "v0.10.1: 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.4: 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.1
short-description: Seal tenant and Hose approval automation (v0.10.1)
version: 0.10.4
short-description: Seal tenant and Hose approval automation (v0.10.4)
---
# Seal Use (v0.10.1)
# Seal Use (v0.10.4)
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.
## Bootstrap & Installation (环境安装与自愈)
If \`seal-use\` or \`seal_cli\` is not installed on the system, the Agent should automatically install it via:
\`\`\`bash
# 国内高速安装(Gitea 镜像源,免代理、秒级完成)
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
# Global / GitHub Direct
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
\`\`\`
After installation, verify with:
\`\`\`bash
seal-use help
seal-use version
seal-use tools list
seal-use corps list
\`\`\`
## First Rules
@@ -262,7 +282,7 @@ seal-use tools list
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run \`seal-use delegation create --corp <corpId> --note '<enterprise>'\`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) AND a hyperlink.
- Packaged customer feedback → approval-rule remediation: read \`references/customer-feedback-rule-remediation.md\`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
- 模拟测试发布闭环: \`seal-use simulation create --mode hosecloud --flow-ids ... --corp <corpId>\` (合思指定单号) 或 \`--mode material_pack --package-ids ... --schema-config file.json\` (材料包导入), 支持多源系统 \`--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>\`, \`simulation wait <batchId>\` 轮询等待完成, \`simulation clean <batchId>\` 清理数据, \`simulation specifications\` 列出单据模板, \`simulation list\`/\`get\`/\`batch-records\` 查看批次与记录。创建前确认目标环境为测试环境。
- HoseCloud 部署与同步发布: \`seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>\`.
- Seal AI 智能审核发布到合思费控: \`seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>\`; read \`references/hose-enterprise-deploy.md\`.
- 审核决策偏好与思考深度: \`seal-use preference get --corp <corpId>\`, \`preference decision update --json '...' --corp <corpId>\`, \`preference thinking-depth set --default <medium|high> --corp <corpId>\`, \`preference thinking-depth policies <list|upsert|remove> --corp <corpId>\`.
- 审核大盘统计与去重分析: \`seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>\`, \`seal-use approval-runs count --corp <corpId>\`.
- User-facing 合思 authorization link (合思/易快报授权): \`seal-use auth hose-link --corp <corpId> --expire 7200\`; read \`references/hose-enterprise-auth.md\`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) AND a hyperlink.
@@ -273,6 +293,7 @@ seal-use tools 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
@@ -288,6 +309,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'
@@ -318,20 +340,22 @@ 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\`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
- \`references/hose-enterprise-deploy.md\`: Seal AI 智能审核发布到合思费控(添加/编辑配置、平台自动探测、一键同步与 EBot 节点发布)。
- \`references/approval-attachment-trace.md\`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。
- \`references/cli.md\`: 完整 CLI 命令清单。
## Safety
Rule, document, style preference, and publish actions mutate Seal configuration. Make the target enterprise explicit, show the intended payload, and verify after the write. Never send real \`enterprises/*.json\` files, tokens, signed URLs, or full raw documents to GitHub, tickets, logs, or chat unless the user explicitly requests a safe export.
`;var CL=`interface:
`;var oy=`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 RL=`# Rule Lightweight Queries
`;var uy=`# 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.
@@ -436,7 +460,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 hL=`# Approval Bad Case Catalog
`;var ey=`# 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.
@@ -486,371 +510,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 mL=`# Seal Use CLI Reference
Run from any directory after installing the global CLI:
\`\`\`bash
seal-use <command>
\`\`\`
Enterprise config lookup:
- If \`SEAL_USE_ENTERPRISES_DIR\` is set, only that directory is loaded.
- Otherwise \`./enterprises\` and \`~/.config/seal-use/enterprises\` are merged.
- User-level configs override same-ID local configs.
Enterprise selection is stateless by default. Commands that access an enterprise require
\`--corp <corpId>\` unless stateful mode is explicitly enabled:
\`\`\`bash
seal-use config mode stateful --corp <corpId>
seal-use corps switch <corpId>
seal-use config mode stateless
\`\`\`
The global mode is stored in \`~/.config/seal-use/config.json\`; set \`SEAL_USE_CONFIG_FILE\` to
override that path. The legacy \`current-corp\` file is not read.
## Top-Level Commands
\`\`\`bash
seal-use version
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use service <start|stop|restart|status>
seal-use http [--port 8787] [--host 127.0.0.1]
seal-use serve [--port 8787]
seal-use update
seal-use tools list
seal-use corps list [--corp <corpId>]
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
seal-use auth diagnose [--corp <corpId>]
seal-use auth hose-link [--corp <corpId>] [--expire 7200]
seal-use delegation list [--corp <corpId>]
seal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]
seal-use delegation revoke <tokenId> [--corp <corpId>]
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-use users reset-password <userId> [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> [--corp <corpId>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
seal-use permissions configs [--corp <corpId>]
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
seal-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>]
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 status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud sync <sign-key> [--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>]
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]
seal-use source config [--corp <corpId>]
seal-use tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
seal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]
seal-use approval-runs count --corp <corpId> [--status APPROVED]
seal-use approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]
seal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
seal-use approval-runs attachments <recordId> --corp <corpId>
seal-use approval-runs result <recordId> --corp <corpId> [--summary]
seal-use approval-runs url --corp <corpId>
seal-use approval-runs url <recordId> --corp <corpId>
seal-use approval-runs url --sourceDocumentSN <sourceDocumentSN> --corp <corpId>
seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sourceDocumentSN>]
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] --corp <corpId>
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp <corpId>
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" --corp <corpId>
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] --corp <corpId>
seal-use simulation clean <batchId> --corp <corpId>
seal-use simulation specifications [--integration <sign-key>] --corp <corpId>
seal-use simulation list [--limit 50] --corp <corpId>
seal-use simulation get <batchId> --corp <corpId>
seal-use simulation templates --corp <corpId>
seal-use simulation integrations --corp <corpId>
seal-use simulation package-upload <材料包.zip> --corp <corpId>
\`\`\`
## Fine-Grained Tools
\`seal-use version\` returns:
\`\`\`json
{
"name": "seal-use",
"version": "<package version>"
}
\`\`\`
\`seal-use service status\` returns the PID, version, state directory, PID file, and log file for the optional local background process.
\`seal-use update\` updates the git checkout, runs \`bun install\`, and restarts the local service if it was running.
Identity and session:
- \`seal-use auth diagnose --corp <corpId>\`
- \`seal_whoami\`
- \`seal_session_get\`
Approval rule maintenance:
- \`seal-use rules count [--corp <corpId>]\`
- \`seal-use rules list --summary [--corp <corpId>]\`
- \`seal-use rules clear [--corp <corpId>] [--dry-run|--yes]\`
- \`seal_approval_rules_list\`
- \`seal_approval_rules_clear\`
- \`seal_approval_rule_create\`
- \`seal_approval_rule_update\`
- \`seal_approval_rule_delete\`
- \`seal_approval_rule_versions_list\`
- \`seal_approval_rule_version_publish\`
Approval run lightweight queries:
- \`seal-use approval-runs get <recordId> --corp <corpId> --fields metadata\`
- \`seal-use approval-runs get <recordId> --corp <corpId> --summary\`
- \`seal-use approval-runs pick --corp <corpId> --sn <单号> --batch <batchId> --latest\`
- \`seal-use approval-runs document-summary <recordId> --corp <corpId>\`
- \`seal-use approval-runs cited-rules <recordId> --corp <corpId>\`
- \`seal-use approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary\`
- \`seal-use approval-runs attachments <recordId> --corp <corpId> --summary\`
- \`seal-use approval-runs result <recordId> --corp <corpId> --summary\`
- \`seal_approval_run_get\` with \`fields\`
- \`seal_approval_run_pick\`
- \`seal_approval_run_cited_rules_get\`
- \`seal_approval_run_document_summary_get\`
- \`seal_approval_run_attachments_get\`
- \`seal_approval_run_result_get\` with \`{"summary":true}\`
Approval knowledge documents:
- \`seal_approval_documents_list\`
- \`seal_approval_document_get\`
- \`seal_approval_document_create\`
- \`seal_approval_document_update\`
Approval search and context:
- \`seal_approval_search\`
- \`seal_approval_context_get\`
- \`seal-use rules get --corp <corpId> --version <number> --code '#0038'\`
- \`seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205\`
Style preferences:
- \`seal_approval_style_preferences_get\`
- \`seal_approval_style_preferences_update\`
Webhook integrations:
- \`seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]\`
- \`seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]\`
- \`seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]\`
- \`seal-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>]\`
- \`seal-use webhook delete <idOrName> --yes [--corp <corpId>]\`
- \`seal_webhook_list\`
- \`seal_webhook_get\`
- \`seal_webhook_add\`
- \`seal_webhook_update\`
- \`seal_webhook_delete\`
Webhook writes read the current AI approval config and POST the merged full config back to \`api/v1/agent/ai-approval/config\`, preserving non-Webhook integrations. List/get mask \`secret\` by default; add returns the generated secret once.
Approval runs, simulations, and Langfuse bridge:
- \`seal_approval_runs_search\`
- \`seal_approval_runs_summary\`
- \`seal_simulation_batch_records_get\`
- \`seal_simulation_batch_create\`
- \`seal_simulation_batches_list\`
- \`seal_simulation_batch_get\`
- \`seal_simulation_templates_get\`
- \`seal_simulation_integrations_get\`
- \`seal_approval_run_langfuse_bridge_get\`
## Common Examples
Add and verify a Hose enterprise:
\`\`\`bash
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use auth diagnose --corp <corpId>
\`\`\`
Force-write a Hose config without verification:
\`\`\`bash
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId","force":true}'
\`\`\`
Diagnose auth failures:
\`\`\`bash
seal-use auth diagnose --corp <corpId>
\`\`\`
The diagnostic stages are \`hose.openapi\`, \`hose.provisional\`, \`seal.sso\`, and \`seal.whoami\`. Tokens are omitted from output.
Search approval content:
\`\`\`bash
seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}'
\`\`\`
Get aggregated approval context:
\`\`\`bash
seal-use tool seal_approval_context_get --corp <corpId> --json '{"documentLimit":20}'
\`\`\`
Create a draft approval rule:
\`\`\`bash
seal-use tool seal_approval_rule_create --corp <corpId> --json '{"description":"规则描述","scope":"适用场景","strictness":"SHOULD_FOLLOW"}'
\`\`\`
Update an approval document:
\`\`\`bash
seal-use tool seal_approval_document_update --corp <corpId> --json '{"documentId":"doc-id","content":"Markdown 内容"}'
\`\`\`
Summarize one local date:
\`\`\`bash
seal-use approval-runs summary --corp <corpId> --date 2026-06-09 --timezone Asia/Shanghai --limit 100
\`\`\`
Find a run and include Langfuse bridge rows:
\`\`\`bash
seal-use approval-runs search --corp <corpId> --query <sourceDocumentSN> --limit 20 --includeBridge true
\`\`\`
Resolve Langfuse trace/session hints:
\`\`\`bash
seal-use approval-runs bridge --corp <corpId> --sourceDocumentSN <sourceDocumentSN>
\`\`\`
模拟测试批次(模拟发布闭环)创建与查询:
\`\`\`bash
# 合思指定单号: 创建批次(响应只含 batchId)
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" --reject-node 财务 --thinking-depth medium --skip-invoice-generation --corp <corpId>
# 材料包导入: 先上传材料包 ZIP(服务端解析并返回 schemaConfig), 再用返回的 id 发起
seal-use simulation package-upload 测试材料包.zip --corp <corpId>
seal-use simulation create --mode material_pack --package-ids <materialPackageId> --template-id conference_reimbursement_v1 --schema-config schema.json --corp <corpId>
# 预留: 其他模式参数通过 --json 透传(如时间范围 startTime/endTime)
seal-use simulation create --mode hosecloud --flow-ids "B26017701" --json '{"startTime":0,"endTime":0}' --corp <corpId>
# 创建后轮询批次状态与记录
seal-use simulation list --limit 50 --corp <corpId>
seal-use simulation get <batchId> --corp <corpId>
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation templates --corp <corpId>
seal-use simulation integrations --corp <corpId>
\`\`\`
## Write Operation Payloads
Create a rule:
\`\`\`json
{
"description": "规则描述",
"scope": "适用场景",
"strictness": "MUST_FOLLOW | SHOULD_FOLLOW | SUGGESTION"
}
\`\`\`
Update a rule:
\`\`\`json
{
"ruleId": "rule-id",
"description": "可选",
"scope": "可选",
"strictness": "SHOULD_FOLLOW"
}
\`\`\`
Publish a rule version:
\`\`\`json
{
"versionName": "版本名称"
}
\`\`\`
Create a document:
\`\`\`json
{
"title": "标题",
"purpose": "用途",
"content": "Markdown 内容",
"contentType": "text/markdown",
"status": "可选",
"scenarios": ["场景"],
"tags": ["标签"]
}
\`\`\`
Update a document:
\`\`\`json
{
"documentId": "doc-id",
"title": "可选",
"purpose": "可选",
"content": "可选",
"enabled": true,
"scenarios": ["可选"],
"tags": ["可选"]
}
\`\`\`
Update style preferences:
\`\`\`json
{
"tone": "可选",
"language": "可选",
"detailLevel": "可选",
"outputFormat": "可选",
"examples": ["可选"],
"prohibitedPhrases": ["可选"],
"customInstructions": "可选"
}
\`\`\`
## Failure Handling
- CLI commands are short-lived processes. In-memory auth/search caches only live for that single process. Use \`seal-use service restart\` after updates so the optional local service picks up new code.
- If no run is found by \`sourceDocumentSN\`, retry with \`sourceDocumentId\` or a broader \`query\`.
- If date-based summaries look wrong, pass \`--timezone Asia/Shanghai\` and an explicit \`--date\`.
- If \`langfuseTraceId\` is missing, use \`langfuseSessionFallback\`.
- If a write operation fails, report the raw JSON error and do not retry with guessed payloads.
`;var xL="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest\nseal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest\nseal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-use approval-runs get <recordId> --corp <corpId> --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-use approval-runs get <recordId> --corp <corpId> --fields metadata\nseal-use approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary\nseal-use approval-runs get <recordId> --corp <corpId> --fields result.summary,result.decision,result.riskPoints\nseal-use approval-runs get <recordId> --corp <corpId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-use approval-runs document-summary <recordId> --corp <corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-use approval-runs cited-rules <recordId> --corp <corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id <recordId> --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\nseal-use approval-runs attachments <recordId> --corp <corpId> --summary\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-use approval-runs result <recordId> --corp <corpId> --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Output Discipline\n\nIf a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.\n";var aL=`# Approval Attachment Trace Investigation
`;var ly="# 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> [--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] [--outputLine 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.
@@ -1071,7 +731,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 sL=`# Customer Feedback Rule Remediation
`;var Iy=`# 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.
@@ -1235,130 +895,7 @@ Return a compact report containing:
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
`;var ny=`# Enterprise Onboarding
Read this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.
## Start With Discovery
Run this before asking for setup parameters:
\`\`\`bash
seal-use version
seal-use corps list
\`\`\`
- If the target enterprise is listed, match the user's human enterprise name to its returned \`id\` and use that value as \`--corp\` on every command. Do not ask the user for \`corpId\`.
- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.
- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”
Do not open with a JSON template or a list of internal fields.
All command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.
## Keep Two Concepts Separate
Classify both the enterprise identity origin and how the current credential was acquired:
| Enterprise identity origin | Credential material the user may have | Meaning |
| --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose \`appKey\` + \`appSecurity\` | Stable, refreshable standard integration |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |
| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |
| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |
Credential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When \`whoami\` returns provider metadata, preserve it and use it to describe the tenant accurately.
## Parameter Ownership
Ask the user only for information that cannot be discovered safely:
| Field | Owner and behavior |
| --- | --- |
| \`appKey\`, \`appSecurity\` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |
| \`domain\` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |
| Enterprise name and \`corpId\` | Discover from the credential response or Seal \`whoami\`. Do not ask the user to invent or locate them first. |
| Administrator and \`staffId\` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |
| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal \`whoami\`. |
| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |
## Route 1: Standard Hose Credentials
This is the preferred durable route for a Hose-sourced tenant. Read \`hose-enterprise-init.md\`, then use:
\`\`\`bash
seal-use corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
\`\`\`
The CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with \`staffName\`, \`staffPhone\`, or the selected \`staffId\` internally. After creation, run:
\`\`\`bash
seal-use auth diagnose --corp <discovered-id>
\`\`\`
Do not ask for \`domain\`, \`corpId\`, or \`proxyStaffBizId\` up front. For a dedicated/private Hose deployment, add \`domain\` only after standard probing reports that it cannot find the enterprise.
## Route 2: Incoming Assistance Link
First distinguish the link by its host and purpose:
- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.
- \`seal-use auth hose-link\` and \`seal-use delegation create\` generate links for an enterprise that is already configured. \`seal-use corps add-link <url>\` imports a received Hose/合思 \`thirdparty.html\` assistance link and verifies the resulting Seal tenant.
Use the direct import route when the incoming link is an HTTPS \`thirdparty.html\` URL from a supported \`ekuaibao.com\` or \`hosecloud.com\` domain:
\`\`\`bash
seal-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home" [--name "企业名称"]
\`\`\`
The command parses \`accessToken\` and \`ekbCorpId\`, exchanges the temporary Hose token at the target Seal tenant, verifies \`/api/v1/auth/me\`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use \`--overwrite\` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use \`seal-use delegation create --from-link <url> [--note ...]\`.
Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it.
## Route 3: Browser F12 cURL
When the user needs capture instructions, give these concrete steps:
1. Open the already signed-in Hose or Seal page.
2. Open browser developer tools: \`F12\` on many keyboards, or \`Option+Command+I\` on macOS.
3. Open **Network**, then select **Fetch/XHR**.
4. Refresh the page or perform one ordinary read-only business action.
5. Choose a successful business API request from the relevant tenant, not analytics, static assets, upload, delete, publish, or logout requests.
6. Right-click it and choose **Copy → Copy as cURL**.
7. Send that complete cURL only to the local trusted Agent handling setup.
When receiving cURL:
1. Treat the entire cURL as a secret. Do not echo it, execute it blindly, paste it into another service, or store it in repository files.
2. Parse it as data. Extract the request host, path, \`Authorization\` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3. Classify whether the captured request is to Hose or Seal. A Seal request with \`Authorization: Bearer ...\` can supply \`sealUrl\` and a session token even when the user's identity origin is Hose.
4. Verify with the narrowest read-only identity endpoint available. For a Seal Bearer session, verify \`/api/v1/auth/me\` through \`seal-use corps add-seal\`; use returned provider metadata to retain the actual origin.
5. Persist only the normalized minimum configuration needed by seal-use. Do not preserve the raw cURL, unrelated headers, request body, cookies, or signed URL.
For a verified Seal Bearer captured from cURL, the existing CLI route is:
\`\`\`bash
seal-use corps add-seal --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
\`\`\`
The current CLI has no raw-cURL import command and \`add-seal\` requires a Bearer token. If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
## Verify and Hand Off
After adding an enterprise:
\`\`\`bash
seal-use corps list
seal-use corps current --corp <discovered-id>
seal-use auth diagnose --corp <discovered-id> # Hose source
\`\`\`
Report the human enterprise name, identity provider, credential method, and whether verification succeeded. Do not expose internal IDs unless they help with troubleshooting. Do not perform approval, rule, document, simulation, publishing, or other business mutations just because onboarding succeeded; continue only with the user's requested task and its normal confirmation rules.
If a temporary assistance-link or browser session expires, explain that it must be renewed or recaptured. Recommend standard Hose app credentials when the user needs durable unattended access.
`;var iy=`# Hose Enterprise Auth
`;var gy="# 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.
@@ -1423,7 +960,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 ty=`# Hose Enterprise Initialization & Automated Discovery
`;var wy=`# 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.
@@ -1529,12 +1066,12 @@ seal-use corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var uy={"SKILL.md":zL,"agents/openai.yaml":CL,"references/rule-lightweight.md":RL,"references/approval-bad-cases.md":hL,"references/cli.md":mL,"references/approval-run-lightweight.md":xL,"references/approval-attachment-trace.md":aL,"references/customer-feedback-rule-remediation.md":sL,"references/enterprise-onboarding.md":ny,"references/hose-enterprise-auth.md":iy,"references/hose-enterprise-init.md":ty};function ey(){return uy["SKILL.md"]||""}function zu(){return z4(oy(),".agents","skills","seal-use")}function ly(){return z4(oy(),".agents","skills","seal-home")}function vy(){let n=ly();if(M4(n))try{return WK(n,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function C4(n=zu()){vy(),ry(n,{recursive:!0});let i=[];for(let[r,o]of Object.entries(uy)){let t=z4(n,r);ry(XK(t),{recursive:!0}),JK(t,o,"utf8"),i.push(r)}return{targetDir:n,files:i}}function R4(){let n=ly(),i=zu(),r=M4(n),o=M4(i);if(r||o)return vy(),C4(i),{synced:!0,targetDir:i};return{synced:!1}}function Iy(n,i,r){if(n==="dump"||n==="cat"||n==="show"){process.stdout.write(`${ey()}
`);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=C4(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:$y(w$(o,"SKILL.md"))},local:{dir:t,installed:$y(w$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${n}. Run 'seal-use help' for available commands.`)}async function gy(n,i){if(n==="config"){B(await xr(i));return}throw Error(`Unknown source command: ${n??""}. Run 'seal-use help' for available commands.`)}async function by(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 wy(){B(Vu.map((n)=>({name:n.name,description:n.description})))}import{chmodSync as HK,mkdirSync as YK,renameSync as h4,rmSync as PK,unlinkSync as Sy,writeFileSync as fy}from"node:fs";import{dirname as pK,join as cy}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 Ay="yunyingk/seal-use",sr="yunyingk/seal-home";var QK="SEAL_USE_GITHUB_REPO",FK="SEAL_HOME_GITHUB_REPO";async function Oy(n,i={}){let r={appRoot:n.appRoot,entryFile:n.entryFile,stateDir:Z4,version:m,launcher:n.launcher},o=i.repo||process.env[QK]?.trim()||process.env[FK]?.trim()||Ay,t=i.targetVersion?.trim(),u=t&&t.toLowerCase()!=="latest"?t:void 0;if(u){let G=u.replace(/^v/,""),N=ky(G,m);if(N<0){B({updated:!1,currentVersion:m,targetVersion:G,mode:f$()?"binary":"source",message:`Cannot downgrade seal-use from v${m} to older version v${G}. Updates must be forward-only.`});return}if(N===0&&!i.force){B({updated:!1,currentVersion:m,targetVersion:G,mode:f$()?"binary":"source",message:`seal-use is already at version v${m}. Use --force to reinstall.`});return}}if(i.changelogOnly){let G=await m4(o,i.limit??10);B({currentVersion:m,totalQueried:G.length,releases:G.map((N)=>({version:N.version,tagName:N.tagName,publishedAt:N.publishedAt,author:N.author,releaseNotes:N.notes,releaseUrl:N.htmlUrl,isCurrent:N.version===m,isNewer:Cu(N.version,m)}))});return}if(!f$()){if(i.checkOnly){let N=await m4(o,30),E=N[0],x=E?.version??m,yn=N.find((un)=>un.version===m),Wn=Cu(x,m),On=N.filter((un)=>Cu(un.version,m));B({updated:!1,updateAvailable:Wn,currentVersion:m,currentVersionPublishedAt:yn?.publishedAt,latestVersion:x,latestVersionPublishedAt:E?.publishedAt,behindCount:On.length,pendingReleases:On.map((un)=>({version:un.version,tagName:un.tagName,publishedAt:un.publishedAt,author:un.author,releaseNotes:un.notes,releaseUrl:un.htmlUrl})),releaseNotes:E?.notes??"",releaseUrl:E?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let G=ar(r).running;if(G)await _t("stop",r);try{Dy("git",["-C",n.appRoot,"pull","--ff-only"])}catch(N){console.error(`git pull skipped: ${N instanceof Error?N.message:String(N)}`)}if(Dy("bun",["install"],{cwd:n.appRoot}),G)await _t("start",r);B({updated:!0,serviceRestarted:G,version:m,mode:"source"});return}let e=KK(),l=BK(),$=await m4(o,30),I=u?$.find((G)=>G.version===u||G.tagName===u||G.tagName===`v${u}`)??await Uy(o,u):$[0]??await Uy(o);if(!I){B({updated:!1,currentVersion:m,mode:"binary",message:`Failed to query releases from repository '${o}'`});return}let g=I.version,b=$.find((G)=>G.version===m),w=Cu(g,m),f=w||Boolean(i.force),c=$.filter((G)=>Cu(G.version,m));if(i.checkOnly){B({updated:!1,updateAvailable:w,currentVersion:m,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:c.length,pendingReleases:c.map((G)=>({version:G.version,tagName:G.tagName,publishedAt:G.publishedAt,author:G.author,releaseNotes:G.notes,releaseUrl:G.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!f){B({updated:!1,currentVersion:m,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-use is already up to date (v${m})`});return}let S=TK(I.assets,e,l);if(!S)throw Error(`No compatible binary found for ${e}-${l} in release v${g}. Available assets: ${I.assets.map((G)=>G.name).join(", ")}`);let k=ar(r).running;if(k)await _t("stop",r);let d=process.execPath,Q=pK(d),Y=cy(Q,`.tmp-update-${Date.now()}`);YK(Y,{recursive:!0});try{let G=cy(Y,S.name);await VK(S.downloadUrl,G,I.tagName,S.name);let N=G;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))N=qK(G,Y,e);else if(S.name.endsWith(".zip"))N=EK(G,Y,e);if(HK(N,493),process.platform==="darwin")try{Zt("/usr/bin/codesign",["--remove-signature",N],{stdio:"ignore"}),Zt("/usr/ Line truncated
`)}catch{}}async function VK(n,i,r,o){let t=[],u=r?r.startsWith("v")?r:`v${r}`:void 0,e=o||n.split("/").pop()||"";if(u&&e)t.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${u}/${e}`);if(n.startsWith("https://git.ying-qing.cn"))t.push(n);if(u&&e){let c=`https://github.com/${Ay}/releases/download/${u}/${e}`;t.push(`https://ghfast.top/${c}`),t.push(`https://gh.ddlc.top/${c}`),t.push(c)}else if(n.includes("github.com"))t.push(`https://ghfast.top/${n}`),t.push(`https://gh.ddlc.top/${n}`),t.push(n);else t.push(n);let l=Array.from(new Set(t)),$,I=6000,g=6000,b=307200,w=1e4,f=180000;for(let c=0;c<l.length;c++){let S=l[c],k=new AbortController,d="",Q=(E)=>{d=E;try{k.abort()}catch{}},Y=setTimeout(()=>{Q("Connection timed out (no response headers within 6s)")},I),G,N;try{c$(`==> [${c+1}/${l.length}] Downloading via: ${S}`);let E=await fetch(S,{signal:k.signal});if(Y)clearTimeout(Y),Y=void 0;if(!E.ok)throw Error(`HTTP ${E.status} ${E.statusText}`);G=setTimeout(()=>{Q("Overall download time exceeded 3 minutes")},f);let x=Number(E.headers.get("content-length"))||0,yn=E.body?.getReader();if(!yn){let wi=Buffer.from(await E.arrayBuffer());if(wi.length<1000)throw Error(`Downloaded content is suspiciously small (${wi.length} bytes)`);fy(i,wi),c$(`✓ Download succeeded (${(wi.length/1024/1024).toFixed(1)} MB)`);return}let Wn=[],On=0,un=0;N=setTimeout(()=>{if(On<b){let wi=(On/1024).toFixed(1);Q(`Initial transfer too slow (${wi} KB < 300 KB in 6s), switching mirror...`)}},g);while(!0){let wi=yn.read(),no,Wy=new Promise((D$,S$)=>{no=setTimeout(()=>{S$(Error("Data transfer stalled (no chunk received for 10s)"))},w)}),s4;try{s4=await Promise.race([wi,Wy])}finally{if(no)clearTimeout(no)}let{done:Jy,value:U$}=s4;if(Jy)break;if(U$){if(Wn.push(U$),On+=U$.length,N&&On>=b)clearTimeout(N),N=void 0;let D$=Date.now();if(D$-un>200){un=D$;let S$=x?Math.round(On/x*100):0,Xy=(On/1048576).toFixed(1),Hy=x?(x/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${S$}% (${Xy} / ${Hy} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let Ot=Buffer.concat(Wn);if(Ot.length<1000)throw Error(`Downloaded content is suspiciously small (${Ot.length} bytes)`);fy(i,Ot),c$(`✓ Download completed successfully (${(Ot.length/1024/1024).toFixed(1)} MB)`);return}catch(E){if(Y)clearTimeout(Y);if(N)clearTimeout(N);if(G)clearTimeout(G);let x=d||(E instanceof Error?E.message:String(E));$=Error(x),c$(`
↳ Mirror failed: ${$.message}`)}finally{if(Y)clearTimeout(Y);if(N)clearTimeout(N);if(G)clearTimeout(G)}}throw Error(`Failed to download asset from all mirrors: ${$?.message}`)}function qK(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()}`);Sy(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 EK(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()}`);Sy(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 ky(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 ky(n,i)>0}function Dy(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 dy(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 Ny(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:F4(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:F4(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=Q4(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=Q4(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 Ly=x4(x4(x4(ZK(import.meta.url)))),MK=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"]),yy=Promise.resolve();function Mu(n,i={}){let r=yy.then(()=>zK(n,i));return yy=r.then(()=>{return},()=>{return}),r}async function zK(n,i){let r=[],o=[],t=console.log,u=console.error,e={appRoot:i.appRoot??Ly,entryFile:i.entryFile??_K(i.appRoot??Ly,"src","cli.ts"),launcher:i.launcher};console.log=(...l)=>{r.push(K4(l))},c Line truncated
`;var Uy={"SKILL.md":ry,"agents/openai.yaml":oy,"references/rule-lightweight.md":uy,"references/approval-bad-cases.md":ey,"references/cli.md":ly,"references/approval-run-lightweight.md":vy,"references/approval-attachment-trace.md":$y,"references/customer-feedback-rule-remediation.md":Iy,"references/enterprise-onboarding.md":gy,"references/hose-enterprise-auth.md":by,"references/hose-enterprise-init.md":wy};function Dy(){return Uy["SKILL.md"]||""}function mu(){return n0(cy(),".agents","skills","seal-use")}function Sy(){return n0(cy(),".agents","skills","seal-home")}function Ay(){let n=Sy();if(s4(n))try{return hB(n,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function i0(n=mu()){Ay(),fy(n,{recursive:!0});let i=[];for(let[r,o]of Object.entries(Uy)){let t=n0(n,r);fy(xB(t),{recursive:!0}),mB(t,o,"utf8"),i.push(r)}return{targetDir:n,files:i}}function t0(){let n=Sy(),i=mu(),r=s4(n),o=s4(i);if(r||o)return Ay(),i0(i),{synced:!0,targetDir:i};return{synced:!1}}function dy(n,i,r){if(n==="dump"||n==="cat"||n==="show"){process.stdout.write(`${Dy()}
`);return}if(n==="install"||n==="init"||n==="sync"){let o=_(r.options.local)||_(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=i0(u);P({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");P({global:{dir:o,installed:ky(c$(o,"SKILL.md"))},local:{dir:t,installed:ky(c$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${n}. Run 'seal-use help' for available commands.`)}async function Oy(n,i){if(n==="config"){P(await io(i));return}throw Error(`Unknown source command: ${n??""}. Run 'seal-use help' for available commands.`)}async function Ly(n,i,r,o){if(!n)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await J(n,i,r,oi(o.json),p(o.options))}function Ny(){P(_u.map((n)=>({name:n.name,description:n.description})))}import{chmodSync as aB,mkdirSync as sB,renameSync as r0,rmSync as nP,unlinkSync as py,writeFileSync as yy}from"node:fs";import{dirname as iP,join as Gy}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 Jy="yunyingk/seal-use",au="yunyingk/seal-home";var tP="SEAL_USE_GITHUB_REPO",rP="SEAL_HOME_GITHUB_REPO";async function Xy(n,i={}){let r={appRoot:n.appRoot,entryFile:n.entryFile,stateDir:a4,version:x,launcher:n.launcher},o=i.repo||process.env[tP]?.trim()||process.env[rP]?.trim()||Jy,t=i.targetVersion?.trim(),u=t&&t.toLowerCase()!=="latest"?t:void 0;if(u){let W=u.replace(/^v/,""),L=Hy(W,x);if(L<0){P({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(L===0&&!i.force){P({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 o0(o,i.limit??10);P({currentVersion:x,totalQueried:W.length,releases:W.map((L)=>({version:L.version,tagName:L.tagName,publishedAt:L.publishedAt,author:L.author,releaseNotes:L.notes,releaseUrl:L.htmlUrl,isCurrent:L.version===x,isNewer:xu(L.version,x)}))});return}if(!U$()){if(i.checkOnly){let L=await o0(o,30),M=L[0],q=M?.version??x,An=L.find((nn)=>nn.version===x),Wn=xu(q,x),jn=L.filter((nn)=>xu(nn.version,x));P({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=to(r).running;if(W)await Mt("stop",r);try{jy("git",["-C",n.appRoot,"pull","--ff-only"])}catch(L){console.error(`git pull skipped: ${L instanceof Error?L.message:String(L)}`)}if(jy("bun",["install"],{cwd:n.appRoot}),W)await Mt("start",r);P({updated:!0,serviceRestarted:W,version:x,mode:"source"});return}let e=oP(),l=uP(),$=await o0(o,30),I=u?$.find((W)=>W.version===u||W.tagName===u||W.tagName===`v${u}`)??await Wy(o,u):$[0]??await Wy(o);if(!I){P({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=xu(g,x),f=w||Boolean(i.force),c=$.filter((W)=>xu(W.version,x));if(i.checkOnly){P({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){P({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=eP(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=to(r).running;if(d)await Mt("stop",r);let O=process.execPath,F=iP(O),Q=Gy(F,`.tmp-update-${Date.now()}`);sB(Q,{recursive:!0});try{let W=Gy(Q,S.name);await lP(S.downloadUrl,W,I.tagName,S.name);let L=W;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))L=vP(W,Q,e);else if(S.name.endsWith(".zip"))L=$P(W,Q,e);if(aB(L,493),process.platform==="darwin")try{zt("/usr/bin/codesign",["--remove-signature",L],{stdio:"ignore"}),zt("/usr/ Line truncated
`)}catch{}}async function lP(n,i,r,o){let t=u0(),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/${Jy}/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],O=new AbortController,F="",Q=(q)=>{F=q;try{O.abort()}catch{}},W=setTimeout(()=>{Q("Connection timed out (no response headers within 6s)")},g),L,M;try{D$(`==> [${S+1}/${$.length}] Downloading via: ${d}`);let q=await fetch(d,{signal:O.signal});if(W)clearTimeout(W),W=void 0;if(!q.ok)throw Error(`HTTP ${q.status} ${q.statusText}`);L=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 Li=Buffer.from(await q.arrayBuffer());if(Li.length<1000)throw Error(`Downloaded content is suspiciously small (${Li.length} bytes)`);yy(i,Li),D$(`✓ Download succeeded (${(Li.length/1024/1024).toFixed(1)} MB)`);return}let jn=[],nn=0,ro=0;M=setTimeout(()=>{if(nn<w){let Li=(nn/1024).toFixed(1);Q(`Initial transfer too slow (${Li} KB < 300 KB in 6s), switching mirror...`)}},b);while(!0){let Li=Wn.read(),S$,Ty=new Promise((k$,d$)=>{S$=setTimeout(()=>{d$(Error("Data transfer stalled (no chunk received for 10s)"))},f)}),v0;try{v0=await Promise.race([Li,Ty])}finally{if(S$)clearTimeout(S$)}let{done:Ey,value:A$}=v0;if(Ey)break;if(A$){if(jn.push(A$),nn+=A$.length,M&&nn>=w)clearTimeout(M),M=void 0;let k$=Date.now();if(k$-ro>200){ro=k$;let d$=An?Math.round(nn/An*100):0,Vy=(nn/1048576).toFixed(1),qy=An?(An/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${d$}% (${Vy} / ${qy} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let Lt=Buffer.concat(jn);if(Lt.length<1000)throw Error(`Downloaded content is suspiciously small (${Lt.length} bytes)`);yy(i,Lt),D$(`✓ Download completed successfully (${(Lt.length/1024/1024).toFixed(1)} MB)`);return}catch(q){if(W)clearTimeout(W);if(M)clearTimeout(M);if(L)clearTimeout(L);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(L)clearTimeout(L)}}throw Error(`Failed to download asset from all mirrors: ${I?.message}`)}function vP(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()}`);py(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 $P(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()}`);py(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 Hy(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 Hy(n,i)>0}function jy(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 Yy(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},p(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},p(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},p(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},p(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},p(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},p(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},p(t.options));return}throw Error(`Unknown users command: ${n??""}. Run 'seal-use help' for available commands.`)}async function Qy(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:Z4(t.options)},p(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:Z4(t.options)},p(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=_4(t.options);await J("seal_webhook_add",r,o,{name:u,mode:q4(U(t.options.mode)),outgoingResultWebhook:e,autoApprovalRate:l,secret:U(t.options.secret)},p(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=_(t.options.rotateSecret)??_(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=q4(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=_4(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},p(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(_(t.options.yes)!==!0)throw Error("Refusing to delete Webhook integration without --yes");await J("seal_webhook_delete",r,o,{selector:u,confirm:!0},p(t.options));return}throw Error(`Unknown webhook command: ${n??""}. Run 'seal-use help' for available commands.`)}var Fy=e0(e0(e0(gP(import.meta.url)))),bP=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"]),Ky=Promise.resolve();function hu(n,i={}){let r=Ky.then(()=>wP(n,i));return Ky=r.then(()=>{return},()=>{return}),r}async function wP(n,i){let r=[],o=[],t=console.log,u=console.error,e={appRoot:i.appRoot??Fy,entryFile:i.entryFile??IP(i.appRoot??Fy,"src","cli.ts"),launcher:i.launcher};console.log=(...l)=>{r.push(M4(l))},c Line truncated
`)?"":`
`}`);process.exitCode=n.exitCode}var t3=Boolean(i0.main==i0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&jy(process.argv[1])===jy(Ri));if(t3)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await i3();else q4().catch((n)=>{console.error(n),process.exitCode=1});export{T4 as tokenizeCommand,q4 as startServer,aK as resolveMcpEnabled,sK as createServer,mK as SEAL_MCP_ENABLED_ENV,hK as SEAL_CLI_TOOL_NAME,xK as LEGACY_SEAL_MCP_ENABLED_ENV};
`}`);process.exitCode=n.exitCode}var LP=Boolean(I0.main==I0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&By(process.argv[1])===By(Ri));if(LP)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await OP();else h4().catch((n)=>{console.error(n),process.exitCode=1});export{C4 as tokenizeCommand,h4 as startServer,AP as resolveMcpEnabled,kP as createServer,DP as SEAL_MCP_ENABLED_ENV,UP as SEAL_CLI_TOOL_NAME,SP 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.1",
"version": "0.10.4",
"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.1
version: 0.10.4
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.1",
"version": "0.10.4",
"type": "module",
"module": "src/server.ts",
"bin": {
+23 -7
View File
@@ -1,19 +1,31 @@
---
name: seal-use
description: "v0.10.1: 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.4: 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.1
short-description: Seal tenant and Hose approval automation (v0.10.1)
version: 0.10.4
short-description: Seal tenant and Hose approval automation (v0.10.4)
---
# Seal Use (v0.10.1)
# Seal Use (v0.10.4)
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.
## Bootstrap & Installation (环境安装与自愈)
If `seal-use` or `seal_cli` is not installed on the system, the Agent should automatically install it via:
```bash
# 国内高速安装(Gitea 镜像源,免代理、秒级完成)
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
# Global / GitHub Direct
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
```
After installation, verify with:
```bash
seal-use help
seal-use version
seal-use tools list
seal-use corps list
```
## First Rules
@@ -44,7 +56,7 @@ seal-use tools list
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp <corpId> --note '<enterprise>'`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
- Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
- HoseCloud 部署与同步发布: `seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>`.
- Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>`; read `references/hose-enterprise-deploy.md`.
- 审核决策偏好与思考深度: `seal-use preference get --corp <corpId>`, `preference decision update --json '...' --corp <corpId>`, `preference thinking-depth set --default <medium|high> --corp <corpId>`, `preference thinking-depth policies <list|upsert|remove> --corp <corpId>`.
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>`, `seal-use approval-runs count --corp <corpId>`.
- User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp <corpId> --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
@@ -55,6 +67,7 @@ seal-use tools 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
@@ -70,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'
@@ -100,9 +114,11 @@ 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`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
- `references/hose-enterprise-deploy.md`: Seal AI 智能审核发布到合思费控(添加/编辑配置、平台自动探测、一键同步与 EBot 节点发布)。
- `references/approval-attachment-trace.md`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。
- `references/cli.md`: 完整 CLI 命令清单。
+10
View File
@@ -24,6 +24,12 @@ seal-use config mode stateless
The global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to
override that path. The legacy `current-corp` file is not read.
## Stream & Exit Code Contract
- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.
- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).
- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.
## Top-Level Commands
```bash
@@ -31,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]
@@ -127,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`
@@ -4,13 +4,14 @@ Read this reference for first installation, zero configured enterprises, incomin
## Start With Discovery
Run this before asking for setup parameters:
Run 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`):
```bash
seal-use version
seal-use corps list
```
- If `seal-use` is not installed on the system, run the curl install script above to install it.
- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.
- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.
- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”
@@ -0,0 +1,94 @@
# Seal AI 智能审核发布到合思费控 (HoseCloud Deployment)
Use this reference when configuring, deploying, or troubleshooting Seal AI smart approval integrations with Hose/合思费控 (界面路径:【智能审核】 $\to$ 【发布】 $\to$ 【合思费控】).
---
## 1. 业务全景与产品心智
将 Seal AI 智能审核能力应用到合思费控的审批流中包含 3 个核心步骤:
```mermaid
flowchart LR
S1["01 添加/编辑配置<br/>(API 凭证 + 模式 + 自动探测)"] --> S2["02 同步到合思<br/>(自动在合思创建出站配置)"]
S2 --> S3["03 添加 EBot 节点<br/>(在合思审批流中插入 AI 审核)"]
```
1. **01 添加配置**:填写合思开放平台的 `appKey` 与 `appSecurity`,设置审核模式(辅助、半自动、全自动)与策略。
2. **02 同步到合思**:一键将配置推送到合思开放平台,自动生成对应的出站消息配置。
3. **03 添加 EBot 节点**:在合思审批流编辑器中,在需要 AI 审核的位置添加“EBot”节点,选择同步生成的出站消息名称即可。
---
## 2. 合思平台/环境自动探测机制 (Auto Platform Probing)
### 为什么需要自动探测?
合思费控在不同客户端平台有独立的服务端环境(例如**钉钉版** `https://dd2.hosecloud.com` 与 **原生独立版** `https://app.ekuaibao.com`)。如果平台环境选择不匹配,合思鉴权会失败并报错:
> `请检查 API 平台和凭证配置是否正确`
### 自动探测行为
在使用 `seal-use deploy hosecloud configure` 时:
- **无需手动猜测平台**:用户只需提供 `apiKey` (appKey) 和 `apiSecret` (appSecurity);
- **并发探测 6 大 SaaS 平台域名**:
1. `https://app.ekuaibao.com` (合思原生/标准版,自动设为 `apiOrigin: "production"`)
2. `https://dd2.hosecloud.com` (钉钉版,自动设为 `apiOrigin: "custom"`, `customApiUrl: "https://dd2.hosecloud.com"`)
3. `https://wx2.ekuaibao.com` (企业微信版)
4. `https://feishu.ekuaibao.com` (飞书版)
5. `https://kdcloud2.ekuaibao.com` (云之家版)
6. `https://ddenterprise.ekuaibao.com` (钉钉自建应用版)
- 若为专属私有云或专有部署环境(如美年大健康),显式传入 `--json '{"apiOrigin":"custom", "customApiUrl":"https://custom.domain.com"}'` 即可。
---
## 3. 核心 CLI 命令速查
```bash
# 1. 查看当前企业【发布到合思费控】的所有配置卡片
seal-use deploy hosecloud list --corp <corpId>
# 2. 查询配置参数说明与字段定义
seal-use deploy hosecloud requirements --corp <corpId>
# 3. 添加新配置(自动探测平台)
seal-use deploy hosecloud configure --corp <corpId> --json '{
"apiKey": "your-app-key",
"apiSecret": "your-app-secret",
"outboundName": "SealAI 财务审批",
"mode": "assisted"
}'
# 4. 编辑已有配置(传入原 signKey)
seal-use deploy hosecloud configure --corp <corpId> --json '{
"signKey": "eE2Nfu7NEnSw",
"apiKey": "your-app-key",
"apiSecret": "your-app-secret",
"mode": "semi_automatic",
"autoApprovalRate": 80
}'
# 5. 一键同步发布到合思审批流
seal-use deploy hosecloud sync <signKey> --corp <corpId>
# 6. 查看单项配置详情
seal-use deploy hosecloud get <signKey> --corp <corpId>
# 7. 检查发布与多平台集成状态
seal-use deploy hosecloud status --corp <corpId>
```
---
## 4. 关键配置参数定义
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
| :--- | :--- | :---: | :--- | :--- |
| `apiKey` | string | 是 | - | 合思开放平台 `appKey` |
| `apiSecret` | string | 是 | - | 合思开放平台 `appSecurity` |
| `outboundName` | string | 否 | `SealAI 审批` | 同步到合思审批流中显示的出站节点名称 |
| `mode` | enum | 否 | `assisted` | `assisted` (辅助审核) / `semi_automatic` (半自动) / `fully_automatic` (全自动) |
| `autoApprovalRate`| number | 否 | - | 自动审批比例(0~100),非 assisted 模式下生效 |
| `rejectResubmitMethod` | enum | 否 | `node_default` | 驳回重提流向:`node_default` / `to_ebot` / `from_start` |
| `autoApproveNodeNames` | string[] | 否 | - | 允许 AI 自动审批的节点名称列表 |
| `signKey` | string | 否 | 随机生成 | 集成配置卡片唯一标识,编辑时传入以更新对应配置 |
| `apiOrigin` | string | 否 | 自动探测 | `production` / `custom` |
| `customApiUrl` | string | 否 | - | 专属私有云 API 地址(当 `apiOrigin=custom` 时必填) |
+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.`);
}
+33 -3
View File
@@ -14,12 +14,42 @@ export async function handleDeployCommand(
corp: CorpConfig,
args: ParsedArgs
) {
const isHosecloud = systemOrAction === "hosecloud" || !systemOrAction;
if (!systemOrAction || systemOrAction === "help") {
throw new Error(
"Usage: seal-use deploy <system> <action> [options]\n\n" +
"支持的审批系统与发布目标:\n" +
" • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>\n" +
" • webhook (通用审批流回调): seal-use webhook <list|get|add|update|delete> --corp <corpId>\n" +
" • feishu (飞书审批): 建议使用 Webhook 模式对接\n" +
" • weaver (泛微 OA): 建议使用 Webhook 模式对接\n" +
" • helios (汇联易): 建议使用 Webhook 模式对接\n" +
" • maycur (每刻报销): 建议使用 Webhook 模式对接"
);
}
if (systemOrAction === "webhook" || systemOrAction === "webhooks") {
throw new Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");
}
if (systemOrAction === "feishu" || systemOrAction === "lark") {
throw new Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");
}
if (systemOrAction === "weaver") {
throw new Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");
}
if (systemOrAction === "maycur" || systemOrAction === "helios") {
const name = systemOrAction === "maycur" ? "每刻报销" : "汇联易";
throw new Error(`${name}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${name}' --result-url <url> --corp <corpId>`);
}
const isHosecloud = systemOrAction === "hosecloud";
const action = systemOrAction === "hosecloud" ? actionOrTarget : systemOrAction;
const target = systemOrAction === "hosecloud" ? maybeTarget : actionOrTarget;
if (!isHosecloud && systemOrAction !== "hosecloud") {
throw new Error(`Unknown deploy target: ${systemOrAction ?? ""}. Currently supported: hosecloud`);
if (!isHosecloud) {
throw new Error(`未知的发布目标系统: ${systemOrAction}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);
}
if (action === "requirements") {
+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.`);
}
+30 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { compareSemVer, isNewerVersion } from "./update.js";
import { compareSemVer, getMirrorMode, isNewerVersion } from "./update.js";
describe("update version comparator", () => {
test("correctly identifies newer semantic versions", () => {
@@ -19,3 +19,32 @@ describe("update version comparator", () => {
expect(compareSemVer("0.3.3", "0.7.1")).toBe(-1);
});
});
describe("getMirrorMode routing", () => {
const originalEnv = { ...process.env };
test("defaults to github when CI is set", () => {
delete process.env.SEAL_USE_MIRROR;
delete process.env.SEAL_HOME_MIRROR;
process.env.CI = "true";
expect(getMirrorMode()).toBe("github");
});
test("defaults to auto when CI is not set", () => {
delete process.env.SEAL_USE_MIRROR;
delete process.env.SEAL_HOME_MIRROR;
delete process.env.CI;
expect(getMirrorMode()).toBe("auto");
});
test("respects SEAL_USE_MIRROR override", () => {
process.env.SEAL_USE_MIRROR = "gitea";
expect(getMirrorMode()).toBe("gitea");
process.env.SEAL_USE_MIRROR = "github";
expect(getMirrorMode()).toBe("github");
});
// Restore env
process.env = originalEnv;
});
+82 -38
View File
@@ -307,6 +307,13 @@ type GitHubRelease = {
assets: GitHubAsset[];
};
export function getMirrorMode(): "auto" | "github" | "gitea" {
const env = (process.env.SEAL_USE_MIRROR || process.env.SEAL_HOME_MIRROR)?.trim().toLowerCase();
if (env === "github" || env === "gitea") return env;
if (process.env.CI) return "github";
return "auto";
}
async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRelease[]> {
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const headers: Record<string, string> = {
@@ -315,13 +322,23 @@ async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRele
...(token ? { Authorization: `Bearer ${token}` } : {})
};
const urls = [
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases?per_page=${limit}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases?per_page=${limit}`,
`https://api.github.com/repos/${repo}/releases?per_page=${limit}`
];
if (repo !== LEGACY_GITHUB_REPO) {
urls.push(`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases?per_page=${limit}`);
const mirrorMode = getMirrorMode();
const urls: string[] = [];
// 1. Gitea releases (bypassed in CI / GitHub-only mode)
if (mirrorMode !== "github") {
urls.push(
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases?per_page=${limit}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases?per_page=${limit}`
);
}
// 2. GitHub releases (bypassed in Gitea-only mode)
if (mirrorMode !== "gitea") {
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
if (repo !== LEGACY_GITHUB_REPO) {
urls.push(`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases?per_page=${limit}`);
}
}
for (const url of urls) {
@@ -379,19 +396,36 @@ async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise
...(token ? { Authorization: `Bearer ${token}` } : {})
};
const urls = tag
? [
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/tags/${tag}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/tags/${tag}`,
`https://api.github.com/repos/${repo}/releases/tags/${tag}`,
...(repo !== LEGACY_GITHUB_REPO ? [`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/tags/${tag}`] : [])
]
: [
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/latest`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/latest`,
`https://api.github.com/repos/${repo}/releases/latest`,
...(repo !== LEGACY_GITHUB_REPO ? [`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/latest`] : [])
];
const mirrorMode = getMirrorMode();
const urls: string[] = [];
// 1. Gitea releases (bypassed in CI / GitHub-only mode)
if (mirrorMode !== "github") {
urls.push(
tag
? `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/tags/${tag}`
: `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/latest`,
tag
? `https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/tags/${tag}`
: `https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/latest`
);
}
// 2. GitHub releases (bypassed in Gitea-only mode)
if (mirrorMode !== "gitea") {
urls.push(
tag
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
: `https://api.github.com/repos/${repo}/releases/latest`
);
if (repo !== LEGACY_GITHUB_REPO) {
urls.push(
tag
? `https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/tags/${tag}`
: `https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/latest`
);
}
}
let fallbackRelease: GitHubRelease | undefined;
@@ -494,30 +528,40 @@ function logProgress(msg: string) {
}
async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) {
const mirrorMode = getMirrorMode();
const candidates: string[] = [];
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
const fileName = assetName || url.split("/").pop() || "";
// 1. High-speed Gitea direct mirror first
if (tag && fileName) {
candidates.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${tag}/${fileName}`);
}
if (url.startsWith("https://git.ying-qing.cn")) {
candidates.push(url);
// 1. High-speed Gitea direct mirror (bypassed in CI / GitHub-only mode)
if (mirrorMode !== "github") {
if (tag && fileName) {
candidates.push(
`https://git.ying-qing.cn/gitea/seal-use/releases/download/${tag}/${fileName}`,
`https://git.ying-qing.cn/gitea/seal-home/releases/download/${tag}/${fileName}`
);
}
if (url.startsWith("https://git.ying-qing.cn")) {
candidates.push(url);
}
}
// 2. Fast GitHub CDN proxies and direct GitHub fallback
if (tag && fileName) {
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
candidates.push(ghDirectUrl);
} else if (url.includes("github.com")) {
candidates.push(`https://ghfast.top/${url}`);
candidates.push(`https://gh.ddlc.top/${url}`);
candidates.push(url);
} else {
candidates.push(url);
// 2. Fast GitHub CDN proxies and direct GitHub fallback (bypassed in Gitea-only mode)
if (mirrorMode !== "gitea") {
if (tag && fileName) {
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
if (!process.env.CI) {
candidates.push(`https://ghfast.top/${ghDirectUrl}`, `https://gh.ddlc.top/${ghDirectUrl}`);
}
candidates.push(ghDirectUrl);
} else if (url.includes("github.com")) {
if (!process.env.CI) {
candidates.push(`https://ghfast.top/${url}`, `https://gh.ddlc.top/${url}`);
}
candidates.push(url);
} else {
candidates.push(url);
}
}
// Deduplicate candidates
+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;
+82
View File
@@ -657,6 +657,47 @@ describe("sealTools", () => {
versionNumber: 16
});
});
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
const tool = sealTools.find((item) => item.name === "seal_deploy_hosecloud_configure");
expect(tool).toBeDefined();
const handler = tool!.handler as ToolHandler;
const client = fakeDeployClient();
// 1. Rejects custom environment without customApiUrl
await expect(
handler(
client,
{
apiKey: "test-ak",
apiSecret: "test-sk",
apiOrigin: "custom"
},
fakeContext()
)
).rejects.toThrow("自定义合思环境必须提供 customApiUrl");
// 2. Saves successfully with customApiUrl
const result = await handler(
client,
{
apiKey: "test-ak",
apiSecret: "test-sk",
apiOrigin: "custom",
customApiUrl: "https://dd2.hosecloud.com",
outboundName: "DingTalk AI Audit"
},
fakeContext()
) as { integration: { corporationId: string; apiOrigin: string; customApiUrl: string; outboundName: string } };
expect(result.integration).toMatchObject({
corporationId: "mock-hose-corp",
apiOrigin: "custom",
customApiUrl: "https://dd2.hosecloud.com",
outboundName: "DingTalk AI Audit"
});
});
});
function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
@@ -953,3 +994,44 @@ function primeHoseEnterpriseUrl(corpId: string, url: string) {
}
}));
}
function fakeDeployClient(): KyInstance {
let config: Record<string, unknown> = {
integrationSystem: "hosecloud",
integrations: []
};
return {
get: (_url: string) => ({
json: async () => config
}),
patch: (url: string, options?: { json?: any }) => {
if (url === "api/v1/agent/ai-approval/config") {
config = options?.json ?? config;
return {
json: async () => config
};
}
return {
json: async () => ({})
};
},
post: (url: string, options?: { json?: any }) => {
if (url === "api/hosecloud/corporation") {
return {
json: async () => ({ corporationId: "mock-hose-corp" })
};
}
if (url === "api/v1/agent/ai-approval/config") {
config = options?.json ?? config;
return {
json: async () => config
};
}
return {
json: async () => ({})
};
}
} as unknown as KyInstance;
}
+175 -19
View File
@@ -3,10 +3,12 @@ import { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "./api.js";
import { defaultSealUrl, getHoseEnterpriseUrl } from "../../core/auth/hose.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 审批知识文档",
@@ -1354,28 +1469,28 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_requirements",
description: "获取合思出站发布所需配置字段与说明",
description: "获取 Seal AI 审批发布到合思费控所需配置字段与说明",
parameters: z.object({}),
handler: async () => {
return {
input: "JSON via --json '{\"apiKey\":\"...\",\"apiSecret\":\"...\",\"mode\":\"assisted\"}'",
questions: [
{ field: "apiOrigin", prompt: "使用哪一种合思版本或 API 环境?(production/custom)", required: true, default: "production" },
{ field: "customApiUrl", prompt: "自定义环境的 API 地址是什么?", requiredWhen: "apiOrigin=custom" },
{ field: "apiOrigin", prompt: "使用哪一种合思版本或 API 环境?(production/custom,未指定时自动探测)", required: false, default: "production" },
{ field: "customApiUrl", prompt: "自定义环境的 API 地址是什么?(如专属私有云域名)", requiredWhen: "apiOrigin=custom" },
{ field: "apiKey", prompt: "合思 API Key(appKey)是什么?", required: true, secret: true },
{ field: "apiSecret", prompt: "合思 API Secret(appSecurity)是什么?", required: true, secret: true },
{ field: "mode", prompt: "使用全自动、半自动还是辅助审核?(fully_automatic/semi_automatic/assisted)", required: true, default: "assisted" },
{ field: "autoApprovalRate", prompt: "自动审批比例是多少?(0-100)", requiredWhen: "mode!=assisted" },
{ field: "rejectResubmitMethod", prompt: "驳回重提后从哪个节点继续?(node_default/to_ebot/from_start)" },
{ field: "autoApproveNodeNames", prompt: "哪些节点允许自动审批?(string[])" },
{ field: "outboundName", prompt: "合思出站消息名称是什么?", default: "SealAI 审批" }
{ field: "outboundName", prompt: "合思审批流节点消息名称是什么?", default: "SealAI 审批" }
]
};
}
},
{
name: "seal_deploy_hosecloud_list",
description: "列出当前已配置的合思集成列表",
description: "列出当前企业【Seal AI 审批发布到合思费控】的集成配置列表",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const config = await api.getApprovalStylePreferences(client);
@@ -1388,7 +1503,7 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_get",
description: "查询单个合思集成配置详情",
description: "查询【Seal AI 审批发布到合思费控】的单项配置详情",
parameters: z.object({
signKey: z.string().describe("合思集成 sign-key")
}),
@@ -1405,7 +1520,7 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_status",
description: "检查合思集成与多平台集成状态",
description: "检查【Seal AI 审批发布到合思费控】与多平台集成状态",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const status = await api.getSimulationIntegrationStatus(client);
@@ -1419,12 +1534,12 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_configure",
description: "校验合思凭据并保存合思集成配置",
description: "自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置",
parameters: z.object({
apiKey: z.string().describe("合思 API Key"),
apiSecret: z.string().describe("合思 API Secret"),
apiKey: z.string().describe("合思 API Key (appKey)"),
apiSecret: z.string().describe("合思 API Secret (appSecurity)"),
signKey: z.string().optional().describe("集成 signKey,不提供则自动生成"),
outboundName: z.string().optional().describe("出站消息名称"),
outboundName: z.string().optional().describe("出站消息名称(合思审批流节点中显示)"),
specificationId: z.string().optional(),
specificationName: z.string().optional(),
mode: z.enum(["fully_automatic", "semi_automatic", "assisted"]).default("assisted"),
@@ -1434,21 +1549,51 @@ export const sealTools = [
apiOrigin: z.string().default("production"),
customApiUrl: z.string().optional()
}),
handler: async (client: KyInstance, params: HosecloudConfigInput) => {
if (params.apiOrigin === "custom" && !params.customApiUrl) {
handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: ToolContext) => {
const apiKey = rawParams.apiKey ?? (rawParams as any).appKey;
const apiSecret = rawParams.apiSecret ?? (rawParams as any).appSecurity;
if (!apiKey || !apiSecret) {
throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
}
const params = { ...rawParams, apiKey, apiSecret };
let effectiveApiOrigin = params.apiOrigin ?? "production";
let effectiveCustomApiUrl = params.customApiUrl;
// 自动平台/域名探测:当未提供 customApiUrl 时,并发探测合思 6 大标准公共 SaaS 平台域名
if (!effectiveCustomApiUrl && effectiveApiOrigin !== "custom") {
try {
const probe = await probeHoseDomain(params.apiKey, params.apiSecret);
if (probe?.domain) {
if (probe.domain === "https://app.ekuaibao.com") {
effectiveApiOrigin = "production";
effectiveCustomApiUrl = undefined;
} else {
effectiveApiOrigin = "custom";
effectiveCustomApiUrl = probe.domain;
}
}
} catch {
// 探测失败时平滑降级,由后续后端校验处理
}
}
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
throw new Error("自定义合思环境必须提供 customApiUrl");
}
const corpResult = await api.getHosecloudCorporation(client, {
apiKey: params.apiKey,
apiSecret: params.apiSecret,
apiOrigin: params.apiOrigin,
customApiUrl: params.customApiUrl
apiOrigin: effectiveApiOrigin,
customApiUrl: effectiveCustomApiUrl
});
const config = await api.getApprovalStylePreferences(client);
const signKey = params.signKey ?? randomBytes(6).toString("hex");
const nextIntegration = {
type: "hosecloud",
...params,
apiOrigin: effectiveApiOrigin,
...(effectiveCustomApiUrl ? { customApiUrl: effectiveCustomApiUrl } : {}),
signKey,
corporationId: corpResult.corporationId
};
@@ -1461,6 +1606,10 @@ export const sealTools = [
integrationSystem: "hosecloud",
integrations: existing
});
console.error(`✓ 配置已保存 (signKey: ${signKey})`);
console.error(`👉 下一步操作:运行 \`seal-use deploy hosecloud sync ${signKey} --corp ${context.corp.id}\` 一键同步发布到合思审批流`);
return {
integration: redactIntegrationSecrets(nextIntegration)
};
@@ -1468,7 +1617,7 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_sync",
description: "同步合思出站消息配置并完成发布",
description: "一键将 Seal AI 审核配置同步发布到合思费控审批流",
parameters: z.object({
signKey: z.string().describe("合思集成 sign-key")
}),
@@ -1481,13 +1630,18 @@ export const sealTools = [
throw new Error(`未找到合思配置:${params.signKey}`);
}
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
const messageName = (integration as any).outboundName ?? "SealAI 审批";
const result = await api.syncHosecloudOutbound(client, {
signKey: params.signKey,
webhookUrl: `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(params.signKey)}`,
completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`,
messageName: (integration as any).outboundName ?? "SealAI 审批",
messageName,
mode: (integration as any).mode ?? "assisted"
});
console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`);
console.error(`👉 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${messageName}"。`);
return {
signKey: params.signKey,
synced: true,
@@ -1701,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",
@@ -1758,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",