Compare commits

..
6 Commits
Author SHA1 Message Date
yunyingk d00fa1b960 Merge pull request #262 from yunyingk/codex/release-v0.11.15
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Release v0.11.15: Automated release bump
2026-10-23 16:46:13 +08:00
gitea 4541f9c4fb Release v0.11.15: Automated release bump 2026-10-23 16:44:25 +08:00
yunyingk fed0a8464c Merge pull request #261 from yunyingk/mac15/simulation-local-search
Add local search for simulation batches
2026-10-23 16:43:50 +08:00
gitea ed57c0cd42 Add local search for simulation batches 2026-10-23 16:42:20 +08:00
yunyingk 4c4a80b10c Merge pull request #260 from yunyingk/mac15/approval-raw-json
Add native JSON fallback for approval record details
2026-10-22 16:26:11 +08:00
gitea 3ae39bcc08 Add native JSON fallback for approval record details 2026-10-22 16:19:52 +08:00
22 changed files with 755 additions and 32 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.14",
"version": "0.11.15",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+9
View File
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.15] - 2026-10-23
### Added
- Merge pull request #261 from yunyingk/mac15/simulation-local-search
- Add local search for simulation batches
- Merge pull request #260 from yunyingk/mac15/approval-raw-json
- Add native JSON fallback for approval record details
## [0.11.14] - 2026-10-22
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.14",
"version": "0.11.15",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+3 -3
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.14: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.15: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.14
short-description: Seal tenant and Hose approval automation (v0.11.14)
version: 0.11.15
short-description: Seal tenant and Hose approval automation (v0.11.15)
---
# Seal Use
@@ -60,6 +60,25 @@ seal-use approval-runs get <recordId> --corp <corpId> --fields document.keyField
Avoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.
## Native JSON Compatibility Fallback
日常读取优先使用 `--summary`、`--fields` 及专用查询命令。只有后台字段结构变化导致常规解析失败,或确需原生响应供本地脚本处理时,使用以下兜底入口:
```bash
# 原生响应写入文件,适合大数据和脚本处理
seal-use approval-runs get <recordId> --raw-json --output-file ./approval-raw.json --corp <corpId>
# 明确需要完整终端输出时
seal-use approval-runs get <recordId> --raw-json --full --corp <corpId>
```
- 常规 `get` 未指定 `--summary/--fields` 时已经返回完整记录,但会解开上游 `data` 包装、校验已知字段类型,并添加 `aliases`、`humanResult` 等派生字段;这不等于原生响应。
- `--raw-json` 保留上游响应的 JSON 结构(包括 `data` 包装、嵌套内容、新字段及上游同名字段),绕过审核记录的业务 schema 校验,不额外添加或覆盖字段。它仍只调用同一条只读审核详情接口,沿用企业认证和 HTTP 错误处理。
- 该模式解析并重新序列化 JSON,缩进等文本格式可能变化,不是 HTTP 响应的字节级副本。上游未返回的内容不会补查;无效 JSON、网络错误或 HTTP 失败仍按原协议报错。
- 输出不会静默截断。共享的 stdout 大小保护超过 200,000 字节时返回退出码 12;`--full` 或 `--output-file` 可输出完整内容。`--full` 只控制大小保护,不会绕过字段校验,也不会撤销 `--summary/--fields`。
- `--raw-json` 不能与 `--summary`、`--fields` 或 `--flow` 同用;这些参数会改写结构或切换接口,CLI 会以退出码 2 明确拒绝。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
- 不把兜底入口作为默认查询,也不将大段原生 JSON 直接贴给用户;Agent 可按需读取文件中的特定字段。
## Understand The Case First
Before pulling the full document, use:
+10 -3
View File
@@ -100,7 +100,7 @@ seal-use approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end
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] [--has-extra-risk] [--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 get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--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>]
@@ -137,7 +137,9 @@ seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp
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 list [--limit 50] [--all] [--query <text>] [--since <time>] [--until <time>] [--max-scan <n>] [--corp <corpId>]
seal-use simulation search <keyword> [--since 7d] [--until <time>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
seal-use simulation search "任务 fe1993e4" --since 2026-10-01 [--corp <corpId>]
seal-use simulation get <batchId> [--corp <corpId>]
seal-use simulation templates [--corp <corpId>]
seal-use simulation integrations [--corp <corpId>]
@@ -420,7 +422,8 @@ Approval runs, simulations, and Langfuse bridge:
- `seal-use simulation approval-definitions --corp <corpId>` lists available Feishu approval definitions so an `approvalCode` can be selected before creating a batch.
- `seal-use simulation wait <batchId> --corp <corpId>`
- `seal-use simulation clean <batchId> --yes --corp <corpId>`
- `seal-use simulation list --corp <corpId>`
- `seal-use simulation list [--query <text>] [--since <time>] [--until <time>] [--all] --corp <corpId>` (过滤在本地完成,见下方“本地聚合”说明)
- `seal-use simulation search "<关键词>" [--since 7d] [--all] --corp <corpId>` (**本地聚合检索,非云端原生**;先按 limit/offset 拉取批次再过滤,响应 `retrieval.serverSideSearch: false`)
- `seal-use simulation get <batchId> --corp <corpId>`
- `seal-use simulation batch-records <batchId> --corp <corpId>`
- `seal-use simulation templates --corp <corpId>`
@@ -521,8 +524,12 @@ seal-use simulation get <batchId> --corp <corpId>
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation templates --corp <corpId>
seal-use simulation integrations --corp <corpId>
# 本地检索批次(服务端无原生 search): 界面「任务 fe1993e4」可直接粘贴
seal-use simulation search "任务 fe1993e4" --since 7d --all --corp <corpId>
```
> **本地聚合,不是云端原生检索**:`/api/v1/simulation/batches` 只有 `limit`/`offset`,没有名称或关键词检索,批次对象也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。`list --query/--since/--until` 与 `search` 都是 CLI 先把批次拉到本地再过滤,返回体固定带 `retrieval: { mode: "local_scan", serverSideSearch: false, scanned }`;命中范围以 `scanned` 为准,不覆盖未扫描的批次(`truncated: true` 时用 `--all` 或调大 `--max-scan`)。不要把它当作服务端能力向用户描述。
## Failure Handling
- If no run is found by `sourceDocumentSN`, retry with `sourceDocumentId` or a broader `query`.
@@ -170,6 +170,8 @@ flowchart TD
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号1>,<单号2>" --wait
```
> **打断/重发防重复扣费**:批次创建默认幂等——复用窗口(默认 5 分钟,`--reuse-window` 可调)内对同一组 `--flow-ids`/`--package-ids` 再次执行 `simulation create` 会直接返回既有批次(`reused: true`),不会重复扣费。若 `--wait` 挂起期间命令被用户消息打断或后台 task 被 kill,**先执行 `seal-use simulation list --limit 3` 查最近批次**(同单批次可能已在服务端跑完),拿到批次 ID 后用 `status`/`batch-records` 取结果;确认无在途同单批次再决定重发。确需立刻重跑同组单号时显式加 `--force`。
>
> **按界面名称找历史批次**:模拟测试服务端没有名称/关键词检索,批次也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。用 `seal-use simulation search "任务 fe1993e4" --since 7d` 或 `seal-use simulation list --query <关键词> --since <时间>`;这是 **CLI 本地聚合检索**(先按 `limit`/`offset` 拉取再过滤,响应带 `retrieval.serverSideSearch: false`),命中范围以 `scanned` 为准,需要覆盖更早批次时加 `--all`(可用 `--max-scan` 控上限)。
- **方式 C:Webhook 原始报文重放 (Webhook Replay,仅限事件通知调测)**:
直接将正式企业的特定单据/不良案例表单抽取并推送到测试企业 Webhook 通道:
+71 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { runCli } from "../runner.js"
@@ -9,6 +9,8 @@ const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
const oldFetch = globalThis.fetch
let dir: string
let requests: Request[]
let rawResponse: unknown
let rawStatus: number
const fixtures = [
{ id: "warning", result: { decision: "APPROVE", otherFindings: [
@@ -41,11 +43,14 @@ beforeEach(() => {
source: { type: "seal", token: "test-token", sealUrl: "https://extra-risk.example.test", staffId: "fixture" }
}))
requests = []
rawResponse = { data: { id: 123, status: { future: true }, document: { fields: "changed-shape" }, addedByBackend: [1, { nested: null }] }, responseMetadata: { future: true } }
rawStatus = 200
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
requests.push(request)
const url = new URL(request.url)
if (request.method !== "GET") return Response.json({ error: "unexpected mutation" }, { status: 405 })
if (url.pathname === "/api/v1/approvals/raw-fixture") return Response.json(rawResponse, { status: rawStatus })
if (url.pathname === "/api/v1/approvals") {
const offset = Number(url.searchParams.get("offset") ?? 0)
const limit = Number(url.searchParams.get("limit") ?? 50)
@@ -56,6 +61,71 @@ beforeEach(() => {
}) as typeof fetch
})
describe("approval run native JSON fallback", () => {
test("preserves upstream envelopes and schema changes that normal get cannot parse", async () => {
const normal = await cli("get", "raw-fixture", "--full")
expect(normal.exitCode).toBe(13)
const raw = await cli("get", "raw-fixture", "--raw-json")
expect(raw.exitCode).toBe(0)
expect(JSON.parse(raw.stdout)).toEqual(rawResponse)
expect(requests.map(request => new URL(request.url).pathname)).toEqual([
"/api/v1/approvals/raw-fixture", "/api/v1/approvals/raw-fixture"
])
expect(requests.every(request => request.method === "GET")).toBe(true)
})
test("preserves bare responses and upstream fields that would otherwise be CLI-derived", async () => {
rawResponse = { id: "raw-fixture", aliases: { fromServer: true }, humanResult: { original: true }, result: { future: { nested: [false, 0, ""] } } }
const result = await cli("get", "raw-fixture", "--raw-json")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toEqual(rawResponse)
})
test("returns complete large payloads with full/file and uses the shared size error otherwise", async () => {
rawResponse = { data: { id: "raw-fixture", result: { text: "x".repeat(210_000) + "END-OF-UPSTREAM-JSON" } } }
const guarded = await cli("get", "raw-fixture", "--raw-json")
expect(guarded.exitCode).toBe(12)
expect(guarded.stdout).toBe("")
const full = await cli("get", "raw-fixture", "--raw-json", "--full")
expect(full.exitCode).toBe(0)
expect(JSON.parse(full.stdout)).toEqual(rawResponse)
const path = join(dir, "raw.json")
const file = await cli("get", "raw-fixture", "--raw-json", "--output-file", path)
expect(file.exitCode).toBe(0)
expect(JSON.parse(file.stdout)).toEqual({ outputFile: path, bytes: Buffer.byteLength(readFileSync(path)) })
expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(rawResponse)
})
test("rejects transformations and flow routing before sending any request", async () => {
for (const flags of [["--summary"], ["--fields", "result"], ["--flow"]]) {
const result = await cli("get", "raw-fixture", "--raw-json", ...flags)
expect(result.exitCode).toBe(2)
expect(result.stdout).toBe("")
expect(result.stderr).toContain("--raw-json cannot be combined")
}
expect(requests).toHaveLength(0)
})
test("keeps HTTP authentication and upstream failures as errors", async () => {
for (const [status, exitCode] of [[401, 11], [400, 1]] as const) {
rawStatus = status
rawResponse = { error: "Upstream rejected request" }
const result = await cli("get", "raw-fixture", "--raw-json")
expect(result.exitCode).toBe(exitCode)
expect(result.stdout).toBe("")
}
})
test("accepts the camelCase alias and explicit false retains normal behavior", async () => {
const raw = await cli("get", "raw-fixture", "--rawJson")
expect(raw.exitCode).toBe(0)
expect(JSON.parse(raw.stdout)).toEqual(rawResponse)
const normal = await cli("get", "warning", "--raw-json=false")
expect(normal.exitCode).toBe(0)
expect(JSON.parse(normal.stdout)).toHaveProperty("aliases")
})
})
afterEach(() => {
for (const key of envKeys) {
if (oldEnv[key] === undefined) delete process.env[key]
+6 -1
View File
@@ -175,6 +175,10 @@ export async function handleApprovalRunsCommand(
if (action === "get") {
const recordId = args.command[2];
if (!recordId) throw new Error("Missing approval run recordId");
const rawJson = booleanOption(args.options["raw-json"]) ?? booleanOption(args.options.rawJson);
if (rawJson && (booleanOption(args.options.flow) || booleanOption(args.options.summary) || stringOption(args.options.fields) !== undefined)) {
throw usageError("--raw-json cannot be combined with --flow, --summary or --fields");
}
if (booleanOption(args.options.flow)) {
await runCapability(
"sealApprovalRunFlowGet",
@@ -192,7 +196,8 @@ export async function handleApprovalRunsCommand(
{
recordId,
fields: stringOption(args.options.fields),
summary: booleanOption(args.options.summary)
summary: booleanOption(args.options.summary),
rawJson
},
outputOptions(args.options)
);
+79
View File
@@ -76,6 +76,85 @@ function trackMutationRequests() {
return mutations;
}
function mockSimulationBatches() {
const requested: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
requested.push(url);
const body = url.includes("/api/v1/simulation/batches")
? {
data: [
{
id: "01a12488-a69d-74c4-88b1-118bfe1993e4",
status: "completed",
approvalCode: "hosecloud",
sourceSystem: "hosecloud",
createdAt: "2026-10-10T06:38:17.757Z"
},
{
id: "01a123be-0742-743a-ac16-87f7c4e121c7",
status: "completed",
approvalCode: "hosecloud",
sourceSystem: "hosecloud",
createdAt: "2026-10-09T02:56:58.000Z"
}
]
}
: { data: {} };
return new Response(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}) as typeof fetch;
return requested;
}
describe("simulation local search", () => {
test("search matches the console「任务 fe1993e4」label locally", async () => {
setupMockEnv();
const requested = mockSimulationBatches();
const result = await runCli(["simulation", "search", "任务 fe1993e4"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout) as {
count: number;
scanned: number;
retrieval: { mode: string; serverSideSearch: boolean };
batches: Array<{ id: string }>;
};
expect(payload.count).toBe(1);
expect(payload.retrieval).toMatchObject({ mode: "local_scan", serverSideSearch: false });
expect(payload.batches[0]?.id).toBe("01a12488-a69d-74c4-88b1-118bfe1993e4");
expect(result.stderr).toContain("本地聚合检索");
expect(requested.every((url) => url.includes("/api/v1/simulation/batches"))).toBe(true);
});
test("search respects a local time window", async () => {
setupMockEnv();
mockSimulationBatches();
const result = await runCli(["simulation", "search", "任务", "--since", "2026-10-09", "--until", "2026-10-09"]);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout) as { count: number; batches: Array<{ id: string }> };
expect(payload.count).toBe(1);
expect(payload.batches[0]?.id).toBe("01a123be-0742-743a-ac16-87f7c4e121c7");
});
test("search without a keyword is a usage error", async () => {
setupMockEnv();
const requested = mockSimulationBatches();
const result = await runCli(["simulation", "search"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(requested).toEqual([]);
});
});
describe("simulation command confirmation gates", () => {
test("simulation clean refuses without --yes and never reaches the API", async () => {
setupMockEnv();
+21 -2
View File
@@ -205,13 +205,32 @@ export async function handleSimulationCommand(
return;
}
if (action === "list") {
if (action === "list" || action === "search") {
const query =
stringOption(args.options.query) ??
stringOption(args.options.q) ??
(action === "search" ? maybeName : undefined);
if (action === "search" && (!query || !query.trim())) {
throw usageError(
"Usage: seal-use simulation search <keyword> [--since 7d] [--until <time>] [--all]"
);
}
const limit = numberOption(args.options.limit);
// search 默认扫到底(受 --max-scan 保护), 避免只搜到最近 50 个;显式 --limit 时按用户范围
const all = booleanOption(args.options.all) ?? (action === "search" ? limit === undefined : false);
await runCapability(
"sealSimulationBatchesList",
client,
corp,
{
limit: numberOption(args.options.limit)
limit,
all,
maxScan: numberOption(args.options.maxScan) ?? numberOption(args.options["max-scan"]),
query,
since: stringOption(args.options.since) ?? stringOption(args.options["created-after"]),
until: stringOption(args.options.until) ?? stringOption(args.options["created-before"])
},
outputOptions(args.options)
);
+17 -4
View File
@@ -530,7 +530,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "get",
summary: "Get detailed approval record payload",
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]"]
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--full] [--output-file file.json] [--corp <corpId>]"],
options: [
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary, --fields and --flow" },
{ flag: "--full", description: "Bypass the shared 200,000-byte stdout size guard; this does not change payload structure" },
{ flag: "--output-file <path>", description: "Write the complete JSON payload to a file, bypassing the stdout size guard" }
]
},
{
name: "cited-rules",
@@ -767,7 +772,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
area: "simulation",
title: "Simulation testing engine",
description: "Execute and analyze offline or HoseCloud batch simulations against approval rules.",
description: "Execute and analyze offline or HoseCloud batch simulations against approval rules. Note: batch search is a local scan over the list API — the server exposes no name/keyword search.",
commands: [
{
name: "batch-records",
@@ -810,8 +815,16 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "list",
summary: "List recent simulation batches",
usage: ["seal-use simulation list [--limit 50] [--corp <corpId>]"]
summary: "List recent simulation batches (filtering is LOCAL only: batches are pulled by limit/offset, the server has no query API)",
usage: ["seal-use simulation list [--limit 50] [--all] [--query <text>] [--since <time>] [--until <time>] [--max-scan <n>] [--corp <corpId>]"]
},
{
name: "search",
summary: "Search simulation batches LOCALLY (not a server-side/native search): scans batches then filters by UI name fragment, document SN, package/template or time window",
usage: [
"seal-use simulation search <keyword> [--since 7d] [--until <time>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]",
"seal-use simulation search \"任务 fe1993e4\" --since 2026-10-01 [--corp <corpId>]"
]
},
{
name: "get",
+1 -1
View File
@@ -32,7 +32,7 @@ export const BOOLEAN_FLAGS = new Set([
"has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"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",
"r", "raw-json", "rawJson", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
"summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow",
+1
View File
@@ -53,6 +53,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
"specifications",
"approval-definitions",
"list",
"search",
"get",
"templates",
"integrations"
+16
View File
@@ -14,6 +14,7 @@ import {
getInsightStats,
getInsightRisksByTag,
getInsightPerformance,
getApprovalRunRawJson,
analyzeInsightRecord,
listExpenses,
listInvoices,
@@ -25,6 +26,21 @@ import {
updateWebhookIntegration
} from "./api.js";
describe("native approval JSON", () => {
test("preserves the JSON response without schema validation or unwrapping and encodes the record ID", async () => {
let path = "";
const response = { data: null, futureEnvelope: { nested: [1, false, ""] } };
const client = {
get: (url: string) => {
path = url;
return { json: async () => response };
}
} as unknown as KyInstance;
expect(await getApprovalRunRawJson(client, "record/with?reserved#chars")).toEqual(response);
expect(path).toBe("api/v1/approvals/record%2Fwith%3Freserved%23chars");
});
});
describe("Seal contact API", () => {
test("sends the contact search term as query", async () => {
let requestedUrl = "";
+9 -4
View File
@@ -736,6 +736,11 @@ export async function getApprovalRun(client: KyInstance, runId: string): Promise
return unwrap(await client.get(`api/v1/approvals/${runId}`), ApprovalRunSchema);
}
/** Compatibility escape hatch: preserve the JSON response envelope without business-schema parsing. */
export async function getApprovalRunRawJson(client: KyInstance, runId: string): Promise<unknown> {
return client.get(`api/v1/approvals/${encodeURIComponent(runId)}`).json<unknown>();
}
export async function listSimulationBatchRecords(
client: KyInstance,
batchId: string
@@ -775,12 +780,12 @@ export async function createMaterialPackBatch(
export async function listSimulationBatches(
client: KyInstance,
opts: { limit?: number } = {}
opts: { limit?: number; offset?: number } = {}
): Promise<SimulationBatch[]> {
const searchParams: Record<string, string> = { limit: String(opts.limit ?? 50) };
if (opts.offset !== undefined && opts.offset > 0) searchParams.offset = String(opts.offset);
const json = (await client
.get("api/v1/simulation/batches", {
searchParams: { limit: String(opts.limit ?? 50) }
})
.get("api/v1/simulation/batches", { searchParams })
.json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationBatchSchema).parse(data);
+10 -3
View File
@@ -1,4 +1,4 @@
import { validationError } from "../../../core/errors.js";
import { usageError, validationError } from "../../../core/errors.js";
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
@@ -216,12 +216,19 @@ export const approvalRunsCapabilities = [
parameters: z.object({
recordId: z.string().describe("Seal approval run record ID"),
fields: z.union([z.string(), z.array(z.string())]).optional().describe("逗号分隔或数组形式的字段路径,如 metadata、document.fields、result.summary"),
summary: z.boolean().optional().describe("返回单据摘要、AI 结果、人工结果和版本号")
summary: z.boolean().optional().describe("返回单据摘要、AI 结果、人工结果和版本号"),
rawJson: z.boolean().optional().describe("兼容兜底:返回上游原生 JSON 响应,保留包装和未知字段,不做业务 schema 校验或派生;不能与 summary/fields 同用")
}),
handler: async (
client: KyInstance,
params: { recordId: string; fields?: string | string[]; summary?: boolean }
params: { recordId: string; fields?: string | string[]; summary?: boolean; rawJson?: boolean }
) => {
if (params.rawJson) {
if (params.summary || params.fields !== undefined) {
throw usageError("--raw-json cannot be combined with --summary or --fields");
}
return api.getApprovalRunRawJson(client, params.recordId);
}
const record = await api.getApprovalRun(client, params.recordId);
if (params.summary) return summarizeApprovalRunDetail(record);
const full = {
@@ -745,6 +745,77 @@ describe("simulation tool handlers", () => {
}
});
});
test("list tool scans pages and filters locally by UI name and time window", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchesList");
expect(tool).toBeDefined();
const newer = {
...hosecloudBatchFixture,
id: "01a12488-a69d-74c4-88b1-118bfe1993e4",
createdAt: "2026-10-10T06:38:17.757Z"
};
const older = {
...hosecloudBatchFixture,
id: "01a123be-0742-743a-ac16-87f7c4e121c7",
createdAt: "2026-10-09T02:56:58.000Z"
};
const calls: string[] = [];
const client = {
get: (_url: string, options: { searchParams: Record<string, string> }) => {
const limit = Number(options.searchParams.limit);
const offset = Number(options.searchParams.offset ?? 0);
calls.push(`${limit}@${offset}`);
const all = [newer, older];
return { json: async () => ({ data: all.slice(offset, offset + limit) }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as CapabilityHandler;
const result = await handler(
client,
{ query: "任务 fe1993e4", since: "2026-10-10", until: "2026-10-10" },
fakeContext()
) as Record<string, unknown>;
expect(calls).toEqual(["50@0"]);
expect(result).toMatchObject({
retrieval: { mode: "local_scan", serverSideSearch: false, scanned: 2 },
scanned: 2,
truncated: false,
count: 1,
filters: {
query: "任务 fe1993e4",
since: "2026-10-10T00:00:00+08:00",
until: "2026-10-10T23:59:59+08:00"
}
});
expect((result.batches as Array<{ id: string }>)[0]?.id).toBe(newer.id);
});
test("list tool paginates when all=true is requested", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchesList");
const calls: string[] = [];
const client = {
get: (_url: string, options: { searchParams: Record<string, string> }) => {
const limit = Number(options.searchParams.limit);
const offset = Number(options.searchParams.offset ?? 0);
calls.push(`${limit}@${offset}`);
// Every page comes back full so the scanner keeps advancing until maxScan.
const data = Array.from({ length: limit }, (_, index) => ({
...hosecloudBatchFixture,
id: `batch-${offset + index}`
}));
return { json: async () => ({ data }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as CapabilityHandler;
const result = await handler(client, { all: true, maxScan: 250 }, fakeContext()) as Record<string, unknown>;
expect(calls).toEqual(["100@0", "100@100", "50@200"]);
expect(result).toMatchObject({ scanned: 250, scanLimit: 250, truncated: true, count: 250 });
});
});
describe("simulation response schemas", () => {
+78 -7
View File
@@ -2,12 +2,21 @@ import { validationError } from "../../../core/errors.js";
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import * as api from "../api.js";
import {
type SimulationBatch
} from "../types.js";
import * as helpers from "./helpers.js";
import { parseDurationMs } from "../../../core/duration.js";
import {
collectSimulationBatches,
DEFAULT_SIMULATION_MAX_SCAN,
DEFAULT_SIMULATION_SCAN_LIMIT,
filterSimulationBatches,
MAX_SIMULATION_SCAN,
parseSimulationTimeBound
} from "../simulation/batch-search.js";
const {
buildSimulationBatchParams,
@@ -187,18 +196,80 @@ export const simulationCapabilities = [
},
{
name: "sealSimulationBatchesList",
description: "列出 Seal 模拟测试批次摘要(含状态、统计计数与展示摘要)",
description: "【本地聚合检索, 非云端原生能力】列出或检索 Seal 模拟测试批次摘要。服务端 /simulation/batches 只支持 limit/offset, 没有名称/关键词检索, 批次对象也没有 name 字段(界面上的「任务 fe1993e4」是 UUID 末 8 位)。CLI 先把批次拉到本地再按关键词与时间窗过滤, 结果完整度取决于 scanned 范围: 默认扫描最近 50 个批次, all=true 分页扫到底。返回体带 retrieval.mode=local_scan / serverSideSearch=false 标记, 不要把它当成服务端搜索。",
parameters: z.object({
limit: z.number().int().positive().max(100).optional().describe("最多返回批次数量, 默认 50")
limit: z.number().int().positive().max(MAX_SIMULATION_SCAN).optional()
.describe(`本地扫描的最近批次数量(不是返回条数上限), 默认 ${DEFAULT_SIMULATION_SCAN_LIMIT}`),
all: z.boolean().optional()
.describe(`分页扫描到底(仍受 maxScan 保护), 用于检索较早批次`),
maxScan: z.number().int().positive().max(MAX_SIMULATION_SCAN).optional()
.describe(`all=true 时的扫描上限, 默认 ${DEFAULT_SIMULATION_MAX_SCAN}`),
query: z.string().optional()
.describe("本地关键词检索(CLI 端过滤, 非服务端): 空格/逗号分隔的多个关键词同时命中(AND); 匹配批次 ID(含无连字符形式)、界面「任务」后缀、单号、材料包/模板、条件摘要等"),
since: z.string().optional()
.describe("创建时间下界(含): ISO、YYYY-MM-DD、毫秒, 或相对时长如 7d"),
until: z.string().optional()
.describe("创建时间上界(含): 格式同 since")
}),
handler: async (client: KyInstance, params: { limit?: number }) => {
const batches = await api.listSimulationBatches(client, { limit: params.limit ?? 50 });
handler: async (
client: KyInstance,
params: {
limit?: number;
all?: boolean;
maxScan?: number;
query?: string;
since?: string;
until?: string;
}
) => {
const sinceMs = parseSimulationTimeBound(params.since, { endOfDay: false });
const untilMs = parseSimulationTimeBound(params.until, { endOfDay: true });
const scanLimit = params.all
? (params.maxScan ?? DEFAULT_SIMULATION_MAX_SCAN)
: (params.limit ?? DEFAULT_SIMULATION_SCAN_LIMIT);
const { batches, capped } = await collectSimulationBatches(client, scanLimit);
const matched = filterSimulationBatches(batches, {
query: params.query,
sinceMs,
untilMs
});
const searching = Boolean(params.query?.trim()) || sinceMs !== undefined || untilMs !== undefined;
if (searching) {
console.error(
`ℹ️ [Simulation] 本地聚合检索(非云端原生): 服务端无关键词/名称检索, 已拉取最近 ${batches.length} 个批次并在本地过滤。`
);
}
if (capped) {
console.error(
`🔎 [Simulation] 已扫描 ${batches.length} 个批次(达到扫描上限), 更早的批次未参与检索; 可用 --all 或调大 --max-scan。`
);
}
return {
count: batches.length,
batches: batches.map(summarizeSimulationBatch),
retrieval: {
mode: "local_scan",
serverSideSearch: false,
scanned: batches.length,
note: searching
? "模拟测试服务端只有 limit/offset 列表, 无名称/关键词检索; 本次结果是 CLI 本地拉取后过滤, 命中范围以 scanned 为准, 不代表服务端全量。"
: "模拟测试服务端只有 limit/offset 列表, 无名称/关键词检索; 本次仅列出最近 scanned 个批次, 不代表服务端全量。"
},
scanned: batches.length,
scanLimit,
truncated: capped,
filters: {
query: params.query ?? null,
since: sinceMs === undefined ? null : formatBeijingIso(sinceMs),
until: untilMs === undefined ? null : formatBeijingIso(untilMs)
},
count: matched.length,
batches: matched.map(summarizeSimulationBatch),
next: {
getBatch: "seal-use simulation get <batchId>",
getRecords: "seal-use simulation batch-records <batchId>"
getRecords: "seal-use simulation batch-records <batchId>",
search: "seal-use simulation search <关键词> [--since 7d] [--all] (本地检索)"
}
};
}
@@ -0,0 +1,155 @@
import { describe, expect, test } from "bun:test";
import { KyInstance } from "ky";
import { CliError } from "../../../core/errors.js";
import { SimulationBatch } from "../types.js";
import {
collectSimulationBatches,
filterSimulationBatches,
parseSimulationTimeBound,
simulationQueryTokens
} from "./batch-search.js";
function batch(id: string, createdAt: string, extra: Partial<SimulationBatch> = {}): SimulationBatch {
return {
id,
status: "completed",
approvalCode: "hosecloud",
sourceSystem: "hosecloud",
totalCount: 1,
processedCount: 1,
successCount: 1,
failedCount: 0,
createdCount: 1,
createFailedCount: 0,
createdAt,
...extra
};
}
const fe1993e4 = batch("01a12488-a69d-74c4-88b1-118bfe1993e4", "2026-10-10T06:38:17.757Z", {
params: {
approvalCode: "hosecloud",
flowIds: ["S26002992"],
packageLabel: "会议材料包.zip"
},
requestSummary: {
mode: "指定单号",
conditions: [{ label: "驳回节点", value: "出纳支付" }]
}
});
const older = batch("01a123be-0742-743a-ac16-87f7c4e121c7", "2026-10-09T02:56:58.000Z", {
params: { approvalCode: "hosecloud", flowIds: ["B26017701"] }
});
describe("simulationQueryTokens", () => {
test("strips the UI 任务 prefix and punctuation", () => {
expect(simulationQueryTokens("任务 fe1993e4")).toEqual(["fe1993e4"]);
expect(simulationQueryTokens("任务:fe1993e4")).toEqual(["fe1993e4"]);
expect(simulationQueryTokens("任务fe1993e4")).toEqual(["fe1993e4"]);
});
test("drops standalone noise words and splits on commas", () => {
expect(simulationQueryTokens("任务, fe1993e4, 出纳")).toEqual(["fe1993e4", "出纳"]);
expect(simulationQueryTokens("task")).toEqual([]);
expect(simulationQueryTokens(undefined)).toEqual([]);
});
});
describe("filterSimulationBatches", () => {
test("matches the last 8 hex chars shown in the console UI", () => {
expect(filterSimulationBatches([fe1993e4, older], { query: "任务 fe1993e4" })).toEqual([fe1993e4]);
});
test("matches hyphen-less UUID fragments", () => {
expect(filterSimulationBatches([fe1993e4, older], { query: "01a12488a69d" })).toEqual([fe1993e4]);
});
test("matches document SN, package label and request summary values", () => {
expect(filterSimulationBatches([fe1993e4, older], { query: "S26002992" })).toEqual([fe1993e4]);
expect(filterSimulationBatches([fe1993e4, older], { query: "会议材料包" })).toEqual([fe1993e4]);
expect(filterSimulationBatches([fe1993e4, older], { query: "出纳支付" })).toEqual([fe1993e4]);
});
test("requires every keyword to match (AND semantics)", () => {
expect(filterSimulationBatches([fe1993e4, older], { query: "任务 fe1993e4 出纳" })).toEqual([fe1993e4]);
expect(filterSimulationBatches([fe1993e4, older], { query: "fe1993e4 B26017701" })).toEqual([]);
});
test("filters by createdAt window, inclusive", () => {
const since = Date.parse("2026-10-10T00:00:00+08:00");
const until = Date.parse("2026-10-10T23:59:59.999+08:00");
expect(filterSimulationBatches([fe1993e4, older], { sinceMs: since, untilMs: until })).toEqual([fe1993e4]);
});
test("returns everything without filters", () => {
expect(filterSimulationBatches([fe1993e4, older])).toEqual([fe1993e4, older]);
});
});
describe("parseSimulationTimeBound", () => {
test("reads Beijing-local dates, epoch millis and ISO timestamps", () => {
expect(parseSimulationTimeBound("2026-10-10")).toBe(Date.parse("2026-10-10T00:00:00+08:00"));
expect(parseSimulationTimeBound("2026-10-10", { endOfDay: true })).toBe(
Date.parse("2026-10-10T23:59:59.999+08:00")
);
expect(parseSimulationTimeBound("1759000000000")).toBe(1759000000000);
expect(parseSimulationTimeBound("2026-10-10T06:38:17.757Z")).toBe(Date.parse("2026-10-10T06:38:17.757Z"));
});
test("interprets relative durations as now minus the offset", () => {
const now = Date.parse("2026-10-23T16:00:00+08:00");
expect(parseSimulationTimeBound("7d", { nowMs: now })).toBe(now - 7 * 86400_000);
expect(parseSimulationTimeBound("90m", { nowMs: now })).toBe(now - 90 * 60_000);
});
test("rejects unparseable bounds with the validation exit code", () => {
let error: unknown;
try {
parseSimulationTimeBound("上周三");
} catch (caught) {
error = caught;
}
expect(error).toBeInstanceOf(CliError);
expect((error as CliError).exitCode).toBe(13);
});
});
describe("collectSimulationBatches", () => {
function pagedClient(total: number) {
const calls: Array<{ limit: number; offset: number }> = [];
const all = Array.from({ length: total }, (_, index) =>
batch(`batch-${index}`, new Date(Date.UTC(2026, 9, 10, 0, index)).toISOString())
);
const client = {
get: (_url: string, options: { searchParams: Record<string, string> }) => {
const limit = Number(options.searchParams.limit);
const offset = Number(options.searchParams.offset ?? 0);
calls.push({ limit, offset });
return { json: async () => ({ data: all.slice(offset, offset + limit) }) };
}
} as unknown as KyInstance;
return { client, calls };
}
test("paginates with offset until the scan limit is reached", async () => {
const { client, calls } = pagedClient(250);
const result = await collectSimulationBatches(client, 250);
expect(result.batches).toHaveLength(250);
expect(result.capped).toBe(true);
expect(calls.map((call) => [call.limit, call.offset])).toEqual([
[100, 0],
[100, 100],
[50, 200]
]);
});
test("stops when the server returns a short page", async () => {
const { client, calls } = pagedClient(30);
const result = await collectSimulationBatches(client, 500);
expect(result.batches).toHaveLength(30);
expect(result.capped).toBe(false);
expect(calls).toEqual([{ limit: 100, offset: 0 }]);
});
});
+173
View File
@@ -0,0 +1,173 @@
import type { KyInstance } from "ky";
import { durationSeconds, tokenizeDuration } from "../../../core/duration.js";
import { validationError } from "../../../core/errors.js";
import * as api from "../api.js";
import type { SimulationBatch } from "../types.js";
/**
* 原生模拟测试没有服务端检索: `/api/v1/simulation/batches` 只接受 limit/offset,
* 批次对象也没有 name 字段(界面上的「任务 fe1993e4」是前端取 UUID 末 8 位拼的)。
* 因此检索放在本地: 先按 limit/offset 把批次扫进内存, 再按关键词与时间窗过滤。
*/
export const SIMULATION_SCAN_PAGE_SIZE = 100;
export const DEFAULT_SIMULATION_SCAN_LIMIT = 50;
export const DEFAULT_SIMULATION_MAX_SCAN = 500;
export const MAX_SIMULATION_SCAN = 2000;
export type SimulationBatchFilter = {
query?: string;
sinceMs?: number;
untilMs?: number;
};
const STANDALONE_NOISE_TOKENS = new Set([
"任务",
"批次",
"模拟测试",
"测试",
"task",
"batch",
"test",
"simulation"
]);
// 界面名称形如「任务 fe1993e4」「任务:fe1993e4」, 直接粘贴时把中文前缀剥掉
const GLUED_NOISE_PREFIXES = ["模拟测试", "任务", "批次"];
function stripGluedNoise(token: string): string {
let value = token;
for (const prefix of GLUED_NOISE_PREFIXES) {
if (value.length > prefix.length && value.startsWith(prefix)) {
value = value.slice(prefix.length);
}
}
return value.replace(/^[\s::#\-_]+/, "");
}
export function simulationQueryTokens(query?: string): string[] {
if (!query) return [];
const raw = query
.split(/[\s,,;;、]+/)
.map((token) => token.trim())
.filter(Boolean)
.map((token) => token.toLowerCase())
.filter((token) => !STANDALONE_NOISE_TOKENS.has(token));
return raw
.map((token) => stripGluedNoise(token))
.filter(Boolean);
}
function batchHaystack(batch: SimulationBatch): string {
const params = batch.params;
const values: Array<string | number | null | undefined> = [
batch.id,
batch.id.replace(/-/g, ""),
batch.approvalCode,
batch.nodeId,
batch.sourceSystem,
batch.status,
batch.requestSummary?.mode,
batch.resultSummary?.message,
params?.packageLabel,
params?.templateId,
params?.signKey,
params?.rejectNodeName,
params?.dataCollectionMode,
...(params?.flowIds ?? []),
...(params?.packageIds ?? []),
...(batch.requestSummary?.conditions ?? []).flatMap((condition) => [
condition.label,
condition.value
])
];
return values
.filter((value): value is string | number => value !== undefined && value !== null && value !== "")
.map((value) => String(value).toLowerCase())
.join("\n");
}
function batchCreatedAtMs(batch: SimulationBatch): number | null {
if (batch.createdAt === undefined) return null;
const ms = typeof batch.createdAt === "number" ? batch.createdAt : Date.parse(batch.createdAt);
return Number.isFinite(ms) ? ms : null;
}
export function filterSimulationBatches(
batches: SimulationBatch[],
filter: SimulationBatchFilter = {}
): SimulationBatch[] {
const tokens = simulationQueryTokens(filter.query);
return batches.filter((batch) => {
if (filter.sinceMs !== undefined || filter.untilMs !== undefined) {
const createdAtMs = batchCreatedAtMs(batch);
if (createdAtMs === null) return false;
if (filter.sinceMs !== undefined && createdAtMs < filter.sinceMs) return false;
if (filter.untilMs !== undefined && createdAtMs > filter.untilMs) return false;
}
if (tokens.length === 0) return true;
const haystack = batchHaystack(batch);
return tokens.every((token) => haystack.includes(token));
});
}
/**
* 解析时间下界/上界: 支持 ISO、`YYYY-MM-DD`、10/13 位毫秒、以及相对时长(`7d` / `24h` / `90m`)。
* 相对时长按「现在往前推」解释, 便于 `--since 7d` 这类用法。
*/
export function parseSimulationTimeBound(
raw: string | undefined,
options: { endOfDay?: boolean; nowMs?: number } = {}
): number | undefined {
if (raw === undefined) return undefined;
const value = raw.trim();
if (!value) return undefined;
if (/^\d{10,13}$/.test(value)) {
return value.length === 10 ? Number(value) * 1000 : Number(value);
}
const relative = tokenizeDuration(value);
if (relative?.unit) {
const offsetMs = Math.round(durationSeconds(relative, "d") * 1000);
return (options.nowMs ?? Date.now()) - offsetMs;
}
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
const timeSuffix = options.endOfDay ? "T23:59:59.999+08:00" : "T00:00:00.000+08:00";
const parsed = new Date(`${value}${timeSuffix}`).getTime();
if (Number.isFinite(parsed)) return parsed;
}
const parsed = new Date(value).getTime();
if (Number.isFinite(parsed)) return parsed;
throw validationError(
`无法解析时间 "${raw}"。支持 ISO 时间、YYYY-MM-DD、10/13 位毫秒, 或相对时长(如 7d / 24h / 90m)。`
);
}
export async function collectSimulationBatches(
client: KyInstance,
scanLimit: number
): Promise<{ batches: SimulationBatch[]; capped: boolean }> {
const target = Math.max(1, Math.min(scanLimit, MAX_SIMULATION_SCAN));
const batches: SimulationBatch[] = [];
let offset = 0;
while (batches.length < target) {
const pageSize = Math.min(SIMULATION_SCAN_PAGE_SIZE, target - batches.length);
const page = await api.listSimulationBatches(client, { limit: pageSize, offset });
batches.push(...page);
// 服务端已无更多批次
if (page.length < pageSize) return { batches, capped: false };
offset += page.length;
}
// 达到扫描上限: 更早的批次未进入检索
return { batches, capped: true };
}
+2 -1
View File
@@ -463,7 +463,8 @@ export const SimulationBatchParamsSchema = z.object({
nodeId: z.string().optional(),
// 合思指定单号模式
flowIds: z.array(z.string()).max(100).optional(),
limit: z.number().int().positive().max(100).optional(),
// 历史批次存在 limit=0(取数模式不按条数限制)与超过 100 的回显值,读路径不能因此整页失败
limit: z.number().int().nonnegative().optional(),
dataCollectionMode: z.string().optional(),
signKey: z.string().optional(),
rejectNodeName: z.string().nullable().optional(),