ci.yml triggered on push/pull_request for both main and master. master does
not exist on the remote (GitHub's default is main, and the stale remote branch
was deleted), so that filter could never match.
Left alone deliberately: AGENTS.md and bump-version.ts referring to
codex/release-vX.Y.Z, which describe the naming pattern for future release
branches rather than a specific existing one.
`872b617` removed the in-repo `.agents/skills/seal-use` symlink, but two docs
still described it as present, so the repository's own instructions
contradicted the tree:
- AGENTS.md claimed the symlink exists "so workspace and Codex skill loading
keep working". It is gone; loading now uses the global
~/.agents/skills/seal-use copy installed by `seal-use skill install`.
- README.md told readers the symlink mirrors `skills/seal-use`, and pointed
them at a path that no longer resolves.
No code or test depended on the removed path — verified by grepping src/ and
scripts/, which only ever reference the global `~/.agents/skills/seal-use`.
plugin-migration-plan.md also mentions the symlink, but it is a historical
record of that migration and is left as-is.
The read-only MCP tool refused three verbs that only query:
approval-runs search, pick and bridge. #117's changelog claimed pick had
'moved into read-only', which was true of the tool registry but not of the CLI
allow-list — the two are hand-maintained in different files and had drifted.
Adds the missing entries, and a test that derives the pairing mechanically:
every 'action === "x"' in src/cli/commands/* that dispatches to a
runTool("seal_...") must be read-only when the tool it reaches is read-only.
It asserts a minimum number of pairs so a change in dispatch shape cannot make
it silently vacuous, and names its exceptions explicitly — the deploy
<action> short forms (rejected at runtime, so unreachable) and
approval-runs search (an accepted alias of list with no registry row).
Half of these were found by that check rather than by reading the code.
The committed MCP bundle is the only thing that ships, but nothing checked
that it matched src/. The gate could not be added while CI ran
'bun-version: latest': that resolved to 1.4.2, and the minifier allocates
identifiers differently across Bun releases, so the runner rebuilt the
macOS/1.3.14-built bundle into different bytes — identical code, renamed
variables (N/S, A/I, q/p). Measured on #116.
Pin bun-version to 1.3.14 in both workflows, matching the local toolchain and
the @types/bun/bun-types already declared in package.json, then add the diff
gate alongside the existing boot check.
The boot check stays: a bundle that cannot start is invisible to a byte diff
when it is in sync with its broken source, which is exactly how #114 shipped.
The read-only MCP tool refused the whole `seal-use tool <name>` area, because
the 98-entry internal tool registry had no read/write classification. Now it
does: SEAL_READ_ONLY_TOOLS (66) and SEAL_MUTATING_TOOLS (32), exported from
src/domains/seal/tools.ts, with the policy delegating `tool` to them.
The two sets are exhaustive by construction — a test asserts they partition
sealTools exactly — so a newly added tool fails the suite until it is
classified, rather than silently defaulting into one bucket.
Classifying by inspection was not enough. Cross-checking mechanically (every
exported function in src/domains/seal that performs a mutating HTTP call,
mapped to the tools that invoke it) caught a real mistake shipped in #115:
`analytics analyze` was allow-listed as read-only, but it calls
seal_insight_record_analyze, which issues a POST and starts an analysis
server-side. Removed from the CLI allow-list; a comment records why it is
absent, since the name reads like a query.
`approval-runs pick` went the other way into read-only: it dispatches to
seal_approval_run_pick, which is a query over approval runs rather than a
local-state mutation.
Read-only means: reads tenant state, or writes only a local file. Anything
that creates, updates, deletes, publishes, pushes, replays, uploads, activates
or mints a credential counts as mutating. `seal_webhook_material_pack` is
mutating because push mode sends the pack even though preview mode does not;
`seal_approval_runs_export` and `seal_insight_export` are read-only because
they only write a local workbook.
CI disproved the freshness gate on the first run: an ubuntu rebuild of the
macOS-built committed dist/mcp/server.js differs, and the diff is entirely
minified identifier renaming (N->S, A->I, q->p) with identical code. The
minifier does not allocate names reproducibly across platforms and Bun
versions, so a byte-for-byte gate cannot work here without pinning the
toolchain and matching runners.
Keep the check that does hold: boot the freshly built bundle and complete an
MCP handshake. Booting is what #114 actually needed — the byte diff would not
have caught that bug either, since the broken bundle was in sync with its
broken source.
The committed bundle is the only thing that ships, but CI only checked that
it compiled — never that it matched src/, and never that it could start.
- Fail when a fresh build differs from the committed dist/mcp/server.js,
mirroring the existing dist/openapi.json gate, with the same actionable
error. This is viable now: the bundle is byte-reproducible with the current
toolchain (a rebuild of the committed file is byte-identical). Before the
#114 rebuild it was not, which is why this was previously left out.
- Keep booting the freshly built bundle through a handshake, since a bundle
that cannot start is invisible to source-level tests.
seal_cli could reach every CLI command, so its tool annotations had to be
all-or-nothing: destructiveHint true on a tool that mostly reads, which meant
clients could not auto-approve anything, and there was no way to gate the
mutating minority. Split it in two:
- seal_cli read-only, readOnlyHint true / destructiveHint false.
- seal_cli_write mutations, publishing, credential minting, self-update and
server commands; destructiveHint true.
The boundary is enforced rather than advertised. seal_cli runs only commands
on an explicit allow-list (84 entries, src/cli/read-only.ts) and fails closed
on anything unclassified, including commands added to the CLI later. Matching
reuses the CLI's own parseArgs and compares whole tokens, so a read prefix
cannot smuggle a mutation (corps listing is refused) and a bare allow-listed
command does not cover its subcommands. Refusals name seal_cli_write.
Deliberately excluded from the read-only set even though they look harmless:
anything writing local config (corps switch, config test-dir), minting or
printing credentials (auth keys, corps extract-keys), self-updating (update),
or standing up a long-running server (http, mcp, service run). seal-use
tool <name> is excluded too, since the 98-entry internal tool registry is not
itself classified.
A test asserts every allow-listed command still exists in the help registry,
so the list cannot silently rot.
Also, per the note that MCP is an optional, default-off path, the skill now
says so explicitly: the CLI is primary, a missing seal_cli* tool is the normal
default rather than a fault, and enabling it is the user's choice in the plugin
settings. Corrected skill docs that presented internal tool-registry names
(seal_webhook_get, seal_webhook_update, ...) as if they were MCP tools; the MCP
server exposes only the two seal_cli* tools.
CI: the MCP build step now boots the freshly built bundle and completes a
handshake, instead of only checking that it compiles. A bundle that cannot
start is invisible to source-level tests, which is how the previous unbootable
entry point shipped. No byte-for-byte dist diff gate here: the committed
bundle is not byte-reproducible with the current toolchain (~186 lines of drift
rebuilding the unmodified release commit), and such a gate would not have
caught that bug anyway, since the broken bundle was in sync with its source.
The plugin ships dist/mcp/server.js as its MCP entry point, and that bundle
could not start at all: it threw "TypeError: ... is not a constructor" while
loading and never answered a request. MCP defaults to off, so enabling it
produced no seal_cli tool and no visible error.
Root cause: src/server.ts is circularly entangled with the CLI command graph
(server -> cli/runner -> cli/commands/mcp -> server, and
server -> cli/runner -> cli/commands/http -> http/routes -> server). When
bun build --target=node flattened that cycle together with zod's own
core <-> classic cycle, zod's class initialisers landed after the top-level
z.lazy() call the SDK makes at import time, leaving ZodLazy undefined.
Not fixable by changing targets: --target=bun, --compile, and dropping
--minify all fail the same way. Only removing the cycles fixes it.
- Moved tokenizeCommand / normalizeCliArgs to a leaf module (src/cli/tokenize.ts)
and made the mcp command import the server lazily, removing both cycles.
- Added a test that boots the packaged bundle over stdio and completes a
handshake; the existing tests exercise source, not the shipped artifact,
which is why this went unnoticed. Verified it fails on the old bundle.
- Committed the rebuilt dist/mcp/server.js, since the previously committed
artifact is the broken one.
Also migrated the monolithic @modelcontextprotocol/sdk v1 to the v2 split
packages (@modelcontextprotocol/server for the server,
@modelcontextprotocol/client for tests):
- Low-level Server + setRequestHandler -> high-level McpServer + registerTool;
hand-written JSON Schema -> z.strictObject (still emits
additionalProperties: false).
- Added the title and annotations clients could not previously see:
readOnlyHint false, destructiveHint true, idempotentHint false,
openWorldHint true. seal_cli is a passthrough that can reach mutating verbs,
so it must not be advertised as safe to auto-run or safe to retry; the
description now names the command families needing user confirmation.
- startServer uses serveStdio, which owns protocol-era negotiation
(2025-era clients keep working) and teardown.
- .mcp.json uses the ZCode-native ${ZCODE_PLUGIN_ROOT}; verified in ZCode's
resolver that CLAUDE_PLUGIN_ROOT and ZCODE_PLUGIN_ROOT are the same alias.
Dropping the v1 SDK removes express, hono, cors and ajv from the dependency
graph (bun.lock -149 lines).
`approval-runs export` returned a bare audit-drift counter with no way to
trace it back to a document: no sourceDocumentSN, no recordId, no reason.
Interpreting it required a separate per-document `approval-runs flow`
query, and the word "drift" alone suggested the tool or the approval flow
was broken rather than a snapshot/lifecycle difference.
The drift itself is already visible in the workbook row: AI 决策「通过」
next to 人工审核「已取消」 and E人工行为「已撤回」, with the retraction
recorded in the standard formatted E人工意见 column. The aggregate carried
no information those columns do not.
`seal_approval_runs_export` never enabled flow alignment, so for MCP
consumers the field was a constant 0.
Rather than enriching the field, remove it. Per-run auditDrift and
auditDriftReason in `approval-runs flow` are unchanged.
git diff --exit-code dist/mcp/server.js || (echo "::error::dist/mcp/server.js is out of sync with src/. Run 'bun run build:plugin' and commit changes." && exit 1)
# Boot the freshly built bundle and complete an MCP handshake. A bundle that cannot start
# is invisible to source-level tests — this has regressed before, when circular imports
# scrambled zod's initialisation order and shipped an entry point that never answered.
# Re-running the server tests here points them at the artifact just built, not the
# committed one.
#
# The diff gate above depends on bun-version being pinned: the minifier allocates
# identifiers differently across Bun releases, so an unpinned runner rebuilds to
# different bytes (measured: a bun 1.4.2 rebuild of a 1.3.14-built bundle differed only
# by renamed minified variables). Keep the pin in step with the committed bundle.
This is a Bun + TypeScript toolkit for the `seal-use` CLI and optional MCP server. Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and tool logic is under `src/domains/seal/`.
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares the plugin manifest, `.mcp.json` declares the optional MCP server (disabled by default), and the agent skill lives under `skills/seal-use/`. `.agents/skills/seal-use` is a symlink to `skills/seal-use` so workspace and Codex skill loading keep working.
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares the plugin manifest, `.mcp.json` declares the optional MCP server (disabled by default), and the agent skill lives under `skills/seal-use/`. The in-repo`.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`.
Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in `openapi/`; bundled output is `dist/openapi.json`. Example enterprise configs are in `enterprises/example.*.json`; real configs must stay untracked.
@@ -31,7 +31,8 @@ Prefer small domain functions over broad utility modules.
## CLI & Agent Harness Protocol Guidelines
- **Machine Channel (`stdout`)**: CLI commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
- **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.
- **Guidance & Diagnostic Channel (`stderr`)**: Use `stderr` for runtime logs, network probing status, self-healing notifications, and explicit **Next-Step Command Suggestions** (e.g. `👉 Next action: seal-use deploy hosecloud sync <signKey>`).
- **Exit Code Contract**:
- Successful executions MUST terminate with exit code `0`.
@@ -52,7 +53,15 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
- Run `bun run bump <new-version | patch | minor>` (automatically updates `package.json`, `.zcode-plugin/plugin.json`, `skills/seal-use/SKILL.md`, `openapi/openapi.yaml`, and bundles `dist/`).
- Update `CHANGELOG.md` with new features and fixes.
- **Isolation Rule**: If the main working directory contains uncommitted changes or another branch is actively being edited, NEVER switch branches or stash in the shared repository. Instead, use an isolated worktree for release operations:
```bash
git worktree add -b codex/release-vX.Y.Z /tmp/seal-use-release main
cd /tmp/seal-use-release
# Execute bump, commit, push, PR, merge, tag here
# When finished, remove the worktree:
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:
```bash
@@ -74,11 +83,14 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
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, so an action bump arrives as a Dependabot PR (`.github/dependabot.yml`) rather than silently.
## Security & Configuration Tips
Never commit real enterprise credentials, Seal tokens, service logs, or local generated state. Use `enterprises/example.hose.json` or `enterprises/example.direct.json` as templates, then place real configs in `enterprises/local.json` or `~/.config/seal-use/enterprises` (with legacy fallback to `~/.config/seal-home/enterprises`). For auth or tenant changes, verify with `bun run probe` or `seal-use auth diagnose`.
Credential files are written `0600`; a config placed by hand keeps the `0o644` default, so run `seal-use doctor` and act on its `credential_permissions` check before sharing a machine or a backup. See `SECURITY.md` for the trust model (local HTTP adapter, self-update, custom linters).
## Agent-Specific Instructions
Do not create `.codex/skills`; Codex is compatible with `.agents/skills`, and this project treats `.agents/` as authoritative. At project scope, prefer `AGENT.md` instructions when present.
@@ -7,6 +7,70 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.10.25] - 2026-09-15
### Added
- **`x-implementation-status` on Every OpenAPI Operation, Gated by a Test**: the published contract and the adapter had drifted in **both** directions, and the CI sync gate only compared `openapi/openapi.yaml` against `dist/openapi.json`, so neither direction was visible. It advertised `/v1/approval/rules/{ruleId}` PATCH/DELETE, `/v1/approval/documents*`, `/v1/corps/current/switch` and `/v1/material-packages/upload` — none of which `src/http/routes.ts` routes, so a caller following the contract got 404 — while omitting `/v1/approval-runs/stats`, `/v1/preferences` and `/v1/preferences/decision`, which it does serve. All 46 operations now carry `implemented` (19) or `planned` (27); the three missing implemented endpoints are documented; and `src/http/openapi-implementation.test.ts` fails when an `implemented` operation has no matching route, when an exact `/v1` route is undocumented, or when either status goes unused.
- **Release Guard: the Tag Must Be on `main`**: `release.yml` published on any pushed `v*` tag with `contents: write`, so a tag on an unreviewed branch shipped binaries, and the `workflow_dispatch` tag input could name a tag that was never merged. A guard step now requires the tagged commit to be an ancestor of `origin/main` and fails loudly otherwise (verified against a real release tag, a nonexistent tag, and a branch name). The Gitea mirror job changed from `always()` to "the publish job succeeded", so it no longer chases assets after a refused publish.
- **`SECURITY.md`, `CODEOWNERS` and Dependabot**: the trust model was implicit in the code. `SECURITY.md` records how to report privately, which files hold credentials and their modes, and the three documented limitations (the local HTTP adapter does not authenticate; `update`/`install.sh` do not verify signatures; `linters/` is executed code). `.github/dependabot.yml` keeps dependencies and the newly SHA-pinned actions fresh, and `CODEOWNERS` gives branch protection something to require.
- **`dist/mcp/server.js` Freshness Gate, Enabled by Pinning Bun**: CI now fails when the committed MCP bundle does not match a fresh build from `src/`, mirroring the `dist/openapi.json` gate. This needed `bun-version` pinned to `1.3.14` in both workflows first — previously `latest`, which resolved to 1.4.2 on the runner, and the minifier allocates identifiers differently across Bun releases, so an unpinned rebuild never matched the committed bytes (measured: identical code, only renamed minified variables). The pin also makes release binaries reproducible and matches the `@types/bun`/`bun-types` already declared in `package.json`.
- **CI Boots the Packaged MCP Bundle**: the MCP build step now starts the freshly built `dist/mcp/server.js` and completes a handshake, instead of only checking that it compiles. The artifact is the only thing that ships, so an unbootable bundle is now caught in CI rather than at runtime. This runs *in addition to* the byte-for-byte freshness diff above, which is what the `bun-version` pin exists to keep meaningful; the handshake covers the failure the diff cannot see (a bundle that rebuilds identically but cannot start).
### Fixed
- **Credential Files Could Be Group/World-Readable**: the tool writes credentials `0600` (`core/config/loader.ts`, `cli/commands/corps.ts`, `core/auth/token-store.ts`), but `usage.json` used the `0o644` default and hand-placed enterprise configs kept it too — `enterprises/local.json` holds a plaintext Hose app key and password. `usage.json` is now written `0600`, and `seal-use doctor` gained a `credential_permissions` check that lists any credential file wider than `0600` (skipping the `example.*.json` templates) instead of leaving the mode to be discovered by hand.
- **`isSealHomeProcess` Matched Substrings Instead of the Daemon**: the pid file proves only that *some* process holds that pid, yet `service stop` accepted any command line containing `seal-use`, `service` and `run` as substrings anywhere — so a stale pid could look like our daemon and get signalled. Identity is now matched as argv tokens: an exact adjacent `service run` pair plus a path to this app root or a `seal-use`/`seal-home` launcher.
- **OpenAPI Described the Adapter as Unimplemented, and an Unauthenticated Header as "Optional"**: `info.description` said the contract applied "once the HTTP adapter is implemented" and `servers[0]` called itself "reserved for a future local HTTP adapter; the current service uses MCP stdio" — both false, since `seal-use http` and the `service start` daemon serve it. The `localSession` scheme was documented as an "optional" header that no code reads. The description now states what is served, and the scheme states plainly that requests are not authenticated and the port must stay on loopback.
- **Read-Only MCP Refused Three Read-Only `approval-runs` Verbs**: `approval-runs search`, `approval-runs pick` and `approval-runs bridge` were refused by the read-only tool even though each only queries. The #117 note that `pick` had "moved into read-only" was true of the tool registry but not of the CLI allow-list, which is exactly the kind of split-brain the next entry prevents.
- **Consistency Test Between the CLI Allow-List and the Tool Registry**: the two read/write classifications are maintained by hand in different files, and they had already disagreed twice (`analytics analyze` allow-listed while its tool POSTs; the three verbs above missing). A test now derives the pairing mechanically — every `action === "x"` in `src/cli/commands/*` that dispatches to a `runTool("seal_…")` — and fails when a CLI verb that reaches a read-only tool is itself refused. It asserts a minimum number of pairs so a change in dispatch shape cannot make it silently vacuous, and names its two exceptions explicitly: the `deploy <action>` short forms, which `deploy` rejects at runtime, and `approval-runs search`, an accepted alias of `list` with no help-registry row.
- **MCP Server Bundle Could Not Start At All**: the plugin shipped `dist/mcp/server.js` as its MCP entry point, but that bundle threw `TypeError: ... is not a constructor` while loading and never answered a single request. Because MCP defaults to off, it failed silently — enabling it produced no `seal_cli` tool and no visible error.
- Root cause: the MCP entry (`src/server.ts`) was circularly entangled with the CLI command graph (`server → cli/runner → cli/commands/mcp → server`, and `server → cli/runner → cli/commands/http → http/routes → server`). When `bun build --target=node` flattened that cycle together with zod's own `core ↔ classic` cycle, zod's class initialisers ended up ordered after the top-level `z.lazy()` call the SDK makes at import time, leaving `ZodLazy` undefined at call time.
- Fix: moved `tokenizeCommand` / `normalizeCliArgs` into a leaf module (`src/cli/tokenize.ts`) and made the `mcp` command import the server lazily, removing both cycles. The stock build command now emits a working bundle.
- Added a regression test that boots the packaged `dist/mcp/server.js` over stdio and completes a handshake. The existing tests exercise source rather than the shipped artifact, which is why this went unnoticed.
### Changed
- **`package.json` Can No Longer Be Published by Accident**: it had no `private` flag, no `files` list and none of `description`/`license`/`author`/`repository`, so an `npm publish` would have shipped 212 files including `.github/workflows`, `openapi/`, `docs/proposals`, `src/**/*.test.ts` and `dist/raw-seal-openapi.json` — and the `bin` entries point at `src/cli.ts`, which npm cannot execute, so the published package would have been broken on arrival. `private: true` makes the Release binaries the only distribution channel (the `bin` field stays for `npm link`, which the README recommends for development). Added the missing metadata.
- **`packageManager` and `engines` Now Match the Pinned CI Toolchain**: both workflows pin `bun-version: 1.3.14` because the MCP bundle's byte-for-byte freshness gate depends on it, but the repository declared nothing — so a contributor on a different Bun got a bundle that failed the gate for reasons unrelated to their change. `packageManager: "bun@1.3.14"` and `engines.bun` record the same pin, alongside the build instructions.
- **Documented Exception for Prose on `stdout`**: `AGENTS.md` required clean JSON on `stdout` without exception, yet `seal-use --help` and `seal-use doctor guide` deliberately write Markdown there — their output *is* the payload callers redirect (`seal-use doctor guide > guide.md`). Rather than break that, the contract now names the allowed document-output commands, keeps `src/probe.ts` out of scope as a developer script, and forbids adding new prose-on-stdout commands.
- **Actions Pinned to Commit SHAs**: `actions/checkout`, `oven-sh/setup-bun` and `actions/upload-artifact` were referenced by moving tags (`@v4`, `@v2`) in a workflow that cross-compiles the binaries users install. Both workflows now pin the commit each tag resolved to, with the version in a trailing comment for Dependabot to update.
- **`plugin-migration-plan.md` Archived to `docs/proposals/`**: a completed migration plan (status: code and release finished 2026-08-12) was sitting at the repository root next to `README.md` and `AGENTS.md`.
- **`linters/` Explains Itself**: the directory is gitignored in full and loaded at runtime from `<cwd>/linters`, so a fresh clone silently had no custom linters and no way to learn the convention. `linters/README.md` is now tracked (the only tracked file there) and records the resolution order, the module shape, and the trust boundary — these files are imported and executed in the CLI process.
- **Read-Only Coverage for `seal-use tool <name>`, and a Misclassification Fixed**: the 98-entry internal tool registry now carries an exhaustive read/write classification (`SEAL_READ_ONLY_TOOLS` / `SEAL_MUTATING_TOOLS` in `src/domains/seal/tools.ts`), so the read-only MCP tool reaches read-only registry tools (66 of them) instead of refusing the whole `tool` area. A test asserts the two sets partition the registry exactly, so a newly added tool fails the suite until it is classified rather than silently defaulting.
- This caught a mistake shipped in #115:`analytics analyze` was allow-listed as read-only, but it calls `seal_insight_record_analyze`, which issues a **POST** and starts an analysis server-side. Removed. The classification was cross-checked mechanically — every exported function in `src/domains/seal` that performs a mutating HTTP call was mapped to the tools invoking it — rather than by trusting tool names.
-`approval-runs pick` moved the other way, into read-only: it is a query, not a local-state mutation.
- **MCP TypeScript SDK v1 to v2**: the monolithic `@modelcontextprotocol/sdk` package has been split into scoped packages. Migrated the server to `@modelcontextprotocol/server` and the tests to `@modelcontextprotocol/client`, both at v2.
- Replaced the low-level `Server` + `setRequestHandler` usage with the high-level `McpServer` + `registerTool`, and the hand-written JSON Schema literal with a Zod `z.strictObject` schema (which still emits `additionalProperties: false`).
- Added tool metadata clients could not previously see: a `title` and `annotations` (`readOnlyHint: false`, `destructiveHint: true`, `idempotentHint: false`, `openWorldHint: true`). `seal_cli` is a passthrough that can reach mutating verbs, so it must not be advertised as safe to auto-run or safe to retry; the description now names the command families that need user confirmation.
-`startServer` uses the v2 `serveStdio` entry point, which owns protocol-era negotiation (2025-era clients keep working) and connection teardown.
-`.mcp.json` uses the ZCode-native `${ZCODE_PLUGIN_ROOT}` instead of the Claude-ecosystem alias (verified equivalent in ZCode's resolver).
- **Approval Runs Export No Longer Emits `driftCount`** (#112): `approval-runs export` returned a bare audit-drift counter with no way to trace it back to a document — no SN, no `recordId`, no reason — so interpreting it required a separate per-document `approval-runs flow` query. The drift itself is already visible in the workbook's `E人工行为` / `E人工意见` columns (e.g. AI 决策「通过」with E人工行为「已撤回」and a formatted retraction opinion), and `seal_approval_runs_export` never enabled the flow alignment, so the field was a constant `0` there. Removed `driftCount` from the export result rather than enriching it; per-run `auditDrift` / `auditDriftReason` in `approval-runs flow` are unchanged.
- **MCP Exposes a Read-Only Tool and a Write Tool Instead of One Passthrough**: `seal_cli` could reach every command, so its annotations had to be all-or-nothing (`destructiveHint: true` on a tool that mostly reads, meaning clients could not auto-approve anything, or nothing could be gated — no middle ground). Split into:
-`seal_cli` — read-only, annotated `readOnlyHint: true` / `destructiveHint: false`, so clients may auto-approve it.
-`seal_cli_write` — mutations, publishing, credential minting, self-update and server commands, annotated `destructiveHint: true`.
- The boundary is **enforced, not just annotated**: `seal_cli` executes only commands on an explicit allow-list (84 read-only entries in `src/cli/read-only.ts`) and fails closed on anything unclassified — including commands added to the CLI later. Matching reuses the CLI's own `parseArgs` and matches whole tokens, so a read prefix cannot smuggle a mutation (`corps listing` is refused) and read prefixes cannot cover subcommands (a bare `doctor` does not cover `doctor <anything>`). Refusals name `seal_cli_write` as the follow-up.
- Deliberately excluded from the read-only set even though they look harmless: anything writing local config (`corps switch`, `config test-dir`), minting or printing credentials (`auth keys`, `corps extract-keys`), self-updating (`update`), or standing up a long-running server (`http`, `mcp`, `service run`). `seal-use tool <name>` is also excluded, since the 98-entry internal tool registry is not itself classified.
- A test asserts every allow-listed command still exists in the help registry, so the list cannot silently rot.
- **MCP Is an Optional Path, Off by Default**: made explicit in the skill. The CLI is the primary channel; a missing `seal_cli*` tool is the normal default rather than a fault, and enabling it is the user's choice in the plugin settings. Also corrected skill docs that presented internal tool-registry names (`seal_webhook_get`, `seal_webhook_update`, …) as if they were MCP tools — the MCP server exposes only the two `seal_cli*` tools, and those registry entries are reached through them.
- Implemented extracting permanent OpenAPI developer credentials (`appKey` and `appSecurity`) from incoming Hose/Ekuaibao assistance links (`thirdparty.html`) via internal session key interfaces (`GET /api/innerapi/v1/key`).
- Added `seal-use corps extract-keys <url>` (alias: `seal-use auth extract-keys`) with `--reveal` (`-r`) for explicit unmasking and `--save` to upgrade short-lived session links into durable standard Hose enterprise configurations.
- Added `--as-hose` option to `seal-use corps add-link` to automatically elevate privileges to standard Hose configuration upon link import.
- Explicitly defined the Hose capability boundary: `seal-use` is the primary smart approval platform; Hose is an upstream integrated ecosystem.
- Calling key extraction or `keys` on native Seal enterprises (`corp.source.type !== "hose"`) is strictly rejected with exit code 2 and explicit subdomain boundary explanations.
- **Multi-Key Disambiguation Guardrails**:
- Enforced interactive disambiguation when an enterprise has multiple OpenAPI keys configured instead of guessing or silently picking the first key.
- Emits candidate key lists with application names, appKeys, keyIds, and active status to `stderr`, requiring explicit selection via `--app-key <key>` or `--key-id <id>`. Single-key enterprises are safely auto-selected.
- Fully documented that a Hose assistance link and a browser cURL from an authenticated Hose admin session are both Hose web frontend sessions with identical privilege scope — the structural difference is delivery format only.
- Updated `SKILL.md` First Rules and `enterprise-onboarding.md` Route 3 with explicit guidance: when a Hose administrator provides a browser cURL, attempt privilege elevation first (extract `accesstoken`+`corpid`+`baseUrl` → call `/api/innerapi/v1/key`), not a downgraded short-term session import.
- Added Route 3a/3b/3c classification in `enterprise-onboarding.md` and a privilege comparison table (F12 session vs. elevated OpenAPI credentials).
The canonical plugin skill lives at `skills/seal-use`;`.agents/skills/seal-use`is a workspace symlink to the same files. Installor copy that folder into a Codex skills directory when you want Codex to invoke the workflow as `$seal-use`.
The canonical plugin skill lives at `skills/seal-use`. There is no in-repo`.agents/skills/seal-use`symlink; run `seal-use skill install` (or copy that folder yourself) to place it in a Codex skills directory such as `~/.agents/skills/seal-use` when you want Codex to invoke the workflow as `$seal-use`.
import{createRequireassS0}from"node:module";variS0=Object.create;var{getPrototypeOf:nS0,defineProperty:NP,getOwnPropertyNames:cS0}=Object;varpS0=Object.prototype.hasOwnProperty;functiondS0($){returnthis[$]}varmS0,lS0,S4=($,q,Y)=>{varz=$!=null&&typeof$==="object";if(z){varU=q?mS0??=newWeakMap:lS0??=newWeakMap,I=U.get($);if(I)returnI}Y=$!=null?iS0(nS0($)):{};letJ=q||!$||!$.__esModule?NP(Y,"default",{value:$,enumerable:!0}):Y;for(letQofcS0($))if(!pS0.call(J,Q))NP(J,Q,{get:dS0.bind($,Q),enumerable:!0});if(z)U.set($,J);returnJ};varM=($,q)=>()=>(q||$((q={exports:{}}).exports,q),q.exports);varoS0=($)=>$;functionrS0($,q){this[$]=oS0.bind(null,q)}var$$=($,q)=>{for(varYinq)NP($,Y,{get:q[Y],enumerable:!0,configurable:!0,set:rS0.bind(q,Y)})};vare=($,q)=>()=>($&&(q=$($=0)),q);varm=sS0(import.meta.url);functiona($,q,Y){functionz(Q,K){if(!Q._zod)Object.defineProperty(Q,"_zod",{value:{def:K,constr:J,traits:newSet},enumerable:!1});if(Q._zod.traits.has($))return;Q._zod.traits.add($),q(Q,K);letH=J.prototype,G=Object.keys(H);for(letZ=0;Z<G.length;Z++){letV=G[Z];if(!(VinQ))Q[V]=H[V].bind(Q)}}letU=Y?.Parent??Object;classIextendsU{}Object.defineProperty(I,"name",{value:$});functionJ(Q){varK;letH=Y?.Parent?newI:this;z(H,Q),(K=H._zod).deferred??(K.deferred=[]);for(letGofH._zod.deferred)G();returnH}returnObject.defineProperty(J,"init",{value:z}),Object.defineProperty(J,Symbol.hasInstance,{value:(Q)=>{if(Y?.Parent&&QinstanceofY.Parent)return!0;returnQ?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}functionm4($){if($)Object.assign(V2,$);returnV2}var_m,DP,AP,B5,w2,V2;varL2=e(()=>{DP=Object.freeze({status:"aborted"});AP=Symbol("zod_brand");B5=classB5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};w2=classw2extendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(_m=globalThis).__zod_globalConfig??(_m.__zod_globalConfig={});V2=globalThis.__zod_globalConfig});varA0={};$$(A0,{unwrapMessage:()=>kJ,uint8ArrayToHex:()=>Dy0,uint8ArrayToBase64url:()=>My0,uint8ArrayToBase64:()=>vm,stringifyPrimitive:()=>O0,slugify:()=>TP,shallowClone:()=>jP,safeExtend:()=>Xy0,required:()=>Ly0,randomString:()=>Jy0,propertyKeyTypes:()=>bJ,promiseAllObject:()=>Iy0,primitiveTypes:()=>_P,prefixIssues:()=>h8,pick:()=>Gy0,partial:()=>wy0,parsedType:()=>N0,optionalKeys:()=>CP,omit:()=>Zy0,objectClone:()=>Yy0,numKeys:()=>Qy0,nullish:()=>P3,normalizeParams:()=>B0,mergeDefs:()=>F9,merge:()=>Vy0,jsonStringifyReplacer:()=>RY,joinValues:()=>I0,issue:()=>hY,isPlainObject:()=>T3,isObject:()=>F2,hexToUint8Array:()=>Ny0,getSizableOrigin:()=>iJ,getParsedType:()=>Ky0,getLengthableOrigin:()=>nJ,getEnumValues:()=>uJ,getElementAtPath:()=>Uy0,floatSafeRemainder:()=>BP,finalizeIssue:()=>w8,extend:()=>Wy0,explicitlyAborted:()=>hP,escapeRegex:()=>O$,esc:()=>xW,defineLazy:()=>H1,createTransparentProxy:()=>Hy0,cloneDef:()=>zy0,clone:()=>V8,cleanRegex:()=>fJ,cleanEnum:()=>Fy0,captureStackTrace:()=>kW,cached:()=>vY,base64urlToUint8Array:()=>Oy0,base64ToUint8Array:()=>Rm,assignProp:()=>B3,assertNotEqual:()=>aS0,assertNever:()=>$y0,assertIs:()=>eS0,assertEqual:()=>tS0,assert:()=>qy0,allowsEval:()=>EP,aborted:()=>E3,NUMBER_FORMAT_RANGES:()=>RP,Class:()=>hm,BIGINT_FORMAT_RANGES:()=>vP});functiontS0($){return$}functionaS0($){return$}functioneS0($){}function$y0($){throwError("Unexpected value in exhaustive check")}functionqy0($){}functionuJ($){letq=Object.values($).filter((z)=>typeofz==="number");returnObject.entries($).filter(([z,U])=>q.indexOf(+z)===-1).map(([z,U])=>U)}functionI0($,q="|"){return$.map((Y)=>O0(Y)).join(q)}functionRY($,q){if(typeofq==="bigint")returnq.toString();returnq}functionvY($){return{getvalue(){{letY=$();returnObject.defineProperty(this,"value",{value:Y}),Y}throwError("cached value already set")}}}functionP3($){return$===null||$===void0}functionfJ($){letq=$.startsWith("^")?1:0,Y=$.endsWith("$")?$.length-1:$.length;return$.slice(q,Y)}functionBP($,q){letY=$/q,z=Math.round(Y),U=Number.EPSILON*Math.max(Math.abs(Y),1);if(Math.abs(Y-z)<U)return0;returnY-z}functionH1($,q,Y){letz=void0;Object.defineProperty($,q,{get(){if(z===Cm)return;if(z===void0)z=Cm,z=Y();returnz},set(U){Object.defineProperty($,q,{value:U})},configurable:!0})}functionYy0($){returnObject.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}functionB3($,q,Y){Object.defineProperty($,q,{value:Y,writable:!0,enumerable:!0,configurable:!0})}functionF9(...$){letq={};for(letYof$){letz=Object.getOwnPropertyDescriptors(Y);Object.assign(q,z)}returnObject.defineProperties({},q)}functionzy0($){returnF9($._zod.def)}functionUy0($,q){if(!q)return$;returnq.reduce((Y,z)=>Y?.[z],$)}functionIy0($){letq=Object.keys($),Y=q.map((z)=>$[z]);returnPromise.all(Y).then((z)=>{letU={};for(letI=0;I<q.length;I++)U[q[I]]=z[I];returnU})}functionJy0($=10){letY=""Line truncated
`)}var gm=($,q)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:q,enumerable:!1}),$.message=JSON.stringify(q,RY,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},cJ,g8;var yP=e(()=>{L2();y0();cJ=a("$ZodError",gm),g8=a("$ZodError",gm,{Parent:Error})});var gY=($)=>(q,Y,z,U)=>{let I=z?{...z,async:!1}:{async:!1},J=q._zod.run({value:Y,issues:[]},I);if(J instanceof Promise)throw new B5;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>w8(K,I,m4())));throw kW(Q,U?.callee),Q}return J.value},mJ,SY=($)=>async(q,Y,z,U)=>{let I=z?{...z,async:!0}:{async:!0},J=q._zod.run({value:Y,issues:[]},I);if(J instanceof Promise)J=await J;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>w8(K,I,m4())));throw kW(Q,U?.callee),Q}return J.value},lJ,yY=($)=>(q,Y,z)=>{let U=z?{...z,async:!1}:{async:!1},I=q._zod.run({value:Y,issues:[]},U);if(I instanceof Promise)throw new B5;return I.issues.length?{success:!1,error:new($??cJ)(I.issues.map((J)=>w8(J,U,m4())))}:{success:!0,data:I.value}},xY,kY=($)=>async(q,Y,z)=>{let U=z?{...z,async:!0}:{async:!0},I=q._zod.run({value:Y,issues:[]},U);if(I instanceof Promise)I=await I;return I.issues.length?{success:!1,error:new $(I.issues.map((J)=>w8(J,U,m4())))}:{success:!0,data:I.value}},oJ,uW=($)=>(q,Y,z)=>{let U=z?{...z,direction:"backward"}:{direction:"backward"};return gY($)(q,Y,U)},ym,fW=($)=>(q,Y,z)=>{return gY($)(q,Y,z)},xm,bW=($)=>async(q,Y,z)=>{let U=z?{...z,direction:"backward"}:{direction:"backward"};return SY($)(q,Y,U)},km,iW=($)=>async(q,Y,z)=>{return SY($)(q,Y,z)},um,nW=($)=>(q,Y,z)=>{let U=z?{...z,direction:"backward"}:{direction:"backward"};return yY($)(q,Y,U)},fm,cW=($)=>(q,Y,z)=>{return yY($)(q,Y,z)},bm,pW=($)=>async(q,Y,z)=>{let U=z?{...z,direction:"backward"}:{direction:"backward"};return kY($)(q,Y,U)},im,dW=($)=>async(q,Y,z)=>{return kY($)(q,Y,z)},nm;var xP=e(()=>{L2();yP();y0();mJ=gY(g8),lJ=SY(g8),xY=yY(g8),oJ=kY(g8),ym=uW(g8),xm=fW(g8),km=bW(g8),um=iW(g8),fm=nW(g8),bm=cW(g8),im=pW(g8),nm=dW(g8)});var q$={};$$(q$,{xid:()=>bP,uuid7:()=>Ey0,uuid6:()=>Ty0,uuid4:()=>By0,uuid:()=>O2,uppercase:()=>ZB,unicodeEmail:()=>cm,undefined:()=>HB,ulid:()=>fP,time:()=>YB,string:()=>UB,sha512_hex:()=>ly0,sha512_base64url:()=>ry0,sha512_base64:()=>oy0,sha384_hex:()=>py0,sha384_base64url:()=>my0,sha384_base64:()=>dy0,sha256_hex:()=>iy0,sha256_base64url:()=>cy0,sha256_base64:()=>ny0,sha1_hex:()=>uy0,sha1_base64url:()=>by0,sha1_base64:()=>fy0,rfc5322Email:()=>_y0,number:()=>rJ,null:()=>KB,nanoid:()=>nP,md5_hex:()=>yy0,md5_base64url:()=>ky0,md5_base64:()=>xy0,mac:()=>rP,lowercase:()=>GB,ksuid:()=>iP,ipv6:()=>oP,ipv4:()=>lP,integer:()=>JB,idnEmail:()=>Cy0,httpProtocol:()=>eP,html5Email:()=>jy0,hostname:()=>hy0,hex:()=>Sy0,guid:()=>pP,extendedDuration:()=>Py0,emoji:()=>mP,email:()=>dP,e164:()=>$B,duration:()=>cP,domain:()=>gy0,datetime:()=>zB,date:()=>qB,cuid2:()=>uP,cuid:()=>kP,cidrv6:()=>tP,cidrv4:()=>sP,browserEmail:()=>Ry0,boolean:()=>QB,bigint:()=>IB,base64url:()=>mW,base64:()=>aP});function mP(){return new RegExp(vy0,"u")}function dm($){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 YB($){return new RegExp(`^${dm($)}$`)}function zB($){let q=dm({precision:$.precision}),Y=["Z"];if($.local)Y.push("");if($.offset)Y.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let z=`${q}(?:${Y.join("|")})`;return new RegExp(`^${pm}T(?:${z})$`)}function sJ($,q){return new RegExp(`^[A-Za-z0-9+/]{${$}}${q}$`)}function tJ($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var kP,uP,fP,bP,iP,nP,cP,Py0,pP,O2=($)=>{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})$`)},By0,Ty0,Ey0,dP,jy0,_y0,cm,Cy0,Ry0,vy0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",lP,oP,rP=($)=>{letq=O$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${q}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${q}){5}[0-9a-f]{2}$`)},sP,tP,aP,mW,hy0,gy0,eP,$B,pm="(?:(?:\\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])))",qB,UB=($)=>{letq=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${q}$`)},IB,JB,rJ,QB,KB,HB,GB,ZB,Sy0,yy0,xy0,ky0,uy0,fy0,by0,iy0,ny0,cy0,py0,dy0,my0,ly0,oy0,ry0;varlW=e(()=>{y0();kP=/^[cC][0-9a-z]{6,}$/,uP=/^[0-9a-z]+$/,fP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bP=/^[0-9a-vA-V]{20}$/,iP=/^[A-Za-z0-9]{27}$/,nP=/^[a-zA-Z0-9_-]{21}$/,cP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?Line truncated
`).filter((I)=>I),z=Math.min(...Y.map((I)=>I.length-I.trimStart().length)),U=Y.map((I)=>I.slice(z)).map((I)=>" ".repeat(this.indent*2)+I);for(let I of U)this.content.push(I)}compile(){let $=Function,q=this?.args,z=[...(this?.content??[""]).map((U)=>`${U}`)];return new $(...q,z.join(`
`))}}var RB;var vB=e(()=>{RB={major:4,minor:4,patch:3}});function eB($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function Hl($){if(!mW.test($))return!1;let q=$.replace(/[-_]/g,(z)=>z==="-"?"+":"/"),Y=q.padEnd(Math.ceil(q.length/4)*4,"=");return eB(Y)}function Gl($,q=null){try{let Y=$.split(".");if(Y.length!==3)return!1;let[z]=Y;if(!z)return!1;let U=JSON.parse(atob(z));if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if(q&&(!("alg"in U)||U.alg!==q))return!1;return!0}catch{return!1}}function rm($,q,Y){if($.issues.length)q.issues.push(...h8(Y,$.issues));q.value[Y]=$.value}function qX($,q,Y,z,U,I){let J=Y in z;if($.issues.length){if(U&&I&&!J)return;q.issues.push(...h8(Y,$.issues))}if(!J&&!U){if(!$.issues.length)q.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[Y]});return}if($.value===void 0){if(J)q.value[Y]=void 0}else q.value[Y]=$.value}function Zl($){let q=Object.keys($.shape);for(let z of q)if(!$.shape?.[z]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${z}":expectedaZodschema`);let Y=CP($.shape);return{...$,keys:q,keySet:new Set(q),numKeys:q.length,optionalKeys:new Set(Y)}}function Wl($,q,Y,z,U,I){let J=[],Q=U.keySet,K=U.catchall._zod,H=K.def.type,G=K.optin==="optional",Z=K.optout==="optional";for(let V in q){if(V==="__proto__")continue;if(Q.has(V))continue;if(H==="never"){J.push(V);continue}let X=K.run({value:q[V],issues:[]},z);if(X instanceof Promise)$.push(X.then((w)=>qX(w,Y,V,q,G,Z)));else qX(X,Y,V,q,G,Z)}if(J.length)Y.issues.push({code:"unrecognized_keys",keys:J,input:q,inst:I});if(!$.length)return Y;return Promise.all($).then(()=>{return Y})}function sm($,q,Y,z){for(let I of $)if(I.issues.length===0)return q.value=I.value,q;let U=$.filter((I)=>!E3(I));if(U.length===1)return q.value=U[0].value,U[0];return q.issues.push({code:"invalid_union",input:q.value,inst:Y,errors:$.map((I)=>I.issues.map((J)=>w8(J,z,m4())))}),q}function tm($,q,Y,z){let U=$.filter((I)=>I.issues.length===0);if(U.length===1)return q.value=U[0].value,q;if(U.length===0)q.issues.push({code:"invalid_union",input:q.value,inst:Y,errors:$.map((I)=>I.issues.map((J)=>w8(J,z,m4())))});else q.issues.push({code:"invalid_union",input:q.value,inst:Y,errors:[],inclusive:!1});return q}function hB($,q){if($===q)return{valid:!0,data:$};if($ instanceof Date&&q instanceof Date&&+$===+q)return{valid:!0,data:$};if(T3($)&&T3(q)){let Y=Object.keys(q),z=Object.keys($).filter((I)=>Y.indexOf(I)!==-1),U={...$,...q};for(let I of z){let J=hB($[I],q[I]);if(!J.valid)return{valid:!1,mergeErrorPath:[I,...J.mergeErrorPath]};U[I]=J.data}return{valid:!0,data:U}}if(Array.isArray($)&&Array.isArray(q)){if($.length!==q.length)return{valid:!1,mergeErrorPath:[]};let Y=[];for(let z=0;z<$.length;z++){let U=$[z],I=q[z],J=hB(U,I);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};Y.push(J.data)}return{valid:!0,data:Y}}return{valid:!1,mergeErrorPath:[]}}function am($,q,Y){let z=new Map,U;for(let Q of q.issues)if(Q.code==="unrecognized_keys"){U??(U=Q);for(let K of Q.keys){if(!z.has(K))z.set(K,{});z.get(K).l=!0}}else $.issues.push(Q);for(let Q of Y.issues)if(Q.code==="unrecognized_keys")for(let K of Q.keys){if(!z.has(K))z.set(K,{});z.get(K).r=!0}else $.issues.push(Q);let I=[...z].filter(([,Q])=>Q.l&&Q.r).map(([Q])=>Q);if(I.length&&U)$.issues.push({...U,keys:I});if(E3($))return $;let J=hB(q.value,Y.value);if(!J.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}function em($,q){for(let Y=$.length-1;Y>=0;Y--)if($[Y]._zod[q]!=="optional")return Y+1;return 0}function $l($,q,Y){if($.issues.length)q.issues.push(...h8(Y,$.issues));q.value[Y]=$.value}function ql($,q,Y,z,U){for(let I=0;I<Y.length;I++){let J=$[I],Q=I<z.length;if(J.issues.length){if(!Q&&I>=U){q.value.length=I;break}q.issues.push(...h8(I,J.issues))}q.value[I]=J.value}for(let I=q.value.length-1;I>=z.length;I--)if(Y[I]._zod.optout==="optional"&&q.value[I]===void 0)q.value.length=I;else break;return q}function Yl($,q,Y,z,U,I,J){if($.issues.length)if(bJ.has(typeof z))Y.issues.push(...h8(z,$.issues));else Y.issues.push({code:"invalid_key",origin:"map",input:U,inst:I,issues:$.issues.map((Q)=>w8(Q,J,m4()))});if(q.issues.length)if(bJ.has(typeof z))Y.issues.push(...h8(z,q.issues));else Y.issues.push({origin:"map",code:"invalid_element",input:U,inst:I,key:z,issues:q.issues.map((Q)=>w8(Q,J,m4()))});Y.value.set($.value,q.value)}function zl($,q){if($.issues.length)q.issues.push(...$.issues);q.value.add($.value)}function Ul($,q){if(q===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function Il($,q){if($.value===void 0)$.value=q.defaultValue;return $}function Jl($,q){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:q});return $}function aW($,q,Y){if($.issues.length)return $.aborted=!0,$;return q._zod.run({value:$.value,issues:$.issues,fa
Line truncated
if(${P}.issues.length){
import{createRequireasEg0}from"node:module";varMg0=Object.create;var{getPrototypeOf:Og0,defineProperty:uT,getOwnPropertyNames:Ng0}=Object;varDg0=Object.prototype.hasOwnProperty;functionBg0($){returnthis[$]}varPg0,Ag0,J6=($,Y,z)=>{varU=$!=null&&typeof$==="object";if(U){varQ=Y?Pg0??=newWeakMap:Ag0??=newWeakMap,J=Q.get($);if(J)returnJ}z=$!=null?Mg0(Og0($)):{};letI=Y||!$||!$.__esModule?uT(z,"default",{value:$,enumerable:!0}):z;for(letKofNg0($))if(!Dg0.call(I,K))uT(I,K,{get:Bg0.bind($,K),enumerable:!0});if(U)Q.set($,I);returnI};varE=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);varTg0=($)=>$;functionjg0($,Y){this[$]=Tg0.bind(null,Y)}varx8=($,Y)=>{for(varzinY)uT($,z,{get:Y[z],enumerable:!0,configurable:!0,set:jg0.bind(Y,z)})};varo=($,Y)=>()=>($&&(Y=$($=0)),Y);varI0=Eg0(import.meta.url);varCg0,yq,Rg0,_g0,vg0,hg0,R0=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports),Ao=($,Y)=>{letz={};for(varUin$)yq(z,U,{get:$[U],enumerable:!0});if(Y)yq(z,Symbol.toStringTag,{value:"Module"});returnz},Sg0=($,Y,z,U)=>{if(Y&&typeofY==="object"||typeofY==="function"){for(varQ=_g0(Y),J=0,I=Q.length,K;J<I;J++)if(K=Q[J],!hg0.call($,K)&&K!==z)yq($,K,{get:((G)=>Y[G]).bind(null,K),enumerable:!(U=Rg0(Y,K))||U.enumerable})}return$},kq=($,Y,z)=>(z=$!=null?Cg0(vg0($)):{},Sg0(Y||!$||!$.__esModule?yq(z,"default",{value:$,enumerable:!0}):z,$));varbT=o(()=>{Cg0=Object.create,yq=Object.defineProperty,Rg0=Object.getOwnPropertyDescriptor,_g0=Object.getOwnPropertyNames,vg0=Object.getPrototypeOf,hg0=Object.prototype.hasOwnProperty});functionjo($){returntypeof$==="string"&&To.has($.replace(/#$/,""))}functionEo($,Y){if(!("$schema"in$)||typeof$.$schema!=="string")return"2020-12";letz=$.$schema.replace(/#$/,"");if(gg0.has(z))return"2020-12";if(To.has(z))return"2019-09";if(yg0.has(z)||kg0.has(z))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}`)}vargg0,To,yg0,kg0;variT=o(()=>{gg0=newSet(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),To=newSet(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),yg0=newSet(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),kg0=newSet(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});functionW0($,Y,z){functionU(K,G){if(!K._zod)Object.defineProperty(K,"_zod",{value:{def:G,constr:I,traits:newSet},enumerable:!1});if(K._zod.traits.has($))return;K._zod.traits.add($),Y(K,G);letW=I.prototype,H=Object.keys(W);for(letX=0;X<H.length;X++){letZ=H[X];if(!(ZinK))K[Z]=W[Z].bind(K)}}letQ=z?.Parent??Object;classJextendsQ{}Object.defineProperty(J,"name",{value:$});functionI(K){varG;letW=z?.Parent?newJ:this;U(W,K),(G=W._zod).deferred??(G.deferred=[]);for(letHofW._zod.deferred)H();returnW}returnObject.defineProperty(I,"init",{value:U}),Object.defineProperty(I,Symbol.hasInstance,{value:(K)=>{if(z?.Parent&&Kinstanceofz.Parent)return!0;returnK?._zod?.traits?.has($)}}),Object.defineProperty(I,"name",{value:$}),I}functiona4($){if($)Object.assign(NY,$);returnNY}varCo,pK,cT,f5,DY,NY;varBY=o(()=>{pK=Object.freeze({status:"aborted"});cT=Symbol("zod_brand");f5=classf5extendsError{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};DY=classDYextendsError{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(Co=globalThis).__zod_globalConfig??(Co.__zod_globalConfig={});NY=globalThis.__zod_globalConfig});vary0={};x8(y0,{unwrapMessage:()=>dK,uint8ArrayToHex:()=>Ky0,uint8ArrayToBase64url:()=>Jy0,uint8ArrayToBase64:()=>vo,stringifyPrimitive:()=>v0,slugify:()=>dT,shallowClone:()=>lT,safeExtend:()=>eg0,required:()=>zy0,randomString:()=>mg0,propertyKeyTypes:()=>oK,promiseAllObject:()=>dg0,primitiveTypes:()=>oT,prefixIssues:()=>f8,pick:()=>sg0,partial:()=>Yy0,parsedType:()=>S0,optionalKeys:()=>rT,omit:()=>ag0,objectClone:()=>cg0,numKeys:()=>lg0,nullish:()=>Q3,normalizeParams:()=>x0,mergeDefs:()=>i9,merge:()=>$y0,jsonStringifyReplacer:()=>fU,joinValues:()=>N0,issue:()=>bU,isPlainObject:()=>I3,isObject:()=>PY,hexToUint8Array:()=>Iy0,getSizableOrigin:()=>rK,getParsedType:()=>og0,getLengthableOrigin:()=>sK,getEnumValues:()=>mK,getElementAtPath:()=>pg0,floatSafeRemainder:()=>pT,finalizeIssue:()=>B8,extend:()=>tg0,explicitlyAborted:()=>tT,escapeRegex:()=>N$,esc:()=>xq,defineLazy:()=>T1,createTransparentProxy:()=>rg0,cloneDef:()=>ng0,clone:()=>D8,cleanRegex:()=>lK,cleanEnum:()=>Uy0,captureStackTrace:()=>fq,cached:()=>uU,base64urlToUint8Array:()=>Qy0,base64ToUint8Array:()=>_o,assignProp:()=>J3,assertNotEqual:()=>fg0,assertNever:()=>bg0,assertIs:()=>ug0,assertEqual:()=>xg0,assert:()=>ig0,allowsEval:()=>mT,aborted:()=>K3,NUMBER_FORMAT_RANGES:()=>sT,Class:()=>hoLine truncated
`)}var So=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,fU,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},aK,u8;var Yj=o(()=>{BY();$1();aK=W0("$ZodError",So),u8=W0("$ZodError",So,{Parent:Error})});var iU=($)=>(Y,z,U,Q)=>{let J=U?{...U,async:!1}:{async:!1},I=Y._zod.run({value:z,issues:[]},J);if(I instanceof Promise)throw new f5;if(I.issues.length){let K=new(Q?.Err??$)(I.issues.map((G)=>B8(G,J,a4())));throw fq(K,Q?.callee),K}return I.value},uq,cU=($)=>async(Y,z,U,Q)=>{let J=U?{...U,async:!0}:{async:!0},I=Y._zod.run({value:z,issues:[]},J);if(I instanceof Promise)I=await I;if(I.issues.length){let K=new(Q?.Err??$)(I.issues.map((G)=>B8(G,J,a4())));throw fq(K,Q?.callee),K}return I.value},bq,nU=($)=>(Y,z,U)=>{let Q=U?{...U,async:!1}:{async:!1},J=Y._zod.run({value:z,issues:[]},Q);if(J instanceof Promise)throw new f5;return J.issues.length?{success:!1,error:new($??aK)(J.issues.map((I)=>B8(I,Q,a4())))}:{success:!0,data:J.value}},zj,pU=($)=>async(Y,z,U)=>{let Q=U?{...U,async:!0}:{async:!0},J=Y._zod.run({value:z,issues:[]},Q);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((I)=>B8(I,Q,a4())))}:{success:!0,data:J.value}},Uj,iq=($)=>(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return iU($)(Y,z,Q)},Wy0,cq=($)=>(Y,z,U)=>{return iU($)(Y,z,U)},Hy0,nq=($)=>async(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return cU($)(Y,z,Q)},Xy0,pq=($)=>async(Y,z,U)=>{return cU($)(Y,z,U)},Zy0,dq=($)=>(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return nU($)(Y,z,Q)},qy0,mq=($)=>(Y,z,U)=>{return nU($)(Y,z,U)},Vy0,lq=($)=>async(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return pU($)(Y,z,Q)},Ly0,oq=($)=>async(Y,z,U)=>{return pU($)(Y,z,U)},Fy0;var Qj=o(()=>{BY();Yj();$1();uq=iU(u8),bq=cU(u8),zj=nU(u8),Uj=pU(u8),Wy0=iq(u8),Hy0=cq(u8),Xy0=nq(u8),Zy0=pq(u8),qy0=dq(u8),Vy0=mq(u8),Ly0=lq(u8),Fy0=oq(u8)});var Y$={};x8(Y$,{xid:()=>Gj,uuid7:()=>Ny0,uuid6:()=>Oy0,uuid4:()=>My0,uuid:()=>AY,uppercase:()=>Sj,unicodeEmail:()=>yo,undefined:()=>vj,ulid:()=>Kj,time:()=>Aj,string:()=>jj,sha512_hex:()=>iy0,sha512_base64url:()=>ny0,sha512_base64:()=>cy0,sha384_hex:()=>fy0,sha384_base64url:()=>by0,sha384_base64:()=>uy0,sha256_hex:()=>yy0,sha256_base64url:()=>xy0,sha256_base64:()=>ky0,sha1_hex:()=>hy0,sha1_base64url:()=>gy0,sha1_base64:()=>Sy0,rfc5322Email:()=>By0,number:()=>$G,null:()=>_j,nanoid:()=>Hj,md5_hex:()=>Ry0,md5_base64url:()=>vy0,md5_base64:()=>_y0,mac:()=>wj,lowercase:()=>hj,ksuid:()=>Wj,ipv6:()=>Fj,ipv4:()=>Lj,integer:()=>Cj,idnEmail:()=>Py0,httpProtocol:()=>Dj,html5Email:()=>Dy0,hostname:()=>jy0,hex:()=>Cy0,guid:()=>Zj,extendedDuration:()=>wy0,emoji:()=>Vj,email:()=>qj,e164:()=>Bj,duration:()=>Xj,domain:()=>Ey0,datetime:()=>Tj,date:()=>Pj,cuid2:()=>Ij,cuid:()=>Jj,cidrv6:()=>Oj,cidrv4:()=>Mj,browserEmail:()=>Ay0,boolean:()=>Rj,bigint:()=>Ej,base64url:()=>rq,base64:()=>Nj});function Vj(){return new RegExp(Ty0,"u")}function xo($){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 Aj($){return new RegExp(`^${xo($)}$`)}function Tj($){let Y=xo({precision:$.precision}),z=["Z"];if($.local)z.push("");if($.offset)z.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let U=`${Y}(?:${z.join("|")})`;return new RegExp(`^${ko}T(?:${U})$`)}function YG($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function zG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var Jj,Ij,Kj,Gj,Wj,Hj,Xj,wy0,Zj,AY=($)=>{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})$`)},My0,Oy0,Ny0,qj,Dy0,By0,yo,Py0,Ay0,Ty0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Lj,Fj,wj=($)=>{letY=N$($??":");returnnewRegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},Mj,Oj,Nj,rq,jy0,Ey0,Dj,Bj,ko="(?:(?:\\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])))",Pj,jj=($)=>{letY=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";returnnewRegExp(`^${Y}$`)},Ej,Cj,$G,Rj,_j,vj,hj,Sj,Cy0,Ry0,_y0,vy0,hy0,Sy0,gy0,yy0,ky0,xy0,fy0,uy0,by0,iy0,cy0,ny0;varsq=o(()=>{$1();Jj=/^[cC][0-9a-z]{6,}$/,Ij=/^[0-9a-z]+$/,Kj=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gj=/^[0-9a-vA-V]{20}$/,Wj=/^[A-Za-z0-9]{27}$/,Hj=/^[a-zA-Z0-9_-]{21}$/,Xj=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((J)=>J),U=Math.min(...z.map((J)=>J.length-J.trimStart().length)),Q=z.map((J)=>J.slice(U)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of Q)this.content.push(J)}compile(){let $=Function,Y=this?.args,U=[...(this?.content??[""]).map((Q)=>`${Q}`)];return new $(...Y,U.join(`
`))}}var tj;var ej=o(()=>{tj={major:4,minor:4,patch:3}});function DE($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function zr($){if(!rq.test($))return!1;let Y=$.replace(/[-_]/g,(U)=>U==="-"?"+":"/"),z=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return DE(z)}function Ur($,Y=null){try{let z=$.split(".");if(z.length!==3)return!1;let[U]=z;if(!U)return!1;let Q=JSON.parse(atob(U));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 io($,Y,z){if($.issues.length)Y.issues.push(...f8(z,$.issues));Y.value[z]=$.value}function QV($,Y,z,U,Q,J){let I=z in U;if($.issues.length){if(Q&&J&&!I)return;Y.issues.push(...f8(z,$.issues))}if(!I&&!Q){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[z]});return}if($.value===void 0){if(I)Y.value[z]=void 0}else Y.value[z]=$.value}function Qr($){let Y=Object.keys($.shape);for(let U of Y)if(!$.shape?.[U]?._zod?.traits?.has("$ZodType"))throw Error(`Invalidelementatkey"${U}":expectedaZodschema`);let z=rT($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(z)}}function Jr($,Y,z,U,Q,J){let I=[],K=Q.keySet,G=Q.catchall._zod,W=G.def.type,H=G.optin==="optional",X=G.optout==="optional";for(let Z in Y){if(Z==="__proto__")continue;if(K.has(Z))continue;if(W==="never"){I.push(Z);continue}let q=G.run({value:Y[Z],issues:[]},U);if(q instanceof Promise)$.push(q.then((V)=>QV(V,z,Z,Y,H,X)));else QV(q,z,Z,Y,H,X)}if(I.length)z.issues.push({code:"unrecognized_keys",keys:I,input:Y,inst:J});if(!$.length)return z;return Promise.all($).then(()=>{return z})}function co($,Y,z,U){for(let J of $)if(J.issues.length===0)return Y.value=J.value,Y;let Q=$.filter((J)=>!K3(J));if(Q.length===1)return Y.value=Q[0].value,Q[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:z,errors:$.map((J)=>J.issues.map((I)=>B8(I,U,a4())))}),Y}function no($,Y,z,U){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:z,errors:$.map((J)=>J.issues.map((I)=>B8(I,U,a4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:z,errors:[],inclusive:!1});return Y}function $E($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(I3($)&&I3(Y)){let z=Object.keys(Y),U=Object.keys($).filter((J)=>z.indexOf(J)!==-1),Q={...$,...Y};for(let J of U){let I=$E($[J],Y[J]);if(!I.valid)return{valid:!1,mergeErrorPath:[J,...I.mergeErrorPath]};Q[J]=I.data}return{valid:!0,data:Q}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let z=[];for(let U=0;U<$.length;U++){let Q=$[U],J=Y[U],I=$E(Q,J);if(!I.valid)return{valid:!1,mergeErrorPath:[U,...I.mergeErrorPath]};z.push(I.data)}return{valid:!0,data:z}}return{valid:!1,mergeErrorPath:[]}}function po($,Y,z){let U=new Map,Q;for(let K of Y.issues)if(K.code==="unrecognized_keys"){Q??(Q=K);for(let G of K.keys){if(!U.has(G))U.set(G,{});U.get(G).l=!0}}else $.issues.push(K);for(let K of z.issues)if(K.code==="unrecognized_keys")for(let G of K.keys){if(!U.has(G))U.set(G,{});U.get(G).r=!0}else $.issues.push(K);let J=[...U].filter(([,K])=>K.l&&K.r).map(([K])=>K);if(J.length&&Q)$.issues.push({...Q,keys:J});if(K3($))return $;let I=$E(Y.value,z.value);if(!I.valid)throw Error(`Unmergableintersection.Errorpath:${JSON.stringify(I.mergeErrorPath)}`);return $.value=I.data,$}function mo($,Y){for(let z=$.length-1;z>=0;z--)if($[z]._zod[Y]!=="optional")return z+1;return 0}function lo($,Y,z){if($.issues.length)Y.issues.push(...f8(z,$.issues));Y.value[z]=$.value}function oo($,Y,z,U,Q){for(let J=0;J<z.length;J++){let I=$[J],K=J<U.length;if(I.issues.length){if(!K&&J>=Q){Y.value.length=J;break}Y.issues.push(...f8(J,I.issues))}Y.value[J]=I.value}for(let J=Y.value.length-1;J>=U.length;J--)if(z[J]._zod.optout==="optional"&&Y.value[J]===void 0)Y.value.length=J;else break;return Y}function ro($,Y,z,U,Q,J,I){if($.issues.length)if(oK.has(typeof U))z.issues.push(...f8(U,$.issues));else z.issues.push({code:"invalid_key",origin:"map",input:Q,inst:J,issues:$.issues.map((K)=>B8(K,I,a4()))});if(Y.issues.length)if(oK.has(typeof U))z.issues.push(...f8(U,Y.issues));else z.issues.push({origin:"map",code:"invalid_element",input:Q,inst:J,key:U,issues:Y.issues.map((K)=>B8(K,I,a4()))});z.value.set($.value,Y.value)}function so($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function ao($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function to($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function eo($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function YV($,Y,z){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa
Line truncated
`)}X.write("payload.value = newResult;"),X.write("return payload;");let A=X.compile();return(B,P)=>A(V,B,P)},I,J=F2,Q=!V2.jitless,H=Q&&EP.value,G=q.catchall,Z;$._zod.parse=(V,X)=>{Z??(Z=z.value);let w=V.value;if(!J(w))return V.issues.push({expected:"object",code:"invalid_type",input:w,inst:$}),V;if(Q&&H&&X?.async===!1&&X.jitless!==!0){if(!I)I=U(q.shape);if(V=I(V,X),!G)return V;return Wl([],w,V,X,Z,$)}return Y(V,X)}});eJ=a("$ZodUnion",($,q)=>{s0.init($,q),H1($._zod,"optin",()=>q.options.some((z)=>z._zod.optin==="optional")?"optional":void 0),H1($._zod,"optout",()=>q.options.some((z)=>z._zod.optout==="optional")?"optional":void 0),H1($._zod,"values",()=>{if(q.options.every((z)=>z._zod.values))return new Set(q.options.flatMap((z)=>Array.from(z._zod.values)));return}),H1($._zod,"pattern",()=>{if(q.options.every((z)=>z._zod.pattern)){let z=q.options.map((U)=>U._zod.pattern);return new RegExp(`^(${z.map((U)=>fJ(U.source)).join("|")})$`)}return});let Y=q.options.length===1?q.options[0]._zod.run:null;$._zod.parse=(z,U)=>{if(Y)return Y(z,U);let I=!1,J=[];for(let Q of q.options){let K=Q._zod.run({value:z.value,issues:[]},U);if(K instanceof Promise)J.push(K),I=!0;else{if(K.issues.length===0)return K;J.push(K)}}if(!I)return sm(J,z,$,U);return Promise.all(J).then((Q)=>{return sm(Q,z,$,U)})}});FT=a("$ZodXor",($,q)=>{eJ.init($,q),q.inclusive=!1;let Y=q.options.length===1?q.options[0]._zod.run:null;$._zod.parse=(z,U)=>{if(Y)return Y(z,U);let I=!1,J=[];for(let Q of q.options){let K=Q._zod.run({value:z.value,issues:[]},U);if(K instanceof Promise)J.push(K),I=!0;else J.push(K)}if(!I)return tm(J,z,$,U);return Promise.all(J).then((Q)=>{return tm(Q,z,$,U)})}}),OT=a("$ZodDiscriminatedUnion",($,q)=>{q.inclusive=!1,eJ.init($,q);let Y=$._zod.parse;H1($._zod,"propValues",()=>{let U={};for(let I of q.options){let J=I._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${q.options.indexOf(I)}"`);for(let[Q,K]of Object.entries(J)){if(!U[Q])U[Q]=new Set;for(let H of K)U[Q].add(H)}}return U});let z=vY(()=>{let U=q.options,I=new Map;for(let J of U){let Q=J._zod.propValues?.[q.discriminator];if(!Q||Q.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${q.options.indexOf(J)}"`);for(let K of Q){if(I.has(K))throw Error(`Duplicatediscriminatorvalue"${String(K)}"`);I.set(K,J)}}return I});$._zod.parse=(U,I)=>{let J=U.value;if(!F2(J))return U.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),U;let Q=z.value.get(J?.[q.discriminator]);if(Q)return Q._zod.run(U,I);if(q.unionFallback||I.direction==="backward")return Y(U,I);return U.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:q.discriminator,options:Array.from(z.value.keys()),input:J,path:[q.discriminator],inst:$}),U}}),MT=a("$ZodIntersection",($,q)=>{s0.init($,q),$._zod.parse=(Y,z)=>{let U=Y.value,I=q.left._zod.run({value:U,issues:[]},z),J=q.right._zod.run({value:U,issues:[]},z);if(I instanceof Promise||J instanceof Promise)return Promise.all([I,J]).then(([K,H])=>{return am(Y,K,H)});return am(Y,I,J)}});UX=a("$ZodTuple",($,q)=>{s0.init($,q);let Y=q.items;$._zod.parse=(z,U)=>{let I=z.value;if(!Array.isArray(I))return z.issues.push({input:I,inst:$,expected:"tuple",code:"invalid_type"}),z;z.value=[];let J=[],Q=em(Y,"optin"),K=em(Y,"optout");if(!q.rest){if(I.length<Q)return z.issues.push({code:"too_small",minimum:Q,inclusive:!0,input:I,inst:$,origin:"array"}),z;if(I.length>Y.length)z.issues.push({code:"too_big",maximum:Y.length,inclusive:!0,input:I,inst:$,origin:"array"})}let H=Array(Y.length);for(let G=0;G<Y.length;G++){let Z=Y[G]._zod.run({value:I[G],issues:[]},U);if(Z instanceof Promise)J.push(Z.then((V)=>{H[G]=V}));else H[G]=Z}if(q.rest){let G=Y.length-1,Z=I.slice(Y.length);for(let V of Z){G++;let X=q.rest._zod.run({value:V,issues:[]},U);if(X instanceof Promise)J.push(X.then((w)=>$l(w,z,G)));else $l(X,z,G)}}if(J.length)return Promise.all(J).then(()=>ql(H,z,Y,I,K));return ql(H,z,Y,I,K)}});NT=a("$ZodRecord",($,q)=>{s0.init($,q),$._zod.parse=(Y,z)=>{let U=Y.value;if(!T3(U))return Y.issues.push({expected:"record",code:"invalid_type",input:U,inst:$}),Y;let I=[],J=q.keyType._zod.values;if(J){Y.value={};let Q=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){Q.add(typeof H==="number"?H.toString():H);let G=q.keyType._zod.run({value:H,issues:[]},z);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(G.issues.length){Y.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((X)=>w8(X,z,m4())),input:H,path:[H],inst:$});continue}let Z=G.value,V=q.valueType._zod.run({value:U[H],issues:[]},z);if(V instanceof Promise)I.push(V.then((X)=>{if(X.issues.length)Y.issues.push(...h8(H,X.issues));Y.value[Z]=X.value}));else{if(V.issues.length)Y.issues.push(...h8(H,V.issues));Y.value[Z]=V.value}}let K;for(let H in U)if(!Q.has(H))K=K??[],K.push(H);if(K&&K.length>0)Y.issues.push({code:"unrecognize
Line truncated
`)}q.write("payload.value = newResult;"),q.write("return payload;");let O=q.compile();return(N,D)=>O(Z,N,D)},J,I=PY,K=!NY.jitless,W=K&&mT.value,H=Y.catchall,X;$._zod.parse=(Z,q)=>{X??(X=U.value);let V=Z.value;if(!I(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(K&&W&&q?.async===!1&&q.jitless!==!0){if(!J)J=Q(Y.shape);if(Z=J(Z,q),!H)return Z;return Jr([],V,Z,q,X,$)}return z(Z,q)}});QG=W0("$ZodUnion",($,Y)=>{q1.init($,Y),T1($._zod,"optin",()=>Y.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),T1($._zod,"optout",()=>Y.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),T1($._zod,"values",()=>{if(Y.options.every((U)=>U._zod.values))return new Set(Y.options.flatMap((U)=>Array.from(U._zod.values)));return}),T1($._zod,"pattern",()=>{if(Y.options.every((U)=>U._zod.pattern)){let U=Y.options.map((Q)=>Q._zod.pattern);return new RegExp(`^(${U.map((Q)=>lK(Q.source)).join("|")})$`)}return});let z=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(U,Q)=>{if(z)return z(U,Q);let J=!1,I=[];for(let K of Y.options){let G=K._zod.run({value:U.value,issues:[]},Q);if(G instanceof Promise)I.push(G),J=!0;else{if(G.issues.length===0)return G;I.push(G)}}if(!J)return co(I,U,$,Q);return Promise.all(I).then((K)=>{return co(K,U,$,Q)})}});uE=W0("$ZodXor",($,Y)=>{QG.init($,Y),Y.inclusive=!1;let z=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(U,Q)=>{if(z)return z(U,Q);let J=!1,I=[];for(let K of Y.options){let G=K._zod.run({value:U.value,issues:[]},Q);if(G instanceof Promise)I.push(G),J=!0;else I.push(G)}if(!J)return no(I,U,$,Q);return Promise.all(I).then((K)=>{return no(K,U,$,Q)})}}),bE=W0("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,QG.init($,Y);let z=$._zod.parse;T1($._zod,"propValues",()=>{let Q={};for(let J of Y.options){let I=J._zod.propValues;if(!I||Object.keys(I).length===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(J)}"`);for(let[K,G]of Object.entries(I)){if(!Q[K])Q[K]=new Set;for(let W of G)Q[K].add(W)}}return Q});let U=uU(()=>{let Q=Y.options,J=new Map;for(let I of Q){let K=I._zod.propValues?.[Y.discriminator];if(!K||K.size===0)throw Error(`Invaliddiscriminatedunionoptionatindex"${Y.options.indexOf(I)}"`);for(let G of K){if(J.has(G))throw Error(`Duplicatediscriminatorvalue"${String(G)}"`);J.set(G,I)}}return J});$._zod.parse=(Q,J)=>{let I=Q.value;if(!PY(I))return Q.issues.push({code:"invalid_type",expected:"object",input:I,inst:$}),Q;let K=U.value.get(I?.[Y.discriminator]);if(K)return K._zod.run(Q,J);if(Y.unionFallback||J.direction==="backward")return z(Q,J);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(U.value.keys()),input:I,path:[Y.discriminator],inst:$}),Q}}),iE=W0("$ZodIntersection",($,Y)=>{q1.init($,Y),$._zod.parse=(z,U)=>{let Q=z.value,J=Y.left._zod.run({value:Q,issues:[]},U),I=Y.right._zod.run({value:Q,issues:[]},U);if(J instanceof Promise||I instanceof Promise)return Promise.all([J,I]).then(([G,W])=>{return po(z,G,W)});return po(z,J,I)}});KV=W0("$ZodTuple",($,Y)=>{q1.init($,Y);let z=Y.items;$._zod.parse=(U,Q)=>{let J=U.value;if(!Array.isArray(J))return U.issues.push({input:J,inst:$,expected:"tuple",code:"invalid_type"}),U;U.value=[];let I=[],K=mo(z,"optin"),G=mo(z,"optout");if(!Y.rest){if(J.length<K)return U.issues.push({code:"too_small",minimum:K,inclusive:!0,input:J,inst:$,origin:"array"}),U;if(J.length>z.length)U.issues.push({code:"too_big",maximum:z.length,inclusive:!0,input:J,inst:$,origin:"array"})}let W=Array(z.length);for(let H=0;H<z.length;H++){let X=z[H]._zod.run({value:J[H],issues:[]},Q);if(X instanceof Promise)I.push(X.then((Z)=>{W[H]=Z}));else W[H]=X}if(Y.rest){let H=z.length-1,X=J.slice(z.length);for(let Z of X){H++;let q=Y.rest._zod.run({value:Z,issues:[]},Q);if(q instanceof Promise)I.push(q.then((V)=>lo(V,U,H)));else lo(q,U,H)}}if(I.length)return Promise.all(I).then(()=>oo(W,U,z,J,G));return oo(W,U,z,J,G)}});cE=W0("$ZodRecord",($,Y)=>{q1.init($,Y),$._zod.parse=(z,U)=>{let Q=z.value;if(!I3(Q))return z.issues.push({expected:"record",code:"invalid_type",input:Q,inst:$}),z;let J=[],I=Y.keyType._zod.values;if(I){z.value={};let K=new Set;for(let W of I)if(typeof W==="string"||typeof W==="number"||typeof W==="symbol"){K.add(typeof W==="number"?W.toString():W);let H=Y.keyType._zod.run({value:W,issues:[]},U);if(H instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(H.issues.length){z.issues.push({code:"invalid_key",origin:"record",issues:H.issues.map((q)=>B8(q,U,a4())),input:W,path:[W],inst:$});continue}let X=H.value,Z=Y.valueType._zod.run({value:Q[W],issues:[]},U);if(Z instanceof Promise)J.push(Z.then((q)=>{if(q.issues.length)z.issues.push(...f8(W,q.issues));z.value[X]=q.value}));else{if(Z.issues.length)z.issues.push(...f8(W,Z.issues));z.value[X]=Z.value}}let G;for(let W in Q)if(!K.has(W))G=G??[],G.push(W);if(G&&G.length>0)z.issues.push({code:"unrec
Line truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letJof$.seen.entries()){letQ=J[1];if(q===J[0]){I(J);continue}if($.external){letH=$.external.registry.get(J[0])?.id;if(q!==J[0]&&H){I(J);continue}}if($.metadataRegistry.get(J[0])?.id){I(J);continue}if(Q.cycle){I(J);continue}if(Q.count>1){if($.reused==="ref"){I(J);continue}}}}functionv3($,q){letY=$.seen.get(q);if(!Y)throwError("Unprocessed schema. This is a bug in Zod.");letz=(Q)=>{letK=$.seen.get(Q);if(K.ref===null)return;letH=K.def??K.schema,G={...H},Z=K.ref;if(K.ref=null,Z){z(Z);letX=$.seen.get(Z),w=X.schema;if(w.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(w);elseObject.assign(H,w);if(Object.assign(H,G),Q._zod.parent===Z)for(letFinH){if(F==="$ref"||F==="allOf")continue;if(!(FinG))deleteH[F]}if(w.$ref&&X.def)for(letFinH){if(F==="$ref"||F==="allOf")continue;if(FinX.def&&JSON.stringify(H[F])===JSON.stringify(X.def[F]))deleteH[F]}}letV=Q._zod.parent;if(V&&V!==Z){z(V);letX=$.seen.get(V);if(X?.schema.$ref){if(H.$ref=X.schema.$ref,X.def)for(letwinH){if(w==="$ref"||w==="allOf")continue;if(winX.def&&JSON.stringify(H[w])===JSON.stringify(X.def[w]))deleteH[w]}}}$.override({zodSchema:Q,jsonSchema:H,path:K.path??[]})};for(letQof[...$.seen.entries()].reverse())z(Q[0]);letU={};if($.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";elseif($.target==="draft-07")U.$schema="http://json-schema.org/draft-07/schema#";elseif($.target==="draft-04")U.$schema="http://json-schema.org/draft-04/schema#";elseif($.target==="openapi-3.0");if($.external?.uri){letQ=$.external.registry.get(q)?.id;if(!Q)throwError("Schema is missing an `id` property");U.$id=$.external.uri(Q)}Object.assign(U,Y.def??Y.schema);letI=$.metadataRegistry.get(q)?.id;if(I!==void0&&U.id===I)deleteU.id;letJ=$.external?.defs??{};for(letQof$.seen.entries()){letK=Q[1];if(K.def&&K.defId){if(K.def.id===K.defId)deleteK.def.id;J[K.defId]=K.def}}if($.external);elseif(Object.keys(J).length>0)if($.target==="draft-2020-12")U.$defs=J;elseU.definitions=J;try{letQ=JSON.parse(JSON.stringify(U));returnObject.defineProperty(Q,"~standard",{value:{...q["~standard"],jsonSchema:{input:eY(q,"input",$.processors),output:eY(q,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throwError("Error converting schema to JSON.")}}functionF8($,q){letY=q??{seen:newSet};if(Y.seen.has($))return!1;Y.seen.add($);letz=$._zod.def;if(z.type==="transform")return!0;if(z.type==="array")returnF8(z.element,Y);if(z.type==="set")returnF8(z.valueType,Y);if(z.type==="lazy")returnF8(z.getter(),Y);if(z.type==="promise"||z.type==="optional"||z.type==="nonoptional"||z.type==="nullable"||z.type==="readonly"||z.type==="default"||z.type==="prefault")returnF8(z.innerType,Y);if(z.type==="intersection")returnF8(z.left,Y)||F8(z.right,Y);if(z.type==="record"||z.type==="map")returnF8(z.keyType,Y)||F8(z.valueType,Y);if(z.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnF8(z.in,Y)||F8(z.out,Y)}if(z.type==="object"){for(letUinz.shape)if(F8(z.shape[U],Y))return!0;return!1}if(z.type==="union"){for(letUofz.options)if(F8(U,Y))return!0;return!1}if(z.type==="tuple"){for(letUofz.items)if(F8(U,Y))return!0;if(z.rest&&F8(z.rest,Y))return!0;return!1}return!1}varRj=($,q={})=>(Y)=>{letz=C3({...Y,processors:q});returns1($,z),R3(z,$),v3(z,$)},eY=($,q,Y={})=>(z)=>{let{libraryOptions:U,target:I}=z??{},J=C3({...U??{},target:I,io:q,processors:Y});returns1($,J),R3(J,$),v3(J,$)};varHQ=e(()=>{JQ()});functionxX($,q){if("_idmap"in$){letz=$,U=C3({...q,processors:gX}),I={};for(letKofz._idmap.entries()){let[H,G]=K;s1(G,U)}letJ={},Q={registry:z,uri:q?.uri,defs:I};U.external=Q;for(letKofz._idmap.entries()){let[H,G]=K;R3(U,G),J[H]=v3(U,G)}if(Object.keys(I).length>0){letK=U.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[K]:I}}return{schemas:J}}letY=C3({...q,processors:gX});returns1($,Y),R3(Y,$),v3(Y,$)}varFk0,vj=($,q,Y,z)=>{letU=Y;U.type="string";let{minimum:I,maximum:J,format:Q,patterns:K,contentEncoding:H}=$._zod.bag;if(typeofI==="number")U.minLength=I;if(typeofJ==="number")U.maxLength=J;if(Q){if(U.format=Fk0[Q]??Q,U.format==="")deleteU.format;if(Q==="time")deleteU.format}if(H)U.contentEncoding=H;if(K&&K.size>0){letG=[...K];if(G.length===1)U.pattern=G[0].source;elseif(G.length>1)U.allOf=[...G.map((Z)=>({...q.target==="draft-07"||q.target==="draft-04"||q.target==="openapi-3.0"?{type:"string"}:{},pattern:Z.source}))]}},hj=($,q,Y,z)=>{letU=Y,{minimum:I,maximum:J,format:Q,multipleOf:K,exclusiveMaximum:H,exclusiveMinimum:G}=$._zod.bag;if(typeofQ==="string"&&Q.includes("int"))U.type="integer";elseU.type="number";letZ=typeofG==="number"&&G>=(I??Number.NEGATIVE_INFINITY),V=typeofH==="number"&&H<=(J??Number.POSITIVE_INFINITY),X=q.target==="draft-04"||q.target==="openapi-3.0";if(Z)if(X)U.minimum=G,U.exclusiveMinimum=!0;elseU.exclusiveMinimuLine truncated
deps:${Y}}`};var pd0={keyword:"dependencies",type:"object",schemaType:"object",error:Pe.error,code($){let[q,Y]=dd0($);De($,q),Ae($,Y)}};function dd0({schema:$}){let q={},Y={};for(let z in $){if(z==="__proto__")continue;let U=Array.isArray($[z])?q:Y;U[z]=$[z]}return[q,Y]}function De($,q=$.schema){let{gen:Y,data:z,it:U}=$;if(Object.keys(q).length===0)return;let I=Y.let("missing");for(let J in q){let Q=q[J];if(Q.length===0)continue;let K=(0,IK.propertyInData)(Y,z,J,U.opts.ownProperties);if($.setParams({property:J,depsCount:Q.length,deps:Q.join(", ")}),U.allErrors)Y.if(K,()=>{for(let H of Q)(0,IK.checkReportMissingProp)($,H)});else Y.if(hR._`${K}&&(${(0,IK.checkMissingProp)($,Q,I)})`),(0,IK.reportMissingProp)($,I),Y.else()}}Pe.validatePropertyDeps=De;function Ae($,q=$.schema){let{gen:Y,data:z,keyword:U,it:I}=$,J=Y.name("valid");for(let Q in q){if((0,cd0.alwaysValidSchema)(I,q[Q]))continue;Y.if((0,IK.propertyInData)(Y,z,Q,I.opts.ownProperties),()=>{let K=$.subschema({keyword:U,schemaProp:Q},J);$.mergeValidEvaluated(K,J)},()=>Y.var(J,!0)),$.ok(J)}}Pe.validateSchemaDeps=Ae;Pe.default=pd0});var Ce=M((_e)=>{Object.defineProperty(_e,"__esModule",{value:!0});var je=J1(),od0=j1(),rd0={message:"property name must be valid",params:({params:$})=>je._`{propertyName:${$.propertyName}}`},sd0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:rd0,code($){let{gen:q,schema:Y,data:z,it:U}=$;if((0,od0.alwaysValidSchema)(U,Y))return;let I=q.name("valid");q.forIn("key",z,(J)=>{$.setParams({propertyName:J}),$.subschema({keyword:"propertyNames",data:J,dataTypes:["string"],propertyName:J,compositeRule:!0},I),q.if((0,je.not)(I),()=>{if($.error(!0),!U.allErrors)q.break()})}),$.ok(I)}};_e.default=sd0});var gR=M((Re)=>{Object.defineProperty(Re,"__esModule",{value:!0});var Uw=D$(),Y5=J1(),ad0=A9(),Iw=j1(),ed0={message:"must NOT have additional properties",params:({params:$})=>Y5._`{additionalProperty:${$.additionalProperty}}`},$m0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ed0,code($){let{gen:q,schema:Y,parentSchema:z,data:U,errsCount:I,it:J}=$;if(!I)throw Error("ajv implementation error");let{allErrors:Q,opts:K}=J;if(J.props=!0,K.removeAdditional!=="all"&&(0,Iw.alwaysValidSchema)(J,Y))return;let H=(0,Uw.allSchemaProperties)(z.properties),G=(0,Uw.allSchemaProperties)(z.patternProperties);Z(),$.ok(Y5._`${I}===${ad0.default.errors}`);function Z(){q.forIn("key",U,(F)=>{if(!H.length&&!G.length)w(F);else q.if(V(F),()=>w(F))})}function V(F){let O;if(H.length>8){let A=(0,Iw.schemaRefOrVal)(J,z.properties,"properties");O=(0,Uw.isOwnProperty)(q,A,F)}else if(H.length)O=(0,Y5.or)(...H.map((A)=>Y5._`${F}===${A}`));else O=Y5.nil;if(G.length)O=(0,Y5.or)(O,...G.map((A)=>Y5._`${(0,Uw.usePattern)($,A)}.test(${F})`));return(0,Y5.not)(O)}function X(F){q.code(Y5._`delete${U}[${F}]`)}function w(F){if(K.removeAdditional==="all"||K.removeAdditional&&Y===!1){X(F);return}if(Y===!1){if($.setParams({additionalProperty:F}),$.error(),!Q)q.break();return}if(typeof Y=="object"&&!(0,Iw.alwaysValidSchema)(J,Y)){let O=q.name("valid");if(K.removeAdditional==="failing")L(F,O,!1),q.if((0,Y5.not)(O),()=>{$.reset(),X(F)});else if(L(F,O),!Q)q.if((0,Y5.not)(O),()=>q.break())}}function L(F,O,A){let B={keyword:"additionalProperties",dataProp:F,dataPropType:Iw.Type.Str};if(A===!1)Object.assign(B,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(B,O)}}};Re.default=$m0});var Se=M((ge)=>{Object.defineProperty(ge,"__esModule",{value:!0});var Ym0=lQ(),ve=D$(),SR=j1(),he=gR(),zm0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:q,schema:Y,parentSchema:z,data:U,it:I}=$;if(I.opts.removeAdditional==="all"&&z.additionalProperties===void 0)he.default.code(new Ym0.KeywordCxt(I,he.default,"additionalProperties"));let J=(0,ve.allSchemaProperties)(Y);for(let Z of J)I.definedProperties.add(Z);if(I.opts.unevaluated&&J.length&&I.props!==!0)I.props=SR.mergeEvaluated.props(q,(0,SR.toHash)(J),I.props);let Q=J.filter((Z)=>!(0,SR.alwaysValidSchema)(I,Y[Z]));if(Q.length===0)return;let K=q.name("valid");for(let Z of Q){if(H(Z))G(Z);else{if(q.if((0,ve.propertyInData)(q,U,Z,I.opts.ownProperties)),G(Z),!I.allErrors)q.else().var(K,!0);q.endIf()}$.it.definedProperties.add(Z),$.ok(K)}function H(Z){return I.opts.useDefaults&&!I.compositeRule&&Y[Z].default!==void 0}function G(Z){$.subschema({keyword:"properties",schemaProp:Z,dataProp:Z},K)}}};ge.default=zm0});var fe=M((ue)=>{Object.defineProperty(ue,"__esModule",{value:!0});var ye=D$(),Jw=J1(),xe=j1(),ke=j1(),Im0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:q,schema:Y,data:z,parentSchema:U,it:I}=$,{opts:J}=I,Q=(0,ye.allSchemaProperties)(Y),K=Q.filter((L)=>(0,xe.alwaysValidSchema)(I,Y[L]));if(Q.length===0||K.length===Q.length&&(!I.opts.unevaluated||I.props===!0))return;let H=J.strictSchema&&!J.allowMatchingProperties&&U.properties,G=q.name("valid");if(I.props!==!0&&!(I.props instanceo
Line truncated
`)}openNode($,q){let Y=this.tos,z=this._xml;if(Y&&this.open)z.push(">");this._stack.push($),z.push("<"),z.push($),US(z,q),this.leaf=!0,this.open=!0}addAttribute($,q){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(q!==void 0)d70(this._xml,$,q)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");US(this._xml,$)}writeText($){let q=this._xml;if(this.open)q.push(">"),this.open=!1;this.leaf=!1,q.push(p70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),q=this._xml;if(this.leaf)q.push("/>");else q.push("</"),q.push($),q.push(">");this.open=!1,this.leaf=!1}leafNode($,q,Y){if(this.openNode($,q),Y!==void 0)this.writeText(Y);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("")}}IS.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};m70.exports=IS});var JS=M((u81)=>{var l70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function k81($){if(typeof $==="string")return $;if(l70)return l70.decode($);return $.toString()}u81.bufferToString=k81});var a70=M((r70)=>{Object.defineProperty(r70,"__esModule",{value:!0});r70.CHAR=`
`,$=this.i;break;case U51:{let{entityReturnState:Y}=this,z=this.entity+q.slice($,this.prevI);this.state=Y;let U;if(z==="")this.fail("empty entity name."),U="&;";else U=this.parseEntity(z),this.entity="";if(Y!==P8||this.textHandler!==void 0)this.text+=U;break $}case v4:this.entity+=q.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(DH($))this.state=e$1,this.unget(),this.xmlDeclPossible=!1;else switch($){case MF:this.state=Y51,this.xmlDeclPossible=!1;break;case D20:this.state=c$1,this.openWakaBang="",this.xmlDeclPossible=!1;break;case p6:this.state=o$1;break;default:this.fail("disallowed character in tag name"),this.state=P8,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=LS,this.openWakaBang="";break;case"--":this.state=wS,this.openWakaBang="";break;case"DOCTYPE":if(this.state=WS,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(OF))this.state=p$1}sCommentEnding(){var $;let q=this.getCodeNorm();if(q===OF)this.state=d$1,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(q)}`,this.state=wS}sCommentEnded(){let $=this.getCodeNorm();if($!==O6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=wS;else this.state=P8}sCData(){if(this.captureToChar(FU))this.state=m$1}sCDataEnding(){let $=this.getCodeNorm();if($===FU)this.state=l$1;else this.text+=`]${String.fromCodePoint($)}`,this.state=LS}sCDataEnding2(){var $;let q=this.getCodeNorm();switch(q){case O6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=P8;break}case FU:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(q)}`,this.state=LS}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=V20;else if($===p6||c8($))this.fail("processing instruction without a target."),this.state=$===p6?FF:FS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=V20}sPIRest(){let{chunk:$,i:q}=this;while(!0){let Y=this.getCodeNorm();if(Y===v4){this.piTarget+=$.slice(q);return}if(!this.nameCheck(Y)){this.piTarget+=$.slice(q,this.prevI);let z=Y===p6;if(z||c8(Y))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=z?e2:w20}else this.state=z?FF:FS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(Y);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===p6)this.state=FF;else if(!c8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(p6))this.state=FF}sPIEnding(){var $;let q=this.getCodeNorm();if(q===O6){let{piTarget:Y}=this;if(Y.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:Y,body:this.text}),this.piTarget=this.text="",this.state=P8}else if(q===p6)this.text+="?";else this.text+=`?${String.fromCodePoint(q)}`,this.state=FS;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===p6){this.state=e2;return}if($!==v4)this.state=r$1,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(Q51);if($===p6){this.state=e2,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(c8($)||$===LU))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=$===LU?L20:s$1}sXMLDeclEq(){let $=this.getCodeNorm();if($===p6){this.state=e2,this.fail("XML declaration is incomplete.");return}if(c8($))return;if($!==LU)this.fail("value required.");this.state=L20}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===p6){this.state=e2,this.fail("XML declaration is incomplete.");return}if(c8($))return;if(!NF($))this.fail("value must be quoted."),this.q=N20;else this.q=$;this.state=t$1}sXMLDeclValue(){let $=this.captureTo([this.q,p6]);if($===p6){this.state=e2,this.text="",this.fail("XML declaration is incomplete.");return}if($===v4)return;let q=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let Y=q;if(this.xmlDecl.version=Y,!/^1\.[0-9]+$/.test(Y))this.fail("ver
Line truncated
`;$=this.i;break;case v4:if(Y!==void 0)this.text+=q.slice($);break $;default:if(!c8(U))z=!0}}if(!z)return;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}pushAttribNS($,q){var Y;let{prefix:z,local:U}=this.qname($),I={name:$,prefix:z,local:U,value:q};if(this.attribList.push(I),(Y=this.attributeHandler)===null||Y===void 0||Y.call(this,I),z==="xmlns"){let J=q.trim();if(this.currentXMLVersion==="1.0"&&J==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[U]=J,PS(this,U,J)}else if($==="xmlns"){let J=q.trim();this.topNS[""]=J,PS(this,"",J)}}pushAttribPlain($,q){var Y;let z={name:$,value:q};this.attribList.push(z),(Y=this.attributeHandler)===null||Y===void 0||Y.call(this,z)}end(){var $,q;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:Y}=this;while(Y.length>0){let U=Y.pop();this.fail(`unclosedtag:${U.name}`)}if(this.state!==X20&&this.state!==P8)this.fail("unexpected end.");let{text:z}=this;if(z.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,z),this.text="";return this._closed=!0,(q=this.endHandler)===null||q===void 0||q.call(this),this._init(),this}resolve($){var q,Y;let z=this.topNS[$];if(z!==void 0)return z;let{tags:U}=this;for(let I=U.length-1;I>=0;I--)if(z=U[I].ns[$],z!==void 0)return z;if(z=this.ns[$],z!==void 0)return z;return(Y=(q=this.opt).resolvePrefix)===null||Y===void 0?void 0:Y.call(q,$)}qname($){let q=$.indexOf(":");if(q===-1)return{prefix:"",local:$};let Y=$.slice(q+1),z=$.slice(0,q);if(z===""||Y===""||Y.includes(":"))this.fail(`malformedname:${$}.`);return{prefix:z,local:Y}}processAttribsNS(){var $;let{attribList:q}=this,Y=this.tag;{let{prefix:I,local:J}=this.qname(Y.name);Y.prefix=I,Y.local=J;let Q=Y.uri=($=this.resolve(I))!==null&&$!==void 0?$:"";if(I!==""){if(I==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(Q==="")this.fail(`unboundnamespaceprefix:${JSON.stringify(I)}.`),Y.uri=I}}if(q.length===0)return;let{attributes:z}=Y,U=new Set;for(let I of q){let{name:J,prefix:Q,local:K}=I,H,G;if(Q==="")H=J==="xmlns"?OU:"",G=J;else{if(H=this.resolve(Q),H===void 0)this.fail(`unboundnamespaceprefix:${JSON.stringify(Q)}.`),H=Q;G=`{${H}}${K}`}if(U.has(G))this.fail(`duplicateattribute:${G}.`);U.add(G),I.uri=H,z[J]=I}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,q=this.tag.attributes;for(let{name:Y,value:z}of $){if(q[Y]!==void 0)this.fail(`duplicateattribute:${Y}.`);q[Y]=z}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:q}=this,Y=this.tag;Y.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,Y),q.push(Y),this.state=P8,this.name=""}openSelfClosingTag(){var $,q,Y;this.processAttribs();let{tags:z}=this,U=this.tag;if(U.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,U),(q=this.closeTagHandler)===null||q===void 0||q.call(this,U),(this.tag=(Y=z[z.length-1])!==null&&Y!==void 0?Y:null)===null)this.closedRoot=!0;this.state=P8,this.name=""}closeTag(){let{tags:$,name:q}=this;if(this.state=P8,this.name="",q===""){this.fail("weird empty close tag."),this.text+="</>";return}let Y=this.closeTagHandler,z=$.length;while(z-- >0){let U=this.tag=$.pop();if(this.topNS=U.ns,Y===null||Y===void 0||Y(U),U.name===q)break;this.fail("unexpected close tag.")}if(z===0)this.closedRoot=!0;else if(z<0)this.fail(`unmatchedclosingtag:${q}.`),this.text+=`</${q}>`}parseEntity($){if($[0]!=="#"){let Y=this.ENTITIES[$];if(Y!==void 0)return Y;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let q=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))q=parseInt($.slice(2),16);elseif(/^#[0-9]+$/.test($))q=parseInt($.slice(1),10);if(!this.isChar(q))returnthis.fail("malformed character entity."),`&${$};`;returnString.fromCodePoint(q)}}h20.SaxesParser=v20});varBH=M((X14,S20)=>{var{SaxesParser:V51}=g20(),{PassThrough:w51}=A8(),{bufferToString:L51}=JS();S20.exports=asyncfunction*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(neww51);letq=newV51,Y;q.on("error",(U)=>{Y=U});letz=[];q.on("opentag",(U)=>z.push({eventType:"opentag",value:U})),q.on("text",(U)=>z.push({eventType:"text",value:U})),q.on("closetag",(U)=>z.push({eventType:"closetag",value:U}));forawait(letUof$){if(q.write(L51(U)),Y)throwY;yieldz,z=[]}}});varD0=M((V14,y20)=>{varF51=BH(),O51=c6();classNU{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,q){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($instanceofNU)$.reset();elseif($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}asyncparse($){forawait(letqof$)for(let{eventType:Y,value:z}ofq)if(Y==="opentag")this.parseOpen(z);elseif(Y==="text")this.parseText(z);elseif(Y==="closetag"){if(!this.parseClose(z.name))returnthLine truncated
Setthe\`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(letIof$.seen.entries()){letK=I[1];if(Y===I[0]){J(I);continue}if($.external){letW=$.external.registry.get(I[0])?.id;if(Y!==I[0]&&W){J(I);continue}}if($.metadataRegistry.get(I[0])?.id){J(I);continue}if(K.cycle){J(I);continue}if(K.count>1){if($.reused==="ref"){J(I);continue}}}}functionZ3($,Y){letz=$.seen.get(Y);if(!z)throwError("Unprocessed schema. This is a bug in Zod.");letU=(K)=>{letG=$.seen.get(K);if(G.ref===null)return;letW=G.def??G.schema,H={...W},X=G.ref;if(G.ref=null,X){U(X);letq=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))W.allOf=W.allOf??[],W.allOf.push(V);elseObject.assign(W,V);if(Object.assign(W,H),K._zod.parent===X)for(letMinW){if(M==="$ref"||M==="allOf")continue;if(!(MinH))deleteW[M]}if(V.$ref&&q.def)for(letMinW){if(M==="$ref"||M==="allOf")continue;if(Minq.def&&JSON.stringify(W[M])===JSON.stringify(q.def[M]))deleteW[M]}}letZ=K._zod.parent;if(Z&&Z!==X){U(Z);letq=$.seen.get(Z);if(q?.schema.$ref){if(W.$ref=q.schema.$ref,q.def)for(letVinW){if(V==="$ref"||V==="allOf")continue;if(Vinq.def&&JSON.stringify(W[V])===JSON.stringify(q.def[V]))deleteW[V]}}}$.override({zodSchema:K,jsonSchema:W,path:G.path??[]})};for(letKof[...$.seen.entries()].reverse())U(K[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){letK=$.external.registry.get(Y)?.id;if(!K)throwError("Schema is missing an `id` property");Q.$id=$.external.uri(K)}Object.assign(Q,z.def??z.schema);letJ=$.metadataRegistry.get(Y)?.id;if(J!==void0&&Q.id===J)deleteQ.id;letI=$.external?.defs??{};for(letKof$.seen.entries()){letG=K[1];if(G.def&&G.defId){if(G.def.id===G.defId)deleteG.def.id;I[G.defId]=G.def}}if($.external);elseif(Object.keys(I).length>0)if($.target==="draft-2020-12")Q.$defs=I;elseQ.definitions=I;try{letK=JSON.parse(JSON.stringify(Q));returnObject.defineProperty(K,"~standard",{value:{...Y["~standard"],jsonSchema:{input:IQ(Y,"input",$.processors),output:IQ(Y,"output",$.processors)}},enumerable:!1,writable:!1}),K}catch(K){throwError("Error converting schema to JSON.")}}functionA8($,Y){letz=Y??{seen:newSet};if(z.seen.has($))return!1;z.seen.add($);letU=$._zod.def;if(U.type==="transform")return!0;if(U.type==="array")returnA8(U.element,z);if(U.type==="set")returnA8(U.valueType,z);if(U.type==="lazy")returnA8(U.getter(),z);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")returnA8(U.innerType,z);if(U.type==="intersection")returnA8(U.left,z)||A8(U.right,z);if(U.type==="record"||U.type==="map")returnA8(U.keyType,z)||A8(U.valueType,z);if(U.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;returnA8(U.in,z)||A8(U.out,z)}if(U.type==="object"){for(letQinU.shape)if(A8(U.shape[Q],z))return!0;return!1}if(U.type==="union"){for(letQofU.options)if(A8(Q,z))return!0;return!1}if(U.type==="tuple"){for(letQofU.items)if(A8(Q,z))return!0;if(U.rest&&A8(U.rest,z))return!0;return!1}return!1}vartR=($,Y={})=>(z)=>{letU=H3({...z,processors:Y});returnI4($,U),X3(U,$),Z3(U,$)},IQ=($,Y,z={})=>(U)=>{let{libraryOptions:Q,target:J}=U??{},I=H3({...Q??{},target:J,io:Y,processors:z});returnI4($,I),X3(I,$),Z3(I,$)};varVG=o(()=>{XG()});functionRY($,Y){if("_idmap"in$){letU=$,Q=H3({...Y,processors:kV}),J={};for(letGofU._idmap.entries()){let[W,H]=G;I4(H,Q)}letI={},K={registry:U,uri:Y?.uri,defs:J};Q.external=K;for(letGofU._idmap.entries()){let[W,H]=G;X3(Q,H),I[W]=Z3(Q,H)}if(Object.keys(J).length>0){letG=Q.target==="draft-2020-12"?"$defs":"definitions";I.__shared={[G]:J}}return{schemas:I}}letz=H3({...Y,processors:kV});returnI4($,z),X3(z,$),Z3(z,$)}varXx0,eR=($,Y,z,U)=>{letQ=z;Q.type="string";let{minimum:J,maximum:I,format:K,patterns:G,contentEncoding:W}=$._zod.bag;if(typeofJ==="number")Q.minLength=J;if(typeofI==="number")Q.maxLength=I;if(K){if(Q.format=Xx0[K]??K,Q.format==="")deleteQ.format;if(K==="time")deleteQ.format}if(W)Q.contentEncoding=W;if(G&&G.size>0){letH=[...G];if(H.length===1)Q.pattern=H[0].source;elseif(H.length>1)Q.allOf=[...H.map((X)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:X.source}))]}},$_=($,Y,z,U)=>{letQ=z,{minimum:J,maximum:I,format:K,multipleOf:G,exclusiveMaximum:W,exclusiveMinimum:H}=$._zod.bag;if(typeofK==="string"&&K.includes("int"))Q.type="integer";elseQ.type="number";letX=typeofH==="number"&&H>=(J??Number.NEGATIVE_INFINITY),Z=typeofW==="number"&&W<=(I??Number.POSITIVE_INFINITY),q=Y.target==="draft-04"||Y.target==="openapi-3.0";if(X)if(q)Q.minimum=H,Q.exclusiveMinimum=!0;elseQ.exclusiveMinimuLine truncated
`}function df0($){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(!pf0.test($)){let z=[...$].filter((U)=>!/[A-Za-z0-9._-]/.test(U)).filter((U,Q,J)=>J.indexOf(U)===Q);return Y.push(`Toolnamecontainsinvalidcharacters:${z.map((U)=>`"${U}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function mf0($,Y){if(Y.length>0){console.warn(`Toolnamevalidationwarningfor"${$}":`);for(let z of Y)console.warn(`-${z}`);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 rh($){let Y=df0($);return mf0($,Y.warnings),Y.isValid}function lf0($){return typeof $==="object"&&$!==null&&"_zod"in $}function of0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function rf0($){if(typeof $!=="object"||$===null)return!1;if(RQ($))return!1;let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return!1;return Object.values($).every((z)=>lf0(z))}function Bw($){if($===void 0)return;if(rf0($))return z0($);if(typeof $==="object"&&$!==null&&!RQ($)&&Object.values($).some((Y)=>of0(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(!RQ($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var Ph,Ex0,B1,V1,Cx0,ea="2026-07-28",T3,zt,vx0,hx0,Sx0,Jt,It,yx0,Iw,Ex1,Cx1,ia,vh,ix0,cx0,EQ,n0,J1,Lw,Wt,vQ,Fw,dx0=0,mx0="private",lx0,Yf0,Gw,yh,Zt,Rx1,_x1,Kf0,Gf0,kh,Ww,WW="2026-07-28",Lt,Xf0,D$=($)=>yG.safeParse($).success,j3=($)=>kG.safeParse($).success,KW=($)=>FQ.safeParse($).success,Nw=($)=>wQ.safeParse($).success,r9=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",ma="x-mcp-header",Zf0,qf0,Vf0,Lf0,Zw=-32020,vx1,Ff0,la=!1,Th="draft-2020-12",Of0,Af0,Tf0,oa,jf0,hf0,Mt=250,Sf0,gf0,Bt,Pt,yf0,kf0,Tt=60000,ff0,uf0,bf0,jt,dh,nf0,hx1,Et=10485760,lh=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??Et}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 Ct(Y)}catch(z){if(z instanceof SyntaxError)continue;throw z}}return null}clear(){this._buffer=void 0}},pf0;var Pw=o(()=>{bT();iT();fa();cv();Ph=Symbol.for("mcp.sdk.errorBrands");Ex0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](Y){return CQ(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 CQ(this,Y)}constructor(Y,z,U){super(z);this.code=Y,this.errorUri=U,this.name="OAuthError",Eh(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)}},B1=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",$}({}),V1=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return CQ(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 CQ(this,$)}constructor($,Y,z){super(Y);this.code=$,this.data=z,this.name="SdkError",Eh(this,new.target)}},Cx0=class extends V1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,Y,z){super($,Y,z);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};T3=[ea];zt=["task","inputRequests","requestState"];hx0=new Set(["const","enum","default","examples"]),Sx0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);Jt={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},It={"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},yx0={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};Ex1=Object.keys(Jt),Cx1=Object.keys(It);ia={ok:!1,reason:"not-in-era"};vh={era:"2025-11-25",hasRequestMethod:Kt,hasNotificationMethod:Gt,validateRequest:($,Y)=>Kw(fx0($),Y),validateResult:($,Y)=>Kw(xx0($),Y),validateNotification:($,Y)=>Kw(ux0($),Y),hasInputRequestMethod:()=>!1,validateInputRequest:()=>ia,validateInputResponse:()=>ia,samplingResultVariant:($,Y)=>{let z=Ut();return Kw($?z.CreateMessageResultWithToolsSchema:z.CreateMessageResultSchema,Y)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,Y){let z=Yt($),U=z.structuredContent;if(U===void 0)return z;let Q=typeof U!=="object"||U===null||Array.isArray(U),J=Y!==void 0&&Qt(Y);if(!Q&&!J)return z;return{...z,structuredContent:{result:U}}},decodeResult($,Y){if(Ah(Y)&&"resultType"in Y){let z={...Y};return delete z.resultType,{kind:"complete",result:na(z)}}return{kind:"complete",result:na(Y)}},encodeResult($,Y){if($!=="tools/list")return Y;l
Line truncated
*content-type
*Copyright(c)2015DouglasChristopherWilson
*MITLicensed
*/nf0=R0(($)=>{var Y=/;*([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,z=/\\([\u000b\u0020-\u00ff])/g,U=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;$.parse=Q;function Q(K){if(!K)throw TypeError("argument string is required");var G=typeof K==="object"?J(K):K;if(typeof G!=="string")throw TypeError("argument string is required to be a string");var W=G.indexOf(";"),H=W!==-1?G.slice(0,W).trim():G.trim();if(!U.test(H))throw TypeError("invalid media type");var X=new I(H.toLowerCase());if(W!==-1){var Z,q,V;Y.lastIndex=W;while(q=Y.exec(G)){if(q.index!==W)throw TypeError("invalid parameter format");if(W+=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(z,"$1")}X.parameters[Z]=V}if(W!==G.length)throw TypeError("invalid parameter format")}return X}function J(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 I(K){this.parameters=Object.create(null),this.type=K}}),hx1=kq(nf0(),1);pf0=/^[A-Za-z0-9._-]{1,128}$/});function sh($){let Y=new $({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Xb0(Y),Y}var Aw,Rt,L1,v1,U5,jw,sf0,_t,vt,Tw,af0,Q5,tf0,ef0,ht,$u0,Ew,hQ,XW,SQ,Cw,Yu0,St,zu0,Uu0,Qu0,ah,Ju0,th,gt,Iu0,Ku0,Gu0,Wu0,Hu0,Xu0,Zu0,qu0,eh,Vu0,Lu0,Fu0,yt,kt,xt,wu0,Mu0,Ou0,$S,Nu0,ft,Du0,Bu0,Pu0,Au0,Tu0,ju0,Eu0,Cu0,ut,Ru0,bt,it,ct,_u0,YS,vu0,nt,pt,dt,hu0,Su0,mt,gu0,yu0,ku0,lt,xu0,fu0,ot,uu0,bu0,iu0,cu0,nu0,pu0,du0,mu0,lu0,ou0,ru0,su0,au0,tu0,eu0,$b0,Yb0,zb0,Ub0,Qb0,Jb0,Ib0,Kb0,rt,Gb0,Wb0,Hb0,Xb0,Rw=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor($){this._userAjv=$!==void 0,this._ajv=$}get ajv(){return this._ajv??=sh(Wb0.Ajv2020)}_engineFor($){if(this._userAjv)return this.ajv;let Y=Eo($,"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??=sh(Gb0.Ajv2019);return this._ajvDraft7??=sh(rt.Ajv)}getValidator($){let Y=this._engineFor($),z="$id"in $&&typeof $.$id==="string"?Y.getSchema($.$id)??Y.compile($):Y.compile($);return(U)=>{return z(U)?{valid:!0,data:U,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:Y.errorsText(z.errors)}}}},px1;var st=o(()=>{bT();iT();Aw=R0(($)=>{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 z=class extends Y{constructor(w){super();if(!$.IDENTIFIER.test(w))throw Error("CodeGen: name must be a valid identifier");this.str=w}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};$.Name=z;var U=class extends Y{constructor(w){super();this._items=typeof w==="string"?[w]:w}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let w=this._items[0];return w===""||w==='""'}get str(){var w;return(w=this._str)!==null&&w!==void 0?w:this._str=this._items.reduce((O,N)=>`${O}${N}`,"")}get names(){var w;return(w=this._names)!==null&&w!==void 0?w:this._names=this._items.reduce((O,N)=>{if(N instanceof z)O[N.str]=(O[N.str]||0)+1;return O},{})}};$._Code=U,$.nil=new U("");function Q(w,...O){let N=[w[0]],D=0;while(D<O.length)K(N,O[D]),N.push(w[++D]);return new U(N)}$._=Q;let J=new U("+");function I(w,...O){let N=[q(w[0])],D=0;while(D<O.length)N.push(J),K(N,O[D]),N.push(J,q(w[++D]));return G(N),new U(N)}$.str=I;function K(w,O){if(O instanceof U)w.push(...O._items);else if(O instanceof z)w.push(O);else w.push(X(O))}$.addCodeArg=K;function G(w){let O=1;while(O<w.length-1){if(w[O]===J){let N=W(w[O-1],w[O+1]);if(N!==void 0){w.splice(O-1,3,N);continue}w[O++]="+"}O++}}function W(w,O){if(O==='""')return w;if(w==='""')return O;if(typeof w=="string"){if(O instanceof z||w[w.length-1]!=='"')return;if(typeof O!="string")return`${w.slice(0,-1)}${O}"`;if(O[0]==='"')return w.slice(0,-1)+O.slice(1);return}if(typeof O=="string"&&O[0]==='"'&&!(w instanceof z))return`"${w}${O.slice(1)}`}function H(w,O){return O.emptyStr()?w:w.emptyStr()?O:I`${w}${O}`}$.strConcat=H;function X(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:q(Array.isArray(w)?w.join(","):w)}function Z(w){return new U(q(w))}$.stringify=Z;function q(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$.safeStringify=q;function V(w){return typeof w=="string"&&$.IDENTIFIER.test(w)?new U(`.${w}`):Q`[${w}]`}$.getProperty=V;function F(w){if(typeof w=="string"&&$.IDENTIFIER.test(w))returnnewU(`${w}`);throwError(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}$.getEsmExportName=F;functionM(w){returnnewU(w.toStringLine truncated
deps:${H}}`};let Q={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[W,H]=J(G);I(G,W),K(G,H)}};function J({schema:G}){let W={},H={};for(let X in G){if(X==="__proto__")continue;let Z=Array.isArray(G[X])?W:H;Z[X]=G[X]}return[W,H]}function I(G,W=G.schema){let{gen:H,data:X,it:Z}=G;if(Object.keys(W).length===0)return;let q=H.let("missing");for(let V in W){let F=W[V];if(F.length===0)continue;let M=(0,U.propertyInData)(H,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:F.length,deps:F.join(", ")}),Z.allErrors)H.if(M,()=>{for(let w of F)(0,U.checkReportMissingProp)(G,w)});else H.if(Y._`${M}&&(${(0,U.checkMissingProp)(G,F,q)})`),(0,U.reportMissingProp)(G,q),H.else()}}$.validatePropertyDeps=I;function K(G,W=G.schema){let{gen:H,data:X,keyword:Z,it:q}=G,V=H.name("valid");for(let F in W){if((0,z.alwaysValidSchema)(q,W[F]))continue;H.if((0,U.propertyInData)(H,X,F,q.opts.ownProperties),()=>{let M=G.subschema({keyword:Z,schemaProp:F},V);G.mergeValidEvaluated(M,V)},()=>H.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=K,$.default=Q}),Nu0=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=L1(),z=v1(),U={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:I,data:K,it:G}=Q;if((0,z.alwaysValidSchema)(G,I))return;let W=J.name("valid");J.forIn("key",K,(H)=>{Q.setParams({propertyName:H}),Q.subschema({keyword:"propertyNames",data:H,dataTypes:["string"],propertyName:H,compositeRule:!0},W),J.if((0,Y.not)(W),()=>{if(Q.error(!0),!G.allErrors)J.break()})}),Q.ok(W)}};$.default=U}),ft=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=Q5(),z=L1(),U=U5(),Q=v1(),J={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:I})=>z._`{additionalProperty:${I.additionalProperty}}`},code(I){let{gen:K,schema:G,parentSchema:W,data:H,errsCount:X,it:Z}=I;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 F=(0,Y.allSchemaProperties)(W.properties),M=(0,Y.allSchemaProperties)(W.patternProperties);w(),I.ok(z._`${X}===${U.default.errors}`);function w(){K.forIn("key",H,(A)=>{if(!F.length&&!M.length)D(A);else K.if(O(A),()=>D(A))})}function O(A){let B;if(F.length>8){let j=(0,Q.schemaRefOrVal)(Z,W.properties,"properties");B=(0,Y.isOwnProperty)(K,j,A)}else if(F.length)B=(0,z.or)(...F.map((j)=>z._`${A}===${j}`));else B=z.nil;if(M.length)B=(0,z.or)(B,...M.map((j)=>z._`${(0,Y.usePattern)(I,j)}.test(${A})`));return(0,z.not)(B)}function N(A){K.code(z._`delete${H}[${A}]`)}function D(A){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){N(A);return}if(G===!1){if(I.setParams({additionalProperty:A}),I.error(),!q)K.break();return}if(typeof G=="object"&&!(0,Q.alwaysValidSchema)(Z,G)){let B=K.name("valid");if(V.removeAdditional==="failing")T(A,B,!1),K.if((0,z.not)(B),()=>{I.reset(),N(A)});else if(T(A,B),!q)K.if((0,z.not)(B),()=>K.break())}}function T(A,B,j){let C={keyword:"additionalProperties",dataProp:A,dataPropType:Q.Type.Str};if(j===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});I.subschema(C,B)}}};$.default=J}),Du0=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=hQ(),z=Q5(),U=v1(),Q=ft(),J={keyword:"properties",type:"object",schemaType:"object",code(I){let{gen:K,schema:G,parentSchema:W,data:H,it:X}=I;if(X.opts.removeAdditional==="all"&&W.additionalProperties===void 0)Q.default.code(new Y.KeywordCxt(X,Q.default,"additionalProperties"));let Z=(0,z.allSchemaProperties)(G);for(let w of Z)X.definedProperties.add(w);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=U.mergeEvaluated.props(K,(0,U.toHash)(Z),X.props);let q=Z.filter((w)=>!(0,U.alwaysValidSchema)(X,G[w]));if(q.length===0)return;let V=K.name("valid");for(let w of q){if(F(w))M(w);else{if(K.if((0,z.propertyInData)(K,H,w,X.opts.ownProperties)),M(w),!X.allErrors)K.else().var(V,!0);K.endIf()}I.it.definedProperties.add(w),I.ok(V)}function F(w){return X.opts.useDefaults&&!X.compositeRule&&G[w].default!==void 0}function M(w){I.subschema({keyword:"properties",schemaProp:w,dataProp:w},V)}}};$.default=J}),Bu0=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=Q5(),z=L1(),U=v1(),Q=v1(),J={keyword:"patternProperties",type:"object",schemaType:"object",code(I){let{gen:K,schema:G,data:W,parentSchema:H,it:X}=I,{opts:Z}=X,q=(0,Y.allSchemaProperties)(G),V=q.filter((T)=>(0,U.alwaysValidSchema)(X,G[T]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let F=Z.strictSchema&&!Z.allowMatchingProperties&&H.properties,M=K.name("valid");if(X.props!==!0&&!(X.props instanceof z.Name))X.props=(0,Q.evaluatedPropsToName)(K,X.props);let{props:w}=X;O();function O(){for(let T of q){if(F)N(T);if(X.allErrors)
Line truncated
`)}openNode($,Y){let z=this.tos,U=this._xml;if(z&&this.open)U.push(">");this._stack.push($),U.push("<"),U.push($),Fk(U,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)N70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");Fk(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(O70.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,z){if(this.openNode($,Y),z!==void 0)this.writeText(z);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("")}}wk.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};D70.exports=wk});var Mk=E((Ca0)=>{var B70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function Ea0($){if(typeof $==="string")return $;if(B70)return B70.decode($);return $.toString()}Ca0.bufferToString=Ea0});var E70=E((A70)=>{Object.defineProperty(A70,"__esModule",{value:!0});A70.CHAR=`
`,$=this.i;break;case ot0:{let{entityReturnState:z}=this,U=this.entity+Y.slice($,this.prevI);this.state=z;let Q;if(U==="")this.fail("empty entity name."),Q="&;";else Q=this.parseEntity(U),this.entity="";if(z!==C8||this.textHandler!==void 0)this.text+=Q;break $}case k4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(EH($))this.state=nt0,this.unget(),this.xmlDeclPossible=!1;else switch($){case bO:this.state=mt0,this.xmlDeclPossible=!1;break;case s70:this.state=St0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case o6:this.state=ft0;break;default:this.fail("disallowed character in tag name"),this.state=C8,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=Ck,this.openWakaBang="";break;case"--":this.state=Ek,this.openWakaBang="";break;case"DOCTYPE":if(this.state=Ak,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(uO))this.state=gt0}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===uO)this.state=yt0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=Ek}sCommentEnded(){let $=this.getCodeNorm();if($!==A6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Ek;else this.state=C8}sCData(){if(this.captureToChar(TJ))this.state=kt0}sCDataEnding(){let $=this.getCodeNorm();if($===TJ)this.state=xt0;else this.text+=`]${String.fromCodePoint($)}`,this.state=Ck}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case A6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=C8;break}case TJ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=Ck}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=n70;else if($===o6||p8($))this.fail("processing instruction without a target."),this.state=$===o6?fO:Rk;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=n70}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let z=this.getCodeNorm();if(z===k4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(z)){this.piTarget+=$.slice(Y,this.prevI);let U=z===o6;if(U||p8(z))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=U?Iz:p70}else this.state=U?fO:Rk;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(z);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===o6)this.state=fO;else if(!p8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(o6))this.state=fO}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===A6){let{piTarget:z}=this;if(z.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:z,body:this.text}),this.piTarget=this.text="",this.state=C8}else if(Y===o6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=Rk;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===o6){this.state=Iz;return}if($!==k4)this.state=ut0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(at0);if($===o6){this.state=Iz,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(p8($)||$===AJ))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=$===AJ?d70:bt0}sXMLDeclEq(){let $=this.getCodeNorm();if($===o6){this.state=Iz,this.fail("XML declaration is incomplete.");return}if(p8($))return;if($!==AJ)this.fail("value required.");this.state=d70}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===o6){this.state=Iz,this.fail("XML declaration is incomplete.");return}if(p8($))return;if(!iO($))this.fail("value must be quoted."),this.q=r70;else this.q=$;this.state=it0}sXMLDeclValue(){let $=this.captureTo([this.q,o6]);if($===o6){this.state=Iz,this.text="",this.fail("XML declaration is incomplete.");return}if($===k4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let z=Y;if(this.xmlDecl.version=z,!/^1\.[0-9]+$/.test(z))this.fail("ver
Line truncated
See:https://github.com/isaacs/node-glob/issues/167`);return new M6($,q).found}function M6($,q){if(!$)throw Error("must provide pattern");if(typeof q==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See:https://github.com/isaacs/node-glob/issues/167`);return new T6($,Y).found}function T6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
`+z0[V0-1];break}}}var D1="a promise was created in a "+D+"handler "+q0+"but was not returned from it, see http://goo.gl/rRqMUw"+r;h._warn(D1,!0,N)}}function w0(o,N){var D=o+" is deprecated and will be removed in a future version.";if(N)D+=" Use "+N+" instead.";return T0(D)}function T0(o,N,D){if(!L0.warnings)return;var h=new U(o),x;if(N)D._attachExtraTrace(h);else if(L0.longStackTraces&&(x=$._peekContext()))x.attachExtraTrace(h);else{var q0=f0(h);h.stack=q0.message+`
`+Z0[P0-1];break}}}var N1="a promise was created in a "+v+"handler "+X0+"but was not returned from it, see http://goo.gl/rRqMUw"+J0;u._warn(N1,!0,P)}}function y(Q0,P){var v=Q0+" is deprecated and will be removed in a future version.";if(P)v+=" Use "+P+" instead.";return s(v)}function s(Q0,P,v){if(!B0.warnings)return;var u=new Q(Q0),r;if(P)v._attachExtraTrace(u);else if(B0.longStackTraces&&(r=$._peekContext()))r.attachExtraTrace(u);else{var X0=b0(u);u.stack=X0.message+`
`)));return}}O=O._target();var A=O._bitField;if((A&50397184)===0)this._yieldedPromise=O,O._proxy(this,null);else if((A&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,O._value());else if((A&16777216)!==0)$._async.invoke(this._promiseRejected,this,O._reason());else this._promiseCancelled()}},$.coroutine=function(w,L){if(typeof w!=="function")throw new Q(`generatorFunctionmustbeafunction
`)));return}}w=w._target();var O=w._bitField;if((O&50397184)===0)this._yieldedPromise=w,w._proxy(this,null);else if((O&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,w._value());else if((O&16777216)!==0)$._async.invoke(this._promiseRejected,this,w._reason());else this._promiseCancelled()}},$.coroutine=function(V,F){if(typeof V!=="function")throw new K(`generatorFunctionmustbeafunction
Seehttp://goo.gl/MqrFmX
`);var F=Object(L).yieldHandler,O=X,A=Error().stack;return function(){var B=w.apply(this,arguments),P=new O(void 0,void 0,F,A),T=P.promise();return P._generator=B,P._promiseFulfilled(void 0),T}},$.coroutine.addYieldHandler=function(w){if(typeof w!=="function")throw new Q("expecting a function but got "+K.classString(w));Z.push(w)},$.spawn=function(w){if(I.deprecated("Promise.spawn()","Promise.coroutine()"),typeof w!=="function")return q(`generatorFunctionmustbeafunction
`);var M=Object(F).yieldHandler,w=q,O=Error().stack;return function(){var N=V.apply(this,arguments),D=new w(void 0,void 0,M,O),T=D.promise();return D._generator=N,D._promiseFulfilled(void 0),T}},$.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(J.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return Y(`generatorFunctionmustbeafunction
`)},q=function(){return new g.PromiseInspection(this._target())},Y=function(j){return g.reject(new Z(j))};function z(){}var U={},I=G4(),J;if(I.isNode)J=function(){var j=process.domain;if(j===void 0)j=null;return j};else J=function(){return null};I.notEnumerableProp(g,"_getDomain",J);var Q=kq(),K=yF0(),H=new K;Q.defineProperty(g,"_async",{value:H});var G=e9(),Z=g.TypeError=G.TypeError;g.RangeError=G.RangeError;var V=g.CancellationError=G.CancellationError;g.TimeoutError=G.TimeoutError,g.OperationalError=G.OperationalError,g.RejectionError=G.OperationalError,g.AggregateError=G.AggregateError;var X=function(){},w={},L={},F=bF0()(g,X),O=nF0()(g,X,F,Y,z),A=pF0()(g),B=A.create,P=mF0()(g,A),T=P.CapturedTrace,y=oF0()(g,F),v=sF0()(L),k=cf(),R=I.errorObj,c=I.tryCatch;function n(j,u){if(typeof u!=="function")throw new Z("expecting a function but got "+I.classString(u));if(j.constructor!==g)throw new Z(`thepromiseconstructorcannotbeinvokeddirectly
`)},Y=function(){return new h.PromiseInspection(this._target())},z=function(x){return h.reject(new X(x))};function U(){}var Q={},J=F4(),I;if(J.isNode)I=function(){var x=process.domain;if(x===void 0)x=null;return x};else I=function(){return null};J.notEnumerableProp(h,"_getDomain",I);var K=pz(),G=HF0(),W=new G;K.defineProperty(h,"_async",{value:W});var H=T7(),X=h.TypeError=H.TypeError;h.RangeError=H.RangeError;var Z=h.CancellationError=H.CancellationError;h.TimeoutError=H.TimeoutError,h.OperationalError=H.OperationalError,h.RejectionError=H.OperationalError,h.AggregateError=H.AggregateError;var q=function(){},V={},F={},M=LF0()(h,q),w=wF0()(h,q,M,z,U),O=OF0()(h),N=O.create,D=DF0()(h,O),T=D.CapturedTrace,A=PF0()(h,M),B=TF0()(F),j=Yc(),C=J.errorObj,b=J.tryCatch;function k(x,d){if(typeof d!=="function")throw new X("expecting a function but got "+J.classString(d));if(x.constructor!==h)throw new X(`thepromiseconstructorcannotbeinvokeddirectly
Seehttp://goo.gl/MqrFmX
`)}function g(j){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,j!==X)n(this,j),this._resolveFromExecutor(j);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(j){var u=arguments.length;if(u>1){var p=Array(u-1),d=0,Y0;for(Y0=0;Y0<u-1;++Y0){var t=arguments[Y0];if(I.isObject(t))p[d++]=t;else return Y("expecting an object but got A catch statement predicate "+I.classString(t))}return p.length=d,j=arguments[Y0],this.then(void 0,v(p,j,this))}return this.then(void 0,j)},g.prototype.reflect=function(){return this._then(q,q,void 0,this,void 0)},g.prototype.then=function(j,u){if(P.warnings()&&arguments.length>0&&typeof j!=="function"&&typeof u!=="function"){var p=".then() only accepts functions but was passed: "+I.classString(j);if(arguments.length>1)p+=", "+I.classString(u);this._warn(p)}return this._then(j,u,void 0,void 0,void 0)},g.prototype.done=function(j,u){var p=this._then(j,u,void 0,void 0,void 0);p._setIsFinal()},g.prototype.spread=function(j){if(typeof j!=="function")return Y("expecting a function but got "+I.classString(j));return this.all()._then(j,void 0,void 0,w,void 0)},g.prototype.toJSON=function(){var j={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())j.fulfillmentValue=this.value(),j.isFulfilled=!0;else if(this.isRejected())j.rejectionReason=this.reason(),j.isRejected=!0;return j},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new O(this).promise()},g.prototype.error=function(j){return this.caught(I.originatesFromRejection,j)},g.getNewLibraryCopy=df.exports,g.is=function(j){return j instanceof g},g.fromNode=g.fromCallback=function(j){var u=new g(X);u._captureStackTrace();var p=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,d=c(j)(k(u,p));if(d===R)u._rejectCallback(d.e,!0);if(!u._isFateSealed())u._setAsyncGuaranteed();return u},g.all=function(j){return new O(j).promise()},g.cast=function(j){var u=F(j);if(!(u instanceof g))u=new g(X),u._captureStackTrace(),u._setFulfilled(),u._rejectionHandler0=j;return u},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(j){var u=new g(X);return u._captureStackTrace(),u._rejectCallback(j,!0),u},g.setScheduler=function(j){if(typeof j!=="function")throw new Z("expecting a function but got "+I.classString(j));return H.setScheduler(j)},g.prototype._then=function(j,u,p,d,Y0){var t=Y0!==void 0,H0=t?Y0:new g(X),w0=this._target(),T0=w0._bitField;if(!t){if(H0._propagateFrom(this,3),H0._captureStackTrace(),d===void 0&&(this._bitField&2097152)!==0)if((T0&50397184)!==0)d=this._boundValue();else d=w0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,H0)}var R0=J();if((T0&50397184)!==0){var E0,i0,Q0=w0._settlePromiseCtx;if((T0&33554432)!==0)i0=w0._rejectionHandler0,E0=j;else if((T0&16777216)!==0)i0=w0._fulfillmentHandler0,E0=u,w0._unsetRejectionIsUnhandled();else Q0=w0._settlePromiseLateCancellationObserver,i0=new V("late cancellation observer"),w0._attachExtraTrace(i0),E0=u;H.invoke(Q0,w0,{handler:R0===null?E0:typeof E0==="function"&&I.domainBind(R0,E0),promise:H0,receiver:d,value:i0})}else w0._addCallbacks(j,u,H0,d,R0);return H0},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(j){this._bitField=this._bitField&-65536|j&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(j){var u=j===0?this._receiver0:this[j*4-4+3];if(u===U)return;else if(u===void 0&&this._isBound())return this._boundValue();return u},g.prototype._promiseAt=function(j){return this[j*4-4+2]},g.prototype._fulfillmentHandlerAt=function(j){return this[j*4-4+0]},g.prototype._rejectionHandlerAt=function(j){return this[j*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(j){var{_bitField:u
Line truncated
`)}function h(x){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,x!==q)k(this,x),this._resolveFromExecutor(x);this._promiseCreated(),this._fireEvent("promiseCreated",this)}h.prototype.toString=function(){return"[object Promise]"},h.prototype.caught=h.prototype.catch=function(x){var d=arguments.length;if(d>1){var t=Array(d-1),$0=0,g;for(g=0;g<d-1;++g){var p=arguments[g];if(J.isObject(p))t[$0++]=p;else return z("expecting an object but got A catch statement predicate "+J.classString(p))}return t.length=$0,x=arguments[g],this.then(void 0,B(t,x,this))}return this.then(void 0,x)},h.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},h.prototype.then=function(x,d){if(D.warnings()&&arguments.length>0&&typeof x!=="function"&&typeof d!=="function"){var t=".then() only accepts functions but was passed: "+J.classString(x);if(arguments.length>1)t+=", "+J.classString(d);this._warn(t)}return this._then(x,d,void 0,void 0,void 0)},h.prototype.done=function(x,d){var t=this._then(x,d,void 0,void 0,void 0);t._setIsFinal()},h.prototype.spread=function(x){if(typeof x!=="function")return z("expecting a function but got "+J.classString(x));return this.all()._then(x,void 0,void 0,V,void 0)},h.prototype.toJSON=function(){var x={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())x.fulfillmentValue=this.value(),x.isFulfilled=!0;else if(this.isRejected())x.rejectionReason=this.reason(),x.isRejected=!0;return x},h.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new w(this).promise()},h.prototype.error=function(x){return this.caught(J.originatesFromRejection,x)},h.getNewLibraryCopy=Uc.exports,h.is=function(x){return x instanceof h},h.fromNode=h.fromCallback=function(x){var d=new h(q);d._captureStackTrace();var t=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,$0=b(x)(j(d,t));if($0===C)d._rejectCallback($0.e,!0);if(!d._isFateSealed())d._setAsyncGuaranteed();return d},h.all=function(x){return new w(x).promise()},h.cast=function(x){var d=M(x);if(!(d instanceof h))d=new h(q),d._captureStackTrace(),d._setFulfilled(),d._rejectionHandler0=x;return d},h.resolve=h.fulfilled=h.cast,h.reject=h.rejected=function(x){var d=new h(q);return d._captureStackTrace(),d._rejectCallback(x,!0),d},h.setScheduler=function(x){if(typeof x!=="function")throw new X("expecting a function but got "+J.classString(x));return W.setScheduler(x)},h.prototype._then=function(x,d,t,$0,g){var p=g!==void 0,e=p?g:new h(q),y=this._target(),s=y._bitField;if(!p){if(e._propagateFrom(this,3),e._captureStackTrace(),$0===void 0&&(this._bitField&2097152)!==0)if((s&50397184)!==0)$0=this._boundValue();else $0=y===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,e)}var Y0=I();if((s&50397184)!==0){var M0,E0,G0=y._settlePromiseCtx;if((s&33554432)!==0)E0=y._rejectionHandler0,M0=x;else if((s&16777216)!==0)E0=y._fulfillmentHandler0,M0=d,y._unsetRejectionIsUnhandled();else G0=y._settlePromiseLateCancellationObserver,E0=new Z("late cancellation observer"),y._attachExtraTrace(E0),M0=d;W.invoke(G0,y,{handler:Y0===null?M0:typeof M0==="function"&&J.domainBind(Y0,M0),promise:e,receiver:$0,value:E0})}else y._addCallbacks(x,d,e,$0,Y0);return e},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(x){this._bitField=this._bitField&-65536|x&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(W.hasCustomScheduler())return;this._bitField=this._bitField|134217728},h.prototype._receiverAt=function(x){var d=x===0?this._receiver0:this[x*4-4+3];if(d===Q)return;else if(d===void 0&&this._isBound())return this._boundValue();return d},h.prototype._promiseAt=function(x){return this[x*4-4+2]},h.prototype._fulfillmentHandlerAt=function(x){return this[x*4-4+0]},h.prototype._rejectionHandlerAt=function(x){return this[x*4-4+1]},h.prototype._boundValue=function(){},h.prototype._migrateCallback0=function(x){var{_bitField:d,_fulfillmentHandler
Line truncated
↳${w}`,operator:I}}function $P0($){if(!$)return[];let q=$.pending||[],Y=String($.rawState||"").toUpperCase(),z=String($.state||"").toUpperCase(),U=[];if(q.length>0)for(let I of q){let J=I.approver?.name||I.approver?.id||"待定",Q=(I.name||$.currentNode||"").trim(),K=Q?`${Q}(${J})`:J,G=I.type?.toUpperCase()==="PAYING"||Q.includes("支付")||Y==="PAYING"||z==="支付中"?"待支付":"待审批";U.push(`${K}:${G}`)}else if($.currentNode?.trim()){let J=$.currentNode.includes("支付")||Y==="PAYING"||z==="支付中"?"待支付":"待审批";U.push(`${$.currentNode.trim()}:${J}`)}return U}function tq($,q){let Y=new Map;if(!$||$.length===0)return Y;if(!q){for(let X of $){let L=(X.result||{}).decision||X.aiDecision||"-";Y.set(X.id,{recordId:X.id,sourceDocumentSN:X.sourceDocumentSN,taskMode:X.taskMode,aiDecision:eA0(typeof L==="string"?L:"-"),aiAction:"-",eHumanAction:"-",eHumanComment:"-",auditDrift:!1})}return Y}let z=[...$].sort((X,w)=>(Number(X.createdAt)||0)-(Number(w.createdAt)||0)),U=q.history||[],I=String(q.rawState||"").toUpperCase(),J=String(q.state||"").toUpperCase(),Q=I==="DRAFT"||I==="REVOKED"||I==="CANCELED"||I==="CANCELLED"||J==="草稿"||J==="已撤回"||J==="已取消",K=I==="REJECTED"||I==="TERMINATED"||J==="审批驳回"||J==="已驳回",H=!Q&&!K&&(I==="PAID"||J==="已支付"||U.some((X)=>!X.isEbot&&(X.rawAction==="freeflow.pay"||X.action==="支付成功"||X.action==="支付完成"))),G=!Q&&!K&&!H&&(I==="PAYING"||J==="支付中"||(q.pending||[]).some((X)=>X.isCurrent&&(X.type?.toUpperCase()==="PAYING"||X.name?.includes("支付")))||q.currentNode?.includes("支付")===!0),V=H||!Q&&!K&&!G&&(I==="COMPLETED"||I==="APPROVED"||J==="已完成"||J==="审批通过");for(let X=0;X<z.length;X++){let w=z[X];if(!w)continue;let L=Number(w.createdAt)||0,F=w.document||{},O=w.manualApprovalRecord||w.result?.manualApprovalRecord||F.manualApprovalRecord||{},A=typeof w.sourceExtendData?.nodeId==="string"?String(w.sourceExtendData.nodeId):void 0,B=typeof O.nodeId==="string"?String(O.nodeId):void 0,P=B?decodeURIComponent(B).replace(/^hcnode_/,"").replace(/_r\d+$/,""):void 0,T=A||P,y=T?U.find((L0)=>L0.nodeId&&(L0.nodeId===T||T.includes(L0.nodeId))):void 0,v=y?.time??L,k=z[X+1],R=k?Number(k.createdAt)||1/0:1/0,c=X===z.length-1,n=U.find((L0)=>(L0.time??0)>v+5000&&L0.isEbot&&(L0.nodeName?.includes("智能")||L0.nodeName?.includes("AI")||L0.action?.includes("智能")||L0.comment?.includes("AI")||L0.comment?.includes("approval-result"))&&!L0.nodeName?.includes("费用标准检查")&&!L0.nodeName?.includes("标准检查")&&!L0.nodeName?.includes("预算"));if(n){if(c=!1,(n.time??1/0)<R)R=n.time}let g=w.result||{},b=g.decision||w.aiDecision||"-",i=typeof b==="string"?b:"-",$0=i.toUpperCase(),j=$0==="REJECT"||$0==="驳回",u=$0==="APPROVE"||$0==="通过",p=$0==="EXEMPT_APPROVE"||$0==="免审通过"||$0==="备注通过",d=w.taskMode||w.finalExecutionMode||"",t=String(d).toLowerCase().includes("auto")||w.finalExecutionMode==="automatic"||d==="automatic"||d==="fully_automatic",H0="-";if(u||p)H0="添加评论";else if(j)H0=t?"驳回":"添加评论";else if($0==="REVIEW"||$0==="转交复核")H0="转交复核";let w0=typeof O.status==="object"&&O.status!==null?String(O.status.type||O.status.label||"").toUpperCase():"",T0=typeof O.status==="object"&&O.status!==null?String(O.status.sourceStatus||""):"",R0=F.manualApprovalStatus||g.manualApprovalStatus||w.manualApprovalStatus,E0=typeof R0==="string"?R0.toUpperCase():"",i0=E0==="CANCELLED"||E0==="CANCELED"||E0==="已取消"||E0==="已撤回"||E0==="REVOKED"||w0==="CANCELLED"||w0==="CANCELED"||T0.includes("撤回")||T0.includes("取消"),Q0=E0==="APPROVED"||E0==="已支付/审批完成"||E0==="已通过"||E0==="已完成"||E0==="已支付"||w0==="APPROVED",f0=!(T0.includes("补偿")||T0.includes("已支付"))&&(E0==="TERMINATED"||E0==="REJECTED"||E0==="REJECT"||E0==="已驳回"||E0==="被驳回"||w0==="TERMINATED"||w0==="REJECTED"||w0==="已驳回"||w0==="被驳回"),c0=y?1000:60000,R1=U.filter((L0)=>{let o=L0.time??0;return o>=v-c0&&o<R}),a0="-",r1="-",F1=!1,b1,$1,U6=u||p,a8=U.filter((L0)=>(L0.time??0)>v+5000),I6=a8.some((L0)=>L0.rawAction==="freeflow.retract"||L0.action==="单据撤回"),e8=a8.some((L0)=>L0.rawAction==="freeflow.submit"||L0.action==="提交送审");if(U6&&c&&(I6||e8))F1=!0,b1="AI通过后单据发生撤回/修改重提,后续未经AI复审";if(t&&j)a0="无操作",r1="-";else{let L0=R1.filter((D)=>(D.time??0)>=v-1000&&!D.isEbot&&D.rawAction!=="freeflow.submit"&&D.action!=="提交送审"&&!((D.rawAction==="freeflow.comment"||D.action==="发表评论")&&!D.comment)&&!((D.rawAction==="freeflow.print"||D.action==="打印提醒")&&!D.comment)&&!(D.rawAction==="freeflow.carbonCopy"||D.rawAction==="freeflow.cc"||D.action==="抄送通知")),o=L0.find((D)=>D.rawAction==="freeflow.retract"||D.action==="单据撤回"),N=L0.find((D)=>D.rawAction==="freeflow.reject"||D.action==="审批驳回");if(!c)if(N||!q&&f0){a0="审批驳回",F1=!1,b1=void 0;let D=Pi(N,void 0,O,U,q);
Line truncated
`,{mode:384}),q}function ki($){let q=MP0();for(let Y of q){if(!X$(Y))continue;for(let z of HD(Y).filter((U)=>U.endsWith(".json")).filter((U)=>!U.startsWith("example."))){let U=J9(Y,z);try{let I=ZD(U,"utf-8"),J=JSON.parse(I);if(J&&typeof J==="object"&&J.id===$)return U}catch{}}}return}function a7($,q){let Y=ki($);if(!Y)throw Error(`Enterpriseconfignotfound:${$}`);let U={...JSON.parse(ZD(Y,"utf-8")),...q};for(let J of Object.keys(q))if(q[J]===void 0)delete U[J];let I=gi.parse(U);return XP0(Y,`${JSON.stringify(I,null,2)}
`,"utf-8"),I}var yi="SEAL_USE_ENTERPRISES_DIR",VP0="SEAL_HOME_ENTERPRISES_DIR",wP0="SEAL_USE_USER_ENTERPRISES_DIR",LP0="SEAL_HOME_USER_ENTERPRISES_DIR",FP0="SEAL_USE_CONFIG_FILE",OP0="SEAL_HOME_CONFIG_FILE",iI,GD,KD,ZP0;var Q3=e(()=>{Si();iI=J9(WD(),".config","seal-use","enterprises"),GD=J9(WD(),".config","seal-home","enterprises"),KD=J9(WD(),".config","seal-use","config.json"),ZP0=J9(WD(),".config","seal-home","config.json")});function e7($,q,Y=[]){let z=q.corpId?.trim()||void 0,U=q.stateful?q.defaultCorpId?.trim()||void 0:void 0,I=z??U;if(I){let Q=$.find((G)=>G.id===I);if(Q)return Q;let K=$.find((G)=>G.id.toLowerCase()===I.toLowerCase());if(K)return K;let H=$.find((G)=>G.name.toLowerCase()===I.toLowerCase());if(H)return H;throw Error(`Noenterpriseconfigfoundfor${I}`)}if(!q.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-homeconfigmodestateful` 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: "+(Y.length?Y.join(", "):"the configured enterprise directories"))}import{existsSync as ui,mkdirSync as Qj1,readFileSync as Kj1,renameSync as Hj1,unlinkSync as Gj1,writeFileSync as Zj1}from"node:fs";import{homedir as Wj1}from"node:os";import{dirname as Xj1,join as Vj1}from"node:path";function bi(){let $=process.env[wj1]?.trim();if($)return $;return Lj1}function NP0($=new Date){return $.toISOString().slice(0,10)}function DP0($=fi,q=new Date){let Y=q.getTime()-Math.max(0,$-1)*86400000;return new Date(Y).toISOString().slice(0,10)}function AP0($=bi()){if(!ui($))return{};try{let q=Kj1($,"utf-8"),Y=JSON.parse(q);if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y;return{}}catch{return{}}}function Fj1($,q){let Y={};for(let[z,U]of Object.entries($)){if(!U||typeof U!=="object")continue;let I={},J=!1;for(let[Q,K]of Object.entries(U))if(typeof K==="number"&&K>0&&Q>=q)I[Q]=K,J=!0;if(J)Y[z]=I}return Y}function Oj1($,q=bi()){let Y=Xj1(q);if(!ui(Y))Qj1(Y,{recursive:!0,mode:448});let z=`${q}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{Zj1(z,JSON.stringify($,null,2),"utf-8"),Hj1(z,q)}catch(U){try{if(ui(z))Gj1(z)}catch{}throw U}}function PP0($,q=new Date){if(!$||typeof $!=="string")return;try{let Y=bi(),z=AP0(Y),U=NP0(q),I=DP0(fi,q),J=Fj1(z,I);J[$]=J[$]||{},J[$][U]=(J[$][U]??0)+1,Oj1(J,Y)}catch{}}function Mj1($,q=fi,Y=new Date){let z=new Map;try{let U=AP0(),I=DP0(q,Y),J=NP0(Y),Q=$??Object.keys(U);for(let K of Q){let H=U[K];if(!H){z.set(K,0);continue}let G=0;for(let[Z,V]of Object.entries(H))if(Z>=I&&Z<=J&&typeof V==="number")G+=V;z.set(K,G)}}catch{if($)for(let U of $)z.set(U,0)}return z}function BP0($,q,Y){let z=Y??Mj1($.map((U)=>U.id));return[...$].sort((U,I)=>{if(q){if(U.id===q&&I.id!==q)return-1;if(I.id===q&&U.id!==q)return 1}let J=z.get(U.id)??0,Q=z.get(I.id)??0;if(J!==Q)return Q-J;let K=U.name??U.id,H=I.name??I.id,G=K.localeCompare(H,"zh-CN");if(G!==0)return G;return U.id.localeCompare(I.id)})}var wj1="SEAL_USE_USAGE_FILE",Lj1,fi=7;var ii=e(()=>{Lj1=Vj1(Wj1(),".config","seal-use","usage.json")});function Nj1($,q){return $.map((Y)=>Y.trim()).filter(Boolean).map((Y)=>q?Y:Y.toLowerCase())}function Dj1($,q){return q?$:$.toLowerCase()}function Aj1($,q,Y,z){let U=Dj1($,z),I=q.filter((J)=>U.includes(J));if(Y==="all"&&I.length!==q.length)return[];return I}function Pj1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function Bj1($,q){if(q.fields&&!q.fields.has($.field))return[];let Y=Pj1($.value),z=[];return Y.forEach((U,I)=>{let J=Aj1(U,q.keywords,q.matchMode,q.caseSensitive);if(J.length===0)return;let Q=Math.max(0,I-q.contextLines),K=Math.min(Y.length,I+q.contextLines+1),H={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:I+1,matchedKeywords:J,matchedText:XD(U,q.maxChars),context:{before:q.snippetOnly?[]:Y.slice(Q,I).map((G)=>XD(G,q.maxChars)),line:XD(U,q.maxChars),after:q.snippetOnly?[]:Y.slice(I+1,K).map((G)=>XD(G,q.maxChars))},metadata:$.metadata};if(q.snippetOnly)H.context={before:[],line:H.context.line,after:[]};z.push(H)}),z}function XD($,q){if(!q||$.length<=q)return $;return`${$.slice(0,Math.max(0,q))}...`}function Tj1($){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 EP0($){return $.rules.flatMap((q,Y)=>{let z=`${$.id}:${q.description.slice(0,32)}`,U={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:q.scope,strictness:q.strictness,code:"code"in q?q.code:void 0,index:Y};return[{area:"rules",entityType:"rule",entityId:z,title:`${$.versionName}/${q.scope}`,field:"history.description",
Line truncated
`,{mode:384}),Y}function sn($){let Y=oD0();for(let z of Y){if(!V$(z))continue;for(let U of _P(z).filter((Q)=>Q.endsWith(".json")).filter((Q)=>!Q.startsWith("example."))){let Q=N9(z,U);try{let J=hP(Q,"utf-8"),I=JSON.parse(J);if(I&&typeof I==="object"&&I.id===$)return Q}catch{}}}return}function x2($,Y){let z=sn($);if(!z)throw Error(`Enterpriseconfignotfound:${$}`);let Q={...JSON.parse(hP(z,"utf-8")),...Y};for(let I of Object.keys(Y))if(Y[I]===void 0)delete Q[I];let J=mn.parse(Q);return cD0(z,`${JSON.stringify(J,null,2)}
`,"utf-8"),J}var on="SEAL_USE_ENTERPRISES_DIR",nD0="SEAL_HOME_ENTERPRISES_DIR",pD0="SEAL_USE_USER_ENTERPRISES_DIR",dD0="SEAL_HOME_USER_ENTERPRISES_DIR",mD0="SEAL_USE_CONFIG_FILE",lD0="SEAL_HOME_CONFIG_FILE",rI,vP,RP,bD0;var S7=o(()=>{ln();rI=N9(SP(),".config","seal-use","enterprises"),vP=N9(SP(),".config","seal-home","enterprises"),RP=N9(SP(),".config","seal-use","config.json"),bD0=N9(SP(),".config","seal-home","config.json")});function f2($,Y,z=[]){let U=Y.corpId?.trim()||void 0,Q=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,J=U??Q;if(J){let K=$.find((H)=>H.id===J);if(K)return K;let G=$.find((H)=>H.id.toLowerCase()===J.toLowerCase());if(G)return G;let W=$.find((H)=>H.name.toLowerCase()===J.toLowerCase());if(W)return W;throw Error(`Noenterpriseconfigfoundfor${J}`)}if(!Y.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-homeconfigmodestateful` to enable a default enterprise.");let I=$[0];if(I)return I;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(z.length?z.join(", "):"the configured enterprise directories"))}import{existsSync as an,mkdirSync as aO1,readFileSync as tO1,renameSync as eO1,unlinkSync as $N1,writeFileSync as YN1}from"node:fs";import{homedir as zN1}from"node:os";import{dirname as UN1,join as QN1}from"node:path";function jZ(){let $=process.env[JN1]?.trim();if($)return $;return IN1}function rD0($=new Date){return $.toISOString().slice(0,10)}function sD0($=tn,Y=new Date){let z=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(z).toISOString().slice(0,10)}function aD0($=jZ()){if(!an($))return{};try{let Y=tO1($,"utf-8"),z=JSON.parse(Y);if(z&&typeof z==="object"&&!Array.isArray(z))return z;return{}}catch{return{}}}function KN1($,Y){let z={};for(let[U,Q]of Object.entries($)){if(!Q||typeof Q!=="object")continue;let J={},I=!1;for(let[K,G]of Object.entries(Q))if(typeof G==="number"&&G>0&&K>=Y)J[K]=G,I=!0;if(I)z[U]=J}return z}function GN1($,Y=jZ()){let z=UN1(Y);if(!an(z))aO1(z,{recursive:!0,mode:448});let U=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{YN1(U,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),eO1(U,Y)}catch(Q){try{if(an(U))$N1(U)}catch{}throw Q}}function tD0($,Y=new Date){if(!$||typeof $!=="string")return;try{let z=jZ(),U=aD0(z),Q=rD0(Y),J=sD0(tn,Y),I=KN1(U,J);I[$]=I[$]||{},I[$][Q]=(I[$][Q]??0)+1,GN1(I,z)}catch{}}function WN1($,Y=tn,z=new Date){let U=new Map;try{let Q=aD0(),J=sD0(Y,z),I=rD0(z),K=$??Object.keys(Q);for(let G of K){let W=Q[G];if(!W){U.set(G,0);continue}let H=0;for(let[X,Z]of Object.entries(W))if(X>=J&&X<=I&&typeof Z==="number")H+=Z;U.set(G,H)}}catch{if($)for(let Q of $)U.set(Q,0)}return U}function eD0($,Y,z){let U=z??WN1($.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 I=U.get(Q.id)??0,K=U.get(J.id)??0;if(I!==K)return K-I;let G=Q.name??Q.id,W=J.name??J.id,H=G.localeCompare(W,"zh-CN");if(H!==0)return H;return Q.id.localeCompare(J.id)})}var JN1="SEAL_USE_USAGE_FILE",IN1,tn=7;var gP=o(()=>{IN1=QN1(zN1(),".config","seal-use","usage.json")});function HN1($,Y){return $.map((z)=>z.trim()).filter(Boolean).map((z)=>Y?z:z.toLowerCase())}function XN1($,Y){return Y?$:$.toLowerCase()}function ZN1($,Y,z,U){let Q=XN1($,U),J=Y.filter((I)=>Q.includes(I));if(z==="all"&&J.length!==Y.length)return[];return J}function qN1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function VN1($,Y){if(Y.fields&&!Y.fields.has($.field))return[];let z=qN1($.value),U=[];return z.forEach((Q,J)=>{let I=ZN1(Q,Y.keywords,Y.matchMode,Y.caseSensitive);if(I.length===0)return;let K=Math.max(0,J-Y.contextLines),G=Math.min(z.length,J+Y.contextLines+1),W={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:J+1,matchedKeywords:I,matchedText:yP(Q,Y.maxChars),context:{before:Y.snippetOnly?[]:z.slice(K,J).map((H)=>yP(H,Y.maxChars)),line:yP(Q,Y.maxChars),after:Y.snippetOnly?[]:z.slice(J+1,G).map((H)=>yP(H,Y.maxChars))},metadata:$.metadata};if(Y.snippetOnly)W.context={before:[],line:W.context.line,after:[]};U.push(W)}),U}function yP($,Y){if(!Y||$.length<=Y)return $;return`${$.slice(0,Math.max(0,Y))}...`}function LN1($){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 YB0($){return $.rules.flatMap((Y,z)=>{let U=`${$.id}:${Y.description.slice(0,32)}`,Q={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:z};return[{area:"rules",entityType:"rule",entityId:U,title:`${$.versionName}/${Y.scope}`,field:"h
Line truncated
@@ -870,55 +876,62 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
}
exportdefaultlintRule;
`}});import{existsSync as $Y,mkdirSync as tj1,readFileSync as aj1,readdirSync as uP0,rmSync as ej1,unlinkSync as $_1,writeFileSync as q_1}from"node:fs";import{homedir as Y_1}from"node:os";import{isAbsolute as z_1,join as R6,resolve as U_1}from"node:path";import{pathToFileURL as xP0}from"node:url";function fP0($=i$){let q=[],Y=[];try{if(!$Y($))tj1($,{recursive:!0});let z=Object.keys(oi);for(let[I,J]of Object.entries(oi)){let Q=R6($,I),K=!0;if($Y(Q))try{if(aj1(Q,"utf8")===J)K=!1}catch{K=!0}if(K)q_1(Q,J,"utf8");q.push(I)}let U=uP0($,{withFileTypes:!0});for(let I of U)if(!z.includes(I.name)){let J=R6($,I.name);try{if(I.isDirectory())ej1(J,{recursive:!0,force:!0});else $_1(J);Y.push(I.name)}catch{}}}catch{}return{synced:q,pruned:Y}}function bP0($={syncOfficial:!0}){if($.syncOfficial!==!1)fP0();let q=[{name:"builtin",type:"builtin",path:R6(i$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:R6(i$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:R6(i$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],Y=[b$,OD];for(let z of Y)if($Y(z))try{let U=uP0(z,{withFileTypes:!0});for(let I of U){if(I.isDirectory())continue;let J=I.name;if(J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")){let Q=J.replace(/\.(ts|js|mjs)$/,"");if(!q.some((K)=>K.name===Q))q.push({name:Q,type:"custom",path:R6(z,J),description:`用户自定义规则校验器(${J})`})}}}catch{}return q}function J_1($){let q=($||"").trim();if(!q||q==="builtin"||q==="default"||q==="official/builtin"||q==="official/builtin.ts")return{path:R6(i$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(q==="strict"||q==="official/strict"||q==="official/strict.ts")return{path:R6(i$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(q==="hlab"||q==="hlab-sop"||q==="hlab-rules"||q==="hlab-standard"||q==="official/hlab"||q==="official/hlab.ts")return{path:R6(i$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(z_1(q)||q.startsWith("./")||q.startsWith("../")){let z=U_1(q);if($Y(z))return{path:z};for(let U of[".ts",".js",".mjs"])if($Y(`${z}${U}`))return{path:`${z}${U}`}}let Y=[R6(b$,`${q}.ts`),R6(b$,`${q}.js`),R6(b$,`${q}.mjs`),R6(OD,`${q}.ts`),R6(OD,`${q}.js`),R6(OD,`${q}.mjs`)];for(let z of Y)if($Y(z))return{path:z};return{}}async function si($){fP0();let q=J_1($??"builtin");if(q.isOfficial){let z=q.officialKind==="strict"?SP0:q.officialKind==="hlab"?yP0:cI,U=q.officialKind==="builtin"?"builtin":"official",I=q.path;if(I&&$Y(I))try{let Q=await import(xP0(I).href),K=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof K==="function")return{name:q.officialKind??"builtin",type:U,filePath:I,linter:kP0(K,z)}}catch{}return{name:q.officialKind??"builtin",type:U,filePath:I,linter:z}}let Y=q.path;if(!Y)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cI};try{let U=await import(xP0(Y).href),I=U.default??U.lintRule??U.linter??U.lint;if(typeof I!=="function")return console.error(`⚠️[linter]自定义校验器"${Y}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cI};return{name:$??"custom",type:"custom",filePath:Y,linter:kP0(I,cI)}}catch(z){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${Y}"失败(语法错误或依赖缺失:${z?.message??z}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cI}}}functionkP0($,q){returnasync(Y,z)=>{try{letU=await$(Y,z);if(U&&typeofU==="object"&&typeofU.score==="number"&&Array.isArray(U.issues))returnU;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),q(Y,z)}catch(U){returnconsole.error("⚠️[linter]自定义校验器执行异常:",U),q(Y,z)}}}varb$,I_1="official",i$,OD;varti=e(()=>{di();li();ri();mi();b$=R6(Y_1(),".config","seal-use","linters"),i$=R6(b$,I_1),OD=R6(process.cwd(),"linters")});asyncfunctionai($,q,Y){letz=awaitq.linter($,Y);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:z.score,passed:z.passed,issues:z.issues,description:$.description}}asyncfunctioniP0($,q,Y,z){letU=z?.minScore??0,I=z?.level??"all",J=[],Q=0;for(letXof$){letw=awaitai(X,q,Y);Q+=w.score;letL=w.issues;if(I==="error")L=w.issues.filter((O)=>O.level==="error");elseif(I==="warning")L=w.issues.filter((O)=>O.level==="warning"||O.level==="error");letF=L.every((O)=>O.level!=="error");if(z?.summary){if(L.length>0)J.push({...w,passed:F,issues:L})}elseJ.push({...w,passed:F,issues:L})}letK=$.length,H=K===0?100:Math.round(Q/K),G=J.filter((X)=>X.issues.length>0).length,Z=K-Line truncated
`}});import{existsSync as KU,mkdirSync as iN1,readFileSync as cN1,readdirSync as qB0,rmSync as nN1,unlinkSync as pN1,writeFileSync as dN1}from"node:fs";import{homedir as mN1}from"node:os";import{isAbsolute as lN1,join as f6,resolve as oN1}from"node:path";import{pathToFileURL as XB0}from"node:url";function VB0($=i$){let Y=[],z=[];try{if(!KU($))iN1($,{recursive:!0});let U=Object.keys(Jp);for(let[J,I]of Object.entries(Jp)){let K=f6($,J),G=!0;if(KU(K))try{if(cN1(K,"utf8")===I)G=!1}catch{G=!0}if(G)dN1(K,I,"utf8");Y.push(J)}let Q=qB0($,{withFileTypes:!0});for(let J of Q)if(!U.includes(J.name)){let I=f6($,J.name);try{if(J.isDirectory())nN1(I,{recursive:!0,force:!0});else pN1(I);z.push(J.name)}catch{}}}catch{}return{synced:Y,pruned:z}}function LB0($={syncOfficial:!0}){if($.syncOfficial!==!1)VB0();let Y=[{name:"builtin",type:"builtin",path:f6(i$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:f6(i$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:f6(i$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],z=[b$,uP];for(let U of z)if(KU(U))try{let Q=qB0(U,{withFileTypes:!0});for(let J of Q){if(J.isDirectory())continue;let I=J.name;if(I.endsWith(".ts")||I.endsWith(".js")||I.endsWith(".mjs")){let K=I.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((G)=>G.name===K))Y.push({name:K,type:"custom",path:f6(U,I),description:`用户自定义规则校验器(${I})`})}}}catch{}return Y}function sN1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:f6(i$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:f6(i$,"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:f6(i$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(lN1(Y)||Y.startsWith("./")||Y.startsWith("../")){let U=oN1(Y);if(KU(U))return{path:U};for(let Q of[".ts",".js",".mjs"])if(KU(`${U}${Q}`))return{path:`${U}${Q}`}}let z=[f6(b$,`${Y}.ts`),f6(b$,`${Y}.js`),f6(b$,`${Y}.mjs`),f6(uP,`${Y}.ts`),f6(uP,`${Y}.js`),f6(uP,`${Y}.mjs`)];for(let U of z)if(KU(U))return{path:U};return{}}async function Kp($){VB0();let Y=sN1($??"builtin");if(Y.isOfficial){let U=Y.officialKind==="strict"?WB0:Y.officialKind==="hlab"?HB0:aI,Q=Y.officialKind==="builtin"?"builtin":"official",J=Y.path;if(J&&KU(J))try{let K=await import(XB0(J).href),G=K.default??K.lintRule??K.linter??K.lint;if(typeof G==="function")return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:ZB0(G,U)}}catch{}return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:U}}let z=Y.path;if(!z)return console.error(`⚠️[linter]未找到自定义校验器"${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:aI};try{let Q=await import(XB0(z).href),J=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof J!=="function")return console.error(`⚠️[linter]自定义校验器"${z}"未导出标准函数(default/lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:aI};return{name:$??"custom",type:"custom",filePath:z,linter:ZB0(J,aI)}}catch(U){returnconsole.error(`⚠️[linter]加载自定义校验器脚本"${z}"失败(语法错误或依赖缺失:${U?.message??U}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:aI}}}functionZB0($,Y){returnasync(z,U)=>{try{letQ=await$(z,U);if(Q&&typeofQ==="object"&&typeofQ.score==="number"&&Array.isArray(Q.issues))returnQ;returnconsole.error("⚠️[linter]自定义校验器返回值格式不符合RuleLintResult契约,已回退至内置结果。"),Y(z,U)}catch(Q){returnconsole.error("⚠️[linter]自定义校验器执行异常:",Q),Y(z,U)}}}varb$,rN1="official",i$,uP;varGp=o(()=>{zp();Qp();Ip();Up();b$=f6(mN1(),".config","seal-use","linters"),i$=f6(b$,rN1),uP=f6(process.cwd(),"linters")});asyncfunctionWp($,Y,z){letU=awaitY.linter($,z);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:U.score,passed:U.passed,issues:U.issues,description:$.description}}asyncfunctionFB0($,Y,z,U){letQ=U?.minScore??0,J=U?.level??"all",I=[],K=0;for(letqof$){letV=awaitWp(q,Y,z);K+=V.score;letF=V.issues;if(J==="error")F=V.issues.filter((w)=>w.level==="error");elseif(J==="warning")F=V.issues.filter((w)=>w.level==="warning"||w.level==="error");letM=F.every((w)=>w.level!=="error");if(U?.summary){if(F.length>0)I.push({...V,passed:M,issues:F})}elseI.push({...V,passed:M,issues:F})}letG=$.length,W=G===0?100:Math.round(K/G),H=I.filter((q)=>q.issues.length>0).length,X=G-Line truncated
`),z=await Promise.all(B.map((P)=>e1($,P.id)))}let U=new Map,I=0;for(let O of z){let A=O.document,B=O.sourceDocumentId??(typeof A?.id==="string"?A.id:void 0)??(typeof A?.sourceDocumentId==="string"?A.sourceDocumentId:void 0)??O.documentId??O.id,P=`${Y.docIdPrefix??""}${B}${Y.docIdSuffix??""}`,T=[];if(Y.includeAttachments!==!1){let v=t7(O,{summary:!1}).attachments,k=new Set;for(let R of v){let c=R.ossSignedUrl??R.url;if(!c)continue;let n=R.fileName??R.fileId??"attachment",g=Ri(n),b=g,i=g.lastIndexOf("."),$0=i>0?g.slice(0,i):g,j=i>0?g.slice(i):"",u=1;while(k.has(b.toLowerCase()))b=`${$0}_${u}${j}`,u++;k.add(b.toLowerCase());try{process.stderr.write(`⬇下载单据「${P}」附件:${n}...
`),await new Promise((O,A)=>{let B=yu1(w),P=new dp({zlib:{level:9}});B.on("close",()=>O()),P.on("error",(T)=>A(T)),P.pipe(B),P.append(Buffer.from(L),{name:"信息表.xlsx"});for(let T of U.values())for(let y of T)P.append(y.buffer,{name:y.zipPath});P.finalize()});let F=ku1(w);return{filePath:w,corpId:q.id,corpName:q.name,recordCount:z.length,attachmentCount:I,fileSizeBytes:F.size,exportedAt:new Date().toISOString(),nextAction:`seal-usewebhookresource-packpush${w}--corp<targetCorpId>`}}var mR0;var mp=e(()=>{pR0();J6();JD();mR0=S4(FZ(),1)});import{readFileSync as nu1}from"node:fs";function cu1($){let q=new URL($),Y=q.pathname.match(/\/webhook\/([^/]+)/);if(!Y)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${q.protocol}//${q.host}`,webhookId:Y[1]}}function pu1($,q){return q.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!q.toLowerCase().endsWith(".xlsx")}function du1($,q){if(!$.length)return;let Y=new Set($.map((I)=>{let J=I.fileName.split("/")[0],Q=J.indexOf("@");return Q>=0?J.slice(0,Q):J}).filter((I)=>I!=="信息表.xlsx")),z=[];for(let I of q){let J=I.document.documentId;if((I.documentAttachments.length>0||Object.values(I.expenseAttachments).some((K)=>K.length>0)||Object.values(I.personAttachments).some((K)=>K.length>0))&&!Y.has(J))z.push(`Excel 会议编号「${J}」声明了附件,但在 ZIP 中找不到对应的根目录「${J}/」或「${J}@.../」。`)}let U=new Set(q.map((I)=>I.document.documentId));for(let I of Y)if(!U.has(I))z.push(`ZIP 根目录对应的编号「${I}」在信息表中找不到对应的会议编号。`);if(z.length)throw new M5(z)}async function lR0($,q,Y){let z=[],U=$;if(pu1($,q)){z=await zT0($),IT0(z,Y);let K=z.find((H)=>H.fileName==="信息表.xlsx");if(!K)throw Error("ZIP 根目录缺少信息表.xlsx");U=await mn($,K)}let I=await WT0(U);du1(z,I);let J=XT0(z,I),Q=I.map((K)=>K.document);return{entries:z,parsed:I,plans:J,documents:Q,fileBuffer:$}}async function DY($,q,Y){let z=await lR0($,q,Y),U=z.parsed.map((I,J)=>an(I.document,z.plans[J],new Map));return{warnings:[],documents:U,attachmentPlan:z.plans}}async function CA($,q,Y){let z=await lR0($,q,Y.materialPackFilePolicy),{baseUrl:U,webhookId:I}=cu1(Y.webhookUrl),J=[];for(let Q=0;Q<z.parsed.length;Q+=1){let K=z.parsed[Q],H=z.plans[Q],G=new Map,Z=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let w of Z)for(let L of w.paths){if(G.has(L))continue;let F=z.entries.find((y)=>y.fileName===L);if(!F)continue;process.stderr.write(`⬆ 上传附件: ${L}
`),U=await Promise.all(N.map((D)=>G4($,D.id)))}let Q=new Map,J=0;for(let w of U){let O=w.document,N=w.sourceDocumentId??(typeof O?.id==="string"?O.id:void 0)??(typeof O?.sourceDocumentId==="string"?O.sourceDocumentId:void 0)??w.documentId??w.id,D=`${z.docIdPrefix??""}${N}${z.docIdSuffix??""}`,T=[];if(z.includeAttachments!==!1){let B=k2(w,{summary:!1}).attachments,j=new Set;for(let C of B){let b=C.ossSignedUrl??C.url;if(!b)continue;let k=C.fileName??C.fileId??"attachment",h=nn(k),i=h,c=h.lastIndexOf("."),U0=c>0?h.slice(0,c):h,x=c>0?h.slice(c):"",d=1;while(j.has(i.toLowerCase()))i=`${U0}_${d}${x}`,d++;j.add(i.toLowerCase());try{process.stderr.write(`⬇下载单据「${D}」附件:${k}...
`),await new Promise((w,O)=>{let N=Tv1(V),D=new Yl({zlib:{level:9}});N.on("close",()=>w()),D.on("error",(T)=>O(T)),D.pipe(N),D.append(Buffer.from(F),{name:"信息表.xlsx"});for(let T of Q.values())for(let A of T)D.append(A.buffer,{name:A.zipPath});D.finalize()});let M=Ev1(V);return{filePath:V,corpId:Y.id,corpName:Y.name,recordCount:U.length,attachmentCount:J,fileSizeBytes:M.size,exportedAt:new Date().toISOString(),nextAction:`seal-usewebhookresource-packpush${V}--corp<targetCorpId>`}}var DR0;var zl=o(()=>{OR0();X6();EP();DR0=J6(PZ(),1)});import{readFileSync as hv1}from"node:fs";function Sv1($){let Y=new URL($),z=Y.pathname.match(/\/webhook\/([^/]+)/);if(!z)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:z[1]}}function gv1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function yv1($,Y){if(!$.length)return;let z=new Set($.map((J)=>{let I=J.fileName.split("/")[0],K=I.indexOf("@");return K>=0?I.slice(0,K):I}).filter((J)=>J!=="信息表.xlsx")),U=[];for(let J of Y){let I=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))&&!z.has(I))U.push(`Excel 会议编号「${I}」声明了附件,但在 ZIP 中找不到对应的根目录「${I}/」或「${I}@.../」。`)}let Q=new Set(Y.map((J)=>J.document.documentId));for(let J of z)if(!Q.has(J))U.push(`ZIP 根目录对应的编号「${J}」在信息表中找不到对应的会议编号。`);if(U.length)throw new D5(U)}async function BR0($,Y,z){let U=[],Q=$;if(gv1($,Y)){U=await hP0($),gP0(U,z);let G=U.find((W)=>W.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");Q=await zd($,G)}let J=await iP0(Q);yv1(U,J);let I=cP0(U,J),K=J.map((G)=>G.document);return{entries:U,parsed:J,plans:I,documents:K,fileBuffer:$}}async function CU($,Y,z){let U=await BR0($,Y,z),Q=U.parsed.map((J,I)=>Gd(J.document,U.plans[I],new Map));return{warnings:[],documents:Q,attachmentPlan:U.plans}}async function sA($,Y,z){let U=await BR0($,Y,z.materialPackFilePolicy),{baseUrl:Q,webhookId:J}=Sv1(z.webhookUrl),I=[];for(let K=0;K<U.parsed.length;K+=1){let G=U.parsed[K],W=U.plans[K],H=new Map,X=[...W.categoryFields,...Object.values(W.personAttachments).flat(),...Object.values(W.expenseAttachments).flat()];for(let V of X)for(let F of V.paths){if(H.has(F))continue;let M=U.entries.find((A)=>A.fileName===F);if(!M)continue;process.stderr.write(`⬆ 上传附件: ${F}
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:q.sso?G:H,sealResultUrl:H,ssoUrl:G,type:q.sso?"sso_link":"deep_link",expiresIn:q.sso?X:void 0,identity:Z,warning:V,enterpriseAssistUrl:J,enterpriseUrl:J,hoseDomain:I.type==="hose"?Nf1(I.domain):void 0,documentUrl:Q,recordId:U?.id,sourceDocumentSN:U?.sourceDocumentSN,sourceDocumentId:U?.sourceDocumentId,sourceSystem:U?.sourceSystem,missing:{enterpriseAssistUrl:J?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:z&&!Q?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:W.object({query:W.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:W.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:W.string().optional().describe("模拟批次 ID"),latest:W.boolean().optional().describe("只返回最新一条匹配记录"),fields:W.union([W.string(),W.array(W.string())]).optional().describe("限制返回字段"),limit:W.number().int().positive().max(100).optional(),maxScan:W.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:W.boolean().optional()}),handler:async($,q)=>{let Y=q.sn??q.query;if(!Y)throw Error("query or sn is required");let z=await Df1($,{query:Y,sn:q.sn,batchId:q.batchId,latest:q.latest,limit:q.latest?1:q.limit??20,maxScan:q.maxScan??1000}),U=await Promise.all(z.records.map((Q)=>e1($,Q.id))),I=eR0(q.fields),J=U.map((Q)=>Ff1(Q,I));return{query:Y,sourceDocumentSN:q.sn,simulationBatchId:q.batchId,latest:q.latest??!1,total:z.total,scanned:z.scanned,matched:J.length,records:J,next:{getSummary:"seal-home approval-runs get <recordId> --summary",getRuleVersion:"seal-home rules version <ruleSetVersionNumber>",searchRuleVersion:`seal-hometoolseal_approval_search--json'{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","ruleVersionNumber":14}'`,getVersionContext:`seal-hometoolseal_approval_context_get--json'{"ruleVersionNumber":14}'`},...q.includeBridge?{bridge:yA(U)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:W.object({batchId:W.string().describe("simulation batch ID"),query:W.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,q)=>{let Y=Ud(await Sv($,q.batchId),q.query);return{batchId:q.batchId,count:Y.length,records:Y.map(PY),bridge:yA(Y)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:W.object({mode:W.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:W.array(W.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:W.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:W.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:W.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:W.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:W.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:W.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:W.array(W.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:W.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:W.record(W.string(),W.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:W.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:W.record(W.string(),W.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,q)=>{let Y=q.mode??"hosecloud",z=q.signKey;if(Y==="hosecloud"&&!z){if(z=(await xv($)).find((Q)=>Q.signKey)?.signKey,!z)throw Error("未找到合思集成 signKey, 请通过 signKey
Line truncated
`)}function vf1($){let q=[];if(q.push(`seal-use${$.area}-${$.title}`),$.description)q.push($.description);q.push(""),q.push("Usage:");for(let Y of $.commands)for(let z of Y.usage)q.push(`${z}`);if($.commands.some((Y)=>Y.name))q.push(""),q.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return q.join(`
`)}function Ov0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let q of Mv0)for(let Y of q.commands)for(let z of Y.usage)$.push(`${z}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var Mv0;var Zd=e(()=>{V$();Mv0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",commands:[{name:"list",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"],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"],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",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",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:"bind-test",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",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",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 version on the test enterprise. Production rules remain safe in draft state."},{name:"replay-test",summary:"Replay approval records from production enterprise to bound test enterprise via Webhook",usage:["seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"],options:[{flag:"<prodCorpId>",description:"Production enterprise ID (default: active enterprise)"},{flag:"--record-id <id>",description:"Replay a specific approval run ID"},{flag:"--sn <sn>",description:"Replay a specific document SN"},{flag:"--limit <n>",description:"Batch replay latest N records from production (default: 1)"},{flag:"--status <status>",descripti
Line truncated
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:Y.sso?H:W,sealResultUrl:W,ssoUrl:H,type:Y.sso?"sso_link":"deep_link",expiresIn:Y.sso?q:void 0,identity:X,warning:Z,enterpriseAssistUrl:I,enterpriseUrl:I,hoseDomain:J.type==="hose"?Xh1(J.domain):void 0,documentUrl:K,recordId:Q?.id,sourceDocumentSN:Q?.sourceDocumentSN,sourceDocumentId:Q?.sourceDocumentId,sourceSystem:Q?.sourceSystem,missing:{enterpriseAssistUrl:I?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:U&&!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)=>{let z=Y.sn??Y.query;if(!z)throw Error("query or sn is required");let U=await Zh1($,{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(U.records.map((K)=>G4($,K.id))),J=CR0(Y.fields),I=Q.map((K)=>Gh1(K,J));return{query:z,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:U.total,scanned:U.scanned,matched:I.length,records:I,next:{getSummary:"seal-home approval-runs get <recordId> --summary",getRuleVersion:"seal-home rules version <ruleSetVersionNumber>",searchRuleVersion:`seal-hometoolseal_approval_search--json'{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","ruleVersionNumber":14}'`,getVersionContext:`seal-hometoolseal_approval_context_get--json'{"ruleVersionNumber":14}'`},...Y.includeBridge?{bridge:zT(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 z=Vl(await mS($,Y.batchId),Y.query);return{batchId:Y.batchId,count:z.length,records:z.map(_U),bridge:zT(z)}}},{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 z=Y.mode??"hosecloud",U=Y.signKey;if(z==="hosecloud"&&!U){if(U=(await oS($)).find((K)=>K.signKey)?.signKey,!U)throw Error("未找到合思集成 signKey, 请通过 signKey
Line truncated
`)}function Bh1($){let Y=[];if(Y.push(`seal-use${$.area}-${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");for(let z of $.commands)for(let U of z.usage)Y.push(`${U}`);if($.commands.some((z)=>z.name))Y.push(""),Y.push(`Run'seal-use ${$.area} <command> --help'fordetailsonaspecificcommand.`);return Y.join(`
`)}function oR0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of rR0)for(let z of Y.commands)for(let U of z.usage)$.push(`${U}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var rR0;var Nl=o(()=>{L$();rR0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",commands:[{name:"list",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"],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"],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",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",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:"bind-test",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",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",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 version on the test enterprise. Production rules remain safe in draft state."},{name:"replay-test",summary:"Replay approval records from production enterprise to bound test enterprise via Webhook",usage:["seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"],options:[{flag:"<prodCorpId>",description:"Production enterprise ID (default: active enterprise)"},{flag:"--record-id <id>",description:"Replay a specific approval run ID"},{flag:"--sn <sn>",description:"Replay a specific document SN"},{flag:"--limit <n>",description:"Batch replay latest N records from production (default: 1)"},{flag:"--status <status>",descripti
Line truncated
`}class tR{constructor($=n00.stdin,q=n00.stdout){this._stdin=$,this._stdout=q,this._readBuffer=new sR,this._started=!1,this._ondata=(Y)=>{this._readBuffer.append(Y),this.processReadBuffer()},this._onerror=(Y)=>{this.onerror?.(Y)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((q)=>{let Y=i00($);if(this._stdout.write(Y))q();else this._stdout.once("drain",q)})}}b8();import{dirname as dd,join as Li1}from"node:path";import{fileURLToPath as Fi1}from"node:url";import{spawnSync as i10}from"node:child_process";var LK={name:"seal-use",version:"0.10.23",type:"module",module:"src/server.ts",bin:{"seal-use":"src/cli.ts","seal-home":"src/cli.ts"},scripts:{dev:"bun run --watch src/server.ts",start:"bun run src/server.ts",probe:"bun run src/probe.ts",cli:"bun run src/cli.ts",check:"tsc --noEmit","build:binary":"node scripts/build-binary.mjs","build:plugin":"node scripts/build-plugin.mjs",bump:"bun run scripts/bump-version.ts","dev:override":"bun run scripts/dev-override.ts","dev:link":"bun run scripts/dev-override.ts","openapi:bundle":"bun run scripts/bundle-openapi.ts","openapi:raw":"bun run scripts/generate-raw-openapi.ts",test:"bun test"},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0",archiver:"^8.0.0",exceljs:"^4.4.0","iconv-lite":"^0.7.3",ky:"^2.0.2","pinyin-pro":"^3.29.3",yauzl:"^3.4.0",zod:"^4.4.3"},devDependencies:{"@types/archiver":"^8.0.0","@types/bun":"^1.3.14","@types/yauzl":"^3.4.0","bun-types":"^1.3.14",typescript:"^5.9.3",yaml:"^2.9.0"}};function _o0($,q=LK.version){let Y=$.trim();if(!Y)return null;let z=Y.endsWith("-dirty"),U=z?Y.slice(0,-6):Y,I=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);if(I&&I[1]&&I[2]&&I[3])return{baseVersion:I[1],commitsAhead:Number.parseInt(I[2],10),commit:I[3],dirty:z,describe:Y};let J=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/);if(J&&J[1])return{baseVersion:J[1],commitsAhead:0,commit:"",dirty:z,describe:Y};let Q=U.match(/^([0-9a-f]{7,40})$/);if(Q&&Q[1])return{baseVersion:q,commitsAhead:0,commit:Q[1],dirty:z,describe:Y};return null}function Co0($,q,Y,z){let I=Y?`+g${Y}${z?".dirty":""}`:z?"+dirty":"";return`${$}-dev.${q}${I}`}function Ro0($){let q=$?.env,Y=q?.SEAL_BUILD_VERSION??process.env.SEAL_BUILD_VERSION,z=q?.SEAL_BUILD_IS_RELEASE??process.env.SEAL_BUILD_IS_RELEASE,U=q?.SEAL_BUILD_CHANNEL??process.env.SEAL_BUILD_CHANNEL,I=q?.SEAL_BUILD_GIT_BASE??process.env.SEAL_BUILD_GIT_BASE,J=q?.SEAL_BUILD_GIT_COMMITS_AHEAD??process.env.SEAL_BUILD_GIT_COMMITS_AHEAD,Q=q?.SEAL_BUILD_GIT_COMMIT??process.env.SEAL_BUILD_GIT_COMMIT,K=q?.SEAL_BUILD_GIT_DIRTY??process.env.SEAL_BUILD_GIT_DIRTY,H=q?.SEAL_BUILD_GIT_DESCRIBE??process.env.SEAL_BUILD_GIT_DESCRIBE,G=q?.SEAL_FORCE_RELEASE??process.env.SEAL_FORCE_RELEASE,Z=$?.cwd;if(Y){let V=z==="true",w={name:"seal-use",version:Y,channel:U||(V?"release":"dev"),isRelease:V};if(I)w.git={baseVersion:I,commitsAhead:Number.parseInt(J||"0",10),commit:Q||"",dirty:K==="true",describe:H||Y};return w}if(z==="true"||G==="1")return{name:"seal-use",version:LK.version,channel:"release",isRelease:!0};try{let V=i10("git",["describe","--tags","--long","--dirty","--always"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(V.status===0&&V.stdout){let X=_o0(V.stdout.trim(),LK.version);if(X){if(!X.commit){let L=i10("git",["rev-parse","--short","HEAD"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(L.status===0&&L.stdout)X.commit=L.stdout.trim()}return{name:"seal-use",version:Co0(X.baseVersion,X.commitsAhead,X.commit,X.dirty),channel:"dev",isRelease:!1,git:X}}}}catch{}return{name:"seal-use",version:`${LK.version}-dev.0+local`,channel:"dev",isRelease:!1}}var FK=Ro0(),Q1=FK.version,Nv=FK.isRelease,et1=FK.channel;J6();UD();JD();p4();_4();o1();b8();p4();J6();J6();DZ();op();_4();o1();V$();import{existsSync as Ev0}from"node:fs";async function jv0($,q){if(!Ev0($))throw Error(`Filenotfound:${$}`);let Y=AY($);console.log(JSON.stringify(await DY(Y.fileBuffer,Y.fileName,q),null,2))}async function mA($,q,Y,z,U){if($==="ready"||$==="status"){let I=q??E(U.options.file)??E(U.options.input),J=await RA(Y,z,{filePath:I,webhook:E(U.options.webhook)??E(U.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.erro
Line truncated
`);c0({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)=>({id:Q.id,name:Q.name||"-",appKey:Q.appKey,appSecurity:U?Q.appSecurity:CS(Q.appSecurity),active:Q.active,createTime:Q.createTime,updateTime:Q.updateTime}))})}async function xl($,Y){let z=E1($),U=Y.reveal===!0;if(z.source.type!=="hose")throw new w4(`【合思子域专享能力】当前企业「${z.name}」(id:${z.id})为原生Seal(${z.source.type})租户,非合思(Hose/合思云/易快报)渠道企业。
`);c0({provider:"hose",capability:"privilege-elevation",corpId:z.id,corpName:z.name,domain:z.source.domain,staffId:z.source.staffId,appKey:Q??"-",appSecurity:J?U?J:CS(J):"-",active:!0})}function uv0($,Y){let{token:z,sealUrl:U,expiresIn:Q,verify:J,remote:I}=Y,K=Y.custom??xv0($),G=I?.user,W=I?.tenant,H=H4($,"tenantSlug")??s2(W?.tenantSlug),X=H4($,"tenantId")??s2(W?.id),Z=H4($,"tenantName")??s2(W?.name),q=H4($,"id")??H??X;if(!q)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let V=H4($,"staffId")??s2(G?.providerUserId)??s2(G?.id)??"seal",F=H4($,"provider")??s2(G?.provider)??s2(W?.providerConfig?.provider),M=H4($,"corpId")??H??X??q,w={id:q,name:H4($,"name")??Z??q,environment:"production",seal:{url:U,tenantSlug:H,headers:K.headers,cookies:K.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:z,sealUrl:U,expiresIn:Q,staffId:V,corpId:M,tenantId:X,tenantSlug:H,tenantName:Z,providerUserId:s2(G?.providerUserId),provider:F},auth:{refreshTtl:300}},O=rn();hv0(O,{recursive:!0,mode:448});let N=gv0(O,`${GT(q)}.json`);if(vv0(N)&&$.overwrite!==!0)throw Error(`Enterpriseconfigalreadyexists:${N}.Pass"overwrite":truetoreplaceit.`);Sv0(N,`${JSON.stringify(w,null,2)}
`,{mode:384}),c0({id:q,name:w.name,tenantId:X,tenantSlug:H,verified:J,path:N})}async function WS1($,Y,z={}){let U=T8($,Y,z),Q=await H8(U);return{user:Q.user??{},tenant:Q.tenant??{}}}function s2($){return typeof $==="string"&&$?$:void 0}var fl=o(()=>{a9();DW();i8();S7();Pv0();gP();ln();X6();X6();gl();RZ();DT();o4();L$();D4();J4()});async function iv0($,Y){let z=$??S(Y.options.link)??S(Y.options.url);if(!z)throw Error("Usage: seal-use auth extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");let U=F0(Y.options.reveal)===!0||F0(Y.options.r)===!0||F0(Y.options.plain)===!0,Q=F0(Y.options.save)===!0||F0(Y.options.add)===!0;await BT(z,{reveal:U,save:Q,name:S(Y.options.name),overwrite:F0(Y.options.overwrite)===!0,force:F0(Y.options.force)===!0,appKey:S(Y.options["app-key"])??S(Y.options.appKey),keyId:S(Y.options["key-id"])??S(Y.options.keyId)})}async function cv0($,Y,z){if($==="diagnose"){c0(await HS1(Y));return}if($==="hose-link"){let U=s0(z.options.expire)??7200;c0(await ow(Y,U));return}if($==="keys"){let U=F0(z.options.reveal)===!0||F0(z.options.r)===!0||F0(z.options.plain)===!0;await xl(Y.id,{reveal:U});return}throw Error(`Unknownauthcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}async function HS1($){if($.source.type!=="hose"){let F=await j1($),M=await H8(F);return{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:M.user,tenant:M.tenant}]}}pw($.id);let Y=$.source,z=Y.appKey??Y.key,U=Y.appSecurity??Y.password,Q=($.seal.url??Y.sealUrl??`https://${Y.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/,""),J=Y.staffId.includes(":")?Y.staffId:`${Y.corpId}:${Y.staffId}`,I=[];if(!z||!U)return{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:!1,stages:[{name:"hose.openapi",ok:!1,error:"Hose source requires appKey/key and appSecurity/password"}]};let K=await PT("hose.openapi",async()=>{let F=await bv0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1/auth/getAccessToken`,{appKey:z,appSecurity:U}),M=d7(F.value),w=b6(M.accessToken)??b6(F.accessToken)??b6(F.token);if(!w)throw Error("Hose login did not return an access token");return{token:w,public:{corporationId:b6(M.corporationId)??b6(d7(M.corporation).id),expireTime:Nq(M.expireTime)}}});I.push(K.public);let G=K.private?.token,W=G?await PT("hose.provisional",async()=>{let F=await bv0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=${encodeURIComponent(G)}`,{uid:J,pageType:"home",expireDate:7200}),M=b6(d7(F.value).message);if(!M)throw Error("Hose CloseAPI did not return a provisional auth URL");let w=new URL(M).searchParams.get("accessToken");if(!w)throw Error("Hose provisional auth URL did not include accessToken");return{token:w,public:{uid:J,enterpriseUrl:Lq(M)}}}):ul("hose.provisional");I.push(W.public);let H=B6($.seal),X=W.private?.token,Z=X?await PT("seal.sso",async()=>{let M=await T8(Q,void 0,H).get(`api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(X)}&returnToken=1`).json(),w=d7(M.data),O=b6(M.token)??b6(M.accessToken)??b6(w.token)??b6(w.accessToken);if(!O)throw Error("Seal SSO did not return a bearer token");return{token:O,public:{sealUrl:Q,expiresIn:Nq(M.expiresIn)??Nq(M.expires_in)??Nq(w.expiresIn)??Nq(w.expires_in)}}}):ul("seal.sso");I.push(Z.public);let q=Z.private?.token,V=q?await PT("seal.whoami",async()=>{let M=await T8(Q,q,H).get("api/v1/auth/me").json(),w=d7(M.data),O=d7(w.user??M.user),N=d7(w.tenant??M.tenant);return{public:{user:{id:b6(O.id),name:b6(O.name),isAdmin:ZS1(O.isAdmin),providerUserId:b6(O.providerUserId)},tenant:{id:b6(N.id),name:b6(N.name),tenantSlug:b6(N.tenantSlug),hoseCorpConfig:qS1(N.hoseCorpConfig)}}}}):ul("seal.whoami");return I.push(V.public),{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:I.every((F)=>F.ok===!0),stages:I}}async function PT($,Y){try{let z=await Y();return{public:{name:$,ok:!0,...nv0(z.public)},private:z.token?{token:z.token}:void 0}}catch(z){return{public:{name:$,ok:!1,error:Lq(z instanceof Error?z.message:String(z))}}}}function ul($){return{public:{name:$,ok:!1,skipped:!0}}}async function bv0($,Y){let z=await fetch($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Y)});return XS1(z)}async function XS1($){let Y=await $.text();if(!$.ok)throw Error(`${$.status} ${Y}`);let z=JSON.parse(Y);return d7(z)}function d7($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function b6($){return typeof $==="string"&&$?$:void 0}function Nq($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function ZS1($){return typeof $==="boolean"?$:void 0}function qS1($){let Y=d7($);return nv0({corporationId:b6(Y.corporationId),corporationName:b6(Y.corporationName)})}function nv0($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))}var pv0=o(()=>{a9();DW();i8();X6();D4();J4();fl()});async function dv0($,Y,z,U){if($==="status"||$==="get"){await k0("seal_billing_status_get",Y,z,{},C0(U.options)
Line truncated
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let X=V.outboundName??"SealAI 审批",w=V.signKey,L=V.apiOrigin??"production";console.error(`•"${X}"(signKey:${w},环境:${L})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${w}--corp${U.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let w of V){let L=w.outboundName??"SealAI 审批",F=w.signKey,O=w.apiOrigin??"production";console.error(`•"${L}"(signKey:${F},环境:${O})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${F}--corp${U.id}
`);throw new b4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,V.length===1?`seal-usedeployhosecloudsync${V[0].signKey}--corp${U.id}`:void 0)}await P0("seal_deploy_hosecloud_sync",z,U,{signKey:H},F0(I.options));return}throw Error(`Unknowndeployhosecloudaction:${Q??""}.Available:requirements,list,get,status,configure,sync.`)}ti();import{accessSync as ub1,constants as fb1,existsSync as X8,readdirSync as bb1}from"node:fs";import{homedir as ib1}from"node:os";import{join as N3}from"node:path";Q3();import{existsSync as Pd,mkdirSync as Xg0,rmSync as yb1,writeFileSync as xb1}from"node:fs";import{homedir as Vg0}from"node:os";import{dirname as kb1,join as Bd}from"node:path";var Yg0=`---
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,F=Z.apiOrigin??"production";console.error(`•"${q}"(signKey:${V},环境:${F})`),console.error(`\uD83D\uDC49查看命令:seal-usedeployhosecloudget${V}--corp${Q.id}
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let F=V.outboundName??"SealAI 审批",M=V.signKey,w=V.apiOrigin??"production";console.error(`•"${F}"(signKey:${M},环境:${w})`),console.error(`\uD83D\uDC49同步命令:seal-usedeployhosecloudsync${M}--corp${Q.id}
description:"v0.10.23: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description:"v0.10.25: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
Usethe\`seal_cli\`MCP tool when it is available; pass the command string as its \`command\` argument. If MCP is unavailable, fall back to the global \`seal-use\` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
**TheCLIistheprimarypath;theMCPserverisanoptionalextrathatisoffbydefault.**Prefertheglobal\`seal-use\`CLI, and only use MCP when it is actually available in the current session. If no \`seal_cli*\` tool is present, that is the normal default — do not try to enable it or treat it as a fault; just use the CLI. Enabling it is the user's choice in the plugin settings (插件配置中的「启用 MCP 服务」,默认关闭,打开后需重连该插件的 MCP 服务).
WhenMCP*is*available,twotoolsareexposed:
-\`seal_cli\` — **read-only only.** Reads tenant state without changing it. It is annotated \`readOnlyHint: true\`, so clients may auto-approve it.
-\`seal_cli_write\` — everything that mutates tenant state, publishes configuration, mints credentials, self-updates or starts a server. Annotated \`destructiveHint: true\`; **confirm the exact command with the user before calling it.**
Theboundaryisenforced,notmerelyadvertised:\`seal_cli\` refuses any command that is not on its read-only allow-list, and unclassified commands fail closed. A refusal names \`seal_cli_write\` as the follow-up. \`seal-use tool <name>\` is allowed through \`seal_cli\` only for tools the registry classifies as read-only (\`SEAL_READ_ONLY_TOOLS\`); the rest need \`seal_cli_write\`.
-TreatCLI/MCPastheAgent's execution channel, not the user'sinterface.Translatenatural-languageintentintocommandsyourself;neverasktheusertocomposeCLIsyntax,JSONpayloads,placeholdervalues,orinternalIDs.
-Beforeaskingforenterpriseparameters,resolvethetargetenterprise:whenanenterpriseisnamed,hinted,orkeyword-identifiable,ALWAYSrun\`seal-use corps search <keyword>\` (or \`seal-use corps get <corpId>\` if an exact ID is known) — DO NOT dump the entire enterprise catalog with \`seal-use corps list\` when the target is already known. Only run \`seal-use corps list\` (or \`corps list --env <test|production>\`) for initial discovery when zero enterprise context is known. Resolve its human name to the returned \`id\` and pass that value as \`--corp\`; do not ask the user to know \`corpId\`. Use \`seal-use corps get <corpId>\` to inspect rich enterprise attributes (URLs, tenant slugs, staff IDs, environment relations, and config file locations) with sensitive secrets safely redacted.
-Ifnoenterpriseisconfigured,theuserisinstallingforthefirsttime,ortheuserprovidescredentials,anassistancelink,orabrowser-copiedcURL,read\`references/enterprise-onboarding.md\` before asking questions or running setup commands.
-WhentheuserprovidesaHose/合思\`thirdparty.html\` assistance link, use \`seal-use corps add-link <url> [--name ...]\`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
-WhentheuserprovidesaHose/合思\`thirdparty.html\` assistance link, use \`seal-use corps add-link <url> [--name ...]\` for temporary session access, or elevate privileges to permanent developer credentials using \`seal-use corps extract-keys <url> --save\` (or \`seal-use corps add-link <url> --as-hose\`). This Hose-exclusive capability extracts \`appKey\`/\`appSecurity\`. If the enterprise has multiple keys, specify \`--app-key <key>\` or \`--key-id <id>\`.
-**同等凭据原则(EqualCredentialScopePrinciple)**:AHoseassistancelinkandacURLcopiedfromanauthenticated**Hoseadmin**pagearebothHosewebfrontendsessions—structurallydifferentinformatonly,carryingthesame\`accesstoken\`/\`corpid\` web session credentials. **When a Hose administrator provides a browser cURL, do NOT silently downgrade it to a plain short-lived session import.** Attempt privilege elevation first by extracting \`accesstoken\`+\`corpid\`+\`baseUrl\` from the cURL and invoking the Hose key interface (\`/api/innerapi/v1/key\`) to retrieve permanent \`appKey\`/\`appSecurity\`. Only fall back to temporary session import if the user is not a Hose administrator or the key interface returns no keys.
-Keepenterpriseidentityoriginseparatefromcredentialacquisition.AHose/合思-sourcedSealtenantcanbeaccessedwithstandardHoseappcredentials,anassistancelink,oracapturedwebsession;receivingaSealBearertokendoesnotbyitselfprovethetenantisSeal-native.Callingkeyextractionor\`keys\` on native Seal enterprises is strictly blocked.
-Neveraskanormaluserfor\`corpId\`, \`staffId\`, \`proxyStaffBizId\`, \`tenantId\`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
-Prefercompactcommandsfirst:\`pick\`, \`--summary\`, \`--fields\`, \`attachments --summary\`, \`rules count\`, and \`rules list --summary\`.
Rule,document,stylepreference,andpublishactionsmutateSealconfiguration.Makethetargetenterpriseexplicit,showtheintendedpayload,andverifyafterthewrite.Neversendreal\`enterprises/*.json\` files, tokens, signed URLs, or full raw documents to GitHub, tickets, logs, or chat unless the user explicitly requests a safe export.
`;var zg0=`interface:
`;var Ih0=()=>{};var Wh0=`interface:
display_name:"Seal Use"
short_description:"Diagnose approval feedback and publish minimal rule fixes"
default_prompt:"Use $seal-use to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation."
@@ -1248,7 +1271,7 @@ Use current search only when the question is about current draft/current knowled
##OutputDiscipline
Ifarulecommandwouldreturnmanydescriptionsormorethanabout20rules,use\`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports.
`;var Jg0="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use<command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise the user-level `~/.config/seal-use/enterprises`directoryisloaded.Aconfigured\n`testEnterprisesDir`isloadedfirstfortest-tenantworkflows.Thecurrentworkingdirectory's\n`./enterprises`directoryisnotloadedimplicitly.\n-Set`SEAL_USE_ENTERPRISES_DIR`touseoneexplicitdirectoryinstead.Legacy\n`~/.config/seal-home/enterprises`filesaremigratedtotheprimarydirectorywhenpossible.\n\nEnterpriseselectionisstatelessbydefault.Commandsthataccessanenterpriserequire\n`--corp<corpId>`unlessstatefulmodeisexplicitlyenabled:\n\n```bash\nseal-useconfigmodestateful--corp<corpId>\nseal-usecorpsswitch<corpId>\nseal-useconfigmodestateless\n```\n\nTheglobalmodeisstoredin`~/.config/seal-use/config.json`;set`SEAL_USE_CONFIG_FILE`to\noverridethatpath.Thelegacy`current-corp`fileisnotread.\n\n##Stream&ExitCodeContract\n\n-**`stdout`**:Pure,deterministicJSONformachine/Agentparsing.\n-**`stderr`**:Diagnostics,probinglogs,and**Next-StepCommandSuggestions**withthestableprefix`👉Nextaction:seal-use...`.\n-**`ExitCode`**:`0`onsuccess;`1`runtime/upstreamfailure,`2`usage/argumenterror,`10`explicitdestructive-operationconfirmationrequired,`11`missing/invalidauthentication,and`12`outputprotectionrequiringacompact/file/queryalternative.\n\n##Top-LevelCommands\n\n```bash\nseal-useversion\nseal-useconfigpaths\nseal-useconfigget\nseal-useconfigmode<stateful|stateless>[--corp<corpId>]\nseal-useconfigtest-dir[<path>|--clear]\nseal-useconfiglint<enable|disable|status>[--linter<name>][--min-score<score>]\nseal-userulescount[--corp<corpId>]\nseal-useruleslist[--summary][--count][--limit20][--offset0][--corp<corpId>]\nseal-userulesclear[--corp<corpId>][--dry-run|--yes]\nseal-userulesversions[--corp<corpId>]\nseal-userulesversion<versionId|versionNumber|latest>[--corp<corpId>]\nseal-userulesget--corp<corpId>--version<number|latest>--code'#0038'\nseal-userulesget--corp<corpId>--record-id<recordId>--runtime-idrule-205\nseal-userulessearch<keyword>[--version<versionId|versionNumber|latest>][--maxResults20][--corp<corpId>]\nseal-userulespull[--corp<corpId>][--version<id|num|latest>][--out<file>]\nseal-useruleslint[--file<path>][--corp<corpId>][--linter<name|path>][--version<num>][--code<code>][--min-score<score>][--summary]\nseal-useruleslinters[--corp<corpId>]\nseal-userulespush[--file<path>][--corp<corpId>][--publish][--version-name<name>][--dry-run|--yes]\nseal-userulesmap[--corp<corpId>][--version<id|num|latest>][--code<code>]\nseal-useservice<start|stop|restart|status|logs>[--port8787][--host127.0.0.1][--lines50]\nseal-usehttp[--port8787][--host127.0.0.1]\nseal-useserve[--port8787]\nseal-useupdate[--check][--force][--version<v>]\nseal-useupdatecheck\nseal-useupdatechangelog[--limit<n>]\nseal-usechangelog[--limit<n>]\nseal-usemcp\nseal-usemcpconfig\nseal-usemcp-config\nseal-useskilldump\nseal-useskillinstall[--dir<path>|--local]\nseal-useskillstatus\nseal-usedoctor[--quiet]\nseal-usedoctortenant[--corp<corpId>][--quiet]\nseal-usedoctorguide\nseal-usedoctorpaths\nseal-usetestregression[--corp<corpId>][--samples<N>][--dry-run][--fail-on-flips]\nseal-useprobe[<corpId>]\nseal-usetoolslist\nseal-usecorpslist[query][--env<production|test>][--limit<n>][--all][--sort<usage|name|id>][--strict][--corp<corpId>]\nseal-usecorpssearch<query>[--env<production|test>][--strict]\nseal-usecorpsget<corpId>\nseal-usecorpscurrent[--corp<corpId>]\nseal-usecorpsswitch<corpId>\nseal-usecorpsmark<corpId>--env<production|test>[--confirm]\nseal-usecorpsbind-test<prodCorpId><testCorpId>[--confirm][--force]\nseal-usecorpsunbind-test[<corpId>][--confirm]\nseal-usecorpssync-test[<prodCorpId>][--dry-run][--yes][--version-name<name>]\nseal-usecorpsreplay-test[<prodCorpId>][--record-id<id>][--sn<sn>][--limit<n>][--status<status>][--webhook<idOrName>][--sn-suffix<str>][--dry-run][--force]\nseal-usecorpsregression[--corp<corpId>][--samples<N>][--dry-run][--fail-on-flips]\nseal-usecorpsadd-hose--json'{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-usecorpsadd-seal--json'{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-usecorpsadd-link<https://.../web/thirdparty.html?...>[--name<customName>][--overwrite]\nseal-useauthdiagnose[--corp<corpId>]\nseal-useauthhose-link[--corp<corpId>][--expire7200]Line truncated
`;var Zh0=()=>{};var Lh0="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use<command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise the user-level `~/.config/seal-use/enterprises`directoryisloaded.Aconfigured\n`testEnterprisesDir`isloadedfirstfortest-tenantworkflows.Thecurrentworkingdirectory's\n`./enterprises`directoryisnotloadedimplicitly.\n-Set`SEAL_USE_ENTERPRISES_DIR`touseoneexplicitdirectoryinstead.Legacy\n`~/.config/seal-home/enterprises`filesaremigratedtotheprimarydirectorywhenpossible.\n\nEnterpriseselectionisstatelessbydefault.Commandsthataccessanenterpriserequire\n`--corp<corpId>`unlessstatefulmodeisexplicitlyenabled:\n\n```bash\nseal-useconfigmodestateful--corp<corpId>\nseal-usecorpsswitch<corpId>\nseal-useconfigmodestateless\n```\n\nTheglobalmodeisstoredin`~/.config/seal-use/config.json`;set`SEAL_USE_CONFIG_FILE`to\noverridethatpath.Thelegacy`current-corp`fileisnotread.\n\n##Stream&ExitCodeContract\n\n-**`stdout`**:Pure,deterministicJSONformachine/Agentparsing.\n-**`stderr`**:Diagnostics,probinglogs,and**Next-StepCommandSuggestions**withthestableprefix`👉Nextaction:seal-use...`.\n-**`ExitCode`**:`0`onsuccess;`1`runtime/upstreamfailure,`2`usage/argumenterror,`10`explicitdestructive-operationconfirmationrequired,`11`missing/invalidauthentication,and`12`outputprotectionrequiringacompact/file/queryalternative.\n\n##Top-LevelCommands\n\n```bash\nseal-useversion\nseal-useconfigpaths\nseal-useconfigget\nseal-useconfigmode<stateful|stateless>[--corp<corpId>]\nseal-useconfigtest-dir[<path>|--clear]\nseal-useconfiglint<enable|disable|status>[--linter<name>][--min-score<score>]\nseal-userulescount[--corp<corpId>]\nseal-useruleslist[--summary][--count][--limit20][--offset0][--corp<corpId>]\nseal-userulesclear[--corp<corpId>][--dry-run|--yes]\nseal-userulesversions[--corp<corpId>]\nseal-userulesversion<versionId|versionNumber|latest>[--corp<corpId>]\nseal-userulesget--corp<corpId>--version<number|latest>--code'#0038'\nseal-userulesget--corp<corpId>--record-id<recordId>--runtime-idrule-205\nseal-userulessearch<keyword>[--version<versionId|versionNumber|latest>][--maxResults20][--corp<corpId>]\nseal-userulespull[--corp<corpId>][--version<id|num|latest>][--out<file>]\nseal-useruleslint[--file<path>][--corp<corpId>][--linter<name|path>][--version<num>][--code<code>][--min-score<score>][--summary]\nseal-useruleslinters[--corp<corpId>]\nseal-userulespush[--file<path>][--corp<corpId>][--publish][--version-name<name>][--dry-run|--yes]\nseal-userulesmap[--corp<corpId>][--version<id|num|latest>][--code<code>]\nseal-useservice<start|stop|restart|status|logs>[--port8787][--host127.0.0.1][--lines50]\nseal-usehttp[--port8787][--host127.0.0.1]\nseal-useserve[--port8787]\nseal-useupdate[--check][--force][--version<v>]\nseal-useupdatecheck\nseal-useupdatechangelog[--limit<n>]\nseal-usechangelog[--limit<n>]\nseal-usemcp\nseal-usemcpconfig\nseal-usemcp-config\nseal-useskilldump\nseal-useskillinstall[--dir<path>|--local]\nseal-useskillstatus\nseal-usedoctor[--quiet]\nseal-usedoctortenant[--corp<corpId>][--quiet]\nseal-usedoctorguide\nseal-usedoctorpaths\nseal-usetestregression[--corp<corpId>][--samples<N>][--dry-run][--fail-on-flips]\nseal-useprobe[<corpId>]\nseal-usetoolslist\nseal-usecorpslist[query][--env<production|test>][--limit<n>][--all][--sort<usage|name|id>][--strict][--corp<corpId>]\nseal-usecorpssearch<query>[--env<production|test>][--strict]\nseal-usecorpsget<corpId>\nseal-usecorpscurrent[--corp<corpId>]\nseal-usecorpsswitch<corpId>\nseal-usecorpsmark<corpId>--env<production|test>[--confirm]\nseal-usecorpsbind-test<prodCorpId><testCorpId>[--confirm][--force]\nseal-usecorpsunbind-test[<corpId>][--confirm]\nseal-usecorpssync-test[<prodCorpId>][--dry-run][--yes][--version-name<name>]\nseal-usecorpsreplay-test[<prodCorpId>][--record-id<id>][--sn<sn>][--limit<n>][--status<status>][--webhook<idOrName>][--sn-suffix<str>][--dry-run][--force]\nseal-usecorpsregression[--corp<corpId>][--samples<N>][--dry-run][--fail-on-flips]\nseal-usecorpsadd-hose--json'{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-usecorpsadd-seal--json'{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-usecorpsadd-link<https://.../web/thirdparty.html?...>[--name<customName>][--as-hose][--app-key<key>][--key-id<id>][--overwrite]\nseal-usecorpsextract-keys<https://.Line truncated
|Hose/合思-sourcedSealtenant|Hose\`appKey\` + \`appSecurity\` | 【最高·永久】自动签名/续期 | Stable, refreshable standard integration; unlocks full OpenAPI and \`corps sync-hosecloud\`. |
|Hose/合思-sourcedSealtenant|Hoseauthorization/assistancelink(\`thirdparty.html\`) | 【两极分化】普通导入→短效;提权→永久 | Temporary session that can be **elevated** to permanent \`appKey\`/\`appSecurity\` with \`extract-keys --save\` or \`add-link --as-hose\`. |
|Hose/合思-sourcedSealtenant|cURLcopiedfromanauthenticated**Hoseadmin**page|【两极分化】普通导入→短效;提权→永久|**Samesessionscopeasanassistancelink.**IftheuserisaHoseadministrator,thiscarriesthesamewebsessioncredentials(\`accesstoken\`, \`corpid\`, cookies) and can equally invoke \`/api/innerapi/v1/key\` to extract permanent \`appKey\`/\`appSecurity\`. |
**同等凭据原则(EqualCredentialScopePrinciple)**:AHoseassistancelinkandabrowsercURLfromanauthenticatedHoseadminsessionarebothHosewebfrontendsessions—theycarrythesameunderlying\`accessToken\`/\`accesstoken\` and \`corpid\`. The **only** structural difference is delivery format. When a Hose administrator sends you a cURL, treat it with the same privilege elevation potential as an assistance link. Do not downgrade it to a plain Seal session import without first attempting key extraction.
Credentialshapealonedoesnotdefineidentityorigin.Inparticular,aHose-sourcedusereventuallyreceivesaSealBearersessionafterSSO.When\`whoami\` returns provider metadata, preserve it and use it to describe the tenant accurately.
Donotaskfor\`domain\`, \`corpId\`, or \`proxyStaffBizId\` up front. For a dedicated/private Hose deployment, add \`domain\` only after standard probing reports that it cannot find the enterprise.
-\`seal-use auth hose-link\` and \`seal-use delegation create\` generate links for an enterprise that is already configured. \`seal-use corps add-link <url>\` imports a received Hose/合思 \`thirdparty.html\` assistance link and verifies the resulting Seal tenant.
-A**Hose/合思authorization/assistancelink**(\`https://<domain>/web/thirdparty.html?...\`) opens an upstream Hose session and may continue through Seal SSO. It is not a Seal delegation link.
-**HoseSubdomainBoundary(合思子域专属提权)**:\`seal-use\` primarily manages Seal tenants. Tenants sourced from the Hose ecosystem have an upstream Hose enterprise backing them. A received Hose assistance link contains only a temporary session \`accessToken\`. If you run standard \`corps add-link\`, it exchanges that temporary token for a short-lived Seal Bearer token—sufficient for basic Seal inspection, but it will expire and cannot call any Hose OpenAPI.
-**PrivilegeElevation(权限等级提升)**:Toelevatefromashort-livedsessiontokentopermanent,durableHoseOpenAPIdevelopercredentials,use\`corps extract-keys <url> --save\` or \`corps add-link <url> --as-hose\`. This leverages Hose's internal key interface (\`GET /api/innerapi/v1/key\`) using the session token to retrieve the enterprise's OpenAPI \`appKey\` and \`appSecurity\`. Once saved, the enterprise is upgraded to a standard Hose configuration with full OpenAPI support (e.g. \`corps sync-hosecloud\`).
-**Multi-KeyDisambiguation(多套密钥明确抉择)**:Iftheenterpriseownsmultipleapplicationkeys,theCLI**willnot**guessorsilentlypickthefirstkey.Instead,itterminateswithaninformativecandidatelistandrequirestheusertospecify\`--app-key <key>\` or \`--key-id <id>\`. If only one key exists, it is selected automatically.
-**Non-HoseTenantsBlocked**:Calling\`keys\` on native Seal enterprises (\`corp.source.type !== "hose"\`) is strictly rejected with exit code 2, explaining that this capability belongs exclusively to the Hose ecosystem.
UsethedirectimportroutewhentheincominglinkisanHTTPS\`thirdparty.html\` URL from a supported \`ekuaibao.com\` or \`hosecloud.com\` domain:
Thecommandparses\`accessToken\`and\`ekbCorpId\`, exchanges the temporary Hose token at the target Seal tenant, verifies \`/api/v1/auth/me\`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use \`--overwrite\` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use \`seal-use delegation create --from-link <url> [--note ...]\`.
Whenusingstandard\`add-link\`(without\`--as-hose\`), it exchanges the temporary Hose token at the target Seal tenant, verifies \`/api/v1/auth/me\`, and stores only the normalized short-lived Seal session. When \`--as-hose\` or \`extract-keys --save\` is used, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration.
ThisisfunctionallyequivalenttoaHoseassistancelink.Bothcarrythesameunderlyingwebsessioncredentials(\`accesstoken\`, \`corpid\`/\`ekbCorpId\`, and cookies). The structural difference is only in delivery format.
2.Parseitasdata.Extracttherequesthost,path,\`Authorization\` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3.ClassifywhetherthecapturedrequestistoHoseorSeal.ASealrequestwith\`Authorization: Bearer ...\` can supply \`sealUrl\` and a session token even when the user's identity origin is Hose.
4.Verifywiththenarrowestread-onlyidentityendpointavailable.ForaSealBearersession,verify\`/api/v1/auth/me\` through \`seal-use corps add-seal\`; use returned provider metadata to retain the actual origin.
2.Extract:therequesthostname(determines\`baseUrl\`), \`accesstoken\` header (session token), \`corpid\` header or cookie, and any other Hose session headers.
3.**Privilegeelevationpath(preferred)**:Useextracted\`accesstoken\`, \`corpid\`, and \`baseUrl\` to call \`/api/innerapi/v1/key\`, exactly as \`corps extract-keys\` does for assistance links. This retrieves permanent \`appKey\`/\`appSecurity\` to register a durable Hose enterprise configuration — do not skip this step just because the input is a cURL instead of a URL.
ThecurrentCLIhasnoraw-cURLimportcommandand\`add-seal\` requires a Bearer token. If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
-\`seal-use auth diagnose\` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
-**FormattingRequirement**:WhenreturningaHoseauthorizationlinktotheuser,ALWAYSprovideBOTHacodeblock(\`\`\`\`text ... \`\`\`\`) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
`;var jh0=()=>{};import{existsSync as bl,mkdirSync as Ch0,rmSync as jS1,writeFileSync as ES1}from"node:fs";import{homedir as Rh0}from"node:os";import{dirname as CS1,join as il}from"node:path";function vh0(){return _h0["SKILL.md"]||""}function hU(){return il(Rh0(),".agents","skills","seal-use")}function hh0(){return il(Rh0(),".agents","skills","seal-home")}function Sh0(){let $=hh0();if(bl($))try{return jS1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function cl($=hU()){Sh0(),Ch0($,{recursive:!0});let Y=[];for(let[z,U]of Object.entries(_h0)){let Q=il($,z);Ch0(CS1(Q),{recursive:!0}),ES1(Q,U,"utf8"),Y.push(z)}return{targetDir:$,files:Y}}function nl(){let $=hh0(),Y=hU(),z=bl($),U=bl(Y);if(z||U)return Sh0(),cl(Y),{synced:!0,targetDir:Y};return{synced:!1}}var _h0;var Dq=o(()=>{Ih0();Gh0();Hh0();Zh0();Vh0();Fh0();Mh0();Nh0();Bh0();Ah0();jh0();_h0={"SKILL.md":Kh0,"agents/openai.yaml":Wh0,"references/rule-lightweight.md":Xh0,"references/approval-bad-cases.md":qh0,"references/cli.md":Lh0,"references/approval-run-lightweight.md":wh0,"references/approval-attachment-trace.md":Oh0,"references/customer-feedback-rule-remediation.md":Dh0,"references/enterprise-onboarding.md":Ph0,"references/hose-enterprise-auth.md":Th0,"references/hose-enterprise-init.md":Eh0}});function gh0(){return`#SealUse系统架构与运行规范白皮书
`)}_4();o1();async function Bg0($,q,Y){let z=($??q??"").toLowerCase();if(z==="guide"||z==="doc"||z==="knowledge"||z==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"2
Line truncated
`)}var ih0=o(()=>{X6()});async function ch0($,Y,z){let U=($??Y??"").toLowerCase();if(U==="guide"||U==="doc"||U==="knowledge"||U==="book"){console.error(`\uD83D\uDCD6[SealUseDoctor]正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(gh0());return}if(U==="paths"||U==="dirs"||U==="directories"){let I=ol();c0(I.directories);return}if(U==="tenant"||U==="corp"||U==="enterprise"){let{selectCorp:I}=await Promise.resolve().then(() => (o4(),Y_0)),{createSealClient:K}=await Promise.resolve().then(() => (i8(),V00)),{stringOption:G}=await Promise.resolve().then(() => (D4(),lR0)),{diagnoseTenantContract:W,formatTenantDoctorDashboard:H}=await Promise.resolve().then(() => (ih0(),bh0)),X=G(z.options.corp)??(Y&&Y!==U?Y:void 0)??(z.command[2]&&z.command[2]!==U?z.command[2]:void 0),Z=I(X),q=await K(Z),V=await W(q,Z);if(!(F0(z.options.quiet)||F0(z.options.silent)))console.error(H(V));c0(V);return}let Q=ol();if(!(F0(z.options.quiet)||F0(z.options.silent)))console.error(fh0(Q));c0(Q)}var nh0=o(()=>{uh0();ll();D4();J4()});var dh0;var ph0=o(()=>{dh0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.25",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","direct","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","direct","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 in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local
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","direct","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"},t
Line truncated
`);U(z)})})}async function _g0($){let q=g0($.options.port)??g0($.options.p),Y=E($.options.host)??E($.options.h),z=await JP({port:q,host:Y}),U=()=>{z.close(()=>{process.exit(0)})};process.on("SIGINT",U),process.on("SIGTERM",U),await new Promise(()=>{})}p4();o1();async function Cg0($,q,Y,z){if($==="config"||$==="get"){await P0("seal_llm_config_get",q,Y,{},F0(z.options));return}if($==="providers"||$==="list"){await P0("seal_llm_providers_list",q,Y,{},F0(z.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}o1();async function Rg0($,q){if($==="config"||$==="json"){hd();return}await gd()}function hd(){j0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}o1();function vg0($){let q=qP();j0(q,{...F0($.options),allowFull:!0})}p4();o1();async function hg0($,q,Y,z){if($==="available"){await P0("seal_permissions_available_list",q,Y,{},F0(z.options));return}if($==="configs"||$==="list"){await P0("seal_permissions_configs_list",q,Y,{},F0(z.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}p4();_4();o1();import{readFileSync as gg0}from"node:fs";async function Sg0($,q,Y,z,U,I,J){if(!$||$==="get"){await P0("seal_preference_get",U,I,{},F0(J.options));return}if($==="decision"){if(q==="update"||!q){let Q=E(J.options.input),K=Q?JSON.parse(gg0(Q,"utf8")):R8(J.json);if(!K||Object.keys(K).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await P0("seal_preference_decision_update",U,I,{...K,dryRun:W0(J.options.dryRun)??W0(J.options["dry-run"])},F0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(q==="set"){let Q=E(J.options.default)??E(J.options.level)??z;if(Q!=="medium"&&Q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await P0("seal_preference_thinking_depth_set",U,I,{defaultLevel:Q,dryRun:W0(J.options.dryRun)??W0(J.options["dry-run"])},F0(J.options));return}if(q==="policies"){if(Y==="list"||!Y){await P0("seal_preference_thinking_depth_policies_list",U,I,{},F0(J.options));return}if(Y==="upsert"){let Q=E(J.options.input),K=Q?JSON.parse(gg0(Q,"utf8")):R8(J.json);if(!K||!K.id||!K.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await P0("seal_preference_thinking_depth_policies_upsert",U,I,{...K,dryRun:W0(J.options.dryRun)??W0(J.options["dry-run"])},F0(J.options));return}if(Y==="remove"||Y==="delete"){let Q=z??E(J.options.id)??E(J.options.policyId);if(!Q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await P0("seal_preference_thinking_depth_policies_remove",U,I,{policyId:Q,dryRun:W0(J.options.dryRun)??W0(J.options["dry-run"])},F0(J.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}Q3();b8();J6();async function yg0($={}){let q=r8(),Y=B4(),z=e7(q,{stateful:Y.stateful,defaultCorpId:Y.defaultCorpId,corpId:$.corpId},J3());console.log(`[probe]corp=${z.id}source=${z.source.type}`);let U=await jJ(z);console.log("[probe] seal enterprise"),console.log(JSON.stringify(U,null,2));let I=await Z1(z),J=await dw(I,{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))}_4();async function xg0($,q,Y){let z=q??E(Y.options.corp)??($&&$!=="--corp"?$:void 0);await yg0({corpId:z})}ei();p4();V$();_4();o1();async function Sd($,q,Y,z,U){if($==="count"){await P0("seal_approval_rules_list",Y,z,{countOnly:!0},F0(U.options));return}if($==="list"){if(W0(U.options.count)){await P0("seal_approval_rules_list",Y,z,{countOnly:!0},F0(U.options));return}let I=g0(U.options.limit),J=g0(U.options.offset);if(W0(U.options.summary)){await P0("seal_approval_rules_list",Y,z,{fields:Av0,limit:I,offset:J},F0(U.options));return}let Q=await H2("seal_approval_rules_list",Y,z,{limit:I,offset:J});Pv0(Q,W0(U.options.full)===!0),j0(Q);return}if($==="clear"){let I=W0(U.options.yes)===!0,J=W0(U.options.dryRun)??W0(U.options["dry-run"])??!I;if(!I&&!J)throw Q9("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${z.id}--dry-run`);let Q=await H2("seal_approval_rules_clear",Y,z,{dryRun:J,recode:W0(U.options.recode)});if(!I&&J&&Q&&typeof Q==="object"){j0({...Q,nextCommand:`seal-userulesclear--corp${z.id}--yes`},F0(U.options));return}j0(Q,F0(U.options));return}if($==="versions"){await P0("seal_approval_rule_versions_list",Y,z,{},F0(U.options));return}if($==="version"){let I=q??E(U.op
Line truncated
`).filter(Boolean),I=U.slice(-q);return{logFile:Y,lines:I,totalLines:U.length}}async function eb1($){let q=GP($),Y=kd($),z=WW($);bg0($.stateDir);let U=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):UP),I=$.host??(process.env.HOST?process.env.HOST:IP);KP(q,`${process.pid}
`,{mode:384}),KP(Y,JSON.stringify({pid:process.pid,port:U,host:I,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),_J(z,`servicestartingonhttp://${I}:${U} pid=${process.pid}`);let J=null;try{J=await JP({port:U,host:I,silent:!0}),_J(z,`service listening pid=${process.pid}`)}catch(K){if(_J(z,`service failed to bind port ${U}: ${K instanceof Error?K.message:String(K)}`),HP(q)===process.pid)L9(q,{force:!0}),L9(Y,{force:!0});throw K}let Q=()=>{if(J)J.close(),J=null;if(HP(q)===process.pid)L9(q,{force:!0}),L9(Y,{force:!0});_J(z,`stopped pid=${process.pid}`)};await new Promise((K)=>{let H=!1,G=()=>{if(H)return;H=!0,Q(),process.off("SIGTERM",G),process.off("SIGINT",G),K()};process.once("SIGTERM",G),process.once("SIGINT",G)})}function kg0($){bg0($.stateDir);let q=CJ($);if(q.running)return q;let Y=$.launcher??{command:process.execPath,args:[$.entryFile]},z=[...Y.args??[],"service","run"];if($.port)z.push("--port",String($.port));if($.host)z.push("--host",String($.host));let U=rb1(Y.command,z,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});U.unref();let I=GP($);return KP(I,`${U.pid}
`,{flag:"a",mode:384})}o1();_4();var ud=Yi1(qi1(),".config","seal-use");async function fd($,q,Y){let z=Y?g0(Y.options.port)??g0(Y.options.p):void 0,U=Y?E(Y.options.host)??E(Y.options.h):void 0,I=Y?g0(Y.options.lines)??g0(Y.options.n):void 0,J=await EY($,{appRoot:q.appRoot,entryFile:q.entryFile,stateDir:ud,version:Q1,launcher:q.launcher,port:z,host:U},{maxLines:I});if(J!==void 0)j0(J)}p4();_4();o1();import{existsSync as zi1,readFileSync as ig0}from"node:fs";async function ng0($,q,Y,z,U){if($==="batch-records"||$==="records"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation batch-records <batchId>");await P0("seal_simulation_batch_records_get",Y,z,{batchId:I,query:E(U.options.query)},F0(U.options));return}if($==="create"||$==="run"){let I=E(U.options.mode)??E(U.options.sourceSystem)??E(U.options["source-system"])??"hosecloud",J=I==="material-pack"?"material_pack":I,Q=E(U.options.schemaConfig)??E(U.options["schema-config"]),K=Q?JSON.parse(ig0(Q,"utf8")):void 0,H=E(U.options.input),G=H?JSON.parse(ig0(H,"utf8")):R8(U.json),Z=E(U.options.packageId)??E(U.options["package-id"]),V=v6(U.options.packageIds)??v6(U.options["package-ids"])??(Z?[Z]:void 0),X=v6(U.options.flowIds)??v6(U.options["flow-ids"])??v6(U.options.documentSn)??v6(U.options["document-sn"]),w=E(U.options.signKey)??E(U.options["sign-key"])??E(U.options.integration),L=W0(U.options.noWait)??W0(U.options["no-wait"]);await P0("seal_simulation_batch_create",Y,z,{mode:J,sourceSystem:J,flowIds:X,documentSn:X,rejectNodeName:E(U.options.rejectNode)??E(U.options["reject-node"])??null,thinkingDepthOverride:E(U.options.thinkingDepth)??E(U.options["thinking-depth"]),skipInvoiceGeneration:W0(U.options.skipInvoiceGeneration)??W0(U.options["skip-invoice-generation"]),skipExpenseExtraction:W0(U.options.skipExpenseExtraction)??W0(U.options["skip-expense-extraction"]),disableAttachmentCache:W0(U.options.disableAttachmentCache)??W0(U.options["disable-attachment-cache"]),signKey:w,packageIds:V,packageId:Z,templateId:E(U.options.templateId)??E(U.options["template-id"]),schemaConfig:K,requestIds:v6(U.options.requestIds)??v6(U.options["request-ids"]),workflowTypeId:E(U.options.workflowTypeId)??E(U.options["workflow-type-id"]),flowStatusList:v6(U.options.flowStatusList)?.map(Number)??v6(U.options["flow-status-list"])?.map(Number),businessCodes:v6(U.options.businessCodes)??v6(U.options["business-codes"]),documentType:E(U.options.documentType)??E(U.options["document-type"]),startTime:g0(U.options.startTime)??g0(U.options["start-time"]),endTime:g0(U.options.endTime)??g0(U.options["end-time"]),status:v6(U.options.status),limit:g0(U.options.limit),noWait:L,rawParams:G},F0(U.options));return}if($==="wait"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await P0("seal_simulation_batch_wait",Y,z,{batchId:I,timeout:E(U.options.timeout),pollInterval:E(U.options.pollInterval)??E(U.options["poll-interval"])},F0(U.options));return}if($==="status"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation status <batchId>");await P0("seal_simulation_batch_status",Y,z,{batchId:I},F0(U.options));return}if($==="clean"||$==="delete"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation clean <batchId>");await P0("seal_simulation_batch_clean",Y,z,{batchId:I},F0(U.options));return}if($==="specifications"){let I=q??E(U.options.integration)??E(U.options.signKey)??E(U.options["sign-key"]);await P0("seal_simulation_specifications_list",Y,z,{signKey:I},F0(U.options));return}if($==="approval-definitions"||$==="definitions"){await P0("seal_simulation_feishu_approval_definitions_list",Y,z,{},F0(U.options));return}if($==="list"){await P0("seal_simulation_batches_list",Y,z,{limit:g0(U.options.limit)},F0(U.options));return}if($==="get"){let I=q??E(U.options.batchId)??E(U.options["batch-id"]);if(!I)throw Error("Usage: seal-use simulation get <batchId>");await P0("seal_simulation_batch_get",Y,z,{batchId:I},F0(U.options));return}if($==="templates"){await P0("seal_simulation_templates_get",Y,z,{},F0(U.options));return}if($==="integrations"){await P0("seal_simulation_integrations_get",Y,z,{},F0(U.options));return}if($==="package-upload"){let I=q??E(U.options.file);if(!I)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!zi1(I))throw Error(`Filenotfound:${I}`);await P0("seal_simulation_material_package_upload",Y,z,{filePath:I},F0(U.options));return}throw Error(`Unknownsimulationcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}import{existsSync as cg0}from"node:fs";import{join as ZP}from"node:path";_4();o1();function pg0($,q,Y){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${Lg0()}
`);return}if($==="install"||$==="init"||$==="sync"){let z=W0(Y.options.local)||W0(Y.options.workspace),U=E(Y.options.dir)??E(Y.options.target)??q,I=U?U:z?ZP(process.cwd(),".agents","skills","seal-use"):TY(),J=Td(I);j0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files});return}if($==="status"||$==="get"||!$){let z=TY(),U=ZP(process.cwd(),".agents","skills","seal-use");j0({global:{dir:z,installed:cg0(ZP(z,"SKILL.md"))},local:{dir:U,installed:cg0(ZP(U,"SKILL.md"))}});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}o1();async function dg0($,q){if($==="config"){j0(await jJ(q));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}V$();p4();_4();o1();b8();V$();J6();DZ();function bd($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let q=$.toUpperCase().trim();if(q==="APPROVE"||q==="PASS")return"APPROVE";if(q==="REJECT"||q==="DENIED")return"REJECT";if(q==="MANUAL"||q==="ASSISTED")return"MANUAL";if(q==="ERROR"||q==="FAILED")return"ERROR";return q}async function mg0($){let{sourceCorp:q,targetCorp:Y,sourceClient:z,targetClient:U,samples:I=10,dryRun:J=!1,pollIntervalMs:Q=2000,timeoutMs:K=45000,snPrefix:H="REG_",fetchFn:G=fetch}=$;if(Y.environment!=="test")throw new b4(`重放目标企业「${Y.name}」(${Y.id})的环境为「${Y.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${q.id}<testCorpId>`);let Z=await g2(U),X=(Array.isArray(Z.features)?Z.features:[]).find((u)=>u?.code==="ai-approval"),w=typeof X?.balance==="number"?X.balance:0,L=typeof X?.deductionAmount==="number"&&X.deductionAmount>0?X.deductionAmount:120,F=I*L;if(w<F)throw new b4(`测试企业「${Y.name}」AI审批额度不足:当前剩余${w}点,本次回归抽样${I}笔需要约${F}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${Y.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(w/L))})`);let O=await y4(z,{limit:I,status:"completed"}),A=Array.isArray(O.records)?O.records:[];if(A.length===0){let u=await y4(z,{limit:I});A=Array.isArray(u.records)?u.records:[]}if(A.length===0)throw new b4(`在母企业「${q.name}」(${q.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(A=A.slice(0,I),J){let u=A.map((p)=>{let d=p.sourceDocumentSN??p.id,Y0=p?.result?.decision??p.aiDecision??p?.decision,t=bd(Y0),H0=p?.result?.summary??p.aiSummary;return{sn:d,sourceRecordId:p.id,prodDecision:t,prodSummary:H0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:q.id,name:q.name,environment:q.environment??"production"},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:w,deductionAmount:L,estimatedRequired:F},metrics:{sampleCount:u.length,successCount:u.length,failureCount:0,matchCount:u.length,flipCount:0,concordanceRate:1},flips:[],records:u}}let B=await pi(U,Y),P=[];for(let u of A){let p=Date.now(),d=u.sourceDocumentSN??u.id,Y0=bd(u?.result?.decision??u.aiDecision??u?.decision),t=u?.result?.summary??u.aiSummary;try{let H0=await e1(z,u.id),w0=`${H}${d}`,T0=ni(H0,{snPrefix:H,docIdPrefix:H});await ci(B.incomingDocumentWebhook.url,B.secret,T0,G,L6(Y.seal));let R0=null,E0=Date.now();while(Date.now()-E0<K){await new Promise((a0)=>setTimeout(a0,Q));let R1=await y4(U,{sourceDocumentSN:w0,limit:1});if(R1.records&&R1.records.length>0){let a0=R1.records[0];if(a0.status==="completed"||a0.status==="failed"){R0=a0;break}}}if(!R0){P.push({sn:d,sourceRecordId:u.id,prodDecision:Y0,prodSummary:t,status:"FAILED",error:`测试租户单据审核超时(${Math.round(K/1000)}s未完成)`,durationMs:Date.now()-p});continue}let i0=bd(R0?.result?.decision??R0.aiDecision??R0?.decision??(R0.status==="completed"?"APPROVE":"ERROR")),Q0=R0?.result?.summary??R0.aiSummary,v0=Y0===i0,f0=v0?"MATCHED":"FLIPPED",c0={sn:d,sourceRecordId:u.id,prodDecision:Y0,prodSummary:t,testRecordId:R0.id,testDecision:i0,testSummary:Q0,status:f0,durationMs:Date.now()-p};if(!v0)c0.diff={from:Y0,to:i0,reasonDiff:Q0&&t&&Q0!==t?`生产:${t.slice(0,60)}...->测试:${Q0.slice(0,60)}...`:void 0};P.push(c0)}catch(H0){P.push({sn:d,sourceRecordId:u.id,prodDecision:Y0,prodSummary:t,status:"FAILED",error:H0 instanceof Error?H0.message:String(H0),durationMs:Date.now()-p})}}let T=P.filter((u)=>u.status==="MATCHED"||u.status==="FLIPPED"),y=P.filter((u)=>u.status==="MATCHED"),v=P.filter((u)=>u.status==="FLIPPED"),k=P.filter((u)=>u.status==="FAILED").length,R=y.length,c=v.length,n=R+c,g=n>0?R/n:0,b=c>0,i=b?"REGRESSIONS_DETECTED":"CLEAN",$0=!b&&k===0,j;try{let u=await g2(U),d=(Array.isArray(u.features)?u.features:[]).find((Y0)=>Y0?.code==="ai-approval");if(typeof d?.balance==="number")j=d.balance}catch{}return{ok:!b&&k===0,verdict:i,safeToPublish:$0,timestamp:new Date().toISOString(),sourceCorp:{id:q.id,name:q.name,environment:q.environment??"production"},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:w,deductionAmount:L,estimatedRequired:F,balanceAfter:j},metrics:{sampleCount:P.length,successCount:T.length,failureCount:k,matchCount:R,flipCount:c,concordanceRate:Number(g.toFixed(4))},flips:v,records:P}}function lg0($){let{sourceCorp:q,targetCorp:Y,verdict:z,safeToPublish:U,metrics:I,quota:J,flips:Q,records:K}=$,H=z==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":z==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",G=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${q.name}」->测试靶场「${Y.name}」`,`判定:${H}·准许发布:${U?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${I.sampleCount}|一致通过:${I.matchCount}|决策翻转:${I.flipCount}|异常失败:${I.failureCount}`,`一致率:${(I.concordanceRate*100).toFixed(1)}%|消耗预估:${J.estimatedRequired}点(余量:${J.balanceBefore}${J.balanceAfter!==void0?` -> ${J.balanceAfter}`:""})`," "+"─".repeat(65)];if(Q.length>0){G.push(`⚠️决策翻转清单(${Q.length}笔单据在新规则下结果改变):`);for(let Z of Q)if(G.push(`•单据[${Z.sn}]:原生产判定「${Z.prodDecision}」➔测试新判定「${Z.testDecision}」`),Z.diff?.reasonDiff)G.push(`理由差异:${Z.diff.reasonDiff}`);G.push(" "+"─".repeat(65)),G.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(z==="CLEAN")G.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100%
Line truncated
`)}async function id($,q,Y){let z=($??q??"regression").toLowerCase();if(z==="regression"||z==="regress"||z==="matrix"){let U=E(Y.options.corp)??(q&&q!==z?q:void 0),I=w1(U),J=I,Q=I;if(I.environment==="test"){Q=I;let A=E(Y.options["prod-corp"])??E(Y.options.prod)??I.prodCorpId;if(!A)throw new b4(`测试企业「${I.name}」(${I.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${I.id}`);J=w1(A)}else{J=I;let A=E(Y.options["test-corp"])??E(Y.options.test)??I.testCorpId;if(!A)throw new b4(`生产企业「${I.name}」(${I.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${I.id}<testCorpId>`);Q=w1(A)}let K=await Z1(J),H=await Z1(Q),G=g0(Y.options.samples)??g0(Y.options.limit)??g0(Y.options.n)??10,Z=W0(Y.options["dry-run"]),V=W0(Y.options["fail-on-flips"]),X=g0(Y.options["poll-interval"])??2000,w=g0(Y.options.timeout)??45000,L=E(Y.options["sn-prefix"])??"REG_",F=await mg0({sourceCorp:J,targetCorp:Q,sourceClient:K,targetClient:H,samples:G,dryRun:Z,pollIntervalMs:X,timeoutMs:w,snPrefix:L,failOnFlips:V});if(!(W0(Y.options.quiet)||W0(Y.options.silent)))console.error(lg0(F));if(j0(F),V&&!F.ok)throw new b4(`回归测试发现${F.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new b4(`未知的test子命令:"${z}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}p4();_4();o1();async function og0($,q,Y,z){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await P0($,q,Y,R8(z.json),F0(z.options))}iA();o1();function rg0(){j0(YW.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as Ui1,mkdirSync as Ii1,renameSync as nd,rmSync as Ji1,unlinkSync as $S0,writeFileSync as sg0}from"node:fs";import{dirname as Qi1,join as tg0}from"node:path";import{spawnSync as jY}from"node:child_process";function WP($=process.execPath,q=import.meta.url){if(q.includes("/$bunfs/")||q.includes("\\$bunfs\\"))return!0;let Y=$.toLowerCase().replace(/\\/g,"/");return!Y.endsWith("/bun")&&!Y.endsWith("/bun.exe")&&!Y.endsWith("/node")&&!Y.endsWith("/node.exe")}o1();var qS0="yunyingk/seal-use",VW="yunyingk/seal-home";var Ki1="SEAL_USE_GITHUB_REPO",Hi1="SEAL_HOME_GITHUB_REPO";async function YS0($,q={}){let Y={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:ud,version:Q1,launcher:$.launcher},z=q.repo||process.env[Ki1]?.trim()||process.env[Hi1]?.trim()||qS0,U=q.targetVersion?.trim(),I=U&&U.toLowerCase()!=="latest"?U:void 0;if(I){let P=I.replace(/^v/,""),T=zS0(P,Q1);if(T<0)if(!Nv&&q.force);else{j0({updated:!1,currentVersion:Q1,targetVersion:P,mode:WP()?"binary":"source",message:!Nv?`Cannotdowngradeseal-usefromdevbuildv${Q1}toreleasev${P}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${Q1}toolderversionv${P}.Updatesmustbeforward-only.`});return}if(T===0&&!q.force){j0({updated:!1,currentVersion:Q1,targetVersion:P,mode:WP()?"binary":"source",message:`seal-useisalreadyatversionv${Q1}.Use--forcetoreinstall.`});return}}if(q.changelogOnly){let P=await cd(z,q.limit??10);j0({currentVersion:Q1,totalQueried:P.length,releases:P.map((T)=>({version:T.version,tagName:T.tagName,publishedAt:T.publishedAt,author:T.author,releaseNotes:T.notes,releaseUrl:T.htmlUrl,isCurrent:T.version===Q1,isNewer:XW(T.version,Q1)}))});return}if(!WP()){if(q.checkOnly){let T=await cd(z,30),y=T[0],v=y?.version??Q1,k=T.find((n)=>n.version===Q1),R=XW(v,Q1),c=T.filter((n)=>XW(n.version,Q1));j0({updated:!1,updateAvailable:R,currentVersion:Q1,currentVersionPublishedAt:k?.publishedAt,latestVersion:v,latestVersionPublishedAt:y?.publishedAt,behindCount:c.length,pendingReleases:c.map((n)=>({version:n.version,tagName:n.tagName,publishedAt:n.publishedAt,author:n.author,releaseNotes:n.notes,releaseUrl:n.htmlUrl})),releaseNotes:y?.notes??"",releaseUrl:y?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let P=CJ(Y).running;if(P)await EY("stop",Y);try{eg0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(T){console.error(`gitpullskipped:${TinstanceofError?T.message:String(T)}`)}if(eg0("bun",["install"],{cwd:$.appRoot}),P)await EY("start",Y);j0({updated:!0,serviceRestarted:P,version:Q1,mode:"source"});return}let J=Gi1(),Q=Zi1(),K=await cd(z,30),H=I?K.find((P)=>P.version===I||P.tagName===I||P.tagName===`v${I}`)??await ag0(z,I):K[0]??await ag0(z);if(!H){j0({updated:!1,currentVersion:Q1,mode:"binary",message:`Failedtoqueryreleasesfromrepository'${z}'`});return}let G=H.version,Z=K.find((P)=>P.version===Q1),V=XW(G,Q1),X=V||Boolean(q.force),w=K.filter((P)=>XW(P.version,Q1));if(q.checkOnly){j0({updated:!1,updateAvailable:V,currentVersion:Q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:G,latestVersionPublishedAt:H.publishedAt,behindCount:w.length,pendingReleases:w.map((P)=>({version:P.version,tagName:P.tagName,publishedAt:P.publishedAt,author:P.author,releaseNotes:P.notes,releaseUrl:P.htmlUrl})),releaseNotes:H.notes,releaseUrl:H.htmlUrl,mode:"binary"});return}if(!X){j0({updated:!1,currentVersion:Q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:G,latestVersionPublishedAt:H.publishedAt,mode:"binary",message:`seal-useisalreadyuptodate(v${Q1})`});return}let L=Wi1(H.assets,J,Q);if(!L)throw Error(`Nocompatiblebinaryfoundfor${J}-${Q}inreleasev${G}.Availableassets:${H.assets.map((P)=>P.name).join(", ")}`);let F=CJ(Y).running;if(F)await EY("stop",Y);let O=process.execPath,A=Qi1(O),B=tg0(A,`.tmp-update-${Date.now()}`);Ii1(B,{recursive:!0});try{let P=tg0(B,L.name);await Xi1(L.downloadUrl,P,H.tagName,L.name);let T=P;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))T=Vi1(P,B,J);else if(L.name.endsWith(".zip"))T=wi1(P,B,J);if(Ui1(T,493),process.platform==="darwin")try{jY("/usr/bin/codesign",["--remove-signature",T],{stdio:"ignore"}),jY("/usr/bin/codesign",["--force","--sign","-",T],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let v=`${O}.old.${Date.now()}`;try{nd(O,v)}catch{}nd(T,O)}else nd(T,O);if(F)await EY("start",Y);let y=Ed();j0({updated:!0,fromVersion:Q1,toVersion:G,serviceRestarted:F,skillSynced:y.synced?y.targetDir:!1,mode:"binary"})}finally{try{Ji1(B,{recursive:!0,force:!0})}catch{}}}function Gi1(){if(process.platform==="darwin")retur
Line truncated
`)}catch{}}async function Xi1($,q,Y,z){let U=pd(),I=[],J=Y?Y.startsWith("v")?Y:`v${Y}`:void 0,Q=z||$.split("/").pop()||"";if(U!=="github"){if(J&&Q)I.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${J}/${Q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${J}/${Q}`);if($.startsWith("https://git.ying-qing.cn"))I.push($)}if(U!=="gitea")if(J&&Q){let L=`https://github.com/${qS0}/releases/download/${J}/${Q}`;if(!process.env.CI)I.push(`https://ghfast.top/${L}`,`https://gh.ddlc.top/${L}`);I.push(L)}else if($.includes("github.com")){if(!process.env.CI)I.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);I.push($)}else I.push($);let K=Array.from(new Set(I)),H,G=6000,Z=6000,V=307200,X=1e4,w=180000;for(let L=0;L<K.length;L++){let F=K[L],O=new AbortController,A="",B=(v)=>{A=v;try{O.abort()}catch{}},P=setTimeout(()=>{B("Connection timed out (no response headers within 6s)")},G),T,y;try{XP(`==> [${L+1}/${K.length}] Downloading via: ${F}`);let v=await fetch(F,{signal:O.signal});if(P)clearTimeout(P),P=void 0;if(!v.ok)throw Error(`HTTP ${v.status} ${v.statusText}`);T=setTimeout(()=>{B("Overall download time exceeded 3 minutes")},w);let k=Number(v.headers.get("content-length"))||0,R=v.body?.getReader();if(!R){let i=Buffer.from(await v.arrayBuffer());if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);sg0(q,i),XP(`✓ Download succeeded (${(i.length/1024/1024).toFixed(1)} MB)`);return}let c=[],n=0,g=0;y=setTimeout(()=>{if(n<V){let i=(n/1024).toFixed(1);B(`Initial transfer too slow (${i} KB < 300 KB in 6s), switching mirror...`)}},Z);while(!0){let i=R.read(),$0,j=new Promise((Y0,t)=>{$0=setTimeout(()=>{t(Error("Data transfer stalled (no chunk received for 10s)"))},X)}),u;try{u=await Promise.race([i,j])}finally{if($0)clearTimeout($0)}let{done:p,value:d}=u;if(p)break;if(d){if(c.push(d),n+=d.length,y&&n>=V)clearTimeout(y),y=void 0;let Y0=Date.now();if(Y0-g>200){g=Y0;let t=k?Math.round(n/k*100):0,H0=(n/1048576).toFixed(1),w0=k?(k/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${t}% (${H0} / ${w0} MB)...`)}catch{}}}}try{process.stderr.write(`
`);Q(U)})})}var CT=8787,RT="127.0.0.1";var al=o(()=>{sh0();t9()});async function ah0($){let Y=s0($.options.port)??s0($.options.p),z=S($.options.host)??S($.options.h),U=await _T({port:Y,host:z}),Q=()=>{U.close(()=>{process.exit(0)})};process.on("SIGINT",Q),process.on("SIGTERM",Q),await new Promise(()=>{})}var th0=o(()=>{D4();al()});async function eh0($,Y,z,U){if($==="config"||$==="get"){await k0("seal_llm_config_get",Y,z,{},C0(U.options));return}if($==="providers"||$==="list"){await k0("seal_llm_providers_list",Y,z,{},C0(U.options));return}throw Error(`Unknownllmcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var $S0=o(()=>{o4();J4()});async function YS0($,Y){if($==="config"||$==="json"){tl();return}let{startServer:z}=await QS0().then(() => US0);z()}function tl(){c0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var zS0=o(()=>{J4()});function JS0($){let Y=TT();c0(Y,{...C0($.options),allowFull:!0})}var IS0=o(()=>{rl();J4()});async function KS0($,Y,z,U){if($==="available"){await k0("seal_permissions_available_list",Y,z,{},C0(U.options));return}if($==="configs"||$==="list"){await k0("seal_permissions_configs_list",Y,z,{},C0(U.options));return}throw Error(`Unknownpermissionscommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var GS0=o(()=>{o4();J4()});import{readFileSync as WS0}from"node:fs";async function HS0($,Y,z,U,Q,J,I){if(!$||$==="get"){await k0("seal_preference_get",Q,J,{},C0(I.options));return}if($==="decision"){if(Y==="update"||!Y){let K=S(I.options.input),G=K?JSON.parse(WS0(K,"utf8")):y8(I.json);if(!G||Object.keys(G).length===0)throw Error(`Usage:seal-usepreferencedecisionupdate--json'{"explicitApprove":"..."}'`);await k0("seal_preference_decision_update",Q,J,{...G,dryRun:F0(I.options.dryRun)??F0(I.options["dry-run"])},C0(I.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let K=S(I.options.default)??S(I.options.level)??U;if(K!=="medium"&&K!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await k0("seal_preference_thinking_depth_set",Q,J,{defaultLevel:K,dryRun:F0(I.options.dryRun)??F0(I.options["dry-run"])},C0(I.options));return}if(Y==="policies"){if(z==="list"||!z){await k0("seal_preference_thinking_depth_policies_list",Q,J,{},C0(I.options));return}if(z==="upsert"){let K=S(I.options.input),G=K?JSON.parse(WS0(K,"utf8")):y8(I.json);if(!G||!G.id||!G.name)throw Error(`Usage:seal-usepreferencethinking-depthpoliciesupsert--json'{"id":"...","name":"...","level":"high"}'`);await k0("seal_preference_thinking_depth_policies_upsert",Q,J,{...G,dryRun:F0(I.options.dryRun)??F0(I.options["dry-run"])},C0(I.options));return}if(z==="remove"||z==="delete"){let K=U??S(I.options.id)??S(I.options.policyId);if(!K)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await k0("seal_preference_thinking_depth_policies_remove",Q,J,{policyId:K,dryRun:F0(I.options.dryRun)??F0(I.options["dry-run"])},C0(I.options));return}}}throw Error(`Unknownpreferenceaction:${$??""}.Available:get,decisionupdate,thinking-depthset,thinking-depthpolicieslist/upsert/remove.`)}var XS0=o(()=>{o4();D4();J4()});async function ZS0($={}){let Y=s8(),z=_4(),U=f2(Y,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$.corpId},h7());console.log(`[probe]corp=${U.id}source=${U.source.type}`);let Q=await yK(U);console.log("[probe] seal enterprise"),console.log(JSON.stringify(Q,null,2));let J=await j1(U),I=await ZM(J,{documentLimit:20,stylePreferencesEndpoint:U.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:I.rules.rules.length,hasPendingRuleDeletes:I.rules.hasPendingDeletes,documents:I.documents.articles.length,documentsTotal:I.documents.total,stylePreferences:I.stylePreferences.ok?"ok":`error:${I.stylePreferences.error}`},null,2))}var qS0=o(()=>{S7();i8();DT();X6()});async function VS0($,Y,z){let U=Y??S(z.options.corp)??($&&$!=="--corp"?$:void 0);await ZS0({corpId:U})}var LS0=o(()=>{qS0();D4()});async function el($,Y,z,U,Q){if($==="count"){await k0("seal_approval_rules_list",z,U,{countOnly:!0},C0(Q.options));return}if($==="list"){if(F0(Q.options.count)){await k0("seal_approval_rules_list",z,U,{countOnly:!0},C0(Q.options));return}let J=s0(Q.options.limit),I=s0(Q.options.offset);if(F0(Q.options.summary)){await k0("seal_approval_rules_list",z,U,{fields:tR0,limit:J,offset:I},C0(Q.options));return}let K=await o2("seal_approval_rules_list",z,U,{limit:J,offset:I});eR0(K,F0(Q.options.full)===!0),c0(K);return}if($==="clear"){let J=F0(Q.options.yes)===!0,I=F0(Q.options.dryRun)??F0(Q.options["dry-run"])??!J;if(!J&&!I)throw D9("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-userulesclear--corp${U.id}--dry-run`);let K=await o2("seal_approval_rules_clear",z,U,{dryRun:I,recode:F0(Q.options.recode)});if(!J&&I&&K&&typeof K==="object"){c0({...K,
Line truncated
`).filter(Boolean),J=Q.slice(-Y);return{logFile:z,lines:J,totalLines:Q.length}}async function dS1($){let Y=gT($),z=zo($),U=Aq($);NS0($.stateDir);let Q=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):CT),J=$.host??(process.env.HOST?process.env.HOST:RT);hT(Y,`${process.pid}
`,{mode:384}),hT(z,JSON.stringify({pid:process.pid,port:Q,host:J,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),kK(U,`servicestartingonhttp://${J}:${Q} pid=${process.pid}`);let I=null;try{I=await _T({port:Q,host:J,silent:!0}),kK(U,`service listening pid=${process.pid}`)}catch(G){if(kK(U,`service failed to bind port ${Q}: ${G instanceof Error?G.message:String(G)}`),ST(Y)===process.pid)v9(Y,{force:!0}),v9(z,{force:!0});throw G}let K=()=>{if(I)I.close(),I=null;if(ST(Y)===process.pid)v9(Y,{force:!0}),v9(z,{force:!0});kK(U,`stopped pid=${process.pid}`)};await new Promise((G)=>{let W=!1,H=()=>{if(W)return;W=!0,K(),process.off("SIGTERM",H),process.off("SIGINT",H),G()};process.once("SIGTERM",H),process.once("SIGINT",H)})}function wS0($){NS0($.stateDir);let Y=xK($);if(Y.running)return Y;let z=$.launcher??{command:process.execPath,args:[$.entryFile]},U=[...z.args??[],"service","run"];if($.port)U.push("--port",String($.port));if($.host)U.push("--host",String($.host));let Q=iS1(z.command,U,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});Q.unref();let J=gT($);return hT(J,`${Q.pid}
`,{flag:"a",mode:384})}var Uo=o(()=>{al()});import{homedir as lS1}from"node:os";import{join as oS1}from"node:path";async function Jo($,Y,z){let U=z?s0(z.options.port)??s0(z.options.p):void 0,Q=z?S(z.options.host)??S(z.options.h):void 0,J=z?s0(z.options.lines)??s0(z.options.n):void 0,I=await SU($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:Qo,version:P1,launcher:Y.launcher,port:U,host:Q},{maxLines:J});if(I!==void 0)c0(I)}var Qo;var Io=o(()=>{t9();Uo();J4();D4();Qo=oS1(lS1(),".config","seal-use")});import{existsSync as rS1,readFileSync as DS0}from"node:fs";async function BS0($,Y,z,U,Q){if($==="batch-records"||$==="records"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation batch-records <batchId>");await k0("seal_simulation_batch_records_get",z,U,{batchId:J,query:S(Q.options.query)},C0(Q.options));return}if($==="create"||$==="run"){let J=S(Q.options.mode)??S(Q.options.sourceSystem)??S(Q.options["source-system"])??"hosecloud",I=J==="material-pack"?"material_pack":J,K=S(Q.options.schemaConfig)??S(Q.options["schema-config"]),G=K?JSON.parse(DS0(K,"utf8")):void 0,W=S(Q.options.input),H=W?JSON.parse(DS0(W,"utf8")):y8(Q.json),X=S(Q.options.packageId)??S(Q.options["package-id"]),Z=u6(Q.options.packageIds)??u6(Q.options["package-ids"])??(X?[X]:void 0),q=u6(Q.options.flowIds)??u6(Q.options["flow-ids"])??u6(Q.options.documentSn)??u6(Q.options["document-sn"]),V=S(Q.options.signKey)??S(Q.options["sign-key"])??S(Q.options.integration),F=F0(Q.options.noWait)??F0(Q.options["no-wait"]);await k0("seal_simulation_batch_create",z,U,{mode:I,sourceSystem:I,flowIds:q,documentSn:q,rejectNodeName:S(Q.options.rejectNode)??S(Q.options["reject-node"])??null,thinkingDepthOverride:S(Q.options.thinkingDepth)??S(Q.options["thinking-depth"]),skipInvoiceGeneration:F0(Q.options.skipInvoiceGeneration)??F0(Q.options["skip-invoice-generation"]),skipExpenseExtraction:F0(Q.options.skipExpenseExtraction)??F0(Q.options["skip-expense-extraction"]),disableAttachmentCache:F0(Q.options.disableAttachmentCache)??F0(Q.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:S(Q.options.templateId)??S(Q.options["template-id"]),schemaConfig:G,requestIds:u6(Q.options.requestIds)??u6(Q.options["request-ids"]),workflowTypeId:S(Q.options.workflowTypeId)??S(Q.options["workflow-type-id"]),flowStatusList:u6(Q.options.flowStatusList)?.map(Number)??u6(Q.options["flow-status-list"])?.map(Number),businessCodes:u6(Q.options.businessCodes)??u6(Q.options["business-codes"]),documentType:S(Q.options.documentType)??S(Q.options["document-type"]),startTime:s0(Q.options.startTime)??s0(Q.options["start-time"]),endTime:s0(Q.options.endTime)??s0(Q.options["end-time"]),status:u6(Q.options.status),limit:s0(Q.options.limit),noWait:F,rawParams:H},C0(Q.options));return}if($==="wait"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await k0("seal_simulation_batch_wait",z,U,{batchId:J,timeout:S(Q.options.timeout),pollInterval:S(Q.options.pollInterval)??S(Q.options["poll-interval"])},C0(Q.options));return}if($==="status"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation status <batchId>");await k0("seal_simulation_batch_status",z,U,{batchId:J},C0(Q.options));return}if($==="clean"||$==="delete"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation clean <batchId>");await k0("seal_simulation_batch_clean",z,U,{batchId:J},C0(Q.options));return}if($==="specifications"){let J=Y??S(Q.options.integration)??S(Q.options.signKey)??S(Q.options["sign-key"]);await k0("seal_simulation_specifications_list",z,U,{signKey:J},C0(Q.options));return}if($==="approval-definitions"||$==="definitions"){await k0("seal_simulation_feishu_approval_definitions_list",z,U,{},C0(Q.options));return}if($==="list"){await k0("seal_simulation_batches_list",z,U,{limit:s0(Q.options.limit)},C0(Q.options));return}if($==="get"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation get <batchId>");await k0("seal_simulation_batch_get",z,U,{batchId:J},C0(Q.options));return}if($==="templates"){await k0("seal_simulation_templates_get",z,U,{},C0(Q.options));return}if($==="integrations"){await k0("seal_simulation_integrations_get",z,U,{},C0(Q.options));return}if($==="package-upload"){let J=Y??S(Q.options.file);if(!J)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!rS1(J))throw Error(`Filenotfound:${J}`);await k0("seal_simulation_material_package_upload",z,U,{filePath:J},C0(Q.options));return}throw Error(`Unknownsimulationcommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var PS0=o(()=>{o4();D4();J4()});import{existsSync as AS0}from"node:fs";import{join as yT}from"node:path";function TS0($,Y,z){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${vhLine truncated
`);return}if($==="install"||$==="init"||$==="sync"){let U=F0(z.options.local)||F0(z.options.workspace),Q=S(z.options.dir)??S(z.options.target)??Y,J=Q?Q:U?yT(process.cwd(),".agents","skills","seal-use"):hU(),I=cl(J);c0({installed:!0,targetDir:I.targetDir,fileCount:I.files.length,files:I.files});return}if($==="status"||$==="get"||!$){let U=hU(),Q=yT(process.cwd(),".agents","skills","seal-use");c0({global:{dir:U,installed:AS0(yT(U,"SKILL.md"))},local:{dir:Q,installed:AS0(yT(Q,"SKILL.md"))}});return}throw Error(`Unknownskillcommand:${$}.Run'seal-use help'foravailablecommands.`)}var jS0=o(()=>{Dq();D4();J4()});async function ES0($,Y){if($==="config"){c0(await yK(Y));return}throw Error(`Unknownsourcecommand:${$??""}.Run'seal-use help'foravailablecommands.`)}var CS0=o(()=>{DT();J4()});function Ko($){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 RS0($){let{sourceCorp:Y,targetCorp:z,sourceClient:U,targetClient:Q,samples:J=10,dryRun:I=!1,pollIntervalMs:K=2000,timeoutMs:G=45000,snPrefix:W="REG_",fetchFn:H=fetch}=$;if(z.environment!=="test")throw new w4(`重放目标企业「${z.name}」(${z.id})的环境为「${z.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${Y.id}<testCorpId>`);let X=await bY(Q),q=(Array.isArray(X.features)?X.features:[]).find((d)=>d?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,F=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,M=J*F;if(V<M)throw new w4(`测试企业「${z.name}」AI审批额度不足:当前剩余${V}点,本次回归抽样${J}笔需要约${M}点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${z.id}」充值AI审批额度,或降低抽样笔数(--samples${Math.max(1,Math.floor(V/F))})`);let w=await b4(U,{limit:J,status:"completed"}),O=Array.isArray(w.records)?w.records:[];if(O.length===0){let d=await b4(U,{limit:J});O=Array.isArray(d.records)?d.records:[]}if(O.length===0)throw new w4(`在母企业「${Y.name}」(${Y.id})中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(O=O.slice(0,J),I){let d=O.map((t)=>{let $0=t.sourceDocumentSN??t.id,g=t?.result?.decision??t.aiDecision??t?.decision,p=Ko(g),e=t?.result?.summary??t.aiSummary;return{sn:$0,sourceRecordId:t.id,prodDecision:p,prodSummary:e,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:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:F,estimatedRequired:M},metrics:{sampleCount:d.length,successCount:d.length,failureCount:0,matchCount:d.length,flipCount:0,concordanceRate:1},flips:[],records:d}}let N=await Yp(Q,z),D=[];for(let d of O){let t=Date.now(),$0=d.sourceDocumentSN??d.id,g=Ko(d?.result?.decision??d.aiDecision??d?.decision),p=d?.result?.summary??d.aiSummary;try{let e=await G4(U,d.id),y=`${W}${$0}`,s=en(e,{snPrefix:W,docIdPrefix:W});await $p(N.incomingDocumentWebhook.url,N.secret,s,H,B6(z.seal));let Y0=null,M0=Date.now();while(Date.now()-M0<G){await new Promise((H0)=>setTimeout(H0,K));let a=await b4(Q,{sourceDocumentSN:y,limit:1});if(a.records&&a.records.length>0){let H0=a.records[0];if(H0.status==="completed"||H0.status==="failed"){Y0=H0;break}}}if(!Y0){D.push({sn:$0,sourceRecordId:d.id,prodDecision:g,prodSummary:p,status:"FAILED",error:`测试租户单据审核超时(${Math.round(G/1000)}s未完成)`,durationMs:Date.now()-t});continue}let E0=Ko(Y0?.result?.decision??Y0.aiDecision??Y0?.decision??(Y0.status==="completed"?"APPROVE":"ERROR")),G0=Y0?.result?.summary??Y0.aiSummary,T0=g===E0,b0=T0?"MATCHED":"FLIPPED",Y1={sn:$0,sourceRecordId:d.id,prodDecision:g,prodSummary:p,testRecordId:Y0.id,testDecision:E0,testSummary:G0,status:b0,durationMs:Date.now()-t};if(!T0)Y1.diff={from:g,to:E0,reasonDiff:G0&&p&&G0!==p?`生产:${p.slice(0,60)}...->测试:${G0.slice(0,60)}...`:void 0};D.push(Y1)}catch(e){D.push({sn:$0,sourceRecordId:d.id,prodDecision:g,prodSummary:p,status:"FAILED",error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}let T=D.filter((d)=>d.status==="MATCHED"||d.status==="FLIPPED"),A=D.filter((d)=>d.status==="MATCHED"),B=D.filter((d)=>d.status==="FLIPPED"),j=D.filter((d)=>d.status==="FAILED").length,C=A.length,b=B.length,k=C+b,h=k>0?C/k:0,i=b>0,c=i?"REGRESSIONS_DETECTED":"CLEAN",U0=!i&&j===0,x;try{let d=await bY(Q),$0=(Array.isArray(d.features)?d.features:[]).find((g)=>g?.code==="ai-approval");if(typeof $0?.balance==="number")x=$0.balance}catch{}return{ok:!i&&j===0,verdict:c,safeToPublish:U0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:F,estimatedRequired:M,balanceAfter:x},metrics:{sampleCount:D.length,successCount:T.length,failureCount:j,matchCount:C,flipCount:b,concordanceRate:Number(h.toFixed(4))},flips:B,records:D}}function _S0($){let{sourceCorp:Y,targetCorp:z,verdict:U,safeToPublish:Q,metrics:J,quota:I,flips:K,records:G}=$,W=U==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":U==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",H=["",`\uD83E\uDDEA[SealUseTest]规则回归测试矩阵:生产「${Y.name}」->测试靶场「${z.name}」`,`判定:${W}·准许发布:${Q?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),`样本总数:${J.sampleCount}|一致通过:${J.matchCount}|决策翻转:${J.flipCount}|异常失败:${J.failureCount}`,`一致率:${(J.concordanceRate*100).toFixed(1)}%|消耗预估:${I.estimatedRequired}点(余量:${I.balanceBefore}${I.balanceAfter!==void0?` -> ${I.balanceAfter}`:""})`," "+"─".repeat(65)];if(K.length>0){H.push(`⚠️决策翻转清单(${K.length}笔单据在新规则下结果改变):`);for(let X of K)if(H.push(`•单据[${X.sn}]:原生产判定「${X.prodDecision}」➔测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)H.push(`理由差异:${X.diff.reasonDiff}`);H.push(" "+"─".repeat(65)),H.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(U==="CLEAN")H.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% 吻合,无任
Line truncated
`)}var vS0=o(()=>{L$();X6();RZ()});async function Go($,Y,z){let U=($??Y??"regression").toLowerCase();if(U==="regression"||U==="regress"||U==="matrix"){let Q=S(z.options.corp)??(Y&&Y!==U?Y:void 0),J=E1(Q),I=J,K=J;if(J.environment==="test"){K=J;let O=S(z.options["prod-corp"])??S(z.options.prod)??J.prodCorpId;if(!O)throw new w4(`测试企业「${J.name}」(${J.id})未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-usecorpsbind-test<prodCorpId>${J.id}`);I=E1(O)}else{I=J;let O=S(z.options["test-corp"])??S(z.options.test)??J.testCorpId;if(!O)throw new w4(`生产企业「${J.name}」(${J.id})未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-usecorpsbind-test${J.id}<testCorpId>`);K=E1(O)}let G=await j1(I),W=await j1(K),H=s0(z.options.samples)??s0(z.options.limit)??s0(z.options.n)??10,X=F0(z.options["dry-run"]),Z=F0(z.options["fail-on-flips"]),q=s0(z.options["poll-interval"])??2000,V=s0(z.options.timeout)??45000,F=S(z.options["sn-prefix"])??"REG_",M=await RS0({sourceCorp:I,targetCorp:K,sourceClient:G,targetClient:W,samples:H,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:F,failOnFlips:Z});if(!(F0(z.options.quiet)||F0(z.options.silent)))console.error(_S0(M));if(c0(M),Z&&!M.ok)throw new w4(`回归测试发现${M.metrics.flipCount}笔单据决策翻转,已按--fail-on-flips策略非零终止。`,1);return}throw new w4(`未知的test子命令:"${U}"。
可用子命令:seal-usetestregression[--corp<id>][--samples<N>][--dry-run]`,2,"seal-use test regression --help")}var hS0=o(()=>{L$();o4();D4();J4();i8();vS0()});async function SS0($,Y,z,U){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await k0($,Y,z,y8(U.json),C0(U.options))}var gS0=o(()=>{o4();D4();J4()});function yS0(){c0(Hq.map(($)=>({name:$.name,description:$.description})))}var kS0=o(()=>{Zq();J4()});function kT($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let z=$.toLowerCase().replace(/\\/g,"/");return!z.endsWith("/bun")&&!z.endsWith("/bun.exe")&&!z.endsWith("/node")&&!z.endsWith("/node.exe")}var xS0=o(()=>{Dq()});import{chmodSync as sS1,mkdirSync as aS1,renameSync as Wo,rmSync as tS1,unlinkSync as cS0,writeFileSync as fS0}from"node:fs";import{dirname as eS1,join as uS0}from"node:path";import{spawnSync as gU}from"node:child_process";async function pS0($,Y={}){let z={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Qo,version:P1,launcher:$.launcher},U=Y.repo||process.env[$g1]?.trim()||process.env[Yg1]?.trim()||nS0,Q=Y.targetVersion?.trim(),J=Q&&Q.toLowerCase()!=="latest"?Q:void 0;if(J){let D=J.replace(/^v/,""),T=dS0(D,P1);if(T<0)if(!hS&&Y.force);else{c0({updated:!1,currentVersion:P1,targetVersion:D,mode:kT()?"binary":"source",message:!hS?`Cannotdowngradeseal-usefromdevbuildv${P1}toreleasev${D}.Use--forcetooverwrite.`:`Cannotdowngradeseal-usefromv${P1}toolderversionv${D}.Updatesmustbeforward-only.`});return}if(T===0&&!Y.force){c0({updated:!1,currentVersion:P1,targetVersion:D,mode:kT()?"binary":"source",message:`seal-useisalreadyatversionv${P1}.Use--forcetoreinstall.`});return}}if(Y.changelogOnly){let D=await Ho(U,Y.limit??10);c0({currentVersion:P1,totalQueried:D.length,releases:D.map((T)=>({version:T.version,tagName:T.tagName,publishedAt:T.publishedAt,author:T.author,releaseNotes:T.notes,releaseUrl:T.htmlUrl,isCurrent:T.version===P1,isNewer:Tq(T.version,P1)}))});return}if(!kT()){if(Y.checkOnly){let T=await Ho(U,30),A=T[0],B=A?.version??P1,j=T.find((k)=>k.version===P1),C=Tq(B,P1),b=T.filter((k)=>Tq(k.version,P1));c0({updated:!1,updateAvailable:C,currentVersion:P1,currentVersionPublishedAt:j?.publishedAt,latestVersion:B,latestVersionPublishedAt:A?.publishedAt,behindCount:b.length,pendingReleases:b.map((k)=>({version:k.version,tagName:k.tagName,publishedAt:k.publishedAt,author:k.author,releaseNotes:k.notes,releaseUrl:k.htmlUrl})),releaseNotes:A?.notes??"",releaseUrl:A?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let D=xK(z).running;if(D)await SU("stop",z);try{iS0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(T){console.error(`gitpullskipped:${TinstanceofError?T.message:String(T)}`)}if(iS0("bun",["install"],{cwd:$.appRoot}),D)await SU("start",z);c0({updated:!0,serviceRestarted:D,version:P1,mode:"source"});return}let I=zg1(),K=Ug1(),G=await Ho(U,30),W=J?G.find((D)=>D.version===J||D.tagName===J||D.tagName===`v${J}`)??await bS0(U,J):G[0]??await bS0(U);if(!W){c0({updated:!1,currentVersion:P1,mode:"binary",message:`Failedtoqueryreleasesfromrepository'${U}'`});return}let H=W.version,X=G.find((D)=>D.version===P1),Z=Tq(H,P1),q=Z||Boolean(Y.force),V=G.filter((D)=>Tq(D.version,P1));if(Y.checkOnly){c0({updated:!1,updateAvailable:Z,currentVersion:P1,currentVersionPublishedAt:X?.publishedAt,latestVersion:H,latestVersionPublishedAt:W.publishedAt,behindCount:V.length,pendingReleases:V.map((D)=>({version:D.version,tagName:D.tagName,publishedAt:D.publishedAt,author:D.author,releaseNotes:D.notes,releaseUrl:D.htmlUrl})),releaseNotes:W.notes,releaseUrl:W.htmlUrl,mode:"binary"});return}if(!q){c0({updated:!1,currentVersion:P1,currentVersionPublishedAt:X?.publishedAt,latestVersion:H,latestVersionPublishedAt:W.publishedAt,mode:"binary",message:`seal-useisalreadyuptodate(v${P1})`});return}let F=Qg1(W.assets,I,K);if(!F)throw Error(`Nocompatiblebinaryfoundfor${I}-${K}inreleasev${H}.Availableassets:${W.assets.map((D)=>D.name).join(", ")}`);let M=xK(z).running;if(M)await SU("stop",z);let w=process.execPath,O=eS1(w),N=uS0(O,`.tmp-update-${Date.now()}`);aS1(N,{recursive:!0});try{let D=uS0(N,F.name);await Jg1(F.downloadUrl,D,W.tagName,F.name);let T=D;if(F.name.endsWith(".tar.gz")||F.name.endsWith(".tgz"))T=Ig1(D,N,I);else if(F.name.endsWith(".zip"))T=Kg1(D,N,I);if(sS1(T,493),process.platform==="darwin")try{gU("/usr/bin/codesign",["--remove-signature",T],{stdio:"ignore"}),gU("/usr/bin/codesign",["--force","--sign","-",T],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let B=`${w}.old.${Date.now()}`;try{Wo(w,B)}catch{}Wo(T,w)}else Wo(T,w);if(M)await SU("start",z);let A=nl();c0({updated:!0,fromVersion:P1,toVersion:H,serviceRestarted:M,skillSynced:A.synced?A.targetDir:!1,mode:"binary"})}finally{try{tS1(N,{recursive:!0,force:!0})}catch{}}}function zg1(){if(process.platform==="darwin")return"darwin";if
Line truncated
`)}catch{}}async function Jg1($,Y,z,U){let Q=Xo(),J=[],I=z?z.startsWith("v")?z:`v${z}`:void 0,K=U||$.split("/").pop()||"";if(Q!=="github"){if(I&&K)J.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${I}/${K}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${I}/${K}`);if($.startsWith("https://git.ying-qing.cn"))J.push($)}if(Q!=="gitea")if(I&&K){let F=`https://github.com/${nS0}/releases/download/${I}/${K}`;if(!process.env.CI)J.push(`https://ghfast.top/${F}`,`https://gh.ddlc.top/${F}`);J.push(F)}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)),W,H=6000,X=6000,Z=307200,q=1e4,V=180000;for(let F=0;F<G.length;F++){let M=G[F],w=new AbortController,O="",N=(B)=>{O=B;try{w.abort()}catch{}},D=setTimeout(()=>{N("Connection timed out (no response headers within 6s)")},H),T,A;try{xT(`==> [${F+1}/${G.length}] Downloading via: ${M}`);let B=await fetch(M,{signal:w.signal});if(D)clearTimeout(D),D=void 0;if(!B.ok)throw Error(`HTTP ${B.status} ${B.statusText}`);T=setTimeout(()=>{N("Overall download time exceeded 3 minutes")},V);let j=Number(B.headers.get("content-length"))||0,C=B.body?.getReader();if(!C){let c=Buffer.from(await B.arrayBuffer());if(c.length<1000)throw Error(`Downloaded content is suspiciously small (${c.length} bytes)`);fS0(Y,c),xT(`✓ Download succeeded (${(c.length/1024/1024).toFixed(1)} MB)`);return}let b=[],k=0,h=0;A=setTimeout(()=>{if(k<Z){let c=(k/1024).toFixed(1);N(`Initial transfer too slow (${c} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let c=C.read(),U0,x=new Promise((g,p)=>{U0=setTimeout(()=>{p(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),d;try{d=await Promise.race([c,x])}finally{if(U0)clearTimeout(U0)}let{done:t,value:$0}=d;if(t)break;if($0){if(b.push($0),k+=$0.length,A&&k>=Z)clearTimeout(A),A=void 0;let g=Date.now();if(g-h>200){h=g;let p=j?Math.round(k/j*100):0,e=(k/1048576).toFixed(1),y=j?(j/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${p}% (${e} / ${y} MB)...`)}catch{}}}}try{process.stderr.write(`
"description":"Planned HTTP contract for the seal-use wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-use is responsible for enterprise\nselection,source authentication, response compaction, and diagnostics-friendly fields.\n"
"version":"0.10.25",
"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 enterpriseselection,\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":"Reserved for a future local HTTP adapter; the current service uses MCP stdio."
"description":"Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default."
}
],
"security":[
@@ -49,6 +49,7 @@
"Corps"
],
"operationId":"listCorps",
"x-implementation-status":"implemented",
"summary":"List configured enterprises",
"responses":{
"200":{
@@ -98,6 +99,7 @@
"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":{
@@ -145,6 +147,7 @@
"Corps"
],
"operationId":"switchCurrentCorp",
"x-implementation-status":"planned",
"summary":"Switch current enterprise",
"requestBody":{
"required":true,
@@ -223,6 +226,7 @@
"Source"
],
"operationId":"getSourceConfig",
"x-implementation-status":"planned",
"summary":"Resolve source-derived Seal enterprise config",
"summary":"Get current wrapped Seal session metadata",
"parameters":[
{
@@ -455,6 +462,7 @@
"Approval Knowledge"
],
"operationId":"getApprovalContext",
"x-implementation-status":"planned",
"summary":"Get rules, documents, and style preferences together",
"parameters":[
{
@@ -518,6 +526,7 @@
"Approval Knowledge"
],
"operationId":"searchApprovalKnowledge",
"x-implementation-status":"planned",
"summary":"Search approval rules, documents, and preferences",
"requestBody":{
"required":true,
@@ -583,6 +592,7 @@
"Approval Knowledge"
],
"operationId":"listApprovalRules",
"x-implementation-status":"implemented",
"summary":"List current draft approval rules",
"responses":{
"200":{
@@ -616,6 +626,7 @@
"Approval Knowledge"
],
"operationId":"createApprovalRule",
"x-implementation-status":"planned",
"summary":"Create draft approval rule",
"requestBody":{
"required":true,
@@ -708,6 +719,7 @@
"Approval Knowledge"
],
"operationId":"updateApprovalRule",
"x-implementation-status":"planned",
"summary":"Update draft approval rule",
"requestBody":{
"required":true,
@@ -783,6 +795,7 @@
"Approval Knowledge"
],
"operationId":"deleteApprovalRule",
"x-implementation-status":"planned",
"summary":"Delete draft approval rule",
"responses":{
"200":{
@@ -797,6 +810,7 @@
"Approval Knowledge"
],
"operationId":"listApprovalRuleVersions",
"x-implementation-status":"planned",
"summary":"List published approval rule versions",
"responses":{
"200":{
@@ -860,6 +874,7 @@
"Approval Knowledge"
],
"operationId":"getApprovalRuleVersion",
"x-implementation-status":"planned",
"summary":"Get published approval rule version",
"responses":{
"200":{
@@ -909,6 +924,7 @@
"Approval Knowledge"
],
"operationId":"getApprovalRuleByVersion",
"x-implementation-status":"planned",
"summary":"Get one wrapped rule from a published version",
"parameters":[
{
@@ -986,6 +1002,7 @@
"Approval Knowledge"
],
"operationId":"publishApprovalRuleVersion",
"x-implementation-status":"planned",
"summary":"Publish current draft rules",
"requestBody":{
"required":true,
@@ -1026,6 +1043,7 @@
"Approval Knowledge"
],
"operationId":"listApprovalDocuments",
"x-implementation-status":"planned",
"summary":"List approval knowledge documents",
"parameters":[
{
@@ -1092,6 +1110,7 @@
"Approval Knowledge"
],
"operationId":"createApprovalDocument",
"x-implementation-status":"planned",
"summary":"Create approval knowledge document",
"requestBody":{
"required":true,
@@ -1210,6 +1229,7 @@
"Approval Knowledge"
],
"operationId":"getApprovalDocument",
"x-implementation-status":"planned",
"summary":"Get approval knowledge document",
"responses":{
"200":{
@@ -1271,6 +1291,7 @@
"Approval Knowledge"
],
"operationId":"updateApprovalDocument",
"x-implementation-status":"planned",
"summary":"Update approval knowledge document",
"requestBody":{
"required":true,
@@ -1375,6 +1396,7 @@
"Approval Knowledge"
],
"operationId":"deleteApprovalDocument",
"x-implementation-status":"planned",
"summary":"Delete approval knowledge document",
"responses":{
"200":{
@@ -1389,6 +1411,7 @@
"Approval Knowledge"
],
"operationId":"getApprovalStylePreferences",
"x-implementation-status":"planned",
"summary":"Get approval style preferences",
"responses":{
"200":{
@@ -1438,6 +1461,7 @@
"Approval Knowledge"
],
"operationId":"updateApprovalStylePreferences",
"x-implementation-status":"planned",
"summary":"Update approval style preferences",
"requestBody":{
"required":true,
@@ -1523,12 +1547,165 @@
}
}
},
"/v1/preferences":{
"get":{
"tags":[
"Approval Knowledge"
],
"operationId":"getPreferences",
"x-implementation-status":"implemented",
"summary":"Get current decision, thinking-depth and rule-version preferences",
"parameters":[
{
"name":"corpId",
"in":"query",
"schema":{
"type":"string"
},
"description":"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
}
],
"responses":{
"200":{
"description":"Decision preferences, thinking depth preference and the bound rule set version.",
"content":{
"application/json":{
"schema":{
"type":"object",
"additionalProperties":true,
"properties":{
"tone":{
"type":"string"
},
"language":{
"type":"string"
},
"detailLevel":{
"type":"string"
},
"outputFormat":{
"type":"string"
},
"examples":{
"type":"array",
"items":{
"type":"string"
}
},
"prohibitedPhrases":{
"type":"array",
"items":{
"type":"string"
}
},
"customInstructions":{
"type":"string"
}
}
}
}
}
}
}
}
},
"/v1/preferences/decision":{
"post":{
"tags":[
"Approval Knowledge"
],
"operationId":"updatePreferenceDecision",
"x-implementation-status":"implemented",
"summary":"Update decision preferences (takes effect immediately for the running approval agent)",
"parameters":[
{
"name":"corpId",
"in":"query",
"schema":{
"type":"string"
},
"description":"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
}
],
"requestBody":{
"required":true,
"content":{
"application/json":{
"schema":{
"type":"object",
"properties":{
"explicitApprove":{
"type":"string"
},
"explicitReject":{
"type":"string"
},
"exemptApprove":{
"type":"string"
},
"review":{
"type":"string"
},
"dryRun":{
"type":"boolean",
"description":"Return the before/after diff without writing."
}
}
}
}
}
},
"responses":{
"200":{
"description":"Updated preferences, or the previewed diff when dryRun is set.",
"content":{
"application/json":{
"schema":{
"type":"object",
"additionalProperties":true,
"properties":{
"tone":{
"type":"string"
},
"language":{
"type":"string"
},
"detailLevel":{
"type":"string"
},
"outputFormat":{
"type":"string"
},
"examples":{
"type":"array",
"items":{
"type":"string"
}
},
"prohibitedPhrases":{
"type":"array",
"items":{
"type":"string"
}
},
"customInstructions":{
"type":"string"
}
}
}
}
}
}
}
}
},
"/v1/approval-runs":{
"get":{
"tags":[
"Approval Runs"
],
"operationId":"searchApprovalRuns",
"x-implementation-status":"implemented",
"summary":"Search wrapped approval run history",
"parameters":[
{
@@ -1690,6 +1867,7 @@
"Approval Runs"
],
"operationId":"summarizeApprovalRuns",
"x-implementation-status":"implemented",
"summary":"Summarize approval runs by local date",
"parameters":[
{
@@ -1780,12 +1958,88 @@
}
}
},
"/v1/approval-runs/stats":{
"get":{
"tags":[
"Approval Runs"
],
"operationId":"statApprovalRuns",
"x-implementation-status":"implemented",
"summary":"Aggregate approval run counts by status and source system",
"parameters":[
{
"name":"corpId",
"in":"query",
"schema":{
"type":"string"
},
"description":"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
},
{
"name":"since",
"in":"query",
"schema":{
"type":"string"
},
"description":"Time window such as 3months, 7days or 24hours."
},
{
"name":"dedupeBy",
"in":"query",
"schema":{
"type":"string",
"enum":[
"sourceDocumentSN",
"sourceDocumentId",
"id"
],
"default":"sourceDocumentSN"
},
"description":"Field used to count distinct business documents."
},
{
"name":"status",
"in":"query",
"schema":{
"type":"string"
}
},
{
"name":"sourceSystem",
"in":"query",
"schema":{
"type":"string"
}
},
{
"name":"taskMode",
"in":"query",
"schema":{
"type":"string"
}
}
],
"responses":{
"200":{
"description":"Counts grouped by status and source system, plus the deduplicated total.",
"content":{
"application/json":{
"schema":{
"type":"object"
}
}
}
}
}
}
},
"/v1/approval-runs/pick":{
"get":{
"tags":[
"Approval Runs"
],
"operationId":"pickApprovalRuns",
"x-implementation-status":"implemented",
"summary":"Pick likely approval runs by document number or trace key",
"parameters":[
{
@@ -1872,6 +2126,7 @@
"Approval Runs"
],
"operationId":"getApprovalRunLangfuseBridge",
"x-implementation-status":"planned",
"summary":"Resolve approval runs to Langfuse trace or session hints",
"parameters":[
{
@@ -1950,6 +2205,7 @@
"Approval Runs"
],
"operationId":"getApprovalRunUrl",
"x-implementation-status":"implemented",
"summary":"Get enterprise assist URL and optional source document URL",
"parameters":[
{
@@ -2031,6 +2287,7 @@
"Approval Runs"
],
"operationId":"getApprovalRun",
"x-implementation-status":"implemented",
"summary":"Get wrapped approval run detail",
"parameters":[
{
@@ -2081,6 +2338,7 @@
"Approval Runs"
],
"operationId":"getApprovalRunCitedRules",
"x-implementation-status":"implemented",
"summary":"Extract rules cited or matched by the AI result",
"responses":{
"200":{
@@ -2114,6 +2372,7 @@
"Approval Runs"
],
"operationId":"getApprovalRunDocumentSummary",
"x-implementation-status":"implemented",
"summary":"Get key document fields and compact AI/manual result",
"responses":{
"200":{
@@ -2147,6 +2406,7 @@
"Approval Runs"
],
"operationId":"getApprovalRunAttachments",
"x-implementation-status":"implemented",
"summary":"List compact attachment metadata",
"parameters":[
{
@@ -2189,6 +2449,7 @@
"Approval Runs"
],
"operationId":"getApprovalRunResult",
"x-implementation-status":"implemented",
"summary":"Get AI result, optionally as a compact summary",
"parameters":[
{
@@ -2220,6 +2481,7 @@
"Simulation"
],
"operationId":"createSimulationBatch",
"x-implementation-status":"implemented",
"summary":"Create a simulation batch",
"requestBody":{
"required":true,
@@ -2253,6 +2515,7 @@
"Simulation"
],
"operationId":"createMaterialPackBatch",
"x-implementation-status":"planned",
"summary":"Create a material pack simulation batch",
"requestBody":{
"required":true,
@@ -2286,6 +2549,7 @@
"Simulation"
],
"operationId":"listSimulationBatches",
"x-implementation-status":"implemented",
"summary":"List simulation batches",
"parameters":[
{
@@ -2332,6 +2596,7 @@
"Simulation"
],
"operationId":"getSimulationBatch",
"x-implementation-status":"implemented",
"summary":"Get a simulation batch detail including echoed create params",
"responses":{
"200":{
@@ -2365,6 +2630,7 @@
"Simulation"
],
"operationId":"getSimulationBatchRecords",
"x-implementation-status":"planned",
"summary":"Get wrapped simulation batch records",
"parameters":[
{
@@ -2397,6 +2663,7 @@
"Simulation"
],
"operationId":"listSimulationTemplates",
"x-implementation-status":"planned",
"summary":"List simulation test templates",
"responses":{
"200":{
@@ -2422,6 +2689,7 @@
"Simulation"
],
"operationId":"getSimulationIntegrationStatus",
"x-implementation-status":"planned",
"summary":"Get available source integration status for simulation",
"summary":"List hosecloud source integrations available for simulation",
"responses":{
"200":{
@@ -2469,6 +2738,7 @@
"Simulation"
],
"operationId":"uploadMaterialPackage",
"x-implementation-status":"planned",
"summary":"Upload a material package ZIP for simulation",
"requestBody":{
"required":true,
@@ -2508,7 +2778,7 @@
"type":"apiKey",
"in":"header",
"name":"X-Seal-Home-Session",
"description":"Optional local service session header for future HTTP deployments."
"description":"Reserved header. The local adapter does not currently authenticate requests: it acts with\nthe credentials already stored on this machine for the selected enterprise. Keep it bound\nto loopback (`--host 127.0.0.1`) and do not expose the port to a network or an origin you\ndo not control.\n"
description:Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.
description:"v0.10.23: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description:"v0.10.25: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version:0.10.23
short-description:Seal tenant and Hose approval automation (v0.10.23)
version:0.10.25
short-description:Seal tenant and Hose approval automation (v0.10.25)
---
# Seal Use (v0.10.23)
# Seal Use (v0.10.25)
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-use` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
**The CLI is the primary path; the MCP server is an optional extra that is off by default.** Prefer the global `seal-use` CLI, and only use MCP when it is actually available in the current session. If no `seal_cli*` tool is present, that is the normal default — do not try to enable it or treat it as a fault; just use the CLI. Enabling it is the user's choice in the plugin settings (插件配置中的「启用 MCP 服务」,默认关闭,打开后需重连该插件的 MCP 服务).
When MCP *is* available, two tools are exposed:
-`seal_cli` — **read-only only.** Reads tenant state without changing it. It is annotated `readOnlyHint: true`, so clients may auto-approve it.
-`seal_cli_write` — everything that mutates tenant state, publishes configuration, mints credentials, self-updates or starts a server. Annotated `destructiveHint: true`; **confirm the exact command with the user before calling it.**
The boundary is enforced, not merely advertised: `seal_cli` refuses any command that is not on its read-only allow-list, and unclassified commands fail closed. A refusal names `seal_cli_write` as the follow-up. `seal-use tool <name>` is allowed through `seal_cli` only for tools the registry classifies as read-only (`SEAL_READ_ONLY_TOOLS`); the rest need `seal_cli_write`.
This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
## Bootstrap & Installation (环境安装与自愈)
@@ -43,8 +52,9 @@ seal-use corps list
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
- Before asking for enterprise parameters, resolve the target enterprise: when an enterprise is named, hinted, or keyword-identifiable, ALWAYS run `seal-use corps search <keyword>` (or `seal-use corps get <corpId>` if an exact ID is known) — DO NOT dump the entire enterprise catalog with `seal-use corps list` when the target is already known. Only run `seal-use corps list` (or `corps list --env <test|production>`) for initial discovery when zero enterprise context is known. Resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`. Use `seal-use corps get <corpId>` to inspect rich enterprise attributes (URLs, tenant slugs, staff IDs, environment relations, and config file locations) with sensitive secrets safely redacted.
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read `references/enterprise-onboarding.md` before asking questions or running setup commands.
- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link <url> [--name ...]`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
-Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link <url> [--name ...]` for temporary session access, or elevate privileges to permanent developer credentials using `seal-use corps extract-keys <url> --save` (or `seal-use corps add-link <url> --as-hose`). This Hose-exclusive capability extracts `appKey`/`appSecurity`. If the enterprise has multiple keys, specify `--app-key <key>` or `--key-id <id>`.
-**同等凭据原则(Equal Credential Scope Principle)**: A Hose assistance link and a cURL copied from an authenticated **Hose admin** page are both Hose web frontend sessions — structurally different in format only, carrying the same `accesstoken`/`corpid` web session credentials. **When a Hose administrator provides a browser cURL, do NOT silently downgrade it to a plain short-lived session import.** Attempt privilege elevation first by extracting `accesstoken`+`corpid`+`baseUrl` from the cURL and invoking the Hose key interface (`/api/innerapi/v1/key`) to retrieve permanent `appKey`/`appSecurity`. Only fall back to temporary session import if the user is not a Hose administrator or the key interface returns no keys.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native. Calling key extraction or `keys` on native Seal enterprises is strictly blocked.
- Never ask a normal user for `corpId`, `staffId`, `proxyStaffBizId`, `tenantId`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
seal-use corps regression [--corp <corpId>][--samples <N>][--dry-run][--fail-on-flips]
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>][--overwrite]
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>][--as-hose][--app-key <key>][--key-id <id>][--overwrite]
seal-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal][--save][--name <customName>][--app-key <key>][--key-id <id>][--overwrite]
seal-use corps keys [<url> | <corpId>][--reveal][--save][--app-key <key>][--key-id <id>]
@@ -206,7 +210,10 @@ Enterprise and tenant management:
-`seal-use corps get <corpId>` (rich enterprise attributes with sensitive secrets safely redacted)
-`seal-use corps current [--corp <corpId>]`
-`seal-use corps switch <corpId>`
-`seal-use auth diagnose --corp <corpId>`
-`seal-use corps extract-keys <url> [--reveal] [--save] [--name <name>] [--app-key <key>] [--key-id <id>] [--overwrite]` extracts OpenAPI keys (`appKey` and `appSecurity`) from a Hose assistance link (`thirdparty.html`). **Hose Subdomain Privilege Elevation**: elevates a short-lived session token to permanent Hose OpenAPI developer credentials. If `--save` is specified, registers the enterprise as a durable Hose tenant. If the enterprise has multiple keys, execution halts and candidates are listed unless `--app-key` or `--key-id` is passed.
-`seal-use corps add-link <url> [--name <name>] [--as-hose] [--app-key <key>] [--key-id <id>] [--overwrite]` imports a Hose assistance link. Without `--as-hose`, creates a temporary Seal Bearer session. With `--as-hose`, elevates permissions by extracting Hose OpenAPI developer keys and saving a durable Hose enterprise configuration.
-`seal-use corps keys [<url> | <corpId>] [--reveal] [--save]` reads/displays OpenAPI keys for a Hose assistance link or configured Hose enterprise (masked by default, `--reveal` displays plaintext). Rejects non-Hose/native-Seal tenants with exit code 2.
-`seal-use auth extract-keys <url>` and `seal-use auth keys [--corp <corpId>]` provide auth-domain aliases for key extraction and inspection.
Read-only discovery:
@@ -611,11 +618,11 @@ When a push fails because of the attachment policy, the error is actionable and
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 MCP: read with `seal_webhook_get`/`seal_webhook_list`, update with `seal_webhook_update` and its `materialPackFilePolicy` patch, then retry `seal_webhook_material_pack` in `push` mode. For MCP, set `maxFileSizeBytes` to `null` to clear the upper bound. `allowedExtensions` is a complete replacement list, so include existing allowed suffixes when adding one.
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 MCP 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.
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.
@@ -34,13 +34,16 @@ All command examples in this reference are for the Agent to run. Do not hand the
Classify both the enterprise identity origin and how the current credential was acquired:
| Enterprise identity origin | Credential material the user may have | Meaning |
| --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |
| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |
| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |
| Enterprise identity origin | Credential material the user may have | 权限等级与时效 | Meaning |
| --- | --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | 【最高·永久】自动签名/续期 | Stable, refreshable standard integration; unlocks full OpenAPI and `corps sync-hosecloud`. |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link (`thirdparty.html`) | 【两极分化】普通导入→短效;提权→永久 | Temporary session that can be **elevated** to permanent `appKey`/`appSecurity` with `extract-keys --save` or `add-link --as-hose`. |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated **Hose admin** page | 【两极分化】普通导入→短效;提权→永久 | **Same session scope as an assistance link.** If the user is a Hose administrator, this carries the same web session credentials (`accesstoken`, `corpid`, cookies) and can equally invoke `/api/innerapi/v1/key` to extract permanent `appKey`/`appSecurity`. |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Seal page | 【短效会话快照】 | Snapshot with Seal Bearer token; can set up temporary Seal session access. |
| Seal-native tenant | Seal assistance/delegation link | 【临时·可撤销】 | Temporary delegated access to a Seal tenant. |
| Seal-native tenant | cURL copied from an authenticated Seal page | 【短效会话快照】 | Snapshot containing the Seal host and session authentication. |
**同等凭据原则(Equal Credential Scope Principle)**: A Hose assistance link and a browser cURL from an authenticated Hose admin session are both Hose web frontend sessions — they carry the same underlying `accessToken`/`accesstoken` and `corpid`. The **only** structural difference is delivery format. When a Hose administrator sends you a cURL, treat it with the same privilege elevation potential as an assistance link. Do not downgrade it to a plain Seal session import without first attempting key extraction.
Credential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.
Do not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.
First distinguish the link by its host and purpose:
First distinguish the link by its host, purpose, and identity origin:
- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.
-`seal-use auth hose-link` and `seal-use delegation create` generate links for an enterprise that is already configured. `seal-use corps add-link <url>` imports a received Hose/合思 `thirdparty.html` assistance link and verifies the resulting Seal tenant.
- A **Hose/合思 authorization/assistance link** (`https://<domain>/web/thirdparty.html?...`) opens an upstream Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A **Seal-native assistance/delegation link** grants temporary delegated access on a Seal tenant. It is not a Hose credential and cannot be elevated to Hose OpenAPI credentials.
-**Hose Subdomain Boundary (合思子域专属提权)**: `seal-use` primarily manages Seal tenants. Tenants sourced from the Hose ecosystem have an upstream Hose enterprise backing them. A received Hose assistance link contains only a temporary session `accessToken`. If you run standard `corps add-link`, it exchanges that temporary token for a short-lived Seal Bearer token—sufficient for basic Seal inspection, but it will expire and cannot call any Hose OpenAPI.
- **Privilege Elevation (权限等级提升)**: To elevate from a short-lived session token to permanent, durable Hose OpenAPI developer credentials, use `corps extract-keys <url> --save` or `corps add-link <url> --as-hose`. This leverages Hose's internal key interface (`GET /api/innerapi/v1/key`) using the session token to retrieve the enterprise's OpenAPI `appKey` and `appSecurity`. Once saved, the enterprise is upgraded to a standard Hose configuration with full OpenAPI support (e.g. `corps sync-hosecloud`).
- **Multi-Key Disambiguation (多套密钥明确抉择)**: If the enterprise owns multiple application keys, the CLI **will not** guess or silently pick the first key. Instead, it terminates with an informative candidate list and requires the user to specify `--app-key <key>` or `--key-id <id>`. If only one key exists, it is selected automatically.
- **Non-Hose Tenants Blocked**: Calling `keys` on native Seal enterprises (`corp.source.type !== "hose"`) is strictly rejected with exit code 2, explaining that this capability belongs exclusively to the Hose ecosystem.
Use the direct import route when the incoming link is an HTTPS `thirdparty.html` URL from a supported `ekuaibao.com` or `hosecloud.com` domain:
### Command Usage
```bash
seal-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home"[--name "企业名称"]
# 1. 提取密钥并脱敏查看(合思子域能力):
seal-use corps extract-keys "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..."
# 2. 显式完整查看密钥明文(--reveal / -r):
seal-use corps extract-keys "<url>" --reveal
# 3. 提权保存为标准持久化合思企业配置:
seal-use corps extract-keys "<url>" --save [--name "企业名称"][--overwrite]
# 或简写为:
seal-use corps add-link "<url>" --as-hose [--name "企业名称"]
# 4. 多套密钥存在时,显式指定具体应用密钥:
seal-use corps extract-keys "<url>" --save --app-key "ekb_app_..."
# 或按 key ID 选取:
seal-use corps extract-keys "<url>" --save --key-id "key_id_..."
# 5. 查看已配置合思企业当前使用的应用密钥:
seal-use corps keys <corpId> [--reveal]
seal-use auth keys --corp <corpId> [--reveal]
```
The command parses `accessToken` and `ekbCorpId`, exchanges the temporary Hose token at the target Seal tenant, verifies `/api/v1/auth/me`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use `--overwrite` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use `seal-use delegation create --from-link <url> [--note ...]`.
When using standard `add-link` (without `--as-hose`), it exchanges the temporary Hose token at the target Seal tenant, verifies `/api/v1/auth/me`, and stores only the normalized short-lived Seal session. When `--as-hose` or `extract-keys --save` is used, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration.
Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it.
@@ -103,21 +127,51 @@ When the user needs capture instructions, give these concrete steps:
6. Right-click it and choose **Copy → Copy as cURL**.
7. Send that complete cURL only to the local trusted Agent handling setup.
When receiving cURL:
When receiving cURL, immediately classify its origin before deciding on an action path:
### 3a. cURL from an authenticated Hose page (合思/易快报 后台)
This is functionally equivalent to a Hose assistance link. Both carry the same underlying web session credentials (`accesstoken`, `corpid`/`ekbCorpId`, and cookies). The structural difference is only in delivery format.
**Always attempt privilege elevation first when the session user is or may be a Hose administrator:**
1. Treat the entire cURL as a secret. Do not echo it, execute it blindly, paste it into another service, or store it in repository files.
2. Parse it as data. Extract the request host, path, `Authorization` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3.Classify whether the captured request is to Hose or Seal. A Seal request with `Authorization: Bearer ...` can supply `sealUrl` and a session token even when the user's identity origin is Hose.
4.Verify with the narrowest read-only identity endpoint available. For a Seal Bearer session, verify `/api/v1/auth/me` through `seal-use corps add-seal`; use returned provider metadata to retain the actual origin.
5.Persist only the normalized minimum configuration needed by seal-use. Do not preserve the raw cURL, unrelated headers, request body, cookies, or signed URL.
2. Extract: the request hostname (determines `baseUrl`), `accesstoken` header (session token), `corpid` header or cookie, and any other Hose session headers.
3.**Privilege elevation path (preferred)**: Use extracted `accesstoken`, `corpid`, and `baseUrl` to call `/api/innerapi/v1/key`, exactly as `corps extract-keys` does for assistance links. This retrieves permanent `appKey`/`appSecurity` to register a durable Hose enterprise configuration — do not skip this step just because the input is a cURL instead of a URL.
4.**Fallback short-term path**: If the session user is not an administrator and the key interface returns no keys, fall back to the Seal SSO bridge to register a temporary Seal session.
5.If key extraction succeeds, inform the user that credentials have been permanently elevated; if it fails, explain the limitation and suggest theadministrator copy a dedicated cURL or provide an assistance link or `appKey`/`appSecurity`.
For a verified Seal Bearer captured from cURL, the existing CLI route is:
### 3b. cURL from an authenticated Seal page (Seal 后台)
1. Treat the entire cURL as a secret.
2. Parse it as data. Extract the request host, path, `Authorization: Bearer ...` header, and provider/tenant hints.
3. Verify with `/api/v1/auth/me` through `seal-use corps add-seal`; use returned provider metadata to retain the actual origin.
4. Persist only the normalized minimum configuration needed by seal-use.
```bash
seal-use corps add-seal --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
```
The current CLI has no raw-cURL import command and `add-seal` requires a Bearer token. If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
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.