Compare commits

..
22 Commits
Author SHA1 Message Date
yunyingk ec513adf38 Merge pull request #256 from yunyingk/codex/release-v0.11.13
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.13: Automated release bump
2026-10-20 23:12:07 +08:00
gitea 9e591cc146 Release v0.11.13: Automated release bump 2026-10-20 23:10:46 +08:00
yunyingk 05dbdb17af Merge pull request #254 from yunyingk/mac15/safe-document-file-editing
Add safe knowledge document file editing
2026-10-20 17:45:32 +08:00
gitea a2963c736c Preserve auth exit codes when document readback fails 2026-10-20 17:40:06 +08:00
gitea b017e1fc48 Add safe knowledge document file editing 2026-10-20 17:30:38 +08:00
yunyingk cbef6d0ef6 Merge pull request #255 from yunyingk/mac15/expense-document-lookup
Add expense store lookup by document number
2026-10-20 17:29:50 +08:00
gitea 10852eb198 Fix platform-dependent config selection test 2026-10-20 10:23:36 +08:00
gitea b21d92efae Add expense store lookup by document number 2026-10-20 10:15:08 +08:00
yunyingk 4b3a899e5a Merge pull request #242 from yunyingk/mac15/clean-report-templates-and-assets
Clean report templates, drop legacy charts, and refine guidelines
2026-10-18 22:54:55 +08:00
yunyingk a83f78b140 Merge pull request #243 from yunyingk/mac15/invoices-flatten-and-conflict-trace
Add normalized invoice fields, first-class invoices CLI, and CLI-attributed conflict diagnosis
2026-10-18 22:54:14 +08:00
gitea 05dfd0f5bb Clean report templates, drop legacy charts, and refine guidelines 2026-10-18 22:53:25 +08:00
gitea d40ab9648d Add normalized invoice fields, first-class invoices CLI, and CLI-attributed conflict diagnosis 2026-10-18 22:52:36 +08:00
yunyingk b17f7ad722 Merge pull request #253 from yunyingk/mac15/add-protocol-test-closure
Add protocol test closures for secure writes, aliases, help and cli docs
2026-10-18 13:45:51 +08:00
gitea 9e7275f09b Add protocol test closures for secure writes, aliases, help and cli docs 2026-10-18 11:16:07 +08:00
yunyingk 97c59fae14 Merge pull request #252 from yunyingk/codex/release-v0.11.12
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.12: credential and CLI consistency fixes
2026-10-17 20:24:38 +08:00
gitea b44800c108 Release v0.11.12: Automated release bump 2026-10-17 20:23:23 +08:00
yunyingk baa47753d3 Merge pull request #251 from yunyingk/mac15/fix-architecture-review
Fix architecture review findings and align CLI metadata
2026-10-17 20:22:04 +08:00
gitea 50e4e492b4 Fix architecture review findings and align CLI metadata 2026-10-17 20:17:06 +08:00
yunyingk 780a4ba9c0 Merge pull request #250 from yunyingk/mac15/refine-report-glossary-and-math-layout
Refine report glossary to plain business language and improve math layout
2026-10-16 18:28:58 +08:00
gitea 818f33a8e1 Refine report glossary to plain business language and improve math layout 2026-10-16 18:27:18 +08:00
yunyingk a760ea9572 Merge pull request #249 from yunyingk/mac15/add-report-glossary-page
Add trailing terms definition appendix to report renderers
2026-10-16 18:07:44 +08:00
gitea 69d5b4f130 Add trailing terms definition appendix to report renderers 2026-10-16 18:06:02 +08:00
128 changed files with 3627 additions and 1701 deletions

No files matched your search

