- Gate rules push behind --yes at CLI and domain layers (fail-closed on
dryRun=false without confirm)
- Raise webhook replay partial failure as CliError so exit 1 survives
cli.ts exitCode overwrite; route webhook stdout through printJson for
exit-12 protection and --output-file support
- Narrow MCP read-only allowlist: drop config mode/lint (write forms are
indistinguishable under token-prefix matching; config get covers reads)
- Extract redactSensitiveText to core, extend credential patterns, apply
to HTTP sendError/500 and domain error messages
- Pass release TAG_NAME via env instead of inline ${{ }} interpolation
to close script injection through crafted tag names
- Track .zcodeignore so enterprise credential exclusions travel with the
repo
- Add .agents/rules/security-posture.md documenting usability-first
accepted risks (loopback adapter auth, update verification, mutation
command gates, skill dump stdout); register skill dump as a documented
stdout Markdown exception in AGENTS.md and cli-protocol.md
- Rebuild dist/mcp/server.js
- Replace a real-looking signKey example with a placeholder in
hose-enterprise-deploy.md and rebuild embedded bundles so no
residual value ships in dist/mcp/server.js.
- Document exit codes 11 (auth missing/invalid) and 12 (output
protection) in AGENTS.md and .agents/rules/cli-protocol.md so
they match src/core/errors.ts and references/cli.md.
- Split the Webhook resource-pack workflow out of references/cli.md
into references/webhook-resource-pack.md (cli.md 50KB -> 39KB) and
add a routing row in SKILL.md; all 14 references stay covered.
@@ -13,7 +13,7 @@ When developing or refactoring CLI commands under `src/cli/`:
- **Machine Channel (`stdout`)**:
- Data commands **MUST** output pure, parseable JSON on `stdout`.
- **NEVER** output human text, logs, spinners, progress banners, or update notices to `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
- **Documented exceptions**: `seal-use --help` / `seal-use help <area>` (`src/cli/printer.ts`) and`seal-use doctor guide` (`src/cli/commands/doctor.ts`) intentionally output Markdown documents on `stdout` because their output *is* the requested document payload. Never add new stdout-prose commands outside this list.
- **Documented exceptions**: `seal-use --help` / `seal-use help <area>` (`src/cli/printer.ts`),`seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally output Markdown documents on `stdout` because their output *is* the requested document payload (e.g. `seal-use skill dump > SKILL.md`). Never add new stdout-prose commands outside this list.
- **Diagnostics & Guidance Channel (`stderr`)**:
- Use `stderr` for runtime logs, network probing status, self-healing notifications, and human tips.
- Explicit **Next-Step Command Suggestions** MUST follow the format:
@@ -68,6 +68,8 @@ When developing or refactoring CLI commands under `src/cli/`:
| `10` | **Confirmation Required** | Mutating command invoked without `--confirm` or `--yes` |
| `11` | **Authentication Missing / Invalid** | Upstream HTTP 401/403, or an expired/missing/invalid `token`/`bearer`/`session` (classified in `classifyCliError`) |
| `12` | **Output Protection** | Response exceeds the size limit (`PayloadTooLargeError` from `printer.ts`); use `--summary`/`--fields`/`--count`/`--output-file`, or `--full` when the full payload is genuinely required |
**Rule**: Never call `process.exit()` deep in domain functions. Throw structured errors and let `src/cli/runner.ts` handle error classification, stream routing, and exit code assignment.
@@ -33,7 +33,7 @@ Prefer small domain functions over broad utility modules.
## CLI & Agent Harness Protocol Guidelines
- **Machine Channel (`stdout`)**: Data 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.
- **Documented exception — document-output commands**: `seal-use --help` / `seal-use help <area>` (`src/cli/printer.ts`) and`seal-use doctor guide` (`src/cli/commands/doctor.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract.
- **Documented exception — document-output commands**: `seal-use --help` / `seal-use help <area>` (`src/cli/printer.ts`),`seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`, `seal-use skill dump > SKILL.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract.
- **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>`).
- **Performance Contract & SWR Architecture**: Read-only discovery and version commands (`seal-use version`, `seal-use doctor`, `seal-use corps list`) MUST execute instantaneously (<10ms). Never block on external network I/O during routine invocations. Use the Stale-While-Revalidate (SWR) pattern: read local cache from `~/.config/seal-use/*.json` synchronously (<0.2ms), and refresh stale/missing data via detached, unref'd child processes (`triggerBackgroundUpdateCheck`, `unref()`).
- **Safety Guardrail & Mutation Preview (`--dry-run`)**: All potentially destructive or state-mutating commands (e.g. `rules push/clear`, `corps sync-test`, `preference update`, `webhook add/update`) MUST support `--dry-run` returning structured JSON previews with `preview: true` and a clean diff, without executing mutations. Live execution requires explicit `--yes` or `--confirm`.
@@ -42,6 +42,8 @@ Prefer small domain functions over broad utility modules.
-`1`: Upstream API failure or domain business block.
-`2`: Parameter validation failure, unknown subcommand, or invalid JSON.
-`10`: Safety gate block requiring user confirmation (`--confirm` / `--yes`).
-`11`: Missing or invalid authentication (HTTP 401/403, or an expired/missing/invalid `token`/`bearer`/`session`).
-`12`: Output protection — response exceeds the size limit; use `--summary`/`--fields`/`--count`/`--output-file` (or `--full` when the full payload is genuinely required).
- 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
@@ -57,20 +59,21 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
@@ -83,7 +86,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
git worktree remove /tmp/seal-use-release
```
- Do not tag or push `main` directly. Create a release branch, commit the version bump, push it, open a PR to `main`, wait for the required CI check, and merge the PR first.
- After the PR is merged, fast-forward the local `main`, then synchronize `home/main` before creating the tag:
- After the PR is merged, fast-forward the local `main`, then create and push the annotated tag to `origin`:
```bash
git switch -c codex/release-vX.Y.Z
git add <release-files>
@@ -94,16 +97,12 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
gh pr merge <pr-number> --merge
git switch main
git pull --ff-only origin main
git push home main
```
- Only after both `origin/main` and `home/main` contain the merged release should you create the annotated tag. Push the tag to `home` first, then to `origin`; pushing the GitHub tag last triggers the Release workflow after the Gitea tag and branch are ready:
```bash
git tag -a vX.Y.Z -m "🚀 Release summary text describing key changes"
git push home refs/tags/vX.Y.Z
git push origin refs/tags/vX.Y.Z
```
- GitHub Actions will automatically extract the tag message, append commit notes via `--generate-notes`, cross-compile all 5 target binaries, and publish GitHub and Gitea releases. Wait for the workflow, then verify that both releases point to the intended tag commit and contain every expected asset exactly once.
- The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`, and the Gitea mirror job runs only after a successful publish. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity.
- GitHub Actions (`release.yml`) is responsible only for cross-compiling all 5 target binaries and publishing the GitHub Release.
- **Gitea & Homebrew Pull-Based Promotion**: Do not manually push branches or tags to `home` (Gitea). On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls the latest GitHub Release every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), pulls the release and assets from GitHub into Gitea, and updates the Homebrew tap (`ops/README.md`).
- The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity.
@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.10.40] - 2026-09-28
### Changed
- Standardize all CLI, MCP, and persisted timestamps (`expiresAt`, `lastCheckedAt`, `publishedAt`, `syncedAt`, `capturedAt`, `exportedAt`, `startedAt`, `timestamp`, `createdAtFormatted`, and local date-time formatters) to Beijing ISO 8601 second precision (`YYYY-MM-DDTHH:mm:ss+08:00`).
- Auto-normalize incoming ISO 8601 timestamps (`Z` or `[+-]HH:mm`, with or without milliseconds) in enterprise configuration validation (`IsoSecondTimestampSchema`) to `YYYY-MM-DDTHH:mm:ss+08:00`.
- Support flexible date/timestamp inputs (`YYYY-MM-DD`, `YYYY-MM-DD HH:mm:ss`, `YYYY-MM-DDTHH:mm:ss+08:00`, `Z`, and 13-digit millisecond timestamps) in `seal_approval_runs_search` and `seal_approval_runs_summary`.
## [0.10.39] - 2026-09-28
### Added
- Add first-class `seal-use documents` CLI domain (`list`, `get`, `search`, `create`, `update`, `delete`) with `--content-file` and `--yes` confirmation support.
- Support `--version <number|latest>` (and silent `--latest` alias) across `rules count`, `rules list`, `rules get`, `rules search`, `rules lint`, and `rules pull`.
### Changed
- Standardize rule `code` to 0-based 4-digit zero-padded strings (`0000`, `0025`, `0038`) across CLI outputs and skill docs while keeping `25`, `#0025`, and `rule-25` inputs silently compatible.
- Default all `rules` read and lint commands (`count`, `list`, `get`, `search`, `lint`, `pull`) to the current draft, requiring `--version latest` to inspect the latest published version.
- Remove legacy `seal-use tool` and `seal-use tools` CLI passthrough commands in favor of first-class domain commands.
### Fixed
- Remove erroneous `+1` array-index offsets in rule code resolution and mapping so 0-based rule codes and gaps from deleted rules resolve accurately.
- Extract and merge `result.rulesResult` and `result.hitRules` in `approval-runs cited-rules`.
- Prevent global `--version` flag handling in `runner.ts` from intercepting `--version` options passed to subcommands such as `seal-use rules`.
5. Rebuilds OpenAPI spec (`dist/openapi.json`) and MCP plugin bundle (`dist/mcp/server.js`);
6. Prints the exact `git commit` and `git tag` commands ready to execute.
### 2. Tag & Dual-Publish Workflow
### 2. Tag & Publish Workflow
1.Update `CHANGELOG.md` with the new version notes;
2. Run test suite:
1.Run the automated protected-branch release wizard:
```bash
bun test && bun run check
bun run release patch
```
3. Commit and push the annotated tag:
Or manually merge the release PR to `main`, fast-forward local `main`, and push the annotated tag to `origin`:
```bash
git commit -am "Release vX.Y.Z: ..."
git tag -a vX.Y.Z -m "🚀 版本更新文案与主要特性说明"
git push origin main --tags && git push home main --tags
git push origin refs/tags/vX.Y.Z
```
**CI Automation Pipeline:**
- GitHub Actions triggers automatically upon pushing a `v*` tag;
- Cross-compiles standalone binaries for 5 target platforms (macOS Apple Silicon/Intel, Linux x86_64/ARM64, Windows x64) in under 60 seconds;
- Automatically extracts your Git tag annotation message and appends commit changelogs (`--generate-notes`);
- Simultaneously publishes release packages to **[GitHub Releases](https://github.com/yunyingk/seal-use/releases)** and **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases)** for global and mainland China high-speed downloads.
**CI & Promotion Pipeline:**
- GitHub Actions triggers automatically upon pushing a `v*` tag to `origin`;
- Cross-compiles standalone binaries for 5 target platforms (macOS Apple Silicon/Intel, Linux x86_64/ARM64, Windows x64) and publishes them to **[GitHub Releases](https://github.com/yunyingk/seal-use/releases)**;
- WSL `seal-use-release-sync.timer` polls the latest GitHub Release and promotes all assets to **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases)** and the Homebrew tap (`ops/README.md`).
import{createRequireasAk0}from"node:module";varqk0=Object.create;var{getPrototypeOf:Vk0,defineProperty:Oj,getOwnPropertyNames:Lk0}=Object;varFk0=Object.prototype.hasOwnProperty;functionwk0($){returnthis[$]}varMk0,Ok0,I6=($,Y,U)=>{varz=$!=null&&typeof$==="object";if(z){varI=Y?Mk0??=newWeakMap:Ok0??=newWeakMap,Q=I.get($);if(Q)returnQ}U=$!=null?qk0(Vk0($)):{};letJ=Y||!$||!$.__esModule?Oj(U,"default",{value:$,enumerable:!0}):U;for(letKofLk0($))if(!Fk0.call(J,K))Oj(J,K,{get:wk0.bind($,K),enumerable:!0});if(z)I.set($,J);returnJ};varE=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);varNk0=($)=>$;functionDk0($,Y){this[$]=Nk0.bind(null,Y)}varT8=($,Y)=>{for(varUinY)Oj($,U,{get:Y[U],enumerable:!0,configurable:!0,set:Dk0.bind(Y,U)})};varm=($,Y)=>()=>($&&(Y=$($=0)),Y);varJ0=Ak0(import.meta.url);varBk0,YV,Pk0,Tk0,jk0,Ek0,E0=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports),Nr=($,Y)=>{letU={};for(varzin$)YV(U,z,{get:$[z],enumerable:!0});if(Y)YV(U,Symbol.toStringTag,{value:"Module"});returnU},Ck0=($,Y,U,z)=>{if(Y&&typeofY==="object"||typeofY==="function"){for(varI=Tk0(Y),Q=0,J=I.length,K;Q<J;Q++)if(K=I[Q],!Ek0.call($,K)&&K!==U)YV($,K,{get:((G)=>Y[G]).bind(null,K),enumerable:!(z=Pk0(Y,K))||z.enumerable})}return$},UV=($,Y,U)=>(U=$!=null?Bk0(jk0($)):{},Ck0(Y||!$||!$.__esModule?YV(U,"default",{value:$,enumerable:!0}):U,$));varNj=m(()=>{Bk0=Object.create,YV=Object.defineProperty,Pk0=Object.getOwnPropertyDescriptor,Tk0=Object.getOwnPropertyNames,jk0=Object.getPrototypeOf,Ek0=Object.prototype.hasOwnProperty});functionAr($){returntypeof$==="string"&&Dr.has($.replace(/#$/,""))}functionBr($,Y){if(!("$schema"in$)||typeof$.$schema!=="string")return"2020-12";letU=$.$schema.replace(/#$/,"");if(Rk0.has(U))return"2020-12";if(Dr.has(U))return"2019-09";if(_k0.has(U)||vk0.has(U))return"draft-7";throwError(`JSON Schema declares an unsupported dialect ("$schema": "${$.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${Y}`)}varRk0,Dr,_k0,vk0;varDj=m(()=>{Rk0=newSet(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Dr=newSet(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),_k0=newSet(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),vk0=newSet(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});functionH0($,Y,U){functionz(K,G){if(!K._zod)Object.defineProperty(K,"_zod",{value:{def:G,constr:J,traits:newSet},enumerable:!1});if(K._zod.traits.has($))return;K._zod.traits.add($),Y(K,G);letH=J.prototype,W=Object.keys(H);for(letX=0;X<W.length;X++){letZ=W[X];if(!(ZinK))K[Z]=H[Z].bind(K)}}letI=U?.Parent??Object;classQextendsI{}Object.defineProperty(Q,"name",{value:$});functionJ(K){varG;letH=U?.Parent?newQ:this;z(H,K),(G=H._zod).deferred??(G.deferred=[]);for(letWofH._zod.deferred)W();returnH}returnObject.defineProperty(J,"init",{value:z}),Object.defineProperty(J,Symbol.hasInstance,{value:(K)=>{if(U?.Parent&&KinstanceofU.Parent)return!0;returnK?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}functions4($){if($)Object.assign(TY,$);returnTY}varPr,aK,Aj,p5,jY,TY;varEY=m(()=>{aK=Object.freeze({status:"aborted"});Aj=Symbol("zod_brand");p5=classp5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};jY=classjYextendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(Pr=globalThis).__zod_globalConfig??(Pr.__zod_globalConfig={});TY=globalThis.__zod_globalConfig});vark0={};T8(k0,{unwrapMessage:()=>tK,uint8ArrayToHex:()=>Ux0,uint8ArrayToBase64url:()=>$x0,uint8ArrayToBase64:()=>Er,stringifyPrimitive:()=>_0,slugify:()=>Tj,shallowClone:()=>Ej,safeExtend:()=>ok0,required:()=>ak0,randomString:()=>ik0,propertyKeyTypes:()=>YG,promiseAllObject:()=>bk0,primitiveTypes:()=>Cj,prefixIssues:()=>b8,pick:()=>dk0,partial:()=>sk0,parsedType:()=>S0,optionalKeys:()=>Rj,omit:()=>mk0,objectClone:()=>xk0,numKeys:()=>ck0,nullish:()=>W7,normalizeParams:()=>f0,mergeDefs:()=>l9,merge:()=>rk0,jsonStringifyReplacer:()=>mz,joinValues:()=>M0,issue:()=>oz,isPlainObject:()=>Z7,isObject:()=>CY,hexToUint8Array:()=>Yx0,getSizableOrigin:()=>UG,getParsedType:()=>nk0,getLengthableOrigin:()=>zG,getEnumValues:()=>eK,getElementAtPath:()=>uk0,floatSafeRemainder:()=>Pj,finalizeIssue:()=>E8,extend:()=>lk0,explicitlyAborted:()=>hj,escapeRegex:()=>B$,esc:()=>zV,defineLazy:()=>E1,createTransparentProxy:()=>pk0,cloneDef:()=>fk0,clone:()=>j8,cleanRegex:()=>$G,cleanEnum:()=>tk0,captureStackTrace:()=>IV,cached:()=>lz,base64urlToUint8Array:()=>ek0,base64ToUint8Array:()=>jr,assignProp:()=>X7,assertNotEqual:()=>Sk0,assertNever:()=>yk0,assertIs:()=>gk0,assertEqual:()=>hk0,assert:()=>kk0,allowsEval:()=>jj,aborted:()=>q7,NUMBER_FORMAT_RANGES:()=>_j,Class:()=>CrLine truncated
`)}var Rr=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,mz,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},IG,i8;var yj=m(()=>{EY();$1();IG=H0("$ZodError",Rr),i8=H0("$ZodError",Rr,{Parent:Error})});var rz=($)=>(Y,U,z,I)=>{let Q=z?{...z,async:!1}:{async:!1},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)throw new p5;if(J.issues.length){let K=new(I?.Err??$)(J.issues.map((G)=>E8(G,Q,s4())));throw IV(K,I?.callee),K}return J.value},QV,sz=($)=>async(Y,U,z,I)=>{let Q=z?{...z,async:!0}:{async:!0},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)J=await J;if(J.issues.length){let K=new(I?.Err??$)(J.issues.map((G)=>E8(G,Q,s4())));throw IV(K,I?.callee),K}return J.value},JV,az=($)=>(Y,U,z)=>{let I=z?{...z,async:!1}:{async:!1},Q=Y._zod.run({value:U,issues:[]},I);if(Q instanceof Promise)throw new p5;return Q.issues.length?{success:!1,error:new($??IG)(Q.issues.map((J)=>E8(J,I,s4())))}:{success:!0,data:Q.value}},kj,tz=($)=>async(Y,U,z)=>{let I=z?{...z,async:!0}:{async:!0},Q=Y._zod.run({value:U,issues:[]},I);if(Q instanceof Promise)Q=await Q;return Q.issues.length?{success:!1,error:new $(Q.issues.map((J)=>E8(J,I,s4())))}:{success:!0,data:Q.value}},xj,KV=($)=>(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return rz($)(Y,U,I)},Ix0,GV=($)=>(Y,U,z)=>{return rz($)(Y,U,z)},Qx0,HV=($)=>async(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return sz($)(Y,U,I)},Jx0,WV=($)=>async(Y,U,z)=>{return sz($)(Y,U,z)},Kx0,XV=($)=>(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return az($)(Y,U,I)},Gx0,ZV=($)=>(Y,U,z)=>{return az($)(Y,U,z)},Hx0,qV=($)=>async(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return tz($)(Y,U,I)},Wx0,VV=($)=>async(Y,U,z)=>{return tz($)(Y,U,z)},Xx0;var fj=m(()=>{EY();yj();$1();QV=rz(i8),JV=sz(i8),kj=az(i8),xj=tz(i8),Ix0=KV(i8),Qx0=GV(i8),Jx0=HV(i8),Kx0=WV(i8),Gx0=XV(i8),Hx0=ZV(i8),Wx0=qV(i8),Xx0=VV(i8)});var z$={};T8(z$,{xid:()=>cj,uuid7:()=>Lx0,uuid6:()=>Vx0,uuid4:()=>qx0,uuid:()=>RY,uppercase:()=>qE,unicodeEmail:()=>vr,undefined:()=>XE,ulid:()=>ij,time:()=>IE,string:()=>JE,sha512_hex:()=>kx0,sha512_base64url:()=>fx0,sha512_base64:()=>xx0,sha384_hex:()=>Sx0,sha384_base64url:()=>yx0,sha384_base64:()=>gx0,sha256_hex:()=>_x0,sha256_base64url:()=>hx0,sha256_base64:()=>vx0,sha1_hex:()=>Ex0,sha1_base64url:()=>Rx0,sha1_base64:()=>Cx0,rfc5322Email:()=>wx0,number:()=>KG,null:()=>WE,nanoid:()=>pj,md5_hex:()=>Px0,md5_base64url:()=>jx0,md5_base64:()=>Tx0,mac:()=>aj,lowercase:()=>ZE,ksuid:()=>nj,ipv6:()=>sj,ipv4:()=>rj,integer:()=>GE,idnEmail:()=>Mx0,httpProtocol:()=>YE,html5Email:()=>Fx0,hostname:()=>Dx0,hex:()=>Bx0,guid:()=>mj,extendedDuration:()=>Zx0,emoji:()=>oj,email:()=>lj,e164:()=>UE,duration:()=>dj,domain:()=>Ax0,datetime:()=>QE,date:()=>zE,cuid2:()=>bj,cuid:()=>uj,cidrv6:()=>ej,cidrv4:()=>tj,browserEmail:()=>Ox0,boolean:()=>HE,bigint:()=>KE,base64url:()=>LV,base64:()=>$E});function oj(){return new RegExp(Nx0,"u")}function Sr($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function IE($){return new RegExp(`^${Sr($)}$`)}function QE($){let Y=Sr({precision:$.precision}),U=["Z"];if($.local)U.push("");if($.offset)U.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let z=`${Y}(?:${U.join("|")})`;return new RegExp(`^${hr}T(?:${z})$`)}function GG($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function HG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var uj,bj,ij,cj,nj,pj,dj,Zx0,mj,RY=($)=>{if(!$)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)$/;returnnewRegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},qx0,Vx0,Lx0,lj,Fx0,wx0,vr,Mx0,Ox0,Nx0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rj,sj,aj=($)=>{letY=B$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},tj,ej,$E,LV,Dx0,Ax0,YE,UE,hr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",zE,JE=($)=>{letY=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${Y}$`)},KE,GE,KG,HE,WE,XE,ZE,qE,Bx0,Px0,Tx0,jx0,Ex0,Cx0,Rx0,_x0,vx0,hx0,Sx0,gx0,yx0,kx0,xx0,fx0;varFV=m(()=>{$1();uj=/^[cC][0-9a-z]{6,}$/,bj=/^[0-9a-z]+$/,ij=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,cj=/^[0-9a-vA-V]{20}$/,nj=/^[A-Za-z0-9]{27}$/,pj=/^[a-zA-Z0-9_-]{21}$/,dj=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((Q)=>Q),z=Math.min(...U.map((Q)=>Q.length-Q.trimStart().length)),I=U.map((Q)=>Q.slice(z)).map((Q)=>" ".repeat(this.indent*2)+Q);for(let Q of I)this.content.push(Q)}compile(){let $=Function,Y=this?.args,z=[...(this?.content??[""]).map((I)=>`${I}`)];return new $(...Y,z.join(`
`))}}var hE;var SE=m(()=>{hE={major:4,minor:4,patch:3}});function YC($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function ar($){if(!LV.test($))return!1;let Y=$.replace(/[-_]/g,(z)=>z==="-"?"+":"/"),U=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return YC(U)}function tr($,Y=null){try{let U=$.split(".");if(U.length!==3)return!1;let[z]=U;if(!z)return!1;let I=JSON.parse(atob(z));if("typ"in I&&I?.typ!=="JWT")return!1;if(!I.alg)return!1;if(Y&&(!("alg"in I)||I.alg!==Y))return!1;return!0}catch{return!1}}function xr($,Y,U){if($.issues.length)Y.issues.push(...b8(U,$.issues));Y.value[U]=$.value}function PV($,Y,U,z,I,Q){let J=U in z;if($.issues.length){if(I&&Q&&!J)return;Y.issues.push(...b8(U,$.issues))}if(!J&&!I){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[U]});return}if($.value===void 0){if(J)Y.value[U]=void 0}else Y.value[U]=$.value}function er($){let Y=Object.keys($.shape);for(let z of Y)if(!$.shape?.[z]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${z}":expectedaZodschema`);let U=Rj($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(U)}}function $s($,Y,U,z,I,Q){let J=[],K=I.keySet,G=I.catchall._zod,H=G.def.type,W=G.optin==="optional",X=G.optout==="optional";for(let Z in Y){if(Z==="__proto__")continue;if(K.has(Z))continue;if(H==="never"){J.push(Z);continue}let q=G.run({value:Y[Z],issues:[]},z);if(q instanceof Promise)$.push(q.then((V)=>PV(V,U,Z,Y,W,X)));else PV(q,U,Z,Y,W,X)}if(J.length)U.issues.push({code:"unrecognized_keys",keys:J,input:Y,inst:Q});if(!$.length)return U;return Promise.all($).then(()=>{return U})}function fr($,Y,U,z){for(let Q of $)if(Q.issues.length===0)return Y.value=Q.value,Y;let I=$.filter((Q)=>!q7(Q));if(I.length===1)return Y.value=I[0].value,I[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((Q)=>Q.issues.map((J)=>E8(J,z,s4())))}),Y}function ur($,Y,U,z){let I=$.filter((Q)=>Q.issues.length===0);if(I.length===1)return Y.value=I[0].value,Y;if(I.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((Q)=>Q.issues.map((J)=>E8(J,z,s4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:[],inclusive:!1});return Y}function gE($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(Z7($)&&Z7(Y)){let U=Object.keys(Y),z=Object.keys($).filter((Q)=>U.indexOf(Q)!==-1),I={...$,...Y};for(let Q of z){let J=gE($[Q],Y[Q]);if(!J.valid)return{valid:!1,mergeErrorPath:[Q,...J.mergeErrorPath]};I[Q]=J.data}return{valid:!0,data:I}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let z=0;z<$.length;z++){let I=$[z],Q=Y[z],J=gE(I,Q);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};U.push(J.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function br($,Y,U){let z=new Map,I;for(let K of Y.issues)if(K.code==="unrecognized_keys"){I??(I=K);for(let G of K.keys){if(!z.has(G))z.set(G,{});z.get(G).l=!0}}else $.issues.push(K);for(let K of U.issues)if(K.code==="unrecognized_keys")for(let G of K.keys){if(!z.has(G))z.set(G,{});z.get(G).r=!0}else $.issues.push(K);let Q=[...z].filter(([,K])=>K.l&&K.r).map(([K])=>K);if(Q.length&&I)$.issues.push({...I,keys:Q});if(q7($))return $;let J=gE(Y.value,U.value);if(!J.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}function ir($,Y){for(let U=$.length-1;U>=0;U--)if($[U]._zod[Y]!=="optional")return U+1;return 0}function cr($,Y,U){if($.issues.length)Y.issues.push(...b8(U,$.issues));Y.value[U]=$.value}function nr($,Y,U,z,I){for(let Q=0;Q<U.length;Q++){let J=$[Q],K=Q<z.length;if(J.issues.length){if(!K&&Q>=I){Y.value.length=Q;break}Y.issues.push(...b8(Q,J.issues))}Y.value[Q]=J.value}for(let Q=Y.value.length-1;Q>=z.length;Q--)if(U[Q]._zod.optout==="optional"&&Y.value[Q]===void 0)Y.value.length=Q;else break;return Y}function pr($,Y,U,z,I,Q,J){if($.issues.length)if(YG.has(typeof z))U.issues.push(...b8(z,$.issues));else U.issues.push({code:"invalid_key",origin:"map",input:I,inst:Q,issues:$.issues.map((K)=>E8(K,J,s4()))});if(Y.issues.length)if(YG.has(typeof z))U.issues.push(...b8(z,Y.issues));else U.issues.push({origin:"map",code:"invalid_element",input:I,inst:Q,key:z,issues:Y.issues.map((K)=>E8(K,J,s4()))});U.value.set($.value,Y.value)}function dr($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function mr($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function lr($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function or($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function DV($,Y,U){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa
Line truncated
import{createRequireasFx0}from"node:module";varzx0=Object.create;var{getPrototypeOf:Gx0,defineProperty:SE,getOwnPropertyNames:Hx0}=Object;varWx0=Object.prototype.hasOwnProperty;functionXx0($){returnthis[$]}varZx0,qx0,H6=($,Y,U)=>{varI=$!=null&&typeof$==="object";if(I){varQ=Y?Zx0??=newWeakMap:qx0??=newWeakMap,J=Q.get($);if(J)returnJ}U=$!=null?zx0(Gx0($)):{};letK=Y||!$||!$.__esModule?SE(U,"default",{value:$,enumerable:!0}):U;for(letzofHx0($))if(!Wx0.call(K,z))SE(K,z,{get:Xx0.bind($,z),enumerable:!0});if(I)Q.set($,K);returnK};varj=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);varVx0=($)=>$;functionLx0($,Y){this[$]=Vx0.bind(null,Y)}varL8=($,Y)=>{for(varUinY)SE($,U,{get:Y[U],enumerable:!0,configurable:!0,set:Lx0.bind(Y,U)})};varo=($,Y)=>()=>($&&(Y=$($=0)),Y);varK0=Fx0(import.meta.url);varwx0,qV,Mx0,Ox0,Nx0,Dx0,_0=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports),br=($,Y)=>{letU={};for(varIin$)qV(U,I,{get:$[I],enumerable:!0});if(Y)qV(U,Symbol.toStringTag,{value:"Module"});returnU},Ax0=($,Y,U,I)=>{if(Y&&typeofY==="object"||typeofY==="function"){for(varQ=Ox0(Y),J=0,K=Q.length,z;J<K;J++)if(z=Q[J],!Dx0.call($,z)&&z!==U)qV($,z,{get:((G)=>Y[G]).bind(null,z),enumerable:!(I=Mx0(Y,z))||I.enumerable})}return$},VV=($,Y,U)=>(U=$!=null?wx0(Nx0($)):{},Ax0(Y||!$||!$.__esModule?qV(U,"default",{value:$,enumerable:!0}):U,$));varhE=o(()=>{wx0=Object.create,qV=Object.defineProperty,Mx0=Object.getOwnPropertyDescriptor,Ox0=Object.getOwnPropertyNames,Nx0=Object.getPrototypeOf,Dx0=Object.prototype.hasOwnProperty});functioncr($){returntypeof$==="string"&&ir.has($.replace(/#$/,""))}functionnr($,Y){if(!("$schema"in$)||typeof$.$schema!=="string")return"2020-12";letU=$.$schema.replace(/#$/,"");if(Bx0.has(U))return"2020-12";if(ir.has(U))return"2019-09";if(Px0.has(U)||Tx0.has(U))return"draft-7";throwError(`JSON Schema declares an unsupported dialect ("$schema": "${$.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${Y}`)}varBx0,ir,Px0,Tx0;varyE=o(()=>{Bx0=newSet(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),ir=newSet(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Px0=newSet(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Tx0=newSet(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});functionH0($,Y,U){functionI(z,G){if(!z._zod)Object.defineProperty(z,"_zod",{value:{def:G,constr:K,traits:newSet},enumerable:!1});if(z._zod.traits.has($))return;z._zod.traits.add($),Y(z,G);letH=K.prototype,W=Object.keys(H);for(letX=0;X<W.length;X++){letZ=W[X];if(!(Zinz))z[Z]=H[Z].bind(z)}}letQ=U?.Parent??Object;classJextendsQ{}Object.defineProperty(J,"name",{value:$});functionK(z){varG;letH=U?.Parent?newJ:this;I(H,z),(G=H._zod).deferred??(G.deferred=[]);for(letWofH._zod.deferred)W();returnH}returnObject.defineProperty(K,"init",{value:I}),Object.defineProperty(K,Symbol.hasInstance,{value:(z)=>{if(U?.Parent&&zinstanceofU.Parent)return!0;returnz?._zod?.traits?.has($)}}),Object.defineProperty(K,"name",{value:$}),K}functione4($){if($)Object.assign(yY,$);returnyY}vardr,GG,gE,e5,gY,yY;varkY=o(()=>{GG=Object.freeze({status:"aborted"});gE=Symbol("zod_brand");e5=classe5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};gY=classgYextendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(dr=globalThis).__zod_globalConfig??(dr.__zod_globalConfig={});yY=globalThis.__zod_globalConfig});varx0={};L8(x0,{unwrapMessage:()=>HG,uint8ArrayToHex:()=>sx0,uint8ArrayToBase64url:()=>ox0,uint8ArrayToBase64:()=>lr,stringifyPrimitive:()=>h0,slugify:()=>fE,shallowClone:()=>bE,safeExtend:()=>cx0,required:()=>px0,randomString:()=>gx0,propertyKeyTypes:()=>ZG,promiseAllObject:()=>yx0,primitiveTypes:()=>iE,prefixIssues:()=>l8,pick:()=>ux0,partial:()=>dx0,parsedType:()=>g0,optionalKeys:()=>cE,omit:()=>bx0,objectClone:()=>vx0,numKeys:()=>kx0,nullish:()=>O7,normalizeParams:()=>f0,mergeDefs:()=>$3,merge:()=>nx0,jsonStringifyReplacer:()=>$Q,joinValues:()=>O0,issue:()=>UQ,isPlainObject:()=>D7,isObject:()=>xY,hexToUint8Array:()=>rx0,getSizableOrigin:()=>qG,getParsedType:()=>xx0,getLengthableOrigin:()=>VG,getEnumValues:()=>WG,getElementAtPath:()=>hx0,floatSafeRemainder:()=>xE,finalizeIssue:()=>S8,extend:()=>ix0,explicitlyAborted:()=>pE,escapeRegex:()=>h$,esc:()=>LV,defineLazy:()=>C1,createTransparentProxy:()=>fx0,cloneDef:()=>Sx0,clone:()=>v8,cleanRegex:()=>XG,cleanEnum:()=>mx0,captureStackTrace:()=>FV,cached:()=>YQ,base64urlToUint8Array:()=>lx0,base64ToUint8Array:()=>mr,assignProp:()=>N7,assertNotEqual:()=>jx0,assertNever:()=>Rx0,assertIs:()=>Cx0,assertEqual:()=>Ex0,assert:()=>_x0,allowsEval:()=>uE,aborted:()=>A7,NUMBER_FORMAT_RANGES:()=>nE,Class:()=>orLine truncated
`)}var rr=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,$Q,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},LG,o8;var oE=o(()=>{kY();$1();LG=H0("$ZodError",rr),o8=H0("$ZodError",rr,{Parent:Error})});var IQ=($)=>(Y,U,I,Q)=>{let J=I?{...I,async:!1}:{async:!1},K=Y._zod.run({value:U,issues:[]},J);if(K instanceof Promise)throw new e5;if(K.issues.length){let z=new(Q?.Err??$)(K.issues.map((G)=>S8(G,J,e4())));throw FV(z,Q?.callee),z}return K.value},wV,QQ=($)=>async(Y,U,I,Q)=>{let J=I?{...I,async:!0}:{async:!0},K=Y._zod.run({value:U,issues:[]},J);if(K instanceof Promise)K=await K;if(K.issues.length){let z=new(Q?.Err??$)(K.issues.map((G)=>S8(G,J,e4())));throw FV(z,Q?.callee),z}return K.value},MV,JQ=($)=>(Y,U,I)=>{let Q=I?{...I,async:!1}:{async:!1},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)throw new e5;return J.issues.length?{success:!1,error:new($??LG)(J.issues.map((K)=>S8(K,Q,e4())))}:{success:!0,data:J.value}},rE,KQ=($)=>async(Y,U,I)=>{let Q=I?{...I,async:!0}:{async:!0},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((K)=>S8(K,Q,e4())))}:{success:!0,data:J.value}},sE,OV=($)=>(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return IQ($)(Y,U,Q)},tx0,NV=($)=>(Y,U,I)=>{return IQ($)(Y,U,I)},ex0,DV=($)=>async(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return QQ($)(Y,U,Q)},$f0,AV=($)=>async(Y,U,I)=>{return QQ($)(Y,U,I)},Yf0,BV=($)=>(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return JQ($)(Y,U,Q)},Uf0,PV=($)=>(Y,U,I)=>{return JQ($)(Y,U,I)},If0,TV=($)=>async(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return KQ($)(Y,U,Q)},Qf0,EV=($)=>async(Y,U,I)=>{return KQ($)(Y,U,I)},Jf0;var aE=o(()=>{kY();oE();$1();wV=IQ(o8),MV=QQ(o8),rE=JQ(o8),sE=KQ(o8),tx0=OV(o8),ex0=NV(o8),$f0=DV(o8),Yf0=AV(o8),Uf0=BV(o8),If0=PV(o8),Qf0=TV(o8),Jf0=EV(o8)});var Z$={};L8(Z$,{xid:()=>Yj,uuid7:()=>Hf0,uuid6:()=>Gf0,uuid4:()=>zf0,uuid:()=>fY,uppercase:()=>Ej,unicodeEmail:()=>ar,undefined:()=>Pj,ulid:()=>$j,time:()=>wj,string:()=>Oj,sha512_hex:()=>_f0,sha512_base64url:()=>Sf0,sha512_base64:()=>vf0,sha384_hex:()=>jf0,sha384_base64url:()=>Rf0,sha384_base64:()=>Cf0,sha256_hex:()=>Pf0,sha256_base64url:()=>Ef0,sha256_base64:()=>Tf0,sha1_hex:()=>Df0,sha1_base64url:()=>Bf0,sha1_base64:()=>Af0,rfc5322Email:()=>Xf0,number:()=>MG,null:()=>Bj,nanoid:()=>Ij,md5_hex:()=>Mf0,md5_base64url:()=>Nf0,md5_base64:()=>Of0,mac:()=>Wj,lowercase:()=>Tj,ksuid:()=>Uj,ipv6:()=>Hj,ipv4:()=>Gj,integer:()=>Dj,idnEmail:()=>Zf0,httpProtocol:()=>Vj,html5Email:()=>Wf0,hostname:()=>Lf0,hex:()=>wf0,guid:()=>Jj,extendedDuration:()=>Kf0,emoji:()=>zj,email:()=>Kj,e164:()=>Lj,duration:()=>Qj,domain:()=>Ff0,datetime:()=>Mj,date:()=>Fj,cuid2:()=>eE,cuid:()=>tE,cidrv6:()=>Zj,cidrv4:()=>Xj,browserEmail:()=>qf0,boolean:()=>Aj,bigint:()=>Nj,base64url:()=>jV,base64:()=>qj});function zj(){return new RegExp(Vf0,"u")}function er($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function wj($){return new RegExp(`^${er($)}$`)}function Mj($){let Y=er({precision:$.precision}),U=["Z"];if($.local)U.push("");if($.offset)U.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let I=`${Y}(?:${U.join("|")})`;return new RegExp(`^${tr}T(?:${I})$`)}function OG($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function NG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var tE,eE,$j,Yj,Uj,Ij,Qj,Kf0,Jj,fY=($)=>{if(!$)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)$/;returnnewRegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},zf0,Gf0,Hf0,Kj,Wf0,Xf0,ar,Zf0,qf0,Vf0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Gj,Hj,Wj=($)=>{letY=h$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},Xj,Zj,qj,jV,Lf0,Ff0,Vj,Lj,tr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Fj,Oj=($)=>{letY=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${Y}$`)},Nj,Dj,MG,Aj,Bj,Pj,Tj,Ej,wf0,Mf0,Of0,Nf0,Df0,Af0,Bf0,Pf0,Tf0,Ef0,jf0,Cf0,Rf0,_f0,vf0,Sf0;varCV=o(()=>{$1();tE=/^[cC][0-9a-z]{6,}$/,eE=/^[0-9a-z]+$/,$j=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yj=/^[0-9a-vA-V]{20}$/,Uj=/^[A-Za-z0-9]{27}$/,Ij=/^[a-zA-Z0-9_-]{21}$/,Qj=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((J)=>J),I=Math.min(...U.map((J)=>J.length-J.trimStart().length)),Q=U.map((J)=>J.slice(I)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of Q)this.content.push(J)}compile(){let $=Function,Y=this?.args,I=[...(this?.content??[""]).map((Q)=>`${Q}`)];return new $(...Y,I.join(`
`))}}var pj;var mj=o(()=>{pj={major:4,minor:4,patch:3}});function VC($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function ws($){if(!jV.test($))return!1;let Y=$.replace(/[-_]/g,(I)=>I==="-"?"+":"/"),U=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return VC(U)}function Ms($,Y=null){try{let U=$.split(".");if(U.length!==3)return!1;let[I]=U;if(!I)return!1;let Q=JSON.parse(atob(I));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(Y&&(!("alg"in Q)||Q.alg!==Y))return!1;return!0}catch{return!1}}function Is($,Y,U){if($.issues.length)Y.issues.push(...l8(U,$.issues));Y.value[U]=$.value}function kV($,Y,U,I,Q,J){let K=U in I;if($.issues.length){if(Q&&J&&!K)return;Y.issues.push(...l8(U,$.issues))}if(!K&&!Q){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[U]});return}if($.value===void 0){if(K)Y.value[U]=void 0}else Y.value[U]=$.value}function Os($){let Y=Object.keys($.shape);for(let I of Y)if(!$.shape?.[I]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${I}":expectedaZodschema`);let U=cE($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(U)}}function Ns($,Y,U,I,Q,J){let K=[],z=Q.keySet,G=Q.catchall._zod,H=G.def.type,W=G.optin==="optional",X=G.optout==="optional";for(let Z in Y){if(Z==="__proto__")continue;if(z.has(Z))continue;if(H==="never"){K.push(Z);continue}let q=G.run({value:Y[Z],issues:[]},I);if(q instanceof Promise)$.push(q.then((V)=>kV(V,U,Z,Y,W,X)));else kV(q,U,Z,Y,W,X)}if(K.length)U.issues.push({code:"unrecognized_keys",keys:K,input:Y,inst:J});if(!$.length)return U;return Promise.all($).then(()=>{return U})}function Qs($,Y,U,I){for(let J of $)if(J.issues.length===0)return Y.value=J.value,Y;let Q=$.filter((J)=>!A7(J));if(Q.length===1)return Y.value=Q[0].value,Q[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((J)=>J.issues.map((K)=>S8(K,I,e4())))}),Y}function Js($,Y,U,I){let Q=$.filter((J)=>J.issues.length===0);if(Q.length===1)return Y.value=Q[0].value,Y;if(Q.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((J)=>J.issues.map((K)=>S8(K,I,e4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:[],inclusive:!1});return Y}function lj($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(D7($)&&D7(Y)){let U=Object.keys(Y),I=Object.keys($).filter((J)=>U.indexOf(J)!==-1),Q={...$,...Y};for(let J of I){let K=lj($[J],Y[J]);if(!K.valid)return{valid:!1,mergeErrorPath:[J,...K.mergeErrorPath]};Q[J]=K.data}return{valid:!0,data:Q}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let I=0;I<$.length;I++){let Q=$[I],J=Y[I],K=lj(Q,J);if(!K.valid)return{valid:!1,mergeErrorPath:[I,...K.mergeErrorPath]};U.push(K.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function Ks($,Y,U){let I=new Map,Q;for(let z of Y.issues)if(z.code==="unrecognized_keys"){Q??(Q=z);for(let G of z.keys){if(!I.has(G))I.set(G,{});I.get(G).l=!0}}else $.issues.push(z);for(let z of U.issues)if(z.code==="unrecognized_keys")for(let G of z.keys){if(!I.has(G))I.set(G,{});I.get(G).r=!0}else $.issues.push(z);let J=[...I].filter(([,z])=>z.l&&z.r).map(([z])=>z);if(J.length&&Q)$.issues.push({...Q,keys:J});if(A7($))return $;let K=lj(Y.value,U.value);if(!K.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(K.mergeErrorPath)}`);return $.value=K.data,$}function zs($,Y){for(let U=$.length-1;U>=0;U--)if($[U]._zod[Y]!=="optional")return U+1;return 0}function Gs($,Y,U){if($.issues.length)Y.issues.push(...l8(U,$.issues));Y.value[U]=$.value}function Hs($,Y,U,I,Q){for(let J=0;J<U.length;J++){let K=$[J],z=J<I.length;if(K.issues.length){if(!z&&J>=Q){Y.value.length=J;break}Y.issues.push(...l8(J,K.issues))}Y.value[J]=K.value}for(let J=Y.value.length-1;J>=I.length;J--)if(U[J]._zod.optout==="optional"&&Y.value[J]===void 0)Y.value.length=J;else break;return Y}function Ws($,Y,U,I,Q,J,K){if($.issues.length)if(ZG.has(typeof I))U.issues.push(...l8(I,$.issues));else U.issues.push({code:"invalid_key",origin:"map",input:Q,inst:J,issues:$.issues.map((z)=>S8(z,K,e4()))});if(Y.issues.length)if(ZG.has(typeof I))U.issues.push(...l8(I,Y.issues));else U.issues.push({origin:"map",code:"invalid_element",input:Q,inst:J,key:I,issues:Y.issues.map((z)=>S8(z,K,e4()))});U.value.set($.value,Y.value)}function Xs($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function Zs($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function qs($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function Vs($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function hV($,Y,U){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa
Line truncated
@@ -60,94 +60,94 @@ import{createRequire as Ak0}from"node:module";var qk0=Object.create;var{getProto
newResult[${P}]=${D}.value;
}
`)}q.write("payload.value = newResult;"),q.write("return payload;");let N=q.compile();return(O,D)=>N(Z,O,D)},Q,J=CY,K=!TY.jitless,H=K&&jj.value,W=Y.catchall,X;$._zod.parse=(Z,q)=>{X??(X=z.value);let V=Z.value;if(!J(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(K&&H&&q?.async===!1&&q.jitless!==!0){if(!Q)Q=I(Y.shape);if(Z=Q(Z,q),!W)return Z;return $s([],V,Z,q,X,$)}return U(Z,q)}});XG=H0("$ZodUnion",($,Y)=>{V1.init($,Y),E1($._zod,"optin",()=>Y.options.some((z)=>z._zod.optin==="optional")?"optional":void 0),E1($._zod,"optout",()=>Y.options.some((z)=>z._zod.optout==="optional")?"optional":void 0),E1($._zod,"values",()=>{if(Y.options.every((z)=>z._zod.values))return new Set(Y.options.flatMap((z)=>Array.from(z._zod.values)));return}),E1($._zod,"pattern",()=>{if(Y.options.every((z)=>z._zod.pattern)){let z=Y.options.map((I)=>I._zod.pattern);return new RegExp(`^(${z.map((I)=>$G(I.source)).join("|")})$`)}return});let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,I)=>{if(U)return U(z,I);let Q=!1,J=[];for(let K of Y.options){let G=K._zod.run({value:z.value,issues:[]},I);if(G instanceof Promise)J.push(G),Q=!0;else{if(G.issues.length===0)return G;J.push(G)}}if(!Q)return fr(J,z,$,I);return Promise.all(J).then((K)=>{return fr(K,z,$,I)})}});OC=H0("$ZodXor",($,Y)=>{XG.init($,Y),Y.inclusive=!1;let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,I)=>{if(U)return U(z,I);let Q=!1,J=[];for(let K of Y.options){let G=K._zod.run({value:z.value,issues:[]},I);if(G instanceof Promise)J.push(G),Q=!0;else J.push(G)}if(!Q)return ur(J,z,$,I);return Promise.all(J).then((K)=>{return ur(K,z,$,I)})}}),NC=H0("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,XG.init($,Y);let U=$._zod.parse;E1($._zod,"propValues",()=>{let I={};for(let Q of Y.options){let J=Q._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(Q)}"`);for(let[K,G]of Object.entries(J)){if(!I[K])I[K]=new Set;for(let H of G)I[K].add(H)}}return I});let z=lz(()=>{let I=Y.options,Q=new Map;for(let J of I){let K=J._zod.propValues?.[Y.discriminator];if(!K||K.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(J)}"`);for(let G of K){if(Q.has(G))throw Error(`Duplicatediscriminatorvalue"${String(G)}"`);Q.set(G,J)}}return Q});$._zod.parse=(I,Q)=>{let J=I.value;if(!CY(J))return I.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),I;let K=z.value.get(J?.[Y.discriminator]);if(K)return K._zod.run(I,Q);if(Y.unionFallback||Q.direction==="backward")return U(I,Q);return I.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(z.value.keys()),input:J,path:[Y.discriminator],inst:$}),I}}),DC=H0("$ZodIntersection",($,Y)=>{V1.init($,Y),$._zod.parse=(U,z)=>{let I=U.value,Q=Y.left._zod.run({value:I,issues:[]},z),J=Y.right._zod.run({value:I,issues:[]},z);if(Q instanceof Promise||J instanceof Promise)return Promise.all([Q,J]).then(([G,H])=>{return br(U,G,H)});return br(U,Q,J)}});EV=H0("$ZodTuple",($,Y)=>{V1.init($,Y);let U=Y.items;$._zod.parse=(z,I)=>{let Q=z.value;if(!Array.isArray(Q))return z.issues.push({input:Q,inst:$,expected:"tuple",code:"invalid_type"}),z;z.value=[];let J=[],K=ir(U,"optin"),G=ir(U,"optout");if(!Y.rest){if(Q.length<K)return z.issues.push({code:"too_small",minimum:K,inclusive:!0,input:Q,inst:$,origin:"array"}),z;if(Q.length>U.length)z.issues.push({code:"too_big",maximum:U.length,inclusive:!0,input:Q,inst:$,origin:"array"})}let H=Array(U.length);for(let W=0;W<U.length;W++){let X=U[W]._zod.run({value:Q[W],issues:[]},I);if(X instanceof Promise)J.push(X.then((Z)=>{H[W]=Z}));else H[W]=X}if(Y.rest){let W=U.length-1,X=Q.slice(U.length);for(let Z of X){W++;let q=Y.rest._zod.run({value:Z,issues:[]},I);if(q instanceof Promise)J.push(q.then((V)=>cr(V,z,W)));else cr(q,z,W)}}if(J.length)return Promise.all(J).then(()=>nr(H,z,U,Q,G));return nr(H,z,U,Q,G)}});AC=H0("$ZodRecord",($,Y)=>{V1.init($,Y),$._zod.parse=(U,z)=>{let I=U.value;if(!Z7(I))return U.issues.push({expected:"record",code:"invalid_type",input:I,inst:$}),U;let Q=[],J=Y.keyType._zod.values;if(J){U.value={};let K=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){K.add(typeof H==="number"?H.toString():H);let W=Y.keyType._zod.run({value:H,issues:[]},z);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length){U.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((q)=>E8(q,z,s4())),input:H,path:[H],inst:$});continue}let X=W.value,Z=Y.valueType._zod.run({value:I[H],issues:[]},z);if(Z instanceof Promise)Q.push(Z.then((q)=>{if(q.issues.length)U.issues.push(...b8(H,q.issues));U.value[X]=q.value}));else{if(Z.issues.length)U.issues.push(...b8(H,Z.issues));U.value[X]=Z.value}}let G;for(let H in I)if(!K.has(H))G=G??[],G.push(H);if(G&&G.length>0)U.issues.push({code:"unrec
Line truncated
`)}q.write("payload.value = newResult;"),q.write("return payload;");let N=q.compile();return(O,D)=>N(Z,O,D)},J,K=xY,z=!yY.jitless,H=z&&uE.value,W=Y.catchall,X;$._zod.parse=(Z,q)=>{X??(X=I.value);let V=Z.value;if(!K(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(z&&H&&q?.async===!1&&q.jitless!==!0){if(!J)J=Q(Y.shape);if(Z=J(Z,q),!W)return Z;return Ns([],V,Z,q,X,$)}return U(Z,q)}});AG=H0("$ZodUnion",($,Y)=>{V1.init($,Y),C1($._zod,"optin",()=>Y.options.some((I)=>I._zod.optin==="optional")?"optional":void 0),C1($._zod,"optout",()=>Y.options.some((I)=>I._zod.optout==="optional")?"optional":void 0),C1($._zod,"values",()=>{if(Y.options.every((I)=>I._zod.values))return new Set(Y.options.flatMap((I)=>Array.from(I._zod.values)));return}),C1($._zod,"pattern",()=>{if(Y.options.every((I)=>I._zod.pattern)){let I=Y.options.map((Q)=>Q._zod.pattern);return new RegExp(`^(${I.map((Q)=>XG(Q.source)).join("|")})$`)}return});let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(I,Q)=>{if(U)return U(I,Q);let J=!1,K=[];for(let z of Y.options){let G=z._zod.run({value:I.value,issues:[]},Q);if(G instanceof Promise)K.push(G),J=!0;else{if(G.issues.length===0)return G;K.push(G)}}if(!J)return Qs(K,I,$,Q);return Promise.all(K).then((z)=>{return Qs(z,I,$,Q)})}});SC=H0("$ZodXor",($,Y)=>{AG.init($,Y),Y.inclusive=!1;let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(I,Q)=>{if(U)return U(I,Q);let J=!1,K=[];for(let z of Y.options){let G=z._zod.run({value:I.value,issues:[]},Q);if(G instanceof Promise)K.push(G),J=!0;else K.push(G)}if(!J)return Js(K,I,$,Q);return Promise.all(K).then((z)=>{return Js(z,I,$,Q)})}}),hC=H0("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,AG.init($,Y);let U=$._zod.parse;C1($._zod,"propValues",()=>{let Q={};for(let J of Y.options){let K=J._zod.propValues;if(!K||Object.keys(K).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(J)}"`);for(let[z,G]of Object.entries(K)){if(!Q[z])Q[z]=new Set;for(let H of G)Q[z].add(H)}}return Q});let I=YQ(()=>{let Q=Y.options,J=new Map;for(let K of Q){let z=K._zod.propValues?.[Y.discriminator];if(!z||z.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(K)}"`);for(let G of z){if(J.has(G))throw Error(`Duplicatediscriminatorvalue"${String(G)}"`);J.set(G,K)}}return J});$._zod.parse=(Q,J)=>{let K=Q.value;if(!xY(K))return Q.issues.push({code:"invalid_type",expected:"object",input:K,inst:$}),Q;let z=I.value.get(K?.[Y.discriminator]);if(z)return z._zod.run(Q,J);if(Y.unionFallback||J.direction==="backward")return U(Q,J);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(I.value.keys()),input:K,path:[Y.discriminator],inst:$}),Q}}),yC=H0("$ZodIntersection",($,Y)=>{V1.init($,Y),$._zod.parse=(U,I)=>{let Q=U.value,J=Y.left._zod.run({value:Q,issues:[]},I),K=Y.right._zod.run({value:Q,issues:[]},I);if(J instanceof Promise||K instanceof Promise)return Promise.all([J,K]).then(([G,H])=>{return Ks(U,G,H)});return Ks(U,J,K)}});uV=H0("$ZodTuple",($,Y)=>{V1.init($,Y);let U=Y.items;$._zod.parse=(I,Q)=>{let J=I.value;if(!Array.isArray(J))return I.issues.push({input:J,inst:$,expected:"tuple",code:"invalid_type"}),I;I.value=[];let K=[],z=zs(U,"optin"),G=zs(U,"optout");if(!Y.rest){if(J.length<z)return I.issues.push({code:"too_small",minimum:z,inclusive:!0,input:J,inst:$,origin:"array"}),I;if(J.length>U.length)I.issues.push({code:"too_big",maximum:U.length,inclusive:!0,input:J,inst:$,origin:"array"})}let H=Array(U.length);for(let W=0;W<U.length;W++){let X=U[W]._zod.run({value:J[W],issues:[]},Q);if(X instanceof Promise)K.push(X.then((Z)=>{H[W]=Z}));else H[W]=X}if(Y.rest){let W=U.length-1,X=J.slice(U.length);for(let Z of X){W++;let q=Y.rest._zod.run({value:Z,issues:[]},Q);if(q instanceof Promise)K.push(q.then((V)=>Gs(V,I,W)));else Gs(q,I,W)}}if(K.length)return Promise.all(K).then(()=>Hs(H,I,U,J,G));return Hs(H,I,U,J,G)}});gC=H0("$ZodRecord",($,Y)=>{V1.init($,Y),$._zod.parse=(U,I)=>{let Q=U.value;if(!D7(Q))return U.issues.push({expected:"record",code:"invalid_type",input:Q,inst:$}),U;let J=[],K=Y.keyType._zod.values;if(K){U.value={};let z=new Set;for(let H of K)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){z.add(typeof H==="number"?H.toString():H);let W=Y.keyType._zod.run({value:H,issues:[]},I);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length){U.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((q)=>S8(q,I,e4())),input:H,path:[H],inst:$});continue}let X=W.value,Z=Y.valueType._zod.run({value:Q[H],issues:[]},I);if(Z instanceof Promise)J.push(Z.then((q)=>{if(q.issues.length)U.issues.push(...l8(H,q.issues));U.value[X]=q.value}));else{if(Z.issues.length)U.issues.push(...l8(H,Z.issues));U.value[X]=Z.value}}let G;for(let H in Q)if(!z.has(H))G=G??[],G.push(H);if(G&&G.length>0)U.issues.push({code:"unrec
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letJof$.seen.entries()){letK=J[1];if(Y===J[0]){Q(J);continue}if($.external){letH=$.external.registry.get(J[0])?.id;if(Y!==J[0]&&H){Q(J);continue}}if($.metadataRegistry.get(J[0])?.id){Q(J);continue}if(K.cycle){Q(J);continue}if(K.count>1){if($.reused==="ref"){Q(J);continue}}}}functionM7($,Y){letU=$.seen.get(Y);if(!U)throwError("Unprocessed schema. This is a bug in Zod.");letz=(K)=>{letG=$.seen.get(K);if(G.ref===null)return;letH=G.def??G.schema,W={...H},X=G.ref;if(G.ref=null,X){z(X);letq=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(V);elseObject.assign(H,V);if(Object.assign(H,W),K._zod.parent===X)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(!(MinW))deleteH[M]}if(V.$ref&&q.def)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(Minq.def&&JSON.stringify(H[M])===JSON.stringify(q.def[M]))deleteH[M]}}letZ=K._zod.parent;if(Z&&Z!==X){z(Z);letq=$.seen.get(Z);if(q?.schema.$ref){if(H.$ref=q.schema.$ref,q.def)for(letVinH){if(V==="$ref"||V==="allOf")continue;if(Vinq.def&&JSON.stringify(H[V])===JSON.stringify(q.def[V]))deleteH[V]}}}$.override({zodSchema:K,jsonSchema:H,path:G.path??[]})};for(letKof[...$.seen.entries()].reverse())z(K[0]);letI={};if($.target==="draft-2020-12")I.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")I.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")I.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letK=$.external.registry.get(Y)?.id;if(!K)throwError("Schema is missing an `id` property");I.$id=$.external.uri(K)}Object.assign(I,U.def??U.schema);letQ=$.metadataRegistry.get(Y)?.id;if(Q!==void0&&I.id===Q)deleteI.id;letJ=$.external?.defs??{};for(letKof$.seen.entries()){letG=K[1];if(G.def&&G.defId){if(G.def.id===G.defId)deleteG.def.id;J[G.defId]=G.def}}if($.external);elseif(Object.keys(J).length>0)if($.target==="draft-2020-12")I.$defs=J;elseI.definitions=J;try{letK=JSON.parse(JSON.stringify(I));returnObject.defineProperty(K,"~standard",{value:{...Y["~standard"],jsonSchema:{input:VI(Y,"input",$.processors),output:VI(Y,"output",$.processors)}},enumerable:!1,writable:!1}),K}catch(K){throwError("Error converting schema to JSON.")}}functionR8($,Y){letU=Y??{seen:newSet};if(U.seen.has($))return!1;U.seen.add($);letz=$._zod.def;if(z.type==="transform")return!0;if(z.type==="array")returnR8(z.element,U);if(z.type==="set")returnR8(z.valueType,U);if(z.type==="lazy")returnR8(z.getter(),U);if(z.type==="promise"||z.type==="optional"||z.type==="nonoptional"||z.type==="nullable"||z.type==="readonly"||z.type==="default"||z.type==="prefault")returnR8(z.innerType,U);if(z.type==="intersection")returnR8(z.left,U)||R8(z.right,U);if(z.type==="record"||z.type==="map")returnR8(z.keyType,U)||R8(z.valueType,U);if(z.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnR8(z.in,U)||R8(z.out,U)}if(z.type==="object"){for(letIinz.shape)if(R8(z.shape[I],U))return!0;return!1}if(z.type==="union"){for(letIofz.options)if(R8(I,U))return!0;return!1}if(z.type==="tuple"){for(letIofz.items)if(R8(I,U))return!0;if(z.rest&&R8(z.rest,U))return!0;return!1}return!1}varh_=($,Y={})=>(U)=>{letz=F7({...U,processors:Y});returnK4($,z),w7(z,$),M7(z,$)},VI=($,Y,U={})=>(z)=>{let{libraryOptions:I,target:Q}=z??{},J=F7({...I??{},target:Q,io:Y,processors:U});returnK4($,J),w7(J,$),M7(J,$)};varDG=m(()=>{MG()});functiongY($,Y){if("_idmap"in$){letz=$,I=F7({...Y,processors:UL}),Q={};for(letGofz._idmap.entries()){let[H,W]=G;K4(W,I)}letJ={},K={registry:z,uri:Y?.uri,defs:Q};I.external=K;for(letGofz._idmap.entries()){let[H,W]=G;w7(I,W),J[H]=M7(I,W)}if(Object.keys(Q).length>0){letG=I.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[G]:Q}}return{schemas:J}}letU=F7({...Y,processors:UL});returnK4($,U),w7(U,$),M7(U,$)}varJu0,S_=($,Y,U,z)=>{letI=U;I.type="string";let{minimum:Q,maximum:J,format:K,patterns:G,contentEncoding:H}=$._zod.bag;if(typeofQ==="number")I.minLength=Q;if(typeofJ==="number")I.maxLength=J;if(K){if(I.format=Ju0[K]??K,I.format==="")deleteI.format;if(K==="time")deleteI.format}if(H)I.contentEncoding=H;if(G&&G.size>0){letW=[...G];if(W.length===1)I.pattern=W[0].source;elseif(W.length>1)I.allOf=[...W.map((X)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:X.source}))]}},g_=($,Y,U,z)=>{letI=U,{minimum:Q,maximum:J,format:K,multipleOf:G,exclusiveMaximum:H,exclusiveMinimum:W}=$._zod.bag;if(typeofK==="string"&&K.includes("int"))I.type="integer";elseI.type="number";letX=typeofW==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),Z=typeofH==="number"&&H<=(J??Number.POSITIVE_INFINITY),q=Y.target==="draft-04"||Y.target==="openapi-3.0";if(X)if(q)I.minimum=W,I.exclusiveMinimum=!0;elseI.exclusiveMinimuLine truncated
`}function bb0($){let Y=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Toolnameexceedsmaximumlengthof128characters(current:${$.length})`]};if($.includes(" "))Y.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))Y.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))Y.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))Y.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!ub0.test($)){let U=[...$].filter((z)=>!/[A-Za-z0-9._-]/.test(z)).filter((z,I,Q)=>Q.indexOf(z)===I);return Y.push(`Toolnamecontainsinvalidcharacters:${U.map((z)=>`"${z}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function ib0($,Y){if(Y.length>0){console.warn(`Toolnamevalidationwarningfor"${$}":`);for(let U of Y)console.warn(`-${U}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function RS($){let Y=bb0($);return ib0($,Y.warnings),Y.isValid}function cb0($){return typeof $==="object"&&$!==null&&"_zod"in $}function nb0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function pb0($){if(typeof $!=="object"||$===null)return!1;if(xI($))return!1;let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return!1;return Object.values($).every((U)=>cb0(U))}function cw($){if($===void 0)return;if(pb0($))return U0($);if(typeof $==="object"&&$!==null&&!xI($)&&Object.values($).some((Y)=>nb0(Y)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!xI($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var zS,Au0,T1,L1,Bu0,ot="2026-07-28",v7,at,ju0,Eu0,Cu0,$e,Ye,_u0,jw,Cb1,Rb1,kt,XS,ku0,xu0,yI,i0,I1,yw,Ie,uI,kw,bu0=0,iu0="private",cu0,su0,Cw,LS,Ke,_b1,vb1,Ub0,zb0,FS,Rw,FH="2026-07-28",We,Jb0,P$=($)=>cG.safeParse($).success,h7=($)=>nG.safeParse($).success,VH=($)=>PI.safeParse($).success,bw=($)=>TI.safeParse($).success,Y3=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",it="x-mcp-header",Kb0,Gb0,Hb0,Wb0,hw=-32020,hb1,Xb0,ct=!1,QS="draft-2020-12",Vb0,Ob0,Nb0,nt,Db0,Eb0,qe=250,Cb0,Rb0,we,Me,_b0,vb0,Ne=60000,Sb0,gb0,yb0,De,TS,fb0,Sb1,Ae=10485760,ES=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??Ae}append($){if((this._buffer?.length??0)+$.length>this._maxBufferSize)throw this.clear(),Error(`ReadBufferexceededmaximumsizeof${this._maxBufferSize}bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){while(this._buffer){let $=this._buffer.indexOf(`
`);if($===-1)return null;let Y=this._buffer.toString("utf8",0,$).replace(/\r$/,"");this._buffer=this._buffer.subarray($+1);try{return Be(Y)}catch(U){if(U instanceof SyntaxError)continue;throw U}}return null}clear(){this._buffer=void 0}},ub0;var nw=m(()=>{Nj();Dj();St();Ah();zS=Symbol.for("mcp.sdk.errorBrands");Au0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](Y){return kI(this,Y)}static isInstance(Y){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return kI(this,Y)}constructor(Y,U,z){super(U);this.code=Y,this.errorUri=z,this.name="OAuthError",KS(this,new.target)}toResponseObject(){let Y={error:this.code,error_description:this.message};if(this.errorUri)Y.error_uri=this.errorUri;return Y}static fromResponse(Y){return new $(Y.error,Y.error_description??Y.error,Y.error_uri)}},T1=function($){return $.NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$}({}),L1=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return kI(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return kI(this,$)}constructor($,Y,U){super(Y);this.code=$,this.data=U,this.name="SdkError",KS(this,new.target)}},Bu0=class extends L1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,Y,U){super($,Y,U);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};v7=[ot];at=["task","inputRequests","requestState"];Eu0=new Set(["const","enum","default","examples"]),Cu0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);$e={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ye={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},_u0={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};Cb1=Object.keys($e),Rb1=Object.keys(Ye);kt={ok:!1,reason:"not-in-era"};XS={era:"2025-11-25",hasRequestMethod:Ue,hasNotificationMethod:ze,validateRequest:($,Y)=>Ew(Su0($),Y),validateResult:($,Y)=>Ew(hu0($),Y),validateNotification:($,Y)=>Ew(gu0($),Y),hasInputRequestMethod:()=>!1,validateInputRequest:()=>kt,validateInputResponse:()=>kt,samplingResultVariant:($,Y)=>{let U=tt();return Ew($?U.CreateMessageResultWithToolsSchema:U.CreateMessageResultSchema,Y)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,Y){let U=st($),z=U.structuredContent;if(z===void 0)return U;let I=typeof z!=="object"||z===null||Array.isArray(z),Q=Y!==void 0&&et(Y);if(!I&&!Q)return U;return{...U,structuredContent:{result:z}}},decodeResult($,Y){if(IS(Y)&&"resultType"in Y){let U={...Y};return delete U.resultType,{kind:"complete",result:ft(U)}}return{kind:"complete",result:ft(Y)}},encodeResult($,Y){if($!=="tools/list")return Y;l
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letKof$.seen.entries()){letz=K[1];if(Y===K[0]){J(K);continue}if($.external){letH=$.external.registry.get(K[0])?.id;if(Y!==K[0]&&H){J(K);continue}}if($.metadataRegistry.get(K[0])?.id){J(K);continue}if(z.cycle){J(K);continue}if(z.count>1){if($.reused==="ref"){J(K);continue}}}}functionj7($,Y){letU=$.seen.get(Y);if(!U)throwError("Unprocessed schema. This is a bug in Zod.");letI=(z)=>{letG=$.seen.get(z);if(G.ref===null)return;letH=G.def??G.schema,W={...H},X=G.ref;if(G.ref=null,X){I(X);letq=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(V);elseObject.assign(H,V);if(Object.assign(H,W),z._zod.parent===X)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(!(MinW))deleteH[M]}if(V.$ref&&q.def)for(letMinH){if(M==="$ref"||M==="allOf")continue;if(Minq.def&&JSON.stringify(H[M])===JSON.stringify(q.def[M]))deleteH[M]}}letZ=z._zod.parent;if(Z&&Z!==X){I(Z);letq=$.seen.get(Z);if(q?.schema.$ref){if(H.$ref=q.schema.$ref,q.def)for(letVinH){if(V==="$ref"||V==="allOf")continue;if(Vinq.def&&JSON.stringify(H[V])===JSON.stringify(q.def[V]))deleteH[V]}}}$.override({zodSchema:z,jsonSchema:H,path:G.path??[]})};for(letzof[...$.seen.entries()].reverse())I(z[0]);letQ={};if($.target==="draft-2020-12")Q.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")Q.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")Q.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letz=$.external.registry.get(Y)?.id;if(!z)throwError("Schema is missing an `id` property");Q.$id=$.external.uri(z)}Object.assign(Q,U.def??U.schema);letJ=$.metadataRegistry.get(Y)?.id;if(J!==void0&&Q.id===J)deleteQ.id;letK=$.external?.defs??{};for(letzof$.seen.entries()){letG=z[1];if(G.def&&G.defId){if(G.def.id===G.defId)deleteG.def.id;K[G.defId]=G.def}}if($.external);elseif(Object.keys(K).length>0)if($.target==="draft-2020-12")Q.$defs=K;elseQ.definitions=K;try{letz=JSON.parse(JSON.stringify(Q));returnObject.defineProperty(z,"~standard",{value:{...Y["~standard"],jsonSchema:{input:AQ(Y,"input",$.processors),output:AQ(Y,"output",$.processors)}},enumerable:!1,writable:!1}),z}catch(z){throwError("Error converting schema to JSON.")}}functiony8($,Y){letU=Y??{seen:newSet};if(U.seen.has($))return!1;U.seen.add($);letI=$._zod.def;if(I.type==="transform")return!0;if(I.type==="array")returny8(I.element,U);if(I.type==="set")returny8(I.valueType,U);if(I.type==="lazy")returny8(I.getter(),U);if(I.type==="promise"||I.type==="optional"||I.type==="nonoptional"||I.type==="nullable"||I.type==="readonly"||I.type==="default"||I.type==="prefault")returny8(I.innerType,U);if(I.type==="intersection")returny8(I.left,U)||y8(I.right,U);if(I.type==="record"||I.type==="map")returny8(I.keyType,U)||y8(I.valueType,U);if(I.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returny8(I.in,U)||y8(I.out,U)}if(I.type==="object"){for(letQinI.shape)if(y8(I.shape[Q],U))return!0;return!1}if(I.type==="union"){for(letQofI.options)if(y8(Q,U))return!0;return!1}if(I.type==="tuple"){for(letQofI.items)if(y8(Q,U))return!0;if(I.rest&&y8(I.rest,U))return!0;return!1}return!1}varp_=($,Y={})=>(U)=>{letI=T7({...U,processors:Y});returnH4($,I),E7(I,$),j7(I,$)},AQ=($,Y,U={})=>(I)=>{let{libraryOptions:Q,target:J}=I??{},K=T7({...Q??{},target:J,io:Y,processors:U});returnH4($,K),E7(K,$),j7(K,$)};varSG=o(()=>{RG()});functionnY($,Y){if("_idmap"in$){letI=$,Q=T7({...Y,processors:VL}),J={};for(letGofI._idmap.entries()){let[H,W]=G;H4(W,Q)}letK={},z={registry:I,uri:Y?.uri,defs:J};Q.external=z;for(letGofI._idmap.entries()){let[H,W]=G;E7(Q,W),K[H]=j7(Q,W)}if(Object.keys(J).length>0){letG=Q.target==="draft-2020-12"?"$defs":"definitions";K.__shared={[G]:J}}return{schemas:K}}letU=T7({...Y,processors:VL});returnH4($,U),E7(U,$),j7(U,$)}var$b0,m_=($,Y,U,I)=>{letQ=U;Q.type="string";let{minimum:J,maximum:K,format:z,patterns:G,contentEncoding:H}=$._zod.bag;if(typeofJ==="number")Q.minLength=J;if(typeofK==="number")Q.maxLength=K;if(z){if(Q.format=$b0[z]??z,Q.format==="")deleteQ.format;if(z==="time")deleteQ.format}if(H)Q.contentEncoding=H;if(G&&G.size>0){letW=[...G];if(W.length===1)Q.pattern=W[0].source;elseif(W.length>1)Q.allOf=[...W.map((X)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:X.source}))]}},l_=($,Y,U,I)=>{letQ=U,{minimum:J,maximum:K,format:z,multipleOf:G,exclusiveMaximum:H,exclusiveMinimum:W}=$._zod.bag;if(typeofz==="string"&&z.includes("int"))Q.type="integer";elseQ.type="number";letX=typeofW==="number"&&W>=(J??Number.NEGATIVE_INFINITY),Z=typeofH==="number"&&H<=(K??Number.POSITIVE_INFINITY),q=Y.target==="draft-04"||Y.target==="openapi-3.0";if(X)if(q)Q.minimum=W,Q.exclusiveMinimum=!0;elseQ.exclusiveMinimuLine truncated
`}function yi0($){let Y=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Toolnameexceedsmaximumlengthof128characters(current:${$.length})`]};if($.includes(" "))Y.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))Y.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))Y.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))Y.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!hi0.test($)){let U=[...$].filter((I)=>!/[A-Za-z0-9._-]/.test(I)).filter((I,Q,J)=>J.indexOf(I)===Q);return Y.push(`Toolnamecontainsinvalidcharacters:${U.map((I)=>`"${I}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function gi0($,Y){if(Y.length>0){console.warn(`Toolnamevalidationwarningfor"${$}":`);for(let U of Y)console.warn(`-${U}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function ch($){let Y=yi0($);return gi0($,Y.warnings),Y.isValid}function ki0($){return typeof $==="object"&&$!==null&&"_zod"in $}function xi0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function fi0($){if(typeof $!=="object"||$===null)return!1;if(pQ($))return!1;let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return!1;return Object.values($).every((U)=>ki0(U))}function $M($){if($===void 0)return;if(fi0($))return U0($);if(typeof $==="object"&&$!==null&&!pQ($)&&Object.values($).some((Y)=>xi0(Y)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!pQ($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var Fh,Fb0,E1,L1,wb0,Ve="2026-07-28",b7,we,Nb0,Db0,Ab0,Ne,De,Pb0,fw,Yc1,Uc1,Ue,Ph,_b0,vb0,nQ,i0,Q1,lw,Pe,lQ,ow,yb0=0,gb0="private",kb0,db0,bw,Ch,je,Ic1,Qc1,sb0,ab0,Rh,iw,jH="2026-07-28",_e,$i0,y$=($)=>eG.safeParse($).success,i7=($)=>$H.safeParse($).success,TH=($)=>SQ.safeParse($).success,tw=($)=>hQ.safeParse($).success,G3=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",ze="x-mcp-header",Yi0,Ui0,Ii0,Qi0,dw=-32020,Jc1,Ji0,Ge=!1,Mh="draft-2020-12",Gi0,qi0,Vi0,He,Li0,Di0,he=250,Ai0,Bi0,xe,fe,Pi0,Ti0,be=60000,ji0,Ci0,Ri0,ie,fh,Si0,Kc1,ce=10485760,bh=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??ce}append($){if((this._buffer?.length??0)+$.length>this._maxBufferSize)throw this.clear(),Error(`ReadBufferexceededmaximumsizeof${this._maxBufferSize}bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){while(this._buffer){let $=this._buffer.indexOf(`
`);if($===-1)return null;let Y=this._buffer.toString("utf8",0,$).replace(/\r$/,"");this._buffer=this._buffer.subarray($+1);try{return ne(Y)}catch(U){if(U instanceof SyntaxError)continue;throw U}}return null}clear(){this._buffer=void 0}},hi0;var YM=o(()=>{hE();yE();et();gS();Fh=Symbol.for("mcp.sdk.errorBrands");Fb0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](Y){return dQ(this,Y)}static isInstance(Y){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return dQ(this,Y)}constructor(Y,U,I){super(U);this.code=Y,this.errorUri=I,this.name="OAuthError",Nh(this,new.target)}toResponseObject(){let Y={error:this.code,error_description:this.message};if(this.errorUri)Y.error_uri=this.errorUri;return Y}static fromResponse(Y){return new $(Y.error,Y.error_description??Y.error,Y.error_uri)}},E1=function($){return $.NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$}({}),L1=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return dQ(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v=>SdkError.isInstance(v)`");return dQ(this,$)}constructor($,Y,U){super(Y);this.code=$,this.data=U,this.name="SdkError",Nh(this,new.target)}},wb0=class extends L1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,Y,U){super($,Y,U);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};b7=[Ve];we=["task","inputRequests","requestState"];Db0=new Set(["const","enum","default","examples"]),Ab0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);Ne={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},De={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Pb0={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};Yc1=Object.keys(Ne),Uc1=Object.keys(De);Ue={ok:!1,reason:"not-in-era"};Ph={era:"2025-11-25",hasRequestMethod:Ae,hasNotificationMethod:Be,validateRequest:($,Y)=>uw(jb0($),Y),validateResult:($,Y)=>uw(Eb0($),Y),validateNotification:($,Y)=>uw(Cb0($),Y),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Ue,validateInputResponse:()=>Ue,samplingResultVariant:($,Y)=>{let U=Me();return uw($?U.CreateMessageResultWithToolsSchema:U.CreateMessageResultSchema,Y)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,Y){let U=Fe($),I=U.structuredContent;if(I===void 0)return U;let Q=typeof I!=="object"||I===null||Array.isArray(I),J=Y!==void 0&&Oe(Y);if(!Q&&!J)return U;return{...U,structuredContent:{result:I}}},decodeResult($,Y){if(wh(Y)&&"resultType"in Y){let U={...Y};return delete U.resultType,{kind:"complete",result:Qe(U)}}return{kind:"complete",result:Qe(Y)}},encodeResult($,Y){if($!=="tools/list")return Y;l
Line truncated
*content-type
*Copyright(c)2015DouglasChristopherWilson
*MITLicensed
*/fb0=E0(($)=>{var Y=/;*([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,U=/\\([\u000b\u0020-\u00ff])/g,z=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;$.parse=I;function I(K){if(!K)throw TypeError("argument string is required");var G=typeof K==="object"?Q(K):K;if(typeof G!=="string")throw TypeError("argument string is required to be a string");var H=G.indexOf(";"),W=H!==-1?G.slice(0,H).trim():G.trim();if(!z.test(W))throw TypeError("invalid media type");var X=new J(W.toLowerCase());if(H!==-1){var Z,q,V;Y.lastIndex=H;while(q=Y.exec(G)){if(q.index!==H)throw TypeError("invalid parameter format");if(H+=q[0].length,Z=q[1].toLowerCase(),V=q[2],V.charCodeAt(0)===34){if(V=V.slice(1,-1),V.indexOf("\\")!==-1)V=V.replace(U,"$1")}X.parameters[Z]=V}if(H!==G.length)throw TypeError("invalid parameter format")}return X}function Q(K){var G;if(typeof K.getHeader==="function")G=K.getHeader("content-type");else if(typeof K.headers==="object")G=K.headers&&K.headers["content-type"];if(typeof G!=="string")throw TypeError("content-type header is missing from object");return G}function J(K){this.parameters=Object.create(null),this.type=K}}),Sb1=UV(fb0(),1);ub0=/^[A-Za-z0-9._-]{1,128}$/});function _S($){let Y=new $({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Jc0(Y),Y}var pw,Pe,F1,v1,K5,mw,db0,Te,je,dw,mb0,G5,lb0,ob0,Ee,rb0,lw,bI,MH,iI,ow,sb0,Ce,ab0,tb0,eb0,vS,$i0,hS,Re,Yi0,Ui0,zi0,Ii0,Qi0,Ji0,Ki0,Gi0,SS,Hi0,Wi0,Xi0,_e,ve,he,Zi0,qi0,Vi0,gS,Li0,Se,Fi0,wi0,Mi0,Oi0,Ni0,Di0,Ai0,Bi0,ge,Pi0,ye,ke,xe,Ti0,yS,ji0,fe,ue,be,Ei0,Ci0,ie,Ri0,_i0,vi0,ce,hi0,Si0,ne,gi0,yi0,ki0,xi0,fi0,ui0,bi0,ii0,ci0,ni0,pi0,di0,mi0,li0,oi0,ri0,si0,ai0,ti0,ei0,$c0,Yc0,Uc0,pe,zc0,Ic0,Qc0,Jc0,rw=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor($){this._userAjv=$!==void 0,this._ajv=$}get ajv(){return this._ajv??=_S(Ic0.Ajv2020)}_engineFor($){if(this._userAjv)return this.ajv;let Y=Br($,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");if(Y==="2020-12")return this.ajv;if(Y==="2019-09")return this._ajv2019??=_S(zc0.Ajv2019);return this._ajvDraft7??=_S(pe.Ajv)}getValidator($){let Y=this._engineFor($),U="$id"in $&&typeof $.$id==="string"?Y.getSchema($.$id)??Y.compile($):Y.compile($);return(z)=>{return U(z)?{valid:!0,data:z,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:Y.errorsText(U.errors)}}}},db1;var de=m(()=>{Nj();Dj();pw=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.regexpCode=$.getEsmExportName=$.getProperty=$.safeStringify=$.stringify=$.strConcat=$.addCodeArg=$.str=$._=$.nil=$._Code=$.Name=$.IDENTIFIER=$._CodeOrName=void 0;var Y=class{};$._CodeOrName=Y,$.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var U=class extends Y{constructor(F){super();if(!$.IDENTIFIER.test(F))throw Error("CodeGen: name must be a valid identifier");this.str=F}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};$.Name=U;var z=class extends Y{constructor(F){super();this._items=typeof F==="string"?[F]:F}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let F=this._items[0];return F===""||F==='""'}get str(){var F;return(F=this._str)!==null&&F!==void 0?F:this._str=this._items.reduce((N,O)=>`${N}${O}`,"")}get names(){var F;return(F=this._names)!==null&&F!==void 0?F:this._names=this._items.reduce((N,O)=>{if(O instanceof U)N[O.str]=(N[O.str]||0)+1;return N},{})}};$._Code=z,$.nil=new z("");function I(F,...N){let O=[F[0]],D=0;while(D<N.length)K(O,N[D]),O.push(F[++D]);return new z(O)}$._=I;let Q=new z("+");function J(F,...N){let O=[q(F[0])],D=0;while(D<N.length)O.push(Q),K(O,N[D]),O.push(Q,q(F[++D]));return G(O),new z(O)}$.str=J;function K(F,N){if(N instanceof z)F.push(...N._items);else if(N instanceof U)F.push(N);else F.push(X(N))}$.addCodeArg=K;function G(F){let N=1;while(N<F.length-1){if(F[N]===Q){let O=H(F[N-1],F[N+1]);if(O!==void 0){F.splice(N-1,3,O);continue}F[N++]="+"}N++}}function H(F,N){if(N==='""')return F;if(F==='""')return N;if(typeof F=="string"){if(N instanceof U||F[F.length-1]!=='"')return;if(typeof N!="string")return`${F.slice(0,-1)}${N}"`;if(N[0]==='"')return F.slice(0,-1)+N.slice(1);return}if(typeof N=="string"&&N[0]==='"'&&!(F instanceof U))return`"${F}${N.slice(1)}`}function W(F,N){return N.emptyStr()?F:F.emptyStr()?N:J`${F}${N}`}$.strConcat=W;function X(F){return typeof F=="number"||typeof F=="boolean"||F===null?F:q(Array.isArray(F)?F.join(","):F)}function Z(F){return new z(q(F))}$.stringify=Z;function q(F){return JSON.stringify(F).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$.safeStringify=q;function V(F){return typeof F=="string"&&$.IDENTIFIER.test(F)?new z(`.${F}`):I`[${F}]`}$.getProperty=V;function w(F){if(typeof F=="string"&&$.IDENTIFIER.test(F))returnnewz(`${F}`);throwError(`CodeGen: invalid export name: ${F}, use explicit $id name mapping`)}$.getEsmExportName=w;functionM(F){returnnewz(F.toStringLine truncated
deps:${W}}`};let I={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[H,W]=Q(G);J(G,H),K(G,W)}};function Q({schema:G}){let H={},W={};for(let X in G){if(X==="__proto__")continue;let Z=Array.isArray(G[X])?H:W;Z[X]=G[X]}return[H,W]}function J(G,H=G.schema){let{gen:W,data:X,it:Z}=G;if(Object.keys(H).length===0)return;let q=W.let("missing");for(let V in H){let w=H[V];if(w.length===0)continue;let M=(0,z.propertyInData)(W,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:w.length,deps:w.join(", ")}),Z.allErrors)W.if(M,()=>{for(let F of w)(0,z.checkReportMissingProp)(G,F)});else W.if(Y._`${M}&&(${(0,z.checkMissingProp)(G,w,q)})`),(0,z.reportMissingProp)(G,q),W.else()}}$.validatePropertyDeps=J;function K(G,H=G.schema){let{gen:W,data:X,keyword:Z,it:q}=G,V=W.name("valid");for(let w in H){if((0,U.alwaysValidSchema)(q,H[w]))continue;W.if((0,z.propertyInData)(W,X,w,q.opts.ownProperties),()=>{let M=G.subschema({keyword:Z,schemaProp:w},V);G.mergeValidEvaluated(M,V)},()=>W.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=K,$.default=I}),Li0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=F1(),U=v1(),z={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:I})=>Y._`{propertyName:${I.propertyName}}`},code(I){let{gen:Q,schema:J,data:K,it:G}=I;if((0,U.alwaysValidSchema)(G,J))return;let H=Q.name("valid");Q.forIn("key",K,(W)=>{I.setParams({propertyName:W}),I.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},H),Q.if((0,Y.not)(H),()=>{if(I.error(!0),!G.allErrors)Q.break()})}),I.ok(H)}};$.default=z}),Se=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=G5(),U=F1(),z=K5(),I=v1(),Q={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:J})=>U._`{additionalProperty:${J.additionalProperty}}`},code(J){let{gen:K,schema:G,parentSchema:H,data:W,errsCount:X,it:Z}=J;if(!X)throw Error("ajv implementation error");let{allErrors:q,opts:V}=Z;if(Z.props=!0,V.removeAdditional!=="all"&&(0,I.alwaysValidSchema)(Z,G))return;let w=(0,Y.allSchemaProperties)(H.properties),M=(0,Y.allSchemaProperties)(H.patternProperties);F(),J.ok(U._`${X}===${z.default.errors}`);function F(){K.forIn("key",W,(T)=>{if(!w.length&&!M.length)D(T);else K.if(N(T),()=>D(T))})}function N(T){let A;if(w.length>8){let j=(0,I.schemaRefOrVal)(Z,H.properties,"properties");A=(0,Y.isOwnProperty)(K,j,T)}else if(w.length)A=(0,U.or)(...w.map((j)=>U._`${T}===${j}`));else A=U.nil;if(M.length)A=(0,U.or)(A,...M.map((j)=>U._`${(0,Y.usePattern)(J,j)}.test(${T})`));return(0,U.not)(A)}function O(T){K.code(U._`delete${W}[${T}]`)}function D(T){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){O(T);return}if(G===!1){if(J.setParams({additionalProperty:T}),J.error(),!q)K.break();return}if(typeof G=="object"&&!(0,I.alwaysValidSchema)(Z,G)){let A=K.name("valid");if(V.removeAdditional==="failing")P(T,A,!1),K.if((0,U.not)(A),()=>{J.reset(),O(T)});else if(P(T,A),!q)K.if((0,U.not)(A),()=>K.break())}}function P(T,A,j){let C={keyword:"additionalProperties",dataProp:T,dataPropType:I.Type.Str};if(j===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});J.subschema(C,A)}}};$.default=Q}),Fi0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=bI(),U=G5(),z=v1(),I=Se(),Q={keyword:"properties",type:"object",schemaType:"object",code(J){let{gen:K,schema:G,parentSchema:H,data:W,it:X}=J;if(X.opts.removeAdditional==="all"&&H.additionalProperties===void 0)I.default.code(new Y.KeywordCxt(X,I.default,"additionalProperties"));let Z=(0,U.allSchemaProperties)(G);for(let F of Z)X.definedProperties.add(F);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=z.mergeEvaluated.props(K,(0,z.toHash)(Z),X.props);let q=Z.filter((F)=>!(0,z.alwaysValidSchema)(X,G[F]));if(q.length===0)return;let V=K.name("valid");for(let F of q){if(w(F))M(F);else{if(K.if((0,U.propertyInData)(K,W,F,X.opts.ownProperties)),M(F),!X.allErrors)K.else().var(V,!0);K.endIf()}J.it.definedProperties.add(F),J.ok(V)}function w(F){return X.opts.useDefaults&&!X.compositeRule&&G[F].default!==void 0}function M(F){J.subschema({keyword:"properties",schemaProp:F,dataProp:F},V)}}};$.default=Q}),wi0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=G5(),U=F1(),z=v1(),I=v1(),Q={keyword:"patternProperties",type:"object",schemaType:"object",code(J){let{gen:K,schema:G,data:H,parentSchema:W,it:X}=J,{opts:Z}=X,q=(0,Y.allSchemaProperties)(G),V=q.filter((P)=>(0,z.alwaysValidSchema)(X,G[P]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let w=Z.strictSchema&&!Z.allowMatchingProperties&&W.properties,M=K.name("valid");if(X.props!==!0&&!(X.props instanceof U.Name))X.props=(0,I.evaluatedPropsToName)(K,X.props);let{props:F}=X;N();function N(){for(let P of q){if(w)O(P);if(X.allErrors)
Line truncated
`)}openNode($,Y){let U=this.tos,z=this._xml;if(U&&this.open)z.push(">");this._stack.push($),z.push("<"),z.push($),ok(z,Y),this.leaf=!0,this.open=!0}addAttribute($,Y){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(Y!==void 0)L70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");ok(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(V70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),Y=this._xml;if(this.leaf)Y.push("/>");else Y.push("</"),Y.push($),Y.push(">");this.open=!1,this.leaf=!1}leafNode($,Y,U){if(this.openNode($,Y),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}rk.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};F70.exports=rk});var sk=E((Ae0)=>{var w70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function De0($){if(typeof $==="string")return $;if(w70)return w70.decode($);return $.toString()}Ae0.bufferToString=De0});var A70=E((O70)=>{Object.defineProperty(O70,"__esModule",{value:!0});O70.CHAR=`
`,$=this.i;break;case c01:{let{entityReturnState:U}=this,z=this.entity+Y.slice($,this.prevI);this.state=U;let I;if(z==="")this.fail("empty entity name."),I="&;";else I=this.parseEntity(z),this.entity="";if(U!==h8||this.textHandler!==void 0)this.text+=I;break $}case x4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(gW($))this.state=x01,this.unget(),this.xmlDeclPossible=!1;else switch($){case KN:this.state=b01,this.xmlDeclPossible=!1;break;case d70:this.state=E01,this.openWakaBang="",this.xmlDeclPossible=!1;break;case s6:this.state=h01;break;default:this.fail("disallowed character in tag name"),this.state=h8,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=Jx,this.openWakaBang="";break;case"--":this.state=Qx,this.openWakaBang="";break;case"DOCTYPE":if(this.state=Ux,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar(JN))this.state=C01}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===JN)this.state=R01,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=Qx}sCommentEnded(){let $=this.getCodeNorm();if($!==T6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Qx;else this.state=h8}sCData(){if(this.captureToChar(hQ))this.state=_01}sCDataEnding(){let $=this.getCodeNorm();if($===hQ)this.state=v01;else this.text+=`]${String.fromCodePoint($)}`,this.state=Jx}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case T6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=h8;break}case hQ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=Jx}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=f70;else if($===s6||m8($))this.fail("processing instruction without a target."),this.state=$===s6?QN:Kx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=f70}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let U=this.getCodeNorm();if(U===x4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(Y,this.prevI);let z=U===s6;if(z||m8(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=z?qU:u70}else this.state=z?QN:Kx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===s6)this.state=QN;else if(!m8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(s6))this.state=QN}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===T6){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=h8}else if(Y===s6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=Kx;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===s6){this.state=qU;return}if($!==x4)this.state=S01,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(d01);if($===s6){this.state=qU,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(m8($)||$===vQ))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expectedthename${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expectedoneof${this.xmlDeclExpects.join(", ")}`)}this.state=$===vQ?b70:g01}sXMLDeclEq(){let $=this.getCodeNorm();if($===s6){this.state=qU,this.fail("XML declaration is incomplete.");return}if(m8($))return;if($!==vQ)this.fail("value required.");this.state=b70}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===s6){this.state=qU,this.fail("XML declaration is incomplete.");return}if(m8($))return;if(!GN($))this.fail("value must be quoted."),this.q=p70;else this.q=$;this.state=y01}sXMLDeclValue(){let $=this.captureTo([this.q,s6]);if($===s6){this.state=qU,this.text="",this.fail("XML declaration is incomplete.");return}if($===x4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=Y;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("ver
Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(Y)}set headers($){this._headers=$}shouldQuote($,Y){let U=Y?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(A71.default(U))return U;if(Array.isArray(U))return U[$];if(this._headers!==null)return U[this._headers[$]];return!1}format($,Y,U){let z=`${B71.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:I}=this;if(I.quote!==""){if(z.indexOf(I.quote)!==-1)return this.quoteField(z.replace(this.REPLACE_REGEXP,I.escapedQuote))}if(z.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(Y,U))return this.quoteField(z);return z}quoteField($){let{quote:Y}=this.formatterOptions;return`${Y}${$}${Y}`}}lQ.FieldFormatter=_K0});var nf=E((vK0)=>{Object.defineProperty(vK0,"__esModule",{value:!0});vK0.isSyncTransform=void 0;vK0.isSyncTransform=($)=>$.length===1});var gK0=E((oQ)=>{var SK0=oQ&&oQ.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(oQ,"__esModule",{value:!0});oQ.RowFormatter=void 0;var T71=SK0(cN()),j71=SK0(DK0()),E71=cf(),C71=nf();class jU{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new E71.FieldFormatter($),this.headers=$.headers,this.shouldWriteHeaders=$.shouldWriteHeaders,this.hasWrittenHeaders=!1,this.headers!==null)this.fieldFormatter.headers=this.headers;if($.transform)this.rowTransform=$.transform}static isRowHashArray($){if(Array.isArray($))return Array.isArray($[0])&&$[0].length===2;return!1}static isRowArray($){return Array.isArray($)&&!this.isRowHashArray($)}static gatherHeaders($){if(jU.isRowHashArray($))return $.map((Y)=>Y[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(C71.isSyncTransform($))return(Y,U)=>{let z=null;try{z=$(Y)}catch(I){return U(I)}return U(null,z)};return(Y,U)=>{$(Y,U)}}set rowTransform($){if(!T71.default($))throw TypeError("The transform should be a function");this._rowTransform=jU.createTransform($)}format($,Y){this.callTransformer($,(U,z)=>{if(U)return Y(U);if(!$)return Y(null);let I=[];if(z){let{shouldFormatColumns:Q,headers:J}=this.checkHeaders(z);if(this.shouldWriteHeaders&&J&&!this.hasWrittenHeaders)I.push(this.formatColumns(J,!0)),this.hasWrittenHeaders=!0;if(Q){let K=this.gatherColumns(z);I.push(this.formatColumns(K,!1))}}return Y(null,I)})}finish($){let Y=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));Y.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)Y.push(this.formatterOptions.rowDelimiter);return $(null,Y)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let Y=jU.gatherHeaders($);if(this.headers=Y,this.fieldFormatter.headers=Y,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!j71.default(Y,$),headers:Y}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((Y)=>$[Y]);if(jU.isRowHashArray($))return this.headers.map((Y,U)=>{let z=$[U];if(z)return z[1];return""});if(jU.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((Y,U)=>$[U])}callTransformer($,Y){if(!this._rowTransform)return Y(null,$);return this._rowTransform($,Y)}formatColumns($,Y){let U=$.map((I,Q)=>this.fieldFormatter.format(I,Q,Y)).join(this.formatterOptions.delimiter),{rowCount:z}=this;if(this.rowCount+=1,z)return[this.formatterOptions.rowDelimiter,U].join("");return U}}oQ.RowFormatter=jU});var yK0=E((YD)=>{Object.defineProperty(YD,"__esModule",{value:!0});YD.FieldFormatter=YD.RowFormatter=void 0;var R71=gK0();Object.defineProperty(YD,"RowFormatter",{enumerable:!0,get:function(){return R71.RowFormatter}});var _71=cf();Object.defineProperty(YD,"FieldFormatter",{enumerable:!0,get:function(){return _71.FieldFormatter}})});var pf=E((xK0)=>{Object.defineProperty(xK0,"__esModule",{value:!0});xK0.CsvFormatterStream=void 0;var h71=J0("stream"),S71=yK0();class kK0 extends h71.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new S71.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,Y,U){let z=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(I,Q)=>{if(I)return z=!0,U(I);if(Q)Q.forEach((J)=>{this.push(Buffer.from(J,"utf8"))});return z=!0,U()})}catch(I){if(z)throw I;U(I)}}_flush($){this.rowFormatter.finish((Y,U)=>{if(Y)return $(Y);if(U)U.forEach((z)=>{this.push(Buffer.from(z,"utf8"))});return $()})}}xK0.CsvFormatterStream=kK0});var bK0=E((a1)=>{var uK0=a1&&a1.__createBinding||(Object.create?function($,Y,U,z){if(z===void 0)z=U;Object.defineProperty($,z,{enumerable:!0,get:function(){return Y[U]}})}:function($,Y,U,z){if(z===void 0)z=U;$[z]=Y[U]}),g71=a1&&a1.__setModuleDefault||(Object.create?function($,Y){O
Line truncated
deps:${W}}`};let Q={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[H,W]=J(G);K(G,H),z(G,W)}};function J({schema:G}){let H={},W={};for(let X in G){if(X==="__proto__")continue;let Z=Array.isArray(G[X])?H:W;Z[X]=G[X]}return[H,W]}function K(G,H=G.schema){let{gen:W,data:X,it:Z}=G;if(Object.keys(H).length===0)return;let q=W.let("missing");for(let V in H){let w=H[V];if(w.length===0)continue;let M=(0,I.propertyInData)(W,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:w.length,deps:w.join(", ")}),Z.allErrors)W.if(M,()=>{for(let F of w)(0,I.checkReportMissingProp)(G,F)});else W.if(Y._`${M}&&(${(0,I.checkMissingProp)(G,w,q)})`),(0,I.reportMissingProp)(G,q),W.else()}}$.validatePropertyDeps=K;function z(G,H=G.schema){let{gen:W,data:X,keyword:Z,it:q}=G,V=W.name("valid");for(let w in H){if((0,U.alwaysValidSchema)(q,H[w]))continue;W.if((0,I.propertyInData)(W,X,w,q.opts.ownProperties),()=>{let M=G.subschema({keyword:Z,schemaProp:w},V);G.mergeValidEvaluated(M,V)},()=>W.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=z,$.default=Q}),Hc0=_0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=F1(),U=S1(),I={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:Q})=>Y._`{propertyName:${Q.propertyName}}`},code(Q){let{gen:J,schema:K,data:z,it:G}=Q;if((0,U.alwaysValidSchema)(G,K))return;let H=J.name("valid");J.forIn("key",z,(W)=>{Q.setParams({propertyName:W}),Q.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},H),J.if((0,Y.not)(H),()=>{if(Q.error(!0),!G.allErrors)J.break()})}),Q.ok(H)}};$.default=I}),ee=_0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=M5(),U=F1(),I=w5(),Q=S1(),J={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:K})=>U._`{additionalProperty:${K.additionalProperty}}`},code(K){let{gen:z,schema:G,parentSchema:H,data:W,errsCount:X,it:Z}=K;if(!X)throw Error("ajv implementation error");let{allErrors:q,opts:V}=Z;if(Z.props=!0,V.removeAdditional!=="all"&&(0,Q.alwaysValidSchema)(Z,G))return;let w=(0,Y.allSchemaProperties)(H.properties),M=(0,Y.allSchemaProperties)(H.patternProperties);F(),K.ok(U._`${X}===${I.default.errors}`);function F(){z.forIn("key",W,(T)=>{if(!w.length&&!M.length)D(T);else z.if(N(T),()=>D(T))})}function N(T){let A;if(w.length>8){let E=(0,Q.schemaRefOrVal)(Z,H.properties,"properties");A=(0,Y.isOwnProperty)(z,E,T)}else if(w.length)A=(0,U.or)(...w.map((E)=>U._`${T}===${E}`));else A=U.nil;if(M.length)A=(0,U.or)(A,...M.map((E)=>U._`${(0,Y.usePattern)(K,E)}.test(${T})`));return(0,U.not)(A)}function O(T){z.code(U._`delete${W}[${T}]`)}function D(T){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){O(T);return}if(G===!1){if(K.setParams({additionalProperty:T}),K.error(),!q)z.break();return}if(typeof G=="object"&&!(0,Q.alwaysValidSchema)(Z,G)){let A=z.name("valid");if(V.removeAdditional==="failing")P(T,A,!1),z.if((0,U.not)(A),()=>{K.reset(),O(T)});else if(P(T,A),!q)z.if((0,U.not)(A),()=>z.break())}}function P(T,A,E){let C={keyword:"additionalProperties",dataProp:T,dataPropType:Q.Type.Str};if(E===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});K.subschema(C,A)}}};$.default=J}),Wc0=_0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=oQ(),U=M5(),I=S1(),Q=ee(),J={keyword:"properties",type:"object",schemaType:"object",code(K){let{gen:z,schema:G,parentSchema:H,data:W,it:X}=K;if(X.opts.removeAdditional==="all"&&H.additionalProperties===void 0)Q.default.code(new Y.KeywordCxt(X,Q.default,"additionalProperties"));let Z=(0,U.allSchemaProperties)(G);for(let F of Z)X.definedProperties.add(F);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=I.mergeEvaluated.props(z,(0,I.toHash)(Z),X.props);let q=Z.filter((F)=>!(0,I.alwaysValidSchema)(X,G[F]));if(q.length===0)return;let V=z.name("valid");for(let F of q){if(w(F))M(F);else{if(z.if((0,U.propertyInData)(z,W,F,X.opts.ownProperties)),M(F),!X.allErrors)z.else().var(V,!0);z.endIf()}K.it.definedProperties.add(F),K.ok(V)}function w(F){return X.opts.useDefaults&&!X.compositeRule&&G[F].default!==void 0}function M(F){K.subschema({keyword:"properties",schemaProp:F,dataProp:F},V)}}};$.default=J}),Xc0=_0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=M5(),U=F1(),I=S1(),Q=S1(),J={keyword:"patternProperties",type:"object",schemaType:"object",code(K){let{gen:z,schema:G,data:H,parentSchema:W,it:X}=K,{opts:Z}=X,q=(0,Y.allSchemaProperties)(G),V=q.filter((P)=>(0,I.alwaysValidSchema)(X,G[P]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let w=Z.strictSchema&&!Z.allowMatchingProperties&&W.properties,M=z.name("valid");if(X.props!==!0&&!(X.props instanceof U.Name))X.props=(0,Q.evaluatedPropsToName)(z,X.props);let{props:F}=X;N();function N(){for(let P of q){if(w)O(P);if(X.allErrors)
Line truncated
`)}openNode($,Y){let U=this.tos,I=this._xml;if(U&&this.open)I.push(">");this._stack.push($),I.push("<"),I.push($),Jx(I,Y),this.leaf=!0,this.open=!0}addAttribute($,Y){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(Y!==void 0)g70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");Jx(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(y70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),Y=this._xml;if(this.leaf)Y.push("/>");else Y.push("</"),Y.push($),Y.push(">");this.open=!1,this.leaf=!1}leafNode($,Y,U){if(this.openNode($,Y),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}Kx.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};k70.exports=Kx});var zx=j((F01)=>{var x70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function L01($){if(typeof $==="string")return $;if(x70)return x70.decode($);return $.toString()}F01.bufferToString=L01});var c70=j((u70)=>{Object.defineProperty(u70,"__esModule",{value:!0});u70.CHAR=`
`,$=this.i;break;case k11:{let{entityReturnState:U}=this,I=this.entity+Y.slice($,this.prevI);this.state=U;let Q;if(I==="")this.fail("empty entity name."),Q="&;";else Q=this.parseEntity(I),this.entity="";if(U!==f8||this.textHandler!==void 0)this.text+=Q;break $}case i4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(pW($))this.state=v11,this.unget(),this.xmlDeclPossible=!1;else switch($){case DN:this.state=y11,this.xmlDeclPossible=!1;break;case X20:this.state=D11,this.openWakaBang="",this.xmlDeclPossible=!1;break;case Y8:this.state=E11;break;default:this.fail("disallowed character in tag name"),this.state=f8,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=wx,this.openWakaBang="";break;case"--":this.state=Fx,this.openWakaBang="";break;case"DOCTYPE":if(this.state=qx,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar(NN))this.state=A11}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===NN)this.state=B11,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=Fx}sCommentEnded(){let $=this.getCodeNorm();if($!==_6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Fx;else this.state=f8}sCData(){if(this.captureToChar(bJ))this.state=P11}sCDataEnding(){let $=this.getCodeNorm();if($===bJ)this.state=T11;else this.text+=`]${String.fromCodePoint($)}`,this.state=wx}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case _6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=f8;break}case bJ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=wx}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=Q20;else if($===Y8||$$($))this.fail("processing instruction without a target."),this.state=$===Y8?ON:Mx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=Q20}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let U=this.getCodeNorm();if(U===i4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(Y,this.prevI);let I=U===Y8;if(I||$$(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=I?AU:J20}else this.state=I?ON:Mx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===Y8)this.state=ON;else if(!$$($))this.text=String.fromCodePoint($)}else if(this.captureToChar(Y8))this.state=ON}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===_6){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=f8}else if(Y===Y8)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=Mx;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===Y8){this.state=AU;return}if($!==i4)this.state=j11,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(u11);if($===Y8){this.state=AU,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!($$($)||$===uJ))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expectedthename${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expectedoneof${this.xmlDeclExpects.join(", ")}`)}this.state=$===uJ?K20:C11}sXMLDeclEq(){let $=this.getCodeNorm();if($===Y8){this.state=AU,this.fail("XML declaration is incomplete.");return}if($$($))return;if($!==uJ)this.fail("value required.");this.state=K20}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===Y8){this.state=AU,this.fail("XML declaration is incomplete.");return}if($$($))return;if(!AN($))this.fail("value must be quoted."),this.q=W20;else this.q=$;this.state=R11}sXMLDeclValue(){let $=this.captureTo([this.q,Y8]);if($===Y8){this.state=AU,this.text="",this.fail("XML declaration is incomplete.");return}if($===i4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=Y;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("ver
Line truncated
See:https://github.com/isaacs/node-glob/issues/167`);return new j6($,Y).found}function j6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See:https://github.com/isaacs/node-glob/issues/167`);return new v6($,Y).found}function v6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
`+Z0[A0-1];break}}}var A1="a promise was created in a "+h+"handler "+W0+"but was not returned from it, see http://goo.gl/rRqMUw"+Q0;u._warn(A1,!0,B)}}function R(I0,B){var h=I0+" is deprecated and will be removed in a future version.";if(B)h+=" Use "+B+" instead.";return o(h)}function o(I0,B,h){if(!D0.warnings)return;var u=new I(I0),s;if(B)h._attachExtraTrace(u);else if(D0.longStackTraces&&(s=$._peekContext()))s.attachExtraTrace(u);else{var W0=o0(u);u.stack=W0.message+`
`+Z0[B0-1];break}}}var B1="a promise was created in a "+S+"handler "+W0+"but was not returned from it, see http://goo.gl/rRqMUw"+J0;u._warn(B1,!0,B)}}function g(Q0,B){var S=Q0+" is deprecated and will be removed in a future version.";if(B)S+=" Use "+B+" instead.";return c(S)}function c(Q0,B,S){if(!D0.warnings)return;var u=new Q(Q0),s;if(B)S._attachExtraTrace(u);else if(D0.longStackTraces&&(s=$._peekContext()))s.attachExtraTrace(u);else{var W0=r0(u);u.stack=W0.message+`
`)));return}}F=F._target();var N=F._bitField;if((N&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((N&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((N&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(V,w){if(typeof V!=="function")throw new K(`generatorFunctionmustbeafunction
`)));return}}F=F._target();var N=F._bitField;if((N&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((N&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((N&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(V,w){if(typeof V!=="function")throw new z(`generatorFunctionmustbeafunction
Seehttp://goo.gl/MqrFmX
`);var M=Object(w).yieldHandler,F=q,N=Error().stack;return function(){var O=V.apply(this,arguments),D=new F(void 0,void 0,M,N),P=D.promise();return D._generator=O,D._promiseFulfilled(void 0),P}},$.coroutine.addYieldHandler=function(V){if(typeof V!=="function")throw new K("expecting a function but got "+G.classString(V));X.push(V)},$.spawn=function(V){if(Q.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return Y(`generatorFunctionmustbeafunction
`);var M=Object(w).yieldHandler,F=q,N=Error().stack;return function(){var O=V.apply(this,arguments),D=new F(void 0,void 0,M,N),P=D.promise();return D._generator=O,D._promiseFulfilled(void 0),P}},$.coroutine.addYieldHandler=function(V){if(typeof V!=="function")throw new z("expecting a function but got "+G.classString(V));X.push(V)},$.spawn=function(V){if(J.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return Y(`generatorFunctionmustbeafunction
`)},Y=function(){return new g.PromiseInspection(this._target())},U=function(k){return g.reject(new X(k))};function z(){}var I={},Q=w4(),J;if(Q.isNode)J=function(){var k=process.domain;if(k===void 0)k=null;return k};else J=function(){return null};Q.notEnumerableProp(g,"_getDomain",J);var K=aU(),G=Qw0(),H=new G;K.defineProperty(g,"_async",{value:H});var W=_3(),X=g.TypeError=W.TypeError;g.RangeError=W.RangeError;var Z=g.CancellationError=W.CancellationError;g.TimeoutError=W.TimeoutError,g.OperationalError=W.OperationalError,g.RejectionError=W.OperationalError,g.AggregateError=W.AggregateError;var q=function(){},V={},w={},M=Ww0()(g,q),F=Zw0()(g,q,M,U,z),N=Vw0()(g),O=N.create,D=Fw0()(g,N),P=D.CapturedTrace,T=Mw0()(g,M),A=Nw0()(w),j=Sc(),C=Q.errorObj,b=Q.tryCatch;function x(k,d){if(typeof d!=="function")throw new X("expecting a function but got "+Q.classString(d));if(k.constructor!==g)throw new X(`thepromiseconstructorcannotbeinvokeddirectly
`)},Y=function(){return new h.PromiseInspection(this._target())},U=function(k){return h.reject(new X(k))};function I(){}var Q={},J=N4(),K;if(J.isNode)K=function(){var k=process.domain;if(k===void 0)k=null;return k};else K=function(){return null};J.notEnumerableProp(h,"_getDomain",K);var z=KI(),G=Tw0(),H=new G;z.defineProperty(h,"_async",{value:H});var W=f3(),X=h.TypeError=W.TypeError;h.RangeError=W.RangeError;var Z=h.CancellationError=W.CancellationError;h.TimeoutError=W.TimeoutError,h.OperationalError=W.OperationalError,h.RejectionError=W.OperationalError,h.AggregateError=W.AggregateError;var q=function(){},V={},w={},M=_w0()(h,q),F=Sw0()(h,q,M,U,I),N=yw0()(h),O=N.create,D=kw0()(h,N),P=D.CapturedTrace,T=fw0()(h,M),A=bw0()(w),E=dc(),C=J.errorObj,i=J.tryCatch;function x(k,m){if(typeof m!=="function")throw new X("expecting a function but got "+J.classString(m));if(k.constructor!==h)throw new X(`thepromiseconstructorcannotbeinvokeddirectly
Seehttp://goo.gl/MqrFmX
`)}function g(k){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,k!==q)x(this,k),this._resolveFromExecutor(k);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(k){var d=arguments.length;if(d>1){var a=Array(d-1),$0=0,y;for(y=0;y<d-1;++y){var p=arguments[y];if(Q.isObject(p))a[$0++]=p;else return U("expecting an object but got A catch statement predicate "+Q.classString(p))}return a.length=$0,k=arguments[y],this.then(void 0,A(a,k,this))}return this.then(void 0,k)},g.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},g.prototype.then=function(k,d){if(D.warnings()&&arguments.length>0&&typeof k!=="function"&&typeof d!=="function"){var a=".then() only accepts functions but was passed: "+Q.classString(k);if(arguments.length>1)a+=", "+Q.classString(d);this._warn(a)}return this._then(k,d,void 0,void 0,void 0)},g.prototype.done=function(k,d){var a=this._then(k,d,void 0,void 0,void 0);a._setIsFinal()},g.prototype.spread=function(k){if(typeof k!=="function")return U("expecting a function but got "+Q.classString(k));return this.all()._then(k,void 0,void 0,V,void 0)},g.prototype.toJSON=function(){var k={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())k.fulfillmentValue=this.value(),k.isFulfilled=!0;else if(this.isRejected())k.rejectionReason=this.reason(),k.isRejected=!0;return k},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},g.prototype.error=function(k){return this.caught(Q.originatesFromRejection,k)},g.getNewLibraryCopy=yc.exports,g.is=function(k){return k instanceof g},g.fromNode=g.fromCallback=function(k){var d=new g(q);d._captureStackTrace();var a=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,$0=b(k)(j(d,a));if($0===C)d._rejectCallback($0.e,!0);if(!d._isFateSealed())d._setAsyncGuaranteed();return d},g.all=function(k){return new F(k).promise()},g.cast=function(k){var d=M(k);if(!(d instanceof g))d=new g(q),d._captureStackTrace(),d._setFulfilled(),d._rejectionHandler0=k;return d},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(k){var d=new g(q);return d._captureStackTrace(),d._rejectCallback(k,!0),d},g.setScheduler=function(k){if(typeof k!=="function")throw new X("expecting a function but got "+Q.classString(k));return H.setScheduler(k)},g.prototype._then=function(k,d,a,$0,y){var p=y!==void 0,Y0=p?y:new g(q),R=this._target(),o=R._bitField;if(!p){if(Y0._propagateFrom(this,3),Y0._captureStackTrace(),$0===void 0&&(this._bitField&2097152)!==0)if((o&50397184)!==0)$0=this._boundValue();else $0=R===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,Y0)}var e=J();if((o&50397184)!==0){var O0,T0,y0=R._settlePromiseCtx;if((o&33554432)!==0)T0=R._rejectionHandler0,O0=k;else if((o&16777216)!==0)T0=R._fulfillmentHandler0,O0=d,R._unsetRejectionIsUnhandled();else y0=R._settlePromiseLateCancellationObserver,T0=new Z("late cancellation observer"),R._attachExtraTrace(T0),O0=d;H.invoke(y0,R,{handler:e===null?O0:typeof O0==="function"&&Q.domainBind(e,O0),promise:Y0,receiver:$0,value:T0})}else R._addCallbacks(k,d,Y0,$0,e);return Y0},g.prototype._length=function(){return this._bitField&65535},g.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},g.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},g.prototype._setLength=function(k){this._bitField=this._bitField&-65536|k&65535},g.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},g.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},g.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},g.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},g.prototype._isFinal=function(){return(this._bitField&4194304)>0},g.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},g.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},g.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},g.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(k){var d=k===0?this._receiver0:this[k*4-4+3];if(d===I)return;else if(d===void 0&&this._isBound())return this._boundValue();return d},g.prototype._promiseAt=function(k){return this[k*4-4+2]},g.prototype._fulfillmentHandlerAt=function(k){return this[k*4-4+0]},g.prototype._rejectionHandlerAt=function(k){return this[k*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(k){var{_bitField:d,_fulfillmentHand
Line truncated
`)}function h(k){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,k!==q)x(this,k),this._resolveFromExecutor(k);this._promiseCreated(),this._fireEvent("promiseCreated",this)}h.prototype.toString=function(){return"[object Promise]"},h.prototype.caught=h.prototype.catch=function(k){var m=arguments.length;if(m>1){var t=Array(m-1),$0=0,y;for(y=0;y<m-1;++y){var p=arguments[y];if(J.isObject(p))t[$0++]=p;else return U("expecting an object but got A catch statement predicate "+J.classString(p))}return t.length=$0,k=arguments[y],this.then(void 0,A(t,k,this))}return this.then(void 0,k)},h.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},h.prototype.then=function(k,m){if(D.warnings()&&arguments.length>0&&typeof k!=="function"&&typeof m!=="function"){var t=".then() only accepts functions but was passed: "+J.classString(k);if(arguments.length>1)t+=", "+J.classString(m);this._warn(t)}return this._then(k,m,void 0,void 0,void 0)},h.prototype.done=function(k,m){var t=this._then(k,m,void 0,void 0,void 0);t._setIsFinal()},h.prototype.spread=function(k){if(typeof k!=="function")return U("expecting a function but got "+J.classString(k));return this.all()._then(k,void 0,void 0,V,void 0)},h.prototype.toJSON=function(){var k={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())k.fulfillmentValue=this.value(),k.isFulfilled=!0;else if(this.isRejected())k.rejectionReason=this.reason(),k.isRejected=!0;return k},h.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},h.prototype.error=function(k){return this.caught(J.originatesFromRejection,k)},h.getNewLibraryCopy=mc.exports,h.is=function(k){return k instanceof h},h.fromNode=h.fromCallback=function(k){var m=new h(q);m._captureStackTrace();var t=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,$0=i(k)(E(m,t));if($0===C)m._rejectCallback($0.e,!0);if(!m._isFateSealed())m._setAsyncGuaranteed();return m},h.all=function(k){return new F(k).promise()},h.cast=function(k){var m=M(k);if(!(m instanceof h))m=new h(q),m._captureStackTrace(),m._setFulfilled(),m._rejectionHandler0=k;return m},h.resolve=h.fulfilled=h.cast,h.reject=h.rejected=function(k){var m=new h(q);return m._captureStackTrace(),m._rejectCallback(k,!0),m},h.setScheduler=function(k){if(typeof k!=="function")throw new X("expecting a function but got "+J.classString(k));return H.setScheduler(k)},h.prototype._then=function(k,m,t,$0,y){var p=y!==void 0,Y0=p?y:new h(q),g=this._target(),c=g._bitField;if(!p){if(Y0._propagateFrom(this,3),Y0._captureStackTrace(),$0===void 0&&(this._bitField&2097152)!==0)if((c&50397184)!==0)$0=this._boundValue();else $0=g===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,Y0)}var e=K();if((c&50397184)!==0){var V0,j0,A0=g._settlePromiseCtx;if((c&33554432)!==0)j0=g._rejectionHandler0,V0=k;else if((c&16777216)!==0)j0=g._fulfillmentHandler0,V0=m,g._unsetRejectionIsUnhandled();else A0=g._settlePromiseLateCancellationObserver,j0=new Z("late cancellation observer"),g._attachExtraTrace(j0),V0=m;H.invoke(A0,g,{handler:e===null?V0:typeof V0==="function"&&J.domainBind(e,V0),promise:Y0,receiver:$0,value:j0})}else g._addCallbacks(k,m,Y0,$0,e);return Y0},h.prototype._length=function(){return this._bitField&65535},h.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},h.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},h.prototype._setLength=function(k){this._bitField=this._bitField&-65536|k&65535},h.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},h.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},h.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},h.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},h.prototype._isFinal=function(){return(this._bitField&4194304)>0},h.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},h.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},h.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},h.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},h.prototype._receiverAt=function(k){var m=k===0?this._receiver0:this[k*4-4+3];if(m===Q)return;else if(m===void 0&&this._isBound())return this._boundValue();return m},h.prototype._promiseAt=function(k){return this[k*4-4+2]},h.prototype._fulfillmentHandlerAt=function(k){return this[k*4-4+0]},h.prototype._rejectionHandlerAt=function(k){return this[k*4-4+1]},h.prototype._boundValue=function(){},h.prototype._migrateCallback0=function(k){var{_bitField:m,_fulfillmentHand
Line truncated
`,{mode:384}),Y}function Tp($){let Y=pA0();for(let U of Y){if(!F$(U))continue;for(let z of tB(U).filter((I)=>I.endsWith(".json")).filter((I)=>!I.startsWith("example."))){let I=j9(U,z);try{let Q=$P(I,"utf-8"),J=JSON.parse(Q);if(J&&typeof J==="object"&&J.id===$)return I}catch{}}}return}function E9($,Y){let U=Tp($);if(!U)throw Error(`Enterpriseconfignotfound:${$}`);let I={...JSON.parse($P(U,"utf-8")),...Y};for(let J of Object.keys(Y))if(Y[J]===void 0)delete I[J];let Q=hZ.parse(I);return fA0(U,`${JSON.stringify(Q,null,2)}
`,"utf-8"),Q}var Pp="SEAL_USE_ENTERPRISES_DIR",uA0="SEAL_HOME_ENTERPRISES_DIR",bA0="SEAL_USE_USER_ENTERPRISES_DIR",iA0="SEAL_HOME_USER_ENTERPRISES_DIR",cA0="SEAL_USE_CONFIG_FILE",nA0="SEAL_HOME_CONFIG_FILE",UK,eB,aB,kA0;var T5=m(()=>{sB();UK=j9(YP(),".config","seal-use","enterprises"),eB=j9(YP(),".config","seal-home","enterprises"),aB=j9(YP(),".config","seal-use","config.json"),kA0=j9(YP(),".config","seal-home","config.json")});function n2($,Y,U=[]){let z=Y.corpId?.trim()||void 0,I=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,Q=z??I;if(Q){let K=$.find((W)=>W.id===Q);if(K)return K;let G=$.find((W)=>W.id.toLowerCase()===Q.toLowerCase());if(G)return G;let H=$.find((W)=>W.name.toLowerCase()===Q.toLowerCase());if(H)return H;throw Error(`Noenterpriseconfigfoundfor${Q}`)}if(!Y.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-useconfigmodestateful` to enable a default enterprise.");let J=$[0];if(J)return J;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{existsSync as jp,mkdirSync as dD1,readFileSync as mD1,renameSync as lD1,unlinkSync as oD1,writeFileSync as rD1}from"node:fs";import{homedir as sD1}from"node:os";import{dirname as aD1,join as tD1}from"node:path";function gZ(){let $=process.env[eD1]?.trim();if($)return $;return $A1}function mA0($=new Date){return $.toISOString().slice(0,10)}function lA0($=Ep,Y=new Date){let U=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(U).toISOString().slice(0,10)}function oA0($=gZ()){if(!jp($))return{};try{let Y=mD1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&!Array.isArray(U))return U;return{}}catch{return{}}}function YA1($,Y){let U={};for(let[z,I]of Object.entries($)){if(!I||typeof I!=="object")continue;let Q={},J=!1;for(let[K,G]of Object.entries(I))if(typeof G==="number"&&G>0&&K>=Y)Q[K]=G,J=!0;if(J)U[z]=Q}return U}function UA1($,Y=gZ()){let U=aD1(Y);if(!jp(U))dD1(U,{recursive:!0,mode:448});let z=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{rD1(z,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),lD1(z,Y)}catch(I){try{if(jp(z))oD1(z)}catch{}throw I}}function rA0($,Y=new Date){if(!$||typeof $!=="string")return;try{let U=gZ(),z=oA0(U),I=mA0(Y),Q=lA0(Ep,Y),J=YA1(z,Q);J[$]=J[$]||{},J[$][I]=(J[$][I]??0)+1,UA1(J,U)}catch{}}function zA1($,Y=Ep,U=new Date){let z=new Map;try{let I=oA0(),Q=lA0(Y,U),J=mA0(U),K=$??Object.keys(I);for(let G of K){let H=I[G];if(!H){z.set(G,0);continue}let W=0;for(let[X,Z]of Object.entries(H))if(X>=Q&&X<=J&&typeof Z==="number")W+=Z;z.set(G,W)}}catch{if($)for(let I of $)z.set(I,0)}return z}function sA0($,Y,U){let z=U??zA1($.map((I)=>I.id));return[...$].sort((I,Q)=>{if(Y){if(I.id===Y&&Q.id!==Y)return-1;if(Q.id===Y&&I.id!==Y)return 1}let J=z.get(I.id)??0,K=z.get(Q.id)??0;if(J!==K)return K-J;let G=I.name??I.id,H=Q.name??Q.id,W=G.localeCompare(H,"zh-CN");if(W!==0)return W;return I.id.localeCompare(Q.id)})}var eD1="SEAL_USE_USAGE_FILE",$A1,Ep=7;var UP=m(()=>{$A1=tD1(sD1(),".config","seal-use","usage.json")});function IA1($,Y){return $.map((U)=>U.trim()).filter(Boolean).map((U)=>Y?U:U.toLowerCase())}function QA1($,Y){return Y?$:$.toLowerCase()}function JA1($,Y,U,z){let I=QA1($,z),Q=Y.filter((J)=>I.includes(J));if(U==="all"&&Q.length!==Y.length)return[];return Q}function KA1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function GA1($,Y){if(Y.fields&&!Y.fields.has($.field))return[];let U=KA1($.value),z=[];return U.forEach((I,Q)=>{let J=JA1(I,Y.keywords,Y.matchMode,Y.caseSensitive);if(J.length===0)return;let K=Math.max(0,Q-Y.contextLines),G=Math.min(U.length,Q+Y.contextLines+1),H={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Q+1,matchedKeywords:J,matchedText:zP(I,Y.maxChars),context:{before:Y.snippetOnly?[]:U.slice(K,Q).map((W)=>zP(W,Y.maxChars)),line:zP(I,Y.maxChars),after:Y.snippetOnly?[]:U.slice(Q+1,G).map((W)=>zP(W,Y.maxChars))},metadata:$.metadata};if(Y.snippetOnly)H.context={before:[],line:H.context.line,after:[]};z.push(H)}),z}function zP($,Y){if(!Y||$.length<=Y)return $;return`${$.slice(0,Math.max(0,Y))}...`}function HA1($){return[{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"description",value:$.description,metadata:{scope:$.scope,strictness:$.strictness,status:$.status}},{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"scope",value:$.scope,metadata:{strictness:$.strictness,status:$.status}}]}function tA0($){return $.rules.flatMap((Y,U)=>{let z=`${$.id}:${Y.description.slice(0,32)}`,I={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:Y.scope,strictness:Y.strictness,code:"code"in Y?Y.code:void 0,index:U};return[{area:"rules",entityType:"rule",entityId:z,title:`${$.versionName}/${Y.scope}`,field:"hi
Line truncated
`)}function zB0($){return{id:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt}}function IB0($,Y){let U=new Map;for(let z of $.rules){let I=yZ(z),Q=Y==="stable-id"?JB0(I):kZ(I.code??I.ruleCode);if(!Q)throw Error(`Ruleversion${$.versionNumber}containsarulewithouta${Y==="stable-id"?"stable rule ID":"code"}.`);if(U.has(Q))throw Error(`Ruleversion${$.versionNumber}containsduplicate${Y==="stable-id"?"stable rule ID":"code"}:${Q}`);U.set(Q,I)}return U}function MA1($,Y,U){if(U!=="auto")return U;if([...$.rules,...Y.rules].every((Q)=>Boolean(JB0(Q))))return"stable-id";if([...$.rules,...Y.rules].every((Q)=>Boolean(kZ(yZ(Q).code??yZ(Q).ruleCode))))return"code";throw Error("Rule snapshots have neither a complete stable-ID mapping nor a complete code mapping.")}function KB0($,Y,U={}){let z=MA1($,Y,U.identityMode??"auto"),I=IB0($,z),Q=IB0(Y,z),J=[...new Set([...I.keys(),...Q.keys()])],K=[],G={added:0,removed:0,modified:0,unchanged:0},H=zB0($),W=zB0(Y);for(let Z of J){let q=I.get(Z),V=Q.get(Z),w=q?Vz(q,z):void 0,M=V?Vz(V,z):void 0,F=!q?"added":!V?"removed":JSON.stringify(w)!==JSON.stringify(M)?"modified":"unchanged";if(G[F]+=1,F==="unchanged"&&!U.includeUnchanged)continue;let N=F==="modified"?[...new Set([...Object.keys(w??{}),...Object.keys(M??{})])].filter((O)=>JSON.stringify(w?.[O])!==JSON.stringify(M?.[O])):void 0;K.push({status:F,ruleId:Z,identityMode:z,...q?{before:q}:{},...V?{after:V}:{},...N?.length?{changedFields:N}:{},...F!=="unchanged"?{diff:wA1(Z,H,W,q,V,z)}:{}})}let X={from:H,to:W,identityMode:z,counts:G,changes:K,unifiedDiff:K.filter((Z)=>Z.diff).map((Z)=>Z.diff).join(`
`)};if(z==="code"){let Z=J.filter((P)=>I.has(P)&&Q.has(P)).length,q=J.filter((P)=>I.has(P)&&Q.has(P)&&JSON.stringify(Vz(I.get(P),"code"))===JSON.stringify(Vz(Q.get(P),"code"))).length,V=I.size,w=Q.size,M=Math.min(V,w)?Z/Math.min(V,w):1,F=new Map;for(let[P,T]of I)F.set(JSON.stringify(Vz(T,"code")),P);let N=0;for(let[P,T]of Q){let A=F.get(JSON.stringify(Vz(T,"code")));if(A&&A!==P)N+=1}let D=(Math.min(V,w)?q/Math.min(V,w):1)>=0.5?"high":q>0||N>0?"ambiguous":"low";X.codeStats={oldCount:V,newCount:w,sameCodeCount:Z,sameCodeUnchanged:q,sameBodyDifferentCode:N,overlapRatio:M,confidence:D,warning:"Published snapshots do not carry stableIDs; code matching can report reorderings as remove/add or modified rules."}}return X}function Rp($,Y=20000,U=!1){if(U||$.unifiedDiff.length<=Y)return{...$,truncation:{truncated:!1,maxChars:Y,omittedChars:0,hint:"Use --full only whenthe complete diff is required."}};let z=$.unifiedDiff.length-Y,I=`
...[difftruncated:${z}charactersomitted;rerunwith--fullforthecompletediff]`,Q=$.changes.map(({before:J,after:K,diff:G,...H})=>({...H,...G?{diff:G.length>Y?`${G.slice(0,Y)}${I}`:G}:{}}));return{...$,changes:Q,unifiedDiff:`${$.unifiedDiff.slice(0,Y)}${I}`,truncation:{truncated:!0,maxChars:Y,omittedChars:z,hint:"Use --full for the complete diff."}}}var QB0,LA1;var GB0=m(()=>{QB0=["id","ruleId","stableId"],LA1=new Set([...QB0,"runtimeRuleId","runtimeId","tenantId","createdAt","updatedAt","versionId","versionNumber"])});import{existsSync as OA1,mkdirSync as NA1,readFileSync as DA1,renameSync as AA1,writeFileSync as BA1}from"node:fs";import{homedir as PA1}from"node:os";import{join as HB0}from"node:path";function xZ($){if($===void 0||$===null)return;let Y=String($).trim().toLowerCase().replace(/^rule[-_:]?/,"").replace(/^#/,"");if(!Y)return;return/^\d+$/.test(Y)?String(Number(Y)):Y}function IP($){return JSON.stringify([$.description??"",$.scope??"",$.strictness??""])}function WB0(){return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim()||HB0(PA1(),".config","seal-use","rule-version-snapshots")}function TA1($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function XB0($,Y){return HB0(WB0(),`${TA1($)}-v${Y}.json`)}function fZ($,Y,U){let z=new Map,I=new Map;for(let W of U){let X=xZ(W.code);if(X)z.set(X,[...z.get(X)??[],W]);let Z=IP(W);I.set(Z,[...I.get(Z)??[],W])}let Q=[];for(let W of Y.rules??[]){let X=xZ(W.code),Z=X?z.get(X)??[]:[],q=I.get(IP(W))??[],V=Z.length===1?Z[0]:q.length===1?q[0]:void 0;if(!V)continue;Q.push({stableId:V.id,...W.code!==void 0?{code:W.code}:{},description:W.description,scope:W.scope,strictness:W.strictness})}let J={corpId:$,versionId:Y.id,versionNumber:Y.versionNumber,capturedAt:new Date().toISOString(),rules:Q},K=WB0();NA1(K,{recursive:!0,mode:448});let G=XB0($,Y.versionNumber),H=`${G}.${process.pid}.tmp`;return BA1(H,`${JSON.stringify(J,null,2)}
`,{mode:384}),Y}function gd($){let Y=WB0();for(let U of Y){if(!T$(U))continue;for(let I of XP(U).filter((Q)=>Q.endsWith(".json")).filter((Q)=>!Q.startsWith("example."))){let Q=y9(U,I);try{let J=qP(Q,"utf-8"),K=JSON.parse(J);if(K&&typeof K==="object"&&K.id===$)return Q}catch{}}}return}function g9($,Y){let U=gd($);if(!U)throw Error(`Enterpriseconfignotfound:${$}`);let Q={...JSON.parse(qP(U,"utf-8")),...Y};for(let K of Object.keys(Y))if(Y[K]===void 0)delete Q[K];let J=dZ.parse(Q);return QB0(U,`${JSON.stringify(J,null,2)}
`,"utf-8"),J}var yd="SEAL_USE_ENTERPRISES_DIR",JB0="SEAL_HOME_ENTERPRISES_DIR",KB0="SEAL_USE_USER_ENTERPRISES_DIR",zB0="SEAL_HOME_USER_ENTERPRISES_DIR",GB0="SEAL_USE_CONFIG_FILE",HB0="SEAL_HOME_CONFIG_FILE",Xz,ZP,WP,UB0;var t$=o(()=>{HP();Xz=y9(VP(),".config","seal-use","enterprises"),ZP=y9(VP(),".config","seal-home","enterprises"),WP=y9(VP(),".config","seal-use","config.json"),UB0=y9(VP(),".config","seal-home","config.json")});function r2($,Y,U=[]){let I=Y.corpId?.trim()||void 0,Q=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,J=I??Q;if(J){let z=$.find((W)=>W.id===J);if(z)return z;let G=$.find((W)=>W.id.toLowerCase()===J.toLowerCase());if(G)return G;let H=$.find((W)=>W.name.toLowerCase()===J.toLowerCase());if(H)return H;throw Error(`Noenterpriseconfigfoundfor${J}`)}if(!Y.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-useconfigmodestateful` to enable a default enterprise.");let K=$[0];if(K)return K;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{existsSync as kd,mkdirSync as uA1,readFileSync as bA1,renameSync as iA1,unlinkSync as cA1,writeFileSync as nA1}from"node:fs";import{homedir as dA1}from"node:os";import{dirname as pA1,join as mA1}from"node:path";function mZ(){let $=process.env[lA1]?.trim();if($)return $;return oA1}function ZB0($=new Date){return $.toISOString().slice(0,10)}function qB0($=xd,Y=new Date){let U=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(U).toISOString().slice(0,10)}function VB0($=mZ()){if(!kd($))return{};try{let Y=bA1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&!Array.isArray(U))return U;return{}}catch{return{}}}function rA1($,Y){let U={};for(let[I,Q]of Object.entries($)){if(!Q||typeof Q!=="object")continue;let J={},K=!1;for(let[z,G]of Object.entries(Q))if(typeof G==="number"&&G>0&&z>=Y)J[z]=G,K=!0;if(K)U[I]=J}return U}function sA1($,Y=mZ()){let U=pA1(Y);if(!kd(U))uA1(U,{recursive:!0,mode:448});let I=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{nA1(I,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),iA1(I,Y)}catch(Q){try{if(kd(I))cA1(I)}catch{}throw Q}}function LB0($,Y=new Date){if(!$||typeof $!=="string")return;try{let U=mZ(),I=VB0(U),Q=ZB0(Y),J=qB0(xd,Y),K=rA1(I,J);K[$]=K[$]||{},K[$][Q]=(K[$][Q]??0)+1,sA1(K,U)}catch{}}function aA1($,Y=xd,U=new Date){let I=new Map;try{let Q=VB0(),J=qB0(Y,U),K=ZB0(U),z=$??Object.keys(Q);for(let G of z){let H=Q[G];if(!H){I.set(G,0);continue}let W=0;for(let[X,Z]of Object.entries(H))if(X>=J&&X<=K&&typeof Z==="number")W+=Z;I.set(G,W)}}catch{if($)for(let Q of $)I.set(Q,0)}return I}function FB0($,Y,U){let I=U??aA1($.map((Q)=>Q.id));return[...$].sort((Q,J)=>{if(Y){if(Q.id===Y&&J.id!==Y)return-1;if(J.id===Y&&Q.id!==Y)return 1}let K=I.get(Q.id)??0,z=I.get(J.id)??0;if(K!==z)return z-K;let G=Q.name??Q.id,H=J.name??J.id,W=G.localeCompare(H,"zh-CN");if(W!==0)return W;return Q.id.localeCompare(J.id)})}var lA1="SEAL_USE_USAGE_FILE",oA1,xd=7;var LP=o(()=>{oA1=mA1(dA1(),".config","seal-use","usage.json")});var H8={};L8(H8,{withApprovalRunFilters:()=>AB1,toDate:()=>rd,timestampOf:()=>bd,summarizeSimulationBatch:()=>JB1,summarizeRunBridge:()=>WB1,summarizeRuleVersion:()=>XB1,summarizeApprovalRuns:()=>KB1,summarizeApprovalRunResult:()=>NP,summarizeApprovalRunDocument:()=>AB0,summarizeApprovalRunDetail:()=>GB1,summarizeApprovalRun:()=>tZ,stringifyHumanResultValue:()=>od,stringFromUnknown:()=>q4,setPath:()=>BB0,scalarIncludes:()=>wP,runtimeRuleIndex:()=>LB1,runtimeRuleIdToCode:()=>jB0,rulesHaveSameContent:()=>OB0,ruleChangedFields:()=>NB0,resolveSealBaseUrl:()=>MB1,resolveRuleVersionSelector:()=>DB1,resolveRuleVersionForLookup:()=>ZB1,resolveRuleVersion:()=>id,resolveManualApprovalStatus:()=>RB0,resolveApprovalRunForUrl:()=>wB1,redactPreviewValue:()=>rZ,redactIntegrationSecrets:()=>UB1,projectApprovalRules:()=>eA1,presentWebhookIntegration:()=>tA1,prepareApprovalRuns:()=>BB1,pickRunFields:()=>DB0,pickRuleFields:()=>MB0,pickApprovalRuns:()=>NB1,pickApprovalRunCandidate:()=>FB1,parseRuleCodeNumber:()=>z$,parseFieldPaths:()=>zB1,parseDurationMs:()=>YB1,objectContainsScalar:()=>MP,numberFromUnknown:()=>PB0,normalizeUrl:()=>OB1,normalizeRuleStrictness:()=>pd,normalizeRuleCode:()=>oZ,mutationPreview:()=>IB1,matchesRunLookup:()=>TB1,localParts:()=>sd,localDateKey:()=>EB1,isHumanResultKey:()=>cd,getPath:()=>e$,getConfiguredSealBaseUrl:()=>wB0,formatRuleCode:()=>a2,formatLocalDateTime:()=>dd,flattenDocumentFields:()=>TB0,firstPath:()=>sZ,firstByLabel:()=>lZ,findRuleInVersion:()=>VB1,findRuleInDraft:()=>qB1,findKeywordLines:()=>ud,findHumanResultValue:()=>OP,filterRunsByHumanResult:()=>CB0,filterRuns:()=>ld,extractHumanResult:()=>BI,extractCitedRules:()=>HB1,countPathCandidates:()=>fd,countBy:()=>nd,compactObject:()=>s2,collectInvoiceSummary:()=>EB0,collectInvoiceObjects:()=>aZ,collectDocumentFields:()=>FP,buildSimulationBatchParams:()=>QB1,
Line truncated
`)}function lB0($){return{id:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt}}function oB0($,Y){let U=new Map;for(let I of $.rules){let Q=eZ(I),J=Y==="stable-id"?sB0(Q):$q(Q.code??Q.ruleCode);if(!J)throw Error(`Ruleversion${$.versionNumber}containsarulewithouta${Y==="stable-id"?"stable rule ID":"code"}.`);if(U.has(J))throw Error(`Ruleversion${$.versionNumber}containsduplicate${Y==="stable-id"?"stable rule ID":"code"}:${J}`);U.set(J,Q)}return U}function mB1($,Y,U){if(U!=="auto")return U;if([...$.rules,...Y.rules].every((J)=>Boolean(sB0(J))))return"stable-id";if([...$.rules,...Y.rules].every((J)=>Boolean($q(eZ(J).code??eZ(J).ruleCode))))return"code";throw Error("Rule snapshots have neither a complete stable-ID mapping nor a complete code mapping.")}function aB0($,Y,U={}){let I=mB1($,Y,U.identityMode??"auto"),Q=oB0($,I),J=oB0(Y,I),K=[...new Set([...Q.keys(),...J.keys()])],z=[],G={added:0,removed:0,modified:0,unchanged:0},H=lB0($),W=lB0(Y);for(let Z of K){let q=Q.get(Z),V=J.get(Z),w=q?PI(q,I):void 0,M=V?PI(V,I):void 0,F=!q?"added":!V?"removed":JSON.stringify(w)!==JSON.stringify(M)?"modified":"unchanged";if(G[F]+=1,F==="unchanged"&&!U.includeUnchanged)continue;let N=F==="modified"?[...new Set([...Object.keys(w??{}),...Object.keys(M??{})])].filter((O)=>JSON.stringify(w?.[O])!==JSON.stringify(M?.[O])):void 0;z.push({status:F,ruleId:Z,identityMode:I,...q?{before:q}:{},...V?{after:V}:{},...N?.length?{changedFields:N}:{},...F!=="unchanged"?{diff:pB1(Z,H,W,q,V,I)}:{}})}let X={from:H,to:W,identityMode:I,counts:G,changes:z,unifiedDiff:z.filter((Z)=>Z.diff).map((Z)=>Z.diff).join(`
`)};if(I==="code"){let Z=K.filter((P)=>Q.has(P)&&J.has(P)).length,q=K.filter((P)=>Q.has(P)&&J.has(P)&&JSON.stringify(PI(Q.get(P),"code"))===JSON.stringify(PI(J.get(P),"code"))).length,V=Q.size,w=J.size,M=Math.min(V,w)?Z/Math.min(V,w):1,F=new Map;for(let[P,T]of Q)F.set(JSON.stringify(PI(T,"code")),P);let N=0;for(let[P,T]of J){let A=F.get(JSON.stringify(PI(T,"code")));if(A&&A!==P)N+=1}let D=(Math.min(V,w)?q/Math.min(V,w):1)>=0.5?"high":q>0||N>0?"ambiguous":"low";X.codeStats={oldCount:V,newCount:w,sameCodeCount:Z,sameCodeUnchanged:q,sameBodyDifferentCode:N,overlapRatio:M,confidence:D,warning:"Published snapshots do not carry stable IDs; code matching can report reorderings as remove/add or modified rules."}}return X}function ed($,Y=20000,U=!1){if(U||$.unifiedDiff.length<=Y)return{...$,truncation:{truncated:!1,maxChars:Y,omittedChars:0,hint:"Use --full only when the complete diff is required."}};let I=$.unifiedDiff.length-Y,Q=`
...[difftruncated:${I}charactersomitted;rerunwith--fullforthecompletediff]`,J=$.changes.map(({before:K,after:z,diff:G,...H})=>({...H,...G?{diff:G.length>Y?`${G.slice(0,Y)}${Q}`:G}:{}}));return{...$,changes:J,unifiedDiff:`${$.unifiedDiff.slice(0,Y)}${Q}`,truncation:{truncated:!0,maxChars:Y,omittedChars:I,hint:"Use --full for the complete diff."}}}var rB0,nB1;var tB0=o(()=>{rB0=["id","ruleId","stableId"],nB1=new Set([...rB0,"runtimeRuleId","runtimeId","tenantId","createdAt","updatedAt","versionId","versionNumber"])});import{existsSync as lB1,mkdirSync as oB1,readFileSync as rB1,renameSync as sB1,writeFileSync as aB1}from"node:fs";import{homedir as tB1}from"node:os";import{join as eB0}from"node:path";function Yq($){if($===void 0||$===null)return;let Y=String($).trim().toLowerCase().replace(/^rule[-_:]?/,"").replace(/^#/,"");if(!Y)return;return/^\d+$/.test(Y)?String(Number(Y)):Y}function PP($){return JSON.stringify([$.description??"",$.scope??"",$.strictness??""])}function $P0(){return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim()||eB0(tB1(),".config","seal-use","rule-version-snapshots")}function eB1($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function YP0($,Y){return eB0($P0(),`${eB1($)}-v${Y}.json`)}function Uq($,Y,U){let I=new Map,Q=new Map;for(let W of U){let X=Yq(W.code);if(X)I.set(X,[...I.get(X)??[],W]);let Z=PP(W);Q.set(Z,[...Q.get(Z)??[],W])}let J=[];for(let W of Y.rules??[]){let X=Yq(W.code),Z=X?I.get(X)??[]:[],q=Q.get(PP(W))??[],V=Z.length===1?Z[0]:q.length===1?q[0]:void 0;if(!V)continue;J.push({stableId:V.id,...W.code!==void 0?{code:W.code}:{},description:W.description,scope:W.scope,strictness:W.strictness})}let K={corpId:$,versionId:Y.id,versionNumber:Y.versionNumber,capturedAt:A1(),rules:J},z=$P0();oB1(z,{recursive:!0,mode:448});let G=YP0($,Y.versionNumber),H=`${G}.${process.pid}.tmp`;return aB1(H,`${JSON.stringify(K,null,2)}
@@ -881,65 +881,66 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
}
exportdefaultlintRule;
`}});import{existsSync as Lz,mkdirSync as lA1,readFileSync as oA1,readdirSync as NB0,rmSync as rA1,unlinkSync as sA1,writeFileSync as aA1}from"node:fs";import{homedir as tA1}from"node:os";import{isAbsolute as eA1,join as b6,resolve as $B1}from"node:path";import{pathToFileURL as MB0}from"node:url";function DB0($=p$){let Y=[],U=[];try{if(!Lz($))lA1($,{recursive:!0});let z=Object.keys(fp);for(let[Q,J]of Object.entries(fp)){let K=b6($,Q),G=!0;if(Lz(K))try{if(oA1(K,"utf8")===J)G=!1}catch{G=!0}if(G)aA1(K,J,"utf8");Y.push(Q)}let I=NB0($,{withFileTypes:!0});for(let Q of I)if(!z.includes(Q.name)){let J=b6($,Q.name);try{if(Q.isDirectory())rA1(J,{recursive:!0,force:!0});else sA1(J);U.push(Q.name)}catch{}}}catch{}return{synced:Y,pruned:U}}function AB0($={syncOfficial:!0}){if($.syncOfficial!==!1)DB0();let Y=[{name:"builtin",type:"builtin",path:b6(p$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:b6(p$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:b6(p$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],U=[n$,GP];for(let z of U)if(Lz(z))try{let I=NB0(z,{withFileTypes:!0});for(let Q of I){if(Q.isDirectory())continue;let J=Q.name;if(J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")){let K=J.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((G)=>G.name===K))Y.push({name:K,type:"custom",path:b6(z,J),description:`用户自定义规则校验器(${J})`})}}}catch{}return Y}function UB1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:b6(p$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:b6(p$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(Y==="hlab"||Y==="hlab-sop"||Y==="hlab-rules"||Y==="hlab-standard"||Y==="official/hlab"||Y==="official/hlab.ts")return{path:b6(p$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(eA1(Y)||Y.startsWith("./")||Y.startsWith("../")){let z=$B1(Y);if(Lz(z))return{path:z};for(let I of[".ts",".js",".mjs"])if(Lz(`${z}${I}`))return{path:`${z}${I}`}}let U=[b6(n$,`${Y}.ts`),b6(n$,`${Y}.js`),b6(n$,`${Y}.mjs`),b6(GP,`${Y}.ts`),b6(GP,`${Y}.js`),b6(GP,`${Y}.mjs`)];for(let z of U)if(Lz(z))return{path:z};return{}}async function bp($){DB0();let Y=UB1($??"builtin");if(Y.isOfficial){let z=Y.officialKind==="strict"?FB0:Y.officialKind==="hlab"?wB0:IK,I=Y.officialKind==="builtin"?"builtin":"official",Q=Y.path;if(Q&&Lz(Q))try{let K=await import(MB0(Q).href),G=K.default??K.lintRule??K.linter??K.lint;if(typeof G==="function")return{name:Y.officialKind??"builtin",type:I,filePath:Q,linter:OB0(G,z)}}catch{}return{name:Y.officialKind??"builtin",type:I,filePath:Q,linter:z}}let U=Y.path;if(!U)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK};try{let I=await import(MB0(U).href),Q=I.default??I.lintRule??I.linter??I.lint;if(typeof Q!=="function")return console.error(`⚠️[linter]自定义校验器"${U}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK};return{name:$??"custom",type:"custom",filePath:U,linter:OB0(Q,IK)}}catch(z){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${U}"失败(语法错误或依赖缺失:${z?.message??z}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK}}}functionOB0($,Y){returnasync(U,z)=>{try{letI=await$(U,z);if(I&&typeofI==="object"&&typeofI.score==="number"&&Array.isArray(I.issues))returnI;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),Y(U,z)}catch(I){returnconsole.error("⚠️[linter]自定义校验器执行异常:",I),Y(U,z)}}}varn$,YB1="official",p$,GP;varip=m(()=>{yp();xp();up();kp();n$=b6(tA1(),".config","seal-use","linters"),p$=b6(n$,YB1),GP=b6(process.cwd(),"linters")});asyncfunctioncp($,Y,U){letz=awaitY.linter($,U);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:z.score,passed:z.passed,issues:z.issues,description:$.description}}asyncfunctionBB0($,Y,U,z){letI=z?.minScore??0,Q=z?.level??"all",J=[],K=0;for(letqof$){letV=awaitcp(q,Y,U);K+=V.score;letw=V.issues;if(Q==="error")w=V.issues.filter((F)=>F.level==="error");elseif(Q==="warning")w=V.issues.filter((F)=>F.level==="warning"||F.level==="error");letM=w.every((F)=>F.level!=="error");if(z?.summary){if(w.length>0)J.push({...V,passed:M,issues:w})}elseJ.push({...V,passed:M,issues:w})}letG=$.length,H=G===0?100:Math.round(K/G),W=J.filter((q)=>q.issues.length>0).length,X=G-Line truncated
`}});import{homedir as LP1}from"node:os";import{join as Kp}from"node:path";var FP1,E$,j$;var zp=o(()=>{FP1=Kp(LP1(),".config","seal-use"),E$=Kp(FP1,"linters"),j$=Kp(E$,"official")});import{existsSync as TI,mkdirSync as wP1,readFileSync as MP1,readdirSync as GP0,rmSync as OP1,unlinkSync as NP1,writeFileSync as DP1}from"node:fs";import{isAbsolute as AP1,join as E8,resolve as BP1}from"node:path";import{pathToFileURL as KP0}from"node:url";function HP0($=j$){let Y=[],U=[];try{if(!TI($))wP1($,{recursive:!0});let I=Object.keys(Qp);for(let[J,K]of Object.entries(Qp)){let z=E8($,J),G=!0;if(TI(z))try{if(MP1(z,"utf8")===K)G=!1}catch{G=!0}if(G)DP1(z,K,"utf8");Y.push(J)}let Q=GP0($,{withFileTypes:!0});for(let J of Q)if(!I.includes(J.name)){let K=E8($,J.name);try{if(J.isDirectory())OP1(K,{recursive:!0,force:!0});else NP1(K);U.push(J.name)}catch{}}}catch{}return{synced:Y,pruned:U}}function WP0($={syncOfficial:!0}){if($.syncOfficial!==!1)HP0();let Y=[{name:"builtin",type:"builtin",path:E8(j$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:E8(j$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:E8(j$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],U=[E$,EP];for(let I of U)if(TI(I))try{let Q=GP0(I,{withFileTypes:!0});for(let J of Q){if(J.isDirectory())continue;let K=J.name;if(K.endsWith(".ts")||K.endsWith(".js")||K.endsWith(".mjs")){let z=K.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((G)=>G.name===z))Y.push({name:z,type:"custom",path:E8(I,K),description:`用户自定义规则校验器(${K})`})}}}catch{}return Y}function PP1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:E8(j$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:E8(j$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(Y==="hlab"||Y==="hlab-sop"||Y==="hlab-rules"||Y==="hlab-standard"||Y==="official/hlab"||Y==="official/hlab.ts")return{path:E8(j$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(AP1(Y)||Y.startsWith("./")||Y.startsWith("../")){let I=BP1(Y);if(TI(I))return{path:I};for(let Q of[".ts",".js",".mjs"])if(TI(`${I}${Q}`))return{path:`${I}${Q}`}}let U=[E8(E$,`${Y}.ts`),E8(E$,`${Y}.js`),E8(E$,`${Y}.mjs`),E8(EP,`${Y}.ts`),E8(EP,`${Y}.js`),E8(EP,`${Y}.mjs`)];for(let I of U)if(TI(I))return{path:I};return{}}async function Gp($){HP0();let Y=PP1($??"builtin");if(Y.isOfficial){let I=Y.officialKind==="strict"?QP0:Y.officialKind==="hlab"?JP0:qz,Q=Y.officialKind==="builtin"?"builtin":"official",J=Y.path;if(J&&TI(J))try{let z=await import(KP0(J).href),G=z.default??z.lintRule??z.linter??z.lint;if(typeof G==="function")return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:zP0(G,I)}}catch{}return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:I}}let U=Y.path;if(!U)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:qz};try{let Q=await import(KP0(U).href),J=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof J!=="function")return console.error(`⚠️[linter]自定义校验器"${U}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:qz};return{name:$??"custom",type:"custom",filePath:U,linter:zP0(J,qz)}}catch(I){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${U}"失败(语法错误或依赖缺失:${I?.message??I}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:qz}}}functionzP0($,Y){returnasync(U,I)=>{try{letQ=await$(U,I);if(Q&&typeofQ==="object"&&typeofQ.score==="number"&&Array.isArray(Q.issues))returnQ;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),Y(U,I)}catch(Q){returnconsole.error("⚠️[linter]自定义校验器执行异常:",Q),Y(U,I)}}}varEP;varXP0=o(()=>{zp();Yp();Ip();Jp();Up();EP=E8(process.cwd(),"linters")});asyncfunctionHp($,Y,U){letI=awaitY.linter($,U);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:I.score,passed:I.passed,issues:I.issues,description:$.description}}asyncfunctionZP0($,Y,U,I){letQ=I?.minScore??0,J=I?.level??"all",K=[],z=0;for(letqof$){letV=awaitHp(q,Y,U);z+=V.score;letw=V.issues;if(J==="error")w=V.issues.filter((F)=>F.level==="error");elseif(J==="warning")w=V.issues.filter((F)=>F.level==="warning"||F.level==="error");letM=w.every((F)=>F.level!=="error");if(I?.summary){if(w.length>0)K.push({...V,passed:M,issues:w})}elseK.push({...V,passed:M,issues:w})}letG=$.length,H=G===Line truncated
`,"utf8"),U}function wP0($){return $.map((Y,U)=>{let I=LP0(Y.code),Q;if(I!==void 0)Q=String(I).padStart(4,"0");else if(typeof Y.code==="string"&&Y.code.trim())Q=Y.code.trim().replace(/^#/,"");else Q=String(U).padStart(4,"0");return{id:Y.id,code:Q,name:Y.name,description:Y.description,scope:Y.scope,strictness:Y.strictness}})}var MP0=()=>{};var T$4,E$4,OP0,j$4,vP1,C$4,R$4,NP0,_$4,v$4,DP0,S$4,h$4,y$4,g$4,k$4,x$4,f$4,u$4,b$4,i$4,c$4,n$4,d$4,p$4,m$4,l$4,o$4,r$4,s$4,a$4,t$4,e$4,$54,Y54,U54,I54,Zp,SP1,hP1,yP1,l3,Vz,Q54,J54,jP,K54,z54,G54,H54,W54,X54,Z54,gP1,qp,q54,V54,L54,F54,w54,M54,O54,N54,D54,A54,B54,P54,T54,E54,j54,C54,R54,_54,AP0;var BP0=o(()=>{W6();X4();t$();pB0();tB0();$p();Wp();MP0();$5();({presentWebhookIntegration:T$4,getConfiguredSealBaseUrl:E$4,projectApprovalRules:OP0,pickRuleFields:j$4,buildRulePushPlan:vP1,rulesHaveSameContent:C$4,ruleChangedFields:R$4,normalizeRuleStrictness:NP0,parseDurationMs:_$4,redactIntegrationSecrets:v$4,mutationPreview:DP0,redactPreviewValue:S$4,buildSimulationBatchParams:h$4,summarizeSimulationBatch:y$4,summarizeApprovalRun:g$4,summarizeApprovalRuns:k$4,parseFieldPaths:x$4,pickRunFields:f$4,approvalRunMetadata:u$4,summarizeApprovalRunDetail:b$4,summarizeApprovalRunResult:i$4,summarizeApprovalRunDocument:c$4,extractCitedRules:n$4,firstPath:d$4,countPathCandidates:p$4,getPath:m$4,setPath:l$4,compactObject:o$4,asRecord:r$4,numberFromUnknown:s$4,flattenDocumentFields:a$4,collectDocumentFields:t$4,firstByLabel:e$4,collectInvoiceSummary:$54,collectInvoiceObjects:Y54,findKeywordLines:U54,summarizeRunBridge:I54,summarizeRuleVersion:Zp,resolveRuleVersionForLookup:SP1,findRuleInDraft:hP1,findRuleInVersion:yP1,parseRuleCodeNumber:l3,normalizeRuleCode:Vz,runtimeRuleIndex:Q54,runtimeRuleIdToCode:J54,formatRuleCode:jP,pickApprovalRunCandidate:K54,resolveApprovalRunForUrl:z54,resolveSealBaseUrl:G54,normalizeUrl:H54,stringFromUnknown:W54,pickApprovalRuns:X54,timestampOf:Z54,resolveRuleVersion:gP1,resolveRuleVersionSelector:qp,filterRuns:q54,scalarIncludes:V54,objectContainsScalar:L54,filterRunsByHumanResult:F54,withApprovalRunFilters:w54,resolveManualApprovalStatus:M54,prepareApprovalRuns:O54,approvalRunAliases:N54,extractHumanResult:D54,findHumanResultValue:A54,isHumanResultKey:B54,stringifyHumanResultValue:P54,matchesRunLookup:T54,countBy:E54,localDateKey:j54,formatLocalDateTime:C54,toDate:R54,localParts:_54}=H8),AP0=[{name:"seal_approval_rules_list",description:"列出 Seal 审批规则(默认当前草稿,传 version='latest' 或版本号则列出对应已发布版本);支持 countOnly、fields、limit",parameters:L.object({version:L.string().optional().describe("可选发布版本号或 'latest';不传则读取当前草稿"),countOnly:L.boolean().optional().describe("只返回规则数量,不返回规则列表"),fields:L.array(L.enum(["id","code","tenantId","status","strictness","scope","createdAt","updatedAt","description"])).optional().describe("只返回指定字段;不传则返回完整规则"),limit:L.number().int().nonnegative().optional().describe("最多返回多少条规则;0 可配合 fields 或 countOnly 只取数量"),offset:L.number().int().nonnegative().optional().describe("跳过前多少条规则")}),handler:async($,Y)=>{if(Y.version){let I=await qp($,Y.version),Q=(I.rules??[]).map((K)=>({id:K.id??String(K.code),tenantId:K.tenantId??"",code:l3(K.code)??K.code,description:K.description,scope:K.scope,strictness:K.strictness,status:typeof K.status==="string"?K.status:"published",createdAt:K.createdAt??I.publishedAt??I.createdAt??0,updatedAt:K.updatedAt??I.publishedAt??I.createdAt??0}));return{...OP0({rules:Q,hasPendingDeletes:!1},Y),versionNumber:I.versionNumber,versionName:I.versionName??null}}let U=await I6($);return OP0(U,Y)}},{name:"seal_approval_rules_clear",description:"清空 Seal 当前草稿审批规则;用于测试环境导入规则前重置草稿规则集",parameters:L.object({dryRun:L.boolean().optional().describe("只预览将删除的规则数量,不执行删除"),recode:L.boolean().optional().describe("删除后尝试重新编排规则编号;失败会作为 warning 返回")}),handler:async($,Y,U)=>{let I=await I6($);if(Y.dryRun)return{...DP0(U,"api/v1/rules",I.rules,[],I.rules.length),corpId:U.corp.id,corpName:U.corp.name,dryRun:!0,beforeCount:I.rules.length,deleted:0,afterCount:I.rules.length,hasPendingDeletes:I.hasPendingDeletes};let Q=[],J=0;for(let H of I.rules)try{await zJ($,H.id),J+=1}catch(W){Q.push({ruleId:H.id,error:a8(W instanceof Error?W.message:String(W))})}let K=[],z;if(J>0&&Y.recode!==!1){if(z=await fM($),z&&typeof z==="object"&&"ok"in z&&z.ok!==!0)K.push("batch-recode did not complete; current rules were still deleted")}let G=await I6($);return{corpId:U.corp.id,corpName:U.corp.name,dryRun:!1,beforeCount:I.rules.length,deleted:J,failed:Q,afterCount:G.rules.length,hasPendingDeletes:G.hasPendingDeletes,warnings:K,recode:z}}},{name:"seal_approval_rule_create",description:"新建 Seal 草稿审批规则",parameters:L.object({
Line truncated
\uD83D\uDC49Nextaction:若您已直接修改远端草稿、仅需发布正式版本,请执行seal-userulespublish"${q}"--corp${U.corp.id}`)}throw Z}let K=Y.confirm!==!0||Y.dryRun===!0,z=await I6($),G=vP1(z.rules,Q.rules);if(K)return{...DP0(U,"api/v1/rules",z.rules,Q.rules.map((Z)=>({description:Z.description,scope:Z.scope??"ALL",strictness:Z.strictness??"MUST_FOLLOW"})),z.rules.length+Q.rules.length),corpId:U.corp.id,dryRun:!0,localFile:Q.resolvedPath,localRulesCount:Q.rules.length,remoteDraftCount:z.rules.length,changes:G,impactCount:G.created.length+G.updated.length+G.deleted.length,preservedRuleIds:[...G.updated.map((Z)=>Z.id),...G.unchanged.map((Z)=>Z.id)],warning:"Incremental mode preserves matched rule IDs and does not recode the draft rule set.",willPublish:Boolean(Y.publish),message:"Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft."};for(let Z of G.deleted)await zJ($,Z.id);let H=[];for(let Z of G.created){let q=await lH($,{description:Z.description,scope:Z.scope??"ALL",strictness:NP0(Z.strictness)});H.push({id:q.id,description:q.description,code:q.code})}let W=[];for(let Z of G.updated)await yy($,Z.id,{description:Z.rule.description,scope:Z.rule.scope??"ALL",strictness:NP0(Z.rule.strictness)}),W.push(Z.id);let X=void 0;if(Y.publish){let Z=A1().slice(0,10).replace(/-/g,""),q=Y.versionName||`v-local-${Z}-${Date.now().toString().slice(-4)}`;X=await oH($,q);try{let V=await I6($);Uq(U.corp.id,X.version,V.rules)}catch{}}return{corpId:U.corp.id,dryRun:!1,localFile:Q.resolvedPath,deletedRules:G.deleted.length,createdRules:H.length,updatedRules:W.length,unchangedRules:G.unchanged.length,preservedRuleIds:[...W,...G.unchanged.map((Z)=>Z.id)],recoded:!1,published:X??!1}}},{name:"seal_approval_documents_list",description:"列出 Seal 审批知识文档",parameters:L.object({scenarios:L.array(L.string()).optional().describe("场景过滤"),offset:L.number().int().nonnegative().optional(),limit:L.number().int().positive().optional()}),handler:async($,Y)=>YU($,Y)},{name:"seal_approval_document_get",description:"获取 Seal 审批知识文档详情",parameters:L.object({documentId:L.string().describe("文档 ID")}),handler:async($,Y)=>O40($,Y.documentId)},{name:"seal_approval_document_create",description:"新建 Seal 审批知识文档",parameters:L.object({title:L.string(),purpose:L.string(),content:L.string().describe("正文,通常为 Markdown"),contentType:L.string().optional(),status:L.string().optional(),enabled:L.boolean().optional(),scenarios:L.array(L.string()).optional(),tags:L.array(L.string()).optional()}),handler:async($,Y)=>uM($,Y)},{name:"seal_approval_document_update",description:"更新 Seal 审批知识文档",parameters:L.object({documentId:L.string(),title:L.string().optional(),purpose:L.string().optional(),content:L.string().optional(),contentType:L.string().optional(),status:L.string().optional(),enabled:L.boolean().optional(),scenarios:L.array(L.string()).optional(),tags:L.array(L.string()).optional()}),handler:async($,Y)=>{let{documentId:U,...I}=Y;return bM($,U,I)}},{name:"seal_approval_delete_document",description:"删除 Seal 审批知识文档",parameters:L.object({documentId:L.string().describe("知识文档 ID")}),handler:($,Y)=>iM($,Y.documentId)},{name:"seal_approval_search",description:"按关键词组检索 Seal 审批规则、审批文档和审批偏好配置,返回命中位置、字段、行号和前后三行上下文",parameters:L.object({keywords:L.array(L.string()).min(1).describe("关键词组"),matchMode:L.enum(["any","all"]).optional().describe("any 命中任一关键词,all 要求同一行命中全部关键词"),areas:L.array(L.enum(["rules","documents","preferences"])).optional().describe("检索范围"),caseSensitive:L.boolean().optional().describe("是否大小写敏感"),contextLines:L.number().int().nonnegative().optional().describe("返回命中行前后几行,默认 3"),documentLimit:L.number().int().positive().optional().describe("缓存刷新时最多拉取文档数,默认 100"),maxResults:L.number().int().positive().optional().describe("最多返回命中数,默认 50"),refresh:L.boolean().optional().describe("是否跳过 5 分钟内存缓存并强制刷新"),ruleVersionScope:L.enum(["current","all","version"]).optional().describe("规则检索范围,默认 current;all 会检索所有已发布历史版本"),ruleVersionId:L.string().optional().describe("ruleVersionScope=version 时指定版本 ID"),ruleVersionNumber:L.number().int().positive().optional().describe("ruleVersionScope=version 时指定版本号"),latestRuleVersion:L.boolean().optional().describe("ruleVersionScope=version 时取最新已发布版本"),snippetOnly:L.boolean().optional().describe("只返回命中行,不返回前后文"),maxChars:L.number().int().positive().optional().describe("每个文本片段最多返回字符数"),fields:L.array(L.string()).optional().describe("只搜索指定字段,如 history.descrip
Line truncated
`),z=await Promise.all(O.map((D)=>H4($,D.id)))}let I=new Map,Q=0;for(let F of z){let N=F.document,O=F.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??F.documentId??F.id,D=`${U.docIdPrefix??""}${O}${U.docIdSuffix??""}`,P=[];if(U.includeAttachments!==!1){let A=c2(F,{summary:!1}).attachments,j=new Set;for(let C of A){let b=C.ossSignedUrl??C.url;if(!b)continue;let x=C.fileName??C.fileId??"attachment",g=Dp(x),i=g,c=g.lastIndexOf("."),z0=c>0?g.slice(0,c):g,k=c>0?g.slice(c):"",d=1;while(j.has(i.toLowerCase()))i=`${z0}_${d}${k}`,d++;j.add(i.toLowerCase());try{process.stderr.write(`⬇下载单据「${D}」附件:${x}...
`),await new Promise((F,N)=>{let O=vS1(V),D=new gl({zlib:{level:9}});O.on("close",()=>F()),D.on("error",(P)=>N(P)),D.pipe(O),D.append(Buffer.from(w),{name:"信息表.xlsx"});for(let P of I.values())for(let T of P)D.append(T.buffer,{name:T.zipPath});D.finalize()});let M=SS1(V);return{filePath:V,corpId:Y.id,corpName:Y.name,recordCount:z.length,attachmentCount:Q,fileSizeBytes:M.size,exportedAt:new Date().toISOString(),nextAction:`seal-usewebhookresource-packpush${V}--corp<targetCorpId>`}}var C_0;var yl=m(()=>{j_0();X6();oB();C_0=I6(_Z(),1)});import{readFileSync as fS1}from"node:fs";function uS1($){let Y=new URL($),U=Y.pathname.match(/\/webhook\/([^/]+)/);if(!U)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:U[1]}}function bS1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function iS1($,Y){if(!$.length)return;let U=new Set($.map((Q)=>{let J=Q.fileName.split("/")[0],K=J.indexOf("@");return K>=0?J.slice(0,K):J}).filter((Q)=>Q!=="信息表.xlsx")),z=[];for(let Q of Y){let J=Q.document.documentId;if((Q.documentAttachments.length>0||Object.values(Q.expenseAttachments).some((G)=>G.length>0)||Object.values(Q.personAttachments).some((G)=>G.length>0))&&!U.has(J))z.push(`Excel 会议编号「${J}」声明了附件,但在 ZIP 中找不到对应的根目录「${J}/」或「${J}@.../」。`)}let I=new Set(Y.map((Q)=>Q.document.documentId));for(let Q of U)if(!I.has(Q))z.push(`ZIP 根目录对应的编号「${Q}」在信息表中找不到对应的会议编号。`);if(z.length)throw new j5(z)}async function R_0($,Y,U){let z=[],I=$;if(bS1($,Y)){z=await uP0($),iP0(z,U);let G=z.find((H)=>H.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");I=await yd($,G)}let Q=await oP0(I);iS1(z,Q);let J=rP0(z,Q),K=Q.map((G)=>G.document);return{entries:z,parsed:Q,plans:J,documents:K,fileBuffer:$}}async function kz($,Y,U){let z=await R_0($,Y,U),I=z.parsed.map((Q,J)=>id(Q.document,z.plans[J],new Map));return{warnings:[],documents:I,attachmentPlan:z.plans}}async function OT($,Y,U){let z=await R_0($,Y,U.materialPackFilePolicy),{baseUrl:I,webhookId:Q}=uS1(U.webhookUrl),J=[];for(let K=0;K<z.parsed.length;K+=1){let G=z.parsed[K],H=z.plans[K],W=new Map,X=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let V of X)for(let w of V.paths){if(W.has(w))continue;let M=z.entries.find((T)=>T.fileName===w);if(!M)continue;process.stderr.write(`⬆ 上传附件: ${w}
`),I=await Promise.all(O.map((D)=>W4($,D.id)))}let Q=new Map,J=0;for(let F of I){let N=F.document,O=F.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??F.documentId??F.id,D=`${U.docIdPrefix??""}${O}${U.docIdSuffix??""}`,P=[];if(U.includeAttachments!==!1){let A=p3(F,{summary:!1}).attachments,E=new Set;for(let C of A){let i=C.ossSignedUrl??C.url;if(!i)continue;let x=C.fileName??C.fileId??"attachment",h=vd(x),b=h,n=h.lastIndexOf("."),I0=n>0?h.slice(0,n):h,k=n>0?h.slice(n):"",m=1;while(E.has(b.toLowerCase()))b=`${I0}_${m}${k}`,m++;E.add(b.toLowerCase());try{process.stderr.write(`⬇下载单据「${D}」附件:${x}...
`),await new Promise((F,N)=>{let O=Wg1(V),D=new Ko({zlib:{level:9}});O.on("close",()=>F()),D.on("error",(P)=>N(P)),D.pipe(O),D.append(Buffer.from(w),{name:"信息表.xlsx"});for(let P of Q.values())for(let T of P)D.append(T.buffer,{name:T.zipPath});D.finalize()});let M=Zg1(V);return{filePath:V,corpId:Y.id,corpName:Y.name,recordCount:I.length,attachmentCount:J,fileSizeBytes:M.size,exportedAt:A1(),nextAction:`seal-usewebhookresource-packpush${V}--corp<targetCorpId>`}}var Tv0;var zo=o(()=>{Bv0();X4();nZ();Tv0=H6(iZ(),1)});import{readFileSync as wg1}from"node:fs";function Mg1($){let Y=new URL($),U=Y.pathname.match(/\/webhook\/([^/]+)/);if(!U)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:U[1]}}function Og1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function Ng1($,Y){if(!$.length)return;let U=new Set($.map((J)=>{let K=J.fileName.split("/")[0],z=K.indexOf("@");return z>=0?K.slice(0,z):K}).filter((J)=>J!=="信息表.xlsx")),I=[];for(let J of Y){let K=J.document.documentId;if((J.documentAttachments.length>0||Object.values(J.expenseAttachments).some((G)=>G.length>0)||Object.values(J.personAttachments).some((G)=>G.length>0))&&!U.has(K))I.push(`Excel 会议编号「${K}」声明了附件,但在 ZIP 中找不到对应的根目录「${K}/」或「${K}@.../」。`)}let Q=new Set(Y.map((J)=>J.document.documentId));for(let J of U)if(!Q.has(J))I.push(`ZIP 根目录对应的编号「${J}」在信息表中找不到对应的会议编号。`);if(I.length)throw new g5(I)}async function Ev0($,Y,U){let I=[],Q=$;if(Og1($,Y)){I=await kT0($),fT0(I,U);let G=I.find((H)=>H.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");Q=await zm($,G)}let J=await pT0(Q);Ng1(I,J);let K=mT0(I,J),z=J.map((G)=>G.document);return{entries:I,parsed:J,plans:K,documents:z,fileBuffer:$}}async function mI($,Y,U){let I=await Ev0($,Y,U),Q=I.parsed.map((J,K)=>qm(J.document,I.plans[K],new Map));return{warnings:[],documents:Q,attachmentPlan:I.plans}}async function iT($,Y,U){let I=await Ev0($,Y,U.materialPackFilePolicy),{baseUrl:Q,webhookId:J}=Mg1(U.webhookUrl),K=[];for(let z=0;z<I.parsed.length;z+=1){let G=I.parsed[z],H=I.plans[z],W=new Map,X=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let V of X)for(let w of V.paths){if(W.has(w))continue;let M=I.entries.find((T)=>T.fileName===w);if(!M)continue;process.stderr.write(`⬆ 上传附件: ${w}
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:W?J:Z?V:G,type:X,mode:Z?"auto_login":"direct",sealResultUrl:G,hoseDocumentUrl:J,documentUrl:J,ssoUrl:V,expiresIn:Z?q:void 0,identity:w,warning:M,hoseDomain:Q.type==="hose"?wg1(Q.domain):void 0,recordId:I.id,sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId,sourceSystem:I.sourceSystem,missing:{hoseDocumentUrl:!J?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:L.object({query:L.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:L.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:L.string().optional().describe("模拟批次 ID"),latest:L.boolean().optional().describe("只返回最新一条匹配记录"),fields:L.union([L.string(),L.array(L.string())]).optional().describe("限制返回字段"),limit:L.number().int().positive().max(100).optional(),maxScan:L.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:L.boolean().optional()}),handler:async($,Y,U)=>{let z=Y.sn??Y.query;if(!z)throw Error("query or sn is required");let I=await Mg1($,{query:z,sn:Y.sn,batchId:Y.batchId,latest:Y.latest,limit:Y.latest?1:Y.limit??20,maxScan:Y.maxScan??1000}),Q=await Promise.all(I.records.map((X)=>H4($,X.id))),J=y_0(Y.fields),K=Q.map((X)=>Vg1(X,J)),G=Q.find((X)=>X.ruleSetVersionNumber!==void 0)?.ruleSetVersionNumber,H=G===void 0?"latest":String(G),W=G===void 0?'"latestRuleVersion":true':`"ruleVersionNumber":${G}`;return{query:z,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:I.total,scanned:I.scanned,matched:K.length,records:K,next:{getSummary:`seal-useapproval-runsget<recordId>--summary--corp${U.corp.id}`,getRuleVersion:`seal-userulesversion${H}--corp${U.corp.id}`,searchRuleVersion:`seal-usetoolseal_approval_search--corp${U.corp.id}--json'{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${W}}'`,getVersionContext:`seal-usetoolseal_approval_context_get--corp${U.corp.id}--json'{${W}}'`},...Y.includeBridge?{bridge:TT(Q)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:L.object({batchId:L.string().describe("simulation batch ID"),query:L.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,Y)=>{let U=ml(await Pg($,Y.batchId),Y.query);return{batchId:Y.batchId,count:U.length,records:U.map(fz),bridge:TT(U)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:L.object({mode:L.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:L.array(L.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:L.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:L.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:L.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:L.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:L.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:L.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:L.array(L.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:L.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:L.record(L.string(),L.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:L.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:L.record(L.string(),L.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,Y)=>{let U=Y.mode??"hosecloud",z=Y.signKey;if(U==="hosecloud"&&!z){if(z=(await jg($)).find((K)=>K.signKey)?.signKey,!z)throw Error("
Line truncated
`)}function Rg1($){let Y=[];if(Y.push(`seal-use${$.area}-${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");let U=new Map;for(let I of $.commands){let Q=I.group??"",J=U.get(Q)??[];J.push(I),U.set(Q,J)}let z=[...$.groupOrder??[],...[...U.keys()].filter((I)=>!$.groupOrder?.includes(I))];for(let I of z){let Q=U.get(I);if(!Q)continue;if(I)Y.push(""),Y.push(`${I}:`);for(let J of Q)for(let K of J.usage)Y.push(`${K}`)}if($.commands.some((I)=>I.name))Y.push(""),Y.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return Y.join(`
`)}function $v0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of Yv0)for(let U of Y.commands)for(let z of U.usage)$.push(`${z}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var Yv0;var el=m(()=>{O8();Yv0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",groupOrder:["企业接入","发现与选择","企业配置","测试配对与验证","Hose 专属能力"],commands:[{name:"list",group:"发现与选择",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],group:"发现与选择",summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],group:"发现与选择",summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",group:"发现与选择",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",group:"发现与选择",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",group:"企业配置",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"rename",group:"企业配置",summary:"Rename an enterprise display name",usage:["seal-use corps rename <corpId> --name <newName>"],options:[{flag:"--name <newName>",description:"New human-readable enterprise name (required)"}],description:"Safely updates the display name of a configured enterprise without modifying underlying files manually."},{name:"bind-test",group:"测试配对与验证",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",group:"测试配对与验证",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",group:"测试配对与验证",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new versi
Line truncated
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:W?K:Z?V:G,type:X,mode:Z?"auto_login":"direct",sealResultUrl:G,hoseDocumentUrl:K,documentUrl:K,ssoUrl:V,expiresIn:Z?q:void 0,identity:w,warning:M,hoseDomain:J.type==="hose"?Sg1(J.domain):void 0,recordId:Q.id,sourceDocumentSN:Q.sourceDocumentSN,sourceDocumentId:Q.sourceDocumentId,sourceSystem:Q.sourceSystem,missing:{hoseDocumentUrl:!K?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:L.object({query:L.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:L.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:L.string().optional().describe("模拟批次 ID"),latest:L.boolean().optional().describe("只返回最新一条匹配记录"),fields:L.union([L.string(),L.array(L.string())]).optional().describe("限制返回字段"),limit:L.number().int().positive().max(100).optional(),maxScan:L.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:L.boolean().optional()}),handler:async($,Y,U)=>{let I=Y.sn??Y.query;if(!I)throw Error("query or sn is required");let Q=await yg1($,{query:I,sn:Y.sn,batchId:Y.batchId,latest:Y.latest,limit:Y.latest?1:Y.limit??20,maxScan:Y.maxScan??1000}),J=await Promise.all(Q.records.map((W)=>W4($,W.id))),K=vv0(Y.fields),z=J.map((W)=>Rg1(W,K)),G=J.find((W)=>W.ruleSetVersionNumber!==void 0)?.ruleSetVersionNumber,H=G===void 0?"latest":String(G);return{query:I,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:Q.total,scanned:Q.scanned,matched:z.length,records:z,next:{getSummary:`seal-useapproval-runsget<recordId>--summary--corp${U.corp.id}`,getRuleVersion:`seal-userulesversion${H}--corp${U.corp.id}`,searchRuleVersion:`seal-userulessearch<keyword>--version${H}--corp${U.corp.id}`,getVersionContext:`seal-usecontext--ruleVersion${H}--corp${U.corp.id}`},...Y.includeBridge?{bridge:Xo(J)}:{}}}},{name:"seal_approval_run_langfuse_bridge_get",description:"从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",parameters:L.object({recordId:L.string().optional(),sourceDocumentSN:L.string().optional(),sourceDocumentId:L.string().optional(),simulationBatchId:L.string().optional(),limit:L.number().int().positive().max(100).optional()}),handler:async($,Y)=>{let I=(Y.simulationBatchId?await mM($,Y.simulationBatchId):(await u4($,{limit:Y.limit??50,search:Y.sourceDocumentSN??Y.sourceDocumentId,sourceDocumentSN:Y.sourceDocumentSN,sourceDocumentId:Y.sourceDocumentId})).records).filter((Q)=>ug1(Q,{recordId:Y.recordId,sourceDocumentSN:Y.sourceDocumentSN,sourceDocumentId:Y.sourceDocumentId}));return{count:I.length,records:I.map(_v0),bridge:Xo(I)}}},{name:"seal_approval_runs_stats",description:"统计审核记录状态分布、来源系统分布及按单号/ID去重统计",parameters:L.object({since:L.string().optional().describe("时间范围,如 3months, 7days, 24hours"),dedupeBy:L.enum(["sourceDocumentSN","sourceDocumentId","id"]).default("sourceDocumentSN").describe("去重字段"),status:L.string().optional(),sourceSystem:L.string().optional(),taskMode:L.string().optional()}),handler:async($,Y)=>{let U=await u4($,{limit:1000,status:Y.status,sourceSystem:Y.sourceSystem,taskMode:Y.taskMode}),I=Y.dedupeBy??"sourceDocumentSN",Q=U.records,J={},K={},z=new Set;for(let H of Q){let W=H.status??"unknown";J[W]=(J[W]??0)+1;let X=H.sourceSystem??"unknown";K[X]=(K[X]??0)+1;let Z=H[I];if(Z)z.add(String(Z))}let G=Math.max(0,Q.length-z.size);return{total:Q.length,dedupeBy:I,unique:z.size,duplicateRuns:G,dedupeNote:G>0?`存在${G}笔重复运行记录(同一单据重跑或修改重推)`:"全部单据唯一,无重复记录",byStatus:J,bySourceSystem:K}}},{name:"seal_approval_runs_count",description:"统计符合条件的审核记录总数",parameters:L.object({status:L.string().optional(),sourceSystem:L.string().optional(),taskMode:L.string().optional(),search:L.string().optional(),startDate:L.string().optional().describe("起始时间戳(毫秒)或日期字符串"),endDate:L.string().optional().describe("结束时间戳(毫秒)或日期字符串")}),handler:async($,Y)=>{let U=await u4($,{limit:1,status:Y.status,sourceSystem:Y.sourceSystem,taskMode:Y.taskMode,search:Y.search,startDate:a$(Y.startDate,!1),endDate:a$(Y.endDate,!0)});return{total:U.total??U.records.length}}}]});import{readFileSync as bg1}from"node:fs";var GI4,HI4,WI4,XI4,ZI4,qI4,VI4,LI4,kv0,FI4,wI4,MI4,ig1,cg1,ng1,OI4,NI4,DI4,AI4,BI4,PI4,TI4,EI4,jI4,CI4,RI4,_I
Line truncated
`)}function Yk1($){let Y=[];if(Y.push(`seal-use${$.area}-${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");let U=new Map;for(let Q of $.commands){let J=Q.group??"",K=U.get(J)??[];K.push(Q),U.set(J,K)}let I=[...$.groupOrder??[],...[...U.keys()].filter((Q)=>!$.groupOrder?.includes(Q))];for(let Q of I){let J=U.get(Q);if(!J)continue;if(Q)Y.push(""),Y.push(`${Q}:`);for(let K of J)for(let z of K.usage)Y.push(`${z}`)}if($.commands.some((Q)=>Q.name))Y.push(""),Y.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return Y.join(`
`)}function dv0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of pv0)for(let U of Y.commands)for(let I of U.usage)$.push(`${I}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var pv0;var No=o(()=>{p8();pv0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",groupOrder:["企业接入","发现与选择","企业配置","测试配对与验证","Hose 专属能力"],commands:[{name:"list",group:"发现与选择",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],group:"发现与选择",summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],group:"发现与选择",summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",group:"发现与选择",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",group:"发现与选择",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",group:"企业配置",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"rename",group:"企业配置",summary:"Rename an enterprise display name",usage:["seal-use corps rename <corpId> --name <newName>"],options:[{flag:"--name <newName>",description:"New human-readable enterprise name (required)"}],description:"Safely updates the display name of a configured enterprise without modifying underlying files manually."},{name:"bind-test",group:"测试配对与验证",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",group:"测试配对与验证",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",group:"测试配对与验证",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new versi
Line truncated
`;if(Y.outputFile){_g1(Y.outputFile,U),console.log(JSON.stringify({outputFile:Y.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function gg1($,Y={}){if(Y.allowFull||Y.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>Sg1)throw new JP(`Outputislarge(${U}bytes).Use--summary,--fields,--count,or--output-file;pass--fullonlywhenyoureallyneedthefullresponse.`)}function Qv0($,Y){if(Y)return;let U=$&&typeof $==="object"?$:{},z=typeof U.count==="number"?U.count:void 0,I=Array.isArray(U.rules)?U.rules.length:void 0,Q=Buffer.byteLength(JSON.stringify($),"utf-8"),J=z??I??0;if(J>vg1||Q>hg1)throw new JP(`Rulelistislarge(${J}rules,${Q}bytes).Use"seal-use rules list --summary","seal-use rules count",or--output-file;pass--fullonlywhenyoureallyneedfulldescriptions.`,"seal-use rules list --summary")}function j0($){return{allowFull:G0($.full)===!0,outputFile:S($.outputFile)??S($["output-file"])}}function Jv0($=[]){console.log(zv0($))}var vg1=100,hg1=120000,Iv0,Sg1=200000;var m1=m(()=>{Z4();O8();el();Iv0=["code","status","strictness","scope","updatedAt"]});var Yo={};T8(Yo,{selectCorp:()=>M1,runToolResult:()=>M$,runTool:()=>x0,globalConfigSummary:()=>t2});function M1($){let Y=t8(),U=v4(),z=n2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$},x3());return rA0(z.id),z}function t2($=v4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:Zz()}}async function x0($,Y,U,z,I={}){R0(await M$($,Y,U,z),I)}async function M$($,Y,U,z){let I=Pq.find((K)=>K.name===$);if(!I)throw Error(`UnknownSealtool:${$}`);let Q=Object.fromEntries(Object.entries(z).filter(([,K])=>K!==void 0)),J=I.handler;return J(Y,Q,{corp:U})}var O4=m(()=>{T5();UP();jq();m1()});import{existsSync as Kv0}from"node:fs";async function Gv0($,Y){if(!Kv0($))throw Error(`Filenotfound:${$}`);let U=xz($);console.log(JSON.stringify(await kz(U.fileBuffer,U.fileName,Y),null,2))}async function gT($,Y,U,z,I){if($==="ready"||$==="status"){let Q=Y??S(I.options.file)??S(I.options.input),J=await NT(U,z,{filePath:Q,webhook:S(I.options.webhook)??S(I.options.selector)});if(console.error(`[webhook-ready]企业环境:${J.corp.name}(${J.corp.id})[${J.stateMode}]`),J.corp.tenant?.name)console.error(`[webhook-ready]租户信息:${J.corp.tenant.name}(${J.corp.tenant.id})`);console.error(`[webhook-ready]凭证状态:${J.authStatus==="ok"?"OK":`异常 (${J.authError})`}`),console.error(`[webhook-ready]Webhook通道:${J.activeWebhooks.length}个可用`);for(let K of J.activeWebhooks){let G=K.isDefault?" [默认通道]":"";console.error(`-${K.name}(${K.id})mode=${K.mode}${G}`)}if(J.materialPack)console.error(`[webhook-ready]材料包预检:${J.materialPack.valid?`通过 (${J.materialPack.documentCount} 单)`:`失败 (${J.materialPack.errors?.join("; ")})`}`);if(J.ready)console.error(`\uD83D\uDFE2${J.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${J.nextAction}`);else console.error(`\uD83D\uDD34准备阶段未通过:${J.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${J.nextAction}`);console.log(JSON.stringify(J,null,2));return}if($==="replay"){let Q=Y??S(I.options.recordId)??S(I.options["record-id"])??S(I.options.id),J=S(I.options.recordIds)??S(I.options["record-ids"]),K=J?J.split(",").map((c)=>c.trim()).filter(Boolean):void 0,G=S(I.options.sn)??S(I.options.documentSn)??S(I.options["document-sn"]),H=S(I.options.sns)??S(I.options["document-sns"]),W=H?H.split(",").map((c)=>c.trim()).filter(Boolean):void 0,X=s0(I.options.limit),Z=S(I.options.status),q=S(I.options.startDate)??S(I.options["start-date"]),V=S(I.options.endDate)??S(I.options["end-date"]);if(!Q&&!K&&!G&&!W&&X===void 0)throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let w=S(I.options.sourceCorp)??S(I.options["source-corp"])??S(I.options.prodCorp)??S(I.options["prod-corp"]),M=S(I.options.targetCorp)??S(I.options["target-corp"])??S(I.options.testCorp)??S(I.options["test-corp"]),F=G0(I.options.force)===!0,{sourceCorp:N,targetCorp:O}=KP({sourceCorpId:w,targetCorpId:M,activeCorp:z,force:F},M1),D=N.id===z.id?U:await B1(N),P=O.id===z.id?U:await B1(O),T=S(I.options.webhook)??S(I.options.selector),A=S(I.options.snSuffix)??S(I.options["sn-suffix"]),j=S(I.options.snPrefix)??S(I.options["sn-prefix"]),C=S(I.options.docIdSuffix)??S(I.options["doc-id-suffix"]),b=S(I.options.docIdPrefix)??S(I.options["doc-id-prefix"]),x=G0(I.options.dryRun)??G0(I.options["dry-run"]),i=await zK({query:{recordId:Q,recordIds:K,sn:G,sns:W,limit:X,status:Z,startDate:q,endDate:V},sourceClient:D,targetClient:P,sourceCorp:N,targetCorp:O,webhookSelector:T,snPrefix:j,snSuffix:A,docIdPrefix:b,docIdSuffix:C,dr
Line truncated
or:seal-usecorpsbind-test<testCorpId>--corp<prodCorpId>[--confirm][--force]`);let Q=M1(z),J=M1(I);if(Q.id===J.id)throw h4(`Cannotbindenterprise'${Q.id}'toitself.`);if(Q.prodCorpId&&Q.prodCorpId!==J.id)throw h4(`Cannotuse'${Q.id}'asaproductionenterprisebecauseitisalreadyregisteredasatestenterprisefor'${Q.prodCorpId}'.Multi-tierchainingisnotpermitted.`);if(J.testCorpId&&J.testCorpId!==Q.id)throw h4(`Cannotbind'${J.id}'asatestenterprisebecauseitalreadyhasaboundtestenterprise'${J.testCorpId}'.Multi-tierchainingisnotpermitted.`);let K=G0(U.options.force)===!0;if(Q.testCorpId&&Q.testCorpId!==J.id||J.prodCorpId&&J.prodCorpId!==Q.id){if(!K)throw w$(`Enterprisebindingconflict:productionenterprise'${Q.id}'isboundto'${Q.testCorpId??"none"}',andtestenterprise'${J.id}'isboundto'${J.prodCorpId??"none"}'.Overwritinganexistingbindingrequires--forceand--confirm.`,`seal-usecorpsbind-test${Q.id}${J.id}--confirm--force`)}if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0)){let X=K?" --force":"";throw w$(`Refusingtobindtestenterprise'${J.name}'(${J.id})toproductionenterprise'${Q.name}'(${Q.id})without--confirm.Enterprisebindingestablishes1-to-1syncpairingandmarks'${J.id}'asatestenvironment.`,`seal-usecorpsbind-test${Q.id}${J.id}--confirm${X}`)}if(Q.testCorpId&&Q.testCorpId!==J.id)try{E9(Q.testCorpId,{prodCorpId:void 0})}catch{}if(J.prodCorpId&&J.prodCorpId!==Q.id)try{E9(J.prodCorpId,{testCorpId:void 0})}catch{}let H=E9(Q.id,{environment:"production",testCorpId:J.id}),W=E9(J.id,{environment:"test",prodCorpId:Q.id});return R0({success:!0,productionEnterprise:{id:H.id,name:H.name,environment:H.environment,testCorpId:H.testCorpId},testEnterprise:{id:W.id,name:W.name,environment:W.environment,prodCorpId:W.prodCorpId}}),!0}if($==="unbind-test"){let z=Y??S(U.options.corp),I=M1(z);if(!I.testCorpId&&!I.prodCorpId)return R0({unbound:!1,message:`Enterprise'${I.name}'(${I.id})doesnothaveanactivetestenterprisebinding.`}),!0;let Q=I.testCorpId?I.id:I.prodCorpId,J=I.testCorpId?I.testCorpId:I.id;if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0))throw w$(`Refusingtounbindproductionenterprise'${Q}'andtestenterprise'${J}'without--confirm.`,`seal-usecorpsunbind-test${I.id}--confirm`);E9(Q,{testCorpId:void 0});try{E9(J,{prodCorpId:void 0})}catch{}return R0({success:!0,unboundProduction:Q,unboundTest:J}),!0}return!1}var Vv0=m(()=>{T5();O4();O8();Z4();m1()});function yT($){let Y;try{Y=new URL($.trim())}catch{throw Error("Invalid Seal delegate link: expected a valid HTTPS URL")}if(Y.protocol!=="https:")throw Error("Invalid Seal delegate link: expected HTTPS");let U=Y.hostname.toLowerCase();if(!U.endsWith(Lv0))throw Error(`InvalidSealdelegatelink:expectedhostendingin${Lv0},got${U}`);let z=Y.pathname.replace(/\/+$/,"");if(z!==Fv0)throw Error(`InvalidSealdelegatelink:expectedpath${Fv0},got${z}`);let I=Y.searchParams.get("token");if(!I)throw Error("Invalid Seal delegate link: token query parameter is required");return{sealUrl:Y.origin,delegateToken:I}}async function wv0($){let Y=typeof $==="string"?yT($):$;return(await B6(Y.sealUrl,void 0).post("api/v1/delegation/preview",{json:{token:Y.delegateToken}}).json()).data}async function Mv0($){let Y=typeof $==="string"?yT($):$,U=Y.sealUrl,z=B6(U,void 0),I=await z.post("api/v1/delegation/consume",{json:{token:Y.delegateToken}}),Q=I.headers.get("set-cookie")??"",J=typeof I.headers.getSetCookie==="function"?I.headers.getSetCookie():[Q],K="";for(let M of J)if(M&&M.includes("session_token=")){K=(M.split(";")[0]??"").trim();break}let G;try{G=await z.get("api/auth/get-session",{headers:K?{cookie:K}:{}}).json()}catch{}let H=G?.session?.token;if(!H&&K){let M=K.match(/session_token=([^.;]+)/);if(M?.[1])H=decodeURIComponent(M[1])}if(!H)throw Error("Seal delegate exchange did not return a session token");let W=86400;if(G?.session?.expiresAt){let M=new Date(G.session.expiresAt).getTime();if(Number.isFinite(M)){let F=Math.floor((M-Date.now())/1000);if(F>0)W=F}}let Z=await B6(U,H).get("api/v1/auth/me").json(),q=Z.data&&typeof Z.data==="object"?Z.data:Z,V=q.user??G?.user??{},w=q.tenant??{};return{sealUrl:U,token:H,expiresIn:W,user:V,tenant:w}}function kT($){let Y=[],U=0,z="";try{let J=new URL($.trim()),K=J.hostname.toLowerCase(),G=J.pathname.replace(/\/+$/,"");if(K.endsWith(".ekuaibao.com")||K.endsWith(".hosecloud.com")||K==="ekuaibao.com"||K==="hosecloud.com")U+=40,z="host is Hose domain";if(G==="/web/thirdparty.html")U+=40,z+="; path is /web/thirdparty.html";if(J.searchParams.has("accessToken"))U+=10,z+="; has accessToken";if(J.searchParams.has("ekbCorpId"))U+=10,z+="; has ekbCorpId"}catch{U=0}if(U>0)Y.push({kind:"hose",score:U,reason:z});let I=0,Q="";try{let J=new URL($.trim()),K=J.hostname.toLowerCase(),G=J.pathname.replace(/\/+$/,"");if(K.endsWith(".sealai.cc"))I+=40,Q="host ends with .sealai.cc";if(G==="/delegate")I+=40,Q+="; path is /delegate";if(
Line truncated
`,{mode:384}),{config:U,path:I}}var Io=m(()=>{T5();sB()});function Qo($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function xT($){let Y=new Date($);if(Number.isNaN(Y.getTime()))return $;return Qo(Y.getTime())}function $5($){return typeof $==="string"&&$?$:void 0}function bg1($){return{headers:Ap.parse($.headers),cookies:Bp.parse($.cookies)}}async function ig1($,Y,U={}){let z=await Z8(B6($,Y,U));return{user:z.user??{},tenant:z.tenant??{}}}async function Ov0($){let Y=$.sealUrl.replace(/\/+$/,""),U=$.expiresIn??2592000,z=$.force===!0||$.verify===!1?!1:!0,I=bg1($),Q=z?await ig1(Y,$.token,A6(I)):void 0,J=Dv0($,{token:$.token,sealUrl:Y,expiresIn:U,expiresAt:$.expiresAt,verify:z,remote:Q,custom:I}),K=$.tenantId??$5(Q?.tenant.id),G=$.tenantSlug??$5(Q?.tenant.tenantSlug);return{...J,verified:z,tenantId:K,tenantSlug:G}}function Nv0($){let Y=$5($.session.tenant.tenantSlug),U=$5($.session.tenant.id),z=Y??U??"seal-delegate";return{...Dv0({id:z,corpId:z,name:$.name,provider:"seal",overwrite:$.overwrite},{token:$.session.token,sealUrl:$.session.sealUrl,expiresIn:$.session.expiresIn,verify:!0,remote:{user:$.session.user,tenant:$.session.tenant}}),tenantId:U,tenantSlug:Y}}function Dv0($,Y){let U=Y.remote?.user,z=Y.remote?.tenant,I=$.tenantSlug??$5(z?.tenantSlug),Q=$.tenantId??$5(z?.id),J=$.tenantName??$5(z?.name),K=$.id??I??Q;if(!K)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let G=Y.expiresAt?xT(Y.expiresAt):Qo(Date.now()+Y.expiresIn*1000),H=$.staffId??$5(U?.providerUserId)??$5(U?.id)??"seal",W=$.provider??$5(U?.provider)??$5(z?.providerConfig?.provider),X=$.corpId??I??Q??K,Z={id:K,name:$.name??J??K,environment:"production",seal:{url:Y.sealUrl,tenantSlug:I,headers:Y.custom?.headers,cookies:Y.custom?.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:Y.token,sealUrl:Y.sealUrl,expiresIn:Y.expiresIn,expiresAt:G,staffId:H,corpId:X,tenantId:Q,tenantSlug:I,tenantName:J,providerUserId:$5(U?.providerUserId),provider:W},auth:{refreshTtl:300}};return _q(Z,{overwrite:$.overwrite===!0})}var Jo=m(()=>{Io();sB();m6();X6()});async function bK($){let[Y,U]=await Promise.all([J10($),B1($)]),z=await Z8(U);return{...Y,tenantId:z.tenant.id,tenantSlug:z.tenant.tenantSlug??Y.tenantSlug,tenantName:z.tenant.name,raw:{...typeof Y.raw==="object"&&Y.raw!==null?Y.raw:{},user:{id:z.user.id,name:z.user.name,isAdmin:z.user.isAdmin,providerUserId:z.user.providerUserId,hosecloudStaff:z.user.hosecloudStaff},tenant:z.tenant}}}var fT=m(()=>{m6();Gg();X6()});async function Av0($){let Y=await rI($.appKey,$.appSecurity,$.domain),U=await FM(Y.domain,Y.openapiToken).catch(()=>[]);return{...Y,roleCount:U.reduce((z,I)=>z+I.roleDefs.length,0),roleGroups:U.map((z)=>({id:z.id,name:z.name,roleDefs:z.roleDefs.map((I)=>({id:I.id,name:I.name,sourceType:I.sourceType}))}))}}async function Bv0($){let Y=await rI($.appKey,$.appSecurity,$.domain),U=$.role??$.roleDefId??"admin",z=await FM(Y.domain,Y.openapiToken),I,Q;for(let G of z){for(let H of G.roleDefs)if(H.id===U||H.id===`${Y.corpId}:${U}`){I=H.id,Q=H.name;break}if(I)break}if(!I&&(U==="admin"||U==="主管理员"))for(let G of z){for(let H of G.roleDefs)if(H.id.endsWith(":admin")||H.name==="主管理员"){I=H.id,Q=H.name;break}if(I)break}if(!I)for(let G of z){for(let H of G.roleDefs)if(H.name.toLowerCase().includes(U.toLowerCase())){I=H.id,Q=H.name;break}if(I)break}if(!I)throw Error(`Rolenotfoundmatchingquery:'${U}'.Run'seal-use corps probe-hose'toviewallavailableroles.`);let J=await Ig(Y.domain,Y.openapiToken,I),K=await Qg(Y.domain,Y.openapiToken,J.staffs);return{domain:Y.domain,corpId:Y.corpId,corpName:Y.corpName??Y.corpId,roleId:I,roleName:Q,staffs:K}}async function vq($){let Y=$.domain,U=$.staffId??$.proxyStaffBizId,z=$.force===!0,I=z||$.verify===!1?!1:!0,Q=Y,J=$.corpId??$.corporationId,K=$.name,G;if(!Q||!J||!U){let V=await rI($.appKey,$.appSecurity,Y);Q=V.domain,J=J??V.corpId,K=K??V.corpName,G=V.openapiToken}let H=U;if(!H&&G&&Q){let V=$.role??"admin",w=await FM(Q,G).catch(()=>[]),M;for(let F of w){for(let N of F.roleDefs)if(N.id.endsWith(`:${V}`)||N.name===V||N.id===V){M=N.id;break}if(M)break}if(!M)M=w.find((F)=>F.roleDefs.some((N)=>N.id.endsWith(":admin")))?.roleDefs.find((F)=>F.id.endsWith(":admin"))?.id;if(M){let F=await Ig(Q,G,M).catch(()=>({staffs:[]})),N=await Qg(Q,G,F.staffs).catch(()=>[]);if($.staffName||$.staffPhone){let O=N.filter((D)=>{if($.staffName&&D.name!==$.staffName&&!D.name.includes($.staffName))return!1;if($.staffPhone&&(!D.cellphone||!D.cellphone.includes($.staffPhone)))return!1;return!0});if(O.length===1&&O[0])H=O[0].id;else if(O.length>1)throw Error(`Multiplestaffmembersmatched'${$.staffName??$.staffPhone}':${O.map((D)=>`${D.name}(${D.id})`).join(", ")}.PleasespecifyexactstaffId.`);else throw Error(`Nostaffmemberfoundmatching'${$.staffName??$.staffPhone}'underrole${M}.Run'seal-use corps hose-staffs'toviewcandidates.`)}else if(!z){let O=N.map(
Line truncated
`+"\uD83D\uDCA1 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。",z);if(U.keyId||U.appKey){let I=$.find((Q)=>U.keyId&&Q.id===U.keyId||U.appKey&&Q.appKey===U.appKey);if(!I)throw new bz(`指定的合思密钥不存在,请从上述候选列表中选择正确的appKey或keyId。
`;if(Y.outputFile){Uk1(Y.outputFile,U),console.log(JSON.stringify({outputFile:Y.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function Kk1($,Y={}){if(Y.allowFull||Y.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>Jk1)throw new Qq(`Outputislarge(${U}bytes).Use--summary,--fields,--count,or--output-file;pass--fullonlywhenyoureallyneedthefullresponse.`)}function rv0($,Y){if(Y)return;let U=$&&typeof $==="object"?$:{},I=typeof U.count==="number"?U.count:void 0,Q=Array.isArray(U.rules)?U.rules.length:void 0,J=Buffer.byteLength(JSON.stringify($),"utf-8"),K=I??Q??0;if(K>Ik1||J>Qk1)throw new Qq(`Rulelistislarge(${K}rules,${J}bytes).Use"seal-use rules list --summary","seal-use rules count",or--output-file;pass--fullonlywhenyoureallyneedfulldescriptions.`,"seal-use rules list --summary")}function T0($){return{allowFull:z0($.full)===!0,outputFile:R($.outputFile)??R($["output-file"])}}function sv0($=[]){console.log(lv0($))}var Ik1=100,Qk1=120000,ov0,Jk1=200000;var $4=o(()=>{L4();p8();No();ov0=["code","status","strictness","scope","updatedAt"]});var Ao={};L8(Ao,{selectCorp:()=>M1,runToolResult:()=>C$,runTool:()=>v0,globalConfigSummary:()=>KY});function M1($){let Y=K$(),U=T4(),I=r2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$},m3());return LB0(I.id),I}function KY($=T4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:DI()}}async function v0($,Y,U,I,Q={}){C0(await C$($,Y,U,I),Q)}async function C$($,Y,U,I){let Q=Zo.find((z)=>z.name===$);if(!Q)throw Error(`UnknownSealtool:${$}`);let J=Object.fromEntries(Object.entries(I).filter(([,z])=>z!==void 0)),K=Q.handler;return K(Y,J,{corp:U})}var D4=o(()=>{t$();LP();qo();$4()});import{existsSync as av0}from"node:fs";async function tv0($,Y){if(!av0($))throw Error(`Filenotfound:${$}`);let U=lI($);C0(await mI(U.fileBuffer,U.fileName,Y))}async function oT($,Y,U,I,Q){if($==="ready"||$==="status"){let J=Y??R(Q.options.file)??R(Q.options.input),K=await cT(U,I,{filePath:J,webhook:R(Q.options.webhook)??R(Q.options.selector)});if(console.error(`[webhook-ready]企业环境:${K.corp.name}(${K.corp.id})[${K.stateMode}]`),K.corp.tenant?.name)console.error(`[webhook-ready]租户信息:${K.corp.tenant.name}(${K.corp.tenant.id})`);console.error(`[webhook-ready]凭证状态:${K.authStatus==="ok"?"OK":`异常 (${K.authError})`}`),console.error(`[webhook-ready]Webhook通道:${K.activeWebhooks.length}个可用`);for(let z of K.activeWebhooks){let G=z.isDefault?" [默认通道]":"";console.error(`-${z.name}(${z.id})mode=${z.mode}${G}`)}if(K.materialPack)console.error(`[webhook-ready]材料包预检:${K.materialPack.valid?`通过 (${K.materialPack.documentCount} 单)`:`失败 (${K.materialPack.errors?.join("; ")})`}`);if(K.ready)console.error(`\uD83D\uDFE2${K.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${K.nextAction}`);else console.error(`\uD83D\uDD34准备阶段未通过:${K.statusMessage}`),console.error(`\uD83D\uDC49Nextaction:${K.nextAction}`);C0(K,T0(Q.options));return}if($==="replay"){let J=Y??R(Q.options.recordId)??R(Q.options["record-id"])??R(Q.options.id),K=R(Q.options.recordIds)??R(Q.options["record-ids"]),z=K?K.split(",").map((n)=>n.trim()).filter(Boolean):void 0,G=R(Q.options.sn)??R(Q.options.documentSn)??R(Q.options["document-sn"]),H=R(Q.options.sns)??R(Q.options["document-sns"]),W=H?H.split(",").map((n)=>n.trim()).filter(Boolean):void 0,X=l0(Q.options.limit),Z=R(Q.options.status),q=R(Q.options.startDate)??R(Q.options["start-date"]),V=R(Q.options.endDate)??R(Q.options["end-date"]);if(!J&&!z&&!G&&!W&&X===void 0)throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let w=R(Q.options.sourceCorp)??R(Q.options["source-corp"])??R(Q.options.prodCorp)??R(Q.options["prod-corp"]),M=R(Q.options.targetCorp)??R(Q.options["target-corp"])??R(Q.options.testCorp)??R(Q.options["test-corp"]),F=z0(Q.options.force)===!0,{sourceCorp:N,targetCorp:O}=_P({sourceCorpId:w,targetCorpId:M,activeCorp:I,force:F},M1),D=N.id===I.id?U:await P1(N),P=O.id===I.id?U:await P1(O),T=R(Q.options.webhook)??R(Q.options.selector),A=R(Q.options.snSuffix)??R(Q.options["sn-suffix"]),E=R(Q.options.snPrefix)??R(Q.options["sn-prefix"]),C=R(Q.options.docIdSuffix)??R(Q.options["doc-id-suffix"]),i=R(Q.options.docIdPrefix)??R(Q.options["doc-id-prefix"]),x=z0(Q.options.dryRun)??z0(Q.options["dry-run"]),b=await Fz({query:{recordId:J,recordIds:z,sn:G,sns:W,limit:X,status:Z,startDate:q,endDate:V},sourceClient:D,targetClient:P,sourceCorp:N,targetCorp:O,webhookSelector:T,snPrefix:E,snSuffix:A,docIdPrefix:i,docIdSuffix:C,dryRun:x});if(x){console.error(`[webhook-replay]预Line truncated
or:seal-usecorpsbind-test<testCorpId>--corp<prodCorpId>[--confirm][--force]`);let J=M1(I),K=M1(Q);if(J.id===K.id)throw E4(`Cannotbindenterprise'${J.id}'toitself.`);if(J.prodCorpId&&J.prodCorpId!==K.id)throw E4(`Cannotuse'${J.id}'asaproductionenterprisebecauseitisalreadyregisteredasatestenterprisefor'${J.prodCorpId}'.Multi-tierchainingisnotpermitted.`);if(K.testCorpId&&K.testCorpId!==J.id)throw E4(`Cannotbind'${K.id}'asatestenterprisebecauseitalreadyhasaboundtestenterprise'${K.testCorpId}'.Multi-tierchainingisnotpermitted.`);let z=z0(U.options.force)===!0;if(J.testCorpId&&J.testCorpId!==K.id||K.prodCorpId&&K.prodCorpId!==J.id){if(!z)throw m6(`Enterprisebindingconflict:productionenterprise'${J.id}'isboundto'${J.testCorpId??"none"}',andtestenterprise'${K.id}'isboundto'${K.prodCorpId??"none"}'.Overwritinganexistingbindingrequires--forceand--confirm.`,`seal-usecorpsbind-test${J.id}${K.id}--confirm--force`)}if(!(z0(U.options.confirm)===!0||z0(U.options.yes)===!0)){let X=z?" --force":"";throw m6(`Refusingtobindtestenterprise'${K.name}'(${K.id})toproductionenterprise'${J.name}'(${J.id})without--confirm.Enterprisebindingestablishes1-to-1syncpairingandmarks'${K.id}'asatestenvironment.`,`seal-usecorpsbind-test${J.id}${K.id}--confirm${X}`)}if(J.testCorpId&&J.testCorpId!==K.id)try{g9(J.testCorpId,{prodCorpId:void 0})}catch{}if(K.prodCorpId&&K.prodCorpId!==J.id)try{g9(K.prodCorpId,{testCorpId:void 0})}catch{}let H=g9(J.id,{environment:"production",testCorpId:K.id}),W=g9(K.id,{environment:"test",prodCorpId:J.id});return C0({success:!0,productionEnterprise:{id:H.id,name:H.name,environment:H.environment,testCorpId:H.testCorpId},testEnterprise:{id:W.id,name:W.name,environment:W.environment,prodCorpId:W.prodCorpId}}),!0}if($==="unbind-test"){let I=Y??R(U.options.corp),Q=M1(I);if(!Q.testCorpId&&!Q.prodCorpId)return C0({unbound:!1,message:`Enterprise'${Q.name}'(${Q.id})doesnothaveanactivetestenterprisebinding.`}),!0;let J=Q.testCorpId?Q.id:Q.prodCorpId,K=Q.testCorpId?Q.testCorpId:Q.id;if(!(z0(U.options.confirm)===!0||z0(U.options.yes)===!0))throw m6(`Refusingtounbindproductionenterprise'${J}'andtestenterprise'${K}'without--confirm.`,`seal-usecorpsunbind-test${Q.id}--confirm`);g9(J,{testCorpId:void 0});try{g9(K,{prodCorpId:void 0})}catch{}return C0({success:!0,unboundProduction:J,unboundTest:K}),!0}return!1}var QS0=o(()=>{t$();D4();p8();L4();$4()});function rT($){let Y;try{Y=new URL($.trim())}catch{throw Error("Invalid Seal delegate link: expected a valid HTTPS URL")}if(Y.protocol!=="https:")throw Error("Invalid Seal delegate link: expected HTTPS");let U=Y.hostname.toLowerCase();if(!U.endsWith(JS0))throw Error(`InvalidSealdelegatelink:expectedhostendingin${JS0},got${U}`);let I=Y.pathname.replace(/\/+$/,"");if(I!==KS0)throw Error(`InvalidSealdelegatelink:expectedpath${KS0},got${I}`);let Q=Y.searchParams.get("token");if(!Q)throw Error("Invalid Seal delegate link: token query parameter is required");return{sealUrl:Y.origin,delegateToken:Q}}async function zS0($){let Y=typeof $==="string"?rT($):$;return(await C6(Y.sealUrl,void 0).post("api/v1/delegation/preview",{json:{token:Y.delegateToken}}).json()).data}async function GS0($){let Y=typeof $==="string"?rT($):$,U=Y.sealUrl,I=C6(U,void 0),Q=await I.post("api/v1/delegation/consume",{json:{token:Y.delegateToken}}),J=Q.headers.get("set-cookie")??"",K=typeof Q.headers.getSetCookie==="function"?Q.headers.getSetCookie():[J],z="";for(let M of K)if(M&&M.includes("session_token=")){z=(M.split(";")[0]??"").trim();break}let G;try{G=await I.get("api/auth/get-session",{headers:z?{cookie:z}:{}}).json()}catch{}let H=G?.session?.token;if(!H&&z){let M=z.match(/session_token=([^.;]+)/);if(M?.[1])H=decodeURIComponent(M[1])}if(!H)throw Error("Seal delegate exchange did not return a session token");let W=86400;if(G?.session?.expiresAt){let M=new Date(G.session.expiresAt).getTime();if(Number.isFinite(M)){let F=Math.floor((M-Date.now())/1000);if(F>0)W=F}}let Z=await C6(U,H).get("api/v1/auth/me").json(),q=Z.data&&typeof Z.data==="object"?Z.data:Z,V=q.user??G?.user??{},w=q.tenant??{};return{sealUrl:U,token:H,expiresIn:W,user:V,tenant:w}}function sT($){let Y=[],U=0,I="";try{let K=new URL($.trim()),z=K.hostname.toLowerCase(),G=K.pathname.replace(/\/+$/,"");if(z.endsWith(".ekuaibao.com")||z.endsWith(".hosecloud.com")||z==="ekuaibao.com"||z==="hosecloud.com")U+=40,I="host is Hose domain";if(G==="/web/thirdparty.html")U+=40,I+="; path is /web/thirdparty.html";if(K.searchParams.has("accessToken"))U+=10,I+="; has accessToken";if(K.searchParams.has("ekbCorpId"))U+=10,I+="; has ekbCorpId"}catch{U=0}if(U>0)Y.push({kind:"hose",score:U,reason:I});let Q=0,J="";try{let K=new URL($.trim()),z=K.hostname.toLowerCase(),G=K.pathname.replace(/\/+$/,"");if(z.endsWith(".sealai.cc"))Q+=40,J="host ends with .sealai.cc";if(G==="/delegate")Q+=40,J+="; path is /delegate";if(
Line truncated
`,{mode:384}),{config:U,path:Q}}var To=o(()=>{t$();HP()});function W5($){return typeof $==="string"&&$?$:void 0}function Zk1($){return{headers:Sd.parse($.headers),cookies:hd.parse($.cookies)}}async function qk1($,Y,U={}){let I=await a6(C6($,Y,U));return{user:I.user??{},tenant:I.tenant??{}}}async function HS0($){let Y=$.sealUrl.replace(/\/+$/,""),U=$.expiresIn??2592000,I=$.force===!0||$.verify===!1?!1:!0,Q=Zk1($),J=I?await qk1(Y,$.token,j6(Q)):void 0,K=XS0($,{token:$.token,sealUrl:Y,expiresIn:U,expiresAt:$.expiresAt,verify:I,remote:J,custom:Q}),z=$.tenantId??W5(J?.tenant.id),G=$.tenantSlug??W5(J?.tenant.tenantSlug);return{...K,verified:I,tenantId:z,tenantSlug:G}}function WS0($){let Y=W5($.session.tenant.tenantSlug),U=W5($.session.tenant.id),I=Y??U??"seal-delegate";return{...XS0({id:I,corpId:I,name:$.name,provider:"seal",overwrite:$.overwrite},{token:$.session.token,sealUrl:$.session.sealUrl,expiresIn:$.session.expiresIn,verify:!0,remote:{user:$.session.user,tenant:$.session.tenant}}),tenantId:U,tenantSlug:Y}}function XS0($,Y){let U=Y.remote?.user,I=Y.remote?.tenant,Q=$.tenantSlug??W5(I?.tenantSlug),J=$.tenantId??W5(I?.id),K=$.tenantName??W5(I?.name),z=$.id??Q??J;if(!z)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let G=Y.expiresAt?T8(Y.expiresAt):A1(Date.now()+Y.expiresIn*1000),H=$.staffId??W5(U?.providerUserId)??W5(U?.id)??"seal",W=$.provider??W5(U?.provider)??W5(I?.providerConfig?.provider),X=$.corpId??Q??J??z,Z={id:z,name:$.name??K??z,environment:"production",seal:{url:Y.sealUrl,tenantSlug:Q,headers:Y.custom?.headers,cookies:Y.custom?.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:Y.token,sealUrl:Y.sealUrl,expiresIn:Y.expiresIn,expiresAt:G,staffId:H,corpId:X,tenantId:J,tenantSlug:Q,tenantName:K,providerUserId:W5(U?.providerUserId),provider:W},auth:{refreshTtl:300}};return cq(Z,{overwrite:$.overwrite===!0})}var Eo=o(()=>{To();HP();i6();X4()});async function az($){let[Y,U]=await Promise.all([E10($),P1($)]),I=await a6(U);return{...Y,tenantId:I.tenant.id,tenantSlug:I.tenant.tenantSlug??Y.tenantSlug,tenantName:I.tenant.name,raw:{...typeof Y.raw==="object"&&Y.raw!==null?Y.raw:{},user:{id:I.user.id,name:I.user.name,isAdmin:I.user.isAdmin,providerUserId:I.user.providerUserId,hosecloudStaff:I.user.hosecloudStaff},tenant:I.tenant}}}var aT=o(()=>{i6();Dy();X4()});async function ZS0($){let Y=await IJ($.appKey,$.appSecurity,$.domain),U=await CM(Y.domain,Y.openapiToken).catch(()=>[]);return{...Y,roleCount:U.reduce((I,Q)=>I+Q.roleDefs.length,0),roleGroups:U.map((I)=>({id:I.id,name:I.name,roleDefs:I.roleDefs.map((Q)=>({id:Q.id,name:Q.name,sourceType:Q.sourceType}))}))}}async function qS0($){let Y=await IJ($.appKey,$.appSecurity,$.domain),U=$.role??$.roleDefId??"admin",I=await CM(Y.domain,Y.openapiToken),Q,J;for(let G of I){for(let H of G.roleDefs)if(H.id===U||H.id===`${Y.corpId}:${U}`){Q=H.id,J=H.name;break}if(Q)break}if(!Q&&(U==="admin"||U==="主管理员"))for(let G of I){for(let H of G.roleDefs)if(H.id.endsWith(":admin")||H.name==="主管理员"){Q=H.id,J=H.name;break}if(Q)break}if(!Q)for(let G of I){for(let H of G.roleDefs)if(H.name.toLowerCase().includes(U.toLowerCase())){Q=H.id,J=H.name;break}if(Q)break}if(!Q)throw Error(`Rolenotfoundmatchingquery:'${U}'.Run'seal-use corps probe-hose'toviewallavailableroles.`);let K=await wy(Y.domain,Y.openapiToken,Q),z=await My(Y.domain,Y.openapiToken,K.staffs);return{domain:Y.domain,corpId:Y.corpId,corpName:Y.corpName??Y.corpId,roleId:Q,roleName:J,staffs:z}}async function nq($){let Y=$.domain,U=$.staffId??$.proxyStaffBizId,I=$.force===!0,Q=I||$.verify===!1?!1:!0,J=Y,K=$.corpId??$.corporationId,z=$.name,G;if(!J||!K||!U){let V=await IJ($.appKey,$.appSecurity,Y);J=V.domain,K=K??V.corpId,z=z??V.corpName,G=V.openapiToken}let H=U;if(!H&&G&&J){let V=$.role??"admin",w=await CM(J,G).catch(()=>[]),M;for(let F of w){for(let N of F.roleDefs)if(N.id.endsWith(`:${V}`)||N.name===V||N.id===V){M=N.id;break}if(M)break}if(!M)M=w.find((F)=>F.roleDefs.some((N)=>N.id.endsWith(":admin")))?.roleDefs.find((F)=>F.id.endsWith(":admin"))?.id;if(M){let F=await wy(J,G,M).catch(()=>({staffs:[]})),N=await My(J,G,F.staffs).catch(()=>[]);if($.staffName||$.staffPhone){let O=N.filter((D)=>{if($.staffName&&D.name!==$.staffName&&!D.name.includes($.staffName))return!1;if($.staffPhone&&(!D.cellphone||!D.cellphone.includes($.staffPhone)))return!1;return!0});if(O.length===1&&O[0])H=O[0].id;else if(O.length>1)throw Error(`Multiplestaffmembersmatched'${$.staffName??$.staffPhone}':${O.map((D)=>`${D.name}(${D.id})`).join(", ")}.PleasespecifyexactstaffId.`);else throw Error(`Nostaffmemberfoundmatching'${$.staffName??$.staffPhone}'underrole${M}.Run'seal-use corps hose-staffs'toviewcandidates.`)}else if(!I){let O=N.map((D)=>({id:D.id,name:D.name,cellphone:D.cellphone,active:D.active}));throw Error(`Missingrequiredparameter:staffId.Candidates:${JSON.stringify(O)}`)}else H=N.find(
Line truncated
`+"\uD83D\uDCA1 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。",I);if(U.keyId||U.appKey){let Q=$.find((J)=>U.keyId&&J.id===U.keyId||U.appKey&&J.appKey===U.appKey);if(!Q)throw new oI(`指定的合思密钥不存在,请从上述候选列表中选择正确的appKey或keyId。
`);R0({provider:"hose",capability:"privilege-elevation",corpId:z.corpId,corpName:z.corpName??z.corpId,baseUrl:z.baseUrl,staffId:z.staffId,keyCount:z.keys.length,keys:z.keys.map((Q)=>Rv0(Q,I))})}async function cT($,Y){let U=M1($),z=Y.reveal===!0;if(U.source.type!=="hose")throw new W4(`【合思子域专享能力】当前企业「${U.name}」(id:${U.id})为原生Seal(${U.source.type})租户,非合思(Hose/合思云/易快报)渠道企业。
`);C0({provider:"hose",capability:"privilege-elevation",corpId:I.corpId,corpName:I.corpName??I.corpId,baseUrl:I.baseUrl,staffId:I.staffId,keyCount:I.keys.length,keys:I.keys.map((J)=>OS0(J,Q))})}async function YE($,Y){let U=M1($),I=Y.reveal===!0;if(U.source.type!=="hose")throw new G4(`【合思子域专享能力】当前企业「${U.name}」(id:${U.id})为原生Seal(${U.source.type})租户,非合思(Hose/合思云/易快报)渠道企业。
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,w=Z.apiOrigin??"production";console.error(`•"${q}"(signKey:${V},环境:${w})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${V}--corp${I.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let w=V.outboundName??"SealAI 审批",M=V.signKey,F=V.apiOrigin??"production";console.error(`•"${w}"(signKey:${M},环境:${F})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${M}--corp${I.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,w=Z.apiOrigin??"production";console.error(`•"${q}"(signKey:${V},环境:${w})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${V}--corp${Q.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let w=V.outboundName??"SealAI 审批",M=V.signKey,F=V.apiOrigin??"production";console.error(`•"${w}"(signKey:${M},环境:${F})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${M}--corp${Q.id}
`);throw new G4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,Z.length===1?`seal-usedeployhosecloudsync${Z[0].signKey}--corp${Q.id}`:void 0)}await v0("seal_deploy_hosecloud_sync",I,Q,{signKey:H},T0(J.options));return}throw Error(`Unknowndeployhosecloudaction:${z??""}.Available:requirements,list,get,status,configure,sync.`)}var Ly0=o(()=>{D4();L4();$4();X4();p8()});var wy0='---\nname: seal-use\ndescription: "v0.10.40: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."\nmetadata:\n version: 0.10.40\n short-description: Seal tenant and Hose approval automation (v0.10.40)\n---\n\n# Seal Use\n\nCLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。MCP 默认关闭。\n\n## 时间与输出\n\n- 机器字段统一使用带 `+08:00` 北京时间偏移的 ISO 8601 秒级格式,不带毫秒,例如 `2026-09-28T11:51:09+08:00`。\n- 面向用户解释时间时,直接基于 `Asia/Shanghai`(北京时间)表述,无需再做 `+8` 小时换算。\n- 不向用户暴露 Bearer、`accessToken`、`closeToken`、`appSecurity`、原始 cURL 或未脱敏手机号。\n- 不向用户直接暴露底层 UUID、`tenantSlug`、`boundCorpRole` 等内部字段;优先使用企业名称、规则编号(例如 `0038`)和脱敏后的业务信息。\n\n## 企业接入:先识别材料,再选择入口\n\n最终企业来源只有两种:`source.type:"seal"` 和 `source.type:"hose"`。不要把材料格式、认证凭据和最终来源混为一谈。\n\n| 用户材料 | 标准入口 | 最终配置形态 |\n| --- | --- | --- |\n| Hose 开放平台 `appKey+appSecurity` | `corpsadd-hose-persistent` | Hose 持久化凭据 |\n| Seal URL + Bearer,或 Seal 页面 cURL | `corpsadd-seal-bearer` | Seal Bearer 会话 |\n| Seal 原生委托链接 | `corpsadd-link<url>` | Seal 委托会话 |\n| Hose 协助链接 | `corpsadd-link<url>` | Hose Web Session;加 `--elevate-hose` 才提取长期密钥 |\n| Hose 页面 cURL | 先提取密钥;失败时 `corpsadd-hose-web-session` | Hose 持久化或 Hose Web Session |\n| 已规范化的 Hose `corpId+accessToken+baseUrl` | `corpsadd-hose-web-session` | Hose Web Session |\n\n### 凭据边界\n\n- Seal Bearer 只能给 `add-seal-bearer`;Hose `accessToken/accesstoken/closeToken` 不能直接当作 Seal Bearer。\n- Hose Web Session 保存 `closeToken+staffId`,需要调用 Seal 时才通过 SSO 换取运行时 Seal Bearer。\n- Hose 持久化配置保存 `appKey+appSecurity`,适合无人值守、部署和长期同步。\n- 会话有有效期时,Hose source 保存 `expiresIn` 和北京时间 ISO 秒级 `expiresAt`(`+08:00`)。\n- `add-link` 是 URL 混合入口,不接收 cURL:自动识别 Seal 委托链接和 Hose 协助链接。\n- `--elevate-hose` 是唯一明确的 Hose 提权动作。\n\n收到 Hose 管理员 cURL 时,按 Hose 协助链接处理:解析主机、`accesstoken`、企业标识和必要会话信息,优先调用密钥提取路径;无法提取长期密钥时才保存 Web Session。收到 Seal cURL 时,提取 Seal 主机和 `Authorization:Bearer`,走 `add-seal-bearer`。不要盲目执行 cURL,也不要把原文写入文件或日志。\n\n详细来源决策、提权边界和 cURL 处理见 `references/enterprise-onboarding.md`;首次找材料时必须使用 `references/first-time-user.md`。\n\n## 首次接入图文规则\n\n当用户首次接入、询问如何取得材料,或需要用户打开后台找凭据时:\n\n1. 先确认用户手上是 Hose 开放平台凭据、协助链接、Seal 委托链接,还是已登录网页 cURL。\n2. 读取 `references/first-time-user.md`,只渲染与当前路径对应的截图;不能只给纯文字步骤。\n3. 接收材料后由 Agent 自动发现企业、域名和管理员。除非自动发现失败,不要要求用户先填写 `corpId`、`staffId` 或域名。\n\n## `corps` 主线\n\n- 接入:`add-link`、`add-seal-bearer`、`add-hose-persistent`、`add-hose-web-session`\n- 发现:`list`、`search`/`find`、`get`/`show`、`current`、`switch`\n- 维护:`mark`、`rename`\n- 测试闭环:`bind-test`、`unbind-test`、`sync-test`、`replay-test`\n- Hose 专属:`probe-hose`、`hose-staffs`、`hose-extract-keys`、`hose-keys`\n\nHose 专属命令应从命令名或选项中明确可见:`authhose-*`、`approval-runshose-flow`、`deployhosecloud`、`simulation--modehosecloud`。跨来源入口只有在明确使用 `--elevate-hose`、`--with-flow` 或 `--typehose-document` 时才启用对应 Hose 能力。\n\n生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`Line truncated
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 hS0=()=>{};var yS0="# 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-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--batch<batchId>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest--fieldsrecordId,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-useapproval-runsget<recordId>--corp<corpId>--summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsmetadata\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.fields,result.summary\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsresult.summary,result.decision,result.riskPoints\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runsget<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-useapproval-runsdocument-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-useapproval-runscited-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 `rulesget--record-id<recordId>--runtime-idrule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\n#查看附件列表摘要(包含文件名、类型、大小及直链可用性)\nseal-useapproval-runsattachments<recordId>--corp<corpId>--summary\n\n#下载全部附件到本地目录(优先使用ossSignedUrl签名直链)\nseal-useapproval-runsattachmentsdownload<recordId>--all--out-dir./downloads--corp<corpId>\n\n#按名称或fileId过滤下载单个附件\nseal-useapproval-runsattachmentsdownload<recordId>--name发票--corp<corpId>\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-useapproval-runsresult<recordId>--corp<corpId>--summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Approval Run Web Links & Auto-Login Links\n\nUse this when the user asks for a link to an approval run or wants to open the run directly in their browser:\n\n```bash\n#默认推荐:生成SealAI审核详情直达链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)\nseal-useapproval-runslink<recordId>--corp<corpId>\nseal-useapproval-runslink--sn<sourceDocumentSN>--corp<corpId>\n\n#生成合思主系统原始单据页面链接\nseal-useapproval-runslink<recordId>--typehose-document--corp<corpId>\n\n#仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带合思单次临时票据的免登直达链接\nseal-useapproval-runslink<recordId>--auto-login[--expire7200]--corp<corpId>\n```\n\n### 返回字段说明与语义规范\n- `sealResultUrl`: Seal AI 单据智能审核结果页\n- `hoseDocumentUrl`: 合思费控主系统原始报销/借款单详情页\n- `type`: 链接类型,默认为 `seal_result`,指定时可为 `hose_document`\n- `mode`: 鉴权模式,`direct`(原生直接打开)或 `auto_login`(免密换票)\n\n### 免登链接安全与声明规范\n当向用户返回 `--auto-login` 链接时
Line truncated
`;var Ay0=()=>{};var Ty0="# 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-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--batch<batchId>--latest\nseal-useapproval-runspick--corp<corpId>--sn<sourceDocumentSN>--latest--fieldsrecordId,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-useapproval-runsget<recordId>--corp<corpId>--summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsmetadata\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.fields,result.summary\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsresult.summary,result.decision,result.riskPoints\nseal-useapproval-runsget<recordId>--corp<corpId>--fieldsdocument.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runsget<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-useapproval-runsdocument-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-useapproval-runscited-rules<recordId>--corp<corpId>\n```\n\nReturn and discuss `code`, `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule from that run's snapshot, use `seal-userulesget<code>--record-id<recordId>--corp<corpId>` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\n#查看附件列表摘要(包含文件名、类型、大小及直链可用性)\nseal-useapproval-runsattachments<recordId>--corp<corpId>--summary\n\n#下载全部附件到本地目录(优先使用ossSignedUrl签名直链)\nseal-useapproval-runsattachmentsdownload<recordId>--all--out-dir./downloads--corp<corpId>\n\n#按名称或fileId过滤下载单个附件\nseal-useapproval-runsattachmentsdownload<recordId>--name发票--corp<corpId>\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-useapproval-runsresult<recordId>--corp<corpId>--summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Approval Run Web Links & Auto-Login Links\n\nUse this when the user asks for a link to an approval run or wants to open the run directly in their browser:\n\n```bash\n#默认推荐:生成SealAI审核详情直达链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)\nseal-useapproval-runslink<recordId>--corp<corpId>\nseal-useapproval-runslink--sn<sourceDocumentSN>--corp<corpId>\n\n#生成合思主系统原始单据页面链接\nseal-useapproval-runslink<recordId>--typehose-document--corp<corpId>\n\n#仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带合思单次临时票据的免登直达链接\nseal-useapproval-runslink<recordId>--auto-login[--expire7200]--corp<corpId>\n```\n\n### 返回字段说明与语义规范\n- `sealResultUrl`: Seal AI 单据智能审核结果页\n- `hoseDocumentUrl`: 合思费控主系统原始报销/借款单详情页\n- `type`: 链接类型,默认为 `seal_result`,指定时可为 `hose_document`\n- `mode`: 鉴权模式,`direct`(原生直接打开)或 `auto_login`(免密换票)\n\n### 免登链接安全与声明规范\nLine truncated
Donotsend\`scope\` or \`strictness\` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing.
Donotpass\`--scope\` or \`--strictness\` when they are unchanged. Fetch the draft again (\`seal-use rules get <code> --corp <corpId>\`) and verify the exact description, scope, strictness, and draft status before publishing.
Foracompletelocalrule-setsync,\`rules push\` is incremental: it matches pulled rules by stable \`id\`, updates only changed fields, creates new entries, and removes entries omitted from the local file. It preserves matched rule IDs and does not recode the whole draft. Preview it with \`rules push --dry-run\` before applying.
@@ -1419,8 +1419,7 @@ For a complete local rule-set sync, \`rules push\` is incremental: it matches pu
3.BOTHacodeblock(\`\`\`\`text ... \`\`\`\`) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
-**DedicatedCLICommand**:Use\`seal-use auth hose-link --corp <corpId> [--expire <seconds>] [--force]\`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports \`--expire\` (default 7200, e.g. 86400 for 1 day).
-**SealAIPlatformDirectLink**:Use\`seal-use auth link --corp <corpId> [--note <note>]\`. This generates a 24-hour provisional delegation link for the Seal AI audit platform (\`https://*.sealai.cc\`).
\`rules list\` and \`rules pull\` operate on the current draft and therefore return draft \`code\` values. A published version stores a separate snapshot and may recode the same rules; publishing, deleting, or reordering rules can make those published codes differ or drift again. A code such as \`#0038\` is only meaningful together with its version context.
Usethedraft\`id\` for current edits and use the approval run's recorded version plus rule text or runtime rule ID for historical investigations. Do not copy a draft code into a report or command that will be interpreted against a published version.
Defaultsummaryshouldincludeonlyfieldssuchas\`id\`, \`code\`, \`scope\`, \`strictness\`, \`status\`, and \`updatedAt\`. Do not pull \`description\` unless the user needs rule text.
Returnthesingleruletextplus\`scope\`, \`strictness\`, \`status\`, \`versionNumber\`, and version metadata. Avoid commands that dump a whole rule version unless the user asks for the full version.
Ifarulecommandwouldreturnmanydescriptionsormorethanabout20rules,use\`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports.
`;var sS0=()=>{};var eS0="# Seal Approval Rule Linter & Quality Validation\n\nUse this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.\n\n## Key Principles\n\n- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled:false`) to avoid unsolicited noise during standard operations.\n- **Doctor Visibility**: `seal-usedoctor` audits the rule linter configuration state and active linter name in its health checks, and surfaces a one-click hint (`seal-useconfiglintenable`) when disabled.\n- **Explicit Triggering**: `seal-useruleslint` always runs regardless of global configuration.\n- **Draft Hook**: When `seal-useconfiglintenable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.\n- **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**.\n\n## CLI Commands\n\n### 1. Lint Current Draft Rules (Whole-RuleSet Scan)\n\n```bash\nseal-useruleslint--corp<corpId>\n```\n\n### 2. Lint Specific Historical Version or Single Rule\n\n```bash\n#Lintrulesinpublishedversion16\nseal-useruleslint--version16--corp<corpId>\n\n#Lintaspecificrulebycode(#0038)\nseal-useruleslint--code'#0038'--corp<corpId>\n\n#Summarymode(onlyshowruleswithissues)\nseal-useruleslint--summary--corp<corpId>\n```\n\n### 3. Quality Gate for CI / Release\n\n```bash\n#Ifoverallscoreisbelow85,terminateswithexitcode1\nseal-useruleslint--min-score85--levelerror--corp<corpId>\n```\n\n### 4. Configure Global Linter Settings\n\n```bash\n#Checkstatus\nseal-useconfiglintstatus\n\n#Enableautolintonruleupdates\nseal-useconfiglintenable--linterbuiltin--min-score80\n\n#Disableautolint\nseal-useconfiglintdisable\n```\n\n## Official Linters\n\n| Linter Name | Scope & Purpose | Aliases |\n| :--- | :--- | :--- |\n| `builtin` | Seal 官方标准校验器:拦截过短描述、主观模糊词与悬空例外条款。 | `default`, `official/builtin` |\n| `strict` | Seal 官方严格风控校验器:强校验字数、刚性定量约束、凭证依据与具体审批人角色。 | `official/strict` |\n| `hlab` | 合思实验室 (HLab) 结构化规则校验器:SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判。 | `hlab-sop`, `hlab-rules`, `hlab-standard`, `official/hlab` |\n\n```bash\n#Inspectavailablelinters\nseal-useruleslinters\n\n#LintrulesusingHLabSOPstandard\nseal-useruleslint--linterhlab--corp<corpId>\n\n#LintlocalruleworkspaceofflinewithHLabstandard\nseal-useruleslint--linterhlab--file./rules.local.json\n```\n\n## Built-In Detection Rules (`builtin`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |\n| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |\n| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |\n\n## HLab SOP Detection Rules (`hlab`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `MISSING_CHECK_METHOD` | `error` | Missing `**检查方法**` section in rule description. | Add `**检查方法**:` specifying fields, vouchers, and normalization logic. |\n| `MISSING_EVAL_STANDARD` | `error` | Missing `**判定标准**` section in rule description. | Add `**判定标准**:` with standard branches. |\n| `INCOMPLETE_TERNARY_BRANCH` | `error` | Incomplete ternary branch under evaluation criteria (missing `PASS`, `FAIL`, or `证据不足`). | Provide complete ternary closure: `-PASS:`, `-FAIL:`, `-证据不足:`. |\n| `INSUFFICIENT_WITHOUT_MANUAL_REVIEW` | `warning` | `证据不足` branch does not specify escalating to `人工复核`. | Add `转人工复核` at the end of `证据不足` branch. |\n| `DISPOSAL_ACTION_LEAK` | `warning` | Contains whole-bill workflow disposal actions (`驳回单据`, `直接驳回`, `进行提醒`, `退回单据`). | Decouple disposal actions from rule text; rely on rule strictness or platform workflow. |\n| `SCOPE_FALSE_SKIP_PRONE` | `warning` | Scope contains material upload conditions (`若上传了`, `若提供了`, `附件需上传`). | Keep scope pure to business triggers; handle missing materials explicitly in FAIL branch to prevent silent SKIP. |\n| `RISK_SUPPRESSION` | `erroLine truncated
`;var fy0=()=>{};var iy0="# Rule Lightweight Queries\n\nUse this reference when the user wants rule counts, compact rule lists, one rule from draft or a historical version, or approval rule search without dumping hundreds of rule descriptions.\n\n## Draft Default vs. Published Version (`--versionlatest`)\n\nEvery rule has a 4-digit zero-padded `code` (`0000,0001,0025,0038,...`).\n\n- **Default = Current Draft (`草稿`)**: When `--version` is omitted, `rulescount`, `ruleslist`, `rulesget<code>`, `rulessearch`, `ruleslint`, and `rulespull` **all read the current draft**.\n- **Latest Published Version = `--versionlatest` (`最新发布`)**: To inspect the latest published version, **always pass `--versionlatest`** (or `--version<number>` for a specific historical version).\n- Publishing or deleting rules can shift `code` numbers across versions, so a `code` in a historical run must be resolved together with `--version<number>` or `--record-id<recordId>`.\n\n## Count Rules\n\nUse count when only scale or existence matters.\n\n```bash\n#Countcurrentdraftrules(default)\nseal-userulescount--corp<corpId>\n\n#Countrulesinlatestpublishedversion\nseal-userulescount--versionlatest--corp<corpId>\n```\n\nExpected shape:\n\n```json\n{\"count\": 191 }\n```\n\n## List Rule Summaries\n\nUse summaries for navigation and selection.\n\n```bash\n# List current draft rule summaries (default)\nseal-use rules list --summary --corp <corpId>\n\n# List latest published version rule summaries\nseal-use rules list --version latest --summary --corp <corpId>\n```\n\nDefault summary includes `code`, `status`, `strictness`, `scope`, and `updatedAt`. Do not pull full `description` fields across all rules unless the user needs rule text.\n\n## Get One Rule (Draft or Published Version)\n\nRead a single rule from the current draft (default):\n\n```bash\nseal-use rules get 0038 --corp <corpId>\n```\n\nRead a single rule from the latest published version, a specific published version, or the version used by an approval run:\n\n```bash\nseal-use rules get 0038 --version latest --corp <corpId>\nseal-use rules get 0038 --version 16 --corp <corpId>\nseal-use rules get 0205 --record-id <recordId> --corp <corpId>\n```\n\nReturns `id`, `code`, `ruleCode`, `runtimeRuleId`, `description`, `scope`, `strictness`, `status`, and version metadata when reading from a published version.\n\n## Search Rules Compactly\n\n```bash\n# Search current draft rules (default)\nseal-use rules search <keyword> --maxResults 20 --corp <corpId>\n\n# Search latest published version or a specific historical version\nseal-use rules search <keyword> --version latest --maxResults 20 --corp <corpId>\nseal-use rules search <keyword> --version 16 --maxResults 20 --corp <corpId>\n```\n\n## Clear Draft Rules Before Import\n\nUse this for test tenants when the next step is importing another tenant's rule set. Always preview first unless the user has already confirmed the exact tenant.\n\n```bash\nseal-use rules clear --dry-run --corp <corpId>\nseal-use rules clear --yes --corp <corpId>\n```\n\nExpected shape:\n\n```json\n{\n \"corpId\": \"xiezihao\",\n \"dryRun\": false,\n \"beforeCount\": 49,\n \"deleted\": 49,\n \"afterCount\": 0\n}\n```\n\n## Output Discipline\n\nIf a rule command would return many descriptions or more than about 20 rules, use `rules count`, `rules list --summary`, `rules search`, or `--output-file`. Use `--full` only for deliberate exports.\n";varby0=()=>{};varny0="#SealApprovalRuleLinter&QualityValidation\n\nUsethisreferencewhenanalyzing,validating,orlintingSealAIapprovalrulestodetectvaguephrasing,missingexceptionevidence,orformattingdefectsbeforepublishing.\n\n##KeyPrinciples\n\n-**DefaultState**:Linteris**disabledbydefault**inglobalconfiguration(`lint.enabled: false`)toavoidunsolicitednoiseduringstandardoperations.\n-**DoctorVisibility**:`seal-use doctor`auditstherulelinterconfigurationstateandactivelinternameinitshealthchecks,andsurfacesaone-clickhint(`seal-use config lint enable`)whendisabled.\n-**ExplicitTriggering**:`seal-use rules lint`alwaysrunsregardlessofglobalconfiguration.\n-**DraftHook**:When`seal-use config lint enable`isset,`seal-use rules update`outputsreal-timediagnosticwarningsto`stderr`withoutmutating`stdout`payloads.\n-**Fault-TolerantFallback**:Ifacustom`.ts`linterfilehassyntaxerrors,runtimeexceptions,orismissing,theenginelogsawarningto`stderr`and**silentlyfallsbacktothebuilt-inheuristiclinterwithoutfailing**.\n\n##CLICommands\n\n###1.LintCurrentDraftRules(Whole-RuleSetScan)\n\n```bash\nseal-use rules lint --corp <corpId>\n```\n\n###2.LintSpecificHistoricalVersionorSingleRule\n\n```bash\n# Lint rules in published version 16\nseal-use rules lint --version 16 --corp <corpId>\n\n# Lint a specific rule by code\nseal-use rules lint --code 0038 --corp <cor
Line truncated
`;var $g0=()=>{};var iy1="iVBORw0KGgoAAAANSUhEUgAADVgAAAdwCAYAAACUWcTmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWKADAAQAAAABAAAHcAAAAAD4n9OGAABAAElEQVR4AeydB4AdVfX/z246pNAD0hK6dOki0rsU+dMJJVIFRYoUFUFAQUCqgHSkxx8gTRCpFkB6CU06SQi9BEhC+u7/fu7b83J3dt7bt33f5nuStzNz5947M583c+fOvPO9p6Y+mMlEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4kUDsHHrMOWQREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQigd7jxo8TChEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYIwkogtUc+bXroEVABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABCBQUx9MKERABERABERABERABERABERABERABERABERABERABERABERABESgqwiMHz/eBgwY0FWb13ZFQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQATmcAKKYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwn0npMPXscuAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj2RwP8+n26vfjbd3vpyho2fPN0+mjLTJs+qs/qaOhvYp8YWGtDLFh/U25YZ3NdWnr+/rTDvgJ6IQcckAhURqKkPVlFOZRIBERABERABERABERABERABERABERABERABERABERABERABERCBDiAwfvx4GzBAP9p2AFpVKQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiMIcR+GhSnT347lT713tT7eOpM4OYqj5+LEzNEFdZ+MyKU5Zr4jLp9fat/r1ss28NtM0WG2KLzN1nDiOnw53TCUhgNaefATp+ERABERABERABERABERABERABERABERABERABERABERABEehiAhJYdfEXoM2LgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhUPYFJ08z+7+Updsc7U8OxFARURKqyIKAqCKnqbVYQUdU2CK7iOiuIr4oirLBcgxArfHZZcrDttcwCNnefXlXPRgcgApUQkMCqEkrKIwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0GEEJLDqMLSqWAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4g8MR7M+2Cp6fY5JmFSFQhRlUQStUVBVUsF0VUCKiSSFZEsKqLkawa5yH/oN5mP195qK0/dPAcQFGHOKcTkMBqTj8DdPwiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0MUEJLDq4i+gCzY/ZcqUuNUBAwZ0wda1SREQAREQAREQAREQAREQAREQAREQAREQAREQARHoHAKd8S501AszbNT/psXIUwWhVDi2IK6qj5GriGRVEE4RlSoVWlUayYry+w2fx0Yst1DnQNNWRKCLCAQ9oUwEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKCaCFz035n20JgZ1stqQowqs9qaWmJVBR1VbRBZkdLLakN0qiCzCtMGgVXMURfW1YQsTHsFEdasMC0UCSWjOIvcbte++6V9MX2mHb7ytzypS6e/+93v7H//+1/uPuy888727W9/O35yMyhRBEoQ4NyXiYAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiECPIXDbbbfZiBEjGh0PP7aSxif90dXzks68G3k8P2VTYznNm67TvAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BoGLHp1lD74zM6qh6kK4qprwqW+YMl9TR1pYHcRWtUFHhZaqLi6TFsJbhflCOYRVtbG818H6+KGOhnr+9v4ku/DlDzrj0Mpug/fz6Xv+bOa//vWvxkcmAi0loAhWLSWm/CIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAt2WAD+sdvQPp/xwy0cjYHbb00A7JgIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAI9msCo5+rt4XdDVKoaIlfVxChVHHCMPtXoyIO4KuSoy0ayqifOFeWJUxVqSCJZfW/hwfbox1/FuqiKHF4zIqt5+39qey+zYEztij/pbwC8p0/NhVc+TddpXgSaIyCBVXOEtF4EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKBqCLz66qudtq/8iPvrX/+607aX3VBniMluvPHG7Ga1LAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUIJAzT+vi2vqN9m3RA4li0DbCTw5xuyWl+qMIFQWIk8Rpqo+Cq1YDlKokL7m4v2D7IrFOgurwvqwoiaEsIpyKebNHv9wki+FdERaSKlq7fytlrEj73vLHvvoq7gNUkM4q1BPKBTque7tCbbUoH62/tDBrOkyQ1yVfUf/u9/9rmx0qy7b2VZu2H8H4FhXXHFF+3//7/+1siYVq4RATX2wSjIqjwiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BIHx48fbgAEDOqLqHlun/6ja0QfYUQKrKVOmxF3X997R36DqFwEREAEREAEREAEREAEREAEREAEREAER6EwCs074btxcr9Me78zNalvdmEB7vwudNM3ssFvNJs2oi0KqWUE0FQVUUUiF6KreLtx5QVtt0X5lqYz+cIodevfYkKcg1KpHfBXKHvadobbvdxay0R9NsgPveyOsD3KTWiQniLjCNHyYDgqhfq7bcCmbu0+vsttpy0rEUlgqLErfje+8885NBEepwMrXE83Ko16ldbVl3zqjbHqsvj0EZdmoXb5O07YTUASrtjNUDSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQqQQ6M1JXpx5YD96Yj3sZR3ntwcdZyaHNmDHDPv74Y1t00UULo95WUqiL8syaNct69eo4J5EuOqwu3Szff58+fZrsg66RJkiU0MkEGJ4YhzSZCHQmAdpEjHtNbW0Ydb4djHvX9OnTNYBBA0ucWfv169dufNvhK+oxVUydOtXq6upsrrnm6jHHpAMRAREQAREQgbYS8OhV1FN/1VFWc8B5ba2yWJ6+45gxY+ytt96y/v3729JLL22LLbZYbj+H9y4u6ilWUGJm7rnntgUXXDCu/frrr+2LL74okbNxMv3XJZZYonFia5fGjLaad0e3tnSx3JwSNezmZ2ts8vQQTSr8C9KoOA2Sp8ChJvyttQPXG9SsuMqh1VEslIviqTBdf5G5o7iK1NUWHmg/XW1Ru/iF960+aK8QVbE1j2SFwOumtz6zg749lOztbqlQygVSCIuYL2cIqDwPoirepfsy5ZgnLRv5qlydXbUu73cAjqka9h1mCMSw1kbdamv5uPEW/pHAqoXAlF0EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEuppA+oNwR0WZ6upj7Enbf+ONN+yUU06Jh3Tsscfa6quv3pMOLx7Lhx9+aMcff3yc33vvvW3LLbfMPcZbbrnF7rjjjrjuF7/4ha2yyiq5+dLEyZMn24QJE2zhhRe23r1720svvWTnn39+zPLLX/7SlllmmTR77jyORb/61a/iuv3339++973v5eZLE99++2076aSTbNlll7UtttiiojJp+WqZHz16dBQ84XziNnPmTPv00099sUVTHLMGDx6cW2bcuHHRAWSzzTazHXfc0eaZZ56Y7/HHH7eLLroozh933HG21FJL2Zlnnmm77LJLm6+Xb775xr766qvc/ckmzjvvvNFJLZveluWzzz7b3nrzTVty2DDjfG2JTZs2ze677z7bZpttGonSvvzyy4od5bLb4zqqJqHnxxNmWcHZK3skLV/u16fG5huUL2B5cPRUO
Line truncated
`,"utf8"),{detected:z,configured:!0,configPath:U,targetDir:Y,action:"prepended"}}function vo($){let Y=$?.targetSkillsDir??Qg0(),U=$?.configFile??Jg0(),z=Kg0(),I=!1;if(fq(U))try{let Q=JSON.parse(Ig0(U,"utf8"));if(Array.isArray(Q?.entries))I=Q.entries.some((J)=>J?.path===Y)}catch{}return{detected:z,configured:I,configPath:U,targetDir:Y}}var ho=()=>{};import{cpSync as ry1,existsSync as nK,lstatSync as Hg0,mkdirSync as sy1,realpathSync as $Y,rmSync as ay1,symlinkSync as ty1,unlinkSync as Gg0}from"node:fs";import{homedir as Wg0}from"node:os";import{dirname as Xg0,join as YY}from"node:path";function ey1($,Y){let U=Y?.baseHomeDir??Wg0(),z=YY(U,$.rootDirName),I=Y?.sourceSkillDir??YY(U,".agents","skills","seal-use"),Q=Xg0(I),J=YY(z,"skills"),K=YY(J,"seal-use");if(!nK(z))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"skipped_not_detected"};if(nK(J)&&nK(Q))try{if($Y(J)===$Y(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:J}}catch{}sy1(J,{recursive:!0});let G;try{G=Hg0(K)}catch{G=void 0}let H=!1;if(G)if(G.isSymbolicLink()){try{if($Y(K)===$Y(I))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"already_linked",targetPath:K}}catch{}try{Gg0(K)}catch{}}else if(G.isDirectory())ay1(K,{recursive:!0,force:!0}),H=!0;else Gg0(K);let W=process.platform==="win32"?"junction":"dir";try{return ty1(I,K,W),{id:$.id,name:$.name,detected:!0,configured:!0,mode:H?"replaced_real_dir":"linked",targetPath:K}}catch{try{return ry1(I,K,{recursive:!0}),{id:$.id,name:$.name,detected:!0,configured:!0,mode:"fallback_copied",targetPath:K}}catch(X){return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"error",targetPath:K,error:X?.message||String(X)}}}}function $k1($,Y){let U=Y?.baseHomeDir??Wg0(),z=YY(U,$.rootDirName),I=Y?.sourceSkillDir??YY(U,".agents","skills","seal-use"),Q=Xg0(I),J=YY(z,"skills"),K=YY(J,"seal-use");if(!nK(z))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"not_detected"};if(nK(J)&&nK(Q))try{if($Y(J)===$Y(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:J}}catch{}let G;try{G=Hg0(K)}catch{G=void 0}if(G){if(G.isSymbolicLink())try{if($Y(K)===$Y(I))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"single_symlinked",targetPath:K}}catch{}else if(G.isDirectory())return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"real_directory",targetPath:K}}return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"not_configured",targetPath:K}}function So($){return Zg0.map((Y)=>ey1(Y,$))}function go($){return Zg0.map((Y)=>$k1(Y,$))}var Zg0;var yo=m(()=>{Zg0=[{id:"workbuddy",name:"WorkBuddy",rootDirName:".workbuddy"},{id:"claude",name:"Claude",rootDirName:".claude"},{id:"qoder",name:"Qoder",rootDirName:".qoder"}]});var ko=m(()=>{ho();yo();ho();yo()});import{existsSync as Yk1,mkdirSync as xo,readFileSync as Uk1,rmSync as zk1,writeFileSync as qg0}from"node:fs";import{homedir as Lg0}from"node:os";import{dirname as Vg0,join as bq}from"node:path";function fo(){return Fg0["SKILL.md"]||""}function wg0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function Mg0($=bq(iz(),"SKILL.md")){try{return wg0(Uk1($,"utf8"))}catch{return}}function iz(){return bq(Lg0(),".agents","skills","seal-use")}function Qk1(){return bq(Lg0(),".agents","skills","seal-home")}function Jk1(){let $=Qk1();if(Yk1($))try{return zk1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Og0($=iz()){Jk1(),xo($,{recursive:!0});let Y=[];for(let[U,z]of Object.entries(Fg0)){let I=bq($,U);xo(Vg0(I),{recursive:!0}),qg0(I,z,"utf8"),Y.push(U)}for(let[U,z]of Object.entries(Ik1)){let I=bq($,U);xo(Vg0(I),{recursive:!0}),qg0(I,z),Y.push(U)}return{targetDir:$,files:Y}}var Fg0,Ik1,Oz4;var iq=m(()=>{Eo();Eo();ko();Fg0=Ug0,Ik1=Object.fromEntries(Object.entries(zg0).map(([$,Y])=>[$,Buffer.from(Y,"base64")]));Oz4=wg0(fo())});function Ng0(){return`#SealUse系统架构与运行规范白皮书
A**Webhookresourcepack**(webhook资源包/资源包,CLI:\`resource-pack\`, alias: \`pack\`, legacy alias: \`material-pack\`) is a ZIP file that bundles an Excel information sheet (\`信息表.xlsx\`) with attachments organised by document ID. It is designed for exporting online approval runs and transferring them offline across environments or teams to be replayed via inbound Webhooks.
>**Note**:ThisisdistinctfromSealbackend'snativesimulation"材料包"(\`simulation material_pack\` / \`/api/v1/material-packages/upload\`). Calling this standard "Webhook 资源包" avoids confusion.
-Therootdirectoryname**mustequal**the\`documentId\` **OR** start with \`documentId@\` (the \`@\` separates an optional annotation ignored during matching).
-\`信息表.xlsx\` at the ZIP root is the only file not associated with any document directory.
|费用明细表(has\`报销金额\` column) | Per-row entries in \`mingxi_list\` |
|劳务明细(has\`姓名\` column) | Per-person entries in \`daoshi_list\` |
###Strictbidirectionalvalidation
Beforepushingorpreviewing,thesystemenforces:
1.**Excel→ZIP**:Everypathdeclaredinan\`[附件]\` column cell **must** exist as a ZIP entry. Error: \`Excel 声明的附件路径在 ZIP 中不存在: <path>\`
2.**ZIP→Excel**:EveryZIPfile(excluding\`信息表.xlsx\`) **must** be declared in exactly one \`[附件]\` column. Error: \`ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>\`
3.**DocumentDirectoryScopeIsolation**:Allattachmentsdeclaredforadocument\`DOC_X\` **must** reside in its own root directory (\`DOC_X/\` or \`DOC_X@annotation/\`). Cross-document references are strictly forbidden. Error: \`单据「X」声明了跨单据或非本单据目录的附件路径: <path>。附件必须位于该单据自己的根目录...\`
4.**StrictDeclarationUniqueness**:AgivenZIPfilepath**cannot**bedeclaredmorethanonceacrosstheentireresourcepack(evenwithinthesamedocumentacrossmultiplerowsorfields).Ifthesamelogicaldocumentisneededinmultipleplaces,separatefilesmustbeplacedindistinctpaths.Error:\`附件路径「<path>」被重复声明了 N 次...\`
5.**Attachmentfilepolicy**:Everyattachmentexcepttheroot\`信息表.xlsx\` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: \`附件文件过小...\` / \`附件文件过大...\` / \`附件后缀不在白名单中...\`
6.**documentId↔ZIProot**:Every\`documentId\` in the Excel main sheet that declares attachments must have a matching ZIP root dir (exact match or \`documentId@annotation\`), and every ZIP root dir must match a declared \`documentId\`. Errors: \`Excel 会议编号「X」在 ZIP 中找不到对应的根目录...\` / \`ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号\`
\`null\` or an omitted \`maxFileSizeBytes\` means no per-file upper bound. Values are bytes; a file smaller than the minimum or larger than the maximum fails. Extensions are normalized case-insensitively and may be written with or without the leading dot. The root \`信息表.xlsx\` remains exempt from attachment policy checks.
Thesavedconfigurationisreturnedby\`webhook get\`/\`webhook list\` under \`materialPackFilePolicy\`. The root \`信息表.xlsx\` is always allowed as the material-pack manifest and is not subject to the attachment policy.
3.Ifconfigurationchangeisauthorized,readthecurrentpolicywith\`webhook get\`/\`webhook list\`, update only the necessary fields, and verify the returned configuration.
4.Retrytheoriginal\`material-pack push\`; it will load the latest saved policy before any upload begins.
Use\`--clear-max-file-size\` on \`seal-use webhook update\` to remove the upper bound. \`--allowed-extensions\` is a complete replacement list, so include existing allowed suffixes when adding one.
Thedirectlocal\`resource-pack preview\` command uses the default or temporary policy. It does not automatically read a selected Webhook's persisted policy. Use \`seal-use webhook ready <资源包.zip> --webhook <idOrName>\` or the actual push path when validating against the saved inbound policy.
###Errormessagesreference
|Errormessage|Meaning|Fix|
|---|---|---|
|\`Excel 声明的附件路径在 ZIP 中不存在: <path>\` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |
|\`ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>\` | ZIP contains a file not referenced by any \`[附件]\` column | Add an \`[附件]\` column entry or remove the file from ZIP |
|\`单据「X」声明了跨单据或非本单据目录的附件路径: <path>\` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |
|\`附件路径「<path>」被重复声明了 N 次\` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |
|\`Excel 会议编号「X」在 ZIP 中找不到对应的根目录\` | No ZIP root dir matches documentId \`X\` | Rename the ZIP folder to match the documentId |
|\`ZIP 根目录对应的编号「X」在信息表中找不到\` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |
|\`ZIP 根目录缺少信息表.xlsx\` | No \`信息表.xlsx\` found at ZIP root | Add the Excel file to the ZIP root |
|\`附件文件过小\` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower \`--min-file-size\` |
|\`附件文件过大\` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise \`--max-file-size\` |
|\`附件后缀不在白名单中\` | Attachment extension is not allowed by the Webhook policy | Add the extension with \`--allowed-extensions\` or convert the file |
|\`附件上传失败 <status>\` | Network/server error during file upload | Check webhook URL, secret, and server availability |
`;var my0=()=>{};var Vx1="iVBORw0KGgoAAAANSUhEUgAADVgAAAdwCAYAAACUWcTmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWKADAAQAAAABAAAHcAAAAAD4n9OGAABAAElEQVR4AeydB4AdVfX/z246pNAD0hK6dOki0rsU+dMJJVIFRYoUFUFAQUCqgHSkxx8gTRCpFkB6CU06SQi9BEhC+u7/fu7b83J3dt7bt33f5nuStzNz5947M583c+fOvPO9p6Y+mMlEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4kUDsHHrMOWQREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQigd7jxo8TChEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYIwkogtUc+bXroEVABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABCBQUx9MKERABERABERABERABERABERABERABERABERABERABERABERABESgqwiMHz/eBgwY0FWb13ZFQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQATmcAKKYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwn0npMPXscuAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj2RwP8+n26vfjbd3vpyho2fPN0+mjLTJs+qs/qaOhvYp8YWGtDLFh/U25YZ3NdWnr+/rTDvgJ6IQcckAhURqKkPVlFOZRIBERABERABERABERABERABERABERABERABERABERABERABERCBDiAwfvx4GzBAP9p2AFpVKQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiMIcR+GhSnT347lT713tT7eOpM4OYqj5+LEzNEFdZ+MyKU5Zr4jLp9fat/r1ss28NtM0WG2KLzN1nDiOnw53TCUhgNaefATp+ERABERABERABERABERABERABERABERABERABERABERABEehiAhJYdfEXoM2LgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhUPYFJ08z+7+Updsc7U8OxFARURKqyIKAqCKnqbVYQUdU2CK7iOiuIr4oirLBcgxArfHZZcrDttcwCNnefXlXPRgcgApUQkMCqEkrKIwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0GEEJLDqMLSqWAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4g8MR7M+2Cp6fY5JmFSFQhRlUQStUVBVUsF0VUCKiSSFZEsKqLkawa5yH/oN5mP195qK0/dPAcQFGHOKcTkMBqTj8DdPwiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0MUEJLDq4i+gCzY/ZcqUuNUBAwZ0wda1SREQAREQAREQAREQAREQAREQAREQAREQAREQARHoHAKd8S501AszbNT/psXIUwWhVDi2IK6qj5GriGRVEE4RlSoVWlUayYry+w2fx0Yst1DnQNNWRKCLCAQ9oUwEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKCaCFz035n20JgZ1stqQowqs9qaWmJVBR1VbRBZkdLLakN0qiCzCtMGgVXMURfW1YQsTHsFEdasMC0UCSWjOIvcbte++6V9MX2mHb7ytzypS6e/+93v7H//+1/uPuy888727W9/O35yMyhRBEoQ4NyXiYAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiECPIXDbbbfZiBEjGh0PP7aSxif90dXzks68G3k8P2VTYznNm67TvAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BoGLHp1lD74zM6qh6kK4qprwqW+YMl9TR1pYHcRWtUFHhZaqLi6TFsJbhflCOYRVtbG818H6+KGOhnr+9v4ku/DlDzrj0Mpug/fz6Xv+bOa//vWvxkcmAi0loAhWLSWm/CIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAt2WAD+sdvQPp/xwy0cjYHbb00A7JgIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAI9msCo5+rt4XdDVKoaIlfVxChVHHCMPtXoyIO4KuSoy0ayqifOFeWJUxVqSCJZfW/hwfbox1/FuqiKHF4zIqt5+39qey+zYEztij/pbwC8p0/NhVc+TddpXgSaIyCBVXOEtF4EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKBqCLz66qudtq/8iPvrX/+607aX3VBniMluvPHG7Ga1LAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUIJAzT+vi2vqN9m3RA4li0DbCTw5xuyWl+qMIFQWIk8Rpqo+Cq1YDlKokL7m4v2D7IrFOgurwvqwoiaEsIpyKebNHv9wki+FdERaSKlq7fytlrEj73vLHvvoq7gNUkM4q1BPKBTque7tCbbUoH62/tDBrOkyQ1yVfUf/u9/9rmx0qy7b2VZu2H8H4FhXXHFF+3//7/+1siYVq4RATX2wSjIqjwiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BIHx48fbgAEDOqLqHlun/6ja0QfYUQKrKVOmxF3X997R36DqFwEREAEREAEREAEREAEREAEREAEREAER6EwCs074btxcr9Me78zNalvdmEB7vwudNM3ssFvNJs2oi0KqWUE0FQVUUUiF6KreLtx5QVtt0X5lqYz+cIodevfYkKcg1KpHfBXKHvadobbvdxay0R9NsgPveyOsD3KTWiQniLjCNHyYDgqhfq7bcCmbu0+vsttpy0rEUlgqLErfje+8885NBEepwMrXE83Ko16ldbVl3zqjbHqsvj0EZdmoXb5O07YTUASrtjNUDSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQqQQ6M1JXpx5YD96Yj3sZR3ntwcdZyaHNmDHDPv74Y1t00UULo95WUqiL8syaNct69eo4J5EuOqwu3Szff58+fZrsg66RJkiU0MkEGJ4YhzSZCHQmAdpEjHtNbW0Ydb4djHvX9OnTNYBBA0ucWfv169dufNvhK+oxVUydOtXq6upsrrnm6jHHpAMRAREQAREQgbYS8OhV1FN/1VFWc8B5ba2yWJ6+45gxY+ytt96y/v3729JLL22LLbZYbj+H9y4u6ilWUGJm7rnntgUXXDCu/frrr+2LL74okbNxMv3XJZZYonFia5fGjLaad0e3tnSx3JwSNezmZ2ts8vQQTSr8C9KoOA2Sp8ChJvyttQPXG9SsuMqh1VEslIviqTBdf5G5o7iK1NUWHmg/XW1Ru/iF960+aK8QVbE1j2SFwOumtz6zg749lOztbqlQygVSCIuYL2cIqDwPoirepfsy5ZgnLRv5qlydXbUu73cAjqka9h1mCMSw1kbdamv5uPEW/pHAqoXAlF0EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEuppA+oNwR0WZ6upj7Enbf+ONN+yUU06Jh3Tsscfa6quv3pMOLx7Lhx9+aMcff3yc33vvvW3LLbfMPcZbbrnF7rjjjrjuF7/4ha2yyiq5+dLEyZMn24QJE2zhhRe23r1720svvWTnn39+zPLLX/7SlllmmTR77jyORb/61a/iuv3339++973v5eZLE99++2076aSTbNlll7UtttiiojJp+WqZHz16dBQ84XziNnPmTPv00099sUVTHLMGDx6cW2bcuHHRAWSzzTazHXfc0eaZZ56Y7/HHH7eLLroozh933HG21FJL2Zlnnmm77LJLm6+Xb775xr766qvc/ckmzjvvvNFJLZveluWzzz7b3nrzTVty2DDjfG2JTZs2ze677z7bZpttGonSvvzyy4od5bLb4zqqJqHnxxNmWcHZK3skLV/u16fG5huUL2B5cPRUO
Line truncated
`,"utf8"),{detected:I,configured:!0,configPath:U,targetDir:Y,action:"prepended"}}function to($){let Y=$?.targetSkillsDir??ay0(),U=$?.configFile??ty0(),I=ey0(),Q=!1;if(sq(U))try{let J=JSON.parse(sy0(U,"utf8"));if(Array.isArray(J?.entries))Q=J.entries.some((K)=>K?.path===Y)}catch{}return{detected:I,configured:Q,configPath:U,targetDir:Y}}var eo=()=>{};import{cpSync as Ax1,existsSync as $G,lstatSync as Yg0,mkdirSync as Bx1,realpathSync as GY,rmSync as Px1,symlinkSync as Tx1,unlinkSync as $g0}from"node:fs";import{homedir as Ug0}from"node:os";import{dirname as Ig0,join as HY}from"node:path";function Ex1($,Y){let U=Y?.baseHomeDir??Ug0(),I=HY(U,$.rootDirName),Q=Y?.sourceSkillDir??HY(U,".agents","skills","seal-use"),J=Ig0(Q),K=HY(I,"skills"),z=HY(K,"seal-use");if(!$G(I))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"skipped_not_detected"};if($G(K)&&$G(J))try{if(GY(K)===GY(J))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:K}}catch{}Bx1(K,{recursive:!0});let G;try{G=Yg0(z)}catch{G=void 0}let H=!1;if(G)if(G.isSymbolicLink()){try{if(GY(z)===GY(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"already_linked",targetPath:z}}catch{}try{$g0(z)}catch{}}else if(G.isDirectory())Px1(z,{recursive:!0,force:!0}),H=!0;else $g0(z);let W=process.platform==="win32"?"junction":"dir";try{return Tx1(Q,z,W),{id:$.id,name:$.name,detected:!0,configured:!0,mode:H?"replaced_real_dir":"linked",targetPath:z}}catch{try{return Ax1(Q,z,{recursive:!0}),{id:$.id,name:$.name,detected:!0,configured:!0,mode:"fallback_copied",targetPath:z}}catch(X){return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"error",targetPath:z,error:X?.message||String(X)}}}}function jx1($,Y){let U=Y?.baseHomeDir??Ug0(),I=HY(U,$.rootDirName),Q=Y?.sourceSkillDir??HY(U,".agents","skills","seal-use"),J=Ig0(Q),K=HY(I,"skills"),z=HY(K,"seal-use");if(!$G(I))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"not_detected"};if($G(K)&&$G(J))try{if(GY(K)===GY(J))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:K}}catch{}let G;try{G=Yg0(z)}catch{G=void 0}if(G){if(G.isSymbolicLink())try{if(GY(z)===GY(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"single_symlinked",targetPath:z}}catch{}else if(G.isDirectory())return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"real_directory",targetPath:z}}return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"not_configured",targetPath:z}}function $r($){return Qg0.map((Y)=>Ex1(Y,$))}function Yr($){return Qg0.map((Y)=>jx1(Y,$))}var Qg0;var Ur=o(()=>{Qg0=[{id:"workbuddy",name:"WorkBuddy",rootDirName:".workbuddy"},{id:"claude",name:"Claude",rootDirName:".claude"},{id:"qoder",name:"Qoder",rootDirName:".qoder"}]});var Ir=o(()=>{eo();Ur();eo();Ur()});import{existsSync as Cx1,mkdirSync as Qr,readFileSync as Rx1,rmSync as _x1,writeFileSync as Jg0}from"node:fs";import{homedir as zg0}from"node:os";import{dirname as Kg0,join as tq}from"node:path";function Jr(){return Gg0["SKILL.md"]||""}function Hg0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function Wg0($=tq(rI(),"SKILL.md")){try{return Hg0(Rx1($,"utf8"))}catch{return}}function rI(){return tq(zg0(),".agents","skills","seal-use")}function Sx1(){return tq(zg0(),".agents","skills","seal-home")}function hx1(){let $=Sx1();if(Cx1($))try{return _x1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Xg0($=rI()){hx1(),Qr($,{recursive:!0});let Y=[];for(let[U,I]of Object.entries(Gg0)){let Q=tq($,U);Qr(Kg0(Q),{recursive:!0}),Jg0(Q,I,"utf8"),Y.push(U)}for(let[U,I]of Object.entries(vx1)){let Q=tq($,U);Qr(Kg0(Q),{recursive:!0}),Jg0(Q,I),Y.push(U)}return{targetDir:$,files:Y}}var Gg0,vx1,Xq4;var eq=o(()=>{oo();oo();Ir();Gg0=oy0,vx1=Object.fromEntries(Object.entries(ry0).map(([$,Y])=>[$,Buffer.from(Y,"base64")]));Xq4=Hg0(Jr())});function Zg0(){return`#SealUse系统架构与运行规范白皮书
`)}var Eg0=m(()=>{X6()});async function Cg0($,Y,U){let z=($??Y??"").toLowerCase();if(z==="guide"||z==="doc"||z==="knowledge"||z==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(Ng0());return}if(z==="paths"||z==="dirs"||z==="directories"){let J=no();R0(J.directories);return}if(z==="auth"){let{selectCorp:J}=await Promise.resolve().then(() => (O4(),Yo)),{stringOption:K}=await Promise.resolve().then(() => (Z4(),tl)),{handleAuthCommand:G}=await Promise.resolve().then(() => (jo(),qS0)),H=K(U.options.corp)??(Y&&Y!==z?Y:void 0)??(U.command[2]&&U.command[2]!==z?U.command[2]:void 0),W=J(H);await G("check",W,U);return}if(z==="tenant"||z==="corp"||z==="enterprise"){let{selectCorp:J}=await Promise.resolve().then(() => (O4(),Yo)),{createSealClient:K}=await Promise.resolve().then(() => (m6(),H10)),{stringOption:G}=await Promise.resolve().then(() => (Z4(),tl)),{diagnoseTenantContract:H,formatTenantDoctorDashboard:W}=await Promise.resolve().then(() => (Eg0(),jg0)),X=G(U.options.corp)??(Y&&Y!==z?Y:void 0)??(U.command[2]&&U.command[2]!==z?U.command[2]:void 0),Z=J(X),q=await K(Z),V=await H(q,Z);if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(W(V));R0(V);return}let I=no();if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Pg0(I));R0(I)}var Rg0=m(()=>{Tg0();co();Z4();m1()});var vg0;var _g0=m(()=>{vg0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.38",description:"HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-usehttp`, or the `seal-useservicestart` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n"},servers:[{url:"http://localhost:8787",description:"Local HTTP adapter (`seal-usehttp`, or the `seal-useservicestart` daemon). Loopback-only by default."}],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","x-implementation-status":"implemented",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","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp","x-implementation-status":"planned",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","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp","x-implementation-status":"planned",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","x-implementation-status":"planned",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 i
Line truncated
toloopback(\`--host 127.0.0.1\`) and do not expose the port to a network or an origin you
donotcontrol.
`}},parameters:{CorpId:{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."},Offset:{name:"offset",in:"query",schema:{type:"integer",minimum:0,default:0},description:"Zero-based pagination offset."},Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50},description:"Maximum number of records to return."},RuleId:{name:"ruleId",in:"path",required:!0,schema:{type:"string"},description:"Approval rule ID."},VersionId:{name:"versionId",in:"path",required:!0,schema:{type:"string"},description:"Published rule version ID."},DocumentId:{name:"documentId",in:"path",required:!0,schema:{type:"string"},description:"Approval knowledge document ID."},RecordId:{name:"recordId",in:"path",required:!0,schema:{type:"string"},description:"seal-use approval run record ID."},BatchId:{name:"batchId",in:"path",required:!0,schema:{type:"string"},description:"Simulation batch ID."}},responses:{BadRequest:{description:"Invalid request.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},Unauthorized:{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:{}}}}}},NotFound:{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}},schemas:{ErrorResponse:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}},CorpSummary:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}},SwitchCorpRequest:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}},SwitchCorpResponse:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}},SourceConfig:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."},AuthStage:{type:"object",additionalProperties:!0,required:["name","ok"],properties:{name:{type:"string",examples:["hose.openapi","hose.provisional","seal.sso","seal.whoami"]},ok:{type:"boolean"},error:{type:"string"}}},AuthDiagnosis:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}},SealUser:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},tenantId:{type:"string"},name:{type:"string"},isAdmin:{type:"boolean"},permissions:{type:"array",items:{type:"string"}}}},SealTenant:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},name:{type:"string"},tenantSlug:{type:"string"}}},WhoamiResponse:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}},SessionResponse:{type:"object",additionalProperties:!0,required:["user","session"],properties:{user:{$ref:"#/components/schemas/SealUser"},session:{type:"object",additionalProperties:!0}}},ApprovalRule:{type:"object",additionalProperties:!0,required:["id","description","scope","strictness"],properties:{id:{type:"string"},description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]},status:{type:"string"}}},ApprovalRuleInput:{type:"object",required:["description","scope","strictness"],properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulePatch:{type:"object",additionalProperties:!1,properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulesResponse:{type:"object",required:["rules"],properties:{rules:{type:"array",items:{$ref:"#/components/schemas/ApprovalRule"}},hasPendingDeletes:{type:"boolean"}}},RuleSetVersion:{type:"object",additionalProperties:!0,required:["id","versionNumber","versionName","rules"],properties:{id:{type:"string"},versionNumber:{type:"integer"},versionName:{type:"string"},publishedByName:{type:"string"},rules:{type:"array",items:{type:"object",additionalProperties:!0}}}},PublishRuleVersionRequest:{type:"object",required:["versionName"],properties:{versionName:{type:"string"}}},ApprovalDocument:{type:"object",additionalProperties:!0,required:["id","title","content"],properties:{id:{type:"string"},title:{typ
Line truncated
`}},parameters:{CorpId:{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."},Offset:{name:"offset",in:"query",schema:{type:"integer",minimum:0,default:0},description:"Zero-based pagination offset."},Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50},description:"Maximum number of records to return."},RuleId:{name:"ruleId",in:"path",required:!0,schema:{type:"string"},description:"Approval rule ID."},VersionId:{name:"versionId",in:"path",required:!0,schema:{type:"string"},description:"Published rule version ID."},DocumentId:{name:"documentId",in:"path",required:!0,schema:{type:"string"},description:"Approval knowledge document ID."},RecordId:{name:"recordId",in:"path",required:!0,schema:{type:"string"},description:"seal-use approval run record ID."},BatchId:{name:"batchId",in:"path",required:!0,schema:{type:"string"},description:"Simulation batch ID."}},responses:{BadRequest:{description:"Invalid request.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},Unauthorized:{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:{}}}}}},NotFound:{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}},schemas:{ErrorResponse:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}},CorpSummary:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}},SwitchCorpRequest:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}},SwitchCorpResponse:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}},SourceConfig:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."},AuthStage:{type:"object",additionalProperties:!0,required:["name","ok"],properties:{name:{type:"string",examples:["hose.openapi","hose.provisional","seal.sso","seal.whoami"]},ok:{type:"boolean"},error:{type:"string"}}},AuthDiagnosis:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}},SealUser:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},tenantId:{type:"string"},name:{type:"string"},isAdmin:{type:"boolean"},permissions:{type:"array",items:{type:"string"}}}},SealTenant:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},name:{type:"string"},tenantSlug:{type:"string"}}},WhoamiResponse:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}},SessionResponse:{type:"object",additionalProperties:!0,required:["user","session"],properties:{user:{$ref:"#/components/schemas/SealUser"},session:{type:"object",additionalProperties:!0}}},ApprovalRule:{type:"object",additionalProperties:!0,required:["id","description","scope","strictness"],properties:{id:{type:"string"},description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]},status:{type:"string"}}},ApprovalRuleInput:{type:"object",required:["description","scope","strictness"],properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulePatch:{type:"object",additionalProperties:!1,properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulesResponse:{type:"object",required:["rules"],properties:{rules:{type:"array",items:{$ref:"#/components/schemas/ApprovalRule"}},hasPendingDeletes:{type:"boolean"}}},RuleSetVersion:{type:"object",additionalProperties:!0,required:["id","versionNumber","versionName","rules"],properties:{id:{type:"string"},versionNumber:{type:"integer"},versionName:{type:"string"},publishedByName:{type:"string"},rules:{type:"array",items:{type:"object",additionalProperties:!0}}}},PublishRuleVersionRequest:{type:"object",required:["versionName"],properties:{versionName:{type:"string"}}},ApprovalDocument:{type:"object",additionalProperties:!0,required:["id","title","content"],properties:{id:{type:"string"},title:{typ
Line truncated
`);I(z)})})}var Qj=8787,Jj="127.0.0.1";var lo=m(()=>{kg0();z3()});async function xg0($){let Y=s0($.options.port)??s0($.options.p),U=S($.options.host)??S($.options.h),z=await Kj({port:Y,host:U}),I=()=>{z.close(()=>{process.exit(0)})};process.on("SIGINT",I),process.on("SIGTERM",I),await new Promise(()=>{})}var fg0=m(()=>{Z4();lo()});async function ug0($,Y,U,z){if($==="config"||$==="get"){await x0("seal_llm_config_get",Y,U,{},j0(z.options));return}if($==="providers"||$==="list"){await x0("seal_llm_providers_list",Y,U,{},j0(z.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var bg0=m(()=>{O4();m1()});async function ig0($,Y){if($==="config"||$==="json"){oo();return}let{startServer:U}=await pg0().then(() => ng0);U()}function oo(){R0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var cg0=m(()=>{m1()});function dg0($){let Y=Uj();R0(Y,{...j0($.options),allowFull:!0})}var mg0=m(()=>{po();m1()});async function lg0($,Y,U,z){if($==="available"){await x0("seal_permissions_available_list",Y,U,{},j0(z.options));return}if($==="configs"||$==="list"){await x0("seal_permissions_configs_list",Y,U,{},j0(z.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var og0=m(()=>{O4();m1()});import{readFileSync as rg0}from"node:fs";async function sg0($,Y,U,z,I,Q,J){if(!$||$==="get"){await x0("seal_preference_get",I,Q,{},j0(J.options));return}if($==="decision"){if(Y==="update"||!Y){let K=S(J.options.input),G=K?JSON.parse(rg0(K,"utf8")):B8(J.json);if(!G||Object.keys(G).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await x0("seal_preference_decision_update",I,Q,{...G,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let K=S(J.options.default)??S(J.options.level)??z;if(K!=="medium"&&K!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await x0("seal_preference_thinking_depth_set",I,Q,{defaultLevel:K,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}if(Y==="policies"){if(U==="list"||!U){await x0("seal_preference_thinking_depth_policies_list",I,Q,{},j0(J.options));return}if(U==="upsert"){let K=S(J.options.input),G=K?JSON.parse(rg0(K,"utf8")):B8(J.json);if(!G||!G.id||!G.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await x0("seal_preference_thinking_depth_policies_upsert",I,Q,{...G,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}if(U==="remove"||U==="delete"){let K=z??S(J.options.id)??S(J.options.policyId);if(!K)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await x0("seal_preference_thinking_depth_policies_remove",I,Q,{policyId:K,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}var ag0=m(()=>{O4();Z4();m1()});async function tg0($={}){let Y=t8(),U=v4(),z=n2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},x3());console.log(`[probe]corp=${z.id}source=${z.source.type}`);let I=await bK(z);console.log("[probe] seal enterprise"),console.log(JSON.stringify(I,null,2));let Q=await B1(z),J=await SM(Q,{documentLimit:20,stylePreferencesEndpoint:z.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:J.rules.rules.length,hasPendingRuleDeletes:J.rules.hasPendingDeletes,documents:J.documents.articles.length,documentsTotal:J.documents.total,stylePreferences:J.stylePreferences.ok?"ok":`error:${J.stylePreferences.error}`},null,2))}var eg0=m(()=>{T5();m6();fT();X6()});async function $y0($,Y,U){let z=Y??S(U.options.corp)??($&&$!=="--corp"?$:void 0);await tg0({corpId:z})}var Yy0=m(()=>{eg0();Z4()});async function ro($,Y,U,z,I){if($==="count"){await x0("seal_approval_rules_list",U,z,{countOnly:!0},j0(I.options));return}if($==="list"){if(G0(I.options.count)){await x0("seal_approval_rules_list",U,z,{countOnly:!0},j0(I.options));return}let Q=s0(I.options.limit),J=s0(I.options.offset);if(G0(I.options.summary)){await x0("seal_approval_rules_list",U,z,{fields:Iv0,limit:Q,offset:J},j0(I.options));return}let K=await M$("seal_approval_rules_list",U,z,{limit:Q,offset:J}),G=j0(I.options);Qv0(K,G.allowFull===!0||Boolean(G.outputFile)),R0(K,G);return}if($==="clear"){let Q=G0(I.options.yes)===!0,J=G0(I.options.dryRun)??G0(I.options["dry-run"])??!Q;if(!Q&&!J)throw w$("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${z.id}--dry-run`);let K=await M$("seal_approval_rules_clear",U,z,{dryRun:J,recode:G0(I.options.recode)});if(!Q&&J&
Line truncated
`).filter(Boolean),Q=I.slice(-Y);return{logFile:U,lines:Q,totalLines:I.length}}async function Bk1($){let Y=Xj($),U=to($),z=pq($);Jy0($.stateDir);let I=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):Qj),Q=$.host??(process.env.HOST?process.env.HOST:Jj);Hj(Y,`${process.pid}
`,{mode:384}),Hj(U,JSON.stringify({pid:process.pid,port:I,host:Q,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),pK(z,`servicestartingonhttp://${Q}:${I} pid=${process.pid}`);let J=null;try{J=await Kj({port:I,host:Q,silent:!0}),pK(z,`service listening pid=${process.pid}`)}catch(G){if(pK(z,`service failed to bind port ${I}: ${G instanceof Error?G.message:String(G)}`),Wj(Y)===process.pid)x9(Y,{force:!0}),x9(U,{force:!0});throw G}let K=()=>{if(J)J.close(),J=null;if(Wj(Y)===process.pid)x9(Y,{force:!0}),x9(U,{force:!0});pK(z,`stopped pid=${process.pid}`)};await new Promise((G)=>{let H=!1,W=()=>{if(H)return;H=!0,K(),process.off("SIGTERM",W),process.off("SIGINT",W),G()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function zy0($){Jy0($.stateDir);let Y=cz($);if(Y.running)return Y;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},z=[...U.args??[],"service","run"];if($.port)z.push("--port",String($.port));if($.host)z.push("--host",String($.host));let I=Ok1(U.command,z,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});I.unref();let Q=Xj($);return Hj(Q,`${I.pid}
`,{flag:"a",mode:384})}var eo=m(()=>{lo()});import{homedir as Tk1}from"node:os";import{join as jk1}from"node:path";async function Yr($,Y,U){let z=U?s0(U.options.port)??s0(U.options.p):void 0,I=U?S(U.options.host)??S(U.options.h):void 0,Q=U?s0(U.options.lines)??s0(U.options.n):void 0,J=await s3($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:$r,version:X1,launcher:Y.launcher,port:z,host:I},{maxLines:Q});if(J!==void 0)R0(J)}var $r;var Ur=m(()=>{z3();eo();m1();Z4();$r=jk1(Tk1(),".config","seal-use")});import{existsSync as Ek1,readFileSync as Ky0}from"node:fs";async function Gy0($,Y,U,z,I){if($==="batch-records"||$==="records"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation batch-records <batchId>");await x0("seal_simulation_batch_records_get",U,z,{batchId:Q,query:S(I.options.query)},j0(I.options));return}if($==="create"||$==="run"){let Q=S(I.options.mode)??S(I.options.sourceSystem)??S(I.options["source-system"])??"hosecloud",J=Q==="material-pack"?"material_pack":Q,K=S(I.options.schemaConfig)??S(I.options["schema-config"]),G=K?JSON.parse(Ky0(K,"utf8")):void 0,H=S(I.options.input),W=H?JSON.parse(Ky0(H,"utf8")):B8(I.json),X=S(I.options.packageId)??S(I.options["package-id"]),Z=i6(I.options.packageIds)??i6(I.options["package-ids"])??(X?[X]:void 0),q=i6(I.options.flowIds)??i6(I.options["flow-ids"])??i6(I.options.documentSn)??i6(I.options["document-sn"]),V=S(I.options.signKey)??S(I.options["sign-key"])??S(I.options.integration),w=G0(I.options.wait)===!0,M=G0(I.options.noWait)??G0(I.options["no-wait"])??(w?!1:!0),F=await M$("seal_simulation_batch_create",U,z,{mode:J,sourceSystem:J,flowIds:q,documentSn:q,rejectNodeName:S(I.options.rejectNode)??S(I.options["reject-node"])??null,thinkingDepthOverride:S(I.options.thinkingDepth)??S(I.options["thinking-depth"]),skipInvoiceGeneration:G0(I.options.skipInvoiceGeneration)??G0(I.options["skip-invoice-generation"]),skipExpenseExtraction:G0(I.options.skipExpenseExtraction)??G0(I.options["skip-expense-extraction"]),disableAttachmentCache:G0(I.options.disableAttachmentCache)??G0(I.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:S(I.options.templateId)??S(I.options["template-id"]),schemaConfig:G,requestIds:i6(I.options.requestIds)??i6(I.options["request-ids"]),workflowTypeId:S(I.options.workflowTypeId)??S(I.options["workflow-type-id"]),flowStatusList:i6(I.options.flowStatusList)?.map(Number)??i6(I.options["flow-status-list"])?.map(Number),businessCodes:i6(I.options.businessCodes)??i6(I.options["business-codes"]),documentType:S(I.options.documentType)??S(I.options["document-type"]),startTime:s0(I.options.startTime)??s0(I.options["start-time"]),endTime:s0(I.options.endTime)??s0(I.options["end-time"]),status:i6(I.options.status),limit:s0(I.options.limit),noWait:M,rawParams:W});if(w&&F&&typeof F==="object"&&"batchId"in F&&typeof F.batchId==="string"){await x0("seal_simulation_batch_wait",U,z,{batchId:F.batchId,timeout:S(I.options.timeout),pollInterval:S(I.options.pollInterval)??S(I.options["poll-interval"])},j0(I.options));return}R0(F,j0(I.options));return}if($==="wait"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await x0("seal_simulation_batch_wait",U,z,{batchId:Q,timeout:S(I.options.timeout),pollInterval:S(I.options.pollInterval)??S(I.options["poll-interval"])},j0(I.options));return}if($==="status"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation status <batchId>");await x0("seal_simulation_batch_status",U,z,{batchId:Q},j0(I.options));return}if($==="clean"||$==="delete"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation clean <batchId>");await x0("seal_simulation_batch_clean",U,z,{batchId:Q},j0(I.options));return}if($==="specifications"){let Q=Y??S(I.options.integration)??S(I.options.signKey)??S(I.options["sign-key"]);await x0("seal_simulation_specifications_list",U,z,{signKey:Q},j0(I.options));return}if($==="approval-definitions"||$==="definitions"){await x0("seal_simulation_feishu_approval_definitions_list",U,z,{},j0(I.options));return}if($==="list"){await x0("seal_simulation_batches_list",U,z,{limit:s0(I.options.limit)},j0(I.options));return}if($==="get"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation get <batchId>");await x0("seal_simulation_batch_get",U,z,{batchId:Q},j0(I.options));return}if($==="templates"){await x0("seal_simulation_templates_get",U,z,{},j0(I.options));return}if($==="integrations"){await x0("seal_simulation_integrations_get",U,z,{},j0(I.options));return}if($==="package-upload"){let Q=Y??S(I.options.file);if(!Q)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!Ek1(Q))throw Error(`Filenotfound:${Q}`);await x0("seal_simulation_material_package_upload",U,z,{filePath:Q},j0(I.o
Line truncated
`);return}if($==="install"||$==="init"||$==="sync"){let z=G0(U.options.local)||G0(U.options.workspace),I=S(U.options.dir)??S(U.options.target)??Y,Q=I?I:z?Zj(process.cwd(),".agents","skills","seal-use"):iz(),J=Og0(Q),K=!z&&!I,G=K?_o():void 0,H=K?So():void 0;R0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files,...G?{antigravity:G}:{},...H?{hosts:H}:{}});return}if($==="status"||$==="get"||!$){let z=iz(),I=Zj(process.cwd(),".agents","skills","seal-use"),Q=vo(),J=go();R0({global:{dir:z,installed:Wy0(Zj(z,"SKILL.md"))},local:{dir:I,installed:Wy0(Zj(I,"SKILL.md"))},antigravity:Q,hosts:J});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}var Zy0=m(()=>{ko();iq();Z4();m1()});async function qy0($,Y){if($==="config"){R0(await bK(Y));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var Vy0=m(()=>{fT();m1()});function zr($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let Y=$.toUpperCase().trim();if(Y==="APPROVE"||Y==="PASS")return"APPROVE";if(Y==="REJECT"||Y==="DENIED")return"REJECT";if(Y==="MANUAL"||Y==="ASSISTED")return"MANUAL";if(Y==="ERROR"||Y==="FAILED")return"ERROR";return Y}async function Ly0($){let{sourceCorp:Y,targetCorp:U,sourceClient:z,targetClient:I,samples:Q=10,dryRun:J=!1,pollIntervalMs:K=2000,timeoutMs:G=45000,snPrefix:H="REG_",fetchFn:W=fetch}=$;if(U.environment!=="test")throw new W4(`重放目标企业「${U.name}」(${U.id})的环境为「${U.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Y.id}<testCorpId>`);let X=await lY(I),q=(Array.isArray(X.features)?X.features:[]).find((d)=>d?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,w=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,M=Q*w;if(V<M)throw new W4(`测试企业「${U.name}」AI审批额度不足:当前剩余${V}点,本次回归抽样${Q}笔需要约${M}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${U.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(V/w))})`);let F=await i4(z,{limit:Q,status:"completed"}),N=Array.isArray(F.records)?F.records:[];if(N.length===0){let d=await i4(z,{limit:Q});N=Array.isArray(d.records)?d.records:[]}if(N.length===0)throw new W4(`在母企业「${Y.name}」(${Y.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(N=N.slice(0,Q),J){let d=N.map((a)=>{let $0=a.sourceDocumentSN??a.id,y=a?.result?.decision??a.aiDecision??a?.decision,p=zr(y),Y0=a?.result?.summary??a.aiSummary;return{sn:$0,sourceRecordId:a.id,prodDecision:p,prodSummary:Y0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M},metrics:{sampleCount:d.length,successCount:d.length,failureCount:0,matchCount:d.length,flipCount:0,concordanceRate:1},flips:[],records:d}}let O=await gp(I,U,$.webhookSelector),D=[];for(let d of N){let a=Date.now(),$0=d.sourceDocumentSN??d.id,y=zr(d?.result?.decision??d.aiDecision??d?.decision),p=d?.result?.summary??d.aiSummary;try{let Y0=await H4(z,d.id),R=`${H}${$0}`,o=hp(Y0,{snPrefix:H,docIdPrefix:H});await Sp(O.incomingDocumentWebhook.url,O.secret,o,W,A6(U.seal));let e=null,O0=Date.now();while(Date.now()-O0<G){await new Promise((X0)=>setTimeout(X0,K));let t=await i4(I,{sourceDocumentSN:R,limit:1});if(t.records&&t.records.length>0){let X0=t.records[0];if(X0.status==="completed"||X0.status==="failed"){e=X0;break}}}if(!e){D.push({sn:$0,sourceRecordId:d.id,prodDecision:y,prodSummary:p,status:"FAILED",error:`测试租户单据审核超时(${Math.round(G/1000)}s未完成)`,durationMs:Date.now()-a});continue}let T0=zr(e?.result?.decision??e.aiDecision??e?.decision??(e.status==="completed"?"APPROVE":"ERROR")),y0=e?.result?.summary??e.aiSummary,v0=y===T0,o0=v0?"MATCHED":"FLIPPED",q1={sn:$0,sourceRecordId:d.id,prodDecision:y,prodSummary:p,testRecordId:e.id,testDecision:T0,testSummary:y0,status:o0,durationMs:Date.now()-a};if(!v0)q1.diff={from:y,to:T0,reasonDiff:y0&&p&&y0!==p?`生产:${p.slice(0,60)}...->测试:${y0.slice(0,60)}...`:void 0};D.push(q1)}catch(Y0){D.push({sn:$0,sourceRecordId:d.id,prodDecision:y,prodSummary:p,status:"FAILED",error:Y0 instanceof Error?Y0.message:String(Y0),durationMs:Date.now()-a})}}let P=D.filter((d)=>d.status==="MATCHED"||d.status==="FLIPPED"),T=D.filter((d)=>d.status==="MATCHED"),A=D.filter((d)=>d.status==="FLIPPED"),j=D.filter((d)=>d.status==="FAILED").length,C=T.length,b=A.length,x=C+b,g=x>0?C/x:0,i=b>0,c=i?"REGRESSIONS_DETECTED":"CLEAN",z0=!i&&j===0,k;try{let d=await lY(I),$0=(Array.isArray(d.features)?d.features:[]).find((y)=>y?.code==="ai-approval");if(typeof $0?.balance==="number")k=$0.balance}catch{}return{ok:!i&&j===0,verdict:c,safeToPublish:z0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M,balanceAfter:k},metrics:{sampleCount:D.length,successCount:P.length,failureCount:j,matchCount:C,flipCount:b,concordanceRate:Number(g.toFixed(4))},flips:A,records:D}}function Fy0($){let{sourceCorp:Y,targetCorp:U,verdict:z,safeToPublish:I,metrics:Q,quota:J,flips:K,records:G}=$,H=z==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":z==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",W=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${Y.name}」->测试靶场「${U.name}」`,`判定:${H}·准许发布:${I?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${Q.sampleCount}|一致通过:${Q.matchCount}|决策翻转:${Q.flipCount}|异常失败:${Q.failureCount}`,`一致率:${(Q.concordanceRate*100).toFixed(1)}%|消耗预估:${J.estimatedRequired}点(余量:${J.balanceBefore}${J.balanceAfter!==void0?` -> ${J.balanceAfter}`:""})`," "+"─".repeat(65)];if(K.length>0){W.push(`⚠️决策翻转清单(${K.length}笔单据在新规则下结果改变):`);for(let X of K)if(W.push(`•单据[${X.sn}]:原生产判定「${X.prodDecision}」➔测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)W.push(`理由差异:${X.diff.reasonDiff}`);W.push(" "+"─".repeat(65)),W.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(z==="CLEAN")W.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100%
Line truncated
`)}var wy0=m(()=>{O8();X6();iZ()});async function Ir($,Y,U){let z=($??Y??"regression").toLowerCase();if(z==="regression"||z==="regress"||z==="matrix"){let I=S(U.options.corp)??(Y&&Y!==z?Y:void 0),Q=M1(I),J=Q,K=Q;if(Q.environment==="test"){K=Q;let O=S(U.options["prod-corp"])??S(U.options.prod)??Q.prodCorpId;if(!O)throw new W4(`测试企业「${Q.name}」(${Q.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${Q.id}`);J=M1(O)}else{J=Q;let O=S(U.options["test-corp"])??S(U.options.test)??Q.testCorpId;if(!O)throw new W4(`生产企业「${Q.name}」(${Q.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Q.id}<testCorpId>`);K=M1(O)}let G=await B1(J),H=await B1(K),W=s0(U.options.samples)??s0(U.options.limit)??s0(U.options.n)??10,X=G0(U.options["dry-run"]),Z=G0(U.options["fail-on-flips"]),q=s0(U.options["poll-interval"])??2000,V=s0(U.options.timeout)??45000,w=S(U.options["sn-prefix"])??"REG_",M=S(U.options.webhook)??S(U.options.selector),F=await Ly0({sourceCorp:J,targetCorp:K,sourceClient:G,targetClient:H,samples:W,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:w,failOnFlips:Z,webhookSelector:M});if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Fy0(F));if(R0(F),Z&&!F.ok)throw new W4(`回归测试发现${F.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new W4(`未知的test子命令:"${z}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}var My0=m(()=>{O8();O4();Z4();m1();m6();wy0()});async function Oy0($,Y,U,z){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await x0($,Y,U,B8(z.json),j0(z.options))}var Ny0=m(()=>{O4();Z4();m1()});function Dy0(){R0(Pq.map(($)=>({name:$.name,description:$.description})))}var Ay0=m(()=>{jq();m1()});function qj($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var By0=m(()=>{iq()});import{existsSync as Ck1,mkdirSync as Rk1,readFileSync as _k1,renameSync as vk1,writeFileSync as hk1}from"node:fs";import{homedir as Sk1}from"node:os";import{dirname as gk1,join as yk1}from"node:path";import{spawn as kk1}from"node:child_process";function Py0($){return $.replace(/\.\d+Z$/,"Z")}function Ty0(){let $=process.env[xk1]?.trim();if($)return $;return uk1}function jy0($=Ty0()){if(!Ck1($))return null;try{let Y=_k1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&typeof U.latestVersion==="string"&&typeof U.checkedAt==="string")return{...U,checkedAt:Py0(U.checkedAt)};return null}catch{return null}}function dq($,Y=Ty0()){try{let U=gk1(Y);Rk1(U,{recursive:!0,mode:448});let z={checkedAt:Py0($.checkedAt??new Date().toISOString()),latestVersion:$.latestVersion,publishedAt:$.publishedAt,releaseUrl:$.releaseUrl},I=`${Y}.tmp.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;hk1(I,JSON.stringify(z,null,2),{mode:384}),vk1(I,Y)}catch{}}function Ey0($,Y=fk1){if(!$||!$.checkedAt)return!0;let U=new Date($.checkedAt).getTime();if(Number.isNaN(U))return!0;return Date.now()-U>Y}function Cy0($){if(process.env.SEAL_DISABLE_BG_UPDATE==="1"||!1||process.env.CI)return!1;if(!$||!$.command)return!1;try{let Y=$.command,U=[...$.args??[],"update","check","--bg-save"];return kk1(Y,U,{detached:!0,stdio:"ignore",env:{...process.env,SEAL_DISABLE_BG_UPDATE:"1"}}).unref(),!0}catch{return!1}}var xk1="SEAL_USE_UPDATE_CACHE_FILE",fk1=86400000,uk1;var Qr=m(()=>{uk1=yk1(Sk1(),".config","seal-use","update-cache.json")});import{chmodSync as bk1,mkdirSync as ik1,readdirSync as ck1,realpathSync as Ry0,renameSync as Jr,rmSync as nk1,unlinkSync as gy0,writeFileSync as _y0}from"node:fs";import{basename as pk1,dirname as dk1,isAbsolute as mk1,join as Fj,relative as lk1}from"node:path";import{spawn as ok1,spawnSync as a3}from"node:child_process";async function ky0($,Y={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:$r,version:X1,launcher:$.launcher},z=Y.repo||process.env[rk1]?.trim()||process.env[sk1]?.trim()||yy0,I=Y.targetVersion?.trim(),Q=I&&I.toLowerCase()!=="latest"?I:void 0;if(Q){let D=Q.replace(/^v/,""),P=by0(D,X1);if(P<0)if(!Wg&&Y.force);else{R0({updated:!1,currentVersion:X1,targetVersion:D,mode:qj()?"binary":"source",message:!Wg?`Cannotdowngradeseal-usefromdevbuildv${X1}toreleasev${D}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${X1}toolderversionv${D}.Updatesmustbeforward-only.`});return}if(P===0&&!Y.force){R0({updated:!1,currentVersion:X1,targetVersion:D,mode:qj()?"binary":"source",message:`seal-useisalreadyatversionv${X1}.Use--forcetoreinstall.`});return}}if(Y.changelogOnly){let D=await Lj(z,Y.limit??10);R0({currentVersion:X1,totalQueried:D.length,releases:D.map((P)=>({version:P.version,tagName:P.tagName,publishedAt:P.publishedAt,author:P.author,releaseNotes:P.notes,releaseUrl:P.htmlUrl,isCurrent:P.version===X1,isNewer:h5(P.version,X1)}))});return}if(!qj()){if(Y.checkOnly){let P=await Lj(z,30),T=P[0],A=T?.version??X1,j=P.find((x)=>x.version===X1),C=h5(A,X1),b=P.filter((x)=>h5(x.version,X1));if(T?.version)dq({latestVersion:T.version,publishedAt:T.publishedAt,releaseUrl:T.htmlUrl});if(Y.bgSave)return;R0({updated:!1,updateAvailable:C,currentVersion:X1,currentVersionPublishedAt:j?.publishedAt,latestVersion:A,latestVersionPublishedAt:T?.publishedAt,behindCount:b.length,pendingReleases:b.map((x)=>({version:x.version,tagName:x.tagName,publishedAt:x.publishedAt,author:x.author,releaseNotes:x.notes,releaseUrl:x.htmlUrl})),releaseNotes:T?.notes??"",releaseUrl:T?.htmlUrl??"",mode:"source",message:"当前运行的是开发版。正式用户请安装正式版后使用 seal-use update。"});return}let D=cz(U).running;if(D)await s3("stop",U);try{Sy0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(P){console.error(`⚠️开发版更新同步失败,继续刷新本地依赖:${PinstanceofError?P.message:String(P)}`)}if(Sy0("bun",["install"],{cwd:$.appRoot}),D)await s3("start",U);R0({updated:!0,serviceRestarted:D,version:X1,mode:"source"});return}if(Yx1())try{await Ux1($,Y,U,z,Q);return}catch(D){console.error(`⚠️Homebrew自动更新失败,回退至原生二进制更新:${DinstanceofError?D.message:String(D)}`)}let J=tk1(),K=ek1(),G=await Lj(z,30),H=Q?G.find((D)=>D.version
Line truncated
`)}catch{}}async function Qx1($,Y,U,z){let I=Kr(),Q=[],J=U?U.startsWith("v")?U:`v${U}`:void 0,K=z||$.split("/").pop()||"";if(I!=="github"){if(J&&K)Q.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${J}/${K}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${J}/${K}`);if($.startsWith("https://git.ying-qing.cn"))Q.push($)}if(I!=="gitea")if(J&&K){let w=`https://github.com/${yy0}/releases/download/${J}/${K}`;if(!process.env.CI)Q.push(`https://ghfast.top/${w}`,`https://gh.ddlc.top/${w}`);Q.push(w)}else if($.includes("github.com")){if(!process.env.CI)Q.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Q.push($)}else Q.push($);let G=Array.from(new Set(Q)),H,W=6000,X=6000,Z=307200,q=1e4,V=180000;for(let w=0;w<G.length;w++){let M=G[w],F=new AbortController,N="",O=(A)=>{N=A;try{F.abort()}catch{}},D=setTimeout(()=>{O("Connection timed out (no response headers within 6s)")},W),P,T;try{Vj(`==> [${w+1}/${G.length}] Downloading via: ${M}`);let A=await fetch(M,{signal:F.signal});if(D)clearTimeout(D),D=void 0;if(!A.ok)throw Error(`HTTP ${A.status} ${A.statusText}`);P=setTimeout(()=>{O("Overall download time exceeded 3 minutes")},V);let j=Number(A.headers.get("content-length"))||0,C=A.body?.getReader();if(!C){let c=Buffer.from(await A.arrayBuffer());if(c.length<1000)throw Error(`Downloaded content is suspiciously small (${c.length} bytes)`);_y0(Y,c),Vj(`✓ Download succeeded (${(c.length/1024/1024).toFixed(1)} MB)`);return}let b=[],x=0,g=0;T=setTimeout(()=>{if(x<Z){let c=(x/1024).toFixed(1);O(`Initial transfer too slow (${c} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let c=C.read(),z0,k=new Promise((y,p)=>{z0=setTimeout(()=>{p(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),d;try{d=await Promise.race([c,k])}finally{if(z0)clearTimeout(z0)}let{done:a,value:$0}=d;if(a)break;if($0){if(b.push($0),x+=$0.length,T&&x>=Z)clearTimeout(T),T=void 0;let y=Date.now();if(y-g>200){g=y;let p=j?Math.round(x/j*100):0,Y0=(x/1048576).toFixed(1),R=j?(j/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${p}% (${Y0} / ${R} MB)...`)}catch{}}}}try{process.stderr.write(`
`);Q(I)})})}var ME=8787,OE="127.0.0.1";var qr=o(()=>{yg0();W3()});async function gg0($){let Y=l0($.options.port)??l0($.options.p),U=R($.options.host)??R($.options.h),I=await NE({port:Y,host:U}),Q=()=>{I.close(()=>{process.exit(0)})};process.on("SIGINT",Q),process.on("SIGTERM",Q),await new Promise(()=>{})}var kg0=o(()=>{L4();qr()});async function xg0($,Y,U,I){if($==="config"||$==="get"){await v0("seal_llm_config_get",Y,U,{},T0(I.options));return}if($==="providers"||$==="list"){await v0("seal_llm_providers_list",Y,U,{},T0(I.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var fg0=o(()=>{D4();$4()});async function ug0($,Y){if($==="config"||$==="json"){Vr();return}let{startServer:U}=await cg0().then(() => ig0);U()}function Vr(){C0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var bg0=o(()=>{$4()});function ng0($){let Y=LE();C0(Y,{...T0($.options),allowFull:!0})}var dg0=o(()=>{Xr();$4()});async function pg0($,Y,U,I){if($==="available"){await v0("seal_permissions_available_list",Y,U,{},T0(I.options));return}if($==="configs"||$==="list"){await v0("seal_permissions_configs_list",Y,U,{},T0(I.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var mg0=o(()=>{D4();$4()});import{readFileSync as lg0}from"node:fs";async function og0($,Y,U,I,Q,J,K){if(!$||$==="get"){await v0("seal_preference_get",Q,J,{},T0(K.options));return}if($==="decision"){if(Y==="update"||!Y){let z=R(K.options.input),G=z?JSON.parse(lg0(z,"utf8")):F6(K.json);if(!G||Object.keys(G).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await v0("seal_preference_decision_update",Q,J,{...G,dryRun:z0(K.options.dryRun)??z0(K.options["dry-run"])},T0(K.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let z=R(K.options.default)??R(K.options.level)??I;if(z!=="medium"&&z!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await v0("seal_preference_thinking_depth_set",Q,J,{defaultLevel:z,dryRun:z0(K.options.dryRun)??z0(K.options["dry-run"])},T0(K.options));return}if(Y==="policies"){if(U==="list"||!U){await v0("seal_preference_thinking_depth_policies_list",Q,J,{},T0(K.options));return}if(U==="upsert"){let z=R(K.options.input),G=z?JSON.parse(lg0(z,"utf8")):F6(K.json);if(!G||!G.id||!G.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await v0("seal_preference_thinking_depth_policies_upsert",Q,J,{...G,dryRun:z0(K.options.dryRun)??z0(K.options["dry-run"])},T0(K.options));return}if(U==="remove"||U==="delete"){let z=I??R(K.options.id)??R(K.options.policyId);if(!z)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await v0("seal_preference_thinking_depth_policies_remove",Q,J,{policyId:z,dryRun:z0(K.options.dryRun)??z0(K.options["dry-run"])},T0(K.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}var rg0=o(()=>{D4();L4();$4()});async function sg0($={}){let Y=K$(),U=T4(),I=r2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},m3());console.log(`[probe]corp=${I.id}source=${I.source.type}`);let Q=await az(I);console.log("[probe] seal enterprise"),console.log(JSON.stringify(Q,null,2));let J=await P1(I),K=await pM(J,{documentLimit:20,stylePreferencesEndpoint:I.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:K.rules.rules.length,hasPendingRuleDeletes:K.rules.hasPendingDeletes,documents:K.documents.articles.length,documentsTotal:K.documents.total,stylePreferences:K.stylePreferences.ok?"ok":`error:${K.stylePreferences.error}`},null,2))}var ag0=o(()=>{t$();i6();aT();X4()});async function tg0($,Y,U){let I=Y??R(U.options.corp)??($&&$!=="--corp"?$:void 0);await sg0({corpId:I})}var eg0=o(()=>{ag0();L4()});import{readFileSync as px1}from"node:fs";function $k0($,Y){let U=R($.options.descriptionFile)??R($.options["description-file"]);if(U)return px1(U,"utf8").trim();let I=R($.options.description)??R($.options.desc);if(I!==void 0)return I;return typeof Y.description==="string"?Y.description:void 0}function WY($,Y){let U=R($.options.version);if(U!==void 0)return U;if(z0($.options.latest))return"latest";if(Y!==void 0&&!Y.startsWith("-"))return Y;return}async function Lr($,Y,U,I,Q){if(!U&&!($==="lint"||$==="linters"||$==="linter-list"||$==="map"))throw Error(`rules${$??""}requiresanauthenticatedenterprise.Run'seal-use corps list'toselectone.`);if($==="count"){let K=WY(Q);await v0("seal_approval_rules_list",U,I,{version:K,countOnly:!0},T0(Q.options));return}if($==="list"){let K=WY(Q);if(z0(Q.options.count)){await v0("seal_approval_rules_list",U,I,{version:K,countOn
Line truncated
`).filter(Boolean),J=Q.slice(-Y);return{logFile:U,lines:J,totalLines:Q.length}}async function sx1($){let Y=PE($),U=Mr($),I=UV($);Jk0($.stateDir);let Q=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):ME),J=$.host??(process.env.HOST?process.env.HOST:OE);AE(Y,`${process.pid}
`,{mode:384}),AE(U,JSON.stringify({pid:process.pid,port:Q,host:J,version:$.version,startedAt:A1()},null,2),{mode:384}),YG(I,`servicestartingonhttp://${J}:${Q} pid=${process.pid}`);let K=null;try{K=await NE({port:Q,host:J,silent:!0}),YG(I,`service listening pid=${process.pid}`)}catch(G){if(YG(I,`service failed to bind port ${Q}: ${G instanceof Error?G.message:String(G)}`),BE(Y)===process.pid)d9(Y,{force:!0}),d9(U,{force:!0});throw G}let z=()=>{if(K)K.close(),K=null;if(BE(Y)===process.pid)d9(Y,{force:!0}),d9(U,{force:!0});YG(I,`stopped pid=${process.pid}`)};await new Promise((G)=>{let H=!1,W=()=>{if(H)return;H=!0,z(),process.off("SIGTERM",W),process.off("SIGINT",W),G()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function Uk0($){Jk0($.stateDir);let Y=sI($);if(Y.running)return Y;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},I=[...U.args??[],"service","run"];if($.port)I.push("--port",String($.port));if($.host)I.push("--host",String($.host));let Q=mx1(U.command,I,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});Q.unref();let J=PE($);return AE(J,`${Q.pid}
`,{flag:"a",mode:384})}var Or=o(()=>{qr()});import{homedir as tx1}from"node:os";import{join as ex1}from"node:path";async function Dr($,Y,U){let I=U?l0(U.options.port)??l0(U.options.p):void 0,Q=U?R(U.options.host)??R(U.options.h):void 0,J=U?l0(U.options.lines)??l0(U.options.n):void 0,K=await J7($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:Nr,version:Z1,launcher:Y.launcher,port:I,host:Q},{maxLines:J});if(K!==void 0)C0(K)}var Nr;var Ar=o(()=>{W3();Or();$4();L4();Nr=ex1(tx1(),".config","seal-use")});import{existsSync as $f1,readFileSync as Kk0}from"node:fs";async function zk0($,Y,U,I,Q){if($==="batch-records"||$==="records"){let J=Y??R(Q.options.batchId)??R(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation batch-records <batchId>");await v0("seal_simulation_batch_records_get",U,I,{batchId:J,query:R(Q.options.query)},T0(Q.options));return}if($==="create"||$==="run"){let J=R(Q.options.mode)??R(Q.options.sourceSystem)??R(Q.options["source-system"])??"hosecloud",K=J==="material-pack"?"material_pack":J,z=R(Q.options.schemaConfig)??R(Q.options["schema-config"]),G=z?JSON.parse(Kk0(z,"utf8")):void 0,H=R(Q.options.input),W=H?JSON.parse(Kk0(H,"utf8")):F6(Q.json),X=R(Q.options.packageId)??R(Q.options["package-id"]),Z=x4(Q.options.packageIds)??x4(Q.options["package-ids"])??(X?[X]:void 0),q=x4(Q.options.flowIds)??x4(Q.options["flow-ids"])??x4(Q.options.documentSn)??x4(Q.options["document-sn"]),V=R(Q.options.signKey)??R(Q.options["sign-key"])??R(Q.options.integration),w=z0(Q.options.wait)===!0,M=z0(Q.options.noWait)??z0(Q.options["no-wait"])??(w?!1:!0),F=await C$("seal_simulation_batch_create",U,I,{mode:K,sourceSystem:K,flowIds:q,documentSn:q,rejectNodeName:R(Q.options.rejectNode)??R(Q.options["reject-node"])??null,thinkingDepthOverride:R(Q.options.thinkingDepth)??R(Q.options["thinking-depth"]),skipInvoiceGeneration:z0(Q.options.skipInvoiceGeneration)??z0(Q.options["skip-invoice-generation"]),skipExpenseExtraction:z0(Q.options.skipExpenseExtraction)??z0(Q.options["skip-expense-extraction"]),disableAttachmentCache:z0(Q.options.disableAttachmentCache)??z0(Q.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:R(Q.options.templateId)??R(Q.options["template-id"]),schemaConfig:G,requestIds:x4(Q.options.requestIds)??x4(Q.options["request-ids"]),workflowTypeId:R(Q.options.workflowTypeId)??R(Q.options["workflow-type-id"]),flowStatusList:x4(Q.options.flowStatusList)?.map(Number)??x4(Q.options["flow-status-list"])?.map(Number),businessCodes:x4(Q.options.businessCodes)??x4(Q.options["business-codes"]),documentType:R(Q.options.documentType)??R(Q.options["document-type"]),startTime:l0(Q.options.startTime)??l0(Q.options["start-time"]),endTime:l0(Q.options.endTime)??l0(Q.options["end-time"]),status:x4(Q.options.status),limit:l0(Q.options.limit),noWait:M,rawParams:W});if(w&&F&&typeof F==="object"&&"batchId"in F&&typeof F.batchId==="string"){await v0("seal_simulation_batch_wait",U,I,{batchId:F.batchId,timeout:R(Q.options.timeout),pollInterval:R(Q.options.pollInterval)??R(Q.options["poll-interval"])},T0(Q.options));return}C0(F,T0(Q.options));return}if($==="wait"){let J=Y??R(Q.options.batchId)??R(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await v0("seal_simulation_batch_wait",U,I,{batchId:J,timeout:R(Q.options.timeout),pollInterval:R(Q.options.pollInterval)??R(Q.options["poll-interval"])},T0(Q.options));return}if($==="status"){let J=Y??R(Q.options.batchId)??R(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation status <batchId>");await v0("seal_simulation_batch_status",U,I,{batchId:J},T0(Q.options));return}if($==="clean"||$==="delete"){let J=Y??R(Q.options.batchId)??R(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation clean <batchId>");await v0("seal_simulation_batch_clean",U,I,{batchId:J},T0(Q.options));return}if($==="specifications"){let J=Y??R(Q.options.integration)??R(Q.options.signKey)??R(Q.options["sign-key"]);await v0("seal_simulation_specifications_list",U,I,{signKey:J},T0(Q.options));return}if($==="approval-definitions"||$==="definitions"){await v0("seal_simulation_feishu_approval_definitions_list",U,I,{},T0(Q.options));return}if($==="list"){await v0("seal_simulation_batches_list",U,I,{limit:l0(Q.options.limit)},T0(Q.options));return}if($==="get"){let J=Y??R(Q.options.batchId)??R(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation get <batchId>");await v0("seal_simulation_batch_get",U,I,{batchId:J},T0(Q.options));return}if($==="templates"){await v0("seal_simulation_templates_get",U,I,{},T0(Q.options));return}if($==="integrations"){await v0("seal_simulation_integrations_get",U,I,{},T0(Q.options));return}if($==="package-upload"){let J=Y??R(Q.options.file);if(!J)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!$f1(J))throw Error(`Filenotfound:${J}`);await v0("seal_simulation_material_package_upload",U,I,{filePath:J},T0(Q.o
Line truncated
`);return}if($==="install"||$==="init"||$==="sync"){let I=z0(U.options.local)||z0(U.options.workspace),Q=R(U.options.dir)??R(U.options.target)??Y,J=Q?Q:I?TE(process.cwd(),".agents","skills","seal-use"):rI(),K=Xg0(J),z=!I&&!Q,G=z?ao():void 0,H=z?$r():void 0;C0({installed:!0,targetDir:K.targetDir,fileCount:K.files.length,files:K.files,...G?{antigravity:G}:{},...H?{hosts:H}:{}});return}if($==="status"||$==="get"||!$){let I=rI(),Q=TE(process.cwd(),".agents","skills","seal-use"),J=to(),K=Yr();C0({global:{dir:I,installed:Hk0(TE(I,"SKILL.md"))},local:{dir:Q,installed:Hk0(TE(Q,"SKILL.md"))},antigravity:J,hosts:K});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}var Xk0=o(()=>{Ir();eq();L4();$4()});async function Zk0($,Y){if($==="config"){C0(await az(Y));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var qk0=o(()=>{aT();$4()});function Br($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let Y=$.toUpperCase().trim();if(Y==="APPROVE"||Y==="PASS")return"APPROVE";if(Y==="REJECT"||Y==="DENIED")return"REJECT";if(Y==="MANUAL"||Y==="ASSISTED")return"MANUAL";if(Y==="ERROR"||Y==="FAILED")return"ERROR";return Y}async function Vk0($){let{sourceCorp:Y,targetCorp:U,sourceClient:I,targetClient:Q,samples:J=10,dryRun:K=!1,pollIntervalMs:z=2000,timeoutMs:G=45000,snPrefix:H="REG_",fetchFn:W=fetch}=$;if(U.environment!=="test")throw new G4(`重放目标企业「${U.name}」(${U.id})的环境为「${U.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Y.id}<testCorpId>`);let X=await UU(Q),q=(Array.isArray(X.features)?X.features:[]).find((m)=>m?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,w=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,M=J*w;if(V<M)throw new G4(`测试企业「${U.name}」AI审批额度不足:当前剩余${V}点,本次回归抽样${J}笔需要约${M}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${U.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(V/w))})`);let F=await u4(I,{limit:J,status:"completed"}),N=Array.isArray(F.records)?F.records:[];if(N.length===0){let m=await u4(I,{limit:J});N=Array.isArray(m.records)?m.records:[]}if(N.length===0)throw new G4(`在母企业「${Y.name}」(${Y.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(N=N.slice(0,J),K){let m=N.map((t)=>{let $0=t.sourceDocumentSN??t.id,y=t?.result?.decision??t.aiDecision??t?.decision,p=Br(y),Y0=t?.result?.summary??t.aiSummary;return{sn:$0,sourceRecordId:t.id,prodDecision:p,prodSummary:Y0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:A1(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M},metrics:{sampleCount:m.length,successCount:m.length,failureCount:0,matchCount:m.length,flipCount:0,concordanceRate:1},flips:[],records:m}}let O=await Fp(Q,U,$.webhookSelector),D=[];for(let m of N){let t=Date.now(),$0=m.sourceDocumentSN??m.id,y=Br(m?.result?.decision??m.aiDecision??m?.decision),p=m?.result?.summary??m.aiSummary;try{let Y0=await W4(I,m.id),g=`${H}${$0}`,c=Vp(Y0,{snPrefix:H,docIdPrefix:H});await Lp(O.incomingDocumentWebhook.url,O.secret,c,W,j6(U.seal));let e=null,V0=Date.now();while(Date.now()-V0<G){await new Promise((X0)=>setTimeout(X0,z));let a=await u4(Q,{sourceDocumentSN:g,limit:1});if(a.records&&a.records.length>0){let X0=a.records[0];if(X0.status==="completed"||X0.status==="failed"){e=X0;break}}}if(!e){D.push({sn:$0,sourceRecordId:m.id,prodDecision:y,prodSummary:p,status:"FAILED",error:`测试租户单据审核超时(${Math.round(G/1000)}s未完成)`,durationMs:Date.now()-t});continue}let j0=Br(e?.result?.decision??e.aiDecision??e?.decision??(e.status==="completed"?"APPROVE":"ERROR")),A0=e?.result?.summary??e.aiSummary,R0=y===j0,r0=R0?"MATCHED":"FLIPPED",X1={sn:$0,sourceRecordId:m.id,prodDecision:y,prodSummary:p,testRecordId:e.id,testDecision:j0,testSummary:A0,status:r0,durationMs:Date.now()-t};if(!R0)X1.diff={from:y,to:j0,reasonDiff:A0&&p&&A0!==p?`生产:${p.slice(0,60)}...->测试:${A0.slice(0,60)}...`:void 0};D.push(X1)}catch(Y0){D.push({sn:$0,sourceRecordId:m.id,prodDecision:y,prodSummary:p,status:"FAILED",error:Y0 instanceof Error?Y0.message:String(Y0),durationMs:Date.now()-t})}}let P=D.filter((m)=>m.status==="MATCHED"||m.status==="FLIPPED"),T=D.filter((m)=>m.status==="MATCHED"),A=D.filter((m)=>m.status==="FLIPPED"),E=D.filter((m)=>m.status==="FAILED").length,C=T.length,i=A.length,x=C+i,h=x>0?C/x:0,b=i>0,n=b?"REGRESSIONS_DETECTED":"CLEAN",I0=!b&&E===0,k;try{let m=await UU(Q),$0=(Array.isArray(m.features)?m.features:[]).find((y)=>y?.code==="ai-approval");if(typeof $0?.balance==="number")k=$0.balance}catch{}return{ok:!b&&E===0,verdict:n,safeToPublish:I0,timestamp:A1(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M,balanceAfter:k},metrics:{sampleCount:D.length,successCount:P.length,failureCount:E,matchCount:C,flipCount:i,concordanceRate:Number(h.toFixed(4))},flips:A,records:D}}function Lk0($){let{sourceCorp:Y,targetCorp:U,verdict:I,safeToPublish:Q,metrics:J,quota:K,flips:z,records:G}=$,H=I==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":I==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",W=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${Y.name}」->测试靶场「${U.name}」`,`判定:${H}·准许发布:${Q?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${J.sampleCount}|一致通过:${J.matchCount}|决策翻转:${J.flipCount}|异常失败:${J.failureCount}`,`一致率:${(J.concordanceRate*100).toFixed(1)}%|消耗预估:${K.estimatedRequired}点(余量:${K.balanceBefore}${K.balanceAfter!==void0?` -> ${K.balanceAfter}`:""})`," "+"─".repeat(65)];if(z.length>0){W.push(`⚠️决策翻转清单(${z.length}笔单据在新规则下结果改变):`);for(let X of z)if(W.push(`•单据[${X.sn}]:原生产判定「${X.prodDecision}」➔测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)W.push(`理由差异:${X.diff.reasonDiff}`);W.push(" "+"─".repeat(65)),W.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(I==="CLEAN")W.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% 吻合,无任何意外误杀或漏判
Line truncated
`)}var Fk0=o(()=>{RP();X4();Jq()});async function Pr($,Y,U){let I=($??Y??"regression").toLowerCase();if(I==="regression"||I==="regress"||I==="matrix"){let Q=R(U.options.corp)??(Y&&Y!==I?Y:void 0),J=M1(Q),K=J,z=J;if(J.environment==="test"){z=J;let O=R(U.options["prod-corp"])??R(U.options.prod)??J.prodCorpId;if(!O)throw new G4(`测试企业「${J.name}」(${J.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${J.id}`);K=M1(O)}else{K=J;let O=R(U.options["test-corp"])??R(U.options.test)??J.testCorpId;if(!O)throw new G4(`生产企业「${J.name}」(${J.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${J.id}<testCorpId>`);z=M1(O)}let G=await P1(K),H=await P1(z),W=l0(U.options.samples)??l0(U.options.limit)??l0(U.options.n)??10,X=z0(U.options["dry-run"]),Z=z0(U.options["fail-on-flips"]),q=l0(U.options["poll-interval"])??2000,V=l0(U.options.timeout)??45000,w=R(U.options["sn-prefix"])??"REG_",M=R(U.options.webhook)??R(U.options.selector),F=await Vk0({sourceCorp:K,targetCorp:z,sourceClient:G,targetClient:H,samples:W,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:w,failOnFlips:Z,webhookSelector:M});if(!(z0(U.options.quiet)||z0(U.options.silent)))console.error(Lk0(F));if(C0(F),Z&&!F.ok)throw new G4(`回归测试发现${F.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new G4(`未知的test子命令:"${I}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}var wk0=o(()=>{p8();D4();L4();$4();i6();Fk0()});function EE($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var Mk0=o(()=>{eq()});import{existsSync as Yf1,mkdirSync as Uf1,readFileSync as If1,renameSync as Qf1,writeFileSync as Jf1}from"node:fs";import{homedir as Kf1}from"node:os";import{dirname as zf1,join as Gf1}from"node:path";import{spawn as Hf1}from"node:child_process";function Ok0(){let $=process.env[Wf1]?.trim();if($)return $;return Zf1}function Nk0($=Ok0()){if(!Yf1($))return null;try{let Y=If1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&typeof U.latestVersion==="string"&&typeof U.checkedAt==="string")return{...U,checkedAt:T8(U.checkedAt),...typeof U.publishedAt==="string"?{publishedAt:T8(U.publishedAt)}:{}};return null}catch{return null}}function IV($,Y=Ok0()){try{let U=zf1(Y);Uf1(U,{recursive:!0,mode:448});let I={checkedAt:$.checkedAt?T8($.checkedAt):A1(),latestVersion:$.latestVersion,publishedAt:$.publishedAt?T8($.publishedAt):void 0,releaseUrl:$.releaseUrl},Q=`${Y}.tmp.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;Jf1(Q,JSON.stringify(I,null,2),{mode:384}),Qf1(Q,Y)}catch{}}function Dk0($,Y=Xf1){if(!$||!$.checkedAt)return!0;let U=new Date($.checkedAt).getTime();if(Number.isNaN(U))return!0;return Date.now()-U>Y}function Ak0($){if(process.env.SEAL_DISABLE_BG_UPDATE==="1"||!1||process.env.CI)return!1;if(!$||!$.command)return!1;try{let Y=$.command,U=[...$.args??[],"update","check","--bg-save"];return Hf1(Y,U,{detached:!0,stdio:"ignore",env:{...process.env,SEAL_DISABLE_BG_UPDATE:"1"}}).unref(),!0}catch{return!1}}var Wf1="SEAL_USE_UPDATE_CACHE_FILE",Xf1=86400000,Zf1;var Tr=o(()=>{Zf1=Gf1(Kf1(),".config","seal-use","update-cache.json")});import{chmodSync as qf1,mkdirSync as Vf1,readdirSync as Lf1,realpathSync as Bk0,renameSync as Er,rmSync as Ff1,unlinkSync as Ck0,writeFileSync as Pk0}from"node:fs";import{basename as wf1,dirname as Mf1,isAbsolute as Of1,join as RE,relative as Nf1}from"node:path";import{spawn as Df1,spawnSync as K7}from"node:child_process";async function _k0($,Y={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Nr,version:Z1,launcher:$.launcher},I=Y.repo||process.env[Af1]?.trim()||process.env[Bf1]?.trim()||Rk0,Q=Y.targetVersion?.trim(),J=Q&&Q.toLowerCase()!=="latest"?Q:void 0;if(J){let D=J.replace(/^v/,""),P=yk0(D,Z1);if(P<0)if(!By&&Y.force);else{C0({updated:!1,currentVersion:Z1,targetVersion:D,mode:EE()?"binary":"source",message:!By?`Cannotdowngradeseal-usefromdevbuildv${Z1}toreleasev${D}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${Z1}toolderversionv${D}.Updatesmustbeforward-only.`});return}if(P===0&&!Y.force){C0({updated:!1,currentVersion:Z1,targetVersion:D,mode:EE()?"binary":"source",message:`seal-useisalreadyatversionv${Z1}.Use--forcetoreinstall.`});return}}if(Y.changelogOnly){let D=await CE(I,Y.limit??10);C0({currentVersion:Z1,totalQueried:D.length,releases:D.map((P)=>({version:P.version,tagName:P.tagName,publishedAt:P.publishedAt,author:P.author,releaseNotes:P.notes,releaseUrl:P.htmlUrl,isCurrent:P.version===Z1,isNewer:i5(P.version,Z1)}))});return}if(!EE()){if(Y.checkOnly){let P=await CE(I,30),T=P[0],A=T?.version??Z1,E=P.find((x)=>x.version===Z1),C=i5(A,Z1),i=P.filter((x)=>i5(x.version,Z1));if(T?.version)IV({latestVersion:T.version,publishedAt:T.publishedAt,releaseUrl:T.htmlUrl});if(Y.bgSave)return;C0({updated:!1,updateAvailable:C,currentVersion:Z1,currentVersionPublishedAt:E?.publishedAt,latestVersion:A,latestVersionPublishedAt:T?.publishedAt,behindCount:i.length,pendingReleases:i.map((x)=>({version:x.version,tagName:x.tagName,publishedAt:x.publishedAt,author:x.author,releaseNotes:x.notes,releaseUrl:x.htmlUrl})),releaseNotes:T?.notes??"",releaseUrl:T?.htmlUrl??"",mode:"source",message:"当前运行的是开发版。正式用户请安装正式版后使用 seal-use update。"});return}let D=sI(U).running;if(D)await J7("stop",U);try{jk0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(P){console.error(`⚠️开发版更新同步失败,继续刷新本地依赖:${PinstanceofError?P.message:String(P)}`)}if(jk0("bun",["install"],{cwd:$.appRoot}),D)await J7("start",U);C0({updated:!0,serviceRestarted:D,version:Z1,mode:"source"});return}if(Cf1())try{await Rf1($,Y,U,I,J);return}catch(D){console.error(`⚠️Homebrew自动更新失败,回退至原生二进制更新:${DinstanceofError?D.message:String(D)}`)}let K=Tf1(),z=Ef1(),G=await CE(I,30),H=J?G.find((D)=>D.version===J||D.tagName===J||D.tagName===`v${J}`)??await _E(I,J):G[0]??await _E(I);if(!H){C0({updated:!1,currentVersion:Z1,mode:"binary",message:`Failedtoqueryreleasesfromrepository'${I}'`});return}let W=H.version,X=G.find((D)=>D.version=
Line truncated
`)}catch{}}async function Sf1($,Y,U,I){let Q=jr(),J=[],K=U?U.startsWith("v")?U:`v${U}`:void 0,z=I||$.split("/").pop()||"";if(Q!=="github"){if(K&&z)J.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${K}/${z}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${K}/${z}`);if($.startsWith("https://git.ying-qing.cn"))J.push($)}if(Q!=="gitea")if(K&&z){let w=`https://github.com/${Rk0}/releases/download/${K}/${z}`;if(!process.env.CI)J.push(`https://ghfast.top/${w}`,`https://gh.ddlc.top/${w}`);J.push(w)}else if($.includes("github.com")){if(!process.env.CI)J.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);J.push($)}else J.push($);let G=Array.from(new Set(J)),H,W=6000,X=6000,Z=307200,q=1e4,V=180000;for(let w=0;w<G.length;w++){let M=G[w],F=new AbortController,N="",O=(A)=>{N=A;try{F.abort()}catch{}},D=setTimeout(()=>{O("Connection timed out (no response headers within 6s)")},W),P,T;try{jE(`==> [${w+1}/${G.length}] Downloading via: ${M}`);let A=await fetch(M,{signal:F.signal});if(D)clearTimeout(D),D=void 0;if(!A.ok)throw Error(`HTTP ${A.status} ${A.statusText}`);P=setTimeout(()=>{O("Overall download time exceeded 3 minutes")},V);let E=Number(A.headers.get("content-length"))||0,C=A.body?.getReader();if(!C){let n=Buffer.from(await A.arrayBuffer());if(n.length<1000)throw Error(`Downloaded content is suspiciously small (${n.length} bytes)`);Pk0(Y,n),jE(`✓ Download succeeded (${(n.length/1024/1024).toFixed(1)} MB)`);return}let i=[],x=0,h=0;T=setTimeout(()=>{if(x<Z){let n=(x/1024).toFixed(1);O(`Initial transfer too slow (${n} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let n=C.read(),I0,k=new Promise((y,p)=>{I0=setTimeout(()=>{p(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),m;try{m=await Promise.race([n,k])}finally{if(I0)clearTimeout(I0)}let{done:t,value:$0}=m;if(t)break;if($0){if(i.push($0),x+=$0.length,T&&x>=Z)clearTimeout(T),T=void 0;let y=Date.now();if(y-h>200){h=y;let p=E?Math.round(x/E*100):0,Y0=(x/1048576).toFixed(1),g=E?(E/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${p}% (${Y0} / ${g} MB)...`)}catch{}}}}try{process.stderr.write(`
"description":"HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n"
description:"v0.10.38: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description:"v0.10.40: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version:0.10.38
short-description:Seal tenant and Hose approval automation (v0.10.38)
version:0.10.40
short-description:Seal tenant and Hose approval automation (v0.10.40)
Return and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.
Return and discuss `code`, `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.
If 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`.
If the user then wants the full text of one cited rule from that run's snapshot, use `seal-use rules get <code> --record-id <recordId> --corp <corpId>` from `rule-lightweight.md`.
@@ -217,7 +223,7 @@ Use the command groups in this order for normal work: **enterprise onboarding**
-`seal-use corps add-hose-web-session --json '{"baseUrl":"https://wx2.ekuaibao.com","corpId":"...","staffId":"...","accessToken":"..."}'` imports a normalized Hose web session (for example, parsed from a Hose admin cURL), saving the Hose `closeToken` and personnel ID. Seal Bearer is exchanged only at runtime; this command does not create or save OpenAPI `appKey/appSecurity` credentials.
-`seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"..."}'` registers and persists a Hose enterprise from durable OpenAPI credentials.
Durable Hose configs are identified by `source.type: "hose"` plus `appKey/appSecurity`; Hose Web Session configs use the same source type with `closeToken + staffId`. When the session material includes an expiry, it is recorded as `expiresIn` (TTL seconds) and `expiresAt` (UTC without milliseconds, for example `2026-09-22T05:30:00Z`).
Durable Hose configs are identified by `source.type: "hose"` plus `appKey/appSecurity`; Hose Web Session configs use the same source type with `closeToken + staffId`. When the session material includes an expiry, it is recorded as `expiresIn` (TTL seconds) and `expiresAt` (Beijing ISO 8601 without milliseconds, for example `2026-09-22T13:30:00+08:00`).
-`seal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--strict] [--corp <corpId>]` (defaults to displaying the top 10 most frequently used enterprises in the last 7 days; sorting is automatic and query results keep relevance order)
-`seal-use corps search <query> [--env <production|test>] [--strict]` (intelligent soft search by default: case-insensitive, Chinese homophones, front/back nasal vowels, flat/retroflex consonants, initials, typo/missing letter tolerance; pass `--strict` for exact substring match)
-`seal-use corps get <corpId>` (rich enterprise attributes with sensitive secrets safely redacted)
-`seal-use rules list --summary [--corp <corpId>]`
-`seal-use rules diff <fromVersion> <toVersion> [--rule-id <stableRuleId>|--code <code>] [--include-unchanged] [--full] [--corp <corpId>]` (uses a locally persisted stable ID map when available, otherwise falls back to code, and returns structured changes plus a Git-style `unifiedDiff`; oversized output is truncated only when it exceeds the safety limit)
-`seal-use rules diff-one <fromVersion> <toVersion> <ruleId> [--full] [--corp <corpId>]` (single-rule view; use `--code` with `rules diff` for snapshots without stable IDs)
-`seal-use rules version <versionNumber|latest> [--corp <corpId>]`
-`seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]` (returns structured changes plus a Git-style `unifiedDiff`; oversized output is truncated only when it exceeds the safety limit)
-`seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: `~/.config/seal-use/linters` and `official/`)
-`seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
-`seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
Rule identity and versioning (Draft by default vs. `--version latest`):
-`rules list` and `rules pull` read the current **draft**rule set. Their `code` values belong to the draft code space.
-A published version has its own snapshot and code space. Publishing can recode rules, so a published `code` may differ from the draft `code`, and codes can shift again after later edits and publishes.
-Published snapshots currently omit stable IDs. The publish flow therefore persists a local code-to-draft-ID map under `~/.config/seal-use/rule-version-snapshots/`; `rules diff` hydrates that map when available and otherwise matches by normalized code. Code fallback can make reorderings look like remove/add or modified rules, and the response includes a confidence warning.
-`rules get <ruleCode> --version ...` interprets the rule number inside that selected published version, while `rules get --record-id ... --runtime-id ...` resolves the version recorded on the run. The legacy `--code` form remains accepted for compatibility.
-**Default = Current Draft**: Whenever `--version` is omitted, `rules count`, `rules list`, `rules get <code>`, `rules search`, `rules lint`, and `rules pull`**always read the current draft**.
-**Latest Published Version = `--version latest`**: To inspect the latest published version, you **must explicitly pass `--version latest`** (or `--version <number>` for a specific historical version, or `rules version latest` for the full version snapshot).
-In Seal, every rule has a 4-digit zero-padded `code` (`0000, 0001, 0025, 0038, ...`).
-A published version has its own snapshot and `code` space. Publishing or deleting rules can shift `code` numbers across versions, so always pair `code` with `--version` or `--record-id` when inspecting historical approval runs.
Approval run lightweight queries:
@@ -304,15 +317,16 @@ Approval run lightweight queries:
A **Webhook resource pack** (webhook 资源包 / 资源包, CLI: `resource-pack`, alias: `pack`, legacy alias: `material-pack`) is a ZIP file that bundles an Excel information sheet (`信息表.xlsx`) with attachments organised by document ID. It is designed for exporting online approval runs and transferring them offline across environments or teams to be replayed via inbound Webhooks.
> **Note**: This is distinct from Seal backend's native simulation "材料包" (`simulation material_pack` / `/api/v1/material-packages/upload`). Calling this standard "Webhook 资源包" avoids confusion.
### ZIP structure convention
```
资源包.zip
├── 信息表.xlsx ← must exist at ZIP root
├── BX20260826003/ ← root dir name = documentId (or documentId@annotation)
│ ├── 合同协议/
│ │ └── 采购合同.pdf
│ └── 支付凭证/
│ └── 支付宝交易明细.pdf
└── BX20260826004@重新提交v2/ ← @annotation is stripped when matching documentId
└── 发票/
└── 增值税专用发票.pdf
```
- The root directory name **must equal** the `documentId`**OR** start with `documentId@` (the `@` separates an optional annotation ignored during matching).
-`信息表.xlsx` at the ZIP root is the only file not associated with any document directory.
- Documents without attachments do not require a directory entry in the ZIP.
### Excel column convention
| Column type | Naming | Purpose |
|---|---|---|
| Regular column | Any header (e.g. `会议编号`, `总金额`, `报销事由`) | Standard document fields |
| Attachment column | Header starts with `[附件]` (e.g. `[附件]合同协议`, `[附件]发票`) | Declares attached files for this row |
- The `[附件]` prefix is stripped to produce the field `label` sent to Seal.
- The cell value contains full ZIP-relative path(s) to the declared files (multiple paths separated by newline, comma, or semicolon).
- Example: column `[附件]合同协议`, cell value `BX20260826003/合同协议/采购合同.pdf`
Before pushing or previewing, the system enforces:
1.**Excel → ZIP**: Every path declared in an `[附件]` column cell **must** exist as a ZIP entry. Error: `Excel 声明的附件路径在 ZIP 中不存在: <path>`
2.**ZIP → Excel**: Every ZIP file (excluding `信息表.xlsx`) **must** be declared in exactly one `[附件]` column. Error: `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>`
3.**Document Directory Scope Isolation**: All attachments declared for a document `DOC_X`**must** reside in its own root directory (`DOC_X/` or `DOC_X@annotation/`). Cross-document references are strictly forbidden. Error: `单据「X」声明了跨单据或非本单据目录的附件路径: <path>。附件必须位于该单据自己的根目录...`
4.**Strict Declaration Uniqueness**: A given ZIP file path **cannot** be declared more than once across the entire resource pack (even within the same document across multiple rows or fields). If the same logical document is needed in multiple places, separate files must be placed in distinct paths. Error: `附件路径「<path>」被重复声明了 N 次...`
5.**Attachment file policy**: Every attachment except the root `信息表.xlsx` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: `附件文件过小...` / `附件文件过大...` / `附件后缀不在白名单中...`
6.**documentId ↔ ZIP root**: Every `documentId` in the Excel main sheet that declares attachments must have a matching ZIP root dir (exact match or `documentId@annotation`), and every ZIP root dir must match a declared `documentId`. Errors: `Excel 会议编号「X」在 ZIP 中找不到对应的根目录...` / `ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号`
All validation errors are collected and reported together in a single `MaterialPackValidationError`.
### CLI usage
```bash
# Export online approval records to a local Webhook resource pack ZIP
# When there is exactly one webhook channel, --webhook can be omitted (auto-locked)
```
### Attachment file policy configuration
The policy is stored per inbound Webhook integration and is applied before any attachment upload or document push. A failed check stops the entire material-pack flow. The policy is intentionally mutable: after an authorized configuration change, retrying the same push reads the saved policy again.
`null` or an omitted `maxFileSizeBytes` means no per-file upper bound. Values are bytes; a file smaller than the minimum or larger than the maximum fails. Extensions are normalized case-insensitively and may be written with or without the leading dot. The root `信息表.xlsx` remains exempt from attachment policy checks.
```bash
# New Webhook: use the default 500-byte minimum and default extension whitelist
The saved configuration is returned by `webhook get`/`webhook list` under `materialPackFilePolicy`. The root `信息表.xlsx` is always allowed as the material-pack manifest and is not subject to the attachment policy.
### Failure recovery loop
When a push fails because of the attachment policy, the error is actionable and should be handled as a two-channel recovery loop:
1. Error channel: read `附件文件过小`, `附件文件过大`, or `附件后缀不在白名单中`, including the attachment path and the configured boundary.
2. Resolution channel: ask whether the user wants to replace/compress the file or explicitly allow the format/size by changing the target Webhook policy.
3. If configuration change is authorized, read the current policy with `webhook get`/`webhook list`, update only the necessary fields, and verify the returned configuration.
4. Retry the original `material-pack push`; it will load the latest saved policy before any upload begins.
The same loop is available through the internal tool registry: read with `seal-use tool seal_webhook_get`/`seal_webhook_list`, update with `seal-use tool seal_webhook_update` and its `materialPackFilePolicy` patch, then retry `seal-use tool seal_webhook_material_pack` in `push` mode. Over MCP these run through `seal_cli` (reads) or `seal_cli_write` (the update and push, which need user confirmation); no separate `seal_webhook_*` MCP tool exists. Set `maxFileSizeBytes` to `null` to clear the upper bound. `allowedExtensions` is a complete replacement list, so include existing allowed suffixes when adding one.
If the assistant lacks permission to update the Webhook or the user does not authorize relaxing the rule, report the block rather than bypassing validation. Since validation happens before the upload loop, a failed attempt does not leave a partially pushed material pack.
The direct local `material-pack preview` command and the tool-registry preview use the default or temporary policy. They do not automatically read a selected Webhook's persisted policy. Use `webhook ready --file --webhook <idOrName>` or the actual push path when validating against the saved inbound policy.
### Error messages reference
| Error message | Meaning | Fix |
|---|---|---|
| `Excel 声明的附件路径在 ZIP 中不存在: <path>` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |
| `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>` | ZIP contains a file not referenced by any `[附件]` column | Add an `[附件]` column entry or remove the file from ZIP |
| `单据「X」声明了跨单据或非本单据目录的附件路径: <path>` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |
| `附件路径「<path>」被重复声明了 N 次` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |
| `Excel 会议编号「X」在 ZIP 中找不到对应的根目录` | No ZIP root dir matches documentId `X` | Rename the ZIP folder to match the documentId |
| `ZIP 根目录对应的编号「X」在信息表中找不到` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |
| `ZIP 根目录缺少信息表.xlsx` | No `信息表.xlsx` found at ZIP root | Add the Excel file to the ZIP root |
| `附件文件过小` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower `--min-file-size` |
| `附件文件过大` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise `--max-file-size` |
| `附件后缀不在白名单中` | Attachment extension is not allowed by the Webhook policy | Add the extension with `--allowed-extensions` or convert the file |
| `附件上传失败 <status>` | Network/server error during file upload | Check webhook URL, secret, and server availability |
## 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.
Do not send`scope` or `strictness` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing.
Do not pass`--scope` or `--strictness` when they are unchanged. Fetch the draft again (`seal-use rules get <code> --corp <corpId>`) and verify the exact description, scope, strictness, and draft status before publishing.
For a complete local rule-set sync, `rules push` is incremental: it matches pulled rules by stable `id`, updates only changed fields, creates new entries, and removes entries omitted from the local file. It preserves matched rule IDs and does not recode the whole draft. Preview it with `rules push --dry-run` before applying.
@@ -188,8 +187,7 @@ For a complete local rule-set sync, `rules push` is incremental: it matches pull
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.
Use this reference when the user wants rule counts, compact rule lists, one rule from draft or a historical version, or approval rule search without dumping hundreds of rule descriptions.
## Draft and Published Rule Codes
## Draft Default vs. Published Version (`--version latest`)
`rules list` and `rules pull` operate on the current draft and therefore return draft `code` values. A published version stores a separate snapshot and may recode the same rules; publishing, deleting, or reordering rules can make those published codes differ or drift again. A code such as `#0038` is only meaningful together with its version context.
Every rule has a 4-digit zero-padded `code` (`0000, 0001, 0025, 0038, ...`).
Use the draft `id` for current edits and use the approval run's recorded version plus rule text or runtime rule ID for historical investigations. Do not copy a draft code into a report or command that will be interpreted against a published version.
- **Default = Current Draft (`草稿`)**: When `--version` is omitted, `rules count`, `rules list`, `rules get <code>`, `rules search`, `rules lint`, and `rules pull`**all read the current draft**.
- **Latest Published Version = `--version latest` (`最新发布`)**: To inspect the latest published version, **always pass `--version latest`** (or `--version <number>` for a specific historical version).
- Publishing or deleting rules can shift `code` numbers across versions, so a `code` in a historical run must be resolved together with `--version <number>` or `--record-id <recordId>`.
seal-use rules list --version latest --summary --corp <corpId>
```
Default summary should include only fields such as `id`,`code`, `scope`, `strictness`, `status`, and `updatedAt`. Do not pull `description` unless the user needs rule text.
Default summary includes`code`, `status`, `strictness`, `scope`, and `updatedAt`. Do not pull full `description` fields across all rules unless the user needs rule text.
Tool-layer equivalent:
## Get One Rule (Draft or Published Version)
Read a single rule from the current draft (default):
Read a single rule from the latest published version, a specific published version, or the version used by an approval run:
```bash
seal-use rules get 0038 --version latest --corp <corpId>
seal-use rules get 0038 --version 16 --corp <corpId>
seal-use rules get 0205 --record-id <recordId> --corp <corpId>
```
Returns `id`, `code`, `ruleCode`, `runtimeRuleId`, `description`, `scope`, `strictness`, `status`, and version metadata when reading from a published version.
Use this for test tenants when the next step is importing another tenant's rule set. Always preview first unless the user has already confirmed the exact tenant.
Use this when a run used a historical rule version and current rules may differ.
```bash
seal-use rules get '#0038' --corp <corpId> --version 16
seal-use rules get '#0038' --corp <corpId> --version latest
```
If the user starts from a run and a runtime ID such as `rule-205`, resolve against that run:
```bash
seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
```
Return the single rule text plus `scope`, `strictness`, `status`, `versionNumber`, and version metadata. Avoid commands that dump a whole rule version unless the user asks for the full version.
Use current search only when the question is about current draft/current knowledge, not why a historical run behaved a certain way.
## 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.
If a rule command would return many descriptions or more than about 20 rules, use `rules count`, `rules list --summary`, `rules search`, or `--output-file`. Use `--full` only for deliberate exports.
@@ -7,7 +7,7 @@ Use this reference when analyzing, validating, or linting Seal AI approval rules
- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled: false`) to avoid unsolicited noise during standard operations.
- **Doctor Visibility**: `seal-use doctor` audits the rule linter configuration state and active linter name in its health checks, and surfaces a one-click hint (`seal-use config lint enable`) when disabled.
- **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.
- **Draft Hook**: When `seal-use config lint enable` is set, `seal-use rules 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**.
A **Webhook resource pack** (webhook 资源包 / 资源包, CLI: `resource-pack`, alias: `pack`, legacy alias: `material-pack`) is a ZIP file that bundles an Excel information sheet (`信息表.xlsx`) with attachments organised by document ID. It is designed for exporting online approval runs and transferring them offline across environments or teams to be replayed via inbound Webhooks.
> **Note**: This is distinct from Seal backend's native simulation "材料包" (`simulation material_pack` / `/api/v1/material-packages/upload`). Calling this standard "Webhook 资源包" avoids confusion.
### ZIP structure convention
```
资源包.zip
├── 信息表.xlsx ← must exist at ZIP root
├── BX20260826003/ ← root dir name = documentId (or documentId@annotation)
│ ├── 合同协议/
│ │ └── 采购合同.pdf
│ └── 支付凭证/
│ └── 支付宝交易明细.pdf
└── BX20260826004@重新提交v2/ ← @annotation is stripped when matching documentId
└── 发票/
└── 增值税专用发票.pdf
```
- The root directory name **must equal** the `documentId`**OR** start with `documentId@` (the `@` separates an optional annotation ignored during matching).
-`信息表.xlsx` at the ZIP root is the only file not associated with any document directory.
- Documents without attachments do not require a directory entry in the ZIP.
### Excel column convention
| Column type | Naming | Purpose |
|---|---|---|
| Regular column | Any header (e.g. `会议编号`, `总金额`, `报销事由`) | Standard document fields |
| Attachment column | Header starts with `[附件]` (e.g. `[附件]合同协议`, `[附件]发票`) | Declares attached files for this row |
- The `[附件]` prefix is stripped to produce the field `label` sent to Seal.
- The cell value contains full ZIP-relative path(s) to the declared files (multiple paths separated by newline, comma, or semicolon).
- Example: column `[附件]合同协议`, cell value `BX20260826003/合同协议/采购合同.pdf`
Before pushing or previewing, the system enforces:
1.**Excel → ZIP**: Every path declared in an `[附件]` column cell **must** exist as a ZIP entry. Error: `Excel 声明的附件路径在 ZIP 中不存在: <path>`
2.**ZIP → Excel**: Every ZIP file (excluding `信息表.xlsx`) **must** be declared in exactly one `[附件]` column. Error: `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>`
3.**Document Directory Scope Isolation**: All attachments declared for a document `DOC_X`**must** reside in its own root directory (`DOC_X/` or `DOC_X@annotation/`). Cross-document references are strictly forbidden. Error: `单据「X」声明了跨单据或非本单据目录的附件路径: <path>。附件必须位于该单据自己的根目录...`
4.**Strict Declaration Uniqueness**: A given ZIP file path **cannot** be declared more than once across the entire resource pack (even within the same document across multiple rows or fields). If the same logical document is needed in multiple places, separate files must be placed in distinct paths. Error: `附件路径「<path>」被重复声明了 N 次...`
5.**Attachment file policy**: Every attachment except the root `信息表.xlsx` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: `附件文件过小...` / `附件文件过大...` / `附件后缀不在白名单中...`
6.**documentId ↔ ZIP root**: Every `documentId` in the Excel main sheet that declares attachments must have a matching ZIP root dir (exact match or `documentId@annotation`), and every ZIP root dir must match a declared `documentId`. Errors: `Excel 会议编号「X」在 ZIP 中找不到对应的根目录...` / `ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号`
All validation errors are collected and reported together in a single `MaterialPackValidationError`.
### CLI usage
```bash
# Export online approval records to a local Webhook resource pack ZIP
# When there is exactly one webhook channel, --webhook can be omitted (auto-locked)
```
### Attachment file policy configuration
The policy is stored per inbound Webhook integration and is applied before any attachment upload or document push. A failed check stops the entire material-pack flow. The policy is intentionally mutable: after an authorized configuration change, retrying the same push reads the saved policy again.
`null` or an omitted `maxFileSizeBytes` means no per-file upper bound. Values are bytes; a file smaller than the minimum or larger than the maximum fails. Extensions are normalized case-insensitively and may be written with or without the leading dot. The root `信息表.xlsx` remains exempt from attachment policy checks.
```bash
# New Webhook: use the default 500-byte minimum and default extension whitelist
The saved configuration is returned by `webhook get`/`webhook list` under `materialPackFilePolicy`. The root `信息表.xlsx` is always allowed as the material-pack manifest and is not subject to the attachment policy.
### Failure recovery loop
When a push fails because of the attachment policy, the error is actionable and should be handled as a two-channel recovery loop:
1. Error channel: read `附件文件过小`, `附件文件过大`, or `附件后缀不在白名单中`, including the attachment path and the configured boundary.
2. Resolution channel: ask whether the user wants to replace/compress the file or explicitly allow the format/size by changing the target Webhook policy.
3. If configuration change is authorized, read the current policy with `webhook get`/`webhook list`, update only the necessary fields, and verify the returned configuration.
4. Retry the original `material-pack push`; it will load the latest saved policy before any upload begins.
Use `--clear-max-file-size` on `seal-use webhook update` to remove the upper bound. `--allowed-extensions` is a complete replacement list, so include existing allowed suffixes when adding one.
If the assistant lacks permission to update the Webhook or the user does not authorize relaxing the rule, report the block rather than bypassing validation. Since validation happens before the upload loop, a failed attempt does not leave a partially pushed material pack.
The direct local `resource-pack preview` command uses the default or temporary policy. It does not automatically read a selected Webhook's persisted policy. Use `seal-use webhook ready <资源包.zip> --webhook <idOrName>` or the actual push path when validating against the saved inbound policy.
### Error messages reference
| Error message | Meaning | Fix |
|---|---|---|
| `Excel 声明的附件路径在 ZIP 中不存在: <path>` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |
| `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>` | ZIP contains a file not referenced by any `[附件]` column | Add an `[附件]` column entry or remove the file from ZIP |
| `单据「X」声明了跨单据或非本单据目录的附件路径: <path>` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |
| `附件路径「<path>」被重复声明了 N 次` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |
| `Excel 会议编号「X」在 ZIP 中找不到对应的根目录` | No ZIP root dir matches documentId `X` | Rename the ZIP folder to match the documentId |
| `ZIP 根目录对应的编号「X」在信息表中找不到` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |
| `ZIP 根目录缺少信息表.xlsx` | No `信息表.xlsx` found at ZIP root | Add the Excel file to the ZIP root |
| `附件文件过小` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower `--min-file-size` |
| `附件文件过大` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise `--max-file-size` |
| `附件后缀不在白名单中` | Attachment extension is not allowed by the Webhook policy | Add the extension with `--allowed-extensions` or convert the file |
| `附件上传失败 <status>` | Network/server error during file upload | Check webhook URL, secret, and server availability |
description:"Query, search, version, lint, import, and export approval audit rules.",
description:"Query, search, edit, publish, version, lint, import, and export approval audit rules. Read commands default to the current draft; pass --version latest (or --version <number>) to inspect published versions.",
commands:[
{
name:"count",
summary:"Count total rules in current enterprise",
usage:["seal-use rules count [--corp <corpId>]"]
summary:"Count approval rules (defaults to current draft; pass --version latest for latest published version)",
{flag:"--rule-id <id>",description:"Compare only one stable rule ID"},
{flag:"--code <code>",description:"Compare only one rule code when stable ID mapping is unavailable"},
{flag:"--code <code>",description:"Compare only one rule code"},
{flag:"--include-unchanged",description:"Include unchanged rules in the structured changes list"},
{flag:"--full",description:"Expand an oversized diff; small diffs are returned in full by default"},
{flag:"--format unified|json",description:"Return unified diff text together with structured metadata"}
],
description:"Uses locally persisted draft IDs when available and otherwise falls back to code. Output is truncated only when the total diff exceeds the safety limit; use --full to expand it."
thrownewError("Auto-login (--auto-login) is only supported for Seal AI audit links (type: seal-result). To generate an auto-login link for Hose document page, please use: seal-use auth hose-link");
}
if(source.type!=="hose"){
thrownewError(
`Auto-login direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use auth link' for authorized access.`
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.