Compare commits

...
24 Commits
Author SHA1 Message Date
yunyingk f64f2b8385 Merge pull request #34 from yunyingk/codex/release-v0.10.7
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.7: Local rules workspace, daemon HTTP server, and global stop
2026-09-04 18:09:49 +08:00
gitea cba3098654 docs: document global stop command and shutdown route in changelog 2026-09-04 18:08:13 +08:00
gitea f9b8b06647 Add global seal-use stop command and shutdown HTTP route 2026-09-04 17:58:30 +08:00
gitea 37580dac44 Release v0.10.7: Local rules workspace and daemon HTTP server 2026-09-04 17:54:47 +08:00
gitea f183cc8294 Add persistent HTTP server to background service daemon 2026-09-04 17:53:40 +08:00
gitea 13ed555bbb Add local approval rules workspace and offline linting 2026-09-04 17:45:46 +08:00
yunyingk 39bbf4d7c0 Merge pull request #33 from yunyingk/codex/release-v0.10.6
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.6: Webhook material pack import
2026-09-03 15:32:08 +08:00
gitea 64819d86cb Release v0.10.6: Webhook material pack import 2026-09-03 15:30:43 +08:00
yunyingk 4b1833409e Merge pull request #32 from yunyingk/codex/issue-27-webhook-material-pack
Add Webhook material pack import
2026-09-03 15:27:44 +08:00
gitea 77ae7d4dca Add Webhook material pack import 2026-09-03 15:26:43 +08:00
yunyingk 1299d70777 Merge pull request #31 from yunyingk/codex/release-v0.10.5
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.5: Intelligent HoseCloud sync discovery, actionable guidance, and --auto support (Fixes #26)
2026-09-03 11:42:54 +08:00
gitea 0a3c984018 Release v0.10.5: Intelligent HoseCloud sync discovery, actionable guidance, and --auto support (Fixes #26) 2026-09-03 11:41:56 +08:00
yunyingk 923184e623 Merge pull request #29 from yunyingk/codex/release-v0.10.4
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.4: Built-in rule linter, dynamic TS plugin loader with fault-tolerant fallback, and default-disabled global config
2026-09-03 11:31:50 +08:00
gitea 1cf35dfd78 Release v0.10.4: Built-in rule linter, dynamic TS plugin loader with fault-tolerant fallback, and default-disabled global config 2026-09-03 11:30:52 +08:00
yunyingk cdab1e2009 Merge pull request #25 from yunyingk/codex/release-v0.10.3
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.3: Hose deployment auto platform probing, alias support, multi-target routing, and stderr next-step guidance
2026-09-02 18:19:48 +08:00
gitea 3e06c0f266 Release v0.10.3: Auto platform probing for Hose deployment, alias support, multi-target routing, and stderr next-step guidance 2026-09-02 18:18:54 +08:00
yunyingk f31afd2d92 Merge pull request #24 from yunyingk/codex/update-gitea-repo-in-workflow
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
ci(release): update GITEA_REPO to gitea/seal-use
2026-09-02 16:41:17 +08:00
gitea e3e49d729e ci(release): update GITEA_REPO to gitea/seal-use 2026-09-02 16:40:25 +08:00
yunyingk 8166ec7d3d Merge pull request #23 from yunyingk/codex/release-v0.10.2
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.2: add agent self-bootstrap guide to SKILL.md and CI mirror isolation
2026-09-02 16:36:58 +08:00
gitea afa039142f Release v0.10.2: add agent self-bootstrap guide to SKILL.md and CI mirror isolation 2026-09-02 16:36:17 +08:00
yunyingk 3c30210bcd Merge pull request #22 from yunyingk/codex/skill-install-instructions
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
docs(skill): add explicit bootstrap & installation guide to SKILL.md
2026-09-02 16:35:49 +08:00
gitea 79e17513ee docs(skill): add explicit bootstrap & installation guide to SKILL.md 2026-09-02 16:35:00 +08:00
yunyingk 46c85181a3 Merge pull request #21 from yunyingk/codex/ci-bypass-gitea-mirror
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
feat(update): block gitea in CI and support SEAL_USE_MIRROR routing
2026-09-02 16:33:00 +08:00
gitea df8c8c8280 feat(update): block gitea in CI and support SEAL_USE_MIRROR routing 2026-09-02 16:32:19 +08:00
51 changed files with 3217 additions and 714 deletions

No files matched your search

+1 -1
View File
@@ -101,7 +101,7 @@ jobs:
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_HOST: "https://git.ying-qing.cn"
GITEA_REPO: "gitea/seal-home"
GITEA_REPO: "gitea/seal-use"
run: |
if [ -z "$GITEA_TOKEN" ]; then
echo "::notice::GITEA_TOKEN secret not configured, skipping Gitea upload."
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.1",
"version": "0.10.7",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+10 -1
View File
@@ -26,7 +26,16 @@ Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in
Use TypeScript ES modules with explicit `.js` import extensions for local files. Validate external data with Zod or narrow types before use. Follow existing style: two-space indentation, double quotes, omitted trailing semicolons, `camelCase` variables/functions, `PascalCase` classes/types, and lowercase hyphenated filenames such as `token-store.ts`.
Prefer small domain functions over broad utility modules. Keep CLI output JSON on stdout and diagnostics/errors on stderr.
Prefer small domain functions over broad utility modules.
## CLI & Agent Harness Protocol Guidelines
- **Machine Channel (`stdout`)**: CLI commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
- **Guidance & Diagnostic Channel (`stderr`)**: Use `stderr` for runtime logs, network probing status, self-healing notifications, and explicit **Next-Step Command Suggestions** (e.g. `👉 Next action: seal-use deploy hosecloud sync <signKey>`).
- **Exit Code Contract**:
- Successful executions MUST terminate with exit code `0`.
- Any parameter validation failure, upstream API error, or business block MUST result in a non-zero exit code (e.g. `1`), allowing the Agent Harness to reliably detect failures and trigger automated error remediation.
- Never call `process.exit()` deep in domain functions; throw structured errors and let `src/cli/runner.ts` handle stream routing and exit code assignment.
## Testing Guidelines
+53
View File
@@ -5,6 +5,59 @@ All notable changes to `seal-use` will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.10.7] - 2026-09-04
### Added & Enhanced
- **Local Approval Rules Workspace & Offline Linting**:
- Added `seal-use rules pull` (`seal_approval_rules_pull`) to export remote draft or published version rules to a local JSON file (defaults to `./rules.local.json`), eliminating unwanted mutations to remote drafts.
- Added `seal-use rules lint --file <path>` to execute rule quality and execution checks completely offline with zero network requests and zero dirty version records in the remote backend. Supports quality score gates (`--min-score`) and operates seamlessly even without configured enterprise credentials.
- Added `seal-use rules push` (`seal_approval_rules_push`) to apply refined local rules to the remote draft with preview (`--dry-run`), confirmation (`--yes`), and optional single-step formal release publishing (`--publish`).
- **Persistent HTTP Companion Daemon in Background Service**:
- Embedded the HTTP API server into `seal-use service run`, allowing `seal-use service start` to run as a detached background daemon with persistent HTTP service (serving `/docs`, `/openapi.json`, and `POST /api/cli`).
- Added `seal-use service logs` (`--lines <N>`) to easily inspect service background activity.
- Enhanced `seal-use service status` to track active host, port, and URL via daemon metadata state.
- Optimized `parseJsonBody` and CLI runner concurrency with standing command bypasses to prevent process queue blocks.
- Added top-level `seal-use stop` command, intuitive service aliases (`seal-use service kill|down|shutdown`), and `POST /shutdown` HTTP endpoint to gracefully terminate the background daemon from any terminal or script.
## [0.10.6] - 2026-09-03
### Added & Enhanced
- **Inbound Webhook Material Pack Import (Issue #27)**: Added local preview and push workflows for SealAI material packs, including strict ZIP/XLSX validation, normalized approval-document parsing, attachment upload, and HMAC-signed Webhook delivery.
- **CLI and MCP Support**: Added `seal-use webhook material-pack preview|push` and the `seal_webhook_material_pack` tool, while keeping the existing simulation `material_pack` flow separate.
- **Test-Enterprise Verification**: Verified the new push path against the configured test enterprise with official sample materials; customer enterprise data was not used.
## [0.10.5] - 2026-09-03
### Added & Enhanced
- **Intelligent HoseCloud Sync Discovery & Actionable Guidance (Issue #26)**: In `seal-use deploy hosecloud sync` and `deploy hosecloud get`, when `<sign-key>` is omitted, the CLI dynamically discovers all active HoseCloud integration configs for the tenant and renders structured cards on `stderr` with 1-click copy commands (e.g. `👉 同步命令: seal-use deploy hosecloud sync <signKey> --corp <corpId>`).
- **Single-Config Fast Track (`--auto`)**: Added `--auto` (and `--yes`) flag to `deploy hosecloud sync`. When a tenant has exactly one configured HoseCloud integration, `--auto` automatically locks and syncs without requiring manual `signKey` extraction.
- **Enhanced Empty State & Diagnostic Hints**: If a tenant has zero HoseCloud integrations configured, clearly prompts the user with next-step configuration command `seal-use deploy hosecloud configure ...`.
- **Updated Reference Documentation**: Updated `skills/seal-use/references/hose-enterprise-deploy.md` and CLI references with `--auto` and dynamic discovery patterns.
## [0.10.4] - 2026-09-03
### Added & Enhanced
- **Built-in Approval Rule Linter & Quality Validation Engine**: Introduced a pure TypeScript/heuristic rule quality validator (`seal-use rules lint` & `seal_approval_rules_lint`). Detects subjective fuzzy words (`原则上`, `尽量`, `适当`, `酌情`), hanging exception clauses lacking evidence keywords (`除非/特殊情况` 未指明 `备注/附件/截图` 凭证来源), and short invalid descriptions.
- **Plugin-as-Code Dynamic TS Linter Loader**: Supports loading custom enterprise TypeScript linter plugins dynamically from `~/.config/seal-use/linters/*.ts` or explicit paths (`--linter <name|path>`).
- **Fault-Tolerant Automatic Fallback (Anti-Crash Guarantee)**: If a user's custom `.ts` linter file contains syntax errors, throws runtime exceptions, or is missing, the engine automatically catches errors, logs diagnostic warnings to `stderr`, and seamlessly falls back to the built-in heuristic linter without failing or blocking CLI execution.
- **Global Config & Default-Disabled Policy**: Added `lint: { enabled: false, activeLinter: "builtin", minScore: 0 }` to global configuration (`~/.config/seal-use/config.json`). Linter is **disabled by default** to avoid unsolicited noise; can be enabled via `seal-use config lint enable`.
- **Real-time Diagnostic Hook on Rule Updates**: When linting is enabled, `seal_approval_rule_update` automatically inspects modified descriptions and outputs structured warnings on `stderr` while keeping clean machine JSON on `stdout`.
- **Comprehensive Scenarios & Gatekeeping**: `seal-use rules lint` supports full draft scanning, historical version review (`--version <num>`), rule filtering (`--code <code>`), summary mode (`--summary`), and quality gate scoring (`--min-score <score>`) with non-zero exit codes.
- **Dedicated Reference Documentation**: Added `skills/seal-use/references/rule-lint.md` and updated SKILL router.
## [0.10.3] - 2026-09-02
### Added & Enhanced
- **Auto Platform Probing for HoseCloud Deployment**: In `deploy hosecloud configure` (`seal_deploy_hosecloud_configure`), automatically probes 6 standard Hose SaaS platform domains (Standard, DingTalk, WeChat Work, Feishu, CloudHub, DingTalk Enterprise) using `probeHoseDomain` when `customApiUrl` is omitted. Eliminates manual platform guessing and prevents authentication failures (`请检查 API 平台和凭证配置是否正确`).
- **Standardized Business Terminology**: Aligned all CLI and tool descriptions with Seal AI product semantics: `Seal AI 智能审核发布到合思费控` (replacing raw backend jargon like "合思出站消息").
- **Dedicated Reference Documentation**: Added `skills/seal-use/references/hose-enterprise-deploy.md` covering end-to-end deployment, auto platform detection, 3-step publishing, and EBot node integration.
## [0.10.2] - 2026-09-02
### Added & Enhanced
- **Agent Skill Self-Bootstrap & Auto-Installation**: Embedded direct 1-line installation scripts into `skills/seal-use/SKILL.md` and onboarding references. Third-party AI Agents can now automatically self-install and bootstrap `seal-use` when missing without human intervention.
- **CI / Mirror Routing Isolation**: Added intelligent mirror mode resolver (`SEAL_USE_MIRROR=github|gitea|auto`). Automatically bypasses Gitea in CI environments to ensure 100% offline, deterministic, and fast (<20s) test execution.
## [0.10.1] - 2026-09-02
### Changed & Infrastructure
+198 -1
View File
@@ -5,11 +5,16 @@
"": {
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.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/bun": "^1.3.14",
"@types/yauzl": "^3.4.0",
"bun-types": "^1.3.14",
"typescript": "^5.9.3",
"yaml": "^2.9.0",
@@ -17,6 +22,10 @@
},
},
"packages": {
"@fast-csv/format": ["@fast-csv/format@4.3.5", "", { "dependencies": { "@types/node": "^14.0.1", "lodash.escaperegexp": "^4.1.2", "lodash.isboolean": "^3.0.3", "lodash.isequal": "^4.5.0", "lodash.isfunction": "^3.0.9", "lodash.isnil": "^4.0.0" } }, "sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A=="],
"@fast-csv/parse": ["@fast-csv/parse@4.3.6", "", { "dependencies": { "@types/node": "^14.0.1", "lodash.escaperegexp": "^4.1.2", "lodash.groupby": "^4.6.0", "lodash.isfunction": "^3.0.9", "lodash.isnil": "^4.0.0", "lodash.isundefined": "^3.0.1", "lodash.uniq": "^4.5.0" } }, "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA=="],
"@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
@@ -25,14 +34,44 @@
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
"ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
"archiver": ["archiver@5.3.2", "", { "dependencies": { "archiver-utils": "^2.1.0", "async": "^3.2.4", "buffer-crc32": "^0.2.1", "readable-stream": "^3.6.0", "readdir-glob": "^1.1.2", "tar-stream": "^2.2.0", "zip-stream": "^4.1.0" } }, "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw=="],
"archiver-utils": ["archiver-utils@2.1.0", "", { "dependencies": { "glob": "^7.1.4", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^2.0.0" } }, "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw=="],
"async": ["async@3.2.6", "", {}, "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA=="],
"balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"big-integer": ["big-integer@1.6.52", "", {}, "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg=="],
"binary": ["binary@0.3.0", "", { "dependencies": { "buffers": "~0.1.1", "chainsaw": "~0.1.0" } }, "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg=="],
"bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
"bluebird": ["bluebird@3.4.7", "", {}, "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA=="],
"body-parser": ["body-parser@2.2.2", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="],
"buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
"buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"buffer-indexof-polyfill": ["buffer-indexof-polyfill@1.0.2", "", {}, "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A=="],
"buffers": ["buffers@0.1.1", "", {}, "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
@@ -41,6 +80,12 @@
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
"chainsaw": ["chainsaw@0.1.0", "", { "dependencies": { "traverse": ">=0.3.0 <0.4" } }, "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ=="],
"compress-commons": ["compress-commons@4.1.2", "", { "dependencies": { "buffer-crc32": "^0.2.13", "crc32-stream": "^4.0.2", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg=="],
"concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
"content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
"content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
@@ -49,20 +94,32 @@
"cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
"core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="],
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"crc-32": ["crc-32@1.2.2", "", { "bin": { "crc32": "bin/crc32.njs" } }, "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ=="],
"crc32-stream": ["crc32-stream@4.0.3", "", { "dependencies": { "crc-32": "^1.2.0", "readable-stream": "^3.4.0" } }, "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"dayjs": ["dayjs@1.11.23", "", {}, "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"duplexer2": ["duplexer2@0.1.4", "", { "dependencies": { "readable-stream": "^2.0.2" } }, "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA=="],
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
"es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
@@ -77,10 +134,14 @@
"eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
"exceljs": ["exceljs@4.4.0", "", { "dependencies": { "archiver": "^5.0.0", "dayjs": "^1.8.34", "fast-csv": "^4.3.1", "jszip": "^3.10.1", "readable-stream": "^3.6.0", "saxes": "^5.0.1", "tmp": "^0.2.0", "unzipper": "^0.10.11", "uuid": "^8.3.0" } }, "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg=="],
"express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
"express-rate-limit": ["express-rate-limit@8.5.2", "", { "dependencies": { "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A=="],
"fast-csv": ["fast-csv@4.3.6", "", { "dependencies": { "@fast-csv/format": "4.3.5", "@fast-csv/parse": "4.3.6" } }, "sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-uri": ["fast-uri@3.1.2", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],
@@ -91,14 +152,24 @@
"fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
"fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fs.realpath": ["fs.realpath@1.0.0", "", {}, "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="],
"fstream": ["fstream@1.0.12", "", { "dependencies": { "graceful-fs": "^4.1.2", "inherits": "~2.0.0", "mkdirp": ">=0.5 0", "rimraf": "2" } }, "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="],
"gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
"graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
"hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
@@ -107,7 +178,13 @@
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="],
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"immediate": ["immediate@3.0.6", "", {}, "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="],
"inflight": ["inflight@1.0.6", "", { "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA=="],
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
@@ -117,6 +194,8 @@
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
"isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],
@@ -125,8 +204,42 @@
"json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
"jszip": ["jszip@3.10.1", "", { "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", "readable-stream": "~2.3.6", "setimmediate": "^1.0.5" } }, "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g=="],
"ky": ["ky@2.0.2", "", {}, "sha512-/GmXpo9F9W+f8n4Ivr2iH+7h7wL7jLbLKWkMlpflcCRb6kGjBfTlASEXaZ9qUgNTn4VgS0P2pwxxzQ4EM6Ulgg=="],
"lazystream": ["lazystream@1.0.1", "", { "dependencies": { "readable-stream": "^2.0.5" } }, "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw=="],
"lie": ["lie@3.3.0", "", { "dependencies": { "immediate": "~3.0.5" } }, "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ=="],
"listenercount": ["listenercount@1.0.1", "", {}, "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ=="],
"lodash.defaults": ["lodash.defaults@4.2.0", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="],
"lodash.difference": ["lodash.difference@4.5.0", "", {}, "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA=="],
"lodash.escaperegexp": ["lodash.escaperegexp@4.1.2", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="],
"lodash.flatten": ["lodash.flatten@4.4.0", "", {}, "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g=="],
"lodash.groupby": ["lodash.groupby@4.6.0", "", {}, "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw=="],
"lodash.isboolean": ["lodash.isboolean@3.0.3", "", {}, "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="],
"lodash.isequal": ["lodash.isequal@4.5.0", "", {}, "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ=="],
"lodash.isfunction": ["lodash.isfunction@3.0.9", "", {}, "sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw=="],
"lodash.isnil": ["lodash.isnil@4.0.0", "", {}, "sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng=="],
"lodash.isplainobject": ["lodash.isplainobject@4.0.6", "", {}, "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="],
"lodash.isundefined": ["lodash.isundefined@3.0.1", "", {}, "sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA=="],
"lodash.union": ["lodash.union@4.6.0", "", {}, "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw=="],
"lodash.uniq": ["lodash.uniq@4.5.0", "", {}, "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ=="],
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
@@ -137,10 +250,16 @@
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],
"mkdirp": ["mkdirp@3.0.1", "", { "bin": { "mkdirp": "dist/cjs/src/bin.js" } }, "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
"normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
@@ -149,14 +268,24 @@
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"pako": ["pako@1.0.11", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="],
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-is-absolute": ["path-is-absolute@1.0.1", "", {}, "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],
"pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
"pinyin-pro": ["pinyin-pro@3.29.3", "", {}, "sha512-+UU9bx6vfDw8amOJGHm0TE0rdQl8VPylsDWviQ5OOQ3e+on1xRP4OqDbiDuMT5OISgvfl/Y6ez1BBRaIP80GLQ=="],
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"qs": ["qs@6.15.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],
@@ -165,16 +294,28 @@
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
"readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"readdir-glob": ["readdir-glob@1.1.3", "", { "dependencies": { "minimatch": "^5.1.0" } }, "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"rimraf": ["rimraf@2.7.1", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "./bin.js" } }, "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w=="],
"router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
"safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"saxes": ["saxes@5.0.1", "", { "dependencies": { "xmlchars": "^2.2.0" } }, "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw=="],
"send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
"serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
"setimmediate": ["setimmediate@1.0.5", "", {}, "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA=="],
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
@@ -191,8 +332,16 @@
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
"tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"traverse": ["traverse@0.3.9", "", {}, "sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ=="],
"type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
@@ -201,18 +350,66 @@
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"unzipper": ["unzipper@0.10.14", "", { "dependencies": { "big-integer": "^1.6.17", "binary": "~0.3.0", "bluebird": "~3.4.1", "buffer-indexof-polyfill": "~1.0.0", "duplexer2": "~0.1.4", "fstream": "^1.0.12", "graceful-fs": "^4.2.2", "listenercount": "~1.0.1", "readable-stream": "~2.3.6", "setimmediate": "~1.0.4" } }, "sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g=="],
"util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="],
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"xmlchars": ["xmlchars@2.2.0", "", {}, "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"yauzl": ["yauzl@3.4.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw=="],
"zip-stream": ["zip-stream@4.1.1", "", { "dependencies": { "archiver-utils": "^3.0.4", "compress-commons": "^4.1.2", "readable-stream": "^3.6.0" } }, "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
"@fast-csv/format/@types/node": ["@types/node@14.18.63", "", {}, "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ=="],
"@fast-csv/parse/@types/node": ["@types/node@14.18.63", "", {}, "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ=="],
"archiver-utils/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"body-parser/iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"duplexer2/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"glob/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
"jszip/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"lazystream/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"raw-body/iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"string_decoder/safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
"unzipper/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"zip-stream/archiver-utils": ["archiver-utils@3.0.4", "", { "dependencies": { "glob": "^7.2.3", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw=="],
"archiver-utils/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"duplexer2/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"glob/minimatch/brace-expansion": ["brace-expansion@1.1.18", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
"jszip/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"lazystream/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"unzipper/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
}
}
+354 -569
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "seal-use Wrapped API",
"version": "0.10.1",
"version": "0.10.7",
"description": "Planned HTTP contract for the seal-use wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-use is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: seal-use Wrapped API
version: 0.10.1
version: 0.10.7
description: |
Planned HTTP contract for the seal-use wrapped backend API.
+6 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.1",
"version": "0.10.7",
"type": "module",
"module": "src/server.ts",
"bin": {
@@ -22,11 +22,16 @@
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.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/bun": "^1.3.14",
"@types/yauzl": "^3.4.0",
"bun-types": "^1.3.14",
"typescript": "^5.9.3",
"yaml": "^2.9.0"
+24 -7
View File
@@ -1,19 +1,31 @@
---
name: seal-use
description: "v0.10.1: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.10.7: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.10.1
short-description: Seal tenant and Hose approval automation (v0.10.1)
version: 0.10.7
short-description: Seal tenant and Hose approval automation (v0.10.7)
---
# Seal Use (v0.10.1)
# Seal Use (v0.10.7)
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-use` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
## Bootstrap & Installation (环境安装与自愈)
If `seal-use` or `seal_cli` is not installed on the system, the Agent should automatically install it via:
```bash
# 国内高速安装(Gitea 镜像源,免代理、秒级完成)
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
# Global / GitHub Direct
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
```
After installation, verify with:
```bash
seal-use help
seal-use version
seal-use tools list
seal-use corps list
```
## First Rules
@@ -44,7 +56,7 @@ seal-use tools list
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp <corpId> --note '<enterprise>'`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
- Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
- HoseCloud 部署与同步发布: `seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>`.
- Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>`; read `references/hose-enterprise-deploy.md`.
- 审核决策偏好与思考深度: `seal-use preference get --corp <corpId>`, `preference decision update --json '...' --corp <corpId>`, `preference thinking-depth set --default <medium|high> --corp <corpId>`, `preference thinking-depth policies <list|upsert|remove> --corp <corpId>`.
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>`, `seal-use approval-runs count --corp <corpId>`.
- User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp <corpId> --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
@@ -54,7 +66,9 @@ seal-use tools list
- System Permissions Config: `seal-use permissions available --corp <corpId>`, `seal-use permissions configs --corp <corpId>`.
- Billing & Feature Quotas: `seal-use billing status --corp <corpId>`, `seal-use billing plans --corp <corpId>`, `seal-use billing features --corp <corpId>`.
- Webhook 审批回调管理: `seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
- Webhook 材料包导入: `seal-use webhook material-pack preview <材料包.zip> --corp <corpId>` 只做本地校验和解析;`... push <材料包.zip> --webhook <idOrName> --corp <corpId>` 上传附件并通过入站 Webhook 触发 AI 审批。它与 `simulation material_pack` 的官方服务端导入流程相互独立。
- HTTP REST API & Docs Server: `seal-use http [--port 8787] [--host 127.0.0.1]` (提供 `/docs` 交互文档、`/openapi.json`、`POST /api/cli` 与 `/v1/*` REST API)。
- 审批规则质量校验 (Linter): `seal-use rules lint [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary] --corp <corpId>`; read `references/rule-lint.md`. 全局配置默认关闭 (`config lint <enable|disable>`)。
- Full CLI inventory: read `references/cli.md`.
## High-Value Commands
@@ -70,6 +84,7 @@ seal-use approval-runs attachments <recordId> --corp <corpId> --summary
seal-use approval-runs result <recordId> --corp <corpId> --summary
seal-use rules count --corp <corpId>
seal-use rules list --corp <corpId> --summary
seal-use rules lint --corp <corpId> --summary
seal-use rules clear --corp <corpId> --dry-run
seal-use rules clear --corp <corpId> --yes
seal-use rules get --corp <corpId> --version 16 --code '#0038'
@@ -100,9 +115,11 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
- `references/enterprise-onboarding.md`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- `references/approval-run-lightweight.md`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- `references/rule-lightweight.md`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- `references/rule-lint.md`: 规则质量检查器(Linter)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
- `references/customer-feedback-rule-remediation.md`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- `references/hose-enterprise-auth.md`: Hose 企业配置、认证诊断、授权链接。
- `references/hose-enterprise-init.md`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
- `references/hose-enterprise-deploy.md`: Seal AI 智能审核发布到合思费控(添加/编辑配置、平台自动探测、一键同步与 EBot 节点发布)。
- `references/approval-attachment-trace.md`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。
- `references/cli.md`: 完整 CLI 命令清单。
+22 -4
View File
@@ -24,6 +24,12 @@ seal-use config mode stateless
The global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to
override that path. The legacy `current-corp` file is not read.
## Stream & Exit Code Contract
- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.
- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).
- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.
## Top-Level Commands
```bash
@@ -31,7 +37,11 @@ seal-use version
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use service <start|stop|restart|status>
seal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]
seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]
seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]
seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]
seal-use service <start|stop|restart|status|logs> [--port 8787] [--host 127.0.0.1] [--lines 50]
seal-use http [--port 8787] [--host 127.0.0.1]
seal-use serve [--port 8787]
seal-use update
@@ -65,10 +75,10 @@ seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
seal-use deploy hosecloud get [<sign-key>] [--corp <corpId>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]
seal-use preference get [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]
@@ -113,7 +123,7 @@ seal-use simulation package-upload <材料包.zip> --corp <corpId>
}
```
`seal-use service status` returns the PID, version, state directory, PID file, and log file for the optional local background process.
`seal-use service <start|stop|restart|status|logs>` manages the persistent background service daemon with embedded HTTP server (serving `/docs`, `/openapi.json`, and `POST /api/cli`). `status` returns the PID, version, host, port, active HTTP URL, state directory, PID file, and log file.
`seal-use update` updates the git checkout, runs `bun install`, and restarts the local service if it was running.
@@ -127,8 +137,14 @@ Approval rule maintenance:
- `seal-use rules count [--corp <corpId>]`
- `seal-use rules list --summary [--corp <corpId>]`
- `seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]`
- `seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]`
- `seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]`
- `seal-use rules clear [--corp <corpId>] [--dry-run|--yes]`
- `seal_approval_rules_list`
- `seal_approval_rules_pull`
- `seal_approval_rules_push`
- `seal_approval_rules_lint`
- `seal_approval_rules_clear`
- `seal_approval_rule_create`
- `seal_approval_rule_update`
@@ -179,6 +195,8 @@ Webhook integrations:
- `seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]`
- `seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]`
- `seal-use webhook delete <idOrName> --yes [--corp <corpId>]`
- `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> --corp <corpId>`
- `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> --webhook <idOrName> --corp <corpId>`
- `seal_webhook_list`
- `seal_webhook_get`
- `seal_webhook_add`
@@ -4,13 +4,14 @@ Read this reference for first installation, zero configured enterprises, incomin
## Start With Discovery
Run this before asking for setup parameters:
Run this before asking for setup parameters (if `seal-use` is not installed, first run `curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash`):
```bash
seal-use version
seal-use corps list
```
- If `seal-use` is not installed on the system, run the curl install script above to install it.
- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.
- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.
- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”
@@ -0,0 +1,98 @@
# Seal AI 智能审核发布到合思费控 (HoseCloud Deployment)
Use this reference when configuring, deploying, or troubleshooting Seal AI smart approval integrations with Hose/合思费控 (界面路径:【智能审核】 $\to$ 【发布】 $\to$ 【合思费控】).
---
## 1. 业务全景与产品心智
将 Seal AI 智能审核能力应用到合思费控的审批流中包含 3 个核心步骤:
```mermaid
flowchart LR
S1["01 添加/编辑配置<br/>(API 凭证 + 模式 + 自动探测)"] --> S2["02 同步到合思<br/>(自动在合思创建出站配置)"]
S2 --> S3["03 添加 EBot 节点<br/>(在合思审批流中插入 AI 审核)"]
```
1. **01 添加配置**:填写合思开放平台的 `appKey` 与 `appSecurity`,设置审核模式(辅助、半自动、全自动)与策略。
2. **02 同步到合思**:一键将配置推送到合思开放平台,自动生成对应的出站消息配置。
3. **03 添加 EBot 节点**:在合思审批流编辑器中,在需要 AI 审核的位置添加“EBot”节点,选择同步生成的出站消息名称即可。
---
## 2. 合思平台/环境自动探测机制 (Auto Platform Probing)
### 为什么需要自动探测?
合思费控在不同客户端平台有独立的服务端环境(例如**钉钉版** `https://dd2.hosecloud.com` 与 **原生独立版** `https://app.ekuaibao.com`)。如果平台环境选择不匹配,合思鉴权会失败并报错:
> `请检查 API 平台和凭证配置是否正确`
### 自动探测行为
在使用 `seal-use deploy hosecloud configure` 时:
- **无需手动猜测平台**:用户只需提供 `apiKey` (appKey) 和 `apiSecret` (appSecurity);
- **并发探测 6 大 SaaS 平台域名**:
1. `https://app.ekuaibao.com` (合思原生/标准版,自动设为 `apiOrigin: "production"`)
2. `https://dd2.hosecloud.com` (钉钉版,自动设为 `apiOrigin: "custom"`, `customApiUrl: "https://dd2.hosecloud.com"`)
3. `https://wx2.ekuaibao.com` (企业微信版)
4. `https://feishu.ekuaibao.com` (飞书版)
5. `https://kdcloud2.ekuaibao.com` (云之家版)
6. `https://ddenterprise.ekuaibao.com` (钉钉自建应用版)
- 若为专属私有云或专有部署环境(如美年大健康),显式传入 `--json '{"apiOrigin":"custom", "customApiUrl":"https://custom.domain.com"}'` 即可。
---
## 3. 核心 CLI 命令速查
```bash
# 1. 查看当前企业【发布到合思费控】的所有配置卡片
seal-use deploy hosecloud list --corp <corpId>
# 2. 查询配置参数说明与字段定义
seal-use deploy hosecloud requirements --corp <corpId>
# 3. 添加新配置(自动探测平台)
seal-use deploy hosecloud configure --corp <corpId> --json '{
"apiKey": "your-app-key",
"apiSecret": "your-app-secret",
"outboundName": "SealAI 财务审批",
"mode": "assisted"
}'
# 4. 编辑已有配置(传入原 signKey)
seal-use deploy hosecloud configure --corp <corpId> --json '{
"signKey": "eE2Nfu7NEnSw",
"apiKey": "your-app-key",
"apiSecret": "your-app-secret",
"mode": "semi_automatic",
"autoApprovalRate": 80
}'
# 5. 一键同步发布到合思审批流
seal-use deploy hosecloud sync <signKey> --corp <corpId>
# 5.1 单配置企业一键自动同步 (--auto)
# 若企业内仅存在 1 个合思配置卡片,可直接传入 --auto 自动锁定执行,免去查询复制 signKey:
seal-use deploy hosecloud sync --auto --corp <corpId>
# 6. 查看单项配置详情(未传 signKey 时自动列出当前企业候选列表与查看命令)
seal-use deploy hosecloud get [<signKey>] --corp <corpId>
# 7. 检查发布与多平台集成状态
seal-use deploy hosecloud status --corp <corpId>
```
---
## 4. 关键配置参数定义
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
| :--- | :--- | :---: | :--- | :--- |
| `apiKey` | string | 是 | - | 合思开放平台 `appKey` |
| `apiSecret` | string | 是 | - | 合思开放平台 `appSecurity` |
| `outboundName` | string | 否 | `SealAI 审批` | 同步到合思审批流中显示的出站节点名称 |
| `mode` | enum | 否 | `assisted` | `assisted` (辅助审核) / `semi_automatic` (半自动) / `fully_automatic` (全自动) |
| `autoApprovalRate`| number | 否 | - | 自动审批比例(0~100),非 assisted 模式下生效 |
| `rejectResubmitMethod` | enum | 否 | `node_default` | 驳回重提流向:`node_default` / `to_ebot` / `from_start` |
| `autoApproveNodeNames` | string[] | 否 | - | 允许 AI 自动审批的节点名称列表 |
| `signKey` | string | 否 | 随机生成 | 集成配置卡片唯一标识,编辑时传入以更新对应配置 |
| `apiOrigin` | string | 否 | 自动探测 | `production` / `custom` |
| `customApiUrl` | string | 否 | - | 专属私有云 API 地址(当 `apiOrigin=custom` 时必填) |
+90
View File
@@ -0,0 +1,90 @@
# Seal Approval Rule Linter & Quality Validation
Use this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.
## Key Principles
- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled: false`) to avoid unsolicited noise during standard operations.
- **Explicit Triggering**: `seal-use rules lint` always runs regardless of global configuration.
- **Draft Hook**: When `seal-use config lint enable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.
- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.
## CLI Commands
### 1. Lint Current Draft Rules (Whole-RuleSet Scan)
```bash
seal-use rules lint --corp <corpId>
```
### 2. Lint Specific Historical Version or Single Rule
```bash
# Lint rules in published version 16
seal-use rules lint --version 16 --corp <corpId>
# Lint a specific rule by code (#0038)
seal-use rules lint --code '#0038' --corp <corpId>
# Summary mode (only show rules with issues)
seal-use rules lint --summary --corp <corpId>
```
### 3. Quality Gate for CI / Release
```bash
# If overall score is below 85, terminates with exit code 1
seal-use rules lint --min-score 85 --level error --corp <corpId>
```
### 4. Configure Global Linter Settings
```bash
# Check status
seal-use config lint status
# Enable auto lint on rule updates
seal-use config lint enable --linter builtin --min-score 80
# Disable auto lint
seal-use config lint disable
```
## Built-In Detection Rules
| Code | Level | Description | Recommendation |
| :--- | :---: | :--- | :--- |
| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |
| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |
| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |
## Custom TS Linters (Plugin-as-Code)
Place custom TypeScript linter functions in `~/.config/seal-use/linters/<name>.ts` or `./linters/<name>.ts`:
```typescript
// ~/.config/seal-use/linters/finance-strict.ts
export default function customLinter(rule: { description: string }) {
const issues = [];
if (rule.description.includes("商务舱") && !rule.description.includes("副总裁")) {
issues.push({
level: "error",
code: "FLIGHT_CABIN_RESTRICTION",
snippet: "商务舱",
message: "乘坐商务舱必须限定副总裁及以上级别",
suggestion: "补充限制: '仅副总裁及以上职级允许报销商务舱'"
});
}
return {
score: issues.length === 0 ? 100 : 60,
passed: issues.length === 0,
issues
};
}
```
Run with custom linter:
```bash
seal-use rules lint --linter finance-strict --corp <corpId>
```
+39 -1
View File
@@ -45,6 +45,7 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
: previousConfig.defaultCorpId
: undefined;
const config = saveGlobalConfig({
...previousConfig,
stateful,
...(defaultCorpId ? { defaultCorpId } : {})
});
@@ -52,5 +53,42 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
if (action === "lint") {
const subAction = maybeName ?? stringOption(args.options.state) ?? stringOption(args.options.enable);
const previousConfig = loadGlobalConfig();
const currentLint = previousConfig.lint ?? { enabled: false, activeLinter: "builtin", minScore: 0 };
if (!subAction || subAction === "status" || subAction === "get") {
printJson({ lint: currentLint, configFile: resolveGlobalConfigFile() });
return;
}
let enabled = currentLint.enabled;
if (subAction === "enable" || subAction === "on" || subAction === "true") {
enabled = true;
} else if (subAction === "disable" || subAction === "off" || subAction === "false") {
enabled = false;
}
const activeLinter = stringOption(args.options.linter) ?? currentLint.activeLinter;
const minScore = args.options.minScore !== undefined || args.options["min-score"] !== undefined
? Number(args.options.minScore ?? args.options["min-score"])
: currentLint.minScore;
const nextLint = {
enabled,
activeLinter,
minScore: isNaN(minScore) ? 0 : Math.max(0, Math.min(100, minScore))
};
const config = saveGlobalConfig({
...previousConfig,
lint: nextLint
});
printJson(globalConfigSummary(config));
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint. Run 'seal-use help' for available commands.`);
}
+93 -6
View File
@@ -2,9 +2,10 @@ import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { jsonObject, stringOption } from "../parser.js";
import { booleanOption, jsonObject, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import * as api from "../../domains/seal/api.js";
export async function handleDeployCommand(
systemOrAction: string | undefined,
@@ -14,12 +15,42 @@ export async function handleDeployCommand(
corp: CorpConfig,
args: ParsedArgs
) {
const isHosecloud = systemOrAction === "hosecloud" || !systemOrAction;
if (!systemOrAction || systemOrAction === "help") {
throw new Error(
"Usage: seal-use deploy <system> <action> [options]\n\n" +
"支持的审批系统与发布目标:\n" +
" • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>\n" +
" • webhook (通用审批流回调): seal-use webhook <list|get|add|update|delete> --corp <corpId>\n" +
" • feishu (飞书审批): 建议使用 Webhook 模式对接\n" +
" • weaver (泛微 OA): 建议使用 Webhook 模式对接\n" +
" • helios (汇联易): 建议使用 Webhook 模式对接\n" +
" • maycur (每刻报销): 建议使用 Webhook 模式对接"
);
}
if (systemOrAction === "webhook" || systemOrAction === "webhooks") {
throw new Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");
}
if (systemOrAction === "feishu" || systemOrAction === "lark") {
throw new Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");
}
if (systemOrAction === "weaver") {
throw new Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");
}
if (systemOrAction === "maycur" || systemOrAction === "helios") {
const name = systemOrAction === "maycur" ? "每刻报销" : "汇联易";
throw new Error(`${name}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${name}' --result-url <url> --corp <corpId>`);
}
const isHosecloud = systemOrAction === "hosecloud";
const action = systemOrAction === "hosecloud" ? actionOrTarget : systemOrAction;
const target = systemOrAction === "hosecloud" ? maybeTarget : actionOrTarget;
if (!isHosecloud && systemOrAction !== "hosecloud") {
throw new Error(`Unknown deploy target: ${systemOrAction ?? ""}. Currently supported: hosecloud`);
if (!isHosecloud) {
throw new Error(`未知的发布目标系统: ${systemOrAction}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);
}
if (action === "requirements") {
@@ -34,7 +65,26 @@ export async function handleDeployCommand(
if (action === "get") {
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
if (!signKey) throw new Error("Usage: seal-use deploy hosecloud get <sign-key>");
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
if (hoseConfigs.length === 0) {
throw new Error(
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
`👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${corp.id}`
);
}
console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${corp.id}]\n`);
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
for (const item of hoseConfigs) {
const name = (item as any).outboundName ?? "SealAI 审批";
const key = item.signKey;
const origin = (item as any).apiOrigin ?? "production";
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。");
}
await runTool("seal_deploy_hosecloud_get", client, corp, { signKey }, outputOptions(args.options));
return;
}
@@ -58,7 +108,44 @@ export async function handleDeployCommand(
if (action === "sync") {
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
if (!signKey) throw new Error("Usage: seal-use deploy hosecloud sync <sign-key>");
const autoOpt = booleanOption(args.options.auto) ?? booleanOption(args.options.yes);
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
if (hoseConfigs.length === 0) {
throw new Error(
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
`👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${corp.id}`
);
}
const firstHose = hoseConfigs[0];
if (firstHose && hoseConfigs.length === 1 && autoOpt) {
const singleKey = firstHose.signKey;
console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${singleKey})`);
await runTool("seal_deploy_hosecloud_sync", client, corp, { signKey: singleKey }, outputOptions(args.options));
return;
}
console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${corp.id}]\n`);
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
for (const item of hoseConfigs) {
const name = (item as any).outboundName ?? "SealAI 审批";
const key = item.signKey;
const origin = (item as any).apiOrigin ?? "production";
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 同步命令: seal-use deploy hosecloud sync ${key} --corp ${corp.id}\n`);
}
if (hoseConfigs.length === 1) {
console.error(`💡 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。");
}
await runTool("seal_deploy_hosecloud_sync", client, corp, { signKey }, outputOptions(args.options));
return;
}
+71 -1
View File
@@ -140,5 +140,75 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
if (action === "pull") {
const version = stringOption(args.options.version) ?? maybeName;
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
await runTool(
"seal_approval_rules_pull",
client,
corp,
{
version,
out
},
outputOptions(args.options)
);
return;
}
if (action === "push") {
const file = stringOption(args.options.file) ?? stringOption(args.options.f) ?? maybeName;
const confirmed = booleanOption(args.options.yes) === true;
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
const publish = booleanOption(args.options.publish);
const versionName = stringOption(args.options.versionName) ?? stringOption(args.options["version-name"]);
const result = await runToolResult(
"seal_approval_rules_push",
client,
corp,
{
file,
dryRun,
confirm: confirmed,
publish,
versionName
}
);
if (!confirmed && dryRun && result && typeof result === "object") {
printJson(
{
...result,
nextCommand: `seal-use rules push --file ${file ?? "./rules.local.json"} --corp ${corp.id} --yes${publish ? " --publish" : ""}`
},
outputOptions(args.options)
);
return;
}
printJson(result, outputOptions(args.options));
return;
}
if (action === "lint") {
await runTool(
"seal_approval_rules_lint",
client,
corp,
{
file: stringOption(args.options.file) ?? stringOption(args.options.f),
linter: stringOption(args.options.linter),
version: stringOption(args.options.version),
code: stringOption(args.options.code),
ruleId: stringOption(args.options.rule) ?? maybeName,
minScore: numberOption(args.options.minScore) ?? numberOption(args.options["min-score"]),
level: stringOption(args.options.level),
summary: booleanOption(args.options.summary)
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, pull, push. Run 'seal-use help' for available commands.`);
}
+24 -9
View File
@@ -3,17 +3,32 @@ import { join } from "node:path";
import { VERSION } from "../../version.js";
import { runServiceCommand } from "../service.js";
import { printJson } from "../printer.js";
import type { CliRuntime } from "../types.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliRuntime, ParsedArgs } from "../types.js";
export const STATE_DIR = join(homedir(), ".config", "seal-use");
export async function handleServiceCommand(action: string | undefined, runtime: CliRuntime) {
const result = await runServiceCommand(action, {
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
stateDir: STATE_DIR,
version: VERSION,
launcher: runtime.launcher
});
export async function handleServiceCommand(
action: string | undefined,
runtime: CliRuntime,
args?: ParsedArgs
) {
const port = args ? numberOption(args.options.port) ?? numberOption(args.options.p) : undefined;
const host = args ? stringOption(args.options.host) ?? stringOption(args.options.h) : undefined;
const maxLines = args ? numberOption(args.options.lines) ?? numberOption(args.options.n) : undefined;
const result = await runServiceCommand(
action,
{
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
stateDir: STATE_DIR,
version: VERSION,
launcher: runtime.launcher,
port,
host
},
{ maxLines }
);
if (result !== undefined) printJson(result);
}
+30 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { compareSemVer, isNewerVersion } from "./update.js";
import { compareSemVer, getMirrorMode, isNewerVersion } from "./update.js";
describe("update version comparator", () => {
test("correctly identifies newer semantic versions", () => {
@@ -19,3 +19,32 @@ describe("update version comparator", () => {
expect(compareSemVer("0.3.3", "0.7.1")).toBe(-1);
});
});
describe("getMirrorMode routing", () => {
const originalEnv = { ...process.env };
test("defaults to github when CI is set", () => {
delete process.env.SEAL_USE_MIRROR;
delete process.env.SEAL_HOME_MIRROR;
process.env.CI = "true";
expect(getMirrorMode()).toBe("github");
});
test("defaults to auto when CI is not set", () => {
delete process.env.SEAL_USE_MIRROR;
delete process.env.SEAL_HOME_MIRROR;
delete process.env.CI;
expect(getMirrorMode()).toBe("auto");
});
test("respects SEAL_USE_MIRROR override", () => {
process.env.SEAL_USE_MIRROR = "gitea";
expect(getMirrorMode()).toBe("gitea");
process.env.SEAL_USE_MIRROR = "github";
expect(getMirrorMode()).toBe("github");
});
// Restore env
process.env = originalEnv;
});
+82 -38
View File
@@ -307,6 +307,13 @@ type GitHubRelease = {
assets: GitHubAsset[];
};
export function getMirrorMode(): "auto" | "github" | "gitea" {
const env = (process.env.SEAL_USE_MIRROR || process.env.SEAL_HOME_MIRROR)?.trim().toLowerCase();
if (env === "github" || env === "gitea") return env;
if (process.env.CI) return "github";
return "auto";
}
async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRelease[]> {
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const headers: Record<string, string> = {
@@ -315,13 +322,23 @@ async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRele
...(token ? { Authorization: `Bearer ${token}` } : {})
};
const urls = [
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases?per_page=${limit}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases?per_page=${limit}`,
`https://api.github.com/repos/${repo}/releases?per_page=${limit}`
];
if (repo !== LEGACY_GITHUB_REPO) {
urls.push(`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases?per_page=${limit}`);
const mirrorMode = getMirrorMode();
const urls: string[] = [];
// 1. Gitea releases (bypassed in CI / GitHub-only mode)
if (mirrorMode !== "github") {
urls.push(
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases?per_page=${limit}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases?per_page=${limit}`
);
}
// 2. GitHub releases (bypassed in Gitea-only mode)
if (mirrorMode !== "gitea") {
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
if (repo !== LEGACY_GITHUB_REPO) {
urls.push(`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases?per_page=${limit}`);
}
}
for (const url of urls) {
@@ -379,19 +396,36 @@ async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise
...(token ? { Authorization: `Bearer ${token}` } : {})
};
const urls = tag
? [
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/tags/${tag}`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/tags/${tag}`,
`https://api.github.com/repos/${repo}/releases/tags/${tag}`,
...(repo !== LEGACY_GITHUB_REPO ? [`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/tags/${tag}`] : [])
]
: [
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/latest`,
`https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/latest`,
`https://api.github.com/repos/${repo}/releases/latest`,
...(repo !== LEGACY_GITHUB_REPO ? [`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/latest`] : [])
];
const mirrorMode = getMirrorMode();
const urls: string[] = [];
// 1. Gitea releases (bypassed in CI / GitHub-only mode)
if (mirrorMode !== "github") {
urls.push(
tag
? `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/tags/${tag}`
: `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/latest`,
tag
? `https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/tags/${tag}`
: `https://git.ying-qing.cn/api/v1/repos/gitea/seal-home/releases/latest`
);
}
// 2. GitHub releases (bypassed in Gitea-only mode)
if (mirrorMode !== "gitea") {
urls.push(
tag
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
: `https://api.github.com/repos/${repo}/releases/latest`
);
if (repo !== LEGACY_GITHUB_REPO) {
urls.push(
tag
? `https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/tags/${tag}`
: `https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/latest`
);
}
}
let fallbackRelease: GitHubRelease | undefined;
@@ -494,30 +528,40 @@ function logProgress(msg: string) {
}
async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) {
const mirrorMode = getMirrorMode();
const candidates: string[] = [];
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
const fileName = assetName || url.split("/").pop() || "";
// 1. High-speed Gitea direct mirror first
if (tag && fileName) {
candidates.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${tag}/${fileName}`);
}
if (url.startsWith("https://git.ying-qing.cn")) {
candidates.push(url);
// 1. High-speed Gitea direct mirror (bypassed in CI / GitHub-only mode)
if (mirrorMode !== "github") {
if (tag && fileName) {
candidates.push(
`https://git.ying-qing.cn/gitea/seal-use/releases/download/${tag}/${fileName}`,
`https://git.ying-qing.cn/gitea/seal-home/releases/download/${tag}/${fileName}`
);
}
if (url.startsWith("https://git.ying-qing.cn")) {
candidates.push(url);
}
}
// 2. Fast GitHub CDN proxies and direct GitHub fallback
if (tag && fileName) {
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
candidates.push(ghDirectUrl);
} else if (url.includes("github.com")) {
candidates.push(`https://ghfast.top/${url}`);
candidates.push(`https://gh.ddlc.top/${url}`);
candidates.push(url);
} else {
candidates.push(url);
// 2. Fast GitHub CDN proxies and direct GitHub fallback (bypassed in Gitea-only mode)
if (mirrorMode !== "gitea") {
if (tag && fileName) {
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
if (!process.env.CI) {
candidates.push(`https://ghfast.top/${ghDirectUrl}`, `https://gh.ddlc.top/${ghDirectUrl}`);
}
candidates.push(ghDirectUrl);
} else if (url.includes("github.com")) {
if (!process.env.CI) {
candidates.push(`https://ghfast.top/${url}`, `https://gh.ddlc.top/${url}`);
}
candidates.push(url);
} else {
candidates.push(url);
}
}
// Deduplicate candidates
+33
View File
@@ -1,6 +1,10 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { existsSync } from "node:fs";
import { runTool } from "../helpers.js";
import * as api from "../../domains/seal/api.js";
import { findWebhookIntegration } from "../../domains/seal/api.js";
import { previewMaterialPack, pushMaterialPack, readMaterialPackFile } from "../../domains/seal/material-pack/index.js";
import {
booleanOption,
parseWebhookMode,
@@ -11,6 +15,12 @@ import {
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleWebhookMaterialPackPreview(filePath: string) {
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
}
export async function handleWebhookCommand(
action: string | undefined,
maybeName: string | undefined,
@@ -18,6 +28,29 @@ export async function handleWebhookCommand(
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "material-pack" || action === "material-pack-push") {
const operation = action === "material-pack-push" ? "push" : maybeName;
const filePath = action === "material-pack-push"
? stringOption(args.options.file) ?? stringOption(args.options.input)
: args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
if (operation === "preview") {
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
return;
}
if (operation !== "push") throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
if (!selector) throw new Error("Push requires --webhook <idOrName>");
const integration = findWebhookIntegration(await api.listWebhookIntegrations(client), selector);
const result = await pushMaterialPack(input.fileBuffer, input.fileName, {
webhookUrl: integration.incomingDocumentWebhook.url,
secret: integration.secret
});
console.log(JSON.stringify(result, null, 2));
return;
}
if (action === "list") {
await runTool(
"seal_webhook_list",
+1
View File
@@ -27,6 +27,7 @@ export function globalConfigSummary(config: GlobalConfig = loadGlobalConfig()) {
...(config.stateful && config.defaultCorpId
? { defaultCorpId: config.defaultCorpId }
: {}),
lint: config.lint,
configFile: resolveGlobalConfigFile()
};
}
+10 -3
View File
@@ -19,12 +19,19 @@ export function parseArgs(argv: string[]): ParsedArgs {
}
if (arg.startsWith("-")) {
const key = arg.replace(/^-+/, "");
const raw = arg.replace(/^-+/, "");
if (raw.includes("=")) {
const eqIdx = raw.indexOf("=");
const key = raw.slice(0, eqIdx);
const val = raw.slice(eqIdx + 1);
options[key] = val;
continue;
}
const next = argv[index + 1];
if (!next || next.startsWith("-")) {
options[key] = true;
options[raw] = true;
} else {
options[key] = next;
options[raw] = next;
index += 1;
}
continue;
+2
View File
@@ -121,6 +121,8 @@ Usage:
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--corp <corpId>]
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> --webhook <idOrName> [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
+45 -2
View File
@@ -3,6 +3,7 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { createSealClient } from "../core/http/factory.js";
import type { CorpConfig } from "../core/config/types.js";
import { VERSION } from "../version.js";
import { handleApprovalRunsCommand } from "./commands/approval-runs.js";
import { handleAuthCommand } from "./commands/auth.js";
@@ -28,7 +29,7 @@ import { handleToolCommand } from "./commands/tool.js";
import { handleToolsListCommand } from "./commands/tools.js";
import { handleUpdateCommand } from "./commands/update.js";
import { handleUsersCommand } from "./commands/users.js";
import { handleWebhookCommand } from "./commands/webhook.js";
import { handleWebhookCommand, handleWebhookMaterialPackPreview } from "./commands/webhook.js";
import { selectCorp } from "./helpers.js";
import { booleanOption, numberOption, parseArgs, stringOption } from "./parser.js";
import {
@@ -44,6 +45,7 @@ const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))
const KNOWN_AREAS = new Set([
"config",
"service",
"stop",
"http",
"serve",
"update",
@@ -77,9 +79,23 @@ const KNOWN_AREAS = new Set([
export type { CliResult, CliRunOptions } from "./types.js";
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
function isStandingCommand(argv: string[]): boolean {
if (!argv.length) return false;
const first = argv[0]?.toLowerCase();
const second = argv[1]?.toLowerCase();
if (first && STANDING_COMMANDS.has(first)) return true;
if ((first === "service" || first === "daemon") && second === "run") return true;
return false;
}
let runQueue = Promise.resolve();
export function runCli(argv: string[], options: CliRunOptions = {}): Promise<CliResult> {
if (isStandingCommand(argv)) {
return runCliOnce(argv, options);
}
const run = runQueue.then(() => runCliOnce(argv, options));
runQueue = run.then(
() => undefined,
@@ -155,6 +171,13 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
if (area === "webhook" && action === "material-pack" && maybeName === "preview") {
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook material-pack preview <材料包.zip>");
await handleWebhookMaterialPackPreview(filePath);
return;
}
if (area === "openapi") {
handleOpenApiCommand(args);
return;
@@ -186,7 +209,12 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
}
if (area === "service") {
await handleServiceCommand(action, runtime);
await handleServiceCommand(action, runtime, args);
return;
}
if (area === "stop") {
await handleServiceCommand("stop", runtime, args);
return;
}
@@ -241,6 +269,21 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "rules" && action === "lint" && ("file" in args.options || "f" in args.options)) {
let corp: CorpConfig;
try {
corp = selectCorp(stringOption(args.options.corp));
} catch {
corp = {
id: "local",
name: "Local Workspace",
source: { type: "native" }
} as any;
}
await handleRulesCommand(action, maybeName, null as any, corp, args);
return;
}
const corp = selectCorp(stringOption(args.options.corp));
if (area === "source") {
+67 -1
View File
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { serviceStatus } from "./service.js";
import { serviceStatus, readServiceLogs, runServiceCommand } from "./service.js";
const tempDirs: string[] = [];
@@ -27,5 +27,71 @@ describe("service lifecycle state", () => {
expect(status.running).toBe(false);
expect(status.pid).toBeUndefined();
expect(status.port).toBe(8787);
expect(status.host).toBe("127.0.0.1");
expect(status.url).toBeUndefined();
});
test("respects custom port and host configuration", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const status = serviceStatus({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir,
version: "0.10.7",
port: 9090,
host: "0.0.0.0"
});
expect(status.port).toBe(9090);
expect(status.host).toBe("0.0.0.0");
});
test("reads service log file lines safely", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const emptyLogs = readServiceLogs({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(emptyLogs.lines).toEqual([]);
expect(emptyLogs.totalLines).toBe(0);
const logFile = join(stateDir, "service.log");
writeFileSync(logFile, "line 1\nline 2\nline 3\nline 4\nline 5\n");
const logs = readServiceLogs(
{
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
},
3
);
expect(logs.totalLines).toBe(5);
expect(logs.lines).toEqual(["line 3", "line 4", "line 5"]);
});
test("runServiceCommand handles logs and status actions", async () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const status = await runServiceCommand("status", {
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(status).toHaveProperty("running");
const logs = await runServiceCommand("logs", {
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(logs).toHaveProperty("lines");
});
});
+106 -12
View File
@@ -1,6 +1,7 @@
import { spawn, execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
export type ServiceConfig = {
appRoot: string;
@@ -11,12 +12,14 @@ export type ServiceConfig = {
command: string;
args?: string[];
};
port?: number;
host?: string;
};
export async function runServiceCommand(
action: string | undefined,
config: ServiceConfig,
options: { quiet?: boolean } = {}
options: { quiet?: boolean; maxLines?: number } = {}
) {
switch (action) {
case "run":
@@ -25,31 +28,55 @@ export async function runServiceCommand(
case "start":
return startService(config);
case "stop":
case "kill":
case "down":
case "shutdown":
return stopService(config, options);
case "restart":
stopService(config, { quiet: true });
return startService(config);
case "logs":
case "log":
return readServiceLogs(config, options.maxLines);
case "status":
case undefined:
return serviceStatus(config);
default:
throw new Error("Usage: seal-use service <start|stop|restart|status>");
throw new Error("Usage: seal-use service <start|stop|restart|status|logs>");
}
}
export function serviceStatus(config: ServiceConfig) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const pid = readServicePid(pidFile);
const running = pid ? isSealHomeProcess(pid, config.appRoot) : false;
if (pid && !running) {
rmSync(pidFile, { force: true });
if (!running) {
if (pid) rmSync(pidFile, { force: true });
if (existsSync(metaFile)) rmSync(metaFile, { force: true });
}
let storedMeta: { port?: number; host?: string; version?: string } | undefined;
if (running && existsSync(metaFile)) {
try {
storedMeta = JSON.parse(readFileSync(metaFile, "utf8"));
} catch {
// ignore
}
}
const port = config.port ?? storedMeta?.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? storedMeta?.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
const version = config.version ?? storedMeta?.version;
return {
running,
pid: running ? pid : undefined,
version: config.version,
version,
port,
host,
url: running ? `http://${host}:${port}` : undefined,
appRoot: config.appRoot,
stateDir: config.stateDir,
pidFile,
@@ -57,28 +84,84 @@ export function serviceStatus(config: ServiceConfig) {
};
}
export function readServiceLogs(config: ServiceConfig, maxLines = 50) {
const logFile = getLogFile(config);
if (!existsSync(logFile)) {
return {
logFile,
lines: [],
totalLines: 0
};
}
const content = readFileSync(logFile, "utf8");
const allLines = content.split("\n").filter(Boolean);
const lines = allLines.slice(-maxLines);
return {
logFile,
lines,
totalLines: allLines.length
};
}
async function runService(config: ServiceConfig) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const logFile = getLogFile(config);
ensureStateDir(config.stateDir);
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
appendLog(logFile, `running pid=${process.pid}`);
const cleanup = () => {
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
writeFileSync(
metaFile,
JSON.stringify(
{
pid: process.pid,
port,
host,
version: config.version,
startedAt: new Date().toISOString()
},
null,
2
),
{ mode: 0o600 }
);
appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`);
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
try {
server = await startHttpServer({ port, host, silent: true });
appendLog(logFile, `service listening pid=${process.pid}`);
} catch (err: unknown) {
appendLog(logFile, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
}
throw err;
}
const cleanup = () => {
if (server) {
server.close();
server = null;
}
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
}
appendLog(logFile, `stopped pid=${process.pid}`);
};
await new Promise<void>((resolve) => {
let stopped = false;
const heartbeat = setInterval(() => {}, 60_000);
const stop = () => {
if (stopped) return;
stopped = true;
cleanup();
clearInterval(heartbeat);
process.off("SIGTERM", stop);
process.off("SIGINT", stop);
resolve();
@@ -96,11 +179,15 @@ function startService(config: ServiceConfig) {
}
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
const child = spawn(launcher.command, [
const serviceArgs = [
...(launcher.args ?? []),
"service",
"run"
], {
];
if (config.port) serviceArgs.push("--port", String(config.port));
if (config.host) serviceArgs.push("--host", String(config.host));
const child = spawn(launcher.command, serviceArgs, {
cwd: config.appRoot,
detached: true,
stdio: ["ignore", "ignore", "ignore"],
@@ -116,14 +203,17 @@ function startService(config: ServiceConfig) {
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const pid = readServicePid(pidFile);
if (!pid || !isSealHomeProcess(pid, config.appRoot)) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
return options.quiet ? undefined : { stopped: false, reason: "not running" };
}
process.kill(pid, "SIGTERM");
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
appendLog(getLogFile(config), `stop requested pid=${pid}`);
return options.quiet ? undefined : { stopped: true, pid };
}
@@ -156,6 +246,10 @@ function getPidFile(config: ServiceConfig) {
return join(config.stateDir, "service.pid");
}
function getMetaFile(config: ServiceConfig) {
return join(config.stateDir, "service.json");
}
function getLogFile(config: ServiceConfig) {
return join(config.stateDir, "service.log");
}
+23 -3
View File
@@ -104,7 +104,14 @@ describe("loadCorpConfigs", () => {
test("defaults global config to stateless", () => {
process.env.SEAL_USE_CONFIG_FILE = join(makeTempDir(), "config.json");
expect(loadGlobalConfig()).toEqual({ stateful: false });
expect(loadGlobalConfig()).toEqual({
stateful: false,
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
test("saves and loads the global state mode", () => {
@@ -113,10 +120,23 @@ describe("loadCorpConfigs", () => {
expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a" })).toEqual({
stateful: true,
defaultCorpId: "corp-a"
defaultCorpId: "corp-a",
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
expect(resolveGlobalConfigFile()).toBe(file);
expect(loadGlobalConfig()).toEqual({ stateful: true, defaultCorpId: "corp-a" });
expect(loadGlobalConfig()).toEqual({
stateful: true,
defaultCorpId: "corp-a",
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
});
+2 -2
View File
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "enterprises";
const CONFIG_ENV = "SEAL_USE_ENTERPRISES_DIR";
@@ -101,7 +101,7 @@ export function loadGlobalConfig(): GlobalConfig {
return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
}
export function saveGlobalConfig(config: GlobalConfig): GlobalConfig {
export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig {
const normalized = GlobalConfigSchema.parse(config);
const configured = (process.env[GLOBAL_CONFIG_ENV] ?? process.env[LEGACY_GLOBAL_CONFIG_ENV])?.trim();
const file = configured || PRIMARY_GLOBAL_CONFIG_FILE;
+14 -2
View File
@@ -82,7 +82,14 @@ describe("CorpConfigSchema", () => {
describe("GlobalConfigSchema", () => {
test("defaults to stateless mode", () => {
expect(GlobalConfigSchema.parse({})).toEqual({ stateful: false });
expect(GlobalConfigSchema.parse({})).toEqual({
stateful: false,
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
test("accepts a stateful default enterprise", () => {
@@ -91,7 +98,12 @@ describe("GlobalConfigSchema", () => {
defaultCorpId: "corp-a"
})).toEqual({
stateful: true,
defaultCorpId: "corp-a"
defaultCorpId: "corp-a",
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
});
+14 -1
View File
@@ -84,9 +84,20 @@ export const CorpConfigSchema = z.object({
auth: CorpAuthConfigSchema
});
export const GlobalLintConfigSchema = z.object({
enabled: z.boolean().default(false),
activeLinter: z.string().default("builtin"),
minScore: z.number().min(0).max(100).default(0)
}).default({
enabled: false,
activeLinter: "builtin",
minScore: 0
});
export const GlobalConfigSchema = z.object({
stateful: z.boolean().default(false),
defaultCorpId: z.string().min(1).optional()
defaultCorpId: z.string().min(1).optional(),
lint: GlobalLintConfigSchema
});
export type HoseSealSource = z.infer<typeof HoseSealSourceSchema>;
@@ -95,4 +106,6 @@ export type NativeSealSource = z.infer<typeof NativeSealSourceSchema>;
export type SealSource = z.infer<typeof SealSourceSchema>;
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
export type GlobalLintConfig = z.infer<typeof GlobalLintConfigSchema>;
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
export type GlobalConfigInput = z.input<typeof GlobalConfigSchema>;
+89
View File
@@ -0,0 +1,89 @@
import type { RuleLintIssue, RuleLintResult, RuleLintTarget } from "./types.js";
export const BUILTIN_VAGUE_WORDS = [
"原则上",
"尽量",
"适当",
"酌情",
"一般情况下",
"尽可能",
"合理控制",
"视情况",
"视具体情况"
];
export const BUILTIN_EXCEPTION_TRIGGERS = [
"除非",
"特殊情况",
"特殊原因",
"经批准",
"经审批",
"经领导同意",
"除外",
"例外"
];
export const BUILTIN_EVIDENCE_KEYWORDS = [
"备注",
"说明",
"附件",
"证明",
"邮件",
"截图",
"凭证",
"审批",
"单据",
"发票"
];
export function builtinRuleLinter(rule: RuleLintTarget): RuleLintResult {
const text = (rule.description || "").trim();
const issues: RuleLintIssue[] = [];
// 1. 规则过短检查
if (text.length < 5) {
issues.push({
level: "error",
code: "TOO_SHORT",
message: "规则描述过于简短(少于 5 个字),大模型难以形成明确的判定逻辑",
suggestion: "请补充具体的费用类型、核验条件与限制标准"
});
}
// 2. 主观模糊词拦截
for (const word of BUILTIN_VAGUE_WORDS) {
if (text.includes(word)) {
issues.push({
level: "error",
code: "VAGUE_WORD",
snippet: word,
message: `包含主观模糊词 "${word}",容易导致大模型判定标准产生波动与幻觉`,
suggestion: `建议移除 "${word}",改为具体的金额上限、枚举范围或刚性判定条件`
});
}
}
// 3. 悬空例外条款检测
const matchedTrigger = BUILTIN_EXCEPTION_TRIGGERS.find((trigger) => text.includes(trigger));
const hasEvidence = BUILTIN_EVIDENCE_KEYWORDS.some((kw) => text.includes(kw));
if (matchedTrigger && !hasEvidence) {
issues.push({
level: "warning",
code: "HANGING_EXCEPTION",
snippet: matchedTrigger,
message: `包含例外条款 "${matchedTrigger}",但未指定 AI 从何处核验该例外成立的依据`,
suggestion: `建议补充明确的凭据来源(例如:"需在【单据备注】中说明原因" 或 "需在【附件】中上传审批截图")`
});
}
const errorCount = issues.filter((i) => i.level === "error").length;
const warningCount = issues.filter((i) => i.level === "warning").length;
const score = Math.max(0, 100 - errorCount * 25 - warningCount * 10);
return {
score,
passed: errorCount === 0,
issues
};
}
+4
View File
@@ -0,0 +1,4 @@
export * from "./types.js";
export * from "./builtin.js";
export * from "./loader.js";
export * from "./service.js";
+112
View File
@@ -0,0 +1,112 @@
import { describe, expect, test } from "bun:test";
import { builtinRuleLinter } from "./builtin.js";
import { loadRuleLinter } from "./loader.js";
import { lintRuleBatch, lintSingleRule } from "./service.js";
import { writeFileSync, unlinkSync, mkdirSync, existsSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
describe("Rule Linter", () => {
test("builtinRuleLinter detects short text, vague words, and hanging exceptions", () => {
// 1. 过短文本
const shortResult = builtinRuleLinter({ description: "测试" });
expect(shortResult.passed).toBe(false);
expect(shortResult.issues.some((i) => i.code === "TOO_SHORT")).toBe(true);
// 2. 主观模糊词
const vagueResult = builtinRuleLinter({
description: "原则上差旅住宿费尽量控制在500元以内"
});
expect(vagueResult.passed).toBe(false);
expect(vagueResult.issues.filter((i) => i.code === "VAGUE_WORD").length).toBe(2);
expect(vagueResult.score).toBeLessThanOrEqual(50);
// 3. 悬空例外条款(无证据说明)
const exceptionResult = builtinRuleLinter({
description: "差旅住宿费单日不得超过500元,特殊情况除外"
});
expect(exceptionResult.issues.some((i) => i.code === "HANGING_EXCEPTION")).toBe(true);
// 4. 完美高质量规则
const cleanResult = builtinRuleLinter({
description: "差旅住宿费每日不可超过500元。若因特殊情况超标,必须在【单据备注】中说明原因并在【附件】中提供总监审批邮件截图。"
});
expect(cleanResult.passed).toBe(true);
expect(cleanResult.score).toBe(100);
expect(cleanResult.issues.length).toBe(0);
});
test("loadRuleLinter returns builtin linter for default or non-existent files safely", async () => {
const builtinLoaded = await loadRuleLinter("builtin");
expect(builtinLoaded.type).toBe("builtin");
// 不存在的文件安全降级至 builtin,不抛错崩溃
const nonExistent = await loadRuleLinter("/tmp/non-existent-linter-xyz.ts");
expect(nonExistent.type).toBe("builtin");
const res = await nonExistent.linter({ description: "原则上不能超标" });
expect(res.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true);
});
test("loadRuleLinter safely executes custom TS/JS linter and catches runtime exceptions", async () => {
const testDir = join(tmpdir(), "seal-use-linter-test");
if (!existsSync(testDir)) mkdirSync(testDir, { recursive: true });
// 1. 有效的自定义校验器
const customTsPath = join(testDir, "custom-valid.ts");
writeFileSync(
customTsPath,
`export default function customLinter(rule) {
if (rule.description.includes("商务舱")) {
return { score: 40, passed: false, issues: [{ level: "error", code: "CUSTOM_FLIGHT", message: "禁止报销商务舱" }] };
}
return { score: 100, passed: true, issues: [] };
}`
);
const loadedCustom = await loadRuleLinter(customTsPath);
expect(loadedCustom.type).toBe("custom");
const customRes = await loadedCustom.linter({ description: "报销商务舱机票一张" });
expect(customRes.passed).toBe(false);
expect(customRes.issues[0]?.code).toBe("CUSTOM_FLIGHT");
// 2. 运行时崩溃的自定义校验器(安全捕获并降级)
const crashingTsPath = join(testDir, "custom-crash.ts");
writeFileSync(
customTsPath,
`export default function crashLinter() {
throw new Error("Intentional Crash");
}`
);
const loadedCrash = await loadRuleLinter(crashingTsPath);
const crashFallbackRes = await loadedCrash.linter({ description: "原则上不能超标" });
// 应当安全降级运行 builtin,返回模糊词拦截结果
expect(crashFallbackRes.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true);
// 清理临时文件
try {
unlinkSync(customTsPath);
} catch {}
});
test("lintRuleBatch computes overall summary, score average, and filters by level", async () => {
const loaded = await loadRuleLinter("builtin");
const rules = [
{ id: "1", code: "#0001", name: "清晰规则", description: "差旅住宿费每日不可超过500元,超标需在【单据备注】中说明并附【审批截图】。" },
{ id: "2", code: "#0002", name: "模糊规则", description: "原则上差旅住宿费尽量控制在500元以内" },
{ id: "3", code: "#0003", name: "悬空例外", description: "差旅住宿费单日不得超过500元,特殊情况除外" }
];
const batchRes = await lintRuleBatch(rules, loaded, undefined, { level: "all" });
expect(batchRes.totalRules).toBe(3);
expect(batchRes.healthyCount).toBe(1);
expect(batchRes.issueCount).toBe(2);
expect(batchRes.overallScore).toBeLessThan(100);
expect(batchRes.passed).toBe(false);
// 摘要模式:只返回有问题的规则
const summaryRes = await lintRuleBatch(rules, loaded, undefined, { summary: true });
expect(summaryRes.issues.length).toBe(2);
expect(summaryRes.issues.map((i) => i.ruleCode)).toEqual(["#0002", "#0003"]);
});
});
+146
View File
@@ -0,0 +1,146 @@
import { existsSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { isAbsolute, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { builtinRuleLinter } from "./builtin.js";
import type { RuleLintContext, RuleLintResult, RuleLintTarget, RuleLinterFn } from "./types.js";
export const PRIMARY_LINTERS_DIR = join(homedir(), ".config", "seal-use", "linters");
export const LOCAL_LINTERS_DIR = join(process.cwd(), "linters");
export interface LoadedLinter {
name: string;
type: "builtin" | "custom";
filePath?: string;
linter: RuleLinterFn;
}
export function listAvailableLinters(): Array<{ name: string; type: "builtin" | "custom"; path?: string }> {
const list: Array<{ name: string; type: "builtin" | "custom"; path?: string }> = [
{ name: "builtin", type: "builtin" }
];
const searchDirs = [PRIMARY_LINTERS_DIR, LOCAL_LINTERS_DIR];
for (const dir of searchDirs) {
if (existsSync(dir)) {
try {
const files = readdirSync(dir);
for (const file of files) {
if (file.endsWith(".ts") || file.endsWith(".js") || file.endsWith(".mjs")) {
const baseName = file.replace(/\.(ts|js|mjs)$/, "");
if (!list.some((item) => item.name === baseName)) {
list.push({
name: baseName,
type: "custom",
path: join(dir, file)
});
}
}
}
} catch {
// 忽略目录读取异常
}
}
}
return list;
}
export function resolveLinterPath(nameOrPath: string): string | undefined {
if (!nameOrPath || nameOrPath === "builtin") {
return undefined;
}
// 1. 绝对路径或显式相对路径
if (isAbsolute(nameOrPath) || nameOrPath.startsWith("./") || nameOrPath.startsWith("../")) {
const absPath = resolve(nameOrPath);
if (existsSync(absPath)) return absPath;
for (const ext of [".ts", ".js", ".mjs"]) {
if (existsSync(`${absPath}${ext}`)) return `${absPath}${ext}`;
}
}
// 2. 搜索预设目录
const candidates = [
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.ts`),
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.js`),
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.mjs`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.ts`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.js`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.mjs`)
];
for (const path of candidates) {
if (existsSync(path)) return path;
}
return undefined;
}
export async function loadRuleLinter(nameOrPath?: string): Promise<LoadedLinter> {
if (!nameOrPath || nameOrPath === "builtin") {
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
const resolvedPath = resolveLinterPath(nameOrPath);
if (!resolvedPath) {
console.error(`⚠️ [linter] 未找到自定义校验器 "${nameOrPath}",已自动安全降级至内置校验器。`);
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
try {
const fileUrl = pathToFileURL(resolvedPath).href;
const mod = await import(fileUrl);
const candidateFn = mod.default ?? mod.lintRule ?? mod.linter ?? mod.lint;
if (typeof candidateFn !== "function") {
console.error(
`⚠️ [linter] 自定义校验器 "${resolvedPath}" 未导出标准函数 (default / lintRule),已安全降级至内置校验器。`
);
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
// 执行期安全包装器:捕获用户自定义函数在运行期间可能抛出的任何未捕获异常
const safeLinter: RuleLinterFn = async (rule: RuleLintTarget, context?: RuleLintContext): Promise<RuleLintResult> => {
try {
const result = await candidateFn(rule, context);
if (result && typeof result === "object" && typeof result.score === "number" && Array.isArray(result.issues)) {
return result;
}
console.error(`⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。`);
return builtinRuleLinter(rule);
} catch (runtimeErr) {
console.error(`⚠️ [linter] 自定义校验器执行异常:`, runtimeErr);
return builtinRuleLinter(rule);
}
};
return {
name: nameOrPath,
type: "custom",
filePath: resolvedPath,
linter: safeLinter
};
} catch (err: any) {
console.error(
`⚠️ [linter] 加载自定义校验器脚本 "${resolvedPath}" 失败(语法错误或依赖缺失: ${err?.message ?? err}),已自动安全降级至内置校验器。`
);
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
}
+94
View File
@@ -0,0 +1,94 @@
import type { LoadedLinter } from "./loader.js";
import type {
RuleLintBatchResult,
RuleLintContext,
RuleLintItemResult,
RuleLintResult,
RuleLintTarget
} from "./types.js";
export interface LintServiceOptions {
level?: "all" | "error" | "warning";
minScore?: number;
summary?: boolean;
}
export async function lintSingleRule(
rule: RuleLintTarget,
loadedLinter: LoadedLinter,
context?: RuleLintContext
): Promise<RuleLintItemResult> {
const result = await loadedLinter.linter(rule, context);
return {
ruleId: rule.id,
ruleCode: rule.code,
ruleName: rule.name,
score: result.score,
passed: result.passed,
issues: result.issues,
description: rule.description
};
}
export async function lintRuleBatch(
rules: RuleLintTarget[],
loadedLinter: LoadedLinter,
context?: RuleLintContext,
options?: LintServiceOptions
): Promise<RuleLintBatchResult> {
const minScoreThreshold = options?.minScore ?? 0;
const levelFilter = options?.level ?? "all";
const itemResults: RuleLintItemResult[] = [];
let totalScoreSum = 0;
for (const rule of rules) {
const rawItem = await lintSingleRule(rule, loadedLinter, context);
totalScoreSum += rawItem.score;
// 根据 level 进行过滤
let filteredIssues = rawItem.issues;
if (levelFilter === "error") {
filteredIssues = rawItem.issues.filter((i) => i.level === "error");
} else if (levelFilter === "warning") {
filteredIssues = rawItem.issues.filter((i) => i.level === "warning" || i.level === "error");
}
const itemPassed = filteredIssues.every((i) => i.level !== "error");
if (options?.summary) {
// 总结模式:只记录有问题的规则项
if (filteredIssues.length > 0) {
itemResults.push({
...rawItem,
passed: itemPassed,
issues: filteredIssues
});
}
} else {
itemResults.push({
...rawItem,
passed: itemPassed,
issues: filteredIssues
});
}
}
const totalRules = rules.length;
const overallScore = totalRules === 0 ? 100 : Math.round(totalScoreSum / totalRules);
const issueCount = itemResults.filter((r) => r.issues.length > 0).length;
const healthyCount = totalRules - issueCount;
const passed = overallScore >= minScoreThreshold && itemResults.every((r) => r.passed);
return {
linter: loadedLinter.name,
linterType: loadedLinter.type,
totalRules,
healthyCount,
issueCount,
overallScore,
passed,
issues: itemResults
};
}
+61
View File
@@ -0,0 +1,61 @@
import { z } from "zod";
export const RuleLintIssueSchema = z.object({
level: z.enum(["error", "warning", "info"]),
code: z.string(),
message: z.string(),
snippet: z.string().optional(),
suggestion: z.string().optional()
});
export const RuleLintResultSchema = z.object({
score: z.number().min(0).max(100),
passed: z.boolean(),
issues: z.array(RuleLintIssueSchema)
});
export const RuleLintItemResultSchema = z.object({
ruleId: z.string().optional(),
ruleCode: z.string().optional(),
ruleName: z.string().optional(),
score: z.number().min(0).max(100),
passed: z.boolean(),
issues: z.array(RuleLintIssueSchema),
description: z.string().optional()
});
export const RuleLintBatchResultSchema = z.object({
linter: z.string(),
linterType: z.enum(["builtin", "custom"]),
totalRules: z.number(),
healthyCount: z.number(),
issueCount: z.number(),
overallScore: z.number().min(0).max(100),
passed: z.boolean(),
issues: z.array(RuleLintItemResultSchema)
});
export type RuleLintIssue = z.infer<typeof RuleLintIssueSchema>;
export type RuleLintResult = z.infer<typeof RuleLintResultSchema>;
export type RuleLintItemResult = z.infer<typeof RuleLintItemResultSchema>;
export type RuleLintBatchResult = z.infer<typeof RuleLintBatchResultSchema>;
export interface RuleLintTarget {
id?: string;
code?: string;
name?: string;
description: string;
scope?: string;
strictness?: string;
}
export interface RuleLintContext {
corpId?: string;
versionNumber?: number;
allRules?: RuleLintTarget[];
}
export type RuleLinterFn = (
rule: RuleLintTarget,
context?: RuleLintContext
) => Promise<RuleLintResult> | RuleLintResult;
@@ -0,0 +1,51 @@
import { pinyin } from "pinyin-pro";
import type { MaterialAttachmentPlan, MaterialDocument, MaterialField } from "./types.js";
import type { ZipEntry } from "./validate.js";
function keyFromLabel(value: string): string {
const label = value.replace(/^\d+[\s.\-_—]*/, "").trim();
const parts = pinyin(label, { toneType: "none", type: "all", nonZh: "consecutive" })
.map((item: any) => item.pinyin ? item.pinyin : String(item.origin).toLowerCase().replace(/[^a-z0-9]+/g, ""))
.filter(Boolean);
return parts.join("") || "attachments";
}
export function buildAttachmentPlans(entries: ZipEntry[], documents: Array<{ document: MaterialDocument; laborNames: string[] }>): MaterialAttachmentPlan[] {
return documents.map(({ document, laborNames }) => {
const plan: MaterialAttachmentPlan = { documentId: document.documentId, categoryFields: [], personAttachments: {} };
for (const entry of entries) {
if (entry.fileName === "信息表.xlsx") continue;
const segments = entry.fileName.split("/");
if (segments[0] !== document.documentId || segments.length < 2) continue;
const add = (list: Array<{ key: string; label: string; entries: any[] }>, label: string) => {
const clean = label.replace(/^\d+[\s.\-_—]*/, "");
const item = list.find((value) => value.label === clean) ?? { key: clean === "附件" ? "attachments" : keyFromLabel(clean), label: clean, entries: [] };
if (!list.includes(item)) list.push(item);
item.entries.push({ fileName: entry.fileName, path: entry.fileName, size: entry.uncompressedSize });
};
if (segments.length === 2) add(plan.categoryFields, "附件");
else if (laborNames.includes(segments[1]!)) {
const list = plan.personAttachments[segments[1]!] ?? (plan.personAttachments[segments[1]!] = []);
add(list, segments.length === 3 ? "附件" : segments[2]!);
} else add(plan.categoryFields, segments[1]!);
}
return plan;
});
}
export function injectAttachmentPlan(document: MaterialDocument, plan: MaterialAttachmentPlan, uploaded: Map<string, unknown[]>): MaterialDocument {
const clone = structuredClone(document);
const lookup = (path: string) => uploaded.get(path) ?? [];
for (const category of plan.categoryFields) {
const value = category.entries.flatMap((entry) => lookup(entry.path));
clone.fields.push({ key: category.key, label: category.label, type: "ATTACHMENT", value });
}
const list = clone.fields.find((item) => item.key === "daoshi_list" && item.type === "LIST");
if (list && Array.isArray(list.value)) {
for (const row of list.value as MaterialField[][]) {
const name = row.find((item) => item.key === "name")?.value;
for (const category of plan.personAttachments[String(name)] ?? []) row.push({ key: category.key, label: category.label, type: "ATTACHMENT", value: category.entries.flatMap((entry) => lookup(entry.path)) });
}
}
return clone;
}
+6
View File
@@ -0,0 +1,6 @@
export * from "./types.js";
export * from "./signature.js";
export * from "./validate.js";
export * from "./parse.js";
export * from "./attachments.js";
export * from "./service.js";
@@ -0,0 +1,29 @@
import ExcelJS from "exceljs";
import { describe, expect, test } from "bun:test";
import { previewMaterialPack } from "./service.js";
import { signWebhookPayload } from "./signature.js";
async function workbookBuffer() {
const workbook = new ExcelJS.Workbook();
const main = workbook.addWorksheet("会议");
main.addRow(["会议编号", "会议名称", "总金额", "申请日期"]);
main.addRow(["DOC-001", "测试单据", 100, "2026-09-03 12:00:00"]);
const labor = workbook.addWorksheet("劳务明细");
labor.addRow(["会议编号", "姓名", "劳务费用"]);
labor.addRow(["DOC-001", "张三", 100]);
return Buffer.from(await workbook.xlsx.writeBuffer());
}
describe("Webhook material pack", () => {
test("previews official workbook shape without network access", async () => {
const result = await previewMaterialPack(await workbookBuffer(), "材料包.xlsx");
expect(result.documents).toHaveLength(1);
expect(result.documents[0]).toMatchObject({ documentId: "DOC-001", documentSN: "DOC-001" });
expect(result.documents[0]?.fields).toContainEqual(expect.objectContaining({ key: "daoshi_list", type: "LIST" }));
});
test("uses the confirmed timestamp.nonce.payload HMAC contract", () => {
expect(signWebhookPayload(1700000000, "nonce", { webhookId: "wh-1", value: 1 }, "secret"))
.toBe("d65d858afb6adc33dc640ebc6b259861c2b73ef0e6f0995ff822b41465fbfdf1");
});
});
+99
View File
@@ -0,0 +1,99 @@
import ExcelJS from "exceljs";
import { MaterialPackValidationError, type MaterialDocument, type MaterialField } from "./types.js";
type Parsed = { document: MaterialDocument; laborNames: string[] };
function field(key: string, label: string, type: string, value: unknown): MaterialField {
return { key, label, type, value };
}
function text(key: string, label: string, value: unknown) {
return field(key, label, "TEXT", value == null ? "" : String(value));
}
function amount(key: string, label: string, value: unknown) {
return field(key, label, "AMOUNT", typeof value === "number" ? { amount: value, currency: "CNY" } : null);
}
function dateValue(value: unknown): string | null {
if (value instanceof Date) return value.toISOString();
if (typeof value === "string" && value.trim()) return value.trim();
return null;
}
function startTimeValue(value: unknown): number | null {
if (value instanceof Date) return Math.floor(value.getTime() / 1000);
if (typeof value === "string" && value.trim()) {
const timestamp = Date.parse(value.trim().replace(" ", "T"));
if (Number.isFinite(timestamp)) return Math.floor(timestamp / 1000);
}
return null;
}
function headerMap(sheet: ExcelJS.Worksheet): Map<string, number> {
const map = new Map<string, number>();
sheet.getRow(1).eachCell((cell, index) => map.set(String(cell.value ?? "").trim(), index));
return map;
}
function cell(row: ExcelJS.Row, map: Map<string, number>, name: string): unknown {
const index = map.get(name);
return index ? row.getCell(index).value : undefined;
}
function buildMainFields(row: ExcelJS.Row, map: Map<string, number>): MaterialField[] {
const specs: Array<[string, string, string]> = [
["会议编号", "meeting_id", "TEXT"], ["会议名称", "meeting_name", "TEXT"], ["状态", "status", "TEXT"],
["总金额", "total_amount", "AMOUNT"], ["税前劳务总额", "pretax_labor_total", "AMOUNT"],
["报销事由", "reimbursement_reason", "TEXT"], ["po码", "po_code", "TEXT"], ["快递单号", "tracking_number", "TEXT"],
["申请日期", "application_date", "DATE"], ["更新日期", "updated_date", "DATE"]
];
return specs.flatMap(([label, key, type]) => {
const value = cell(row, map, label);
if (value == null || value === "") return [];
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))];
});
}
function buildDetailFields(row: ExcelJS.Row, map: Map<string, number>, specs: Array<[string, string, string]>): MaterialField[] {
return specs.flatMap(([label, key, type]) => {
const value = cell(row, map, label);
if (value == null || value === "") return [];
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))];
});
}
const laborSpecs: Array<[string, string, string]> = [["姓名", "name", "TEXT"], ["身份证号码", "id_number", "TEXT"], ["手机号", "phone", "TEXT"], ["劳务费用", "labor_fee", "AMOUNT"], ["税前费用", "pretax_fee", "AMOUNT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["联行号", "bank_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"]];
const expenseSpecs: Array<[string, string, string]> = [["报销金额", "reimbursement_amount", "AMOUNT"], ["费用类型", "expense_type", "TEXT"], ["发生时间", "occurrence_time", "DATE"], ["收款人", "payee", "TEXT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["支行行号", "branch_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"], ["费用说明", "expense_description", "TEXT"]];
export async function parseMaterialWorkbook(buffer: Uint8Array): Promise<Parsed[]> {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.load(Buffer.from(buffer) as any);
if (!workbook.worksheets.length) throw new MaterialPackValidationError(["信息表没有任何 Sheet"]);
const sheets = workbook.worksheets;
const mainSheet = sheets[0]!;
const maps = sheets.map(headerMap);
const mainMap = maps[0]!;
const idColumn = mainMap.get("会议编号") ?? 1;
const mainRows = (mainSheet.getRows(2, mainSheet.rowCount) ?? []).filter((row) => row.getCell(idColumn).value != null && row.getCell(idColumn).value !== "");
const ids = new Set<string>();
const parsed: Parsed[] = mainRows.map((row) => {
const id = String(row.getCell(idColumn).value).trim();
if (!id) throw new MaterialPackValidationError(["主表会议编号不能为空"]);
if (ids.has(id)) throw new MaterialPackValidationError([`主表会议编号重复: ${id}`]);
ids.add(id);
const apply = cell(row, mainMap, "申请日期");
const laborSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("姓名"));
const expenseSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("报销金额"));
const laborMap = laborSheet ? headerMap(laborSheet) : undefined;
const expenseMap = expenseSheet ? headerMap(expenseSheet) : undefined;
const laborRows = (laborSheet?.getRows(2, laborSheet.rowCount) ?? []).filter((r) => String(cell(r, laborMap!, "会议编号") ?? "").trim() === id);
const expenseRows = (expenseSheet?.getRows(2, expenseSheet.rowCount) ?? []).filter((r) => String(cell(r, expenseMap!, "会议编号") ?? "").trim() === id);
const laborNames = laborRows.map((r) => String(cell(r, headerMap(laborSheet!), "姓名") ?? "").trim()).filter(Boolean);
const fields = buildMainFields(row, mainMap);
if (laborRows.length) fields.push({ key: "daoshi_list", label: "导师列表", type: "LIST", value: laborRows.map((r) => buildDetailFields(r, laborMap!, laborSpecs)) });
if (expenseRows.length) fields.push({ key: "mingxi_list", label: "明细列表", type: "LIST", value: expenseRows.map((r) => buildDetailFields(r, expenseMap!, expenseSpecs)) });
return { laborNames, document: { type: "document", documentId: id, documentSN: id, startTime: startTimeValue(apply), fields } };
});
return parsed;
}
+71
View File
@@ -0,0 +1,71 @@
import { readFileSync } from "node:fs";
import { webhookHeaders } from "./signature.js";
import { buildAttachmentPlans, injectAttachmentPlan } from "./attachments.js";
import { parseMaterialWorkbook } from "./parse.js";
import { extractZipEntry, readZipEntries, validatePackEntries, type ZipEntry } from "./validate.js";
import type { MaterialPackPreview, MaterialPackPushResult } from "./types.js";
function webhookInfo(url: string): { baseUrl: string; webhookId: string } {
const parsed = new URL(url);
const match = parsed.pathname.match(/\/webhook\/([^/]+)/);
if (!match) throw new Error("Webhook URL 必须包含 /webhook/{webhookId}/document");
return { baseUrl: `${parsed.protocol}//${parsed.host}`, webhookId: match[1]! };
}
function isZip(buffer: Uint8Array, fileName: string): boolean {
return fileName.toLowerCase().endsWith(".zip") || (buffer[0] === 0x50 && buffer[1] === 0x4b && !fileName.toLowerCase().endsWith(".xlsx"));
}
async function prepare(fileBuffer: Uint8Array, fileName: string) {
let entries: ZipEntry[] = [];
let workbook = fileBuffer;
if (isZip(fileBuffer, fileName)) {
entries = await readZipEntries(fileBuffer);
validatePackEntries(entries);
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
if (!info) throw new Error("ZIP 根目录缺少信息表.xlsx");
workbook = await extractZipEntry(fileBuffer, info);
}
const parsed = await parseMaterialWorkbook(workbook);
const plans = buildAttachmentPlans(entries, parsed);
const documents = parsed.map((item) => item.document);
return { entries, parsed, plans, documents, fileBuffer };
}
export async function previewMaterialPack(fileBuffer: Uint8Array, fileName: string): Promise<MaterialPackPreview> {
const prepared = await prepare(fileBuffer, fileName);
return { warnings: [], documents: prepared.documents, attachmentPlan: prepared.plans };
}
export async function pushMaterialPack(fileBuffer: Uint8Array, fileName: string, config: { webhookUrl: string; secret: string }): Promise<MaterialPackPushResult> {
const prepared = await prepare(fileBuffer, fileName);
const { baseUrl, webhookId } = webhookInfo(config.webhookUrl);
const results: MaterialPackPushResult["results"] = [];
for (let index = 0; index < prepared.parsed.length; index += 1) {
const item = prepared.parsed[index]!;
const plan = prepared.plans[index]!;
const uploaded = new Map<string, unknown[]>();
for (const category of [...plan.categoryFields, ...Object.values(plan.personAttachments).flat()]) {
for (const entry of category.entries) {
const zipEntry = prepared.entries.find((candidate) => candidate.fileName === entry.path);
if (!zipEntry) continue;
const body = new FormData();
const attachment = await extractZipEntry(prepared.fileBuffer, zipEntry);
body.append("files", new File([new Uint8Array(attachment)], entry.fileName));
const response = await fetch(`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/attachments`, { method: "POST", headers: webhookHeaders({}, config.secret), body });
if (!response.ok) throw new Error(`附件上传失败 ${response.status}: ${await response.text()}`);
const json = await response.json() as { data?: unknown; attachments?: Array<{ data: unknown }> };
uploaded.set(entry.path, json.attachments?.map((value) => value.data) ?? (json.data === undefined ? [] : [json.data]));
}
}
const document = injectAttachmentPlan(item.document, plan, uploaded);
const response = await fetch(`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/document`, { method: "POST", headers: { "Content-Type": "application/json", ...webhookHeaders({ webhookId, ...document }, config.secret) }, body: JSON.stringify(document) });
if (!response.ok) throw new Error(`Webhook 单据推送失败 ${response.status}: ${await response.text()}`);
results.push({ documentId: document.documentId, document, pushResult: await response.json() });
}
return { warnings: [], results };
}
export function readMaterialPackFile(filePath: string): { fileBuffer: Buffer; fileName: string } {
return { fileBuffer: readFileSync(filePath), fileName: filePath.split(/[\\/]/).pop() ?? "material-pack.zip" };
}
@@ -0,0 +1,18 @@
import { createHmac, randomBytes } from "node:crypto";
export function signWebhookPayload(timestamp: number, nonce: string, payload: unknown, secret: string): string {
return createHmac("sha256", secret)
.update(`${timestamp}.${nonce}.${JSON.stringify(payload)}`)
.digest("hex");
}
export function webhookHeaders(payload: unknown, secret: string): Record<string, string> {
const timestamp = Math.floor(Date.now() / 1000);
const nonce = randomBytes(16).toString("hex");
return {
Authorization: `Bearer ${secret}`,
"x-webhook-signature": signWebhookPayload(timestamp, nonce, payload, secret),
"x-webhook-timestamp": String(timestamp),
"x-webhook-nonce": nonce
};
}
+44
View File
@@ -0,0 +1,44 @@
export type MaterialField = {
key: string;
label: string;
type: string;
value: unknown;
};
export type MaterialDocument = {
type: "document";
documentId: string;
documentSN: string;
startTime: number | null;
fields: MaterialField[];
};
export type MaterialAttachmentEntry = {
fileName: string;
size: number;
path: string;
};
export type MaterialAttachmentPlan = {
documentId: string;
categoryFields: Array<{ key: string; label: string; entries: MaterialAttachmentEntry[] }>;
personAttachments: Record<string, Array<{ key: string; label: string; entries: MaterialAttachmentEntry[] }>>;
};
export type MaterialPackPreview = {
warnings: string[];
documents: MaterialDocument[];
attachmentPlan: MaterialAttachmentPlan[];
};
export type MaterialPackPushResult = {
warnings: string[];
results: Array<{ documentId: string; document: MaterialDocument; pushResult: unknown }>;
};
export class MaterialPackValidationError extends Error {
constructor(public readonly errors: string[], public readonly warnings: string[] = []) {
super(`材料包校验失败:${errors.length} 个错误`);
this.name = "MaterialPackValidationError";
}
}
@@ -0,0 +1,77 @@
import yauzl from "yauzl";
import iconv from "iconv-lite";
import { MaterialPackValidationError } from "./types.js";
export const MATERIAL_PACK_LIMITS = { maxEntries: 1000, maxTotalSize: 500 * 1024 * 1024, maxCompressionRatio: 150 };
export type ZipEntry = { fileName: string; uncompressedSize: number; compressedSize: number; raw: unknown };
export async function readZipEntries(buffer: Uint8Array): Promise<ZipEntry[]> {
return new Promise((resolve, reject) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true }, (openError: Error | null, zipFile: any) => {
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
const entries: ZipEntry[] = [];
zipFile.readEntry();
zipFile.on("entry", (entry: any) => {
const fileName = decodeZipEntryName(entry);
if (!fileName.endsWith("/") && !isJunk(fileName)) {
entries.push({ fileName, uncompressedSize: entry.uncompressedSize, compressedSize: entry.compressedSize, raw: entry });
}
zipFile.readEntry();
});
zipFile.on("end", () => resolve(entries));
zipFile.on("error", reject);
});
});
}
function decodeZipEntryName(entry: any): string {
if (entry.fileNameUTF8 || (entry.generalPurposeBitFlag & 0x800)) return entry.fileNameUTF8 ?? entry.fileName;
const raw = Buffer.from(String(entry.fileName), "binary");
const utf8 = raw.toString("utf8");
if (utf8.includes("\uFFFD") || /[\u0080-\u00FF]/.test(utf8)) {
const gbk = iconv.decode(raw, "gbk");
if (!gbk.includes("\uFFFD")) return gbk;
}
return utf8;
}
export function isJunk(name: string): boolean {
const base = name.split("/").pop() ?? "";
return name.split("/").includes("__MACOSX") || base === ".DS_Store" || base.startsWith("._") || base.startsWith(".~") || base.startsWith("~$");
}
export function validatePackEntries(entries: ZipEntry[]): void {
const errors: string[] = [];
if (entries.length > MATERIAL_PACK_LIMITS.maxEntries) errors.push(`文件数超过 ${MATERIAL_PACK_LIMITS.maxEntries}`);
const total = entries.reduce((sum, entry) => sum + entry.uncompressedSize, 0);
if (total > MATERIAL_PACK_LIMITS.maxTotalSize) errors.push("解压后总大小超过 500MB");
for (const entry of entries) {
if (entry.fileName.startsWith("/") || entry.fileName.split("/").includes("..")) errors.push(`存在不安全路径: ${entry.fileName}`);
if (entry.compressedSize > 0 && entry.uncompressedSize / entry.compressedSize > MATERIAL_PACK_LIMITS.maxCompressionRatio) errors.push(`压缩比超过 150: ${entry.fileName}`);
}
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
if (!info) errors.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");
if (entries.some((entry) => entry.fileName.toLowerCase().endsWith(".zip"))) errors.push("不允许嵌套 ZIP");
if (errors.length) throw new MaterialPackValidationError(errors);
}
export function extractZipEntry(buffer: Uint8Array, target: ZipEntry): Promise<Buffer> {
return new Promise((resolve, reject) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true }, (openError: Error | null, zipFile: any) => {
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
zipFile.readEntry();
zipFile.on("entry", (entry: any) => {
if (decodeZipEntryName(entry) !== target.fileName) return zipFile.readEntry();
zipFile.openReadStream(entry, (error: Error | null, stream: any) => {
if (error || !stream) return reject(error ?? new Error(`无法读取 ${target.fileName}`));
const chunks: Buffer[] = [];
stream.on("data", (chunk: Buffer) => chunks.push(chunk));
stream.on("end", () => resolve(Buffer.concat(chunks)));
stream.on("error", reject);
});
});
zipFile.on("error", reject);
});
});
}
+163
View File
@@ -0,0 +1,163 @@
import { describe, expect, test, afterEach } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
parseLocalRulesContent,
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets
} from "./rules-local.js";
import { findSealTool } from "./tools.js";
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("rules-local workspace", () => {
test("parses wrapped rules object", () => {
const raw = JSON.stringify({
corpId: "corp-1",
source: "draft",
rules: [
{ code: 1, description: "餐饮发票必须提供水单", scope: "MEAL", strictness: "MUST_FOLLOW" },
{ code: 2, description: "单张发票金额不得超标", scope: "ALL" }
]
});
const parsed = parseLocalRulesContent(raw);
expect(parsed.rules.length).toBe(2);
expect(parsed.meta.corpId).toBe("corp-1");
expect(parsed.meta.source).toBe("draft");
expect(parsed.rules[0]!.description).toBe("餐饮发票必须提供水单");
expect(parsed.rules[0]!.strictness).toBe("MUST_FOLLOW");
expect(parsed.rules[1]!.strictness).toBe("MUST_FOLLOW"); // default
});
test("parses raw rules array", () => {
const raw = JSON.stringify([
{ description: "打车必须备注起止地点", scope: "TAXI" }
]);
const parsed = parseLocalRulesContent(raw);
expect(parsed.rules.length).toBe(1);
expect(parsed.rules[0]!.description).toBe("打车必须备注起止地点");
expect(parsed.rules[0]!.code).toBe(1);
});
test("rejects invalid format or empty description", () => {
expect(() => parseLocalRulesContent("not-json")).toThrow("JSON 解析失败");
expect(() => parseLocalRulesContent(JSON.stringify({ other: 123 }))).toThrow("本地规则文件格式错误");
expect(() => parseLocalRulesContent(JSON.stringify([{ code: 1 }]))).toThrow("缺少有效的 'description'");
});
test("saves and loads local rules file accurately", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-rules-test-"));
tempDirs.push(dir);
const filePath = join(dir, "sub", "rules.json");
const savedPath = saveLocalRulesFile(filePath, {
corpId: "test-corp",
source: "version:5",
rules: [
{ code: 10, description: "酒店住宿必须提供明细清单", scope: "HOTEL", strictness: "MUST_FOLLOW" }
]
});
expect(savedPath).toBe(filePath);
const loaded = loadLocalRulesFile(filePath);
expect(loaded.rules.length).toBe(1);
expect(loaded.meta.corpId).toBe("test-corp");
expect(loaded.rules[0]!.code).toBe(10);
expect(loaded.rules[0]!.description).toBe("酒店住宿必须提供明细清单");
});
test("converts local rules to lint targets", () => {
const targets = localRulesToLintTargets([
{ code: 1, description: "规则一", name: "R1" },
{ code: "0002", description: "规则二" },
{ description: "规则三" }
]);
expect(targets[0]!.code).toBe("#0001");
expect(targets[0]!.name).toBe("R1");
expect(targets[1]!.code).toBe("#0002");
expect(targets[2]!.code).toBe("#0003");
});
});
describe("rules-local offline lint tool integration", () => {
test("lints local file directly with 0 network calls and high score", async () => {
const dir = mkdtempSync(join(tmpdir(), "seal-lint-test-"));
tempDirs.push(dir);
const filePath = join(dir, "clean-rules.json");
saveLocalRulesFile(filePath, {
corpId: "test-corp",
rules: [
{
code: 1,
description: "单张发票金额超过500元时,必须提供经办人签字的费用明细水单与消费清单。",
scope: "MEAL",
strictness: "MUST_FOLLOW"
}
]
});
const lintTool = findSealTool("seal_approval_rules_lint")!;
expect(lintTool).toBeDefined();
const result = await lintTool.handler(
null as any,
{ file: filePath } as any,
{ corp: { id: "test-corp" } } as any
) as any;
expect(result.totalRules).toBe(1);
expect(result.passed).toBe(true);
expect(result.overallScore).toBe(100);
});
test("detects vague wording in local rules file and enforces minScore gate", async () => {
const dir = mkdtempSync(join(tmpdir(), "seal-lint-test-"));
tempDirs.push(dir);
const filePath = join(dir, "vague-rules.json");
saveLocalRulesFile(filePath, {
corpId: "test-corp",
rules: [
{
code: 1,
description: "金额适当即可,视情况而定。",
scope: "ALL"
}
]
});
const lintTool = findSealTool("seal_approval_rules_lint")!;
const result = await lintTool.handler(
null as any,
{ file: filePath } as any,
{ corp: { id: "test-corp" } } as any
) as any;
expect(result.totalRules).toBe(1);
expect(result.overallScore).toBeLessThan(100);
expect(result.issues[0].issues.some((i: any) => i.code === "VAGUE_WORD")).toBe(true);
// minScore enforcement
await expect(
lintTool.handler(
null as any,
{ file: filePath, minScore: 95 } as any,
{ corp: { id: "test-corp" } } as any
)
).rejects.toThrow("Linter 质量门禁未通过");
});
});
+153
View File
@@ -0,0 +1,153 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import type { RuleLintTarget } from "./linter/types.js";
export interface LocalRuleItem {
id?: string;
code?: number | string;
name?: string;
description: string;
scope?: string;
strictness?: string;
status?: string;
[key: string]: unknown;
}
export interface LocalRulesPayload {
corpId?: string;
source?: string;
versionNumber?: number;
exportedAt?: string;
rulesCount?: number;
rules: LocalRuleItem[];
}
/**
* Parses raw local rule content (JSON array or object with `rules` array)
* and normalizes them into a consistent structure.
*/
export function parseLocalRulesContent(rawText: string): {
rules: LocalRuleItem[];
meta: Omit<LocalRulesPayload, "rules">;
} {
let parsed: unknown;
try {
parsed = JSON.parse(rawText);
} catch (err) {
throw new Error(`本地规则文件 JSON 解析失败: ${err instanceof Error ? err.message : String(err)}`);
}
if (Array.isArray(parsed)) {
return {
rules: normalizeRuleItems(parsed),
meta: {
rulesCount: parsed.length
}
};
}
if (parsed && typeof parsed === "object") {
const obj = parsed as Record<string, unknown>;
const rawRules = Array.isArray(obj.rules) ? obj.rules : undefined;
if (!rawRules) {
throw new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象");
}
return {
rules: normalizeRuleItems(rawRules),
meta: {
corpId: typeof obj.corpId === "string" ? obj.corpId : undefined,
source: typeof obj.source === "string" ? obj.source : undefined,
versionNumber: typeof obj.versionNumber === "number" ? obj.versionNumber : undefined,
exportedAt: typeof obj.exportedAt === "string" ? obj.exportedAt : undefined,
rulesCount: rawRules.length
}
};
}
throw new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象");
}
function normalizeRuleItems(items: unknown[]): LocalRuleItem[] {
return items.map((item, idx) => {
if (!item || typeof item !== "object") {
throw new Error(`第 ${idx + 1} 条规则格式错误: 必须为对象`);
}
const r = item as Record<string, unknown>;
const description = typeof r.description === "string" ? r.description.trim() : "";
if (!description) {
throw new Error(`第 ${idx + 1} 条规则缺少有效的 'description' (规则描述) 字段`);
}
const code =
typeof r.code === "number" || typeof r.code === "string"
? r.code
: idx + 1;
return {
...r,
code,
description,
scope: typeof r.scope === "string" ? r.scope : "ALL",
strictness: typeof r.strictness === "string" ? r.strictness : "MUST_FOLLOW"
};
});
}
/**
* Loads a local rules file from path.
*/
export function loadLocalRulesFile(filePath: string): {
rules: LocalRuleItem[];
meta: Omit<LocalRulesPayload, "rules">;
resolvedPath: string;
} {
const resolved = resolve(filePath);
if (!existsSync(resolved)) {
throw new Error(`未找到本地规则文件: ${filePath} (${resolved})`);
}
const content = readFileSync(resolved, "utf8");
const parsed = parseLocalRulesContent(content);
return {
...parsed,
resolvedPath: resolved
};
}
/**
* Saves rules to a formatted JSON file.
*/
export function saveLocalRulesFile(
filePath: string,
data: LocalRulesPayload
): string {
const resolved = resolve(filePath);
mkdirSync(dirname(resolved), { recursive: true });
writeFileSync(resolved, `${JSON.stringify(data, null, 2)}\n`, "utf8");
return resolved;
}
/**
* Converts local rule items to linter targets.
*/
export function localRulesToLintTargets(rules: LocalRuleItem[]): RuleLintTarget[] {
return rules.map((r, idx) => {
let codeStr: string | undefined;
if (typeof r.code === "number") {
codeStr = `#${String(r.code).padStart(4, "0")}`;
} else if (typeof r.code === "string") {
codeStr = r.code.startsWith("#") ? r.code : `#${r.code}`;
} else {
codeStr = `#${String(idx + 1).padStart(4, "0")}`;
}
return {
id: r.id,
code: codeStr,
name: r.name,
description: r.description,
scope: r.scope,
strictness: r.strictness
};
});
}
+82
View File
@@ -235,6 +235,7 @@ describe("sealTools", () => {
"seal_whoami",
"seal_approval_search",
"seal_approval_context_get",
"seal_webhook_material_pack",
"seal_runs_search",
"seal_action"
]);
@@ -657,6 +658,47 @@ describe("sealTools", () => {
versionNumber: 16
});
});
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
const tool = sealTools.find((item) => item.name === "seal_deploy_hosecloud_configure");
expect(tool).toBeDefined();
const handler = tool!.handler as ToolHandler;
const client = fakeDeployClient();
// 1. Rejects custom environment without customApiUrl
await expect(
handler(
client,
{
apiKey: "test-ak",
apiSecret: "test-sk",
apiOrigin: "custom"
},
fakeContext()
)
).rejects.toThrow("自定义合思环境必须提供 customApiUrl");
// 2. Saves successfully with customApiUrl
const result = await handler(
client,
{
apiKey: "test-ak",
apiSecret: "test-sk",
apiOrigin: "custom",
customApiUrl: "https://dd2.hosecloud.com",
outboundName: "DingTalk AI Audit"
},
fakeContext()
) as { integration: { corporationId: string; apiOrigin: string; customApiUrl: string; outboundName: string } };
expect(result.integration).toMatchObject({
corporationId: "mock-hose-corp",
apiOrigin: "custom",
customApiUrl: "https://dd2.hosecloud.com",
outboundName: "DingTalk AI Audit"
});
});
});
function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
@@ -953,3 +995,43 @@ function primeHoseEnterpriseUrl(corpId: string, url: string) {
}
}));
}
function fakeDeployClient(): KyInstance {
let config: Record<string, unknown> = {
integrationSystem: "hosecloud",
integrations: []
};
return {
get: (_url: string) => ({
json: async () => config
}),
patch: (url: string, options?: { json?: any }) => {
if (url === "api/v1/agent/ai-approval/config") {
config = options?.json ?? config;
return {
json: async () => config
};
}
return {
json: async () => ({})
};
},
post: (url: string, options?: { json?: any }) => {
if (url === "api/hosecloud/corporation") {
return {
json: async () => ({ corporationId: "mock-hose-corp" })
};
}
if (url === "api/v1/agent/ai-approval/config") {
config = options?.json ?? config;
return {
json: async () => config
};
}
return {
json: async () => ({})
};
}
} as unknown as KyInstance;
}
+371 -20
View File
@@ -3,10 +3,19 @@ import { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "./api.js";
import { defaultSealUrl, getHoseEnterpriseUrl } from "../../core/auth/hose.js";
import { defaultSealUrl, getHoseEnterpriseUrl, probeHoseDomain } from "../../core/auth/hose.js";
import { CorpConfig } from "../../core/config/types.js";
import { loadGlobalConfig } from "../../core/config/loader.js";
import { createSealClientForToken } from "../../core/http/factory.js";
import { searchApprovalContent } from "./search.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "./linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "./rules-local.js";
import { previewMaterialPack, pushMaterialPack, readMaterialPackFile } from "./material-pack/index.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
@@ -315,7 +324,30 @@ export const sealTools = [
params: { ruleId: string; description?: string; scope?: string; strictness?: string }
) => {
const { ruleId, ...rest } = params;
return api.updateApprovalRule(client, ruleId, rest);
const result = await api.updateApprovalRule(client, ruleId, rest);
if (params.description) {
try {
const globalConfig = loadGlobalConfig();
if (globalConfig.lint?.enabled) {
const loaded = await loadRuleLinter(globalConfig.lint.activeLinter);
const lintResult = await lintSingleRule({ id: ruleId, description: params.description }, loaded);
if (lintResult.issues.length > 0) {
console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${lintResult.score}/100 (发现 ${lintResult.issues.length} 处潜在风险):`);
for (const issue of lintResult.issues) {
console.error(` • [${issue.level.toUpperCase()}] ${issue.message}${issue.snippet ? ` ("${issue.snippet}")` : ""}`);
if (issue.suggestion) {
console.error(` 👉 建议: ${issue.suggestion}`);
}
}
}
}
} catch {
// 容错降级:质检异常绝不阻断规则更新
}
}
return result;
}
},
{
@@ -412,6 +444,260 @@ export const sealTools = [
return rule;
}
},
{
name: "seal_approval_rules_lint",
description: "对 Seal 本地规则文件、草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",
parameters: z.object({
file: z.string().optional().describe("指定本地规则文件路径进行离线质检(支持 .json),0网络请求、不污染远端草稿"),
linter: z.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),
version: z.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),
code: z.string().optional().describe("按规则展示编号过滤(如 #0038)"),
ruleId: z.string().optional().describe("按规则 ID 过滤"),
minScore: z.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),
level: z.enum(["all", "error", "warning"]).default("all").describe("问题报告等级过滤"),
summary: z.boolean().optional().describe("为 true 时仅返回存在瑕疵/扣分的规则")
}),
handler: async (
client: KyInstance,
params: {
file?: string;
linter?: string;
version?: string;
code?: string;
ruleId?: string;
minScore?: number;
level?: "all" | "error" | "warning";
summary?: boolean;
},
context: ToolContext
) => {
let targets: RuleLintTarget[] = [];
let versionNumber: number | undefined;
if (params.file) {
const local = loadLocalRulesFile(params.file);
targets = localRulesToLintTargets(local.rules);
versionNumber = local.meta.versionNumber;
} else if (params.version) {
const versions = await api.listApprovalRuleVersions(client);
const versionNumberParsed = Number(params.version);
const version = isNaN(versionNumberParsed)
? params.version === "latest"
? versions[0]
: versions.find((v) => v.id === params.version)
: versions.find((v) => v.versionNumber === versionNumberParsed);
if (!version) {
throw new Error(`未找到指定的规则版本: ${params.version}`);
}
versionNumber = version.versionNumber;
targets = (version.rules ?? []).map((r, idx) => ({
id: (r as any).id ?? (r as any).runtimeId,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: (r as any).scope,
strictness: (r as any).strictness
}));
} else {
const draftData = await api.listApprovalRules(client);
targets = (draftData.rules ?? []).map((r, idx) => ({
id: r.id,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: r.scope,
strictness: r.strictness
}));
}
if (params.code) {
targets = targets.filter(
(r) => r.code === params.code || r.code?.replace(/[#\s]/g, "") === params.code?.replace(/[#\s]/g, "")
);
}
if (params.ruleId) {
targets = targets.filter((r) => r.id === params.ruleId || r.code === params.ruleId);
}
const globalConfig = loadGlobalConfig();
const linterNameOrPath = params.linter ?? globalConfig.lint?.activeLinter ?? "builtin";
const loadedLinter = await loadRuleLinter(linterNameOrPath);
const batchResult = await lintRuleBatch(
targets,
loadedLinter,
{ corpId: context?.corp?.id, versionNumber, allRules: targets },
{ minScore: params.minScore, level: params.level, summary: params.summary }
);
if (params.minScore && batchResult.overallScore < params.minScore) {
throw new Error(
`[Linter 质量门禁未通过] 综合评分 ${batchResult.overallScore} 低于要求的最低分 ${params.minScore} 分 (共发现 ${batchResult.issueCount} 条问题规则)。`
);
}
return batchResult;
}
},
{
name: "seal_approval_rules_pull",
description: "从 Seal 远端拉取草稿或指定版本规则,保存至本地规则文件(支持离线编辑与本地 Lint,绝不污染远端草稿)",
parameters: z.object({
version: z.string().optional().describe("指定拉取的历史发布版本号或 ID(如 16 或 latest),不传默认拉取当前草稿规则"),
out: z.string().optional().describe("保存的目标本地文件路径,默认为 ./rules.local.json")
}),
handler: async (
client: KyInstance,
params: {
version?: string;
out?: string;
},
context: ToolContext
) => {
const outPath = params.out ?? "./rules.local.json";
let rules: LocalRuleItem[] = [];
let source = "draft";
let versionNumber: number | undefined;
if (params.version) {
const versions = await api.listApprovalRuleVersions(client);
const versionNumberParsed = Number(params.version);
const targetVersion = isNaN(versionNumberParsed)
? params.version === "latest"
? versions[0]
: versions.find((v) => v.id === params.version)
: versions.find((v) => v.versionNumber === versionNumberParsed);
if (!targetVersion) {
throw new Error(`未找到指定的规则版本: ${params.version}`);
}
versionNumber = targetVersion.versionNumber;
source = `version:${versionNumber}`;
rules = (targetVersion.rules ?? []).map((r, idx) => ({
code: (r as any).code ? Number(String((r as any).code).replace(/^#/, "")) || idx + 1 : idx + 1,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: (r as any).scope ?? "ALL",
strictness: (r as any).strictness ?? "MUST_FOLLOW"
}));
} else {
const draftData = await api.listApprovalRules(client);
rules = (draftData.rules ?? []).map((r, idx) => ({
id: r.id,
code: r.code ?? idx + 1,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: r.scope ?? "ALL",
strictness: r.strictness ?? "MUST_FOLLOW",
status: r.status
}));
}
const savedPath = saveLocalRulesFile(outPath, {
corpId: context.corp.id,
source,
versionNumber,
exportedAt: new Date().toISOString(),
rulesCount: rules.length,
rules
});
return {
saved: true,
path: savedPath,
rulesCount: rules.length,
corpId: context.corp.id,
source,
versionNumber
};
}
},
{
name: "seal_approval_rules_push",
description: "将本地规则文件推送到远端草稿(本地调优通过后一键应用,支持直接发布为正式版本)",
parameters: z.object({
file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),
dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),
confirm: z.boolean().optional().describe("确认覆盖写入远端草稿"),
publish: z.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)")
}),
handler: async (
client: KyInstance,
params: {
file?: string;
dryRun?: boolean;
confirm?: boolean;
publish?: boolean;
versionName?: string;
},
context: ToolContext
) => {
const filePath = params.file ?? "./rules.local.json";
const local = loadLocalRulesFile(filePath);
const isConfirmed = params.confirm === true;
const isDryRun = params.dryRun ?? !isConfirmed;
const before = await api.listApprovalRules(client);
if (isDryRun) {
return {
corpId: context.corp.id,
dryRun: true,
localFile: local.resolvedPath,
localRulesCount: local.rules.length,
remoteDraftCount: before.rules.length,
willPublish: Boolean(params.publish),
message: "Preview mode. Use --yes or confirm=true to apply local rules to remote draft."
};
}
// Step 1: Clear existing draft rules
let deleted = 0;
for (const rule of before.rules) {
await api.deleteApprovalRule(client, rule.id);
deleted += 1;
}
// Step 2: Create new rules from local
const created: Array<{ id: string; description: string; code?: number }> = [];
for (const rule of local.rules) {
const strictness = rule.strictness?.toUpperCase()?.includes("SHOULD")
? "SHOULD_FOLLOW"
: rule.strictness?.toUpperCase()?.includes("SUGGEST")
? "SUGGESTION"
: "MUST_FOLLOW";
const newRule = await api.createApprovalRule(client, {
description: rule.description,
scope: rule.scope ?? "ALL",
strictness
});
created.push({ id: newRule.id, description: newRule.description, code: newRule.code });
}
// Step 3: Recode
await api.recodeApprovalRules(client);
// Step 4: Optional publish
let publishedVersion: unknown = undefined;
if (params.publish) {
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
publishedVersion = await api.publishApprovalRuleVersion(client, name);
}
return {
corpId: context.corp.id,
dryRun: false,
localFile: local.resolvedPath,
clearedDraftRules: deleted,
createdRules: created.length,
published: publishedVersion ?? false
};
}
},
{
name: "seal_approval_documents_list",
description: "列出 Seal 审批知识文档",
@@ -1246,6 +1532,25 @@ export const sealTools = [
};
}
},
{
name: "seal_webhook_material_pack",
description: "将官方材料包格式本地校验、解析并通过 Seal 入站 Webhook 触发 AI 审批;preview 模式不联网",
parameters: z.object({
filePath: z.string().describe("材料包 ZIP 或 信息表.xlsx 文件路径"),
mode: z.enum(["preview", "push"]).default("preview"),
webhook: z.string().optional().describe("Webhook ID 或名称,push 模式必填")
}),
handler: async (client: KyInstance, params: { filePath: string; mode?: "preview" | "push"; webhook?: string }) => {
const input = readMaterialPackFile(params.filePath);
if (params.mode !== "push") return previewMaterialPack(input.fileBuffer, input.fileName);
if (!params.webhook) throw new Error("push 模式需要 webhook");
const integration = api.findWebhookIntegration(await api.listWebhookIntegrations(client), params.webhook);
return pushMaterialPack(input.fileBuffer, input.fileName, {
webhookUrl: integration.incomingDocumentWebhook.url,
secret: integration.secret
});
}
},
{
name: "seal_approval_run_langfuse_bridge_get",
description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",
@@ -1354,28 +1659,28 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_requirements",
description: "获取合思出站发布所需配置字段与说明",
description: "获取 Seal AI 审批发布到合思费控所需配置字段与说明",
parameters: z.object({}),
handler: async () => {
return {
input: "JSON via --json '{\"apiKey\":\"...\",\"apiSecret\":\"...\",\"mode\":\"assisted\"}'",
questions: [
{ field: "apiOrigin", prompt: "使用哪一种合思版本或 API 环境?(production/custom)", required: true, default: "production" },
{ field: "customApiUrl", prompt: "自定义环境的 API 地址是什么?", requiredWhen: "apiOrigin=custom" },
{ field: "apiOrigin", prompt: "使用哪一种合思版本或 API 环境?(production/custom,未指定时自动探测)", required: false, default: "production" },
{ field: "customApiUrl", prompt: "自定义环境的 API 地址是什么?(如专属私有云域名)", requiredWhen: "apiOrigin=custom" },
{ field: "apiKey", prompt: "合思 API Key(appKey)是什么?", required: true, secret: true },
{ field: "apiSecret", prompt: "合思 API Secret(appSecurity)是什么?", required: true, secret: true },
{ field: "mode", prompt: "使用全自动、半自动还是辅助审核?(fully_automatic/semi_automatic/assisted)", required: true, default: "assisted" },
{ field: "autoApprovalRate", prompt: "自动审批比例是多少?(0-100)", requiredWhen: "mode!=assisted" },
{ field: "rejectResubmitMethod", prompt: "驳回重提后从哪个节点继续?(node_default/to_ebot/from_start)" },
{ field: "autoApproveNodeNames", prompt: "哪些节点允许自动审批?(string[])" },
{ field: "outboundName", prompt: "合思出站消息名称是什么?", default: "SealAI 审批" }
{ field: "outboundName", prompt: "合思审批流节点消息名称是什么?", default: "SealAI 审批" }
]
};
}
},
{
name: "seal_deploy_hosecloud_list",
description: "列出当前已配置的合思集成列表",
description: "列出当前企业【Seal AI 审批发布到合思费控】的集成配置列表",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const config = await api.getApprovalStylePreferences(client);
@@ -1388,7 +1693,7 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_get",
description: "查询单个合思集成配置详情",
description: "查询【Seal AI 审批发布到合思费控】的单项配置详情",
parameters: z.object({
signKey: z.string().describe("合思集成 sign-key")
}),
@@ -1405,7 +1710,7 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_status",
description: "检查合思集成与多平台集成状态",
description: "检查【Seal AI 审批发布到合思费控】与多平台集成状态",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const status = await api.getSimulationIntegrationStatus(client);
@@ -1419,12 +1724,12 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_configure",
description: "校验合思凭据并保存合思集成配置",
description: "自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置",
parameters: z.object({
apiKey: z.string().describe("合思 API Key"),
apiSecret: z.string().describe("合思 API Secret"),
apiKey: z.string().describe("合思 API Key (appKey)"),
apiSecret: z.string().describe("合思 API Secret (appSecurity)"),
signKey: z.string().optional().describe("集成 signKey,不提供则自动生成"),
outboundName: z.string().optional().describe("出站消息名称"),
outboundName: z.string().optional().describe("出站消息名称(合思审批流节点中显示)"),
specificationId: z.string().optional(),
specificationName: z.string().optional(),
mode: z.enum(["fully_automatic", "semi_automatic", "assisted"]).default("assisted"),
@@ -1434,21 +1739,51 @@ export const sealTools = [
apiOrigin: z.string().default("production"),
customApiUrl: z.string().optional()
}),
handler: async (client: KyInstance, params: HosecloudConfigInput) => {
if (params.apiOrigin === "custom" && !params.customApiUrl) {
handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: ToolContext) => {
const apiKey = rawParams.apiKey ?? (rawParams as any).appKey;
const apiSecret = rawParams.apiSecret ?? (rawParams as any).appSecurity;
if (!apiKey || !apiSecret) {
throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
}
const params = { ...rawParams, apiKey, apiSecret };
let effectiveApiOrigin = params.apiOrigin ?? "production";
let effectiveCustomApiUrl = params.customApiUrl;
// 自动平台/域名探测:当未提供 customApiUrl 时,并发探测合思 6 大标准公共 SaaS 平台域名
if (!effectiveCustomApiUrl && effectiveApiOrigin !== "custom") {
try {
const probe = await probeHoseDomain(params.apiKey, params.apiSecret);
if (probe?.domain) {
if (probe.domain === "https://app.ekuaibao.com") {
effectiveApiOrigin = "production";
effectiveCustomApiUrl = undefined;
} else {
effectiveApiOrigin = "custom";
effectiveCustomApiUrl = probe.domain;
}
}
} catch {
// 探测失败时平滑降级,由后续后端校验处理
}
}
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
throw new Error("自定义合思环境必须提供 customApiUrl");
}
const corpResult = await api.getHosecloudCorporation(client, {
apiKey: params.apiKey,
apiSecret: params.apiSecret,
apiOrigin: params.apiOrigin,
customApiUrl: params.customApiUrl
apiOrigin: effectiveApiOrigin,
customApiUrl: effectiveCustomApiUrl
});
const config = await api.getApprovalStylePreferences(client);
const signKey = params.signKey ?? randomBytes(6).toString("hex");
const nextIntegration = {
type: "hosecloud",
...params,
apiOrigin: effectiveApiOrigin,
...(effectiveCustomApiUrl ? { customApiUrl: effectiveCustomApiUrl } : {}),
signKey,
corporationId: corpResult.corporationId
};
@@ -1461,6 +1796,10 @@ export const sealTools = [
integrationSystem: "hosecloud",
integrations: existing
});
console.error(`✓ 配置已保存 (signKey: ${signKey})`);
console.error(`👉 下一步操作:运行 \`seal-use deploy hosecloud sync ${signKey} --corp ${context.corp.id}\` 一键同步发布到合思审批流`);
return {
integration: redactIntegrationSecrets(nextIntegration)
};
@@ -1468,7 +1807,7 @@ export const sealTools = [
},
{
name: "seal_deploy_hosecloud_sync",
description: "同步合思出站消息配置并完成发布",
description: "一键将 Seal AI 审核配置同步发布到合思费控审批流",
parameters: z.object({
signKey: z.string().describe("合思集成 sign-key")
}),
@@ -1481,13 +1820,18 @@ export const sealTools = [
throw new Error(`未找到合思配置:${params.signKey}`);
}
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
const messageName = (integration as any).outboundName ?? "SealAI 审批";
const result = await api.syncHosecloudOutbound(client, {
signKey: params.signKey,
webhookUrl: `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(params.signKey)}`,
completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`,
messageName: (integration as any).outboundName ?? "SealAI 审批",
messageName,
mode: (integration as any).mode ?? "assisted"
});
console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`);
console.error(`👉 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${messageName}"。`);
return {
signKey: params.signKey,
synced: true,
@@ -1688,7 +2032,8 @@ const sealToolByName = new Map<string, SealTool>(
const mcpDirectToolNames = [
"seal_whoami",
"seal_approval_search",
"seal_approval_context_get"
"seal_approval_context_get",
"seal_webhook_material_pack"
] as const;
const sealActionNames = [
@@ -1701,6 +2046,9 @@ const sealActionNames = [
"seal_approval_rule_versions_list",
"seal_approval_rule_version_get",
"seal_approval_rule_get",
"seal_approval_rules_lint",
"seal_approval_rules_pull",
"seal_approval_rules_push",
"seal_approval_rule_version_publish",
"seal_approval_documents_list",
"seal_approval_document_get",
@@ -1758,6 +2106,9 @@ const sealActionAliases: Record<string, (typeof sealActionNames)[number]> = {
"rule.versions.list": "seal_approval_rule_versions_list",
"rule.version.get": "seal_approval_rule_version_get",
"rule.get": "seal_approval_rule_get",
"rule.lint": "seal_approval_rules_lint",
"rule.pull": "seal_approval_rules_pull",
"rule.push": "seal_approval_rules_push",
"rule.publish": "seal_approval_rule_version_publish",
"doc.list": "seal_approval_documents_list",
"doc.get": "seal_approval_document_get",
+25 -22
View File
@@ -75,6 +75,18 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
return;
}
if (method === "POST" && (pathname === "/shutdown" || pathname === "/api/shutdown")) {
sendJson(res, 200, {
success: true,
message: "Shutting down seal-use background daemon",
pid: process.pid
});
setTimeout(() => {
process.kill(process.pid, "SIGTERM");
}, 50);
return;
}
// 3. Command Execution Endpoint: POST /api/cli
if (method === "POST" && pathname === "/api/cli") {
const body = await parseJsonBody(req);
@@ -393,28 +405,19 @@ export function extractCorpId(
}
export async function parseJsonBody(req: IncomingMessage): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
let raw = "";
req.on("data", (chunk) => {
raw += chunk;
if (raw.length > 20 * 1024 * 1024) {
// 20MB limit
reject(new Error("Payload too large"));
}
});
req.on("end", () => {
if (!raw.trim()) {
resolve({});
return;
}
try {
resolve(JSON.parse(raw));
} catch (err) {
reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`));
}
});
req.on("error", reject);
});
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (raw.length > 20 * 1024 * 1024) {
throw new Error("Payload too large");
}
}
if (!raw.trim()) return {};
try {
return JSON.parse(raw);
} catch (err) {
throw new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`);
}
}
export function sendJson(res: ServerResponse, statusCode: number, data: unknown) {
+5 -2
View File
@@ -8,9 +8,12 @@ export type HttpServerOptions = {
silent?: boolean;
};
export const DEFAULT_HTTP_PORT = 8787;
export const DEFAULT_HTTP_HOST = "127.0.0.1";
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 8787);
const host = options.host ?? (process.env.HOST ? process.env.HOST : "127.0.0.1");
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
const server = createServer(async (req, res) => {
try {