Compare commits

..
41 Commits
Author SHA1 Message Date
gitea e716f069ed Release v0.7.1: Add approval-runs list alias, handle EPIPE, and improve summary hints
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 15:19:11 +08:00
gitea b998a0527e Add Chinese onboarding guidance and empty corps diagnostic
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 14:46:16 +08:00
gitea 7f3a4b0fe4 Update installer to use user-writable bin directory without sudo
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 14:36:58 +08:00
gitea f0d3477d69 Add one-line install script and quick installation guide
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 14:34:17 +08:00
gitea a7b09e8d9b Optimize release workflow to single-job Bun cross-compilation
Binaries / Build & Release Binaries (push) Has been cancelled
2026-08-25 14:27:01 +08:00
gitea 1c57950309 Tolerate detached HEAD during source mode update
Binaries / Verify (push) Has been cancelled
Binaries / Build linux-x64 (push) Has been cancelled
Binaries / Build macos-arm64 (push) Has been cancelled
Binaries / Build macos-x64 (push) Has been cancelled
Binaries / Build windows-x64 (push) Has been cancelled
Binaries / Publish release assets (push) Has been cancelled
2026-08-25 14:21:45 +08:00
gitea bf2bb3d87a Add embedded OpenAPI specification exporter subcommand
Binaries / Verify (push) Has been cancelled
Binaries / Build linux-x64 (push) Has been cancelled
Binaries / Build macos-arm64 (push) Has been cancelled
Binaries / Build macos-x64 (push) Has been cancelled
Binaries / Build windows-x64 (push) Has been cancelled
Binaries / Publish release assets (push) Has been cancelled
2026-08-25 14:19:29 +08:00
gitea f1380873e4 Add embedded skill exporter and mcp config subcommands and bump to v0.7.0 2026-08-25 14:17:12 +08:00
gitea ce06d8f600 Add GitHub Release self-update support for standalone binary 2026-08-25 13:54:29 +08:00
gitea c86ee6a235 Add dual-mode self-update and multi-target binary build 2026-08-25 13:51:53 +08:00
gitea 85ca31f4ad Refactor CLI runner into modular command handlers 2026-08-25 13:50:44 +08:00
gitea b109f3f49f Add runtime detection and unified mcp and probe CLI commands 2026-08-25 13:49:00 +08:00
gitea 551fb9177f Organize local project artifacts 2026-08-25 11:43:46 +08:00
gitea baab26bcda Route material pack batches to their own create endpoint
Material pack simulation uses POST /api/v1/simulation/create-material-pack-batch
with approvalCode/nodeId/runMode in the request body; keep the shared
create-batch payload for hosecloud single-number mode.

Verification: material pack create on xiezihao staging returns 200 and
ingests records (HY001/HY002, taskMode=simulation); 116 tests pass.
2026-08-24 18:27:55 +08:00
gitea 997f1f60ac Mirror real create-batch payload captured from staging console
The server derives approvalCode/nodeId/limit/startTime/endTime from the
request; the response params echo is normalized, not the request shape.
- send sourceSystem + thinkingDepthOverride "default" (按偏好设置)
- drop limit and server-derived fields from the request body
- keep material_pack payload free of hosecloud-specific fields

Verification: simulation create against xiezihao staging now succeeds
(200) and batch records appear with taskMode=simulation; 114 tests pass.
2026-08-24 18:16:51 +08:00
gitea 0e52a295ba Add simulation test batch creation and material package upload
Support the release loop against Seal simulation batches:
- simulation create (hosecloud specified single-number and material_pack
  modes; other collection modes reserved via rawParams passthrough)
- simulation list/get/templates/integrations/package-upload
- schema modeling from captured staging traffic, mode-scoped request params
- new MCP tools and OpenAPI paths; bump version to 0.6.0