+2 -2
View File
@@ -25,8 +25,8 @@ When developing or refactoring CLI commands under `src/cli/`:
## 2. Performance Contract & SWR Architecture
- **Sub-50ms Local Execution**:
- Read-only discovery commands (e.g. `seal-use version`, `seal-use doctor paths`, `seal-use corps list`) MUST return in under 50ms wall clock (Bun interpreter startup is ~7ms on its own, so this leaves ~40ms for the module graph).
- **Sub-70ms Local Execution**:
- Read-only discovery commands (e.g. `seal-use version`, `seal-use doctor paths`, `seal-use corps list`) MUST return in under 70ms wall clock (Bun interpreter startup is ~7ms on its own, so this leaves ~60ms for the module graph).
- Achieved by keeping `src/cli/runner.ts` free of static command-module imports: dispatch branches load their handler with `await import("./commands/<area>.js")` on demand, so `seal-use version` never loads the Excel/zip tool chain.
- Never trigger synchronous external HTTP requests during routine discovery or inspection invocations. Measured on the maintainer's machine (2026-09): version 45ms, help 41ms, corps list 41ms, bare `bun -e` 7ms.
- **Stale-While-Revalidate (SWR) Pattern**:
+6
View File
@@ -41,6 +41,12 @@ jobs:
- name: Linter Plaintext Sync
run: bun run verify:linter-plaintext
- name: CLI Documentation Sync
run: bun run verify:cli-md
- name: Embedded Skill Sync
run: bun run verify:embedded-skill
- name: Colocated Unit Tests
run: bun test
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.11",
"version": "0.11.13",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+1 -1
View File
@@ -34,7 +34,7 @@ Prefer small domain functions over broad utility modules.
- **Machine Channel (`stdout`)**: Data commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
- **Documented exception — document-output commands**: `seal-use --help` / `seal-use help <area>` (`src/cli/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`, `seal-use skill dump > SKILL.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract.
- **Guidance & Diagnostic Channel (`stderr`)**: Use `stderr` for runtime logs, network probing status, self-healing notifications, and explicit **Next-Step Command Suggestions** (e.g. `👉 Next action: seal-use deploy hosecloud sync <signKey>`).
- **Performance Contract & SWR Architecture**: Read-only discovery and version commands (`seal-use version`, `seal-use doctor`, `seal-use corps list`) MUST execute in under 50ms wall clock (Bun startup alone is ~7ms; runner dispatch uses lazy `await import()` per command area, so the version path never loads the Excel/zip tool chain). Never block on external network I/O during routine invocations. Use the Stale-While-Revalidate (SWR) pattern: read local cache from `~/.config/seal-use/*.json` synchronously (<0.2ms), and refresh stale/missing data via detached, unref'd child processes (`triggerBackgroundUpdateCheck`, `unref()`).
- **Performance Contract & SWR Architecture**: Read-only discovery and version commands (`seal-use version`, `seal-use doctor`, `seal-use corps list`) MUST execute in under 70ms wall clock (Bun startup alone is ~7ms; runner dispatch uses lazy `await import()` per command area, so the version path never loads the Excel/zip tool chain). Never block on external network I/O during routine invocations. Use the Stale-While-Revalidate (SWR) pattern: read local cache from `~/.config/seal-use/*.json` synchronously (<0.2ms), and refresh stale/missing data via detached, unref'd child processes (`triggerBackgroundUpdateCheck`, `unref()`).
- **Safety Guardrail & Mutation Preview (`--dry-run`)**: All potentially destructive or state-mutating commands (e.g. `rules push/clear`, `corps sync-test`, `preference update`, `webhook add/update`) MUST support `--dry-run` returning structured JSON previews with `preview: true` and a clean diff, without executing mutations. Live execution requires explicit `--yes` or `--confirm`.
- **Exit Code Contract**:
- `0`: Successful execution.
+24
View File
@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.13] - 2026-10-20
### Added
- Merge pull request #254 from yunyingk/mac15/safe-document-file-editing
- Preserve auth exit codes when document readback fails
- Add safe knowledge document file editing
- Merge pull request #255 from yunyingk/mac15/expense-document-lookup
- Fix platform-dependent config selection test
- Add expense store lookup by document number
- Merge pull request #242 from yunyingk/mac15/clean-report-templates-and-assets
- Merge pull request #243 from yunyingk/mac15/invoices-flatten-and-conflict-trace
## [0.11.12] - 2026-10-17
### Added
- Merge pull request #251 from yunyingk/mac15/fix-architecture-review
- Fix architecture review findings and align CLI metadata
- Merge pull request #250 from yunyingk/mac15/refine-report-glossary-and-math-layout
- Refine report glossary to plain business language and improve math layout
- Merge pull request #249 from yunyingk/mac15/add-report-glossary-page
- Add trailing terms definition appendix to report renderers
## [0.11.11] - 2026-10-16
### Added
+1 -1
View File
@@ -22,7 +22,7 @@ initial response within a few business days — this is a small project, not a s
| `enterprises/*.json` (working tree) | Same, for enterprises added from a checkout | `0600` |
| `~/.cache/seal-use/usage.json` | Per-enterprise command counts | `0600` |
The tool writes these `0600`; a config placed by hand can keep the `0o644` default, so
Credential writes tighten existing files to `0600` before storing new content, including updates, overwrites, and legacy migration. A hand-placed file can retain `0o644` until the next write, so
`seal-use doctor` reports any credential file whose mode is wider than `0600`. Real enterprise
configs are gitignored — never commit them.
+6 -2
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.11",
"version": "0.11.13",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
@@ -35,7 +35,11 @@
"generate:linter-plaintext": "bun run scripts/generate-linter-plaintext.mjs",
"verify:linter-plaintext": "bun run scripts/check-linter-plaintext.mjs",
"test": "bun test",
"prepare": "git config core.hooksPath .githooks"
"prepare": "git config core.hooksPath .githooks",
"generate:embedded-skill": "bun run scripts/generate-embedded-skill.mjs",
"verify:embedded-skill": "bun run scripts/check-embedded-skill.mjs",
"generate:cli-md": "bun run scripts/generate-cli-md.mjs",
"verify:cli-md": "bun run scripts/check-cli-md.mjs"
},
"dependencies": {
"@modelcontextprotocol/server": "^2.0.0",
+5
View File
@@ -128,6 +128,11 @@ function getBuildInfo(releaseMode) {
async function main() {
const startTime = Date.now();
const generatedCliDoc = spawnSync(bun, [resolve(root, "scripts/generate-cli-md.mjs")], {
cwd: root,
stdio: "inherit"
});
if (generatedCliDoc.status !== 0) throw new Error("Failed to generate CLI documentation");
const generatedSkill = spawnSync(bun, [resolve(root, "scripts/generate-embedded-skill.mjs")], {
cwd: root,
stdio: "inherit"
+4
View File
@@ -87,6 +87,10 @@ writeFileSync(skillPath, skillContent);
console.log("✓ Updated skills/seal-use/SKILL.md");
// Keep command documentation and the embedded file manifest synchronized before installation.
execSync("bun run generate:cli-md", { cwd: ROOT, stdio: "inherit" });
execSync("bun run generate:embedded-skill", { cwd: ROOT, stdio: "inherit" });
// 5. Sync to global ~/.agents/skills/seal-use/ if present
const globalSkillDir = join(homedir(), ".agents", "skills", "seal-use");
const legacyGlobalSkillDir = join(homedir(), ".agents", "skills", "seal-home");
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bun
import { readFileSync } from "node:fs";
import { cliDocPath, updateCliDoc } from "./generate-cli-md.mjs";
const content = readFileSync(cliDocPath, "utf8");
if (content !== updateCliDoc(content)) {
console.error("CLI command documentation is stale. Run bun run generate:cli-md and commit the result.");
process.exitCode = 1;
} else {
console.log("CLI command documentation is synchronized.");
}
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bun
import { existsSync, readFileSync } from "node:fs";
import { embeddedSkillOutput, renderEmbeddedSkill } from "./generate-embedded-skill.mjs";
if (!existsSync(embeddedSkillOutput) || readFileSync(embeddedSkillOutput, "utf8") !== renderEmbeddedSkill()) {
console.error("Embedded Skill manifest is stale. Run bun run generate:embedded-skill and commit the result.");
process.exitCode = 1;
} else {
console.log("Embedded Skill manifest is synchronized.");
}
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bun
import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { HELP_REGISTRY } from "../src/cli/help.ts";
export const cliDocPath = resolve(import.meta.dirname, "../skills/seal-use/references/cli.md");
const begin = "<!-- BEGIN GENERATED CLI COMMANDS -->";
const end = "<!-- END GENERATED CLI COMMANDS -->";
export function renderCliCommandBlock() {
const usages = ["seal-use version", ...HELP_REGISTRY.flatMap((area) => area.commands.flatMap((command) => command.usage))];
return [begin, "", "```bash", ...usages, "```", "", end].join("\n");
}
export function updateCliDoc(markdown) {
if (markdown.split(begin).length !== 2 || markdown.split(end).length !== 2 || markdown.indexOf(end) < markdown.indexOf(begin)) {
throw new Error("CLI documentation must contain exactly one ordered generated command block.");
}
const start = markdown.indexOf(begin);
const finish = markdown.indexOf(end) + end.length;
return markdown.slice(0, start) + renderCliCommandBlock() + markdown.slice(finish);
}
if (import.meta.main) {
const before = readFileSync(cliDocPath, "utf8");
const after = updateCliDoc(before);
if (before !== after) writeFileSync(cliDocPath, after, "utf8");
}
+31 -32
View File
@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const skillRoot = resolve(root, "skills", "seal-use");
const output = resolve(root, "src", "core", "embedded-skill.generated.ts");
export const embeddedSkillOutput = resolve(root, "src", "core", "embedded-skill.generated.ts");
const textExtensions = new Set([".md", ".yaml", ".yml", ".json", ".txt"]);
function walk(dir) {
@@ -20,40 +20,39 @@ function walk(dir) {
return files;
}
const files = walk(skillRoot).map((fullPath) => ({
fullPath,
relativePath: relative(skillRoot, fullPath).split("\\").join("/"),
importPath: relative(resolve(root, "src", "core"), fullPath).split("\\").join("/"),
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
}));
export function renderEmbeddedSkill(sourceDir = skillRoot, coreDir = resolve(root, "src", "core")) {
const files = walk(sourceDir).map((fullPath) => ({
relativePath: relative(sourceDir, fullPath).split("\\").join("/"),
importPath: relative(coreDir, fullPath).split("\\").join("/"),
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
}));
const lines = [
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
""
];
const lines = [
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
""
];
for (const [index, file] of files.entries()) {
if (file.kind === "text") {
lines.push(`import file${index} from ${JSON.stringify(file.importPath)} with { type: "text" };`);
} else {
const base64 = readFileSync(file.fullPath).toString("base64");
lines.push(`const file${index} = ${JSON.stringify(base64)};`);
for (const [index, file] of files.entries()) {
const loader = file.kind === "text" ? "text" : "file";
lines.push(`import file${index} from ${JSON.stringify(file.importPath)} with { type: "${loader}" };`);
}
lines.push("", "export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {");
for (const [index, file] of files.entries()) {
if (file.kind === "text") lines.push(` ${JSON.stringify(file.relativePath)}: file${index},`);
}
lines.push("};", "", "export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {");
for (const [index, file] of files.entries()) {
if (file.kind === "asset") lines.push(` ${JSON.stringify(file.relativePath)}: file${index},`);
}
lines.push("};", "", "export const EMBEDDED_SKILL_ALL_PATHS = [");
for (const file of files) lines.push(` ${JSON.stringify(file.relativePath)},`);
lines.push("];", "");
return lines.join("\n");
}
lines.push("", "export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {");
for (const [index, file] of files.entries()) {
if (file.kind === "text") lines.push(` ${JSON.stringify(file.relativePath)}: file${index},`);
if (import.meta.main) {
const content = renderEmbeddedSkill();
const previous = existsSync(embeddedSkillOutput) ? readFileSync(embeddedSkillOutput, "utf8") : "";
if (previous !== content) writeFileSync(embeddedSkillOutput, content, "utf8");
}
lines.push("};", "", "export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {");
for (const [index, file] of files.entries()) {
if (file.kind === "asset") lines.push(` ${JSON.stringify(file.relativePath)}: file${index},`);
}
lines.push("};", "", "export const EMBEDDED_SKILL_ALL_PATHS = [");
for (const file of files) lines.push(` ${JSON.stringify(file.relativePath)},`);
lines.push("];", "");
const content = lines.join("\n");
const previous = existsSync(output) ? readFileSync(output, "utf8").replace(/\r\n/g, "\n") : "";
if (previous !== content) writeFileSync(output, content, "utf8");
+77
View File
@@ -0,0 +1,77 @@
import { afterEach, describe, expect, test } from "bun:test"
import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { embeddedSkillOutput, renderEmbeddedSkill } from "./generate-embedded-skill.mjs"
import { cliDocPath, renderCliCommandBlock, updateCliDoc } from "./generate-cli-md.mjs"
const tempDirs: string[] = []
afterEach(() => {
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
describe("generated documentation contracts", () => {
test("both committed generated artifacts match their source", () => {
const markdown = readFileSync(cliDocPath, "utf8")
expect(updateCliDoc(markdown)).toBe(markdown)
expect(readFileSync(embeddedSkillOutput, "utf8")).toBe(renderEmbeddedSkill())
})
test("CLI regeneration repairs drift while preserving surrounding handwritten content", () => {
const block = renderCliCommandBlock()
const drifted = `before\n${block.replace("seal-use version", "seal-use stale-command")}\nafter`
expect(updateCliDoc(drifted)).toBe(`before\n${block}\nafter`)
expect(() => updateCliDoc("missing markers")).toThrow("exactly one ordered")
expect(() => updateCliDoc(`${block}\n${block}`)).toThrow("exactly one ordered")
})
test("embedded manifests follow added and removed paths without inlining asset bytes", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-generator-"))
tempDirs.push(dir)
const skill = join(dir, "skill")
mkdirSync(skill)
writeFileSync(join(skill, "SKILL.md"), "first")
const before = renderEmbeddedSkill(skill, dir)
writeFileSync(join(skill, "SKILL.md"), "second")
expect(renderEmbeddedSkill(skill, dir)).toBe(before)
writeFileSync(join(skill, "fixture.png"), new Uint8Array([1, 2, 3]))
const after = renderEmbeddedSkill(skill, dir)
expect(after).not.toBe(before)
expect(after).toContain('with { type: "file" }')
expect(after).not.toContain("AQID")
// Rendering and checking never write the generated output or alter sources.
expect(readFileSync(join(skill, "SKILL.md"), "utf8")).toBe("second")
rmSync(join(skill, "fixture.png"))
expect(renderEmbeddedSkill(skill, dir)).toBe(before)
})
test("check commands reject stale artifacts without rewriting them", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-generator-check-"))
tempDirs.push(dir)
const scripts = join(dir, "scripts")
const core = join(dir, "src/core")
const cli = join(dir, "src/cli")
const skill = join(dir, "skills/seal-use")
for (const path of [scripts, core, cli, join(skill, "references")]) mkdirSync(path, { recursive: true })
for (const name of ["generate-embedded-skill.mjs", "check-embedded-skill.mjs", "generate-cli-md.mjs", "check-cli-md.mjs"]) {
copyFileSync(join(import.meta.dir, name), join(scripts, name))
}
writeFileSync(join(cli, "help.ts"), 'export const HELP_REGISTRY = [{ commands: [{ usage: ["seal-use fixture list"] }] }];')
writeFileSync(join(skill, "SKILL.md"), "fixture skill")
const embeddedPath = join(core, "embedded-skill.generated.ts")
const markdownPath = join(skill, "references/cli.md")
writeFileSync(embeddedPath, "stale embedded fixture")
const markdown = renderCliCommandBlock().replace("seal-use version", "seal-use stale-command")
writeFileSync(markdownPath, markdown)
for (const script of ["check-embedded-skill.mjs", "check-cli-md.mjs"]) {
const result = Bun.spawnSync([process.execPath, join(scripts, script)], { cwd: dir })
expect(result.exitCode).toBe(1)
}
expect(readFileSync(embeddedPath, "utf8")).toBe("stale embedded fixture")
expect(readFileSync(markdownPath, "utf8")).toBe(markdown)
for (const script of ["generate-cli-md.mjs", "generate-embedded-skill.mjs", "check-embedded-skill.mjs", "check-cli-md.mjs"]) {
const result = Bun.spawnSync([process.execPath, join(scripts, script)], { cwd: dir })
expect(result.exitCode).toBe(0)
}
})
})
+8 -10
View File
@@ -1,14 +1,14 @@
---
name: seal-use
description: "v0.11.11: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.13: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.11
short-description: Seal tenant and Hose approval automation (v0.11.11)
version: 0.11.13
short-description: Seal tenant and Hose approval automation (v0.11.13)
---
# Seal Use
CLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。插件不带 MCP;本地 MCP 需显式 `seal-use mcp` 启动。
CLI 是主执行通道。运行 `seal-use help` 获取完整命令清单,使用 `seal-use help <area> [command]` 按需查询参数。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。插件不带 MCP;本地 MCP 需显式 `seal-use mcp` 启动。
## 工具就绪检测与安装 (Bootstrap & Installation)
@@ -86,11 +86,7 @@ bun run dev:override # 编译本机二进制、打版本号并原子覆盖
## `corps` 主线
- 接入:`add-link`、`add-seal-bearer`、`add-hose-persistent`、`add-hose-web-session`
- 发现:`list`、`search`/`find`、`get`/`show`、`current`、`switch`
- 维护:`mark`、`rename`
- 测试闭环:`bind-test`、`unbind-test`、`sync-test`、`replay-test`
- Hose 专属:`probe-hose`、`hose-staffs`、`hose-extract-keys`、`hose-keys`
企业接入、发现、维护与测试配对的具体语法见 `seal-use help corps`;材料选择与操作流程按下方 reference 路由。
Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`approval-runs hose-flow`、`deploy hosecloud`、`simulation --mode hosecloud`。跨来源入口只有在明确使用 `--elevate-hose`、`--with-flow` 或 `--type hose-document` 时才启用对应 Hose 能力。
@@ -132,9 +128,11 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
| 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` |
| 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` |
| 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` |
| 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` |
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
| 规则数量、摘要列表、历史规则、编号重排、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 规则数量、摘要列表、历史规则、编号重排或规则搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 制度/知识文档(`documents`)、正文文件导出编辑、文档更新/删除或本地快照 | `references/documents.md` | 只查命令参数时读 `cli.md` |
| 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 |
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
+162 -121
View File
@@ -35,13 +35,30 @@ override that path. The legacy `current-corp` file is not read.
## Top-Level Commands
<!-- BEGIN GENERATED CLI COMMANDS -->
```bash
seal-use version
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config test-dir [<path>|--clear]
seal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]
seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]
seal-use corps search <query> [--env <production|test>] [--strict]
seal-use corps get <corpId>
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps rename <corpId> --name <newName>
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]
seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--confirm|--yes] [--force]
seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal-bearer --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-hose-web-session --json '{"baseUrl":"https://wx2.ekuaibao.com","corpId":"...","staffId":"...","accessToken":"..."}'
seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--app-key <key>] [--key-id <id>] [--overwrite] [--dry-run]
seal-use corps probe-hose --json '{"appKey":"...","appSecurity":"...","domain":"https://..."}'
seal-use corps hose-staffs --json '{"appKey":"...","appSecurity":"...","role":"admin"}'
seal-use corps hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]
seal-use corps hose-keys [<url> | <corpId>] [--reveal] [--save] [--app-key <key>]
seal-use rules count [--version <number|latest>] [--corp <corpId>]
seal-use rules list [--version <number|latest>] [--summary] [--limit 20] [--offset 0] [--output-file <path>] [--corp <corpId>]
seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]
@@ -61,102 +78,78 @@ seal-use rules push status [--file <path>] [--corp <corpId>]
seal-use rules clear [--dry-run|--yes] [--corp <corpId>]
seal-use rules recode [--dry-run] --corp <corpId>
seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]
seal-use documents list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]
seal-use documents get <documentId> [--corp <corpId>]
seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]
seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
seal-use documents delete <documentId> --yes [--corp <corpId>]
seal-use langfuse check
seal-use langfuse cache-refresh <traceId>
seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full] [--refresh-if-missing]
seal-use langfuse search <traceId> --query <term1,term2> [--fields <fields>] [--max-results <n>] [--context-chars <n>] [--observation-types <types>] [--metadata <json>] [--session-id <id>] [--refresh-if-missing]
seal-use langfuse observation <traceId> <observationId> [--fields <fields>] [--max-chars <n>] [--json-path <path>] [--full] [--refresh-if-missing]
seal-use langfuse session <sessionId> [--trace-limit <n>]
seal-use langfuse observations <traceId> [--name-contains <text>] [--type <type>] [--metadata-key <key>] [--has-input] [--has-output] [--max-results <n>] [--refresh-if-missing]
seal-use langfuse url <traceId>
seal-use langfuse attachment-flow <traceId> [--file-id <id>] [--file-name <name>] [--content-hints <hints>] [--context-chars <n>] [--refresh-if-missing]
seal-use langfuse rule-flow <traceId> --rule <text> [--rule-hints <hints>] [--context-chars <n>] [--refresh-if-missing]
seal-use update [--check] [--force] [--version <v>]
seal-use update check
seal-use update changelog [--limit <n>]
seal-use changelog [--limit <n>]
seal-use mcp
seal-use mcp config
seal-use mcp-config
seal-use skill dump
seal-use skill install [--dir <path>|--local]
seal-use skill status
seal-use doctor [--quiet]
seal-use doctor tenant [--corp <corpId>] [--quiet]
seal-use doctor guide
seal-use doctor paths
seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]
seal-use probe [<corpId>]
seal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--strict] [--corp <corpId>]
seal-use corps search <query> [--env <production|test>] [--strict]
seal-use corps get <corpId>
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]
seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--confirm|--yes] [--force]
seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal-bearer --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--app-key <key>] [--key-id <id>] [--overwrite] [--dry-run]
seal-use corps probe-hose --json '{"appKey":"...","appSecurity":"...","domain":"https://..."}'
seal-use corps hose-staffs --json '{"appKey":"...","appSecurity":"...","role":"admin"}'
seal-use corps hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--app-key <key>] [--key-id <id>] [--overwrite]
seal-use corps hose-keys [<url> | <corpId>] [--reveal] [--save] [--app-key <key>] [--key-id <id>]
seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--app-key <key>] [--key-id <id>] [--overwrite]
seal-use auth hose-keys [--corp <corpId>] [--reveal]
seal-use auth check [--corp <corpId>]
seal-use auth link [--corp <corpId>] [--note <note>]
seal-use auth link --from-link <url> [--note <note>]
seal-use auth link list [--corp <corpId>]
seal-use auth link revoke <tokenId> [--corp <corpId>]
seal-use auth hose-link [--corp <corpId>] [--expire <seconds>] [--force]
seal-use auth hose-openapi-token [--corp <corpId>] [--force]
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-use users search <keyword> [--corp <corpId>]
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]
seal-use users activate <userId> [--corp <corpId>]
seal-use users reset-password <userId> --yes [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> --yes [--corp <corpId>]
seal-use contacts departments [<departmentId>] [--corp <corpId>]
seal-use contacts children <departmentId> [--corp <corpId>]
seal-use contacts users <departmentId> [--corp <corpId>]
seal-use contacts sync-time [--corp <corpId>]
seal-use data expenses --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]
seal-use data invoices --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
seal-use permissions configs [--corp <corpId>]
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook ready [<资源包.zip>] [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook status [<材料包.zip>] [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size 500] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] [--corp <corpId>]
seal-use webhook resource-pack export <recordId> [--output <file.zip>] [--corp <corpId>]
seal-use webhook resource-pack export --record-ids <id1,id2> [--corp <corpId>]
seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--channel webhook|hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--dry-run] [--yes|--confirm] [--force] [--corp <corpId>]
seal-use approval-runs replay --sn <sn> [--channel hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use webhook replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]
seal-use webhook replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]
seal-use approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] [--corp <corpId>]
seal-use approval-runs count [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--corp <corpId>]
seal-use approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads|--to-downloads] [--with-flow] [--out <file>] [--corp <corpId>]
seal-use approval-runs hose-flow <recordId|SN> [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]
seal-use approval-runs document-summary <recordId> [--corp <corpId>]
seal-use approval-runs attachments <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] [--corp <corpId>]
seal-use approval-runs result <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs link <recordId> [--corp <corpId>]
seal-use approval-runs link <recordId> --auto-login [--expire 7200] [--corp <corpId>]
seal-use approval-runs link <recordId> --type hose-document [--corp <corpId>]
seal-use approval-runs link --sn <documentSN> [--auto-login] [--corp <corpId>]
seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]
seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]
seal-use approval-runs replay --sn <documentSN> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm]
seal-use approval-runs replay <recordId> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm]
seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]
seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--limit <n>] [--out <file.xlsx>] [--corp <corpId>]
seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--corp <corpId>]
seal-use report template [--out <file.md>]
seal-use report chart venn --ai <acc> --human <acc> [--both <both>] [--out <file.svg>]
seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--limit <n>] [--allow-unreviewed] [--corp <corpId>]
seal-use report validate <报告.md>
seal-use report render <报告.md> --out <build/报告> [--format <all|html|png|pdf>]
seal-use report export <报告.md> --out <输出目录> [--format <all|html|pdf>]
seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]
seal-use report review list [--corp <corpId>]
seal-use report review import <台账.xlsx|csv> --corp <corpId>
seal-use simulation batch-records <batchId> [--corp <corpId>]
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp <corpId>]
seal-use simulation status <batchId> [--corp <corpId>]
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
seal-use simulation clean <batchId> --yes [--corp <corpId>]
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
seal-use simulation approval-definitions [--corp <corpId>]
seal-use simulation list [--limit 50] [--corp <corpId>]
seal-use simulation get <batchId> [--corp <corpId>]
seal-use simulation templates [--corp <corpId>]
seal-use simulation integrations [--corp <corpId>]
seal-use simulation package-upload <材料包.zip> [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--rejection-num <n>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <id> --message-id <msgId> [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use deploy hosecloud test-outbound [--sign-key <key>] --sn <SN> --message-id <msgId> [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]
seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]
seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
@@ -166,45 +159,93 @@ seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--co
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config test-dir [<path>|--clear]
seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>]
seal-use auth check [--corp <corpId>]
seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]
seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]
seal-use auth link list [--corp <corpId>]
seal-use auth link revoke <tokenId> [--corp <corpId>]
seal-use auth hose-link [--corp <corpId>] [--expire <duration>] [--force]
seal-use auth hose-openapi-token [--corp <corpId>] [--force]
seal-use auth hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]
seal-use auth hose-keys [--corp <corpId>] [--reveal]
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-use users search <keyword> [--corp <corpId>]
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--corp <corpId>]
seal-use users reset-password <userId> --yes [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> --yes [--corp <corpId>]
seal-use contacts departments [<departmentId>] [--corp <corpId>]
seal-use contacts children <departmentId> [--corp <corpId>]
seal-use contacts users <departmentId> [--corp <corpId>]
seal-use contacts sync-time [--corp <corpId>]
seal-use data expenses [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]
seal-use invoices [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]
seal-use invoices trace <invoiceNumber> [--corp <corpId>]
seal-use invoices <invoiceNumber> [--corp <corpId>]
seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
seal-use permissions configs [--corp <corpId>]
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use analytics insight [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]
seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]
seal-use analytics performance [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--corp <corpId>]
seal-use analytics analyze <recordId> [--corp <corpId>]
seal-use analytics export [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--force] [--limit <n>] [--corp <corpId>]
seal-use context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50] [--corp <corpId>]
seal-use source config [--corp <corpId>]
seal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
seal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]
seal-use analytics insight --corp <corpId> [--start-date <ISO>] [--end-date <ISO>] [--limit <n>]
seal-use analytics risks <tagId> --corp <corpId> [--start-date <ISO>] [--end-date <ISO>]
seal-use analytics performance --corp <corpId> [--start-date <ISO|ms>] [--end-date <ISO|ms>]
seal-use analytics analyze <recordId> --corp <corpId>
seal-use analytics export --corp <corpId> [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--force]
seal-use approval-runs count --corp <corpId> [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>]
seal-use approval-runs export --corp <corpId> [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--out <file>] [--with-flow]
seal-use documents list [--summary] [--fields <id,title,purpose,updatedAt>] [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]
seal-use documents get <documentId> [--out <path>] [--content-format raw] [--overwrite] [--corp <corpId>]
seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]
seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]
seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]
seal-use documents delete <documentId> [--dry-run|--yes|--confirm] [--corp <corpId>]
seal-use update [--check] [--force] [--version <v>]
seal-use update check
seal-use update changelog [--limit <n>]
seal-use changelog [--limit <n>]
seal-use probe [<corpId>]
seal-use langfuse check
seal-use langfuse cache-refresh <traceId> [--trace-id <traceId>]
seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full]
seal-use langfuse search <traceId> --query <term1,term2> [--fields input,output] [--max-results <n>]
seal-use langfuse observation <traceId> <observationId> [--fields input,output] [--max-chars <n>]
seal-use langfuse session <sessionId> [--trace-limit <n>]
seal-use langfuse observations <traceId> [--name-contains <text>] [--type <type>]
seal-use langfuse url <traceId>
seal-use langfuse attachment-flow <traceId> [--file-id <id>] [--file-name <name>]
seal-use langfuse rule-flow <traceId> --rule <规则内容>
seal-use mcp
seal-use mcp config
seal-use mcp-config
seal-use skill dump
seal-use skill install [--dir <path>|--local]
seal-use skill status
seal-use doctor [--quiet]
seal-use doctor guide
seal-use doctor paths
seal-use doctor tenant [--corp <corpId>] [--quiet]
seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]
```
<!-- END GENERATED CLI COMMANDS -->
以下补充说明独立维护:
```bash
# --sn / --sns: 定向筛选单据编号(支持逗号/分号/空格分隔,跳过全量分页,秒级定向导出特定单据)
# --with-flow: 启用合思原生审批流对齐,输出 E人工行为 / E人工意见 两列(含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,默认关闭以节省合思 API 调用)
# 导出文件名自动追加精确到分钟的 _YYYYMMDD_HHmm 时间戳后缀防止文件覆盖,格式:${企业名称}_审核记录_${时间区间}_${条数}_${导出时间戳}.xlsx
seal-use approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]
seal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
seal-use approval-runs attachments <recordId> --corp <corpId>
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] --corp <corpId>
seal-use approval-runs result <recordId> --corp <corpId> [--summary]
seal-use approval-runs link <recordId> --corp <corpId>
seal-use approval-runs link <recordId> --auto-login [--expire 7200] --corp <corpId>
seal-use approval-runs link <recordId> --type hose-document --corp <corpId>
seal-use approval-runs link --sn <documentSN> [--auto-login] --corp <corpId>
# 生成审批详情链接:seal-use approval-runs link <recordId>
seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sourceDocumentSN>]
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--force] [--reuse-window 5m] --corp <corpId>
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp <corpId>
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" --corp <corpId>
seal-use simulation status <batchId> --corp <corpId>
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] --corp <corpId>
seal-use simulation clean <batchId> --yes --corp <corpId>
seal-use simulation specifications [--integration <sign-key>] --corp <corpId>
seal-use simulation approval-definitions --corp <corpId>
seal-use simulation list [--limit 50] --corp <corpId>
seal-use simulation get <batchId> --corp <corpId>
seal-use simulation templates --corp <corpId>
seal-use simulation integrations --corp <corpId>
seal-use simulation package-upload <材料包.zip> --corp <corpId>
```
## CLI Command Overview
+65
View File
@@ -0,0 +1,65 @@
# 知识文档:文件编辑与安全更新
## 列表与读取
```bash
seal-use documents list --summary --corp <corpId>
seal-use documents list --fields id,title,purpose,updatedAt --corp <corpId>
seal-use documents get <documentId> --corp <corpId>
```
`list` 默认保留既有完整 JSON;`--summary` 返回 id、title、purpose、contentType、status、enabled、scenarios、tags、updatedAt,不返回 content。显式 `--fields` 覆盖摘要字段,非法字段报 exit 2。分页、过滤、total 不变;投影在客户端完成,不能据此声称减少了上游网络流量,也不会逐篇请求详情。
`get` 默认输出完整文档 JSON,正文位于 `content`。`--output-file <path>` 保存整份 JSON;`--out <path>` 单独导出正文,两者互斥。
## 导出 → 编辑 → 预览 → 更新
```bash
seal-use documents get <documentId> --out ./document.txt --corp <corpId>
# 编辑 document.txt;保留相邻的 document.txt.seal-use.json
seal-use documents update <documentId> --content-file ./document.txt --dry-run --corp <corpId>
seal-use documents update <documentId> --content-file ./document.txt --yes --corp <corpId>
```
导出产生三个本地文件:指定路径的 UTF-8 正文、相邻的 `.seal-use.json` 来源清单、配置目录 `document-history/` 下的原文快照。stdout 仍是 JSON 回执,包含路径、字节数、内容哈希和 snapshotId;文件权限为 0600,历史目录为 0700。正文不插入标题或 frontmatter,不 trim、不补末尾换行。扩展名可以是 `.md`,但不会改变编码行为。目标父目录须已存在;覆盖既有导出必须显式 `--overwrite`,目录和符号链接不可覆盖。
本期只支持 raw;`--content-format raw` 可显式指定。正文中的反斜杠、转义竖线、硬换行、代码与路径全部保持。Markdown 自动互转尚未开放,`--content-format markdown` 报 exit 2。不要批量替换 `\\` 或 `\|`:平台编码尚需真实脱敏样本证明可逆,JSON 显示转义也不能当作存储协议。
更新自动读取相邻来源清单,核对企业、Seal 服务地址与文档身份,并比较本次拟修改字段的导出基线哈希。远端变化返回 exit 1、`DOCUMENT_CONFLICT`,不会写入;`--yes` 不能绕过。重新导出并合并编辑后再预览。存在但损坏的清单报 exit 13,不会退化成无基线更新。
没有清单的旧 `--content-file` / `--content` 输入仍支持,但 preview、stderr 和回执明确 `baselineAvailable:false`,无法发现编辑期间发生的他人修改。不要为了绕过冲突删除清单。一次成功更新后,如需继续编辑,应重新导出新基线;保留本地修改前先自行留存,`--overwrite` 会覆盖正文。
仅传 `--content-file` 时,PATCH 只提交 content;title、purpose、status、enabled、scenarios、tags 保持。多个正文来源同时给出报 exit 2;非法 UTF-8、文件不可读或清单不可用报 exit 13。空或纯空白正文默认拒绝;明确要清空时加 `--allow-empty`。未变化的内容返回 `changed:false`,不写远端、不产生更新快照。
## 写入安全与兼容变化
所有 documents 创建、更新、删除正式执行均要求 `--yes` 或 `--confirm`,否则 exit 10。旧创建和更新脚本必须补确认标志。`--dry-run` 始终只读,即使同时提供确认标志也不写远端;预览不写历史快照。预览返回 `preview:true` 和结构化 `changesDiff`;内容过大时使用 `--output-file` 或有意选择 `--full`,仍遵守 exit 12 输出保护。
```bash
seal-use documents create --title <title> --purpose <purpose> --content-file ./document.txt --dry-run --corp <corpId>
seal-use documents create --title <title> --purpose <purpose> --content-file ./document.txt --yes --corp <corpId>
seal-use documents delete <documentId> --dry-run --corp <corpId>
seal-use documents delete <documentId> --yes --corp <corpId>
```
创建/更新成功回执改为紧凑执行结果,不再输出整篇文档;需要全文时重新 `get`。正式更新和删除前先保存实际将被覆盖的完整文档快照,备份失败则不写远端。创建和更新后回读,只有正文及预期保留字段核对通过才返回 `verified:true`。写请求禁用自动重试。
更新错误同时返回 JSON 状态和非零退出码:
- `DOCUMENT_CONFLICT`:未执行写入,重新导出并审阅。
- `DOCUMENT_WRITE_UNCERTAIN`:写入结果不确定,`executed:null`;先用返回的只读 next action 回读,不能盲目重跑。
- `DOCUMENT_READBACK_FAILED`:已完成写请求,回读失败,`executed:true, verified:false`。
- `DOCUMENT_VERIFICATION_FAILED`:回读和预期不符,保留 snapshotId / snapshotFile,核对当前状态后处理。
- `DOCUMENT_AUTH_FAILED`:认证失败,exit 11;其他上述失败一般 exit 1。
创建请求失败时可能无法取得新文档 ID,应先查看列表,避免重复创建。删除成功表示服务端已接受删除;快照保留原对象,但重建不承诺保留原文档 ID。错误结果不会自动再次覆盖,也不会自动回滚。快照记录采集阶段,不能仅凭快照存在判断后续写入是否成功。
## 本地恢复、草稿和平台版本边界
历史默认位于当前配置文件所在目录的 `document-history/<来源哈希>/<snapshotId>.json`。包含正文和元数据,视为敏感业务数据,勿加入项目 Git。首期不自动清理快照,也没有快照浏览/一键恢复命令。
需要恢复时先回读当前文档,读取快照的 `document.content` 写成独立正文文件,再预览并确认更新;标题/状态等仅在明确需要时逐项传入。不要把整个快照当 PATCH 上传,不要覆盖作者、时间戳等系统字段。恢复本身是一次新更新,仍需备份与回读。
当前 CLI 有 `--status draft` 输入,但未验证其是否允许“旧发布版继续生效,同时编辑新草稿”。不要为了获得本地编辑稿而修改线上 status。文档更新可能立即影响生产;已发布版本与草稿并存、跨设备完整版本历史、原生回滚和原子条件写入属于待验证的平台能力。
客户端 GET→PATCH 之间仍有竞态窗口;哈希检查不能替代服务端 If-Match/修订号条件更新。本地快照只覆盖本机 CLI 留存过的内容,不能称为平台原生版本历史。
@@ -0,0 +1,60 @@
# 费用明细:按单号核验入库
## 首选入口
用户问“某单据的费用明细是否进入 SealAI 数据管理 → 费用明细”时,先确定目标企业,再运行:
```bash
seal-use expenses --sn <documentSN> --corp <corpId>
```
这是只读查询,使用同一个 `sealExpensesList` 内部能力和既有 MCP 网关,不触发同步、审批或费用写入。`data expenses --sn` 与该入口等价。不要把查询扩大为自动补录或重新审核。
## 已验证的关联路径
2026-10-20 对测试站点公开前端契约和测试企业进行只读往返验证:费用列表支持 `filter.recordId`,返回 `id`、`documentId`、`recordId` 等字段;普通文本搜索用于费用类型、描述、金额。同一已存在费用对应的原单号作为普通搜索词时未命中,按关联审批记录 ID 筛选则命中。因此不能用 `--search <单号>` 的空结果判断未入库,也不能仅因审批记录存在就说费用已入库。
CLI 先分页查询单号候选审批记录,对 `sourceDocumentSN` 做精确相等匹配,再对每个匹配记录调用费用列表的 `filter[recordId]`。返回的费用必须与请求记录 ID 一致;若双方都有 documentId,还必须一致。重审/重放产生的多个记录均纳入查询,不默认只查最新一次;费用按稳定费用 ID 去重,不按单号去重。
单号对应多个不同来源单据时返回 `ambiguous_source_documents`,不混合归因。费用列表本身没有已验证的单号直接过滤;找不到关联审批记录时返回 `approval_link_not_found` 和“无法确定”,无法凭该路径排除孤立费用记录。必要时取得明确关联记录 ID,用下面的原始列表入口补查。
## 结论判定
- `status:found, found:true`:至少一条费用已从费用库读取并通过关联校验。`matchedCount` 是已观察到的去重条数,`complete:false` 时仅为下限。
- `status:not_found, found:false, complete:true`:单号匹配到的可见审批记录及其费用分页均已查完,指定费用日期范围内未找到关联费用。对外表述“关联范围内未找到”,不要断言该单据从未入库或推断入库失败根因。
- `status:unknown, found:null, complete:false`:没有足够证据确认存在或不存在。常见原因包括没有审批关联、同号多原单据、扫描上限、分页重复/变化、关联字段不符或接口失败。
所有结果都有 `source:seal_expense_store`、`verification:existence_only`、查询时间、queryScope、scanned、关联记录及费用摘要;摘要不输出员工手机号和邮箱。不得把存在性查询解释成“所有原始费用明细均完整入库”;逐项完整性对账需另有原单明细和稳定行标识。
## 日期、分页和上限
单号查询不自动添加本月或最近一年范围;显式日期只过滤费用列表,不过滤用于定位的审批记录创建日期:
```bash
seal-use expenses --sn <documentSN> --start-date 2025-01-01 --end-date 2025-12-31T23:59:59+08:00 --corp <corpId>
seal-use expenses --sn <documentSN> --limit 100 --max-scan 10000 --corp <corpId>
```
queryScope.startDate/endDate 是规范化毫秒时间戳,null 表示未显式传入;不代表服务端所有历史数据都永久可见。费用记录时间戳和 checkedAt 使用北京时间 ISO 秒级格式。
单号查询中 `--limit` 为每页大小(1–100,默认 100),不是最多返回匹配条数。审批候选扫描和费用扫描各最多 `--max-scan` 条(默认 5000,最高 10000);整个流程最多发起 100 次业务分页调用。命中上限保留已发现证据,标记 `complete:false`,不会以不完整查询得出否定结论。HTTP 层安全 GET 重试不包含在业务分页调用计数中。
总数缺失或变化、重复页、过早空页、记录变化、响应超出页大小都不能认为查询完整。分页不是数据库快照,`complete:true` 只表示当前观察到的相关分页已遍历,不是对并发写入的事务保证。
`--sn` 与 `--search`、`--record-id`、`--offset` 互斥;`--max-scan` 仅用于 `--sn`。非法组合报 exit 2,扫描范围参数未通过 schema 校验报 exit 13。
## 普通费用列表
```bash
seal-use expenses list --search <text> --offset 0 --limit 50 --corp <corpId>
seal-use expenses list --record-id <recordId> --corp <corpId>
seal-use data expenses --record-id <recordId> --corp <corpId>
```
不传 `--sn` 时继续返回原始 `{expenses,total}`,不进行入库判定;`--record-id` 透传精确关联过滤,普通列表由调用者控制分页。列表请求始终包含平台要求的 filter 对象,未指定筛选时发送空搜索值。日期支持 ISO 或时间戳,并转换为接口所需毫秒值。未知子命令和裸位置单号会报用法错误,不会被忽略后返回无关列表。
## 失败和大结果
单号查询接口失败时 stdout 保留结构化查询状态,stderr 说明不完整,进程返回非零:认证失败 exit 11,其他上游/响应格式失败 exit 1。已有确切匹配仍保留 `found:true`,但 `complete:false`;没有匹配证据时保持 unknown。不能把失败当作未入库。
大结果可使用 `--output-file <path>` 保存 JSON,或有意选择 `--full` 放开现有输出保护;默认超过输出限制返回 exit 12。原始费用列表和结构化单号查询均遵守 stdout 纯 JSON。
@@ -34,6 +34,8 @@ Read the JSON `stages` in order:
Do not expect tokens in the output; the command intentionally redacts or omits them.
Seal requests made with a renewable Hose session recover from HTTP 401 once for GET/HEAD/OPTIONS: the CLI exchanges a fresh Seal session and retries that read. Concurrent reads share the refresh, and another 401 stops with exit 11. Fixed Seal Bearer credentials are not refreshed automatically. Mutation requests are never replayed by this recovery path; inspect their result before deciding whether to retry.
When the caller needs the actual OpenAPI `accessToken` itself (for example to call Hose OpenAPI from their own script), use `seal-use auth hose-openapi-token --corp <corpId> [--force]`. It prints the unredacted token as JSON together with `expiresAt` and `cached` (`cached: true` means a still-fresh local token was reused; pass `--force` to mint a new one). Non-Hose enterprises are rejected with exit 2, and a Hose enterprise without persisted `appKey/appSecurity` exits 13.
## Get a Hose authorization link
+17 -9
View File
@@ -167,30 +167,33 @@ sequenceDiagram
Agent->>CLI: 4. seal-use report validate 报告.md
CLI-->>Agent: 门禁通过 (valid: true)
Agent->>CLI: 5. seal-use report render 报告.md --out build/报告/
Agent->>CLI: 5. seal-use report render 报告.md --out <输出目录>/报告/
CLI-->>User: 交付单文件 HTML、A4 PDF 与长图 PNG
```
#### 具体操作指令:
```bash
# 步骤 1:一键拉取指定周期的全量明细台账(含 AI 完整意见与人工批注)
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out reports/明细台账.xlsx
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out <输出目录>/明细台账.xlsx
# 步骤 2:Agent 或用户在 Excel 中自由裁量,增删模板行并填入裁决;
# 步骤 3:严格以修改后的台账为唯一事实源,出具报告草稿
seal-use report generate --ledger reports/明细台账.xlsx --corp <corpId> --out reports/审核报告.md
seal-use report generate --ledger <输出目录>/明细台账.xlsx --corp <corpId> --out <输出目录>/审核报告.md
# 步骤 4:严格门禁校验(必须通过)
seal-use report validate reports/审核报告.md
seal-use report validate <输出目录>/审核报告.md
# 步骤 5:本地全格式编译渲染
seal-use report render reports/审核报告.md --out build/审核报告/
seal-use report render <输出目录>/审核报告.md --out <输出目录>/审核报告/
```
> [!TIP]
> **全量取数与分页控制**:`seal-use report ledger`、`report data` 与 `report generate` 默认自动分页拉取所选时间区间内的**全部审批单据**(内置 100,000 笔安全防死循环上限),无任何 500 条的人工截断限制。如需做小样本分析或限定抓取笔数,可传入 `--limit <n>`(别名 `--max-runs <n>` / `-n <n>`,例如 `--limit 2000`)。
> [!IMPORTANT]
> **落盘位置红线(代码仓零污染)**:`seal-use` 是全局 CLI,输出目录与执行目录解耦。最终交付物以客户/用户要求为最高准则,放用户指定目录或系统下载目录(如 `~/Downloads/<企业名>-<YYYYMM>/`),**严禁在代码仓库根目录(如 `Code/seal-use/reports/`)生成或留存业务报告文件**。会话内供 Agent 快速读取的只读快照落在全局缓存 `~/.cache/seal-use/reports/<corpId>/<YYYY-MM>/`,缓存天然可丢弃、可随时清理,且不占用 `~/.config/`。
---
### 模式 B:CLI 命令行实时研讨驱动
@@ -232,7 +235,7 @@ seal-use report render reports/审核报告.md --out build/审核报告/
4. **离线台账批量导入**:
若线下已在 Excel 台账中集中批量评审完毕,可一键导入持久化存储:
```bash
seal-use report review import reports/明细台账.xlsx --corp <corpId>
seal-use report review import <输出目录>/明细台账.xlsx --corp <corpId>
```
---
@@ -265,6 +268,7 @@ seal-use report render reports/审核报告.md --out build/审核报告/
- **准确率严密计算公式**(必须在正文中由 LaTeX 公式呈现):
$$\text{AI 准确率} = \frac{D_1 + D_4}{S} = \frac{\text{双方同向一致通过数} + \text{AI 依规正确拦截数}}{\text{样本总量}}$$
- 动态内嵌维恩图(`图 1:AI 与人工审核准确率对比.svg`),直观呈现两者的交集与重合度。
- **图表纯粹性**:标准模板只保留这一张数据驱动维恩图;旧版图二(综合效益耗时直方图)与图三(截图占位)已全面废弃并清理,严禁再引入冗余图表或相关死代码。
### 3. §2 AI 判定误判分析
- **2.1 误判构成总览**:总结在分歧复核中判定为“人工正确 / AI 判定误判”的单据总量及在全样本中的占比。
@@ -322,7 +326,7 @@ seal-use report render reports/审核报告.md --out build/审核报告/
在执行最终渲染交付前,Agent **必须**执行门禁校验命令:
```bash
seal-use report validate reports/审核报告.md
seal-use report validate <输出目录>/审核报告.md
```
若存在任何格式或数学勾稽问题,命令将以 **退出码 1** 阻断导出,并输出带有错误代码的 JSON。Agent 必须根据报错信息自主编辑修正。
@@ -351,10 +355,10 @@ seal-use report validate reports/审核报告.md
```bash
# 一键编译全套产物(单文件 HTML、A4 PDF、超清拼接长图 PNG)
seal-use report render reports/审核报告.md --out build/审核报告/ --format all
seal-use report render <输出目录>/审核报告.md --out <输出目录>/审核报告/ --format all
# 整包打包归档(产出 ZIP / 完整文件夹,自动收拢 Markdown、配图与明细台账)
seal-use report export reports/审核报告.md --out build/交付整包/
seal-use report export <输出目录>/审核报告.md --out <输出目录>/交付整包/
```
### 交付产物技术特性与适用场景:
@@ -369,3 +373,7 @@ seal-use report export reports/审核报告.md --out build/交付整包/
3. **超高清拼接长图 (`.png`)**:
- 由原生无头浏览器以 4x 视口倍率切片截取,并通过高性能图形算法在内存中无损拼接;
- 专为钉钉、微信、飞书等移动端 IM 聊天窗口设计,方便管理层在手机上顺滑滑动审阅。
4. **末尾术语与指标定义规范附录页 (Glossary Page)**:
- 渲染流水线在生成 HTML、PDF、PNG 产物时,自动在末尾追加独立术语解释与指标定义附录页(涵盖审批决策与五类裁决、人机一致性与极性、KaTeX 量化公式、`recordId` 与 `SN` 双主键规范);
- 原始报告 Markdown 保持干净不被侵入修改;PDF 在打印时拥有独立的物理分页隔离(`page-break-before: always`);
- 若特定简报场景不需要附录页,可在 `report render` 或 `report export` 中指定 `--no-glossary` 参数跳过追加。
+3 -2
View File
@@ -107,12 +107,13 @@ describe("CLI version & help handling", () => {
expect(result.stderr).toContain("Usage: seal-use documents get <documentId>");
});
test("requires --yes confirmation on documents delete", () => {
test("requires explicit confirmation on documents delete", () => {
const env = makeConfigEnv();
const result = runCli(["documents", "delete", "doc-123", "--corp", "corp-a"], env);
expect(result.status).toBe(10);
expect(result.stderr).toContain("Refusing to delete document 'doc-123' without --yes.");
expect(result.stderr).toContain("documents delete requires --yes or --confirm");
expect(result.stderr).toContain("--dry-run");
});
test("does not hijack --version option when passed to subcommands like rules", () => {
+1 -1
View File
@@ -11,7 +11,7 @@ process.stderr.on("error", (err: any) => {
if (err?.code === "EPIPE") process.exit(0);
});
performRuntimeSelfHealing();
await performRuntimeSelfHealing();
const entryFile = fileURLToPath(import.meta.url);
const isCompiled = isCompiledBinary();
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, test } from "bun:test";
import { AREA_ALIASES, UPDATE_ALIASES, normalizeCliArea } from "./area-aliases.js";
import { KNOWN_AREAS } from "./runner.js";
/**
* Drift guard for the shared alias table.
*
* `read-only.ts` once hand-copied the alias pairs from `runner.ts` and the two
* silently diverged — the exact class of bug the 2026-10-17 architecture
* review called "two sources of truth". The tables now live in one module and
* are imported by dispatch, help, and the read-only gateway; these tests make
* the remaining cross-module contract explicit: an alias may only point at an
* area the dispatcher actually handles, may not chain into another alias, and
* must not shadow a real area name.
*/
describe("area alias integrity", () => {
test("every alias resolves to a dispatchable area", () => {
const dangling = Object.entries(AREA_ALIASES)
.filter(([, target]) => !KNOWN_AREAS.has(target))
.map(([alias, target]) => `${alias} -> ${target}`);
expect(dangling).toEqual([]);
});
test("no alias chains into another alias", () => {
// normalizeCliArea applies one lookup; a chained alias would dispatch the
// raw alias spelling as a command area and fail with "Unknown command".
const chained = Object.values(AREA_ALIASES).filter((target) => target in AREA_ALIASES);
expect(chained).toEqual([]);
});
test("alias spellings never shadow a real area name", () => {
// KNOWN_AREAS is the handler tables plus the alias keys; subtracting the
// alias keys recovers the real dispatch areas. An alias colliding with
// one of them would be dead weight at best and ambiguous at worst.
const realAreas = new Set([...KNOWN_AREAS].filter((area) => !(area in AREA_ALIASES)));
const shadowing = Object.keys(AREA_ALIASES).filter((alias) => realAreas.has(alias));
expect(shadowing).toEqual([]);
});
test("every update spelling normalizes onto the real update area", () => {
for (const spelling of UPDATE_ALIASES) {
expect(normalizeCliArea(spelling)).toBe("update");
}
expect(KNOWN_AREAS.has("update")).toBe(true);
});
test("normalization is idempotent and case-insensitive", () => {
expect(normalizeCliArea(normalizeCliArea("corp"))).toBe("corps");
expect(normalizeCliArea("CORP")).toBe("corps");
expect(normalizeCliArea("Self-Update")).toBe("update");
});
test("every alias and update spelling resolves through KNOWN_AREAS", () => {
// Alias keys must be members outright: help lookup and the read-only
// gateway resolve the raw spelling before any normalization. Update
// spellings are normalized first, so their canonical target is the
// dispatchable name.
for (const alias of Object.keys(AREA_ALIASES)) {
expect(KNOWN_AREAS.has(alias)).toBe(true);
}
for (const spelling of UPDATE_ALIASES) {
expect(KNOWN_AREAS.has(normalizeCliArea(spelling))).toBe(true);
}
});
});
+18
View File
@@ -0,0 +1,18 @@
/** Execution aliases shared by dispatch, help, and the read-only gateway. */
export const AREA_ALIASES: Readonly<Record<string, string>> = {
corp: "corps",
webhooks: "webhook",
preferences: "preference",
server: "mcp",
invoice: "invoices",
expense: "expenses"
}
export const UPDATE_ALIASES = new Set([
"update", "upgrade", "up", "self-update", "selfupdate"
])
export function normalizeCliArea(area: string): string {
const lower = area.toLowerCase()
return UPDATE_ALIASES.has(lower) ? "update" : AREA_ALIASES[lower] ?? lower
}
+4 -3
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { exportInsightReportToExcel } from "../../domains/seal/insight/export.js";
@@ -31,7 +32,7 @@ export async function handleAnalyticsCommand(
if (action === "risks" || action === "risks-by-tag" || action === "tag-risks") {
const tagId = maybeName ?? stringOption(args.options.tagId) ?? stringOption(args.options["tag-id"]);
if (!tagId) {
throw new Error("Usage: seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]");
throw usageError("Usage: seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]");
}
await runCapability(
"sealInsightRisksByTagGet",
@@ -64,7 +65,7 @@ export async function handleAnalyticsCommand(
if (action === "analyze" || action === "reanalyze") {
const recordId = maybeName ?? stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]);
if (!recordId) {
throw new Error("Usage: seal-use analytics analyze <recordId> [--corp <corpId>]");
throw usageError("Usage: seal-use analytics analyze <recordId> [--corp <corpId>]");
}
await runCapability(
"sealInsightRecordAnalyze",
@@ -91,5 +92,5 @@ export async function handleAnalyticsCommand(
return;
}
throw new Error(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+12 -15
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import * as api from "../../domains/seal/api.js";
@@ -151,7 +152,7 @@ export async function handleApprovalRunsCommand(
if (action === "pick") {
const query = maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.sn);
if (!query) throw new Error("Usage: seal-use approval-runs pick --sn <documentSN>");
if (!query) throw usageError("Usage: seal-use approval-runs pick --sn <documentSN>");
await runCapability(
"sealApprovalRunPick",
client,
@@ -199,14 +200,14 @@ export async function handleApprovalRunsCommand(
if (action === "cited-rules") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs cited-rules <recordId>");
if (!recordId) throw usageError("Usage: seal-use approval-runs cited-rules <recordId>");
await runCapability("sealApprovalRunCitedRulesGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "document-summary") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs document-summary <recordId>");
if (!recordId) throw usageError("Usage: seal-use approval-runs document-summary <recordId>");
await runCapability("sealApprovalRunDocumentSummaryGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
@@ -215,7 +216,7 @@ export async function handleApprovalRunsCommand(
const recordId = args.command[2];
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
if (!recordId && !sn) {
throw new Error("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
throw usageError("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRunDiagnose",
@@ -236,9 +237,7 @@ export async function handleApprovalRunsCommand(
if (subAction === "download") {
const recordId = args.command[3];
if (!recordId) {
throw new Error(
"Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
throw usageError("Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]");
}
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
@@ -259,7 +258,7 @@ export async function handleApprovalRunsCommand(
}
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");
if (!recordId) throw usageError("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");
if (booleanOption(args.options.download)) {
const record = await api.getApprovalRun(client, recordId);
@@ -291,9 +290,7 @@ export async function handleApprovalRunsCommand(
if (action === "download") {
const recordId = args.command[2];
if (!recordId) {
throw new Error(
"Usage: seal-use approval-runs download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
throw usageError("Usage: seal-use approval-runs download <recordId> [--all] [--name <name>] [--out-dir <dir>]");
}
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
@@ -315,7 +312,7 @@ export async function handleApprovalRunsCommand(
if (action === "result") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs result <recordId> [--summary]");
if (!recordId) throw usageError("Usage: seal-use approval-runs result <recordId> [--summary]");
await runCapability(
"sealApprovalRunResultGet",
client,
@@ -344,7 +341,7 @@ export async function handleApprovalRunsCommand(
const sourceDocumentId = stringOption(args.options.sourceDocumentId);
if (!recordId && !sn && !sourceDocumentId) {
throw new Error("Usage: seal-use approval-runs link <recordId> [--sn <sn>] [--type seal-result|hose-document] [--auto-login] [--corp <corpId>]");
throw usageError("Usage: seal-use approval-runs link <recordId> [--sn <sn>] [--type seal-result|hose-document] [--auto-login] [--corp <corpId>]");
}
await runCapability(
@@ -373,7 +370,7 @@ export async function handleApprovalRunsCommand(
stringOption(args.options.id) ??
stringOption(args.options.recordId);
if (!target) {
throw new Error("Usage: seal-use approval-runs hose-flow <recordId|SN>");
throw usageError("Usage: seal-use approval-runs hose-flow <recordId|SN>");
}
await runCapability(
@@ -451,5 +448,5 @@ export async function handleApprovalRunsCommand(
return;
}
throw new Error(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+5 -7
View File
@@ -8,7 +8,7 @@ import {
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import { CliError, validationError } from "../../core/errors.js";
import { CliError, validationError, usageError } from "../../core/errors.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { createDelegation, getMe } from "../../domains/seal/api.js";
@@ -26,9 +26,7 @@ import { extractKeysFromLinkAction, showCorpKeysAction } from "./corps.js";
export async function handleAuthExtractKeysCommand(maybeName: string | undefined, args: ParsedArgs) {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error(
"Usage: seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]"
);
throw usageError("Usage: seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");
}
const reveal =
booleanOption(args.options.reveal) === true ||
@@ -81,7 +79,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
}
if (!corp) {
throw new Error(`auth ${action ?? ""} requires an enterprise. Provide --corp <id> or select one.`);
throw validationError(`auth ${action ?? ""} requires an enterprise. Provide --corp <id> or select one.`);
}
if (action === "check" || action === "diagnose" || action === "status" || action === "test" || action === "doctor") {
@@ -99,7 +97,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
if (subAction === "revoke") {
const tokenId = args.command[3] ?? stringOption(args.options.tokenId) ?? stringOption(args.options.id);
if (!tokenId) throw new Error("Usage: seal-use auth link revoke <tokenId>");
if (!tokenId) throw usageError("Usage: seal-use auth link revoke <tokenId>");
await runCapability("sealDelegationRevoke", client, corp, { tokenId }, outputOptions(args.options));
return;
}
@@ -201,7 +199,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
return;
}
throw new Error(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
async function diagnoseAuth(corp: CorpConfig) {
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -25,5 +26,5 @@ export async function handleBillingCommand(
return;
}
throw new Error(`Unknown billing command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown billing command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import {
getEnterprisesDirCandidates,
loadCorpConfigs,
@@ -123,5 +124,5 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint, test-dir. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint, test-dir. Run 'seal-use help' for available commands.`);
}
+4 -3
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -27,16 +28,16 @@ export async function handleContactsCommand(
}
if (action === "children" || action === "department-children") {
if (!maybeName) throw new Error("Usage: seal-use contacts children <departmentId>");
if (!maybeName) throw usageError("Usage: seal-use contacts children <departmentId>");
await runCapability("sealContactsDepartmentChildrenList", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
if (action === "users" || action === "department-users") {
if (!maybeName) throw new Error("Usage: seal-use contacts users <departmentId>");
if (!maybeName) throw usageError("Usage: seal-use contacts users <departmentId>");
await runCapability("sealContactsDepartmentUsersList", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
throw new Error(`Unknown contacts command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown contacts command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import { handleCorpBindings } from "./corps/bindings.js";
import { handleCorpOnboarding, extractKeysFromLinkAction, showCorpKeysAction } from "./corps/onboarding.js";
import { handleCorpOverview } from "./corps/overview.js";
@@ -17,5 +18,5 @@ export async function handleCorpsCommand(
if (await handleCorpSync(action, maybeName, args)) return;
if (await handleCorpOnboarding(action, maybeName, args)) return;
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { updateCorpConfig } from "../../../core/config/loader.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../errors.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
+4 -4
View File
@@ -14,7 +14,7 @@ import {
formatHoseKeyForOutput,
HoseKeySelectionError
} from "../../../domains/hose/keys.js";
import { CliError } from "../../errors.js";
import { CliError, usageError } from "../../../core/errors.js";
import { selectCorp } from "../../helpers.js";
import {
booleanOption,
@@ -181,7 +181,7 @@ export async function handleCorpOnboarding(
if (action === "add-link") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error("Usage: seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--overwrite]");
throw usageError("Usage: seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--overwrite]");
}
const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true;
const legacyAsHose = booleanOption(args.options["as-hose"]) === true || booleanOption(args.options.hose) === true;
@@ -211,7 +211,7 @@ export async function handleCorpOnboarding(
if (action === "extract-keys" || action === "extract-key" || action === "extract-hose-keys" || action === "hose-extract-keys") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error("Usage: seal-use corps hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]");
throw usageError("Usage: seal-use corps hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]");
}
await extractKeysFromLinkAction(link, {
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true || booleanOption(args.options.plain) === true,
@@ -250,7 +250,7 @@ export async function handleCorpOnboarding(
async function addSealCorp(input: Record<string, unknown>) {
const token = requiredString(input, "token");
const sealUrl = (optionalString(input, "sealUrl") ?? optionalString(input, "url") ?? "").replace(/\/+$/, "");
if (!sealUrl) throw new Error("Missing required JSON field: sealUrl");
if (!sealUrl) throw usageError("Missing required JSON field: sealUrl");
const result = await onboardSealBearer({
...input,
token,
+3 -3
View File
@@ -12,7 +12,7 @@ import {
} from "../../../core/stats/usage-tracker.js";
import type { CorpEnvironment } from "../../../core/config/types.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../errors.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
@@ -192,7 +192,7 @@ export async function handleCorpOverview(
(args.command[3] && !args.command[3].startsWith("-") ? args.command[3] : undefined);
if (!targetCorpId || !newName) {
throw new Error("Usage: seal-use corps rename <corpId> --name <newName>");
throw usageError("Usage: seal-use corps rename <corpId> --name <newName>");
}
const corp = selectCorp(targetCorpId);
@@ -208,7 +208,7 @@ export async function handleCorpOverview(
if (action === "switch") {
const corpId = maybeName;
if (!corpId) throw new Error("Usage: seal-use corps switch <corpId>");
if (!corpId) throw usageError("Usage: seal-use corps switch <corpId>");
const globalConfig = loadGlobalConfig();
if (!globalConfig.stateful) {
throw new Error(
+1 -1
View File
@@ -3,7 +3,7 @@ import type { CorpConfig } from "../../../core/config/types.js";
import { syncTestEnterprise } from "../../../domains/seal/testing/sync.js";
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/replay/webhook.js";
import { selectCorp } from "../../helpers.js";
import { CliError, confirmationRequired, usageError } from "../../errors.js";
import { CliError, confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { outputOptions, printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
+8 -14
View File
@@ -1,8 +1,6 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
import { numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleDataCommand(
@@ -11,23 +9,19 @@ export async function handleDataCommand(
corp: CorpConfig,
args: ParsedArgs
) {
const params = {
offset: numberOption(args.options.offset),
limit: numberOption(args.options.limit),
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
search: stringOption(args.options.search) ?? stringOption(args.options.query)
};
if (action === "expenses" || action === "expense") {
await runCapability("sealExpensesList", client, corp, params, outputOptions(args.options));
const { handleExpensesCommand } = await import("./expenses.js");
await handleExpensesCommand(args.command[2], client, corp, args);
return;
}
if (action === "invoices" || action === "invoice") {
await runCapability("sealInvoicesList", client, corp, params, outputOptions(args.options));
const subAction = args.command[2];
const maybeTarget = args.command[3];
const { handleInvoicesCommand } = await import("./invoices.js");
await handleInvoicesCommand(subAction, maybeTarget, client, corp, args);
return;
}
throw new Error(`Unknown data command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown data command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+6 -8
View File
@@ -7,7 +7,7 @@ import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import * as api from "../../domains/seal/api.js";
import { listHoseIntegrations } from "../../domains/seal/outbound/push.js";
import { CliError } from "../errors.js";
import { CliError, usageError, validationError } from "../../core/errors.js";
export async function handleDeployCommand(
systemOrAction: string | undefined,
@@ -18,16 +18,14 @@ export async function handleDeployCommand(
args: ParsedArgs
) {
if (!systemOrAction || systemOrAction === "help") {
throw new Error(
"Usage: seal-use deploy <system> <action> [options]\n\n" +
throw usageError("Usage: seal-use deploy <system> <action> [options]\n\n" +
"支持的审批系统与发布目标:\n" +
" • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>\n" +
" • webhook (通用审批流回调): seal-use webhook <list|get|add|update|delete> --corp <corpId>\n" +
" • feishu (飞书审批): 建议使用 Webhook 模式对接\n" +
" • weaver (泛微 OA): 建议使用 Webhook 模式对接\n" +
" • helios (汇联易): 建议使用 Webhook 模式对接\n" +
" • maycur (每刻报销): 建议使用 Webhook 模式对接"
);
" • maycur (每刻报销): 建议使用 Webhook 模式对接");
}
if (systemOrAction === "webhook" || systemOrAction === "webhooks") {
@@ -52,7 +50,7 @@ export async function handleDeployCommand(
const target = systemOrAction === "hosecloud" ? maybeTarget : actionOrTarget;
if (!isHosecloud) {
throw new Error(`未知的发布目标系统: ${systemOrAction}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);
throw validationError(`未知的发布目标系统: ${systemOrAction}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);
}
if (action === "requirements") {
@@ -108,7 +106,7 @@ export async function handleDeployCommand(
? JSON.parse(readFileSync(rawInput, "utf8"))
: jsonObject(args.json);
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");
throw usageError("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");
}
await runCapability("sealDeployHosecloudConfigure", client, corp, {
...payload,
@@ -200,6 +198,6 @@ export async function handleDeployCommand(
return;
}
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`);
throw usageError(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`);
}
+1 -1
View File
@@ -44,7 +44,7 @@ export async function handleDoctorCommand(
const { selectCorp } = await import("../helpers.js");
const { createSealClient } = await import("../../core/http/factory.js");
const { stringOption } = await import("../parser.js");
const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../core/doctor/tenant-diagnose.js");
const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../domains/seal/doctor/tenant-diagnose.js");
const corpSelector =
stringOption(args.options.corp) ??
+180
View File
@@ -0,0 +1,180 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { runCli } from "../runner.js"
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
const oldFetch = globalThis.fetch
let dir: string
let document = { id: "doc-1", title: "Fixture policy", purpose: "Testing", content: "Line one\\\r\n| a \\| b |", status: "published", enabled: true, scenarios: ["audit"], tags: ["test"] }
let requests: Array<{ method: string; path: string; query: string; body?: Record<string, unknown> }>
let failReadback: boolean
let failReadbackStatus: number
const original = structuredClone(document)
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-documents-cli-"))
const enterprises = join(dir, "enterprises")
mkdirSync(enterprises)
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
writeFileSync(join(enterprises, "document-cli-test.json"), JSON.stringify({
id: "document-cli-test", name: "Document Test", environment: "test",
seal: { url: "https://documents.example.test" },
source: { type: "seal", token: "test-token", sealUrl: "https://documents.example.test", staffId: "fixture" }
}))
document = structuredClone(original)
requests = []
failReadback = false
failReadbackStatus = 400
let writeCount = 0
let readbackWrites = 0
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
const url = new URL(request.url)
const method = request.method
const body = ["PATCH", "POST"].includes(method) ? JSON.parse(await request.text()) as Record<string, unknown> : undefined
requests.push({ method, path: url.pathname, query: url.searchParams.toString(), body })
if (failReadback && method === "GET" && writeCount > readbackWrites) {
readbackWrites = writeCount
return Response.json({ error: "offline" }, { status: failReadbackStatus })
}
if (method === "PATCH") {
writeCount++
document = { ...document, ...(body?.attributes as object) }
}
if (method === "POST") document = { ...document, ...body }
return Response.json({ data: url.pathname.endsWith("/articles") && method === "GET" ? { articles: [document], total: 115 } : document })
}) as typeof fetch
})
afterEach(() => {
for (const key of envKeys) {
if (oldEnv[key] === undefined) delete process.env[key]
else process.env[key] = oldEnv[key]
}
globalThis.fetch = oldFetch
rmSync(dir, { recursive: true, force: true })
})
function cli(...argv: string[]) { return runCli(["documents", ...argv, "--corp", "document-cli-test"]) }
const writes = () => requests.filter(request => request.method !== "GET")
describe("documents CLI", () => {
test("exports body plus baseline, previews edits, and updates only body with JSON receipts", async () => {
const out = join(dir, "body.txt")
const exported = await cli("get", "doc-1", "--out", out)
expect(exported.exitCode).toBe(0)
expect(JSON.parse(exported.stdout)).toMatchObject({ contentFile: out, contentFormat: "raw" })
expect(readFileSync(out, "utf8")).toBe(original.content)
writeFileSync(out, "edited content")
const preview = await cli("update", "doc-1", "--content-file", out, "--dry-run", "--yes")
expect(preview.exitCode).toBe(0)
expect(JSON.parse(preview.stdout)).toMatchObject({ preview: true, executed: false, baselineAvailable: true, changedFields: ["content"] })
expect(writes()).toHaveLength(0)
const result = await cli("update", "doc-1", "--content-file", out, "--yes")
expect(result.exitCode).toBe(0)
const payload = JSON.parse(result.stdout)
expect(payload).toMatchObject({ verified: true, executed: true, baselineAvailable: true })
expect(JSON.parse(readFileSync(payload.snapshotFile, "utf8")).document.content).toBe(original.content)
expect(writes()).toHaveLength(1)
expect(writes()[0]?.body).toEqual({ attributes: { content: "edited content" } })
expect(document.title).toBe(original.title)
expect(document.status).toBe("published")
})
test("plain get and output-file still produce whole document JSON", async () => {
expect(JSON.parse((await cli("get", "doc-1")).stdout)).toMatchObject(original)
const path = join(dir, "document.json")
const result = await cli("get", "doc-1", "--output-file", path)
expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path })
expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject(original)
})
test("lightweight list and explicit fields do not request per-document details", async () => {
const summary = await cli("list", "--summary", "--limit", "2", "--offset", "1")
expect(summary.exitCode).toBe(0)
expect(JSON.parse(summary.stdout).articles[0]).not.toHaveProperty("content")
expect(new URLSearchParams(requests[0]?.query).get("limit")).toBe("2")
expect(new URLSearchParams(requests[0]?.query).get("offset")).toBe("1")
const fields = await cli("list", "--summary", "--fields", "id,title")
expect(JSON.parse(fields.stdout)).toEqual({ total: 115, articles: [{ id: "doc-1", title: original.title }] })
expect(requests.every(request => request.path === "/api/v1/knowledge/articles")).toBe(true)
expect((await cli("list", "--fields", "typo")).exitCode).toBe(2)
})
test("all write commands require confirmation and all previews remain read-only", async () => {
const variants = [
["create", "--title", "new", "--purpose", "test", "--content", "new"],
["update", "doc-1", "--content", "new"],
["delete", "doc-1"]
]
for (const argv of variants) {
expect((await cli(...argv)).exitCode).toBe(10)
for (const flag of ["--dry-run", "--dryRun"]) {
const result = await cli(...argv, flag, "--confirm")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ preview: true, executed: false })
}
}
expect(writes()).toHaveLength(0)
expect(existsSync(join(dir, "document-history"))).toBe(false)
})
test("conflicts and failed readback return JSON state with nonzero exit codes", async () => {
const path = join(dir, "body")
await cli("get", "doc-1", "--out", path)
writeFileSync(path, "my edit")
document.content = "remote edit"
const conflict = await cli("update", "doc-1", "--content-file", path, "--yes")
expect(conflict.exitCode).toBe(1)
expect(JSON.parse(conflict.stdout)).toMatchObject({ code: "DOCUMENT_CONFLICT", executed: false })
expect(writes()).toHaveLength(0)
failReadback = true
const uncertain = await cli("update", "doc-1", "--content", "new", "--yes")
expect(uncertain.exitCode).toBe(1)
expect(JSON.parse(uncertain.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false })
expect(uncertain.stderr).toContain("Next action:")
failReadbackStatus = 401
const authFailed = await cli("update", "doc-1", "--content", "newer", "--yes")
expect(authFailed.exitCode).toBe(11)
expect(JSON.parse(authFailed.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false })
})
test("unsupported format and path/input conflicts fail before requests or file changes", async () => {
const path = join(dir, "body")
writeFileSync(path, "keep")
for (const argv of [
["get", "doc-1", "--out", path, "--content-format", "markdown"],
["get", "doc-1", "--out", path, "--output-file", path],
["update", "doc-1", "--content-file", path, "--content", "other", "--yes"],
["update", "doc-1", "--content-file", path, "--output-file", path, "--yes"],
["update", "doc-1", "--content-file", path, "--output-file", `${path}.seal-use.json`, "--yes"]
]) expect((await cli(...argv)).exitCode).toBe(2)
expect(readFileSync(path, "utf8")).toBe("keep")
expect(requests).toHaveLength(0)
})
test("invalid UTF-8, missing file and damaged baseline fail with exit 13 and zero writes", async () => {
const path = join(dir, "body")
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
writeFileSync(path, Buffer.from([0xff]))
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
writeFileSync(path, "new")
writeFileSync(`${path}.seal-use.json`, "{}")
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
expect(writes()).toHaveLength(0)
})
test("legacy raw input is supported and discloses absence of an editing baseline", async () => {
const result = await cli("update", "doc-1", "--content", "new", "--confirm")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ verified: true, baselineAvailable: false })
expect(result.stderr).toContain("baselineAvailable:false")
})
})
+72 -43
View File
@@ -1,8 +1,11 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { runCapability } from "../helpers.js";
import { usageError } from "../../core/errors.js";
import { runCapability, runCapabilityResult } from "../helpers.js";
import { exportDocument, readDocumentBaseline, readDocumentText } from "../../domains/seal/documents/files.js";
import { DocumentMutationError } from "../../domains/seal/documents/service.js";
import { ApprovalDocumentSchema } from "../../domains/seal/types.js";
import {
booleanOption,
jsonObject,
@@ -10,17 +13,25 @@ import {
splitOption,
stringOption
} from "../parser.js";
import { outputOptions } from "../printer.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
function readContentInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
const filePath =
function contentFilePath(args: ParsedArgs): string | undefined {
return (
stringOption(args.options.contentFile) ??
stringOption(args.options["content-file"]) ??
stringOption(args.options.file) ??
stringOption(args.options.f);
stringOption(args.options.f)
);
}
function readContentInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
const filePath = contentFilePath(args);
const fileInputs = ["contentFile", "content-file", "file", "f"].filter(key => args.options[key] !== undefined).length;
const sources = fileInputs + Number(args.options.content !== undefined) + Number(payload.content !== undefined);
if (sources > 1) throw usageError("Specify exactly one document content source: --content-file, --content, or JSON content");
if (filePath) {
return readFileSync(filePath, "utf8");
return readDocumentText(filePath);
}
const direct = stringOption(args.options.content);
if (direct !== undefined) return direct;
@@ -34,6 +45,33 @@ export async function handleDocumentsCommand(
corp: CorpConfig,
args: ParsedArgs
) {
const out = stringOption(args.options.out);
const format = stringOption(args.options["content-format"]) ?? stringOption(args.options.contentFormat);
if (format !== undefined && format !== "raw") throw usageError("--content-format supports raw only; Markdown conversion requires a verified platform codec");
if (out && action !== "get") throw usageError("--out is supported only by documents get");
if (format !== undefined && !["get", "create", "update"].includes(action ?? "")) throw usageError("--content-format is supported only by documents get/create/update");
if (out && outputOptions(args.options).outputFile) throw usageError("--out (body) and --output-file (JSON) are mutually exclusive");
if (booleanOption(args.options.overwrite) && !out) throw usageError("--overwrite requires documents get --out");
const contentPath = contentFilePath(args);
const jsonOutput = outputOptions(args.options).outputFile;
if (contentPath && jsonOutput && [resolve(contentPath), `${resolve(contentPath)}.seal-use.json`].includes(resolve(jsonOutput))) {
throw usageError("--output-file must not overwrite the input body or its export baseline");
}
const safety = {
dryRun: booleanOption(args.options["dry-run"]) ?? booleanOption(args.options.dryRun),
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true,
allowEmpty: booleanOption(args.options["allow-empty"]) ?? booleanOption(args.options.allowEmpty)
};
const mutate = async (name: string, params: Record<string, unknown>) => {
try {
printJson(await runCapabilityResult(name, client, corp, params), outputOptions(args.options));
} catch (error) {
if (error instanceof DocumentMutationError) printJson(error.payload, outputOptions(args.options));
throw error;
}
};
if (!action || action === "list") {
const scenarios = splitOption(args.options.scenarios);
const limit = numberOption(args.options.limit);
@@ -42,7 +80,7 @@ export async function handleDocumentsCommand(
"sealApprovalDocumentsList",
client,
corp,
{ scenarios, limit, offset },
{ scenarios, limit, offset, summary: booleanOption(args.options.summary), fields: splitOption(args.options.fields) },
outputOptions(args.options)
);
return;
@@ -55,7 +93,12 @@ export async function handleDocumentsCommand(
stringOption(args.options["document-id"]) ??
stringOption(args.options.id);
if (!documentId) {
throw new Error("Usage: seal-use documents get <documentId> [--corp <corpId>]");
throw usageError("Usage: seal-use documents get <documentId> [--corp <corpId>]");
}
if (out) {
const document = ApprovalDocumentSchema.parse(await runCapabilityResult("sealApprovalDocumentGet", client, corp, { documentId }));
printJson(exportDocument(corp, document, out, booleanOption(args.options.overwrite)));
return;
}
await runCapability(
"sealApprovalDocumentGet",
@@ -70,7 +113,7 @@ export async function handleDocumentsCommand(
if (action === "search") {
const keyword = maybeName ?? stringOption(args.options.query);
if (!keyword) {
throw new Error("Usage: seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]");
throw usageError("Usage: seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]");
}
await runCapability(
"sealApprovalSearch",
@@ -115,15 +158,11 @@ export async function handleDocumentsCommand(
(Array.isArray(payload.tags) ? (payload.tags as string[]) : undefined);
if (!title || !purpose || content === undefined) {
throw new Error(
"Usage: seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
);
throw usageError("Usage: seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]");
}
await runCapability(
await mutate(
"sealApprovalDocumentCreate",
client,
corp,
{
title,
purpose,
@@ -132,9 +171,9 @@ export async function handleDocumentsCommand(
status,
enabled,
scenarios,
tags
},
outputOptions(args.options)
tags,
...safety
}
);
return;
}
@@ -179,15 +218,14 @@ export async function handleDocumentsCommand(
tags !== undefined;
if (!documentId || !hasChanges) {
throw new Error(
"Usage: seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
);
throw usageError("Usage: seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]");
}
await runCapability(
const filePath = contentFilePath(args);
const baseline = filePath ? readDocumentBaseline(filePath) : undefined;
if (content !== undefined && !baseline) console.error("Document input has no export baseline; changes made by others during editing cannot be detected (baselineAvailable:false).");
await mutate(
"sealApprovalDocumentUpdate",
client,
corp,
{
documentId,
title,
@@ -197,9 +235,10 @@ export async function handleDocumentsCommand(
status,
enabled,
scenarios,
tags
},
outputOptions(args.options)
tags,
baseline,
...safety
}
);
return;
}
@@ -211,24 +250,14 @@ export async function handleDocumentsCommand(
stringOption(args.options["document-id"]) ??
stringOption(args.options.id);
if (!documentId) {
throw new Error("Usage: seal-use documents delete <documentId> --yes [--corp <corpId>]");
throw usageError("Usage: seal-use documents delete <documentId> --yes [--corp <corpId>]");
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to delete document '${documentId}' without --yes.`,
`seal-use documents delete ${documentId} --corp ${corp.id} --yes`
);
}
await runCapability(
await mutate(
"sealApprovalDeleteDocument",
client,
corp,
{ documentId },
outputOptions(args.options)
{ documentId, dryRun: safety.dryRun, confirm: safety.confirm }
);
return;
}
throw new Error(`Unknown documents command: ${action}. Available: list, get, search, create, update, delete.`);
throw usageError(`Unknown documents command: ${action}. Available: list, get, search, create, update, delete.`);
}
+127
View File
@@ -0,0 +1,127 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { runCli } from "../runner.js"
const envKeys = ["SEAL_USE_CONFIG_FILE", "SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
const oldFetch = globalThis.fetch
let dir: string
let requests: Array<{ method: string; path: string; query: URLSearchParams }>
let approvalSN: string
let expenseCount: number
let failureStatus: number | undefined
let description: string
const sn = "SN-CLI-FIXTURE"
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-expense-cli-"))
const enterprises = join(dir, "enterprises")
mkdirSync(enterprises)
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
writeFileSync(join(enterprises, "expense-cli-test.json"), JSON.stringify({
id: "expense-cli-test", name: "Expense Test", environment: "test", seal: { url: "https://expense.example.test" },
source: { type: "seal", token: "test-token", sealUrl: "https://expense.example.test", staffId: "fixture" }
}))
requests = []
approvalSN = sn
expenseCount = 2
failureStatus = undefined
description = "Fixture only"
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
const url = new URL(request.url)
requests.push({ method: request.method, path: url.pathname, query: url.searchParams })
if (request.method !== "GET") throw new Error("Unexpected mutation")
if (url.pathname === "/api/v1/approvals") return Response.json({ data: { records: [{ id: "record-1", sourceDocumentSN: approvalSN, sourceDocumentId: "source-1", documentId: "document-1" }], total: 1 } })
if (failureStatus) return Response.json({ error: { message: "fixture failure" } }, { status: failureStatus })
if (!url.searchParams.has("filter[search]") && !url.searchParams.has("filter[recordId]")) return Response.json({ error: "filter required" }, { status: 400 })
const offset = Number(url.searchParams.get("offset"))
const limit = Number(url.searchParams.get("limit"))
const expenses = Array.from({ length: expenseCount }, (_, i) => ({ id: `expense-${i}`, recordId: "record-1", documentId: "document-1", type: "fixture", amount: i + 1, currency: "CNY", description, user: { mobile: "private-fixture" } }))
return Response.json({ data: { expenses: expenses.slice(offset, offset + limit), total: expenses.length } })
}) as typeof fetch
})
afterEach(() => {
for (const key of envKeys) {
if (oldEnv[key] === undefined) delete process.env[key]
else process.env[key] = oldEnv[key]
}
globalThis.fetch = oldFetch
rmSync(dir, { recursive: true, force: true })
})
function cli(...argv: string[]) { return runCli([...argv, "--corp", "expense-cli-test"]) }
describe("expense document lookup CLI", () => {
test("canonical, singular, list and data entrances all execute the same read-only lookup", async () => {
for (const prefix of [["expenses"], ["expense"], ["expenses", "list"], ["data", "expenses"], ["data", "expense", "list"]]) {
const result = await cli(...prefix, "--sn", sn, "--limit", "1")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", found: true, complete: true, matchedCount: 2 })
expect(result.stdout).not.toContain("private-fixture")
}
expect(requests.every(request => request.method === "GET")).toBe(true)
expect(requests.filter(request => request.path.includes("expenses")).every(request => request.query.get("filter[recordId]") === "record-1")).toBe(true)
})
test("raw list behavior stays compatible while bare list and record filters get a required filter object", async () => {
const raw = await cli("expenses", "list")
expect(raw.exitCode).toBe(0)
expect(JSON.parse(raw.stdout)).toHaveProperty("expenses")
expect(requests[0]?.query.get("filter[search]")).toBe("")
expect(requests[0]?.query.has("filter[startDate]")).toBe(false)
const byRecord = await cli("data", "expenses", "--record-id", "record-1")
expect(byRecord.exitCode).toBe(0)
expect(requests[1]?.query.get("filter[recordId]")).toBe("record-1")
await cli("expenses", "--search", "交通", "--offset", "2")
expect(requests[2]?.query.get("filter[search]")).toBe("交通")
expect(requests[2]?.query.get("offset")).toBe("2")
})
test("absence and unresolved linking have different JSON conclusions", async () => {
expenseCount = 0
expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "not_found", found: false, complete: true })
approvalSN = `${sn}-UNRELATED`
expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "unknown", found: null, complete: false, reason: "approval_link_not_found" })
})
test("limits are explicit and partial scans cannot return not_found", async () => {
const result = await cli("expenses", "--sn", sn, "--max-scan", "1")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", complete: false, reason: "scan_limit", matchedCount: 1 })
})
test("bad selector combinations, unknown verbs and invalid scan budgets fail before requests", async () => {
for (const argv of [
["expenses", "delete"], ["expenses", "SN-as-unsupported-positional"], ["expenses", "list", sn], ["data", "expenses", "list", sn],
["expenses", "--sn", sn, "--search", "text"], ["expenses", "--sn", sn, "--record-id", "record-1"],
["expenses", "--sn", sn, "--offset", "0"], ["expenses", "--max-scan", "1"]
]) expect((await cli(...argv)).exitCode).toBe(2)
expect((await cli("expenses", "--sn", sn, "--max-scan", "0")).exitCode).toBe(13)
expect(requests).toHaveLength(0)
})
test("expense lookup failures retain JSON uncertainty and correct exit codes", async () => {
for (const status of [400, 403]) {
failureStatus = status
const result = await cli("expenses", "--sn", sn)
expect(result.exitCode).toBe(status === 403 ? 11 : 1)
expect(JSON.parse(result.stdout)).toMatchObject({ status: "unknown", complete: false, found: null })
expect(result.stderr).toContain("incomplete")
}
})
test("oversized reports retain existing output protection and can be exported as JSON", async () => {
description = "x".repeat(210000)
expect((await cli("expenses", "--sn", sn)).exitCode).toBe(12)
const path = join(dir, "report.json")
const result = await cli("expenses", "--sn", sn, "--output-file", path)
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path })
expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject({ status: "found", complete: true, matchedCount: 2 })
})
})
+33
View File
@@ -0,0 +1,33 @@
import type { CorpConfig } from "../../core/config/types.js"
import type { createSealClient } from "../../core/http/factory.js"
import { usageError } from "../../core/errors.js"
import { ExpenseLookupError } from "../../domains/seal/expenses/lookup.js"
import { runCapabilityResult } from "../helpers.js"
import { numberOption, stringOption } from "../parser.js"
import { outputOptions, printJson } from "../printer.js"
import type { ParsedArgs } from "../types.js"
export async function handleExpensesCommand(action: string | undefined, client: Awaited<ReturnType<typeof createSealClient>>, corp: CorpConfig, args: ParsedArgs) {
const prefixLength = args.command[0]?.toLowerCase() === "data" ? 2 : 1
if ((action && action !== "list") || args.command.length > prefixLength + Number(Boolean(action))) {
throw usageError("Usage: seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>]")
}
const sn = stringOption(args.options.sn)
const recordId = stringOption(args.options["record-id"]) ?? stringOption(args.options.recordId)
const search = stringOption(args.options.search) ?? stringOption(args.options.query)
const offset = numberOption(args.options.offset)
const maxScan = numberOption(args.options["max-scan"]) ?? numberOption(args.options.maxScan)
if (sn !== undefined && (recordId !== undefined || search !== undefined || offset !== undefined)) throw usageError("--sn cannot be combined with --search, --record-id, or --offset")
if (maxScan !== undefined && sn === undefined) throw usageError("--max-scan requires --sn")
try {
const result = await runCapabilityResult("sealExpensesList", client, corp, {
sn, recordId, search, offset, maxScan, limit: numberOption(args.options.limit),
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"])
})
printJson(result, outputOptions(args.options))
} catch (error) {
if (error instanceof ExpenseLookupError) printJson(error.report, outputOptions(args.options))
throw error
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { CliError } from "../errors.js";
import { CliError } from "../../core/errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
+65
View File
@@ -0,0 +1,65 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { traceInvoice } from "../../domains/seal/approval-runs/invoices.js";
import { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleInvoicesCommand(
action: string | undefined,
maybeTarget: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
// Check if subcommand is "trace" or a positional invoice number
const isTrace = action === "trace";
const invoiceNumberToTrace = isTrace
? (maybeTarget ?? stringOption(args.options.number) ?? stringOption(args.options.invoice))
: (action && /^\d{10,25}$/.test(action) ? action : undefined);
if (invoiceNumberToTrace) {
const report = await traceInvoice(client, invoiceNumberToTrace, corp.id);
if (!report) {
printJson(
{
found: false,
invoiceNumber: invoiceNumberToTrace,
message: `未在进项发票库中找到发票号码为 ${invoiceNumberToTrace} 的记录。`
},
outputOptions(args.options)
);
return;
}
if (report.conflictStatus === "MULTIPLE_DOCUMENTS_ATTACHED") {
console.error(
`\n💡 [CLI 辅助溯源指引](注:此指引由 seal-use CLI 基于进项发票库关联数据自动提炼,非后端大模型生成):\n` +
`• 发票 ${report.invoice.invoiceNumber}(${report.invoice.sellerName},¥${report.invoice.totalAmount})在 ${report.associatedDocuments.length} 笔单据中均有挂载记录:\n` +
report.associatedDocuments.map((d) => ` - 单号: ${d.sourceDocumentSN}(已占 ¥${d.usedAmount ?? 0})👉 诊断命令: ${d.nextDiagnose}`).join("\n") +
`\n`
);
}
printJson(report, outputOptions(args.options));
return;
}
// Otherwise, default to list / search
const searchQuery =
stringOption(args.options.search) ??
stringOption(args.options.query) ??
(action && action !== "list" ? action : undefined);
const params = {
offset: numberOption(args.options.offset),
limit: numberOption(args.options.limit),
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
search: searchQuery,
full: booleanOption(args.options.full) === true
};
await runCapability("sealInvoicesList", client, corp, params, outputOptions(args.options));
}
+2 -4
View File
@@ -1,4 +1,4 @@
import { validationError } from "../../core/errors.js";
import { validationError, usageError } from "../../core/errors.js";
import { booleanOption, numberOption, splitOption, stringOption } from "../parser.js";
import { runLangfuseCapability } from "../helpers.js";
import { outputOptions } from "../printer.js";
@@ -151,9 +151,7 @@ export async function handleLangfuseCommand(
return;
}
throw new Error(
`Unknown langfuse command: ${action ?? ""}. Run 'seal-use help' for available commands.`
);
throw usageError(`Unknown langfuse command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
function parseMetadataOption(raw: string | undefined): Record<string, string | number | boolean> | undefined {
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -20,5 +21,5 @@ export async function handleLlmCommand(
return;
}
throw new Error(`Unknown llm command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown llm command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -20,5 +21,5 @@ export async function handlePermissionsCommand(
return;
}
throw new Error(`Unknown permissions command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown permissions command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+6 -5
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
@@ -27,7 +28,7 @@ export async function handlePreferenceCommand(
? JSON.parse(readFileSync(rawInput, "utf8"))
: jsonObject(args.json);
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use preference decision update --json '{\"explicitApprove\":\"...\"}'");
throw usageError("Usage: seal-use preference decision update --json '{\"explicitApprove\":\"...\"}'");
}
await runCapability("sealPreferenceDecisionUpdate", client, corp, {
...payload,
@@ -44,7 +45,7 @@ export async function handlePreferenceCommand(
stringOption(args.options.level) ??
maybeTarget;
if (defaultLevel !== "medium" && defaultLevel !== "high") {
throw new Error("Usage: seal-use preference thinking-depth set --default <medium|high>");
throw usageError("Usage: seal-use preference thinking-depth set --default <medium|high>");
}
await runCapability("sealPreferenceThinkingDepthSet", client, corp, {
defaultLevel,
@@ -65,7 +66,7 @@ export async function handlePreferenceCommand(
? JSON.parse(readFileSync(rawInput, "utf8"))
: jsonObject(args.json);
if (!payload || !payload.id || !payload.name) {
throw new Error("Usage: seal-use preference thinking-depth policies upsert --json '{\"id\":\"...\",\"name\":\"...\",\"level\":\"high\"}'");
throw usageError("Usage: seal-use preference thinking-depth policies upsert --json '{\"id\":\"...\",\"name\":\"...\",\"level\":\"high\"}'");
}
await runCapability("sealPreferenceThinkingDepthPoliciesUpsert", client, corp, {
...payload,
@@ -77,7 +78,7 @@ export async function handlePreferenceCommand(
if (thirdAction === "remove" || thirdAction === "delete") {
const policyId = maybeTarget ?? stringOption(args.options.id) ?? stringOption(args.options.policyId);
if (!policyId) {
throw new Error("Usage: seal-use preference thinking-depth policies remove <policyId>");
throw usageError("Usage: seal-use preference thinking-depth policies remove <policyId>");
}
await runCapability("sealPreferenceThinkingDepthPoliciesRemove", client, corp, {
policyId,
@@ -88,5 +89,5 @@ export async function handlePreferenceCommand(
}
}
throw new Error(`Unknown preference action: ${action ?? ""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`);
throw usageError(`Unknown preference action: ${action ?? ""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`);
}
+5 -2
View File
@@ -78,10 +78,12 @@ export async function handleLocalReportCommand(action: string | undefined, args:
}
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (!out) throw usageError(`Usage: seal-use report ${action} <报告文件.md> --out <${action === "export" ? "目标文件夹" : "产物路径词干"}>`);
const glossary = args.options["no-glossary"] ? false : booleanOption(args.options.glossary) ?? true;
if (action === "export") {
const result = await exportReportPackage(file, {
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite),
glossary
});
printJson(result, outputOptions(args.options));
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成完整导出包。请按 validation.issues 修正后重试。", 1);
@@ -89,7 +91,8 @@ export async function handleLocalReportCommand(action: string | undefined, args:
}
const result = await renderReportFile(file, {
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite),
glossary
});
printJson(result, outputOptions(args.options));
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
+11 -11
View File
@@ -9,7 +9,7 @@ import {
OFFICIAL_LINTERS_DIR
} from "../../domains/seal/linter/index.js";
import { runCapability, runCapabilityResult } from "../helpers.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, validationError, usageError } from "../../core/errors.js";
import {
booleanOption,
jsonObject,
@@ -58,7 +58,7 @@ export async function handleRulesCommand(
// lint, linters, and map actions can run without a network client
const clientless = action === "lint" || action === "linters" || action === "linter-list" || action === "map";
if (!client && !clientless) {
throw new Error(`rules ${action ?? ""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);
throw validationError(`rules ${action ?? ""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);
}
if (action === "count") {
@@ -145,7 +145,7 @@ export async function handleRulesCommand(
if (action === "version") {
const version = resolveVersionOption(args, maybeName);
if (!version) throw new Error("Usage: seal-use rules version <versionNumber|latest>");
if (!version) throw usageError("Usage: seal-use rules version <versionNumber|latest>");
await runCapability(
"sealApprovalRuleVersionGet",
client!,
@@ -160,7 +160,7 @@ export async function handleRulesCommand(
const from = stringOption(args.options.from) ?? maybeName;
const to = stringOption(args.options.to) ?? args.command[3];
if (!from || !to) {
throw new Error("Usage: seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--full]");
throw usageError("Usage: seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--full]");
}
const singleSelector = args.command[4];
await runCapability(
@@ -190,7 +190,7 @@ export async function handleRulesCommand(
stringOption(args.options.ruleId) ??
stringOption(args.options["rule-id"]);
if (!target) {
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]");
throw usageError("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleGet",
@@ -214,7 +214,7 @@ export async function handleRulesCommand(
stringOption(args.options.strictness) ??
(typeof payload.strictness === "string" ? payload.strictness : "MUST_FOLLOW");
if (!description || !scope) {
throw new Error("Usage: seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]");
throw usageError("Usage: seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleCreate",
@@ -240,7 +240,7 @@ export async function handleRulesCommand(
stringOption(args.options.strictness) ??
(typeof payload.strictness === "string" ? payload.strictness : undefined);
if (!ruleId || (description === undefined && scope === undefined && strictness === undefined)) {
throw new Error("Usage: seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]");
throw usageError("Usage: seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleUpdate",
@@ -259,7 +259,7 @@ export async function handleRulesCommand(
stringOption(args.options["rule-id"]) ??
stringOption(args.options.code);
if (!ruleId) {
throw new Error("Usage: seal-use rules delete <code> --yes [--corp <corpId>]");
throw usageError("Usage: seal-use rules delete <code> --yes [--corp <corpId>]");
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
@@ -287,7 +287,7 @@ export async function handleRulesCommand(
stringOption(args.options.name) ??
(typeof payload.versionName === "string" ? payload.versionName : undefined);
if (!versionName) {
throw new Error("Usage: seal-use rules publish <versionName> [--corp <corpId>]");
throw usageError("Usage: seal-use rules publish <versionName> [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleVersionPublish",
@@ -301,7 +301,7 @@ export async function handleRulesCommand(
if (action === "search") {
const keyword = maybeName ?? stringOption(args.options.query);
if (!keyword) throw new Error("Usage: seal-use rules search <keyword> [--version <number|latest>] [--maxResults 20] [--corp <corpId>]");
if (!keyword) throw usageError("Usage: seal-use rules search <keyword> [--version <number|latest>] [--maxResults 20] [--corp <corpId>]");
await runCapability(
"sealApprovalSearch",
client!,
@@ -465,5 +465,5 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, get, search, create, update, delete, publish, versions, version, diff, lint, linters, pull, push, clear, map. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown rules command: ${action ?? ""}. Available: count, list, get, search, create, update, delete, publish, versions, version, diff, lint, linters, pull, push, clear, map. Run 'seal-use help' for available commands.`);
}
+9 -9
View File
@@ -1,7 +1,7 @@
import { existsSync, readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, usageError, validationError } from "../../core/errors.js";
import { runCapability, runCapabilityResult } from "../helpers.js";
import {
booleanOption,
@@ -22,7 +22,7 @@ export async function handleSimulationCommand(
) {
if (action === "batch-records" || action === "records") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation batch-records <batchId>");
if (!batchId) throw usageError("Usage: seal-use simulation batch-records <batchId>");
await runCapability(
"sealSimulationBatchRecordsGet",
client,
@@ -142,7 +142,7 @@ export async function handleSimulationCommand(
if (action === "wait") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");
if (!batchId) throw usageError("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");
await runCapability(
"sealSimulationBatchWait",
client,
@@ -159,7 +159,7 @@ export async function handleSimulationCommand(
if (action === "status") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation status <batchId>");
if (!batchId) throw usageError("Usage: seal-use simulation status <batchId>");
await runCapability(
"sealSimulationBatchStatus",
client,
@@ -172,7 +172,7 @@ export async function handleSimulationCommand(
if (action === "clean" || action === "delete") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation clean <batchId> --yes");
if (!batchId) throw usageError("Usage: seal-use simulation clean <batchId> --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
@@ -220,7 +220,7 @@ export async function handleSimulationCommand(
if (action === "get") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation get <batchId>");
if (!batchId) throw usageError("Usage: seal-use simulation get <batchId>");
await runCapability("sealSimulationBatchGet", client, corp, { batchId }, outputOptions(args.options));
return;
}
@@ -237,11 +237,11 @@ export async function handleSimulationCommand(
if (action === "package-upload") {
const filePath = maybeName ?? stringOption(args.options.file);
if (!filePath) throw new Error("Usage: seal-use simulation package-upload <材料包.zip>");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
if (!filePath) throw usageError("Usage: seal-use simulation package-upload <材料包.zip>");
if (!existsSync(filePath)) throw validationError(`File not found: ${filePath}`);
await runCapability("sealSimulationMaterialPackageUpload", client, corp, { filePath }, outputOptions(args.options));
return;
}
throw new Error(`Unknown simulation command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown simulation command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
@@ -66,5 +67,5 @@ export function handleSkillCommand(action: string | undefined, maybeName: string
return;
}
throw new Error(`Unknown skill command: ${action}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown skill command: ${action}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/enterprise/source.js";
import { printJson } from "../printer.js";
@@ -8,5 +9,5 @@ export async function handleSourceCommand(action: string | undefined, corp: Corp
return;
}
throw new Error(`Unknown source command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown source command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { CliError } from "../errors.js";
import { CliError } from "../../core/errors.js";
import { selectCorp } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson } from "../printer.js";
+8 -8
View File
@@ -1,6 +1,6 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, usageError } from "../../core/errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, parseDelegationExpireHours, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
@@ -16,7 +16,7 @@ export async function handleUsersCommand(
if (action === "create") {
const name = stringOption(args.options.name) ?? maybeName;
const phone = stringOption(args.options.phone);
if (!name || !phone) throw new Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");
if (!name || !phone) throw usageError("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");
const deptId = stringOption(args.options.dept) ?? stringOption(args.options.departmentId);
const departmentIds = deptId ? [deptId] : undefined;
await runCapability("sealUserCreate", client, corp, { name, phone, departmentIds }, outputOptions(args.options));
@@ -25,7 +25,7 @@ export async function handleUsersCommand(
if (action === "reset-password") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users reset-password <userId> --yes");
if (!userId) throw usageError("Usage: seal-use users reset-password <userId> --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
@@ -45,14 +45,14 @@ export async function handleUsersCommand(
if (action === "get") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users get <userId>");
if (!userId) throw usageError("Usage: seal-use users get <userId>");
await runCapability("sealUserGet", client, corp, { userId }, outputOptions(args.options));
return;
}
if (action === "delete") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users delete <userId> --yes");
if (!userId) throw usageError("Usage: seal-use users delete <userId> --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
@@ -66,14 +66,14 @@ export async function handleUsersCommand(
if (action === "activate") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users activate <userId>");
if (!userId) throw usageError("Usage: seal-use users activate <userId>");
await runCapability("sealUserActivate", client, corp, { userId }, outputOptions(args.options));
return;
}
if (action === "delegation" || action === "impersonate") {
const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone);
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>] [--expire <duration>]");
if (!userIdOrPhone) throw usageError("Usage: seal-use users delegation <userIdOrPhone> [--note <note>] [--expire <duration>]");
const note = stringOption(args.options.note);
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
@@ -87,5 +87,5 @@ export async function handleUsersCommand(
return;
}
throw new Error(`Unknown users command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown users command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+11 -13
View File
@@ -32,13 +32,13 @@ import {
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
import { CliError, confirmationRequired, usageError, validationError } from "../errors.js";
import { CliError, confirmationRequired, usageError, validationError } from "../../core/errors.js";
export async function handleWebhookResourcePackPreview(
filePath: string,
filePolicy?: MaterialPackFilePolicyPatch
) {
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
if (!existsSync(filePath)) throw validationError(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
printJson(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy));
}
@@ -110,9 +110,7 @@ export async function handleWebhookCommand(
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
if (!recordId && !recordIds && !sn && !sns && limit === undefined) {
throw new Error(
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]"
);
throw usageError("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");
}
const sourceCorpId =
@@ -317,14 +315,14 @@ export async function handleWebhookCommand(
? stringOption(args.options.file) ?? stringOption(args.options.input)
: args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
if (!filePath) throw usageError("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (!existsSync(filePath)) throw validationError(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
if (operation === "preview") {
printJson(await previewMaterialPack(input.fileBuffer, input.fileName), outputOptions(args.options));
return;
}
if (operation !== "push") throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (operation !== "push") throw usageError("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
let integration: WebhookIntegration;
@@ -370,7 +368,7 @@ export async function handleWebhookCommand(
if (action === "get" || action === "find") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-use webhook get <idOrName> [--show-secret]");
if (!selector) throw usageError("Usage: seal-use webhook get <idOrName> [--show-secret]");
await runCapability(
"sealWebhookGet",
client,
@@ -392,7 +390,7 @@ export async function handleWebhookCommand(
stringOption(args.options.outgoingResultWebhook) ??
stringOption(args.options["outgoing-result-webhook"]);
if (!name || !outgoingResultWebhook) {
throw new Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
throw usageError("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
}
const autoApprovalRate = webhookRateOption(args.options);
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
@@ -417,7 +415,7 @@ export async function handleWebhookCommand(
if (action === "update") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-use webhook update <idOrName> [options]");
if (!selector) throw usageError("Usage: seal-use webhook update <idOrName> [options]");
const secret = stringOption(args.options.secret);
const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]);
if (secret !== undefined && rotateSecret) {
@@ -468,7 +466,7 @@ export async function handleWebhookCommand(
if (action === "delete") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
if (!selector) throw new Error("Usage: seal-use webhook delete <idOrName> [--yes|--dry-run]");
if (!selector) throw usageError("Usage: seal-use webhook delete <idOrName> [--yes|--dry-run]");
if (booleanOption(args.options.yes) !== true && !dryRun) {
throw confirmationRequired(
"Refusing to delete Webhook integration without --yes",
@@ -489,5 +487,5 @@ export async function handleWebhookCommand(
return;
}
throw new Error(`Unknown webhook command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown webhook command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+77
View File
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { parseArgs } from "./parser.js";
import { KNOWN_AREAS, UPDATE_ALIASES } from "./runner.js";
/**
@@ -67,3 +68,79 @@ describe("documentation references live commands", () => {
expect(stale).toEqual({});
});
});
/**
* Usage-level closure for the generated cli.md block.
*
* `verify:cli-md` proves the block byte-matches what HELP_REGISTRY renders,
* and parser.test.ts proves registry usage flags are registered — but nothing
* fed the rendered lines back through the real parser. That is exactly the
* hole the 2026-10-17 review found in the opposite direction: 22 parser tests
* green while nine documented flags were rejected at runtime. Rendering is
* code too, so the doc reader's copy-paste path gets its own parse.
*/
const CLI_DOC_PATH = join(REPO_ROOT, "skills/seal-use/references/cli.md");
function generatedUsageLines(markdown: string): string[] {
const block = markdown.match(
/<!-- BEGIN GENERATED CLI COMMANDS -->([\s\S]*?)<!-- END GENERATED CLI COMMANDS -->/
);
if (!block?.[1]) throw new Error(`generated command block missing in ${CLI_DOC_PATH}`);
return block[1].split("\n").filter((line) => line.startsWith("seal-use "));
}
/**
* Turn a documented usage line into argv the way a reader would type it:
* keep one alternative of each `a|b` group, unwrap `[...]` optionality, and
* replace `<value hints>` with a neutral placeholder token. Single quotes are
* respected so `--json '{...}'` payloads survive as one argument.
*/
function usageToArgv(line: string): string[] {
// `--json '{...}'` is a fill-in placeholder in the docs, not literal JSON;
// substitute a valid empty object so the parser sees a well-formed payload.
const hinted = line.slice("seal-use ".length)
.replace(/<[^<>]*>/g, " __HINT__ ")
.replace(/'\{\.\.\.\}'/g, "'{}'");
const unbracketed = hinted.replace(/[[\]]/g, " ");
const tokens: string[] = [];
let current = "";
let quoted = false;
for (const char of unbracketed) {
if (char === "'") {
quoted = !quoted;
continue;
}
if (!quoted && /\s/.test(char)) {
if (current) tokens.push(current);
current = "";
continue;
}
current += char;
}
if (current) tokens.push(current);
return tokens.map((token) => token.split("|")[0]!).filter((token) => token.length > 0);
}
describe("generated cli.md usage lines parse", () => {
test("every documented usage line is accepted by parseArgs", () => {
const lines = generatedUsageLines(readFileSync(CLI_DOC_PATH, "utf8"));
// Format guard: if the markers or the `seal-use ` line convention change,
// the extraction silently yields nothing and this suite would pass while
// checking zero lines.
expect(lines.length).toBeGreaterThan(100);
const rejected: Record<string, string> = {};
for (const line of lines) {
try {
parseArgs(usageToArgv(line));
} catch (error) {
rejected[line] = error instanceof Error ? error.message : String(error);
}
}
expect(rejected).toEqual({});
});
});
-12
View File
@@ -1,12 +0,0 @@
// Re-export from core — this file is the legacy entry point.
// Domain-layer code should import from "../core/errors.js" directly.
export {
type CliExitCode,
CliError,
PayloadTooLargeError,
usageError,
validationError,
safetyBlocked,
confirmationRequired,
classifyCliError
} from "../core/errors.js";
+12 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { extractHelpRequest, renderHelp } from "./help.js";
import { extractHelpRequest, HELP_REGISTRY, renderHelp } from "./help.js";
import { KNOWN_AREAS, runCli } from "./runner.js";
describe("extractHelpRequest", () => {
@@ -210,6 +210,17 @@ describe("help coverage", () => {
}
});
test("every help registry area is dispatchable", () => {
// The forward direction is checked above. The reverse catches a registry
// area that renders help but no longer reaches a handler table — the
// "documented for two releases after the dispatcher dropped it" failure
// mode this suite exists to prevent, applied to `seal-use help` itself.
const dead = HELP_REGISTRY.map((entry) => entry.area)
.filter((area) => !KNOWN_AREAS.has(area));
expect(dead).toEqual([]);
});
test("stop shortcut and server alias resolve to help", () => {
expect(renderHelp(["server"])).toContain("seal-use mcp");
});
+55 -20
View File
@@ -1,5 +1,6 @@
import { normalizeCliArea } from "./area-aliases.js";
import type { ParsedArgs } from "./types.js";
import { usageError } from "./errors.js";
import { usageError } from "../core/errors.js";
export interface CommandOptionHelp {
flag: string;
@@ -706,6 +707,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--format <format>", description: "all (default), html, png, or pdf; PNG/PDF also produce HTML" },
{ flag: "--width <px>", description: "PNG viewport width, default 1200 (320–5000)" },
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
{ flag: "--no-glossary", description: "Omit the trailing terms definition and calculation standards appendix" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files after successful rendering" }
],
description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Validation and HTML use the bundled runtime; PNG/PDF need Chrome/Chromium. No Python or Pillow required. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency."
@@ -719,6 +721,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--format <format>", description: "all (default), html, or pdf" },
{ flag: "--width <px>", description: "PNG viewport width, default 1200" },
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
{ flag: "--no-glossary", description: "Omit the trailing terms definition and calculation standards appendix" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" }
],
description: "Bundles the report into a clean single directory: includes the Markdown with its .md.assets/ companion folder, plus self-contained HTML and print-ready PDF."
@@ -1166,13 +1169,49 @@ export const HELP_REGISTRY: AreaHelp[] = [
commands: [
{
name: "expenses",
summary: "Search raw expense items",
usage: ["seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"]
summary: "List expenses, or verify expense-store membership by exact document number with --sn",
usage: ["seal-use data expenses [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]"]
},
{
name: "invoices",
summary: "Search raw invoice records",
usage: ["seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"]
summary: "Search raw invoice records (also available as 'seal-use invoices')",
usage: ["seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]"]
}
]
},
{
area: "invoices",
title: "进项发票查询与溯源",
description: "查看已审批单据中出现的进项发票,支持单据关联穿透、跨单据重复占用排查与扁平化业务视图。",
commands: [
{
name: "list",
summary: "分页查询进项发票(默认输出扁平化业务字段,对齐控制台表格)",
usage: [
"seal-use invoices [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]"
]
},
{
name: "trace",
summary: "穿透溯源指定发票,排查在哪些报销单据中被使用及是否存在跨单重复占用",
usage: [
"seal-use invoices trace <invoiceNumber> [--corp <corpId>]",
"seal-use invoices <invoiceNumber> [--corp <corpId>]"
]
}
]
},
{
area: "expenses",
title: "费用明细查询",
description: "查询历史费用明细;--sn 按单号关联审批记录并核验费用库存在性,区分找到、关联范围内未找到和无法确定。",
commands: [
{
name: "list",
summary: "普通查询分页返回原始记录;--sn 自动翻页核验,--limit 为页大小,--max-scan 默认为 5000",
usage: [
"seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]"
]
}
]
},
@@ -1308,13 +1347,13 @@ export const HELP_REGISTRY: AreaHelp[] = [
commands: [
{
name: "list",
summary: "List approval knowledge documents",
usage: ["seal-use documents list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]"]
summary: "List knowledge documents; --summary omits body, --fields selects explicit fields",
usage: ["seal-use documents list [--summary] [--fields <id,title,purpose,updatedAt>] [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]"]
},
{
name: "get",
summary: "Get approval knowledge document details by ID",
usage: ["seal-use documents get <documentId> [--corp <corpId>]"]
summary: "Get document JSON, or export exact UTF-8 body plus baseline with --out; --output-file saves JSON",
usage: ["seal-use documents get <documentId> [--out <path>] [--content-format raw] [--overwrite] [--corp <corpId>]"]
},
{
name: "search",
@@ -1323,22 +1362,22 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "create",
summary: "Create a new approval knowledge document",
summary: "Preview with --dry-run; --yes/--confirm creates and verifies a knowledge document",
usage: [
"seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
"seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]"
]
},
{
name: "update",
summary: "Update an approval knowledge document by ID",
summary: "Preview changes; confirmed updates check export baseline, snapshot and verify readback",
usage: [
"seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
"seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]"
]
},
{
name: "delete",
summary: "Delete an approval knowledge document by ID",
usage: ["seal-use documents delete <documentId> --yes [--corp <corpId>]"]
summary: "Preview deletion; --yes/--confirm snapshots the document before deleting it",
usage: ["seal-use documents delete <documentId> [--dry-run|--yes|--confirm] [--corp <corpId>]"]
}
]
},
@@ -1637,14 +1676,10 @@ export function renderHelp(target: string[] = []): string {
}
function normalizeArea(area: string): string {
const lower = area.toLowerCase();
if (lower === "corp") return "corps";
if (lower === "webhooks") return "webhook";
if (lower === "preferences") return "preference";
const lower = normalizeCliArea(area);
if (lower === "changelog") return "update";
if (lower === "serve") return "http";
if (lower === "mcp-config") return "mcp";
if (lower === "server") return "mcp";
return lower;
}
+22 -16
View File
@@ -1,6 +1,5 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { HELP_REGISTRY } from "./help.js";
import {
booleanOption,
BOOLEAN_FLAGS,
@@ -203,23 +202,30 @@ describe("option helpers", () => {
describe("flag registry cross-check", () => {
test("every flag documented in help.ts is registered", () => {
const help = readFileSync(join(import.meta.dirname, "help.ts"), "utf-8");
const documented = new Set(
[...help.matchAll(/flag: "--([a-z][a-z0-9-]*)"/g)].map((match) => match[1]!)
);
for (const flag of documented) {
expect(KNOWN_FLAGS.has(flag)).toBe(true);
}
const documented = new Set(HELP_REGISTRY.flatMap((area) => area.commands.flatMap((command) =>
(command.options ?? []).flatMap((option) => [...option.flag.matchAll(/--([a-zA-Z][a-zA-Z0-9-]*)/g)].map((match) => match[1]!))
)));
expect([...documented].filter((flag) => !KNOWN_FLAGS.has(flag))).toEqual([]);
expect(documented.size).toBeGreaterThanOrEqual(20);
});
test("every flag shown in a help usage line is registered", () => {
const help = readFileSync(join(import.meta.dirname, "help.ts"), "utf-8");
const usageFlags = new Set(
[...help.matchAll(/ --([a-z][a-z0-9-]*)/g)].map((match) => match[1]!)
);
const missing = [...usageFlags].filter((flag) => !KNOWN_FLAGS.has(flag));
expect(missing).toEqual([]);
test("every flag shown in a help usage line is registered, including bracket and pipe forms", () => {
const usageFlags = new Set(HELP_REGISTRY.flatMap((area) => area.commands.flatMap((command) =>
command.usage.flatMap((usage) => [...usage.matchAll(/--([a-zA-Z][a-zA-Z0-9-]*)/g)].map((match) => match[1]!))
)));
expect([...usageFlags].filter((flag) => !KNOWN_FLAGS.has(flag))).toEqual([]);
});
test("formerly rejected public flags retain their boolean and value arity", () => {
const parsed = parseArgs(["report", "data", "--templates", "one,two", "--latest", "record"]);
expect(parsed.options).toEqual({ templates: "one,two", latest: true });
expect(parsed.command).toEqual(["report", "data", "record"]);
expect(parseArgs(["config", "test-dir", "--clear"]).options.clear).toBe(true);
expect(parseArgs(["webhook", "get", "id", "--show-secret"]).options["show-secret"]).toBe(true);
expect(parseArgs(["webhook", "update", "id", "--min-file-size", "10", "--clear-max-file-size"]).options)
.toEqual({ "min-file-size": "10", "clear-max-file-size": true });
expect(() => parseArgs(["report", "data", "--templates"])).toThrow("requires a value");
expect(() => parseArgs(["corps", "list", "--limitt=5"])).toThrow("Unknown option: --limitt");
});
test("boolean and value sets partition the registry apart from the ambiguous three", () => {
+20 -64
View File
@@ -2,7 +2,7 @@ import type { WebhookMode } from "../domains/seal/types.js";
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
import type { ParsedArgs } from "./types.js";
import { type DurationToken, EXPIRE_UNITS, expireSeconds, tokenizeDuration } from "../core/duration.js";
import { usageError } from "./errors.js";
import { usageError, validationError } from "../core/errors.js";
/**
* Flag metadata for argv parsing, derived from how the code reads each flag:
@@ -23,13 +23,14 @@ import { usageError } from "./errors.js";
// Read with booleanOption(...) / Boolean(...) / presence check.
export const BOOLEAN_FLAGS = new Set([
"allow-empty", "allowEmpty", "clear", "clear-max-file-size", "clearMaxFileSize", "latest", "show-secret", "showSecret",
"V", "add", "all", "allow-unreviewed", "allowUnreviewed", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
"hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
@@ -40,10 +41,13 @@ export const BOOLEAN_FLAGS = new Set([
// Read with stringOption/numberOption/splitOption(...).
export const VALUE_FLAGS = new Set([
"allowed-extensions", "allowedExtensions", "extensions", "auto-approval-rate", "autoApprovalRate", "approval-rate",
"min-file-size", "min-file-size-bytes", "minFileSize", "minFileSizeBytes",
"max-file-size", "max-file-size-bytes", "maxFileSize", "maxFileSizeBytes", "templates",
"access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
"channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
"content-format", "contentFormat", "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
@@ -55,7 +59,7 @@ export const VALUE_FLAGS = new Set([
"json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit",
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"max-runs", "max-scan", "maxScan",
"month",
"n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out",
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
@@ -86,60 +90,9 @@ export const VALUE_FLAGS = new Set([
// Registered flags. Unknown flags are rejected.
export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key",
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
"bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
"code", "comment", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
"default", "departmentId", "dept", "desc", "description", "description-file",
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expires-in", "expiresIn", "f", "fail-on-flips",
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list",
"flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
"host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
"json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait", "node-id", "nodeId",
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
"phone", "plain", "policy", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
"query", "quiet", "r", "recode", "record-id", "record-ids",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum", "repo",
"report-id",
"request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"reviewed-by", "reviewedBy",
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId",
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
"simulationBatchId", "since", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration",
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
"staffId", "staffName", "staffPhone", "start", "start-date", "start-time",
"startDate", "startTime", "state", "status", "strict", "strictness",
"summary", "tag", "tag-id", "tagId", "tags", "target",
"template",
"target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId",
"test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title",
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
"until", "url", "userId", "v", "version", "version-name",
"verdict",
"versionName", "wait", "webhook", "width", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
"workspace", "yes"
...BOOLEAN_FLAGS,
...VALUE_FLAGS,
"f", "h", "version"
]);
export function parseArgs(argv: string[]): ParsedArgs {
@@ -170,6 +123,9 @@ export function parseArgs(argv: string[]): ParsedArgs {
const key = raw.slice(0, eqIdx);
const val = raw.slice(eqIdx + 1);
if (key === "python") throw usageError("--python 已移除:报告工具不再依赖 Python。");
if (!KNOWN_FLAGS.has(key)) {
throw usageError(`Unknown option: --${key}.${suggestFlag(key)}`);
}
options[key] = val;
continue;
}
@@ -283,7 +239,7 @@ export function booleanOption(value: string | boolean | undefined): boolean | un
export function requiredString(input: Record<string, unknown>, key: string): string {
const value = optionalString(input, key);
if (!value) throw new Error(`Missing required JSON field: ${key}`);
if (!value) throw usageError(`Missing required JSON field: ${key}`);
return value;
}
@@ -292,7 +248,7 @@ export function requiredStringAlias(input: Record<string, unknown>, keys: string
const value = optionalString(input, key);
if (value) return value;
}
throw new Error(`Missing required JSON field: ${keys.join(" or ")}`);
throw usageError(`Missing required JSON field: ${keys.join(" or ")}`);
}
export function optionalString(input: Record<string, unknown>, key: string): string | undefined {
@@ -318,7 +274,7 @@ export function parseStateMode(value: string): boolean {
const normalized = value.trim().toLowerCase();
if (["stateful", "state", "有状态"].includes(normalized)) return true;
if (["stateless", "无状态"].includes(normalized)) return false;
throw new Error("Invalid config mode. Use stateful or stateless.");
throw validationError("Invalid config mode. Use stateful or stateless.");
}
export function parseRuleVersionSelector(value: string) {
@@ -388,7 +344,7 @@ export function parseWebhookMode(value?: string): WebhookMode | undefined {
};
const mode = aliases[normalized];
if (!mode) {
throw new Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");
throw validationError("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");
}
return mode;
}
@@ -398,7 +354,7 @@ export function webhookRateOption(options: Record<string, string | boolean>): nu
options.autoApprovalRate ?? options["auto-approval-rate"] ?? options["approval-rate"]
);
if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 100)) {
throw new Error("Webhook auto approval rate must be an integer between 0 and 100");
throw validationError("Webhook auto approval rate must be an integer between 0 and 100");
}
return value;
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { writeFileSync } from "node:fs";
import { booleanOption, stringOption } from "./parser.js";
import { PayloadTooLargeError } from "./errors.js";
import { PayloadTooLargeError } from "../core/errors.js";
import { redactSensitiveText } from "../core/redact.js";
import type { OutputOptions } from "./types.js";
+9 -1
View File
@@ -27,7 +27,8 @@ describe("CLI read-only classification", () => {
"auth test",
"auth doctor",
"auth seal-link list",
"doctor auth"
"doctor auth",
"expenses "
]);
test("every allow-listed command exists in the help registry", () => {
@@ -55,7 +56,13 @@ describe("CLI read-only classification", () => {
["corp", "list"],
["corp", "get", "corp-a"],
["documents", "list", "--corp", "corp-a"],
["expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
["expenses", "list", "--record-id", "run-1", "--corp", "corp-a"],
["expense", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
["data", "expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
["documents", "get", "doc-1", "--corp", "corp-a"],
["documents", "get", "doc-1", "--out", "./body.txt", "--corp", "corp-a"],
["documents", "list", "--summary", "--fields", "id,title", "--corp", "corp-a"],
["documents", "search", "差旅", "--corp", "corp-a"],
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
["approval-runs", "list", "--corp", "corp-a"],
@@ -89,6 +96,7 @@ describe("CLI read-only classification", () => {
["rules", "clear"],
["documents", "create"],
["documents", "update", "doc-1"],
["documents", "update", "doc-1", "--content-file", "body.txt", "--dry-run", "--yes"],
["documents", "delete", "doc-1"],
["simulation", "create", "--mode", "hosecloud"],
["deploy", "hosecloud", "sync", "sign-key"],
+3 -8
View File
@@ -1,3 +1,4 @@
import { normalizeCliArea } from "./area-aliases.js";
import { parseArgs } from "./parser.js";
/**
@@ -12,13 +13,6 @@ import { parseArgs } from "./parser.js";
* Prefix matching is boundary-safe by construction: `list-evil` does not match `list`.
*/
/** Area aliases the CLI dispatches under an alternative name; mirrors the pairs in runner.ts. */
const AREA_ALIASES: Record<string, string> = {
corp: "corps",
webhooks: "webhook",
preferences: "preference"
};
/**
* Commands that only read tenant state, produce a local file, or inspect local configuration.
* Deliberately excluded even though they look harmless: anything that writes local config
@@ -76,6 +70,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
users: ["search", "get"],
contacts: ["departments", "children", "users", "sync-time"],
data: ["expenses", "invoices"],
expenses: ["", "list"],
llm: ["config", "providers"],
permissions: ["available", "configs"],
billing: ["status", "plans", "features"],
@@ -122,7 +117,7 @@ export function describeCliCommand(argv: string[]): { area: string; actionTokens
const { command } = parseArgs(argv);
const area = (command[0] ?? "").toLowerCase();
return {
area: AREA_ALIASES[area] ?? area,
area: normalizeCliArea(area),
actionTokens: command.slice(1).map((token) => token.toLowerCase())
};
}
+121 -227
View File
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
import type { CorpConfig } from "../core/config/types.js";
import { VERSION_INFO } from "../version.js";
import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js";
import { classifyCliError } from "./errors.js";
import { classifyCliError, usageError } from "../core/errors.js";
import {
booleanOption,
materialPackFilePolicyOptions,
@@ -22,52 +22,72 @@ import {
printJson,
redactSensitiveText
} from "./printer.js";
import type { CliResult, CliRunOptions, CliRuntime } from "./types.js";
import type { KyInstance } from "ky";
import type { ParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
export const UPDATE_ALIASES = new Set([
"update",
"upgrade",
"up",
"self-update",
"selfupdate"
]);
export { UPDATE_ALIASES } from "./area-aliases.js";
import { AREA_ALIASES, normalizeCliArea, UPDATE_ALIASES } from "./area-aliases.js";
type LocalCommand = (args: ParsedArgs, runtime: CliRuntime) => Promise<void>;
type CorpCommand = (args: ParsedArgs, corp: CorpConfig) => Promise<void>;
type ClientCommand = (args: ParsedArgs, corp: CorpConfig, client: KyInstance) => Promise<void>;
// Handler tables also define the known command surface. Imports stay lazy so
// local discovery never loads the tenant, Excel, or zip implementation graphs.
const LOCAL_COMMANDS: Record<string, LocalCommand> = {
"mcp-config": async () => (await import("./commands/mcp.js")).printMcpConfig(),
skill: async (args) => (await import("./commands/skill.js")).handleSkillCommand(args.command[1], args.command[2], args),
mcp: async (args) => (await import("./commands/mcp.js")).handleMcpCommand(args.command[1]),
probe: async (args) => (await import("./commands/probe.js")).handleProbeCommand(args.command[1], args.command[2], args),
doctor: async (args) => (await import("./commands/doctor.js")).handleDoctorCommand(args.command[1], args.command[2], args),
langfuse: async (args) => (await import("./commands/langfuse.js")).handleLangfuseCommand(args.command[1], args.command[2], args),
test: async (args) => (await import("./commands/test.js")).handleTestCommand(args.command[1], args.command[2], args),
config: async (args) => (await import("./commands/config.js")).handleConfigCommand(args.command[1], args.command[2], args),
update: dispatchUpdate,
changelog: dispatchUpdate,
corps: async (args) => {
const action = args.command[1];
if (action === "regression" || action === "test-regression") {
await (await import("./commands/test.js")).handleTestCommand("regression", args.command[2], args);
return;
}
await (await import("./commands/corps.js")).handleCorpsCommand(action, args.command[2], args);
}
};
const CORP_COMMANDS: Record<string, CorpCommand> = {
source: async (args, corp) => (await import("./commands/source.js")).handleSourceCommand(args.command[1], corp),
auth: async (args, corp) => (await import("./commands/auth.js")).handleAuthCommand(args.command[1], corp, args)
};
const CLIENT_COMMANDS: Record<string, ClientCommand> = {
"users": async (args, corp, client) => (await import("./commands/users.js")).handleUsersCommand(args.command[1], args.command[2], client, corp, args),
"contacts": async (args, corp, client) => (await import("./commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args),
"data": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand(args.command[1], client, corp, args),
"invoices": async (args, corp, client) => (await import("./commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args),
"expenses": async (args, corp, client) => (await import("./commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args),
"llm": async (args, corp, client) => (await import("./commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args),
"permissions": async (args, corp, client) => (await import("./commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args),
"billing": async (args, corp, client) => (await import("./commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args),
"webhook": async (args, corp, client) => (await import("./commands/webhook.js")).handleWebhookCommand(args.command[1], args.command[2], client, corp, args),
"context": async (args, corp, client) => (await import("./commands/context.js")).handleContextCommand(client, corp, args),
"documents": async (args, corp, client) => (await import("./commands/documents.js")).handleDocumentsCommand(args.command[1], args.command[2], client, corp, args),
"rules": async (args, corp, client) => (await import("./commands/rules.js")).handleRulesCommand(args.command[1], args.command[2], client, corp, args),
"approval-runs": async (args, corp, client) => (await import("./commands/approval-runs.js")).handleApprovalRunsCommand(args.command[1], args.command[2], client, corp, args),
"analytics": async (args, corp, client) => (await import("./commands/analytics.js")).handleAnalyticsCommand(args.command[1], args.command[2], client, corp, args),
"report": async (args, corp, client) => (await import("./commands/report.js")).handleReportCommand(args.command[1], client, corp, args),
"simulation": async (args, corp, client) => (await import("./commands/simulation.js")).handleSimulationCommand(args.command[1], args.command[2], client, corp, args),
"deploy": async (args, corp, client) => (await import("./commands/deploy.js")).handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args),
"hose-ebot": async (args, corp, client) => (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args),
"preference": async (args, corp, client) => (await import("./commands/preference.js")).handlePreferenceCommand(args.command[1], args.command[2], args.command[3], args.command[4], client, corp, args),
};
export const KNOWN_AREAS = new Set([
"config",
"update",
"corps",
"corp",
"source",
"hose-ebot",
"auth",
"users",
"contacts",
"data",
"llm",
"permissions",
"billing",
"webhook",
"webhooks",
"context",
"documents",
"rules",
"approval-runs",
"analytics",
"report",
"simulation",
"deploy",
"preference",
"preferences",
"mcp",
"server",
"mcp-config",
"skill",
"probe",
"doctor",
"langfuse",
"changelog",
"test"
...Object.keys(LOCAL_COMMANDS),
...Object.keys(CORP_COMMANDS),
...Object.keys(CLIENT_COMMANDS),
...Object.keys(AREA_ALIASES)
]);
export type { CliResult, CliRunOptions } from "./types.js";
@@ -140,12 +160,53 @@ async function runCliOnce(argv: string[], options: CliRunOptions): Promise<CliRe
}
}
async function dispatchUpdate(args: ParsedArgs, runtime: CliRuntime): Promise<void> {
const [rawArea, action] = args.command;
const isUpdate = rawArea ? UPDATE_ALIASES.has(rawArea.toLowerCase()) : false;
const area = rawArea?.toLowerCase();
if (isUpdate && rawArea !== "update") {
console.error(`⚠️ Notice: '${rawArea}' is an alias for 'seal-use update'. Please use 'seal-use update' instead.`);
}
const lowerAction = action?.toLowerCase();
const isChangelog =
area === "changelog" ||
lowerAction === "changelog" ||
lowerAction === "log" ||
lowerAction === "history" ||
booleanOption(args.options.changelog) === true;
const isCheck =
lowerAction === "check" ||
booleanOption(args.options.check) === true ||
booleanOption(args.options["check-only"]) === true;
const isBgSave =
booleanOption(args.options["bg-save"]) === true ||
booleanOption(args.options["silent-save"]) === true;
const targetVersion =
stringOption(args.options.version) ??
stringOption(args.options.tag) ??
(!isChangelog && !isCheck && !isBgSave && action && !action.startsWith("-") ? action : undefined);
await (await import("./commands/update.js")).handleUpdateCommand(runtime, {
checkOnly: isCheck || isBgSave,
changelogOnly: isChangelog,
limit: numberOption(args.options.limit),
force: booleanOption(args.options.force),
targetVersion,
repo: stringOption(args.options.repo),
bgSave: isBgSave
});
return;
}
async function dispatch(argv: string[], runtime: CliRuntime) {
const args = parseArgs(argv);
const [rawArea, action, maybeName] = args.command;
const lowerArea = rawArea?.toLowerCase();
const isUpdate = lowerArea ? UPDATE_ALIASES.has(lowerArea) : false;
const area = isUpdate ? "update" : lowerArea;
const area = lowerArea ? normalizeCliArea(lowerArea) : undefined;
if (
area === "version" ||
@@ -186,7 +247,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
}
if (!area || !KNOWN_AREAS.has(area)) {
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
if (
@@ -195,36 +256,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
maybeName === "preview"
) {
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");
if (!filePath) throw usageError("Usage: seal-use webhook resource-pack preview <资源包.zip>");
await (await import("./commands/webhook.js")).handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options));
return;
}
if (area === "mcp-config") {
(await import("./commands/mcp.js")).printMcpConfig();
return;
}
if (area === "skill") {
(await import("./commands/skill.js")).handleSkillCommand(action, maybeName, args);
return;
}
if (area === "mcp" || area === "server") {
await (await import("./commands/mcp.js")).handleMcpCommand(action);
return;
}
if (area === "probe") {
await (await import("./commands/probe.js")).handleProbeCommand(action, maybeName, args);
return;
}
if (area === "doctor") {
await (await import("./commands/doctor.js")).handleDoctorCommand(action, maybeName, args);
return;
}
if (
area === "report" &&
(action === "validate" ||
@@ -239,69 +275,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
// Langfuse trace inspection needs no tenant: it authenticates with the
// compile-time injected read-only key pair, so it dispatches before corp
// selection (like probe/doctor) and never touches a Seal client.
if (area === "langfuse") {
await (await import("./commands/langfuse.js")).handleLangfuseCommand(action, maybeName, args);
return;
}
if (area === "test") {
await (await import("./commands/test.js")).handleTestCommand(action, maybeName, args);
return;
}
if (area === "config") {
(await import("./commands/config.js")).handleConfigCommand(action, maybeName, args);
return;
}
if (isUpdate || area === "changelog") {
if (isUpdate && rawArea !== "update") {
console.error(`⚠️ Notice: '${rawArea}' is an alias for 'seal-use update'. Please use 'seal-use update' instead.`);
}
const lowerAction = action?.toLowerCase();
const isChangelog =
area === "changelog" ||
lowerAction === "changelog" ||
lowerAction === "log" ||
lowerAction === "history" ||
booleanOption(args.options.changelog) === true;
const isCheck =
lowerAction === "check" ||
booleanOption(args.options.check) === true ||
booleanOption(args.options["check-only"]) === true;
const isBgSave =
booleanOption(args.options["bg-save"]) === true ||
booleanOption(args.options["silent-save"]) === true;
const targetVersion =
stringOption(args.options.version) ??
stringOption(args.options.tag) ??
(!isChangelog && !isCheck && !isBgSave && action && !action.startsWith("-") ? action : undefined);
await (await import("./commands/update.js")).handleUpdateCommand(runtime, {
checkOnly: isCheck || isBgSave,
changelogOnly: isChangelog,
limit: numberOption(args.options.limit),
force: booleanOption(args.options.force),
targetVersion,
repo: stringOption(args.options.repo),
bgSave: isBgSave
});
return;
}
if (area === "corps" || area === "corp") {
if (action === "regression" || action === "test-regression") {
await (await import("./commands/test.js")).handleTestCommand("regression", maybeName, args);
return;
}
await (await import("./commands/corps.js")).handleCorpsCommand(action, maybeName, args);
// These handlers intentionally run before enterprise selection, including
// Langfuse's compile-time credentials and purely local discovery commands.
const localCommand = LOCAL_COMMANDS[area];
if (localCommand) {
await localCommand(args, runtime);
return;
}
@@ -339,102 +317,18 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
if (area === "source") {
await (await import("./commands/source.js")).handleSourceCommand(action, corp);
const corpCommand = CORP_COMMANDS[area];
if (corpCommand) {
await corpCommand(args, corp);
return;
}
if (area === "auth") {
await (await import("./commands/auth.js")).handleAuthCommand(action, corp, args);
const clientCommand = CLIENT_COMMANDS[area];
if (clientCommand) {
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
await clientCommand(args, corp, client);
return;
}
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
if (area === "users") {
await (await import("./commands/users.js")).handleUsersCommand(action, maybeName, client, corp, args);
return;
}
if (area === "contacts") {
await (await import("./commands/contacts.js")).handleContactsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "data") {
await (await import("./commands/data.js")).handleDataCommand(action, client, corp, args);
return;
}
if (area === "llm") {
await (await import("./commands/llm.js")).handleLlmCommand(action, client, corp, args);
return;
}
if (area === "permissions") {
await (await import("./commands/permissions.js")).handlePermissionsCommand(action, client, corp, args);
return;
}
if (area === "billing") {
await (await import("./commands/billing.js")).handleBillingCommand(action, client, corp, args);
return;
}
if (area === "webhook" || area === "webhooks") {
await (await import("./commands/webhook.js")).handleWebhookCommand(action, maybeName, client, corp, args);
return;
}
if (area === "context") {
await (await import("./commands/context.js")).handleContextCommand(client, corp, args);
return;
}
if (area === "documents") {
await (await import("./commands/documents.js")).handleDocumentsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "rules") {
await (await import("./commands/rules.js")).handleRulesCommand(action, maybeName, client, corp, args);
return;
}
if (area === "approval-runs") {
await (await import("./commands/approval-runs.js")).handleApprovalRunsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "analytics") {
await (await import("./commands/analytics.js")).handleAnalyticsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "report") {
await (await import("./commands/report.js")).handleReportCommand(action, client, corp, args);
return;
}
if (area === "simulation") {
await (await import("./commands/simulation.js")).handleSimulationCommand(action, maybeName, client, corp, args);
return;
}
if (area === "deploy") {
await (await import("./commands/deploy.js")).handleDeployCommand(action, maybeName, args.command[3], client, corp, args);
return;
}
if (area === "hose-ebot") {
await (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(action, maybeName, client, corp, args);
return;
}
if (area === "preference" || area === "preferences") {
await (await import("./commands/preference.js")).handlePreferenceCommand(action, maybeName, args.command[3], args.command[4], client, corp, args);
return;
}
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
+3 -2
View File
@@ -3,6 +3,7 @@
* reach the CLI intact. Lives in its own module because both the MCP server and the HTTP routes
* need it; importing it from the server entry would make the CLI graph circular.
*/
import { usageError } from "../core/errors.js";
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
@@ -53,8 +54,8 @@ export function tokenizeCommand(command: string): string[] {
tokenStarted = true;
}
if (escaped) throw new Error("Invalid command: trailing escape");
if (quote) throw new Error("Invalid command: unterminated quote");
if (escaped) throw usageError("Invalid command: trailing escape");
if (quote) throw usageError("Invalid command: unterminated quote");
if (tokenStarted) tokens.push(token);
return tokens;
}
+18 -4
View File
@@ -5,6 +5,7 @@ import { clearSealSession, getSealSession, setSealSession } from "./token-store.
import { SealEnterpriseConfig, SealSession } from "./types.js";
const memoryCache = new Map<string, SealSession>();
const pendingSessions = new Map<string, Promise<SealSession>>();
function isExpired(session: SealSession, refreshTtl: number): boolean {
return Date.now() >= session.expiresAt - refreshTtl * 1000;
@@ -32,10 +33,15 @@ export async function getSealSessionForCorp(corp: CorpConfig): Promise<SealSessi
return stored;
}
const next = await refreshSealSession(corp);
memoryCache.set(corp.id, next);
setSealSession(corp.id, next);
return next;
const pending = pendingSessions.get(corp.id);
if (pending) return pending;
const request = refreshSealSession(corp).then((next) => {
memoryCache.set(corp.id, next);
setSealSession(corp.id, next);
return next;
}).finally(() => pendingSessions.delete(corp.id));
pendingSessions.set(corp.id, request);
return request;
}
export async function resolveSealEnterpriseConfig(
@@ -48,3 +54,11 @@ export function clearSealToken(corpId: string): void {
memoryCache.delete(corpId);
clearSealSession(corpId);
}
/** Reuse a concurrent refresh rather than invalidating a newer session on a late 401. */
export async function recoverSealSessionForCorp(corp: CorpConfig, rejectedToken: string): Promise<SealSession> {
const current = await getSealSessionForCorp(corp);
if (current.token !== rejectedToken) return current;
clearSealToken(corp.id);
return getSealSessionForCorp(corp);
}
+12 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { chmodSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
@@ -80,6 +80,17 @@ describe("token-store", () => {
expect(getSealSession("corp-1")).toBeUndefined();
});
test.skipIf(process.platform === "win32")("tightens an existing token store without losing other corp caches", () => {
const path = makeTempStore();
const cache = { openapi: { token: "fixture-token", expiresAt: Date.now() + 3600000 } };
setHoseAuthCache("other", cache);
chmodSync(path, 0o644);
setHoseAuthCache("target", cache);
expect(statSync(path).mode & 0o777).toBe(0o600);
expect(getHoseAuthCache("other")).toEqual(cache);
expect(getHoseAuthCache("target")).toEqual(cache);
});
test("sets, retrieves, and clears hose auth cache", () => {
makeTempStore();
const hoseCache = {
+4 -4
View File
@@ -1,5 +1,6 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { writeSecureFile } from "../secure-file.js";
import { SEAL_CONFIG_DIR } from "../paths.js";
import {
CorpTokenCache,
@@ -41,8 +42,7 @@ function readStore(): TokenStore {
function writeStore(store: TokenStore): void {
const path = resolveWriteStorePath();
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
writeFileSync(path, JSON.stringify(store, null, 2), { mode: 0o600 });
writeSecureFile(path, JSON.stringify(store, null, 2));
}
export function getSealSession(corpId: string): SealSession | undefined {
+65 -1
View File
@@ -1,7 +1,8 @@
import { afterEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { saveCorpConfig } from "./repository.js";
import {
findCorpConfigFile,
getLastCorpConfigLoadIssues,
@@ -118,6 +119,69 @@ describe("loadCorpConfigs", () => {
expect(corps.map((corp) => corp.id).sort()).toEqual(["test-corp", "user-corp"].sort());
});
test("updates the same user override that reads select", () => {
delete process.env.SEAL_USE_ENTERPRISES_DIR;
delete process.env.SEAL_HOME_ENTERPRISES_DIR;
const testDir = makeTempDir();
const userDir = makeTempDir();
process.env.SEAL_USE_USER_ENTERPRISES_DIR = userDir;
process.env.SEAL_USE_CONFIG_FILE = join(makeTempDir(), "config.json");
saveGlobalConfig({ testEnterprisesDir: testDir });
const testPath = join(testDir, "corp.json");
const userPath = join(userDir, "corp.json");
writeCorpConfig(testPath, "duplicate", "Test copy");
writeCorpConfig(userPath, "duplicate", "User copy");
expect(loadCorpConfigs()[0]?.name).toBe("User copy");
expect(findCorpConfigFile("duplicate")).toBe(userPath);
updateCorpConfig("duplicate", { name: "Renamed" });
expect(loadCorpConfigs()[0]?.name).toBe("Renamed");
expect(JSON.parse(readFileSync(testPath, "utf8")).name).toBe("Test copy");
});
test("same-directory duplicates and invalid shadows use the selected valid file", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
const first = join(dir, "a.json");
const second = join(dir, "b.json");
writeCorpConfig(first, "duplicate", "First");
writeCorpConfig(second, "duplicate", "Second");
writeFileSync(join(dir, "z-invalid.json"), JSON.stringify({ id: "duplicate" }));
// Filesystem enumeration order differs across platforms; writes must follow reads.
const selectedName = loadCorpConfigs()[0]?.name;
expect(["First", "Second"]).toContain(selectedName ?? "");
const selected = selectedName === "First" ? first : second;
const untouched = selectedName === "First" ? second : first;
const untouchedName = JSON.parse(readFileSync(untouched, "utf8")).name;
expect(findCorpConfigFile("duplicate")).toBe(selected);
updateCorpConfig("duplicate", { name: "Updated" });
expect(loadCorpConfigs()[0]?.name).toBe("Updated");
expect(JSON.parse(readFileSync(selected, "utf8")).name).toBe("Updated");
expect(JSON.parse(readFileSync(untouched, "utf8")).name).toBe(untouchedName);
});
test.skipIf(process.platform === "win32")("credential updates and overwrites tighten existing files", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
const path = join(dir, "alpha.json");
writeCorpConfig(path, "alpha", "Alpha");
chmodSync(path, 0o644);
const config = updateCorpConfig("alpha", { name: "Updated" });
expect(statSync(path).mode & 0o777).toBe(0o600);
chmodSync(path, 0o644);
saveCorpConfig(config, { overwrite: true });
expect(statSync(path).mode & 0o777).toBe(0o600);
const globalPath = join(dir, "global-config");
process.env.SEAL_USE_CONFIG_FILE = globalPath;
writeFileSync(globalPath, "{}");
chmodSync(globalPath, 0o644);
saveGlobalConfig({ stateful: false });
expect(statSync(globalPath).mode & 0o777).toBe(0o600);
const migratedDir = makeTempDir();
syncLegacyEnterprisesDir(migratedDir, dir);
expect(statSync(join(migratedDir, "alpha.json")).mode & 0o777).toBe(0o600);
});
test("defaults global config to stateless", () => {
process.env.SEAL_USE_CONFIG_FILE = join(makeTempDir(), "config.json");
+15 -28
View File
@@ -1,8 +1,10 @@
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.js";
import { writeSecureFile } from "../secure-file.js";
const CONFIG_ENV = "SEAL_USE_ENTERPRISES_DIR";
const LEGACY_CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR";
const USER_DIR_ENV = "SEAL_USE_USER_ENTERPRISES_DIR";
@@ -39,13 +41,13 @@ export function syncLegacyEnterprisesDir(
const primaryPath = join(primaryDir, file);
if (!existsSync(primaryPath)) {
copyFileSync(legacyPath, primaryPath);
writeSecureFile(primaryPath, readFileSync(legacyPath));
copied.push(file);
} else {
const legacyMtime = statSync(legacyPath).mtimeMs;
const primaryMtime = statSync(primaryPath).mtimeMs;
if (legacyMtime > primaryMtime) {
copyFileSync(legacyPath, primaryPath);
writeSecureFile(primaryPath, readFileSync(legacyPath));
copied.push(file);
}
}
@@ -103,8 +105,12 @@ export function getLastCorpConfigLoadIssues(): CorpConfigLoadIssue[] {
}
export function loadCorpConfigs(): CorpConfig[] {
return loadCorpConfigEntries().map((entry) => entry.config);
}
function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
const dirs = resolveEnterprisesDirs();
const byId = new Map<string, CorpConfig>();
const byId = new Map<string, { config: CorpConfig; path: string }>();
const issues: CorpConfigLoadIssue[] = [];
for (const dir of dirs) {
@@ -120,7 +126,7 @@ export function loadCorpConfigs(): CorpConfig[] {
issues.push({ dir, file, reason: error instanceof Error ? error.message : String(error) });
continue;
}
byId.set(corp.id, corp);
byId.set(corp.id, { config: corp, path: fullPath });
}
}
@@ -241,31 +247,12 @@ export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig {
const normalized = GlobalConfigSchema.parse(config);
const configured = (process.env[GLOBAL_CONFIG_ENV] ?? process.env[LEGACY_GLOBAL_CONFIG_ENV])?.trim();
const file = configured || PRIMARY_GLOBAL_CONFIG_FILE;
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
writeFileSync(file, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
writeSecureFile(file, `${JSON.stringify(normalized, null, 2)}\n`);
return normalized;
}
export function findCorpConfigFile(corpId: string): string | undefined {
const dirs = resolveEnterprisesDirs();
for (const dir of dirs) {
if (!existsSync(dir)) continue;
for (const file of readdirSync(dir)
.filter((item) => item.endsWith(".json"))
.filter((item) => !item.startsWith("example."))) {
const fullPath = join(dir, file);
try {
const content = readFileSync(fullPath, "utf-8");
const parsed = JSON.parse(content);
if (parsed && typeof parsed === "object" && parsed.id === corpId) {
return fullPath;
}
} catch {
// ignore malformed files
}
}
}
return undefined;
return loadCorpConfigEntries().find((entry) => entry.config.id === corpId)?.path;
}
export function updateCorpConfig(corpId: string, patch: Partial<CorpConfig>): CorpConfig {
@@ -281,6 +268,6 @@ export function updateCorpConfig(corpId: string, patch: Partial<CorpConfig>): Co
}
}
const validated = CorpConfigSchema.parse(merged);
writeFileSync(filePath, `${JSON.stringify(validated, null, 2)}\n`, "utf-8");
writeSecureFile(filePath, `${JSON.stringify(validated, null, 2)}\n`);
return validated;
}
+6 -9
View File
@@ -1,3 +1,4 @@
import { validationError } from "../errors.js";
import { CorpConfig, GlobalConfig } from "./types.js";
export function resolveCorpConfig(
@@ -18,23 +19,19 @@ export function resolveCorpConfig(
if (caseInsensitive) return caseInsensitive;
const byName = corps.find((item) => item.name.toLowerCase() === selectedCorpId.toLowerCase());
if (byName) return byName;
throw new Error(`No enterprise config found for ${selectedCorpId}`);
throw validationError(`No enterprise config found for ${selectedCorpId}`);
}
if (!options.stateful) {
throw new Error(
"Stateless mode is enabled. Every enterprise command requires --corp <corpId>. " +
"Use `seal-use config mode stateful` to enable a default enterprise."
);
throw validationError("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. " +
"Use `seal-use config mode stateful` to enable a default enterprise.");
}
const firstCorp = corps[0];
if (firstCorp) return firstCorp;
throw new Error(
"No enterprise config found. Add a non-example JSON file under one of: " +
(candidates.length ? candidates.join(", ") : "the configured enterprise directories")
);
throw validationError("No enterprise config found. Add a non-example JSON file under one of: " +
(candidates.length ? candidates.join(", ") : "the configured enterprise directories"));
}
export type CorpContextOptions = Pick<GlobalConfig, "stateful" | "defaultCorpId">;
+3 -3
View File
@@ -1,4 +1,5 @@
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { existsSync } from "node:fs";
import { writeSecureFile } from "../secure-file.js";
import { join } from "node:path";
import { resolveWritableEnterprisesDir } from "./loader.js";
import { CorpConfigSchema, type CorpConfig } from "./types.js";
@@ -20,13 +21,12 @@ export function saveCorpConfig(
): SavedCorpConfig {
const config = CorpConfigSchema.parse(input);
const enterprisesDir = resolveWritableEnterprisesDir();
mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 });
const path = join(enterprisesDir, `${safeCorpFileName(config.id)}.json`);
if (existsSync(path) && options.overwrite !== true) {
throw new Error(`Enterprise config already exists: ${path}. Pass "overwrite": true to replace it.`);
}
writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
writeSecureFile(path, `${JSON.stringify(config, null, 2)}\n`);
return { config, path };
}
-8
View File
@@ -1,8 +0,0 @@
// Re-export from domain layer — this file is the legacy entry point.
// tenant-diagnose inherently depends on domains/seal/api, so it now lives there.
export {
type TenantHealthCheck,
type TenantDoctorDiagnosis,
diagnoseTenantContract,
formatTenantDoctorDashboard
} from "../../domains/seal/doctor/tenant-diagnose.js";
+35 -29
View File
@@ -2,28 +2,30 @@
import file0 from "../../skills/seal-use/SKILL.md" with { type: "text" };
import file1 from "../../skills/seal-use/agents/openai.yaml" with { type: "text" };
const file2 = "iVBORw0KGgoAAAANSUhEUgAADVgAAAdwCAYAAACUWcTmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWKADAAQAAAABAAAHcAAAAAD4n9OGAABAAElEQVR4AeydB4AdVfX/z246pNAD0hK6dOki0rsU+dMJJVIFRYoUFUFAQUCqgHSkxx8gTRCpFkB6CU06SQi9BEhC+u7/fu7b83J3dt7bt33f5nuStzNz5947M583c+fOvPO9p6Y+mMlEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4kUDsHHrMOWQREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQigd7jxo8TChEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYIwkogtUc+bXroEVABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABCBQUx9MKERABERABERABERABERABERABERABERABERABERABERABERABESgqwiMHz/eBgwY0FWb13ZFQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQATmcAKKYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwn0npMPXscuAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj2RwP8+n26vfjbd3vpyho2fPN0+mjLTJs+qs/qaOhvYp8YWGtDLFh/U25YZ3NdWnr+/rTDvgJ6IQcckAhURqKkPVlFOZRIBERABERABERABERABERABERABERABERABERABERABERABERCBDiAwfvx4GzBAP9p2AFpVKQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiMIcR+GhSnT347lT713tT7eOpM4OYqj5+LEzNEFdZ+MyKU5Zr4jLp9fat/r1ss28NtM0WG2KLzN1nDiOnw53TCUhgNaefATp+ERABERABERABERABERABERABERABERABERABERABERABEehiAhJYdfEXoM2LgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhUPYFJ08z+7+Updsc7U8OxFARURKqyIKAqCKnqbVYQUdU2CK7iOiuIr4oirLBcgxArfHZZcrDttcwCNnefXlXPRgcgApUQkMCqEkrKIwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0GEEJLDqMLSqWAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4g8MR7M+2Cp6fY5JmFSFQhRlUQStUVBVUsF0VUCKiSSFZEsKqLkawa5yH/oN5mP195qK0/dPAcQFGHOKcTkMBqTj8DdPwiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0MUEJLDq4i+gCzY/ZcqUuNUBAwZ0wda1SREQAREQAREQAREQAREQAREQAREQAREQAREQARHoHAKd8S501AszbNT/psXIUwWhVDi2IK6qj5GriGRVEE4RlSoVWlUayYry+w2fx0Yst1DnQNNWRKCLCAQ9oUwEREAEREAEREAEREAE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iRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAgWeAIVWBf4tQAAkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQALRO3fvlNTUVJIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggQJLgBGtCuyfnidOAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRgEYhIV7MOuCUBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiCBgkiAEa0K4l+d50wCJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJOBGgEIrNxw8IAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKIgEKLQqiH91njMJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkIAbAQqt3HDwgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIoCASoNCqIP7Vec4kQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAJuBCi0csPBAxIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggYJIgEKrgvhX5zmTAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAm4EaDQyg0HD0iABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABAoiAQqtCuJfnedMAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiTgRoBCKzccPCABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiiIBCi0Koh/dZ4zCZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZCAGwEKrdxw8IAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKAgEqDQqiD+1XnOJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACbgQotHLDwQMSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIIGCSIBCq4L4V+c5kwAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJuBGg0MoNBw9IgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgAQKIgEKrQriX53nTAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIk4EaAQis3HDwgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIoiASiC+JJ85xJgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgATyAIFlSyVtyWJJjY+XlK3bJP3QYTOoiLPPkugqlSWqVi2JbNRYpEHDPDBYDoEESCC/E4hIV8vvJ8nzIwESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESyDsE0idPlOQxYyRl89agBhVVrYrEtmwpEbffGVR5FiIBEiCBrBCg0Cor1FiHBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEggdAL/rpfkzz+T5BWrQq+rNWIurSMxHTqKXFAjS/VZiQRIgAT8EaDQyh8d5pEACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACYSHwG+/SUKPHmFpq0ivXiJNm4alLTZCAiRAAhYBCq0sEl626ZoWoS9raxVJ04RIzUhJE3n151T5UyMVFi8eIeVLRkqFs0XOP0fFsaVEyhQXKVdMpEScVZNbEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiiABMIosrLoUWxlkeC2IBJIS0uT5JQUSUlJldTUVMExXunp6eYFJhEREeYVGRkpeEVFRUl0dJTEREeb44LILdA5U2hlIwQBVVKqyMaDIv/sF7mvlkiUCqogtLLMEl6h7IY9adJmRKqcStfUmEiRaBVgxeobT7exMSq+ihUpqSKrS0uL3HmRSM3zND3KIdKy2uOWBEiABEiABEiABEiABEiABHwSWL5cZOkySY2Pl9SNWyRt525JO3zcFI88q5hEVignUedXlahaevPSsIFI/fo+m2IGCZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZw2Av+ul4S2zwTdfXSNCyTyLI2Copa8fIWkJyf7rFtk6FcaKaWGz3xmkEB+IpCcnCJJSUmSpJ8JiKuyYxBdxcbESGxsrMTEqBCGZggULine truncated
const file5 = "iVBORw0KGgoAAAANSUhEUgAADVoAAAdyCAYAAADdZLXQAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWqADAAQAAAABAAAHcgAAAABWYxAhAABAAElEQVR4AeydB6BO5R/Hf3fbWshOS4QiWipR2ktRirZSoWgPMhLtPciISv0rITOzZJRkhMyQlVW2u8f/933e93nved/7zrtc935/9TrnPPt87jvOec7v+/yistSERgIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIlmEB0CT53njoJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJGAIUWvGNQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkUOIJUGhV4t8CBEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJBC7bfs2ycjIIAkSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKLEEGNGqxP7peeIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAKWQFSWmj3glgRIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARKIgFGtCqJf3WeMwmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQgBcBCq28cPCABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEigJBKg0Kok/tV5ziRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAl4EKLTywsEDEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiCBkkiAQquS+FfnOZMACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACXgRoNDKCwcPSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESiIBCq1K4l+d50wCJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJOBFgEIrLxw8IAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKIkEKLQqiX91njMJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkIAXAQqtvHDwgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIoCQSoNCqJP7Vec4kQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAJeBCi08sLBAxIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggZJIgEKrkvhX5zmTAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAl4EaDQygsHD0iABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEoiAQqtSuJfnedMAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiTgRYBCKy8cPCABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiiJBCi0Kol/dZ4zCZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZCAFwEKrbxw8IAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKAkEogtiSfNcyYBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEigCBBYvkszfF0rGypWSvmmzZO3dZwYVdewxElu7lsTUry/RTZuJNDmnCAyWQyABEijuBKKy1Ir7SfL8SIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIA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s+576ScaFBQ4edLEy7xDzTJ9xrRtO3ZpNDV0ev+hqE4ZCgwJ7j5x/JjD0Ufo9KYtf44bO9rf3/9y7xTA5VepVru5ujo52XyVr6qqUqurAgMD2nOvrmZ5efn01cT+PEVFxZWVlZ6envZLLine truncated
const file7 = "iVBORw0KGgoAAAANSUhEUgAADVwAAAdwCAIAAAAS0PPLAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANXKADAAQAAAABAAAHcAAAAACLl/RJAABAAElEQVR4AeydB2AURRuGJ52E3jsIUqR35KcjKooFFBCkSRORXhRF6QioICJNehNQpPfee5fea+i9pSd3/7s3ybC527tcCnAJ73oes998Mzv77GZ3b/adb9yuXr8aEREhuJAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACSRmAh4eHu6Juf1sOwmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQwDMCbmaz+dkaUyRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAomWACMFJtpDx4aTAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQQHQCFAVG58E1EiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEki0BCgKTLSHjg0nARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggegEKAqMzoNrJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJJBoCVAUmGgPHRtOAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAtEJUBQYnQfXSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESCDREqAoMNEeOjacBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABKIToCgwOg+ukQAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkECiJUBRYKI9dGw4CZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACUQnQFFgdB5cIwESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIIFES4CiwER76NhwEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEohOgKLA6Dy4RgIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAKJlgBFgYn20LHhJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJBCdAEWB0XlwjQRIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgAQSLQGKAhPtoWPDSYAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESCA6AYoCo/PgGgmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAkkWgIUBSbaQ8eGkwAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkEB0AhQFRufBNRIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARJItAQ8E23L2XASIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAGXJ3BgfwQ+x4+H+18x33+E5rqlS+2ZM5dHkSIeZcoKfLiQAAkkKAE3s9mcoBWyMhIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIQ5hXLQufPC794xQELjzy5fOo3cPvgIwc+zCIBEogVAYoCY4WLziRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAjEROHcmdPSosMPHYvKLzPcqUdS7U2eRr4CT/nQjARJwQICiQAdwmEUCJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJBBLAps3B/TvH8symntylKpePQ4FWYQESEBPIGmKAjEjspsQ8lvurcks3N1EuEn0nGfafcWcIpVbtlTu2dKJ19OKfJlE1hQiS0qRykdPhmkSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIIFYEoirIlBuhrrAWOKmezQCJpMpLBxLhLZgJSLCbFng5GZZ3D08PNy1L09PDy9PT3d392jlk8pK0hEFQvYXGiHO3xPH74p6hYWHmyYKlIsUCMLh7A1T02kRIWY34eXu5incfNw9PIW3l0iFj48omVl8VFAUzCi8PTQFIRcSIAESIAESIAESIAG7BA4dFPsPhZ88HnH+sunaTdPDJ/B0T5PSPXsWj9dzexYqIsqWEqVK2y3ODBIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggSRJ4NyZgDZtHe+ZR4F8HmnSwifs4H/m8DBb5+STJ3IeYVsstDggEBYWHhoaGhIaFhER7sDNNgviQB9vL29vby8vT9vcxGtJ9KJAs1lEmIX/I7HXX6w/J04/FN3+J+q8oan6VKRAqQ4MCzePWG2avT8iwgOKQDd3L3eTu3D3douABNByAD3chY+7KJZevJ1XlM8lcqcWsLhRHZh4z262nARIgARIgARIIMEJXLlsWrw0ZNEKk//1GOt2z5nN55Pa7nXriFy5Y3SmAwmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQQBI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pjUFocDmDt4QXRaKhf9paS4kQAIkQAIkQAIk8EoRiOjdJ+iPyQm1y6gKFSZUbayHBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEjAdQhExKThc/P1c/+0vtbgs6cdhwmUOxVjha6z72zJiyEQEhJ6//6D0NDQF7M5bAibw0ZfzOYSdiueCVvdc60N4r2nIWLmbjHzoAgKF5Z5gLUNQuPn5qYFCCyXXXh7aFpAeOLzbDGLrScjAkPMmFdYm0UaQkCIIS0qQMj+NPkgggsi4SY0s6YYFB6Wb4QShCXCLC4/EL9uEbefiC8qiOQ+z+SGzzbBFAmQAAmQAAmQAAkkOQIQ8AX/syRhdwsVJhPC46dBCVstayMBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEni5BCKOH3fcAJ9PPxGpU8EndOpUx54yFxV6OONHn1eDQGBgECb2ffH7+vjJk+QRfn5+vi9+0/HZYqKJFAit3qNA0W+5mLZfPA3VJvNFnD93RPWzxPNDqD/IG4vnEB6WHZIxAjW1n4VNSIT5 Line truncated
import file2 from "../../skills/seal-use/assets/hose-curl-copy-as-curl.png" with { type: "file" };
import file3 from "../../skills/seal-use/assets/hose-curl-network-fetch-xhr.png" with { type: "file" };
import file4 from "../../skills/seal-use/assets/hose-curl-open-page-check.png" with { type: "file" };
import file5 from "../../skills/seal-use/assets/hose-open-platform-app-center.png" with { type: "file" };
import file6 from "../../skills/seal-use/assets/hose-open-platform-credentials.png" with { type: "file" };
import file7 from "../../skills/seal-use/assets/hose-open-platform-product-config.png" with { type: "file" };
import file8 from "../../skills/seal-use/references/approval-attachment-trace.md" with { type: "text" };
import file9 from "../../skills/seal-use/references/approval-bad-cases.md" with { type: "text" };
import file10 from "../../skills/seal-use/references/approval-run-lightweight.md" with { type: "text" };
import file11 from "../../skills/seal-use/references/cli.md" with { type: "text" };
import file12 from "../../skills/seal-use/references/customer-feedback-rule-remediation.md" with { type: "text" };
import file13 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" };
import file14 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" };
import file15 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
import file16 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
import file17 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
import file18 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
import file19 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
import file13 from "../../skills/seal-use/references/documents.md" with { type: "text" };
import file14 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" };
import file15 from "../../skills/seal-use/references/expense-data.md" with { type: "text" };
import file16 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" };
import file17 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
import file18 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
import file19 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file24 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"SKILL.md": file0,
@@ -33,20 +35,22 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"references/approval-run-lightweight.md": file10,
"references/cli.md": file11,
"references/customer-feedback-rule-remediation.md": file12,
"references/enterprise-onboarding.md": file13,
"references/first-time-user.md": file14,
"references/hose-enterprise-auth.md": file15,
"references/hose-enterprise-deploy.md": file16,
"references/hose-enterprise-init.md": file17,
"references/langfuse-trace.md": file18,
"references/report-templates.md": file19,
"references/rule-lightweight.md": file20,
"references/rule-lint.md": file21,
"references/staging-simulation-workflow.md": file22,
"references/webhook-resource-pack.md": file23,
"references/documents.md": file13,
"references/enterprise-onboarding.md": file14,
"references/expense-data.md": file15,
"references/first-time-user.md": file16,
"references/hose-enterprise-auth.md": file17,
"references/hose-enterprise-deploy.md": file18,
"references/hose-enterprise-init.md": file19,
"references/langfuse-trace.md": file20,
"references/report-templates.md": file21,
"references/rule-lightweight.md": file22,
"references/rule-lint.md": file23,
"references/staging-simulation-workflow.md": file24,
"references/webhook-resource-pack.md": file25,
};
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {
"assets/hose-curl-copy-as-curl.png": file2,
"assets/hose-curl-network-fetch-xhr.png": file3,
"assets/hose-curl-open-page-check.png": file4,
@@ -69,7 +73,9 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"references/approval-run-lightweight.md",
"references/cli.md",
"references/customer-feedback-rule-remediation.md",
"references/documents.md",
"references/enterprise-onboarding.md",
"references/expense-data.md",
"references/first-time-user.md",
"references/hose-enterprise-auth.md",
"references/hose-enterprise-deploy.md",
+5 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import packageJson from "../../package.json" with { type: "json" };
@@ -37,6 +37,10 @@ describe("embedded-skill", () => {
expect(existsSync(join(tmp, "references", "enterprise-onboarding.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "first-time-user.md"))).toBe(true);
expect(existsSync(join(tmp, "assets", "hose-curl-copy-as-curl.png"))).toBe(true);
expect([...res.files].sort()).toEqual([...EMBEDDED_SKILL_ALL_PATHS].sort());
for (const path of EMBEDDED_SKILL_ALL_PATHS) {
expect(readFileSync(join(tmp, path))).toEqual(readFileSync(join(import.meta.dir, "../../skills/seal-use", path)));
}
} finally {
rmSync(tmp, { recursive: true, force: true });
}
+11 -4
View File
@@ -3,16 +3,23 @@ import { homedir } from "node:os";
import { dirname, join } from "node:path";
import {
EMBEDDED_SKILL_ASSET_DATA,
EMBEDDED_SKILL_ASSET_PATHS,
EMBEDDED_SKILL_TEXT_FILES
} from "./embedded-skill.generated.js";
export { EMBEDDED_SKILL_ALL_PATHS } from "./embedded-skill.generated.js";
export const EMBEDDED_SKILL_FILES = EMBEDDED_SKILL_TEXT_FILES;
export const EMBEDDED_SKILL_ASSETS: Record<string, Uint8Array> = Object.fromEntries(
Object.entries(EMBEDDED_SKILL_ASSET_DATA).map(([relPath, base64]) => [relPath, Buffer.from(base64, "base64")])
);
// Runtime self-healing imports this module even for `version`. Read asset bytes
// only when installation actually asks for them, preserving local startup latency.
export const EMBEDDED_SKILL_ASSETS: Record<string, Uint8Array> = {};
for (const [relPath, path] of Object.entries(EMBEDDED_SKILL_ASSET_PATHS)) {
let bytes: Uint8Array | undefined;
Object.defineProperty(EMBEDDED_SKILL_ASSETS, relPath, {
enumerable: true,
get: () => bytes ??= readFileSync(path)
});
}
export function getSkillContent(): string {
return EMBEDDED_SKILL_FILES["SKILL.md"] || "";
@@ -44,44 +44,22 @@ describe("CLI semantic errors", () => {
expect(classifyCliError(new Error("Unknown deploy hosecloud action: x"))).toEqual({ exitCode: 2 });
});
test("classifies local config and input-data failures as validation errors (13)", () => {
// Chinese-language usage wording: the message names a flag/parameter to supply.
expect(
classifyCliError(new Error("当前租户存在多个 Webhook 通道 [\"a\" (1)],请通过 --webhook <idOrName> 指定目标通道。"))
).toEqual({ exitCode: 13 });
expect(classifyCliError(new Error("必须提供 target、recordId 或 sourceDocumentSN 参数。"))).toEqual({ exitCode: 13 });
// Enterprise selection: well-formed command, incomplete local config.
expect(
classifyCliError(new Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>."))
).toEqual({ exitCode: 13 });
expect(classifyCliError(new Error("No enterprise config found for nope"))).toEqual({ exitCode: 13 });
expect(
classifyCliError(new Error("rules lint requires an authenticated enterprise. Run 'seal-use corps list' to select one."))
).toEqual({ exitCode: 13 });
// Local file input the caller must fix.
expect(classifyCliError(new Error("File not found: /tmp/missing.json"))).toEqual({ exitCode: 13 });
expect(
classifyCliError(new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象"))
).toEqual({ exitCode: 13 });
// Structural signals that carry no message prefix.
test("classifies structural input failures without matching their wording", () => {
expect(classifyCliError(validationError("请选择目标通道"))).toMatchObject({ exitCode: 13 });
expect(classifyCliError(new SyntaxError("JSON Parse error: Expected '}'"))).toEqual({ exitCode: 13 });
expect(classifyCliError({ issues: [{ path: ["environment"], message: "Invalid option" }] })).toEqual({ exitCode: 13 });
});
test("classifies safety-guard blocks distinctly (14)", () => {
expect(
classifyCliError(new Error("目标企业「生产目标企业」(prod) 标记为生产正式环境 (production)。"))
).toEqual({ exitCode: 14 });
expect(classifyCliError(new Error("重放目标企业「T」(t) 的环境为「production」,非测试环境!"))).toEqual({
exitCode: 14
});
expect(classifyCliError(safetyBlocked("blocked by environment guard", "seal-use webhook replay --force"))).toEqual({
exitCode: 14,
nextAction: "seal-use webhook replay --force"
});
test("safety guards carry their code independently of user-facing text", () => {
expect(classifyCliError(safetyBlocked("blocked by environment guard", "seal-use webhook replay --force")))
.toEqual({ exitCode: 14, nextAction: "seal-use webhook replay --force" });
expect(classifyCliError(safetyBlocked("换一种中文解释"))).toMatchObject({ exitCode: 14 });
});
test("upstream messages containing validation or safety words stay domain failures", () => {
for (const message of ["上游格式错误,请提供工单", "No enterprise config found upstream", "File not found: remote object", "禁止向生产环境传输失败"]) {
expect(classifyCliError(new Error(message))).toEqual({ exitCode: 1 });
}
});
test("validationError helper carries exit 13 with next action", () => {
-28
View File
@@ -54,25 +54,6 @@ export function confirmationRequired(message: string, nextAction: string): CliEr
const USAGE_PREFIX =
/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )*(?:command|action|subcommand|target)|Invalid (?:number|boolean|command)|--json must|Missing required JSON field|Invalid JSON:)/i;
// Wording a Chinese-language usage error uses when it names a flag/parameter
// the caller must supply, or rejects a value the caller chose. Exit `13`.
// Deliberately excludes generic recovery verbs like "请先"/"请重试" so post-write
// or upstream failures that offer recovery advice stay at exit `1`.
const CN_USAGE =
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用 --|请提供)/;
// Enterprise-selection failures: the caller must pass --corp or fix config. Exit `13`.
const CORP_SELECTION =
/^(?:Stateless mode is enabled\.|No enterprise config found|.*requires an authenticated enterprise|.*requires an enterprise\.)/;
// Local file input problems that are the caller's responsibility to fix. Exit `13`.
const LOCAL_FILE_INPUT =
/^(?:File not found:|本地规则文件(?: JSON 解析失败|格式错误|包含重复)|未找到本地规则文件|第 \d+ 条规则(?:格式错误|缺少有效的)|ZIP 根目录缺少|起始时间 .* 不能晚于结束时间)/;
// Safety-guard wording: blocked by target environment, not by input shape. Exit `14`.
const SAFETY_GUARD =
/(?:标记为生产正式环境|非测试环境|严禁在生产环境|禁止向生产环境)/;
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
@@ -89,15 +70,6 @@ export function classifyCliError(error: unknown): {
if (USAGE_PREFIX.test(value)) {
return { exitCode: 2 };
}
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
return { exitCode: 10 };
}
if (SAFETY_GUARD.test(value)) {
return { exitCode: 14 };
}
if (CN_USAGE.test(value) || CORP_SELECTION.test(value) || LOCAL_FILE_INPUT.test(value)) {
return { exitCode: 13 };
}
// Structural validation: a ZodError carries an `issues` array rather than a
// message prefix, so it never matches a text pattern.
if (isValidationIssueList(error)) {
+97 -1
View File
@@ -1,13 +1,109 @@
import { afterEach, describe, expect, test } from "bun:test";
import { createSealClientForUrl } from "./factory.js";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CorpConfigSchema } from "../config/types.js";
import { setSealSession, getSealSession } from "../auth/token-store.js";
import { clearSealToken } from "../auth/seal.js";
import { classifyCliError } from "../errors.js";
import { createSealClient, createSealClientForUrl } from "./factory.js";
const servers: Array<ReturnType<typeof Bun.serve>> = [];
const tempDirs: string[] = [];
const corpIds: string[] = [];
const originalStore = process.env.SEAL_USE_TOKEN_STORE;
const originalFetch = globalThis.fetch;
afterEach(() => {
for (const server of servers.splice(0)) server.stop(true);
for (const id of corpIds.splice(0)) clearSealToken(id);
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
if (originalStore === undefined) delete process.env.SEAL_USE_TOKEN_STORE;
else process.env.SEAL_USE_TOKEN_STORE = originalStore;
globalThis.fetch = originalFetch;
});
function recoveryFixture(sourceType: "hose" | "seal", alwaysUnauthorized = false) {
const dir = mkdtempSync(join(tmpdir(), "seal-http-recovery-"));
tempDirs.push(dir);
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json");
const id = `http-recovery-${crypto.randomUUID()}`;
corpIds.push(id);
const corp = CorpConfigSchema.parse({
id, name: "Recovery fixture",
source: sourceType === "hose"
? { type: "hose", closeToken: "fixture-close-token", staffId: "fixture-staff", corpId: id, sealUrl: "https://fixture.invalid" }
: { type: "seal", token: "fixed-token", sealUrl: "https://fixture.invalid" }
});
setSealSession(id, {
token: "stale-token", expiresAt: Date.now() + 3600000,
enterprise: { provider: sourceType, staffId: "fixture-staff", sealUrl: "https://fixture.invalid" }
});
const requests: Array<{ method: string; token: string | null }> = [];
let refreshes = 0;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = input instanceof Request ? input : new Request(input, init);
if (new URL(request.url).pathname === "/api/auth/oauth2/session/oem-hosecloud") {
refreshes += 1;
// Allow simultaneous failures to join one in-flight refresh.
await Promise.resolve();
return Response.json({ token: "fresh-token", expiresIn: 3600 });
}
const token = request.headers.get("Authorization");
requests.push({ method: request.method, token });
return Response.json({ ok: true }, { status: !alwaysUnauthorized && token === "Bearer fresh-token" ? 200 : 401 });
}) as typeof fetch;
return { corp, requests, refreshCount: () => refreshes };
}
describe("Seal HTTP client errors", () => {
test("a renewable read recovers once and the same client uses the new session afterwards", async () => {
const fixture = recoveryFixture("hose");
const client = await createSealClient(fixture.corp);
expect(await client.get("api/read").json<{ ok: boolean }>()).toEqual({ ok: true });
expect(await client.get("api/read-again").json<{ ok: boolean }>()).toEqual({ ok: true });
expect(fixture.refreshCount()).toBe(1);
expect(fixture.requests.map((request) => request.token)).toEqual([
"Bearer stale-token", "Bearer fresh-token", "Bearer fresh-token"
]);
});
test("concurrent 401 reads share a refresh", async () => {
const fixture = recoveryFixture("hose");
const client = await createSealClient(fixture.corp);
await Promise.all([client.get("api/one"), client.get("api/two")]);
expect(fixture.refreshCount()).toBe(1);
});
test("a second 401 stops, clears the rejected cache, and remains an auth failure", async () => {
const fixture = recoveryFixture("hose", true);
const client = await createSealClient(fixture.corp);
const error = await client.get("api/read").catch((error: unknown) => error);
expect(classifyCliError(error)).toEqual({ exitCode: 11 });
expect(fixture.refreshCount()).toBe(1);
expect(fixture.requests).toHaveLength(2);
expect(getSealSession(fixture.corp.id)).toBeUndefined();
});
test("mutations, fixed bearers, and explicit retry opt-out are never replayed", async () => {
for (const source of ["hose", "seal"] as const) {
const fixture = recoveryFixture(source);
const client = await createSealClient(fixture.corp);
await expect(client.post("api/write", { json: { value: 1 } })).rejects.toThrow();
expect(fixture.requests).toHaveLength(1);
expect(fixture.refreshCount()).toBe(0);
}
const fixture = recoveryFixture("hose");
const client = await createSealClient(fixture.corp);
await expect(client.get("api/read", { retry: 0 })).rejects.toThrow();
expect(fixture.refreshCount()).toBe(0);
expect(fixture.requests).toHaveLength(1);
const fixed = recoveryFixture("seal");
await expect((await createSealClient(fixed.corp)).get("api/read")).rejects.toThrow();
expect(fixed.requests).toHaveLength(1);
expect(fixed.refreshCount()).toBe(0);
});
test("includes ky's parsed response body after the response stream is consumed", async () => {
const server = Bun.serve({
port: 0,
+19 -1
View File
@@ -1,6 +1,6 @@
import ky, { HTTPError, KyInstance } from "ky";
import { CorpConfig } from "../config/types.js";
import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js";
import { clearSealToken, getSealSessionForCorp, recoverSealSessionForCorp } from "../auth/seal.js";
import { resolveSealCustomHeaders } from "./request-headers.js";
function formatErrorData(data: unknown): string {
@@ -40,6 +40,24 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
Authorization: `Bearer ${session.token}`
},
hooks: {
beforeRequest: [async ({ request }) => {
const current = await getSealSessionForCorp(corp);
request.headers.set("Authorization", `Bearer ${current.token}`);
}],
afterResponse: [async ({ request, response, retryCount, options }) => {
// Only renewable sessions and safe reads are replayed. A fixed native
// bearer cannot be refreshed, and mutation requests must never be replayed here.
if (
response.status !== 401 || retryCount !== 0 || options.retry.limit === 0 ||
corp.source.type !== "hose" || !["GET", "HEAD", "OPTIONS"].includes(request.method)
) return;
const rejectedToken = request.headers.get("Authorization")?.replace(/^Bearer /, "") ?? "";
const refreshed = await recoverSealSessionForCorp(corp, rejectedToken);
if (new URL(request.url).origin !== new URL(refreshed.enterprise.sealUrl).origin) return;
const headers = new Headers(request.headers);
headers.set("Authorization", `Bearer ${refreshed.token}`);
return ky.retry({ request: new Request(request, { headers }), delay: 0, code: "SEAL_SESSION_REFRESHED" });
}],
beforeError: [createBeforeErrorHook(corp.id)]
}
});
+4 -4
View File
@@ -2,7 +2,6 @@ import { existsSync, symlinkSync } from "node:fs";
import { homedir } from "node:os";
import { basename, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { syncGlobalSkillIfPresent } from "./embedded-skill.js";
export function isCompiledBinary(execPath = process.execPath, metaUrl = import.meta.url): boolean {
if (metaUrl.includes("/$bunfs/") || metaUrl.includes("\\$bunfs\\")) {
@@ -42,10 +41,10 @@ export function resolveDefaultLauncher(
};
}
export function performRuntimeSelfHealing(): {
export async function performRuntimeSelfHealing(): Promise<{
binaryHealed?: boolean;
skillHealed?: boolean;
} {
}> {
const result: { binaryHealed?: boolean; skillHealed?: boolean } = {};
// 1. Binary executable alias self-healing
@@ -77,7 +76,8 @@ export function performRuntimeSelfHealing(): {
try {
const legacySkillDir = join(homedir(), ".agents", "skills", "seal-home");
if (existsSync(legacySkillDir)) {
syncGlobalSkillIfPresent();
// Ordinary discovery must not initialize the embedded resource graph.
(await import("./embedded-skill.js")).syncGlobalSkillIfPresent();
result.skillHealed = true;
}
} catch {
+102
View File
@@ -0,0 +1,102 @@
import { afterEach, describe, expect, test } from "bun:test";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { writeSecureFile } from "./secure-file.js";
/**
* Direct unit tests for the credential write path.
*
* Indirect coverage exists through loader/token-store mode assertions, but
* this helper is the single choke point that keeps existing world-readable
* credential files from staying world-readable — the P0 from the 2026-10-17
* architecture review. Its guarantees deserve their own colocated tests so a
* refactor of either caller cannot silently drop them.
*/
const tempDirs: string[] = [];
function tempDir(): string {
const dir = mkdtempSync(join(tmpdir(), "seal-secure-file-"));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function fileMode(path: string): number {
return statSync(path).mode & 0o777;
}
describe("writeSecureFile", () => {
test("creates a new credential file as 0600 with exact content", () => {
const dir = tempDir();
const target = join(dir, "tokens.json");
writeSecureFile(target, '{"token":"secret"}\n');
expect(fileMode(target)).toBe(0o600);
expect(readFileSync(target, "utf8")).toBe('{"token":"secret"}\n');
});
test("tightens a pre-existing 0644 file to 0600 on write", () => {
const dir = tempDir();
const target = join(dir, "corp.json");
writeFileSync(target, '{"old":"legacy-inherited"}', { mode: 0o644 });
chmodSync(target, 0o644);
expect(fileMode(target)).toBe(0o644);
writeSecureFile(target, '{"new":"rotated-secret"}');
expect(fileMode(target)).toBe(0o600);
expect(readFileSync(target, "utf8")).toBe('{"new":"rotated-secret"}');
});
test("truncates longer previous content so no secret residue survives", () => {
const dir = tempDir();
const target = join(dir, "tokens.json");
writeSecureFile(target, '{"access":"a","refresh":"b","extra":"padding-padding"}');
writeSecureFile(target, "{}");
expect(readFileSync(target, "utf8")).toBe("{}");
});
test("accepts binary content such as embedded skill assets", () => {
const dir = tempDir();
const target = join(dir, "asset.png");
const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]);
writeSecureFile(target, bytes);
expect(fileMode(target)).toBe(0o600);
expect(new Uint8Array(readFileSync(target))).toEqual(bytes);
});
test("creates missing parent directories as 0700", () => {
const dir = tempDir();
const target = join(dir, "nested", "deeper", "tokens.json");
writeSecureFile(target, "{}");
expect(fileMode(target)).toBe(0o600);
expect(fileMode(join(dir, "nested"))).toBe(0o700);
expect(fileMode(join(dir, "nested", "deeper"))).toBe(0o700);
});
test("does not rewrite the mode of a user-owned parent directory", () => {
const dir = tempDir();
const shared = join(dir, "shared");
mkdirSync(shared, { mode: 0o755 });
chmodSync(shared, 0o755);
writeSecureFile(join(shared, "corp.json"), "{}");
expect(fileMode(shared)).toBe(0o755);
expect(fileMode(join(shared, "corp.json"))).toBe(0o600);
});
});
+14
View File
@@ -0,0 +1,14 @@
import { closeSync, fchmodSync, mkdirSync, openSync, writeFileSync } from "node:fs"
import { dirname } from "node:path"
/** Tighten an existing credential file before writing any new secret bytes. */
export function writeSecureFile(path: string, content: string | Uint8Array): void {
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
const fd = openSync(path, "w", 0o600)
try {
fchmodSync(fd, 0o600)
writeFileSync(fd, content)
} finally {
closeSync(fd)
}
}
+6
View File
@@ -22,3 +22,9 @@ declare module "*.svg" {
const content: string;
export default content;
}
/** Bun file-loader imports resolve to a source or compiled embedded asset path. */
declare module "*.png" {
const path: string
export default path
}
+17
View File
@@ -280,6 +280,23 @@ describe("Seal contact API", () => {
]);
});
test("expenses always sends a filter object and supports recordId plus normalized dates", async () => {
const queries: URLSearchParams[] = [];
const client = {
get: (_url: string, options: { searchParams: URLSearchParams }) => {
queries.push(options.searchParams);
return { json: async () => ({ data: { expenses: [], total: 0 } }) };
}
} as unknown as KyInstance;
await listExpenses(client);
expect(queries[0]?.has("filter[search]")).toBe(true);
expect(queries[0]?.get("filter[search]")).toBe("");
expect(queries[0]?.has("filter[startDate]")).toBe(false);
await listExpenses(client, { recordId: "record-fixture", startDate: "2025-01-01T00:00:00+08:00" });
expect(queries[1]?.get("filter[recordId]")).toBe("record-fixture");
expect(queries[1]?.get("filter[startDate]")).toBe("1735660800000");
});
test("lists Feishu simulation approval definitions", async () => {
let requestedUrl = "";
const client = {
+18 -4
View File
@@ -10,7 +10,7 @@ import { CorpConfig } from "../../core/config/types.js";
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { redactSensitiveText } from "../../core/redact.js";
import { safetyBlocked } from "../../core/errors.js";
import { safetyBlocked, validationError } from "../../core/errors.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import {
ApprovalDocumentListData,
@@ -245,6 +245,7 @@ export async function createApprovalDocument(
) {
return unwrap(
await client.post("api/v1/knowledge/articles", {
retry: 0,
json: {
...params,
contentType: params.contentType ?? "policy",
@@ -278,6 +279,7 @@ export async function updateApprovalDocument(
return unwrap(
await client.patch(`api/v1/knowledge/articles/${documentId}`, {
retry: 0,
json: { attributes }
}),
ApprovalDocumentSchema
@@ -288,7 +290,7 @@ export async function deleteApprovalDocument(
client: KyInstance,
documentId: string
): Promise<{ success: boolean; id: string }> {
await client.delete(`api/v1/knowledge/articles/${documentId}`);
await client.delete(`api/v1/knowledge/articles/${documentId}`, { retry: 0 });
return { success: true, id: documentId };
}
@@ -1123,6 +1125,8 @@ export type DataListParams = {
search?: string;
};
export type ExpenseListParams = DataListParams & { recordId?: string };
function dataListSearchParams(params: DataListParams): URLSearchParams {
const searchParams = new URLSearchParams();
setOptional(searchParams, "filter[startDate]", params.startDate);
@@ -1135,10 +1139,20 @@ function dataListSearchParams(params: DataListParams): URLSearchParams {
export async function listExpenses(
client: KyInstance,
params: DataListParams = {}
params: ExpenseListParams = {}
): Promise<ExpenseListData> {
// The expense endpoint requires a filter object even for an unfiltered list.
const searchParams = dataListSearchParams(params);
searchParams.set("filter[search]", params.search ?? "");
setOptional(searchParams, "filter[recordId]", params.recordId);
for (const [key, value] of [["startDate", params.startDate], ["endDate", params.endDate]] as const) {
if (value !== undefined) {
try { searchParams.set(`filter[${key}]`, String(normalizeToTimestamp(value))); }
catch { throw validationError(`Invalid expense ${key}: expected ISO date or timestamp`); }
}
}
return unwrap(
await client.get("api/v1/expenses/list", { searchParams: dataListSearchParams(params) }),
await client.get("api/v1/expenses/list", { searchParams }),
ExpenseListDataSchema
);
}
@@ -1,3 +1,4 @@
import { validationError } from "../../../core/errors.js";
import fs from "node:fs";
import path from "node:path";
import type { ApprovalRun } from "../types.js";
@@ -320,9 +321,7 @@ export async function downloadApprovalRunAttachments(
} else if (!options.all) {
if (allAttachments.length > 1) {
const available = allAttachments.map((a) => a.fileName ?? a.fileId).filter(Boolean).join(", ");
throw new Error(
`共发现 ${allAttachments.length} 个附件。请使用 --all 下载全部附件,或使用 --name <名称|fileId> 指定下载项。可选附件: ${available}`
);
throw validationError(`共发现 ${allAttachments.length} 个附件。请使用 --all 下载全部附件,或使用 --name <名称|fileId> 指定下载项。可选附件: ${available}`);
}
selected = allAttachments;
} else {
+5 -10
View File
@@ -1,3 +1,4 @@
import { validationError } from "../../../core/errors.js";
import { existsSync, mkdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, extname, resolve } from "node:path";
@@ -147,9 +148,7 @@ export function resolveExportDateRange(
if (hasStart) {
const formatted = formatDate(options.startDate);
if (!formatted) {
throw new Error(
`无效的起始时间参数: "${String(options.startDate)}"。请使用 YYYY-MM-DD 或有效时间戳。`
);
throw validationError(`无效的起始时间参数: "${String(options.startDate)}"。请使用 YYYY-MM-DD 或有效时间戳。`);
}
startDateStr = formatted;
}
@@ -157,9 +156,7 @@ export function resolveExportDateRange(
if (hasEnd) {
const formatted = formatDate(options.endDate);
if (!formatted) {
throw new Error(
`无效的结束时间参数: "${String(options.endDate)}"。请使用 YYYY-MM-DD 或有效时间戳。`
);
throw validationError(`无效的结束时间参数: "${String(options.endDate)}"。请使用 YYYY-MM-DD 或有效时间戳。`);
}
endDateStr = formatted;
}
@@ -198,7 +195,7 @@ export function resolveExportDateRange(
const endTs = normalizeTimestamp(endDateStr, true)!;
if (Number(startTs) > Number(endTs)) {
throw new Error(`起始时间 (${startDateStr}) 不能晚于结束时间 (${endDateStr})。`);
throw validationError(`起始时间 (${startDateStr}) 不能晚于结束时间 (${endDateStr})。`);
}
// 计算天数跨度
@@ -299,9 +296,7 @@ export function resolveOutputFilePath(options: {
let p = resolve(options.outputFile);
const ext = extname(p).toLowerCase();
if (ext && ext !== ".xlsx") {
throw new Error(
`导出路径错误: 本命令仅支持导出 Excel 工作簿,文件扩展名必须为 .xlsx(当前指定为 "${ext}")。请使用 .xlsx 后缀,例如: ${p.slice(0, -ext.length)}.xlsx`
);
throw validationError(`导出路径错误: 本命令仅支持导出 Excel 工作簿,文件扩展名必须为 .xlsx(当前指定为 "${ext}")。请使用 .xlsx 后缀,例如: ${p.slice(0, -ext.length)}.xlsx`);
}
if (!ext) {
p = `${p}.xlsx`;
@@ -0,0 +1,168 @@
import { describe, expect, test } from "bun:test";
import {
flattenInvoiceRecord,
extractDocumentInvoices,
detectInvoiceConflicts,
normalizeInvoiceDate,
normalizeInvoiceStatus
} from "./invoices.js";
import type { ApprovalRun } from "../types.js";
describe("invoices domain module", () => {
test("normalizeInvoiceDate formats 8-digit and slash dates to YYYY-MM-DD", () => {
expect(normalizeInvoiceDate("20260617")).toBe("2026-06-17");
expect(normalizeInvoiceDate("2026/06/17")).toBe("2026-06-17");
expect(normalizeInvoiceDate("2026-06-17")).toBe("2026-06-17");
expect(normalizeInvoiceDate("")).toBe("");
});
test("normalizeInvoiceStatus correctly normalizes verified status", () => {
expect(normalizeInvoiceStatus(undefined, "NORMAL_BLUE")).toBe("已验真 (verified)");
expect(normalizeInvoiceStatus("verified", undefined)).toBe("已验真 (verified)");
expect(normalizeInvoiceStatus(undefined, undefined, "NORMAL_BLUE")).toBe("已验真 (verified)");
});
test("flattenInvoiceRecord flattens nested verifyResult and fileInfo into 8 core business fields", () => {
const raw = {
id: "inv-1",
invoiceNumber: "26957000000102316227",
sourceDocumentSN: "B26002404",
totalAmount: 500,
usedAmount: 409.02,
verifyStatus: "verified",
verifyResult: {
invoiceType: "电子发票(普通发票)",
sellerName: "深圳石油公明加油站",
buyerName: "钰泰半导体股份有限公司",
invoiceDate: "2026-06-17"
},
fileInfo: {
fileName: "test.pdf",
ossSignedUrl: "https://oss.example.com/test.pdf"
},
relatedDocuments: [
{
sourceDocumentSN: "B26002404",
sourceDocumentId: "ID01WfOdmKUHyT",
approvalRecordId: "rec-1",
relatedAt: 1790001624549
}
]
};
const flattened = flattenInvoiceRecord(raw);
expect(flattened.sourceDocumentSN).toBe("B26002404");
expect(flattened.invoiceNumber).toBe("26957000000102316227");
expect(flattened.invoiceType).toBe("电子发票(普通发票)");
expect(flattened.invoiceDate).toBe("2026-06-17");
expect(flattened.sellerName).toBe("深圳石油公明加油站");
expect(flattened.buyerName).toBe("钰泰半导体股份有限公司");
expect(flattened.totalAmount).toBe(500);
expect(flattened.usedAmount).toBe(409.02);
expect(flattened.status).toBe("已验真 (verified)");
expect(flattened.fileName).toBe("test.pdf");
expect(flattened.attachmentUrl).toBe("https://oss.example.com/test.pdf");
expect(flattened.relatedDocuments).toHaveLength(1);
expect(flattened.relatedDocuments[0]?.sourceDocumentSN).toBe("B26002404");
});
test("detectInvoiceConflicts identifies cross-document invoice reuse and attributes to CLI", () => {
const mockRun = {
id: "run-2570",
sourceDocumentSN: "B26002570",
sourceDocumentId: "doc-2570",
document: {
fields: [
{
label: "明细",
value: [
{
invoice: {
invoiceNumber: "26957000000102316227",
totalAmount: 500,
usedAmount: 409.02,
sellerName: "深圳石油公明加油站",
relatedDocuments: [
{
sourceDocumentSN: "B26002404",
sourceDocumentId: "doc-2404",
approvalRecordId: "run-2404"
}
]
}
}
]
}
]
}
} as unknown as ApprovalRun;
const conflicts = detectInvoiceConflicts(mockRun, "testCorp");
expect(conflicts).toHaveLength(1);
const c = conflicts[0]!;
expect(c.source).toBe("cli_analysis");
expect(c.detectedBy).toContain("seal-use CLI");
expect(c.invoiceNumber).toBe("26957000000102316227");
expect(c.conflictingSN).toBe("B26002404");
expect(c.usedAmount).toBe(409.02);
expect(c.nextCommand).toBe("seal-use approval-runs diagnose --sn B26002404 --corp testCorp");
});
test("detectInvoiceConflicts returns empty array when invoices only relate to current document", () => {
const mockRun = {
id: "run-2570",
sourceDocumentSN: "B26002570",
sourceDocumentId: "doc-2570",
document: {
fields: [
{
invoice: {
invoiceNumber: "26952000000810724261",
totalAmount: 400,
relatedDocuments: [
{
sourceDocumentSN: "B26002570",
sourceDocumentId: "doc-2570",
approvalRecordId: "run-2570"
}
]
}
}
]
}
} as unknown as ApprovalRun;
const conflicts = detectInvoiceConflicts(mockRun, "testCorp");
expect(conflicts).toHaveLength(0);
});
test("extractDocumentInvoices extracts and normalizes unique invoices from document fields", () => {
const mockRun = {
id: "run-2570",
sourceDocumentSN: "B26002570",
document: {
fields: [
{
invoice: {
invoiceNumber: "26957000000102316227",
totalAmount: 500
}
},
{
// duplicate invoice reference in another field
invoice: {
invoiceNumber: "26957000000102316227",
totalAmount: 500
}
}
]
}
} as unknown as ApprovalRun;
const invoices = extractDocumentInvoices(mockRun);
expect(invoices).toHaveLength(1);
expect(invoices[0]?.invoiceNumber).toBe("26957000000102316227");
expect(invoices[0]?.totalAmount).toBe(500);
});
});
+290
View File
@@ -0,0 +1,290 @@
import type { KyInstance } from "ky";
import * as api from "../api.js";
import type { ApprovalRun } from "../types.js";
export interface NormalizedInvoice {
sourceDocumentSN: string;
sourceDocumentId?: string;
approvalRecordId?: string;
invoiceNumber: string;
invoiceType: string;
invoiceDate: string;
sellerName: string;
buyerName: string;
totalAmount: number;
taxAmount: number;
usedAmount: number;
status: string;
fileName: string;
attachmentUrl?: string;
relatedDocuments: Array<{
sourceDocumentSN?: string;
sourceDocumentId?: string;
approvalRecordId?: string;
relatedAt?: number;
}>;
}
export interface InvoiceConflict {
source: "cli_analysis";
detectedBy: "seal-use CLI (基于单据原始发票关联数据自动提炼,非后端大模型生成)";
invoiceNumber: string;
sellerName?: string;
invoiceDate?: string;
totalAmount?: number;
usedAmount?: number;
conflictingSN: string;
conflictingDocumentId?: string;
conflictingRecordId?: string;
explanation: string;
nextCommand: string;
}
export interface InvoiceTraceReport {
invoice: NormalizedInvoice;
associatedDocuments: Array<{
sourceDocumentSN: string;
sourceDocumentId?: string;
approvalRecordId?: string;
usedAmount?: number;
relatedAt?: number;
nextDiagnose: string;
}>;
conflictStatus: "NONE" | "MULTIPLE_DOCUMENTS_ATTACHED";
guidance: {
source: "cli_analysis";
detectedBy: "seal-use CLI (基于进项发票库关联数据提炼,非后端大模型生成)";
summary: string;
};
}
export function normalizeInvoiceDate(rawDate?: unknown): string {
if (!rawDate) return "";
const str = String(rawDate).trim();
if (/^\d{8}$/.test(str)) {
return `${str.slice(0, 4)}-${str.slice(4, 6)}-${str.slice(6, 8)}`;
}
if (/^\d{4}[-/]\d{1,2}[-/]\d{1,2}/.test(str)) {
return str.replace(/\//g, "-").slice(0, 10);
}
return str;
}
export function normalizeInvoiceStatus(status?: unknown, verifyStatus?: unknown, verifyCode?: unknown): string {
const combined = `${status ?? ""} ${verifyStatus ?? ""} ${verifyCode ?? ""}`.toLowerCase();
if (combined.includes("verified") || combined.includes("normal_blue") || combined.includes("已验真")) {
return "已验真 (verified)";
}
if (combined.includes("fail") || combined.includes("不合规")) {
return "验真失败 (failed)";
}
return String(status ?? verifyStatus ?? "未知");
}
export function flattenInvoiceRecord(raw: Record<string, unknown>): NormalizedInvoice {
const verifyResult = (raw.verifyResult && typeof raw.verifyResult === "object" ? raw.verifyResult : {}) as Record<string, unknown>;
const rawForm = (verifyResult.form && typeof verifyResult.form === "object" ? verifyResult.form : {}) as Record<string, unknown>;
const fileInfo = (raw.fileInfo && typeof raw.fileInfo === "object" ? raw.fileInfo : {}) as Record<string, unknown>;
const relatedDocs = Array.isArray(raw.relatedDocuments) ? raw.relatedDocuments : [];
const invoiceNumber = String(raw.invoiceNumber ?? verifyResult.invoiceNumber ?? rawForm["发票号码"] ?? "");
const invoiceDate = normalizeInvoiceDate(verifyResult.invoiceDate ?? raw.invoiceDate ?? rawForm["发票日期"]);
const invoiceType = String(verifyResult.invoiceType ?? raw.invoiceType ?? rawForm["发票类别"] ?? rawForm["发票类型"] ?? "");
const sellerName = String(verifyResult.sellerName ?? raw.sellerName ?? rawForm["销售方名称"] ?? "");
const buyerName = String(verifyResult.buyerName ?? raw.buyerName ?? rawForm["购买方名称"] ?? "");
const totalAmount = typeof raw.totalAmount === "number"
? raw.totalAmount
: Number(verifyResult.totalAmount ?? (rawForm["价税合计"] as string)?.replace(/[^0-9.]/g, "") ?? 0);
const taxAmount = typeof raw.taxAmount === "number"
? raw.taxAmount
: Number(verifyResult.taxAmount ?? (rawForm["税额"] as string)?.replace(/[^0-9.]/g, "") ?? 0);
const usedAmount = typeof raw.usedAmount === "number" ? raw.usedAmount : Number(raw.usedAmount ?? 0);
const status = normalizeInvoiceStatus(raw.status, raw.verifyStatus ?? verifyResult.verify, rawForm["发票状态"]);
const fileName = String(fileInfo.fileName ?? fileInfo.name ?? raw.fileName ?? "");
const attachmentUrl = String(fileInfo.ossSignedUrl ?? fileInfo.fileUrl ?? raw.fileUrl ?? "");
const sourceDocumentSN = String(
raw.sourceDocumentSN ??
(relatedDocs[0] as Record<string, unknown>)?.sourceDocumentSN ??
""
);
return {
sourceDocumentSN,
sourceDocumentId: raw.sourceDocumentId ? String(raw.sourceDocumentId) : undefined,
approvalRecordId: raw.approvalRecordId ? String(raw.approvalRecordId) : undefined,
invoiceNumber,
invoiceType,
invoiceDate,
sellerName,
buyerName,
totalAmount,
taxAmount,
usedAmount,
status,
fileName,
attachmentUrl: attachmentUrl || undefined,
relatedDocuments: relatedDocs.map((item) => {
const doc = item as Record<string, unknown>;
return {
sourceDocumentSN: doc.sourceDocumentSN ? String(doc.sourceDocumentSN) : undefined,
sourceDocumentId: doc.sourceDocumentId ? String(doc.sourceDocumentId) : undefined,
approvalRecordId: doc.approvalRecordId ? String(doc.approvalRecordId) : undefined,
relatedAt: typeof doc.relatedAt === "number" ? doc.relatedAt : undefined
};
})
};
}
export function extractDocumentInvoices(record: ApprovalRun): NormalizedInvoice[] {
const rawInvoices: Array<Record<string, unknown>> = [];
function traverse(obj: unknown) {
if (!obj) return;
if (Array.isArray(obj)) {
obj.forEach(traverse);
return;
}
if (typeof obj === "object") {
const r = obj as Record<string, unknown>;
if (r.invoice && typeof r.invoice === "object") {
rawInvoices.push(r.invoice as Record<string, unknown>);
} else if (r.invoiceNumber) {
rawInvoices.push(r);
}
for (const val of Object.values(r)) {
traverse(val);
}
}
}
traverse(record.document);
const seen = new Set<string>();
const uniqueNormalized: NormalizedInvoice[] = [];
for (const raw of rawInvoices) {
const normalized = flattenInvoiceRecord(raw);
if (!normalized.invoiceNumber) continue;
if (seen.has(normalized.invoiceNumber)) continue;
seen.add(normalized.invoiceNumber);
uniqueNormalized.push(normalized);
}
return uniqueNormalized;
}
export function detectInvoiceConflicts(detail: ApprovalRun, corpId?: string): InvoiceConflict[] {
const invoices = extractDocumentInvoices(detail);
const conflicts: InvoiceConflict[] = [];
const currentSN = detail.sourceDocumentSN ?? "";
const currentDocId = detail.sourceDocumentId ?? "";
const currentRunId = detail.id ?? "";
for (const inv of invoices) {
const conflictingDocs = inv.relatedDocuments.filter((doc) => {
const sameSN = currentSN && doc.sourceDocumentSN === currentSN;
const sameDocId = currentDocId && doc.sourceDocumentId === currentDocId;
const sameRunId = currentRunId && doc.approvalRecordId === currentRunId;
return !(sameSN || sameDocId || sameRunId);
});
if (conflictingDocs.length > 0) {
for (const cDoc of conflictingDocs) {
const conflictingSN = cDoc.sourceDocumentSN ?? cDoc.sourceDocumentId ?? "未知单据";
const corpArg = corpId ? ` --corp ${corpId}` : "";
const nextCommand = cDoc.sourceDocumentSN
? `seal-use approval-runs diagnose --sn ${cDoc.sourceDocumentSN}${corpArg}`
: `seal-use approval-runs diagnose ${cDoc.approvalRecordId ?? ""}${corpArg}`;
const usedNote = inv.usedAmount > 0 ? `,历史占用/报销金额 ¥${inv.usedAmount}` : "";
conflicts.push({
source: "cli_analysis",
detectedBy: "seal-use CLI (基于单据原始发票关联数据自动提炼,非后端大模型生成)",
invoiceNumber: inv.invoiceNumber,
sellerName: inv.sellerName,
invoiceDate: inv.invoiceDate,
totalAmount: inv.totalAmount,
usedAmount: inv.usedAmount,
conflictingSN,
conflictingDocumentId: cDoc.sourceDocumentId,
conflictingRecordId: cDoc.approvalRecordId,
explanation: `发票 ${inv.invoiceNumber}(${inv.sellerName || "销售方"},¥${inv.totalAmount})曾被历史单据 ${conflictingSN} 挂载${usedNote}。请核实是否为重复报销。`,
nextCommand
});
}
}
}
return conflicts;
}
export async function traceInvoice(
client: KyInstance,
invoiceNumber: string,
corpId?: string
): Promise<InvoiceTraceReport | null> {
const cleanNumber = invoiceNumber.trim();
if (!cleanNumber) return null;
const data = await api.listInvoices(client, { search: cleanNumber, limit: 10 });
if (!data.invoices || data.invoices.length === 0) {
return null;
}
const matched = data.invoices.find((item) => {
const num = String(item.invoiceNumber ?? (item.verifyResult as any)?.invoiceNumber ?? "");
return num === cleanNumber;
}) ?? data.invoices[0]!;
const invoice = flattenInvoiceRecord(matched as Record<string, unknown>);
const associatedDocuments: InvoiceTraceReport["associatedDocuments"] = [];
const corpArg = corpId ? ` --corp ${corpId}` : "";
if (invoice.sourceDocumentSN) {
associatedDocuments.push({
sourceDocumentSN: invoice.sourceDocumentSN,
sourceDocumentId: invoice.sourceDocumentId,
approvalRecordId: invoice.approvalRecordId,
usedAmount: invoice.usedAmount,
nextDiagnose: `seal-use approval-runs diagnose --sn ${invoice.sourceDocumentSN}${corpArg}`
});
}
for (const doc of invoice.relatedDocuments) {
if (doc.sourceDocumentSN && !associatedDocuments.some((d) => d.sourceDocumentSN === doc.sourceDocumentSN)) {
associatedDocuments.push({
sourceDocumentSN: doc.sourceDocumentSN,
sourceDocumentId: doc.sourceDocumentId,
approvalRecordId: doc.approvalRecordId,
relatedAt: doc.relatedAt,
nextDiagnose: `seal-use approval-runs diagnose --sn ${doc.sourceDocumentSN}${corpArg}`
});
}
}
const hasMultiple = associatedDocuments.length > 1;
const conflictStatus = hasMultiple ? "MULTIPLE_DOCUMENTS_ATTACHED" : "NONE";
const docListStr = associatedDocuments.map((d) => d.sourceDocumentSN).join("、");
const summary = hasMultiple
? `发票 ${invoice.invoiceNumber} 在 ${associatedDocuments.length} 笔单据(${docListStr})中均有挂载记录。若其中有单据已被驳回或删票,请确认合思发票池是否释放;若均在审批或已核销,则属于真实重复报销。`
: `发票 ${invoice.invoiceNumber} 当前仅关联单据 ${invoice.sourceDocumentSN || "未知"},未检测到跨单据重复挂载冲突。`;
return {
invoice,
associatedDocuments,
conflictStatus,
guidance: {
source: "cli_analysis",
detectedBy: "seal-use CLI (基于进项发票库关联数据提炼,非后端大模型生成)",
summary
}
};
}
+16 -1
View File
@@ -1,3 +1,4 @@
import { validationError } from "../../../core/errors.js";
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
@@ -13,6 +14,7 @@ import {
import {
type ApprovalRun
} from "../types.js";
import { detectInvoiceConflicts } from "../approval-runs/invoices.js";
import type {
CapabilityContext
} from "./helpers.js";
@@ -242,7 +244,7 @@ export const approvalRunsCapabilities = [
const input = (params.target || params.sourceDocumentSN || params.recordId)?.trim();
if (!input) {
throw new Error("必须提供 target、recordId 或 sourceDocumentSN 参数。");
throw validationError("必须提供 target、recordId 或 sourceDocumentSN 参数。");
}
let sn = input;
@@ -716,6 +718,16 @@ export const approvalRunsCapabilities = [
}
}
const invoiceConflicts = detectInvoiceConflicts(detail, context.corp.id);
if (invoiceConflicts.length > 0) {
console.error(
`\n💡 [CLI 辅助诊断指引](注:此冲突指引由 seal-use CLI 基于单据原始发票关联数据自动分析提炼,非后端大模型生成):\n` +
invoiceConflicts.map((c) => `• 发票 ${c.invoiceNumber}(${c.sellerName || "销售方"},¥${c.totalAmount})曾被单据 ${c.conflictingSN} 挂载${c.usedAmount ? `(已占报销金额 ¥${c.usedAmount})` : ""}\n 👉 诊断冲突原单:${c.nextCommand}`).join("\n") +
`\n`
);
}
return {
recordId: detail.id,
sourceDocumentSN: detail.sourceDocumentSN,
@@ -726,10 +738,13 @@ export const approvalRunsCapabilities = [
result: params.full === true ? detail.result : resultSummary,
citedRules,
ruleVersion,
invoiceConflicts: invoiceConflicts.length > 0 ? invoiceConflicts : undefined,
bridge: summarizeRunBridge([detail]),
next: {
url: `seal-use approval-runs url ${detail.id} --corp ${context.corp.id}`,
hoseDocument: `seal-use approval-runs url ${detail.id} --type hose-document --corp ${context.corp.id}`,
diagnoseConflict: invoiceConflicts[0]?.nextCommand,
traceInvoice: invoiceConflicts[0] ? `seal-use invoices trace ${invoiceConflicts[0].invoiceNumber} --corp ${context.corp.id}` : undefined,
replay: `seal-use approval-runs replay ${detail.id} --dry-run --corp ${context.corp.id}`
}
};
+2 -2
View File
@@ -123,14 +123,14 @@ export const deployCapabilities = [
const apiKey = inputParams.apiKey ?? (typeof appKey === "string" ? appKey : undefined);
const apiSecret = inputParams.apiSecret ?? (typeof appSecurity === "string" ? appSecurity : undefined);
if (!apiKey || !apiSecret) {
throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
throw validationError("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
}
const params = { ...inputParams, apiKey, apiSecret };
let effectiveApiOrigin = params.apiOrigin ?? "production";
let effectiveCustomApiUrl = params.customApiUrl;
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
throw new Error("自定义合思环境必须提供 customApiUrl");
throw validationError("自定义合思环境必须提供 customApiUrl");
}
if (!dryRun && confirm !== true) {
throw confirmationRequired(
+6 -6
View File
@@ -27,7 +27,7 @@ import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import type { LocalRuleItem } from "../rules/local.js";
import { loadRuleMappingSnapshot } from "../rules/mapping.js";
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
import { validationError } from "../../../core/errors.js";
import { validationError, usageError } from "../../../core/errors.js";
export type CapabilityContext = {
corp: CorpConfig;
@@ -324,7 +324,7 @@ export function buildSimulationBatchParams(input: SimulationBatchCreateInput): R
if (sourceSystem === "hosecloud") {
if (!docSns?.length && input.startTime === undefined) {
throw new Error("hosecloud 模式需要提供 flowIds(单号列表)");
throw validationError("hosecloud 模式需要提供 flowIds(单号列表)");
}
Object.assign(params, {
dataCollectionMode: "2",
@@ -340,11 +340,11 @@ export function buildSimulationBatchParams(input: SimulationBatchCreateInput): R
} else if (sourceSystem === "material_pack" || sourceSystem === "material-pack") {
const packageIds = input.packageIds ?? (input.packageId ? [input.packageId] : undefined);
if (!packageIds?.length) {
throw new Error("material_pack 模式需要提供 packageIds(材料包 id)");
throw validationError("material_pack 模式需要提供 packageIds(材料包 id)");
}
const templateId = input.templateId ?? (input.schemaConfig as { id?: string } | undefined)?.id;
if (!templateId) {
throw new Error("material_pack 模式需要提供 templateId(或 schemaConfig.id)");
throw validationError("material_pack 模式需要提供 templateId(或 schemaConfig.id)");
}
Object.assign(params, {
templateId,
@@ -1030,7 +1030,7 @@ export function findRuleInDraft(
) {
const rawTarget = selector.ruleId ?? selector.code ?? selector.runtimeId;
if (!rawTarget || !rawTarget.trim()) {
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>]");
throw usageError("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>]");
}
const trimmed = rawTarget.trim();
const targetCodeNum = parseRuleCodeNumber(trimmed);
@@ -1068,7 +1068,7 @@ export function findRuleInVersion(
) {
const rawTarget = selector.ruleId ?? selector.code ?? selector.runtimeId;
if (!rawTarget || !rawTarget.trim()) {
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>]");
throw usageError("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>]");
}
const trimmed = rawTarget.trim();
const targetCodeNum = parseRuleCodeNumber(trimmed);
+30 -6
View File
@@ -6,6 +6,10 @@ import type {
CapabilityContext
} from "./helpers.js";
import { flattenInvoiceRecord } from "../approval-runs/invoices.js";
import { lookupDocumentExpenses } from "../expenses/lookup.js";
import { usageError } from "../../../core/errors.js";
export const insightCapabilities = [
{
name: "sealInsightStatsGet",
@@ -75,26 +79,46 @@ export const insightCapabilities = [
},
{
name: "sealExpensesList",
description: "分页查询费用明细",
description: "分页查询费用明细;传 sn 时精确关联审批记录、分页核验费用库并返回存在性证据",
parameters: z.object({
offset: z.number().int().nonnegative().optional(),
limit: z.number().int().positive().max(100).optional(),
startDate: z.string().optional().describe("开始时间"),
endDate: z.string().optional().describe("结束时间"),
search: z.string().optional().describe("搜索费用类型、描述或金额")
search: z.string().optional().describe("搜索费用类型、描述或金额"),
recordId: z.string().trim().min(1).optional().describe("按关联审批记录 ID 精确筛选"),
sn: z.string().trim().min(1).optional().describe("按源单号核验入库;不能与 search、offset 或 recordId 同传"),
maxScan: z.number().int().positive().max(10000).optional().describe("单号核验每阶段最多扫描条数,默认 5000")
}),
handler: async (client: KyInstance, params: api.DataListParams) => api.listExpenses(client, params)
handler: async (client: KyInstance, params: api.ExpenseListParams & { sn?: string; maxScan?: number }) => {
if (params.sn !== undefined) {
if (params.search !== undefined || params.offset !== undefined || params.recordId !== undefined) throw usageError("--sn cannot be combined with search, offset, or recordId");
return lookupDocumentExpenses(client, { ...params, sn: params.sn });
}
if (params.maxScan !== undefined) throw usageError("maxScan requires sn");
return api.listExpenses(client, params);
}
},
{
name: "sealInvoicesList",
description: "分页查询进项发票",
description: "分页查询进项发票(默认输出扁平化业务字段,对齐控制台表格)",
parameters: z.object({
offset: z.number().int().nonnegative().optional(),
limit: z.number().int().positive().max(100).optional(),
startDate: z.string().optional().describe("开始时间"),
endDate: z.string().optional().describe("结束时间"),
search: z.string().optional().describe("搜索发票号码或销售方")
search: z.string().optional().describe("搜索发票号码或销售方"),
full: z.boolean().optional().describe("是否返回未扁平化的后端原始数据,默认 false (扁平化)")
}),
handler: async (client: KyInstance, params: api.DataListParams) => api.listInvoices(client, params)
handler: async (client: KyInstance, params: api.DataListParams & { full?: boolean }) => {
const result = await api.listInvoices(client, params);
if (params.full === true) {
return result;
}
return {
...result,
invoices: (result.invoices ?? []).map((inv) => flattenInvoiceRecord(inv as Record<string, unknown>))
};
}
}
];
+15 -59
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
import { createDocument, deleteDocument, documentCreateSchema, documentDeleteSchema, documentListSchema, documentUpdateSchema, listDocuments, updateDocument } from "../documents/service.js";
import { recodeRules, type RecodeOptions } from "../rules/recode.js";
import { executeRulePush } from "../rules/push.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
@@ -679,15 +680,11 @@ export const rulesCapabilities = [
{
name: "sealApprovalDocumentsList",
description: "列出 Seal 审批知识文档",
parameters: z.object({
scenarios: z.array(z.string()).optional().describe("场景过滤"),
offset: z.number().int().nonnegative().optional(),
limit: z.number().int().positive().optional()
}),
parameters: documentListSchema,
handler: async (
client: KyInstance,
params: { scenarios?: string[]; offset?: number; limit?: number }
) => api.listApprovalDocuments(client, params)
params: z.infer<typeof documentListSchema>
) => listDocuments(client, params)
},
{
name: "sealApprovalDocumentGet",
@@ -701,70 +698,29 @@ export const rulesCapabilities = [
{
name: "sealApprovalDocumentCreate",
description: "新建 Seal 审批知识文档",
parameters: z.object({
title: z.string(),
purpose: z.string(),
content: z.string().describe("正文,通常为 Markdown"),
contentType: z.string().optional(),
status: z.string().optional(),
enabled: z.boolean().optional(),
scenarios: z.array(z.string()).optional(),
tags: z.array(z.string()).optional()
}),
parameters: documentCreateSchema,
handler: async (
client: KyInstance,
params: {
title: string;
purpose: string;
content: string;
contentType?: string;
status?: string;
enabled?: boolean;
scenarios?: string[];
tags?: string[];
}
) => api.createApprovalDocument(client, params)
params: z.infer<typeof documentCreateSchema>,
context: CapabilityContext
) => createDocument(client, context.corp, params)
},
{
name: "sealApprovalDocumentUpdate",
description: "更新 Seal 审批知识文档",
parameters: z.object({
documentId: z.string(),
title: z.string().optional(),
purpose: z.string().optional(),
content: z.string().optional(),
contentType: z.string().optional(),
status: z.string().optional(),
enabled: z.boolean().optional(),
scenarios: z.array(z.string()).optional(),
tags: z.array(z.string()).optional()
}),
parameters: documentUpdateSchema,
handler: async (
client: KyInstance,
params: {
documentId: string;
title?: string;
purpose?: string;
content?: string;
contentType?: string;
status?: string;
enabled?: boolean;
scenarios?: string[];
tags?: string[];
}
) => {
const { documentId, ...rest } = params;
return api.updateApprovalDocument(client, documentId, rest);
}
params: z.infer<typeof documentUpdateSchema>,
context: CapabilityContext
) => updateDocument(client, context.corp, params)
},
{
name: "sealApprovalDeleteDocument",
description: "删除 Seal 审批知识文档",
parameters: z.object({
documentId: z.string().describe("知识文档 ID")
}),
handler: (client: KyInstance, params: { documentId: string }) =>
api.deleteApprovalDocument(client, params.documentId)
parameters: documentDeleteSchema,
handler: (client: KyInstance, params: z.infer<typeof documentDeleteSchema>, context: CapabilityContext) =>
deleteDocument(client, context.corp, params)
},
{
name: "sealApprovalSearch",
+2 -1
View File
@@ -1,3 +1,4 @@
import { validationError } from "../../../core/errors.js";
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
@@ -98,7 +99,7 @@ export const simulationCapabilities = [
const integrations = await api.listSimulationHosecloudIntegrations(client);
signKey = integrations.find((item) => item.signKey)?.signKey;
if (!signKey) {
throw new Error("未找到合思集成 signKey, 请通过 signKey 参数提供");
throw validationError("未找到合思集成 signKey, 请通过 signKey 参数提供");
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
import { validationError } from "../../../core/errors.js";
import { validationError, confirmationRequired } from "../../../core/errors.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient } from "../../../core/http/factory.js";
@@ -200,7 +200,7 @@ export const webhookCapabilities = [
context: CapabilityContext
) => {
if (!params.confirm && !params.dryRun) {
throw new Error("Refusing to delete Webhook integration without confirm=true");
throw confirmationRequired("Refusing to delete Webhook integration without confirm=true", "seal-use webhook delete <id> --yes");
}
const preview = params.dryRun
? await api.previewDeleteWebhookIntegration(client, params.selector, context.corp.seal.endpoints.approvalStylePreferences)
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import { diagnoseTenantContract, formatTenantDoctorDashboard } from "./tenant-diagnose.js";
import type { CorpConfig } from "../config/types.js";
import type { CorpConfig } from "../../../core/config/types.js";
function createMockClient(opts: {
whoami?: any;
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more