Merge pull request #278 from yunyingk/mac15/official-rules-export

feat: 增加 SealAI 官方规则 CSV 导出
This commit is contained in:
yunyingk authored and GitHub committed 2026-11-06 15:01:42 +08:00
commit cb07fad536
14 files changed
+143 -9

No files matched your search

+1
View File
@@ -147,6 +147,7 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
| 第一次接入、不会找凭据、需要截图 | `references/first-time-user.md` | 用户交付材料后,再读 `enterprise-onboarding.md` 做来源决策 |
| 判断材料来源、Token 边界、cURL、Hose 提权 | `references/enterprise-onboarding.md` | 需要具体域名/员工探测时,再读 `hose-enterprise-init.md` |
| Hose 登录检查、认证失败、合思/Seal 协助链接及登录人员身份 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
| SealAI 浏览器会话回放、RUM telemetry 接口 | `references/sealai-browser-rum.md` | 仅在排查浏览器录制/回放采集时读取;不要用于审核业务数据导出 |
| Hose 域名探测、角色/员工发现、管理员选择 | `references/hose-enterprise-init.md` | 不要先加载部署或规则文档 |
| 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` |
| 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` |
+3 -2
View File
@@ -72,7 +72,7 @@ seal-use rules version <versionNumber|latest> [--corp <corpId>]
seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]
seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]
seal-use rules linters [--corp <corpId>]
seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]
seal-use rules pull [--official] [--version <number|latest>] [--out <file>] [--corp <corpId>]
seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]
seal-use rules push status [--file <path>] [--corp <corpId>]
seal-use rules clear [--dry-run|--yes] [--corp <corpId>]
@@ -369,7 +369,8 @@ Approval rule maintenance:
- `seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]` (returns structured changes plus a Git-style `unifiedDiff`; oversized output is truncated only when it exceeds the safety limit)
- `seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]`
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: custom in `~/.config/seal-use/linters` and official in `~/.cache/seal-use/linters/official`)
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]`
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]` saves the current draft or selected published snapshot as local JSON.
- `seal-use rules pull --official [--out <file>] [--corp <corpId>]` calls the SealAI server's CSV export endpoint and saves its returned CSV unchanged (defaults to Downloads). `--official` cannot be combined with `--version`; this endpoint exports the server's current rules and does not expose historical versions.
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Live execution persists a per-step recovery ledger (`status`: `not_started`, `partial`, `completed`, `uncertain`) and hydrates newly created IDs so an interrupted run can be inspected and resumed without duplicating rules.
- `seal-use rules push status [--file <path>] [--corp <corpId>]` (or `--check`) inspects the last push recovery ledger and reconciles remaining diff against the live draft without mutating state.
- `seal-use rules clear [--dry-run|--yes] [--corp <corpId>]`
@@ -60,6 +60,19 @@ seal-use rules get 0205 --record-id <recordId> --corp <corpId>
Returns `id`, `code`, `ruleCode`, `runtimeRuleId`, `description`, `scope`, `strictness`, `status`, and version metadata when reading from a published version.
## Pull the Official Server CSV
Use `rules pull --official` when the user wants the CSV generated by the SealAI rules page:
```bash
seal-use rules pull --official --corp <corpId>
seal-use rules pull --official --out <file.csv> --corp <corpId>
```
This calls `GET /api/v1/rules/export/csv` with the configured Seal session. The observed response is a JSON envelope with a `data.csv` string. The command writes that string unchanged to a UTF-8 CSV file; it does not parse rows, rename or reorder columns, normalize line endings, or rebuild the workbook. The response is the official CSV export, not an XLSX file. The endpoint has no observed version parameter, so `--official` cannot be combined with `--version`; use `rules pull --version latest` for the latest published snapshot as JSON.
When `--out` is omitted, the CSV is saved to the user's Downloads directory. CLI stdout remains structured JSON with the output path and byte size.
## Search Rules Compactly
```bash
@@ -0,0 +1,16 @@
# SealAI Browser RUM Replay Endpoint
This reference records the observed browser request to `gc-openway.hosecloud.com` for future diagnostics. It is not an approval or rule-data API.
## Observed request shape
- `POST /v1/write/rum/replay?token=...&to_headless=true&precision=ms`
- `multipart/form-data` with a binary `segment` part and replay metadata such as `start`, `end`, `creation_reason`, `records_count`, `has_full_snapshot`, `index_in_view`, `source`, `sdk_name`, `sdk_version`, `env`, `service`, `app_id`, `session_id`, `view_id`, and `raw_segment_size`.
- The captured request uses `app_id=seal_ai`, `source=browser`, and SDK name `df_web_rum_sdk`.
- `x-datadog-*` request headers and the replay-specific fields indicate a Datadog RUM-compatible browser session replay ingestion/relay endpoint. This is an inference from the request shape; the response and server-side implementation have not been inspected.
## Operational boundary
- The `token` query value is credential material. Never copy it into source code, documentation, CLI output, or logs.
- The uploaded `segment` contains browser replay telemetry. Do not treat it as approval decisions, audit rules, or business documents.
- This endpoint is not part of normal Seal Use CLI operation. Do not embed browser fingerprint emulation or replay credentials in the distributed binary. If future diagnostics need browser replay, keep the adapter separate and use an authorized browser/test session.
+13
View File
@@ -327,6 +327,19 @@ export async function handleRulesCommand(
if (action === "pull") {
const version = resolveVersionOption(args, maybeName);
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
if (booleanOption(args.options.official) === true) {
if (version) {
throw usageError("rules pull --official uses SealAI's official current-rules CSV export and cannot be combined with --version.");
}
await runCapability(
"sealApprovalRulesExportCsv",
client!,
corp,
{ out },
outputOptions(args.options)
);
return;
}
await runCapability(
"sealApprovalRulesPull",
client!,
+7 -2
View File
@@ -340,8 +340,13 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "pull",
summary: "Export rules to local JSON file",
usage: ["seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]"]
summary: "Pull rules as local JSON, or use --official for the server-generated CSV",
usage: ["seal-use rules pull [--official] [--version <number|latest>] [--out <file>] [--corp <corpId>]"],
options: [
{ flag: "--official", description: "Call SealAI's official CSV export endpoint and save its returned CSV unchanged; cannot be combined with --version" },
{ flag: "--version <number|latest>", description: "Pull a published version as JSON; unavailable with --official" },
{ flag: "--out <file>", description: "Output path; defaults to ./rules.local.json for JSON or Downloads for official CSV" }
]
},
{
name: "push",
+4
View File
@@ -27,6 +27,10 @@ describe("parseArgs flag handling", () => {
expect(parseArgs(["corps", "list", "--all"]).options.all).toBe(true);
});
test("rules pull official is parsed as a boolean flag", () => {
expect(parseArgs(["rules", "pull", "--official"]).options.official).toBe(true);
});
test("value flags consume exactly one token", () => {
const parsed = parseArgs(["approval-runs", "list", "--limit", "25", "--status", "completed"]);
+1 -1
View File
@@ -31,7 +31,7 @@ export const BOOLEAN_FLAGS = new Set([
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
"has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"include-bridge", "includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
"no-wait", "noWait", "official", "outbound", "overwrite", "plain", "publish", "quiet",
"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",
+7 -4
View File
@@ -25,8 +25,9 @@ import file21 from "../../skills/seal-use/references/langfuse-trace.md" with { t
import file22 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file24 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file26 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/sealai-browser-rum.md" with { type: "text" };
import file26 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file27 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"SKILL.md": file0,
@@ -48,8 +49,9 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"references/report-templates.md": file22,
"references/rule-lightweight.md": file23,
"references/rule-lint.md": file24,
"references/staging-simulation-workflow.md": file25,
"references/webhook-resource-pack.md": file26,
"references/sealai-browser-rum.md": file25,
"references/staging-simulation-workflow.md": file26,
"references/webhook-resource-pack.md": file27,
};
export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {
@@ -87,6 +89,7 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"references/report-templates.md",
"references/rule-lightweight.md",
"references/rule-lint.md",
"references/sealai-browser-rum.md",
"references/staging-simulation-workflow.md",
"references/webhook-resource-pack.md",
];
+16
View File
@@ -15,6 +15,7 @@ import {
getInsightRisksByTag,
getInsightPerformance,
getApprovalRunRawJson,
exportApprovalRulesCsv,
analyzeInsightRecord,
listExpenses,
listInvoices,
@@ -41,6 +42,21 @@ describe("native approval JSON", () => {
});
});
describe("official approval rules CSV export", () => {
test("reads the server-generated CSV from the data envelope", async () => {
let requestedUrl = "";
const client = {
get: (url: string) => {
requestedUrl = url;
return { json: async () => ({ data: { csv: "code,description\r\n001,测试" } }) };
}
} as unknown as KyInstance;
await expect(exportApprovalRulesCsv(client)).resolves.toBe("code,description\r\n001,测试");
expect(requestedUrl).toBe("api/v1/rules/export/csv");
});
});
describe("Seal contact API", () => {
test("sends the contact search term as query", async () => {
let requestedUrl = "";
+6
View File
@@ -121,6 +121,12 @@ export async function listApprovalRules(client: KyInstance): Promise<ApprovalRul
return unwrap(await client.get("api/v1/rules"), ApprovalRulesDataSchema);
}
export async function exportApprovalRulesCsv(client: KyInstance): Promise<string> {
const response = await client.get("api/v1/rules/export/csv");
const result = await unwrap(response, z.object({ csv: z.string() }));
return result.csv;
}
export async function createApprovalRule(
client: KyInstance,
params: { description: string; scope: string; strictness: string }
+1
View File
@@ -60,6 +60,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
"sealApprovalRuleVersionsList",
"sealApprovalRulesLint",
"sealApprovalRulesList",
"sealApprovalRulesExportCsv",
"sealApprovalRulesPull",
"sealApprovalRunAttachmentsGet",
"sealApprovalRunCitedRulesGet",
+13
View File
@@ -3,6 +3,7 @@ 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 { exportOfficialRulesCsv } from "../rules/export-csv.js";
import { executeRulePush } from "../rules/push.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { loadGlobalConfig } from "../../../core/config/loader.js";
@@ -719,6 +720,18 @@ export const rulesCapabilities = [
};
}
},
{
name: "sealApprovalRulesExportCsv",
description: "Call the official SealAI rules CSV export endpoint and save its CSV payload unchanged",
parameters: z.object({
out: z.string().optional().describe("Output file path; defaults to the Downloads directory")
}),
handler: async (
client: KyInstance,
params: { out?: string },
context: CapabilityContext
) => exportOfficialRulesCsv(client, context.corp, params.out)
},
{
name: "sealApprovalRulesPush",
description: "将本地规则文件增量同步到远端草稿;支持持久化步骤恢复记录、状态核对(--status)与直接发布正式版本",
+42
View File
@@ -0,0 +1,42 @@
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import type { KyInstance } from "ky";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { writeSecureFile } from "../../../core/secure-file.js";
import * as api from "../api.js";
import { sanitizeFileName } from "../approval-runs/attachments.js";
export interface OfficialRulesCsvExportResult {
filePath: string;
corpName: string;
byteLength: number;
exportedAt: string;
source: "sealai-official-csv-endpoint";
}
export async function exportOfficialRulesCsv(
client: KyInstance,
corp: CorpConfig,
outputFile?: string
): Promise<OfficialRulesCsvExportResult> {
const exportedAt = formatBeijingIso();
const stamp = exportedAt.slice(0, 19).replace(/[-:T]/g, "");
const safeCorpName = sanitizeFileName(corp.name || corp.id);
const filePath = resolve(
outputFile ?? join(homedir(), "Downloads", `${safeCorpName}_审核规则官方导出_${stamp}.csv`)
);
const csv = await api.exportApprovalRulesCsv(client);
// The API response is a JSON envelope containing the server-generated CSV string.
// Persist that string as UTF-8 without parsing, reordering, normalizing, or rewriting CSV rows.
writeSecureFile(filePath, csv);
return {
filePath,
corpName: corp.name || corp.id,
byteLength: Buffer.byteLength(csv, "utf8"),
exportedAt,
source: "sealai-official-csv-endpoint"
};
}