Tests: bun run check, bun test (114 pass).
2026-08-24 18:10:05 +08:00
gitea 39de757042 Add rule code to list summaries and schemas 2026-08-19 10:59:34 +08:00
gitea f0522b72da Refine AGENTS.md for plugin layout 2026-08-13 14:36:34 +08:00
gitea c81511175d Ignore local Mimosa runtime state 2026-08-13 11:19:34 +08:00
gitea 8be627e1c6 Add configurable seal-home MCP toggle 2026-08-13 10:34:03 +08:00
gitea 883798b157 Mark plugin UI verification as manual 2026-08-12 14:41:34 +08:00
gitea 38610d3573 Add seal-home ZCode plugin packaging 2026-08-12 14:35:40 +08:00
gitea 0959cef1cc Add stateful and stateless enterprise selection 2026-08-12 11:38:25 +08:00
gitea d383b3aad8 Add customer feedback rule remediation workflow 2026-08-09 22:46:04 +08:00
gitea 32149762c9 Add Webhook integration CLI management 2026-08-07 15:53:46 +08:00
gitea 48d20a788f Fix Seal contact search and SSO errors 2026-08-05 18:48:52 +08:00
gitea 8435ed7fd9 feat(config): support provider field for seal source and display provider in corps list
- Add optional provider and providerName to NativeSealSourceSchema
- Extract provider from remote user/tenant in addSealCorp
- Output provider field in corps list and corps current commands
2026-07-31 09:57:19 +08:00
gitea 2ca45d935e Refine CLI service and align project metadata 2026-07-30 19:13:54 +08:00
gitea 802c32c6bd Refine CLI version flag alias parsing and test expectations 2026-07-29 22:28:38 +08:00
gitea ab440024b8 Refactor codebase architecture and add core auth/search unit tests 2026-07-29 22:27:16 +08:00
gitea f315fc7485 docs: fix install instructions to use npm link instead of bun link
- Replace incorrect 'bun link' with 'npm link' in public usage section
- Add explicit warning: do NOT use 'npm install -g .' for development (creates stale copy)
- Document symlink verification command
- Clarify that git pull is sufficient after npm link (no reinstall needed)
2026-07-29 18:40:35 +08:00
gitea ef115835ac feat(delegation): v0.4.2 - Hose SSO fallback for synced users in users delegation
- createDelegationForUser now detects hosecloud-synced users (provider != local)
- Falls back to Hose Provisional Auth → Seal SSO session exchange → delegation create
- Generates a true user-identity Seal delegation link without password reset
- Fixes name search to prefer exact match before falling back to first result
- Exports normalizeBaseUrl, defaultSealUrl, ensureHoseOpenapiToken, fetchHoseCloseApiToken
- Updates SKILL.md: documents users delegation hosecloud limitation and fallback behavior
2026-07-29 18:39:26 +08:00
gitea c0318df70b Add user search, activation, and automated delegation flow and bump version to 0.4.0
Binaries / Verify (push) Has been cancelled
Binaries / Build linux-x64 (push) Has been cancelled
Binaries / Build macos-arm64 (push) Has been cancelled
Binaries / Build windows-x64 (push) Has been cancelled
Binaries / Publish release assets (push) Has been cancelled
2026-07-29 17:24:22 +08:00
gitea 957cd2f70e Symlink skills/seal-home to .agents/skills/seal-home and add version metadata (v0.3.8)
Binaries / Verify (push) Has been cancelled
Binaries / Build linux-x64 (push) Has been cancelled
Binaries / Build macos-arm64 (push) Has been cancelled
Binaries / Build windows-x64 (push) Has been cancelled
Binaries / Publish release assets (push) Has been cancelled
2026-07-29 16:54:18 +08:00
gitea ae4653bb32 Add .agents/skills/seal-home
Binaries / Verify (push) Has been cancelled
Binaries / Build linux-x64 (push) Has been cancelled
Binaries / Build macos-arm64 (push) Has been cancelled
Binaries / Build windows-x64 (push) Has been cancelled
Binaries / Publish release assets (push) Has been cancelled
2026-07-29 16:49:36 +08:00
gitea a79d7516a5 Update seal-home skill documentation
Binaries / Verify (push) Has been cancelled
Binaries / Build linux-x64 (push) Has been cancelled
Binaries / Build macos-arm64 (push) Has been cancelled
Binaries / Build windows-x64 (push) Has been cancelled
Binaries / Publish release assets (push) Has been cancelled
2026-07-29 16:45:45 +08:00
gitea e7ebfcd16a Add system configuration endpoints support and bump version to 0.3.8 2026-07-29 16:41:15 +08:00
gitea 8b070cf956 Add user management and password reset support and bump version to 0.3.7 2026-07-29 16:38:57 +08:00
gitea 33ca5fcb4a Add delegation link support and bump version to 0.3.6 2026-07-29 16:31:10 +08:00
gitea 997ece006a Add Seal-native enterprise support 2026-07-08 15:22:31 +08:00
gitea 2611ce4c85 Add rules clear command 2026-07-08 15:22:04 +08:00
93 changed files with 43383 additions and 1523 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
../../skills/seal-home
+16 -67
View File
@@ -15,8 +15,8 @@ permissions:
contents: write
jobs:
verify:
name: Verify
build-and-release:
name: Build & Release Binaries
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -36,78 +36,27 @@ jobs:
- name: Test
run: bun test
build:
name: Build ${{ matrix.name }}
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
needs: verify
strategy:
fail-fast: false
matrix:
include:
- name: linux-x64
os: ubuntu-latest
ext: ""
- name: macos-arm64
os: macos-latest
ext: ""
- name: windows-x64
os: windows-latest
ext: ".exe"
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Compile CLI
shell: bash
- name: Compile multi-target binaries
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
run: |
mkdir -p dist/bin
bun build --compile --outfile "dist/bin/seal-home-${{ matrix.name }}${{ matrix.ext }}" src/cli.ts
node scripts/build-binary.mjs --all
- name: Package artifact
shell: bash
- name: Package release archives
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
run: |
sudo apt-get update && sudo apt-get install -y zip
cd dist/bin
if [[ "${{ matrix.os }}" == "windows-latest" ]]; then
7z a "seal-home-${{ matrix.name }}.zip" "seal-home-${{ matrix.name }}${{ matrix.ext }}"
else
tar -czf "seal-home-${{ matrix.name }}.tar.gz" "seal-home-${{ matrix.name }}${{ matrix.ext }}"
fi
tar -czf seal-home-linux-x64.tar.gz seal-home-linux-x64
tar -czf seal-home-linux-arm64.tar.gz seal-home-linux-arm64
tar -czf seal-home-darwin-x64.tar.gz seal-home-darwin-x64
tar -czf seal-home-darwin-arm64.tar.gz seal-home-darwin-arm64
zip -q seal-home-windows-x64.zip seal-home-windows-x64.exe
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: seal-home-${{ matrix.name }}
path: |
dist/bin/seal-home-${{ matrix.name }}.tar.gz
dist/bin/seal-home-${{ matrix.name }}.zip
if-no-files-found: error
release:
name: Publish release assets
if: startsWith(github.ref, 'refs/tags/v')
needs: build
runs-on: ubuntu-latest
steps:
- name: Download artifacts
uses: actions/download-artifact@v4
with:
path: release-assets
pattern: seal-home-*
merge-multiple: true
- name: Upload release assets
shell: bash
- name: Publish GitHub Release
if: startsWith(github.ref, 'refs/tags/v')
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --notes "Automated binary release for ${GITHUB_REF_NAME}."
gh release upload "${GITHUB_REF_NAME}" release-assets/* --repo "${GITHUB_REPOSITORY}" --clobber
gh release upload "${GITHUB_REF_NAME}" dist/bin/seal-home-* --repo "${GITHUB_REPOSITORY}" --clobber
+4
View File
@@ -5,7 +5,11 @@ node_modules/
tmp/*
!tmp/.gitkeep
dist/bin/
.mimosa/
# Local enterprise configs can contain credentials.
enterprises/*.json
!enterprises/example.*.json
# Local generated reports and exported deliverables.
.local/
+15
View File
@@ -0,0 +1,15 @@
{
"mcpServers": {
"seal-home": {
"type": "stdio",
"command": "node",
"args": [
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
],
"env": {
"SEAL_HOME_MCP_ENABLED": "${user_config.enable_mcp}"
},
"timeoutMs": 120000
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"name": "seal-home",
"version": "0.7.1",
"description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
},
"license": "MIT",
"skills": "skills",
"mcpServers": "./.mcp.json",
"userConfig": {
"enable_mcp": {
"type": "boolean",
"title": "启用 MCP 服务",
"description": "开启后向 Agent 暴露 seal_cli 工具;默认关闭。保存后重新连接该插件的 MCP 服务。",
"default": false
}
}
}
+6 -2
View File
@@ -4,7 +4,9 @@
This is a Bun + TypeScript toolkit for the `seal-home` CLI and optional MCP server. Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and tool logic is under `src/domains/seal/`.
Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in `openapi/`; bundled output is `dist/openapi.json`. Example enterprise configs are in `enterprises/example.*.json`; real configs must stay untracked. Project skills live under `skills/seal-home/`.
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares the plugin manifest, `.mcp.json` declares the optional MCP server (disabled by default), and the agent skill lives under `skills/seal-home/`. `.agents/skills/seal-home` is a symlink to `skills/seal-home` so workspace and Codex skill loading keep working.
Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in `openapi/`; bundled output is `dist/openapi.json`. Example enterprise configs are in `enterprises/example.*.json`; real configs must stay untracked.
## Build, Test, and Development Commands
@@ -12,10 +14,12 @@ Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in
- `bun run dev`: run `src/server.ts` with watch mode.
- `bun run start`: run the MCP server once.
- `bun run cli -- <args>`: execute CLI commands, such as `bun run cli version`.
- `bun run probe`: run the local connectivity/config probe.
- `bun run probe -- <corpId>`: run the local connectivity/config probe.
- `bun run check`: type-check with `tsc --noEmit`.
- `bun test`: run all colocated Bun tests.
- `bun run openapi:bundle`: rebuild `dist/openapi.json`.
- `bun run build:binary`: compile the standalone `seal-home` binary to `dist/bin/seal-home` (gitignored).
- `bun run build:plugin`: bundle the MCP server to `dist/mcp/server.js` (tracked, used by `.mcp.json`).
## Coding Style & Naming Conventions
+93 -35
View File
@@ -4,19 +4,38 @@ Bun + TypeScript CLI and optional local service for pulling Seal enterprise appr
The first provider is Hose/合思: `key`, `password`, `corpId`, `staffId`, and an optional Hose domain. The provider exchanges those credentials for a Seal enterprise session, then the Seal domain tools can read and maintain approval rules, approval documents, and approval style preferences.
`direct` is also available for later sources that already provide a Seal Bearer token.
Seal-native enterprise pages can be added with a Seal Bearer token. The older `direct` source remains available for existing configs that already provide a Seal Bearer token.
## Setup
## Quick Install (Standalone Binary)
No Node.js, Bun, or external runtime required. Run the one-line installer for macOS and Linux:
```bash
bun install
cp enterprises/example.hose.json enterprises/local.json
bun run check
bun run probe
bun run start
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-home/master/scripts/install.sh | bash
```
For an already-authenticated Seal source, copy `enterprises/example.direct.json` instead.
Or download the native binary directly from [GitHub Releases](https://github.com/yunyingk/seal-home/releases/latest):
- **macOS (Apple Silicon)**: `curl -fsSL https://github.com/yunyingk/seal-home/releases/latest/download/seal-home-darwin-arm64 -o /usr/local/bin/seal-home && chmod +x /usr/local/bin/seal-home`
- **macOS (Intel)**: `curl -fsSL https://github.com/yunyingk/seal-home/releases/latest/download/seal-home-darwin-x64 -o /usr/local/bin/seal-home && chmod +x /usr/local/bin/seal-home`
- **Linux (x86_64)**: `curl -fsSL https://github.com/yunyingk/seal-home/releases/latest/download/seal-home-linux-x64 -o /usr/local/bin/seal-home && chmod +x /usr/local/bin/seal-home`
- **Linux (ARM64)**: `curl -fsSL https://github.com/yunyingk/seal-home/releases/latest/download/seal-home-linux-arm64 -o /usr/local/bin/seal-home && chmod +x /usr/local/bin/seal-home`
- **Windows (x64)**: Download `seal-home-windows-x64.zip` from Releases and extract `seal-home-windows-x64.exe`.
After installation:
```bash
seal-home version # Check version
seal-home skill install # Install Agent skill to ~/.agents/skills/seal-home
seal-home mcp-config # Print .mcp.json snippet for Cursor / Claude Desktop / Codex
seal-home update # Future self-update directly from GitHub Release
```
## Source Setup & Development
For local development from source with Bun:
For an already-authenticated Seal-native source, use `seal-home corps add-seal` or copy `enterprises/example.seal.json`. Existing `direct` configs remain supported via `enterprises/example.direct.json`.
## Public Usage
@@ -28,21 +47,43 @@ Install the global CLI from a checkout:
git clone <repo-url>
cd seal-home
bun install
bun link
npm link
seal-home version
```
`npm link` creates a symlink from `/opt/homebrew/lib/node_modules/seal-home` → your local checkout. The `seal-home` binary on PATH then runs source files directly via bun — **no reinstall needed after editing source code**.
> ⚠️ **Do NOT use `npm install -g .`** for development. That copies files into the global node_modules directory and the copy becomes stale as soon as you edit the source. Always use `npm link` so edits take effect immediately.
To verify the symlink is in place (and not a stale copy):
```bash
ls -la $(dirname $(which seal-home))/../lib/node_modules/seal-home
# Should show: seal-home -> ../../../../Users/<you>/Code/seal-home
```
If it shows a plain directory instead of a symlink, re-run `npm link` from the repo root.
Create a user-level Hose enterprise config that works from any directory:
```bash
mkdir -p ~/.config/seal-home/enterprises
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-home auth diagnose
seal-home auth diagnose --corp <corpId>
seal-home tools list
```
`corps add-hose` verifies by default before writing the config. It uses the Hose OpenAPI credential response to derive the corporation ID, then checks provisional auth, Seal SSO, and Seal `whoami`. Pass `"force":true` or `"verify":false` only when you intentionally want to write a config that may fail later.
Create a user-level Seal-native enterprise config from an already signed-in Seal Home page:
```bash
seal-home corps add-seal --json '{"sealUrl":"https://tenant.staging.sealai.cc","token":"seal-bearer-token"}'
seal-home auth diagnose --corp tenant
```
`corps add-seal` verifies `/api/v1/auth/me` by default and writes the tenant slug, tenant ID, tenant name, and provider user ID into local config metadata. Pass `"force":true` or `"verify":false` only when writing an offline config intentionally.
For custom config locations, set `SEAL_HOME_ENTERPRISES_DIR` to a directory containing non-example `*.json` enterprise config files.
Update an existing checkout:
@@ -53,6 +94,8 @@ seal-home update
`seal-home update` runs `git pull --ff-only`, installs dependencies, and restarts the local service if it was running.
Because `npm link` makes the global command a symlink into your checkout, **updating the checkout is sufficient** — no reinstall step required. The symlink continues to point to the updated source.
Local enterprise config files are ignored by git:
```text
@@ -60,7 +103,20 @@ enterprises/*.json
!enterprises/example.*.json
```
The standard Codex skill lives at `skills/seal-home`. Install or copy that folder into a Codex skills directory when you want Codex to invoke the workflow as `$seal-home`.
The canonical plugin skill lives at `skills/seal-home`; `.agents/skills/seal-home` is a workspace symlink to the same files. Install or copy that folder into a Codex skills directory when you want Codex to invoke the workflow as `$seal-home`.
## ZCode Plugin
The repository is also a ZCode plugin. Install `seal-home` from the `yingqing-plugins` marketplace in **Settings → Plugin Management**, or add this repository as a local plugin directory while developing. The plugin provides the `skills/seal-home` skill and an optional MCP server.
The `seal_cli` MCP tool is disabled by default. Open the plugin detail page and enable **启用 MCP 服务** in the configuration section, then reconnect the plugin MCP server; this exposes the tool. When the option is off, the MCP process can complete the protocol handshake but does not register any tools. The tool accepts the same command syntax as the global CLI, including `version` and `seal-home version`.
For a standalone compiled CLI, build and run the binary from a checkout:
```bash
bun run build:binary
./dist/bin/seal-home version
```
## CLI
@@ -69,11 +125,14 @@ Use the CLI from skills, shell scripts, or agents. CLI intentionally keeps the f
```bash
seal-home version
seal-home config paths
seal-home config get
seal-home config mode stateless
seal-home config mode stateful --corp <corpId>
seal-home tools list
seal-home corps list
seal-home auth diagnose
seal-home approval-runs summary --date 2026-06-08 --timezone Asia/Shanghai
seal-home tool seal_approval_runs_summary --json '{"date":"2026-06-08","timezone":"Asia/Shanghai"}'
seal-home auth diagnose --corp <corpId>
seal-home approval-runs summary --corp <corpId> --date 2026-06-08 --timezone Asia/Shanghai
seal-home tool seal_approval_runs_summary --corp <corpId> --json '{"date":"2026-06-08","timezone":"Asia/Shanghai"}'
```
CLI output is JSON on stdout. Errors are written to stderr.
@@ -84,11 +143,18 @@ Enterprise config lookup:
- Otherwise `./enterprises` and `~/.config/seal-home/enterprises` are merged.
- User-level configs override same-ID configs from `./enterprises`.
Use `seal-home auth diagnose [--corp <corpId>]` when login fails. It reports four stages without printing tokens: `hose.openapi`, `hose.provisional`, `seal.sso`, and `seal.whoami`. A failed stage points to whether the problem is Hose app credentials, staff authorization, Seal SSO/tenant reachability, or Seal user/session access.
Global enterprise selection is stateless by default. Its configuration is stored in
`~/.config/seal-home/config.json` (override with `SEAL_HOME_CONFIG_FILE`). In stateless mode,
every command that accesses an enterprise must receive `--corp <corpId>`; no `current-corp` file
or first-config fallback is used. Run `seal-home config mode stateful --corp <corpId>` to enable
a default enterprise, then `seal-home corps switch <corpId>` to change it. Run
`seal-home config mode stateless` to require explicit enterprise selection again.
Use `seal-home auth diagnose --corp <corpId>` when login fails in stateless mode. It reports four stages without printing tokens: `hose.openapi`, `hose.provisional`, `seal.sso`, and `seal.whoami`. A failed stage points to whether the problem is Hose app credentials, staff authorization, Seal SSO/tenant reachability, or Seal user/session access.
## Wrapped API Documentation
The OpenAPI source under `openapi/` describes the seal-home wrapped API for frontend developers and agents. It is intentionally not the raw downstream Seal API: endpoints are named around seal-home concepts such as corps, auth diagnosis, approval context, run summaries, document URLs, and Langfuse bridge hints.
The OpenAPI source under `openapi/` describes the planned HTTP contract for a seal-home wrapped API. The current implementation exposes the MCP server over stdio and does not listen on the OpenAPI server URL. It is intentionally not the raw downstream Seal API: endpoints are named around seal-home concepts such as corps, auth diagnosis, approval context, run summaries, document URLs, and Langfuse bridge hints.
Source files are split by domain:
@@ -122,7 +188,7 @@ Service state is stored under `~/.config/seal-home/`:
- `service.pid`
- `service.log`
The service is intentionally local. It is useful as a stable process lifecycle for future warmed caches and update/restart workflows; normal CLI commands still work without it.
The service is intentionally local and currently acts as a lifecycle wrapper for a long-lived stdio/MCP process; it does not expose the HTTP/OpenAPI contract. It is useful as a stable process lifecycle for future warmed caches and update/restart workflows; normal CLI commands still work without it.
## Enterprise Config
@@ -154,26 +220,16 @@ The service is intentionally local. It is useful as a stable process lifecycle f
Most users do not need MCP. The public/shared path is the global `seal-home` CLI plus the optional local service.
For protocol-native development clients, the MCP server intentionally keeps a narrow exported surface:
- `seal_corp_switch`: switch the active local enterprise config.
- `seal_whoami`: current Seal user and tenant.
- `seal_approval_search`: keyword search across approval rules, documents, approval preferences, and optionally published rule history. Results include area, entity, field, line number, and surrounding context. Search data is cached in memory for 5 minutes only within a long-lived process such as the MCP server; separate CLI invocations do not share this cache.
- `seal_approval_context_get`: read current approval rules, approval documents, and approval style preferences in one call.
- `seal_runs_search`: search the approval run history from `api/v1/approvals`. This is the broad record table for historical runs and returns compact run fields; set `includeBridge` only when full Langfuse bridge rows are needed.
- `seal_action`: low-frequency management router. Use `action: "help"` or `payload.topic` to discover actions.
`seal_corps_list`, `seal_source_config`, and older fine-grained tool names are still accepted by the MCP call handler for compatibility, but they are not advertised by MCP `tools/list`.
`seal_action` uses this shape:
The MCP server advertises exactly one tool, `seal_cli`:
```json
{
"action": "rule.create | rule.update | rule.publish | doc.create | doc.update | runs.summary | langfuse.bridge.get",
"payload": {}
"command": "version"
}
```
It runs the same CLI dispatcher as the global binary, so read operations, write operations, `config`, `service`, and `update` remain available. Write-operation confirmations and explicit enterprise-ID rules continue to be defined by this skill.
## CLI Tools
These tools remain available to the CLI:
@@ -198,9 +254,11 @@ These tools remain available to the CLI:
- `seal_simulation_batch_records_get`: read records from one simulation batch via `api/v1/simulation/batch/{batchId}/records`.
- `seal_approval_run_langfuse_bridge_get`: resolve approval run records to Langfuse lookup hints. It prefers `sourceExtendData._langfuseTraceId`; if that is missing, it returns `hosecloud-{sourceDocumentSN}` as the session fallback.
For rule list commands, prefer `seal-home rules count` or `seal-home rules list --summary` before requesting full rule descriptions. `seal-home rules list` protects large outputs and asks for `--summary`, `--count`, or explicit `--full` when the response would be too large.
For rule list commands, prefer `seal-home rules count --corp <corpId>` or `seal-home rules list --corp <corpId> --summary` before requesting full rule descriptions. `seal-home rules list` protects large outputs and asks for `--summary`, `--count`, or explicit `--full` when the response would be too large.
For approval run detail commands, prefer `seal-home approval-runs pick --sn <单号> --latest`, `seal-home approval-runs get <recordId> --summary`, `seal-home approval-runs document-summary <recordId>`, `seal-home approval-runs cited-rules <recordId>`, `seal-home approval-runs attachments <recordId> --summary`, or `seal-home approval-runs result <recordId> --summary` before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-home auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
For test tenants that need a clean slate before importing another rule set, use `seal-home rules clear --corp <corpId> --dry-run` first, then `seal-home rules clear --corp <corpId> --yes` to delete the current draft rules and verify the remaining count.
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-home approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-home approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-home auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
## Approval Run To Langfuse Bridge
@@ -226,7 +284,7 @@ When `_langfuseTraceId` exists, downstream tools should fetch the trace directly
- Prefer Bun-native commands in this repository: `bun run check`, `bun test`, and `seal-home ...`. `npm run check` may work, but Bun is the project runtime and lockfile owner.
- Keep CLI entry points thin. Shared behavior belongs in `src/core` and `src/domains`; `src/cli.ts` should only handle command parsing, process lifecycle, and JSON output.
- Do not print diagnostic text to stdout from the MCP server. MCP uses stdout as the protocol stream; use stderr for server diagnostics.
- Keep any MCP exported surface narrow. High-frequency read tools can be direct MCP tools; low-frequency maintenance should go through `seal_action` or CLI commands.
- Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal-home approval-runs summary ...` instead of reading long `seal_approval_runs_search` output manually.
- Keep the MCP exported surface to the single `seal_cli` router; command knowledge belongs in this skill and its focused references.
- Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal-home approval-runs summary --corp <corpId> ...` instead of reading long `seal_approval_runs_search` output manually.
- Keep broad search tools compact by default. Add explicit opt-in flags such as `includeBridge` for verbose fields that are useful only in deeper debugging.
- When Seal API timestamp filters are uncertain, filter again in tool code by `createdAt` and explicit timezone before presenting date-based answers.
+35262
View File
File diff suppressed because it is too large. Load diff
+266 -18
View File
@@ -2,13 +2,13 @@
"openapi": "3.1.0",
"info": {
"title": "seal-home Wrapped API",
"version": "0.3.3",
"description": "HTTP contract for the seal-home wrapped backend API.\n\nThese endpoints describe the stable API that frontend developers and agents should use.\nThey are not the raw downstream Seal endpoints. seal-home is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
"version": "0.7.1",
"description": "Planned HTTP contract for the seal-home 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-home is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
},
"servers": [
{
"url": "http://localhost:8787",
"description": "Local seal-home service"
"description": "Reserved for a future local HTTP adapter; the current service uses MCP stdio."
}
],
"security": [
@@ -76,7 +76,8 @@
"type": "string",
"enum": [
"hose",
"direct"
"direct",
"seal"
]
},
"current": {
@@ -98,6 +99,7 @@
],
"operationId": "getCurrentCorp",
"summary": "Get current enterprise",
"description": "Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",
"responses": {
"200": {
"description": "Current enterprise.",
@@ -122,7 +124,8 @@
"type": "string",
"enum": [
"hose",
"direct"
"direct",
"seal"
]
},
"current": {
@@ -228,7 +231,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
}
],
"responses": {
@@ -284,7 +287,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
}
],
"responses": {
@@ -326,7 +329,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
}
],
"responses": {
@@ -392,7 +395,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
}
],
"responses": {
@@ -460,7 +463,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
},
{
"name": "documentLimit",
@@ -914,7 +917,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
},
{
"name": "versionNumber",
@@ -1522,7 +1525,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
},
{
"name": "offset",
@@ -1683,7 +1686,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
},
{
"name": "date",
@@ -1779,7 +1782,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
},
{
"name": "query",
@@ -1865,7 +1868,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
},
{
"name": "recordId",
@@ -1943,7 +1946,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
},
{
"name": "recordId",
@@ -2199,6 +2202,140 @@
}
}
},
"/v1/simulation/create-batch": {
"post": {
"tags": [
"Simulation"
],
"operationId": "createSimulationBatch",
"summary": "Create a simulation batch",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
},
"responses": {
"200": {
"description": "Created batch id.",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
},
"/v1/simulation/create-material-pack-batch": {
"post": {
"tags": [
"Simulation"
],
"operationId": "createMaterialPackBatch",
"summary": "Create a material pack simulation batch",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
},
"responses": {
"200": {
"description": "Created batch id.",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
},
"/v1/simulation/batches": {
"get": {
"tags": [
"Simulation"
],
"operationId": "listSimulationBatches",
"summary": "List simulation batches",
"parameters": [
{
"name": "limit",
"in": "query",
"schema": {
"type": "integer"
},
"description": "Max batches to return."
}
],
"responses": {
"200": {
"description": "Simulation batches.",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
}
},
"/v1/simulation/batch/{batchId}": {
"parameters": [
{
"name": "batchId",
"in": "path",
"required": true,
"schema": {
"type": "string"
},
"description": "Simulation batch ID."
}
],
"get": {
"tags": [
"Simulation"
],
"operationId": "getSimulationBatch",
"summary": "Get a simulation batch detail including echoed create params",
"responses": {
"200": {
"description": "Simulation batch detail.",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
},
"/v1/simulation/batches/{batchId}/records": {
"parameters": [
{
@@ -2241,6 +2378,116 @@
}
}
}
},
"/v1/simulation/templates": {
"get": {
"tags": [
"Simulation"
],
"operationId": "listSimulationTemplates",
"summary": "List simulation test templates",
"responses": {
"200": {
"description": "Simulation templates.",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
}
},
"/v1/simulation/integration-status": {
"get": {
"tags": [
"Simulation"
],
"operationId": "getSimulationIntegrationStatus",
"summary": "Get available source integration status for simulation",
"responses": {
"200": {
"description": "Integration status.",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
},
"/v1/simulation/hosecloud-integrations": {
"get": {
"tags": [
"Simulation"
],
"operationId": "listSimulationHosecloudIntegrations",
"summary": "List hosecloud source integrations available for simulation",
"responses": {
"200": {
"description": "Hosecloud integrations.",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
}
},
"/v1/material-packages/upload": {
"post": {
"tags": [
"Simulation"
],
"operationId": "uploadMaterialPackage",
"summary": "Upload a material package ZIP for simulation",
"requestBody": {
"required": true,
"content": {
"multipart/form-data": {
"schema": {
"type": "object",
"properties": {
"file": {
"type": "string",
"format": "binary"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Parsed material package with schema config.",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
}
},
"components": {
@@ -2259,7 +2506,7 @@
"schema": {
"type": "string"
},
"description": "Optional local enterprise config ID. Defaults to the current selected enterprise."
"description": "Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."
},
"Offset": {
"name": "offset",
@@ -2435,7 +2682,8 @@
"type": "string",
"enum": [
"hose",
"direct"
"direct",
"seal"
]
},
"current": {
+26
View File
@@ -0,0 +1,26 @@
{
"id": "tenant-slug",
"name": "Seal 原生企业",
"seal": {
"url": "https://tenant.sealai.cc",
"tenantSlug": "tenant-slug",
"endpoints": {
"approvalStylePreferences": "api/v1/agent/ai-approval/config"
}
},
"source": {
"type": "seal",
"token": "seal-bearer-token",
"sealUrl": "https://tenant.sealai.cc",
"expiresIn": 2592000,
"staffId": "seal-user-id",
"corpId": "tenant-slug",
"tenantId": "seal-tenant-id",
"tenantSlug": "tenant-slug",
"tenantName": "Seal 原生企业",
"providerUserId": "provider-user-id"
},
"auth": {
"refreshTtl": 300
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ CorpId:
in: query
schema:
type: string
description: Optional local enterprise config ID. Defaults to the current selected enterprise.
description: Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used.
Offset:
name: offset
in: query
+1 -1
View File
@@ -18,7 +18,7 @@ CorpSummary:
type: string
sourceType:
type: string
enum: [hose, direct]
enum: [hose, direct, seal]
current:
type: boolean
SwitchCorpRequest:
+5 -4
View File
@@ -1,16 +1,17 @@
openapi: 3.1.0
info:
title: seal-home Wrapped API
version: 0.3.3
version: 0.7.1
description: |
HTTP contract for the seal-home wrapped backend API.
Planned HTTP contract for the seal-home wrapped backend API.
These endpoints describe the stable API that frontend developers and agents should use.
These endpoints describe the intended stable API for frontend developers and agents once
the HTTP adapter is implemented.
They are not the raw downstream Seal endpoints. seal-home is responsible for enterprise
selection, source authentication, response compaction, and diagnostics-friendly fields.
servers:
- url: http://localhost:8787
description: Local seal-home service
description: Reserved for a future local HTTP adapter; the current service uses MCP stdio.
security:
- localSession: []
tags:
+1
View File
@@ -18,6 +18,7 @@ paths:
tags: [Corps]
operationId: getCurrentCorp
summary: Get current enterprise
description: Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.
responses:
"200":
description: Current enterprise.
+16
View File
@@ -54,5 +54,21 @@
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1attachments
/v1/approval-runs/{recordId}/result:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1{recordId}~1result
/v1/simulation/create-batch:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1create-batch
/v1/simulation/create-material-pack-batch:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1create-material-pack-batch
/v1/simulation/batches:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1batches
/v1/simulation/batch/{batchId}:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1batch~1{batchId}
/v1/simulation/batches/{batchId}/records:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1batches~1{batchId}~1records
/v1/simulation/templates:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1templates
/v1/simulation/integration-status:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1integration-status
/v1/simulation/hosecloud-integrations:
$ref: ./simulation.yaml#/paths/~1v1~1simulation~1hosecloud-integrations
/v1/material-packages/upload:
$ref: ./simulation.yaml#/paths/~1v1~1material-packages~1upload
+142
View File
@@ -1,4 +1,80 @@
paths:
/v1/simulation/create-batch:
post:
tags: [Simulation]
operationId: createSimulationBatch
summary: Create a simulation batch
requestBody:
required: true
content:
application/json:
schema:
type: object
additionalProperties: true
responses:
"200":
description: Created batch id.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/simulation/create-material-pack-batch:
post:
tags: [Simulation]
operationId: createMaterialPackBatch
summary: Create a material pack simulation batch
requestBody:
required: true
content:
application/json:
schema:
type: object
additionalProperties: true
responses:
"200":
description: Created batch id.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/simulation/batches:
get:
tags: [Simulation]
operationId: listSimulationBatches
summary: List simulation batches
parameters:
- name: limit
in: query
schema:
type: integer
description: Max batches to return.
responses:
"200":
description: Simulation batches.
content:
application/json:
schema:
type: array
items:
type: object
additionalProperties: true
/v1/simulation/batch/{batchId}:
parameters:
- $ref: ../components/parameters.yaml#/BatchId
get:
tags: [Simulation]
operationId: getSimulationBatch
summary: Get a simulation batch detail including echoed create params
responses:
"200":
description: Simulation batch detail.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/simulation/batches/{batchId}/records:
parameters:
- $ref: ../components/parameters.yaml#/BatchId
@@ -20,3 +96,69 @@ paths:
schema:
type: object
additionalProperties: true
/v1/simulation/templates:
get:
tags: [Simulation]
operationId: listSimulationTemplates
summary: List simulation test templates
responses:
"200":
description: Simulation templates.
content:
application/json:
schema:
type: array
items:
type: object
additionalProperties: true
/v1/simulation/integration-status:
get:
tags: [Simulation]
operationId: getSimulationIntegrationStatus
summary: Get available source integration status for simulation
responses:
"200":
description: Integration status.
content:
application/json:
schema:
type: object
additionalProperties: true
/v1/simulation/hosecloud-integrations:
get:
tags: [Simulation]
operationId: listSimulationHosecloudIntegrations
summary: List hosecloud source integrations available for simulation
responses:
"200":
description: Hosecloud integrations.
content:
application/json:
schema:
type: array
items:
type: object
additionalProperties: true
/v1/material-packages/upload:
post:
tags: [Simulation]
operationId: uploadMaterialPackage
summary: Upload a material package ZIP for simulation
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
properties:
file:
type: string
format: binary
responses:
"200":
description: Parsed material package with schema config.
content:
application/json:
schema:
type: object
additionalProperties: true
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "seal-home",
"version": "0.3.3",
"version": "0.7.1",
"type": "module",
"module": "src/server.ts",
"bin": {
@@ -12,7 +12,8 @@
"probe": "bun run src/probe.ts",
"cli": "bun run src/cli.ts",
"check": "tsc --noEmit",
"build:binary": "bun build --compile --outfile dist/bin/seal-home src/cli.ts",
"build:binary": "node scripts/build-binary.mjs",
"build:plugin": "node scripts/build-plugin.mjs",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
"test": "bun test"
},
+157
View File
@@ -0,0 +1,157 @@
# seal-home 插件化改造计划(供 Codex 执行)
> 状态:代码与发布已完成(2026-08-12)。全局配置改造已先合入 `master`;插件改造已从最新 `master` 分支完成、快进合并并推送。ZCode Settings → Plugin Management 的本地安装与启用由用户手工完成。
> 本文件记录实际交付结果与验收项。
## 1. 背景
seal-home 是一个 Bun + TypeScript 的 CLI + MCP server 工具仓库(v0.5.1),skill 文档位于 `skills/seal-home/`,工作区入口 `.agents/skills/seal-home` 为符号链接。目标是把仓库包装成标准的 ZCode 插件,同时保留全局 CLI 能力。
**最终形态(混合模式,两条线并存):**
| 线 | 面向 | 形态 |
|---|---|---|
| 全局 CLI | 客户/脚本/手动 | `seal-home` 二进制(`bun build --compile`),可独立安装、可与其他 shell 命令组合使用,**保留现状** |
| ZCode 插件 | agent | `skills/seal-home/`(知识层)+ MCP server(可选启用,执行层) |
**插件内的 MCP 采用单工具模式:** 只注册一个 `seal_cli` 工具,接受一个命令行字符串,内部透传到 CLI 的命令分发层。命令知识全部收敛在 skill 文档,工具 schema 只做路由(一句 description 指针),不写教程。
## 2. 目标布局
```
seal-home/ # 仓库根即插件根
├── .zcode-plugin/plugin.json # 插件清单(新增)
├── .mcp.json # MCP server 声明,userConfig 控制 seal_cli(新增)
├── skills/
│ └── seal-home/ # 从 .agents/skills/seal-home 迁入
│ ├── SKILL.md
│ └── references/
├── dist/
│ ├── bin/seal-home # 全局 CLI 编译产物(已有 build:binary)
│ └── mcp/server.js # MCP server 单文件 bundle(新增)
├── src/ # 源码保留,仓库继续独立开发测试
├── openapi/ package.json README.md
└── .agents/skills/seal-home # 保留为指向 skills/seal-home 的链接或副本(开发期 workspace 使用)
```
## 3. 已定决策(执行时不要更改)
1. **MCP 工具默认不启用**:`.zcode-plugin/plugin.json` 的 `userConfig.enable_mcp` 默认 `false`,用户需要时在插件详情的配置区打开。
2. **MCP 单工具 `seal_cli`**:schema 只含 `command: string`;description 用一句话指针(如 "Run seal-home CLI commands. See the seal-home skill for command reference."),具体用法在 SKILL.md。
3. **CLI 命令语法不变**:MCP 与全局 CLI 共享同一命令分发实现,不允许两套逻辑。
4. **企业配置不迁移到 userConfig**:`enterprises/*.json` 与 `~/.config/seal-home/enterprises` 的现有加载机制保持不变。
5. **插件格式**:`.zcode-plugin/plugin.json`(ZCode 原生);如本机验证 ZCode 不识别,再补 `.claude-plugin/plugin.json` 兼容副本。
6. **版本号**:改造完成后统一升到 `0.5.1`(`package.json`、plugin manifest、SKILL.md frontmatter、marketplace 条目对齐)。
7. **发布时间**:主功能迭代完成后,在干净的 release 基础上单独开分支执行。
## 4. 任务拆解(按序执行)
### T1 构建产物
- 新增 `scripts/build-plugin.mjs`(或扩展 package.json scripts):
- MCP server 单文件 bundle:`bun build src/server.ts --target=node --outfile dist/mcp/server.js`(优先 node target;若因 `@modelcontextprotocol/sdk`/ky 等依赖无法 bundle 成功,退回 `--target=bun` 并在 `.mcp.json` 用 `command: "bun"`)。
- 保留/复用 `build:binary` 产出 `dist/bin/seal-home`。
- 若 CLI 运行时读取 `dist/openapi.json` 则随包拷贝,否则不打包(先 grep 确认是否有运行时读取)。
- `bun run check`、`bun test` 必须通过。
### T2 CLI 分发层抽离(MCP 复用的前提)
- 当前 `src/cli.ts` 是 1441 行的 bin 入口。抽出纯逻辑分发层(如 `src/cli/runner.ts`),导出类似 `runCli(args: string[]): Promise<{ stdout: string; isError: boolean }>` 的可复用函数。
- **关键约束**:分发层内部禁止 `process.exit`,错误一律通过返回值/异常传播;`src/cli.ts` 变薄为"调 runner + 处理退出码"。
- 保持 CLI 行为与输出格式(JSON stdout / 诊断走 stderr)完全不变,现有 `cli.test.ts` 全绿。
### T3 MCP 单工具改造
- `src/server.ts`:从"注册 ~20 个 sealMcpTools"改为只注册 `seal_cli` 一个工具。
- handler 收到 `command` 字符串后调用 T2 的 `runCli`(同进程调用,不 spawn 子进程、不依赖全局二进制)。
- 返回 `{ content: [{ type: "text", text: <stdout> }], isError: <失败标记> }`,透传 CLI 的 JSON 输出。
- 原 `sealMcpTools` 的逐一注册逻辑可保留在代码中但不再注册(或标记废弃),避免删除时牵连未迁移命令。
### T4 skill 迁移
- 将 `.agents/skills/seal-home/` 整体迁到 `skills/seal-home/`(根目录 `skills/` 目前为空)。
- `.agents/skills/seal-home` 改为指向 `skills/seal-home` 的符号链接(或最小副本),保证当前 workspace skill 加载不中断;AGENTS.md 中 `.agents/` authoritative 的约定不受影响(链接不改变内容来源)。
- SKILL.md 执行路径更新为:**优先 `seal_cli` MCP 工具(若会话中可用),否则回退全局 `seal-home` 命令**;命令语法部分不变。
- 清理:`~/.agents/skills/seal-home` 若为空目录则删除(先确认无内容);`~/.agents/skills/seal` bundle 与插件 skill 的共存关系保持不变,不做合并。
### T5 插件清单与 MCP 声明
- `.zcode-plugin/plugin.json`:
```json
{
"name": "seal-home",
"version": "0.5.1",
"description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, search.",
"author": { "name": "yingqing" },
"license": "MIT",
"skills": "skills",
"mcpServers": "./.mcp.json",
"userConfig": {
"enable_mcp": {
"type": "boolean",
"title": "启用 MCP 服务",
"default": false
}
}
}
```
- `.mcp.json`:
```json
{
"mcpServers": {
"seal-home": {
"type": "stdio",
"command": "node",
"args": ["${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"],
"env": {
"SEAL_HOME_MCP_ENABLED": "${user_config.enable_mcp}"
}
}
}
}
```
(若 T1 退化为 bun target,则 `command: "bun"`;变量名以本机 ZCode 支持的插件根变量为准,先查 zcode 文档/已有插件示例再定。)
### T6 本地安装验证
- 通过 ZCode **Settings → Plugin Management** 添加本仓库目录,验证:
1. 插件 skill 可发现(`seal-home` skill 出现在 skill 列表,来源为插件)。
2. 插件配置区显示 `启用 MCP 服务`,默认值为关闭。
3. 打开配置并重新连接插件 MCP 后,`seal_cli` 工具可用,端到端跑通一个命令(如 `seal-home corps list`、`seal-home version`)。
4. 关闭配置后,MCP 不注册任何工具;全局 CLI 仍可 `bun run build:binary` 并独立使用。
### T7 发布(marketplace)
- 在 `yunyingk/yingqing-plugins` 的 `marketplace.json` 增加 `seal-home` 条目。
- 优先使用 github source 引用本仓库(参照已有条目 xiaohongshu-skills 的 `source: {source: "github", repo, ref, sha}` 写法 + `skills: "./skills"`);若 marketplace 结构不支持,则退化为把插件 payload(`.zcode-plugin/`、`.mcp.json`、`skills/`、`dist/`、README)镜像到 `plugins/seal-home/` 并同步维护。
- 三处版本对齐:`package.json` / SKILL.md frontmatter / marketplace.json。
- 敏感检查:确认发布内容不含 `enterprises/local.json` 等真实凭据(对照 `.gitignore`)。
### T8 文档
- README 增加"插件安装"小节:marketplace 安装方式、MCP 启用/关闭方式、全局 CLI 安装方式对比。
- 本计划文件在改造完成后更新状态或归档。
## 5. 验收标准
- [x] `bun run check`、`bun test` 通过;CLI 输出格式与改造前一致。
- [x] 仓库根结构符合 §2 目标布局。
- [ ] 本机插件安装后 skill 可发现、MCP 默认 disabled、启用后 `seal_cli` 端到端可用(待用户在 ZCode Settings → Plugin Management 中手工验收)。
- [x] 全局 `seal-home` 二进制可独立构建、安装、与 shell 命令组合使用。
- [x] `.agents/skills/seal-home` 在开发环境中仍可加载(链接生效)。
- [x] marketplace 条目存在且版本一致,无真实凭据泄漏。
- [x] skill 文档中 MCP/CLI 双路径指引明确。
## 6. 非目标
- 不把 MCP 拆成多个细粒度工具(保持单工具)。
- 不迁移企业配置存储方式、不改 CLI 命令语法。
- 不合并 `~/.agents/skills/seal` bundle。
- 不处理主功能迭代中的需求(本计划在其之后执行)。
## 7. 风险与注意
- **cli.ts 抽离是最大改动面**:1441 行的 bin 入口重构需保证零行为变化,以 `cli.test.ts` + 手工冒烟为准。
- **node target bundle 可行性未验证**:`@modelcontextprotocol/sdk` 为纯 JS、ky/zod 通用,预期可行;失败则退 bun target,不影响整体设计。
- **插件根变量名**:`${CLAUDE_PLUGIN_ROOT}` 是 Claude 生态约定,ZCode 是否沿用需以本机实测为准。
- **workspace skill 来源变更**:迁移后开发期 workspace 的 seal-home skill 来自符号链接,若 ZCode 不支持链接目录,改用副本并接受双份维护(以 §4 T4 的验证结果为准)。
+70
View File
@@ -0,0 +1,70 @@
import { mkdirSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bun = process.env.BUN_BIN || "bun";
const TARGET_MAP = {
"darwin-arm64": { bunTarget: "bun-darwin-arm64", outfile: "dist/bin/seal-home-darwin-arm64" },
"darwin-x64": { bunTarget: "bun-darwin-x64", outfile: "dist/bin/seal-home-darwin-x64" },
"linux-x64": { bunTarget: "bun-linux-x64", outfile: "dist/bin/seal-home-linux-x64" },
"linux-arm64": { bunTarget: "bun-linux-arm64", outfile: "dist/bin/seal-home-linux-arm64" },
"windows-x64": { bunTarget: "bun-windows-x64", outfile: "dist/bin/seal-home-windows-x64.exe" }
};
const args = process.argv.slice(2);
const isAll = args.includes("--all") || args.includes("--matrix");
const targetArg = args.find((arg) => arg.startsWith("--target="))?.replace("--target=", "");
if (isAll) {
for (const [name, config] of Object.entries(TARGET_MAP)) {
buildTarget(name, config.bunTarget, resolve(root, config.outfile));
}
} else if (targetArg) {
const config = TARGET_MAP[targetArg];
if (!config) {
throw new Error(`Unknown target: ${targetArg}. Available targets: ${Object.keys(TARGET_MAP).join(", ")}`);
}
buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile));
} else {
const output = resolve(root, "dist/bin/seal-home");
buildTarget("host", null, output);
}
function buildTarget(name, bunTarget, output) {
mkdirSync(dirname(output), { recursive: true });
const buildArgs = ["build", "--compile"];
if (bunTarget) {
buildArgs.push(`--target=${bunTarget}`);
}
buildArgs.push("--outfile", output, "src/cli.ts");
console.log(`[build:binary] compiling target: ${name} -> ${output}`);
run(bun, buildArgs);
if (process.platform === "darwin" && (name.startsWith("darwin") || name === "host")) {
try {
run("/usr/bin/codesign", ["--remove-signature", output], { quiet: true });
} catch {
// ignore
}
try {
run("/usr/bin/codesign", ["--force", "--sign", "-", output], { quiet: true });
} catch {
// ignore
}
}
}
function run(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: root,
stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit"
});
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`${command} ${args.join(" ")} failed with status ${result.status}`);
}
}
+24
View File
@@ -0,0 +1,24 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bun = process.env.BUN_BIN || "bun";
function run(args) {
const result = spawnSync(bun, args, {
cwd: root,
stdio: "inherit"
});
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`${bun} ${args.join(" ")} failed with status ${result.status}`);
}
}
const mcpOutput = resolve(root, "dist/mcp/server.js");
mkdirSync(dirname(mcpOutput), { recursive: true });
run(["build", "src/server.ts", "--target=node", "--outfile", mcpOutput]);
writeFileSync(mcpOutput, readFileSync(mcpOutput, "utf8").replace(/[ \t]+$/gm, ""));
run(["run", "build:binary"]);
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env bash
set -e
REPO="yunyingk/seal-home"
echo "==> Detecting platform and architecture..."
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case "$OS" in
darwin)
PLATFORM="darwin"
;;
linux)
PLATFORM="linux"
;;
*)
echo "Unsupported operating system: $OS" >&2
exit 1
;;
esac
case "$ARCH" in
x86_64|amd64)
ARCH_NAME="x64"
;;
arm64|aarch64)
ARCH_NAME="arm64"
;;
*)
echo "Unsupported architecture: $ARCH" >&2
exit 1
;;
esac
# Resolve best writable bin directory without requiring sudo
TARGET_DIR=""
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
TARGET_DIR="$candidate"
break
fi
done
if [ -z "$TARGET_DIR" ]; then
mkdir -p "$HOME/.local/bin"
TARGET_DIR="$HOME/.local/bin"
fi
ASSET_NAME="seal-home-${PLATFORM}-${ARCH_NAME}"
DOWNLOAD_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
TARGET_PATH="${TARGET_DIR}/seal-home"
echo "==> Downloading seal-home (${PLATFORM}-${ARCH_NAME}) into ${TARGET_DIR}..."
TMP_FILE="$(mktemp)"
if ! curl -fL "$DOWNLOAD_URL" -o "$TMP_FILE"; then
echo "Error: Failed to download $DOWNLOAD_URL" >&2
rm -f "$TMP_FILE"
exit 1
fi
chmod +x "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_PATH"
# Ad-hoc sign on macOS
if [ "$PLATFORM" = "darwin" ] && command -v codesign >/dev/null 2>&1; then
codesign --force --sign - "$TARGET_PATH" 2>/dev/null || true
fi
echo "==> Initializing agent skill..."
"$TARGET_PATH" skill install >/dev/null 2>&1 || true
echo ""
echo "✨ seal-home successfully installed to ${TARGET_PATH}!"
"$TARGET_PATH" version
echo ""
echo "Quick start:"
echo " 1. Add enterprise: seal-home corps add-hose --json '{...}'"
echo " 2. View MCP config: seal-home mcp-config"
echo " 3. Self-update: seal-home update"
echo ""
+46 -31
View File
@@ -1,13 +1,14 @@
---
name: seal-home
description: Use when working with Seal Home approval automation: 合思/易快报企业认证, Hose authorization links, approval run lookup by 单号/SN/recordId/batch, compact approval run summaries, AI cited rules, document/attachment summaries, approval rules by count/list/version/code/runtime-id, approval knowledge search, simulations, and Langfuse trace hints.
description: "v0.7.1: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
metadata:
short-description: Seal approval automation tools
version: 0.7.1
short-description: Seal tenant and Hose approval automation (v0.7.1)
---
# Seal Home
# Seal Home (v0.7.1)
Use the global `seal-home` 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.
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-home` 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.
```bash
seal-home help
@@ -20,45 +21,58 @@ seal-home tools list
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use `seal-home corps ...`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For repeat test-environment rule resets, prefer `rules clear --dry-run` followed by `rules clear --yes`.
- For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of `description`; preserve `scope`, `strictness`, and unrelated clauses unless the user explicitly approves otherwise.
- Resolve and lock the target enterprise `corpId` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing.
- For date questions, use explicit dates and `--timezone Asia/Shanghai`.
- If output may be large, use `--summary`, `--fields`, `--count`, or `--output-file`; use `--full` only when the user really needs full payloads.
- When returning ANY authorization, login, or delegation links (e.g. 合思授权链接, Seal授权链接/委托链接), ALWAYS provide BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- For delegation links, always prefer `seal-home delegation create` over `users delegation` for link generation to ensure persistent token tracking.
- Never treat “Seal 协助/Seal 授权/委托” as a 合思授权入口. They are different links and must use different commands.
- In the default stateless mode, every enterprise command requires `--corp <corpId>`. In stateful mode, omitting `--corp` uses the configured default enterprise and is unsafe for an explicitly named enterprise.
- For an explicitly named enterprise, first resolve it with `seal-home corps list`, then pass its exact `corpId` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link.
## Route By Intent
- Current tenant or identity: `seal-home tool seal_whoami`.
- Enterprise list/current/switch/add: `seal-home corps ...`; for Hose setup read `references/hose-enterprise-auth.md`.
- Hose login/SSO/auth failures: `seal-home auth diagnose --corp <corpId>`.
- User-facing 合思 authorization link: `seal-home auth hose-link --corp <corpId> --expire 7200`; read `references/hose-enterprise-auth.md`.
- One approval document by 单号/SN: use `seal-home approval-runs pick --sn <单号> --latest`; read `references/approval-run-lightweight.md`.
- One approval run detail: use `approval-runs get <recordId> --summary` or `--fields ...`; read `references/approval-run-lightweight.md`.
- AI used which rules: use `approval-runs cited-rules <recordId>`; read `references/approval-run-lightweight.md`.
- Case/document facts before deep dive: use `approval-runs document-summary <recordId>`.
- Attachments/invoices without full raw document: use `approval-runs attachments <recordId> --summary`.
- Customer disputes OCR, receipt, invoice, image, or attachment findings: read `references/approval-attachment-trace.md`.
- Rules count/list/version lookup: use `rules count`, `rules list --summary`, or `rules get`; read `references/rule-lightweight.md`.
- Rule/document/style maintenance: use fine-grained `seal-home tool <toolName> --json ...`.
- Approval knowledge search: use `seal_approval_search` with `snippetOnly`, `maxChars`, and `fields` when possible; read `references/rule-lightweight.md`.
- Daily run summary: `seal-home approval-runs summary --date YYYY-MM-DD --timezone Asia/Shanghai --limit 100`.
- Simulation batch: `seal-home simulation batch-records <batchId>`.
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-home 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-home simulation create --mode hosecloud --flow-ids ... --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 创建后 `simulation list`/`get`/`batch-records` 轮询批次与记录; 其他取数模式通过 `--json` 透传预留。创建前确认目标环境为测试环境。
- User-facing 合思 authorization link (合思/易快报授权): `seal-home 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.
- Delegation links management: `seal-home delegation list --corp <corpId>`, `create [--note ...] --corp <corpId>`, `revoke <tokenId> --corp <corpId>`.
- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-home users search [keyword] --corp <corpId>`, `users delegation <userIdOrPhone> --corp <corpId>` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate <userId> --corp <corpId>`, `users create --name ... --phone ... --corp <corpId>`, `reset-password <userId> --corp <corpId>`, `get <userId> --corp <corpId>`, `delete <userId> --corp <corpId>`.
- LLM Model Config & Providers: `seal-home llm config --corp <corpId>`, `seal-home llm providers --corp <corpId>`.
- System Permissions Config: `seal-home permissions available --corp <corpId>`, `seal-home permissions configs --corp <corpId>`.
- Billing & Feature Quotas: `seal-home billing status --corp <corpId>`, `seal-home billing plans --corp <corpId>`, `seal-home billing features --corp <corpId>`.
- Enterprise Onboarding (新机企业接入与配置):
- 合思/易快报企业: 从合思管理员后台获取 `appKey`、`appSecurity` 及员工工号 `proxyStaffBizId` (形如 `corpId:staffId`),运行 `seal-home corps add-hose --json '{"name":"企业名","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'`。
- Seal 租户直连: 登录 Seal 控制台获取 Bearer Token,运行 `seal-home corps add-seal --json '{"sealUrl":"https://<tenant>.sealai.cc","token":"<bearer-token>"}'`。
- 连通性诊断: 运行 `seal-home auth diagnose --corp <corpId>` 验证四级鉴权。
- Full CLI inventory: read `references/cli.md`.
## High-Value Commands
```bash
seal-home approval-runs pick --sn <sourceDocumentSN> --latest
seal-home approval-runs pick --sn <sourceDocumentSN> --batch <batchId> --latest --fields recordId,status,aiDecision,aiSummary
seal-home approval-runs get <recordId> --summary
seal-home approval-runs get <recordId> --fields metadata,document.fields,result.summary
seal-home approval-runs document-summary <recordId>
seal-home approval-runs cited-rules <recordId>
seal-home approval-runs attachments <recordId> --summary
seal-home approval-runs result <recordId> --summary
seal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest
seal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest --fields recordId,status,aiDecision,aiSummary
seal-home approval-runs get <recordId> --corp <corpId> --summary
seal-home approval-runs get <recordId> --corp <corpId> --fields metadata,document.fields,result.summary
seal-home approval-runs document-summary <recordId> --corp <corpId>
seal-home approval-runs cited-rules <recordId> --corp <corpId>
seal-home approval-runs attachments <recordId> --corp <corpId> --summary
seal-home approval-runs result <recordId> --corp <corpId> --summary
seal-home rules count --corp <corpId>
seal-home rules list --corp <corpId> --summary
seal-home rules get --version 16 --code '#0038'
seal-home rules get --record-id <recordId> --runtime-id rule-205
seal-home tool seal_approval_search --json '{"keywords":["差旅","发票"],"areas":["rules"],"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}'
seal-home rules clear --corp <corpId> --dry-run
seal-home rules clear --corp <corpId> --yes
seal-home rules get --corp <corpId> --version 16 --code '#0038'
seal-home rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
seal-home simulation create --corp <corpId> --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high]
seal-home simulation create --corp <corpId> --mode material_pack --package-ids <materialPackageId> [--schema-config file.json]
seal-home simulation package-upload <材料包.zip> --corp <corpId>
seal-home simulation list --corp <corpId>
seal-home simulation get <batchId> --corp <corpId>
seal-home simulation batch-records <batchId> --corp <corpId>
seal-home tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅","发票"],"areas":["rules"],"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}'
```
## Important Fields
@@ -77,6 +91,7 @@ seal-home tool seal_approval_search --json '{"keywords":["差旅","发票"],"are
- `references/approval-run-lightweight.md`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- `references/rule-lightweight.md`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- `references/customer-feedback-rule-remediation.md`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- `references/hose-enterprise-auth.md`: Hose 企业配置、认证诊断、授权链接。
- `references/approval-attachment-trace.md`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。
- `references/cli.md`: 完整 CLI 命令清单。
+2 -2
View File
@@ -1,4 +1,4 @@
interface:
display_name: "Seal Home"
short_description: "Inspect Seal approval runs, rules, Hose auth, and compact diagnostics"
default_prompt: "Use $seal-home for Seal approval automation: locate runs by 单号/SN, read compact summaries, inspect cited rules, rule versions, Hose auth links, and Langfuse trace hints."
short_description: "Diagnose approval feedback and publish minimal rule fixes"
default_prompt: "Use $seal-home to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation."
@@ -33,9 +33,9 @@ Approval traces commonly contain these stages:
Start from the Seal run and Langfuse trace.
```bash
seal-home approval-runs search --query <sourceDocumentSN> --limit 50
seal-home approval-runs get <recordId> > /tmp/seal-run.json
seal-home approval-runs bridge --sourceDocumentSN <sourceDocumentSN>
seal-home approval-runs search --corp <corpId> --query <sourceDocumentSN> --limit 50
seal-home approval-runs get <recordId> --corp <corpId> > /tmp/seal-run.json
seal-home approval-runs bridge --corp <corpId> --sourceDocumentSN <sourceDocumentSN>
```
Refresh and inspect the Langfuse trace.
@@ -21,16 +21,16 @@ If there are multiple candidates and `--latest` was not used, report the candida
Use `--summary` for most diagnosis and support questions.
```bash
seal-home approval-runs get <recordId> --summary
seal-home approval-runs get <recordId> --corp <corpId> --summary
```
Use `--fields` when the user needs a particular slice.
```bash
seal-home approval-runs get <recordId> --fields metadata
seal-home approval-runs get <recordId> --fields document.fields,result.summary
seal-home approval-runs get <recordId> --fields result.summary,result.decision,result.riskPoints
seal-home approval-runs get <recordId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber
seal-home approval-runs get <recordId> --corp <corpId> --fields metadata
seal-home approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary
seal-home approval-runs get <recordId> --corp <corpId> --fields result.summary,result.decision,result.riskPoints
seal-home approval-runs get <recordId> --corp <corpId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber
```
Avoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.
@@ -40,7 +40,7 @@ Avoid full `approval-runs get <recordId>` unless the user specifically needs raw
Before pulling the full document, use:
```bash
seal-home approval-runs document-summary <recordId>
seal-home approval-runs document-summary <recordId> --corp <corpId>
```
This is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.
@@ -50,7 +50,7 @@ This is for quick case reading: template/title, key fields, amount, expense type
Use this when the user asks "AI 用了哪条规则", "为什么命中这条", or needs the rule evidence for a specific run.
```bash
seal-home approval-runs cited-rules <recordId>
seal-home approval-runs cited-rules <recordId> --corp <corpId>
```
Return and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.
@@ -62,7 +62,7 @@ If the user then wants the full text of one cited rule, use `rules get --record-
Use:
```bash
seal-home approval-runs attachments <recordId> --summary
seal-home approval-runs attachments <recordId> --corp <corpId> --summary
```
This should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.
@@ -72,7 +72,7 @@ This should be enough for file names, file IDs, mime types, positions, invoice/a
Use:
```bash
seal-home approval-runs result <recordId> --summary
seal-home approval-runs result <recordId> --corp <corpId> --summary
```
This is for decision, summary, risk point count, matched rule count, trace ID, and record ID.
+106 -31
View File
@@ -12,32 +12,73 @@ Enterprise config lookup:
- Otherwise `./enterprises` and `~/.config/seal-home/enterprises` are merged.
- User-level configs override same-ID local configs.
Enterprise selection is stateless by default. Commands that access an enterprise require
`--corp <corpId>` unless stateful mode is explicitly enabled:
```bash
seal-home config mode stateful --corp <corpId>
seal-home corps switch <corpId>
seal-home config mode stateless
```
The global mode is stored in `~/.config/seal-home/config.json`; set `SEAL_HOME_CONFIG_FILE` to
override that path. The legacy `current-corp` file is not read.
## Top-Level Commands
```bash
seal-home version
seal-home config paths
seal-home config get
seal-home config mode <stateful|stateless> [--corp <corpId>]
seal-home service <start|stop|restart|status>
seal-home update
seal-home tools list
seal-home corps list [--corp <corpId>]
seal-home corps current
seal-home corps current [--corp <corpId>]
seal-home corps switch <corpId>
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-home auth diagnose [--corp <corpId>]
seal-home auth hose-link [--corp <corpId>] [--expire 7200]
seal-home delegation list [--corp <corpId>]
seal-home delegation create [--note <note>] [--corp <corpId>]
seal-home delegation revoke <tokenId> [--corp <corpId>]
seal-home users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-home users reset-password <userId> [--corp <corpId>]
seal-home users get <userId> [--corp <corpId>]
seal-home users delete <userId> [--corp <corpId>]
seal-home llm config [--corp <corpId>]
seal-home llm providers [--corp <corpId>]
seal-home permissions available [--corp <corpId>]
seal-home permissions configs [--corp <corpId>]
seal-home billing status [--corp <corpId>]
seal-home billing plans [--corp <corpId>]
seal-home billing features [--corp <corpId>]
seal-home webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-home webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
seal-home 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-home webhook delete <idOrName> --yes [--corp <corpId>]
seal-home source config [--corp <corpId>]
seal-home tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
seal-home approval-runs search [--query text] [--limit 20] [--includeBridge true]
seal-home approval-runs get <recordId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
seal-home approval-runs attachments <recordId>
seal-home approval-runs result <recordId> [--summary]
seal-home approval-runs url
seal-home approval-runs url <recordId>
seal-home approval-runs url --sourceDocumentSN <sourceDocumentSN>
seal-home approval-runs bridge [--sourceDocumentSN <sourceDocumentSN>]
seal-home simulation batch-records <batchId>
seal-home approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
seal-home approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]
seal-home approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
seal-home approval-runs attachments <recordId> --corp <corpId>
seal-home approval-runs result <recordId> --corp <corpId> [--summary]
seal-home approval-runs url --corp <corpId>
seal-home approval-runs url <recordId> --corp <corpId>
seal-home approval-runs url --sourceDocumentSN <sourceDocumentSN> --corp <corpId>
seal-home approval-runs bridge --corp <corpId> [--sourceDocumentSN <sourceDocumentSN>]
seal-home simulation batch-records <batchId> --corp <corpId>
seal-home simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] --corp <corpId>
seal-home simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp <corpId>
seal-home simulation list [--limit 50] --corp <corpId>
seal-home simulation get <batchId> --corp <corpId>
seal-home simulation templates --corp <corpId>
seal-home simulation integrations --corp <corpId>
seal-home simulation package-upload <材料包.zip> --corp <corpId>
```
## Fine-Grained Tools
@@ -57,7 +98,7 @@ seal-home simulation batch-records <batchId>
Identity and session:
- `seal-home auth diagnose [--corp <corpId>]`
- `seal-home auth diagnose --corp <corpId>`
- `seal_whoami`
- `seal_session_get`
@@ -65,7 +106,9 @@ Approval rule maintenance:
- `seal-home rules count [--corp <corpId>]`
- `seal-home rules list --summary [--corp <corpId>]`
- `seal-home rules clear [--corp <corpId>] [--dry-run|--yes]`
- `seal_approval_rules_list`
- `seal_approval_rules_clear`
- `seal_approval_rule_create`
- `seal_approval_rule_update`
- `seal_approval_rule_delete`
@@ -74,14 +117,14 @@ Approval rule maintenance:
Approval run lightweight queries:
- `seal-home approval-runs get <recordId> --fields metadata`
- `seal-home approval-runs get <recordId> --summary`
- `seal-home approval-runs pick --sn <单号> --batch <batchId> --latest`
- `seal-home approval-runs document-summary <recordId>`
- `seal-home approval-runs cited-rules <recordId>`
- `seal-home approval-runs get <recordId> --fields document.fields,result.summary`
- `seal-home approval-runs attachments <recordId> --summary`
- `seal-home approval-runs result <recordId> --summary`
- `seal-home approval-runs get <recordId> --corp <corpId> --fields metadata`
- `seal-home approval-runs get <recordId> --corp <corpId> --summary`
- `seal-home approval-runs pick --corp <corpId> --sn <单号> --batch <batchId> --latest`
- `seal-home approval-runs document-summary <recordId> --corp <corpId>`
- `seal-home approval-runs cited-rules <recordId> --corp <corpId>`
- `seal-home approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary`
- `seal-home approval-runs attachments <recordId> --corp <corpId> --summary`
- `seal-home approval-runs result <recordId> --corp <corpId> --summary`
- `seal_approval_run_get` with `fields`
- `seal_approval_run_pick`
- `seal_approval_run_cited_rules_get`
@@ -100,19 +143,39 @@ Approval search and context:
- `seal_approval_search`
- `seal_approval_context_get`
- `seal-home rules get --version <number> --code '#0038'`
- `seal-home rules get --record-id <recordId> --runtime-id rule-205`
- `seal-home rules get --corp <corpId> --version <number> --code '#0038'`
- `seal-home rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205`
Style preferences:
- `seal_approval_style_preferences_get`
- `seal_approval_style_preferences_update`
Webhook integrations:
- `seal-home webhook list [--query <text>] [--show-secret] [--corp <corpId>]`
- `seal-home webhook get|find <idOrName> [--show-secret] [--corp <corpId>]`
- `seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]`
- `seal-home 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-home webhook delete <idOrName> --yes [--corp <corpId>]`
- `seal_webhook_list`
- `seal_webhook_get`
- `seal_webhook_add`
- `seal_webhook_update`
- `seal_webhook_delete`
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once.
Approval runs, simulations, and Langfuse bridge:
- `seal_approval_runs_search`
- `seal_approval_runs_summary`
- `seal_simulation_batch_records_get`
- `seal_simulation_batch_create`
- `seal_simulation_batches_list`
- `seal_simulation_batch_get`
- `seal_simulation_templates_get`
- `seal_simulation_integrations_get`
- `seal_approval_run_langfuse_bridge_get`
## Common Examples
@@ -141,49 +204,61 @@ The diagnostic stages are `hose.openapi`, `hose.provisional`, `seal.sso`, and `s
Search approval content:
```bash
seal-home tool seal_approval_search --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}'
seal-home tool seal_approval_search --corp <corpId> --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}'
```
Get aggregated approval context:
```bash
seal-home tool seal_approval_context_get --json '{"documentLimit":20}'
seal-home tool seal_approval_context_get --corp <corpId> --json '{"documentLimit":20}'
```
Create a draft approval rule:
```bash
seal-home tool seal_approval_rule_create --json '{"description":"规则描述","scope":"适用场景","strictness":"SHOULD_FOLLOW"}'
seal-home tool seal_approval_rule_create --corp <corpId> --json '{"description":"规则描述","scope":"适用场景","strictness":"SHOULD_FOLLOW"}'
```
Update an approval document:
```bash
seal-home tool seal_approval_document_update --json '{"documentId":"doc-id","content":"Markdown 内容"}'
seal-home tool seal_approval_document_update --corp <corpId> --json '{"documentId":"doc-id","content":"Markdown 内容"}'
```
Summarize one local date:
```bash
seal-home approval-runs summary --date 2026-06-09 --timezone Asia/Shanghai --limit 100
seal-home approval-runs summary --corp <corpId> --date 2026-06-09 --timezone Asia/Shanghai --limit 100
```
Find a run and include Langfuse bridge rows:
```bash
seal-home approval-runs search --query <sourceDocumentSN> --limit 20 --includeBridge true
seal-home approval-runs search --corp <corpId> --query <sourceDocumentSN> --limit 20 --includeBridge true
```
Resolve Langfuse trace/session hints:
```bash
seal-home approval-runs bridge --sourceDocumentSN <sourceDocumentSN>
seal-home approval-runs bridge --corp <corpId> --sourceDocumentSN <sourceDocumentSN>
```
Read simulation batch records:
模拟测试批次(模拟发布闭环)创建与查询:
```bash
seal-home simulation batch-records <batchId>
# 合思指定单号: 创建批次(响应只含 batchId)
seal-home simulation create --mode hosecloud --flow-ids "B26017701,B26022501" --reject-node 财务 --thinking-depth medium --skip-invoice-generation --corp <corpId>
# 材料包导入: 先上传材料包 ZIP(服务端解析并返回 schemaConfig), 再用返回的 id 发起
seal-home simulation package-upload 测试材料包.zip --corp <corpId>
seal-home simulation create --mode material_pack --package-ids <materialPackageId> --template-id conference_reimbursement_v1 --schema-config schema.json --corp <corpId>
# 预留: 其他模式参数通过 --json 透传(如时间范围 startTime/endTime)
seal-home simulation create --mode hosecloud --flow-ids "B26017701" --json '{"startTime":0,"endTime":0}' --corp <corpId>
# 创建后轮询批次状态与记录
seal-home simulation list --limit 50 --corp <corpId>
seal-home simulation get <batchId> --corp <corpId>
seal-home simulation batch-records <batchId> --corp <corpId>
seal-home simulation templates --corp <corpId>
seal-home simulation integrations --corp <corpId>
```
## Write Operation Payloads
@@ -0,0 +1,164 @@
# Customer Feedback Rule Remediation
Use this low-freedom workflow when the user provides packaged customer feedback from WeChat, screenshots, rejection notifications, a document number, or expected business behavior and wants diagnosis or an approval-rule change.
## Workflow states
Follow these states in order:
1. `EVIDENCE_RECEIVED`
2. `TENANT_RESOLVED`
3. `RUN_RESOLVED`
4. `CAUSE_CLASSIFIED`
5. `PATCH_PROPOSED`
6. `PATCH_CONFIRMED`
7. `DRAFT_UPDATED`
8. `VERSION_PUBLISHED`
9. `VERSION_VERIFIED`
Stop at `PATCH_PROPOSED` unless the user explicitly approves the exact change and publication. A request to analyze, explain, or propose does not authorize a rule update or publish.
## 1. Normalize the evidence package
Extract only facts supported by the supplied package:
- Customer or enterprise hints
- Source document number
- Submitter and document template when visible
- AI rejection or disputed finding
- Customer-stated business behavior
- Screenshots, invoices, or attachments relevant to the dispute
- Requested action: analysis, proposal, update, or publish
Treat chat text as the customer's expected behavior, not proof of the current Seal rule or tenant identity.
## 2. Resolve and lock the enterprise
List configured enterprises first:
```bash
seal-home corps list
```
If the enterprise is named, resolve its exact `corpId`. If the enterprise is unclear but a source document number exists, run compact `approval-runs pick` queries across configured tenants and select the tenant that actually contains the document.
After resolution, pass the exact `--corp <corpId>` to every command. Do not rely on the current/default tenant.
Report the enterprise name, `corpId`, and how it was resolved.
## 3. Resolve the approval run
Start compactly:
```bash
seal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest
seal-home approval-runs get <recordId> --summary --corp <corpId>
seal-home approval-runs document-summary <recordId> --corp <corpId>
seal-home approval-runs result <recordId> --summary --corp <corpId>
seal-home approval-runs cited-rules <recordId> --corp <corpId>
```
Read attachment summaries only when the dispute depends on invoices, receipts, OCR, file type, or upload position. Use the run's historical `ruleSetVersionNumber`; do not explain a historical decision from the current draft alone.
## 4. Classify the cause
Classify the issue before proposing a change:
- `SOURCE_DATA`: source fields are wrong or incomplete.
- `ATTACHMENT_UNDERSTANDING`: OCR, vision, or attachment classification introduced the disputed fact.
- `RULE_DEFINITION`: the rule is missing, ambiguous, contradictory, or too broad.
- `MODEL_INTERPRETATION`: the supplied rule covers the case, but the model invented or misapplied a requirement.
- `SYSTEM_LOGIC`: deterministic preprocessing, grouping, or aggregation produced the wrong review unit or values.
When the editable boundary is rules only, say whether a rule-only mitigation can block the observed false positive and state any residual system limitation.
## 5. Trace only when needed
Use the Langfuse workflow from `approval-attachment-trace.md` when:
- The final decision contradicts the supplied rule.
- Cited rules are missing or incomplete.
- A disputed requirement may have entered during pre-analysis.
- The finding depends on attachment understanding.
Identify the final UI finding, the earliest stage where the disputed claim appeared, the exact rule supplied to final review, and whether final review followed or contradicted it.
## 6. Design the minimal rule patch
Fetch and compare:
- The historical rule version used by the disputed run.
- The latest published version.
- The current draft rule, including its stable rule ID.
Apply these defaults:
1. Preserve `scope`.
2. Preserve `strictness`.
3. Preserve every unrelated description clause.
4. Change only the narrowest sentence needed to block the reproduced false positive.
5. Put an exception or negative constraint next to the clause that was misinterpreted.
6. If the rule already states a positive allowance but the model still rejects it, add a narrow `不得因……驳回或建议复核` constraint covering the actual failure mode.
7. Do not add new business requirements, broad examples, or unrelated exceptions without explicit user direction.
Show a description-only unified diff by default:
```diff
unchanged text
+minimal added or changed sentence
unchanged text
```
State the target enterprise, target rule ID, changed fields, preserved fields, expected behavior, and residual limitation.
## 7. Mutation gate and concurrency check
Do not update until the user explicitly approves the exact diff.
Immediately before updating:
1. Fetch the current draft rule again.
2. Confirm its rule ID, description, scope, strictness, and status.
3. Compare the current description with the reviewed `before` text.
4. Stop if the rule changed concurrently or more than one rule matches the target.
## 8. Update and verify the draft
Send only approved fields. For a description-only change:
```bash
seal-home tool seal_approval_rule_update --corp <corpId> \
--json '{"ruleId":"<ruleId>","description":"<confirmed description>"}'
```
Do not send `scope` or `strictness` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing.
## 9. Publish and verify
Publish only when explicitly authorized:
```bash
seal-home tool seal_approval_rule_version_publish --corp <corpId> \
--json '{"versionName":"<specific business change>"}'
```
Verify after publishing:
- The new version is latest.
- Version number and version name are correct.
- Rule count is unchanged unless intentionally modified.
- The target rule contains the exact confirmed description.
- The target rule's `scope` and `strictness` are unchanged.
Do not automatically rerun or resubmit the customer's production document. Run a simulation or regression only when separately requested and authorized.
## Final response contract
Return a compact report containing:
- Enterprise and source document number
- Root-cause classification
- Target rule and exact changed text
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
@@ -9,7 +9,7 @@ Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit
```bash
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-home corps list
seal-home corps current
seal-home corps current --corp <corpId>
seal-home corps switch <corpId>
```
@@ -57,4 +57,5 @@ Important:
- Do not return the Seal tenant URL such as `https://<tenant>.sealai.cc`; that is not the Hose authorization link.
- Do not manually assemble `thirdparty.html` with a global/OpenAPI token.
- `seal-home auth diagnose` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
- **Formatting Requirement**: When returning a Hose authorization link to the user, ALWAYS provide BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- If the CLI later provides a dedicated command for this, prefer that command.
@@ -19,8 +19,8 @@ Expected shape:
Tool-layer equivalent:
```bash
seal-home tool seal_approval_rules_list --json '{"countOnly":true}'
seal-home tool seal_approval_rules_list --json '{"fields":["id"],"limit":0}'
seal-home tool seal_approval_rules_list --corp <corpId> --json '{"countOnly":true}'
seal-home tool seal_approval_rules_list --corp <corpId> --json '{"fields":["id"],"limit":0}'
```
## List Rule Summaries
@@ -31,12 +31,40 @@ Use summaries for navigation and selection.
seal-home rules list --corp <corpId> --summary
```
Default summary should include only fields such as `id`, `scope`, `strictness`, `status`, and `updatedAt`. Do not pull `description` unless the user needs rule text.
Default summary should include only fields such as `id`, `code`, `scope`, `strictness`, `status`, and `updatedAt`. Do not pull `description` unless the user needs rule text.
Tool-layer equivalent:
```bash
seal-home tool seal_approval_rules_list --json '{"fields":["id","scope","strictness","status","updatedAt"]}'
seal-home tool seal_approval_rules_list --corp <corpId> --json '{"fields":["id","code","scope","strictness","status","updatedAt"]}'
```
## Clear Draft Rules Before Import
Use this for test tenants when the next step is importing another tenant's rule set. Always preview first unless the user has already confirmed the exact tenant.
```bash
seal-home rules clear --corp <corpId> --dry-run
seal-home rules clear --corp <corpId> --yes
```
Expected shape:
```json
{
"corpId": "xiezihao",
"dryRun": false,
"beforeCount": 49,
"deleted": 49,
"afterCount": 0
}
```
Tool-layer equivalent:
```bash
seal-home tool seal_approval_rules_clear --corp <corpId> --json '{"dryRun":true}'
seal-home tool seal_approval_rules_clear --corp <corpId> --json '{"dryRun":false}'
```
## Get One Historical Rule
@@ -44,14 +72,14 @@ seal-home tool seal_approval_rules_list --json '{"fields":["id","scope","strictn
Use this when a run used a historical rule version and current rules may differ.
```bash
seal-home rules get --version 16 --code '#0038'
seal-home rules get --version latest --code '#0038'
seal-home rules get --corp <corpId> --version 16 --code '#0038'
seal-home rules get --corp <corpId> --version latest --code '#0038'
```
If the user starts from a run and a runtime ID such as `rule-205`, resolve against that run:
```bash
seal-home rules get --record-id <recordId> --runtime-id rule-205
seal-home rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
```
Return the single rule text plus `scope`, `strictness`, `status`, `versionNumber`, and version metadata. Avoid commands that dump a whole rule version unless the user asks for the full version.
@@ -61,13 +89,13 @@ Return the single rule text plus `scope`, `strictness`, `status`, `versionNumber
Prefer scoped and trimmed search:
```bash
seal-home tool seal_approval_search --json '{"keywords":["关键词"],"areas":["rules"],"matchMode":"any","maxResults":20,"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}'
seal-home tool seal_approval_search --corp <corpId> --json '{"keywords":["关键词"],"areas":["rules"],"matchMode":"any","maxResults":20,"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}'
```
When investigating historical behavior, search the matching rule version if the API supports it:
```bash
seal-home tool seal_approval_search --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","versionNumber":16,"snippetOnly":true,"maxChars":500}'
seal-home tool seal_approval_search --corp <corpId> --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","versionNumber":16,"snippetOnly":true,"maxChars":500}'
```
Use current search only when the question is about current draft/current knowledge, not why a historical run behaved a certain way.
+188
View File
@@ -0,0 +1,188 @@
import { afterEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { VERSION } from "./version.js";
const CLI_PATH = join(import.meta.dirname, "cli.ts");
const tempDirs: string[] = [];
function runCli(args: string[], env: Record<string, string> = {}) {
return spawnSync("bun", [CLI_PATH, ...args], {
encoding: "utf-8",
env: { ...process.env, ...env }
});
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("CLI version & help handling", () => {
test.each([
["version"],
["v"],
["-v"],
["-version"],
["--version"],
["-V"],
["--v"],
["--V"]
])("version command alias '%s' returns version JSON", (flag) => {
const result = runCli([flag]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.name).toBe("seal-home");
expect(parsed.version).toBe(VERSION);
});
test("help command prints standard help banner", () => {
const result = runCli(["help"]);
expect(result.status).toBe(0);
expect(result.stdout).toContain("seal-home CLI");
expect(result.stdout).toContain("Usage:");
expect(result.stdout).toContain("seal-home mcp");
expect(result.stdout).toContain("seal-home probe [<corpId>]");
expect(result.stdout).toContain("seal-home users search <keyword>");
expect(result.stdout).toContain("seal-home users delegation <userIdOrPhone|name>");
expect(result.stdout).toContain("seal-home webhook get|find <idOrName>");
expect(result.stdout).toContain("seal-home webhook add --name <name> --result-url <url>");
expect(result.stdout).toContain("[--secret <secret>|--rotate-secret]");
});
test("invalid command displays unknown command error with help hint", () => {
const result = runCli(["invalid-command"]);
expect(result.status).toBe(1);
expect(result.stderr).toContain("Unknown command: invalid-command. Run 'seal-home help' for available commands.");
});
test("requires --corp in the default stateless mode", () => {
const env = makeConfigEnv();
const result = runCli(["corps", "current"], env);
expect(result.status).toBe(1);
expect(result.stderr).toContain("Stateless mode is enabled");
expect(result.stderr).toContain("--corp <corpId>");
});
test("allows an explicit corp in stateless mode", () => {
const env = makeConfigEnv();
const result = runCli(["corps", "current", "--corp", "corp-a"], env);
expect(result.status).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({ id: "corp-a" });
});
test("keeps the fine-grained tool command reachable in stateless mode", () => {
const env = makeConfigEnv();
const result = runCli(["tool", "unknown-tool", "--corp", "corp-a"], env);
expect(result.status).toBe(1);
expect(result.stderr).toContain("Unknown Seal tool: unknown-tool");
});
test("can enable stateful mode and select a default corp", () => {
const env = makeConfigEnv();
const mode = runCli(["config", "mode", "stateful", "--corp", "corp-a"], env);
const current = runCli(["corps", "current"], env);
expect(mode.status).toBe(0);
expect(JSON.parse(mode.stdout)).toMatchObject({
mode: "stateful",
defaultCorpId: "corp-a"
});
expect(current.status).toBe(0);
expect(JSON.parse(current.stdout)).toMatchObject({ id: "corp-a" });
});
test("removes the default when switching back to stateless mode", () => {
const env = makeConfigEnv();
runCli(["config", "mode", "stateful", "--corp", "corp-a"], env);
const mode = runCli(["config", "mode", "stateless"], env);
const current = runCli(["corps", "current"], env);
expect(mode.status).toBe(0);
expect(JSON.parse(mode.stdout)).toMatchObject({ mode: "stateless" });
expect(JSON.parse(mode.stdout)).not.toHaveProperty("defaultCorpId");
expect(current.status).toBe(1);
expect(current.stderr).toContain("Stateless mode is enabled");
});
test("update command runs in source mode when executed from bun", () => {
const result = runCli(["update"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.updated).toBe(true);
expect(parsed.mode).toBe("source");
expect(parsed.version).toBe(VERSION);
});
test("mcp-config outputs valid mcp configuration json", () => {
const result = runCli(["mcp-config"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.mcpServers["seal-home"]).toMatchObject({
command: "seal-home",
args: ["mcp"]
});
});
test("skill dump outputs embedded skill markdown", () => {
const result = runCli(["skill", "dump"]);
expect(result.status).toBe(0);
expect(result.stdout).toContain("name: seal-home");
expect(result.stdout).toContain("# Seal Home");
});
test("skill status outputs installation directories", () => {
const result = runCli(["skill", "status"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.global).toHaveProperty("dir");
expect(parsed.local).toHaveProperty("dir");
});
test("skill install writes files to specified directory", () => {
const tmp = mkdtempSync(join(tmpdir(), "cli-skill-install-"));
tempDirs.push(tmp);
const result = runCli(["skill", "install", "--dir", tmp]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.installed).toBe(true);
expect(parsed.targetDir).toBe(tmp);
expect(parsed.fileCount).toBeGreaterThan(5);
});
test("openapi command outputs embedded OpenAPI specification", () => {
const result = runCli(["openapi"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.openapi).toBe("3.1.0");
expect(parsed.info.title).toContain("seal-home");
expect(parsed.paths).toHaveProperty("/v1/corps");
});
});
function makeConfigEnv(): Record<string, string> {
const root = mkdtempSync(join(tmpdir(), "seal-home-cli-"));
tempDirs.push(root);
const enterprises = join(root, "enterprises");
mkdirSync(enterprises, { recursive: true });
writeFileSync(join(enterprises, "corp-a.json"), JSON.stringify({
id: "corp-a",
name: "Corp A",
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://corp-a.seal.test"
}
}));
return {
SEAL_HOME_ENTERPRISES_DIR: enterprises,
SEAL_HOME_CONFIG_FILE: join(root, "config.json")
};
}
+31 -1158
View File
File diff suppressed because it is too large. Load diff
+185
View File
@@ -0,0 +1,185 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool, runToolResult } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleApprovalRunsCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "summary") {
const result = await runToolResult(
"seal_approval_runs_summary",
client,
corp,
{
date: stringOption(args.options.date),
timezone: stringOption(args.options.timezone),
limit: numberOption(args.options.limit),
startDate: stringOption(args.options.startDate),
endDate: stringOption(args.options.endDate),
status: stringOption(args.options.status),
taskMode: stringOption(args.options.taskMode),
manualApprovalStatus: stringOption(args.options.manualApprovalStatus),
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
sourceDocumentId: stringOption(args.options.sourceDocumentId),
humanResult: stringOption(args.options.humanResult),
query: stringOption(args.options.query)
}
);
if ((result as any)?.matched === 0 && (result as any)?.total > 0) {
console.error(
`提示:在 ${(result as any).date} 未匹配到记录(该企业共有 ${(result as any).total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-home approval-runs list --limit 10 查看最近记录。`
);
}
printJson(result, outputOptions(args.options));
return;
}
if (action === "search" || action === "list") {
await runTool(
"seal_approval_runs_search",
client,
corp,
{
limit: numberOption(args.options.limit),
offset: numberOption(args.options.offset),
startDate: stringOption(args.options.startDate),
endDate: stringOption(args.options.endDate),
status: stringOption(args.options.status),
taskMode: stringOption(args.options.taskMode),
manualApprovalStatus: stringOption(args.options.manualApprovalStatus),
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
sourceDocumentId: stringOption(args.options.sourceDocumentId),
humanResult: stringOption(args.options.humanResult),
query: stringOption(args.options.query),
includeBridge: booleanOption(args.options.includeBridge)
},
outputOptions(args.options)
);
return;
}
if (action === "bridge") {
await runTool(
"seal_approval_run_langfuse_bridge_get",
client,
corp,
{
recordId: stringOption(args.options.recordId),
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
sourceDocumentId: stringOption(args.options.sourceDocumentId),
simulationBatchId: stringOption(args.options.simulationBatchId),
limit: numberOption(args.options.limit)
},
outputOptions(args.options)
);
return;
}
if (action === "pick") {
const query = maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.sn);
if (!query) throw new Error("Usage: seal-home approval-runs pick --sn <documentSN>");
await runTool(
"seal_approval_run_pick",
client,
corp,
{
query,
sn: stringOption(args.options.sn),
batchId: stringOption(args.options.batch) ?? stringOption(args.options.batchId),
latest: booleanOption(args.options.latest),
fields: stringOption(args.options.fields),
limit: numberOption(args.options.limit),
includeBridge: booleanOption(args.options.includeBridge)
},
outputOptions(args.options)
);
return;
}
if (action === "get") {
const recordId = args.command[2];
if (!recordId) throw new Error("Missing approval run recordId");
await runTool(
"seal_approval_run_get",
client,
corp,
{
recordId,
fields: stringOption(args.options.fields),
summary: booleanOption(args.options.summary)
},
outputOptions(args.options)
);
return;
}
if (action === "cited-rules") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-home approval-runs cited-rules <recordId>");
await runTool("seal_approval_run_cited_rules_get", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "document-summary") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-home approval-runs document-summary <recordId>");
await runTool("seal_approval_run_document_summary_get", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "attachments") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-home approval-runs attachments <recordId>");
await runTool(
"seal_approval_run_attachments_get",
client,
corp,
{
recordId,
summary: booleanOption(args.options.summary)
},
outputOptions(args.options)
);
return;
}
if (action === "result") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-home approval-runs result <recordId> [--summary]");
await runTool(
"seal_approval_run_result_get",
client,
corp,
{
recordId,
summary: booleanOption(args.options.summary)
},
outputOptions(args.options)
);
return;
}
if (action === "url") {
await runTool(
"seal_approval_run_url_get",
client,
corp,
{
recordId: maybeName,
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
sourceDocumentId: stringOption(args.options.sourceDocumentId)
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+280
View File
@@ -0,0 +1,280 @@
import { getHoseProvisionalAuthLink } from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import type { CorpConfig } from "../../core/config/types.js";
import { createSealClient } from "../../core/http/factory.js";
import { getMe } from "../../domains/seal/api.js";
import { numberOption } from "../parser.js";
import { printJson, redactSensitiveText } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleAuthCommand(action: string | undefined, corp: CorpConfig, args: ParsedArgs) {
if (action === "diagnose") {
printJson(await diagnoseAuth(corp));
return;
}
if (action === "hose-link") {
const expiresIn = numberOption(args.options.expire) ?? 7200;
printJson(await getHoseProvisionalAuthLink(corp, expiresIn));
return;
}
throw new Error(`Unknown auth command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
export async function diagnoseAuth(corp: CorpConfig) {
if (corp.source.type !== "hose") {
const client = await createSealClient(corp);
const me = await getMe(client);
return {
corp: {
id: corp.id,
name: corp.name,
sourceType: corp.source.type
},
ok: true,
stages: [
{
name: "seal.whoami",
ok: true,
user: me.user,
tenant: me.tenant
}
]
};
}
clearCorpTokenCache(corp.id);
const source = corp.source;
const appKey = source.appKey ?? source.key;
const appSecurity = source.appSecurity ?? source.password;
const sealUrl = (corp.seal.url ?? source.sealUrl ?? `https://${source.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
const uid = source.staffId.includes(":") ? source.staffId : `${source.corpId}:${source.staffId}`;
const stages: Array<Record<string, unknown>> = [];
if (!appKey || !appSecurity) {
return {
corp: {
id: corp.id,
name: corp.name,
sourceType: corp.source.type
},
ok: false,
stages: [
{
name: "hose.openapi",
ok: false,
error: "Hose source requires appKey/key and appSecurity/password"
}
]
};
}
const openapi = await runDiagnoseStage("hose.openapi", async () => {
const json = await postJson(`${source.domain.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, {
appKey,
appSecurity
});
const value = objectValue(json.value);
const token = stringValue(value.accessToken) ?? stringValue(json.accessToken) ?? stringValue(json.token);
if (!token) throw new Error("Hose login did not return an access token");
return {
token,
public: {
corporationId: stringValue(value.corporationId) ?? stringValue(objectValue(value.corporation).id),
expireTime: numberValue(value.expireTime)
}
};
});
stages.push(openapi.public);
const openapiToken = openapi.private?.token;
const provisional = openapiToken
? await runDiagnoseStage("hose.provisional", async () => {
const json = await postJson(
`${source.domain.replace(/\/+$/, "")}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=${encodeURIComponent(openapiToken)}`,
{
uid,
pageType: "home",
expireDate: 7200
}
);
const url = stringValue(objectValue(json.value).message);
if (!url) throw new Error("Hose CloseAPI did not return a provisional auth URL");
const token = new URL(url).searchParams.get("accessToken");
if (!token) throw new Error("Hose provisional auth URL did not include accessToken");
return {
token,
public: {
uid,
enterpriseUrl: redactSensitiveText(url)
}
};
})
: skippedStage("hose.provisional");
stages.push(provisional.public);
const provisionalToken = provisional.private?.token;
const sealSession = provisionalToken
? await runDiagnoseStage("seal.sso", async () => {
const json = await getJson(
`${sealUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&returnToken=1`
);
const data = objectValue(json.data);
const token =
stringValue(json.token) ??
stringValue(json.accessToken) ??
stringValue(data.token) ??
stringValue(data.accessToken);
if (!token) throw new Error("Seal SSO did not return a bearer token");
return {
token,
public: {
sealUrl,
expiresIn: numberValue(json.expiresIn) ?? numberValue(json.expires_in) ?? numberValue(data.expiresIn) ?? numberValue(data.expires_in)
}
};
})
: skippedStage("seal.sso");
stages.push(sealSession.public);
const sealToken = sealSession.private?.token;
const whoami = sealToken
? await runDiagnoseStage("seal.whoami", async () => {
const json = await getJson(`${sealUrl}/api/v1/auth/me`, {
authorization: `Bearer ${sealToken}`
});
const data = objectValue(json.data);
const user = objectValue(data.user ?? json.user);
const tenant = objectValue(data.tenant ?? json.tenant);
return {
public: {
user: {
id: stringValue(user.id),
name: stringValue(user.name),
isAdmin: booleanValue(user.isAdmin),
providerUserId: stringValue(user.providerUserId)
},
tenant: {
id: stringValue(tenant.id),
name: stringValue(tenant.name),
tenantSlug: stringValue(tenant.tenantSlug),
hoseCorpConfig: summarizeHoseCorpConfig(tenant.hoseCorpConfig)
}
}
};
})
: skippedStage("seal.whoami");
stages.push(whoami.public);
return {
corp: {
id: corp.id,
name: corp.name,
sourceType: corp.source.type
},
ok: stages.every((stage) => stage.ok === true),
stages
};
}
type DiagnoseStageResult = {
public: Record<string, unknown>;
private?: {
token?: string;
};
};
async function runDiagnoseStage(
name: string,
action: () => Promise<{ public: Record<string, unknown>; token?: string }>
): Promise<DiagnoseStageResult> {
try {
const result = await action();
return {
public: {
name,
ok: true,
...compactObject(result.public)
},
private: result.token ? { token: result.token } : undefined
};
} catch (error) {
return {
public: {
name,
ok: false,
error: redactSensitiveText(error instanceof Error ? error.message : String(error))
}
};
}
}
function skippedStage(name: string): DiagnoseStageResult {
return {
public: {
name,
ok: false,
skipped: true
}
};
}
async function postJson(url: string, body: Record<string, unknown>): Promise<Record<string, unknown>> {
const response = await fetch(url, {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify(body)
});
return parseJsonResponse(response);
}
async function getJson(url: string, headers: Record<string, string> = {}): Promise<Record<string, unknown>> {
const response = await fetch(url, {
headers
});
return parseJsonResponse(response);
}
async function parseJsonResponse(response: Response): Promise<Record<string, unknown>> {
const body = await response.text();
if (!response.ok) {
throw new Error(`${response.status} ${body}`);
}
const json = JSON.parse(body) as unknown;
return objectValue(json);
}
function objectValue(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function stringValue(value: unknown): string | undefined {
return typeof value === "string" && value ? value : undefined;
}
function numberValue(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function booleanValue(value: unknown): boolean | undefined {
return typeof value === "boolean" ? value : undefined;
}
function summarizeHoseCorpConfig(value: unknown) {
const config = objectValue(value);
return compactObject({
corporationId: stringValue(config.corporationId),
corporationName: stringValue(config.corporationName)
});
}
function compactObject<T extends Record<string, unknown>>(value: T): T {
return Object.fromEntries(
Object.entries(value).filter(([, item]) => item !== undefined)
) as T;
}
+29
View File
@@ -0,0 +1,29 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleBillingCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "status" || action === "get") {
await runTool("seal_billing_status_get", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "plans") {
await runTool("seal_billing_plans_list", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "features") {
await runTool("seal_billing_features_list", client, corp, {}, outputOptions(args.options));
return;
}
throw new Error(`Unknown billing command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+56
View File
@@ -0,0 +1,56 @@
import {
getEnterprisesDirCandidates,
loadCorpConfigs,
loadGlobalConfig,
resolveGlobalConfigFile,
saveGlobalConfig
} from "../../core/config/loader.js";
import { resolveCorpConfig } from "../../core/config/manager.js";
import { globalConfigSummary } from "../helpers.js";
import { parseStateMode, stringOption } from "../parser.js";
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export function handleConfigCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
if (action === "paths") {
printJson({
candidates: getEnterprisesDirCandidates(),
globalConfigFile: resolveGlobalConfigFile()
});
return;
}
if (action === "get" || action === "status") {
printJson(globalConfigSummary());
return;
}
if (action === "mode") {
const mode = maybeName ?? stringOption(args.options.mode);
if (!mode) {
printJson(globalConfigSummary());
return;
}
const stateful = parseStateMode(mode);
const requestedCorpId = stringOption(args.options.corp);
const previousConfig = loadGlobalConfig();
const defaultCorpId = stateful
? requestedCorpId
? resolveCorpConfig(
loadCorpConfigs(),
{ stateful: true, corpId: requestedCorpId },
getEnterprisesDirCandidates()
).id
: previousConfig.defaultCorpId
: undefined;
const config = saveGlobalConfig({
stateful,
...(defaultCorpId ? { defaultCorpId } : {})
});
printJson(globalConfigSummary(config));
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+23
View File
@@ -0,0 +1,23 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { numberOption, ruleVersionContextOptions, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleContextCommand(
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
await runTool(
"seal_approval_context_get",
client,
corp,
{
documentLimit: numberOption(args.options.documentLimit),
...ruleVersionContextOptions(stringOption(args.options.ruleVersion))
},
outputOptions(args.options)
);
}
+300
View File
@@ -0,0 +1,300 @@
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import {
loadCorpConfigs,
loadGlobalConfig,
resolveWritableEnterprisesDir,
saveGlobalConfig
} from "../../core/config/loader.js";
import type { CorpConfig } from "../../core/config/types.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
import { selectCorp } from "../helpers.js";
import {
inferCorpIdFromStaffId,
jsonObject,
optionalNumber,
optionalString,
requiredString,
requiredStringAlias,
safeFileName,
stringOption
} from "../parser.js";
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleCorpsCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
if (action === "list") {
const corpId = stringOption(args.options.corp);
const corps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
const currentCorpId = corpId ?? (
globalConfig.stateful
? globalConfig.defaultCorpId ?? corps[0]?.id
: undefined
);
if (corps.length === 0) {
console.error("提示:当前未检测到企业配置。你可以使用 seal-home corps add-hose 或 seal-home corps add-seal 添加企业,或运行 seal-home help 查看说明。");
}
printJson(corps.map((item) => ({
id: item.id,
name: item.name,
sourceType: item.source.type,
provider: (item.source as any).provider ?? item.source.type,
current: item.id === currentCorpId
})));
return;
}
if (action === "current") {
const corp = selectCorp(stringOption(args.options.corp));
printJson({
id: corp.id,
name: corp.name,
sourceType: corp.source.type,
provider: (corp.source as any).provider ?? corp.source.type
});
return;
}
if (action === "switch") {
const corpId = maybeName;
if (!corpId) throw new Error("Usage: seal-home corps switch <corpId>");
const globalConfig = loadGlobalConfig();
if (!globalConfig.stateful) {
throw new Error(
"Cannot switch the default enterprise while stateless mode is enabled. " +
"Use `seal-home config mode stateful` first."
);
}
const corp = selectCorp(corpId);
saveGlobalConfig({ ...globalConfig, stateful: true, defaultCorpId: corp.id });
printJson({
current: true,
id: corp.id,
name: corp.name
});
return;
}
if (action === "add-hose") {
await addHoseCorp(jsonObject(args.json));
return;
}
if (action === "add-seal") {
await addSealCorp(jsonObject(args.json));
return;
}
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
async function addHoseCorp(input: Record<string, unknown>) {
const nameInput = optionalString(input, "name");
const appKey = requiredString(input, "appKey");
const appSecurity = requiredString(input, "appSecurity");
const staffId = requiredStringAlias(input, ["staffId", "proxyStaffBizId"]);
const corpIdInput =
optionalString(input, "corpId") ??
optionalString(input, "corporationId");
const domain = optionalString(input, "domain") ?? "https://app.ekuaibao.com";
const verify = input.force === true || input.verify === false ? false : true;
const remote = corpIdInput && !verify
? undefined
: await resolveHoseCorporation(domain, appKey, appSecurity);
const corpId = corpIdInput ?? remote?.id ?? (!verify ? inferCorpIdFromStaffId(staffId) : undefined);
if (!corpId) {
throw new Error(
"Missing required JSON field: corpId. Hose login did not return corporationId. Pass force:true to infer it from proxyStaffBizId."
);
}
const id = optionalString(input, "id") ?? corpId;
const name = nameInput ?? remote?.name ?? corpId;
const sealUrl = optionalString(input, "sealUrl") ?? `https://${corpId.toLowerCase()}.sealai.cc`;
const config: CorpConfig = {
id,
name,
seal: {
url: sealUrl,
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "hose",
domain,
appKey,
appSecurity,
corpId,
staffId
},
auth: {
refreshTtl: 300
}
};
if (verify) {
clearCorpTokenCache(id);
await resolveLiveSealEnterpriseConfig(config);
}
const enterprisesDir = resolveWritableEnterprisesDir();
mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 });
const file = join(enterprisesDir, `${safeFileName(id)}.json`);
if (existsSync(file) && input.overwrite !== true) {
throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`);
}
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
printJson({
id,
name,
corpId,
verified: verify,
path: file
});
}
async function addSealCorp(input: Record<string, unknown>) {
const token = requiredString(input, "token");
const sealUrl = (optionalString(input, "sealUrl") ?? optionalString(input, "url") ?? "").replace(/\/+$/, "");
if (!sealUrl) throw new Error("Missing required JSON field: sealUrl");
const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60;
const verify = input.force === true || input.verify === false ? false : true;
const remote = verify ? await resolveSealWhoami(sealUrl, token) : undefined;
const remoteUser = remote?.user;
const remoteTenant = remote?.tenant;
const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue(remoteTenant?.tenantSlug);
const tenantId = optionalString(input, "tenantId") ?? stringValue(remoteTenant?.id);
const tenantName = optionalString(input, "tenantName") ??
optionalString(input, "name") ??
stringValue(remoteTenant?.name);
const id = optionalString(input, "id") ?? tenantSlug ?? tenantId;
if (!id) {
throw new Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");
}
const staffId = optionalString(input, "staffId") ??
stringValue(remoteUser?.providerUserId) ??
stringValue(remoteUser?.id) ??
"seal";
const provider = optionalString(input, "provider") ??
stringValue(remoteUser?.provider) ??
stringValue((remoteTenant as any)?.providerConfig?.provider);
const config: CorpConfig = {
id,
name: tenantName ?? id,
seal: {
url: sealUrl,
tenantSlug,
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "seal",
token,
sealUrl,
expiresIn,
staffId,
corpId: tenantSlug ?? tenantId ?? id,
tenantId,
tenantSlug,
tenantName,
providerUserId: stringValue(remoteUser?.providerUserId),
provider
},
auth: {
refreshTtl: 300
}
};
const enterprisesDir = resolveWritableEnterprisesDir();
mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 });
const file = join(enterprisesDir, `${safeFileName(id)}.json`);
if (existsSync(file) && input.overwrite !== true) {
throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`);
}
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
printJson({
id,
name: config.name,
tenantId,
tenantSlug,
verified: verify,
path: file
});
}
async function resolveHoseCorporation(domain: string, appKey: string, appSecurity: string) {
const response = await fetch(`${domain.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
appKey,
appSecurity
})
});
if (!response.ok) {
const body = await response.text().catch(() => "");
throw new Error(`Hose login failed: ${response.status}${body ? ` ${body}` : ""}`);
}
const data = (await response.json()) as {
value?: {
corporationId?: string;
corporation?: {
id?: string;
name?: string;
};
};
};
const corporationId = data.value?.corporationId ?? data.value?.corporation?.id;
return corporationId
? {
id: corporationId,
name: data.value?.corporation?.name
}
: undefined;
}
async function resolveSealWhoami(sealUrl: string, token: string) {
const json = await getJson(`${sealUrl}/api/v1/auth/me`, {
authorization: `Bearer ${token}`
});
const data = objectValue(json.data);
return {
user: objectValue(data.user ?? json.user),
tenant: objectValue(data.tenant ?? json.tenant)
};
}
async function getJson(url: string, headers: Record<string, string> = {}): Promise<Record<string, unknown>> {
const response = await fetch(url, {
headers
});
const body = await response.text();
if (!response.ok) {
throw new Error(`${response.status} ${body}`);
}
const json = JSON.parse(body) as unknown;
return objectValue(json);
}
function objectValue(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function stringValue(value: unknown): string | undefined {
return typeof value === "string" && value ? value : undefined;
}
+34
View File
@@ -0,0 +1,34 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleDelegationCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "list") {
await runTool("seal_delegation_list", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "create") {
const note = stringOption(args.options.note) ?? (maybeName ? [maybeName, ...args.command.slice(2)].join(" ") : undefined);
await runTool("seal_delegation_create", client, corp, { note }, outputOptions(args.options));
return;
}
if (action === "revoke") {
const tokenId = maybeName ?? stringOption(args.options.tokenId);
if (!tokenId) throw new Error("Usage: seal-home delegation revoke <tokenId>");
await runTool("seal_delegation_revoke", client, corp, { tokenId }, outputOptions(args.options));
return;
}
throw new Error(`Unknown delegation command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+24
View File
@@ -0,0 +1,24 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleLlmCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "config" || action === "get") {
await runTool("seal_llm_config_get", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "providers" || action === "list") {
await runTool("seal_llm_providers_list", client, corp, {}, outputOptions(args.options));
return;
}
throw new Error(`Unknown llm command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+27
View File
@@ -0,0 +1,27 @@
import { startServer } from "../../server.js";
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleMcpCommand(action: string | undefined, args: ParsedArgs) {
if (action === "config" || action === "json") {
printMcpConfig();
return;
}
await startServer();
}
export function printMcpConfig() {
printJson({
mcpServers: {
"seal-home": {
type: "stdio",
command: "seal-home",
args: ["mcp"],
env: {
SEAL_HOME_MCP_ENABLED: "true"
}
}
}
});
}
+8
View File
@@ -0,0 +1,8 @@
import { getOpenApiSchema } from "../../core/embedded-openapi.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export function handleOpenApiCommand(args: ParsedArgs) {
const schema = getOpenApiSchema();
printJson(schema, { ...outputOptions(args.options), allowFull: true });
}
+24
View File
@@ -0,0 +1,24 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handlePermissionsCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "available") {
await runTool("seal_permissions_available_list", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "configs" || action === "list") {
await runTool("seal_permissions_configs_list", client, corp, {}, outputOptions(args.options));
return;
}
throw new Error(`Unknown permissions command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+8
View File
@@ -0,0 +1,8 @@
import { runProbe } from "../../probe.js";
import { stringOption } from "../parser.js";
import type { ParsedArgs } from "../types.js";
export async function handleProbeCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
const corpId = maybeName ?? stringOption(args.options.corp) ?? (action && action !== "--corp" ? action : undefined);
await runProbe({ corpId });
}
+144
View File
@@ -0,0 +1,144 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool, runToolResult } from "../helpers.js";
import {
booleanOption,
numberOption,
parseRuleVersionSelector,
ruleVersionGetOptions,
ruleVersionSearchOptions,
splitOption,
stringOption
} from "../parser.js";
import {
outputOptions,
printJson,
protectLargeRuleListOutput,
RULE_SUMMARY_FIELDS
} from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleRulesCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "count") {
await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options));
return;
}
if (action === "list") {
if (booleanOption(args.options.count)) {
await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options));
return;
}
const limit = numberOption(args.options.limit);
const offset = numberOption(args.options.offset);
if (booleanOption(args.options.summary)) {
await runTool(
"seal_approval_rules_list",
client,
corp,
{
fields: RULE_SUMMARY_FIELDS,
limit,
offset
},
outputOptions(args.options)
);
return;
}
const result = await runToolResult("seal_approval_rules_list", client, corp, { limit, offset });
protectLargeRuleListOutput(result, booleanOption(args.options.full) === true);
printJson(result);
return;
}
if (action === "clear") {
const confirmed = booleanOption(args.options.yes) === true;
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
if (!confirmed && !dryRun) {
throw new Error("Refusing to clear rules without --yes. Use --dry-run to preview.");
}
const result = await runToolResult("seal_approval_rules_clear", client, corp, {
dryRun,
recode: booleanOption(args.options.recode)
});
if (!confirmed && dryRun && result && typeof result === "object") {
printJson(
{
...result,
nextCommand: `seal-home rules clear --corp ${corp.id} --yes`
},
outputOptions(args.options)
);
return;
}
printJson(result, outputOptions(args.options));
return;
}
if (action === "versions") {
await runTool("seal_approval_rule_versions_list", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "version") {
const version = maybeName ?? stringOption(args.options.version);
if (!version) throw new Error("Usage: seal-home rules version <versionId|versionNumber|latest>");
await runTool(
"seal_approval_rule_version_get",
client,
corp,
parseRuleVersionSelector(version),
outputOptions(args.options)
);
return;
}
if (action === "get") {
await runTool(
"seal_approval_rule_get",
client,
corp,
{
...ruleVersionGetOptions(stringOption(args.options.version)),
code: stringOption(args.options.code),
runtimeId: stringOption(args.options.runtimeId) ?? stringOption(args.options["runtime-id"]),
recordId: stringOption(args.options.recordId) ?? stringOption(args.options["record-id"])
},
outputOptions(args.options)
);
return;
}
if (action === "search") {
const keyword = maybeName ?? stringOption(args.options.query);
if (!keyword) throw new Error("Usage: seal-home rules search <keyword> [--version <versionId|versionNumber|latest>]");
await runTool(
"seal_approval_search",
client,
corp,
{
keywords: [keyword],
areas: ["rules"],
maxResults: numberOption(args.options.maxResults),
contextLines: numberOption(args.options.contextLines),
refresh: booleanOption(args.options.refresh),
snippetOnly: booleanOption(args.options.snippetOnly) ?? booleanOption(args.options["snippet-only"]),
maxChars: numberOption(args.options.maxChars) ?? numberOption(args.options["max-chars"]),
fields: splitOption(args.options.fields),
...ruleVersionSearchOptions(stringOption(args.options.version))
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+19
View File
@@ -0,0 +1,19 @@
import { homedir } from "node:os";
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";
export const STATE_DIR = join(homedir(), ".config", "seal-home");
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
});
if (result !== undefined) printJson(result);
}
+107
View File
@@ -0,0 +1,107 @@
import { existsSync, 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 {
booleanOption,
jsonObject,
numberOption,
splitOption,
stringOption
} from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleSimulationCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "batch-records") {
const batchId = maybeName ?? stringOption(args.options.batchId);
if (!batchId) throw new Error("Usage: seal-home simulation batch-records <batchId>");
await runTool(
"seal_simulation_batch_records_get",
client,
corp,
{
batchId,
query: stringOption(args.options.query)
},
outputOptions(args.options)
);
return;
}
if (action === "create") {
const modeArg = stringOption(args.options.mode) ?? "hosecloud";
const mode = modeArg === "material-pack" ? "material_pack" : modeArg;
const schemaConfigPath = stringOption(args.options.schemaConfig) ?? stringOption(args.options["schema-config"]);
const schemaConfig = schemaConfigPath
? JSON.parse(readFileSync(schemaConfigPath, "utf8"))
: undefined;
await runTool(
"seal_simulation_batch_create",
client,
corp,
{
mode,
flowIds: splitOption(args.options.flowIds) ?? splitOption(args.options["flow-ids"]),
rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null,
thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]),
skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]),
skipExpenseExtraction: booleanOption(args.options.skipExpenseExtraction) ?? booleanOption(args.options["skip-expense-extraction"]),
disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]),
signKey: stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]),
packageIds: splitOption(args.options.packageIds) ?? splitOption(args.options["package-ids"]),
templateId: stringOption(args.options.templateId) ?? stringOption(args.options["template-id"]),
schemaConfig,
rawParams: jsonObject(args.json)
},
outputOptions(args.options)
);
return;
}
if (action === "list") {
await runTool(
"seal_simulation_batches_list",
client,
corp,
{
limit: numberOption(args.options.limit)
},
outputOptions(args.options)
);
return;
}
if (action === "get") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-home simulation get <batchId>");
await runTool("seal_simulation_batch_get", client, corp, { batchId }, outputOptions(args.options));
return;
}
if (action === "templates") {
await runTool("seal_simulation_templates_get", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "integrations") {
await runTool("seal_simulation_integrations_get", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "package-upload") {
const filePath = maybeName ?? stringOption(args.options.file);
if (!filePath) throw new Error("Usage: seal-home simulation package-upload <材料包.zip>");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
await runTool("seal_simulation_material_package_upload", client, corp, { filePath }, outputOptions(args.options));
return;
}
throw new Error(`Unknown simulation command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+54
View File
@@ -0,0 +1,54 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
getDefaultGlobalSkillDir,
getSkillContent,
installSkillFiles
} from "../../core/embedded-skill.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export function handleSkillCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
if (action === "dump" || action === "cat" || action === "show") {
process.stdout.write(`${getSkillContent()}\n`);
return;
}
if (action === "install" || action === "init" || action === "sync") {
const isLocal = booleanOption(args.options.local) || booleanOption(args.options.workspace);
const customDir = stringOption(args.options.dir) ?? stringOption(args.options.target) ?? maybeName;
const targetDir = customDir
? customDir
: isLocal
? join(process.cwd(), ".agents", "skills", "seal-home")
: getDefaultGlobalSkillDir();
const result = installSkillFiles(targetDir);
printJson({
installed: true,
targetDir: result.targetDir,
fileCount: result.files.length,
files: result.files
});
return;
}
if (action === "status" || action === "get" || !action) {
const globalDir = getDefaultGlobalSkillDir();
const localDir = join(process.cwd(), ".agents", "skills", "seal-home");
printJson({
global: {
dir: globalDir,
installed: existsSync(join(globalDir, "SKILL.md"))
},
local: {
dir: localDir,
installed: existsSync(join(localDir, "SKILL.md"))
}
});
return;
}
throw new Error(`Unknown skill command: ${action}. Run 'seal-home help' for available commands.`);
}
+12
View File
@@ -0,0 +1,12 @@
import type { CorpConfig } from "../../core/config/types.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
import { printJson } from "../printer.js";
export async function handleSourceCommand(action: string | undefined, corp: CorpConfig) {
if (action === "config") {
printJson(await resolveLiveSealEnterpriseConfig(corp));
return;
}
throw new Error(`Unknown source command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+16
View File
@@ -0,0 +1,16 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { jsonObject } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleToolCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (!action) throw new Error("Usage: seal-home tool <toolName> [--json '{...}']");
await runTool(action, client, corp, jsonObject(args.json), outputOptions(args.options));
}
+6
View File
@@ -0,0 +1,6 @@
import { sealTools } from "../../domains/seal/tools.js";
import { printJson } from "../printer.js";
export function handleToolsListCommand() {
printJson(sealTools.map((tool) => ({ name: tool.name, description: tool.description })));
}
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, test } from "bun:test";
import { isNewerVersion } from "./update.js";
describe("update version comparator", () => {
test("correctly identifies newer semantic versions", () => {
expect(isNewerVersion("0.7.0", "0.6.0")).toBe(true);
expect(isNewerVersion("1.0.0", "0.6.0")).toBe(true);
expect(isNewerVersion("0.6.1", "0.6.0")).toBe(true);
expect(isNewerVersion("0.6.0", "0.6.0")).toBe(false);
expect(isNewerVersion("0.5.9", "0.6.0")).toBe(false);
expect(isNewerVersion("0.6.0", "0.7.0")).toBe(false);
});
});
+364
View File
@@ -0,0 +1,364 @@
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
import { isCompiledBinary } from "../../core/runtime.js";
import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js";
import { VERSION } from "../../version.js";
import { runServiceCommand, serviceStatus } from "../service.js";
import { printJson } from "../printer.js";
import { STATE_DIR } from "./service.js";
import type { CliRuntime } from "../types.js";
const DEFAULT_GITHUB_REPO = "yunyingk/seal-home";
const UPDATE_URL_ENV = "SEAL_HOME_UPDATE_URL";
const GITHUB_REPO_ENV = "SEAL_HOME_GITHUB_REPO";
export type UpdateOptions = {
checkOnly?: boolean;
force?: boolean;
targetVersion?: string;
repo?: string;
};
export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOptions = {}) {
const serviceConfig = {
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
stateDir: STATE_DIR,
version: VERSION,
launcher: runtime.launcher
};
// 1. Source development mode (running via bun/node)
if (!isCompiledBinary()) {
if (options.checkOnly) {
printJson({
updated: false,
version: VERSION,
mode: "source",
message: "Running in source development mode. Run 'seal-home update' to git pull & bun install."
});
return;
}
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
try {
runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]);
} catch (err) {
console.error(`git pull skipped: ${err instanceof Error ? err.message : String(err)}`);
}
runCommand("bun", ["install"], { cwd: runtime.appRoot });
if (wasRunning) await runServiceCommand("start", serviceConfig);
printJson({
updated: true,
serviceRestarted: wasRunning,
version: VERSION,
mode: "source"
});
return;
}
// 2. Standalone binary mode: check GitHub Releases
const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || DEFAULT_GITHUB_REPO;
const platform = detectPlatform();
const arch = detectArch();
const release = await fetchGitHubRelease(repo, options.targetVersion);
if (!release) {
printJson({
updated: false,
currentVersion: VERSION,
mode: "binary",
message: `Failed to query releases from GitHub repository '${repo}'`
});
return;
}
const latestVersion = release.version;
const isUpgrade = isNewerVersion(latestVersion, VERSION);
const shouldUpdate = options.force || Boolean(options.targetVersion) || isUpgrade;
if (options.checkOnly) {
printJson({
updated: false,
updateAvailable: isUpgrade,
currentVersion: VERSION,
latestVersion,
releaseNotes: release.notes,
releaseUrl: release.htmlUrl,
mode: "binary"
});
return;
}
if (!shouldUpdate) {
printJson({
updated: false,
currentVersion: VERSION,
latestVersion,
mode: "binary",
message: `seal-home is already up to date (v${VERSION})`
});
return;
}
// Find matching asset
const asset = matchAssetForPlatform(release.assets, platform, arch);
if (!asset) {
throw new Error(
`No compatible binary found for ${platform}-${arch} in release v${latestVersion}. ` +
`Available assets: ${release.assets.map((a) => a.name).join(", ")}`
);
}
// Download binary or archive
const wasRunning = serviceStatus(serviceConfig).running;
if (wasRunning) await runServiceCommand("stop", serviceConfig);
const execPath = process.execPath;
const execDir = dirname(execPath);
const tmpDir = join(execDir, `.tmp-update-${Date.now()}`);
mkdirSync(tmpDir, { recursive: true });
try {
const downloadedFile = join(tmpDir, asset.name);
await downloadFile(asset.downloadUrl, downloadedFile);
let newBinaryPath = downloadedFile;
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform);
} else if (asset.name.endsWith(".zip")) {
newBinaryPath = extractZip(downloadedFile, tmpDir, platform);
}
chmodSync(newBinaryPath, 0o755);
// Re-sign on macOS ad-hoc if codesign exists
if (process.platform === "darwin") {
try {
spawnSync("/usr/bin/codesign", ["--remove-signature", newBinaryPath], { stdio: "ignore" });
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", newBinaryPath], { stdio: "ignore" });
} catch {
// ignore
}
}
// Atomic replace
if (process.platform === "win32") {
const oldBinary = `${execPath}.old.${Date.now()}`;
try {
renameSync(execPath, oldBinary);
} catch {
// ignore
}
renameSync(newBinaryPath, execPath);
} else {
renameSync(newBinaryPath, execPath);
}
if (wasRunning) await runServiceCommand("start", serviceConfig);
const skillSync = syncGlobalSkillIfPresent();
printJson({
updated: true,
fromVersion: VERSION,
toVersion: latestVersion,
serviceRestarted: wasRunning,
skillSynced: skillSync.synced ? skillSync.targetDir : false,
mode: "binary"
});
} finally {
try {
rmSync(tmpDir, { recursive: true, force: true });
} catch {
// ignore
}
}
}
function detectPlatform(): "darwin" | "linux" | "windows" {
if (process.platform === "darwin") return "darwin";
if (process.platform === "win32") return "windows";
return "linux";
}
function detectArch(): "arm64" | "x64" {
return process.arch === "arm64" ? "arm64" : "x64";
}
type GitHubAsset = {
name: string;
downloadUrl: string;
size: number;
};
type GitHubRelease = {
version: string;
tagName: string;
notes: string;
htmlUrl: string;
assets: GitHubAsset[];
};
async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise<GitHubRelease | undefined> {
const url = targetVersion
? `https://api.github.com/repos/${repo}/releases/tags/${targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`}`
: `https://api.github.com/repos/${repo}/releases/latest`;
const headers: Record<string, string> = {
"User-Agent": `seal-home/${VERSION}`,
Accept: "application/vnd.github.v3+json"
};
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (token) {
headers.Authorization = `Bearer ${token}`;
}
try {
const res = await fetch(url, { headers });
if (!res.ok) return undefined;
const json = (await res.json()) as {
tag_name?: string;
body?: string;
html_url?: string;
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
};
const tagName = json.tag_name ?? "";
const version = tagName.replace(/^v/, "");
if (!version) return undefined;
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
name: item.name,
downloadUrl: item.browser_download_url,
size: item.size ?? 0
}));
return {
version,
tagName,
notes: json.body ?? "",
htmlUrl: json.html_url ?? "",
assets
};
} catch {
return undefined;
}
}
function matchAssetForPlatform(
assets: GitHubAsset[],
platform: "darwin" | "linux" | "windows",
arch: "arm64" | "x64"
): GitHubAsset | undefined {
const platformKeywords: Record<string, string[]> = {
darwin: ["darwin", "macos", "osx", "apple"],
linux: ["linux"],
windows: ["windows", "win32", "win"]
};
const archKeywords: Record<string, string[]> = {
arm64: ["arm64", "aarch64"],
x64: ["x64", "x86_64", "amd64"]
};
const pKeys = platformKeywords[platform] || [];
const aKeys = archKeywords[arch] || [];
const matched = assets.filter((asset) => {
const lower = asset.name.toLowerCase();
const matchesP = pKeys.some((k) => lower.includes(k));
const matchesA = aKeys.some((k) => lower.includes(k));
return matchesP && matchesA;
});
// Prefer direct raw executable over tar.gz / zip if both exist
const directBinary = matched.find(
(asset) => !asset.name.endsWith(".tar.gz") && !asset.name.endsWith(".tgz") && !asset.name.endsWith(".zip") && !asset.name.endsWith(".sha256")
);
if (directBinary) return directBinary;
// Fallback to archive
const archive = matched.find(
(asset) => asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz") || asset.name.endsWith(".zip")
);
return archive || matched[0];
}
async function downloadFile(url: string, destPath: string) {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Failed to download asset from ${url}: ${res.status} ${res.statusText}`);
}
const buffer = Buffer.from(await res.arrayBuffer());
writeFileSync(destPath, buffer);
}
function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
if (result.status !== 0) {
throw new Error(`Failed to extract tar archive: ${result.stderr.toString()}`);
}
unlinkSync(archivePath);
// Look for executable in targetDir
const expectedName = platform === "windows" ? "seal-home.exe" : "seal-home";
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
return files[0] || archivePath;
}
function extractZip(archivePath: string, targetDir: string, platform: string): string {
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
if (result.status !== 0) {
throw new Error(`Failed to extract zip archive: ${result.stderr.toString()}`);
}
unlinkSync(archivePath);
const expectedName = platform === "windows" ? "seal-home.exe" : "seal-home";
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
return files[0] || archivePath;
}
export function isNewerVersion(latest: string, current: string): boolean {
const lParts = latest.split(".").map(Number);
const cParts = current.split(".").map(Number);
for (let i = 0; i < Math.max(lParts.length, cParts.length); i++) {
const l = lParts[i] ?? 0;
const c = cParts[i] ?? 0;
if (l > c) return true;
if (l < c) return false;
}
return false;
}
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"]
});
if (result.stdout) console.error(result.stdout.trimEnd());
if (result.stderr) console.error(result.stderr.trimEnd());
if (result.status !== 0) {
throw new Error(`${command} ${args.join(" ")} failed with status ${result.status}`);
}
}
+68
View File
@@ -0,0 +1,68 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleUsersCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "create") {
const name = stringOption(args.options.name) ?? maybeName;
const phone = stringOption(args.options.phone);
if (!name || !phone) throw new Error("Usage: seal-home users create --name <name> --phone <phone> [--dept <deptId>]");
const deptId = stringOption(args.options.dept) ?? stringOption(args.options.departmentId);
const departmentIds = deptId ? [deptId] : undefined;
await runTool("seal_user_create", client, corp, { name, phone, departmentIds }, outputOptions(args.options));
return;
}
if (action === "reset-password") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-home users reset-password <userId>");
await runTool("seal_user_reset_password", client, corp, { userId }, outputOptions(args.options));
return;
}
if (action === "search" || action === "list") {
const keyword = maybeName ?? stringOption(args.options.keyword) ?? stringOption(args.options.query) ?? "";
await runTool("seal_user_search", client, corp, { keyword }, outputOptions(args.options));
return;
}
if (action === "get") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-home users get <userId>");
await runTool("seal_user_get", client, corp, { userId }, outputOptions(args.options));
return;
}
if (action === "delete") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-home users delete <userId>");
await runTool("seal_user_delete", client, corp, { userId }, outputOptions(args.options));
return;
}
if (action === "activate") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-home users activate <userId>");
await runTool("seal_user_activate", client, corp, { userId }, outputOptions(args.options));
return;
}
if (action === "delegation" || action === "impersonate") {
const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone);
if (!userIdOrPhone) throw new Error("Usage: seal-home users delegation <userIdOrPhone> [--note <note>]");
const note = stringOption(args.options.note);
await runTool("seal_user_delegation_create", client, corp, { userIdOrPhone, note }, outputOptions(args.options));
return;
}
throw new Error(`Unknown users command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+142
View File
@@ -0,0 +1,142 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import {
booleanOption,
parseWebhookMode,
stringOption,
webhookRateOption,
webhookShowSecretOption
} from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleWebhookCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "list") {
await runTool(
"seal_webhook_list",
client,
corp,
{
query: stringOption(args.options.query) ?? stringOption(args.options.keyword),
includeSecret: webhookShowSecretOption(args.options)
},
outputOptions(args.options)
);
return;
}
if (action === "get" || action === "find") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-home webhook get <idOrName> [--show-secret]");
await runTool(
"seal_webhook_get",
client,
corp,
{
selector,
includeSecret: webhookShowSecretOption(args.options)
},
outputOptions(args.options)
);
return;
}
if (action === "add" || action === "create") {
const name = stringOption(args.options.name) ?? maybeName;
const outgoingResultWebhook =
stringOption(args.options.resultUrl) ??
stringOption(args.options["result-url"]) ??
stringOption(args.options.outgoingResultWebhook) ??
stringOption(args.options["outgoing-result-webhook"]);
if (!name || !outgoingResultWebhook) {
throw new Error("Usage: seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
}
const autoApprovalRate = webhookRateOption(args.options);
await runTool(
"seal_webhook_add",
client,
corp,
{
name,
mode: parseWebhookMode(stringOption(args.options.mode)),
outgoingResultWebhook,
autoApprovalRate,
secret: stringOption(args.options.secret)
},
outputOptions(args.options)
);
return;
}
if (action === "update") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-home webhook update <idOrName> [options]");
const secret = stringOption(args.options.secret);
const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]);
if (secret !== undefined && rotateSecret) {
throw new Error("Use either --secret or --rotate-secret, not both");
}
const name = stringOption(args.options.name);
const mode = parseWebhookMode(stringOption(args.options.mode));
const outgoingResultWebhook =
stringOption(args.options.resultUrl) ??
stringOption(args.options["result-url"]) ??
stringOption(args.options.outgoingResultWebhook) ??
stringOption(args.options["outgoing-result-webhook"]);
const autoApprovalRate = webhookRateOption(args.options);
if (
name === undefined &&
mode === undefined &&
outgoingResultWebhook === undefined &&
autoApprovalRate === undefined &&
secret === undefined &&
!rotateSecret
) {
throw new Error("Webhook update requires at least one field option");
}
await runTool(
"seal_webhook_update",
client,
corp,
{
selector,
name,
mode,
outgoingResultWebhook,
autoApprovalRate,
secret,
rotateSecret
},
outputOptions(args.options)
);
return;
}
if (action === "delete") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-home webhook delete <idOrName> --yes");
if (booleanOption(args.options.yes) !== true) {
throw new Error("Refusing to delete Webhook integration without --yes");
}
await runTool(
"seal_webhook_delete",
client,
corp,
{
selector,
confirm: true
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown webhook command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
+58
View File
@@ -0,0 +1,58 @@
import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig, resolveGlobalConfigFile } from "../core/config/loader.js";
import { resolveCorpConfig } from "../core/config/manager.js";
import { createSealClient } from "../core/http/factory.js";
import { sealTools, type SealTool } from "../domains/seal/tools.js";
import type { CorpConfig, GlobalConfig } from "../core/config/types.js";
import { printJson } from "./printer.js";
import type { OutputOptions } from "./types.js";
export function selectCorp(corpId?: string): CorpConfig {
const corps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
return resolveCorpConfig(
corps,
{
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId,
corpId
},
getEnterprisesDirCandidates()
);
}
export function globalConfigSummary(config: GlobalConfig = loadGlobalConfig()) {
return {
mode: config.stateful ? "stateful" : "stateless",
stateful: config.stateful,
...(config.stateful && config.defaultCorpId
? { defaultCorpId: config.defaultCorpId }
: {}),
configFile: resolveGlobalConfigFile()
};
}
export async function runTool(
name: string,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
params: Record<string, unknown>,
options: OutputOptions = {}
) {
printJson(await runToolResult(name, client, corp, params), options);
}
export async function runToolResult(
name: string,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
params: Record<string, unknown>
) {
const tool = sealTools.find((item) => item.name === name);
if (!tool) throw new Error(`Unknown Seal tool: ${name}`);
const compactParams = Object.fromEntries(
Object.entries(params).filter(([, value]) => value !== undefined)
);
const handler = tool.handler as SealTool["handler"];
return handler(client, compactParams as never, { corp });
}
+196
View File
@@ -0,0 +1,196 @@
import type { WebhookMode } from "../domains/seal/types.js";
import type { ParsedArgs } from "./types.js";
export function parseArgs(argv: string[]): ParsedArgs {
const command: string[] = [];
const options: Record<string, string | boolean> = {};
let json: unknown;
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (!arg) continue;
if (arg === "--json") {
const raw = argv[index + 1];
if (!raw) throw new Error("--json requires a JSON object argument");
json = JSON.parse(raw);
index += 1;
continue;
}
if (arg.startsWith("-")) {
const key = arg.replace(/^-+/, "");
const next = argv[index + 1];
if (!next || next.startsWith("-")) {
options[key] = true;
} else {
options[key] = next;
index += 1;
}
continue;
}
command.push(arg);
}
return { command, options, json };
}
export function jsonObject(value: unknown): Record<string, unknown> {
if (value === undefined) return {};
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("--json must be an object");
}
return value as Record<string, unknown>;
}
export function stringOption(value: string | boolean | undefined): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function numberOption(value: string | boolean | undefined): number | undefined {
if (typeof value !== "string") return undefined;
const number = Number(value);
if (!Number.isFinite(number)) throw new Error(`Invalid number: ${value}`);
return number;
}
export function splitOption(value: string | boolean | undefined): string[] | undefined {
if (typeof value !== "string") return undefined;
const items = value.split(",").map((item) => item.trim()).filter(Boolean);
return items.length ? items : undefined;
}
export function booleanOption(value: string | boolean | undefined): boolean | undefined {
if (value === undefined) return undefined;
if (typeof value === "boolean") return value;
if (value === "true") return true;
if (value === "false") return false;
throw new Error(`Invalid boolean: ${value}`);
}
export function requiredString(input: Record<string, unknown>, key: string): string {
const value = optionalString(input, key);
if (!value) throw new Error(`Missing required JSON field: ${key}`);
return value;
}
export function requiredStringAlias(input: Record<string, unknown>, keys: string[]): string {
for (const key of keys) {
const value = optionalString(input, key);
if (value) return value;
}
throw new Error(`Missing required JSON field: ${keys.join(" or ")}`);
}
export function optionalString(input: Record<string, unknown>, key: string): string | undefined {
const value = input[key];
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
export function optionalNumber(input: Record<string, unknown>, key: string): number | undefined {
const value = input[key];
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
export function inferCorpIdFromStaffId(staffId: string): string | undefined {
const [corpId] = staffId.split(":", 1);
return corpId || undefined;
}
export function safeFileName(value: string): string {
return value.replace(/[^a-zA-Z0-9._-]/g, "_");
}
export function parseStateMode(value: string): boolean {
const normalized = value.trim().toLowerCase();
if (["stateful", "state", "有状态"].includes(normalized)) return true;
if (["stateless", "无状态"].includes(normalized)) return false;
throw new Error("Invalid config mode. Use stateful or stateless.");
}
export function parseRuleVersionSelector(value: string) {
if (value === "latest") return { latest: true };
const versionNumber = Number(value);
if (Number.isInteger(versionNumber) && versionNumber > 0) {
return { versionNumber };
}
return { versionId: value };
}
export function ruleVersionSearchOptions(value?: string) {
if (!value) return {};
const selector = parseRuleVersionSelector(value);
if ("latest" in selector) {
return {
ruleVersionScope: "version",
latestRuleVersion: true
};
}
if ("versionNumber" in selector) {
return {
ruleVersionScope: "version",
ruleVersionNumber: selector.versionNumber
};
}
return {
ruleVersionScope: "version",
ruleVersionId: selector.versionId
};
}
export function ruleVersionContextOptions(value?: string) {
if (!value) return {};
const selector = parseRuleVersionSelector(value);
if ("latest" in selector) {
return { latestRuleVersion: true };
}
if ("versionNumber" in selector) {
return { ruleVersionNumber: selector.versionNumber };
}
return { ruleVersionId: selector.versionId };
}
export function ruleVersionGetOptions(value?: string) {
if (!value) return {};
const selector = parseRuleVersionSelector(value);
if ("latest" in selector) {
return { latest: true };
}
if ("versionNumber" in selector) {
return { versionNumber: selector.versionNumber };
}
return { versionId: selector.versionId };
}
export function parseWebhookMode(value?: string): WebhookMode | undefined {
if (!value) return undefined;
const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_");
const aliases: Record<string, WebhookMode> = {
assisted: "assisted",
辅助: "assisted",
semi_automatic: "semi_automatic",
半自动: "semi_automatic",
fully_automatic: "fully_automatic",
全自动: "fully_automatic"
};
const mode = aliases[normalized];
if (!mode) {
throw new Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");
}
return mode;
}
export function webhookRateOption(options: Record<string, string | boolean>): number | undefined {
const value = numberOption(
options.autoApprovalRate ?? options["auto-approval-rate"] ?? options["approval-rate"]
);
if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 100)) {
throw new Error("Webhook auto approval rate must be an integer between 0 and 100");
}
return value;
}
export function webhookShowSecretOption(options: Record<string, string | boolean>): boolean | undefined {
return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]);
}
+151
View File
@@ -0,0 +1,151 @@
import { writeFileSync } from "node:fs";
import { booleanOption, stringOption } from "./parser.js";
import type { OutputOptions } from "./types.js";
export const RULE_LIST_FULL_COUNT_LIMIT = 100;
export const RULE_LIST_FULL_BYTES_LIMIT = 120_000;
export const RULE_SUMMARY_FIELDS = ["id", "code", "status", "strictness", "scope", "createdAt", "updatedAt"];
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
export function formatConsoleOutput(values: unknown[]): string {
return values.map((value) => (typeof value === "string" ? value : String(value))).join(" ");
}
export function joinOutput(lines: string[]): string {
if (!lines.length) return "";
return `${lines.join("\n")}\n`;
}
export function redactSensitiveText(value: string): string {
return value
.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi, "$1<redacted>")
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>");
}
export function printJson(value: unknown, options: OutputOptions = {}) {
protectLargeOutput(value, options);
const json = `${JSON.stringify(value, null, 2)}\n`;
if (options.outputFile) {
writeFileSync(options.outputFile, json);
console.log(JSON.stringify({ outputFile: options.outputFile, bytes: Buffer.byteLength(json, "utf-8") }, null, 2));
return;
}
console.log(json.trimEnd());
}
export function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
if (options.allowFull || options.outputFile) return;
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
throw new Error(
`Output is large (${bodyBytes} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`
);
}
}
export function protectLargeRuleListOutput(result: unknown, allowFull: boolean) {
if (allowFull) return;
const data = result && typeof result === "object" ? (result as {
count?: unknown;
rules?: unknown;
}) : {};
const count = typeof data.count === "number" ? data.count : undefined;
const rulesCount = Array.isArray(data.rules) ? data.rules.length : undefined;
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
const effectiveCount = count ?? rulesCount ?? 0;
if (effectiveCount > RULE_LIST_FULL_COUNT_LIMIT || bodyBytes > RULE_LIST_FULL_BYTES_LIMIT) {
throw new Error(
`Rule list is large (${effectiveCount} rules, ${bodyBytes} bytes). Use "seal-home rules list --summary" or "seal-home rules count"; pass --full only when you really need full descriptions.`
);
}
}
export function outputOptions(options: Record<string, string | boolean>): OutputOptions {
return {
allowFull: booleanOption(options.full) === true,
outputFile: stringOption(options.outputFile) ?? stringOption(options["output-file"])
};
}
export function printHelp() {
console.log(`seal-home CLI
Usage:
seal-home version
seal-home mcp
seal-home mcp config
seal-home mcp-config
seal-home skill dump
seal-home skill install [--dir <path>|--local]
seal-home skill status
seal-home openapi
seal-home probe [<corpId>]
seal-home config paths
seal-home config get
seal-home config mode <stateful|stateless> [--corp <corpId>]
seal-home service <start|stop|restart|status>
seal-home update
seal-home tools list
seal-home corps list [--corp <corpId>]
seal-home corps current [--corp <corpId>]
seal-home corps switch <corpId>
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-home auth diagnose [--corp <corpId>]
seal-home auth hose-link [--corp <corpId>] [--expire 7200]
seal-home delegation list [--corp <corpId>]
seal-home delegation create [--note <note>] [--corp <corpId>]
seal-home delegation revoke <tokenId> [--corp <corpId>]
seal-home users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-home users search <keyword> [--corp <corpId>]
seal-home users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]
seal-home users reset-password <userId> [--corp <corpId>]
seal-home users get <userId> [--corp <corpId>]
seal-home users delete <userId> [--corp <corpId>]
seal-home llm config [--corp <corpId>]
seal-home llm providers [--corp <corpId>]
seal-home permissions available [--corp <corpId>]
seal-home permissions configs [--corp <corpId>]
seal-home billing status [--corp <corpId>]
seal-home billing plans [--corp <corpId>]
seal-home billing features [--corp <corpId>]
seal-home webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-home webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
seal-home 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-home webhook delete <idOrName> --yes [--corp <corpId>]
seal-home source config [--corp <corpId>]
seal-home tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-home rules count [--corp <corpId>]
seal-home rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp <corpId>]
seal-home rules clear [--corp <corpId>] [--dry-run|--yes]
seal-home rules versions [--corp <corpId>]
seal-home rules version <versionId|versionNumber|latest> [--corp <corpId>]
seal-home rules get --corp <corpId> --version <number|latest> --code '#0038'
seal-home rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
seal-home rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]
seal-home context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50] [--corp <corpId>]
seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-home approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
seal-home approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
seal-home approval-runs cited-rules <recordId> [--corp <corpId>]
seal-home approval-runs document-summary <recordId> [--corp <corpId>]
seal-home approval-runs attachments <recordId> [--summary] [--corp <corpId>]
seal-home approval-runs result <recordId> [--summary] [--corp <corpId>]
seal-home approval-runs url [--corp <corpId>]
seal-home approval-runs url <recordId> [--corp <corpId>]
seal-home approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]
seal-home approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]
seal-home simulation batch-records <batchId> [--corp <corpId>]
seal-home simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--corp <corpId>]
seal-home simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]
seal-home simulation list [--limit 50] [--corp <corpId>]
seal-home simulation get <batchId> [--corp <corpId>]
seal-home simulation templates [--corp <corpId>]
seal-home simulation integrations [--corp <corpId>]
seal-home simulation package-upload <材料包.zip> [--corp <corpId>]
`);
}
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, test } from "bun:test";
import { runCli } from "./runner.js";
describe("CLI runner", () => {
test("returns version output without touching the process lifecycle", async () => {
const result = await runCli(["version"]);
expect(result).toMatchObject({
stderr: "",
isError: false,
exitCode: 0
});
expect(JSON.parse(result.stdout)).toMatchObject({ name: "seal-home" });
});
test("returns diagnostics and a non-zero exit code for invalid commands", async () => {
const result = await runCli(["not-a-command"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("Unknown command: not-a-command");
});
});
+275
View File
@@ -0,0 +1,275 @@
#!/usr/bin/env bun
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { createSealClient } from "../core/http/factory.js";
import { VERSION } from "../version.js";
import { handleApprovalRunsCommand } from "./commands/approval-runs.js";
import { handleAuthCommand } from "./commands/auth.js";
import { handleBillingCommand } from "./commands/billing.js";
import { handleConfigCommand } from "./commands/config.js";
import { handleContextCommand } from "./commands/context.js";
import { handleCorpsCommand } from "./commands/corps.js";
import { handleDelegationCommand } from "./commands/delegation.js";
import { handleLlmCommand } from "./commands/llm.js";
import { handleMcpCommand, printMcpConfig } from "./commands/mcp.js";
import { handleOpenApiCommand } from "./commands/openapi.js";
import { handlePermissionsCommand } from "./commands/permissions.js";
import { handleProbeCommand } from "./commands/probe.js";
import { handleRulesCommand } from "./commands/rules.js";
import { handleServiceCommand } from "./commands/service.js";
import { handleSimulationCommand } from "./commands/simulation.js";
import { handleSkillCommand } from "./commands/skill.js";
import { handleSourceCommand } from "./commands/source.js";
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 { selectCorp } from "./helpers.js";
import { booleanOption, parseArgs, stringOption } from "./parser.js";
import {
formatConsoleOutput,
joinOutput,
printHelp,
printJson,
redactSensitiveText
} from "./printer.js";
import type { CliResult, CliRunOptions, CliRuntime } from "./types.js";
const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
const KNOWN_AREAS = new Set([
"config",
"service",
"update",
"tools",
"corps",
"tool",
"source",
"auth",
"delegation",
"users",
"llm",
"permissions",
"billing",
"webhook",
"webhooks",
"context",
"rules",
"approval-runs",
"simulation",
"mcp",
"server",
"mcp-config",
"skill",
"openapi",
"probe"
]);
export type { CliResult, CliRunOptions } from "./types.js";
let runQueue = Promise.resolve();
export function runCli(argv: string[], options: CliRunOptions = {}): Promise<CliResult> {
const run = runQueue.then(() => runCliOnce(argv, options));
runQueue = run.then(
() => undefined,
() => undefined
);
return run;
}
async function runCliOnce(argv: string[], options: CliRunOptions): Promise<CliResult> {
const stdout: string[] = [];
const stderr: string[] = [];
const originalLog = console.log;
const originalError = console.error;
const runtime: CliRuntime = {
appRoot: options.appRoot ?? DEFAULT_APP_ROOT,
entryFile: options.entryFile ?? join(options.appRoot ?? DEFAULT_APP_ROOT, "src", "cli.ts"),
launcher: options.launcher
};
console.log = (...values: unknown[]) => {
stdout.push(formatConsoleOutput(values));
};
console.error = (...values: unknown[]) => {
stderr.push(formatConsoleOutput(values));
};
try {
await dispatch(argv, runtime);
return {
stdout: joinOutput(stdout),
stderr: joinOutput(stderr),
isError: false,
exitCode: 0
};
} catch (error) {
stderr.push(redactSensitiveText(error instanceof Error ? error.message : String(error)));
return {
stdout: joinOutput(stdout),
stderr: joinOutput(stderr),
isError: true,
exitCode: 1
};
} finally {
console.log = originalLog;
console.error = originalError;
}
}
async function dispatch(argv: string[], runtime: CliRuntime) {
const args = parseArgs(argv);
const [area, action, maybeName] = args.command;
if (
area === "version" ||
area === "v" ||
Boolean(args.options.version) ||
Boolean(args.options.v) ||
Boolean(args.options.V)
) {
printJson({
name: "seal-home",
version: VERSION
});
return;
}
if (!area || area === "help" || args.options.help) {
printHelp();
return;
}
if (!KNOWN_AREAS.has(area)) {
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`);
}
if (area === "openapi") {
handleOpenApiCommand(args);
return;
}
if (area === "mcp-config") {
printMcpConfig();
return;
}
if (area === "skill") {
handleSkillCommand(action, maybeName, args);
return;
}
if (area === "mcp" || area === "server") {
await handleMcpCommand(action, args);
return;
}
if (area === "probe") {
await handleProbeCommand(action, maybeName, args);
return;
}
if (area === "config") {
handleConfigCommand(action, maybeName, args);
return;
}
if (area === "service") {
await handleServiceCommand(action, runtime);
return;
}
if (area === "update") {
const targetVersion = stringOption(args.options.version) ?? stringOption(args.options.tag) ?? (action && !action.startsWith("-") ? action : undefined);
await handleUpdateCommand(runtime, {
checkOnly: booleanOption(args.options.check) ?? booleanOption(args.options["check-only"]),
force: booleanOption(args.options.force),
targetVersion,
repo: stringOption(args.options.repo)
});
return;
}
if (area === "tools" && action === "list") {
handleToolsListCommand();
return;
}
if (area === "corps") {
await handleCorpsCommand(action, maybeName, args);
return;
}
const corp = selectCorp(stringOption(args.options.corp));
if (area === "source") {
await handleSourceCommand(action, corp);
return;
}
if (area === "auth") {
await handleAuthCommand(action, corp, args);
return;
}
const client = await createSealClient(corp);
if (area === "delegation") {
await handleDelegationCommand(action, maybeName, client, corp, args);
return;
}
if (area === "users") {
await handleUsersCommand(action, maybeName, client, corp, args);
return;
}
if (area === "llm") {
await handleLlmCommand(action, client, corp, args);
return;
}
if (area === "permissions") {
await handlePermissionsCommand(action, client, corp, args);
return;
}
if (area === "billing") {
await handleBillingCommand(action, client, corp, args);
return;
}
if (area === "webhook" || area === "webhooks") {
await handleWebhookCommand(action, maybeName, client, corp, args);
return;
}
if (area === "context") {
await handleContextCommand(client, corp, args);
return;
}
if (area === "rules") {
await handleRulesCommand(action, maybeName, client, corp, args);
return;
}
if (area === "approval-runs") {
await handleApprovalRunsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "simulation") {
await handleSimulationCommand(action, maybeName, client, corp, args);
return;
}
if (area === "tool") {
await handleToolCommand(action, client, corp, args);
return;
}
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`);
}
+31
View File
@@ -0,0 +1,31 @@
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";
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("service lifecycle state", () => {
test("clears a stale pid file instead of reporting another process as running", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-home-service-"));
tempDirs.push(stateDir);
writeFileSync(join(stateDir, "service.pid"), "999999\n");
const status = serviceStatus({
appRoot: "/tmp/seal-home",
entryFile: "/tmp/seal-home/src/cli.ts",
stateDir,
version: "0.4.2"
});
expect(status.running).toBe(false);
expect(status.pid).toBeUndefined();
});
});
+175
View File
@@ -0,0 +1,175 @@
import { spawn, execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
export type ServiceConfig = {
appRoot: string;
entryFile: string;
stateDir: string;
version?: string;
launcher?: {
command: string;
args?: string[];
};
};
export async function runServiceCommand(
action: string | undefined,
config: ServiceConfig,
options: { quiet?: boolean } = {}
) {
switch (action) {
case "run":
await runService(config);
return undefined;
case "start":
return startService(config);
case "stop":
return stopService(config, options);
case "restart":
stopService(config, { quiet: true });
return startService(config);
case "status":
case undefined:
return serviceStatus(config);
default:
throw new Error("Usage: seal-home service <start|stop|restart|status>");
}
}
export function serviceStatus(config: ServiceConfig) {
const pidFile = getPidFile(config);
const pid = readServicePid(pidFile);
const running = pid ? isSealHomeProcess(pid, config.appRoot) : false;
if (pid && !running) {
rmSync(pidFile, { force: true });
}
return {
running,
pid: running ? pid : undefined,
version: config.version,
appRoot: config.appRoot,
stateDir: config.stateDir,
pidFile,
logFile: getLogFile(config)
};
}
async function runService(config: ServiceConfig) {
const pidFile = getPidFile(config);
const logFile = getLogFile(config);
ensureStateDir(config.stateDir);
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
appendLog(logFile, `running pid=${process.pid}`);
const cleanup = () => {
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { 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();
};
process.once("SIGTERM", stop);
process.once("SIGINT", stop);
});
}
function startService(config: ServiceConfig) {
ensureStateDir(config.stateDir);
const current = serviceStatus(config);
if (current.running) {
return current;
}
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
const child = spawn(launcher.command, [
...(launcher.args ?? []),
"service",
"run"
], {
cwd: config.appRoot,
detached: true,
stdio: ["ignore", "ignore", "ignore"],
env: process.env
});
child.unref();
const pidFile = getPidFile(config);
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
appendLog(getLogFile(config), `started pid=${child.pid}`);
return { started: true, ...serviceStatus(config) };
}
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
const pidFile = getPidFile(config);
const pid = readServicePid(pidFile);
if (!pid || !isSealHomeProcess(pid, config.appRoot)) {
rmSync(pidFile, { force: true });
return options.quiet ? undefined : { stopped: false, reason: "not running" };
}
process.kill(pid, "SIGTERM");
rmSync(pidFile, { force: true });
appendLog(getLogFile(config), `stop requested pid=${pid}`);
return options.quiet ? undefined : { stopped: true, pid };
}
function isSealHomeProcess(pid: number, appRoot: string) {
if (!isProcessRunning(pid)) return false;
try {
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
const matchesTarget =
command.includes(appRoot) ||
command.includes("seal-home") ||
command.includes("src/cli.ts");
return matchesTarget && command.includes("service") && command.includes("run");
} catch {
return false;
}
}
function isProcessRunning(pid: number) {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function getPidFile(config: ServiceConfig) {
return join(config.stateDir, "service.pid");
}
function getLogFile(config: ServiceConfig) {
return join(config.stateDir, "service.log");
}
function readServicePid(path: string): number | undefined {
if (!existsSync(path)) return undefined;
const pid = Number(readFileSync(path, "utf8").trim());
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
}
function ensureStateDir(stateDir: string) {
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
}
function appendLog(path: string, message: string) {
writeFileSync(path, `${new Date().toISOString()} ${message}\n`, { flag: "a", mode: 0o600 });
}
+36
View File
@@ -0,0 +1,36 @@
import type { ServiceConfig } from "./service.js";
export type ParsedArgs = {
command: string[];
options: Record<string, string | boolean>;
json?: unknown;
};
export type OutputOptions = {
allowFull?: boolean;
outputFile?: string;
};
export type CliResult = {
stdout: string;
stderr: string;
isError: boolean;
exitCode: number;
};
export type CliRunOptions = {
appRoot?: string;
entryFile?: string;
launcher?: ServiceConfig["launcher"];
};
export type CliRuntime = {
appRoot: string;
entryFile: string;
launcher?: ServiceConfig["launcher"];
};
export type CommandContext = {
runtime: CliRuntime;
args: ParsedArgs;
};
+91
View File
@@ -0,0 +1,91 @@
import { describe, expect, test } from "bun:test";
import { CorpConfig } from "../config/types.js";
import { getDirectSealSession } from "./direct.js";
describe("getDirectSealSession", () => {
test("resolves direct source session correctly", async () => {
const corp: CorpConfig = {
id: "corp-direct-1",
name: "Direct Corp",
seal: {
url: "https://seal.example.com",
tenantSlug: "direct-slug",
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "direct",
token: "bearer-token-direct",
sealUrl: "https://seal.example.com",
expiresIn: 3600,
staffId: "staff-123",
corpId: "corp-direct-1"
},
auth: {
refreshTtl: 300
}
};
const session = await getDirectSealSession(corp);
expect(session.token).toBe("bearer-token-direct");
expect(session.enterprise).toEqual({
provider: "direct",
corpId: "corp-direct-1",
staffId: "staff-123",
sealUrl: "https://seal.example.com",
tenantId: undefined,
tenantSlug: "direct-slug",
tenantName: undefined,
raw: {
sourceType: "direct"
}
});
expect(session.expiresAt).toBeGreaterThan(Date.now());
});
test("resolves native seal source session correctly", async () => {
const corp: CorpConfig = {
id: "corp-native-1",
name: "Native Seal Corp",
seal: {
url: "https://tenant.sealai.cc",
tenantSlug: "tenant-slug",
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "seal",
token: "bearer-token-native",
sealUrl: "https://tenant.sealai.cc",
expiresIn: 7200,
staffId: "seal-admin",
tenantId: "tenant-100",
tenantSlug: "tenant-slug",
tenantName: "Tenant 100 Name"
},
auth: {
refreshTtl: 300
}
};
const session = await getDirectSealSession(corp);
expect(session.token).toBe("bearer-token-native");
expect(session.enterprise.provider).toBe("seal");
expect(session.enterprise.tenantId).toBe("tenant-100");
expect(session.enterprise.tenantName).toBe("Tenant 100 Name");
});
test("throws error for unsupported source type", async () => {
const invalidCorp = {
id: "corp-invalid",
name: "Invalid",
seal: { endpoints: { approvalStylePreferences: "" } },
source: { type: "hose" as const, domain: "https://app.ekuaibao.com", staffId: "a", corpId: "b" },
auth: { refreshTtl: 300 }
} as unknown as CorpConfig;
expect(getDirectSealSession(invalidCorp)).rejects.toThrow("Unsupported Seal source");
});
});
+7 -4
View File
@@ -2,23 +2,26 @@ import { CorpConfig } from "../config/types.js";
import { SealSession } from "./types.js";
export async function getDirectSealSession(corp: CorpConfig): Promise<SealSession> {
if (corp.source.type !== "direct") {
if (corp.source.type !== "direct" && corp.source.type !== "seal") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const sealUrl = corp.seal.url ?? corp.source.sealUrl;
const nativeSource = corp.source.type === "seal" ? corp.source : undefined;
return {
token: corp.source.token,
expiresAt: Date.now() + corp.source.expiresIn * 1000,
enterprise: {
provider: "direct",
provider: nativeSource ? "seal" : "direct",
corpId: corp.source.corpId ?? corp.id,
staffId: corp.source.staffId,
sealUrl,
tenantSlug: corp.seal.tenantSlug,
tenantId: nativeSource?.tenantId,
tenantSlug: corp.seal.tenantSlug ?? nativeSource?.tenantSlug,
tenantName: nativeSource?.tenantName,
raw: {
sourceType: "direct"
sourceType: corp.source.type
}
}
};
+98
View File
@@ -0,0 +1,98 @@
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 { CorpConfig, HoseSealSource } from "../config/types.js";
import { defaultSealUrl, getHoseEnterpriseUrl, normalizeBaseUrl } from "./hose.js";
const ORIGINAL_ENV = process.env.SEAL_HOME_TOKEN_STORE;
const tempDirs: string[] = [];
function setupTokenStore(data: Record<string, unknown>): string {
const dir = mkdtempSync(join(tmpdir(), "hose-auth-test-"));
tempDirs.push(dir);
const storePath = join(dir, "tokens.json");
process.env.SEAL_HOME_TOKEN_STORE = storePath;
writeFileSync(storePath, JSON.stringify(data, null, 2));
return storePath;
}
afterEach(() => {
if (ORIGINAL_ENV === undefined) {
delete process.env.SEAL_HOME_TOKEN_STORE;
} else {
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_ENV;
}
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("hose auth helpers", () => {
test("normalizeBaseUrl strips trailing slashes", () => {
expect(normalizeBaseUrl("https://app.ekuaibao.com///")).toBe("https://app.ekuaibao.com");
expect(normalizeBaseUrl("https://app.ekuaibao.com")).toBe("https://app.ekuaibao.com");
});
test("defaultSealUrl resolves corp.seal.url, source.sealUrl, or fallback subdomain", () => {
const source: HoseSealSource = {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key",
appSecurity: "sec",
staffId: "user1",
corpId: "CORP123"
};
const corpWithSealUrl: CorpConfig = {
id: "corp-1",
name: "Corp 1",
seal: { url: "https://custom.sealai.cc", endpoints: { approvalStylePreferences: "" } },
source,
auth: { refreshTtl: 300 }
};
expect(defaultSealUrl(corpWithSealUrl, source)).toBe("https://custom.sealai.cc");
const corpWithoutSealUrl: CorpConfig = {
id: "corp-1",
name: "Corp 1",
seal: { endpoints: { approvalStylePreferences: "" } },
source,
auth: { refreshTtl: 300 }
};
expect(defaultSealUrl(corpWithoutSealUrl, source)).toBe("https://corp123.sealai.cc");
});
test("getHoseEnterpriseUrl retrieves cached provisional auth URL", async () => {
setupTokenStore({
"corp-cached": {
hose: {
closeapi: {
token: "close-token",
url: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
expiresAt: Date.now() + 3600_000
}
}
}
});
const corp: CorpConfig = {
id: "corp-cached",
name: "Corp Cached",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key",
appSecurity: "sec",
staffId: "staff",
corpId: "corp"
},
auth: { refreshTtl: 300 }
};
const url = await getHoseEnterpriseUrl(corp);
expect(url).toBe("https://app.ekuaibao.com/web/home.html?accessToken=close-token");
});
});
+37 -18
View File
@@ -40,7 +40,10 @@ type SealTokenResponse = {
};
};
function normalizeBaseUrl(url: string): string {
const openapiTokenRequests = new Map<string, Promise<string>>();
const closeApiTokenRequests = new Map<string, Promise<TokenEntry>>();
export function normalizeBaseUrl(url: string): string {
return url.replace(/\/+$/, "");
}
@@ -48,7 +51,7 @@ function isFresh(entry: TokenEntry | undefined, refreshTtl = 60): entry is Token
return Boolean(entry && Date.now() < entry.expiresAt - refreshTtl * 1000);
}
function defaultSealUrl(corp: CorpConfig, source: HoseSealSource): string {
export function defaultSealUrl(corp: CorpConfig, source: HoseSealSource): string {
if (corp.seal.url) return corp.seal.url;
if (source.sealUrl) return source.sealUrl;
return `https://${source.corpId.toLowerCase()}.sealai.cc`;
@@ -108,25 +111,32 @@ async function fetchHoseOpenapiToken(source: HoseSealSource): Promise<TokenEntry
};
}
async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string> {
export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const cache = getHoseAuthCache(corp.id);
if (isFresh(cache.openapi)) {
return cache.openapi.token;
}
const openapi = await fetchHoseOpenapiToken(corp.source);
setHoseAuthCache(corp.id, {
...cache,
openapi
});
return openapi.token;
const pending = openapiTokenRequests.get(corp.id);
if (pending) return pending;
const request = fetchHoseOpenapiToken(corp.source)
.then((openapi) => {
setHoseAuthCache(corp.id, {
...getHoseAuthCache(corp.id),
openapi
});
return openapi.token;
})
.finally(() => openapiTokenRequests.delete(corp.id));
openapiTokenRequests.set(corp.id, request);
return request;
}
async function fetchHoseCloseApiToken(
export async function fetchHoseCloseApiToken(
source: HoseSealSource,
openapiToken: string,
expiresIn = 7200
@@ -168,19 +178,28 @@ async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEntry> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const source = corp.source;
const cache = getHoseAuthCache(corp.id);
if (isFresh(cache.closeapi) && cache.closeapi.url) {
return cache.closeapi;
}
const openapiToken = await ensureHoseOpenapiToken(corp);
const closeapi = await fetchHoseCloseApiToken(corp.source, openapiToken);
setHoseAuthCache(corp.id, {
...getHoseAuthCache(corp.id),
closeapi
});
return closeapi;
const pending = closeApiTokenRequests.get(corp.id);
if (pending) return pending;
const request = ensureHoseOpenapiToken(corp)
.then((openapiToken) => fetchHoseCloseApiToken(source, openapiToken))
.then((closeapi) => {
setHoseAuthCache(corp.id, {
...getHoseAuthCache(corp.id),
closeapi
});
return closeapi;
})
.finally(() => closeApiTokenRequests.delete(corp.id));
closeApiTokenRequests.set(corp.id, request);
return request;
}
export async function getHoseEnterpriseUrl(corp: CorpConfig): Promise<string> {
+1
View File
@@ -15,6 +15,7 @@ async function refreshSealSession(corp: CorpConfig): Promise<SealSession> {
case "hose":
return getHoseSealSession(corp);
case "direct":
case "seal":
return getDirectSealSession(corp);
}
}
+94
View File
@@ -0,0 +1,94 @@
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 {
clearCorpTokenCache,
clearSealSession,
getCorpTokenCache,
getHoseAuthCache,
getSealSession,
setHoseAuthCache,
setSealSession
} from "./token-store.js";
import { SealSession } from "./types.js";
const ORIGINAL_ENV = process.env.SEAL_HOME_TOKEN_STORE;
const tempDirs: string[] = [];
function makeTempStore(): string {
const dir = mkdtempSync(join(tmpdir(), "seal-token-store-test-"));
tempDirs.push(dir);
const filePath = join(dir, "tokens.json");
process.env.SEAL_HOME_TOKEN_STORE = filePath;
return filePath;
}
afterEach(() => {
if (ORIGINAL_ENV === undefined) {
delete process.env.SEAL_HOME_TOKEN_STORE;
} else {
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_ENV;
}
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("token-store", () => {
test("returns empty cache when store file does not exist", () => {
makeTempStore();
expect(getSealSession("corp-test")).toBeUndefined();
expect(getCorpTokenCache("corp-test")).toEqual({});
expect(getHoseAuthCache("corp-test")).toEqual({});
});
test("handles corrupted JSON gracefully", () => {
const storePath = makeTempStore();
writeFileSync(storePath, "{ invalid json", "utf-8");
expect(getSealSession("corp-test")).toBeUndefined();
});
test("sets, retrieves, and clears seal session", () => {
makeTempStore();
const session: SealSession = {
token: "test-token-123",
expiresAt: Date.now() + 3600_000,
enterprise: {
provider: "direct",
corpId: "corp-1",
staffId: "staff-1",
sealUrl: "https://seal.example.com"
}
};
setSealSession("corp-1", session);
expect(getSealSession("corp-1")).toEqual(session);
clearSealSession("corp-1");
expect(getSealSession("corp-1")).toBeUndefined();
});
test("sets, retrieves, and clears hose auth cache", () => {
makeTempStore();
const hoseCache = {
openapi: {
token: "openapi-token",
expiresAt: Date.now() + 3600_000
},
closeapi: {
token: "closeapi-token",
url: "https://app.ekuaibao.com/web/home.html",
expiresAt: Date.now() + 7200_000
}
};
setHoseAuthCache("corp-hose", hoseCache);
expect(getHoseAuthCache("corp-hose")).toEqual(hoseCache);
clearCorpTokenCache("corp-hose");
expect(getHoseAuthCache("corp-hose")).toEqual({});
expect(getCorpTokenCache("corp-hose")).toEqual({});
});
});
+31 -1
View File
@@ -2,10 +2,17 @@ import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { loadCorpConfigs, resolveEnterprisesDir } from "./loader.js";
import {
loadCorpConfigs,
loadGlobalConfig,
resolveEnterprisesDir,
resolveGlobalConfigFile,
saveGlobalConfig
} from "./loader.js";
const ORIGINAL_ENV = process.env.SEAL_HOME_ENTERPRISES_DIR;
const ORIGINAL_USER_DIR_ENV = process.env.SEAL_HOME_USER_ENTERPRISES_DIR;
const ORIGINAL_CONFIG_FILE_ENV = process.env.SEAL_HOME_CONFIG_FILE;
const ORIGINAL_CWD = process.cwd();
const tempDirs: string[] = [];
@@ -21,6 +28,11 @@ afterEach(() => {
} else {
process.env.SEAL_HOME_USER_ENTERPRISES_DIR = ORIGINAL_USER_DIR_ENV;
}
if (ORIGINAL_CONFIG_FILE_ENV === undefined) {
delete process.env.SEAL_HOME_CONFIG_FILE;
} else {
process.env.SEAL_HOME_CONFIG_FILE = ORIGINAL_CONFIG_FILE_ENV;
}
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
@@ -69,6 +81,24 @@ describe("loadCorpConfigs", () => {
["user-only", "User Only"]
]);
});
test("defaults global config to stateless", () => {
process.env.SEAL_HOME_CONFIG_FILE = join(makeTempDir(), "config.json");
expect(loadGlobalConfig()).toEqual({ stateful: false });
});
test("saves and loads the global state mode", () => {
const file = join(makeTempDir(), "nested", "config.json");
process.env.SEAL_HOME_CONFIG_FILE = file;
expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a" })).toEqual({
stateful: true,
defaultCorpId: "corp-a"
});
expect(resolveGlobalConfigFile()).toBe(file);
expect(loadGlobalConfig()).toEqual({ stateful: true, defaultCorpId: "corp-a" });
});
});
function makeTempDir(): string {
+26 -3
View File
@@ -1,11 +1,13 @@
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { CorpConfig, CorpConfigSchema } from "./types.js";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "enterprises";
const CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR";
const USER_DIR_ENV = "SEAL_HOME_USER_ENTERPRISES_DIR";
const GLOBAL_CONFIG_ENV = "SEAL_HOME_CONFIG_FILE";
const GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-home", "config.json");
export const USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-home", "enterprises");
export function loadCorpConfigs(): CorpConfig[] {
@@ -56,3 +58,24 @@ export function getEnterprisesDirCandidates(): string[] {
USER_ENTERPRISES_DIR
];
}
export function resolveGlobalConfigFile(): string {
return process.env[GLOBAL_CONFIG_ENV]?.trim() || GLOBAL_CONFIG_FILE;
}
export function loadGlobalConfig(): GlobalConfig {
const file = resolveGlobalConfigFile();
if (!existsSync(file)) {
return GlobalConfigSchema.parse({});
}
return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
}
export function saveGlobalConfig(config: GlobalConfig): GlobalConfig {
const normalized = GlobalConfigSchema.parse(config);
const file = resolveGlobalConfigFile();
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
writeFileSync(file, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
return normalized;
}
+45 -6
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import { CorpConfig } from "./types.js";
import { CorpContext } from "./manager.js";
import { CorpContext, resolveCorpConfig } from "./manager.js";
function corp(id: string, name = id): CorpConfig {
return {
@@ -26,7 +26,7 @@ function corp(id: string, name = id): CorpConfig {
describe("CorpContext", () => {
test("refresh adds newly loaded corps", () => {
const context = new CorpContext([corp("corp-a")]);
const context = new CorpContext([corp("corp-a")], { stateful: true });
context.refresh([corp("corp-a"), corp("corp-b")]);
@@ -34,7 +34,7 @@ describe("CorpContext", () => {
});
test("refresh keeps the selected corp when it still exists", () => {
const context = new CorpContext([corp("corp-a"), corp("corp-b")]);
const context = new CorpContext([corp("corp-a"), corp("corp-b")], { stateful: true });
expect(context.switchCorp("corp-b")).toBe(true);
context.refresh([corp("corp-a"), corp("corp-b", "Corp B updated")]);
@@ -43,12 +43,51 @@ describe("CorpContext", () => {
expect(context.getCurrent()?.name).toBe("Corp B updated");
});
test("refresh falls back when the selected corp disappears", () => {
const context = new CorpContext([corp("corp-a"), corp("corp-b")]);
test("clears the default when the selected corp disappears", () => {
const context = new CorpContext([corp("corp-a"), corp("corp-b")], { stateful: true });
expect(context.switchCorp("corp-b")).toBe(true);
context.refresh([corp("corp-c")]);
expect(context.getCurrent()?.id).toBe("corp-c");
expect(context.getCurrent()).toBeNull();
});
test("does not keep a current corp in stateless mode", () => {
const context = new CorpContext([corp("corp-a"), corp("corp-b")]);
expect(context.getCurrent()).toBeNull();
expect(context.switchCorp("corp-b")).toBe(false);
expect(context.resolve("corp-b")?.id).toBe("corp-b");
});
test("uses the configured default corp in stateful mode", () => {
const context = new CorpContext(
[corp("corp-a"), corp("corp-b")],
{ stateful: true, defaultCorpId: "corp-b" }
);
expect(context.getCurrent()?.id).toBe("corp-b");
});
});
describe("resolveCorpConfig", () => {
test("requires an explicit corp in stateless mode", () => {
expect(() => resolveCorpConfig([corp("corp-a")], { stateful: false })).toThrow(
"Every enterprise command requires --corp <corpId>"
);
});
test("resolves an explicit corp in stateless mode", () => {
expect(resolveCorpConfig(
[corp("corp-a"), corp("corp-b")],
{ stateful: false, corpId: "corp-b" }
).id).toBe("corp-b");
});
test("resolves the configured default corp in stateful mode", () => {
expect(resolveCorpConfig(
[corp("corp-a"), corp("corp-b")],
{ stateful: true, defaultCorpId: "corp-b" }
).id).toBe("corp-b");
});
});
+72 -7
View File
@@ -1,19 +1,62 @@
import { CorpConfig } from "./types.js";
import { CorpConfig, GlobalConfig } from "./types.js";
export function resolveCorpConfig(
corps: CorpConfig[],
options: Pick<GlobalConfig, "stateful" | "defaultCorpId"> & { corpId?: string },
candidates: string[] = []
): CorpConfig {
const requestedCorpId = options.corpId?.trim() || undefined;
const configuredCorpId = options.stateful
? options.defaultCorpId?.trim() || undefined
: undefined;
const selectedCorpId = requestedCorpId ?? configuredCorpId;
if (selectedCorpId) {
const corp = corps.find((item) => item.id === selectedCorpId);
if (corp) return corp;
throw new Error(`No enterprise config found for ${selectedCorpId}`);
}
if (!options.stateful) {
throw new Error(
"Stateless mode is enabled. Every enterprise command requires --corp <corpId>. " +
"Use `seal-home config mode stateful` to enable a default enterprise."
);
}
const firstCorp = corps[0];
if (firstCorp) return firstCorp;
throw new Error(
"No enterprise config found. Add a non-example JSON file under one of: " +
(candidates.length ? candidates.join(", ") : "the configured enterprise directories")
);
}
export type CorpContextOptions = Pick<GlobalConfig, "stateful" | "defaultCorpId">;
export class CorpContext {
private current: CorpConfig | null = null;
private corps = new Map<string, CorpConfig>();
private stateful = false;
private defaultCorpId: string | undefined;
constructor(corps: CorpConfig[]) {
constructor(corps: CorpConfig[], options: CorpContextOptions = { stateful: false }) {
this.stateful = options.stateful;
this.defaultCorpId = options.defaultCorpId;
this.replaceCorps(corps);
this.current = corps[0] ?? null;
this.selectCurrent(corps[0]);
}
refresh(corps: CorpConfig[]): void {
const currentId = this.current?.id ?? null;
refresh(corps: CorpConfig[], options: CorpContextOptions = {
stateful: this.stateful,
defaultCorpId: this.defaultCorpId
}): void {
const currentId = this.current?.id;
this.stateful = options.stateful;
this.defaultCorpId = options.defaultCorpId;
this.replaceCorps(corps);
this.current = currentId ? this.corps.get(currentId) ?? null : null;
this.current ??= corps[0] ?? null;
this.selectCurrent(currentId ? this.corps.get(currentId) ?? corps[0] : corps[0]);
}
private replaceCorps(corps: CorpConfig[]): void {
@@ -27,10 +70,21 @@ export class CorpContext {
return this.current;
}
getCorp(corpId: string): CorpConfig | null {
return this.corps.get(corpId) ?? null;
}
resolve(corpId?: string): CorpConfig | null {
if (corpId) return this.getCorp(corpId);
return this.current;
}
switchCorp(corpId: string): boolean {
if (!this.stateful) return false;
const corp = this.corps.get(corpId);
if (!corp) return false;
this.current = corp;
this.defaultCorpId = corp.id;
return true;
}
@@ -42,4 +96,15 @@ export class CorpContext {
current: corp.id === this.current?.id
}));
}
private selectCurrent(fallback?: CorpConfig): void {
if (!this.stateful) {
this.current = null;
return;
}
this.current = this.defaultCorpId !== undefined
? this.corps.get(this.defaultCorpId) ?? null
: fallback ?? null;
}
}
+38 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { CorpConfigSchema } from "./types.js";
import { CorpConfigSchema, GlobalConfigSchema } from "./types.js";
describe("CorpConfigSchema", () => {
test("accepts Hose key/password aliases", () => {
@@ -57,4 +57,41 @@ describe("CorpConfigSchema", () => {
}
expect(config.source.expiresIn).toBe(3600);
});
test("accepts native Seal bearer source", () => {
const config = CorpConfigSchema.parse({
id: "xiezihao",
name: "谢子豪的测试环境",
source: {
type: "seal",
token: "seal-token",
sealUrl: "https://xiezihao.staging.sealai.cc",
tenantSlug: "xiezihao",
tenantId: "tenant-id"
}
});
expect(config.source.type).toBe("seal");
if (config.source.type !== "seal") {
throw new Error("expected seal source");
}
expect(config.source.staffId).toBe("seal");
expect(config.source.tenantSlug).toBe("xiezihao");
});
});
describe("GlobalConfigSchema", () => {
test("defaults to stateless mode", () => {
expect(GlobalConfigSchema.parse({})).toEqual({ stateful: false });
});
test("accepts a stateful default enterprise", () => {
expect(GlobalConfigSchema.parse({
stateful: true,
defaultCorpId: "corp-a"
})).toEqual({
stateful: true,
defaultCorpId: "corp-a"
});
});
});
+24 -1
View File
@@ -37,9 +37,25 @@ export const DirectSealSourceSchema = z.object({
corpId: z.string().optional()
});
export const NativeSealSourceSchema = z.object({
type: z.literal("seal"),
token: z.string(),
sealUrl: z.string().url(),
expiresIn: z.number().int().positive().default(3600),
staffId: z.string().default("seal"),
corpId: z.string().optional(),
tenantId: z.string().optional(),
tenantSlug: z.string().optional(),
tenantName: z.string().optional(),
providerUserId: z.string().optional(),
provider: z.string().optional(),
providerName: z.string().optional()
});
export const SealSourceSchema = z.discriminatedUnion("type", [
HoseSealSourceSchema,
DirectSealSourceSchema
DirectSealSourceSchema,
NativeSealSourceSchema
]);
export const SealEndpointSchema = z.object({
@@ -68,8 +84,15 @@ export const CorpConfigSchema = z.object({
auth: CorpAuthConfigSchema
});
export const GlobalConfigSchema = z.object({
stateful: z.boolean().default(false),
defaultCorpId: z.string().min(1).optional()
});
export type HoseSealSource = z.infer<typeof HoseSealSourceSchema>;
export type DirectSealSource = z.infer<typeof DirectSealSourceSchema>;
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 GlobalConfig = z.infer<typeof GlobalConfigSchema>;
+12
View File
@@ -0,0 +1,12 @@
import { describe, expect, test } from "bun:test";
import { getOpenApiSchema } from "./embedded-openapi.js";
describe("embedded-openapi", () => {
test("returns valid OpenAPI 3.x schema object", () => {
const schema = getOpenApiSchema();
expect(schema).toBeDefined();
expect(schema.openapi).toBe("3.1.0");
expect(schema.info).toHaveProperty("title");
expect(schema.paths).toBeDefined();
});
});
+5
View File
@@ -0,0 +1,5 @@
import openapiSchema from "../../dist/openapi.json" with { type: "json" };
export function getOpenApiSchema(): Record<string, unknown> {
return openapiSchema as Record<string, unknown>;
}
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { EMBEDDED_SKILL_FILES, getSkillContent, installSkillFiles } from "./embedded-skill.js";
describe("embedded-skill", () => {
test("embeds SKILL.md and reference files", () => {
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: seal-home");
expect(EMBEDDED_SKILL_FILES["references/cli.md"]).toBeDefined();
expect(getSkillContent()).toContain("name: seal-home");
});
test("installSkillFiles writes all embedded files to target directory", () => {
const tmp = mkdtempSync(join(tmpdir(), "skill-test-"));
try {
const res = installSkillFiles(tmp);
expect(res.targetDir).toBe(tmp);
expect(res.files.length).toBeGreaterThan(5);
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "cli.md"))).toBe(true);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
});
+59
View File
@@ -0,0 +1,59 @@
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import skillMain from "../../skills/seal-home/SKILL.md" with { type: "text" };
import agentOpenAi from "../../skills/seal-home/agents/openai.yaml" with { type: "text" };
import refRuleLightweight from "../../skills/seal-home/references/rule-lightweight.md" with { type: "text" };
import refApprovalBadCases from "../../skills/seal-home/references/approval-bad-cases.md" with { type: "text" };
import refCli from "../../skills/seal-home/references/cli.md" with { type: "text" };
import refApprovalRunLightweight from "../../skills/seal-home/references/approval-run-lightweight.md" with { type: "text" };
import refApprovalAttachmentTrace from "../../skills/seal-home/references/approval-attachment-trace.md" with { type: "text" };
import refCustomerFeedbackRuleRemediation from "../../skills/seal-home/references/customer-feedback-rule-remediation.md" with { type: "text" };
import refHoseEnterpriseAuth from "../../skills/seal-home/references/hose-enterprise-auth.md" with { type: "text" };
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
"SKILL.md": skillMain,
"agents/openai.yaml": agentOpenAi,
"references/rule-lightweight.md": refRuleLightweight,
"references/approval-bad-cases.md": refApprovalBadCases,
"references/cli.md": refCli,
"references/approval-run-lightweight.md": refApprovalRunLightweight,
"references/approval-attachment-trace.md": refApprovalAttachmentTrace,
"references/customer-feedback-rule-remediation.md": refCustomerFeedbackRuleRemediation,
"references/hose-enterprise-auth.md": refHoseEnterpriseAuth
};
export function getSkillContent(): string {
return EMBEDDED_SKILL_FILES["SKILL.md"] || "";
}
export function getDefaultGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "seal-home");
}
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): { targetDir: string; files: string[] } {
mkdirSync(targetDir, { recursive: true });
const installed: string[] = [];
for (const [relPath, content] of Object.entries(EMBEDDED_SKILL_FILES)) {
const fullPath = join(targetDir, relPath);
mkdirSync(dirname(fullPath), { recursive: true });
writeFileSync(fullPath, content, "utf8");
installed.push(relPath);
}
return {
targetDir,
files: installed
};
}
export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: string } {
const globalDir = getDefaultGlobalSkillDir();
if (existsSync(globalDir)) {
installSkillFiles(globalDir);
return { synced: true, targetDir: globalDir };
}
return { synced: false };
}
+24
View File
@@ -28,3 +28,27 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
}
});
}
export async function createSealClientForToken(corp: CorpConfig, token: string): Promise<KyInstance> {
const session = await getSealSessionForCorp(corp);
return ky.create({
prefix: session.enterprise.sealUrl,
timeout: 30000,
headers: {
Authorization: `Bearer ${token}`
},
hooks: {
beforeError: [
async ({ error }) => {
const body =
error instanceof HTTPError
? await error.response.text().catch(() => "")
: "";
error.message = `${error.message}${body ? `: ${body}` : ""}`;
return error;
}
]
}
});
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, test } from "bun:test";
import { isCompiledBinary, resolveAppRoot, resolveDefaultLauncher } from "./runtime.js";
describe("runtime detection and launcher", () => {
test("isCompiledBinary detects bun runtime executable vs standalone binary", () => {
expect(isCompiledBinary("/Users/user/.bun/bin/bun", "file:///Users/user/code/src/cli.ts")).toBe(false);
expect(isCompiledBinary("C:\\Users\\user\\.bun\\bin\\bun.exe", "file:///C:/code/src/cli.ts")).toBe(false);
expect(isCompiledBinary("/usr/local/bin/seal-home", "file:///Users/user/code/src/cli.ts")).toBe(true);
expect(isCompiledBinary("/Users/user/.bun/bin/bun", "file:///$bunfs/root/src/cli.ts")).toBe(true);
});
test("resolveAppRoot returns cwd for compiled binary and project root for source", () => {
const sourceRoot = resolveAppRoot("/Users/user/code/src/cli.ts", false);
expect(sourceRoot).toBe("/Users/user/code");
const binaryRoot = resolveAppRoot(undefined, true);
expect(binaryRoot).toBe(process.cwd());
});
test("resolveDefaultLauncher configures args based on compiled mode", () => {
const sourceLauncher = resolveDefaultLauncher("/Users/user/code/src/cli.ts", false, "/path/to/bun");
expect(sourceLauncher).toEqual({
command: "/path/to/bun",
args: ["/Users/user/code/src/cli.ts"]
});
const binaryLauncher = resolveDefaultLauncher("/ignored", true, "/usr/local/bin/seal-home");
expect(binaryLauncher).toEqual({
command: "/usr/local/bin/seal-home",
args: []
});
});
});
+40
View File
@@ -0,0 +1,40 @@
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
export function isCompiledBinary(execPath = process.execPath, metaUrl = import.meta.url): boolean {
if (metaUrl.includes("/$bunfs/") || metaUrl.includes("\\$bunfs\\")) {
return true;
}
const lower = execPath.toLowerCase().replace(/\\/g, "/");
return !lower.endsWith("/bun") && !lower.endsWith("/bun.exe");
}
export function resolveAppRoot(entryFile?: string, isCompiled = isCompiledBinary()): string {
if (isCompiled) {
return process.cwd();
}
const file = entryFile || fileURLToPath(import.meta.url);
return dirname(dirname(file));
}
export type LauncherConfig = {
command: string;
args?: string[];
};
export function resolveDefaultLauncher(
entryFile: string,
isCompiled = isCompiledBinary(),
execPath = process.execPath
): LauncherConfig {
if (isCompiled) {
return {
command: execPath,
args: []
};
}
return {
command: execPath,
args: [entryFile]
};
}
+14
View File
@@ -0,0 +1,14 @@
declare module "*.md" {
const content: string;
export default content;
}
declare module "*.yaml" {
const content: string;
export default content;
}
declare module "*.yml" {
const content: string;
export default content;
}
+160
View File
@@ -0,0 +1,160 @@
import { describe, expect, test } from "bun:test";
import type { KyInstance } from "ky";
import {
addWebhookIntegration,
deleteWebhookIntegration,
filterWebhookIntegrations,
findWebhookIntegration,
listWebhookIntegrations,
searchUsers,
updateWebhookIntegration
} from "./api.js";
describe("Seal contact API", () => {
test("sends the contact search term as query", async () => {
let requestedUrl = "";
let requestedParams: Record<string, string> | undefined;
const client = {
get: (url: string, options?: { searchParams?: Record<string, string> }) => {
requestedUrl = url;
requestedParams = options?.searchParams;
return {
json: async () => ({
data: {
departments: [],
users: [{ _id: "user-1", name: "欧阳楠楠" }]
}
})
};
}
} as unknown as KyInstance;
const result = await searchUsers(client, "欧阳楠楠");
expect(requestedUrl).toBe("api/v1/contacts/search");
expect(requestedParams).toEqual({ query: "欧阳楠楠" });
expect(result.users).toEqual([{ _id: "user-1", name: "欧阳楠楠", departmentIds: [], permissions: [] }]);
});
});
describe("Seal Webhook API", () => {
test("reads only Webhook integrations from the approval config", async () => {
let requestedUrl = "";
const client = {
get: (url: string) => {
requestedUrl = url;
return {
json: async () => ({ data: webhookConfig() })
};
}
} as unknown as KyInstance;
const result = await listWebhookIntegrations(client);
expect(requestedUrl).toBe("api/v1/agent/ai-approval/config");
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({
id: "integration-1",
name: "Existing webhook",
type: "webhook"
});
});
test("adds a Webhook by POSTing the merged full config", async () => {
let posted: Record<string, unknown> | undefined;
const client = {
get: () => ({
json: async () => ({ data: webhookConfig() })
}),
post: (_url: string, options: { json: Record<string, unknown> }) => {
posted = options.json;
return Promise.resolve({
ok: true,
json: async () => ({ success: true })
});
}
} as unknown as KyInstance;
const result = await addWebhookIntegration(client, "https://seal.test", {
name: "New webhook",
mode: "assisted",
outgoingResultWebhook: "https://callback.test/result"
});
const integrations = posted?.integrations as Array<Record<string, unknown>>;
expect(result.name).toBe("New webhook");
expect(result.incomingDocumentWebhook.url).toContain("/document");
expect(result.incomingManualResultWebhook.url).toContain("/manual-result");
expect(result.secret).toHaveLength(32);
expect(integrations).toHaveLength(3);
expect(integrations[2]).toMatchObject({
id: result.id,
name: "New webhook"
});
expect(integrations[1]).toMatchObject({ type: "hosecloud" });
expect(posted?.integrationSystem).toBe("feishu");
});
test("updates, deletes, and finds Webhooks without replacing other integrations", async () => {
let posted: Record<string, unknown> | undefined;
const client = {
get: () => ({
json: async () => ({ data: webhookConfig() })
}),
post: (_url: string, options: { json: Record<string, unknown> }) => {
posted = options.json;
return Promise.resolve({
ok: true,
json: async () => ({ success: true })
});
}
} as unknown as KyInstance;
const updated = await updateWebhookIntegration(client, "integration-1", {
name: "Renamed webhook",
rotateSecret: true
});
expect(updated.name).toBe("Renamed webhook");
expect(updated.secret).not.toBe("webhook-secret");
expect((posted?.integrations as Array<Record<string, unknown>>)[1]).toMatchObject({ type: "hosecloud" });
const found = findWebhookIntegration([updated], "Renamed webhook");
expect(found.id).toBe("integration-1");
expect(filterWebhookIntegrations([updated], "renamed")).toEqual([updated]);
const deleted = await deleteWebhookIntegration(client, "integration-1");
expect(deleted.id).toBe("integration-1");
expect((posted?.integrations as Array<Record<string, unknown>>)).toHaveLength(1);
});
});
function webhookConfig() {
return {
decisionPreferences: {},
integrationSystem: "feishu",
integrations: [
{
type: "webhook",
id: "integration-1",
name: "Existing webhook",
mode: "assisted",
incomingDocumentWebhook: {
id: "wh_1_test",
url: "https://seal.test/api/v1/integrations/webhook/wh_1_test/document"
},
outgoingResultWebhook: "https://callback.test/existing",
incomingManualResultWebhook: {
id: "wh_1_test",
url: "https://seal.test/api/v1/integrations/webhook/wh_1_test/manual-result"
},
secret: "webhook-secret",
autoApprovalRate: 60
},
{
type: "hosecloud",
outboundName: "Other integration",
signKey: "other-secret"
}
]
};
}
+667 -2
View File
@@ -1,5 +1,8 @@
import { KyInstance } from "ky";
import { randomBytes } from "node:crypto";
import ky, { HTTPError, KyInstance } from "ky";
import { z } from "zod";
import { CorpConfig } from "../../core/config/types.js";
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
import {
ApprovalDocumentListData,
ApprovalDocumentListDataSchema,
@@ -20,9 +23,56 @@ import {
SealSessionData,
SealSessionDataSchema,
RuleSetVersion,
RuleSetVersionSchema
RuleSetVersionSchema,
SealDelegationItem,
SealDelegationItemSchema,
SealDelegationCreateResult,
SealDelegationCreateResultSchema,
SealUserCreateResult,
SealUserCreateResultSchema,
SealUserResetPasswordResult,
SealUserResetPasswordResultSchema,
SealUserDetail,
SealUserDetailSchema,
SealContactSearchResult,
SealContactSearchResultSchema,
LlmConfig,
LlmConfigSchema,
LlmProvider,
LlmProviderSchema,
AvailablePermissionsData,
AvailablePermissionsDataSchema,
PermissionConfigsData,
PermissionConfigsDataSchema,
BillingStatusData,
BillingStatusDataSchema,
WebhookIntegration,
WebhookIntegrationSchema,
WebhookMode,
SimulationBatch,
SimulationBatchSchema,
SimulationCreateResult,
SimulationCreateResultSchema,
SimulationTemplate,
SimulationTemplateSchema,
SimulationIntegrationStatus,
SimulationIntegrationStatusSchema,
SimulationHosecloudIntegration,
SimulationHosecloudIntegrationSchema,
MaterialPackage,
MaterialPackageSchema
} from "./types.js";
const SuccessResponseSchema = z.object({ success: z.boolean().optional() }).passthrough();
const RootDepartmentResponseSchema = z.object({
items: z.array(z.object({ _id: z.string() })).optional()
}).passthrough();
const PasswordLoginResponseSchema = z.object({
user: z.unknown().optional(),
session: z.object({ token: z.string().optional() }).optional()
}).passthrough();
const JsonResponseSchema = z.json();
async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
const json = (await response.json()) as { data?: unknown };
return schema.parse(json.data ?? json);
@@ -59,6 +109,20 @@ export async function deleteApprovalRule(client: KyInstance, ruleId: string): Pr
await client.delete(`api/v1/rules/${ruleId}`);
}
export async function recodeApprovalRules(client: KyInstance): Promise<unknown> {
const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false });
const body = await response.json().catch(() => ({}));
return z.object({
ok: z.boolean(),
status: z.number(),
body: z.unknown()
}).parse({
ok: response.ok,
status: response.status,
body
});
}
export async function listApprovalRuleVersions(client: KyInstance): Promise<RuleSetVersion[]> {
return unwrap(await client.get("api/v1/rule-set-versions"), z.array(RuleSetVersionSchema));
}
@@ -189,6 +253,254 @@ export async function updateApprovalStylePreferences(
);
}
export async function saveApprovalStylePreferences(
client: KyInstance,
params: Record<string, unknown>,
endpoint = "api/v1/agent/ai-approval/config"
): Promise<boolean> {
const response = await client.post(endpoint, { json: params });
const json = await response.json().catch(() => ({}));
const data = SuccessResponseSchema.safeParse(
(json as { data?: unknown }).data ?? json
);
return data.success ? data.data.success ?? response.ok : response.ok;
}
export async function listWebhookIntegrations(
client: KyInstance,
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookIntegration[]> {
const preferences = await getApprovalStylePreferences(client, endpoint);
return parseWebhookIntegrations(preferences.integrations);
}
export async function addWebhookIntegration(
client: KyInstance,
baseUrl: string,
params: {
name: string;
mode?: WebhookMode;
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookIntegration> {
const preferences = await getApprovalStylePreferences(client, endpoint);
const existing = parseWebhookIntegrations(preferences.integrations);
const integration = createWebhookIntegration(baseUrl, existing, params);
const saved = await saveApprovalStylePreferences(client, {
...preferences,
integrations: [...preferences.integrations, integration]
}, endpoint);
if (!saved) {
throw new Error("Seal did not confirm saving the Webhook integration");
}
return integration;
}
export async function updateWebhookIntegration(
client: KyInstance,
selector: string,
params: {
name?: string;
mode?: WebhookMode;
outgoingResultWebhook?: string;
autoApprovalRate?: number;
secret?: string;
rotateSecret?: boolean;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookIntegration> {
const preferences = await getApprovalStylePreferences(client, endpoint);
const entries = getWebhookEntries(preferences.integrations);
const entry = findWebhookEntry(entries, selector);
const updated = WebhookIntegrationSchema.parse({
...entry.integration,
...(params.name === undefined ? {} : { name: requiredText(params.name, "name") }),
...(params.mode === undefined ? {} : { mode: params.mode }),
...(params.outgoingResultWebhook === undefined
? {}
: { outgoingResultWebhook: validUrl(params.outgoingResultWebhook, "outgoingResultWebhook") }),
...(params.autoApprovalRate === undefined
? {}
: { autoApprovalRate: validApprovalRate(params.autoApprovalRate) }),
...(params.rotateSecret || params.secret !== undefined
? { secret: params.rotateSecret ? generateWebhookSecret() : requiredText(params.secret ?? "", "secret") }
: {})
});
const saved = await saveApprovalStylePreferences(client, {
...preferences,
integrations: preferences.integrations.map((integration, index) =>
index === entry.index ? updated : integration
)
}, endpoint);
if (!saved) {
throw new Error("Seal did not confirm saving the Webhook integration");
}
return updated;
}
export async function deleteWebhookIntegration(
client: KyInstance,
selector: string,
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookIntegration> {
const preferences = await getApprovalStylePreferences(client, endpoint);
const entries = getWebhookEntries(preferences.integrations);
const entry = findWebhookEntry(entries, selector);
const saved = await saveApprovalStylePreferences(client, {
...preferences,
integrations: preferences.integrations.filter((_, index) => index !== entry.index)
}, endpoint);
if (!saved) {
throw new Error("Seal did not confirm deleting the Webhook integration");
}
return entry.integration;
}
export function findWebhookIntegration(
integrations: WebhookIntegration[],
selector: string
): WebhookIntegration {
const normalized = selector.trim();
if (!normalized) throw new Error("Webhook selector must not be empty");
const exactId = integrations.find((integration) => integration.id === normalized);
if (exactId) return exactId;
const byName = integrations.filter((integration) => integration.name === normalized);
if (byName.length === 1) return byName[0]!;
if (byName.length > 1) {
throw new Error(`Multiple Webhook integrations match name: ${normalized}. Use the integration ID.`);
}
throw new Error(`Webhook integration not found: ${normalized}`);
}
export function filterWebhookIntegrations(
integrations: WebhookIntegration[],
query?: string
): WebhookIntegration[] {
const needle = query?.trim().toLowerCase();
if (!needle) return integrations;
return integrations.filter((integration) => [
integration.id,
integration.name,
integration.mode,
integration.outgoingResultWebhook,
integration.incomingDocumentWebhook.url,
integration.incomingManualResultWebhook.url
].some((value) => value.toLowerCase().includes(needle)));
}
function parseWebhookIntegrations(
integrations: Array<{ type: string } & Record<string, unknown>>
): WebhookIntegration[] {
return integrations
.filter((integration) => integration.type === "webhook")
.map((integration) => WebhookIntegrationSchema.parse(integration));
}
function getWebhookEntries(
integrations: Array<{ type: string } & Record<string, unknown>>
): Array<{ index: number; integration: WebhookIntegration }> {
return integrations.flatMap((integration, index) => {
if (integration.type !== "webhook") return [];
return [{ index, integration: WebhookIntegrationSchema.parse(integration) }];
});
}
function findWebhookEntry(
entries: Array<{ index: number; integration: WebhookIntegration }>,
selector: string
) {
const integration = findWebhookIntegration(
entries.map((entry) => entry.integration),
selector
);
return entries.find((entry) => entry.integration.id === integration.id)!;
}
function createWebhookIntegration(
baseUrl: string,
existing: WebhookIntegration[],
params: {
name: string;
mode?: WebhookMode;
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
}
): WebhookIntegration {
const name = requiredText(params.name, "name");
const mode = params.mode ?? "assisted";
const outgoingResultWebhook = validUrl(params.outgoingResultWebhook, "outgoingResultWebhook");
const autoApprovalRate = validApprovalRate(params.autoApprovalRate ?? 60);
const stamp = nextWebhookTimestamp(existing);
const webhookId = `wh_${stamp}_${randomBytes(8).toString("hex").slice(0, 7)}`;
const root = normalizeBaseUrl(baseUrl);
return WebhookIntegrationSchema.parse({
type: "webhook",
id: `integration-${stamp}`,
name,
mode,
incomingDocumentWebhook: {
id: webhookId,
url: `${root}/api/v1/integrations/webhook/${webhookId}/document`
},
outgoingResultWebhook,
incomingManualResultWebhook: {
id: webhookId,
url: `${root}/api/v1/integrations/webhook/${webhookId}/manual-result`
},
secret: params.secret ? requiredText(params.secret, "secret") : generateWebhookSecret(),
autoApprovalRate
});
}
function nextWebhookTimestamp(existing: WebhookIntegration[]): number {
const usedIds = new Set(existing.map((integration) => integration.id));
let stamp = Date.now();
while (usedIds.has(`integration-${stamp}`)) stamp += 1;
return stamp;
}
function generateWebhookSecret(): string {
return randomBytes(16).toString("hex");
}
function requiredText(value: string, field: string): string {
const normalized = value.trim();
if (!normalized) throw new Error(`Webhook ${field} must not be empty`);
return normalized;
}
function validUrl(value: string, field: string): string {
const normalized = requiredText(value, field);
try {
return new URL(normalized).toString();
} catch {
throw new Error(`Webhook ${field} must be a valid URL`);
}
}
function validApprovalRate(value: number): number {
if (!Number.isInteger(value) || value < 0 || value > 100) {
throw new Error("Webhook autoApprovalRate must be an integer between 0 and 100");
}
return value;
}
export async function getApprovalContext(
client: KyInstance,
params: {
@@ -277,6 +589,78 @@ export async function listSimulationBatchRecords(
return parsed.records;
}
export async function createSimulationBatch(
client: KyInstance,
params: Record<string, unknown>
): Promise<SimulationCreateResult> {
return unwrap(
await client.post("api/v1/simulation/create-batch", { json: params }),
SimulationCreateResultSchema
);
}
export async function createMaterialPackBatch(
client: KyInstance,
params: Record<string, unknown>
): Promise<SimulationCreateResult> {
return unwrap(
await client.post("api/v1/simulation/create-material-pack-batch", { json: params }),
SimulationCreateResultSchema
);
}
export async function listSimulationBatches(
client: KyInstance,
opts: { limit?: number } = {}
): Promise<SimulationBatch[]> {
const json = (await client
.get("api/v1/simulation/batches", {
searchParams: { limit: String(opts.limit ?? 50) }
})
.json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationBatchSchema).parse(data);
}
export async function getSimulationBatch(
client: KyInstance,
batchId: string
): Promise<SimulationBatch> {
return unwrap(await client.get(`api/v1/simulation/batch/${batchId}`), SimulationBatchSchema);
}
export async function listSimulationTemplates(client: KyInstance): Promise<SimulationTemplate[]> {
const json = (await client.get("api/v1/simulation/templates").json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationTemplateSchema).parse(data);
}
export async function getSimulationIntegrationStatus(
client: KyInstance
): Promise<SimulationIntegrationStatus> {
return unwrap(await client.get("api/v1/simulation/integration-status"), SimulationIntegrationStatusSchema);
}
export async function listSimulationHosecloudIntegrations(
client: KyInstance
): Promise<SimulationHosecloudIntegration[]> {
const json = (await client.get("api/v1/simulation/hosecloud-integrations").json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationHosecloudIntegrationSchema).parse(data);
}
export async function uploadMaterialPackage(
client: KyInstance,
params: { fileName: string; fileBuffer: Uint8Array }
): Promise<MaterialPackage> {
const form = new FormData();
form.append("file", new Blob([new Uint8Array(params.fileBuffer)]), params.fileName);
return unwrap(
await client.post("api/v1/material-packages/upload", { body: form }),
MaterialPackageSchema
);
}
function setOptional(searchParams: URLSearchParams, key: string, value?: string) {
if (value) {
searchParams.set(key, value);
@@ -298,3 +682,284 @@ function setArrayOptional(
searchParams.set(`${key}[${index}]`, item);
});
}
export async function listDelegations(client: KyInstance): Promise<SealDelegationItem[]> {
return unwrap(await client.get("api/v1/delegation/list"), z.array(SealDelegationItemSchema));
}
export async function createDelegation(
client: KyInstance,
params?: { note?: string }
): Promise<SealDelegationCreateResult> {
return unwrap(
await client.post("api/v1/delegation/create", { json: params ?? {} }),
SealDelegationCreateResultSchema
);
}
export async function revokeDelegation(client: KyInstance, tokenId: string): Promise<boolean> {
const response = await client.post("api/v1/delegation/revoke", { json: { tokenId } });
const json = (await response.json()) as { data?: unknown };
const data = SuccessResponseSchema.safeParse(json.data ?? json);
return data.success ? data.data.success ?? response.ok : response.ok;
}
export async function createLocalUser(
client: KyInstance,
params: { name: string; phone: string; permissions?: string[]; departmentIds?: string[] }
): Promise<SealUserCreateResult> {
let departmentIds = params.departmentIds && params.departmentIds.length > 0 ? params.departmentIds : undefined;
if (!departmentIds) {
const rootDepts = (await client.get("api/v1/contacts/departments/root/children").json()) as { data?: unknown };
const rootData = RootDepartmentResponseSchema.safeParse(rootDepts.data ?? rootDepts);
const firstId = rootData.success ? rootData.data.items?.[0]?._id : undefined;
if (firstId) {
departmentIds = [firstId];
}
}
return unwrap(
await client.post("api/v1/contacts/local/users", {
json: {
name: params.name,
phone: params.phone,
permissions: params.permissions ?? [],
departmentIds: departmentIds ?? []
}
}),
SealUserCreateResultSchema
);
}
export async function resetUserPassword(
client: KyInstance,
userId: string
): Promise<SealUserResetPasswordResult> {
return unwrap(
await client.post(`api/v1/contacts/local/users/${userId}/reset-password`, { json: {} }),
SealUserResetPasswordResultSchema
);
}
export async function getUserDetail(
client: KyInstance,
userId: string
): Promise<SealUserDetail> {
return unwrap(
await client.get(`api/v1/contacts/users/${userId}`),
SealUserDetailSchema
);
}
export async function searchUsers(
client: KyInstance,
keyword = ""
): Promise<SealContactSearchResult> {
return unwrap(
await client.get("api/v1/contacts/search", { searchParams: { query: keyword } }),
SealContactSearchResultSchema
);
}
export async function deleteLocalUser(
client: KyInstance,
userId: string
): Promise<boolean> {
const response = await client.delete(`api/v1/contacts/local/users/${userId}`);
const json = (await response.json()) as { data?: unknown };
const data = SuccessResponseSchema.safeParse(json.data ?? json);
return data.success ? data.data.success ?? response.ok : response.ok;
}
export async function activateLocalUser(
client: KyInstance,
userId: string
): Promise<boolean> {
const response = await client.post(`api/v1/contacts/local/users/${userId}/activate`, { json: {} });
const json = (await response.json()) as { data?: unknown };
const data = SuccessResponseSchema.safeParse(json.data ?? json);
return data.success ? data.data.success ?? response.ok : response.ok;
}
export async function loginWithPhonePassword(
client: KyInstance,
params: { phone: string; password: string }
): Promise<{ token: string; user: unknown }> {
const response = await client.post("api/auth/sms-otp/sign-in-password", {
json: params
});
const setAuthToken = response.headers.get("set-auth-token");
const json = PasswordLoginResponseSchema.parse(await response.json());
const token = setAuthToken ?? json.session?.token;
if (!token) {
throw new Error("Failed to retrieve authentication token from login response");
}
return { token, user: json.user };
}
export async function createDelegationForUser(
client: KyInstance,
params: { userIdOrPhone: string; note?: string },
createClientForToken: (token: string) => Promise<KyInstance>,
corp?: CorpConfig
): Promise<{
targetUser: SealUserDetail;
delegation: SealDelegationCreateResult;
temporaryPassword: string;
}> {
let user: SealUserDetail;
if (params.userIdOrPhone.startsWith("+") || /^\d{11}$/.test(params.userIdOrPhone)) {
const search = await searchUsers(client, params.userIdOrPhone);
const found = search.users.find(
(u) => u.mobile?.includes(params.userIdOrPhone) || u._id === params.userIdOrPhone
) ?? search.users[0];
if (!found) {
throw new Error(`User not found with phone/ID: ${params.userIdOrPhone}`);
}
user = found;
} else {
user = await getUserDetail(client, params.userIdOrPhone).catch(async () => {
const search = await searchUsers(client, params.userIdOrPhone);
// 优先精确匹配姓名,避免返回错误用户
const found =
search.users.find((u) => u.name === params.userIdOrPhone) ?? search.users[0];
if (!found) throw new Error(`User not found: ${params.userIdOrPhone}`);
return found;
});
}
if (user.status === "resigned") {
await activateLocalUser(client, user._id);
user = await getUserDetail(client, user._id);
}
const userAny = user as any;
const isSynced =
(Array.isArray(userAny.identities) &&
(userAny.identities as Array<{ provider?: string }>).some(
(i) => i.provider && i.provider !== "local"
)) ||
!!userAny.apps?.hosecloud;
if (isSynced && corp && corp.source.type === "hose") {
const rawPhone =
user.mobile ||
(userAny.identities as Array<{ providerId?: string }>)?.[0]?.providerId ||
"";
const cleanPhone = rawPhone.replace(/^\+86/, "");
const hoseIdentity = (userAny.identities as Array<{ provider?: string; providerId?: string }>)?.find(
(i) => i.provider === "hosecloud"
)?.providerId;
const staffId =
(userAny.apps?.hosecloud as { boundId?: string })?.boundId ||
hoseIdentity ||
(cleanPhone ? `${corp.source.corpId}:${cleanPhone}` : undefined);
if (staffId) {
const openapiToken = await ensureHoseOpenapiToken(corp);
const provisional = await fetchHoseCloseApiToken({ ...corp.source, staffId }, openapiToken);
const closeapiToken = provisional.token;
const sealUrl = defaultSealUrl(corp, corp.source);
let sealResponse: { token?: string; accessToken?: string; data?: { token?: string } };
try {
sealResponse = await ky
.get(`${normalizeBaseUrl(sealUrl)}/api/auth/oauth2/session/oem-hosecloud`, {
searchParams: {
token: closeapiToken,
returnToken: "1"
},
timeout: 30000
})
.json<{ token?: string; accessToken?: string; data?: { token?: string } }>();
} catch (error: unknown) {
if (error instanceof HTTPError && error.response.status === 400) {
throw new Error(`Seal AI 用户“${user.name}”未绑定合思账号,无法生成个人协助链接。`);
}
throw error;
}
const targetUserSealToken =
sealResponse.token ?? sealResponse.accessToken ?? sealResponse.data?.token;
if (targetUserSealToken) {
const userClient = await createClientForToken(targetUserSealToken);
const delegation = await createDelegation(userClient, {
note: params.note ?? `Delegation generated by admin for ${user.name}`
});
return {
targetUser: user,
delegation,
temporaryPassword: "N/A (Hose SSO)"
};
}
}
}
let resetRes: SealUserResetPasswordResult;
try {
resetRes = await resetUserPassword(client, user._id);
} catch (err: any) {
if (isSynced) {
throw new Error(
`用户 "${user.name}" (${user.mobile || user._id}) 为合思同步账号 (provider: hosecloud),无 Seal 本地密码。` +
`Seal 系统暂不支持对同步账号直接重置本地密码。`
);
}
throw err;
}
const rawPhone = user.mobile || (user as unknown as { identities?: Array<{ providerId?: string }> }).identities?.[0]?.providerId || "";
const cleanPhone = rawPhone.replace(/^\+86/, "");
if (!cleanPhone) {
throw new Error(`User ${user.name} has no associated phone number for password login`);
}
const { token } = await loginWithPhonePassword(client, {
phone: cleanPhone,
password: resetRes.password
});
const userClient = await createClientForToken(token);
const delegation = await createDelegation(userClient, {
note: params.note ?? `Delegation generated by admin for ${user.name}`
});
return {
targetUser: user,
delegation,
temporaryPassword: resetRes.password
};
}
export async function getLlmConfig(client: KyInstance): Promise<LlmConfig> {
return unwrap(await client.get("api/v1/llm/config"), LlmConfigSchema);
}
export async function listLlmProviders(client: KyInstance): Promise<LlmProvider[]> {
return unwrap(await client.get("api/v1/llm/providers"), z.array(LlmProviderSchema));
}
export async function listAvailablePermissions(client: KyInstance): Promise<AvailablePermissionsData> {
return unwrap(await client.get("api/v1/permissions/available"), AvailablePermissionsDataSchema);
}
export async function listPermissionConfigs(client: KyInstance): Promise<PermissionConfigsData> {
return unwrap(await client.get("api/v1/permissions/configs"), PermissionConfigsDataSchema);
}
export async function getBillingStatus(client: KyInstance): Promise<BillingStatusData> {
return unwrap(await client.get("api/v1/billing/status"), BillingStatusDataSchema);
}
export async function listBillingPlans(client: KyInstance): Promise<unknown> {
const response = await client.get("api/v1/billing/plans");
const json = (await response.json()) as { data?: unknown };
return JsonResponseSchema.parse(json.data ?? json);
}
export async function listBillingFeatures(client: KyInstance): Promise<unknown> {
const response = await client.get("api/v1/billing/features");
const json = (await response.json()) as { data?: unknown };
return JsonResponseSchema.parse(json.data ?? json);
}
+174
View File
@@ -0,0 +1,174 @@
import { describe, expect, test } from "bun:test";
import { KyInstance } from "ky";
import { CorpConfig } from "../../core/config/types.js";
import { searchApprovalContent } from "./search.js";
function fakeSearchClient(): KyInstance {
return {
get: (url: string) => ({
json: async () => {
if (url.startsWith("api/v1/rules")) {
return {
data: {
rules: [
{
id: "rule-101",
scope: "差旅报销",
strictness: "MUST_FOLLOW",
status: "active",
description: "差旅住宿发票必须提供明细与住宿清单"
},
{
id: "rule-102",
scope: "餐饮招待",
strictness: "SHOULD_FOLLOW",
status: "active",
description: "餐饮发票单笔超过 500 元需附同人同行名单"
}
]
}
};
}
if (url.startsWith("api/v1/knowledge/articles")) {
return {
data: {
total: 1,
articles: [
{
id: "doc-1",
title: "企业差旅管理制度",
purpose: "规范集团员工出差标准",
contentType: "policy",
content: "第一条 出差前需提交申请单\n第二条 住宿费标准每晚最高 800 元\n第三条 报销须在出差结束后 15 天内提交",
status: "published",
scenarios: ["差旅"],
tags: ["制度"]
}
]
}
};
}
if (url === "api/v1/agent/ai-approval/config") {
return {
data: {
tone: "professional",
decisionPreferences: {
explicitApprove: "规则全过且无风险时直接通过",
review: "存疑单据转人工复核"
},
integrations: [
{
type: "hosecloud",
outboundName: "合思推送",
mode: "automatic"
}
]
}
};
}
return { data: {} };
}
})
} as unknown as KyInstance;
}
function fakeCorp(): CorpConfig {
return {
id: "corp-search-test",
name: "Search Test Corp",
seal: {
url: "https://seal.test",
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "direct",
token: "tok",
sealUrl: "https://seal.test",
expiresIn: 3600,
staffId: "direct"
},
auth: {
refreshTtl: 300
}
};
}
describe("searchApprovalContent", () => {
test("searches across rules, documents, and preferences by default", async () => {
const client = fakeSearchClient();
const corp = fakeCorp();
const result = await searchApprovalContent(client, corp, {
keywords: ["差旅"],
refresh: true
});
expect(result.total).toBeGreaterThan(0);
const areas = new Set(result.results.map((r) => r.area));
expect(areas.has("rules")).toBe(true);
expect(areas.has("documents")).toBe(true);
});
test("respects matchMode 'all' vs 'any'", async () => {
const client = fakeSearchClient();
const corp = fakeCorp();
const anyResult = await searchApprovalContent(client, corp, {
keywords: ["住宿", "发票"],
matchMode: "any",
refresh: true
});
expect(anyResult.total).toBeGreaterThan(0);
const allResult = await searchApprovalContent(client, corp, {
keywords: ["住宿", "发票"],
matchMode: "all",
refresh: true
});
// Line: "差旅住宿发票必须提供明细与住宿清单" contains both "住宿" and "发票"
expect(allResult.total).toBeGreaterThan(0);
expect(allResult.results[0]?.matchedKeywords).toEqual(["住宿", "发票"]);
});
test("filters search by explicit area", async () => {
const client = fakeSearchClient();
const corp = fakeCorp();
const rulesOnly = await searchApprovalContent(client, corp, {
keywords: ["住宿"],
areas: ["rules"],
refresh: true
});
expect(rulesOnly.results.every((r) => r.area === "rules")).toBe(true);
});
test("supports snippetOnly and maxChars truncation", async () => {
const client = fakeSearchClient();
const corp = fakeCorp();
const snippetResult = await searchApprovalContent(client, corp, {
keywords: ["住宿"],
snippetOnly: true,
maxChars: 10,
refresh: true
});
const first = snippetResult.results[0];
expect(first).toBeDefined();
expect(first?.context.before).toEqual([]);
expect(first?.context.after).toEqual([]);
expect(first?.matchedText.length).toBeLessThanOrEqual(13); // 10 chars + "..."
});
test("throws error when keywords array is empty", () => {
const client = fakeSearchClient();
const corp = fakeCorp();
expect(searchApprovalContent(client, corp, { keywords: [" "] })).rejects.toThrow(
"keywords must contain at least one non-empty string"
);
});
});
+534
View File
@@ -0,0 +1,534 @@
import { describe, expect, test } from "bun:test";
import { KyInstance } from "ky";
import { CorpConfig } from "../../core/config/types.js";
import {
createMaterialPackBatch,
createSimulationBatch,
getSimulationBatch,
getSimulationIntegrationStatus,
listSimulationBatches,
listSimulationHosecloudIntegrations,
listSimulationTemplates,
uploadMaterialPackage
} from "./api.js";
import { buildSimulationBatchParams, sealTools } from "./tools.js";
import {
MaterialPackageSchema,
SimulationBatchSchema,
SimulationIntegrationStatusSchema,
SimulationTemplateSchema
} from "./types.js";
type ToolHandler = (
client: KyInstance,
params: Record<string, unknown>,
context: { corp: CorpConfig }
) => Promise<unknown>;
// Fixtures captured from xiezihao staging console traffic (2026-08-24).
// Real tenant signKey is redacted; capture the value locally if needed.
const SIGN_KEY = "test-sign-key";
const hosecloudBatchFixture = {
id: "01a032f6-9798-7021-a632-f9fffb48f463",
tenantId: "019ef38b-b80a-732e-abb6-8bcb62a373a9",
approvalCode: "hosecloud",
nodeId: "hosecloud",
sourceSystem: "hosecloud",
status: "syncing",
totalCount: 0,
processedCount: 0,
successCount: 0,
failedCount: 0,
createdCount: 0,
createFailedCount: 0,
params: {
approvalCode: "hosecloud",
nodeId: "hosecloud",
startTime: 0,
endTime: 0,
limit: 1,
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
disableAttachmentCache: false,
dataCollectionMode: "2",
flowIds: ["B26017701"],
signKey: SIGN_KEY,
rejectNodeName: null,
thinkingDepthOverride: "medium"
},
requestSummary: {
mode: "指定单号",
conditions: [
{ label: "取数模式", value: "指定单号" },
{ label: "指定单号数量", value: "1" }
]
},
resultSummary: null,
createdAt: "2026-08-24T08:50:16.600Z",
updatedAt: "2026-08-24T08:50:16.606Z"
};
const templateFixture = {
id: "019ef84b-1065-71f8-b916-c6592d869fd3",
tenantId: "019ef38b-b80a-732e-abb6-8bcb62a373a9",
name: "ack11",
description: "find",
approvalSystem: "hosecloud",
hosecloudConfig: {
dataCollectionMode: "2",
flowIds: ["B26022501", "B26028572"],
rejectNodeName: null,
skipInvoiceGeneration: false,
skipExpenseExtraction: true
},
createdAt: "2026-06-24T06:22:09.507Z",
updatedAt: "2026-06-24T06:22:09.507Z"
};
const integrationStatusFixture = {
hasFeishu: false,
hasHosecloud: true,
hasWeaver: false,
hasHelios: false,
hasMaycur: false,
hasMaycurStandard: false
};
const materialPackageUploadFixture = {
id: "019fcae7-21f5-73fc-8bf1-cfff0a464607",
tenantId: "019ef38b-b80a-732e-abb6-8bcb62a373a9",
name: "测试材料包",
templateId: "conference_reimbursement_v1",
originalFileName: "测试材料包.zip",
status: "ready",
documentCount: 2,
attachmentCount: 18,
uploadedBy: "019ef38b-b850-768e-bbbf-bee26b81416a",
schemaConfig: {
id: "conference_reimbursement_v1",
listSheets: [
{
columns: [
{ key: "code", type: "AMOUNT", label: "费类code", column: "费类code" },
{ key: "feiyongleixing", type: "TEXT", label: "费用类型", column: "费用类型" },
{ key: "jine", type: "AMOUNT", label: "金额", column: "金额" }
],
fieldKey: "sheet1_list",
keyColumn: "会议编号",
sheetName: "Sheet1",
fieldLabel: "Sheet1列表"
}
],
mainColumns: [
{ key: "huiyibianhao", type: "TEXT", label: "会议编号", column: "会议编号" },
{ key: "tijiaoren", type: "TEXT", label: "提交人", column: "提交人" },
{ key: "shifouyiwancheng", type: "TEXT", label: "是否已完成", column: "是否已完成" },
{ key: "jine", type: "AMOUNT", label: "金额", column: "金额" }
],
workbookName: "信息表.xlsx",
mainKeyColumn: "会议编号",
mainSheetName: "会议",
attachmentFieldKey: "supporting_files",
attachmentFieldLabel: "支撑材料"
},
createdAt: "2026-08-04T03:52:52.979Z",
updatedAt: "2026-08-04T04:07:12.368Z"
};
function fakeContext(): { corp: CorpConfig } {
return {
corp: {
id: "xiezihao",
name: "谢子豪的测试环境",
seal: {
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "token",
sealUrl: "https://xiezihao.staging.sealai.cc",
expiresIn: 3600,
staffId: "test"
}
} as CorpConfig
};
}
describe("buildSimulationBatchParams", () => {
test("builds hosecloud request payload matching the captured create-batch body", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26017701"],
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
disableAttachmentCache: false,
rejectNodeName: null,
thinkingDepthOverride: "default",
signKey: SIGN_KEY
});
expect(params).toEqual({
dataCollectionMode: "2",
rejectNodeName: null,
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
disableAttachmentCache: false,
thinkingDepthOverride: "default",
sourceSystem: "hosecloud",
flowIds: ["B26017701"],
signKey: SIGN_KEY
});
// approvalCode/nodeId/limit/startTime/endTime 由服务端从请求推导,不进请求体
expect(params).not.toHaveProperty("approvalCode");
expect(params).not.toHaveProperty("nodeId");
expect(params).not.toHaveProperty("limit");
expect(params).not.toHaveProperty("startTime");
expect(params).not.toHaveProperty("endTime");
});
test("supports node override and deep thinking depth", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26010080", "B25011446"],
skipExpenseExtraction: false,
disableAttachmentCache: true,
rejectNodeName: "财务",
thinkingDepthOverride: "high",
signKey: SIGN_KEY
});
expect(params).toMatchObject({
flowIds: ["B26010080", "B25011446"],
skipInvoiceGeneration: true,
skipExpenseExtraction: false,
disableAttachmentCache: true,
rejectNodeName: "财务",
thinkingDepthOverride: "high"
});
expect(params).not.toHaveProperty("limit");
});
test("builds material_pack payload with the confirmed schema config", () => {
const params = buildSimulationBatchParams({
mode: "material_pack",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
templateId: "conference_reimbursement_v1",
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
schemaConfig: {
id: "conference_reimbursement_v1",
mainColumns: [
{ key: "huiyibianhao", type: "TEXT", label: "会议编号", column: "会议编号" }
],
listSheets: [],
workbookName: "信息表.xlsx",
mainKeyColumn: "会议编号",
mainSheetName: "Sheet1",
attachmentFieldKey: "supporting_files",
attachmentFieldLabel: "支撑材料"
}
});
expect(params).toMatchObject({
templateId: "conference_reimbursement_v1",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
approvalCode: "material_pack",
nodeId: "material_pack",
runMode: "import_and_simulate",
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
disableAttachmentCache: false,
thinkingDepthOverride: "default",
schemaConfig: {
id: "conference_reimbursement_v1",
mainKeyColumn: "会议编号",
attachmentFieldKey: "supporting_files"
}
});
// 材料包走独立端点, 请求体不带合思专属字段和服务端推导字段
expect(params).not.toHaveProperty("sourceSystem");
expect(params).not.toHaveProperty("flowIds");
expect(params).not.toHaveProperty("dataCollectionMode");
expect(params).not.toHaveProperty("rejectNodeName");
expect(params).not.toHaveProperty("limit");
expect(params).not.toHaveProperty("packageLabel");
});
test("derives templateId from schemaConfig.id when omitted", () => {
const params = buildSimulationBatchParams({
mode: "material_pack",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
schemaConfig: { id: "conference_reimbursement_v1", mainSheetName: "Sheet1" }
});
expect(params).toMatchObject({
templateId: "conference_reimbursement_v1",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
approvalCode: "material_pack"
});
});
test("rawParams can introduce reserved time-range fields", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26017701"],
signKey: SIGN_KEY,
rawParams: { startTime: 1786000000000, endTime: 1787000000000 }
});
expect(params).toMatchObject({
startTime: 1786000000000,
endTime: 1787000000000
});
});
test("rejects hosecloud mode without flowIds", () => {
expect(() => buildSimulationBatchParams({ mode: "hosecloud", signKey: SIGN_KEY }))
.toThrow("hosecloud 模式需要提供 flowIds");
});
test("rejects material_pack mode without packageIds", () => {
expect(() => buildSimulationBatchParams({ mode: "material_pack" }))
.toThrow("material_pack 模式需要提供 packageIds");
});
});
describe("simulation API client", () => {
test("creates a batch by POSTing to create-batch", async () => {
let postedUrl = "";
let postedBody: Record<string, unknown> | undefined;
const client = {
post: (url: string, options: { json: Record<string, unknown> }) => {
postedUrl = url;
postedBody = options.json;
return { json: async () => ({ data: { batchId: "01a032f6-9798-7021-a632-f9fffb48f463" } }) };
}
} as unknown as KyInstance;
const result = await createSimulationBatch(client, { approvalCode: "hosecloud" });
expect(postedUrl).toBe("api/v1/simulation/create-batch");
expect(postedBody).toEqual({ approvalCode: "hosecloud" });
expect(result.batchId).toBe("01a032f6-9798-7021-a632-f9fffb48f463");
});
test("creates a material pack batch via its own endpoint", async () => {
let postedUrl = "";
const client = {
post: (url: string, options: { json: Record<string, unknown> }) => {
postedUrl = url;
expect(options.json).toMatchObject({ templateId: "conference_reimbursement_v1" });
return { json: async () => ({ data: { batchId: "material-batch-1" } }) };
}
} as unknown as KyInstance;
const result = await createMaterialPackBatch(client, { templateId: "conference_reimbursement_v1" });
expect(postedUrl).toBe("api/v1/simulation/create-material-pack-batch");
expect(result.batchId).toBe("material-batch-1");
});
test("lists batches with a limit query", async () => {
let requestedUrl = "";
let requestedParams: Record<string, string> | undefined;
const client = {
get: (url: string, options?: { searchParams?: Record<string, string> }) => {
requestedUrl = url;
requestedParams = options?.searchParams;
return { json: async () => ({ data: [hosecloudBatchFixture] }) };
}
} as unknown as KyInstance;
const result = await listSimulationBatches(client, { limit: 10 });
expect(requestedUrl).toBe("api/v1/simulation/batches");
expect(requestedParams).toEqual({ limit: "10" });
expect(result).toHaveLength(1);
expect(result[0]!.id).toBe("01a032f6-9798-7021-a632-f9fffb48f463");
});
test("gets batch detail and templates", async () => {
const client = {
get: (url: string) => {
if (url === "api/v1/simulation/batch/01a032f6-9798-7021-a632-f9fffb48f463") {
return { json: async () => ({ data: hosecloudBatchFixture }) };
}
if (url === "api/v1/simulation/templates") {
return { json: async () => ({ data: [templateFixture] }) };
}
throw new Error(`unexpected url ${url}`);
}
} as unknown as KyInstance;
const batch = await getSimulationBatch(client, "01a032f6-9798-7021-a632-f9fffb48f463");
expect(batch.params?.flowIds).toEqual(["B26017701"]);
expect(batch.requestSummary?.mode).toBe("指定单号");
const templates = await listSimulationTemplates(client);
expect(templates).toHaveLength(1);
expect(templates[0]!.name).toBe("ack11");
});
test("uploads a material package as multipart with the file field", async () => {
let postedUrl = "";
let postedBody: unknown;
const client = {
post: (url: string, options: { body: unknown }) => {
postedUrl = url;
postedBody = options.body;
return { json: async () => ({ data: materialPackageUploadFixture }) };
}
} as unknown as KyInstance;
const result = await uploadMaterialPackage(client, {
fileName: "测试材料包.zip",
fileBuffer: new Uint8Array([1, 2, 3])
});
expect(postedUrl).toBe("api/v1/material-packages/upload");
expect(postedBody).toBeInstanceOf(FormData);
const entry = (postedBody as FormData).get("file");
expect(entry).toBeInstanceOf(File);
expect((entry as File).name).toBe("测试材料包.zip");
expect(result.id).toBe("019fcae7-21f5-73fc-8bf1-cfff0a464607");
expect(result.schemaConfig?.mainKeyColumn).toBe("会议编号");
});
test("gets integration status and hosecloud integrations", async () => {
const client = {
get: (url: string) => {
if (url === "api/v1/simulation/integration-status") {
return { json: async () => ({ data: integrationStatusFixture }) };
}
if (url === "api/v1/simulation/hosecloud-integrations") {
return {
json: async () => ({
data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试-不要配置到审批流", corporationId: "ID01Nl1kQVYbKL" }]
})
};
}
throw new Error(`unexpected url ${url}`);
}
} as unknown as KyInstance;
const status = await getSimulationIntegrationStatus(client);
expect(status.hasHosecloud).toBe(true);
expect(status.hasFeishu).toBe(false);
const integrations = await listSimulationHosecloudIntegrations(client);
expect(integrations[0]!.signKey).toBe(SIGN_KEY);
});
});
describe("simulation tool handlers", () => {
test("create tool resolves signKey automatically and posts the payload", async () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_create");
expect(tool).toBeDefined();
let postedBody: Record<string, unknown> | undefined;
let assertPosted = false;
const client = {
get: (url: string) => {
if (url === "api/v1/simulation/hosecloud-integrations") {
return {
json: async () => ({
data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试" }]
})
};
}
throw new Error(`unexpected url ${url}`);
},
post: (url: string, options: { json: Record<string, unknown> }) => {
assertPosted = url === "api/v1/simulation/create-batch";
postedBody = options.json;
return { json: async () => ({ data: { batchId: "batch-1" } }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, {
mode: "hosecloud",
flowIds: ["B26017701"],
thinkingDepthOverride: "default"
}, fakeContext());
expect(assertPosted).toBe(true);
expect(postedBody).toMatchObject({
flowIds: ["B26017701"],
signKey: SIGN_KEY,
thinkingDepthOverride: "default",
sourceSystem: "hosecloud"
});
expect(postedBody).not.toHaveProperty("limit");
expect(result).toMatchObject({ batchId: "batch-1", created: true });
});
test("create tool surface exposes mode, flowIds, and rawParams", () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_create");
const { z } = require("zod") as typeof import("zod");
const schema = z.toJSONSchema(tool!.parameters) as { properties?: Record<string, unknown> };
expect(Object.keys(schema.properties ?? {})).toEqual(
expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds"])
);
});
test("includes the simulation management tool set", () => {
expect(sealTools.find((item) => item.name === "seal_simulation_batches_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_templates_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_integrations_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_records_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_material_package_upload")).toBeDefined();
});
});
describe("simulation response schemas", () => {
test("parses the captured batch detail including echoed params", () => {
const parsed = SimulationBatchSchema.parse(hosecloudBatchFixture);
expect(parsed.status).toBe("syncing");
expect(parsed.params?.thinkingDepthOverride).toBe("medium");
expect(parsed.requestSummary?.conditions).toHaveLength(2);
});
test("tolerates legacy batches without requestSummary", () => {
const legacy = {
...hosecloudBatchFixture,
id: "019f3556-9c4e-7599-b13a-9df52c18f8a2",
requestSummary: null,
params: {
approvalCode: "hosecloud",
nodeId: "hosecloud",
startTime: 0,
endTime: 0,
limit: 2,
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
dataCollectionMode: "2",
flowIds: ["B26022501", "B26028572"],
signKey: SIGN_KEY,
rejectNodeName: null
}
};
const parsed = SimulationBatchSchema.parse(legacy);
expect(parsed.id).toBe("019f3556-9c4e-7599-b13a-9df52c18f8a2");
expect(parsed.requestSummary).toBeNull();
});
test("parses the captured template with hosecloudConfig", () => {
const parsed = SimulationTemplateSchema.parse(templateFixture);
expect(parsed.name).toBe("ack11");
expect(parsed.hosecloudConfig?.flowIds).toContain("B26022501");
});
test("parses the captured integration status", () => {
const parsed = SimulationIntegrationStatusSchema.parse(integrationStatusFixture);
expect(parsed.hasHosecloud).toBe(true);
});
test("parses the captured material package upload response", () => {
const parsed = MaterialPackageSchema.parse(materialPackageUploadFixture);
expect(parsed.templateId).toBe("conference_reimbursement_v1");
expect(parsed.schemaConfig?.mainColumns).toHaveLength(4);
expect(parsed.schemaConfig?.listSheets[0]?.keyColumn).toBe("会议编号");
});
});
+152 -3
View File
@@ -56,6 +56,52 @@ describe("sealTools", () => {
expect(tool).toBeDefined();
});
test("includes the delegation management tools", () => {
const listTool = sealTools.find((item) => item.name === "seal_delegation_list");
const createTool = sealTools.find((item) => item.name === "seal_delegation_create");
const revokeTool = sealTools.find((item) => item.name === "seal_delegation_revoke");
expect(listTool).toBeDefined();
expect(createTool).toBeDefined();
expect(revokeTool).toBeDefined();
});
test("includes user management tools", () => {
const createTool = sealTools.find((item) => item.name === "seal_user_create");
const resetTool = sealTools.find((item) => item.name === "seal_user_reset_password");
const getTool = sealTools.find((item) => item.name === "seal_user_get");
const searchTool = sealTools.find((item) => item.name === "seal_user_search");
const deleteTool = sealTools.find((item) => item.name === "seal_user_delete");
const activateTool = sealTools.find((item) => item.name === "seal_user_activate");
const userDelegationTool = sealTools.find((item) => item.name === "seal_user_delegation_create");
expect(createTool).toBeDefined();
expect(resetTool).toBeDefined();
expect(getTool).toBeDefined();
expect(searchTool).toBeDefined();
expect(deleteTool).toBeDefined();
expect(activateTool).toBeDefined();
expect(userDelegationTool).toBeDefined();
});
test("includes system configuration tools", () => {
expect(sealTools.find((item) => item.name === "seal_llm_config_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_llm_providers_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_permissions_available_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_permissions_configs_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_billing_status_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_billing_plans_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_billing_features_list")).toBeDefined();
});
test("includes Webhook management tools", () => {
expect(sealTools.find((item) => item.name === "seal_webhook_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_webhook_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_webhook_add")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_webhook_update")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_webhook_delete")).toBeDefined();
});
test("includes the approval search tool", () => {
const tool = sealTools.find((item) => item.name === "seal_approval_search");
expect(tool).toBeDefined();
@@ -88,7 +134,7 @@ describe("sealTools", () => {
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeRulesClient(),
{ fields: ["id", "status", "strictness", "scope"], limit: 1 },
{ fields: ["id", "code", "status", "strictness", "scope"], limit: 1 },
fakeContext()
) as { count: number; rules: Array<Record<string, unknown>> };
@@ -96,6 +142,7 @@ describe("sealTools", () => {
expect(result.rules).toEqual([
{
id: "rule-1",
code: 29,
status: "active",
strictness: "MUST_FOLLOW",
scope: "travel"
@@ -104,6 +151,52 @@ describe("sealTools", () => {
expect(result.rules[0]).not.toHaveProperty("description");
});
test("approval rules clear can dry run without deleting", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_rules_clear");
expect(tool).toBeDefined();
const client = fakeClearRulesClient();
const handler = tool!.handler as ToolHandler;
const result = await handler(client, { dryRun: true }, fakeContext()) as {
dryRun: boolean;
beforeCount: number;
deleted: number;
afterCount: number;
};
expect(result).toMatchObject({
dryRun: true,
beforeCount: 2,
deleted: 0,
afterCount: 2
});
expect(await countFakeRules(client)).toBe(2);
});
test("approval rules clear deletes all draft rules", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_rules_clear");
expect(tool).toBeDefined();
const client = fakeClearRulesClient();
const handler = tool!.handler as ToolHandler;
const result = await handler(client, {}, fakeContext()) as {
dryRun: boolean;
beforeCount: number;
deleted: number;
afterCount: number;
failed: unknown[];
};
expect(result).toMatchObject({
dryRun: false,
beforeCount: 2,
deleted: 2,
afterCount: 0,
failed: []
});
expect(await countFakeRules(client)).toBe(0);
});
test("includes approval run Langfuse bridge tools", () => {
expect(sealTools.find((item) => item.name === "seal_approval_runs_search")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_approval_runs_summary")).toBeDefined();
@@ -528,12 +621,12 @@ describe("sealTools", () => {
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeRulesClient(),
{ versionNumber: 16, code: "#0002" },
{ versionNumber: 16, code: "#0044" },
fakeContext()
) as { ruleCode?: string; description?: string; versionNumber?: number };
expect(result).toMatchObject({
ruleCode: "#0002",
ruleCode: "#0044",
description: "Second published rule",
versionNumber: 16
});
@@ -670,11 +763,13 @@ function fakeRulesClient(): KyInstance {
publishedByName: "Tester",
rules: [
{
code: "rule-29",
description: "First published rule",
scope: "travel",
strictness: "MUST_FOLLOW"
},
{
code: "rule-44",
description: "Second published rule",
scope: "meal",
strictness: "SHOULD_FOLLOW"
@@ -688,6 +783,7 @@ function fakeRulesClient(): KyInstance {
{
id: "rule-1",
tenantId: "tenant-1",
code: 29,
description: "Must include full invoice detail",
scope: "travel",
strictness: "MUST_FOLLOW",
@@ -698,6 +794,7 @@ function fakeRulesClient(): KyInstance {
{
id: "rule-2",
tenantId: "tenant-1",
code: 44,
description: "Prefer matching attendee names",
scope: "meal",
strictness: "SHOULD_FOLLOW",
@@ -712,6 +809,58 @@ function fakeRulesClient(): KyInstance {
} as unknown as KyInstance;
}
function fakeClearRulesClient(): KyInstance {
const rules = [
{
id: "rule-1",
tenantId: "tenant-1",
code: 29,
description: "Must include full invoice detail",
scope: "travel",
strictness: "MUST_FOLLOW",
status: "active"
},
{
id: "rule-2",
tenantId: "tenant-1",
code: 44,
description: "Prefer matching attendee names",
scope: "meal",
strictness: "SHOULD_FOLLOW",
status: "draft"
}
];
return {
get: () => ({
json: async () => ({
data: {
hasPendingDeletes: false,
rules: [...rules]
}
})
}),
delete: (url: string) => {
const ruleId = url.split("/").pop();
const index = rules.findIndex((rule) => rule.id === ruleId);
if (index >= 0) rules.splice(index, 1);
return Promise.resolve({});
},
post: () => Promise.resolve({
ok: true,
status: 200,
json: async () => ({ activeRules: rules.length, pendingDeleteRules: 0, nextCode: 1 })
})
} as unknown as KyInstance;
}
async function countFakeRules(client: KyInstance): Promise<number> {
const response = await client.get("api/v1/rules").json() as {
data: { rules: unknown[] };
};
return response.data.rules.length;
}
function fakeContext(): { corp: CorpConfig } {
return {
corp: {
+661 -5
View File
@@ -1,10 +1,12 @@
import { z } from "zod";
import { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import * as api from "./api.js";
import { getHoseEnterpriseUrl } from "../../core/auth/hose.js";
import { defaultSealUrl, getHoseEnterpriseUrl } from "../../core/auth/hose.js";
import { CorpConfig } from "../../core/config/types.js";
import { createSealClientForToken } from "../../core/http/factory.js";
import { searchApprovalContent } from "./search.js";
import type { ApprovalRule, ApprovalRun, RuleSetVersion } from "./types.js";
import type { ApprovalRule, ApprovalRun, RuleSetVersion, SimulationBatch, WebhookIntegration, WebhookMode } from "./types.js";
type ToolContext = {
corp: CorpConfig;
@@ -30,6 +32,150 @@ export const sealTools = [
parameters: z.object({}),
handler: async (client: KyInstance) => api.getSession(client)
},
{
name: "seal_delegation_list",
description: "查询当前 Seal 租户下的授权链接 (Delegation) 列表",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listDelegations(client)
},
{
name: "seal_delegation_create",
description: "创建新的 Seal 授权链接 (Delegation)",
parameters: z.object({
note: z.string().optional().describe("授权链接的备注或说明信息")
}),
handler: async (client: KyInstance, params: { note?: string }) =>
api.createDelegation(client, params)
},
{
name: "seal_delegation_revoke",
description: "撤销/废除指定的 Seal 授权链接 (Delegation)",
parameters: z.object({
tokenId: z.string().describe("授权链接 ID (delegation record ID)")
}),
handler: async (client: KyInstance, params: { tokenId: string }) =>
api.revokeDelegation(client, params.tokenId)
},
{
name: "seal_user_create",
description: "创建本地 Seal 用户,生成并返回初始随机密码",
parameters: z.object({
name: z.string().describe("用户姓名"),
phone: z.string().describe("手机号码 (例如 13300001111 或 +8613300001111)"),
permissions: z.array(z.string()).optional().describe("权限列表,默认为 []"),
departmentIds: z.array(z.string()).optional().describe("关联部门 ID 数组")
}),
handler: async (
client: KyInstance,
params: { name: string; phone: string; permissions?: string[]; departmentIds?: string[] }
) => api.createLocalUser(client, params)
},
{
name: "seal_user_reset_password",
description: "重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.resetUserPassword(client, params.userId)
},
{
name: "seal_user_get",
description: "获取指定 Seal 用户的详细信息",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.getUserDetail(client, params.userId)
},
{
name: "seal_user_search",
description: "按姓名、手机号或邮箱搜索 Seal 成员用户列表",
parameters: z.object({
keyword: z.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")
}),
handler: async (client: KyInstance, params: { keyword?: string }) =>
api.searchUsers(client, params.keyword ?? "")
},
{
name: "seal_user_delete",
description: "删除指定 Seal 本地用户",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.deleteLocalUser(client, params.userId)
},
{
name: "seal_user_activate",
description: "启用/激活已离职的 Seal 用户账号",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.activateLocalUser(client, params.userId)
},
{
name: "seal_user_delegation_create",
description: "为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录并生成其专属授权链接 (Delegation)",
parameters: z.object({
userIdOrPhone: z.string().describe("目标用户 ID、手机号或姓名"),
note: z.string().optional().describe("授权链接备注信息")
}),
handler: async (
client: KyInstance,
params: { userIdOrPhone: string; note?: string },
context: ToolContext
) =>
api.createDelegationForUser(
client,
params,
(token) => createSealClientForToken(context.corp, token),
context.corp
)
},
{
name: "seal_llm_config_get",
description: "查询当前 Seal 租户的大模型 (LLM) 配置",
parameters: z.object({}),
handler: async (client: KyInstance) => api.getLlmConfig(client)
},
{
name: "seal_llm_providers_list",
description: "查询支持的大模型 (LLM) 供应商与配置属性字段",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listLlmProviders(client)
},
{
name: "seal_permissions_available_list",
description: "查询系统可选权限清单(如超级管理员、智能审核管理、数据管理等)",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listAvailablePermissions(client)
},
{
name: "seal_permissions_configs_list",
description: "查询当前租户已绑定的权限配置",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listPermissionConfigs(client)
},
{
name: "seal_billing_status_get",
description: "查询当前 Seal 租户的订阅状态与各功能额度(AI审批、审核规则、知识文档等)",
parameters: z.object({}),
handler: async (client: KyInstance) => api.getBillingStatus(client)
},
{
name: "seal_billing_plans_list",
description: "查询系统支持的订阅套餐列表",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listBillingPlans(client)
},
{
name: "seal_billing_features_list",
description: "查询系统支持的功能特性定义列表",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listBillingFeatures(client)
},
{
name: "seal_approval_rules_list",
description: "列出 Seal 当前草稿审批规则;支持 countOnly、fields、limit 以避免返回规则正文",
@@ -37,6 +183,7 @@ export const sealTools = [
countOnly: z.boolean().optional().describe("只返回规则数量,不返回规则列表"),
fields: z.array(z.enum([
"id",
"code",
"tenantId",
"status",
"strictness",
@@ -61,6 +208,74 @@ export const sealTools = [
return projectApprovalRules(data, params);
}
},
{
name: "seal_approval_rules_clear",
description: "清空 Seal 当前草稿审批规则;用于测试环境导入规则前重置草稿规则集",
parameters: z.object({
dryRun: z.boolean().optional().describe("只预览将删除的规则数量,不执行删除"),
recode: z.boolean().optional().describe("删除后尝试重新编排规则编号;失败会作为 warning 返回")
}),
handler: async (
client: KyInstance,
params: { dryRun?: boolean; recode?: boolean },
context: ToolContext
) => {
const before = await api.listApprovalRules(client);
if (params.dryRun) {
return {
corpId: context.corp.id,
corpName: context.corp.name,
dryRun: true,
beforeCount: before.rules.length,
deleted: 0,
afterCount: before.rules.length,
hasPendingDeletes: before.hasPendingDeletes
};
}
const failed: Array<{ ruleId: string; error: string }> = [];
let deleted = 0;
for (const rule of before.rules) {
try {
await api.deleteApprovalRule(client, rule.id);
deleted += 1;
} catch (error) {
failed.push({
ruleId: rule.id,
error: error instanceof Error ? error.message : String(error)
});
}
}
const warnings: string[] = [];
let recode: unknown;
if (deleted > 0 && params.recode !== false) {
recode = await api.recodeApprovalRules(client);
if (
recode &&
typeof recode === "object" &&
"ok" in recode &&
recode.ok !== true
) {
warnings.push("batch-recode did not complete; current rules were still deleted");
}
}
const after = await api.listApprovalRules(client);
return {
corpId: context.corp.id,
corpName: context.corp.name,
dryRun: false,
beforeCount: before.rules.length,
deleted,
failed,
afterCount: after.rules.length,
hasPendingDeletes: after.hasPendingDeletes,
warnings,
recode
};
}
},
{
name: "seal_approval_rule_create",
description: "新建 Seal 草稿审批规则",
@@ -377,6 +592,156 @@ export const sealTools = [
context.corp.seal.endpoints.approvalStylePreferences
)
},
{
name: "seal_webhook_list",
description: "列出当前 Seal 租户的 Webhook 集成,可按 ID、名称或 URL 查找",
parameters: z.object({
query: z.string().optional().describe("按集成 ID、名称或 URL 做本地包含匹配"),
includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")
}),
handler: async (
client: KyInstance,
params: { query?: string; includeSecret?: boolean },
context: ToolContext
) => {
const integrations = api.filterWebhookIntegrations(
await api.listWebhookIntegrations(
client,
context.corp.seal.endpoints.approvalStylePreferences
),
params.query
);
return {
count: integrations.length,
integrations: integrations.map((integration) => presentWebhookIntegration(integration, params.includeSecret === true))
};
}
},
{
name: "seal_webhook_get",
description: "按 Webhook 集成 ID 或名称精确查找一条集成",
parameters: z.object({
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")
}),
handler: async (
client: KyInstance,
params: { selector: string; includeSecret?: boolean },
context: ToolContext
) => {
const integration = api.findWebhookIntegration(
await api.listWebhookIntegrations(
client,
context.corp.seal.endpoints.approvalStylePreferences
),
params.selector
);
return presentWebhookIntegration(integration, params.includeSecret === true);
}
},
{
name: "seal_webhook_add",
description: "新增 Webhook 集成并通过 AI 审批配置保存接口持久化",
parameters: z.object({
name: z.string().min(1).describe("集成名称"),
mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(),
outgoingResultWebhook: z.string().url().describe("Seal 完成 AI 审核后回调的外部地址"),
autoApprovalRate: z.number().int().min(0).max(100).optional(),
secret: z.string().min(1).optional().describe("可选;不传则生成 32 位十六进制 secret")
}),
handler: async (
client: KyInstance,
params: {
name: string;
mode?: WebhookMode;
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
},
context: ToolContext
) => {
const baseUrl = getConfiguredSealBaseUrl(context.corp);
const integration = await api.addWebhookIntegration(
client,
baseUrl,
params,
context.corp.seal.endpoints.approvalStylePreferences
);
return {
saved: true,
integration: presentWebhookIntegration(integration, true)
};
}
},
{
name: "seal_webhook_update",
description: "更新现有 Webhook 集成并通过 AI 审批配置保存接口持久化",
parameters: z.object({
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
name: z.string().min(1).optional(),
mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(),
outgoingResultWebhook: z.string().url().optional(),
autoApprovalRate: z.number().int().min(0).max(100).optional(),
secret: z.string().min(1).optional(),
rotateSecret: z.boolean().optional().describe("生成新 secret;与 secret 二选一")
}),
handler: async (
client: KyInstance,
params: {
selector: string;
name?: string;
mode?: WebhookMode;
outgoingResultWebhook?: string;
autoApprovalRate?: number;
secret?: string;
rotateSecret?: boolean;
},
context: ToolContext
) => {
if (params.secret !== undefined && params.rotateSecret) {
throw new Error("Webhook secret and rotateSecret cannot be used together");
}
const integration = await api.updateWebhookIntegration(
client,
params.selector,
params,
context.corp.seal.endpoints.approvalStylePreferences
);
return {
saved: true,
integration: presentWebhookIntegration(
integration,
params.secret !== undefined || params.rotateSecret === true
)
};
}
},
{
name: "seal_webhook_delete",
description: "删除指定 Webhook 集成并通过 AI 审批配置保存接口持久化",
parameters: z.object({
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
confirm: z.boolean().describe("必须明确传 true 才执行删除")
}),
handler: async (
client: KyInstance,
params: { selector: string; confirm: boolean },
context: ToolContext
) => {
if (!params.confirm) {
throw new Error("Refusing to delete Webhook integration without confirm=true");
}
const integration = await api.deleteWebhookIntegration(
client,
params.selector,
context.corp.seal.endpoints.approvalStylePreferences
);
return {
deleted: true,
integration: presentWebhookIntegration(integration, false)
};
}
},
{
name: "seal_approval_runs_search",
description: "查询 Seal 审批/审核运行记录总表,并整理合思单据到 Langfuse trace/session 的桥接字段",
@@ -703,6 +1068,172 @@ export const sealTools = [
};
}
},
{
name: "seal_simulation_batch_create",
description: "创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",
parameters: z.object({
mode: z.enum(["hosecloud", "material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),
flowIds: z.array(z.string()).max(100).optional().describe("合思模式: 单据流水号列表"),
rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),
thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),
skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"),
skipExpenseExtraction: z.boolean().optional().describe("跳过费用提取, 默认 true"),
disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"),
signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),
packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),
templateId: z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),
schemaConfig: z.record(z.string(), z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),
rawParams: z.record(z.string(), z.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")
}),
handler: async (
client: KyInstance,
params: {
mode?: "hosecloud" | "material_pack";
flowIds?: string[];
rejectNodeName?: string | null;
thinkingDepthOverride?: "default" | "medium" | "high";
skipInvoiceGeneration?: boolean;
skipExpenseExtraction?: boolean;
disableAttachmentCache?: boolean;
signKey?: string;
packageIds?: string[];
templateId?: string;
schemaConfig?: Record<string, unknown>;
rawParams?: Record<string, unknown>;
}
) => {
const mode = params.mode ?? "hosecloud";
let signKey = params.signKey;
if (mode === "hosecloud" && !signKey) {
const integrations = await api.listSimulationHosecloudIntegrations(client);
signKey = integrations.find((item) => item.signKey)?.signKey;
if (!signKey) {
throw new Error("未找到合思集成 signKey, 请通过 signKey 参数提供");
}
}
const payload = buildSimulationBatchParams({
mode,
flowIds: params.flowIds,
rejectNodeName: params.rejectNodeName,
thinkingDepthOverride: params.thinkingDepthOverride,
skipInvoiceGeneration: params.skipInvoiceGeneration,
skipExpenseExtraction: params.skipExpenseExtraction,
disableAttachmentCache: params.disableAttachmentCache,
signKey,
packageIds: params.packageIds,
templateId: params.templateId,
schemaConfig: params.schemaConfig,
rawParams: params.rawParams
});
const result = mode === "material_pack"
? await api.createMaterialPackBatch(client, payload)
: await api.createSimulationBatch(client, payload);
return {
...result,
created: true,
next: {
getBatch: "seal-home simulation get <batchId>",
getRecords: "seal-home simulation batch-records <batchId>",
listBatches: "seal-home simulation list"
}
};
}
},
{
name: "seal_simulation_batches_list",
description: "列出 Seal 模拟测试批次摘要(含状态、统计计数与展示摘要)",
parameters: z.object({
limit: z.number().int().positive().max(100).optional().describe("最多返回批次数量, 默认 50")
}),
handler: async (client: KyInstance, params: { limit?: number }) => {
const batches = await api.listSimulationBatches(client, { limit: params.limit ?? 50 });
return {
count: batches.length,
batches: batches.map(summarizeSimulationBatch),
next: {
getBatch: "seal-home simulation get <batchId>",
getRecords: "seal-home simulation batch-records <batchId>"
}
};
}
},
{
name: "seal_simulation_batch_get",
description: "获取某一次 Seal 模拟测试批次的详情,包含服务端回显的创建参数、展示摘要和任务统计",
parameters: z.object({
batchId: z.string().describe("simulation batch ID")
}),
handler: async (client: KyInstance, params: { batchId: string }) => {
const batch = await api.getSimulationBatch(client, params.batchId);
return {
batch,
next: {
getRecords: "seal-home simulation batch-records <batchId>"
}
};
}
},
{
name: "seal_simulation_templates_get",
description: "列出 Seal 模拟测试模板(我的模板,保存常用配置快速复用)",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const templates = await api.listSimulationTemplates(client);
return {
count: templates.length,
templates: templates.map((template) => ({
id: template.id,
name: template.name,
description: template.description,
approvalSystem: template.approvalSystem,
hosecloudConfig: template.hosecloudConfig,
updatedAt: template.updatedAt
})),
next: {
createBatch: "seal-home simulation create --mode hosecloud --flow-ids ..."
}
};
}
},
{
name: "seal_simulation_integrations_get",
description: "查询模拟测试可用的来源集成状态与合思集成选项(signKey 等)",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const [status, hosecloudIntegrations] = await Promise.all([
api.getSimulationIntegrationStatus(client),
api.listSimulationHosecloudIntegrations(client)
]);
return { status, hosecloudIntegrations };
}
},
{
name: "seal_simulation_material_package_upload",
description: "上传材料包 ZIP 到 Seal 模拟测试;服务端解析 Excel/AI 推断配置并返回材料包 id 与 schemaConfig(字段映射确认后用于创建模拟批次)",
parameters: z.object({
filePath: z.string().describe("材料包 ZIP 文件路径(含 信息表.xlsx 与附件)")
}),
handler: async (client: KyInstance, params: { filePath?: string }) => {
if (!params.filePath) {
throw new Error("filePath is required");
}
const fileBuffer = readFileSync(params.filePath);
const fileName = params.filePath.split(/[\\/]/).pop() ?? "material-pack.zip";
const materialPackage = await api.uploadMaterialPackage(client, {
fileName,
fileBuffer
});
return {
materialPackage,
next: {
createBatch: `seal-home simulation create --mode material_pack --package-ids ${materialPackage.id} --schema-config schema.json`
}
};
}
},
{
name: "seal_approval_run_langfuse_bridge_get",
description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",
@@ -764,6 +1295,7 @@ const mcpDirectToolNames = [
const sealActionNames = [
"seal_session_get",
"seal_approval_rules_list",
"seal_approval_rules_clear",
"seal_approval_rule_create",
"seal_approval_rule_update",
"seal_approval_rule_delete",
@@ -777,6 +1309,11 @@ const sealActionNames = [
"seal_approval_document_update",
"seal_approval_style_preferences_get",
"seal_approval_style_preferences_update",
"seal_webhook_list",
"seal_webhook_get",
"seal_webhook_add",
"seal_webhook_update",
"seal_webhook_delete",
"seal_approval_runs_summary",
"seal_approval_run_get",
"seal_approval_run_cited_rules_get",
@@ -786,12 +1323,19 @@ const sealActionNames = [
"seal_approval_run_url_get",
"seal_approval_run_pick",
"seal_simulation_batch_records_get",
"seal_simulation_batch_create",
"seal_simulation_batches_list",
"seal_simulation_batch_get",
"seal_simulation_templates_get",
"seal_simulation_integrations_get",
"seal_simulation_material_package_upload",
"seal_approval_run_langfuse_bridge_get"
] as const;
const sealActionAliases: Record<string, (typeof sealActionNames)[number]> = {
"session.get": "seal_session_get",
"rule.list": "seal_approval_rules_list",
"rule.clear": "seal_approval_rules_clear",
"rule.create": "seal_approval_rule_create",
"rule.update": "seal_approval_rule_update",
"rule.delete": "seal_approval_rule_delete",
@@ -805,6 +1349,11 @@ const sealActionAliases: Record<string, (typeof sealActionNames)[number]> = {
"doc.update": "seal_approval_document_update",
"style.get": "seal_approval_style_preferences_get",
"style.update": "seal_approval_style_preferences_update",
"webhook.list": "seal_webhook_list",
"webhook.get": "seal_webhook_get",
"webhook.add": "seal_webhook_add",
"webhook.update": "seal_webhook_update",
"webhook.delete": "seal_webhook_delete",
"runs.summary": "seal_approval_runs_summary",
"runs.get": "seal_approval_run_get",
"runs.citedRules": "seal_approval_run_cited_rules_get",
@@ -814,6 +1363,12 @@ const sealActionAliases: Record<string, (typeof sealActionNames)[number]> = {
"runs.url": "seal_approval_run_url_get",
"runs.pick": "seal_approval_run_pick",
"batch.records.get": "seal_simulation_batch_records_get",
"batch.create": "seal_simulation_batch_create",
"batch.list": "seal_simulation_batches_list",
"batch.get": "seal_simulation_batch_get",
"batch.templates.list": "seal_simulation_templates_get",
"batch.integrations.get": "seal_simulation_integrations_get",
"batch.materialPackageUpload": "seal_simulation_material_package_upload",
"langfuse.bridge.get": "seal_approval_run_langfuse_bridge_get"
};
@@ -826,9 +1381,9 @@ export const sealMcpTools: SealToolDefinition[] = [
},
{
name: "seal_action",
description: "Seal 低频管理操作统一入口。传 action=help 查看可用动作;支持 rule/doc/style/runs/batch/langfuse 等管理与诊断操作。",
description: "Seal 低频管理操作统一入口。传 action=help 查看可用动作;支持 rule/doc/style/webhook/runs/batch/langfuse 等管理与诊断操作。",
parameters: z.object({
action: z.string().describe("动作名,如 help、rule.create、doc.update、runs.summary、langfuse.bridge.get;也兼容旧 tool 名"),
action: z.string().describe("动作名,如 help、rule.create、doc.update、webhook.list、runs.summary、langfuse.bridge.get;也兼容旧 tool 名"),
payload: z.record(z.string(), z.unknown()).optional().describe("动作参数对象")
}),
handler: async (
@@ -888,7 +1443,7 @@ function sealActionHelp(topic: unknown) {
return {
usage: "seal_action({ action, payload })",
topics: ["session", "rule", "doc", "style", "runs", "batch", "langfuse"],
topics: ["session", "rule", "doc", "style", "webhook", "runs", "batch", "langfuse"],
actions
};
}
@@ -903,6 +1458,21 @@ function isSealActionToolName(name: string): name is (typeof sealActionNames)[nu
return sealActionNames.includes(name as (typeof sealActionNames)[number]);
}
function presentWebhookIntegration(
integration: WebhookIntegration,
includeSecret: boolean
) {
return includeSecret
? integration
: { ...integration, secret: "<redacted>" };
}
function getConfiguredSealBaseUrl(corp: CorpConfig): string {
if (corp.seal.url) return corp.seal.url;
if (corp.source.type === "hose") return defaultSealUrl(corp, corp.source);
return corp.source.sealUrl;
}
type ApprovalRunSummary = {
id: string;
tenantId?: string;
@@ -972,6 +1542,92 @@ function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[]) {
return output;
}
export type SimulationBatchCreateInput = {
mode: "hosecloud" | "material_pack";
flowIds?: string[];
rejectNodeName?: string | null;
thinkingDepthOverride?: "default" | "medium" | "high";
skipInvoiceGeneration?: boolean;
skipExpenseExtraction?: boolean;
disableAttachmentCache?: boolean;
signKey?: string;
packageIds?: string[];
templateId?: string;
schemaConfig?: Record<string, unknown>;
// 预留:其他取数模式(如合思时间范围)透传参数,覆盖构建结果
rawParams?: Record<string, unknown>;
};
export function buildSimulationBatchParams(input: SimulationBatchCreateInput): Record<string, unknown> {
// 请求体按前端真实载荷建模: approvalCode/nodeId/limit/startTime/endTime 由服务端
// 从 sourceSystem/flowIds 推导,回显 params 是归一化结果,不是请求体本身。
const params: Record<string, unknown> = {
skipInvoiceGeneration: input.skipInvoiceGeneration ?? true,
skipExpenseExtraction: input.skipExpenseExtraction ?? true,
thinkingDepthOverride: input.thinkingDepthOverride ?? "default"
};
if (input.mode === "hosecloud") {
if (!input.flowIds?.length) {
throw new Error("hosecloud 模式需要提供 flowIds(单号列表)");
}
Object.assign(params, {
dataCollectionMode: "2",
rejectNodeName: input.rejectNodeName ?? null,
skipInvoiceGeneration: input.skipInvoiceGeneration ?? true,
skipExpenseExtraction: input.skipExpenseExtraction ?? true,
disableAttachmentCache: input.disableAttachmentCache ?? false,
thinkingDepthOverride: input.thinkingDepthOverride ?? "default",
sourceSystem: "hosecloud",
flowIds: input.flowIds
});
if (input.signKey) params.signKey = input.signKey;
} else {
if (!input.packageIds?.length) {
throw new Error("material_pack 模式需要提供 packageIds(材料包 id)");
}
const templateId = input.templateId ?? (input.schemaConfig as { id?: string } | undefined)?.id;
if (!templateId) {
throw new Error("material_pack 模式需要提供 templateId(或 schemaConfig.id)");
}
// 材料包模式走独立端点 /api/v1/simulation/create-material-pack-batch:
// 请求直接携带 approvalCode/nodeId/runMode, 不带 sourceSystem/时间范围等字段。
Object.assign(params, {
templateId,
packageIds: input.packageIds,
approvalCode: "material_pack",
nodeId: "material_pack",
runMode: "import_and_simulate",
skipInvoiceGeneration: input.skipInvoiceGeneration ?? true,
skipExpenseExtraction: input.skipExpenseExtraction ?? true,
disableAttachmentCache: input.disableAttachmentCache ?? false,
thinkingDepthOverride: input.thinkingDepthOverride ?? "default"
});
if (input.schemaConfig !== undefined) params.schemaConfig = input.schemaConfig;
}
if (input.rawParams) Object.assign(params, input.rawParams);
return params;
}
function summarizeSimulationBatch(batch: SimulationBatch) {
return {
id: batch.id,
status: batch.status,
approvalCode: batch.approvalCode,
sourceSystem: batch.sourceSystem,
totalCount: batch.totalCount,
processedCount: batch.processedCount,
successCount: batch.successCount,
failedCount: batch.failedCount,
createdCount: batch.createdCount,
createFailedCount: batch.createFailedCount,
requestSummary: batch.requestSummary,
resultSummary: batch.resultSummary,
createdAt: batch.createdAt
};
}
function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
const sourceDocumentSN = record.sourceDocumentSN;
const humanResult = extractHumanResult(record);
+271 -3
View File
@@ -73,6 +73,7 @@ export const SealSessionDataSchema = z.object({
export const ApprovalRuleSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),
code: z.number().optional(),
description: z.string(),
scope: z.string(),
strictness: z.string(),
@@ -87,6 +88,7 @@ export const ApprovalRulesDataSchema = z.object({
});
export const PublishedRuleSnapshotSchema = z.object({
code: z.string().optional(),
description: z.string(),
scope: z.string(),
strictness: z.string()
@@ -96,9 +98,9 @@ export const RuleSetVersionSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),
versionNumber: z.number(),
versionName: z.string(),
publishedBy: z.string().optional(),
publishedByName: z.string().optional(),
versionName: z.string().nullable().optional(),
publishedBy: z.string().nullable().optional(),
publishedByName: z.string().nullable().optional(),
rules: z.array(PublishedRuleSnapshotSchema).default([]),
publishedAt: z.number().optional(),
createdAt: z.number().optional()
@@ -159,6 +161,29 @@ export const ApprovalIntegrationSchema = z.object({
completionMessageId: z.string().optional()
}).passthrough();
export const WebhookModeSchema = z.enum([
"assisted",
"semi_automatic",
"fully_automatic"
]);
export const WebhookEndpointSchema = z.object({
id: z.string(),
url: z.string().url()
}).passthrough();
export const WebhookIntegrationSchema = z.object({
type: z.literal("webhook"),
id: z.string(),
name: z.string(),
mode: WebhookModeSchema,
incomingDocumentWebhook: WebhookEndpointSchema,
outgoingResultWebhook: z.string().url(),
incomingManualResultWebhook: WebhookEndpointSchema,
secret: z.string().min(1),
autoApprovalRate: z.number().int().min(0).max(100).optional()
}).passthrough();
export const ApprovalStylePreferencesSchema = z.object({
id: z.string().optional(),
tenantId: z.string().optional(),
@@ -217,6 +242,223 @@ export const ApprovalRunListDataSchema = z.object({
pageSize: z.number().optional()
}).passthrough();
export const SealDelegationItemSchema = z.object({
id: z.string(),
expiresAt: z.number().nullable().optional(),
revokedAt: z.number().nullable().optional(),
createdAt: z.number().nullable().optional(),
lastUsedAt: z.number().nullable().optional(),
useCount: z.number().default(0),
note: z.string().nullable().optional(),
link: z.string()
}).passthrough();
export const SealDelegationCreateResultSchema = z.object({
id: z.string(),
token: z.string(),
link: z.string()
}).passthrough();
export const SealUserCreateResultSchema = z.object({
userId: z.string(),
password: z.string()
}).passthrough();
export const SealUserResetPasswordResultSchema = z.object({
password: z.string()
}).passthrough();
export const SealUserDetailSchema = z.object({
_id: z.string(),
tenantId: z.string().optional(),
name: z.string(),
mobile: z.string().optional(),
email: z.string().optional(),
departmentIds: z.array(z.string()).default([]),
status: z.string().optional(),
permissions: z.array(z.string()).default([]),
createdAt: z.string().optional(),
updatedAt: z.string().optional()
}).passthrough();
export const SealContactSearchResultSchema = z.object({
departments: z.array(z.record(z.string(), z.unknown())).default([]),
users: z.array(SealUserDetailSchema).default([])
}).passthrough();
export const LlmConfigSchema = z.object({
provider: z.string(),
config: z.record(z.string(), z.unknown()).default({})
}).passthrough();
export const LlmProviderSchema = z.object({
id: z.string(),
name: z.string(),
description: z.string().optional(),
available: z.boolean().default(true),
fields: z.array(z.record(z.string(), z.unknown())).default([])
}).passthrough();
export const AvailablePermissionsDataSchema = z.object({
permissions: z.array(z.object({
key: z.string(),
name: z.string(),
description: z.string().optional()
}).passthrough()).default([])
}).passthrough();
export const PermissionConfigsDataSchema = z.object({
configs: z.array(z.record(z.string(), z.unknown())).default([])
}).passthrough();
export const BillingStatusDataSchema = z.object({
subscriptions: z.array(z.record(z.string(), z.unknown())).default([]),
features: z.array(z.record(z.string(), z.unknown())).default([])
}).passthrough();
export const SimulationColumnSchema = z.object({
key: z.string(),
type: z.string(),
label: z.string(),
column: z.string(),
mask: z.string().optional()
}).passthrough();
export const SimulationListSheetSchema = z.object({
columns: z.array(SimulationColumnSchema).default([]),
fieldKey: z.string().optional(),
keyColumn: z.string().optional(),
sheetName: z.string().optional(),
fieldLabel: z.string().optional()
}).passthrough();
export const SimulationSchemaConfigSchema = z.object({
id: z.string().optional(),
listSheets: z.array(SimulationListSheetSchema).default([]),
mainColumns: z.array(SimulationColumnSchema).default([]),
workbookName: z.string().optional(),
mainKeyColumn: z.string().optional(),
mainSheetName: z.string().optional(),
titleColumn: z.string().optional(),
statusColumn: z.string().optional(),
applicationDateColumn: z.string().optional(),
updatedDateColumn: z.string().optional(),
attachmentFieldKey: z.string().optional(),
attachmentFieldLabel: z.string().optional()
}).passthrough();
export const SimulationBatchParamsSchema = z.object({
approvalCode: z.string(),
nodeId: z.string().optional(),
// 合思指定单号模式
flowIds: z.array(z.string()).max(100).optional(),
limit: z.number().int().positive().max(100).optional(),
dataCollectionMode: z.string().optional(),
signKey: z.string().optional(),
rejectNodeName: z.string().nullable().optional(),
skipInvoiceGeneration: z.boolean().optional(),
skipExpenseExtraction: z.boolean().optional(),
disableAttachmentCache: z.boolean().optional(),
thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional(),
// 预留:合思时间范围等其他取数模式
startTime: z.number().optional(),
endTime: z.number().optional(),
// 材料包导入模式
templateId: z.string().optional(),
packageIds: z.array(z.string()).optional(),
packageLabel: z.string().optional(),
runMode: z.string().optional(),
schemaConfig: SimulationSchemaConfigSchema.optional()
}).passthrough();
export const SimulationRequestSummarySchema = z.object({
mode: z.string().optional(),
conditions: z.array(z.object({
label: z.string(),
value: z.string()
}).passthrough()).default([])
}).passthrough();
export const SimulationResultSummarySchema = z.object({
kind: z.string().optional(),
stage: z.string().optional(),
code: z.string().optional(),
message: z.string().optional()
}).passthrough();
export const SimulationBatchSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),
approvalCode: z.string().optional(),
nodeId: z.string().optional(),
sourceSystem: z.string().optional(),
status: z.string().optional(),
totalCount: z.number().default(0),
processedCount: z.number().default(0),
successCount: z.number().default(0),
failedCount: z.number().default(0),
createdCount: z.number().default(0),
createFailedCount: z.number().default(0),
params: SimulationBatchParamsSchema.optional(),
requestSummary: SimulationRequestSummarySchema.nullable().optional(),
resultSummary: SimulationResultSummarySchema.nullable().optional(),
createdAt: z.union([z.string(), z.number()]).optional(),
updatedAt: z.union([z.string(), z.number()]).optional()
}).passthrough();
export const SimulationCreateResultSchema = z.object({
batchId: z.string()
}).passthrough();
export const SimulationHosecloudConfigSchema = z.object({
dataCollectionMode: z.string().optional(),
flowIds: z.array(z.string()).max(100).optional(),
rejectNodeName: z.string().nullable().optional(),
skipInvoiceGeneration: z.boolean().optional(),
skipExpenseExtraction: z.boolean().optional()
}).passthrough();
export const SimulationTemplateSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),
name: z.string().optional(),
description: z.string().optional(),
approvalSystem: z.string().optional(),
hosecloudConfig: SimulationHosecloudConfigSchema.optional(),
createdAt: z.union([z.string(), z.number()]).optional(),
updatedAt: z.union([z.string(), z.number()]).optional()
}).passthrough();
export const SimulationIntegrationStatusSchema = z.object({
hasFeishu: z.boolean().default(false),
hasHosecloud: z.boolean().default(false),
hasWeaver: z.boolean().default(false),
hasHelios: z.boolean().default(false),
hasMaycur: z.boolean().default(false),
hasMaycurStandard: z.boolean().default(false)
}).passthrough();
export const SimulationHosecloudIntegrationSchema = z.object({
signKey: z.string().optional(),
displayName: z.string().optional(),
corporationId: z.string().optional()
}).passthrough();
export const MaterialPackageSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),
name: z.string().optional(),
templateId: z.string().optional(),
originalFileName: z.string().optional(),
status: z.string().optional(),
documentCount: z.number().optional(),
attachmentCount: z.number().optional(),
uploadedBy: z.string().optional(),
schemaConfig: SimulationSchemaConfigSchema.nullable().optional(),
createdAt: z.union([z.string(), z.number()]).optional(),
updatedAt: z.union([z.string(), z.number()]).optional()
}).passthrough();
export type MeData = z.infer<typeof MeDataSchema>;
export type SealSessionData = z.infer<typeof SealSessionDataSchema>;
export type ApprovalRule = z.infer<typeof ApprovalRuleSchema>;
@@ -226,6 +468,32 @@ export type ApprovalDocument = z.infer<typeof ApprovalDocumentSchema>;
export type ApprovalDocumentListData = z.infer<typeof ApprovalDocumentListDataSchema>;
export type DecisionPreferences = z.infer<typeof DecisionPreferencesSchema>;
export type ApprovalIntegration = z.infer<typeof ApprovalIntegrationSchema>;
export type WebhookMode = z.infer<typeof WebhookModeSchema>;
export type WebhookEndpoint = z.infer<typeof WebhookEndpointSchema>;
export type WebhookIntegration = z.infer<typeof WebhookIntegrationSchema>;
export type ApprovalStylePreferences = z.infer<typeof ApprovalStylePreferencesSchema>;
export type ApprovalRun = z.infer<typeof ApprovalRunSchema>;
export type ApprovalRunListData = z.infer<typeof ApprovalRunListDataSchema>;
export type SealDelegationItem = z.infer<typeof SealDelegationItemSchema>;
export type SealDelegationCreateResult = z.infer<typeof SealDelegationCreateResultSchema>;
export type SealUserCreateResult = z.infer<typeof SealUserCreateResultSchema>;
export type SealUserResetPasswordResult = z.infer<typeof SealUserResetPasswordResultSchema>;
export type SealUserDetail = z.infer<typeof SealUserDetailSchema>;
export type SealContactSearchResult = z.infer<typeof SealContactSearchResultSchema>;
export type LlmConfig = z.infer<typeof LlmConfigSchema>;
export type LlmProvider = z.infer<typeof LlmProviderSchema>;
export type AvailablePermissionsData = z.infer<typeof AvailablePermissionsDataSchema>;
export type PermissionConfigsData = z.infer<typeof PermissionConfigsDataSchema>;
export type BillingStatusData = z.infer<typeof BillingStatusDataSchema>;
export type SimulationColumn = z.infer<typeof SimulationColumnSchema>;
export type SimulationListSheet = z.infer<typeof SimulationListSheetSchema>;
export type SimulationSchemaConfig = z.infer<typeof SimulationSchemaConfigSchema>;
export type SimulationBatchParams = z.infer<typeof SimulationBatchParamsSchema>;
export type SimulationBatch = z.infer<typeof SimulationBatchSchema>;
export type SimulationCreateResult = z.infer<typeof SimulationCreateResultSchema>;
export type SimulationTemplate = z.infer<typeof SimulationTemplateSchema>;
export type SimulationIntegrationStatus = z.infer<typeof SimulationIntegrationStatusSchema>;
export type SimulationHosecloudIntegration = z.infer<typeof SimulationHosecloudIntegrationSchema>;
export type MaterialPackage = z.infer<typeof MaterialPackageSchema>;
+21 -18
View File
@@ -1,22 +1,21 @@
import { getEnterprisesDirCandidates, loadCorpConfigs } from "./core/config/loader.js";
import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "./core/config/loader.js";
import { resolveCorpConfig } from "./core/config/manager.js";
import { createSealClient } from "./core/http/factory.js";
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
import { getApprovalContext } from "./domains/seal/api.js";
async function main() {
const corpId = Bun.argv[2];
export async function runProbe(options: { corpId?: string } = {}) {
const corps = loadCorpConfigs();
const corp = corpId
? corps.find((item) => item.id === corpId)
: corps[0];
if (!corp) {
throw new Error(
corpId
? `No enterprise config found for ${corpId}`
: `No enterprise config found. Add a config file under one of: ${getEnterprisesDirCandidates().join(", ")}`
);
}
const globalConfig = loadGlobalConfig();
const corp = resolveCorpConfig(
corps,
{
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId,
corpId: options.corpId
},
getEnterprisesDirCandidates()
);
console.log(`[probe] corp=${corp.id} source=${corp.source.type}`);
@@ -42,7 +41,11 @@ async function main() {
}, null, 2));
}
main().catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});
if (import.meta.main) {
const args = process.argv.slice(2);
const corpId = args[0] === "--corp" ? args[1] : args[0];
runProbe({ corpId }).catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});
}
+108
View File
@@ -0,0 +1,108 @@
import { describe, expect, test } from "bun:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import {
createServer,
resolveMcpEnabled,
SEAL_CLI_TOOL_NAME,
SEAL_MCP_ENABLED_ENV,
tokenizeCommand
} from "./server.js";
describe("seal-home MCP server", () => {
test("tokenizes quoted JSON without invoking a shell", () => {
expect(tokenizeCommand(
`seal-home tool seal_approval_search --json '{"keywords":["差旅 发票"]}' --corp corp-a`
)).toEqual([
"seal-home",
"tool",
"seal_approval_search",
"--json",
'{"keywords":["差旅 发票"]}',
"--corp",
"corp-a"
]);
});
test("defaults MCP tools to disabled and parses the plugin boolean setting", () => {
const original = process.env[SEAL_MCP_ENABLED_ENV];
delete process.env[SEAL_MCP_ENABLED_ENV];
try {
expect(resolveMcpEnabled()).toBe(false);
expect(resolveMcpEnabled("false")).toBe(false);
expect(resolveMcpEnabled("0")).toBe(false);
expect(resolveMcpEnabled("true")).toBe(true);
expect(resolveMcpEnabled("1")).toBe(true);
expect(resolveMcpEnabled("yes")).toBe(true);
} finally {
if (original === undefined) delete process.env[SEAL_MCP_ENABLED_ENV];
else process.env[SEAL_MCP_ENABLED_ENV] = original;
}
});
test("advertises one tool and executes version through the CLI runner", async () => {
const server = createServer({ enableCli: true });
const client = new Client({ name: "seal-home-test", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport)
]);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(1);
expect(listed.tools[0]?.name).toBe(SEAL_CLI_TOOL_NAME);
expect(listed.tools[0]?.inputSchema).toMatchObject({
type: "object",
required: ["command"]
});
const result = await client.callTool({
name: SEAL_CLI_TOOL_NAME,
arguments: { command: "seal-home version" }
});
const content = result.content as Array<{ type: "text"; text: string }>;
const text = content[0];
expect(result.isError).not.toBe(true);
expect(text?.type).toBe("text");
if (text?.type === "text") {
expect(JSON.parse(text.text)).toMatchObject({ name: "seal-home" });
}
const invalid = await client.callTool({
name: SEAL_CLI_TOOL_NAME,
arguments: { command: "not-a-command" }
});
expect(invalid.isError).toBe(true);
const invalidContent = invalid.content as Array<{ type: "text"; text: string }>;
const errorText = invalidContent[0];
expect(errorText?.type).toBe("text");
if (errorText?.type === "text") {
expect(errorText.text).toContain("Unknown command: not-a-command");
}
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
test("does not advertise tools when MCP is disabled", async () => {
const server = createServer({ enableCli: false });
const client = new Client({ name: "seal-home-disabled-test", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport)
]);
const listed = await client.listTools();
expect(listed.tools).toEqual([]);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
});
+172 -77
View File
@@ -1,21 +1,29 @@
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { getEnterprisesDirCandidates, loadCorpConfigs } from "./core/config/loader.js";
import { CorpContext } from "./core/config/manager.js";
import { createSealClient } from "./core/http/factory.js";
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
import { findSealMcpTool, findSealTool, sealMcpTools } from "./domains/seal/tools.js";
import { runCli } from "./cli/runner.js";
import { VERSION } from "./version.js";
async function main() {
const corps = loadCorpConfigs();
const corpContext = new CorpContext(corps);
const serverEntryFile = fileURLToPath(import.meta.url);
const pluginRoot = serverEntryFile.includes("/dist/mcp/") || serverEntryFile.includes("\\dist\\mcp\\")
? dirname(dirname(dirname(serverEntryFile)))
: dirname(dirname(serverEntryFile));
export const SEAL_CLI_TOOL_NAME = "seal_cli";
export const SEAL_MCP_ENABLED_ENV = "SEAL_HOME_MCP_ENABLED";
export function resolveMcpEnabled(value = process.env[SEAL_MCP_ENABLED_ENV]): boolean {
if (value === undefined) return false;
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
}
export function createServer(options: { enableCli?: boolean } = {}) {
const enableCli = options.enableCli ?? true;
const server = new Server(
{
name: "seal-home",
@@ -29,93 +37,180 @@ async function main() {
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: "seal_corp_switch",
description: "切换当前 Seal 企业",
inputSchema: {
type: "object",
properties: {
corpId: { type: "string", description: "企业配置 ID" }
},
required: ["corpId"]
}
},
...sealMcpTools.map((tool) => ({
name: tool.name,
description: tool.description,
inputSchema: z.toJSONSchema(tool.parameters)
}))
]
tools: enableCli
? [
{
name: SEAL_CLI_TOOL_NAME,
description: "Run seal-home CLI commands. See the seal-home skill for command reference.",
inputSchema: {
type: "object",
properties: {
command: {
type: "string",
description: "A seal-home CLI command, with or without the leading 'seal-home'."
}
},
required: ["command"],
additionalProperties: false
}
}
]
: []
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
corpContext.refresh(loadCorpConfigs());
if (name === "seal_corps_list") {
return textResult(corpContext.listCorps());
}
if (name === "seal_corp_switch") {
const { corpId } = args as { corpId: string };
const success = corpContext.switchCorp(corpId);
return textResult(
success ? { success: true, current: corpId } : { success: false, message: `Unknown corp: ${corpId}` },
!success
);
}
const currentCorp = corpContext.getCurrent();
if (!currentCorp) {
return textResult(
{
error:
"No enterprise config loaded. Add a non-example JSON file to an enterprises config directory.",
candidates: getEnterprisesDirCandidates()
},
true
);
if (enableCli) server.setRequestHandler(CallToolRequestSchema, async (request) => {
const args = request.params.arguments;
const command = args && typeof args.command === "string" ? args.command : undefined;
if (!command?.trim()) {
return cliResult({
stdout: "",
stderr: "seal_cli requires a non-empty command string",
isError: true,
exitCode: 1
});
}
try {
if (name === "seal_source_config") {
return textResult(await resolveLiveSealEnterpriseConfig(currentCorp));
const tokens = tokenizeCommand(command);
const cliArgs = normalizeCliArgs(tokens);
if (!cliArgs.length) {
throw new Error("seal_cli requires a non-empty command string");
}
const tool = findSealMcpTool(name) ?? findSealTool(name);
if (!tool) {
return textResult({ error: `Unknown tool: ${name}` }, true);
}
const client = await createSealClient(currentCorp);
const result = await tool.handler(client, args as never, { corp: currentCorp });
return textResult(result);
return cliResult(await runCli(cliArgs, {
appRoot: pluginRoot,
entryFile: serverEntryFile,
launcher: {
command: process.execPath,
args: [serverEntryFile, "--seal-home-cli"]
}
}));
} catch (error) {
return textResult(
{ error: error instanceof Error ? error.message : String(error) },
true
);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
isError: true,
exitCode: 1
});
}
});
await server.connect(new StdioServerTransport());
console.error("seal-home MCP server running on stdio");
return server;
}
function textResult(value: unknown, isError = false) {
export async function startServer() {
const enableCli = resolveMcpEnabled();
const server = createServer({ enableCli });
await server.connect(new StdioServerTransport());
console.error(
enableCli
? "seal-home MCP server running on stdio"
: "seal-home MCP server connected with seal_cli disabled by configuration"
);
}
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
let quote: "'" | '"' | undefined;
let escaped = false;
let tokenStarted = false;
for (const character of command) {
if (escaped) {
token += character;
escaped = false;
tokenStarted = true;
continue;
}
if (character === "\\" && quote !== "'") {
escaped = true;
tokenStarted = true;
continue;
}
if (quote) {
if (character === quote) {
quote = undefined;
} else {
token += character;
}
tokenStarted = true;
continue;
}
if (character === "'" || character === '"') {
quote = character;
tokenStarted = true;
continue;
}
if (/\s/.test(character)) {
if (tokenStarted) {
tokens.push(token);
token = "";
tokenStarted = false;
}
continue;
}
token += character;
tokenStarted = true;
}
if (escaped) throw new Error("Invalid command: trailing escape");
if (quote) throw new Error("Invalid command: unterminated quote");
if (tokenStarted) tokens.push(token);
return tokens;
}
function normalizeCliArgs(tokens: string[]): string[] {
const first = tokens[0];
if (!first) return [];
if (first === "seal-home" || first.endsWith("/seal-home")) return tokens.slice(1);
return tokens;
}
function cliResult(result: { stdout: string; stderr: string; isError: boolean; exitCode: number }) {
const text = result.isError ? result.stderr || result.stdout : result.stdout;
return {
content: [
{
type: "text" as const,
text: JSON.stringify(value, null, 2)
text
}
],
isError
isError: result.isError
};
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
async function runEmbeddedCli() {
const result = await runCli(process.argv.slice(3), {
appRoot: pluginRoot,
entryFile: serverEntryFile,
launcher: {
command: process.execPath,
args: [serverEntryFile, "--seal-home-cli"]
}
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
process.exitCode = result.exitCode;
}
const isMainModule = Boolean(
(import.meta as any).main ||
(!import.meta.url.includes("$bunfs") && process.argv[1] && resolve(process.argv[1]) === resolve(serverEntryFile))
);
if (isMainModule) {
if (process.argv[2] === "--seal-home-cli") {
await runEmbeddedCli();
} else {
startServer().catch((error) => {
console.error(error);
process.exitCode = 1;
});
}
}
View File
Whitespace-only changes.