Compare commits

...
14 Commits
Author SHA1 Message Date
yunyingk 69d2bc0147 Merge pull request #14 from yunyingk/codex/issue-13-assist-link
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
Add Hose assistance-link onboarding (#13)
2026-09-02 15:08:01 +08:00
gitea d6e9b505ea Reject incomplete tenant identity metadata (#13) 2026-09-02 15:02:54 +08:00
gitea ade7156c01 Release v0.9.8: Add assistance link onboarding (#13) 2026-09-02 14:55:08 +08:00
gitea 4ce206a2ce Add Hose assistance link onboarding (#13) 2026-09-02 14:33:37 +08:00
yunyingk 9f3975a6a5 Merge pull request #12 from yunyingk/codex/simplify-gitea-idempotency
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Avoid Gitea asset download checks
2026-09-01 15:25:51 +08:00
gitea 2a14849bfc Avoid Gitea asset download checks 2026-09-01 15:24:49 +08:00
yunyingk 2334d14595 Merge pull request #11 from yunyingk/codex/fix-gitea-asset-delete
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Fix Gitea release asset deletion path
2026-09-01 15:17:58 +08:00
gitea a72a9de08f Fix Gitea release asset deletion path 2026-09-01 15:16:41 +08:00
yunyingk f4f1e78b5f Merge pull request #10 from yunyingk/codex/harden-release-process
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Harden release publishing workflow
2026-09-01 15:13:05 +08:00
gitea 524a0b57dd Harden release publishing workflow 2026-09-01 15:08:49 +08:00
yunyingk 940a7514b1 Merge pull request #9 from yunyingk/codex/release-v0.9.7
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Release v0.9.7: Improve agent onboarding
2026-09-01 14:48:46 +08:00
gitea e1f7c76d19 Release v0.9.7: Improve agent onboarding
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-01 14:46:18 +08:00
yunyingk 6a4f49b766 Release v0.9.6: Add dynamic transfer speed and stall detection (#8)
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
* Release v0.9.6: Add dynamic transfer speed and stall detection to update downloader

* refactor(update): enforce 6s 300KB initial warmup gate and 10s stall resilience
2026-08-27 16:23:33 +08:00
gitea 26e3bc631d ci: ensure build:plugin step verifies build execution without cross-platform whitespace drift
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 16:16:00 +08:00
26 changed files with 1158 additions and 146 deletions

No files matched your search

+1 -2
View File
@@ -43,10 +43,9 @@ jobs:
bun run openapi:bundle
git diff --exit-code dist/openapi.json || (echo "::error::dist/openapi.json is out of sync with openapi/openapi.yaml. Run 'bun run openapi:bundle' and commit changes." && exit 1)
- name: Build MCP Plugin & Validate Sync
- name: Build MCP Plugin & Verify
run: |
bun run build:plugin
git diff --exit-code dist/mcp/server.js || (echo "::error::dist/mcp/server.js is out of sync. Run 'bun run build:plugin' and commit changes." && exit 1)
- name: Verify Binary Compilation
run: |
+126 -21
View File
@@ -100,32 +100,137 @@ jobs:
fi
if [ -z "$RELEASE_ID" ]; then
echo "::warning::Failed to create or find Gitea release ID. Proceeding anyway."
exit 0
echo "::error::Failed to create or find the Gitea release."
exit 1
fi
echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..."
upload_asset() {
local file="$1"
local filename
filename=$(basename "$file")
echo " [start] Uploading ${filename} to Gitea..."
RESP=$(curl -s -m 120 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
priority_files=(
"dist/bin/seal-home-darwin-arm64.tar.gz"
"dist/bin/seal-home-darwin-arm64"
"dist/bin/seal-home-darwin-x64.tar.gz"
"dist/bin/seal-home-darwin-x64"
)
remaining_files=(
"dist/bin/seal-home-linux-arm64.tar.gz"
"dist/bin/seal-home-linux-arm64"
"dist/bin/seal-home-linux-x64.tar.gz"
"dist/bin/seal-home-linux-x64"
"dist/bin/seal-home-windows-x64.zip"
"dist/bin/seal-home-windows-x64.exe"
"dist/bin/checksums.txt"
)
expected_files=("${priority_files[@]}" "${remaining_files[@]}")
for file in "${expected_files[@]}"; do
if [ ! -f "$file" ]; then
echo "::error::Expected release asset is missing locally: ${file}"
exit 1
fi
done
release_json() {
curl -fsS \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@${file}")
STATUS=$(echo "$RESP" | tail -n 1)
echo " [done] ${filename} -> ${STATUS}"
"${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"
}
pids=()
for file in dist/bin/seal-home-* dist/bin/checksums.txt; do
[ -f "$file" ] || continue
upload_asset "$file" &
pids+=($!)
delete_asset() {
local asset_id="$1"
curl -fsS -X DELETE \
-H "Authorization: token ${GITEA_TOKEN}" \
"${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets/${asset_id}" \
>/dev/null
}
upload_asset() {
local file="$1"
local filename file_size assets matching_id asset_id response_file http_code
filename=$(basename "$file")
file_size=$(wc -c < "$file" | tr -d ' ')
assets=$(release_json)
matching_id=$(echo "$assets" | jq -r --arg name "$filename" --argjson size "$file_size" \
'[.assets[] | select(.name == $name and .size == $size) | .id][0] // empty')
if [ -n "$matching_id" ]; then
echo " [keep] ${filename} already exists with the expected size"
while IFS= read -r asset_id; do
[ -n "$asset_id" ] || continue
if [ "$asset_id" != "$matching_id" ]; then
echo " [dedupe] removing duplicate ${filename} asset ${asset_id}"
delete_asset "$asset_id"
fi
done < <(echo "$assets" | jq -r --arg name "$filename" '.assets[] | select(.name == $name) | .id')
return
fi
while IFS= read -r asset_id; do
[ -n "$asset_id" ] || continue
echo " [replace] removing stale ${filename} asset ${asset_id}"
delete_asset "$asset_id"
done < <(echo "$assets" | jq -r --arg name "$filename" '.assets[] | select(.name == $name) | .id')
response_file=$(mktemp)
echo " [start] uploading ${filename} (${file_size} bytes)"
if ! http_code=$(curl -sS --fail-with-body \
--connect-timeout 10 \
--max-time 900 \
--retry 3 \
--retry-delay 5 \
--retry-all-errors \
--retry-max-time 2700 \
-o "$response_file" \
-w '%{http_code}' \
-X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@${file}"); then
echo "::error::Failed to upload ${filename} to Gitea."
sed -n '1,20p' "$response_file"
rm -f "$response_file"
return 1
fi
rm -f "$response_file"
if [ "$http_code" != "201" ]; then
echo "::error::Unexpected Gitea upload status for ${filename}: HTTP ${http_code}"
return 1
fi
echo " [done] ${filename} -> HTTP ${http_code}"
}
echo "==> Uploading macOS assets first (Apple Silicon archive has highest priority)..."
for file in "${priority_files[@]}"; do
upload_asset "$file"
done
# Wait for all parallel uploads to complete
for pid in "${pids[@]}"; do
wait "$pid" || true
echo "==> Uploading remaining assets with at most 2 concurrent transfers..."
for ((index=0; index<${#remaining_files[@]}; index+=2)); do
pids=()
for ((offset=0; offset<2 && index+offset<${#remaining_files[@]}; offset++)); do
upload_asset "${remaining_files[index+offset]}" &
pids+=("$!")
done
for pid in "${pids[@]}"; do
wait "$pid"
done
done
echo "✓ Successfully published release assets to Gitea!"
echo "==> Verifying the Gitea release asset manifest..."
final_release=$(release_json)
verification_failed=false
for file in "${expected_files[@]}"; do
filename=$(basename "$file")
file_size=$(wc -c < "$file" | tr -d ' ')
matching_count=$(echo "$final_release" | jq -r --arg name "$filename" --argjson size "$file_size" \
'[.assets[] | select(.name == $name and .size == $size)] | length')
total_count=$(echo "$final_release" | jq -r --arg name "$filename" \
'[.assets[] | select(.name == $name)] | length')
if [ "$matching_count" != "1" ] || [ "$total_count" != "1" ]; then
echo "::error::Gitea asset verification failed for ${filename}: matching=${matching_count}, total=${total_count}"
verification_failed=true
fi
done
if [ "$verification_failed" = "true" ]; then
exit 1
fi
echo "✓ Successfully published and verified all Gitea release assets!"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-home",
"version": "0.9.5",
"version": "0.9.8",
"description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+20 -7
View File
@@ -42,14 +42,28 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
- Run `bun run bump <new-version | patch | minor>` (automatically updates `package.json`, `.zcode-plugin/plugin.json`, `skills/seal-home/SKILL.md`, `openapi/openapi.yaml`, and bundles `dist/`).
- Update `CHANGELOG.md` with new features and fixes.
- Run `bun test && bun run check`.
2. **Tag & Release**:
- Create an annotated Git tag with a descriptive release summary:
2. **Protected-Branch Release**:
- Do not tag or push `master` directly. Create a release branch, commit the version bump, push it, open a PR to `master`, wait for the required CI check, and merge the PR first.
- After the PR is merged, fast-forward the local `master`, then synchronize `home/master` before creating the tag:
```bash
git commit -am "Release vX.Y.Z: ..."
git tag -a vX.Y.Z -m "🚀 Release summary text describing key changes"
git push origin master --tags && git push home master --tags
git switch -c codex/release-vX.Y.Z
git add <release-files>
git commit -m "Release vX.Y.Z: ..."
git push origin HEAD:refs/heads/codex/release-vX.Y.Z
gh pr create --base master --head codex/release-vX.Y.Z --title "Release vX.Y.Z: ..." --body "..."
gh pr checks <pr-number> --watch
gh pr merge <pr-number> --merge
git switch master
git pull --ff-only origin master
git push home master
```
- GitHub Actions will automatically extract the tag message, append commit notes via `--generate-notes`, cross-compile all 5 target binaries in ~50s, and publish the GitHub Release.
- Only after both `origin/master` and `home/master` contain the merged release should you create the annotated tag. Push the tag to `home` first, then to `origin`; pushing the GitHub tag last triggers the Release workflow after the Gitea tag and branch are ready:
```bash
git tag -a vX.Y.Z -m "🚀 Release summary text describing key changes"
git push home refs/tags/vX.Y.Z
git push origin refs/tags/vX.Y.Z
```
- GitHub Actions will automatically extract the tag message, append commit notes via `--generate-notes`, cross-compile all 5 target binaries, and publish GitHub and Gitea releases. Wait for the workflow, then verify that both releases point to the intended tag commit and contain every expected asset exactly once.
## Security & Configuration Tips
@@ -58,4 +72,3 @@ Never commit real enterprise credentials, Seal tokens, service logs, or local ge
## Agent-Specific Instructions
Do not create `.codex/skills`; Codex is compatible with `.agents/skills`, and this project treats `.agents/` as authoritative. At project scope, prefer `AGENT.md` instructions when present.
+26
View File
@@ -5,6 +5,32 @@ All notable changes to `seal-home` will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.9.8] - 2026-09-02
### Added
- **Hose Assistance-Link Onboarding**: Added `seal-home corps add-link <url>` to parse supported `thirdparty.html` links, exchange the temporary Hose token through Seal SSO, verify the tenant identity, and write a short-lived enterprise config.
- **Direct Delegation Link Generation**: Added `seal-home delegation create --from-link <url>` to generate a Seal delegation link without first persisting an enterprise config.
- **Credential Safety Checks**: Restricted incoming links to HTTPS Hose domains, redacted temporary credentials from CLI output, rejected tenant mismatches, and added focused parser, exchange, onboarding, and delegation tests.
## [0.9.7] - 2026-09-01
### Enhanced
- **Agent-first Enterprise Onboarding**: Added a dedicated first-run workflow that makes Agents discover configured enterprises before asking users for parameters, resolves human enterprise names to internal IDs, and avoids asking users for discoverable `corpId`, `staffId`, or tenant identifiers.
- **Identity and Credential Classification**: Clearly separated Hose/合思-sourced versus Seal-native tenant identity from the way access was obtained: standard Hose app credentials, incoming assistance links, or browser-copied cURL sessions.
- **Browser cURL Guidance and Secret Handling**: Added concrete F12/Network/Fetch-XHR capture instructions, read-only verification guidance, credential redaction rules, and explicit boundaries for raw cURL and assistance-link capabilities not yet supported by the CLI.
- **Simplified Hose Setup Routing**: Updated the standard Hose path to request only `appKey` and `appSecurity` initially, while automatically discovering the domain, enterprise, and administrator candidates.
---
## [0.9.6] - 2026-08-27
### Fixed & Enhanced
- **Smart Download Speed & Stall Monitor**: Added dynamic transfer speed monitoring with a 50 KB/s low-speed threshold and 5s stall detection in `seal-home update`, allowing fast downloads to complete without artificial timeouts while proactively abandoning crawling mirrors.
- **Deduplicated Progress Logging**: Eliminated duplicated stderr/console progress logging in binary downloads.
- **Curated Mirror List**: Pruned expired/broken CDN mirrors from the fallback candidate chain.
---
## [0.9.5] - 2026-08-27
### Enhanced & Optimized
+18 -1
View File
@@ -11,6 +11,8 @@ The first provider is Hose/合思: `key`, `password`, `corpId`, `staffId`, and a
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.
An incoming Hose/合思 `thirdparty.html` assistance link can be imported directly; the CLI exchanges its temporary token through Seal SSO, verifies the tenant, and stores a short-lived local Seal session.
## Quick Install (Standalone Binary)
No Node.js, Bun, or external runtime required. Run the one-line installer for macOS and Linux:
@@ -93,6 +95,22 @@ 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.
Import a Hose/合思 assistance link when you do not have OpenAPI app credentials:
```bash
seal-home corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home" [--name "企业名称"]
```
The command accepts HTTPS links from the supported Hose domains, verifies the Seal tenant with `/api/v1/auth/me`, and writes a `seal` source with `provider: "hosecloud"`. The incoming token is never printed, but the resulting session is temporary and must be renewed after it expires. Use `--overwrite` to replace an existing config explicitly.
To generate a Seal delegation link directly from the same incoming Hose link without saving a config:
```bash
seal-home delegation create --from-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home" --note "客户支持"
```
The link is treated as a credential and is not echoed by the CLI; only the generated delegation result is returned.
For custom config locations, set `SEAL_HOME_ENTERPRISES_DIR` to a directory containing non-example `*.json` enterprise config files.
Update an existing checkout:
@@ -347,4 +365,3 @@ bun run bump 0.8.5
- Cross-compiles standalone binaries for 5 target platforms (macOS Apple Silicon/Intel, Linux x86_64/ARM64, Windows x64) in under 60 seconds;
- Automatically extracts your Git tag annotation message and appends commit changelogs (`--generate-notes`);
- Simultaneously publishes release packages to **[GitHub Releases](https://github.com/yunyingk/seal-home/releases)** and **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-home/releases)** for global and mainland China high-speed downloads.
+221 -82
View File
@@ -1,82 +1,82 @@
import{createRequire as $j}from"node:module";var ij=Object.create;var{getPrototypeOf:nj,defineProperty:o$,getOwnPropertyNames:rj}=Object;var tj=Object.prototype.hasOwnProperty;function oj(i){return this[i]}var uj,lj,V0=(i,n,t)=>{var o=i!=null&&typeof i==="object";if(o){var r=n?uj??=new WeakMap:lj??=new WeakMap,u=r.get(i);if(u)return u}t=i!=null?ij(nj(i)):{};let l=n||!i||!i.__esModule?o$(t,"default",{value:i,enumerable:!0}):t;for(let e of rj(i))if(!tj.call(l,e))o$(l,e,{get:oj.bind(i,e),enumerable:!0});if(o)r.set(i,l);return l};var Q=(i,n)=>()=>(n||i((n={exports:{}}).exports,n),n.exports);var ej=(i)=>i;function vj(i,n){this[i]=ej.bind(null,n)}var Hn=(i,n)=>{for(var t in n)o$(i,t,{get:n[t],enumerable:!0,configurable:!0,set:vj.bind(n,t)})};var T0=$j(import.meta.url);var Ro=Q((w1)=>{Object.defineProperty(w1,"__esModule",{value:!0});w1.regexpCode=w1.getEsmExportName=w1.getProperty=w1.safeStringify=w1.stringify=w1.strConcat=w1.addCodeArg=w1.str=w1._=w1.nil=w1._Code=w1.Name=w1.IDENTIFIER=w1._CodeOrName=void 0;class Pe{}w1._CodeOrName=Pe;w1.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Wt extends Pe{constructor(i){super();if(!w1.IDENTIFIER.test(i))throw Error("CodeGen: name must be a valid identifier");this.str=i}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}w1.Name=Wt;class fn extends Pe{constructor(i){super();this._items=typeof i==="string"?[i]:i}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let i=this._items[0];return i===""||i==='""'}get str(){var i;return(i=this._str)!==null&&i!==void 0?i:this._str=this._items.reduce((n,t)=>`${n}${t}`,"")}get names(){var i;return(i=this._names)!==null&&i!==void 0?i:this._names=this._items.reduce((n,t)=>{if(t instanceof Wt)n[t.str]=(n[t.str]||0)+1;return n},{})}}w1._Code=fn;w1.nil=new fn("");function g1(i,...n){let t=[i[0]],o=0;while(o<n.length)S6(t,n[o]),t.push(i[++o]);return new fn(t)}w1._=g1;var c6=new fn("+");function b1(i,...n){let t=[mo(i[0])],o=0;while(o<n.length)t.push(c6),S6(t,n[o]),t.push(c6,mo(i[++o]));return Y8(t),new fn(t)}w1.str=b1;function S6(i,n){if(n instanceof fn)i.push(...n._items);else if(n instanceof Wt)i.push(n);else i.push(H8(n))}w1.addCodeArg=S6;function Y8(i){let n=1;while(n<i.length-1){if(i[n]===c6){let t=P8(i[n-1],i[n+1]);if(t!==void 0){i.splice(n-1,3,t);continue}i[n++]="+"}n++}}function P8(i,n){if(n==='""')return i;if(i==='""')return n;if(typeof i=="string"){if(n instanceof Wt||i[i.length-1]!=='"')return;if(typeof n!="string")return`${i.slice(0,-1)}${n}"`;if(n[0]==='"')return i.slice(0,-1)+n.slice(1);return}if(typeof n=="string"&&n[0]==='"'&&!(i instanceof Wt))return`"${i}${n.slice(1)}`;return}function Q8(i,n){return n.emptyStr()?i:i.emptyStr()?n:b1`${i}${n}`}w1.strConcat=Q8;function H8(i){return typeof i=="number"||typeof i=="boolean"||i===null?i:mo(Array.isArray(i)?i.join(","):i)}function F8(i){return new fn(mo(i))}w1.stringify=F8;function mo(i){return JSON.stringify(i).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}w1.safeStringify=mo;function K8(i){return typeof i=="string"&&w1.IDENTIFIER.test(i)?new fn(`.${i}`):g1`[${i}]`}w1.getProperty=K8;function B8(i){if(typeof i=="string"&&w1.IDENTIFIER.test(i))return new fn(`${i}`);throw Error(`CodeGen: invalid export name: ${i}, use explicit $id name mapping`)}w1.getEsmExportName=B8;function V8(i){return new fn(i.toString())}w1.regexpCode=V8});var L6=Q((c1)=>{Object.defineProperty(c1,"__esModule",{value:!0});c1.ValueScope=c1.ValueScopeName=c1.Scope=c1.varKinds=c1.UsedValueState=void 0;var xi=Ro();class D1 extends Error{constructor(i){super(`CodeGen: "code" for ${i} not defined`);this.value=i.value}}var He;(function(i){i[i.Started=0]="Started",i[i.Completed=1]="Completed"})(He||(c1.UsedValueState=He={}));c1.varKinds={const:new xi.Name("const"),let:new xi.Name("let"),var:new xi.Name("var")};class A6{constructor({prefixes:i,parent:n}={}){this._names={},this._prefixes=i,this._parent=n}toName(i){return i instanceof xi.Name?i:this.name(i)}name(i){return new xi.Name(this._newName(i))}_newName(i){let n=this._names[i]||this._nameGroup(i);return`${i}${n.index++}`}_nameGroup(i){var n,t;if(((t=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||t===void 0?void 0:t.has(i))||this._prefixes&&!this._prefixes.has(i))throw Error(`CodeGen: prefix "${i}" is not allowed in this scope`);return this._names[i]={prefix:i,index:0}}}c1.Scope=A6;class N6 extends xi.Name{constructor(i,n){super(n);this.prefix=i}setValue(i,{property:n,itemIndex:t}){this.value=i,this.scopePath=xi._`.${new xi.Name(n)}[${t}]`}}c1.ValueScopeName=N6;var R8=xi._`\n`;class U1 extends A6{constructor(i){super(i);this._values={},this._scope=i.scope,this.opts={...i,_n:i.lines?R8:xi.nil}}get(){return this._scope}name(i){return new N6(i,this._newName(i))}value(i,n){var t;if(n.ref===void 0)throw Error("CodeGen: ref must be passed in value");let o=this.toName(i),{prefix:r}=o,u=(t=n.key)!==null&&t!==void 0?t:n.ref,l=this._values[r];if(l){let I=l.get(u);if(I)return I}else l=this._values[r]=newLine truncated
`:""},this._extScope=i,this._scope=new Dn.Scope({parent:i}),this._nodes=[new j1]}toString(){return this._root.render(this.opts)}name(i){return this._scope.name(i)}scopeName(i){return this._extScope.name(i)}scopeValue(i,n){let t=this._extScope.value(i,n);return(this._values[t.prefix]||(this._values[t.prefix]=new Set)).add(t),t}getScopeValue(i,n){return this._extScope.getValue(i,n)}scopeRefs(i){return this._extScope.scopeRefs(i,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(i,n,t,o){let r=this._scope.toName(n);if(t!==void 0&&o)this._constants[r.str]=t;return this._leafNode(new O1(i,r,t)),r}const(i,n,t){return this._def(Dn.varKinds.const,i,n,t)}let(i,n,t){return this._def(Dn.varKinds.let,i,n,t)}var(i,n,t){return this._def(Dn.varKinds.var,i,n,t)}assign(i,n,t){return this._leafNode(new j6(i,n,t))}add(i,n){return this._leafNode(new A1(i,ai.operators.ADD,n))}code(i){if(typeof i=="function")i();else if(i!==x.nil)this._leafNode(new G1(i));return this}object(...i){let n=["{"];for(let[t,o]of i){if(n.length>1)n.push(",");if(n.push(t),t!==o||this.opts.es5)n.push(":"),(0,x.addCodeArg)(n,o)}return n.push("}"),new x._Code(n)}if(i,n,t){if(this._blockNode(new Tn(i)),n&&t)this.code(n).else().code(t).endIf();else if(n)this.code(n).endIf();else if(t)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(i){return this._elseNode(new Tn(i))}else(){return this._elseNode(new xo)}endIf(){return this._endBlockNode(Tn,xo)}_for(i,n){if(this._blockNode(i),n)this.code(n).endFor();return this}for(i,n){return this._for(new W1(i),n)}forRange(i,n,t,o,r=this.opts.es5?Dn.varKinds.var:Dn.varKinds.let){let u=this._scope.toName(i);return this._for(new y1(r,u,n,t),()=>o(u))}forOf(i,n,t,o=Dn.varKinds.const){let r=this._scope.toName(i);if(this.opts.es5){let u=n instanceof x.Name?n:this.var("_arr",n);return this.forRange("_i",0,x._`${u}.length`,(l)=>{this.var(r,x._`${u}[${l}]`),t(r)})}return this._for(new k6("of",o,r,n),()=>t(r))}forIn(i,n,t,o=this.opts.es5?Dn.varKinds.var:Dn.varKinds.const){if(this.opts.ownProperties)return this.forOf(i,x._`Object.keys(${n})`,t);let r=this._scope.toName(i);return this._for(new k6("in",o,r,n),()=>t(r))}endFor(){return this._endBlockNode(yt)}label(i){return this._leafNode(new N1(i))}break(i){return this._leafNode(new L1(i))}return(i){let n=new Ke;if(this._blockNode(n),this.code(i),n.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Ke)}try(i,n,t){if(!n&&!t)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new J1;if(this._blockNode(o),this.code(i),n){let r=this.name("e");this._currNode=o.catch=new Be(r),n(r)}if(t)this._currNode=o.finally=new Ve,this.code(t);return this._endBlockNode(Be,Ve)}throw(i){return this._leafNode(new k1(i))}block(i,n){if(this._blockStarts.push(this._nodes.length),i)this.code(i).endBlock(n);return this}endBlock(i){let n=this._blockStarts.pop();if(n===void 0)throw Error("CodeGen: not in self-balancing block");let t=this._nodes.length-n;if(t<0||i!==void 0&&t!==i)throw Error(`CodeGen: wrong number of nodes: ${t} vs ${i} expected`);return this._nodes.length=n,this}func(i,n=x.nil,t,o){if(this._blockNode(new Fe(i,n,t)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(Fe)}optimize(i=1){while(i-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(i){return this._currNode.nodes.push(i),this}_blockNode(i){this._currNode.nodes.push(i),this._nodes.push(i)}_endBlockNode(i,n){let t=this._currNode;if(t instanceof i||n&&t instanceof n)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${n?`${i.kind}/${n.kind}`:i.kind}"`)}_elseNode(i){let n=this._currNode;if(!(n instanceof Tn))throw Error('CodeGen: "else" without "if"');return this._currNode=n.else=i,this}get _root(){return this._nodes[0]}get _currNode(){let i=this._nodes;return i[i.length-1]}set _currNode(i){let n=this._nodes;n[n.length-1]=i}}ai.CodeGen=X1;function Jr(i,n){for(let t in n)i[t]=(i[t]||0)+(n[t]||0);return i}function Te(i,n){return n instanceof x._CodeOrName?Jr(i,n.names):i}function Jt(i,n,t){if(i instanceof x.Name)return o(i);if(!r(i))return i;return new x._Code(i._items.reduce((u,l)=>{if(l instanceof x.Name)l=o(l);if(l instanceof x._Code)u.push(...l._items);else u.push(l);return u},[]));function o(u){let l=t[u.str];if(l===void 0||n[u.str]!==1)return u;return delete n[u.str],l}function r(u){return u instanceof x._Code&&u._items.some((l)=>l instanceof x.Name&&n[l.str]===1&&t[l.str]!==void 0)}}function i9(i,n){for(let t in n)i[t]=(i[t]||0)-(n[t]||0)}function Y1(i){return typeof i=="boolean"||typeof i=="number"||i===null?!i:x._`!${G6(i)}`}ai.not=Y1;var n9=P1(ai.operators.AND);function r9(...i){return i.reduce(n9)}ai.and=r9;var t9=P1(ai.operators.OR);function o9(...i){return i.reduce(t9)}ai.or=o9;function P1(i){return(n,t)=>n===x.nil?t:t===x.nil?n:x._`${G6(n)} ${i} ${G6(t)}`}function G6(i){return i instanceof x.Name?i:x._`(${i})`}});var s=Q((q1)=>{Object. Line truncated
|| (${l} == "string" && ${r} && ${r} == +${r})`).assign(e,d._`+${r}`);return;case"integer":o.elseIf(d._`${l} === "boolean" || ${r} === null
|| (${l} === "string" && ${r} && ${r} == +${r} && !(${r} % 1))`).assign(e,d._`+${r}`);return;case"boolean":o.elseIf(d._`${r} === "false" || ${r} === 0 || ${r} === null`).assign(e,!1).elseIf(d._`${r} === "true" || ${r} === 1`).assign(e,!0);return;case"null":o.elseIf(d._`${r} === "" || ${r} === 0 || ${r} === false`),o.assign(e,null);return;case"array":o.elseIf(d._`${l} === "string" || ${l} === "number"
|| ${l} === "boolean" || ${r} === null`).assign(e,d._`[${r}]`)}}}function cX({gen:i,parentData:n,parentDataProperty:t},o){i.if(d._`${n} !== undefined`,()=>i.assign(d._`${n}[${t}]`,o))}function Q6(i,n,t,o=Xt.Correct){let r=o===Xt.Correct?d.operators.EQ:d.operators.NEQ,u;switch(i){case"null":return d._`${n} ${r} null`;case"array":u=d._`Array.isArray(${n})`;break;case"object":u=d._`${n} && typeof ${n} == "object" && !Array.isArray(${n})`;break;case"integer":u=l(d._`!(${n} % 1) && !isNaN(${n})`);break;case"number":u=l();break;default:return d._`typeof ${n} ${r} ${i}`}return o===Xt.Correct?u:(0,d.not)(u);function l(e=d.nil){return(0,d.and)(d._`typeof ${n} == "number"`,e,t?d._`isFinite(${n})`:d.nil)}}ec.checkDataType=Q6;function H6(i,n,t,o){if(i.length===1)return Q6(i[0],n,t,o);let r,u=(0,oc.toHash)(i);if(u.array&&u.object){let l=d._`typeof ${n} != "object"`;r=u.null?l:d._`!${n} || ${l}`,delete u.null,delete u.array,delete u.object}else r=d.nil;if(u.number)delete u.integer;for(let l in u)r=(0,d.and)(r,Q6(l,n,t,o));return r}ec.checkDataTypes=H6;var SX={message:({schema:i})=>`must be ${i}`,params:({schema:i,schemaValue:n})=>typeof i=="string"?d._`{type: ${i}}`:d._`{type: ${n}}`};function F6(i){let n=OX(i);(0,bX.reportError)(n,SX)}ec.reportTypeError=F6;function OX(i){let{gen:n,data:t,schema:o}=i,r=(0,oc.schemaRefOrVal)(i,o,"type");return{gen:n,keyword:"type",data:t,schema:o.type,schemaCode:r,schemaValue:r,parentSchema:o,params:{},it:i}}});var bc=Q((Ic)=>{Object.defineProperty(Ic,"__esModule",{value:!0});Ic.assignDefaults=void 0;var Yt=p(),WX=s();function yX(i,n){let{properties:t,items:o}=i.schema;if(n==="object"&&t)for(let r in t)$c(i,r,t[r].default);else if(n==="array"&&Array.isArray(o))o.forEach((r,u)=>$c(i,u,r.default))}Ic.assignDefaults=yX;function $c(i,n,t){let{gen:o,compositeRule:r,data:u,opts:l}=i;if(t===void 0)return;let e=Yt._`${u}${(0,Yt.getProperty)(n)}`;if(r){(0,WX.checkStrictMode)(i,`default is ignored for: ${e}`);return}let $=Yt._`${e} === undefined`;if(l.useDefaults==="empty")$=Yt._`${$} || ${e} === null || ${e} === ""`;o.if($,Yt._`${e} = ${(0,Yt.stringify)(t)}`)}});var In=Q((Dc)=>{Object.defineProperty(Dc,"__esModule",{value:!0});Dc.validateUnion=Dc.validateArray=Dc.usePattern=Dc.callValidateCode=Dc.schemaProperties=Dc.allSchemaProperties=Dc.noPropertyInData=Dc.propertyInData=Dc.isOwnProperty=Dc.hasPropFunc=Dc.reportMissingProp=Dc.checkMissingProp=Dc.checkReportMissingProp=void 0;var ci=p(),K6=s(),vr=_n(),JX=s();function XX(i,n){let{gen:t,data:o,it:r}=i;t.if(V6(t,o,n,r.opts.ownProperties),()=>{i.setParams({missingProperty:ci._`${n}`},!0),i.error()})}Dc.checkReportMissingProp=XX;function YX({gen:i,data:n,it:{opts:t}},o,r){return(0,ci.or)(...o.map((u)=>(0,ci.and)(V6(i,n,u,t.ownProperties),ci._`${r} = ${u}`)))}Dc.checkMissingProp=YX;function PX(i,n){i.setParams({missingProperty:n},!0),i.error()}Dc.reportMissingProp=PX;function wc(i){return i.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:ci._`Object.prototype.hasOwnProperty`})}Dc.hasPropFunc=wc;function B6(i,n,t){return ci._`${wc(i)}.call(${n}, ${t})`}Dc.isOwnProperty=B6;function QX(i,n,t,o){let r=ci._`${n}${(0,ci.getProperty)(t)} !== undefined`;return o?ci._`${r} && ${B6(i,n,t)}`:r}Dc.propertyInData=QX;function V6(i,n,t,o){let r=ci._`${n}${(0,ci.getProperty)(t)} === undefined`;return o?(0,ci.or)(r,(0,ci.not)(B6(i,n,t))):r}Dc.noPropertyInData=V6;function fc(i){return i?Object.keys(i).filter((n)=>n!=="__proto__"):[]}Dc.allSchemaProperties=fc;function HX(i,n){return fc(n).filter((t)=>!(0,K6.alwaysValidSchema)(i,n[t]))}Dc.schemaProperties=HX;function FX({schemaCode:i,data:n,it:{gen:t,topSchemaRef:o,schemaPath:r,errorPath:u},it:l},e,$,I){let g=I?ci._`${i}, ${n}, ${o}${r}`:n,b=[[vr.default.instancePath,(0,ci.strConcat)(vr.default.instancePath,u)],[vr.default.parentData,l.parentData],[vr.default.parentDataProperty,l.parentDataProperty],[vr.default.rootData,vr.default.rootData]];if(l.opts.dynamicRef)b.push([vr.default.dynamicAnchors,vr.default.dynamicAnchors]);let w=ci._`${g}, ${t.object(...b)}`;return $!==ci.nil?ci._`${e}.call(${$}, ${w})`:ci._`${e}(${w})`}Dc.callValidateCode=FX;var KX=ci._`new RegExp`;function BX({gen:i,it:{opts:n}},t){let o=n.unicodeRegExp?"u":"",{regExp:r}=n.code,u=r(t,o);return i.scopeValue("pattern",{key:u.toString(),ref:u,code:ci._`${r.code==="new RegExp"?KX:(0,JX.useFunc)(i,r)}(${t}, ${o})`})}Dc.usePattern=BX;function VX(i){let{gen:n,data:t,keyword:o,it:r}=i,u=n.name("valid");if(r.allErrors){let e=n.let("valid",!0);return l(()=>n.assign(e,!1)),e}return n.var(u,!0),l(()=>n.break()),u;function l(e){let $=n.const("len",ci._`${t}.length`);n.forRange("i",0,$,(I)=>{i.subschema({keyword:o,dataProp:I,dataPropType:K6.Type.Num},u),n.if((0,ci.not)(u),e)})}}Dc.validateArray=VX;function TX(i){let{gen:n,schema:t,keyword:o,it:r}=i;if(!Array.isArray(t))throw Error("ajv implementation error");if(t.some(($)=>(0,K6.alwaysValidSchema)(r,$))&&!r.opts.unevaluated)return;let l=n.let("valid",!1),e=n.name("_valid");n.block(()=>t.for Line truncated
import{createRequire as Ny}from"node:module";var cy=Object.create;var{getPrototypeOf:Uy,defineProperty:w$,getOwnPropertyNames:Dy}=Object;var Sy=Object.prototype.hasOwnProperty;function Ay(n){return this[n]}var Oy,ky,m4=(n,i,r)=>{var o=n!=null&&typeof n==="object";if(o){var t=i?Oy??=new WeakMap:ky??=new WeakMap,e=t.get(n);if(e)return e}r=n!=null?cy(Uy(n)):{};let u=i||!n||!n.__esModule?w$(r,"default",{value:n,enumerable:!0}):r;for(let l of Dy(n))if(!Sy.call(u,l))w$(u,l,{get:Ay.bind(n,l),enumerable:!0});if(o)t.set(n,u);return u};var P=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports);var dy=(n)=>n;function Ly(n,i){this[n]=dy.bind(null,i)}var pi=(n,i)=>{for(var r in i)w$(n,r,{get:i[r],enumerable:!0,configurable:!0,set:Ly.bind(i,r)})};var Z4=Ny(import.meta.url);var ne=P((kD)=>{Object.defineProperty(kD,"__esModule",{value:!0});kD.regexpCode=kD.getEsmExportName=kD.getProperty=kD.safeStringify=kD.stringify=kD.strConcat=kD.addCodeArg=kD.str=kD._=kD.nil=kD._Code=kD.Name=kD.IDENTIFIER=kD._CodeOrName=void 0;class Ql{}kD._CodeOrName=Ql;kD.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Jr extends Ql{constructor(n){super();if(!kD.IDENTIFIER.test(n))throw Error("CodeGen: name must be a valid identifier");this.str=n}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}kD.Name=Jr;class ci extends Ql{constructor(n){super();this._items=typeof n==="string"?[n]:n}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let n=this._items[0];return n===""||n==='""'}get str(){var n;return(n=this._str)!==null&&n!==void 0?n:this._str=this._items.reduce((i,r)=>`${i}${r}`,"")}get names(){var n;return(n=this._names)!==null&&n!==void 0?n:this._names=this._items.reduce((i,r)=>{if(r instanceof Jr)i[r.str]=(i[r.str]||0)+1;return i},{})}}kD._Code=ci;kD.nil=new ci("");function AD(n,...i){let r=[n[0]],o=0;while(o<i.length)jc(r,i[o]),r.push(n[++o]);return new ci(r)}kD._=AD;var Gc=new ci("+");function OD(n,...i){let r=[so(n[0])],o=0;while(o<i.length)r.push(Gc),jc(r,i[o]),r.push(Gc,so(n[++o]));return mJ(r),new ci(r)}kD.str=OD;function jc(n,i){if(i instanceof ci)n.push(...i._items);else if(i instanceof Jr)n.push(i);else n.push(zJ(i))}kD.addCodeArg=jc;function mJ(n){let i=1;while(i<n.length-1){if(n[i]===Gc){let r=ZJ(n[i-1],n[i+1]);if(r!==void 0){n.splice(i-1,3,r);continue}n[i++]="+"}i++}}function ZJ(n,i){if(i==='""')return n;if(n==='""')return i;if(typeof n=="string"){if(i instanceof Jr||n[n.length-1]!=='"')return;if(typeof i!="string")return`${n.slice(0,-1)}${i}"`;if(i[0]==='"')return n.slice(0,-1)+i.slice(1);return}if(typeof i=="string"&&i[0]==='"'&&!(n instanceof Jr))return`"${n}${i.slice(1)}`;return}function MJ(n,i){return i.emptyStr()?n:n.emptyStr()?i:OD`${n}${i}`}kD.strConcat=MJ;function zJ(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:so(Array.isArray(n)?n.join(","):n)}function CJ(n){return new ci(so(n))}kD.stringify=CJ;function so(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}kD.safeStringify=so;function RJ(n){return typeof n=="string"&&kD.IDENTIFIER.test(n)?new ci(`.${n}`):AD`[${n}]`}kD.getProperty=RJ;function xJ(n){if(typeof n=="string"&&kD.IDENTIFIER.test(n))return new ci(`${n}`);throw Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}kD.getEsmExportName=xJ;function aJ(n){return new ci(n.toString())}kD.regexpCode=aJ});var Xc=P((yD)=>{Object.defineProperty(yD,"__esModule",{value:!0});yD.ValueScope=yD.ValueScopeName=yD.Scope=yD.varKinds=yD.UsedValueState=void 0;var an=ne();class LD extends Error{constructor(n){super(`CodeGen: "code" for ${n} not defined`);this.value=n.value}}var Kl;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed"})(Kl||(yD.UsedValueState=Kl={}));yD.varKinds={const:new an.Name("const"),let:new an.Name("let"),var:new an.Name("var")};class Jc{constructor({prefixes:n,parent:i}={}){this._names={},this._prefixes=n,this._parent=i}toName(n){return n instanceof an.Name?n:this.name(n)}name(n){return new an.Name(this._newName(n))}_newName(n){let i=this._names[n]||this._nameGroup(n);return`${n}${i.index++}`}_nameGroup(n){var i,r;if(((r=(i=this._parent)===null||i===void 0?void 0:i._prefixes)===null||r===void 0?void 0:r.has(n))||this._prefixes&&!this._prefixes.has(n))throw Error(`CodeGen: prefix "${n}" is not allowed in this scope`);return this._names[n]={prefix:n,index:0}}}yD.Scope=Jc;class Hc extends an.Name{constructor(n,i){super(i);this.prefix=n}setValue(n,{property:i,itemIndex:r}){this.value=n,this.scopePath=an._`.${new an.Name(i)}[${r}]`}}yD.ValueScopeName=Hc;var g8=an._`\n`;class ND extends Jc{constructor(n){super(n);this._values={},this._scope=n.scope,this.opts={...n,_n:n.lines?g8:an.nil}}get(){return this._scope}name(n){return new Hc(n,this._newName(n))}value(n,i){var r;if(i.ref===void 0)throw Error("CodeGen: ref must be passed in value");let o=this.toName(n),{prefix:t}=o,e=(r=i.key)!==null&&r!==void 0?r:i.ref,u=this._values[t];if(u){let I=u.get(e);if(I)return I}else u=this._values[t]=newLine truncated
`:""},this._extScope=n,this._scope=new Ui.Scope({parent:n}),this._nodes=[new PD]}toString(){return this._root.render(this.opts)}name(n){return this._scope.name(n)}scopeName(n){return this._extScope.name(n)}scopeValue(n,i){let r=this._extScope.value(n,i);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(n,i){return this._extScope.getValue(n,i)}scopeRefs(n){return this._extScope.scopeRefs(n,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(n,i,r,o){let t=this._scope.toName(i);if(r!==void 0&&o)this._constants[t.str]=r;return this._leafNode(new jD(n,t,r)),t}const(n,i,r){return this._def(Ui.varKinds.const,n,i,r)}let(n,i,r){return this._def(Ui.varKinds.let,n,i,r)}var(n,i,r){return this._def(Ui.varKinds.var,n,i,r)}assign(n,i,r){return this._leafNode(new Yc(n,i,r))}add(n,i){return this._leafNode(new WD(n,sn.operators.ADD,i))}code(n){if(typeof n=="function")n();else if(n!==s.nil)this._leafNode(new hD(n));return this}object(...n){let i=["{"];for(let[r,o]of n){if(i.length>1)i.push(",");if(i.push(r),r!==o||this.opts.es5)i.push(":"),(0,s.addCodeArg)(i,o)}return i.push("}"),new s._Code(i)}if(n,i,r){if(this._blockNode(new Vi(n)),i&&r)this.code(i).else().code(r).endIf();else if(i)this.code(i).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(n){return this._elseNode(new Vi(n))}else(){return this._elseNode(new ie)}endIf(){return this._endBlockNode(Vi,ie)}_for(n,i){if(this._blockNode(n),i)this.code(i).endFor();return this}for(n,i){return this._for(new YD(n),i)}forRange(n,i,r,o,t=this.opts.es5?Ui.varKinds.var:Ui.varKinds.let){let e=this._scope.toName(n);return this._for(new pD(t,e,i,r),()=>o(e))}forOf(n,i,r,o=Ui.varKinds.const){let t=this._scope.toName(n);if(this.opts.es5){let e=i instanceof s.Name?i:this.var("_arr",i);return this.forRange("_i",0,s._`${e}.length`,(u)=>{this.var(t,s._`${e}[${u}]`),r(t)})}return this._for(new hc("of",o,t,i),()=>r(t))}forIn(n,i,r,o=this.opts.es5?Ui.varKinds.var:Ui.varKinds.const){if(this.opts.ownProperties)return this.forOf(n,s._`Object.keys(${i})`,r);let t=this._scope.toName(n);return this._for(new hc("in",o,t,i),()=>r(t))}endFor(){return this._endBlockNode(Hr)}label(n){return this._leafNode(new JD(n))}break(n){return this._leafNode(new HD(n))}return(n){let i=new Vl;if(this._blockNode(i),this.code(n),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Vl)}try(n,i,r){if(!i&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new QD;if(this._blockNode(o),this.code(n),i){let t=this.name("e");this._currNode=o.catch=new Tl(t),i(t)}if(r)this._currNode=o.finally=new ql,this.code(r);return this._endBlockNode(Tl,ql)}throw(n){return this._leafNode(new XD(n))}block(n,i){if(this._blockStarts.push(this._nodes.length),n)this.code(n).endBlock(i);return this}endBlock(n){let i=this._blockStarts.pop();if(i===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-i;if(r<0||n!==void 0&&r!==n)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${n} expected`);return this._nodes.length=i,this}func(n,i=s.nil,r,o){if(this._blockNode(new Bl(n,i,r)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(Bl)}optimize(n=1){while(n-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(n){return this._currNode.nodes.push(n),this}_blockNode(n){this._currNode.nodes.push(n),this._nodes.push(n)}_endBlockNode(n,i){let r=this._currNode;if(r instanceof n||i&&r instanceof i)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${i?`${n.kind}/${i.kind}`:n.kind}"`)}_elseNode(n){let i=this._currNode;if(!(i instanceof Vi))throw Error('CodeGen: "else" without "if"');return this._currNode=i.else=n,this}get _root(){return this._nodes[0]}get _currNode(){let n=this._nodes;return n[n.length-1]}set _currNode(n){let i=this._nodes;i[i.length-1]=n}}sn.CodeGen=FD;function Xt(n,i){for(let r in i)n[r]=(n[r]||0)+(i[r]||0);return n}function _l(n,i){return i instanceof s._CodeOrName?Xt(n,i.names):n}function Xr(n,i,r){if(n instanceof s.Name)return o(n);if(!t(n))return n;return new s._Code(n._items.reduce((e,u)=>{if(u instanceof s.Name)u=o(u);if(u instanceof s._Code)e.push(...u._items);else e.push(u);return e},[]));function o(e){let u=r[e.str];if(u===void 0||i[e.str]!==1)return e;return delete i[e.str],u}function t(e){return e instanceof s._Code&&e._items.some((u)=>u instanceof s.Name&&i[u.str]===1&&r[u.str]!==void 0)}}function c8(n,i){for(let r in i)n[r]=(n[r]||0)-(i[r]||0)}function KD(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:s._`!${Pc(n)}`}sn.not=KD;var U8=BD(sn.operators.AND);function D8(...n){return n.reduce(U8)}sn.and=D8;var S8=BD(sn.operators.OR);function A8(...n){return n.reduce(S8)}sn.or=A8;function BD(n){return(i,r)=>i===s.nil?r:r===s.nil?i:s._`${Pc(i)} ${n} ${Pc(r)}`}function Pc(n){return n instanceof s.Name?n:s._`(${n})`}});var nn=P((zD)=>{Object Line truncated
|| (${u} == "string" && ${t} && ${t} == +${t})`).assign(l,Z._`+${t}`);return;case"integer":o.elseIf(Z._`${u} === "boolean" || ${t} === null
|| (${u} === "string" && ${t} && ${t} == +${t} && !(${t} % 1))`).assign(l,Z._`+${t}`);return;case"boolean":o.elseIf(Z._`${t} === "false" || ${t} === 0 || ${t} === null`).assign(l,!1).elseIf(Z._`${t} === "true" || ${t} === 1`).assign(l,!0);return;case"null":o.elseIf(Z._`${t} === "" || ${t} === 0 || ${t} === false`),o.assign(l,null);return;case"array":o.elseIf(Z._`${u} === "string" || ${u} === "number"
|| ${u} === "boolean" || ${t} === null`).assign(l,Z._`[${t}]`)}}}function hH({gen:n,parentData:i,parentDataProperty:r},o){n.if(Z._`${i} !== undefined`,()=>n.assign(Z._`${i}[${r}]`,o))}function Tc(n,i,r,o=hr.Correct){let t=o===hr.Correct?Z.operators.EQ:Z.operators.NEQ,e;switch(n){case"null":return Z._`${i} ${t} null`;case"array":e=Z._`Array.isArray(${i})`;break;case"object":e=Z._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":e=u(Z._`!(${i} % 1) && !isNaN(${i})`);break;case"number":e=u();break;default:return Z._`typeof ${i} ${t} ${n}`}return o===hr.Correct?e:(0,Z.not)(e);function u(l=Z.nil){return(0,Z.and)(Z._`typeof ${i} == "number"`,l,r?Z._`isFinite(${i})`:Z.nil)}}c1.checkDataType=Tc;function qc(n,i,r,o){if(n.length===1)return Tc(n[0],i,r,o);let t,e=(0,b1.toHash)(n);if(e.array&&e.object){let u=Z._`typeof ${i} != "object"`;t=e.null?u:Z._`!${i} || ${u}`,delete e.null,delete e.array,delete e.object}else t=Z.nil;if(e.number)delete e.integer;for(let u in e)t=(0,Z.and)(t,Tc(u,i,r,o));return t}c1.checkDataTypes=qc;var PH={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:i})=>typeof n=="string"?Z._`{type: ${n}}`:Z._`{type: ${i}}`};function _c(n){let i=YH(n);(0,jH.reportError)(i,PH)}c1.reportTypeError=_c;function YH(n){let{gen:i,data:r,schema:o}=n,t=(0,b1.schemaRefOrVal)(n,o,"type");return{gen:i,keyword:"type",data:r,schema:o.type,schemaCode:t,schemaValue:t,parentSchema:o,params:{},it:n}}});var O1=P((S1)=>{Object.defineProperty(S1,"__esModule",{value:!0});S1.assignDefaults=void 0;var Pr=M(),TH=nn();function qH(n,i){let{properties:r,items:o}=n.schema;if(i==="object"&&r)for(let t in r)D1(n,t,r[t].default);else if(i==="array"&&Array.isArray(o))o.forEach((t,e)=>D1(n,e,t.default))}S1.assignDefaults=qH;function D1(n,i,r){let{gen:o,compositeRule:t,data:e,opts:u}=n;if(r===void 0)return;let l=Pr._`${e}${(0,Pr.getProperty)(i)}`;if(t){(0,TH.checkStrictMode)(n,`default is ignored for: ${l}`);return}let $=Pr._`${l} === undefined`;if(u.useDefaults==="empty")$=Pr._`${$} || ${l} === null || ${l} === ""`;o.if($,Pr._`${l} = ${(0,Pr.stringify)(r)}`)}});var Ii=P((L1)=>{Object.defineProperty(L1,"__esModule",{value:!0});L1.validateUnion=L1.validateArray=L1.usePattern=L1.callValidateCode=L1.schemaProperties=L1.allSchemaProperties=L1.noPropertyInData=L1.propertyInData=L1.isOwnProperty=L1.hasPropFunc=L1.reportMissingProp=L1.checkMissingProp=L1.checkReportMissingProp=void 0;var Sn=M(),Ec=nn(),gt=Ti(),_H=nn();function EH(n,i){let{gen:r,data:o,it:t}=n;r.if(Zc(r,o,i,t.opts.ownProperties),()=>{n.setParams({missingProperty:Sn._`${i}`},!0),n.error()})}L1.checkReportMissingProp=EH;function mH({gen:n,data:i,it:{opts:r}},o,t){return(0,Sn.or)(...o.map((e)=>(0,Sn.and)(Zc(n,i,e,r.ownProperties),Sn._`${t} = ${e}`)))}L1.checkMissingProp=mH;function ZH(n,i){n.setParams({missingProperty:i},!0),n.error()}L1.reportMissingProp=ZH;function k1(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Sn._`Object.prototype.hasOwnProperty`})}L1.hasPropFunc=k1;function mc(n,i,r){return Sn._`${k1(n)}.call(${i}, ${r})`}L1.isOwnProperty=mc;function MH(n,i,r,o){let t=Sn._`${i}${(0,Sn.getProperty)(r)} !== undefined`;return o?Sn._`${t} && ${mc(n,i,r)}`:t}L1.propertyInData=MH;function Zc(n,i,r,o){let t=Sn._`${i}${(0,Sn.getProperty)(r)} === undefined`;return o?(0,Sn.or)(t,(0,Sn.not)(mc(n,i,r))):t}L1.noPropertyInData=Zc;function d1(n){return n?Object.keys(n).filter((i)=>i!=="__proto__"):[]}L1.allSchemaProperties=d1;function zH(n,i){return d1(i).filter((r)=>!(0,Ec.alwaysValidSchema)(n,i[r]))}L1.schemaProperties=zH;function CH({schemaCode:n,data:i,it:{gen:r,topSchemaRef:o,schemaPath:t,errorPath:e},it:u},l,$,I){let g=I?Sn._`${n}, ${i}, ${o}${t}`:i,b=[[gt.default.instancePath,(0,Sn.strConcat)(gt.default.instancePath,e)],[gt.default.parentData,u.parentData],[gt.default.parentDataProperty,u.parentDataProperty],[gt.default.rootData,gt.default.rootData]];if(u.opts.dynamicRef)b.push([gt.default.dynamicAnchors,gt.default.dynamicAnchors]);let w=Sn._`${g}, ${r.object(...b)}`;return $!==Sn.nil?Sn._`${l}.call(${$}, ${w})`:Sn._`${l}(${w})`}L1.callValidateCode=CH;var RH=Sn._`new RegExp`;function xH({gen:n,it:{opts:i}},r){let o=i.unicodeRegExp?"u":"",{regExp:t}=i.code,e=t(r,o);return n.scopeValue("pattern",{key:e.toString(),ref:e,code:Sn._`${t.code==="new RegExp"?RH:(0,_H.useFunc)(n,t)}(${r}, ${o})`})}L1.usePattern=xH;function aH(n){let{gen:i,data:r,keyword:o,it:t}=n,e=i.name("valid");if(t.allErrors){let l=i.let("valid",!0);return u(()=>i.assign(l,!1)),l}return i.var(e,!0),u(()=>i.break()),e;function u(l){let $=i.const("len",Sn._`${r}.length`);i.forRange("i",0,$,(I)=>{n.subschema({keyword:o,dataProp:I,dataPropType:Ec.Type.Num},e),i.if((0,Sn.not)(e),l)})}}L1.validateArray=aH;function sH(n){let{gen:i,schema:r,keyword:o,it:t}=n;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(($)=>(0,Ec.alwaysValidSchema)(t,$))&&!t.opts.unevaluated)return;let u=i.let("valid",!1),l=i.name("_valid");i.block(()=>r. Line truncated
missingProperty: ${o},
depsCount: ${n},
deps: ${t}}`};var tQ={keyword:"dependencies",type:"object",schemaType:"object",error:QO.error,code(i){let[n,t]=oQ(i);YO(i,n),PO(i,t)}};function oQ({schema:i}){let n={},t={};for(let o in i){if(o==="__proto__")continue;let r=Array.isArray(i[o])?n:t;r[o]=i[o]}return[n,t]}function YO(i,n=i.schema){let{gen:t,data:o,it:r}=i;if(Object.keys(n).length===0)return;let u=t.let("missing");for(let l in n){let e=n[l];if(e.length===0)continue;let $=(0,Du.propertyInData)(t,o,l,r.opts.ownProperties);if(i.setParams({property:l,depsCount:e.length,deps:e.join(", ")}),r.allErrors)t.if($,()=>{for(let I of e)(0,Du.checkReportMissingProp)(i,I)});else t.if(l4._`${$} && (${(0,Du.checkMissingProp)(i,e,u)})`),(0,Du.reportMissingProp)(i,u),t.else()}}QO.validatePropertyDeps=YO;function PO(i,n=i.schema){let{gen:t,data:o,keyword:r,it:u}=i,l=t.name("valid");for(let e in n){if((0,rQ.alwaysValidSchema)(u,n[e]))continue;t.if((0,Du.propertyInData)(t,o,e,u.opts.ownProperties),()=>{let $=i.subschema({keyword:r,schemaProp:e},l);i.mergeValidEvaluated($,l)},()=>t.var(l,!0)),i.ok(l)}}QO.validateSchemaDeps=PO;QO.default=tQ});var TO=Q((VO)=>{Object.defineProperty(VO,"__esModule",{value:!0});var BO=p(),eQ=s(),vQ={message:"property name must be valid",params:({params:i})=>BO._`{propertyName: ${i.propertyName}}`},$Q={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:vQ,code(i){let{gen:n,schema:t,data:o,it:r}=i;if((0,eQ.alwaysValidSchema)(r,t))return;let u=n.name("valid");n.forIn("key",o,(l)=>{i.setParams({propertyName:l}),i.subschema({keyword:"propertyNames",data:l,dataTypes:["string"],propertyName:l,compositeRule:!0},u),n.if((0,BO.not)(u),()=>{if(i.error(!0),!r.allErrors)n.break()})}),i.ok(u)}};VO.default=$Q});var e4=Q((_O)=>{Object.defineProperty(_O,"__esModule",{value:!0});var lv=In(),Sn=p(),gQ=_n(),ev=s(),bQ={message:"must NOT have additional properties",params:({params:i})=>Sn._`{additionalProperty: ${i.additionalProperty}}`},wQ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:bQ,code(i){let{gen:n,schema:t,parentSchema:o,data:r,errsCount:u,it:l}=i;if(!u)throw Error("ajv implementation error");let{allErrors:e,opts:$}=l;if(l.props=!0,$.removeAdditional!=="all"&&(0,ev.alwaysValidSchema)(l,t))return;let I=(0,lv.allSchemaProperties)(o.properties),g=(0,lv.allSchemaProperties)(o.patternProperties);b(),i.ok(Sn._`${u} === ${gQ.default.errors}`);function b(){n.forIn("key",r,(N)=>{if(!I.length&&!g.length)D(N);else n.if(w(N),()=>D(N))})}function w(N){let L;if(I.length>8){let K=(0,ev.schemaRefOrVal)(l,o.properties,"properties");L=(0,lv.isOwnProperty)(n,K,N)}else if(I.length)L=(0,Sn.or)(...I.map((K)=>Sn._`${N} === ${K}`));else L=Sn.nil;if(g.length)L=(0,Sn.or)(L,...g.map((K)=>Sn._`${(0,lv.usePattern)(i,K)}.test(${N})`));return(0,Sn.not)(L)}function f(N){n.code(Sn._`delete ${r}[${N}]`)}function D(N){if($.removeAdditional==="all"||$.removeAdditional&&t===!1){f(N);return}if(t===!1){if(i.setParams({additionalProperty:N}),i.error(),!e)n.break();return}if(typeof t=="object"&&!(0,ev.alwaysValidSchema)(l,t)){let L=n.name("valid");if($.removeAdditional==="failing")S(N,L,!1),n.if((0,Sn.not)(L),()=>{i.reset(),f(N)});else if(S(N,L),!e)n.if((0,Sn.not)(L),()=>n.break())}}function S(N,L,K){let F={keyword:"additionalProperties",dataProp:N,dataPropType:ev.Type.Str};if(K===!1)Object.assign(F,{compositeRule:!0,createErrors:!1,allErrors:!1});i.subschema(F,L)}}};_O.default=wQ});var MO=Q((ZO)=>{Object.defineProperty(ZO,"__esModule",{value:!0});var DQ=tu(),qO=In(),v4=s(),EO=e4(),UQ={keyword:"properties",type:"object",schemaType:"object",code(i){let{gen:n,schema:t,parentSchema:o,data:r,it:u}=i;if(u.opts.removeAdditional==="all"&&o.additionalProperties===void 0)EO.default.code(new DQ.KeywordCxt(u,EO.default,"additionalProperties"));let l=(0,qO.allSchemaProperties)(t);for(let b of l)u.definedProperties.add(b);if(u.opts.unevaluated&&l.length&&u.props!==!0)u.props=v4.mergeEvaluated.props(n,(0,v4.toHash)(l),u.props);let e=l.filter((b)=>!(0,v4.alwaysValidSchema)(u,t[b]));if(e.length===0)return;let $=n.name("valid");for(let b of e){if(I(b))g(b);else{if(n.if((0,qO.propertyInData)(n,r,b,u.opts.ownProperties)),g(b),!u.allErrors)n.else().var($,!0);n.endIf()}i.it.definedProperties.add(b),i.ok($)}function I(b){return u.opts.useDefaults&&!u.compositeRule&&t[b].default!==void 0}function g(b){i.subschema({keyword:"properties",schemaProp:b,dataProp:b},$)}}};ZO.default=UQ});var CO=Q((hO)=>{Object.defineProperty(hO,"__esModule",{value:!0});var dO=In(),vv=p(),zO=s(),pO=s(),SQ={keyword:"patternProperties",type:"object",schemaType:"object",code(i){let{gen:n,schema:t,data:o,parentSchema:r,it:u}=i,{opts:l}=u,e=(0,dO.allSchemaProperties)(t),$=e.filter((S)=>(0,zO.alwaysValidSchema)(u,t[S]));if(e.length===0||$.length===e.length&&(!u.opts.unevaluated||u.props===!0))return;let I=l.strictSchema&&!l.allowMatchingProperties&&r.properties,g=n.name("valid");if(u.props!==!0&&!(u.props instanceof vv.Name))u.props=(0,pO.evalu Line truncated
`)}var pr=(i)=>(n,t,o,r)=>{let u=o?{...o,async:!1}:{async:!1},l=n._zod.run({value:t,issues:[]},u);if(l instanceof Promise)throw new kn;if(l.issues.length){let e=new(r?.Err??i)(l.issues.map(($)=>Zi($,u,Oi())));throw Zu(e,r?.callee),e}return l.value},lo=pr(mi),hr=(i)=>async(n,t,o,r)=>{let u=o?{...o,async:!0}:{async:!0},l=n._zod.run({value:t,issues:[]},u);if(l instanceof Promise)l=await l;if(l.issues.length){let e=new(r?.Err??i)(l.issues.map(($)=>Zi($,u,Oi())));throw Zu(e,r?.callee),e}return l.value},eo=hr(mi),Cr=(i)=>(n,t,o)=>{let r=o?{...o,async:!1}:{async:!1},u=n._zod.run({value:t,issues:[]},r);if(u instanceof Promise)throw new kn;return u.issues.length?{success:!1,error:new(i??to)(u.issues.map((l)=>Zi(l,r,Oi())))}:{success:!0,data:u.value}},mr=Cr(mi),Rr=(i)=>async(n,t,o)=>{let r=o?{...o,async:!0}:{async:!0},u=n._zod.run({value:t,issues:[]},r);if(u instanceof Promise)u=await u;return u.issues.length?{success:!1,error:new i(u.issues.map((l)=>Zi(l,r,Oi())))}:{success:!0,data:u.value}},vo=Rr(mi),Mu=(i)=>(n,t,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return pr(i)(n,t,r)},p0=Mu(mi),du=(i)=>(n,t,o)=>{return pr(i)(n,t,o)},h0=du(mi),zu=(i)=>async(n,t,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return hr(i)(n,t,r)},C0=zu(mi),pu=(i)=>async(n,t,o)=>{return hr(i)(n,t,o)},m0=pu(mi),hu=(i)=>(n,t,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return Cr(i)(n,t,r)},R0=hu(mi),Cu=(i)=>(n,t,o)=>{return Cr(i)(n,t,o)},x0=Cu(mi),mu=(i)=>async(n,t,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return Rr(i)(n,t,r)},a0=mu(mi),Ru=(i)=>async(n,t,o)=>{return Rr(i)(n,t,o)},s0=Ru(mi);var on={};Hn(on,{xid:()=>L$,uuid7:()=>_j,uuid6:()=>Tj,uuid4:()=>Vj,uuid:()=>Lr,uppercase:()=>h$,unicodeEmail:()=>iD,undefined:()=>z$,ulid:()=>N$,time:()=>T$,string:()=>q$,sha512_hex:()=>lW,sha512_base64url:()=>vW,sha512_base64:()=>eW,sha384_hex:()=>tW,sha384_base64url:()=>uW,sha384_base64:()=>oW,sha256_hex:()=>iW,sha256_base64url:()=>rW,sha256_base64:()=>nW,sha1_hex:()=>xj,sha1_base64url:()=>sj,sha1_base64:()=>aj,rfc5322Email:()=>Ej,number:()=>$o,null:()=>d$,nanoid:()=>G$,md5_hex:()=>Cj,md5_base64url:()=>Rj,md5_base64:()=>mj,mac:()=>P$,lowercase:()=>p$,ksuid:()=>k$,ipv6:()=>Y$,ipv4:()=>X$,integer:()=>Z$,idnEmail:()=>Zj,httpProtocol:()=>K$,html5Email:()=>qj,hostname:()=>zj,hex:()=>hj,guid:()=>W$,extendedDuration:()=>Bj,emoji:()=>J$,email:()=>y$,e164:()=>B$,duration:()=>j$,domain:()=>pj,datetime:()=>_$,date:()=>V$,cuid2:()=>A$,cuid:()=>O$,cidrv6:()=>H$,cidrv4:()=>Q$,browserEmail:()=>Mj,boolean:()=>M$,bigint:()=>E$,base64url:()=>xu,base64:()=>F$});var O$=/^[cC][0-9a-z]{6,}$/,A$=/^[0-9a-z]+$/,N$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,L$=/^[0-9a-vA-V]{20}$/,k$=/^[A-Za-z0-9]{27}$/,G$=/^[a-zA-Z0-9_-]{21}$/,j$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Bj=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,W$=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Lr=(i)=>{if(!i)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${i}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Vj=Lr(4),Tj=Lr(6),_j=Lr(7),y$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,qj=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Ej=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,iD=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Zj=iD,Mj=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,dj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function J$(){return new RegExp(dj,"u")}var X$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Y$=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,P$=(i)=>{let n=en(i??":");return new RegExp(`^(?:[0-9A-F]{2}${n}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${n}){5}[0-9a-f]{2}$`)},Q$=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-Line truncated
`).filter((u)=>u),o=Math.min(...t.map((u)=>u.length-u.trimStart().length)),r=t.map((u)=>u.slice(o)).map((u)=>" ".repeat(this.indent*2)+u);for(let u of r)this.content.push(u)}compile(){let i=Function,n=this?.args,o=[...(this?.content??[""]).map((r)=>` ${r}`)];return new i(...n,o.join(`
`))}}var bI={major:4,minor:4,patch:3};var _=U("$ZodType",(i,n)=>{var t;i??(i={}),i._zod.def=n,i._zod.bag=i._zod.bag||{},i._zod.version=bI;let o=[...i._zod.def.checks??[]];if(i._zod.traits.has("$ZodCheck"))o.unshift(i);for(let r of o)for(let u of r._zod.onattach)u(i);if(o.length===0)(t=i._zod).deferred??(t.deferred=[]),i._zod.deferred?.push(()=>{i._zod.run=i._zod.parse});else{let r=(l,e,$)=>{let I=mn(l),g;for(let b of e){if(b._zod.def.when){if(U$(l))continue;if(!b._zod.def.when(l))continue}else if(I)continue;let w=l.issues.length,f=b._zod.check(l);if(f instanceof Promise&&$?.async===!1)throw new kn;if(g||f instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await f,l.issues.length===w)return;if(!I)I=mn(l,w)});else{if(l.issues.length===w)continue;if(!I)I=mn(l,w)}}if(g)return g.then(()=>{return l});return l},u=(l,e,$)=>{if(mn(l))return l.aborted=!0,l;let I=r(e,o,$);if(I instanceof Promise){if($.async===!1)throw new kn;return I.then((g)=>i._zod.parse(g,$))}return i._zod.parse(I,$)};i._zod.run=(l,e)=>{if(e.skipChecks)return i._zod.parse(l,e);if(e.direction==="backward"){let I=i._zod.parse({value:l.value,issues:[]},{...e,skipChecks:!0});if(I instanceof Promise)return I.then((g)=>{return u(g,l,e)});return u(I,l,e)}let $=i._zod.parse(l,e);if($ instanceof Promise){if(e.async===!1)throw new kn;return $.then((I)=>r(I,o,e))}return r($,o,e)}}h(i,"~standard",()=>({validate:(r)=>{try{let u=mr(i,r);return u.success?{value:u.data}:{issues:u.error?.issues}}catch(u){return vo(i,r).then((l)=>l.success?{value:l.data}:{issues:l.error?.issues})}},vendor:"zod",version:1}))}),kr=U("$ZodString",(i,n)=>{_.init(i,n),i._zod.pattern=[...i?._zod.bag?.patterns??[]].pop()??q$(i._zod.bag),i._zod.parse=(t,o)=>{if(n.coerce)try{t.value=String(t.value)}catch(r){}if(typeof t.value==="string")return t;return t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:i}),t}}),ei=U("$ZodStringFormat",(i,n)=>{xr.init(i,n),kr.init(i,n)}),fI=U("$ZodGUID",(i,n)=>{n.pattern??(n.pattern=W$),ei.init(i,n)}),DI=U("$ZodUUID",(i,n)=>{if(n.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[n.version];if(o===void 0)throw Error(`Invalid UUID version: "${n.version}"`);n.pattern??(n.pattern=Lr(o))}else n.pattern??(n.pattern=Lr());ei.init(i,n)}),UI=U("$ZodEmail",(i,n)=>{n.pattern??(n.pattern=y$),ei.init(i,n)}),cI=U("$ZodURL",(i,n)=>{ei.init(i,n),i._zod.check=(t)=>{try{let o=t.value.trim();if(!n.normalize&&n.protocol?.source===K$.source){if(!/^https?:\/\//i.test(o)){t.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:t.value,inst:i,continue:!n.abort});return}}let r=new URL(o);if(n.hostname){if(n.hostname.lastIndex=0,!n.hostname.test(r.hostname))t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:n.hostname.source,input:t.value,inst:i,continue:!n.abort})}if(n.protocol){if(n.protocol.lastIndex=0,!n.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol))t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:n.protocol.source,input:t.value,inst:i,continue:!n.abort})}if(n.normalize)t.value=r.href;else t.value=o;return}catch(o){t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:i,continue:!n.abort})}}}),SI=U("$ZodEmoji",(i,n)=>{n.pattern??(n.pattern=J$()),ei.init(i,n)}),OI=U("$ZodNanoID",(i,n)=>{n.pattern??(n.pattern=G$),ei.init(i,n)}),AI=U("$ZodCUID",(i,n)=>{n.pattern??(n.pattern=O$),ei.init(i,n)}),NI=U("$ZodCUID2",(i,n)=>{n.pattern??(n.pattern=A$),ei.init(i,n)}),LI=U("$ZodULID",(i,n)=>{n.pattern??(n.pattern=N$),ei.init(i,n)}),kI=U("$ZodXID",(i,n)=>{n.pattern??(n.pattern=L$),ei.init(i,n)}),GI=U("$ZodKSUID",(i,n)=>{n.pattern??(n.pattern=k$),ei.init(i,n)}),jI=U("$ZodISODateTime",(i,n)=>{n.pattern??(n.pattern=_$(n)),ei.init(i,n)}),WI=U("$ZodISODate",(i,n)=>{n.pattern??(n.pattern=V$),ei.init(i,n)}),yI=U("$ZodISOTime",(i,n)=>{n.pattern??(n.pattern=T$(n)),ei.init(i,n)}),JI=U("$ZodISODuration",(i,n)=>{n.pattern??(n.pattern=j$),ei.init(i,n)}),XI=U("$ZodIPv4",(i,n)=>{n.pattern??(n.pattern=X$),ei.init(i,n),i._zod.bag.format="ipv4"}),YI=U("$ZodIPv6",(i,n)=>{n.pattern??(n.pattern=Y$),ei.init(i,n),i._zod.bag.format="ipv6",i._zod.check=(t)=>{try{new URL(`http://[${t.value}]`)}catch{t.issues.push({code:"invalid_format",format:"ipv6",input:t.value,inst:i,continue:!n.abort})}}}),PI=U("$ZodMAC",(i,n)=>{n.pattern??(n.pattern=P$(n.delimiter)),ei.init(i,n),i._zod.bag.format="mac"}),QI=U("$ZodCIDRv4",(i,n)=>{n.pattern??(n.pattern=Q$),ei.init(i,n)}),HI=U("$ZodCIDRv6",(i,n)=>{n.pattern??(n.pattern=H$),ei.init(i,n),i._zod.check=(t)=>{let o=t.value.split("/");try{if(o.length!==2)throw Error();let[r,u]=o;if(!u)throw Error();let l=Number(u);if(`${l}`!==u)throw Error();if(l<0||l>128)throw Error();new URL(`http://[${r}]`)}catch{t.issues.push({code:"invalid_format",format:"cidrv6",input:t.value,inst:i,continue:!n.abort})}}});function FI(i){if(i==="")return!0;if(/\s/.test(i))return!1;if(i.length%4!==0)return!1;try{return atob(i),!0}catch{return!1}}var Line truncated
if (${y}.issues.length) {
if (${G} in input) {
payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
depsCount: ${i},
deps: ${r}}`};var SY={keyword:"dependencies",type:"object",schemaType:"object",error:VA.error,code(n){let[i,r]=AY(n);KA(n,i),BA(n,r)}};function AY({schema:n}){let i={},r={};for(let o in n){if(o==="__proto__")continue;let t=Array.isArray(n[o])?i:r;t[o]=n[o]}return[i,r]}function KA(n,i=n.schema){let{gen:r,data:o,it:t}=n;if(Object.keys(i).length===0)return;let e=r.let("missing");for(let u in i){let l=i[u];if(l.length===0)continue;let $=(0,Ae.propertyInData)(r,o,u,t.opts.ownProperties);if(n.setParams({property:u,depsCount:l.length,deps:l.join(", ")}),t.allErrors)r.if($,()=>{for(let I of l)(0,Ae.checkReportMissingProp)(n,I)});else r.if(c6._`${$} && (${(0,Ae.checkMissingProp)(n,l,e)})`),(0,Ae.reportMissingProp)(n,e),r.else()}}VA.validatePropertyDeps=KA;function BA(n,i=n.schema){let{gen:r,data:o,keyword:t,it:e}=n,u=r.name("valid");for(let l in i){if((0,DY.alwaysValidSchema)(e,i[l]))continue;r.if((0,Ae.propertyInData)(r,o,l,e.opts.ownProperties),()=>{let $=n.subschema({keyword:t,schemaProp:l},u);n.mergeValidEvaluated($,u)},()=>r.var(u,!0)),n.ok(u)}}VA.validateSchemaDeps=BA;VA.default=SY});var ZA=P((mA)=>{Object.defineProperty(mA,"__esModule",{value:!0});var EA=M(),dY=nn(),LY={message:"property name must be valid",params:({params:n})=>EA._`{propertyName: ${n.propertyName}}`},NY={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:LY,code(n){let{gen:i,schema:r,data:o,it:t}=n;if((0,dY.alwaysValidSchema)(t,r))return;let e=i.name("valid");i.forIn("key",o,(u)=>{n.setParams({propertyName:u}),n.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},e),i.if((0,EA.not)(e),()=>{if(n.error(!0),!t.allErrors)i.break()})}),n.ok(e)}};mA.default=NY});var U6=P((MA)=>{Object.defineProperty(MA,"__esModule",{value:!0});var gv=Ii(),Ai=M(),GY=Ti(),bv=nn(),jY={message:"must NOT have additional properties",params:({params:n})=>Ai._`{additionalProperty: ${n.additionalProperty}}`},WY={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:jY,code(n){let{gen:i,schema:r,parentSchema:o,data:t,errsCount:e,it:u}=n;if(!e)throw Error("ajv implementation error");let{allErrors:l,opts:$}=u;if(u.props=!0,$.removeAdditional!=="all"&&(0,bv.alwaysValidSchema)(u,r))return;let I=(0,gv.allSchemaProperties)(o.properties),g=(0,gv.allSchemaProperties)(o.patternProperties);b(),n.ok(Ai._`${e} === ${GY.default.errors}`);function b(){i.forIn("key",t,(k)=>{if(!I.length&&!g.length)c(k);else i.if(w(k),()=>c(k))})}function w(k){let d;if(I.length>8){let p=(0,bv.schemaRefOrVal)(u,o.properties,"properties");d=(0,gv.isOwnProperty)(i,p,k)}else if(I.length)d=(0,Ai.or)(...I.map((p)=>Ai._`${k} === ${p}`));else d=Ai.nil;if(g.length)d=(0,Ai.or)(d,...g.map((p)=>Ai._`${(0,gv.usePattern)(n,p)}.test(${k})`));return(0,Ai.not)(d)}function f(k){i.code(Ai._`delete ${t}[${k}]`)}function c(k){if($.removeAdditional==="all"||$.removeAdditional&&r===!1){f(k);return}if(r===!1){if(n.setParams({additionalProperty:k}),n.error(),!l)i.break();return}if(typeof r=="object"&&!(0,bv.alwaysValidSchema)(u,r)){let d=i.name("valid");if($.removeAdditional==="failing")S(k,d,!1),i.if((0,Ai.not)(d),()=>{n.reset(),f(k)});else if(S(k,d),!l)i.if((0,Ai.not)(d),()=>i.break())}}function S(k,d,p){let h={keyword:"additionalProperties",dataProp:k,dataPropType:bv.Type.Str};if(p===!1)Object.assign(h,{compositeRule:!0,createErrors:!1,allErrors:!1});n.subschema(h,d)}}};MA.default=WY});var xA=P((RA)=>{Object.defineProperty(RA,"__esModule",{value:!0});var HY=le(),zA=Ii(),D6=nn(),CA=U6(),XY={keyword:"properties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,parentSchema:o,data:t,it:e}=n;if(e.opts.removeAdditional==="all"&&o.additionalProperties===void 0)CA.default.code(new HY.KeywordCxt(e,CA.default,"additionalProperties"));let u=(0,zA.allSchemaProperties)(r);for(let b of u)e.definedProperties.add(b);if(e.opts.unevaluated&&u.length&&e.props!==!0)e.props=D6.mergeEvaluated.props(i,(0,D6.toHash)(u),e.props);let l=u.filter((b)=>!(0,D6.alwaysValidSchema)(e,r[b]));if(l.length===0)return;let $=i.name("valid");for(let b of l){if(I(b))g(b);else{if(i.if((0,zA.propertyInData)(i,t,b,e.opts.ownProperties)),g(b),!e.allErrors)i.else().var($,!0);i.endIf()}n.it.definedProperties.add(b),n.ok($)}function I(b){return e.opts.useDefaults&&!e.compositeRule&&r[b].default!==void 0}function g(b){n.subschema({keyword:"properties",schemaProp:b,dataProp:b},$)}}};RA.default=XY});var tO=P((iO)=>{Object.defineProperty(iO,"__esModule",{value:!0});var aA=Ii(),wv=M(),sA=nn(),nO=nn(),PY={keyword:"patternProperties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,data:o,parentSchema:t,it:e}=n,{opts:u}=e,l=(0,aA.allSchemaProperties)(r),$=l.filter((S)=>(0,sA.alwaysValidSchema)(e,r[S]));if(l.length===0||$.length===l.length&&(!e.opts.unevaluated||e.props===!0))return;let I=u.strictSchema&&!u.allowMatchingProperties&&t.properties,g=i.name("valid");if(e.props!==!0&&!(e.props instanceof wv.Name))e.props=(0,nO. Line truncated
`)}var Ct=(n)=>(i,r,o,t)=>{let e=o?{...o,async:!1}:{async:!1},u=i._zod.run({value:r,issues:[]},e);if(u instanceof Promise)throw new Ni;if(u.issues.length){let l=new(t?.Err??n)(u.issues.map(($)=>_n($,e,kn())));throw Me(l,t?.callee),l}return u.value},Io=Ct(Rn),Rt=(n)=>async(i,r,o,t)=>{let e=o?{...o,async:!0}:{async:!0},u=i._zod.run({value:r,issues:[]},e);if(u instanceof Promise)u=await u;if(u.issues.length){let l=new(t?.Err??n)(u.issues.map(($)=>_n($,e,kn())));throw Me(l,t?.callee),l}return u.value},go=Rt(Rn),xt=(n)=>(i,r,o)=>{let t=o?{...o,async:!1}:{async:!1},e=i._zod.run({value:r,issues:[]},t);if(e instanceof Promise)throw new Ni;return e.issues.length?{success:!1,error:new(n??lo)(e.issues.map((u)=>_n(u,t,kn())))}:{success:!0,data:e.value}},at=xt(Rn),st=(n)=>async(i,r,o)=>{let t=o?{...o,async:!0}:{async:!0},e=i._zod.run({value:r,issues:[]},t);if(e instanceof Promise)e=await e;return e.issues.length?{success:!1,error:new n(e.issues.map((u)=>_n(u,t,kn())))}:{success:!0,data:e.value}},bo=st(Rn),ze=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Ct(n)(i,r,t)},n0=ze(Rn),Ce=(n)=>(i,r,o)=>{return Ct(n)(i,r,o)},i0=Ce(Rn),Re=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Rt(n)(i,r,t)},t0=Re(Rn),xe=(n)=>async(i,r,o)=>{return Rt(n)(i,r,o)},r0=xe(Rn),ae=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return xt(n)(i,r,t)},o0=ae(Rn),se=(n)=>(i,r,o)=>{return xt(n)(i,r,o)},e0=se(Rn),nu=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return st(n)(i,r,t)},u0=nu(Rn),iu=(n)=>async(i,r,o)=>{return st(n)(i,r,o)},l0=iu(Rn);var oi={};pi(oi,{xid:()=>X$,uuid7:()=>nG,uuid6:()=>sy,uuid4:()=>ay,uuid:()=>yt,uppercase:()=>tI,unicodeEmail:()=>v0,undefined:()=>nI,ulid:()=>H$,time:()=>M$,string:()=>C$,sha512_hex:()=>kG,sha512_base64url:()=>LG,sha512_base64:()=>dG,sha384_hex:()=>SG,sha384_base64url:()=>OG,sha384_base64:()=>AG,sha256_hex:()=>cG,sha256_base64url:()=>DG,sha256_base64:()=>UG,sha1_hex:()=>bG,sha1_base64url:()=>fG,sha1_base64:()=>wG,rfc5322Email:()=>tG,number:()=>wo,null:()=>s$,nanoid:()=>P$,md5_hex:()=>$G,md5_base64url:()=>gG,md5_base64:()=>IG,mac:()=>V$,lowercase:()=>iI,ksuid:()=>h$,ipv6:()=>B$,ipv4:()=>K$,integer:()=>x$,idnEmail:()=>rG,httpProtocol:()=>E$,html5Email:()=>iG,hostname:()=>uG,hex:()=>vG,guid:()=>p$,extendedDuration:()=>xy,emoji:()=>F$,email:()=>Q$,e164:()=>m$,duration:()=>Y$,domain:()=>lG,datetime:()=>z$,date:()=>Z$,cuid2:()=>J$,cuid:()=>W$,cidrv6:()=>q$,cidrv4:()=>T$,browserEmail:()=>oG,boolean:()=>a$,bigint:()=>R$,base64url:()=>tu,base64:()=>_$});var W$=/^[cC][0-9a-z]{6,}$/,J$=/^[0-9a-z]+$/,H$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X$=/^[0-9a-vA-V]{20}$/,h$=/^[A-Za-z0-9]{27}$/,P$=/^[a-zA-Z0-9_-]{21}$/,Y$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xy=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,p$=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,yt=(n)=>{if(!n)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},ay=yt(4),sy=yt(6),nG=yt(7),Q$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,iG=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,tG=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,v0=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,rG=v0,oG=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,eG="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function F$(){return new RegExp(eG,"u")}var K$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B$=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,V$=(n)=>{let i=li(n??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},T$=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-Line truncated
`).filter((e)=>e),o=Math.min(...r.map((e)=>e.length-e.trimStart().length)),t=r.map((e)=>e.slice(o)).map((e)=>" ".repeat(this.indent*2)+e);for(let e of t)this.content.push(e)}compile(){let n=Function,i=this?.args,o=[...(this?.content??[""]).map((t)=>` ${t}`)];return new n(...i,o.join(`
`))}}var kI={major:4,minor:4,patch:3};var B=U("$ZodType",(n,i)=>{var r;n??(n={}),n._zod.def=i,n._zod.bag=n._zod.bag||{},n._zod.version=kI;let o=[...n._zod.def.checks??[]];if(n._zod.traits.has("$ZodCheck"))o.unshift(n);for(let t of o)for(let e of t._zod.onattach)e(n);if(o.length===0)(r=n._zod).deferred??(r.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let t=(u,l,$)=>{let I=ai(u),g;for(let b of l){if(b._zod.def.when){if(y$(u))continue;if(!b._zod.def.when(u))continue}else if(I)continue;let w=u.issues.length,f=b._zod.check(u);if(f instanceof Promise&&$?.async===!1)throw new Ni;if(g||f instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await f,u.issues.length===w)return;if(!I)I=ai(u,w)});else{if(u.issues.length===w)continue;if(!I)I=ai(u,w)}}if(g)return g.then(()=>{return u});return u},e=(u,l,$)=>{if(ai(u))return u.aborted=!0,u;let I=t(l,o,$);if(I instanceof Promise){if($.async===!1)throw new Ni;return I.then((g)=>n._zod.parse(g,$))}return n._zod.parse(I,$)};n._zod.run=(u,l)=>{if(l.skipChecks)return n._zod.parse(u,l);if(l.direction==="backward"){let I=n._zod.parse({value:u.value,issues:[]},{...l,skipChecks:!0});if(I instanceof Promise)return I.then((g)=>{return e(g,u,l)});return e(I,u,l)}let $=n._zod.parse(u,l);if($ instanceof Promise){if(l.async===!1)throw new Ni;return $.then((I)=>t(I,o,l))}return t($,o,l)}}z(n,"~standard",()=>({validate:(t)=>{try{let e=at(n,t);return e.success?{value:e.data}:{issues:e.error?.issues}}catch(e){return bo(n,t).then((u)=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Gt=U("$ZodString",(n,i)=>{B.init(n,i),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??C$(n._zod.bag),n._zod.parse=(r,o)=>{if(i.coerce)try{r.value=String(r.value)}catch(t){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:n}),r}}),$n=U("$ZodStringFormat",(n,i)=>{nr.init(n,i),Gt.init(n,i)}),LI=U("$ZodGUID",(n,i)=>{i.pattern??(i.pattern=p$),$n.init(n,i)}),NI=U("$ZodUUID",(n,i)=>{if(i.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[i.version];if(o===void 0)throw Error(`Invalid UUID version: "${i.version}"`);i.pattern??(i.pattern=yt(o))}else i.pattern??(i.pattern=yt());$n.init(n,i)}),yI=U("$ZodEmail",(n,i)=>{i.pattern??(i.pattern=Q$),$n.init(n,i)}),GI=U("$ZodURL",(n,i)=>{$n.init(n,i),n._zod.check=(r)=>{try{let o=r.value.trim();if(!i.normalize&&i.protocol?.source===E$.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:n,continue:!i.abort});return}}let t=new URL(o);if(i.hostname){if(i.hostname.lastIndex=0,!i.hostname.test(t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:i.hostname.source,input:r.value,inst:n,continue:!i.abort})}if(i.protocol){if(i.protocol.lastIndex=0,!i.protocol.test(t.protocol.endsWith(":")?t.protocol.slice(0,-1):t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:i.protocol.source,input:r.value,inst:n,continue:!i.abort})}if(i.normalize)r.value=t.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:n,continue:!i.abort})}}}),jI=U("$ZodEmoji",(n,i)=>{i.pattern??(i.pattern=F$()),$n.init(n,i)}),WI=U("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=P$),$n.init(n,i)}),JI=U("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=W$),$n.init(n,i)}),HI=U("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=J$),$n.init(n,i)}),XI=U("$ZodULID",(n,i)=>{i.pattern??(i.pattern=H$),$n.init(n,i)}),hI=U("$ZodXID",(n,i)=>{i.pattern??(i.pattern=X$),$n.init(n,i)}),PI=U("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=h$),$n.init(n,i)}),YI=U("$ZodISODateTime",(n,i)=>{i.pattern??(i.pattern=z$(i)),$n.init(n,i)}),pI=U("$ZodISODate",(n,i)=>{i.pattern??(i.pattern=Z$),$n.init(n,i)}),QI=U("$ZodISOTime",(n,i)=>{i.pattern??(i.pattern=M$(i)),$n.init(n,i)}),FI=U("$ZodISODuration",(n,i)=>{i.pattern??(i.pattern=Y$),$n.init(n,i)}),KI=U("$ZodIPv4",(n,i)=>{i.pattern??(i.pattern=K$),$n.init(n,i),n._zod.bag.format="ipv4"}),BI=U("$ZodIPv6",(n,i)=>{i.pattern??(i.pattern=B$),$n.init(n,i),n._zod.bag.format="ipv6",n._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:n,continue:!i.abort})}}}),VI=U("$ZodMAC",(n,i)=>{i.pattern??(i.pattern=V$(i.delimiter)),$n.init(n,i),n._zod.bag.format="mac"}),TI=U("$ZodCIDRv4",(n,i)=>{i.pattern??(i.pattern=T$),$n.init(n,i)}),qI=U("$ZodCIDRv6",(n,i)=>{i.pattern??(i.pattern=q$),$n.init(n,i),n._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[t,e]=o;if(!e)throw Error();let u=Number(e);if(`${u}`!==e)throw Error();if(u<0||u>128)throw Error();new URL(`http://[${t}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:n,continue:!i.abort})}}});function _I(n){if(n==="")return!0;if(/\s/.test(n))return!1;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}var Line truncated
if (${j}.issues.length) {
if (${L} in input) {
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
...iss,
path: iss.path ? [${G}, ...iss.path] : [${G}]
path: iss.path ? [${L}, ...iss.path] : [${L}]
})));
}
}
if (${y}.value === undefined) {
if (${G} in input) {
newResult[${G}] = undefined;
if (${j}.value === undefined) {
if (${L} in input) {
newResult[${L}] = undefined;
}
} else {
newResult[${G}] = ${y}.value;
newResult[${L}] = ${j}.value;
}
`);else if(!ni)f.write(`
const ${y}_present = ${G} in input;
if (${y}.issues.length) {
payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
`);else if(!x)f.write(`
const ${j}_present = ${L} in input;
if (${j}.issues.length) {
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
...iss,
path: iss.path ? [${G}, ...iss.path] : [${G}]
path: iss.path ? [${L}, ...iss.path] : [${L}]
})));
}
if (!${y}_present && !${y}.issues.length) {
if (!${j}_present && !${j}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${G}]
path: [${L}]
});
}
if (${y}_present) {
if (${y}.value === undefined) {
newResult[${G}] = undefined;
if (${j}_present) {
if (${j}.value === undefined) {
newResult[${L}] = undefined;
} else {
newResult[${G}] = ${y}.value;
newResult[${L}] = ${j}.value;
}
}
`);else f.write(`
if (${y}.issues.length) {
payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
if (${j}.issues.length) {
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
...iss,
path: iss.path ? [${G}, ...iss.path] : [${G}]
path: iss.path ? [${L}, ...iss.path] : [${L}]
})));
}
if (${y}.value === undefined) {
if (${G} in input) {
newResult[${G}] = undefined;
if (${j}.value === undefined) {
if (${L} in input) {
newResult[${L}] = undefined;
}
} else {
newResult[${G}] = ${y}.value;
newResult[${L}] = ${j}.value;
}
`)}f.write("payload.value = newResult;"),f.write("return payload;");let K=f.compile();return(F,y)=>K(w,F,y)},u,l=Nr,e=!Or.jitless,I=e&&I$.value,g=n.catchall,b;i._zod.parse=(w,f)=>{b??(b=o.value);let D=w.value;if(!l(D))return w.issues.push({expected:"object",code:"invalid_type",input:D,inst:i}),w;if(e&&I&&f?.async===!1&&f.jitless!==!0){if(!u)u=r(n.shape);if(w=u(w,f),!g)return w;return kD([],D,w,f,b,i)}return t(w,f)}});function eD(i,n,t,o){for(let u of i)if(u.issues.length===0)return n.value=u.value,n;let r=i.filter((u)=>!mn(u));if(r.length===1)return n.value=r[0].value,r[0];return n.issues.push({code:"invalid_union",input:n.value,inst:t,errors:i.map((u)=>u.issues.map((l)=>Zi(l,o,Oi())))}),n}var wo=U("$ZodUnion",(i,n)=>{_.init(i,n),h(i._zod,"optin",()=>n.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),h(i._zod,"optout",()=>n.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),h(i._zod,"values",()=>{if(n.options.every((o)=>o._zod.values))return new Set(n.options.flatMap((o)=>Array.from(o._zod.values)));return}),h(i._zod,"pattern",()=>{if(n.options.every((o)=>o._zod.pattern)){let o=n.options.map((r)=>r._zod.pattern);return new RegExp(`^(${o.map((r)=>st(r.source)).join("|")})$`)}return});let t=n.options.length===1?n.options[0]._zod.run:null;i._zod.parse=(o,r)=>{if(t)return t(o,r);let u=!1,l=[];for(let e of n.options){let $=e._zod.run({value:o.value,issues:[]},r);if($ instanceof Promise)l.push($),u=!0;else{if($.issues.length===0)return $;l.push($)}}if(!u)return eD(l,o,i,r);return Promise.all(l).then((e)=>{return eD(e,o,i,r)})}});function vD(i,n,t,o){let r=i.filter((u)=>u.issues.length===0);if(r.length===1)return n.value=r[0].value,n;if(r.length===0)n.issues.push({code:"invalid_union",input:n.value,inst:t,errors:i.map((u)=>u.issues.map((l)=>Zi(l,o,Oi())))});else n.issues.push({code:"invalid_union",input:n.value,inst:t,errors:[],inclusive:!1});return n}var aI=U("$ZodXor",(i,n)=>{wo.init(i,n),n.inclusive=!1;let t=n.options.length===1?n.options[0]._zod.run:null;i._zod.parse=(o,r)=>{if(t)return t(o,r);let u=!1,l=[];for(let e of n.options){let $=e._zod.run({value:o.value,issues:[]},r);if($ instanceof Promise)l.push($),u=!0;else l.push($)}if(!u)return vD(l,o,i,r);return Promise.all(l).then((e)=>{return vD(e,o,i,r)})}}),sI=U("$ZodDiscriminatedUnion",(i,n)=>{n.inclusive=!1,wo.init(i,n);let t=i._zod.parse;h(i._zod,"propValues",()=>{let r={};for(let u of n.options){let l=u._zod.propValues;if(!l||Object.keys(l).length===0)throw Error(`Invalid discriminated union option at index "${n.options.indexOf(u)}"`);for(let[e,$]of Object.entries(l)){if(!r[e])r[e]=new Set;for(let I of $)r[e].add(I)}}return r});let o=dr(()=>{let r=n.options,u=new Map;for(let l of r){let e=l._zod.propValues?.[n.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${n.options.indexOf(l)}"`);for(let $ of e){if(u.has($))throw Error(`Duplicate discriminator value "${String($)}"`);u.set($,l)}}return u});i._zod.parse=(r,u)=>{let l=r.value;if(!Nr(l))return r.issues.push({code:"invalid_type",expected:"object",input:l,inst:i}),r;let e=o.value.get(l?.[n.discriminator]);if(e)return e._zod.run(r,u);if(n.unionFallback||u.direction==="backward")return t(r,u);return r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:n.discriminator,options:Array.from(o.value.keys()),input:l,path:[n.discriminator],inst:i}),r}}),ig=U("$ZodIntersection",(i,n)=>{_.init(i,n),i._zod.parse=(t,o)=>{let r=t.value,u=n.left._zod.run({value:r,issues:[]},o),l=n.right._zod.run({value:r,issues:[]},o);if(u instanceof Promise||l instanceof Promise)return Promise.all([u,l]).then(([$,I])=>{return $D(t,$,I)});return $D(t,u,l)}});function wI(i,n){if(i===n)return{valid:!0,data:i};if(i instanceof Date&&n instanceof Date&&+i===+n)return{valid:!0,data:i};if(Cn(i)&&Cn(n)){let t=Object.keys(n),o=Object.keys(i).filter((u)=>t.indexOf(u)!==-1),r={...i,...n};for(let u of o){let l=wI(i[u],n[u]);if(!l.valid)return{valid:!1,mergeErrorPath:[u,...l.mergeErrorPath]};r[u]=l.data}return{valid:!0,data:r}}if(Array.isArray(i)&&Array.isArray(n)){if(i.length!==n.length)return{valid:!1,mergeErrorPath:[]};let t=[];for(let o=0;o<i.length;o++){let r=i[o],u=n[o],l=wI(r,u);if(!l.valid)return{valid:!1,mergeErrorPath:[o,...l.mergeErrorPath]};t.push(l.data)}return{valid:!0,data:t}}return{valid:!1,mergeErrorPath:[]}}function $D(i,n,t){let o=new Map,r;for(let e of n.issues)if(e.code==="unrecognized_keys"){r??(r=e);for(let $ of e.keys){if(!o.has($))o.set($,{});o.get($).l=!0}}else i.issues.push(e);for(let e of t.issues)if(e.code==="unrecognized_keys")for(let $ of e.keys){if(!o.has($))o.set($,{});o.get($).r=!0}else i.issues.push(e);let u=[...o].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(u.length&&r)i.issues.push({...r,keys:u});if(mn(i))return i;let l=wI(n.value,t.value);if(!l.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`);return i.value=l.data,i}var el=U("$ZodTuple",(i,n)=>{_.init(i,n Line truncated
`)}f.write("payload.value = newResult;"),f.write("return payload;");let p=f.compile();return(h,j)=>p(w,h,j)},e,u=Nt,l=!dt.jitless,I=l&&A$.value,g=i.catchall,b;n._zod.parse=(w,f)=>{b??(b=o.value);let c=w.value;if(!u(c))return w.issues.push({expected:"object",code:"invalid_type",input:c,inst:n}),w;if(l&&I&&f?.async===!1&&f.jitless!==!0){if(!e)e=t(i.shape);if(w=e(w,f),!g)return w;return X0([],c,w,f,b,n)}return r(w,f)}});function c0(n,i,r,o){for(let e of n)if(e.issues.length===0)return i.value=e.value,i;let t=n.filter((e)=>!ai(e));if(t.length===1)return i.value=t[0].value,t[0];return i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((e)=>e.issues.map((u)=>_n(u,o,kn())))}),i}var Do=U("$ZodUnion",(n,i)=>{B.init(n,i),z(n._zod,"optin",()=>i.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),z(n._zod,"optout",()=>i.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),z(n._zod,"values",()=>{if(i.options.every((o)=>o._zod.values))return new Set(i.options.flatMap((o)=>Array.from(o._zod.values)));return}),z(n._zod,"pattern",()=>{if(i.options.every((o)=>o._zod.pattern)){let o=i.options.map((t)=>t._zod.pattern);return new RegExp(`^(${o.map((t)=>ro(t.source)).join("|")})$`)}return});let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let e=!1,u=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)u.push($),e=!0;else{if($.issues.length===0)return $;u.push($)}}if(!e)return c0(u,o,n,t);return Promise.all(u).then((l)=>{return c0(l,o,n,t)})}});function U0(n,i,r,o){let t=n.filter((e)=>e.issues.length===0);if(t.length===1)return i.value=t[0].value,i;if(t.length===0)i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((e)=>e.issues.map((u)=>_n(u,o,kn())))});else i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:[],inclusive:!1});return i}var lg=U("$ZodXor",(n,i)=>{Do.init(n,i),i.inclusive=!1;let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let e=!1,u=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)u.push($),e=!0;else u.push($)}if(!e)return U0(u,o,n,t);return Promise.all(u).then((l)=>{return U0(l,o,n,t)})}}),vg=U("$ZodDiscriminatedUnion",(n,i)=>{i.inclusive=!1,Do.init(n,i);let r=n._zod.parse;z(n._zod,"propValues",()=>{let t={};for(let e of i.options){let u=e._zod.propValues;if(!u||Object.keys(u).length===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(e)}"`);for(let[l,$]of Object.entries(u)){if(!t[l])t[l]=new Set;for(let I of $)t[l].add(I)}}return t});let o=Mt(()=>{let t=i.options,e=new Map;for(let u of t){let l=u._zod.propValues?.[i.discriminator];if(!l||l.size===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(u)}"`);for(let $ of l){if(e.has($))throw Error(`Duplicate discriminator value "${String($)}"`);e.set($,u)}}return e});n._zod.parse=(t,e)=>{let u=t.value;if(!Nt(u))return t.issues.push({code:"invalid_type",expected:"object",input:u,inst:n}),t;let l=o.value.get(u?.[i.discriminator]);if(l)return l._zod.run(t,e);if(i.unionFallback||e.direction==="backward")return r(t,e);return t.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:i.discriminator,options:Array.from(o.value.keys()),input:u,path:[i.discriminator],inst:n}),t}}),$g=U("$ZodIntersection",(n,i)=>{B.init(n,i),n._zod.parse=(r,o)=>{let t=r.value,e=i.left._zod.run({value:t,issues:[]},o),u=i.right._zod.run({value:t,issues:[]},o);if(e instanceof Promise||u instanceof Promise)return Promise.all([e,u]).then(([$,I])=>{return D0(r,$,I)});return D0(r,e,u)}});function dI(n,i){if(n===i)return{valid:!0,data:n};if(n instanceof Date&&i instanceof Date&&+n===+i)return{valid:!0,data:n};if(xi(n)&&xi(i)){let r=Object.keys(i),o=Object.keys(n).filter((e)=>r.indexOf(e)!==-1),t={...n,...i};for(let e of o){let u=dI(n[e],i[e]);if(!u.valid)return{valid:!1,mergeErrorPath:[e,...u.mergeErrorPath]};t[e]=u.data}return{valid:!0,data:t}}if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<n.length;o++){let t=n[o],e=i[o],u=dI(t,e);if(!u.valid)return{valid:!1,mergeErrorPath:[o,...u.mergeErrorPath]};r.push(u.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function D0(n,i,r){let o=new Map,t;for(let l of i.issues)if(l.code==="unrecognized_keys"){t??(t=l);for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).l=!0}}else n.issues.push(l);for(let l of r.issues)if(l.code==="unrecognized_keys")for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).r=!0}else n.issues.push(l);let e=[...o].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(e.length&&t)n.issues.push({...t,keys:e});if(ai(n))return n;let u=dI(i.value,r.value);if(!u.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return n.value=u.data,n}var bu=U("$ZodTuple",(n,i)=>{B.init(n,i Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of i.seen.entries()){let e=l[1];if(n===l[0]){u(l);continue}if(i.external){let I=i.external.registry.get(l[0])?.id;if(n!==l[0]&&I){u(l);continue}}if(i.metadataRegistry.get(l[0])?.id){u(l);continue}if(e.cycle){u(l);continue}if(e.count>1){if(i.reused==="ref"){u(l);continue}}}}function ir(i,n){let t=i.seen.get(n);if(!t)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(e)=>{let $=i.seen.get(e);if($.ref===null)return;let I=$.def??$.schema,g={...I},b=$.ref;if($.ref=null,b){o(b);let f=i.seen.get(b),D=f.schema;if(D.$ref&&(i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"))I.allOf=I.allOf??[],I.allOf.push(D);else Object.assign(I,D);if(Object.assign(I,g),e._zod.parent===b)for(let N in I){if(N==="$ref"||N==="allOf")continue;if(!(N in g))delete I[N]}if(D.$ref&&f.def)for(let N in I){if(N==="$ref"||N==="allOf")continue;if(N in f.def&&JSON.stringify(I[N])===JSON.stringify(f.def[N]))delete I[N]}}let w=e._zod.parent;if(w&&w!==b){o(w);let f=i.seen.get(w);if(f?.schema.$ref){if(I.$ref=f.schema.$ref,f.def)for(let D in I){if(D==="$ref"||D==="allOf")continue;if(D in f.def&&JSON.stringify(I[D])===JSON.stringify(f.def[D]))delete I[D]}}}i.override({zodSchema:e,jsonSchema:I,path:$.path??[]})};for(let e of[...i.seen.entries()].reverse())o(e[0]);let r={};if(i.target==="draft-2020-12")r.$schema="https://json-schema.org/draft/2020-12/schema";else if(i.target==="draft-07")r.$schema="http://json-schema.org/draft-07/schema#";else if(i.target==="draft-04")r.$schema="http://json-schema.org/draft-04/schema#";else if(i.target==="openapi-3.0");if(i.external?.uri){let e=i.external.registry.get(n)?.id;if(!e)throw Error("Schema is missing an `id` property");r.$id=i.external.uri(e)}Object.assign(r,t.def??t.schema);let u=i.metadataRegistry.get(n)?.id;if(u!==void 0&&r.id===u)delete r.id;let l=i.external?.defs??{};for(let e of i.seen.entries()){let $=e[1];if($.def&&$.defId){if($.def.id===$.defId)delete $.def.id;l[$.defId]=$.def}}if(i.external);else if(Object.keys(l).length>0)if(i.target==="draft-2020-12")r.$defs=l;else r.definitions=l;try{let e=JSON.parse(JSON.stringify(r));return Object.defineProperty(e,"~standard",{value:{...n["~standard"],jsonSchema:{input:bt(n,"input",i.processors),output:bt(n,"output",i.processors)}},enumerable:!1,writable:!1}),e}catch(e){throw Error("Error converting schema to JSON.")}}function di(i,n){let t=n??{seen:new Set};if(t.seen.has(i))return!1;t.seen.add(i);let o=i._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return di(o.element,t);if(o.type==="set")return di(o.valueType,t);if(o.type==="lazy")return di(o.getter(),t);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return di(o.innerType,t);if(o.type==="intersection")return di(o.left,t)||di(o.right,t);if(o.type==="record"||o.type==="map")return di(o.keyType,t)||di(o.valueType,t);if(o.type==="pipe"){if(i._zod.traits.has("$ZodCodec"))return!0;return di(o.in,t)||di(o.out,t)}if(o.type==="object"){for(let r in o.shape)if(di(o.shape[r],t))return!0;return!1}if(o.type==="union"){for(let r of o.options)if(di(r,t))return!0;return!1}if(o.type==="tuple"){for(let r of o.items)if(di(r,t))return!0;if(o.rest&&di(o.rest,t))return!0;return!1}return!1}var lw=(i,n={})=>(t)=>{let o=an({...t,processors:n});return oi(i,o),sn(o,i),ir(o,i)},bt=(i,n,t={})=>(o)=>{let{libraryOptions:r,target:u}=o??{},l=an({...r??{},target:u,io:n,processors:t});return oi(i,l),sn(l,i),ir(l,i)};var Yy={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ew=(i,n,t,o)=>{let r=t;r.type="string";let{minimum:u,maximum:l,format:e,patterns:$,contentEncoding:I}=i._zod.bag;if(typeof u==="number")r.minLength=u;if(typeof l==="number")r.maxLength=l;if(e){if(r.format=Yy[e]??e,r.format==="")delete r.format;if(e==="time")delete r.format}if(I)r.contentEncoding=I;if($&&$.size>0){let g=[...$];if(g.length===1)r.pattern=g[0].source;else if(g.length>1)r.allOf=[...g.map((b)=>({...n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))]}},vw=(i,n,t,o)=>{let r=t,{minimum:u,maximum:l,format:e,multipleOf:$,exclusiveMaximum:I,exclusiveMinimum:g}=i._zod.bag;if(typeof e==="string"&&e.includes("int"))r.type="integer";else r.type="number";let b=typeof g==="number"&&g>=(u??Number.NEGATIVE_INFINITY),w=typeof I==="number"&&I<=(l??Number.POSITIVE_INFINITY),f=n.target==="draft-04"||n.target==="openapi-3.0";if(b)if(f)r.minimum=g,r.exclusiveMinimum=!0;else r.exclusiveMinimum=g;else if(typeof u==="number")r.minimum=u;if(w)if(f)r.maximum=I,r.exclusiveMaximum=!0;else r.exclusiveMaximum=I;else if(typeof l==="number")r.maximum=l;if(typeof $==="number")r.multipleOf=$},$w=(i,n,t,o)=>{t.type="boolean"},Iw=(i,n,t,o)=>{if(n.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},gw=(i,n,t,o)=>{if(n.unrepresentable==="Line truncated
`);if(i===-1)return null;let n=this._buffer.toString("utf8",0,i).replace(/\r$/,"");return this._buffer=this._buffer.subarray(i+1),aH(n)}clear(){this._buffer=void 0}}function aH(i){return i1.parse(JSON.parse(i))}function RA(i){return JSON.stringify(i)+`
`}class j4{constructor(i=xA.stdin,n=xA.stdout){this._stdin=i,this._stdout=n,this._readBuffer=new G4,this._started=!1,this._ondata=(t)=>{this._readBuffer.append(t),this.processReadBuffer()},this._onerror=(t)=>{this.onerror?.(t)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let i=this._readBuffer.readMessage();if(i===null)break;this.onmessage?.(i)}catch(i){this.onerror?.(i)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(i){return new Promise((n)=>{let t=RA(i);if(this._stdout.write(t))n();else this._stdout.once("drain",n)})}}import{dirname as H0,join as e3}from"node:path";import{fileURLToPath as v3}from"node:url";class Zn extends Error{name="KyError";get isKyError(){return!0}}class rn extends Zn{name="HTTPError";response;request;options;data;constructor(i,n,t){let o=i.status||i.status===0?i.status:"",r=i.statusText??"",u=`${o} ${r}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${n.method} ${n.url}`);this.response=i,this.request=n,this.options=t}}class Su extends Zn{name="NetworkError";request;constructor(i,n){super(`Request failed due to a network error: ${i.method} ${i.url}`,n);this.request=i}}class Ou extends Error{name="NonError";value;constructor(i){let n="Non-error value was thrown";try{if(typeof i==="string")n=i;else if(i&&typeof i==="object"&&"message"in i&&typeof i.message==="string")n=i.message}catch{}super(n);this.value=i}}class _t extends Zn{name="ForceRetryError";customDelay;code;customRequest;constructor(i){let n=i?.cause?i.cause instanceof Error?i.cause:new Ou(i.cause):void 0;super(i?.code?`Forced retry: ${i.code}`:"Forced retry",n?{cause:n}:void 0);this.customDelay=i?.delay,this.code=i?.code,this.customRequest=i?.request}}class W4 extends Error{name="SchemaValidationError";issues;constructor(i){super("Response schema validation failed");this.issues=i}}class An extends Zn{name="TimeoutError";request;constructor(i){super(`Request timed out: ${i.method} ${i.url}`);this.request=i}}var y4=(()=>{let i=!1,n=!1,t=typeof globalThis.ReadableStream==="function",o=typeof globalThis.Request==="function";if(t&&o)try{n=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return i=!0,"half"}}).headers.has("Content-Type")}catch(r){if(r instanceof Error&&r.message==="unsupported BodyInit type")return!1;throw r}return i&&!n})(),aA=typeof globalThis.AbortController==="function",wv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",sA=typeof globalThis.ReadableStream==="function",iN=typeof globalThis.FormData==="function",fv=["get","post","put","patch","head","delete"],sH=()=>{return};sH();var nN={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},qt=2147483647,rN=40,Dv=Symbol("stop");class Uv{options;constructor(i){this.options=i}}var tN=(i)=>new Uv(i),oN={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},uN={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var cv=new TextEncoder,iF=(i)=>{if(!i)return 0;if(i instanceof FormData){let n=0;for(let[t,o]of i)n+=rN,n+=cv.encode(`Content-Disposition: form-data; name="${t}"`).byteLength,n+=typeof o==="string"?cv.encode(o).byteLength:o.size;return n}if(i instanceof Blob)return i.size;if(i instanceof ArrayBuffer||ArrayBuffer.isView(i))return i.byteLength;if(typeof i==="string")return cv.encode(i).byteLength;if(i instanceof URLSearchParams)return cv.encode(i.toString()).byteLength;return 0},lN=(i,n,t)=>{let o,r=0;return i.pipeThrough(new TransformStream({transform(u,l){if(l.enqueue(u),o){r+=o.byteLength;let e=n===0?0:r/n;if(e>=1)e=1-Number.EPSILON;t?.({percent:e,totalBytes:Math.max(n,r),transferredBytes:r},o)}o=u},flush(){if(o)r+=o.byteLength,t?.({percent:1,totalBytes:Math.max(n,r),transferredBytes:r},o)}}))},eN=(i,n)=>{if(!i.body)return i;let t={status:i.status,statusText:i.statusText,headers:i.headers};if(i.status===204)return new Response(null,t);let o=Math.max(0,Number(i.headers.get("content-length"))||0);return new Response(lN(i.body,o,n),t)},vN=(i,n,t)=>{if(!i.body)return i;let o=iF(t??i.body);return new Request(i,{duplex:"half",body:lN(i.body,o,n)})};var Yn=(i)=>i!==null&&typeof i==="object";var nF=Symbol("replaceOption"),J4=(i)=>Yn(i)&&i[nF]===!0?{isReplace:!0,value:i.value}:{isReplace:!1,value:i};var Nu=(...i)=>{for(let n of i)if((!Yn(n)| Line truncated
`,{mode:384}),n}function zt(i,n,t=[]){let o=n.corpId?.trim()||void 0,r=n.stateful?n.defaultCorpId?.trim()||void 0:void 0,u=o??r;if(u){let e=i.find(($)=>$.id===u);if(e)return e;throw Error(`No enterprise config found for ${u}`)}if(!n.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let l=i[0];if(l)return l;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(t.length?t.join(", "):"the configured enterprise directories"))}import{readFileSync as YK}from"node:fs";import{randomBytes as PK}from"node:crypto";import{randomBytes as wL}from"node:crypto";var CF=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),mF=v.object({id:v.string(),tenantId:v.string(),name:v.string(),isAdmin:v.boolean().default(!1),permissions:v.array(v.string()).default([]),providerUserId:v.string().optional(),hosecloudStaff:CF.optional()}),RF=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),xF=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:RF.optional()}),zN=v.object({user:mF,tenant:xF}),aF=v.object({id:v.string(),name:v.string(),email:v.string().nullable().optional(),emailVerified:v.boolean().optional(),image:v.string().nullable().optional(),tenantId:v.string().optional(),provider:v.string().optional(),providerUserId:v.string().optional(),mobile:v.string().nullable().optional(),status:v.string().optional(),permissions:v.array(v.string()).default([]),isAdmin:v.boolean().default(!1),hosecloudStaff:v.unknown().optional()}).passthrough(),sF=v.object({id:v.string(),token:v.string().optional(),expiresAt:v.string(),createdAt:v.string().optional(),updatedAt:v.string().optional(),ipAddress:v.string().optional(),userAgent:v.string().optional(),userId:v.string(),delegationId:v.string().nullable().optional()}).passthrough(),pN=v.object({user:aF,session:sF}),Yv=v.object({id:v.string(),tenantId:v.string().optional(),code:v.number().optional(),description:v.string(),scope:v.string(),strictness:v.string(),status:v.string().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional()}),hN=v.object({rules:v.array(Yv),hasPendingDeletes:v.boolean().default(!1)}),iK=v.object({code:v.string().optional(),description:v.string(),scope:v.string(),strictness:v.string()}),Pv=v.object({id:v.string(),tenantId:v.string().optional(),versionNumber:v.number(),versionName:v.string().nullable().optional(),publishedBy:v.string().nullable().optional(),publishedByName:v.string().nullable().optional(),rules:v.array(iK).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),CN=v.object({version:Pv,rulesCount:v.number()}),Wu=v.object({id:v.string(),tenantId:v.string().optional(),title:v.string(),purpose:v.string().default(""),contentType:v.string().default("policy"),content:v.string(),status:v.string().default("published"),enabled:v.boolean().default(!0),scenarios:v.array(v.string()).default([]),tags:v.array(v.string()).default([]),category:v.string().nullable().optional(),categoryTags:v.array(v.string()).default([]),createdBy:v.string().nullable().optional(),createdByName:v.string().nullable().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional(),updatedBy:v.string().nullable().optional(),updatedByName:v.string().nullable().optional(),isDeleted:v.boolean().default(!1)}),mN=v.object({articles:v.array(Wu),total:v.number().optional()}),nK=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),rK=v.object({type:v.string(),signKey:v.string().optional(),outboundName:v.string().optional(),mode:v.string().optional(),autoApprovalRate:v.number().optional(),apiKey:v.string().optional(),apiSecret:v.string().optional(),apiOrigin:v.string().optional(),corporationId:v.string().optional(),ebotSignKey:v.string().optional(),completionSignKey:v.string().optional(),outboundMessageId:v.string().optional(),completionMessageId:v.string().optional()}).passthrough(),tK=v.enum(["assisted","semi_automatic","fully_automatic"]),dN=v.object({id:v.string(),url:v.string().url()}).passthrough(),yu=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:tK,incomingDocumentWebhook:dN,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:dN,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),p4=v.object({id:v.string().optional(),tenantId:v.string().optional(),tone:v.string().optional(),language:v.string().optional(),detailLevel:v.string().optional(),outputFormat:v.string().optional(),examples:v.array(v.string()).default([]),prohibitedPhrases:v.array(v.string()).default([]),cus Line truncated
`);return{recordId:i.id,sourceDocumentSN:i.sourceDocumentSN,sourceDocumentId:i.sourceDocumentId,document:Dr({id:n?.id,sn:n?.sn??n?.sourceDocumentSN??i.sourceDocumentSN,title:n?.title??n?.name,template:Zv(n,["template.name","templateName","form.name","formName","formTitle"]),amount:qv(t,["金额","报销金额","付款金额","合计","价税合计"])??Zv(n,["amount","totalAmount","expenseAmount"]),expenseType:qv(t,["费用类型","费用类别","报销类型"]),costCompany:qv(t,["费用承担公司","承担公司","成本中心","费用归属"]),payee:qv(t,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:t.slice(0,30)}),invoices:mK(i),attachments:Ak(i,{summary:!0}).attachments,aiResult:dv(i),manualResult:qr(i)?.value,hints:Dr({amountMentions:vk(o,["金额","合计","税率"],8),partyMentions:vk(o,["买方","卖方","甲方","乙方","收款"],8)})}}function Ak(i,n={}){let t=[["document",i.document],["result",i.result],["pipelineData",i.pipelineData],["sourceExtendData",i.sourceExtendData]],o=[],r=new Set;for(let[u,l]of t)I0(l,u,o,r);return{recordId:i.id,sourceDocumentSN:i.sourceDocumentSN,sourceDocumentId:i.sourceDocumentId,count:o.length,attachments:n.summary?o.map((u)=>Dr({path:u.path,kind:u.kind,fileName:u.fileName,mimeType:u.mimeType,fileId:u.fileId,sourceField:u.sourceField})):o}}function MK(i){let n=[["result.citedRules",Mn(i,"result.citedRules")],["result.matchedRules",Mn(i,"result.matchedRules")],["result.ruleResults",Mn(i,"result.ruleResults")],["result.rules",Mn(i,"result.rules")],["pipelineData.citedRules",Mn(i,"pipelineData.citedRules")],["pipelineData.matchedRules",Mn(i,"pipelineData.matchedRules")]],t=[],o=new Set;for(let[r,u]of n)(Array.isArray(u)?u:u&&typeof u==="object"?Object.values(u):[]).forEach((e,$)=>{let I=ht(e);if(!I)return;let g=E(I.runtimeRuleId)??E(I.runtimeId)??E(I.id)??E(I.ruleId),b=E(I.ruleCode)??E(I.code)??(g?aK(g):void 0),w=Dr({runtimeRuleId:g,ruleCode:b,versionNumber:hK(I.versionNumber)??i.ruleSetVersionNumber,scope:E(I.scope),strictness:E(I.strictness),appliedAnalysis:I.appliedAnalysis??I.analysis??I.reasoning,checkResult:I.checkResult??I.result??I.decision,findings:I.findings??I.riskPoints??I.evidence,sourcePath:`${r}.${$}`}),f=JSON.stringify(w);if(!o.has(f))o.add(f),t.push(w)});return{recordId:i.id,sourceDocumentSN:i.sourceDocumentSN,sourceDocumentId:i.sourceDocumentId,ruleSetVersionNumber:i.ruleSetVersionNumber,count:t.length,rules:t}}function I0(i,n,t,o){if(Array.isArray(i)){i.forEach((u,l)=>I0(u,`${n}.${l}`,t,o));return}let r=ht(i);if(!r)return;if(dK(r,n)){let u=Dr({path:n,fieldPath:n,kind:zK(n,r),fileName:E(r.fileName)??E(r.filename)??E(r.name)??E(r.originalName),mimeType:E(r.mimeType)??E(r.mimetype)??E(r.contentType),fileId:E(r.fileId)??E(r.id)??E(r.attachmentId),ossPath:E(r.ossPath)??E(r.ossKey)??E(r.key),url:E(r.url)??E(r.signedUrl)??E(r.downloadUrl)??E(r.previewUrl),invoiceId:E(r.invoiceId),sourceField:E(r.fieldName)??E(r.label)}),l=JSON.stringify(u);if(!o.has(l))o.add(l),t.push(u)}for(let[u,l]of Object.entries(r))I0(l,`${n}.${u}`,t,o)}function dK(i,n){let t=Object.keys(i).map((u)=>u.toLowerCase());return/(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(n)&&["filename","fileName","mimeType","mimetype","contentType","fileId","ossPath","signedUrl","downloadUrl","previewUrl","attachmentId"].some((u)=>t.includes(u.toLowerCase()))}function zK(i,n){let t=`${i} ${E(n.type)??""}`.toLowerCase();if(t.includes("invoice")||t.includes("发票"))return"invoice";if(t.includes("receipt"))return"receipt";return"attachment"}function Zv(i,n){if(!i)return;for(let t of n){let o=Mn(i,t);if(o!==void 0)return o}return}function ek(i,n){if(!i)return 0;for(let t of n){let o=Mn(i,t);if(Array.isArray(o))return o.length;if(o&&typeof o==="object")return Object.keys(o).length;if(typeof o==="number")return o}return 0}function Mn(i,n){return n.split(".").reduce((t,o)=>{if(t===void 0||t===null)return;if(Array.isArray(t)){let r=Number(o);return Number.isInteger(r)?t[r]:void 0}if(typeof t==="object")return t[o];return},i)}function pK(i,n,t){let o=n.split("."),r=i;for(let u of o.slice(0,-1)){let l=r[u];if(!l||typeof l!=="object"||Array.isArray(l))r[u]={};r=r[u]}r[o[o.length-1]??n]=t}function Dr(i){return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function ht(i){return i&&typeof i==="object"&&!Array.isArray(i)?i:void 0}function hK(i){return typeof i==="number"&&Number.isFinite(i)?i:void 0}function CK(i){let n=[];return g0(i,"document",n),n}function g0(i,n,t){if(Array.isArray(i)){i.forEach((l,e)=>g0(l,`${n}.${e}`,t));return}let o=ht(i);if(!o)return;let r=E(o.label)??E(o.name)??E(o.title)??E(o.fieldName),u=o.value??o.displayValue??o.text??o.content;if(r&&u!==void 0&&typeof u!=="object")t.push(Dr({path:n,label:r,value:u,type:E(o.type)??E(o.fieldType)}));for(let[l,e]of Object.entries(o)){if(l==="attachments")continue;g0(e,`${n}.${l}`,t)}}function qv(i,n){return i.find((o)=>{let r=E(o.label)??"";return n.some((u)=>r.includes(u)) Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of n.seen.entries()){let l=u[1];if(i===u[0]){e(u);continue}if(n.external){let I=n.external.registry.get(u[0])?.id;if(i!==u[0]&&I){e(u);continue}}if(n.metadataRegistry.get(u[0])?.id){e(u);continue}if(l.cycle){e(u);continue}if(l.count>1){if(n.reused==="ref"){e(u);continue}}}}function rt(n,i){let r=n.seen.get(i);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(l)=>{let $=n.seen.get(l);if($.ref===null)return;let I=$.def??$.schema,g={...I},b=$.ref;if($.ref=null,b){o(b);let f=n.seen.get(b),c=f.schema;if(c.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0"))I.allOf=I.allOf??[],I.allOf.push(c);else Object.assign(I,c);if(Object.assign(I,g),l._zod.parent===b)for(let k in I){if(k==="$ref"||k==="allOf")continue;if(!(k in g))delete I[k]}if(c.$ref&&f.def)for(let k in I){if(k==="$ref"||k==="allOf")continue;if(k in f.def&&JSON.stringify(I[k])===JSON.stringify(f.def[k]))delete I[k]}}let w=l._zod.parent;if(w&&w!==b){o(w);let f=n.seen.get(w);if(f?.schema.$ref){if(I.$ref=f.schema.$ref,f.def)for(let c in I){if(c==="$ref"||c==="allOf")continue;if(c in f.def&&JSON.stringify(I[c])===JSON.stringify(f.def[c]))delete I[c]}}}n.override({zodSchema:l,jsonSchema:I,path:$.path??[]})};for(let l of[...n.seen.entries()].reverse())o(l[0]);let t={};if(n.target==="draft-2020-12")t.$schema="https://json-schema.org/draft/2020-12/schema";else if(n.target==="draft-07")t.$schema="http://json-schema.org/draft-07/schema#";else if(n.target==="draft-04")t.$schema="http://json-schema.org/draft-04/schema#";else if(n.target==="openapi-3.0");if(n.external?.uri){let l=n.external.registry.get(i)?.id;if(!l)throw Error("Schema is missing an `id` property");t.$id=n.external.uri(l)}Object.assign(t,r.def??r.schema);let e=n.metadataRegistry.get(i)?.id;if(e!==void 0&&t.id===e)delete t.id;let u=n.external?.defs??{};for(let l of n.seen.entries()){let $=l[1];if($.def&&$.defId){if($.def.id===$.defId)delete $.def.id;u[$.defId]=$.def}}if(n.external);else if(Object.keys(u).length>0)if(n.target==="draft-2020-12")t.$defs=u;else t.definitions=u;try{let l=JSON.parse(JSON.stringify(t));return Object.defineProperty(l,"~standard",{value:{...i["~standard"],jsonSchema:{input:cr(i,"input",n.processors),output:cr(i,"output",n.processors)}},enumerable:!1,writable:!1}),l}catch(l){throw Error("Error converting schema to JSON.")}}function mn(n,i){let r=i??{seen:new Set};if(r.seen.has(n))return!1;r.seen.add(n);let o=n._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return mn(o.element,r);if(o.type==="set")return mn(o.valueType,r);if(o.type==="lazy")return mn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return mn(o.innerType,r);if(o.type==="intersection")return mn(o.left,r)||mn(o.right,r);if(o.type==="record"||o.type==="map")return mn(o.keyType,r)||mn(o.valueType,r);if(o.type==="pipe"){if(n._zod.traits.has("$ZodCodec"))return!0;return mn(o.in,r)||mn(o.out,r)}if(o.type==="object"){for(let t in o.shape)if(mn(o.shape[t],r))return!0;return!1}if(o.type==="union"){for(let t of o.options)if(mn(t,r))return!0;return!1}if(o.type==="tuple"){for(let t of o.items)if(mn(t,r))return!0;if(o.rest&&mn(o.rest,r))return!0;return!1}return!1}var cw=(n,i={})=>(r)=>{let o=it({...r,processors:i});return un(n,o),tt(o,n),rt(o,n)},cr=(n,i,r={})=>(o)=>{let{libraryOptions:t,target:e}=o??{},u=it({...t??{},target:e,io:i,processors:r});return un(n,u),tt(u,n),rt(u,n)};var mj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Uw=(n,i,r,o)=>{let t=r;t.type="string";let{minimum:e,maximum:u,format:l,patterns:$,contentEncoding:I}=n._zod.bag;if(typeof e==="number")t.minLength=e;if(typeof u==="number")t.maxLength=u;if(l){if(t.format=mj[l]??l,t.format==="")delete t.format;if(l==="time")delete t.format}if(I)t.contentEncoding=I;if($&&$.size>0){let g=[...$];if(g.length===1)t.pattern=g[0].source;else if(g.length>1)t.allOf=[...g.map((b)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))]}},Dw=(n,i,r,o)=>{let t=r,{minimum:e,maximum:u,format:l,multipleOf:$,exclusiveMaximum:I,exclusiveMinimum:g}=n._zod.bag;if(typeof l==="string"&&l.includes("int"))t.type="integer";else t.type="number";let b=typeof g==="number"&&g>=(e??Number.NEGATIVE_INFINITY),w=typeof I==="number"&&I<=(u??Number.POSITIVE_INFINITY),f=i.target==="draft-04"||i.target==="openapi-3.0";if(b)if(f)t.minimum=g,t.exclusiveMinimum=!0;else t.exclusiveMinimum=g;else if(typeof e==="number")t.minimum=e;if(w)if(f)t.maximum=I,t.exclusiveMaximum=!0;else t.exclusiveMaximum=I;else if(typeof u==="number")t.maximum=u;if(typeof $==="number")t.multipleOf=$},Sw=(n,i,r,o)=>{r.type="boolean"},Aw=(n,i,r,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Ow=(n,i,r,o)=>{if(i.unrepresentable==="Line truncated
`);if(n===-1)return null;let i=this._buffer.toString("utf8",0,n).replace(/\r$/,"");return this._buffer=this._buffer.subarray(n+1),w7(i)}clear(){this._buffer=void 0}}function w7(n){return vD.parse(JSON.parse(n))}function ok(n){return JSON.stringify(n)+`
`}class Y6{constructor(n=ek.stdin,i=ek.stdout){this._stdin=n,this._stdout=i,this._readBuffer=new P6,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let n=this._readBuffer.readMessage();if(n===null)break;this.onmessage?.(n)}catch(n){this.onerror?.(n)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(n){return new Promise((i)=>{let r=ok(n);if(this._stdout.write(r))i();else this._stdout.once("drain",i)})}}import{dirname as q4,join as JF}from"node:path";import{fileURLToPath as HF}from"node:url";class Ei extends Error{name="KyError";get isKyError(){return!0}}class ti extends Ei{name="HTTPError";response;request;options;data;constructor(n,i,r){let o=n.status||n.status===0?n.status:"",t=n.statusText??"",e=`${o} ${t}`.trim(),u=e?`status code ${e}`:"an unknown error";super(`Request failed with ${u}: ${i.method} ${i.url}`);this.response=n,this.request=i,this.options=r}}class de extends Ei{name="NetworkError";request;constructor(n,i){super(`Request failed due to a network error: ${n.method} ${n.url}`,i);this.request=n}}class Le extends Error{name="NonError";value;constructor(n){let i="Non-error value was thrown";try{if(typeof n==="string")i=n;else if(n&&typeof n==="object"&&"message"in n&&typeof n.message==="string")i=n.message}catch{}super(i);this.value=n}}class qr extends Ei{name="ForceRetryError";customDelay;code;customRequest;constructor(n){let i=n?.cause?n.cause instanceof Error?n.cause:new Le(n.cause):void 0;super(n?.code?`Forced retry: ${n.code}`:"Forced retry",i?{cause:i}:void 0);this.customDelay=n?.delay,this.code=n?.code,this.customRequest=n?.request}}class p6 extends Error{name="SchemaValidationError";issues;constructor(n){super("Response schema validation failed");this.issues=n}}class ki extends Ei{name="TimeoutError";request;constructor(n){super(`Request timed out: ${n.method} ${n.url}`);this.request=n}}var Q6=(()=>{let n=!1,i=!1,r=typeof globalThis.ReadableStream==="function",o=typeof globalThis.Request==="function";if(r&&o)try{i=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type")}catch(t){if(t instanceof Error&&t.message==="unsupported BodyInit type")return!1;throw t}return n&&!i})(),uk=typeof globalThis.AbortController==="function",Sv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",lk=typeof globalThis.ReadableStream==="function",vk=typeof globalThis.FormData==="function",Av=["get","post","put","patch","head","delete"],f7=()=>{return};f7();var $k={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},_r=2147483647,Ik=40,Ov=Symbol("stop");class kv{options;constructor(n){this.options=n}}var gk=(n)=>new kv(n),bk={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},wk={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var dv=new TextEncoder,c7=(n)=>{if(!n)return 0;if(n instanceof FormData){let i=0;for(let[r,o]of n)i+=Ik,i+=dv.encode(`Content-Disposition: form-data; name="${r}"`).byteLength,i+=typeof o==="string"?dv.encode(o).byteLength:o.size;return i}if(n instanceof Blob)return n.size;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return n.byteLength;if(typeof n==="string")return dv.encode(n).byteLength;if(n instanceof URLSearchParams)return dv.encode(n.toString()).byteLength;return 0},fk=(n,i,r)=>{let o,t=0;return n.pipeThrough(new TransformStream({transform(e,u){if(u.enqueue(e),o){t+=o.byteLength;let l=i===0?0:t/i;if(l>=1)l=1-Number.EPSILON;r?.({percent:l,totalBytes:Math.max(i,t),transferredBytes:t},o)}o=e},flush(){if(o)t+=o.byteLength,r?.({percent:1,totalBytes:Math.max(i,t),transferredBytes:t},o)}}))},ck=(n,i)=>{if(!n.body)return n;let r={status:n.status,statusText:n.statusText,headers:n.headers};if(n.status===204)return new Response(null,r);let o=Math.max(0,Number(n.headers.get("content-length"))||0);return new Response(fk(n.body,o,i),r)},Uk=(n,i,r)=>{if(!n.body)return n;let o=c7(r??n.body);return new Request(n,{duplex:"half",body:fk(n.body,o,i)})};var Xi=(n)=>n!==null&&typeof n==="object";var U7=Symbol("replaceOption"),F6=(n)=>Xi(n)&&n[U7]===!0?{isReplace:!0,value:n.value}:{isReplace:!1,value:n};var ye=(...n)=>{for(let i of n)if((!Xi(i)| Line truncated
`,{mode:384}),i}function zr(n,i,r=[]){let o=i.corpId?.trim()||void 0,t=i.stateful?i.defaultCorpId?.trim()||void 0:void 0,e=o??t;if(e){let l=n.find(($)=>$.id===e);if(l)return l;throw Error(`No enterprise config found for ${e}`)}if(!i.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let u=n[0];if(u)return u;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(r.length?r.join(", "):"the configured enterprise directories"))}import{readFileSync as R5}from"node:fs";import{randomBytes as x5}from"node:crypto";import{randomBytes as dd}from"node:crypto";var f5=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),c5=v.object({id:v.string(),tenantId:v.string(),name:v.string(),isAdmin:v.boolean().default(!1),permissions:v.array(v.string()).default([]),providerUserId:v.string().optional(),hosecloudStaff:f5.optional()}),U5=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),D5=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:U5.optional()}),nd=v.object({user:c5,tenant:D5}),S5=v.object({id:v.string(),name:v.string(),email:v.string().nullable().optional(),emailVerified:v.boolean().optional(),image:v.string().nullable().optional(),tenantId:v.string().optional(),provider:v.string().optional(),providerUserId:v.string().optional(),mobile:v.string().nullable().optional(),status:v.string().optional(),permissions:v.array(v.string()).default([]),isAdmin:v.boolean().default(!1),hosecloudStaff:v.unknown().optional()}).passthrough(),A5=v.object({id:v.string(),token:v.string().optional(),expiresAt:v.string(),createdAt:v.string().optional(),updatedAt:v.string().optional(),ipAddress:v.string().optional(),userAgent:v.string().optional(),userId:v.string(),delegationId:v.string().nullable().optional()}).passthrough(),id=v.object({user:S5,session:A5}),Fv=v.object({id:v.string(),tenantId:v.string().optional(),code:v.number().optional(),description:v.string(),scope:v.string(),strictness:v.string(),status:v.string().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional()}),td=v.object({rules:v.array(Fv),hasPendingDeletes:v.boolean().default(!1)}),O5=v.object({code:v.string().optional(),description:v.string(),scope:v.string(),strictness:v.string()}),Kv=v.object({id:v.string(),tenantId:v.string().optional(),versionNumber:v.number(),versionName:v.string().nullable().optional(),publishedBy:v.string().nullable().optional(),publishedByName:v.string().nullable().optional(),rules:v.array(O5).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),rd=v.object({version:Kv,rulesCount:v.number()}),Xe=v.object({id:v.string(),tenantId:v.string().optional(),title:v.string(),purpose:v.string().default(""),contentType:v.string().default("policy"),content:v.string(),status:v.string().default("published"),enabled:v.boolean().default(!0),scenarios:v.array(v.string()).default([]),tags:v.array(v.string()).default([]),category:v.string().nullable().optional(),categoryTags:v.array(v.string()).default([]),createdBy:v.string().nullable().optional(),createdByName:v.string().nullable().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional(),updatedBy:v.string().nullable().optional(),updatedByName:v.string().nullable().optional(),isDeleted:v.boolean().default(!1)}),od=v.object({articles:v.array(Xe),total:v.number().optional()}),k5=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),d5=v.object({type:v.string(),signKey:v.string().optional(),outboundName:v.string().optional(),mode:v.string().optional(),autoApprovalRate:v.number().optional(),apiKey:v.string().optional(),apiSecret:v.string().optional(),apiOrigin:v.string().optional(),corporationId:v.string().optional(),ebotSignKey:v.string().optional(),completionSignKey:v.string().optional(),outboundMessageId:v.string().optional(),completionMessageId:v.string().optional()}).passthrough(),L5=v.enum(["assisted","semi_automatic","fully_automatic"]),sk=v.object({id:v.string(),url:v.string().url()}).passthrough(),he=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:L5,incomingDocumentWebhook:sk,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:sk,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),i4=v.object({id:v.string().optional(),tenantId:v.string().optional(),tone:v.string().optional(),language:v.string().optional(),detailLevel:v.string().optional(),outputFormat:v.string().optional(),examples:v.array(v.string()).default([]),prohibitedPhrases:v.array(v.string()).default([]),cus Line truncated
`);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,document:Dt({id:i?.id,sn:i?.sn??i?.sourceDocumentSN??n.sourceDocumentSN,title:i?.title??i?.name,template:zv(i,["template.name","templateName","form.name","formName","formTitle"]),amount:Zv(r,["金额","报销金额","付款金额","合计","价税合计"])??zv(i,["amount","totalAmount","expenseAmount"]),expenseType:Zv(r,["费用类型","费用类别","报销类型"]),costCompany:Zv(r,["费用承担公司","承担公司","成本中心","费用归属"]),payee:Zv(r,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:r.slice(0,30)}),invoices:cQ(n),attachments:JL(n,{summary:!0}).attachments,aiResult:Rv(n),manualResult:_t(n)?.value,hints:Dt({amountMentions:DL(o,["金额","合计","税率"],8),partyMentions:DL(o,["买方","卖方","甲方","乙方","收款"],8)})}}function JL(n,i={}){let r=[["document",n.document],["result",n.result],["pipelineData",n.pipelineData],["sourceExtendData",n.sourceExtendData]],o=[],t=new Set;for(let[e,u]of r)A4(u,e,o,t);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,count:o.length,attachments:i.summary?o.map((e)=>Dt({path:e.path,kind:e.kind,fileName:e.fileName,mimeType:e.mimeType,fileId:e.fileId,sourceField:e.sourceField})):o}}function $Q(n){let i=[["result.citedRules",Zi(n,"result.citedRules")],["result.matchedRules",Zi(n,"result.matchedRules")],["result.ruleResults",Zi(n,"result.ruleResults")],["result.rules",Zi(n,"result.rules")],["pipelineData.citedRules",Zi(n,"pipelineData.citedRules")],["pipelineData.matchedRules",Zi(n,"pipelineData.matchedRules")]],r=[],o=new Set;for(let[t,e]of i)(Array.isArray(e)?e:e&&typeof e==="object"?Object.values(e):[]).forEach((l,$)=>{let I=Rr(l);if(!I)return;let g=T(I.runtimeRuleId)??T(I.runtimeId)??T(I.id)??T(I.ruleId),b=T(I.ruleCode)??T(I.code)??(g?SQ(g):void 0),w=Dt({runtimeRuleId:g,ruleCode:b,versionNumber:wQ(I.versionNumber)??n.ruleSetVersionNumber,scope:T(I.scope),strictness:T(I.strictness),appliedAnalysis:I.appliedAnalysis??I.analysis??I.reasoning,checkResult:I.checkResult??I.result??I.decision,findings:I.findings??I.riskPoints??I.evidence,sourcePath:`${t}.${$}`}),f=JSON.stringify(w);if(!o.has(f))o.add(f),r.push(w)});return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,ruleSetVersionNumber:n.ruleSetVersionNumber,count:r.length,rules:r}}function A4(n,i,r,o){if(Array.isArray(n)){n.forEach((e,u)=>A4(e,`${i}.${u}`,r,o));return}let t=Rr(n);if(!t)return;if(IQ(t,i)){let e=Dt({path:i,fieldPath:i,kind:gQ(i,t),fileName:T(t.fileName)??T(t.filename)??T(t.name)??T(t.originalName),mimeType:T(t.mimeType)??T(t.mimetype)??T(t.contentType),fileId:T(t.fileId)??T(t.id)??T(t.attachmentId),ossPath:T(t.ossPath)??T(t.ossKey)??T(t.key),url:T(t.url)??T(t.signedUrl)??T(t.downloadUrl)??T(t.previewUrl),invoiceId:T(t.invoiceId),sourceField:T(t.fieldName)??T(t.label)}),u=JSON.stringify(e);if(!o.has(u))o.add(u),r.push(e)}for(let[e,u]of Object.entries(t))A4(u,`${i}.${e}`,r,o)}function IQ(n,i){let r=Object.keys(n).map((e)=>e.toLowerCase());return/(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(i)&&["filename","fileName","mimeType","mimetype","contentType","fileId","ossPath","signedUrl","downloadUrl","previewUrl","attachmentId"].some((e)=>r.includes(e.toLowerCase()))}function gQ(n,i){let r=`${n} ${T(i.type)??""}`.toLowerCase();if(r.includes("invoice")||r.includes("发票"))return"invoice";if(r.includes("receipt"))return"receipt";return"attachment"}function zv(n,i){if(!n)return;for(let r of i){let o=Zi(n,r);if(o!==void 0)return o}return}function UL(n,i){if(!n)return 0;for(let r of i){let o=Zi(n,r);if(Array.isArray(o))return o.length;if(o&&typeof o==="object")return Object.keys(o).length;if(typeof o==="number")return o}return 0}function Zi(n,i){return i.split(".").reduce((r,o)=>{if(r===void 0||r===null)return;if(Array.isArray(r)){let t=Number(o);return Number.isInteger(t)?r[t]:void 0}if(typeof r==="object")return r[o];return},n)}function bQ(n,i,r){let o=i.split("."),t=n;for(let e of o.slice(0,-1)){let u=t[e];if(!u||typeof u!=="object"||Array.isArray(u))t[e]={};t=t[e]}t[o[o.length-1]??i]=r}function Dt(n){return Object.fromEntries(Object.entries(n).filter(([,i])=>i!==void 0))}function Rr(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function wQ(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function fQ(n){let i=[];return O4(n,"document",i),i}function O4(n,i,r){if(Array.isArray(n)){n.forEach((u,l)=>O4(u,`${i}.${l}`,r));return}let o=Rr(n);if(!o)return;let t=T(o.label)??T(o.name)??T(o.title)??T(o.fieldName),e=o.value??o.displayValue??o.text??o.content;if(t&&e!==void 0&&typeof e!=="object")r.push(Dt({path:i,label:t,value:e,type:T(o.type)??T(o.fieldType)}));for(let[u,l]of Object.entries(o)){if(u==="attachments")continue;O4(l,`${i}.${u}`,r)}}function Zv(n,i){return n.find((o)=>{let t=T(o.label)??"";return i.some((e)=>t.includes(e)) Line truncated
`)}
`}function Ku(i){return i.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function T(i,n={}){gB(i,n);let t=`${JSON.stringify(i,null,2)}
`;if(n.outputFile){eB(n.outputFile,t),console.log(JSON.stringify({outputFile:n.outputFile,bytes:Buffer.byteLength(t,"utf-8")},null,2));return}console.log(t.trimEnd())}function gB(i,n={}){if(n.allowFull||n.outputFile)return;let t=Buffer.byteLength(JSON.stringify(i),"utf-8");if(t>IB)throw Error(`Output is large (${t} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function Hk(i,n){if(n)return;let t=i&&typeof i==="object"?i:{},o=typeof t.count==="number"?t.count:void 0,r=Array.isArray(t.rules)?t.rules.length:void 0,u=Buffer.byteLength(JSON.stringify(i),"utf-8"),l=o??r??0;if(l>vB||u>$B)throw Error(`Rule list is large (${l} rules, ${u} bytes). Use "seal-home rules list --summary" or "seal-home rules count"; pass --full only when you really need full descriptions.`)}function X(i){return{allowFull:z(i.full)===!0,outputFile:c(i.outputFile)??c(i["output-file"])}}function Fk(){console.log(`seal-home CLI
`}function Ve(n){return n.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function K(n,i={}){XQ(n,i);let r=`${JSON.stringify(n,null,2)}
`;if(i.outputFile){jQ(i.outputFile,r),console.log(JSON.stringify({outputFile:i.outputFile,bytes:Buffer.byteLength(r,"utf-8")},null,2));return}console.log(r.trimEnd())}function XQ(n,i={}){if(i.allowFull||i.outputFile)return;let r=Buffer.byteLength(JSON.stringify(n),"utf-8");if(r>HQ)throw Error(`Output is large (${r} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function qL(n,i){if(i)return;let r=n&&typeof n==="object"?n:{},o=typeof r.count==="number"?r.count:void 0,t=Array.isArray(r.rules)?r.rules.length:void 0,e=Buffer.byteLength(JSON.stringify(n),"utf-8"),u=o??t??0;if(u>WQ||e>JQ)throw Error(`Rule list is large (${u} rules, ${e} bytes). Use "seal-home rules list --summary" or "seal-home rules count"; pass --full only when you really need full descriptions.`)}function J(n){return{allowFull:_(n.full)===!0,outputFile:D(n.outputFile)??D(n["output-file"])}}function _L(){console.log(`seal-home CLI
Usage:
seal-home version
@@ -103,10 +103,11 @@ Usage:
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 corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
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 create [--note <note>] [--from-link <url>] [--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>]
@@ -175,23 +176,23 @@ Usage:
seal-home simulation templates [--corp <corpId>]
seal-home simulation integrations [--corp <corpId>]
seal-home simulation package-upload <材料包.zip> [--corp <corpId>]
`)}function Li(i){let n=Pn(),t=bn();return zt(n,{stateful:t.stateful,defaultCorpId:t.defaultCorpId,corpId:i},Kr())}function zv(i=bn()){return{mode:i.stateful?"stateful":"stateless",stateful:i.stateful,...i.stateful&&i.defaultCorpId?{defaultCorpId:i.defaultCorpId}:{},configFile:dt()}}async function Y(i,n,t,o,r={}){T(await Ct(i,n,t,o),r)}async function Ct(i,n,t,o){let r=Ur.find((e)=>e.name===i);if(!r)throw Error(`Unknown Seal tool: ${i}`);let u=Object.fromEntries(Object.entries(o).filter(([,e])=>e!==void 0)),l=r.handler;return l(n,u,{corp:t})}async function Kk(i,n,t,o,r){if(i==="summary"){let u=await Ct("seal_approval_runs_summary",t,o,{date:c(r.options.date),timezone:c(r.options.timezone),limit:ui(r.options.limit),startDate:c(r.options.startDate),endDate:c(r.options.endDate),status:c(r.options.status),taskMode:c(r.options.taskMode),manualApprovalStatus:c(r.options.manualApprovalStatus),sourceDocumentSN:c(r.options.sourceDocumentSN),sourceDocumentId:c(r.options.sourceDocumentId),humanResult:c(r.options.humanResult),query:c(r.options.query)});if(u?.matched===0&&u?.total>0)console.error(`提示:在 ${u.date} 未匹配到记录(该企业共有 ${u.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-home approval-runs list --limit 10 查看最近记录。`);T(u,X(r.options));return}if(i==="stats"){await Y("seal_approval_runs_stats",t,o,{since:c(r.options.since),dedupeBy:c(r.options.dedupeBy)??c(r.options["dedupe-by"]),status:c(r.options.status),sourceSystem:c(r.options.sourceSystem)??c(r.options["source-system"]),taskMode:c(r.options.taskMode)??c(r.options["task-mode"])},X(r.options));return}if(i==="count"){await Y("seal_approval_runs_count",t,o,{status:c(r.options.status),sourceSystem:c(r.options.sourceSystem)??c(r.options["source-system"]),taskMode:c(r.options.taskMode)??c(r.options["task-mode"]),search:c(r.options.search)??c(r.options.query)},X(r.options));return}if(i==="search"||i==="list"){await Y("seal_approval_runs_search",t,o,{limit:ui(r.options.limit),offset:ui(r.options.offset),startDate:c(r.options.startDate),endDate:c(r.options.endDate),status:c(r.options.status),taskMode:c(r.options.taskMode),manualApprovalStatus:c(r.options.manualApprovalStatus),sourceDocumentSN:c(r.options.sourceDocumentSN),sourceDocumentId:c(r.options.sourceDocumentId),humanResult:c(r.options.humanResult),query:c(r.options.query),includeBridge:z(r.options.includeBridge)},X(r.options));return}if(i==="bridge"){await Y("seal_approval_run_langfuse_bridge_get",t,o,{recordId:c(r.options.recordId),sourceDocumentSN:c(r.options.sourceDocumentSN),sourceDocumentId:c(r.options.sourceDocumentId),simulationBatchId:c(r.options.simulationBatchId),limit:ui(r.options.limit)},X(r.options));return}if(i==="pick"){let u=n??c(r.options.query)??c(r.options.sn);if(!u)throw Error("Usage: seal-home approval-runs pick --sn <documentSN>");await Y("seal_approval_run_pick",t,o,{query:u,sn:c(r.options.sn),batchId:c(r.options.batch)??c(r.options.batchId),latest:z(r.options.latest),fields:c(r.options.fields),limit:ui(r.options.limit),includeBridge:z(r.options.includeBridge)},X(r.options));return}if(i==="get"){let u=r.command[2];if(!u)throw Error("Missing approval run recordId");await Y("seal_approval_run_get",t,o,{recordId:u,fields:c(r.options.fields),summary:z(r.options.summary)},X(r.options));return}if(i==="cited-rules"){let u=r.command[2];if(!u)throw Error("Usage: seal-home approval-runs cited-rules <recordId>");await Y("seal_approval_run_cited_rules_get",t,o,{recordId:u},X(r.options));return}if(i==="document-summary"){let u=r.command[2];if(!u)throw Error("Usage: seal-home approval-runs document-summary <recordId>");await Y("seal_approval_run_document_summary_get",t,o,{recordId:u},X(r.options));return}if(i==="attachments"){let u=r.command[2];if(!u)throw Error("Usage: seal-home approval-runs attachments <recordId>");await Y("seal_approval_run_attachments_get",t,o,{recordId:u,summary:z(r.options.summary)},X(r.options));return}if(i==="result"){let u=r.command[2];if(!u)throw Error("Usage: seal-home approval-runs result <recordId> [--summary]");await Y("seal_approval_run_result_get",t,o,{recordId:u,summary:z(r.options.summary)},X(r.options));return}if(i==="url"){await Y("seal_approval_run_url_get",t,o,{recordId:n,sourceDocumentSN:c(r.options.sourceDocumentSN),sourceDocumentId:c(r.options.sourceDocumentId)},X(r.options));return}throw Error(`Unknown approval-runs command: ${i??""}. Run 'seal-home help' for available commands.`)}async function Tk(i,n,t){if(i==="diagnose"){T(await bB(n));return}if(i==="hose-link"){let o=ui(t.options.expire)??7200;T(await HN(n,o));return}throw Error(`Unknown auth command: ${i??""}. Run 'seal-home help' for available commands.`)}async function bB(i){if(i.source.type!=="hose"){let D=await Si(i),S=await pt(D);return{corp:{id:i.id,name:i.name,sourceType:i.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:S.user,tenant:S.tenant}]}}Nv(i.id);let n=i.source,t=n.appKey??n.key,o=n.appSecurity??n.passw Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${Bi.length} candidate administrators:
- ${Vi}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!S)if(!g&&u)S=u;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-home corps hose-staffs' to discover available administrators.");let N=Di(i,"id")??w,L=f??w,K=Di(i,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,F={id:N,name:L,seal:{url:K,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:b,appKey:t,appSecurity:o,corpId:w,staffId:S},auth:{refreshTtl:300}};if(g)Nv(N),await mt(F);let y=z4();zk(y,{recursive:!0,mode:448});let G=hk(y,`${S0(N)}.json`);if(dk(G)&&i.overwrite!==!0)throw Error(`Enterprise config already exists: ${G}. Pass "overwrite": true to replace it.`);pk(G,`${JSON.stringify(F,null,2)}
`,{mode:384}),T({id:N,name:L,corpId:w,domain:b,staffId:S,verified:g,path:G})}async function SB(i){let n=cr(i,"token"),t=(Di(i,"sealUrl")??Di(i,"url")??"").replace(/\/+$/,"");if(!t)throw Error("Missing required JSON field: sealUrl");let o=yk(i,"expiresIn")??2592000,r=i.force===!0||i.verify===!1?!1:!0,u=r?await OB(t,n):void 0,l=u?.user,e=u?.tenant,$=Di(i,"tenantSlug")??Sr(e?.tenantSlug),I=Di(i,"tenantId")??Sr(e?.id),g=Di(i,"tenantName")??Di(i,"name")??Sr(e?.name),b=Di(i,"id")??$??I;if(!b)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let w=Di(i,"staffId")??Sr(l?.providerUserId)??Sr(l?.id)??"seal",f=Di(i,"provider")??Sr(l?.provider)??Sr(e?.providerConfig?.provider),D={id:b,name:g??b,seal:{url:t,tenantSlug:$,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:n,sealUrl:t,expiresIn:o,staffId:w,corpId:$??I??b,tenantId:I,tenantSlug:$,tenantName:g,providerUserId:Sr(l?.providerUserId),provider:f},auth:{refreshTtl:300}},S=z4();zk(S,{recursive:!0,mode:448});let N=hk(S,`${S0(b)}.json`);if(dk(N)&&i.overwrite!==!0)throw Error(`Enterprise config already exists: ${N}. Pass "overwrite": true to replace it.`);pk(N,`${JSON.stringify(D,null,2)}
`,{mode:384}),T({id:b,name:D.name,tenantId:I,tenantSlug:$,verified:r,path:N})}async function OB(i,n){let t=await AB(`${i}/api/v1/auth/me`,{authorization:`Bearer ${n}`}),o=hv(t.data);return{user:hv(o.user??t.user),tenant:hv(o.tenant??t.tenant)}}async function AB(i,n={}){let t=await fetch(i,{headers:n}),o=await t.text();if(!t.ok)throw Error(`${t.status} ${o}`);let r=JSON.parse(o);return hv(r)}function hv(i){return i&&typeof i==="object"&&!Array.isArray(i)?i:{}}function Sr(i){return typeof i==="string"&&i?i:void 0}async function mk(i,n,t,o,r){if(i==="list"){await Y("seal_delegation_list",t,o,{},X(r.options));return}if(i==="create"){let u=c(r.options.note)??(n?[n,...r.command.slice(2)].join(" "):void 0);await Y("seal_delegation_create",t,o,{note:u},X(r.options));return}if(i==="revoke"){let u=n??c(r.options.tokenId);if(!u)throw Error("Usage: seal-home delegation revoke <tokenId>");await Y("seal_delegation_revoke",t,o,{tokenId:u},X(r.options));return}throw Error(`Unknown delegation command: ${i??""}. Run 'seal-home help' for available commands.`)}import{readFileSync as NB}from"node:fs";async function Rk(i,n,t,o,r,u){let l=i==="hosecloud"||!i,e=i==="hosecloud"?n:i,$=i==="hosecloud"?t:n;if(!l&&i!=="hosecloud")throw Error(`Unknown deploy target: ${i??""}. Currently supported: hosecloud`);if(e==="requirements"){await Y("seal_deploy_hosecloud_requirements",o,r,{},X(u.options));return}if(e==="list"){await Y("seal_deploy_hosecloud_list",o,r,{},X(u.options));return}if(e==="get"){let I=$??c(u.options.signKey)??c(u.options["sign-key"]);if(!I)throw Error("Usage: seal-home deploy hosecloud get <sign-key>");await Y("seal_deploy_hosecloud_get",o,r,{signKey:I},X(u.options));return}if(e==="status"){await Y("seal_deploy_hosecloud_status",o,r,{},X(u.options));return}if(e==="configure"){let I=c(u.options.input),g=I?JSON.parse(NB(I,"utf8")):tn(u.json);if(!g||Object.keys(g).length===0)throw Error("Usage: seal-home deploy hosecloud configure --json '{...}' or --input <file>");await Y("seal_deploy_hosecloud_configure",o,r,g,X(u.options));return}if(e==="sync"){let I=$??c(u.options.signKey)??c(u.options["sign-key"]);if(!I)throw Error("Usage: seal-home deploy hosecloud sync <sign-key>");await Y("seal_deploy_hosecloud_sync",o,r,{signKey:I},X(u.options));return}throw Error(`Unknown deploy hosecloud action: ${e??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as WB}from"node:http";import{URL as kB}from"node:url";var xk={openapi:"3.1.0",info:{title:"seal-home Wrapped API",version:"0.9.5",description:`Planned HTTP contract for the seal-home wrapped backend API.
`)}function Nn(n){let i=hi(),r=bi();return zr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n},Kt())}function xv(n=bi()){return{mode:n.stateful?"stateful":"stateless",stateful:n.stateful,...n.stateful&&n.defaultCorpId?{defaultCorpId:n.defaultCorpId}:{},configFile:Mr()}}async function H(n,i,r,o,t={}){K(await xr(n,i,r,o),t)}async function xr(n,i,r,o){let t=St.find((l)=>l.name===n);if(!t)throw Error(`Unknown Seal tool: ${n}`);let e=Object.fromEntries(Object.entries(o).filter(([,l])=>l!==void 0)),u=t.handler;return u(i,e,{corp:r})}async function EL(n,i,r,o,t){if(n==="summary"){let e=await xr("seal_approval_runs_summary",r,o,{date:D(t.options.date),timezone:D(t.options.timezone),limit:ln(t.options.limit),startDate:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query)});if(e?.matched===0&&e?.total>0)console.error(`提示:在 ${e.date} 未匹配到记录(该企业共有 ${e.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-home approval-runs list --limit 10 查看最近记录。`);K(e,J(t.options));return}if(n==="stats"){await H("seal_approval_runs_stats",r,o,{since:D(t.options.since),dedupeBy:D(t.options.dedupeBy)??D(t.options["dedupe-by"]),status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"])},J(t.options));return}if(n==="count"){await H("seal_approval_runs_count",r,o,{status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"]),search:D(t.options.search)??D(t.options.query)},J(t.options));return}if(n==="search"||n==="list"){await H("seal_approval_runs_search",r,o,{limit:ln(t.options.limit),offset:ln(t.options.offset),startDate:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query),includeBridge:_(t.options.includeBridge)},J(t.options));return}if(n==="bridge"){await H("seal_approval_run_langfuse_bridge_get",r,o,{recordId:D(t.options.recordId),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),simulationBatchId:D(t.options.simulationBatchId),limit:ln(t.options.limit)},J(t.options));return}if(n==="pick"){let e=i??D(t.options.query)??D(t.options.sn);if(!e)throw Error("Usage: seal-home approval-runs pick --sn <documentSN>");await H("seal_approval_run_pick",r,o,{query:e,sn:D(t.options.sn),batchId:D(t.options.batch)??D(t.options.batchId),latest:_(t.options.latest),fields:D(t.options.fields),limit:ln(t.options.limit),includeBridge:_(t.options.includeBridge)},J(t.options));return}if(n==="get"){let e=t.command[2];if(!e)throw Error("Missing approval run recordId");await H("seal_approval_run_get",r,o,{recordId:e,fields:D(t.options.fields),summary:_(t.options.summary)},J(t.options));return}if(n==="cited-rules"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs cited-rules <recordId>");await H("seal_approval_run_cited_rules_get",r,o,{recordId:e},J(t.options));return}if(n==="document-summary"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs document-summary <recordId>");await H("seal_approval_run_document_summary_get",r,o,{recordId:e},J(t.options));return}if(n==="attachments"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs attachments <recordId>");await H("seal_approval_run_attachments_get",r,o,{recordId:e,summary:_(t.options.summary)},J(t.options));return}if(n==="result"){let e=t.command[2];if(!e)throw Error("Usage: seal-home approval-runs result <recordId> [--summary]");await H("seal_approval_run_result_get",r,o,{recordId:e,summary:_(t.options.summary)},J(t.options));return}if(n==="url"){await H("seal_approval_run_url_get",r,o,{recordId:i,sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId)},J(t.options));return}throw Error(`Unknown approval-runs command: ${n??""}. Run 'seal-home help' for available commands.`)}async function ML(n,i,r){if(n==="diagnose"){K(await hQ(i));return}if(n==="hose-link"){let o=ln(r.options.expire)??7200;K(await qk(i,o));return}throw Error(`Unknown auth command: ${n??""}. Run 'seal-home help' for available commands.`)}async function hQ(n){if(n.source.type!=="hose"){let c=await An(n),S=await Yi(c);return{corp:{id:n.id,name:n.name,sourceType:n.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:S.user,tenant:S.tenant}]}}Gv(n.id);let i=n.source,r=i.appKey??i.key,o=i.appSecurity??i.passw Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${Wn.length} candidate administrators:
- ${On}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!S)if(!g&&e)S=e;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-home corps hose-staffs' to discover available administrators.");let k=Un(n,"id")??w,d=f??w,p=Un(n,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,h={id:k,name:d,seal:{url:p,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:b,appKey:r,appSecurity:o,corpId:w,staffId:S},auth:{refreshTtl:300}};if(g)Gv(k),await ar(h);let j=n4();nN(j,{recursive:!0,mode:448});let L=tN(j,`${j4(k)}.json`);if(sL(L)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${L}. Pass "overwrite": true to replace it.`);iN(L,`${JSON.stringify(h,null,2)}
`,{mode:384}),K({id:k,name:d,corpId:w,domain:b,staffId:S,verified:g,path:L})}async function KQ(n){let i=At(n,"token"),r=(Un(n,"sealUrl")??Un(n,"url")??"").replace(/\/+$/,"");if(!r)throw Error("Missing required JSON field: sealUrl");let o=QL(n,"expiresIn")??2592000,t=n.force===!0||n.verify===!1?!1:!0,e=t?await VQ(r,i):void 0;oN(n,{token:i,sealUrl:r,expiresIn:o,verify:t,remote:e})}async function BQ(n,i,r){let o=await jv(n),t=He(o.sealUrl,o.token),e=await Yi(t),u={user:e.user,tenant:e.tenant};Wv(o.corpId,u.tenant),oN({id:o.corpId,corpId:o.corpId,name:i,provider:"hosecloud",overwrite:r},{token:o.token,sealUrl:o.sealUrl,expiresIn:o.expiresIn,verify:!0,remote:u})}function oN(n,i){let{token:r,sealUrl:o,expiresIn:t,verify:e,remote:u}=i,l=u?.user,$=u?.tenant,I=Un(n,"tenantSlug")??Ot($?.tenantSlug),g=Un(n,"tenantId")??Ot($?.id),b=Un(n,"tenantName")??Ot($?.name),w=Un(n,"id")??I??g;if(!w)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let f=Un(n,"staffId")??Ot(l?.providerUserId)??Ot(l?.id)??"seal",c=Un(n,"provider")??Ot(l?.provider)??Ot($?.providerConfig?.provider),S=Un(n,"corpId")??I??g??w,k={id:w,name:Un(n,"name")??b??w,seal:{url:o,tenantSlug:I,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:r,sealUrl:o,expiresIn:t,staffId:f,corpId:S,tenantId:g,tenantSlug:I,tenantName:b,providerUserId:Ot(l?.providerUserId),provider:c},auth:{refreshTtl:300}},d=n4();nN(d,{recursive:!0,mode:448});let p=tN(d,`${j4(w)}.json`);if(sL(p)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${p}. Pass "overwrite": true to replace it.`);iN(p,`${JSON.stringify(k,null,2)}
`,{mode:384}),K({id:w,name:k.name,tenantId:g,tenantSlug:I,verified:e,path:p})}async function VQ(n,i){let r=await TQ(`${n}/api/v1/auth/me`,{authorization:`Bearer ${i}`}),o=sv(r.data);return{user:sv(o.user??r.user),tenant:sv(o.tenant??r.tenant)}}async function TQ(n,i={}){let r=await fetch(n,{headers:i}),o=await r.text();if(!r.ok)throw Error(`${r.status} ${o}`);let t=JSON.parse(o);return sv(t)}function sv(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:{}}function Ot(n){return typeof n==="string"&&n?n:void 0}async function eN(n,i){let r=await jv(n),o=He(r.sealUrl,r.token),t=await Yi(o);Wv(r.corpId,t.tenant);let e=await Cr(o,{note:i});K({tenant:{id:t.tenant.id,name:t.tenant.name,tenantSlug:t.tenant.tenantSlug,corpId:r.corpId},user:{id:t.user.id,name:t.user.name,providerUserId:t.user.providerUserId,isAdmin:t.user.isAdmin},delegation:e,expiresIn:r.expiresIn})}async function uN(n,i,r,o,t){if(n==="list"){await H("seal_delegation_list",r,o,{},J(t.options));return}if(n==="create"){let e=D(t.options.note)??(i?[i,...t.command.slice(2)].join(" "):void 0);await H("seal_delegation_create",r,o,{note:e},J(t.options));return}if(n==="revoke"){let e=i??D(t.options.tokenId);if(!e)throw Error("Usage: seal-home delegation revoke <tokenId>");await H("seal_delegation_revoke",r,o,{tokenId:e},J(t.options));return}throw Error(`Unknown delegation command: ${n??""}. Run 'seal-home help' for available commands.`)}import{readFileSync as qQ}from"node:fs";async function lN(n,i,r,o,t,e){let u=n==="hosecloud"||!n,l=n==="hosecloud"?i:n,$=n==="hosecloud"?r:i;if(!u&&n!=="hosecloud")throw Error(`Unknown deploy target: ${n??""}. Currently supported: hosecloud`);if(l==="requirements"){await H("seal_deploy_hosecloud_requirements",o,t,{},J(e.options));return}if(l==="list"){await H("seal_deploy_hosecloud_list",o,t,{},J(e.options));return}if(l==="get"){let I=$??D(e.options.signKey)??D(e.options["sign-key"]);if(!I)throw Error("Usage: seal-home deploy hosecloud get <sign-key>");await H("seal_deploy_hosecloud_get",o,t,{signKey:I},J(e.options));return}if(l==="status"){await H("seal_deploy_hosecloud_status",o,t,{},J(e.options));return}if(l==="configure"){let I=D(e.options.input),g=I?JSON.parse(qQ(I,"utf8")):ri(e.json);if(!g||Object.keys(g).length===0)throw Error("Usage: seal-home deploy hosecloud configure --json '{...}' or --input <file>");await H("seal_deploy_hosecloud_configure",o,t,g,J(e.options));return}if(l==="sync"){let I=$??D(e.options.signKey)??D(e.options["sign-key"]);if(!I)throw Error("Usage: seal-home deploy hosecloud sync <sign-key>");await H("seal_deploy_hosecloud_sync",o,t,{signKey:I},J(e.options));return}throw Error(`Unknown deploy hosecloud action: ${l??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as MQ}from"node:http";import{URL as EQ}from"node:url";var vN={openapi:"3.1.0",info:{title:"seal-home Wrapped API",version:"0.9.8",description:`Planned HTTP contract for the seal-home wrapped backend API.
These endpoints describe the intended stable API for frontend developers and agents once
the HTTP adapter is implemented.
They are not the raw downstream Seal endpoints. seal-home is responsible for enterprise
selection, source authentication, response compaction, and diagnostics-friendly fields.
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"2 Line truncated
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"2 Line truncated
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Seal Home API Docs (v${m})</title>
<title>Seal Home API Docs (v${R})</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>\uD83E\uDDAD</text></svg>" />
<style>
body {
@@ -210,20 +211,20 @@ selection, source authentication, response compaction, and diagnostics-friendly
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`}async function Wi(i,n,t,o){let r=i.handler;return r(n,t,{corp:o})}async function sk(i,n){if(n.setHeader("Access-Control-Allow-Origin","*"),n.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),n.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),i.method==="OPTIONS"){n.writeHead(204),n.end();return}let t=i.headers.host||"localhost",o=i.headers["x-forwarded-proto"]||"http",r=new kB(i.url||"/",`${o}://${t}`),u=r.pathname.replace(/\/+$/,"")||"/",l=(i.method||"GET").toUpperCase();try{if(l==="GET"&&u==="/"){Ui(n,200,{name:"seal-home",version:m,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(l==="GET"&&u==="/docs"){jB(n,200,ak());return}if(l==="GET"&&(u==="/openapi.json"||u==="/openapi")){let e=Cv();Ui(n,200,e);return}if(l==="GET"&&(u==="/health"||u==="/version")){Ui(n,200,{status:"ok",name:"seal-home",version:m,uptimeSeconds:Math.floor(process.uptime()),timestamp:new Date().toISOString()});return}if(l==="GET"&&u==="/api/tools"){Ui(n,200,{count:Ur.length,tools:Ur.map((e)=>({name:e.name,description:e.description}))});return}if(l==="POST"&&u==="/api/cli"){let e=await Rv(i),$=typeof e?.command==="string"?e.command.trim():"";if(!$){mv(n,400,"Missing or empty 'command' field in request body");return}let I=G0($),g=I[0]==="seal-home"||I[0]?.endsWith("/seal-home")?I.slice(1):I,b=await Vu(g),w=void 0;try{if(b.stdout.trim().startsWith("{")||b.stdout.trim().startsWith("["))w=JSON.parse(b.stdout)}catch{}Ui(n,b.isError?400:200,{success:!b.isError,stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,data:w});return}if(l==="POST"&&u.startsWith("/api/tool/")){let e=u.slice(10).trim(),$=Gi(e,{includeMcpAliases:!0});if(!$){mv(n,404,`Tool not found: '${e}'`);return}let I=await Rv(i)||{},g=hi(i,r,I),b=Li(g),w=await Si(b),f={...I};delete f.corp;let D=await Wi($,w,f,b);Ui(n,200,D);return}if(u.startsWith("/v1/")){if(await GB(i,n,l,u,r))return}mv(n,404,`Cannot ${l} ${u}. Visit /docs for available endpoints.`)}catch(e){let $=e instanceof Error?e.message:String(e);mv(n,500,$)}}async function GB(i,n,t,o,r){let u=Object.fromEntries(r.searchParams.entries());if(t==="GET"&&o==="/v1/corps"){let l=Pn(),e=bn();return Ui(n,200,{count:l.length,mode:e.stateful?"stateful":"stateless",defaultCorpId:e.defaultCorpId,corps:l.map(($)=>({id:$.id,name:$.name,sourceType:$.source.type,sealUrl:$.seal?.url}))}),!0}if(t==="GET"&&o==="/v1/whoami"){let l=hi(i,r,u),e=Li(l),$=await Si(e),I=Gi("seal_whoami"),g=await Wi(I,$,{},e);return Ui(n,200,g),!0}if(t==="GET"&&o==="/v1/session"){let l=hi(i,r,u),e=Li(l),$=await Si(e),I=Gi("seal_session_get"),g=await Wi(I,$,{},e);return Ui(n,200,g),!0}if(t==="GET"&&o==="/v1/approval-runs/summary"){let l=hi(i,r,u),e=Li(l),$=await Si(e),I=Gi("seal_approval_runs_summary"),g=await Wi(I,$,u,e);return Ui(n,200,g),!0}if(t==="GET"&&o==="/v1/approval-runs/stats"){let l=hi(i,r,u),e=Li(l),$=await Si(e),I=Gi("seal_approval_runs_stats"),g=await Wi(I,$,u,e);return Ui(n,200,g),!0}if(t==="GET"&&o==="/v1/approval-runs/pick"){let l=hi(i,r,u),e=Li(l),$=await Si(e),I=Gi("seal_approval_run_pick"),g=await Wi(I,$,u,e);return Ui(n,200,g),!0}if(t==="GET"&&o==="/v1/approval-runs/url"){let l=hi(i,r,u),e=Li(l),$=await Si(e),I=Gi("seal_approval_run_url_get"),g=await Wi(I,$,u,e);return Ui(n,200,g),!0}if(o.startsWith("/v1/approval-runs/")){let l=o.slice(18).split("/"),e=l[0],$=l[1];if(e&&!["summary","pick","stats","url","bridge"].includes(e)){let I=hi(i,r,u),g=Li(I),b=await Si(g);if(!$){let w=Gi("seal_approval_run_get"),f=await Wi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}if($==="attachments"){let w=Gi("seal_approval_run_attachments_get"),f=await Wi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}if($==="cited-rules"){let w=Gi("seal_approval_run_cited_rules_get"),f=await Wi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}if($==="document-summary"){let w=Gi("seal_approval_run_document_summary_get"),f=await Wi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}if($==="result"){let w=Gi("seal_approval_run_result_get"),f=await Wi(w,b,{recordId:e,...u},g);return Ui(n,200,f),!0}}}if(t==="GET"&&o==="/v1/approval-runs"){let l=hi(i,r,u),e=Li(l),$=await Si(e),I=Gi("seal_approval_runs_search"),g=await Wi(I,$,{...u,limit:u.limit?Number(u.limit):void 0,offset:u.offset?Number(u.offset):void 0,includeBridge:u.includeBridge==="true"},e);return Ui(n,200,g),!0}if(t==="GET"&&o==="/v1/approval/rules"){let l=hi(i,r,u),e=Li(l),$=await Si(e),I=Gi("seal_approval_rules_list"),g=await Wi(I,$,u,e);return Ui(n,200,g),!0}if(t==="GET"&&o==="/v1/simulation/batches"){let l=hi(i,r,u),e=Li(l),$=await Si(e),I=Gi("seal_simulation_batches_list"),g=await Wi(I,$,u,e);return Ui(n,200,g),!0}if(t==="POST"&&o==="/v1/simulation/create-batch"){let l=await Rv(i)||{},e=hi(i,r,l),$=Li(e),I=await Si($),g=Gi("seal_simulaLine truncated
\uD83D\uDE80 seal-home HTTP Server (v${m}) started`),console.error(` URL: http://${t}:${n}`),console.error(` Docs: http://${t}:${n}/docs`),console.error(` OpenAPI: http://${t}:${n}/openapi.json`),console.error(` CLI Exec: POST http://${t}:${n}/api/cli`),console.error(` REST API: http://${t}:${n}/v1/...
`);r(o)})})}async function nG(i){let n=ui(i.options.port)??ui(i.options.p),t=c(i.options.host)??c(i.options.h),o=await iG({port:n,host:t}),r=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",r),process.on("SIGTERM",r),await new Promise(()=>{})}async function rG(i,n,t,o){if(i==="config"||i==="get"){await Y("seal_llm_config_get",n,t,{},X(o.options));return}if(i==="providers"||i==="list"){await Y("seal_llm_providers_list",n,t,{},X(o.options));return}throw Error(`Unknown llm command: ${i??""}. Run 'seal-home help' for available commands.`)}async function tG(i,n){if(i==="config"||i==="json"){j0();return}await W0()}function j0(){T({mcpServers:{"seal-home":{type:"stdio",command:"seal-home",args:["mcp"],env:{SEAL_HOME_MCP_ENABLED:"true"}}}})}function oG(i){let n=Cv();T(n,{...X(i.options),allowFull:!0})}async function uG(i,n,t,o){if(i==="available"){await Y("seal_permissions_available_list",n,t,{},X(o.options));return}if(i==="configs"||i==="list"){await Y("seal_permissions_configs_list",n,t,{},X(o.options));return}throw Error(`Unknown permissions command: ${i??""}. Run 'seal-home help' for available commands.`)}import{readFileSync as lG}from"node:fs";async function eG(i,n,t,o,r,u,l){if(!i||i==="get"){await Y("seal_preference_get",r,u,{},X(l.options));return}if(i==="decision"){if(n==="update"||!n){let e=c(l.options.input),$=e?JSON.parse(lG(e,"utf8")):tn(l.json);if(!$||Object.keys($).length===0)throw Error(`Usage: seal-home preference decision update --json '{"explicitApprove":"..."}'`);await Y("seal_preference_decision_update",r,u,$,X(l.options));return}}if(i==="thinking-depth"||i==="thinkingDepth"){if(n==="set"){let e=c(l.options.default)??c(l.options.level)??o;if(e!=="medium"&&e!=="high")throw Error("Usage: seal-home preference thinking-depth set --default <medium|high>");await Y("seal_preference_thinking_depth_set",r,u,{defaultLevel:e},X(l.options));return}if(n==="policies"){if(t==="list"||!t){await Y("seal_preference_thinking_depth_policies_list",r,u,{},X(l.options));return}if(t==="upsert"){let e=c(l.options.input),$=e?JSON.parse(lG(e,"utf8")):tn(l.json);if(!$||!$.id||!$.name)throw Error(`Usage: seal-home preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await Y("seal_preference_thinking_depth_policies_upsert",r,u,$,X(l.options));return}if(t==="remove"||t==="delete"){let e=o??c(l.options.id)??c(l.options.policyId);if(!e)throw Error("Usage: seal-home preference thinking-depth policies remove <policyId>");await Y("seal_preference_thinking_depth_policies_remove",r,u,{policyId:e},X(l.options));return}}}throw Error(`Unknown preference action: ${i??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function vG(i={}){let n=Pn(),t=bn(),o=zt(n,{stateful:t.stateful,defaultCorpId:t.defaultCorpId,corpId:i.corpId},Kr());console.log(`[probe] corp=${o.id} source=${o.source.type}`);let r=await mt(o);console.log("[probe] seal enterprise"),console.log(JSON.stringify(r,null,2));let u=await Si(o),l=await Vv(u,{documentLimit:20,stylePreferencesEndpoint:o.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:l.rules.rules.length,hasPendingRuleDeletes:l.rules.hasPendingDeletes,documents:l.documents.articles.length,documentsTotal:l.documents.total,stylePreferences:l.stylePreferences.ok?"ok":`error: ${l.stylePreferences.error}`},null,2))}async function $G(i,n,t){let o=n??c(t.options.corp)??(i&&i!=="--corp"?i:void 0);await vG({corpId:o})}async function IG(i,n,t,o,r){if(i==="count"){await Y("seal_approval_rules_list",t,o,{countOnly:!0},X(r.options));return}if(i==="list"){if(z(r.options.count)){await Y("seal_approval_rules_list",t,o,{countOnly:!0},X(r.options));return}let u=ui(r.options.limit),l=ui(r.options.offset);if(z(r.options.summary)){await Y("seal_approval_rules_list",t,o,{fields:Qk,limit:u,offset:l},X(r.options));return}let e=await Ct("seal_approval_rules_list",t,o,{limit:u,offset:l});Hk(e,z(r.options.full)===!0),T(e);return}if(i==="clear"){let u=z(r.options.yes)===!0,l=z(r.options.dryRun)??z(r.options["dry-run"])??!u;if(!u&&!l)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let e=await Ct("seal_approval_rules_clear",t,o,{dryRun:l,recode:z(r.options.recode)});if(!u&&l&&e&&typeof e==="object"){T({...e,nextCommand:`seal-home rules clear --corp ${o.id} --yes`},X(r.options));return}T(e,X(r.options));return}if(i==="versions"){await Y("seal_approval_rule_versions_list",t,o,{},X(r.options));return}if(i==="version"){let u=n??c(r.options.version);if(!u)throw Error("Usage: seal-home rules version <versionId|versionNumber|latest>");await Y("seal_approval_rule_version_get",t,o,Hu(u),X(r.options));return}if(i==="get"){await Y("seal_approval_rule_get",t,o,{...Pk(c(r.options.version)),code:c(r.options.code),runtimeId:c(r.options.runtimeId)??c(r.options["runtime-id"]),recordId:c(r.options.recordId)??c(r.options["record-id"])},X(r.options)) Line truncated
`,{mode:384}),av(t,`running pid=${process.pid}`);let o=()=>{if(J0(n)===process.pid)xv(n,{force:!0});av(t,`stopped pid=${process.pid}`)};await new Promise((r)=>{let u=!1,l=setInterval(()=>{},60000),e=()=>{if(u)return;u=!0,o(),clearInterval(l),process.off("SIGTERM",e),process.off("SIGINT",e),r()};process.once("SIGTERM",e),process.once("SIGINT",e)})}function gG(i){DG(i.stateDir);let n=Rt(i);if(n.running)return n;let t=i.launcher??{command:process.execPath,args:[i.entryFile]},o=yB(t.command,[...t.args??[],"service","run"],{cwd:i.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});o.unref();let r=sv(i);return y0(r,`${o.pid}
`,{mode:384}),av(i$(i),`started pid=${o.pid}`),{started:!0,...Rt(i)}}function bG(i,n={}){let t=sv(i),o=J0(t);if(!o||!fG(o,i.appRoot))return xv(t,{force:!0}),n.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(o,"SIGTERM"),xv(t,{force:!0}),av(i$(i),`stop requested pid=${o}`),n.quiet?void 0:{stopped:!0,pid:o}}function fG(i,n){if(!HB(i))return!1;try{let t=JB("ps",["-p",String(i),"-o","command="],{encoding:"utf8"});return(t.includes(n)||t.includes("seal-home")||t.includes("src/cli.ts"))&&t.includes("service")&&t.includes("run")}catch{return!1}}function HB(i){try{return process.kill(i,0),!0}catch{return!1}}function sv(i){return wG(i.stateDir,"service.pid")}function i$(i){return wG(i.stateDir,"service.log")}function J0(i){if(!XB(i))return;let n=Number(PB(i,"utf8").trim());return Number.isInteger(n)&&n>0?n:void 0}function DG(i){YB(i,{recursive:!0,mode:448})}function av(i,n){y0(i,`${new Date().toISOString()} ${n}
`,{flag:"a",mode:384})}var X0=KB(FB(),".config","seal-home");async function UG(i,n){let t=await Er(i,{appRoot:n.appRoot,entryFile:n.entryFile,stateDir:X0,version:m,launcher:n.launcher});if(t!==void 0)T(t)}import{existsSync as BB,readFileSync as cG}from"node:fs";async function SG(i,n,t,o,r){if(i==="batch-records"||i==="records"){let u=n??c(r.options.batchId)??c(r.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation batch-records <batchId>");await Y("seal_simulation_batch_records_get",t,o,{batchId:u,query:c(r.options.query)},X(r.options));return}if(i==="create"||i==="run"){let u=c(r.options.mode)??c(r.options.sourceSystem)??c(r.options["source-system"])??"hosecloud",l=u==="material-pack"?"material_pack":u,e=c(r.options.schemaConfig)??c(r.options["schema-config"]),$=e?JSON.parse(cG(e,"utf8")):void 0,I=c(r.options.input),g=I?JSON.parse(cG(I,"utf8")):tn(r.json),b=c(r.options.packageId)??c(r.options["package-id"]),w=qi(r.options.packageIds)??qi(r.options["package-ids"])??(b?[b]:void 0),f=qi(r.options.flowIds)??qi(r.options["flow-ids"])??qi(r.options.documentSn)??qi(r.options["document-sn"]),D=c(r.options.signKey)??c(r.options["sign-key"])??c(r.options.integration);await Y("seal_simulation_batch_create",t,o,{mode:l,sourceSystem:l,flowIds:f,documentSn:f,rejectNodeName:c(r.options.rejectNode)??c(r.options["reject-node"])??null,thinkingDepthOverride:c(r.options.thinkingDepth)??c(r.options["thinking-depth"]),skipInvoiceGeneration:z(r.options.skipInvoiceGeneration)??z(r.options["skip-invoice-generation"]),skipExpenseExtraction:z(r.options.skipExpenseExtraction)??z(r.options["skip-expense-extraction"]),disableAttachmentCache:z(r.options.disableAttachmentCache)??z(r.options["disable-attachment-cache"]),signKey:D,packageIds:w,packageId:b,templateId:c(r.options.templateId)??c(r.options["template-id"]),schemaConfig:$,requestIds:qi(r.options.requestIds)??qi(r.options["request-ids"]),workflowTypeId:c(r.options.workflowTypeId)??c(r.options["workflow-type-id"]),flowStatusList:qi(r.options.flowStatusList)?.map(Number)??qi(r.options["flow-status-list"])?.map(Number),businessCodes:qi(r.options.businessCodes)??qi(r.options["business-codes"]),documentType:c(r.options.documentType)??c(r.options["document-type"]),startTime:ui(r.options.startTime)??ui(r.options["start-time"]),endTime:ui(r.options.endTime)??ui(r.options["end-time"]),status:qi(r.options.status),limit:ui(r.options.limit),rawParams:g},X(r.options));return}if(i==="wait"){let u=n??c(r.options.batchId)??c(r.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await Y("seal_simulation_batch_wait",t,o,{batchId:u,timeout:c(r.options.timeout),pollInterval:c(r.options.pollInterval)??c(r.options["poll-interval"])},X(r.options));return}if(i==="clean"||i==="delete"){let u=n??c(r.options.batchId)??c(r.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation clean <batchId>");await Y("seal_simulation_batch_clean",t,o,{batchId:u},X(r.options));return}if(i==="specifications"){let u=n??c(r.options.integration)??c(r.options.signKey)??c(r.options["sign-key"]);await Y("seal_simulation_specifications_list",t,o,{signKey:u},X(r.options));return}if(i==="list"){await Y("seal_simulation_batches_list",t,o,{limit:ui(r.options.limit)},X(r.options));return}if(i==="get"){let u=n??c(r.options.batchId)??c(r.options["batch-id"]);if(!u)throw Error("Usage: seal-home simulation get <batchId>");await Y("seal_simulation_batch_get",t,o,{batchId:u},X(r.options));return}if(i==="templates"){await Y("seal_simulation_templates_get",t,o,{},X(r.options));return}if(i==="integrations"){await Y("seal_simulation_integrations_get",t,o,{},X(r.options));return}if(i==="package-upload"){let u=n??c(r.options.file);if(!u)throw Error("Usage: seal-home simulation package-upload <材料包.zip>");if(!BB(u))throw Error(`File not found: ${u}`);await Y("seal_simulation_material_package_upload",t,o,{filePath:u},X(r.options));return}throw Error(`Unknown simulation command: ${i??""}. Run 'seal-home help' for available commands.`)}import{existsSync as FG}from"node:fs";import{join as n$}from"node:path";import{mkdirSync as XG,writeFileSync as hB}from"node:fs";import{homedir as CB}from"node:os";import{dirname as mB,join as YG}from"node:path";var OG=`---
</html>`}async function Hn(n,i,r,o){let t=n.handler;return t(i,r,{corp:o})}async function IN(n,i){if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),n.method==="OPTIONS"){i.writeHead(204),i.end();return}let r=n.headers.host||"localhost",o=n.headers["x-forwarded-proto"]||"http",t=new EQ(n.url||"/",`${o}://${r}`),e=t.pathname.replace(/\/+$/,"")||"/",u=(n.method||"GET").toUpperCase();try{if(u==="GET"&&e==="/"){Dn(i,200,{name:"seal-home",version:R,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(u==="GET"&&e==="/docs"){ZQ(i,200,$N());return}if(u==="GET"&&(e==="/openapi.json"||e==="/openapi")){let l=n$();Dn(i,200,l);return}if(u==="GET"&&(e==="/health"||e==="/version")){Dn(i,200,{status:"ok",name:"seal-home",version:R,uptimeSeconds:Math.floor(process.uptime()),timestamp:new Date().toISOString()});return}if(u==="GET"&&e==="/api/tools"){Dn(i,200,{count:St.length,tools:St.map((l)=>({name:l.name,description:l.description}))});return}if(u==="POST"&&e==="/api/cli"){let l=await t$(n),$=typeof l?.command==="string"?l.command.trim():"";if(!$){i$(i,400,"Missing or empty 'command' field in request body");return}let I=P4($),g=I[0]==="seal-home"||I[0]?.endsWith("/seal-home")?I.slice(1):I,b=await qe(g),w=void 0;try{if(b.stdout.trim().startsWith("{")||b.stdout.trim().startsWith("["))w=JSON.parse(b.stdout)}catch{}Dn(i,b.isError?400:200,{success:!b.isError,stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,data:w});return}if(u==="POST"&&e.startsWith("/api/tool/")){let l=e.slice(10).trim(),$=jn(l,{includeMcpAliases:!0});if(!$){i$(i,404,`Tool not found: '${l}'`);return}let I=await t$(n)||{},g=zn(n,t,I),b=Nn(g),w=await An(b),f={...I};delete f.corp;let c=await Hn($,w,f,b);Dn(i,200,c);return}if(e.startsWith("/v1/")){if(await mQ(n,i,u,e,t))return}i$(i,404,`Cannot ${u} ${e}. Visit /docs for available endpoints.`)}catch(l){let $=l instanceof Error?l.message:String(l);i$(i,500,$)}}async function mQ(n,i,r,o,t){let e=Object.fromEntries(t.searchParams.entries());if(r==="GET"&&o==="/v1/corps"){let u=hi(),l=bi();return Dn(i,200,{count:u.length,mode:l.stateful?"stateful":"stateless",defaultCorpId:l.defaultCorpId,corps:u.map(($)=>({id:$.id,name:$.name,sourceType:$.source.type,sealUrl:$.seal?.url}))}),!0}if(r==="GET"&&o==="/v1/whoami"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_whoami"),g=await Hn(I,$,{},l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/session"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_session_get"),g=await Hn(I,$,{},l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/summary"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_runs_summary"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/stats"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_runs_stats"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/pick"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_run_pick"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/url"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_run_url_get"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(o.startsWith("/v1/approval-runs/")){let u=o.slice(18).split("/"),l=u[0],$=u[1];if(l&&!["summary","pick","stats","url","bridge"].includes(l)){let I=zn(n,t,e),g=Nn(I),b=await An(g);if(!$){let w=jn("seal_approval_run_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="attachments"){let w=jn("seal_approval_run_attachments_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="cited-rules"){let w=jn("seal_approval_run_cited_rules_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="document-summary"){let w=jn("seal_approval_run_document_summary_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}if($==="result"){let w=jn("seal_approval_run_result_get"),f=await Hn(w,b,{recordId:l,...e},g);return Dn(i,200,f),!0}}}if(r==="GET"&&o==="/v1/approval-runs"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_runs_search"),g=await Hn(I,$,{...e,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):void 0,includeBridge:e.includeBridge==="true"},l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval/rules"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_approval_rules_list"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="GET"&&o==="/v1/simulation/batches"){let u=zn(n,t,e),l=Nn(u),$=await An(l),I=jn("seal_simulation_batches_list"),g=await Hn(I,$,e,l);return Dn(i,200,g),!0}if(r==="POST"&&o==="/v1/simulation/create-batch"){let u=await t$(n)||{},l=zn(n,t,u),$=Nn(l),I=await An($),g=jn("seal_simulaLine truncated
\uD83D\uDE80 seal-home HTTP Server (v${R}) started`),console.error(` URL: http://${r}:${i}`),console.error(` Docs: http://${r}:${i}/docs`),console.error(` OpenAPI: http://${r}:${i}/openapi.json`),console.error(` CLI Exec: POST http://${r}:${i}/api/cli`),console.error(` REST API: http://${r}:${i}/v1/...
`);t(o)})})}async function bN(n){let i=ln(n.options.port)??ln(n.options.p),r=D(n.options.host)??D(n.options.h),o=await gN({port:i,host:r}),t=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}async function wN(n,i,r,o){if(n==="config"||n==="get"){await H("seal_llm_config_get",i,r,{},J(o.options));return}if(n==="providers"||n==="list"){await H("seal_llm_providers_list",i,r,{},J(o.options));return}throw Error(`Unknown llm command: ${n??""}. Run 'seal-home help' for available commands.`)}async function fN(n,i){if(n==="config"||n==="json"){Y4();return}await p4()}function Y4(){K({mcpServers:{"seal-home":{type:"stdio",command:"seal-home",args:["mcp"],env:{SEAL_HOME_MCP_ENABLED:"true"}}}})}function cN(n){let i=n$();K(i,{...J(n.options),allowFull:!0})}async function UN(n,i,r,o){if(n==="available"){await H("seal_permissions_available_list",i,r,{},J(o.options));return}if(n==="configs"||n==="list"){await H("seal_permissions_configs_list",i,r,{},J(o.options));return}throw Error(`Unknown permissions command: ${n??""}. Run 'seal-home help' for available commands.`)}import{readFileSync as DN}from"node:fs";async function SN(n,i,r,o,t,e,u){if(!n||n==="get"){await H("seal_preference_get",t,e,{},J(u.options));return}if(n==="decision"){if(i==="update"||!i){let l=D(u.options.input),$=l?JSON.parse(DN(l,"utf8")):ri(u.json);if(!$||Object.keys($).length===0)throw Error(`Usage: seal-home preference decision update --json '{"explicitApprove":"..."}'`);await H("seal_preference_decision_update",t,e,$,J(u.options));return}}if(n==="thinking-depth"||n==="thinkingDepth"){if(i==="set"){let l=D(u.options.default)??D(u.options.level)??o;if(l!=="medium"&&l!=="high")throw Error("Usage: seal-home preference thinking-depth set --default <medium|high>");await H("seal_preference_thinking_depth_set",t,e,{defaultLevel:l},J(u.options));return}if(i==="policies"){if(r==="list"||!r){await H("seal_preference_thinking_depth_policies_list",t,e,{},J(u.options));return}if(r==="upsert"){let l=D(u.options.input),$=l?JSON.parse(DN(l,"utf8")):ri(u.json);if(!$||!$.id||!$.name)throw Error(`Usage: seal-home preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await H("seal_preference_thinking_depth_policies_upsert",t,e,$,J(u.options));return}if(r==="remove"||r==="delete"){let l=o??D(u.options.id)??D(u.options.policyId);if(!l)throw Error("Usage: seal-home preference thinking-depth policies remove <policyId>");await H("seal_preference_thinking_depth_policies_remove",t,e,{policyId:l},J(u.options));return}}}throw Error(`Unknown preference action: ${n??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function AN(n={}){let i=hi(),r=bi(),o=zr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n.corpId},Kt());console.log(`[probe] corp=${o.id} source=${o.source.type}`);let t=await ar(o);console.log("[probe] seal enterprise"),console.log(JSON.stringify(t,null,2));let e=await An(o),u=await _v(e,{documentLimit:20,stylePreferencesEndpoint:o.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:u.rules.rules.length,hasPendingRuleDeletes:u.rules.hasPendingDeletes,documents:u.documents.articles.length,documentsTotal:u.documents.total,stylePreferences:u.stylePreferences.ok?"ok":`error: ${u.stylePreferences.error}`},null,2))}async function ON(n,i,r){let o=i??D(r.options.corp)??(n&&n!=="--corp"?n:void 0);await AN({corpId:o})}async function kN(n,i,r,o,t){if(n==="count"){await H("seal_approval_rules_list",r,o,{countOnly:!0},J(t.options));return}if(n==="list"){if(_(t.options.count)){await H("seal_approval_rules_list",r,o,{countOnly:!0},J(t.options));return}let e=ln(t.options.limit),u=ln(t.options.offset);if(_(t.options.summary)){await H("seal_approval_rules_list",r,o,{fields:TL,limit:e,offset:u},J(t.options));return}let l=await xr("seal_approval_rules_list",r,o,{limit:e,offset:u});qL(l,_(t.options.full)===!0),K(l);return}if(n==="clear"){let e=_(t.options.yes)===!0,u=_(t.options.dryRun)??_(t.options["dry-run"])??!e;if(!e&&!u)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let l=await xr("seal_approval_rules_clear",r,o,{dryRun:u,recode:_(t.options.recode)});if(!e&&u&&l&&typeof l==="object"){K({...l,nextCommand:`seal-home rules clear --corp ${o.id} --yes`},J(t.options));return}K(l,J(t.options));return}if(n==="versions"){await H("seal_approval_rule_versions_list",r,o,{},J(t.options));return}if(n==="version"){let e=i??D(t.options.version);if(!e)throw Error("Usage: seal-home rules version <versionId|versionNumber|latest>");await H("seal_approval_rule_version_get",r,o,Ke(e),J(t.options));return}if(n==="get"){await H("seal_approval_rule_get",r,o,{...VL(D(t.options.version)),code:D(t.options.code),runtimeId:D(t.options.runtimeId)??D(t.options["runtime-id"]),recordId:D(t.options.recordId)??D(t.options["record-id"])},J(t.options)) Line truncated
`,{mode:384}),o$(r,`running pid=${process.pid}`);let o=()=>{if(F4(i)===process.pid)r$(i,{force:!0});o$(r,`stopped pid=${process.pid}`)};await new Promise((t)=>{let e=!1,u=setInterval(()=>{},60000),l=()=>{if(e)return;e=!0,o(),clearInterval(u),process.off("SIGTERM",l),process.off("SIGINT",l),t()};process.once("SIGTERM",l),process.once("SIGINT",l)})}function dN(n){GN(n.stateDir);let i=sr(n);if(i.running)return i;let r=n.launcher??{command:process.execPath,args:[n.entryFile]},o=zQ(r.command,[...r.args??[],"service","run"],{cwd:n.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});o.unref();let t=e$(n);return Q4(t,`${o.pid}
`,{mode:384}),o$(u$(n),`started pid=${o.pid}`),{started:!0,...sr(n)}}function LN(n,i={}){let r=e$(n),o=F4(r);if(!o||!yN(o,n.appRoot))return r$(r,{force:!0}),i.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(o,"SIGTERM"),r$(r,{force:!0}),o$(u$(n),`stop requested pid=${o}`),i.quiet?void 0:{stopped:!0,pid:o}}function yN(n,i){if(!nF(n))return!1;try{let r=CQ("ps",["-p",String(n),"-o","command="],{encoding:"utf8"});return(r.includes(i)||r.includes("seal-home")||r.includes("src/cli.ts"))&&r.includes("service")&&r.includes("run")}catch{return!1}}function nF(n){try{return process.kill(n,0),!0}catch{return!1}}function e$(n){return NN(n.stateDir,"service.pid")}function u$(n){return NN(n.stateDir,"service.log")}function F4(n){if(!RQ(n))return;let i=Number(aQ(n,"utf8").trim());return Number.isInteger(i)&&i>0?i:void 0}function GN(n){xQ(n,{recursive:!0,mode:448})}function o$(n,i){Q4(n,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var K4=tF(iF(),".config","seal-home");async function jN(n,i){let r=await Et(n,{appRoot:i.appRoot,entryFile:i.entryFile,stateDir:K4,version:R,launcher:i.launcher});if(r!==void 0)K(r)}import{existsSync as rF,readFileSync as WN}from"node:fs";async function JN(n,i,r,o,t){if(n==="batch-records"||n==="records"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation batch-records <batchId>");await H("seal_simulation_batch_records_get",r,o,{batchId:e,query:D(t.options.query)},J(t.options));return}if(n==="create"||n==="run"){let e=D(t.options.mode)??D(t.options.sourceSystem)??D(t.options["source-system"])??"hosecloud",u=e==="material-pack"?"material_pack":e,l=D(t.options.schemaConfig)??D(t.options["schema-config"]),$=l?JSON.parse(WN(l,"utf8")):void 0,I=D(t.options.input),g=I?JSON.parse(WN(I,"utf8")):ri(t.json),b=D(t.options.packageId)??D(t.options["package-id"]),w=Tn(t.options.packageIds)??Tn(t.options["package-ids"])??(b?[b]:void 0),f=Tn(t.options.flowIds)??Tn(t.options["flow-ids"])??Tn(t.options.documentSn)??Tn(t.options["document-sn"]),c=D(t.options.signKey)??D(t.options["sign-key"])??D(t.options.integration);await H("seal_simulation_batch_create",r,o,{mode:u,sourceSystem:u,flowIds:f,documentSn:f,rejectNodeName:D(t.options.rejectNode)??D(t.options["reject-node"])??null,thinkingDepthOverride:D(t.options.thinkingDepth)??D(t.options["thinking-depth"]),skipInvoiceGeneration:_(t.options.skipInvoiceGeneration)??_(t.options["skip-invoice-generation"]),skipExpenseExtraction:_(t.options.skipExpenseExtraction)??_(t.options["skip-expense-extraction"]),disableAttachmentCache:_(t.options.disableAttachmentCache)??_(t.options["disable-attachment-cache"]),signKey:c,packageIds:w,packageId:b,templateId:D(t.options.templateId)??D(t.options["template-id"]),schemaConfig:$,requestIds:Tn(t.options.requestIds)??Tn(t.options["request-ids"]),workflowTypeId:D(t.options.workflowTypeId)??D(t.options["workflow-type-id"]),flowStatusList:Tn(t.options.flowStatusList)?.map(Number)??Tn(t.options["flow-status-list"])?.map(Number),businessCodes:Tn(t.options.businessCodes)??Tn(t.options["business-codes"]),documentType:D(t.options.documentType)??D(t.options["document-type"]),startTime:ln(t.options.startTime)??ln(t.options["start-time"]),endTime:ln(t.options.endTime)??ln(t.options["end-time"]),status:Tn(t.options.status),limit:ln(t.options.limit),rawParams:g},J(t.options));return}if(n==="wait"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await H("seal_simulation_batch_wait",r,o,{batchId:e,timeout:D(t.options.timeout),pollInterval:D(t.options.pollInterval)??D(t.options["poll-interval"])},J(t.options));return}if(n==="clean"||n==="delete"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation clean <batchId>");await H("seal_simulation_batch_clean",r,o,{batchId:e},J(t.options));return}if(n==="specifications"){let e=i??D(t.options.integration)??D(t.options.signKey)??D(t.options["sign-key"]);await H("seal_simulation_specifications_list",r,o,{signKey:e},J(t.options));return}if(n==="list"){await H("seal_simulation_batches_list",r,o,{limit:ln(t.options.limit)},J(t.options));return}if(n==="get"){let e=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!e)throw Error("Usage: seal-home simulation get <batchId>");await H("seal_simulation_batch_get",r,o,{batchId:e},J(t.options));return}if(n==="templates"){await H("seal_simulation_templates_get",r,o,{},J(t.options));return}if(n==="integrations"){await H("seal_simulation_integrations_get",r,o,{},J(t.options));return}if(n==="package-upload"){let e=i??D(t.options.file);if(!e)throw Error("Usage: seal-home simulation package-upload <材料包.zip>");if(!rF(e))throw Error(`File not found: ${e}`);await H("seal_simulation_material_package_upload",r,o,{filePath:e},J(t.options));return}throw Error(`Unknown simulation command: ${n??""}. Run 'seal-home help' for available commands.`)}import{existsSync as ZN}from"node:fs";import{join as l$}from"node:path";import{mkdirSync as TN,writeFileSync as cF}from"node:fs";import{homedir as UF}from"node:os";import{dirname as DF,join as qN}from"node:path";var HN=`---
name: seal-home
description: "v0.9.5: 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."
description: "v0.9.8: Use for Seal Home first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.9.5
short-description: Seal tenant and Hose approval automation (v0.9.5)
version: 0.9.8
short-description: Seal tenant and Hose approval automation (v0.9.8)
---
# Seal Home (v0.9.5)
# Seal Home (v0.9.8)
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.
@@ -235,6 +236,12 @@ seal-home tools list
## First Rules
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
- Before asking for enterprise parameters, run \`seal-home corps list\`. If the target is already configured, resolve its human name to the returned \`id\` and pass that value as \`--corp\`; do not ask the user to know \`corpId\`.
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read \`references/enterprise-onboarding.md\` before asking questions or running setup commands.
- When the user provides a Hose/合思 \`thirdparty.html\` assistance link, use \`seal-home corps add-link <url> [--name ...]\`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
- Never ask a normal user for \`corpId\`, \`staffId\`, \`proxyStaffBizId\`, \`tenantId\`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
- Prefer compact commands first: \`pick\`, \`--summary\`, \`--fields\`, \`attachments --summary\`, \`rules count\`, and \`rules list --summary\`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use \`seal-home corps ...\`.
@@ -251,6 +258,7 @@ seal-home tools list
## Route By Intent
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read \`references/enterprise-onboarding.md\`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
- 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\` (材料包导入), 支持多源系统 \`--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>\`, \`simulation wait <batchId>\` 轮询等待完成, \`simulation clean <batchId>\` 清理数据, \`simulation specifications\` 列出单据模板, \`simulation list\`/\`get\`/\`batch-records\` 查看批次与记录。创建前确认目标环境为测试环境。
@@ -258,7 +266,7 @@ seal-home tools list
- 审核决策偏好与思考深度: \`seal-home preference get --corp <corpId>\`, \`preference decision update --json '...' --corp <corpId>\`, \`preference thinking-depth set --default <medium|high> --corp <corpId>\`, \`preference thinking-depth policies <list|upsert|remove> --corp <corpId>\`.
- 审核大盘统计与去重分析: \`seal-home approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>\`, \`seal-home approval-runs count --corp <corpId>\`.
- 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>\`.
- Delegation links management: \`seal-home delegation list --corp <corpId>\`, \`create [--note ...] --corp <corpId>\`, \`create --from-link <url> [--note ...]\`, \`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>\`.
@@ -307,21 +315,23 @@ seal-home tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅
## References
- \`references/enterprise-onboarding.md\`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- \`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/hose-enterprise-init.md\`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
- \`references/approval-attachment-trace.md\`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。
- \`references/cli.md\`: 完整 CLI 命令清单。
## Safety
Rule, document, style preference, and publish actions mutate Seal configuration. Make the target enterprise explicit, show the intended payload, and verify after the write. Never send real \`enterprises/*.json\` files, tokens, signed URLs, or full raw documents to GitHub, tickets, logs, or chat unless the user explicitly requests a safe export.
`;var AG=`interface:
`;var XN=`interface:
display_name: "Seal Home"
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."
`;var NG=`# Rule Lightweight Queries
`;var hN=`# Rule Lightweight Queries
Use this reference when the user wants rule counts, compact rule lists, one rule from a historical version, or approval knowledge search without dumping hundreds of rule descriptions.
@@ -426,7 +436,7 @@ Use current search only when the question is about current draft/current knowled
## Output Discipline
If a rule command would return many descriptions or more than about 20 rules, use \`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports.
`;var LG=`# Approval Bad Case Catalog
`;var PN=`# Approval Bad Case Catalog
Use this file only as a comparison catalog after inspecting the current trace. Do not treat any case below as a default diagnosis.
@@ -476,7 +486,7 @@ Important nuance:
- This is a bad-case pattern, not a general rule that every amount-total dispute is caused by \`pre_analysis\`.
- Use it when the current trace shows recognized amounts being excluded downstream or duplicate attachments producing inconsistent conclusions.
`;var kG=`# Seal Home CLI Reference
`;var YN=`# Seal Home CLI Reference
Run from any directory after installing the global CLI:
@@ -519,10 +529,11 @@ 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 corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
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 create [--note <note>] [--from-link <url>] [--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>]
@@ -839,7 +850,7 @@ Update style preferences:
- If date-based summaries look wrong, pass \`--timezone Asia/Shanghai\` and an explicit \`--date\`.
- If \`langfuseTraceId\` is missing, use \`langfuseSessionFallback\`.
- If a write operation fails, report the raw JSON error and do not retry with guessed payloads.
`;var GG="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-home approval-runs get <recordId> --corp <corpId> --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-home approval-runs get <recordId> --corp <corpId> --fields metadata\nseal-home approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary\nseal-home approval-runs get <recordId> --corp <corpId> --fields result.summary,result.decision,result.riskPoints\nseal-home approval-runs get <recordId> --corp <corpId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-home approval-runs document-summary <recordId> --corp <corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-home approval-runs cited-rules <recordId> --corp <corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id <recordId> --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\nseal-home approval-runs attachments <recordId> --corp <corpId> --summary\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-home approval-runs result <recordId> --corp <corpId> --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Output Discipline\n\nIf a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.\n";var jG=`# Approval Attachment Trace Investigation
`;var pN="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest\nseal-home approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-home approval-runs get <recordId> --corp <corpId> --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-home approval-runs get <recordId> --corp <corpId> --fields metadata\nseal-home approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary\nseal-home approval-runs get <recordId> --corp <corpId> --fields result.summary,result.decision,result.riskPoints\nseal-home approval-runs get <recordId> --corp <corpId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-home approval-runs document-summary <recordId> --corp <corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-home approval-runs cited-rules <recordId> --corp <corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id <recordId> --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\nseal-home approval-runs attachments <recordId> --corp <corpId> --summary\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-home approval-runs result <recordId> --corp <corpId> --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Output Discipline\n\nIf a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.\n";var QN=`# Approval Attachment Trace Investigation
Use this workflow when a customer disputes an AI approval finding about an attachment, invoice, receipt, OCR result, or a UI-highlighted audit result.
@@ -1060,7 +1071,7 @@ Manual image check:
- The customer's objection that they were receipts rather than invoices was reasonable.
However, the final rejection also had an independent rule-37 reason: payment screenshots totaled 699.48 while reimbursement was 700.00.
`;var WG=`# Customer Feedback Rule Remediation
`;var FN=`# 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.
@@ -1224,7 +1235,130 @@ Return a compact report containing:
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
`;var yG=`# Hose Enterprise Auth
`;var KN=`# Enterprise Onboarding
Read this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.
## Start With Discovery
Run this before asking for setup parameters:
\`\`\`bash
seal-home version
seal-home corps list
\`\`\`
- If the target enterprise is listed, match the user's human enterprise name to its returned \`id\` and use that value as \`--corp\` on every command. Do not ask the user for \`corpId\`.
- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.
- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”
Do not open with a JSON template or a list of internal fields.
All command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.
## Keep Two Concepts Separate
Classify both the enterprise identity origin and how the current credential was acquired:
| Enterprise identity origin | Credential material the user may have | Meaning |
| --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose \`appKey\` + \`appSecurity\` | Stable, refreshable standard integration |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |
| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |
| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |
Credential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When \`whoami\` returns provider metadata, preserve it and use it to describe the tenant accurately.
## Parameter Ownership
Ask the user only for information that cannot be discovered safely:
| Field | Owner and behavior |
| --- | --- |
| \`appKey\`, \`appSecurity\` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |
| \`domain\` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |
| Enterprise name and \`corpId\` | Discover from the credential response or Seal \`whoami\`. Do not ask the user to invent or locate them first. |
| Administrator and \`staffId\` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |
| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal \`whoami\`. |
| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |
## Route 1: Standard Hose Credentials
This is the preferred durable route for a Hose-sourced tenant. Read \`hose-enterprise-init.md\`, then use:
\`\`\`bash
seal-home corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
\`\`\`
The CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with \`staffName\`, \`staffPhone\`, or the selected \`staffId\` internally. After creation, run:
\`\`\`bash
seal-home auth diagnose --corp <discovered-id>
\`\`\`
Do not ask for \`domain\`, \`corpId\`, or \`proxyStaffBizId\` up front. For a dedicated/private Hose deployment, add \`domain\` only after standard probing reports that it cannot find the enterprise.
## Route 2: Incoming Assistance Link
First distinguish the link by its host and purpose:
- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.
- \`seal-home auth hose-link\` and \`seal-home delegation create\` generate links for an enterprise that is already configured. \`seal-home corps add-link <url>\` imports a received Hose/合思 \`thirdparty.html\` assistance link and verifies the resulting Seal tenant.
Use the direct import route when the incoming link is an HTTPS \`thirdparty.html\` URL from a supported \`ekuaibao.com\` or \`hosecloud.com\` domain:
\`\`\`bash
seal-home corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home" [--name "企业名称"]
\`\`\`
The command parses \`accessToken\` and \`ekbCorpId\`, exchanges the temporary Hose token at the target Seal tenant, verifies \`/api/v1/auth/me\`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use \`--overwrite\` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use \`seal-home delegation create --from-link <url> [--note ...]\`.
Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it.
## Route 3: Browser F12 cURL
When the user needs capture instructions, give these concrete steps:
1. Open the already signed-in Hose or Seal page.
2. Open browser developer tools: \`F12\` on many keyboards, or \`Option+Command+I\` on macOS.
3. Open **Network**, then select **Fetch/XHR**.
4. Refresh the page or perform one ordinary read-only business action.
5. Choose a successful business API request from the relevant tenant, not analytics, static assets, upload, delete, publish, or logout requests.
6. Right-click it and choose **Copy → Copy as cURL**.
7. Send that complete cURL only to the local trusted Agent handling setup.
When receiving cURL:
1. Treat the entire cURL as a secret. Do not echo it, execute it blindly, paste it into another service, or store it in repository files.
2. Parse it as data. Extract the request host, path, \`Authorization\` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3. Classify whether the captured request is to Hose or Seal. A Seal request with \`Authorization: Bearer ...\` can supply \`sealUrl\` and a session token even when the user's identity origin is Hose.
4. Verify with the narrowest read-only identity endpoint available. For a Seal Bearer session, verify \`/api/v1/auth/me\` through \`seal-home corps add-seal\`; use returned provider metadata to retain the actual origin.
5. Persist only the normalized minimum configuration needed by seal-home. Do not preserve the raw cURL, unrelated headers, request body, cookies, or signed URL.
For a verified Seal Bearer captured from cURL, the existing CLI route is:
\`\`\`bash
seal-home corps add-seal --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
\`\`\`
The current CLI has no raw-cURL import command and \`add-seal\` requires a Bearer token. If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
## Verify and Hand Off
After adding an enterprise:
\`\`\`bash
seal-home corps list
seal-home corps current --corp <discovered-id>
seal-home auth diagnose --corp <discovered-id> # Hose source
\`\`\`
Report the human enterprise name, identity provider, credential method, and whether verification succeeded. Do not expose internal IDs unless they help with troubleshooting. Do not perform approval, rule, document, simulation, publishing, or other business mutations just because onboarding succeeded; continue only with the user's requested task and its normal confirmation rules.
If a temporary assistance-link or browser session expires, explain that it must be renewed or recaptured. Recommend standard Hose app credentials when the user needs durable unattended access.
`;var BN=`# Hose Enterprise Auth
Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links.
@@ -1232,14 +1366,18 @@ Use this reference for Hose/合思 enterprise configuration and user-facing Hose
Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit \`~/.config/seal-home/enterprises/*.json\` unless the CLI fails or the user explicitly asks for low-level config debugging.
For first-time setup or when the user has an assistance link or browser cURL instead of standard application credentials, read \`enterprise-onboarding.md\` first. This reference's \`add-hose\` route is specifically for durable Hose OpenAPI credentials.
\`\`\`bash
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-home corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
seal-home corps list
seal-home corps current --corp <corpId>
seal-home corps switch <corpId>
\`\`\`
\`corps add-hose\` verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at \`corps\` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
\`corps add-hose\` probes standard domains and discovers the enterprise automatically. If it returns multiple administrator candidates, present their names and masked phones for the user to choose, then retry with \`staffName\`, \`staffPhone\`, or the selected \`staffId\`. Do not ask for \`domain\`, \`corpId\`, \`staffId\`, or \`proxyStaffBizId\` before discovery. Ask for a dedicated/private-cloud \`domain\` only after standard probing fails.
The command verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at \`corps\` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
## Diagnose authentication
@@ -1285,7 +1423,7 @@ Important:
- \`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.
`;var JG=`# Hose Enterprise Initialization & Automated Discovery
`;var VN=`# Hose Enterprise Initialization & Automated Discovery
Use this reference for automated Hose/合思 enterprise onboarding, multi-domain probing (including dedicated private cloud domains like 美年大健康), OpenAPI role and staff discovery, and non-TUI safe administrator selection.
@@ -1391,11 +1529,12 @@ seal-home corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var PG={"SKILL.md":OG,"agents/openai.yaml":AG,"references/rule-lightweight.md":NG,"references/approval-bad-cases.md":LG,"references/cli.md":kG,"references/approval-run-lightweight.md":GG,"references/approval-attachment-trace.md":jG,"references/customer-feedback-rule-remediation.md":WG,"references/hose-enterprise-auth.md":yG,"references/hose-enterprise-init.md":JG};function QG(){return PG["SKILL.md"]||""}function Tu(){return YG(CB(),".agents","skills","seal-home")}function Y0(i=Tu()){XG(i,{recursive:!0});let n=[];for(let[t,o]of Object.entries(PG)){let r=YG(i,t);XG(mB(r),{recursive:!0}),hB(r,o,"utf8"),n.push(t)}return{targetDir:i,files:n}}function HG(){let i=Tu();return Y0(i),{synced:!0,targetDir:i}}function KG(i,n,t){if(i==="dump"||i==="cat"||i==="show"){process.stdout.write(`${QG()}
`);return}if(i==="install"||i==="init"||i==="sync"){let o=z(t.options.local)||z(t.options.workspace),r=c(t.options.dir)??c(t.options.target)??n,u=r?r:o?n$(process.cwd(),".agents","skills","seal-home"):Tu(),l=Y0(u);T({installed:!0,targetDir:l.targetDir,fileCount:l.files.length,files:l.files});return}if(i==="status"||i==="get"||!i){let o=Tu(),r=n$(process.cwd(),".agents","skills","seal-home");T({global:{dir:o,installed:FG(n$(o,"SKILL.md"))},local:{dir:r,installed:FG(n$(r,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${i}. Run 'seal-home help' for available commands.`)}async function BG(i,n){if(i==="config"){T(await mt(n));return}throw Error(`Unknown source command: ${i??""}. Run 'seal-home help' for available commands.`)}async function VG(i,n,t,o){if(!i)throw Error("Usage: seal-home tool <toolName> [--json '{...}']");await Y(i,n,t,tn(o.json),X(o.options))}function TG(){T(Ur.map((i)=>({name:i.name,description:i.description})))}import{chmodSync as RB,mkdirSync as xB,renameSync as P0,rmSync as aB,unlinkSync as MG,writeFileSync as _G}from"node:fs";import{dirname as sB,join as qG}from"node:path";import{spawnSync as Zr}from"node:child_process";function r$(i=process.execPath,n=import.meta.url){if(n.includes("/$bunfs/")||n.includes("\\$bunfs\\"))return!0;let t=i.toLowerCase().replace(/\\/g,"/");return!t.endsWith("/bun")&&!t.endsWith("/bun.exe")}var dG="yunyingk/seal-home";var i3="SEAL_HOME_GITHUB_REPO";async function zG(i,n={}){let t={appRoot:i.appRoot,entryFile:i.entryFile,stateDir:X0,version:m,launcher:i.launcher},o=n.repo||process.env[i3]?.trim()||dG,r=n.targetVersion?.trim(),u=r&&r.toLowerCase()!=="latest"?r:void 0;if(u){let y=u.replace(/^v/,""),G=pG(y,m);if(G<0){T({updated:!1,currentVersion:m,targetVersion:y,mode:r$()?"binary":"source",message:`Cannot downgrade seal-home from v${m} to older version v${y}. Updates must be forward-only.`});return}if(G===0&&!n.force){T({updated:!1,currentVersion:m,targetVersion:y,mode:r$()?"binary":"source",message:`seal-home is already at version v${m}. Use --force to reinstall.`});return}}if(n.changelogOnly){let y=await Q0(o,n.limit??10);T({currentVersion:m,totalQueried:y.length,releases:y.map((G)=>({version:G.version,tagName:G.tagName,publishedAt:G.publishedAt,author:G.author,releaseNotes:G.notes,releaseUrl:G.htmlUrl,isCurrent:G.version===m,isNewer:_u(G.version,m)}))});return}if(!r$()){if(n.checkOnly){let G=await Q0(o,30),a=G[0],ni=a?.version??m,Ji=G.find((gi)=>gi.version===m),Bi=_u(ni,m),Vi=G.filter((gi)=>_u(gi.version,m));T({updated:!1,updateAvailable:Bi,currentVersion:m,currentVersionPublishedAt:Ji?.publishedAt,latestVersion:ni,latestVersionPublishedAt:a?.publishedAt,behindCount:Vi.length,pendingReleases:Vi.map((gi)=>({version:gi.version,tagName:gi.tagName,publishedAt:gi.publishedAt,author:gi.author,releaseNotes:gi.notes,releaseUrl:gi.htmlUrl})),releaseNotes:a?.notes??"",releaseUrl:a?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-home update' to git pull & bun install."});return}let y=Rt(t).running;if(y)await Er("stop",t);try{ZG("git",["-C",i.appRoot,"pull","--ff-only"])}catch(G){console.error(`git pull skipped: ${G instanceof Error?G.message:String(G)}`)}if(ZG("bun",["install"],{cwd:i.appRoot}),y)await Er("start",t);T({updated:!0,serviceRestarted:y,version:m,mode:"source"});return}let l=n3(),e=r3(),$=await Q0(o,30),I=u?$.find((y)=>y.version===u||y.tagName===u||y.tagName===`v${u}`)??await EG(o,u):$[0]??await EG(o);if(!I){T({updated:!1,currentVersion:m,mode:"binary",message:`Failed to query releases from GitHub repository '${o}'`});return}let g=I.version,b=$.find((y)=>y.version===m),w=_u(g,m),f=w||Boolean(n.force),D=$.filter((y)=>_u(y.version,m));if(n.checkOnly){T({updated:!1,updateAvailable:w,currentVersion:m,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:D.length,pendingReleases:D.map((y)=>({version:y.version,tagName:y.tagName,publishedAt:y.publishedAt,author:y.author,releaseNotes:y.notes,releaseUrl:y.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!f){T({updated:!1,currentVersion:m,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-home is already up to date (v${m})`});return}let S=t3(I.assets,l,e);if(!S)throw Error(`No compatible binary found for ${l}-${e} in release v${g}. Available assets: ${I.assets.map((y)=>y.name).join(", ")}`);let N=Rt(t).running;if(N)await Er("stop",t);let L=process.execPath,K=sB(L),F=qG(K,`.tmp-update-${Date.now()}`);xB(F,{recursive:!0});try{let y=qG(F,S.name);await o3(S.downloadUrl,y,I.tagName,S.name);let G=y;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))G=u3(y,F,l);else if(S.name.endsWith(".zip"))G=l3(y,F,l);if(RB(G,493),process.platform==="darwin")try{Zr("/usr/bin/codesign",["--remove-signature",G],{stdio:"ignore"}),Zr("/usr/bin/codesign",["--force","--sign","-",G],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let ni Line truncated
`)}catch{}console.error(i)}async function o3(i,n,t,o){let r=[],u=t?t.startsWith("v")?t:`v${t}`:void 0,l=o||i.split("/").pop()||"";if(u&&l)r.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${u}/${l}`);if(i.startsWith("https://git.ying-qing.cn"))r.push(i);if(u&&l){let I=`https://github.com/${dG}/releases/download/${u}/${l}`;r.push(`https://ghfast.top/${I}`),r.push(`https://ghproxy.net/${I}`),r.push(`https://gh.ddlc.top/${I}`),r.push(`https://mirror.ghproxy.com/${I}`),r.push(I)}else if(i.includes("github.com"))r.push(`https://ghfast.top/${i}`),r.push(`https://ghproxy.net/${i}`),r.push(`https://gh.ddlc.top/${i}`),r.push(`https://mirror.ghproxy.com/${i}`),r.push(i);else r.push(i);let e=Array.from(new Set(r)),$;for(let I=0;I<e.length;I++){let g=e[I];try{t$(`==> [${I+1}/${e.length}] Downloading via: ${g}`);let b=await fetch(g,{signal:AbortSignal.timeout(6000)});if(!b.ok)throw Error(`HTTP ${b.status} ${b.statusText}`);let w=Number(b.headers.get("content-length"))||0,f=b.body?.getReader();if(!f){let K=Buffer.from(await b.arrayBuffer());if(K.length<1000)throw Error(`Downloaded content is suspiciously small (${K.length} bytes)`);_G(n,K),t$(`✓ Download succeeded (${(K.length/1024/1024).toFixed(1)} MB)`);return}let D=[],S=0,N=0;while(!0){let{done:K,value:F}=await f.read();if(K)break;if(F){D.push(F),S+=F.length;let y=Date.now();if(y-N>200){N=y;let G=w?Math.round(S/w*100):0,a=(S/1048576).toFixed(1),ni=w?(w/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${G}% (${a} / ${ni} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let L=Buffer.concat(D);if(L.length<1000)throw Error(`Downloaded content is suspiciously small (${L.length} bytes)`);_G(n,L),t$(`✓ Download completed successfully (${(L.length/1024/1024).toFixed(1)} MB)`);return}catch(b){$=b instanceof Error?b:Error(String(b)),t$(` ↳ Mirror failed: ${$.message}`)}}throw Error(`Failed to download asset from all mirrors: ${$?.message}`)}function u3(i,n,t){let o=Zr("tar",["-xzf",i,"-C",n],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract tar archive: ${o.stderr.toString()}`);MG(i);let r=t==="windows"?"seal-home.exe":"seal-home",u=Zr("find",[n,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),l=u.find((e)=>e.endsWith(`/${r}`)||e.endsWith(r));if(l)return l;return u[0]||i}function l3(i,n,t){let o=Zr("unzip",["-q","-o",i,"-d",n],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract zip archive: ${o.stderr.toString()}`);MG(i);let r=t==="windows"?"seal-home.exe":"seal-home",u=Zr("find",[n,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),l=u.find((e)=>e.endsWith(`/${r}`)||e.endsWith(r));if(l)return l;return u[0]||i}function pG(i,n){let t=i.replace(/^v/,"").split(".").map((r)=>Number.parseInt(r,10)||0),o=n.replace(/^v/,"").split(".").map((r)=>Number.parseInt(r,10)||0);for(let r=0;r<Math.max(t.length,o.length);r++){let u=t[r]??0,l=o[r]??0;if(u>l)return 1;if(u<l)return-1}return 0}function _u(i,n){return pG(i,n)>0}function ZG(i,n,t={}){let o=Zr(i,n,{cwd:t.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(o.stdout)console.error(o.stdout.trimEnd());if(o.stderr)console.error(o.stderr.trimEnd());if(o.status!==0)throw Error(`${i} ${n.join(" ")} failed with status ${o.status}`)}async function hG(i,n,t,o,r){if(i==="create"){let u=c(r.options.name)??n,l=c(r.options.phone);if(!u||!l)throw Error("Usage: seal-home users create --name <name> --phone <phone> [--dept <deptId>]");let e=c(r.options.dept)??c(r.options.departmentId);await Y("seal_user_create",t,o,{name:u,phone:l,departmentIds:e?[e]:void 0},X(r.options));return}if(i==="reset-password"){let u=n??c(r.options.userId);if(!u)throw Error("Usage: seal-home users reset-password <userId>");await Y("seal_user_reset_password",t,o,{userId:u},X(r.options));return}if(i==="search"||i==="list"){let u=n??c(r.options.keyword)??c(r.options.query)??"";await Y("seal_user_search",t,o,{keyword:u},X(r.options));return}if(i==="get"){let u=n??c(r.options.userId);if(!u)throw Error("Usage: seal-home users get <userId>");await Y("seal_user_get",t,o,{userId:u},X(r.options));return}if(i==="delete"){let u=n??c(r.options.userId);if(!u)throw Error("Usage: seal-home users delete <userId>");await Y("seal_user_delete",t,o,{userId:u},X(r.options));return}if(i==="activate"){let u=n??c(r.options.userId);if(!u)throw Error("Usage: seal-home users activate <userId>");await Y("seal_user_activate",t,o,{userId:u},X(r.options));return}if(i==="delegation"||i==="impersonate"){let u=n??c(r.options.userId)??c(r.options.phone);if(!u)throw Error("Usage: seal-home users delegation <userIdOrPhone> [--note <note>]");let l=c(r.options.note);await Y("seal_user_delegation_create",t,o,{userIdOrPhone:u,note:l},X(r.options));return}throw Error(`Unknown users command: ${i??""}. Run 'seal-home help' for available commands.`)}async function CG(i,n,t,o,r){if(i==="list"){await Y("seal_webhook_list",t,o,{query:c(r.options.query)??c(r.options.keyword),includeSecret:N0(r.options)},X(r.options));return}if(i==="get"||i==="find"){let u=n??c(r.options.selector)??c(r.options.id);if(!u)throw Error("Usage: seal-home webhook get <idOrName> [--show-secret]");await Y("seal_webhook_get",t,o,{selector:u,includeSecret:N0(r.options)},X(r.options));return}if(i==="add"||i==="create"){let u=c(r.options.name)??n,l=c(r.options.resultUrl)??c(r.options["result-url"])??c(r.options.outgoingResultWebhook)??c(r.options["outgoing-result-webhook"]);if(!u||!l)throw Error("Usage: seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let e=A0(r.options);await Y("seal_webhook_add",t,o,{name:u,mode:O0(c(r.options.mode)),outgoingResultWebhook:l,autoApprovalRate:e,secret:c(r.options.secret)},X(r.options));return}if(i==="update"){let u=n??c(r.options.selector)??c(r.options.id);if(!u)throw Error("Usage: seal-home webhook update <idOrName> [options]");let l=c(r.options.secret),e=z(r.options.rotateSecret)??z(r.options["rotate-secret"]);if(l!==void 0&&e)throw Error("Use either --secret or --rotate-secret, not both");let $=c(r.options.name),I=O0(c(r.options.mode)),g=c(r.options.resultUrl)??c(r.options["result-url"])??c(r.options.outgoingResultWebhook)??c(r.options["outgoing-result-webhook"]),b=A0(r.options);if($===void 0&&I===void 0&&g===void 0&&b===void 0&&l===void 0&&!e)throw Error("Webhook update requires at least one field option");await Y("seal_webhook_update",t,o,{selector:u,name:$,mode:I,outgoingResultWebhook:g,autoApprovalRate:b,secret:l,rotateSecret:e},X(r.options));return}if(i==="delete"){let u=n??c(r.options.selector)??c(r.options.id);if(!u)throw Error("Usage: seal-home webhook delete <idOrName> --yes");if(z(r.options.yes)!==!0)throw Error("Refusing to delete Webhook integration without --yes");await Y("seal_webhook_delete",t,o,{selector:u,confirm:!0},X(r.options));return}throw Error(`Unknown webhook command: ${i??""}. Run 'seal-home help' for available commands.`)}var mG=H0(H0(H0(v3(import.meta.url)))),$3=new Set(["config","service","http","serve","update","tools","corps","tool","source","auth","delegation","users","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","changelog"]),RG=Promise.resolve();function Vu(i,n={}){let t=RG.then(()=>I3(i,n));return RG=t.then(()=>{return},()=>{return}),t}async function I3(i,n){let t=[],o=[],r=console.log,u=console.error,l={appRoot:n.appRoot??mG,entryFile:n.entryFile??e3(n.appRoot??mG,"src","cli.ts"),launcher:n.launcher};console.log=(...e)=>{t.pu Line truncated
`;var _N={"SKILL.md":HN,"agents/openai.yaml":XN,"references/rule-lightweight.md":hN,"references/approval-bad-cases.md":PN,"references/cli.md":YN,"references/approval-run-lightweight.md":pN,"references/approval-attachment-trace.md":QN,"references/customer-feedback-rule-remediation.md":FN,"references/enterprise-onboarding.md":KN,"references/hose-enterprise-auth.md":BN,"references/hose-enterprise-init.md":VN};function EN(){return _N["SKILL.md"]||""}function _e(){return qN(UF(),".agents","skills","seal-home")}function B4(n=_e()){TN(n,{recursive:!0});let i=[];for(let[r,o]of Object.entries(_N)){let t=qN(n,r);TN(DF(t),{recursive:!0}),cF(t,o,"utf8"),i.push(r)}return{targetDir:n,files:i}}function mN(){let n=_e();return B4(n),{synced:!0,targetDir:n}}function MN(n,i,r){if(n==="dump"||n==="cat"||n==="show"){process.stdout.write(`${EN()}
`);return}if(n==="install"||n==="init"||n==="sync"){let o=_(r.options.local)||_(r.options.workspace),t=D(r.options.dir)??D(r.options.target)??i,e=t?t:o?l$(process.cwd(),".agents","skills","seal-home"):_e(),u=B4(e);K({installed:!0,targetDir:u.targetDir,fileCount:u.files.length,files:u.files});return}if(n==="status"||n==="get"||!n){let o=_e(),t=l$(process.cwd(),".agents","skills","seal-home");K({global:{dir:o,installed:ZN(l$(o,"SKILL.md"))},local:{dir:t,installed:ZN(l$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${n}. Run 'seal-home help' for available commands.`)}async function zN(n,i){if(n==="config"){K(await ar(i));return}throw Error(`Unknown source command: ${n??""}. Run 'seal-home help' for available commands.`)}async function CN(n,i,r,o){if(!n)throw Error("Usage: seal-home tool <toolName> [--json '{...}']");await H(n,i,r,ri(o.json),J(o.options))}function RN(){K(St.map((n)=>({name:n.name,description:n.description})))}import{chmodSync as SF,mkdirSync as AF,renameSync as V4,rmSync as OF,unlinkSync as iy,writeFileSync as xN}from"node:fs";import{dirname as kF,join as aN}from"node:path";import{spawnSync as mt}from"node:child_process";function v$(n=process.execPath,i=import.meta.url){if(i.includes("/$bunfs/")||i.includes("\\$bunfs\\"))return!0;let r=n.toLowerCase().replace(/\\/g,"/");return!r.endsWith("/bun")&&!r.endsWith("/bun.exe")}var ty="yunyingk/seal-home";var dF="SEAL_HOME_GITHUB_REPO";async function ry(n,i={}){let r={appRoot:n.appRoot,entryFile:n.entryFile,stateDir:K4,version:R,launcher:n.launcher},o=i.repo||process.env[dF]?.trim()||ty,t=i.targetVersion?.trim(),e=t&&t.toLowerCase()!=="latest"?t:void 0;if(e){let j=e.replace(/^v/,""),L=oy(j,R);if(L<0){K({updated:!1,currentVersion:R,targetVersion:j,mode:v$()?"binary":"source",message:`Cannot downgrade seal-home from v${R} to older version v${j}. Updates must be forward-only.`});return}if(L===0&&!i.force){K({updated:!1,currentVersion:R,targetVersion:j,mode:v$()?"binary":"source",message:`seal-home is already at version v${R}. Use --force to reinstall.`});return}}if(i.changelogOnly){let j=await T4(o,i.limit??10);K({currentVersion:R,totalQueried:j.length,releases:j.map((L)=>({version:L.version,tagName:L.tagName,publishedAt:L.publishedAt,author:L.author,releaseNotes:L.notes,releaseUrl:L.htmlUrl,isCurrent:L.version===R,isNewer:Ee(L.version,R)}))});return}if(!v$()){if(i.checkOnly){let L=await T4(o,30),q=L[0],x=q?.version??R,yn=L.find((en)=>en.version===R),Wn=Ee(x,R),On=L.filter((en)=>Ee(en.version,R));K({updated:!1,updateAvailable:Wn,currentVersion:R,currentVersionPublishedAt:yn?.publishedAt,latestVersion:x,latestVersionPublishedAt:q?.publishedAt,behindCount:On.length,pendingReleases:On.map((en)=>({version:en.version,tagName:en.tagName,publishedAt:en.publishedAt,author:en.author,releaseNotes:en.notes,releaseUrl:en.htmlUrl})),releaseNotes:q?.notes??"",releaseUrl:q?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-home update' to git pull & bun install."});return}let j=sr(r).running;if(j)await Et("stop",r);try{ny("git",["-C",n.appRoot,"pull","--ff-only"])}catch(L){console.error(`git pull skipped: ${L instanceof Error?L.message:String(L)}`)}if(ny("bun",["install"],{cwd:n.appRoot}),j)await Et("start",r);K({updated:!0,serviceRestarted:j,version:R,mode:"source"});return}let u=LF(),l=NF(),$=await T4(o,30),I=e?$.find((j)=>j.version===e||j.tagName===e||j.tagName===`v${e}`)??await sN(o,e):$[0]??await sN(o);if(!I){K({updated:!1,currentVersion:R,mode:"binary",message:`Failed to query releases from GitHub repository '${o}'`});return}let g=I.version,b=$.find((j)=>j.version===R),w=Ee(g,R),f=w||Boolean(i.force),c=$.filter((j)=>Ee(j.version,R));if(i.checkOnly){K({updated:!1,updateAvailable:w,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:c.length,pendingReleases:c.map((j)=>({version:j.version,tagName:j.tagName,publishedAt:j.publishedAt,author:j.author,releaseNotes:j.notes,releaseUrl:j.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!f){K({updated:!1,currentVersion:R,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-home is already up to date (v${R})`});return}let S=yF(I.assets,u,l);if(!S)throw Error(`No compatible binary found for ${u}-${l} in release v${g}. Available assets: ${I.assets.map((j)=>j.name).join(", ")}`);let k=sr(r).running;if(k)await Et("stop",r);let d=process.execPath,p=kF(d),h=aN(p,`.tmp-update-${Date.now()}`);AF(h,{recursive:!0});try{let j=aN(h,S.name);await GF(S.downloadUrl,j,I.tagName,S.name);let L=j;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))L=jF(j,h,u);else if(S.name.endsWith(".zip"))L=WF(j,h,u);if(SF(L,493),process.platform==="darwin")try{mt("/usr/bin/codesign",["--remove-signature",L],{stdio:"ignore"}),mt("/usr/bin/codesign",["--force","--sign","-",L],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let x=`${Line truncated
`)}catch{}}async function GF(n,i,r,o){let t=[],e=r?r.startsWith("v")?r:`v${r}`:void 0,u=o||n.split("/").pop()||"";if(e&&u)t.push(`https://git.ying-qing.cn/gitea/seal-home/releases/download/${e}/${u}`);if(n.startsWith("https://git.ying-qing.cn"))t.push(n);if(e&&u){let c=`https://github.com/${ty}/releases/download/${e}/${u}`;t.push(`https://ghfast.top/${c}`),t.push(`https://gh.ddlc.top/${c}`),t.push(c)}else if(n.includes("github.com"))t.push(`https://ghfast.top/${n}`),t.push(`https://gh.ddlc.top/${n}`),t.push(n);else t.push(n);let l=Array.from(new Set(t)),$,I=6000,g=6000,b=307200,w=1e4,f=180000;for(let c=0;c<l.length;c++){let S=l[c],k=new AbortController,d="",p=(q)=>{d=q;try{k.abort()}catch{}},h=setTimeout(()=>{p("Connection timed out (no response headers within 6s)")},I),j,L;try{$$(`==> [${c+1}/${l.length}] Downloading via: ${S}`);let q=await fetch(S,{signal:k.signal});if(h)clearTimeout(h),h=void 0;if(!q.ok)throw Error(`HTTP ${q.status} ${q.statusText}`);j=setTimeout(()=>{p("Overall download time exceeded 3 minutes")},f);let x=Number(q.headers.get("content-length"))||0,yn=q.body?.getReader();if(!yn){let wi=Buffer.from(await q.arrayBuffer());if(wi.length<1000)throw Error(`Downloaded content is suspiciously small (${wi.length} bytes)`);xN(i,wi),$$(`✓ Download succeeded (${(wi.length/1024/1024).toFixed(1)} MB)`);return}let Wn=[],On=0,en=0;L=setTimeout(()=>{if(On<b){let wi=(On/1024).toFixed(1);p(`Initial transfer too slow (${wi} KB < 300 KB in 6s), switching mirror...`)}},g);while(!0){let wi=yn.read(),no,gy=new Promise((g$,b$)=>{no=setTimeout(()=>{b$(Error("Data transfer stalled (no chunk received for 10s)"))},w)}),E4;try{E4=await Promise.race([wi,gy])}finally{if(no)clearTimeout(no)}let{done:by,value:I$}=E4;if(by)break;if(I$){if(Wn.push(I$),On+=I$.length,L&&On>=b)clearTimeout(L),L=void 0;let g$=Date.now();if(g$-en>200){en=g$;let b$=x?Math.round(On/x*100):0,wy=(On/1048576).toFixed(1),fy=x?(x/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${b$}% (${wy} / ${fy} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let kt=Buffer.concat(Wn);if(kt.length<1000)throw Error(`Downloaded content is suspiciously small (${kt.length} bytes)`);xN(i,kt),$$(`✓ Download completed successfully (${(kt.length/1024/1024).toFixed(1)} MB)`);return}catch(q){if(h)clearTimeout(h);if(L)clearTimeout(L);if(j)clearTimeout(j);let x=d||(q instanceof Error?q.message:String(q));$=Error(x),$$(`
↳ Mirror failed: ${$.message}`)}finally{if(h)clearTimeout(h);if(L)clearTimeout(L);if(j)clearTimeout(j)}}throw Error(`Failed to download asset from all mirrors: ${$?.message}`)}function jF(n,i,r){let o=mt("tar",["-xzf",n,"-C",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract tar archive: ${o.stderr.toString()}`);iy(n);let t=r==="windows"?"seal-home.exe":"seal-home",e=mt("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),u=e.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(u)return u;return e[0]||n}function WF(n,i,r){let o=mt("unzip",["-q","-o",n,"-d",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract zip archive: ${o.stderr.toString()}`);iy(n);let t=r==="windows"?"seal-home.exe":"seal-home",e=mt("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),u=e.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(u)return u;return e[0]||n}function oy(n,i){let r=n.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0),o=i.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0);for(let t=0;t<Math.max(r.length,o.length);t++){let e=r[t]??0,u=o[t]??0;if(e>u)return 1;if(e<u)return-1}return 0}function Ee(n,i){return oy(n,i)>0}function ny(n,i,r={}){let o=mt(n,i,{cwd:r.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(o.stdout)console.error(o.stdout.trimEnd());if(o.stderr)console.error(o.stderr.trimEnd());if(o.status!==0)throw Error(`${n} ${i.join(" ")} failed with status ${o.status}`)}async function ey(n,i,r,o,t){if(n==="create"){let e=D(t.options.name)??i,u=D(t.options.phone);if(!e||!u)throw Error("Usage: seal-home users create --name <name> --phone <phone> [--dept <deptId>]");let l=D(t.options.dept)??D(t.options.departmentId);await H("seal_user_create",r,o,{name:e,phone:u,departmentIds:l?[l]:void 0},J(t.options));return}if(n==="reset-password"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users reset-password <userId>");await H("seal_user_reset_password",r,o,{userId:e},J(t.options));return}if(n==="search"||n==="list"){let e=i??D(t.options.keyword)??D(t.options.query)??"";await H("seal_user_search",r,o,{keyword:e},J(t.options));return}if(n==="get"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users get <userId>");await H("seal_user_get",r,o,{userId:e},J(t.options));return}if(n==="delete"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users delete <userId>");await H("seal_user_delete",r,o,{userId:e},J(t.options));return}if(n==="activate"){let e=i??D(t.options.userId);if(!e)throw Error("Usage: seal-home users activate <userId>");await H("seal_user_activate",r,o,{userId:e},J(t.options));return}if(n==="delegation"||n==="impersonate"){let e=i??D(t.options.userId)??D(t.options.phone);if(!e)throw Error("Usage: seal-home users delegation <userIdOrPhone> [--note <note>]");let u=D(t.options.note);await H("seal_user_delegation_create",r,o,{userIdOrPhone:e,note:u},J(t.options));return}throw Error(`Unknown users command: ${n??""}. Run 'seal-home help' for available commands.`)}async function uy(n,i,r,o,t){if(n==="list"){await H("seal_webhook_list",r,o,{query:D(t.options.query)??D(t.options.keyword),includeSecret:H4(t.options)},J(t.options));return}if(n==="get"||n==="find"){let e=i??D(t.options.selector)??D(t.options.id);if(!e)throw Error("Usage: seal-home webhook get <idOrName> [--show-secret]");await H("seal_webhook_get",r,o,{selector:e,includeSecret:H4(t.options)},J(t.options));return}if(n==="add"||n==="create"){let e=D(t.options.name)??i,u=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]);if(!e||!u)throw Error("Usage: seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let l=J4(t.options);await H("seal_webhook_add",r,o,{name:e,mode:W4(D(t.options.mode)),outgoingResultWebhook:u,autoApprovalRate:l,secret:D(t.options.secret)},J(t.options));return}if(n==="update"){let e=i??D(t.options.selector)??D(t.options.id);if(!e)throw Error("Usage: seal-home webhook update <idOrName> [options]");let u=D(t.options.secret),l=_(t.options.rotateSecret)??_(t.options["rotate-secret"]);if(u!==void 0&&l)throw Error("Use either --secret or --rotate-secret, not both");let $=D(t.options.name),I=W4(D(t.options.mode)),g=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]),b=J4(t.options);if($===void 0&&I===void 0&&g===void 0&&b===void 0&&u===void 0&&!l)throw Error("Webhook update requires at least one field option");await H("seal_webhook_update",r,o,{selector:e,name:$,mode:I,outgoingResultWebhook:g,autoApprovalRate:b,secret:u,rotateSecret:l},J(t.options));return}if(n==="delete"){let e=i??D(t.options.selector)??D(t.options.id);if(!e)throw Error("Usage: seal-home webhook delete <idOrName> --yes");if(_(t.options.yes)!==!0)throw Error("Refusing to delete Webhook integration without --yes");await H("seal_webhook_delete",r,o,{selector:e,confirm:!0},J(t.options));return}throw Error(`Unknown webhook command: ${n??""}. Run 'seal-home help' for available commands.`)}var ly=q4(q4(q4(HF(import.meta.url)))),XF=new Set(["config","service","http","serve","update","tools","corps","tool","source","auth","delegation","users","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","changelog"]),vy=Promise.resolve();function qe(n,i={}){let r=vy.then(()=>hF(n,i));return vy=r.then(()=>{return},()=>{return}),r}async function hF(n,i){let r=[],o=[],t=console.log,e=console.error,u={appRoot:i.appRoot??ly,entryFile:i.entryFile??JF(i.appRoot??ly,"src","cli.ts"),launcher:i.launcher};console.log=(...l)=>{r.pu Line truncated
`)?"":`
`}`);process.exitCode=i.exitCode}var O3=Boolean(T0.main==T0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&xG(process.argv[1])===xG(zn));if(O3)if(process.argv[2]==="--seal-home-cli")await S3();else W0().catch((i)=>{console.error(i),process.exitCode=1});export{G0 as tokenizeCommand,W0 as startServer,D3 as resolveMcpEnabled,U3 as createServer,f3 as SEAL_MCP_ENABLED_ENV,w3 as SEAL_CLI_TOOL_NAME};
`}`);process.exitCode=n.exitCode}var TF=Boolean(Z4.main==Z4.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&$y(process.argv[1])===$y(zi));if(TF)if(process.argv[2]==="--seal-home-cli")await VF();else p4().catch((n)=>{console.error(n),process.exitCode=1});export{P4 as tokenizeCommand,p4 as startServer,FF as resolveMcpEnabled,KF as createServer,QF as SEAL_MCP_ENABLED_ENV,pF as SEAL_CLI_TOOL_NAME};
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "seal-home Wrapped API",
"version": "0.9.5",
"version": "0.9.8",
"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": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: seal-home Wrapped API
version: 0.9.5
version: 0.9.8
description: |
Planned HTTP contract for the seal-home wrapped backend API.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-home",
"version": "0.9.5",
"version": "0.9.8",
"type": "module",
"module": "src/server.ts",
"bin": {
+14 -5
View File
@@ -1,12 +1,12 @@
---
name: seal-home
description: "v0.9.5: 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."
description: "v0.9.8: Use for Seal Home first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.9.5
short-description: Seal tenant and Hose approval automation (v0.9.5)
version: 0.9.8
short-description: Seal tenant and Hose approval automation (v0.9.8)
---
# Seal Home (v0.9.5)
# Seal Home (v0.9.8)
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.
@@ -18,6 +18,12 @@ seal-home tools list
## First Rules
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
- Before asking for enterprise parameters, run `seal-home corps list`. If the target is already configured, resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`.
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read `references/enterprise-onboarding.md` before asking questions or running setup commands.
- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-home corps add-link <url> [--name ...]`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
- Never ask a normal user for `corpId`, `staffId`, `proxyStaffBizId`, `tenantId`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use `seal-home corps ...`.
@@ -34,6 +40,7 @@ seal-home tools list
## Route By Intent
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read `references/enterprise-onboarding.md`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
- 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` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
@@ -41,7 +48,7 @@ seal-home tools list
- 审核决策偏好与思考深度: `seal-home preference get --corp <corpId>`, `preference decision update --json '...' --corp <corpId>`, `preference thinking-depth set --default <medium|high> --corp <corpId>`, `preference thinking-depth policies <list|upsert|remove> --corp <corpId>`.
- 审核大盘统计与去重分析: `seal-home approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>`, `seal-home approval-runs count --corp <corpId>`.
- 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>`.
- Delegation links management: `seal-home delegation list --corp <corpId>`, `create [--note ...] --corp <corpId>`, `create --from-link <url> [--note ...]`, `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>`.
@@ -90,10 +97,12 @@ seal-home tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅
## References
- `references/enterprise-onboarding.md`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- `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/hose-enterprise-init.md`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
- `references/approval-attachment-trace.md`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。
- `references/cli.md`: 完整 CLI 命令清单。
+2 -1
View File
@@ -41,10 +41,11 @@ 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 corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
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 create [--note <note>] [--from-link <url>] [--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>]
@@ -0,0 +1,123 @@
# Enterprise Onboarding
Read this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.
## Start With Discovery
Run this before asking for setup parameters:
```bash
seal-home version
seal-home corps list
```
- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.
- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.
- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”
Do not open with a JSON template or a list of internal fields.
All command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.
## Keep Two Concepts Separate
Classify both the enterprise identity origin and how the current credential was acquired:
| Enterprise identity origin | Credential material the user may have | Meaning |
| --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |
| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |
| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |
Credential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.
## Parameter Ownership
Ask the user only for information that cannot be discovered safely:
| Field | Owner and behavior |
| --- | --- |
| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |
| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |
| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |
| Administrator and `staffId` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |
| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |
| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |
## Route 1: Standard Hose Credentials
This is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:
```bash
seal-home corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
```
The CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:
```bash
seal-home auth diagnose --corp <discovered-id>
```
Do not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.
## Route 2: Incoming Assistance Link
First distinguish the link by its host and purpose:
- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.
- `seal-home auth hose-link` and `seal-home delegation create` generate links for an enterprise that is already configured. `seal-home corps add-link <url>` imports a received Hose/合思 `thirdparty.html` assistance link and verifies the resulting Seal tenant.
Use the direct import route when the incoming link is an HTTPS `thirdparty.html` URL from a supported `ekuaibao.com` or `hosecloud.com` domain:
```bash
seal-home corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home" [--name "企业名称"]
```
The command parses `accessToken` and `ekbCorpId`, exchanges the temporary Hose token at the target Seal tenant, verifies `/api/v1/auth/me`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use `--overwrite` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use `seal-home delegation create --from-link <url> [--note ...]`.
Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it.
## Route 3: Browser F12 cURL
When the user needs capture instructions, give these concrete steps:
1. Open the already signed-in Hose or Seal page.
2. Open browser developer tools: `F12` on many keyboards, or `Option+Command+I` on macOS.
3. Open **Network**, then select **Fetch/XHR**.
4. Refresh the page or perform one ordinary read-only business action.
5. Choose a successful business API request from the relevant tenant, not analytics, static assets, upload, delete, publish, or logout requests.
6. Right-click it and choose **Copy → Copy as cURL**.
7. Send that complete cURL only to the local trusted Agent handling setup.
When receiving cURL:
1. Treat the entire cURL as a secret. Do not echo it, execute it blindly, paste it into another service, or store it in repository files.
2. Parse it as data. Extract the request host, path, `Authorization` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3. Classify whether the captured request is to Hose or Seal. A Seal request with `Authorization: Bearer ...` can supply `sealUrl` and a session token even when the user's identity origin is Hose.
4. Verify with the narrowest read-only identity endpoint available. For a Seal Bearer session, verify `/api/v1/auth/me` through `seal-home corps add-seal`; use returned provider metadata to retain the actual origin.
5. Persist only the normalized minimum configuration needed by seal-home. Do not preserve the raw cURL, unrelated headers, request body, cookies, or signed URL.
For a verified Seal Bearer captured from cURL, the existing CLI route is:
```bash
seal-home corps add-seal --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
```
The current CLI has no raw-cURL import command and `add-seal` requires a Bearer token. If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
## Verify and Hand Off
After adding an enterprise:
```bash
seal-home corps list
seal-home corps current --corp <discovered-id>
seal-home auth diagnose --corp <discovered-id> # Hose source
```
Report the human enterprise name, identity provider, credential method, and whether verification succeeded. Do not expose internal IDs unless they help with troubleshooting. Do not perform approval, rule, document, simulation, publishing, or other business mutations just because onboarding succeeded; continue only with the user's requested task and its normal confirmation rules.
If a temporary assistance-link or browser session expires, explain that it must be renewed or recaptured. Recommend standard Hose app credentials when the user needs durable unattended access.
@@ -6,14 +6,18 @@ Use this reference for Hose/合思 enterprise configuration and user-facing Hose
Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit `~/.config/seal-home/enterprises/*.json` unless the CLI fails or the user explicitly asks for low-level config debugging.
For first-time setup or when the user has an assistance link or browser cURL instead of standard application credentials, read `enterprise-onboarding.md` first. This reference's `add-hose` route is specifically for durable Hose OpenAPI credentials.
```bash
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-home corps add-hose --json '{"appKey":"...","appSecurity":"..."}'
seal-home corps list
seal-home corps current --corp <corpId>
seal-home corps switch <corpId>
```
`corps add-hose` verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at `corps` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
`corps add-hose` probes standard domains and discovers the enterprise automatically. If it returns multiple administrator candidates, present their names and masked phones for the user to choose, then retry with `staffName`, `staffPhone`, or the selected `staffId`. Do not ask for `domain`, `corpId`, `staffId`, or `proxyStaffBizId` before discovery. Ask for a dedicated/private-cloud `domain` only after standard probing fails.
The command verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at `corps` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands.
## Diagnose authentication
+2
View File
@@ -50,6 +50,8 @@ describe("CLI version & help handling", () => {
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("seal-home corps add-link <https://.../web/thirdparty.html?...>");
expect(result.stdout).toContain("seal-home delegation create [--note <note>] [--from-link <url>]");
expect(result.stdout).toContain("[--secret <secret>|--rotate-secret]");
});
+197
View File
@@ -0,0 +1,197 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../runner.js";
const ORIGINAL_ENV = {
enterprises: process.env.SEAL_HOME_ENTERPRISES_DIR,
config: process.env.SEAL_HOME_CONFIG_FILE,
tokenStore: process.env.SEAL_HOME_TOKEN_STORE
};
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
restoreEnv("SEAL_HOME_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
restoreEnv("SEAL_HOME_CONFIG_FILE", ORIGINAL_ENV.config);
restoreEnv("SEAL_HOME_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("corps link onboarding", () => {
test("imports a Hose assistance link and writes a verified Seal config", async () => {
const enterprises = setupConfigEnv();
mockSealLinkRequests();
const link = hoseLink();
const result = await runCli(["corps", "add-link", link, "--name", "Acme Corporation"]);
expect(result.isError).toBe(false);
expect(result.stdout).not.toContain("hose-token");
expect(result.stdout).not.toContain(link);
const config = JSON.parse(readFileSync(join(enterprises, "acme-01.json"), "utf-8")) as {
id: string;
name: string;
seal: { url?: string; tenantSlug?: string };
source: {
type: string;
token: string;
expiresIn: number;
provider?: string;
corpId?: string;
};
};
expect(config).toMatchObject({
id: "acme-01",
name: "Acme Corporation",
seal: {
url: "https://acme-01.sealai.cc",
tenantSlug: "acme-01"
},
source: {
type: "seal",
token: "seal-bearer-token",
expiresIn: 1800,
provider: "hosecloud",
corpId: "acme-01"
}
});
});
test("creates a delegation directly from a Hose assistance link", async () => {
mockSealLinkRequests({ delegation: true });
const result = await runCli([
"delegation",
"create",
"--from-link",
hoseLink(),
"--note",
"Customer support"
]);
expect(result.isError).toBe(false);
expect(JSON.parse(result.stdout)).toMatchObject({
tenant: {
corpId: "acme-01",
tenantSlug: "acme-01"
},
user: {
id: "user-1",
providerUserId: "staff-1"
},
delegation: {
id: "delegation-1",
token: "delegation-token",
link: "https://acme-01.sealai.cc/delegation?token=delegation-token"
},
expiresIn: 1800
});
});
test("rejects a link when Seal identity does not match ekbCorpId", async () => {
mockSealLinkRequests({ tenantSlug: "other-tenant", corporationId: "other-corp" });
const enterprises = setupConfigEnv();
const result = await runCli(["corps", "add-link", hoseLink()]);
expect(result.isError).toBe(true);
expect(result.stderr).toContain("tenant mismatch");
expect(result.stderr).not.toContain("hose-token");
expect(readDirectory(enterprises)).toEqual([]);
});
});
function setupConfigEnv() {
const root = mkdtempSync(join(tmpdir(), "seal-home-link-cli-"));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
process.env.SEAL_HOME_ENTERPRISES_DIR = enterprises;
process.env.SEAL_HOME_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_HOME_TOKEN_STORE = join(root, "tokens.json");
return enterprises;
}
function hoseLink() {
return "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=hose-token&ekbCorpId=Acme-01&pageType=home";
}
function mockSealLinkRequests(options: {
delegation?: boolean;
tenantSlug?: string;
corporationId?: string;
} = {}) {
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
const url = new URL(requestUrl);
if (url.pathname === "/api/auth/oauth2/session/oem-hosecloud") {
return jsonResponse({ accessToken: "seal-bearer-token", expiresIn: 1800 });
}
if (url.pathname === "/api/v1/auth/me") {
return jsonResponse({
data: {
user: {
id: "user-1",
tenantId: "tenant-1",
name: "Support User",
providerUserId: "staff-1",
isAdmin: true
},
tenant: {
id: "tenant-1",
name: "Acme Tenant",
tenantSlug: options.tenantSlug ?? "acme-01",
hoseCorpConfig: {
corporationId: options.corporationId ?? "acme-01",
corporationName: "Acme Corporation"
}
}
}
});
}
if (options.delegation && url.pathname === "/api/v1/delegation/create") {
return jsonResponse({
data: {
id: "delegation-1",
token: "delegation-token",
link: "https://acme-01.sealai.cc/delegation?token=delegation-token"
}
});
}
return jsonResponse({ error: `Unexpected request: ${url.pathname}` }, 404);
}) as typeof fetch;
}
function jsonResponse(value: unknown, status = 200) {
return new Response(JSON.stringify(value), {
status,
headers: { "content-type": "application/json" }
});
}
function readDirectory(path: string) {
try {
return Array.from(new Bun.Glob("*.json").scanSync({ cwd: path })).sort();
} catch {
return [];
}
}
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
+67 -5
View File
@@ -1,12 +1,15 @@
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
assertHoseAssistTenantMatches,
exchangeHoseAssistLink,
fetchHoseRoleDefGroups,
fetchHoseRoleStaffs,
fetchHoseStaffDetails,
probeHoseDomain
} from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import {
loadCorpConfigs,
loadGlobalConfig,
@@ -14,10 +17,12 @@ import {
saveGlobalConfig
} from "../../core/config/loader.js";
import type { CorpConfig } from "../../core/config/types.js";
import { getMe } from "../../domains/seal/api.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
import { selectCorp } from "../helpers.js";
import {
inferCorpIdFromStaffId,
booleanOption,
jsonObject,
optionalNumber,
optionalString,
@@ -103,6 +108,17 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
return;
}
if (action === "add-link") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error(
"Usage: seal-home corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]"
);
}
await addLinkCorp(link, stringOption(args.options.name), booleanOption(args.options.overwrite) === true);
return;
}
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-home help' for available commands.`);
}
@@ -359,13 +375,58 @@ async function addSealCorp(input: Record<string, unknown>) {
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;
writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote });
}
async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean) {
const session = await exchangeHoseAssistLink(link);
const client = createSealClientForUrl(session.sealUrl, session.token);
const me = await getMe(client);
const identity = {
user: me.user as unknown as Record<string, unknown>,
tenant: me.tenant as unknown as Record<string, unknown>
};
assertHoseAssistTenantMatches(session.corpId, identity.tenant);
writeSealCorpConfig(
{
id: session.corpId,
corpId: session.corpId,
name,
provider: "hosecloud",
overwrite
},
{
token: session.token,
sealUrl: session.sealUrl,
expiresIn: session.expiresIn,
verify: true,
remote: identity
}
);
}
type RemoteSealIdentity = {
user: Record<string, unknown>;
tenant: Record<string, unknown>;
};
function writeSealCorpConfig(
input: Record<string, unknown>,
auth: {
token: string;
sealUrl: string;
expiresIn: number;
verify: boolean;
remote?: RemoteSealIdentity;
}
) {
const { token, sealUrl, expiresIn, verify, remote } = auth;
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 tenantName = optionalString(input, "tenantName") ?? 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.");
@@ -378,10 +439,11 @@ async function addSealCorp(input: Record<string, unknown>) {
const provider = optionalString(input, "provider") ??
stringValue(remoteUser?.provider) ??
stringValue((remoteTenant as any)?.providerConfig?.provider);
const corpId = optionalString(input, "corpId") ?? tenantSlug ?? tenantId ?? id;
const config: CorpConfig = {
id,
name: tenantName ?? id,
name: optionalString(input, "name") ?? tenantName ?? id,
seal: {
url: sealUrl,
tenantSlug,
@@ -395,7 +457,7 @@ async function addSealCorp(input: Record<string, unknown>) {
sealUrl,
expiresIn,
staffId,
corpId: tenantSlug ?? tenantId ?? id,
corpId,
tenantId,
tenantSlug,
tenantName,
+30 -2
View File
@@ -1,9 +1,37 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { assertHoseAssistTenantMatches, exchangeHoseAssistLink } from "../../core/auth/hose.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { createDelegation, getMe } from "../../domains/seal/api.js";
import { runTool } from "../helpers.js";
import { stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import type { createSealClient } from "../../core/http/factory.js";
export async function handleDelegationFromHoseLink(link: string, note?: string) {
const session = await exchangeHoseAssistLink(link);
const client = createSealClientForUrl(session.sealUrl, session.token);
const me = await getMe(client);
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
const delegation = await createDelegation(client, { note });
printJson({
tenant: {
id: me.tenant.id,
name: me.tenant.name,
tenantSlug: me.tenant.tenantSlug,
corpId: session.corpId
},
user: {
id: me.user.id,
name: me.user.name,
providerUserId: me.user.providerUserId,
isAdmin: me.user.isAdmin
},
delegation,
expiresIn: session.expiresIn
});
}
export async function handleDelegationCommand(
action: string | undefined,
+77 -9
View File
@@ -477,7 +477,6 @@ function logProgress(msg: string) {
} catch {
// ignore
}
console.error(msg);
}
async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) {
@@ -497,15 +496,11 @@ async function downloadFile(url: string, destPath: string, tagName?: string, ass
if (tag && fileName) {
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
candidates.push(ghDirectUrl);
} else if (url.includes("github.com")) {
candidates.push(`https://ghfast.top/${url}`);
candidates.push(`https://ghproxy.net/${url}`);
candidates.push(`https://gh.ddlc.top/${url}`);
candidates.push(`https://mirror.ghproxy.com/${url}`);
candidates.push(url);
} else {
candidates.push(url);
@@ -515,15 +510,48 @@ async function downloadFile(url: string, destPath: string, tagName?: string, ass
const uniqueCandidates = Array.from(new Set(candidates));
let lastError: Error | undefined;
const CONNECT_TIMEOUT_MS = 6000; // 6s connection & headers timeout
const WARMUP_WINDOW_MS = 6000; // 6s initial grace window
const WARMUP_MIN_BYTES = 300 * 1024; // Must download at least 300 KB within first 6s (otherwise switch)
const STALL_TIMEOUT_MS = 10000; // 10s completely stalled (0 bytes received) before giving up
const MAX_TOTAL_TIMEOUT_MS = 180000; // 3m max safety limit
for (let i = 0; i < uniqueCandidates.length; i++) {
const candidate = uniqueCandidates[i]!;
const controller = new AbortController();
let abortReason = "";
const abortWith = (reason: string) => {
abortReason = reason;
try {
controller.abort();
} catch {
// ignore
}
};
let connectTimer: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {
abortWith("Connection timed out (no response headers within 6s)");
}, CONNECT_TIMEOUT_MS);
let maxTimer: ReturnType<typeof setTimeout> | undefined;
let warmupTimer: ReturnType<typeof setTimeout> | undefined;
try {
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] Downloading via: ${candidate}`);
const res = await fetch(candidate, { signal: AbortSignal.timeout(6000) });
const res = await fetch(candidate, { signal: controller.signal });
if (connectTimer) {
clearTimeout(connectTimer);
connectTimer = undefined;
}
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
maxTimer = setTimeout(() => {
abortWith("Overall download time exceeded 3 minutes");
}, MAX_TOTAL_TIMEOUT_MS);
const totalBytes = Number(res.headers.get("content-length")) || 0;
const reader = res.body?.getReader();
if (!reader) {
@@ -540,12 +568,44 @@ async function downloadFile(url: string, destPath: string, tagName?: string, ass
let receivedBytes = 0;
let lastReport = 0;
// Initial 6-second warmup speed check: must reach 300KB
warmupTimer = setTimeout(() => {
if (receivedBytes < WARMUP_MIN_BYTES) {
const kb = (receivedBytes / 1024).toFixed(1);
abortWith(`Initial transfer too slow (${kb} KB < 300 KB in 6s), switching mirror...`);
}
}, WARMUP_WINDOW_MS);
while (true) {
const { done, value } = await reader.read();
// Read next chunk with 10s stall timeout
const readPromise = reader.read();
let chunkTimeoutTimer: ReturnType<typeof setTimeout> | undefined;
const stallPromise = new Promise<never>((_, reject) => {
chunkTimeoutTimer = setTimeout(() => {
reject(new Error("Data transfer stalled (no chunk received for 10s)"));
}, STALL_TIMEOUT_MS);
});
let result: { done: boolean; value?: Uint8Array };
try {
result = await Promise.race([readPromise, stallPromise]);
} finally {
if (chunkTimeoutTimer) clearTimeout(chunkTimeoutTimer);
}
const { done, value } = result;
if (done) break;
if (value) {
chunks.push(value);
receivedBytes += value.length;
// Clear warmup timer early if we already passed 300KB
if (warmupTimer && receivedBytes >= WARMUP_MIN_BYTES) {
clearTimeout(warmupTimer);
warmupTimer = undefined;
}
const now = Date.now();
if (now - lastReport > 200) {
lastReport = now;
@@ -575,8 +635,16 @@ async function downloadFile(url: string, destPath: string, tagName?: string, ass
logProgress(`✓ Download completed successfully (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
return;
} catch (err) {
lastError = err instanceof Error ? err : new Error(String(err));
logProgress(` ↳ Mirror failed: ${lastError.message}`);
if (connectTimer) clearTimeout(connectTimer);
if (warmupTimer) clearTimeout(warmupTimer);
if (maxTimer) clearTimeout(maxTimer);
const msg = abortReason || (err instanceof Error ? err.message : String(err));
lastError = new Error(msg);
logProgress(`\n ↳ Mirror failed: ${lastError.message}`);
} finally {
if (connectTimer) clearTimeout(connectTimer);
if (warmupTimer) clearTimeout(warmupTimer);
if (maxTimer) clearTimeout(maxTimer);
}
}
+2 -1
View File
@@ -97,10 +97,11 @@ Usage:
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 corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
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 create [--note <note>] [--from-link <url>] [--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>]
+8 -1
View File
@@ -10,7 +10,7 @@ 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 { handleDelegationCommand, handleDelegationFromHoseLink } from "./commands/delegation.js";
import { handleDeployCommand } from "./commands/deploy.js";
import { handleHttpCommand } from "./commands/http.js";
import { handleLlmCommand } from "./commands/llm.js";
@@ -234,6 +234,13 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "delegation" && action === "create" && ("from-link" in args.options || "link" in args.options)) {
const link = stringOption(args.options["from-link"]) ?? stringOption(args.options.link);
if (!link) throw new Error("Usage: seal-home delegation create --from-link <url> [--note <note>]");
await handleDelegationFromHoseLink(link, stringOption(args.options.note));
return;
}
const corp = selectCorp(stringOption(args.options.corp));
if (area === "source") {
+79 -2
View File
@@ -5,13 +5,17 @@ import { join } from "node:path";
import { CorpConfig, HoseSealSource } from "../config/types.js";
import {
HOSE_STANDARD_DOMAINS,
assertHoseAssistTenantMatches,
defaultSealUrl,
exchangeHoseAssistLink,
fetchHoseStaffDetails,
getHoseEnterpriseUrl,
normalizeBaseUrl
normalizeBaseUrl,
parseHoseAssistLink
} from "./hose.js";
const ORIGINAL_ENV = process.env.SEAL_HOME_TOKEN_STORE;
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
function setupTokenStore(data: Record<string, unknown>): string {
@@ -29,6 +33,7 @@ afterEach(() => {
} else {
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_ENV;
}
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
@@ -116,5 +121,77 @@ describe("hose auth helpers", () => {
const details = await fetchHoseStaffDetails("https://app.ekuaibao.com", "fake-token", []);
expect(details).toEqual([]);
});
});
test("parses a Hose third-party assistance link without exposing its token", () => {
const result = parseHoseAssistLink(
"https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=temporary-token&ekbCorpId=Acme-01&pageType=home"
);
expect(result).toEqual({
corpId: "acme-01",
accessToken: "temporary-token"
});
});
test("rejects unsupported Hose assistance link shapes", () => {
expect(() => parseHoseAssistLink("http://wx2.ekuaibao.com/web/thirdparty.html?accessToken=t&ekbCorpId=acme")).toThrow(
"expected an HTTPS"
);
expect(() => parseHoseAssistLink("https://example.com/web/thirdparty.html?accessToken=t&ekbCorpId=acme")).toThrow(
"expected an HTTPS"
);
expect(() => parseHoseAssistLink("https://wx2.ekuaibao.com/web/home.html?accessToken=t&ekbCorpId=acme")).toThrow(
"expected an HTTPS"
);
expect(() => parseHoseAssistLink("https://wx2.ekuaibao.com/web/thirdparty.html?ekbCorpId=acme")).toThrow(
"required exactly once"
);
});
test("exchanges a Hose assistance link for a Seal session", async () => {
let requestedUrl = "";
globalThis.fetch = (async (input: RequestInfo | URL) => {
requestedUrl = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
return new Response(JSON.stringify({
data: {
accessToken: "seal-bearer-token",
expiresIn: 1800
}
}), {
status: 200,
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
const result = await exchangeHoseAssistLink(
"https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=hose-token&ekbCorpId=Acme-01"
);
const url = new URL(requestedUrl);
expect(url.origin).toBe("https://acme-01.sealai.cc");
expect(url.pathname).toBe("/api/auth/oauth2/session/oem-hosecloud");
expect(url.searchParams.get("token")).toBe("hose-token");
expect(url.searchParams.get("returnToken")).toBe("1");
expect(result).toEqual({
corpId: "acme-01",
sealUrl: "https://acme-01.sealai.cc",
token: "seal-bearer-token",
expiresIn: 1800
});
});
test("requires complete and consistent tenant identity metadata", () => {
expect(() => assertHoseAssistTenantMatches("acme-01", {})).toThrow("tenant mismatch");
expect(() => assertHoseAssistTenantMatches("acme-01", {
tenantSlug: "acme-01",
hoseCorpConfig: { corporationId: "other-corp" }
})).toThrow("tenant mismatch");
expect(() => assertHoseAssistTenantMatches("Acme-01", {
hoseCorpConfig: { corporationId: " ACME-01 " }
})).not.toThrow();
});
});
+126
View File
@@ -40,6 +40,18 @@ type SealTokenResponse = {
};
};
export type HoseAssistLink = {
corpId: string;
accessToken: string;
};
export type HoseAssistSealSession = {
corpId: string;
sealUrl: string;
token: string;
expiresIn: number;
};
export const HOSE_STANDARD_DOMAINS = [
"https://app.ekuaibao.com",
"https://dd2.hosecloud.com",
@@ -49,6 +61,10 @@ export const HOSE_STANDARD_DOMAINS = [
"https://feishu.ekuaibao.com"
] as const;
const HOSE_ASSIST_HOST_SUFFIXES = [".ekuaibao.com", ".hosecloud.com"] as const;
const HOSE_ASSIST_PATH = "/web/thirdparty.html";
const CORP_ID_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
export type HoseRoleDef = {
id: string;
name: string;
@@ -101,6 +117,116 @@ export function normalizeBaseUrl(url: string): string {
return url.replace(/\/+$/, "");
}
export function parseHoseAssistLink(value: string): HoseAssistLink {
let url: URL;
try {
url = new URL(value.trim());
} catch {
throw new Error("Invalid Hose assistance link: expected a valid HTTPS URL");
}
if (
url.protocol !== "https:" ||
url.port ||
!isHoseAssistHost(url.hostname) ||
url.pathname.replace(/\/+$/, "") !== HOSE_ASSIST_PATH
) {
throw new Error(
"Invalid Hose assistance link: expected an HTTPS */web/thirdparty.html URL from ekuaibao.com or hosecloud.com"
);
}
const accessTokens = url.searchParams.getAll("accessToken").filter(Boolean);
const corpIds = url.searchParams.getAll("ekbCorpId").filter(Boolean);
if (accessTokens.length !== 1 || corpIds.length !== 1) {
throw new Error("Invalid Hose assistance link: accessToken and ekbCorpId are required exactly once");
}
const corpId = corpIds[0]!.trim().toLowerCase();
if (!CORP_ID_PATTERN.test(corpId)) {
throw new Error("Invalid Hose assistance link: ekbCorpId is not a valid tenant slug");
}
return {
corpId,
accessToken: accessTokens[0]!
};
}
export async function exchangeHoseAssistLink(
value: string | HoseAssistLink
): Promise<HoseAssistSealSession> {
const link = typeof value === "string" ? parseHoseAssistLink(value) : normalizeHoseAssistLink(value);
const sealUrl = `https://${link.corpId}.sealai.cc`;
const sealResponse = await ky
.get(`${sealUrl}/api/auth/oauth2/session/oem-hosecloud`, {
searchParams: {
token: link.accessToken,
returnToken: "1"
},
timeout: 30000
})
.json<SealTokenResponse>();
const token =
sealResponse.token ??
sealResponse.accessToken ??
sealResponse.data?.token ??
sealResponse.data?.accessToken;
if (!token) {
throw new Error("Seal SSO did not return a bearer token");
}
const expiresIn =
sealResponse.expiresIn ??
sealResponse.expires_in ??
sealResponse.data?.expiresIn ??
sealResponse.data?.expires_in ??
3600;
return {
corpId: link.corpId,
sealUrl,
token,
expiresIn: Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600
};
}
export function assertHoseAssistTenantMatches(corpId: string, tenant: Record<string, unknown>): void {
const hoseCorpConfig = tenant.hoseCorpConfig && typeof tenant.hoseCorpConfig === "object"
? tenant.hoseCorpConfig as Record<string, unknown>
: undefined;
const candidates = [tenant.tenantSlug, hoseCorpConfig?.corporationId]
.filter((value): value is string => typeof value === "string" && Boolean(value));
const expectedCorpId = corpId.trim().toLowerCase();
const normalizedCandidates = candidates
.map((value) => value.trim().toLowerCase())
.filter(Boolean);
if (
normalizedCandidates.length === 0 ||
normalizedCandidates.some((value) => value !== expectedCorpId)
) {
throw new Error("Hose assistance link tenant mismatch: the Seal tenant does not match ekbCorpId");
}
}
function isHoseAssistHost(hostname: string): boolean {
const normalized = hostname.toLowerCase();
return HOSE_ASSIST_HOST_SUFFIXES.some((suffix) => normalized.endsWith(suffix));
}
function normalizeHoseAssistLink(value: HoseAssistLink): HoseAssistLink {
const corpId = typeof value?.corpId === "string" ? value.corpId.trim().toLowerCase() : "";
const accessToken = typeof value?.accessToken === "string" ? value.accessToken.trim() : "";
if (!CORP_ID_PATTERN.test(corpId) || !accessToken) {
throw new Error("Invalid Hose assistance link: accessToken and ekbCorpId are required");
}
return {
corpId,
accessToken
};
}
function isFresh(entry: TokenEntry | undefined, refreshTtl = 60): entry is TokenEntry {
return Boolean(entry && Date.now() < entry.expiresAt - refreshTtl * 1000);
}
+2
View File
@@ -9,6 +9,7 @@ describe("embedded-skill", () => {
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(EMBEDDED_SKILL_FILES["references/enterprise-onboarding.md"]).toContain("# Enterprise Onboarding");
expect(getSkillContent()).toContain("name: seal-home");
});
@@ -20,6 +21,7 @@ describe("embedded-skill", () => {
expect(res.files.length).toBeGreaterThan(5);
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "cli.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "enterprise-onboarding.md"))).toBe(true);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
+2
View File
@@ -10,6 +10,7 @@ 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 refEnterpriseOnboarding from "../../skills/seal-home/references/enterprise-onboarding.md" with { type: "text" };
import refHoseEnterpriseAuth from "../../skills/seal-home/references/hose-enterprise-auth.md" with { type: "text" };
import refHoseEnterpriseInit from "../../skills/seal-home/references/hose-enterprise-init.md" with { type: "text" };
@@ -22,6 +23,7 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
"references/approval-run-lightweight.md": refApprovalRunLightweight,
"references/approval-attachment-trace.md": refApprovalAttachmentTrace,
"references/customer-feedback-rule-remediation.md": refCustomerFeedbackRuleRemediation,
"references/enterprise-onboarding.md": refEnterpriseOnboarding,
"references/hose-enterprise-auth.md": refHoseEnterpriseAuth,
"references/hose-enterprise-init.md": refHoseEnterpriseInit
};
+5 -1
View File
@@ -32,8 +32,12 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
export async function createSealClientForToken(corp: CorpConfig, token: string): Promise<KyInstance> {
const session = await getSealSessionForCorp(corp);
return createSealClientForUrl(session.enterprise.sealUrl, token);
}
export function createSealClientForUrl(sealUrl: string, token: string): KyInstance {
return ky.create({
prefix: session.enterprise.sealUrl,
prefix: sealUrl.replace(/\/+$/, ""),
timeout: 30000,
headers: {
Authorization: `Bearer ${token}`